07070100000000000041FD00000000000000000000000667AE111400000000000000000000000000000000000000000000001300000000susemanager-schema    07070100000001000081B400000000000000000000000167AE111400000463000000000000000000000000000000000000001C00000000susemanager-schema/Makefile   include ../../rel-eng/Makefile

TOP      := .
SPECFILE := $(firstword $(wildcard *.spec))
NAME     := $(shell rpm -q --qf '%{name}\n' --specfile $(SPECFILE) | head -n1)
VERSION  := $(shell rpm -q --qf '%{version}\n' --specfile $(SPECFILE) | head -n1)
RELEASE  := $(shell rpm -q --qf '%{release}\n' --specfile $(SPECFILE) | head -n1)
NEXTVERSION := $(shell echo $(VERSION) | awk '{ pre=post=$$0; gsub("[0-9]+$$","",pre); gsub(".*\\.","",post); print pre post+1; }')

spacewalk-clean satellite-clean : FORCE
	$(MAKE) -f $(TOP)/Makefile.schema clean

spacewalk-release satellite-release : FORCE
	$(MAKE) -f $(TOP)/Makefile.schema SCHEMA=$(NAME) VERSION=$(VERSION) RELEASE=$(RELEASE) all

FORCE :

newmigration:
	@mkdir -p upgrade/$(NAME)-$(VERSION)-to-$(NAME)-$(NEXTVERSION)
	@if [ -e upgrade/$(NAME)-$(VERSION)-to-$(NAME)-$(NEXTVERSION)/new.sql ]; then \
		echo "Please rename first upgrade/$(NAME)-$(VERSION)-to-$(NAME)-$(NEXTVERSION)/new.sql"; \
		exit 1; \
	fi
	@touch upgrade/$(NAME)-$(VERSION)-to-$(NAME)-$(NEXTVERSION)/new.sql
	@echo "New migration file at upgrade/$(NAME)-$(VERSION)-to-$(NAME)-$(NEXTVERSION)/new.sql"
 07070100000002000081B400000000000000000000000167AE1114000002C9000000000000000000000000000000000000002300000000susemanager-schema/Makefile.schema    #
# Process the .pre files
# Then, build the oracle and postgres schemas
# Expected Args:
#   SCHEMA
#   VERSION
#   RELEASE

PRE_FILES  := $(shell find . -name \*.pre)
POST_FILES := $(addsuffix .sql,$(basename $(PRE_FILES)))

SANITY_CHECK_SCRIPT := "schema-source-sanity-check.pl"
all : sanity-check $(POST_FILES) postgres upgrade

upgrade:
	echo Upgrade
	for i in $@/*/. ; do $(MAKE) -C $$i -f ../Makefile ; done

postgres :
	$(MAKE) -C $@ -f Makefile

clean :
	echo rm -f $(POST_FILES)

%.sql : %.pre
	sed -e "s!SCHEMA_NAME!'$(SCHEMA)'!g" -e "s!SCHEMA_VERSION!'$(VERSION)'!g" -e "s!SCHEMA_RELEASE!'$(RELEASE)'!" $< > $@

sanity-check :
	perl $(SANITY_CHECK_SCRIPT)

.PHONY: postgres clean sanity-check upgrade
   07070100000003000081B400000000000000000000000167AE111400001013000000000000000000000000000000000000001A00000000susemanager-schema/README 

DIRECTORIES
-------------------------------------------------------------------------------

/schema/spacewalk
/schema/spacewalk/common                - Common DDL
/schema/spacewalk/common/tables         - Common DDL: table,index,sequences
/schema/spacewalk/common/data           - Common SQL: INSERTs
/schema/spacewalk/common/views          - Generic view DDL

POSTGRES:

/schema/spacewalk/postgres                - Postgres specific DDL
/schema/spacewalk/postgres/class          - Postgres specific class DDL
/schema/spacewalk/postgres/tables         - Postgres specific table DDL
/schema/spacewalk/postgres/tables/common  - Generated from common/tables
/schema/spacewalk/postgres/views          - Postgres specific view DDL
/schema/spacewalk/postgres/views/common   - Copied from common/views
/schema/spacewalk/postgres/data           - Postgres specific INSERTs
/schema/spacewalk/postgres/data/common    - Generated from common/data
/schema/spacewalk/postgres/triggers       - Postgres specific trigger DDL
/schema/spacewalk/postgres/procs          - PG/SQL procedures/functions DDL.
/schema/spacewalk/postgres/packages       - PG/SQL packages DDL.


TOOLS
-------------------------------------------------------------------------------

chameleon - Used to translate the common DDL to oracle|postgres specific
            DDL and upgrade scripts.

blend     - Used to generate the main.sql based on .deps files.


DEPENDENCY FILES (.deps)
-------------------------------------------------------------------------------

Terms:
  namespace - A root directory.
              May be: (.|class|tables|views|procs|packages)
              where (.) represents the current namesapce.

  qname     - A qualified name.
              May be: [namespace/]basename[.ext].  When the namespace
              is not specified, the name is unqualified and resolved
              using the "path".  Using the extension is only necessary
              when more than (1) file exists in a given namespace with
              the same name but with different extensions.

Format:

  path = {namespace}([\s,]+{namespace})*

  {qname} :: {qname}([\s,]+{qname})*

Examples:

  path = . tables packages"

  * :: sequence_nextval

  rhnSharedChannelView :: rhnChannel procs/lookup_functions \
                          rhn_channel.pks

  Assuming the current namespace (or directory) is /views.
  The table dependency "rhnChannel" is unqualifed and would be searched
  for in the following order:
    1st. views/rhnChannel
    2nd. tables/rhnChannel
    3rd. packages/rhnChannel
  However, lookup_functions dependency is qualified by namespace so the
  path will not be used.
  The package header dependency "rhn_channel.pks" is unqualifed and but has
  an extension and would be searched for in the following order:
    1st. views/rhn_channel.pks
    2nd. tables/rhn_channel.pks
    3rd. packages/rhn_channel.pks

  The star notation prepends its list to all following entries in the file.

Lines may be joined by (\).

MAIN.SQL

The main.sql file is generated and references includes
the individual .sql, .pks, .pkb files within the directory
tree.  This file is generated by blend and ordered
based on .deps files.  This takes the place of the universal .sql
file.

SPECIAL FILES

clean.sql - If found in the current directory, the contents of this file is
            inserted at the beginning of the output.  This file is expected
            to contain commands to clean (clear) the database before schema
            installation.

start.sql - If found in the current directory, the contents of this file is
            inserted at the beginning of the output (after clean.sql).  This
            file is expected to contain commands used to condition the database
            or database session to schema installation.

end.sql -   If found in the current directory, the contents of this file is
            appended to the end of the output.  This file contains commands
            to commit or post process the installed schema such as commit inserted
            data or to exit an application used for the installation.
 07070100000004000081FD00000000000000000000000167AE11140000457D000000000000000000000000000000000000001900000000susemanager-schema/blend  #!/usr/bin/python3
# This program is free software; you can redistribute it and/or modify
# it under the terms of the (LGPL) GNU Lesser General Public License as
# published by the Free Software Foundation; either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Library Lesser General Public License for more details at
# ( http://www.gnu.org/licenses/lgpl.html ).
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.

"""
Blend is a tool used to sort and combine .sql files as defined by the arguments
and the contents of the .deps files.  Files with an extension of (.sql|.pkb|.pks)
are dependancy sorted as defined by the (optional) .deps files contained within each
subdirectory.  The initial ordering is the natural alphabetical (directory) ordering.
The secondary ordering is based on dependancies.

DEPENDENCY FILES (.deps)
-------------------------------------------------------------------------------

Terms:
  namespace - A root directory.
              May be: (.|class|tables|views|procs|packages)
              where (.) represents the current namesapce.

  qname     - A qualified name.
              May be: [namespace/]basename[.ext].  When the namespace
              is not specified, the name is unqualified and resolved
              using the "path".  Using the extension is only necessary
              when more than (1) file exists in a given namespace with
              the same name but with different extensions.

Format:

  path = {namespace}([\s,]+{namespace})*

  {qname} :: {qname}([\s,]+{qname})*

Examples:

  path = . tables packages"

  * :: sequence_nextval

  rhnSharedChannelView :: rhnChannel procs/lookup_functions \
                          rhn_channel.pks

  Assuming the current namespace (or directory) is /views.
  The table dependency "rhnChannel" is unqualifed and would be searched
  for in the following order:
    1st. views/rhnChannel
    2nd. tables/rhnChannel
    3rd. packages/rhnChannel
  However, lookup_functions dependency is qualified by namespace so the
  path will not be used.
  The package header dependency "rhn_channel.pks" is unqualifed and but has
  an extension and would be searched for in the following order:
    1st. views/rhn_channel.pks
    2nd. tables/rhn_channel.pks
    3rd. packages/rhn_channel.pks

  The star notation prepends its list to all following entries in the file.

Lines may be joined by (\).

MAIN.SQL

The main.sql file is generated and references includes
the individual .sql, .pks, .pkb files within the directory
tree.  This file is generated by blend and ordered
based on .deps files.  This takes the place of the universal .sql
file.

SPECIAL FILES

clean.sql - If found in the current directory, the contents of this file is
            inserted at the beginning of the output.  This file is expected
            to contain commands to clean (clear) the database before schema
            installation.

start.sql - If found in the current directory, the contents of this file is
            inserted at the beginning of the output (after clean.sql).  This
            file is expected to contain commands used to condition the database
            or database session to schema installation.

end.sql -   If found in the current directory, the contents of this file is
            appended to the end of the output.  This file contains commands
            to commit or post process the installed schema such as commit inserted
            data or to exit an application used for the installation.
"""

import sys, os, re
from getopt import getopt, GetoptError
from functools import cmp_to_key

verbose = False
aggregated = False

#
# CLASSES
#

class Name:

    @classmethod
    def qualify(cls, nss, fn):
        names = []
        if cls.qualified(fn):
            for bn in cls.basenames(fn):
                names.append(bn)
            return tuple(names)
        if not isinstance(nss, (tuple,list)):
            nss = (nss,)
        for ns in nss:
            for bn in cls.basenames(fn):
                name = '%s/%s' % (ns, bn)
                names.append(name)
        return tuple(names)

    @classmethod
    def basenames(cls, fn):
        names = [fn]
        try:
            basename, ext = fn.rsplit('.', 1)
            names.append(basename)
        except:
            pass
        return names

    @classmethod
    def qualified(cls, name):
        return ( '/' in name )

    @classmethod
    def unqualified(cls, name):
        return ( not cls.qualified(name) )


class DepTab:

    class Options(object):
        def __setitem__(self, k, v):
            setattr(self, k, v)

    class Entry:
        def __init__(self, tab, info, subject):
            self.tab = tab
            self.info = info
            self.subject = subject
            self.deps = ()
            self.hits = 0

        def __iter__(self):
            expanded = self.expanded([])
            return iter(expanded)

        def expanded(self, history):
            deps = []
            for keyset in self.deps:
                keyset, expanded = self.tab.expand(keyset, history)
                if len(keyset):
                    deps.append(tuple(keyset))
                deps += expanded
            return deps


        def __repr__(self):
            s = []
            s.append(self.subject)
            s.append('::')
            s.append(str(self.deps))
            s.append('@')
            s.append(self.info)
            s.append('/%d' % self.hits)
            return ''.join(s)

    pattern = re.compile('[,\s]+')

    def __init__(self):
        self.content = []
        self.index = {}
        self.options = self.Options()
        self.aliases = None

    def read(self, ns, path):
        fp = open(path)
        self.options.path = (ns,)
        star_entry = None
        for line in self.lines(fp):
            if self.setoption(ns, line[1]):
                continue
            parts = line[1].split('::', 1)
            if len(parts) < 2:
                continue
            info = '%s:%d' % (path, line[0])
            subject = parts[0].strip()
            entry = self.Entry(self, info, subject)
            parts[1] = parts[1].replace('\\', '')
            deps = []
            for dep in self.values(parts[1]):
                dep = dep.strip()
                if not len(dep):
                    continue
                qnames = []
                for qn in Name.qualify(self.options.path, dep):
                    qnames.append(qn)
                deps.append(tuple(qnames))
            entry.deps = tuple(deps)
            if star_entry is not None:
                entry.deps = star_entry.deps + entry.deps
            if subject == '*':
                star_entry = entry
                continue
            self.content.append(entry)
            for key in Name.qualify(ns, subject):
                self.index[key] = entry
        fp.close()

    def setoption(self, ns, line):
        parts = line.split('=', 1)
        if len(parts) == 2:
            tag = parts[0].strip()
            if tag == 'path':
                values = []
                for v in self.values(parts[1]):
                    if v == '.':
                        v = ns
                    values.append(v)
                self.options[tag] = values
                return True
        return False

    def values(self, line):
        return self.pattern.split(line.strip())

    def lines(self, fp):
        ln = 0
        lines = []
        append = False
        for line in fp.readlines():
            ln += 1
            if not len(line):
                continue
            if line[0] == '#':
                continue
            if len(lines) and lines[-1][1].endswith('\\\n'):
                last = lines.pop()[1][:-2]
                joined = ' '.join((last, line))
                lines.append((ln, joined))
            else:
                lines.append((ln, line))
        return lines

    def find(self, ns, fn):
        result = ()
        for key in Name.qualify(ns, fn):
            entry = self.index.get(key)
            if entry is None:
                continue
            entry.hits += 1
            result = entry
            break
        return result

    def expand(self, keyset, history):
        result = ([],[])
        for key in keyset:
            if key in history:
                print('circular (alias) reference:%s' % history)
                continue
            alias = self.aliases.get(key)
            if alias is None:
                result[0].append(key)
                continue
            history.append(key)
            alias.hits += 1
            for deps in alias.expanded(history):
                result[1].append(deps)
        if len(result[1]):
            result = ([], result[1])
        return result

    def findaliases(self):
        self.aliases = {}
        for s,e in self.index.items():
            if e.hits == 0:
                self.aliases[s] = e
        return self

class Reader:

    EXT = ['sql', 'pks', 'pkb']

    def __init__(self):
        self.deptab = DepTab()
        self.deplist = DepList()
        self.overrides = []

    def read(self, directories):
        self.opendeptabs(directories)
        self.getfiles(directories)
        self.deptab.findaliases()
        return self

    def sort(self):
        sorted = self.deplist.sort()
        return [x[2] for x in sorted]


    def opendeptabs(self, directories):
        for d in directories:
            for fn, path in self.files(d, ('deps',)):
                self.deptab.read(d, path)
        return self

    def getfiles(self, directories):
        for d in directories:
            for fn, path in self.files(d, self.EXT):
                entry = self.deptab.find(d, fn)
                keys = Name.qualify(d, fn)
                found = self.deplist.find(keys[0])
                if found is None:
                    self.deplist.add(keys, entry, path)
                    continue
                pk = found[2]
                self.overrides.append((path, pk))
        return self

    def path(self, d, fn):
        return '%s/%s' % (d, fn)

    def files(self, d, extensions):
        files = []
        for fn, dir in self.flattened(d):
            parts = fn.rsplit('.', 1)
            if len(parts) != 2:
                continue
            if parts[1] in extensions:
                path = self.path(dir, fn)
                files.append((fn, path))
        return files

    def flattened(self, d):
        files = []
        for n in os.walk(d):
            for f in n[2]:
                files.append((f, n[0]))
        files = sorted(files, key=cmp_to_key(self.fsort))
        return files

    def fsort(self, a, b):
        def cmp(a, b):
            return (a > b) - (a < b) 
        try:
            A = a[0].rsplit('.', 1)
            B = b[0].rsplit('.', 1)
            BC = cmp(A[0], B[0])
            if BC:
                return BC
            IA = self.EXT.index(A[1])
            IB = self.EXT.index(B[1])
            return cmp(IA, IB)
        except:
            return 0

class Writer:

    comment = """
-- Source: %s
    """

    def __init__(self, aggregated=True):
        self.aggregated = aggregated

    def write(self, sorted, output):
        self.copy('clean.sql', output, True)
        self.copy('start.sql', output, True)
        for p in sorted:
            self.copy(p, output)
        self.copy('end.sql', output, True)

    def copy(self, path, output, optional=False):
        if optional:
            if not os.path.exists(path):
                return
        f = open(path)
        output.write(self.comment % path)
        for line in f.readlines():
            if line.startswith('--'):
                continue
            if line.startswith('@'):
                self.copy(line[1:].strip(), output)
                continue
            if line.startswith('\i'):
                self.copy(line[2:].strip(), output)
                continue
            output.write(line)
        f.close()



class Postgres(Writer):

    def write(self, sorted, output):
        if self.aggregated:
            Writer.write(self, sorted, output)
            return
        self.start(output)
        for p in sorted:
            entry = '\\i %s' % p
            output.write('\n')
            output.write(entry)



class DepList:

    def __init__(self):
        """ """
        self.unsorted = []
        self.index = {}
        self.reset()

    def reset(self):
        self.stack = []
        self.pushed = set()
        self.sorted = []
        self.unfound = []

    def add(self, keys, deps, *payload):
        item = [keys, deps]
        item += payload
        item = tuple(item)
        self.unsorted.append(item)
        for key in keys:
            self.index[key] = item
        return self

    def sort(self):
        self.reset()
        for item in self.unsorted:
            popped = []
            self.push(item)
            while len(self.stack):
                try:
                    top = self.top()
                    try:
                        ref = top[1].__next__()
                    except AttributeError:
                        ref = top[1].next()
                    refd = self.find(ref)
                    if refd is None:
                        info = top[0][1].info
                        self.unfound.append((ref, info))
                        continue
                    self.push(refd)
                except StopIteration:
                    popped.append(self.pop())
                    continue
            for p in popped:
                self.sorted.append(p)
        self.unsorted = self.sorted
        return self.sorted

    def find(self, key):
        if not isinstance(key, (tuple,list)):
            key = (key,)
        for k in key:
            v = self.index.get(k)
            if v is not None:
                return v
        return None

    def top(self):
        return self.stack[-1]

    def push(self, item):
        if item in self.pushed:
            return
        frame = (item, iter(item[1]))
        self.stack.append(frame)
        self.pushed.add(item)

    def pop(self):
        try:
            frame = self.stack.pop()
            return frame[0]
        except:
            pass

#
# FUNCTIONS
#

def generate(path, reader, writer, output, directories):
    os.chdir(path)
    out = open(output, 'w')
    ds = []
    for fn in directories:
        if os.path.isdir(fn):
            ds.append(fn)
    reader.read(ds)
    sorted = reader.sort()
    overrides = reader.overrides
    print('\nOVERRIDES (%d):' % len(overrides))
    for entry in overrides:
        print('\t"%s" overridden by "%s"' % entry)
    unused = \
        [x for x in reader.deptab.content if x.hits == 0]
    print('\nUNUSED RULES (%d):' % len(unused))
    for entry in unused:
        if entry.hits == 0:
            print('\t%s @%s' % (entry.subject,entry.info))
    unfound = reader.deplist.unfound
    print('\nUNFOUND (rule) REFERENCES (%d):' % len(unfound))
    for unf in unfound:
        print('\t"%s" @%s' % unf)
    if verbose:
        ln = 1
        print('\n\nFILES (%d):' % len(sorted))
        for p in sorted:
            print('\t%d %s' % (ln, p))
            ln += 1
    writer.write(sorted, out)
    out.close()
    errnum = 0
    if (len(overrides)+len(unused)+len(unfound) > 0): errnum = 1
    return errnum

def usage():
    s = []
    s.append('Usage blend: [OPTIONS] directory ...')
    s.append(' Options:')
    s.append('  -h, --help')
    s.append('      Show usage information.')
    s.append('  -v, --verbose')
    s.append('      Show extra processing information.')
    s.append('  -a, --aggregated')
    s.append('      Aggregate the contents vs. reference by includes')
    s.append('  -s, --style')
    s.append('      The output style (postres ).')
    s.append('  -o, --output')
    s.append('      The output file.  Default: main.sql')
    s.append('  -d, --directory')
    s.append('      The working directory to process.')
    print('\n'.join(s))

def main(argv):
    path = '.'
    global verbose, aggregated
    reader = Reader()
    writer = Postgres()
    output = 'main.sql'
    flags = 'vhad:o:s:'
    keywords = [
        '--help',
        '--verbose',
        '--directory',
        '--output',
        '--style'
        '--aggregated',
    ]
    try:
        opts, args = getopt(argv, flags, keywords)
        for opt, arg in opts:
            if opt in ('-h', '--help'):
                usage()
                sys.exit(0)
            if opt in ('-v', '--verbose'):
                verbose = True
                continue
            if opt in ('-a', '--aggregated'):
                aggregated = True
                continue
            if opt in ('-o', '--output'):
                output = arg
                continue
            if opt in ('-d', '--directory'):
                path = arg
                continue
            if opt in ('-s', '--style'):
                if arg == 'postgres':
                    writer = Postgres()
                    continue
                raise Exception('style "%s" not valid' % arg)
        writer.aggregated = aggregated
        errnum = generate(path, reader, writer, output, args)
        sys.exit(errnum)
    except GetoptError as e:
        print(e)
        usage()
        sys.exit(2)

if __name__ == '__main__':
    main(sys.argv[1:])

   07070100000005000041FD00000000000000000000000567AE111400000000000000000000000000000000000000000000001A00000000susemanager-schema/common 07070100000006000081B400000000000000000000000167AE1114000003F1000000000000000000000000000000000000002300000000susemanager-schema/common/Makefile    #
# This software is licensed to you under the GNU General Public License,
# version 2 (GPLv2). There is NO WARRANTY for this software, express or
# implied, including the implied warranties of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
# along with this software; if not, see
# http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
#
# Red Hat trademarks are not licensed under GPLv2. No permission is
# granted to use or replicate Red Hat trademarks that are incorporated
# in this software or its documentation.
#

ifndef COMMON
COMMON := ../../../common
$(warning COMMON not defined, using $(COMMON))
endif
ifndef NAME
NAME := $(notdir $(shell cd ../; pwd))
endif

SRCDIR    := $(shell find $(COMMON) -name $(NAME))
SOURCES   := $(wildcard $(SRCDIR)/*)
FILES     := $(notdir $(SOURCES))
RMLINKS   := find . -type l -delete
RMTRASH   := rm -f lextab* parsetab* parser.out


all :
	$(MAKE) $(MAKEOVERRIDES) files

files : $(FILES)
	@$(RMTRASH)

.PHONY :
   07070100000007000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000001F00000000susemanager-schema/common/data    07070100000008000081B400000000000000000000000167AE111400000823000000000000000000000000000000000000002900000000susemanager-schema/common/data/data.deps  #
# Copyright (c) 2008--2017 Red Hat, Inc.
#
# This software is licensed to you under the GNU General Public License,
# version 2 (GPLv2). There is NO WARRANTY for this software, express or
# implied, including the implied warranties of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
# along with this software; if not, see
# http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
#
# Dependencies for data (insert) objects in this (namespace) directory.
# See: ../../README for details.
# No TABS, PLEASE!
#

path = . tables procs

* :: procs/sequence_nextval
rhnChannelArch                   :: lookup_arch_type
rhnChannelPackageArchCompat      :: data/rhnChannelArch \
                                    data/rhnPackageArch lookup_functions
rhnServerServerGroupArchCompat   :: lookup_functions
rhnPackageArch                   :: lookup_arch_type
rhnPackageKey                    :: rhnPackageKey \
                                    rhnPackageProvider \
                                    lookup_package_provider \
                                    lookup_package_key_type \
                                    data/rhnPackageKeyType \
                                    data/rhnPackageProvider
rhnPackageProvider               :: rhnPackageProvider 
rhnPackageKeyType                :: rhnPackageKeyType
rhnServerArch                    :: lookup_arch_type
rhnServerGroupTypeFeature        :: data/rhnFeature \
                                    data/rhnServerGroupType \
                                    lookup_sg_type \
                                    lookup_feature_type 
rhnSGTypeBaseAddonCompat         :: data/rhnServerGroupType
rhnVersionInfo                   :: lookup_functions

rhnArchTypeActions         :: data/rhnArchType data/rhnActionType
rhnKickstartTimezone       :: data/rhnKSInstallType
rhnTaskoSchedule           :: rhnTaskoBunch
rhnTaskoTemplate           :: rhnTaskoBunch rhnTaskoTask
rhnTemplateString          :: data/rhnTemplateCategory
reschedule                 :: data/rhnTaskoSchedule

 07070100000009000081B400000000000000000000000167AE11140000040B000000000000000000000000000000000000003300000000susemanager-schema/common/data/rhnActionStatus.sql    --
-- Copyright (c) 2008--2013 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--
-- data for rhnActionStatus

insert into rhnActionStatus values (0, 'Queued', current_timestamp, current_timestamp);
insert into rhnActionStatus values (1, 'Picked Up', current_timestamp, current_timestamp);
insert into rhnActionStatus values (2, 'Completed', current_timestamp, current_timestamp);
insert into rhnActionStatus values (3, 'Failed', current_timestamp, current_timestamp);

commit;

 0707010000000A000081B400000000000000000000000167AE1114000021B7000000000000000000000000000000000000003100000000susemanager-schema/common/data/rhnActionType.sql  --
-- Copyright (c) 2012--2014 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--
-- data for rhnActionType

-- last three boolean values are for TRIGGER_SNAPSHOT, UNLOCKED_ONLY, MAINTENANCE_MODE_ONLY
insert into rhnActionType values (1, 'packages.refresh_list', 'Package List Refresh', 'Y', 'N', 'N');
insert into rhnActionType values (2, 'hardware.refresh_list', 'Hardware List Refresh', 'N', 'N', 'N');
insert into rhnActionType values (3, 'packages.update', 'Package Install', 'Y', 'Y', 'Y');
insert into rhnActionType values (4, 'packages.remove', 'Package Removal', 'Y', 'Y', 'Y');
insert into rhnActionType values (5, 'errata.update', 'Patch Update', 'Y', 'Y', 'Y');
insert into rhnActionType values (6, 'up2date_config.get', 'Get server up2date config', 'Y', 'Y', 'Y');
insert into rhnActionType values (7, 'up2date_config.update', 'Update server up2date config', 'Y', 'Y', 'Y');
insert into rhnActionType values (8, 'packages.delta', 'Package installation and removal in one RPM transaction', 'Y', 'Y', 'N');
insert into rhnActionType values (9, 'reboot.reboot', 'System reboot', 'N', 'Y', 'Y');
insert into rhnActionType values (10, 'rollback.config', 'Enable or Disable RPM Transaction Rollback', 'N', 'Y', 'Y');
insert into rhnActionType values (11, 'rollback.listTransactions', 'Refresh server-side transaction list', 'N', 'N', 'N');
insert into rhnActionType values (12, 'rollback.rollback', 'RPM Transaction Rollback', 'Y', 'Y', 'Y');
insert into rhnActionType values (13, 'packages.autoupdate', 'Automatic package installation', 'Y', 'Y', 'Y');
insert into rhnActionType values (14, 'packages.runTransaction', 'Package Synchronization', 'Y', 'Y', 'Y');
insert into rhnActionType values (15, 'configfiles.upload', 'Upload config file data to server', 'N', 'N', 'N');
insert into rhnActionType values (16, 'configfiles.deploy', 'Deploy config files to system', 'Y', 'Y', 'Y');
insert into rhnActionType values (17, 'configfiles.verify', 'Verify deployed config files', 'N', 'N', 'N');
insert into rhnActionType values (18, 'configfiles.diff', 'Show differences between profiled config files and deployed config files', 'N', 'N', 'N');
insert into rhnActionType values (19, 'kickstart.initiate', 'Initiate an auto installation', 'N', 'Y', 'Y');
insert into rhnActionType values (20, 'kickstart.schedule_sync', 'Schedule a package sync for auto installations', 'N', 'N', 'N');
insert into rhnActionType values (21, 'activation.schedule_pkg_install', 'Schedule a package install for activation key', 'N', 'N', 'N');
insert into rhnActionType values (22, 'activation.schedule_deploy', 'Schedule a config deploy for activation key', 'N', 'N', 'N');
insert into rhnActionType values (23, 'configfiles.mtime_upload', 'Upload config file data based upon mtime to server', 'N', 'N', 'N');
insert into rhnActionType values (24, 'solarispkgs.install', 'Solaris Package Install', 'Y', 'Y', 'Y');
insert into rhnActionType values (25, 'solarispkgs.remove', 'Solaris Package Removal', 'Y', 'Y', 'Y');
insert into rhnActionType values (26, 'solarispkgs.patchInstall', 'Solaris Patch Install', 'Y', 'Y', 'Y');
insert into rhnActionType values (27, 'solarispkgs.patchRemove', 'Solaris Patch Removal', 'Y', 'Y', 'Y');
insert into rhnActionType values (28, 'solarispkgs.patchClusterInstall', 'Solaris Patch Cluster Install', 'Y', 'Y', 'Y');
insert into rhnActionType values (29, 'solarispkgs.patchClusterRemove', 'Solaris Patch Cluster Removal', 'Y', 'Y', 'Y');
insert into rhnActionType values (30, 'script.run', 'Run an arbitrary script', 'N', 'N', 'Y');
insert into rhnActionType values (31, 'solarispkgs.refresh_list', 'Solaris Package List Refresh','Y','Y', 'Y');
insert into rhnActionType values (32, 'rhnsd.configure', 'SUSE Manager Network Daemon Configuration','N','N', 'N');
insert into rhnActionType values (33, 'packages.verify', 'Verify deployed packages','N','N', 'N');
insert into rhnActionType values (34, 'rhn_applet.use_satellite', 'Allows for rhn-applet use with an Spacewalk','N','N', 'N');
insert into rhnActionType values (35, 'kickstart_guest.initiate', 'Initiate an auto installation for a virtual guest.','N','Y', 'N');
insert into rhnActionType values (36, 'virt.shutdown', 'Shuts down a virtual domain.', 'N', 'N', 'N');
insert into rhnActionType values (37, 'virt.start', 'Starts up a virtual domain.', 'N', 'N', 'N');
insert into rhnActionType values (38, 'virt.suspend', 'Suspends a virtual domain.', 'N', 'N', 'N');
insert into rhnActionType values (39, 'virt.resume', 'Resumes a virtual domain.', 'N', 'N', 'N');
insert into rhnActionType values (40, 'virt.reboot', 'Reboots a virtual domain.', 'N', 'N', 'N');
insert into rhnActionType values (41, 'virt.destroy', 'Destroys a virtual domain.', 'N', 'N', 'N');
insert into rhnActionType values (42, 'virt.setMemory', 'Sets the maximum memory usage for a virtual domain.', 'N', 'N', 'N');
insert into rhnActionType values (43, 'virt.schedulePoller', 'Sets when the poller should run.', 'N', 'N', 'N');
insert into rhnActionType values (44, 'kickstart_host.schedule_virt_host_pkg_install', 'Schedule a package install of host specific functionality.', 'N', 'N', 'N');
insert into rhnActionType values (45, 'kickstart_guest.schedule_virt_guest_pkg_install', 'Schedule a package install of guest specific functionality.', 'N', 'N', 'N');
insert into rhnActionType values (46, 'kickstart_host.add_tools_channel', 'Subscribes a server to the Spacewalk Tools channel associated with its base channel.', 'N', 'N', 'N');
insert into rhnActionType values (47, 'kickstart_guest.add_tools_channel', 'Subscribes a virtualization guest to the Spacewalk Tools channel associated with its base channel.', 'N', 'N', 'N');
insert into rhnActionType values (48, 'virt.setVCPUs', 'Sets the Vcpu usage for a virtual domain.', 'N', 'N', 'N');
insert into rhnActionType values (49, 'proxy.deactivate', 'Deactivate Proxy', 'N', 'N', 'N');
insert into rhnActionType values (50, 'scap.xccdf_eval', 'OpenSCAP xccdf scanning', 'N', 'Y', 'N');
insert into rhnActionType values (51, 'clientcert.update_client_cert', 'Update Client Certificate', 'N', 'Y', 'Y');
insert into rhnActionType values (500, 'image.deploy', 'Deploy an image to a virtual host.', 'N', 'N', 'N');
insert into rhnActionType values (501, 'distupgrade.upgrade', 'Product Migration', 'N', 'N', 'Y');
insert into rhnActionType values (502, 'packages.setLocks', 'Lock packages', 'N', 'N', 'N');
insert into rhnActionType values (503, 'states.apply', 'Apply states', 'N', 'N', 'Y');
insert into rhnActionType values (504, 'image.build', 'Build an Image Profile', 'N', 'N', 'N');
insert into rhnActionType values (505, 'image.inspect', 'Inspect an Image', 'N', 'N', 'N');
insert into rhnActionType values (506, 'channels.subscribe', 'Subscribe to channels', 'N', 'N', 'N');
insert into rhnActionType values (507, 'virt.delete', 'Deletes a virtual domain.', 'N', 'N', 'N');
insert into rhnActionType values (508, 'virt.create', 'Creates a virtual domain.', 'N', 'N', 'N');
insert into rhnActionType values (509, 'virt.pool_refresh', 'Refresh a virtual storage pool', 'N', 'N', 'N');
insert into rhnActionType values (510, 'virt.pool_start', 'Starts a virtual storage pool', 'N', 'N', 'N');
insert into rhnActionType values (511, 'virt.pool_stop', 'Stops a virtual storage pool', 'N', 'N', 'N');
insert into rhnActionType values (512, 'virt.pool_delete', 'Deletes a virtual storage pool', 'N', 'N', 'N');
insert into rhnActionType values (513, 'virt.pool_create', 'Creates a virtual storage pool', 'N', 'N', 'N');
insert into rhnActionType values (514, 'virt.volume_delete', 'Deletes a virtual storage volume', 'N', 'N', 'N');
insert into rhnActionType values (519, 'virt.network_state', 'Change a virtual network state', 'N', 'N', 'N');
insert into rhnActionType values (520, 'virt.network_create', 'Creates a virtual network', 'N', 'N', 'N');
insert into rhnActionType values (521, 'ansible.playbook', 'Execute an Ansible playbook', 'N', 'N', 'N');
insert into rhnActionType values (522, 'virt.guest_migrate', 'Migrate a virtual domain', 'N', 'N', 'N');
commit;

 0707010000000B000081B400000000000000000000000167AE1114000003C8000000000000000000000000000000000000002F00000000susemanager-schema/common/data/rhnArchType.sql    --
-- Copyright (c) 2008--2013 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--
insert into rhnArchType (id, label, name) values
	(sequence_nextval('rhn_archtype_id_seq'), 'rpm', 'RPM');
insert into rhnArchType (id, label, name) values
	(sequence_nextval('rhn_archtype_id_seq'), 'deb', 'DEB');
insert into rhnArchType (id, label, name) values
	(sequence_nextval('rhn_archtype_id_seq'), 'tar', 'tar');
commit;

0707010000000C000081B400000000000000000000000167AE111400000E2F000000000000000000000000000000000000003600000000susemanager-schema/common/data/rhnArchTypeActions.sql --
-- Copyright (c) 2008--2010 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
INSERT
  INTO rhnArchTypeActions (arch_type_id, action_style, action_type_id)
       (SELECT ArchT.id, 'install', ActionT.id
          FROM rhnArchType ArchT, rhnActionType ActionT
	 WHERE ArchT.label = 'rpm'
	   AND ActionT.label = 'packages.update');

INSERT
  INTO rhnArchTypeActions (arch_type_id, action_style, action_type_id)
       (SELECT ArchT.id, 'remove', ActionT.id
          FROM rhnArchType ArchT, rhnActionType ActionT
	 WHERE ArchT.label = 'rpm'
	   AND ActionT.label = 'packages.remove');

INSERT
  INTO rhnArchTypeActions (arch_type_id, action_style, action_type_id)
       (SELECT ArchT.id, 'install', ActionT.id
          FROM rhnArchType ArchT, rhnActionType ActionT
	 WHERE ArchT.label = 'sysv-solaris'
	   AND ActionT.label = 'solarispkgs.install');

INSERT
  INTO rhnArchTypeActions (arch_type_id, action_style, action_type_id)
       (SELECT ArchT.id, 'remove', ActionT.id
          FROM rhnArchType ArchT, rhnActionType ActionT
	 WHERE ArchT.label = 'sysv-solaris'
	   AND ActionT.label = 'solarispkgs.remove');

INSERT
  INTO rhnArchTypeActions (arch_type_id, action_style, action_type_id)
       (SELECT ArchT.id, 'install', ActionT.id
          FROM rhnArchType ArchT, rhnActionType ActionT
	 WHERE ArchT.label = 'solaris-patch'
	   AND ActionT.label = 'solarispkgs.patchInstall');

INSERT
  INTO rhnArchTypeActions (arch_type_id, action_style, action_type_id)
       (SELECT ArchT.id, 'remove', ActionT.id
          FROM rhnArchType ArchT, rhnActionType ActionT
	 WHERE ArchT.label = 'solaris-patch'
	   AND ActionT.label = 'solarispkgs.patchRemove');

INSERT
  INTO rhnArchTypeActions (arch_type_id, action_style, action_type_id)
       (SELECT ArchT.id, 'install', ActionT.id
          FROM rhnArchType ArchT, rhnActionType ActionT
	 WHERE ArchT.label = 'solaris-patch-cluster'
	   AND ActionT.label = 'solarispkgs.patchClusterInstall');

INSERT
  INTO rhnArchTypeActions (arch_type_id, action_style, action_type_id)
       (SELECT ArchT.id, 'remove', ActionT.id
          FROM rhnArchType ArchT, rhnActionType ActionT
	 WHERE ArchT.label = 'solaris-patch-cluster'
	   AND ActionT.label = 'solarispkgs.patchClusterRemove');

INSERT
  INTO rhnArchTypeActions (arch_type_id, action_style, action_type_id)
       (SELECT ArchT.id, 'refresh_list', ActionT.id
          FROM rhnArchType ArchT, rhnActionType ActionT
         WHERE ArchT.label = 'sysv-solaris'
           AND ActionT.label = 'solarispkgs.refresh_list');

INSERT
  INTO rhnArchTypeActions (arch_type_id, action_style, action_type_id)
       (SELECT ArchT.id, 'refresh_list', ActionT.id
          FROM rhnArchType ArchT, rhnActionType ActionT
         WHERE ArchT.label = 'rpm'
           AND ActionT.label = 'packages.refresh_list');

INSERT
  INTO rhnArchTypeActions (arch_type_id, action_style, action_type_id)
       (SELECT ArchT.id, 'verify', ActionT.id
          FROM rhnArchType ArchT, rhnActionType ActionT
         WHERE ArchT.label = 'rpm'
           AND ActionT.label = 'packages.verify');

commit;
 0707010000000D000081B400000000000000000000000167AE111400001305000000000000000000000000000000000000003200000000susemanager-schema/common/data/rhnChannelArch.sql --
-- Copyright (c) 2008--2014 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--
--
-- Please note when adding new architectures also update the file
-- StringResource_*.xml (search for rhnChannelArch.sql comment).

insert into rhnChannelArch (id, label, name, arch_type_id) values
(sequence_nextval('rhn_channel_arch_id_seq'), 'channel-ia32', 'IA-32', lookup_arch_type('rpm'));

insert into rhnChannelArch (id, label, name, arch_type_id) values
(sequence_nextval('rhn_channel_arch_id_seq'), 'channel-ia32-deb', 'IA-32 Debian', lookup_arch_type('deb'));

insert into rhnChannelArch (id, label, name, arch_type_id) values
(sequence_nextval('rhn_channel_arch_id_seq'), 'channel-ia64', 'IA-64', lookup_arch_type('rpm'));

insert into rhnChannelArch (id, label, name, arch_type_id) values
(sequence_nextval('rhn_channel_arch_id_seq'), 'channel-ia64-deb', 'IA-64 Debian', lookup_arch_type('deb'));

insert into rhnChannelArch (id, label, name, arch_type_id) values
(sequence_nextval('rhn_channel_arch_id_seq'), 'channel-sparc', 'Sparc', lookup_arch_type('rpm'));

insert into rhnChannelArch (id, label, name, arch_type_id) values
(sequence_nextval('rhn_channel_arch_id_seq'), 'channel-sparc-deb', 'Sparc Debian', lookup_arch_type('deb'));

insert into rhnChannelArch (id, label, name, arch_type_id) values
(sequence_nextval('rhn_channel_arch_id_seq'), 'channel-alpha', 'Alpha', lookup_arch_type('rpm'));

insert into rhnChannelArch (id, label, name, arch_type_id) values
(sequence_nextval('rhn_channel_arch_id_seq'), 'channel-alpha-deb', 'Alpha Debian', lookup_arch_type('deb'));

insert into rhnChannelArch (id, label, name, arch_type_id) values
(sequence_nextval('rhn_channel_arch_id_seq'), 'channel-s390', 's390', lookup_arch_type('rpm'));

insert into rhnChannelArch (id, label, name, arch_type_id) values
(sequence_nextval('rhn_channel_arch_id_seq'), 'channel-s390-deb', 's390 Debian', lookup_arch_type('deb'));

insert into rhnChannelArch (id, label, name, arch_type_id) values
(sequence_nextval('rhn_channel_arch_id_seq'), 'channel-s390x', 's390x', lookup_arch_type('rpm'));

insert into rhnChannelArch (id, label, name, arch_type_id) values
(sequence_nextval('rhn_channel_arch_id_seq'), 'channel-iSeries', 'iSeries', lookup_arch_type('rpm'));

insert into rhnChannelArch (id, label, name, arch_type_id) values
(sequence_nextval('rhn_channel_arch_id_seq'), 'channel-pSeries', 'pSeries', lookup_arch_type('rpm'));

insert into rhnChannelArch (id, label, name, arch_type_id) values
(sequence_nextval('rhn_channel_arch_id_seq'), 'channel-x86_64', 'x86_64', lookup_arch_type('rpm'));

insert into rhnChannelArch (id, label, name, arch_type_id) values
(sequence_nextval('rhn_channel_arch_id_seq'), 'channel-amd64-deb', 'AMD64 Debian', lookup_arch_type('deb'));

insert into rhnChannelArch (id, label, name, arch_type_id) values
(sequence_nextval('rhn_channel_arch_id_seq'), 'channel-ppc', 'PPC', lookup_arch_type('rpm'));

insert into rhnChannelArch (id, label, name, arch_type_id) values
(sequence_nextval('rhn_channel_arch_id_seq'), 'channel-ppc64le', 'PPC64LE', lookup_arch_type('rpm'));

insert into rhnChannelArch (id, label, name, arch_type_id) values
(sequence_nextval('rhn_channel_arch_id_seq'), 'channel-powerpc-deb', 'PowerPC Debian', lookup_arch_type('deb'));

insert into rhnChannelArch (id, label, name, arch_type_id) values
(sequence_nextval('rhn_channel_arch_id_seq'), 'channel-arm', 'ARM soft. FP', lookup_arch_type('rpm'));

insert into rhnChannelArch (id, label, name, arch_type_id) values
(sequence_nextval('rhn_channel_arch_id_seq'), 'channel-armhfp', 'ARM hard. FP', lookup_arch_type('rpm'));

insert into rhnChannelArch (id, label, name, arch_type_id) values
(sequence_nextval('rhn_channel_arch_id_seq'), 'channel-aarch64', 'AArch64', lookup_arch_type('rpm'));

insert into rhnChannelArch (id, label, name, arch_type_id) values
(sequence_nextval('rhn_channel_arch_id_seq'), 'channel-arm-deb', 'arm Debian', lookup_arch_type('deb'));

insert into rhnChannelArch (id, label, name, arch_type_id) values
(sequence_nextval('rhn_channel_arch_id_seq'), 'channel-mips-deb', 'mips Debian', lookup_arch_type('deb'));

insert into rhnChannelArch (id, label, name, arch_type_id) values
(sequence_nextval('rhn_channel_arch_id_seq'), 'channel-arm64-deb', 'ARM64 Debian', lookup_arch_type('deb'));

commit;

   0707010000000E000081B400000000000000000000000167AE111400004525000000000000000000000000000000000000003F00000000susemanager-schema/common/data/rhnChannelPackageArchCompat.sql    --
-- Copyright (c) 2008--2014 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--

insert into rhnChannelPackageArchCompat (channel_arch_id, package_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-ia32'), LOOKUP_PACKAGE_ARCH('noarch'));

insert into rhnChannelPackageArchCompat (channel_arch_id, package_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-ia32'), LOOKUP_PACKAGE_ARCH('i386'));

insert into rhnChannelPackageArchCompat (channel_arch_id, package_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-ia32'), LOOKUP_PACKAGE_ARCH('i486'));

insert into rhnChannelPackageArchCompat (channel_arch_id, package_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-ia32'), LOOKUP_PACKAGE_ARCH('i586'));

insert into rhnChannelPackageArchCompat (channel_arch_id, package_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-ia32'), LOOKUP_PACKAGE_ARCH('i686'));

insert into rhnChannelPackageArchCompat (channel_arch_id, package_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-ia32'), LOOKUP_PACKAGE_ARCH('src'));

insert into rhnChannelPackageArchCompat (channel_arch_id, package_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-ia32'), LOOKUP_PACKAGE_ARCH('athlon'));

insert into rhnChannelPackageArchCompat (channel_arch_id, package_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-ia32-deb'), LOOKUP_PACKAGE_ARCH('all-deb'));

insert into rhnChannelPackageArchCompat (channel_arch_id, package_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-ia32-deb'), LOOKUP_PACKAGE_ARCH('i386-deb'));

insert into rhnChannelPackageArchCompat (channel_arch_id, package_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-ia32-deb'), LOOKUP_PACKAGE_ARCH('src-deb'));

insert into rhnChannelPackageArchCompat (channel_arch_id, package_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-ia64'), LOOKUP_PACKAGE_ARCH('noarch'));

insert into rhnChannelPackageArchCompat (channel_arch_id, package_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-ia64'), LOOKUP_PACKAGE_ARCH('i386'));

insert into rhnChannelPackageArchCompat (channel_arch_id, package_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-ia64'), LOOKUP_PACKAGE_ARCH('i486'));

insert into rhnChannelPackageArchCompat (channel_arch_id, package_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-ia64'), LOOKUP_PACKAGE_ARCH('i586'));

insert into rhnChannelPackageArchCompat (channel_arch_id, package_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-ia64'), LOOKUP_PACKAGE_ARCH('i686'));

insert into rhnChannelPackageArchCompat (channel_arch_id, package_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-ia64'), LOOKUP_PACKAGE_ARCH('ia64'));

insert into rhnChannelPackageArchCompat (channel_arch_id, package_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-ia64'), LOOKUP_PACKAGE_ARCH('src'));

insert into rhnChannelPackageArchCompat (channel_arch_id, package_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-aarch64'), LOOKUP_PACKAGE_ARCH('aarch64'));

insert into rhnChannelPackageArchCompat (channel_arch_id, package_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-aarch64'), LOOKUP_PACKAGE_ARCH('noarch'));

insert into rhnChannelPackageArchCompat (channel_arch_id, package_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-armhfp'), LOOKUP_PACKAGE_ARCH('armv7hl'));

insert into rhnChannelPackageArchCompat (channel_arch_id, package_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-armhfp'), LOOKUP_PACKAGE_ARCH('armv7hnl'));

insert into rhnChannelPackageArchCompat (channel_arch_id, package_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-armhfp'), LOOKUP_PACKAGE_ARCH('noarch'));

insert into rhnChannelPackageArchCompat (channel_arch_id, package_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-arm'), LOOKUP_PACKAGE_ARCH('noarch'));

insert into rhnChannelPackageArchCompat (channel_arch_id, package_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-arm'), LOOKUP_PACKAGE_ARCH('armv5tel'));

insert into rhnChannelPackageArchCompat (channel_arch_id, package_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-arm'), LOOKUP_PACKAGE_ARCH('armv6hl'));

insert into rhnChannelPackageArchCompat (channel_arch_id, package_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-arm'), LOOKUP_PACKAGE_ARCH('armv6l'));

insert into rhnChannelPackageArchCompat (channel_arch_id, package_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-arm'), LOOKUP_PACKAGE_ARCH('armv7l'));

insert into rhnChannelPackageArchCompat (channel_arch_id, package_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-ia64-deb'), LOOKUP_PACKAGE_ARCH('all-deb'));

insert into rhnChannelPackageArchCompat (channel_arch_id, package_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-ia64-deb'), LOOKUP_PACKAGE_ARCH('i386-deb'));

insert into rhnChannelPackageArchCompat (channel_arch_id, package_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-ia64-deb'), LOOKUP_PACKAGE_ARCH('ia64-deb'));

insert into rhnChannelPackageArchCompat (channel_arch_id, package_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-ia64-deb'), LOOKUP_PACKAGE_ARCH('src-deb'));


insert into rhnChannelPackageArchCompat (channel_arch_id, package_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-sparc'), LOOKUP_PACKAGE_ARCH('noarch'));

insert into rhnChannelPackageArchCompat (channel_arch_id, package_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-sparc'), LOOKUP_PACKAGE_ARCH('sparc'));

insert into rhnChannelPackageArchCompat (channel_arch_id, package_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-sparc'), LOOKUP_PACKAGE_ARCH('sparcv9'));

insert into rhnChannelPackageArchCompat (channel_arch_id, package_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-sparc'), LOOKUP_PACKAGE_ARCH('sparc64'));

insert into rhnChannelPackageArchCompat (channel_arch_id, package_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-sparc'), LOOKUP_PACKAGE_ARCH('src'));

insert into rhnChannelPackageArchCompat (channel_arch_id, package_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-sparc-deb'), LOOKUP_PACKAGE_ARCH('all-deb'));

insert into rhnChannelPackageArchCompat (channel_arch_id, package_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-sparc-deb'), LOOKUP_PACKAGE_ARCH('sparc-deb'));

insert into rhnChannelPackageArchCompat (channel_arch_id, package_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-sparc-deb'), LOOKUP_PACKAGE_ARCH('src-deb'));


insert into rhnChannelPackageArchCompat (channel_arch_id, package_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-alpha'), LOOKUP_PACKAGE_ARCH('noarch'));

insert into rhnChannelPackageArchCompat (channel_arch_id, package_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-alpha'), LOOKUP_PACKAGE_ARCH('alpha'));

insert into rhnChannelPackageArchCompat (channel_arch_id, package_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-alpha'), LOOKUP_PACKAGE_ARCH('alphaev6'));

insert into rhnChannelPackageArchCompat (channel_arch_id, package_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-alpha'), LOOKUP_PACKAGE_ARCH('src'));

insert into rhnChannelPackageArchCompat (channel_arch_id, package_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-alpha-deb'), LOOKUP_PACKAGE_ARCH('all-deb'));

insert into rhnChannelPackageArchCompat (channel_arch_id, package_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-alpha-deb'), LOOKUP_PACKAGE_ARCH('alpha-deb'));

insert into rhnChannelPackageArchCompat (channel_arch_id, package_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-alpha-deb'), LOOKUP_PACKAGE_ARCH('src-deb'));


insert into rhnChannelPackageArchCompat (channel_arch_id, package_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-s390'), LOOKUP_PACKAGE_ARCH('noarch'));

insert into rhnChannelPackageArchCompat (channel_arch_id, package_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-s390'), LOOKUP_PACKAGE_ARCH('s390'));

insert into rhnChannelPackageArchCompat (channel_arch_id, package_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-s390'), LOOKUP_PACKAGE_ARCH('src'));

insert into rhnChannelPackageArchCompat (channel_arch_id, package_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-s390-deb'), LOOKUP_PACKAGE_ARCH('all-deb'));

insert into rhnChannelPackageArchCompat (channel_arch_id, package_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-s390-deb'), LOOKUP_PACKAGE_ARCH('s390-deb'));

insert into rhnChannelPackageArchCompat (channel_arch_id, package_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-s390-deb'), LOOKUP_PACKAGE_ARCH('src-deb'));


insert into rhnChannelPackageArchCompat (channel_arch_id, package_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-s390x'), LOOKUP_PACKAGE_ARCH('noarch'));

insert into rhnChannelPackageArchCompat (channel_arch_id, package_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-s390x'), LOOKUP_PACKAGE_ARCH('s390'));

insert into rhnChannelPackageArchCompat (channel_arch_id, package_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-s390x'), LOOKUP_PACKAGE_ARCH('s390x'));

insert into rhnChannelPackageArchCompat (channel_arch_id, package_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-s390x'), LOOKUP_PACKAGE_ARCH('src'));


insert into rhnChannelPackageArchCompat (channel_arch_id, package_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-iSeries'), LOOKUP_PACKAGE_ARCH('noarch'));

insert into rhnChannelPackageArchCompat (channel_arch_id, package_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-iSeries'), LOOKUP_PACKAGE_ARCH('s390x'));

insert into rhnChannelPackageArchCompat (channel_arch_id, package_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-iSeries'), LOOKUP_PACKAGE_ARCH('ppc'));

insert into rhnChannelPackageArchCompat (channel_arch_id, package_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-iSeries'), LOOKUP_PACKAGE_ARCH('ppc64'));

insert into rhnChannelPackageArchCompat (channel_arch_id, package_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-iSeries'), LOOKUP_PACKAGE_ARCH('src'));


insert into rhnChannelPackageArchCompat (channel_arch_id, package_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-pSeries'), LOOKUP_PACKAGE_ARCH('noarch'));

insert into rhnChannelPackageArchCompat (channel_arch_id, package_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-pSeries'), LOOKUP_PACKAGE_ARCH('ppc'));

insert into rhnChannelPackageArchCompat (channel_arch_id, package_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-pSeries'), LOOKUP_PACKAGE_ARCH('ppc64'));

insert into rhnChannelPackageArchCompat (channel_arch_id, package_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-pSeries'), LOOKUP_PACKAGE_ARCH('src'));


insert into rhnChannelPackageArchCompat (channel_arch_id, package_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-x86_64'), LOOKUP_PACKAGE_ARCH('noarch'));

insert into rhnChannelPackageArchCompat (channel_arch_id, package_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-x86_64'), LOOKUP_PACKAGE_ARCH('i386'));

insert into rhnChannelPackageArchCompat (channel_arch_id, package_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-x86_64'), LOOKUP_PACKAGE_ARCH('i486'));

insert into rhnChannelPackageArchCompat (channel_arch_id, package_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-x86_64'), LOOKUP_PACKAGE_ARCH('i586'));

insert into rhnChannelPackageArchCompat (channel_arch_id, package_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-x86_64'), LOOKUP_PACKAGE_ARCH('i686'));

insert into rhnChannelPackageArchCompat (channel_arch_id, package_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-x86_64'), LOOKUP_PACKAGE_ARCH('athlon'));

insert into rhnChannelPackageArchCompat (channel_arch_id, package_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-x86_64'), LOOKUP_PACKAGE_ARCH('ia32e'));

insert into rhnChannelPackageArchCompat (channel_arch_id, package_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-x86_64'), LOOKUP_PACKAGE_ARCH('amd64'));

insert into rhnChannelPackageArchCompat (channel_arch_id, package_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-x86_64'), LOOKUP_PACKAGE_ARCH('x86_64'));

insert into rhnChannelPackageArchCompat (channel_arch_id, package_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-x86_64'), LOOKUP_PACKAGE_ARCH('src'));

insert into rhnChannelPackageArchCompat (channel_arch_id, package_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-amd64-deb'), LOOKUP_PACKAGE_ARCH('all-deb'));

insert into rhnChannelPackageArchCompat (channel_arch_id, package_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-amd64-deb'), LOOKUP_PACKAGE_ARCH('i386-deb'));

insert into rhnChannelPackageArchCompat (channel_arch_id, package_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-amd64-deb'), LOOKUP_PACKAGE_ARCH('amd64-deb'));

insert into rhnChannelPackageArchCompat (channel_arch_id, package_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-amd64-deb'), LOOKUP_PACKAGE_ARCH('src-deb'));


insert into rhnChannelPackageArchCompat (channel_arch_id, package_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-ppc'), LOOKUP_PACKAGE_ARCH('noarch'));

insert into rhnChannelPackageArchCompat (channel_arch_id, package_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-ppc'), LOOKUP_PACKAGE_ARCH('ppc'));

insert into rhnChannelPackageArchCompat (channel_arch_id, package_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-ppc'), LOOKUP_PACKAGE_ARCH('ppc64'));

insert into rhnChannelPackageArchCompat (channel_arch_id, package_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-ppc'), LOOKUP_PACKAGE_ARCH('ppc64iseries'));

insert into rhnChannelPackageArchCompat (channel_arch_id, package_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-ppc'), LOOKUP_PACKAGE_ARCH('ppc64pseries'));

insert into rhnChannelPackageArchCompat (channel_arch_id, package_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-ppc'), LOOKUP_PACKAGE_ARCH('src'));

insert into rhnChannelPackageArchCompat (channel_arch_id, package_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-ppc64le'), LOOKUP_PACKAGE_ARCH('noarch'));

insert into rhnChannelPackageArchCompat (channel_arch_id, package_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-ppc64le'), LOOKUP_PACKAGE_ARCH('ppc64le'));

insert into rhnChannelPackageArchCompat (channel_arch_id, package_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-powerpc-deb'), LOOKUP_PACKAGE_ARCH('all-deb'));

insert into rhnChannelPackageArchCompat (channel_arch_id, package_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-powerpc-deb'), LOOKUP_PACKAGE_ARCH('powerpc-deb'));

insert into rhnChannelPackageArchCompat (channel_arch_id, package_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-powerpc-deb'), LOOKUP_PACKAGE_ARCH('src-deb'));

insert into rhnChannelPackageArchCompat (channel_arch_id, package_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-arm-deb'), LOOKUP_PACKAGE_ARCH('all-deb'));

insert into rhnChannelPackageArchCompat (channel_arch_id, package_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-arm-deb'), LOOKUP_PACKAGE_ARCH('arm-deb'));

insert into rhnChannelPackageArchCompat (channel_arch_id, package_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-arm-deb'), LOOKUP_PACKAGE_ARCH('armhf-deb'));

insert into rhnChannelPackageArchCompat (channel_arch_id, package_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-arm-deb'), LOOKUP_PACKAGE_ARCH('src-deb'));

insert into rhnChannelPackageArchCompat (channel_arch_id, package_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-mips-deb'), LOOKUP_PACKAGE_ARCH('all-deb'));

insert into rhnChannelPackageArchCompat (channel_arch_id, package_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-mips-deb'), LOOKUP_PACKAGE_ARCH('mips-deb'));

insert into rhnChannelPackageArchCompat (channel_arch_id, package_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-mips-deb'), LOOKUP_PACKAGE_ARCH('src-deb'));

insert into rhnChannelPackageArchCompat (channel_arch_id, package_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-ia32'), LOOKUP_PACKAGE_ARCH('nosrc'));

insert into rhnChannelPackageArchCompat (channel_arch_id, package_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-ia64'), LOOKUP_PACKAGE_ARCH('nosrc'));

insert into rhnChannelPackageArchCompat (channel_arch_id, package_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-sparc'), LOOKUP_PACKAGE_ARCH('nosrc'));

insert into rhnChannelPackageArchCompat (channel_arch_id, package_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-alpha'), LOOKUP_PACKAGE_ARCH('nosrc'));

insert into rhnChannelPackageArchCompat (channel_arch_id, package_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-s390'), LOOKUP_PACKAGE_ARCH('nosrc'));

insert into rhnChannelPackageArchCompat (channel_arch_id, package_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-s390x'), LOOKUP_PACKAGE_ARCH('nosrc'));

insert into rhnChannelPackageArchCompat (channel_arch_id, package_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-iSeries'), LOOKUP_PACKAGE_ARCH('nosrc'));

insert into rhnChannelPackageArchCompat (channel_arch_id, package_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-pSeries'), LOOKUP_PACKAGE_ARCH('nosrc'));

insert into rhnChannelPackageArchCompat (channel_arch_id, package_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-x86_64'), LOOKUP_PACKAGE_ARCH('nosrc'));

insert into rhnChannelPackageArchCompat (channel_arch_id, package_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-ppc'), LOOKUP_PACKAGE_ARCH('nosrc'));

insert into rhnChannelPackageArchCompat (channel_arch_id, package_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-arm64-deb'), LOOKUP_PACKAGE_ARCH('arm64-deb'));

insert into rhnChannelPackageArchCompat (channel_arch_id, package_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-arm64-deb'), LOOKUP_PACKAGE_ARCH('all-deb'));

insert into rhnChannelPackageArchCompat (channel_arch_id, package_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-arm64-deb'), LOOKUP_PACKAGE_ARCH('src-deb'));

commit;
   0707010000000F000081B400000000000000000000000167AE1114000003CB000000000000000000000000000000000000003C00000000susemanager-schema/common/data/rhnChannelPermissionRole.sql   --
-- Copyright (c) 2008--2013 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--

insert into rhnChannelPermissionRole (id, label, description)
	values (sequence_nextval('rhn_cperm_role_id_seq'),
		'subscribe',
		'Permission to subscribe to channel');
insert into rhnChannelPermissionRole (id, label, description)
	values (sequence_nextval('rhn_cperm_role_id_seq'),
		'manage',
		'Permission to manage channel');

 07070100000010000081B400000000000000000000000167AE111400000537000000000000000000000000000000000000003300000000susemanager-schema/common/data/rhnChecksumType.sql    --
-- Copyright (c) 2008--2010 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--


insert into rhnChecksumType (id, label, description) values
            (sequence_nextval('rhn_checksum_id_seq'), 'md5', 'MD5sum' );
insert into rhnChecksumType (id, label, description) values
            (sequence_nextval('rhn_checksum_id_seq'), 'sha1', 'SHA1sum' );
insert into rhnChecksumType (id, label, description) values
            (sequence_nextval('rhn_checksum_id_seq'), 'sha256', 'SHA256sum' );
insert into rhnChecksumType (id, label, description) values
            (sequence_nextval('rhn_checksum_id_seq'), 'sha384', 'SHA384sum' );
insert into rhnChecksumType (id, label, description) values
            (sequence_nextval('rhn_checksum_id_seq'), 'sha512', 'SHA512sum' );

commit;

 07070100000011000081B400000000000000000000000167AE111400001486000000000000000000000000000000000000003D00000000susemanager-schema/common/data/rhnChildChannelArchCompat.sql  --
-- Copyright (c) 2014 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--

insert into rhnChildChannelArchCompat (parent_arch_id, child_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-ia32'), LOOKUP_CHANNEL_ARCH('channel-ia32'));

insert into rhnChildChannelArchCompat (parent_arch_id, child_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-ia64'), LOOKUP_CHANNEL_ARCH('channel-ia32'));

insert into rhnChildChannelArchCompat (parent_arch_id, child_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-ia64'), LOOKUP_CHANNEL_ARCH('channel-ia64'));

insert into rhnChildChannelArchCompat (parent_arch_id, child_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-ia32-deb'), LOOKUP_CHANNEL_ARCH('channel-ia32-deb'));

insert into rhnChildChannelArchCompat (parent_arch_id, child_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-ia64-deb'), LOOKUP_CHANNEL_ARCH('channel-ia32-deb'));

insert into rhnChildChannelArchCompat (parent_arch_id, child_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-ia64-deb'), LOOKUP_CHANNEL_ARCH('channel-ia64-deb'));

insert into rhnChildChannelArchCompat (parent_arch_id, child_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-sparc'), LOOKUP_CHANNEL_ARCH('channel-sparc'));

insert into rhnChildChannelArchCompat (parent_arch_id, child_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-sparc-deb'), LOOKUP_CHANNEL_ARCH('channel-sparc-deb'));

insert into rhnChildChannelArchCompat (parent_arch_id, child_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-alpha'), LOOKUP_CHANNEL_ARCH('channel-alpha'));

insert into rhnChildChannelArchCompat (parent_arch_id, child_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-alpha-deb'), LOOKUP_CHANNEL_ARCH('channel-alpha-deb'));

insert into rhnChildChannelArchCompat (parent_arch_id, child_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-s390'), LOOKUP_CHANNEL_ARCH('channel-s390'));

insert into rhnChildChannelArchCompat (parent_arch_id, child_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-s390-deb'), LOOKUP_CHANNEL_ARCH('channel-s390-deb'));

insert into rhnChildChannelArchCompat (parent_arch_id, child_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-s390x'), LOOKUP_CHANNEL_ARCH('channel-s390'));

insert into rhnChildChannelArchCompat (parent_arch_id, child_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-s390x'), LOOKUP_CHANNEL_ARCH('channel-s390x'));

insert into rhnChildChannelArchCompat (parent_arch_id, child_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-iSeries'), LOOKUP_CHANNEL_ARCH('channel-iSeries'));

insert into rhnChildChannelArchCompat (parent_arch_id, child_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-pSeries'), LOOKUP_CHANNEL_ARCH('channel-pSeries'));

insert into rhnChildChannelArchCompat (parent_arch_id, child_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-x86_64'), LOOKUP_CHANNEL_ARCH('channel-ia32'));

insert into rhnChildChannelArchCompat (parent_arch_id, child_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-x86_64'), LOOKUP_CHANNEL_ARCH('channel-x86_64'));

insert into rhnChildChannelArchCompat (parent_arch_id, child_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-amd64-deb'), LOOKUP_CHANNEL_ARCH('channel-ia32-deb'));

insert into rhnChildChannelArchCompat (parent_arch_id, child_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-amd64-deb'), LOOKUP_CHANNEL_ARCH('channel-amd64-deb'));

insert into rhnChildChannelArchCompat (parent_arch_id, child_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-ppc'), LOOKUP_CHANNEL_ARCH('channel-ppc'));

insert into rhnChildChannelArchCompat (parent_arch_id, child_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-powerpc-deb'), LOOKUP_CHANNEL_ARCH('channel-powerpc-deb'));

insert into rhnChildChannelArchCompat (parent_arch_id, child_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-arm'), LOOKUP_CHANNEL_ARCH('channel-arm'));

insert into rhnChildChannelArchCompat (parent_arch_id, child_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-armhfp'), LOOKUP_CHANNEL_ARCH('channel-armhfp'));

insert into rhnChildChannelArchCompat (parent_arch_id, child_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-arm-deb'), LOOKUP_CHANNEL_ARCH('channel-arm-deb'));

insert into rhnChildChannelArchCompat (parent_arch_id, child_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-mips-deb'), LOOKUP_CHANNEL_ARCH('channel-mips-deb'));

insert into rhnChildChannelArchCompat (parent_arch_id, child_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-aarch64'), LOOKUP_CHANNEL_ARCH('channel-aarch64'));

insert into rhnChildChannelArchCompat (parent_arch_id, child_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-ppc64le'), LOOKUP_CHANNEL_ARCH('channel-ppc64le'));

insert into rhnChildChannelArchCompat (parent_arch_id, child_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-arm64-deb'), LOOKUP_CHANNEL_ARCH('channel-arm64-deb'));

commit;

  07070100000012000081B400000000000000000000000167AE111400000326000000000000000000000000000000000000003000000000susemanager-schema/common/data/rhnCompsType.sql   --
-- Copyright (c) 2018 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

INSERT INTO rhnCompsType (id, label) VALUES (1, 'comps');
INSERT INTO rhnCompsType (id, label) VALUES (2, 'modules');
INSERT INTO rhnCompsType (id, label) VALUES (3, 'mediaproducts');
  07070100000013000081B400000000000000000000000167AE111400000530000000000000000000000000000000000000003800000000susemanager-schema/common/data/rhnConfigChannelType.sql   --
-- Copyright (c) 2008--2013 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--

insert into rhnConfigChannelType(id, label, name, priority) values (
	sequence_nextval('rhn_confchantype_id_seq'), 'normal',
	'A general purpose configuration channel', 1);

insert into rhnConfigChannelType(id, label, name, priority) values (
	sequence_nextval('rhn_confchantype_id_seq'), 'local_override',
	'Files on disk win', 0);

insert into rhnConfigChannelType(id, label, name, priority) values (
	sequence_nextval('rhn_confchantype_id_seq'), 'server_import',
	'Files imported from the server', 2);

insert into rhnConfigChannelType(id, label, name, priority) values (
	sequence_nextval('rhn_confchantype_id_seq'), 'state',
	'Configuration channel based on SALT state', 1);

commit;
07070100000014000081B400000000000000000000000167AE1114000004E6000000000000000000000000000000000000003800000000susemanager-schema/common/data/rhnConfigFileFailure.sql   --
-- Copyright (c) 2008--2013 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--

insert into rhnConfigFileFailure (id, label, name) values
    (sequence_nextval('rhn_conffile_failure_id_seq'), 'missing',
    'Missing file');

insert into rhnConfigFileFailure (id, label, name) values
    (sequence_nextval('rhn_conffile_failure_id_seq'), 'too_big',
    'File too big');

insert into rhnConfigFileFailure (id, label, name) values
    (sequence_nextval('rhn_conffile_failure_id_seq'), 'binary_file',
    'Binary file');

insert into rhnConfigFileFailure (id, label, name) values
    (sequence_nextval('rhn_conffile_failure_id_seq'), 'insufficient_quota',
    'Insufficient free quota space');


commit;

  07070100000015000081B400000000000000000000000167AE11140000038B000000000000000000000000000000000000003600000000susemanager-schema/common/data/rhnConfigFileState.sql --
-- Copyright (c) 2008--2013 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--

insert into rhnConfigFileState(id, label, name) values
	(sequence_nextval('rhn_cfstate_id_seq'), 'dead', 'Will not be deployed');

insert into rhnConfigFileState(id, label, name) values
	(sequence_nextval('rhn_cfstate_id_seq'), 'alive', 'Will be deployed');

commit;

 07070100000016000081B400000000000000000000000167AE11140000040E000000000000000000000000000000000000003500000000susemanager-schema/common/data/rhnConfigFileType.sql  --
-- Copyright (c) 2008--2013 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--

insert into rhnConfigFileType values (1, 'file', 'File', current_timestamp, current_timestamp);
insert into rhnConfigFileType values (2, 'directory', 'Directory', current_timestamp, current_timestamp);
insert into rhnConfigFileType values (3, 'symlink', 'Symlink', current_timestamp, current_timestamp);
insert into rhnConfigFileType values (4, 'sls', 'SLS', current_timestamp, current_timestamp);

  07070100000017000081B400000000000000000000000167AE111400000242000000000000000000000000000000000000003400000000susemanager-schema/common/data/rhnConfiguration.sql   INSERT INTO rhnConfiguration (key, description) VALUES ('extauth_default_orgid', 'Organization id, where externally authenticated users will be created.');
INSERT INTO rhnConfiguration (key, description, default_value) VALUES ('extauth_use_orgunit', 'Use Org. Unit IPA setting as organization name to create externally authenticated users in.', 'false');
INSERT INTO rhnConfiguration (key, description, default_value) VALUES ('extauth_keep_temproles', 'Keep temporary user roles granted due to the external authentication setup for subsequent logins using password.', 'false');
  07070100000018000081B400000000000000000000000167AE1114000003D0000000000000000000000000000000000000003800000000susemanager-schema/common/data/rhnContentSourceType.sql   --
-- Copyright (c) 2008--2010 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--
--
--
--

insert into rhnContentSourceType (id, label) values
(sequence_nextval('rhn_content_source_type_id_seq'), 'yum');
insert into rhnContentSourceType (id, label) values
(sequence_nextval('rhn_content_source_type_id_seq'), 'uln');
insert into rhnContentSourceType (id, label) values
(sequence_nextval('rhn_content_source_type_id_seq'), 'deb');
07070100000019000081B400000000000000000000000167AE11140000104A000000000000000000000000000000000000002E00000000susemanager-schema/common/data/rhnCpuArch.sql --
-- Copyright (c) 2008--2014 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--

insert into rhnCpuArch (id, label, name) values
(sequence_nextval('rhn_cpu_arch_id_seq'), 'i386', 'i386');
insert into rhnCpuArch (id, label, name) values
(sequence_nextval('rhn_cpu_arch_id_seq'), 'i486', 'i486');
insert into rhnCpuArch (id, label, name) values
(sequence_nextval('rhn_cpu_arch_id_seq'), 'i586', 'i586');
insert into rhnCpuArch (id, label, name) values
(sequence_nextval('rhn_cpu_arch_id_seq'), 'i686', 'i686');
insert into rhnCpuArch (id, label, name) values
(sequence_nextval('rhn_cpu_arch_id_seq'), 'athlon', 'athlon');
insert into rhnCpuArch (id, label, name) values
(sequence_nextval('rhn_cpu_arch_id_seq'), 'alpha', 'alpha');
insert into rhnCpuArch (id, label, name) values
(sequence_nextval('rhn_cpu_arch_id_seq'), 'alphaev6', 'alphaev6');
insert into rhnCpuArch (id, label, name) values
(sequence_nextval('rhn_cpu_arch_id_seq'), 'ia64', 'ia64');
insert into rhnCpuArch (id, label, name) values
(sequence_nextval('rhn_cpu_arch_id_seq'), 'sparc', 'sparc');
insert into rhnCpuArch (id, label, name) values
(sequence_nextval('rhn_cpu_arch_id_seq'), 'sparcv9', 'sparcv9');
insert into rhnCpuArch (id, label, name) values
(sequence_nextval('rhn_cpu_arch_id_seq'), 'sparc64', 'sparc64');
insert into rhnCpuArch (id, label, name) values
(sequence_nextval('rhn_cpu_arch_id_seq'), 's390', 's390');
insert into rhnCpuArch (id, label, name) values
(sequence_nextval('rhn_cpu_arch_id_seq'), 's390x', 's390x');
insert into rhnCpuArch (id, label, name) values
(sequence_nextval('rhn_cpu_arch_id_seq'), 'ppc', 'ppc');
insert into rhnCpuArch (id, label, name) values
(sequence_nextval('rhn_cpu_arch_id_seq'), 'ppc64', 'ppc64');
insert into rhnCpuArch (id, label, name) values
(sequence_nextval('rhn_cpu_arch_id_seq'), 'ppc64le', 'ppc64le');
insert into rhnCpuArch (id, label, name) values
(sequence_nextval('rhn_cpu_arch_id_seq'), 'pSeries', 'pSeries');
insert into rhnCpuArch (id, label, name) values
(sequence_nextval('rhn_cpu_arch_id_seq'), 'iSeries', 'iSeries');
insert into rhnCpuArch (id, label, name) values
(sequence_nextval('rhn_cpu_arch_id_seq'), 'x86_64', 'x86_64');
insert into rhnCpuArch (id, label, name) values
(sequence_nextval('rhn_cpu_arch_id_seq'), 'sun4u', 'sun4u');
insert into rhnCpuArch (id, label, name) values
(sequence_nextval('rhn_cpu_arch_id_seq'), 'sun4v', 'sun4v');
insert into rhnCpuArch (id, label, name) values
(sequence_nextval('rhn_cpu_arch_id_seq'), 'sun4m', 'sun4m');
insert into rhnCpuArch (id, label, name) values
(sequence_nextval('rhn_cpu_arch_id_seq'), 'ia32e', 'EM64T');
insert into rhnCpuArch (id, label, name) values
(sequence_nextval('rhn_cpu_arch_id_seq'), 'amd64', 'AMD64');
insert into rhnCpuArch (id, label, name) values
(sequence_nextval('rhn_cpu_arch_id_seq'), 'i86pc', 'i86pc');
insert into rhnCpuArch (id, label, name) values
(sequence_nextval('rhn_cpu_arch_id_seq'), 'aarch64', 'AArch64');
insert into rhnCpuArch (id, label, name) values
(sequence_nextval('rhn_cpu_arch_id_seq'), 'armv7l', 'ARMv7l');
insert into rhnCpuArch (id, label, name) values
(sequence_nextval('rhn_cpu_arch_id_seq'), 'armv5tejl', 'ARMv5tejl');
insert into rhnCpuArch (id, label, name) values
(sequence_nextval('rhn_cpu_arch_id_seq'), 'armv6l', 'ARMv6l');
insert into rhnCpuArch (id, label, name) values
(sequence_nextval('rhn_cpu_arch_id_seq'), 'armv6hl', 'ARMv6hl');
insert into rhnCpuArch (id, label, name) values
(sequence_nextval('rhn_cpu_arch_id_seq'), 'cloud', 'cloud');
insert into rhnCpuArch (id, label, name) values
(sequence_nextval('rhn_cpu_arch_id_seq'), 'arm64', 'ARM64');
commit;

  0707010000001A000081B400000000000000000000000167AE11140000037B000000000000000000000000000000000000003400000000susemanager-schema/common/data/rhnCryptoKeyType.sql   --
-- Copyright (c) 2008--2013 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--

insert into rhnCryptoKeyType(id, label, description) values
	(sequence_nextval('rhn_cryptokeytype_id_seq'),'GPG','GPG');
insert into rhnCryptoKeyType(id, label, description) values
	(sequence_nextval('rhn_cryptokeytype_id_seq'),'SSL','SSL');

commit;

 0707010000001B000081B400000000000000000000000167AE11140000043B000000000000000000000000000000000000003500000000susemanager-schema/common/data/rhnErrataFileType.sql  --
-- Copyright (c) 2008--2013 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--

insert into rhnErrataFileType ( id, label )
	values ( sequence_nextval('rhn_erratafile_type_id_seq'), 'RPM' );
insert into rhnErrataFileType ( id, label )
	values ( sequence_nextval('rhn_erratafile_type_id_seq'), 'SRPM' );
insert into rhnErrataFileType ( id, label )
	values ( sequence_nextval('rhn_erratafile_type_id_seq'), 'IMG' );
insert into rhnErrataFileType ( id, label )
	values ( sequence_nextval('rhn_erratafile_type_id_seq'), 'OVAL' );

 0707010000001C000081B400000000000000000000000167AE111400000393000000000000000000000000000000000000003500000000susemanager-schema/common/data/rhnErrataSeverity.sql  --
-- Copyright (c) 2008 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
INSERT INTO RHNErrataSeverity VALUES (0, 0, 'errata.sev.label.critical');
INSERT INTO RHNErrataSeverity VALUES (1, 1, 'errata.sev.label.important');
INSERT INTO RHNErrataSeverity VALUES (2, 2, 'errata.sev.label.moderate');
INSERT INTO RHNErrataSeverity VALUES (3, 3, 'errata.sev.label.low');
 0707010000001D000081B400000000000000000000000167AE1114000020DA000000000000000000000000000000000000003000000000susemanager-schema/common/data/rhnException.sql   --
-- Copyright (c) 2008--2013 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--
-- data for rhnException

insert into rhnException values (-20002, 'testing_error', 'An error used for testing and testing only');

insert into rhnException values (-20100, 'channel_no_parent_subscription', 'A server must be subscribed to the parent channel to subscribe to the child channel');
insert into rhnException values (-20101, 'channel_must_subscribe_to_parent', 'A server must be subscribed to all parents of all children');
insert into rhnException values (-20102, 'channel_server_one_base', 'A server can be subscribed to at most one base channel');

insert into rhnException values (-20200, 'usergroup_max_members', 'User group membership cannot exceed maximum membership');

insert into rhnException values (-20230, 'ugm_different_orgs', 'User and usergroup must be in same group to make a user a member');
insert into rhnException values (-20231, 'sgm_different_orgs', 'Server and servergroup must be in same group to make a server a member');
insert into rhnException values (-20232, 'no_org_admin_group', 'Organization has no org_admin usergroup');
insert into rhnException values (-20233, 'sg_delete_typed', 'Special server groups (non-null group_type) cannot be deleted');
insert into rhnException values (-20234, 'ug_delete_typed', 'Special user groups (non-null group_type) cannot be deleted');

insert into rhnException values (-20236, 'channel_subscribe_no_family', 'Attempt to subscribe to a channel with no family');

insert into rhnException values (-20237, 'invalid_enterprise_flag','Enterprise flag must be Y or N');

insert into rhnException values (-20238, 'channel_unsubscribe_no_family','Attempt to unsubscribe from a channel with no family');
insert into rhnException values (-20239, 'arch_not_found','Architecture could not be found');

insert into rhnException values (-20240, 'channel_consent_no_license','No license agreement exists for that channel');
insert into rhnException values (-20241, 'channel_subscrib_no_consent','Channel requires consent to license for subscription');

insert into rhnException values (-20242, 'channel_arch_not_found','Channel architecture could not be found');
insert into rhnException values (-20243, 'package_arch_not_found','Package architecture could not be found');
insert into rhnException values (-20244, 'server_arch_not_found','Server architecture could not be found');
insert into rhnException values (-20245, 'cpu_arch_not_found','CPU architecture could not be found');

insert into rhnException values (-20246, 'channel_unsubscribe_child_exists','Unsubscribe failed because server is subscribed to child channels');

insert into rhnException values (-20247, 'null_email_address','A user must have either a pending or a validated email address');

insert into rhnException values (-20248, 'invalid_item_code','The specified item does not exist');
insert into rhnException values (-20249, 'invalid_server_group','The specified server group does not exist');

insert into rhnException values (-20251, 'invalid_state','The specified state does not exist');
insert into rhnException values (-20253, 'invalid_state_transition','The specified transition is not allowed');
insert into rhnException values (-20254, 'ep_error','Entitlement Proxy error');
insert into rhnException values (-20255, 'cannot_delete_user','The specified user may not be deleted.');
insert into rhnException values (-20256, 'no_channel_product','No products were found to entitle this channel');
insert into rhnException values (-20257, 'no_server_multiple_swmgr_entitlements','Server is already entitled');
insert into rhnException values (-20258, 'erratafile_type_not_found','No such errata file type exists');
insert into rhnException values (-20259, 'invalid_quantity','Number fields may not be null');
insert into rhnException values (-20260, 'invalid_operation','The operation specified is not supported');
insert into rhnException values (-20261, 'sgm_insert_diff_orgs','Server does not belong to same org as server_group');
insert into rhnException values (-20262, 'invalid_transaction_operation', 'Invalid transaction operation');
insert into rhnException values (-20263, 'no_subscribe_permissions','Insufficient permissions for subscription');
insert into rhnException values (-20264, 'invalid_user_group','The specified user group does not exist');
insert into rhnException values (-20265, 'invalid_snapshot_invalid_reason','The specified reason for snapshot invalidation does not exist');
insert into rhnException values (-20266, 'action_is_child','The specified action is in a chain, but is not the first action in the chain');
insert into rhnException values (-20267, 'not_enough_quota','Insufficient available quota for the specified action');
insert into rhnException values (-20268, 'server_not_in_group','The specified server is not a member of the specified group');
insert into rhnException values (-20269, 'servergroup_use_upgrade', 'The specified server group is full, upgrades are available');
insert into rhnException values (-20270, 'invalid_upgrade', 'The specified server cannot be upgraded from management to provisioning');
insert into rhnException values (-20271, 'arch_type_not_found','Architecture type could not be found');
insert into rhnException values (-20272, 'mismatching_entitlement', 'The server architecture does not match the specified entitlement level');
insert into rhnException values (-20273, 'usgp_different_orgs', 'User and servergroup must be in same org in order to add this permission');
insert into rhnException values (-20274, 'usgp_already_allowed', 'The specified user already has permissions for this server group');
insert into rhnException values (-20275, 'usgp_not_allowed', 'The specified user does not have permissions for this server group');
insert into rhnException values (-20276, 'product_not_registered', 'The specified item is not registered to this customer');
insert into rhnException values (-20277, 'product_no_service', 'This product grants no services');
insert into rhnException values (-20278, 'webreg_duplicate', 'Registration number is already registered');
insert into rhnException values (-20279, 'webreg_not_active', 'Registration number is not active');
insert into rhnException values (-20280, 'webreg_sync_error', 'Error synchronizing, xxrh_oai_wrapper.sync_registration_uber');
insert into rhnException values (-20281, 'webreg_not_found', 'Registration number does not exist');
insert into rhnException values (-20282, 'webreg_unkown_error', 'Unknown error during web registration');
insert into rhnException values (-20283, 'invalid_feature', 'The specified feature does not exist');
insert into rhnException values (-20284, 'invalid_base_entitlement', 'The base entitlement is not valid for adding on other entitlements'); 
insert into rhnException values (-20285, 'invalid_addon_entitlement', 'The addon entitlement is not valid for adding onto other entitlements'); 
insert into rhnException values (-20286, 'no_available_server_group', 'The server can be entitled to that entitlement, but no valid server group was found');
insert into rhnException values (-20287, 'invalid_entitlement', 'The server can not be entitled to the specified level'); 
insert into rhnException values (-20288, 'invalid_server_group_member', 'The specified entitlement can not be removed from the specified server because the server does not have that entitlement level');

insert into rhnException
values (-20291,
        'cannot_delete_base_org',
        'You cannot delete the base org.');
insert into rhnException values (-20292, 'package_provider_not_found', 'The specified package provider could not be found.');

insert into rhnException values (-20293, 'package_key_type_not_found', 'The specified package key type could not be found.');

commit;

  0707010000001E000081B400000000000000000000000167AE111400001CC8000000000000000000000000000000000000002E00000000susemanager-schema/common/data/rhnFeature.sql --
-- Copyright (c) 2008--2010 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
-- 

insert into rhnFeature (id, label, name, created, modified)
values (sequence_nextval('rhn_feature_seq'), 'ftr_package_updates', 'Update Packages',
        current_timestamp, current_timestamp);
insert into rhnFeature (id, label, name, created, modified)
values (sequence_nextval('rhn_feature_seq'), 'ftr_errata_updates', 'Errata Updates',
        current_timestamp, current_timestamp);
insert into rhnFeature (id, label, name, created, modified)
values (sequence_nextval('rhn_feature_seq'), 'ftr_hardware_refresh', 'Refresh Hardware Profile',
        current_timestamp, current_timestamp);
insert into rhnFeature (id, label, name, created, modified)
values (sequence_nextval('rhn_feature_seq'), 'ftr_package_refresh', 'Refresh Packages Profile',
        current_timestamp, current_timestamp);
insert into rhnFeature (id, label, name, created, modified)
values (sequence_nextval('rhn_feature_seq'), 'ftr_package_remove', 'Remove Packages',
        current_timestamp, current_timestamp);
insert into rhnFeature (id, label, name, created, modified)
values (sequence_nextval('rhn_feature_seq'), 'ftr_auto_errata_updates', 'Auto Errata Update',
        current_timestamp, current_timestamp);
insert into rhnFeature (id, label, name, created, modified)
values (sequence_nextval('rhn_feature_seq'), 'ftr_system_grouping', 'System Groups',
        current_timestamp, current_timestamp);
insert into rhnFeature (id, label, name, created, modified)
values (sequence_nextval('rhn_feature_seq'), 'ftr_package_verify', 'Verify Packages',
        current_timestamp, current_timestamp);
insert into rhnFeature (id, label, name, created, modified)
values (sequence_nextval('rhn_feature_seq'), 'ftr_profile_compare', 'Compare Package Profiles',
        current_timestamp, current_timestamp);
insert into rhnFeature (id, label, name, created, modified)
values (sequence_nextval('rhn_feature_seq'), 'ftr_proxy_capable', 'Proxy Capable',
        current_timestamp, current_timestamp);
insert into rhnFeature (id, label, name, created, modified)
values (sequence_nextval('rhn_feature_seq'), 'ftr_sat_capable', 'SUSE Manager Capable',
        current_timestamp, current_timestamp);
insert into rhnFeature (id, label, name, created, modified)
values (sequence_nextval('rhn_feature_seq'), 'ftr_reboot', 'Reboot System',
        current_timestamp, current_timestamp);
insert into rhnFeature (id, label, name, created, modified)
values (sequence_nextval('rhn_feature_seq'), 'ftr_satellite_applet', 'SUSE Manager Applet',
        current_timestamp, current_timestamp);
insert into rhnFeature (id, label, name, created, modified)
values (sequence_nextval('rhn_feature_seq'), 'ftr_osa_bus', 'OSA Bus',
        current_timestamp, current_timestamp);
insert into rhnFeature (id, label, name, created, modified)
values (sequence_nextval('rhn_feature_seq'), 'ftr_kickstart', 'Kickstart',
        current_timestamp, current_timestamp);
insert into rhnFeature (id, label, name, created, modified)
values (sequence_nextval('rhn_feature_seq'), 'ftr_config', 'Config File Management',
        current_timestamp, current_timestamp);
insert into rhnFeature (id, label, name, created, modified)
values (sequence_nextval('rhn_feature_seq'), 'ftr_custom_info', 'Custom Information',
        current_timestamp, current_timestamp);
insert into rhnFeature (id, label, name, created, modified)
values (sequence_nextval('rhn_feature_seq'), 'ftr_delta_action', 'Package Profile Sync',
        current_timestamp, current_timestamp);
insert into rhnFeature (id, label, name, created, modified)
values (sequence_nextval('rhn_feature_seq'), 'ftr_snapshotting', 'System Snapshotting',
        current_timestamp, current_timestamp);
insert into rhnFeature (id, label, name, created, modified)
values (sequence_nextval('rhn_feature_seq'), 'ftr_agent_smith', 'Agent Smith',
        current_timestamp, current_timestamp);
insert into rhnFeature (id, label, name, created, modified)
values (sequence_nextval('rhn_feature_seq'), 'ftr_remote_command', 'Execute Remote Command',
        current_timestamp, current_timestamp);
insert into rhnFeature (id, label, name, created, modified)
values (sequence_nextval('rhn_feature_seq'), 'ftr_daily_summary', 'Daily Summary',
        current_timestamp, current_timestamp);
insert into rhnFeature (id, label, name)
values (sequence_nextval('rhn_feature_seq'), 'ftr_xen_provision_domain', 'Provision new Xen domains');
insert into rhnFeature (id, label, name)
values (sequence_nextval('rhn_feature_seq'), 'ftr_xen_manage_domains', 'Manage existing Xen domains');
insert into rhnFeature (id, label, name, created, modified)
values (sequence_nextval('rhn_feature_seq'), 'ftr_channel_membership', 'Channel Memberships',
        current_timestamp, current_timestamp);
insert into rhnFeature (id, label, name, created, modified)
values (sequence_nextval('rhn_feature_seq'), 'ftr_channel_config_subscription', 'Config Channel Subscriptions',
        current_timestamp, current_timestamp);
insert into rhnFeature (id, label, name, created, modified)
values (sequence_nextval('rhn_feature_seq'), 'ftr_channel_deploy_diff', 'Deploy/Diff Config Channel',
        current_timestamp, current_timestamp);
insert into rhnFeature (id, label, name, created, modified)
values (sequence_nextval('rhn_feature_seq'), 'ftr_tag_system', 'Tag System',
        current_timestamp, current_timestamp);
insert into rhnFeature (id, label, name, created, modified)
values (sequence_nextval('rhn_feature_seq'), 'ftr_power_management', 'Power Management Operations',
        current_timestamp, current_timestamp);
insert into rhnFeature (id, label, name, created, modified)
values (sequence_nextval('rhn_feature_seq'), 'ftr_system_preferences', 'System Preferences',
        current_timestamp, current_timestamp);
insert into rhnFeature (id, label, name, created, modified)
values (sequence_nextval('rhn_feature_seq'), 'ftr_system_custom_values', 'System Custom Values',
        current_timestamp, current_timestamp);
insert into rhnFeature (id, label, name, created, modified)
values (sequence_nextval('rhn_feature_seq'), 'ftr_add_rm_addon_type', 'Add/Remove Addon Type',
        current_timestamp, current_timestamp);
insert into rhnFeature (id, label, name, created, modified)
values (sequence_nextval('rhn_feature_seq'), 'ftr_system_lock', 'Lock System',
        current_timestamp, current_timestamp);
insert into rhnFeature (id, label, name, created, modified)
values (sequence_nextval('rhn_feature_seq'), 'ftr_system_audit', 'Audit System',
        current_timestamp, current_timestamp);
insert into rhnFeature (id, label, name, created, modified)
values (sequence_nextval('rhn_feature_seq'), 'ftr_package_lock', 'Lock Packages',
        current_timestamp, current_timestamp);
0707010000001F000081B400000000000000000000000167AE111400000603000000000000000000000000000000000000002F00000000susemanager-schema/common/data/rhnInfoPane.sql    --
-- Copyright (c) 2008--2010 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
insert into RHNINFOPANE(ID,LABEL,ACL) values (sequence_nextval('rhn_info_pane_id_seq'),'tasks',null);
insert into RHNINFOPANE(ID,LABEL,ACL) values (sequence_nextval('rhn_info_pane_id_seq'),'critical-systems',null);
insert into RHNINFOPANE(ID,LABEL,ACL) values (sequence_nextval('rhn_info_pane_id_seq'),'system-groups-widget',null);
insert into RHNINFOPANE(ID,LABEL,ACL) values (sequence_nextval('rhn_info_pane_id_seq'),'latest-errata',null);
insert into RHNINFOPANE(ID,LABEL,ACL) values (sequence_nextval('rhn_info_pane_id_seq'),'inactive-systems',null);
insert into RHNINFOPANE(ID,LABEL,ACL) values (sequence_nextval('rhn_info_pane_id_seq'),'pending-actions',null);
insert into RHNINFOPANE(ID,LABEL,ACL) values (sequence_nextval('rhn_info_pane_id_seq'),'recently-registered-systems', null);
insert into RHNINFOPANE(ID,LABEL,ACL) values (sequence_nextval('rhn_info_pane_id_seq'),'subscription-warning', null);
 07070100000020000081B400000000000000000000000167AE1114000009E7000000000000000000000000000000000000003400000000susemanager-schema/common/data/rhnKSInstallType.sql   --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
insert into rhnKSInstallType (id, label, name)
        values (sequence_nextval('rhn_ksinstalltype_id_seq'),
                'rhel_7','Red Hat Enterprise Linux 7'
        );

insert into rhnKSInstallType (id, label, name)
        values (sequence_nextval('rhn_ksinstalltype_id_seq'),
                'rhel_6','Red Hat Enterprise Linux 6'
        );

insert into rhnKSInstallType (id, label, name)
        values (sequence_nextval('rhn_ksinstalltype_id_seq'),
                'fedora18','Fedora'
        );

insert into rhnKSInstallType (id, label, name)
        values (sequence_nextval('rhn_ksinstalltype_id_seq'),
                'generic_rpm','Generic RPM'
        );

insert into rhnKSInstallType (id, label, name)
        values (sequence_nextval('rhn_ksinstalltype_id_seq'),
                'suse','SUSE Linux'
        );

insert into rhnKSInstallType (id, label, name)
        values (sequence_nextval('rhn_ksinstalltype_id_seq'),
                'sles10generic','SUSE Linux Enterprise 10'
        );

insert into rhnKSInstallType (id, label, name)
        values (sequence_nextval('rhn_ksinstalltype_id_seq'),
                'sles11generic','SUSE Linux Enterprise 11'
        );

insert into rhnKSInstallType (id, label, name)
        values (sequence_nextval('rhn_ksinstalltype_id_seq'),
                'sles12generic','SUSE Linux Enterprise 12'
        );
insert into rhnKSInstallType (id, label, name)
        values (sequence_nextval('rhn_ksinstalltype_id_seq'),
                'sles15generic','SUSE Linux Enterprise 15'
        );

insert into rhnKSInstallType (id, label, name)
        values (sequence_nextval('rhn_ksinstalltype_id_seq'),
                'rhel_8','Red Hat Enterprise Linux 8'
        );

insert into rhnKSInstallType (id, label, name)
        values (sequence_nextval('rhn_ksinstalltype_id_seq'),
                'rhel_9','Red Hat Enterprise Linux 9'
        );

commit;
 07070100000021000081B400000000000000000000000167AE1114000003E9000000000000000000000000000000000000003100000000susemanager-schema/common/data/rhnKSTreeType.sql  --
-- Copyright (c) 2008--2010 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
insert into rhnKSTreeType (id, label, name)
        values (sequence_nextval('rhn_kstree_type_seq'),
                'rhn-managed','Spacewalk managed kickstart tree'
        );

insert into rhnKSTreeType (id, label, name)
        values (sequence_nextval('rhn_kstree_type_seq'),
                'externally-managed','Externally managed kickstart tree'
        );

commit;
   07070100000022000081B400000000000000000000000167AE11140000223E000000000000000000000000000000000000003B00000000susemanager-schema/common/data/rhnKickstartCommandName.sql    --
-- Copyright (c) 2008--2011 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--

insert into rhnKickstartCommandName (id, name, uses_arguments, sort_order, required)
values (sequence_nextval('rhn_kscommandname_id_seq'), 'deviceprobe', 'Y', 17, 'N');

insert into rhnKickstartCommandName (id, name, uses_arguments, sort_order, required)
values (sequence_nextval('rhn_kscommandname_id_seq'), 'device', 'Y', 16, 'N');

insert into rhnKickstartCommandName (id, name, uses_arguments, sort_order, required)
values (sequence_nextval('rhn_kscommandname_id_seq'), 'driverdisk', 'Y', 18, 'N');

insert into rhnKickstartCommandName (id, name, uses_arguments, sort_order, required)
values (sequence_nextval('rhn_kscommandname_id_seq'), 'nfs', 'Y', 10, 'N');

insert into rhnKickstartCommandName (id, name, uses_arguments, sort_order, required)
values (sequence_nextval('rhn_kscommandname_id_seq'), 'interactive', 'N', 2, 'N');

insert into rhnKickstartCommandName (id, name, uses_arguments, sort_order, required)
values (sequence_nextval('rhn_kscommandname_id_seq'), 'harddrive', 'Y', 9, 'N');

insert into rhnKickstartCommandName (id, name, uses_arguments, sort_order, required)
values (sequence_nextval('rhn_kscommandname_id_seq'), 'upgrade', 'N', 4, 'N');

insert into rhnKickstartCommandName (id, name, uses_arguments, sort_order, required)
values (sequence_nextval('rhn_kscommandname_id_seq'), 'install', 'N', 3, 'N');

insert into rhnKickstartCommandName (id, name, uses_arguments, sort_order, required)
values (sequence_nextval('rhn_kscommandname_id_seq'), 'lilocheck', 'N', 5, 'N');

insert into rhnKickstartCommandName (id, name, uses_arguments, sort_order, required)
values (sequence_nextval('rhn_kscommandname_id_seq'), 'text', 'N', 6, 'N');

insert into rhnKickstartCommandName (id, name, uses_arguments, sort_order, required)
values (sequence_nextval('rhn_kscommandname_id_seq'), 'network', 'Y', 7, 'N');

insert into rhnKickstartCommandName (id, name, uses_arguments, sort_order, required)
values (sequence_nextval('rhn_kscommandname_id_seq'), 'url', 'Y', 11, 'N');

insert into rhnKickstartCommandName (id, name, uses_arguments, sort_order, required)
values (sequence_nextval('rhn_kscommandname_id_seq'), 'lang', 'Y', 12, 'Y');

insert into rhnKickstartCommandName (id, name, uses_arguments, sort_order, required)
values (sequence_nextval('rhn_kscommandname_id_seq'), 'langsupport', 'Y', 13, 'N');

insert into rhnKickstartCommandName (id, name, uses_arguments, sort_order, required)
values (sequence_nextval('rhn_kscommandname_id_seq'), 'keyboard', 'Y', 14, 'Y');

insert into rhnKickstartCommandName (id, name, uses_arguments, sort_order, required)
values (sequence_nextval('rhn_kscommandname_id_seq'), 'mouse', 'Y', 15, 'N');

insert into rhnKickstartCommandName (id, name, uses_arguments, sort_order, required)
values (sequence_nextval('rhn_kscommandname_id_seq'), 'zerombr', 'Y', 19, 'N');

insert into rhnKickstartCommandName (id, name, uses_arguments, sort_order, required)
values (sequence_nextval('rhn_kscommandname_id_seq'), 'clearpart', 'Y', 20, 'N');

insert into rhnKickstartCommandName (id, name, uses_arguments, sort_order, required)
values (sequence_nextval('rhn_kscommandname_id_seq'), 'bootloader', 'Y', 26, 'Y');

insert into rhnKickstartCommandName (id, name, uses_arguments, sort_order, required)
values (sequence_nextval('rhn_kscommandname_id_seq'), 'timezone', 'Y', 27, 'Y');

insert into rhnKickstartCommandName (id, name, uses_arguments, sort_order, required)
values (sequence_nextval('rhn_kscommandname_id_seq'), 'auth', 'Y', 28, 'Y');

insert into rhnKickstartCommandName (id, name, uses_arguments, sort_order, required)
values (sequence_nextval('rhn_kscommandname_id_seq'), 'reboot', 'N', 31, 'N');

insert into rhnKickstartCommandName (id, name, uses_arguments, sort_order, required)
values (sequence_nextval('rhn_kscommandname_id_seq'), 'xconfig', 'Y', 32, 'N');

insert into rhnKickstartCommandName (id, name, uses_arguments, sort_order, required)
values (sequence_nextval('rhn_kscommandname_id_seq'), 'rootpw', 'Y', 29, 'Y');

insert into rhnKickstartCommandName (id, name, uses_arguments, sort_order, required)
values (sequence_nextval('rhn_kscommandname_id_seq'), 'firewall', 'Y', 31, 'N');

insert into rhnKickstartCommandName (id, name, uses_arguments, sort_order, required)
values (sequence_nextval('rhn_kscommandname_id_seq'), 'skipx', 'N', 32, 'N');

insert into rhnKickstartCommandName (id, name, uses_arguments, sort_order, required)
values (sequence_nextval('rhn_kscommandname_id_seq'), 'cdrom', 'N', 8, 'N');

insert into rhnKickstartCommandName (id, name, uses_arguments, sort_order, required)
values (sequence_nextval('rhn_kscommandname_id_seq'), 'selinux', 'Y', 30, 'N');

insert into rhnKickstartCommandName (id, name, uses_arguments, sort_order, required)
values (sequence_nextval('rhn_kscommandname_id_seq'), 'autostep', 'Y', 1, 'N');

insert into rhnKickstartCommandName (id, name, uses_arguments, sort_order, required)
values (sequence_nextval('rhn_kscommandname_id_seq'), 'repo', 'Y', 33, 'N');

insert into rhnKickstartCommandName (id, name, uses_arguments, sort_order, required)
values (sequence_nextval('rhn_kscommandname_id_seq'), 'key', 'Y', 34, 'N');

insert into rhnKickstartCommandName (id, name, uses_arguments, sort_order, required)
values (sequence_nextval('rhn_kscommandname_id_seq'), 'ignoredisk', 'Y', 35, 'N');

insert into rhnKickstartCommandName (id, name, uses_arguments, sort_order, required)
values (sequence_nextval('rhn_kscommandname_id_seq'), 'autopart', 'N', 36, 'N');

insert into rhnKickstartCommandName (id, name, uses_arguments, sort_order, required)
values (sequence_nextval('rhn_kscommandname_id_seq'), 'cmdline', 'N', 37, 'N');

insert into rhnKickstartCommandName (id, name, uses_arguments, sort_order, required)
values (sequence_nextval('rhn_kscommandname_id_seq'), 'firstboot', 'Y', 38, 'N');

insert into rhnKickstartCommandName (id, name, uses_arguments, sort_order, required)
values (sequence_nextval('rhn_kscommandname_id_seq'), 'graphical', 'N', 39, 'N');

insert into rhnKickstartCommandName (id, name, uses_arguments, sort_order, required)
values (sequence_nextval('rhn_kscommandname_id_seq'), 'iscsiname', 'Y', 40, 'N');

insert into rhnKickstartCommandName (id, name, uses_arguments, sort_order, required)
values (sequence_nextval('rhn_kscommandname_id_seq'), 'iscsi', 'Y', 41, 'N');

insert into rhnKickstartCommandName (id, name, uses_arguments, sort_order, required)
values (sequence_nextval('rhn_kscommandname_id_seq'), 'logging', 'Y', 42, 'N');

insert into rhnKickstartCommandName (id, name, uses_arguments, sort_order, required)
values (sequence_nextval('rhn_kscommandname_id_seq'), 'monitor', 'Y', 43, 'N');

insert into rhnKickstartCommandName (id, name, uses_arguments, sort_order, required)
values (sequence_nextval('rhn_kscommandname_id_seq'), 'multipath', 'Y', 44, 'N');

insert into rhnKickstartCommandName (id, name, uses_arguments, sort_order, required)
values (sequence_nextval('rhn_kscommandname_id_seq'), 'poweroff', 'N', 45, 'N');

insert into rhnKickstartCommandName (id, name, uses_arguments, sort_order, required)
values (sequence_nextval('rhn_kscommandname_id_seq'), 'halt', 'N', 46, 'N');

insert into rhnKickstartCommandName (id, name, uses_arguments, sort_order, required)
values (sequence_nextval('rhn_kscommandname_id_seq'), 'services', 'Y', 47, 'N');

insert into rhnKickstartCommandName (id, name, uses_arguments, sort_order, required)
values (sequence_nextval('rhn_kscommandname_id_seq'), 'shutdown', 'N', 48, 'N');

insert into rhnKickstartCommandName (id, name, uses_arguments, sort_order, required)
values (sequence_nextval('rhn_kscommandname_id_seq'), 'user', 'Y', 49, 'N');

insert into rhnKickstartCommandName (id, name, uses_arguments, sort_order, required)
values (sequence_nextval('rhn_kscommandname_id_seq'), 'vnc', 'Y', 50, 'N');

insert into rhnKickstartCommandName (id, name, uses_arguments, sort_order, required)
values (sequence_nextval('rhn_kscommandname_id_seq'), 'zfcp', 'Y', 51, 'N');

insert into rhnKickstartCommandName (id, name, uses_arguments, sort_order, required)
values (sequence_nextval('rhn_kscommandname_id_seq'), 'custom', 'Y', 52, 'N');

commit;
  07070100000023000081B400000000000000000000000167AE111400000F0C000000000000000000000000000000000000003C00000000susemanager-schema/common/data/rhnKickstartSessionState.sql   --
-- Copyright (c) 2008--2013 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--
--data for rhnKickstartSessionState

insert
  into rhnKickstartSessionState
       (id, name, label, description)
values (sequence_nextval('rhn_ks_session_state_id_seq'), 'Created', 'created',
        'Autoinstallation session created, but has not yet been used.'
       );

insert
  into rhnKickstartSessionState
       (id, name, label, description)
values (sequence_nextval('rhn_ks_session_state_id_seq'), 'Deployed', 'deployed',
        'Files required for autoinstall action have been installed.'
       );

insert
  into rhnKickstartSessionState
       (id, name, label, description)
values (sequence_nextval('rhn_ks_session_state_id_seq'), 'Injected', 'injected',
        'The system configuration has been modified to begin autoinstallation upon next boot.'
       );

insert
  into rhnKickstartSessionState
       (id, name, label, description)
values (sequence_nextval('rhn_ks_session_state_id_seq'), 'Restarted', 'restarted',
        'The system has been restarted in order to begin the autoinstallation process.'
       );

insert
  into rhnKickstartSessionState
       (id, name, label, description)
values (sequence_nextval('rhn_ks_session_state_id_seq'), 'Configuration accessed', 'configuration_accessed',
        'The system has downloaded the autoinstallation configuraton file from Spacewalk.'
       );

insert
  into rhnKickstartSessionState
       (id, name, label, description)
values (sequence_nextval('rhn_ks_session_state_id_seq'), 'Started', 'started',
        'The initial files required for autoinstallation have been downloaded.'
       );

insert
  into rhnKickstartSessionState
       (id, name, label, description)
values (sequence_nextval('rhn_ks_session_state_id_seq'), 'In Progress', 'in_progress',
        'The system is downloading the RPMs required to install.'
       );

insert
  into rhnKickstartSessionState
       (id, name, label, description)
values (sequence_nextval('rhn_ks_session_state_id_seq'), 'Registration Complete', 'registered',
        'The system has successfully registered with Spacewalk after autoinstalling.'
       );

insert
  into rhnKickstartSessionState
       (id, name, label, description)
values (sequence_nextval('rhn_ks_session_state_id_seq'), 'Package Synch', 'package_synch',
        'Package synchronization in progress.'
       );

insert
  into rhnKickstartSessionState
       (id, name, label, description)
values (sequence_nextval('rhn_ks_session_state_id_seq'), 'Package Synch Scheduled',
        'package_synch_scheduled', 'Package synchronization scheduled.'
       );

insert
  into rhnKickstartSessionState
       (id, name, label, description)
values (sequence_nextval('rhn_ks_session_state_id_seq'), 'Configuration Deployment',
        'configuration_deploy', 'Configuration files are being deployed.'
       );

insert
  into rhnKickstartSessionState
       (id, name, label, description)
values (sequence_nextval('rhn_ks_session_state_id_seq'), 'Complete', 'complete',
        'Autoinstallation complete.'
       );

insert
  into rhnKickstartSessionState
       (id, name, label, description)
values (sequence_nextval('rhn_ks_session_state_id_seq'), 'Failed', 'failed',
        'Autoinstallation failed.'
       );

commit;

07070100000024000081B400000000000000000000000167AE1114000706E4000000000000000000000000000000000000003800000000susemanager-schema/common/data/rhnKickstartTimezone.sql   --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
-- Timezones can change between RHEL releases, so just to be safe, define them separately

-- RHEL 6 timezones

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Europe/Andorra',
	    	'Europe/Andorra',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Asia/Dubai',
	    	'Asia/Dubai',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Asia/Kabul',
	    	'Asia/Kabul',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'America/Antigua',
	    	'America/Antigua',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'America/Anguilla',
	    	'America/Anguilla',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Europe/Tirane',
	    	'Europe/Tirane',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Asia/Yerevan',
	    	'Asia/Yerevan',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'America/Curacao',
	    	'America/Curacao',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Africa/Luanda',
	    	'Africa/Luanda',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Antarctica/McMurdo',
	    	'Antarctica/McMurdo',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Antarctica/South_Pole',
	    	'Antarctica/South_Pole',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Antarctica/Palmer',
	    	'Antarctica/Palmer',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Antarctica/Mawson',
	    	'Antarctica/Mawson',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Antarctica/Davis',
	    	'Antarctica/Davis',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Antarctica/Casey',
	    	'Antarctica/Casey',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Antarctica/Vostok',
	    	'Antarctica/Vostok',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Antarctica/DumontDUrville',
	    	'Antarctica/DumontDUrville',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Antarctica/Syowa',
	    	'Antarctica/Syowa',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'America/Buenos_Aires',
	    	'America/Buenos_Aires',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'America/Cordoba',
	    	'America/Cordoba',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'America/Jujuy',
	    	'America/Jujuy',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'America/Catamarca',
	    	'America/Catamarca',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'America/Mendoza',
	    	'America/Mendoza',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Pacific/Pago_Pago',
	    	'Pacific/Pago_Pago',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Europe/Vienna',
	    	'Europe/Vienna',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Australia/Lord_Howe',
	    	'Australia/Lord_Howe',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Australia/Hobart',
	    	'Australia/Hobart',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Australia/Melbourne',
	    	'Australia/Melbourne',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Australia/Sydney',
	    	'Australia/Sydney',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Australia/Broken_Hill',
	    	'Australia/Broken_Hill',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Australia/Brisbane',
	    	'Australia/Brisbane',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Australia/Lindeman',
	    	'Australia/Lindeman',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Australia/Adelaide',
	    	'Australia/Adelaide',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Australia/Darwin',
	    	'Australia/Darwin',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Australia/Perth',
	    	'Australia/Perth',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'America/Aruba',
	    	'America/Aruba',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Asia/Baku',
	    	'Asia/Baku',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Europe/Sarajevo',
	    	'Europe/Sarajevo',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'America/Barbados',
	    	'America/Barbados',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Asia/Dhaka',
	    	'Asia/Dhaka',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Europe/Brussels',
	    	'Europe/Brussels',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Africa/Ouagadougou',
	    	'Africa/Ouagadougou',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Europe/Sofia',
	    	'Europe/Sofia',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Asia/Bahrain',
	    	'Asia/Bahrain',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Africa/Bujumbura',
	    	'Africa/Bujumbura',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Africa/Porto-Novo',
	    	'Africa/Porto-Novo',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Atlantic/Bermuda',
	    	'Atlantic/Bermuda',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Asia/Brunei',
	    	'Asia/Brunei',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'America/La_Paz',
	    	'America/La_Paz',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'America/Noronha',
	    	'America/Noronha',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'America/Belem',
	    	'America/Belem',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'America/Fortaleza',
	    	'America/Fortaleza',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'America/Recife',
	    	'America/Recife',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'America/Araguaina',
	    	'America/Araguaina',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'America/Maceio',
	    	'America/Maceio',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'America/Sao_Paulo',
	    	'America/Sao_Paulo',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'America/Cuiaba',
	    	'America/Cuiaba',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'America/Porto_Velho',
	    	'America/Porto_Velho',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'America/Boa_Vista',
	    	'America/Boa_Vista',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'America/Manaus',
	    	'America/Manaus',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'America/Eirunepe',
	    	'America/Eirunepe',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'America/Rio_Branco',
	    	'America/Rio_Branco',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'America/Nassau',
	    	'America/Nassau',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Asia/Thimphu',
	    	'Asia/Thimphu',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Africa/Gaborone',
	    	'Africa/Gaborone',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Europe/Minsk',
	    	'Europe/Minsk',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'America/Belize',
	    	'America/Belize',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'America/St_Johns',
	    	'America/St_Johns',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'America/Halifax',
	    	'America/Halifax',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'America/Glace_Bay',
	    	'America/Glace_Bay',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'America/Goose_Bay',
	    	'America/Goose_Bay',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'America/Montreal',
	    	'America/Montreal',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'America/Nipigon',
	    	'America/Nipigon',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'America/Thunder_Bay',
	    	'America/Thunder_Bay',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'America/Pangnirtung',
	    	'America/Pangnirtung',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'America/Iqaluit',
	    	'America/Iqaluit',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'America/Rankin_Inlet',
	    	'America/Rankin_Inlet',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'America/Winnipeg',
	    	'America/Winnipeg',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'America/Rainy_River',
	    	'America/Rainy_River',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'America/Cambridge_Bay',
	    	'America/Cambridge_Bay',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'America/Regina',
	    	'America/Regina',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'America/Swift_Current',
	    	'America/Swift_Current',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'America/Edmonton',
	    	'America/Edmonton',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'America/Yellowknife',
	    	'America/Yellowknife',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'America/Inuvik',
	    	'America/Inuvik',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'America/Dawson_Creek',
	    	'America/Dawson_Creek',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'America/Vancouver',
	    	'America/Vancouver',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'America/Whitehorse',
	    	'America/Whitehorse',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'America/Dawson',
	    	'America/Dawson',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Indian/Cocos',
	    	'Indian/Cocos',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Africa/Kinshasa',
	    	'Africa/Kinshasa',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Africa/Lubumbashi',
	    	'Africa/Lubumbashi',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Africa/Bangui',
	    	'Africa/Bangui',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Africa/Brazzaville',
	    	'Africa/Brazzaville',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Europe/Zurich',
	    	'Europe/Zurich',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Africa/Abidjan',
	    	'Africa/Abidjan',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Pacific/Rarotonga',
	    	'Pacific/Rarotonga',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'America/Santiago',
	    	'America/Santiago',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Pacific/Easter',
	    	'Pacific/Easter',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Africa/Douala',
	    	'Africa/Douala',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Asia/Shanghai',
	    	'Asia/Shanghai',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Asia/Harbin',
	    	'Asia/Harbin',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Asia/Chongqing',
	    	'Asia/Chongqing',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Asia/Urumqi',
	    	'Asia/Urumqi',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Asia/Kashgar',
	    	'Asia/Kashgar',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'America/Bogota',
	    	'America/Bogota',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'America/Costa_Rica',
	    	'America/Costa_Rica',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'America/Havana',
	    	'America/Havana',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Atlantic/Cape_Verde',
	    	'Atlantic/Cape_Verde',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Indian/Christmas',
	    	'Indian/Christmas',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Asia/Nicosia',
	    	'Asia/Nicosia',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Europe/Prague',
	    	'Europe/Prague',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Europe/Berlin',
	    	'Europe/Berlin',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Africa/Djibouti',
	    	'Africa/Djibouti',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Europe/Copenhagen',
	    	'Europe/Copenhagen',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'America/Dominica',
	    	'America/Dominica',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'America/Santo_Domingo',
	    	'America/Santo_Domingo',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Africa/Algiers',
	    	'Africa/Algiers',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'America/Guayaquil',
	    	'America/Guayaquil',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Pacific/Galapagos',
	    	'Pacific/Galapagos',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Europe/Tallinn',
	    	'Europe/Tallinn',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Africa/Cairo',
	    	'Africa/Cairo',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Africa/El_Aaiun',
	    	'Africa/El_Aaiun',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Africa/Asmera',
	    	'Africa/Asmera',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Europe/Madrid',
	    	'Europe/Madrid',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Africa/Ceuta',
	    	'Africa/Ceuta',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Atlantic/Canary',
	    	'Atlantic/Canary',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Africa/Addis_Ababa',
	    	'Africa/Addis_Ababa',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Europe/Helsinki',
	    	'Europe/Helsinki',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Pacific/Fiji',
	    	'Pacific/Fiji',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Atlantic/Stanley',
	    	'Atlantic/Stanley',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Pacific/Yap',
	    	'Pacific/Yap',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Pacific/Truk',
	    	'Pacific/Truk',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Pacific/Ponape',
	    	'Pacific/Ponape',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Pacific/Kosrae',
	    	'Pacific/Kosrae',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Atlantic/Faeroe',
	    	'Atlantic/Faeroe',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Europe/Paris',
	    	'Europe/Paris',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Africa/Libreville',
	    	'Africa/Libreville',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Europe/London',
	    	'Europe/London',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Europe/Belfast',
	    	'Europe/Belfast',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'America/Grenada',
	    	'America/Grenada',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Asia/Tbilisi',
	    	'Asia/Tbilisi',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'America/Cayenne',
	    	'America/Cayenne',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Africa/Accra',
	    	'Africa/Accra',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Europe/Gibraltar',
	    	'Europe/Gibraltar',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'America/Godthab',
	    	'America/Godthab',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'America/Danmarkshavn',
	    	'America/Danmarkshavn',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'America/Scoresbysund',
	    	'America/Scoresbysund',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'America/Thule',
	    	'America/Thule',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Africa/Banjul',
	    	'Africa/Banjul',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Africa/Conakry',
	    	'Africa/Conakry',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'America/Guadeloupe',
	    	'America/Guadeloupe',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Africa/Malabo',
	    	'Africa/Malabo',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Europe/Athens',
	    	'Europe/Athens',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Atlantic/South_Georgia',
	    	'Atlantic/South_Georgia',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'America/Guatemala',
	    	'America/Guatemala',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Pacific/Guam',
	    	'Pacific/Guam',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Africa/Bissau',
	    	'Africa/Bissau',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'America/Guyana',
	    	'America/Guyana',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Asia/Hong_Kong',
	    	'Asia/Hong_Kong',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'America/Tegucigalpa',
	    	'America/Tegucigalpa',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Europe/Zagreb',
	    	'Europe/Zagreb',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'America/Port-au-Prince',
	    	'America/Port-au-Prince',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Europe/Budapest',
	    	'Europe/Budapest',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Asia/Jakarta',
	    	'Asia/Jakarta',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Asia/Pontianak',
	    	'Asia/Pontianak',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Asia/Makassar',
	    	'Asia/Makassar',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Asia/Jayapura',
	    	'Asia/Jayapura',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Europe/Dublin',
	    	'Europe/Dublin',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Asia/Jerusalem',
	    	'Asia/Jerusalem',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Asia/Calcutta',
	    	'Asia/Calcutta',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Indian/Chagos',
	    	'Indian/Chagos',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Asia/Baghdad',
	    	'Asia/Baghdad',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Asia/Tehran',
	    	'Asia/Tehran',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Atlantic/Reykjavik',
	    	'Atlantic/Reykjavik',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Europe/Rome',
	    	'Europe/Rome',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'America/Jamaica',
	    	'America/Jamaica',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Asia/Amman',
	    	'Asia/Amman',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Asia/Tokyo',
	    	'Asia/Tokyo',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Africa/Nairobi',
	    	'Africa/Nairobi',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Asia/Bishkek',
	    	'Asia/Bishkek',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Asia/Phnom_Penh',
	    	'Asia/Phnom_Penh',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Pacific/Tarawa',
	    	'Pacific/Tarawa',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Pacific/Enderbury',
	    	'Pacific/Enderbury',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Pacific/Kiritimati',
	    	'Pacific/Kiritimati',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Indian/Comoro',
	    	'Indian/Comoro',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'America/St_Kitts',
	    	'America/St_Kitts',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Asia/Pyongyang',
	    	'Asia/Pyongyang',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Asia/Seoul',
	    	'Asia/Seoul',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Asia/Kuwait',
	    	'Asia/Kuwait',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'America/Cayman',
	    	'America/Cayman',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Asia/Almaty',
	    	'Asia/Almaty',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Asia/Qyzylorda',
	    	'Asia/Qyzylorda',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Asia/Aqtobe',
	    	'Asia/Aqtobe',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Asia/Aqtau',
	    	'Asia/Aqtau',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Asia/Oral',
	    	'Asia/Oral',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Asia/Vientiane',
	    	'Asia/Vientiane',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Asia/Beirut',
	    	'Asia/Beirut',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'America/St_Lucia',
	    	'America/St_Lucia',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Europe/Vaduz',
	    	'Europe/Vaduz',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Asia/Colombo',
	    	'Asia/Colombo',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Africa/Monrovia',
	    	'Africa/Monrovia',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Africa/Maseru',
	    	'Africa/Maseru',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Europe/Vilnius',
	    	'Europe/Vilnius',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Europe/Luxembourg',
	    	'Europe/Luxembourg',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Europe/Riga',
	    	'Europe/Riga',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Africa/Tripoli',
	    	'Africa/Tripoli',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Africa/Casablanca',
	    	'Africa/Casablanca',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Europe/Monaco',
	    	'Europe/Monaco',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Europe/Chisinau',
	    	'Europe/Chisinau',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Indian/Antananarivo',
	    	'Indian/Antananarivo',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Pacific/Majuro',
	    	'Pacific/Majuro',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Pacific/Kwajalein',
	    	'Pacific/Kwajalein',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Europe/Skopje',
	    	'Europe/Skopje',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Africa/Bamako',
	    	'Africa/Bamako',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Africa/Timbuktu',
	    	'Africa/Timbuktu',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Asia/Rangoon',
	    	'Asia/Rangoon',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Asia/Ulaanbaatar',
	    	'Asia/Ulaanbaatar',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Asia/Hovd',
	    	'Asia/Hovd',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Asia/Choibalsan',
	    	'Asia/Choibalsan',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Asia/Macau',
	    	'Asia/Macau',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Pacific/Saipan',
	    	'Pacific/Saipan',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'America/Martinique',
	    	'America/Martinique',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Africa/Nouakchott',
	    	'Africa/Nouakchott',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'America/Montserrat',
	    	'America/Montserrat',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Europe/Malta',
	    	'Europe/Malta',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Indian/Mauritius',
	    	'Indian/Mauritius',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Indian/Maldives',
	    	'Indian/Maldives',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Africa/Blantyre',
	    	'Africa/Blantyre',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'America/Mexico_City',
	    	'America/Mexico_City',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'America/Cancun',
	    	'America/Cancun',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'America/Merida',
	    	'America/Merida',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'America/Monterrey',
	    	'America/Monterrey',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'America/Mazatlan',
	    	'America/Mazatlan',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'America/Chihuahua',
	    	'America/Chihuahua',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'America/Hermosillo',
	    	'America/Hermosillo',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'America/Tijuana',
	    	'America/Tijuana',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Asia/Kuala_Lumpur',
	    	'Asia/Kuala_Lumpur',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Asia/Kuching',
	    	'Asia/Kuching',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Africa/Maputo',
	    	'Africa/Maputo',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Africa/Windhoek',
	    	'Africa/Windhoek',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Pacific/Noumea',
	    	'Pacific/Noumea',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Africa/Niamey',
	    	'Africa/Niamey',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Pacific/Norfolk',
	    	'Pacific/Norfolk',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Africa/Lagos',
	    	'Africa/Lagos',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'America/Managua',
	    	'America/Managua',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Europe/Amsterdam',
	    	'Europe/Amsterdam',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Europe/Oslo',
	    	'Europe/Oslo',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Asia/Katmandu',
	    	'Asia/Katmandu',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Pacific/Nauru',
	    	'Pacific/Nauru',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Pacific/Niue',
	    	'Pacific/Niue',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Pacific/Auckland',
	    	'Pacific/Auckland',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Pacific/Chatham',
	    	'Pacific/Chatham',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Asia/Muscat',
	    	'Asia/Muscat',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'America/Panama',
	    	'America/Panama',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'America/Lima',
	    	'America/Lima',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Pacific/Tahiti',
	    	'Pacific/Tahiti',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Pacific/Marquesas',
	    	'Pacific/Marquesas',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Pacific/Gambier',
	    	'Pacific/Gambier',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Pacific/Port_Moresby',
	    	'Pacific/Port_Moresby',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Asia/Manila',
	    	'Asia/Manila',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Asia/Karachi',
	    	'Asia/Karachi',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Europe/Warsaw',
	    	'Europe/Warsaw',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'America/Miquelon',
	    	'America/Miquelon',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Pacific/Pitcairn',
	    	'Pacific/Pitcairn',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'America/Puerto_Rico',
	    	'America/Puerto_Rico',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Asia/Gaza',
	    	'Asia/Gaza',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Europe/Lisbon',
	    	'Europe/Lisbon',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Atlantic/Madeira',
	    	'Atlantic/Madeira',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Atlantic/Azores',
	    	'Atlantic/Azores',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Pacific/Palau',
	    	'Pacific/Palau',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'America/Asuncion',
	    	'America/Asuncion',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Asia/Qatar',
	    	'Asia/Qatar',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Indian/Reunion',
	    	'Indian/Reunion',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Europe/Bucharest',
	    	'Europe/Bucharest',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Europe/Kaliningrad',
	    	'Europe/Kaliningrad',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Europe/Moscow',
	    	'Europe/Moscow',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Europe/Samara',
	    	'Europe/Samara',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Asia/Yekaterinburg',
	    	'Asia/Yekaterinburg',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Asia/Omsk',
	    	'Asia/Omsk',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Asia/Novosibirsk',
	    	'Asia/Novosibirsk',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Asia/Krasnoyarsk',
	    	'Asia/Krasnoyarsk',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Asia/Irkutsk',
	    	'Asia/Irkutsk',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Asia/Yakutsk',
	    	'Asia/Yakutsk',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Asia/Vladivostok',
	    	'Asia/Vladivostok',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Asia/Sakhalin',
	    	'Asia/Sakhalin',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Asia/Magadan',
	    	'Asia/Magadan',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Asia/Kamchatka',
	    	'Asia/Kamchatka',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Asia/Anadyr',
	    	'Asia/Anadyr',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Africa/Kigali',
	    	'Africa/Kigali',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Asia/Riyadh',
	    	'Asia/Riyadh',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Pacific/Guadalcanal',
	    	'Pacific/Guadalcanal',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Indian/Mahe',
	    	'Indian/Mahe',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Africa/Khartoum',
	    	'Africa/Khartoum',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Europe/Stockholm',
	    	'Europe/Stockholm',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Asia/Singapore',
	    	'Asia/Singapore',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Atlantic/St_Helena',
	    	'Atlantic/St_Helena',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Europe/Ljubljana',
	    	'Europe/Ljubljana',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Arctic/Longyearbyen',
	    	'Arctic/Longyearbyen',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Atlantic/Jan_Mayen',
	    	'Atlantic/Jan_Mayen',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Europe/Bratislava',
	    	'Europe/Bratislava',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Africa/Freetown',
	    	'Africa/Freetown',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Europe/San_Marino',
	    	'Europe/San_Marino',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Africa/Dakar',
	    	'Africa/Dakar',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Africa/Mogadishu',
	    	'Africa/Mogadishu',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'America/Paramaribo',
	    	'America/Paramaribo',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Africa/Sao_Tome',
	    	'Africa/Sao_Tome',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'America/El_Salvador',
	    	'America/El_Salvador',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Asia/Damascus',
	    	'Asia/Damascus',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Africa/Mbabane',
	    	'Africa/Mbabane',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'America/Grand_Turk',
	    	'America/Grand_Turk',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Africa/Ndjamena',
	    	'Africa/Ndjamena',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Indian/Kerguelen',
	    	'Indian/Kerguelen',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Africa/Lome',
	    	'Africa/Lome',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Asia/Bangkok',
	    	'Asia/Bangkok',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Asia/Dushanbe',
	    	'Asia/Dushanbe',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Pacific/Fakaofo',
	    	'Pacific/Fakaofo',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Asia/Ashgabat',
	    	'Asia/Ashgabat',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Africa/Tunis',
	    	'Africa/Tunis',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Pacific/Tongatapu',
	    	'Pacific/Tongatapu',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Asia/Dili',
	    	'Asia/Dili',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Europe/Istanbul',
	    	'Europe/Istanbul',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'America/Port_of_Spain',
	    	'America/Port_of_Spain',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Pacific/Funafuti',
	    	'Pacific/Funafuti',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Asia/Taipei',
	    	'Asia/Taipei',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Africa/Dar_es_Salaam',
	    	'Africa/Dar_es_Salaam',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Europe/Kiev',
	    	'Europe/Kiev',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Europe/Uzhgorod',
	    	'Europe/Uzhgorod',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Europe/Zaporozhye',
	    	'Europe/Zaporozhye',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Europe/Simferopol',
	    	'Europe/Simferopol',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Africa/Kampala',
	    	'Africa/Kampala',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Pacific/Johnston',
	    	'Pacific/Johnston',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Pacific/Midway',
	    	'Pacific/Midway',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Pacific/Wake',
	    	'Pacific/Wake',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'America/New_York',
	    	'America/New_York',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'America/Detroit',
	    	'America/Detroit',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'America/Louisville',
	    	'America/Louisville',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'America/Kentucky/Monticello',
	    	'America/Kentucky/Monticello',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'America/Indianapolis',
	    	'America/Indianapolis',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'America/Indiana/Marengo',
	    	'America/Indiana/Marengo',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'America/Indiana/Knox',
	    	'America/Indiana/Knox',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'America/Indiana/Vevay',
	    	'America/Indiana/Vevay',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'America/Chicago',
	    	'America/Chicago',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'America/Menominee',
	    	'America/Menominee',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'America/North_Dakota/Center',
	    	'America/North_Dakota/Center',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'America/Denver',
	    	'America/Denver',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'America/Boise',
	    	'America/Boise',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'America/Shiprock',
	    	'America/Shiprock',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'America/Phoenix',
	    	'America/Phoenix',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'America/Los_Angeles',
	    	'America/Los_Angeles',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'America/Anchorage',
	    	'America/Anchorage',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'America/Juneau',
	    	'America/Juneau',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'America/Yakutat',
	    	'America/Yakutat',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'America/Nome',
	    	'America/Nome',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'America/Adak',
	    	'America/Adak',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Pacific/Honolulu',
	    	'Pacific/Honolulu',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'America/Montevideo',
	    	'America/Montevideo',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Asia/Samarkand',
	    	'Asia/Samarkand',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Asia/Tashkent',
	    	'Asia/Tashkent',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Europe/Vatican',
	    	'Europe/Vatican',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'America/St_Vincent',
	    	'America/St_Vincent',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'America/Caracas',
	    	'America/Caracas',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'America/Tortola',
	    	'America/Tortola',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'America/St_Thomas',
	    	'America/St_Thomas',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Asia/Saigon',
	    	'Asia/Saigon',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Pacific/Efate',
	    	'Pacific/Efate',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Pacific/Wallis',
	    	'Pacific/Wallis',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Pacific/Apia',
	    	'Pacific/Apia',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Asia/Aden',
	    	'Asia/Aden',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Indian/Mayotte',
	    	'Indian/Mayotte',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Europe/Belgrade',
	    	'Europe/Belgrade',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Africa/Johannesburg',
	    	'Africa/Johannesburg',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Africa/Lusaka',
	    	'Africa/Lusaka',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'Africa/Harare',
	    	'Africa/Harare',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
	    	'America/Toronto',
	    	'America/Toronto',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );
insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Abidjan',
                'Africa/Abidjan',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Accra',
                'Africa/Accra',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Addis_Ababa',
                'Africa/Addis_Ababa',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Algiers',
                'Africa/Algiers',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Asmara',
                'Africa/Asmara',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Bamako',
                'Africa/Bamako',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Bangui',
                'Africa/Bangui',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Banjul',
                'Africa/Banjul',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Bissau',
                'Africa/Bissau',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Blantyre',
                'Africa/Blantyre',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Brazzaville',
                'Africa/Brazzaville',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Bujumbura',
                'Africa/Bujumbura',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Cairo',
                'Africa/Cairo',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Casablanca',
                'Africa/Casablanca',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Ceuta',
                'Africa/Ceuta',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Conakry',
                'Africa/Conakry',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Dakar',
                'Africa/Dakar',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Dar_es_Salaam',
                'Africa/Dar_es_Salaam',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Djibouti',
                'Africa/Djibouti',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Douala',
                'Africa/Douala',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/El_Aaiun',
                'Africa/El_Aaiun',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Freetown',
                'Africa/Freetown',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Gaborone',
                'Africa/Gaborone',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Harare',
                'Africa/Harare',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Johannesburg',
                'Africa/Johannesburg',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Juba',
                'Africa/Juba',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Kampala',
                'Africa/Kampala',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Khartoum',
                'Africa/Khartoum',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Kigali',
                'Africa/Kigali',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Kinshasa',
                'Africa/Kinshasa',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Lagos',
                'Africa/Lagos',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Libreville',
                'Africa/Libreville',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Lome',
                'Africa/Lome',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Luanda',
                'Africa/Luanda',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Lubumbashi',
                'Africa/Lubumbashi',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Lusaka',
                'Africa/Lusaka',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Malabo',
                'Africa/Malabo',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Maputo',
                'Africa/Maputo',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Maseru',
                'Africa/Maseru',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Mbabane',
                'Africa/Mbabane',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Mogadishu',
                'Africa/Mogadishu',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Monrovia',
                'Africa/Monrovia',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Nairobi',
                'Africa/Nairobi',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Ndjamena',
                'Africa/Ndjamena',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Niamey',
                'Africa/Niamey',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Nouakchott',
                'Africa/Nouakchott',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Ouagadougou',
                'Africa/Ouagadougou',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Porto-Novo',
                'Africa/Porto-Novo',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Sao_Tome',
                'Africa/Sao_Tome',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Tripoli',
                'Africa/Tripoli',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Tunis',
                'Africa/Tunis',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Windhoek',
                'Africa/Windhoek',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Adak',
                'America/Adak',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Anchorage',
                'America/Anchorage',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Anguilla',
                'America/Anguilla',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Antigua',
                'America/Antigua',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Araguaina',
                'America/Araguaina',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Argentina/Buenos_Aires',
                'America/Argentina/Buenos_Aires',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Argentina/Catamarca',
                'America/Argentina/Catamarca',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Argentina/Cordoba',
                'America/Argentina/Cordoba',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Argentina/Jujuy',
                'America/Argentina/Jujuy',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Argentina/La_Rioja',
                'America/Argentina/La_Rioja',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Argentina/Mendoza',
                'America/Argentina/Mendoza',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Argentina/Rio_Gallegos',
                'America/Argentina/Rio_Gallegos',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Argentina/Salta',
                'America/Argentina/Salta',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Argentina/San_Juan',
                'America/Argentina/San_Juan',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Argentina/San_Luis',
                'America/Argentina/San_Luis',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Argentina/Tucuman',
                'America/Argentina/Tucuman',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Argentina/Ushuaia',
                'America/Argentina/Ushuaia',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Aruba',
                'America/Aruba',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Asuncion',
                'America/Asuncion',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Atikokan',
                'America/Atikokan',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Bahia',
                'America/Bahia',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Bahia_Banderas',
                'America/Bahia_Banderas',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Barbados',
                'America/Barbados',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Belem',
                'America/Belem',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Belize',
                'America/Belize',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Blanc-Sablon',
                'America/Blanc-Sablon',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Boa_Vista',
                'America/Boa_Vista',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Bogota',
                'America/Bogota',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Boise',
                'America/Boise',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Cambridge_Bay',
                'America/Cambridge_Bay',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Campo_Grande',
                'America/Campo_Grande',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Cancun',
                'America/Cancun',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Caracas',
                'America/Caracas',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Cayenne',
                'America/Cayenne',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Cayman',
                'America/Cayman',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Chicago',
                'America/Chicago',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Chihuahua',
                'America/Chihuahua',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Costa_Rica',
                'America/Costa_Rica',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Creston',
                'America/Creston',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Cuiaba',
                'America/Cuiaba',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Curacao',
                'America/Curacao',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Danmarkshavn',
                'America/Danmarkshavn',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Dawson',
                'America/Dawson',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Dawson_Creek',
                'America/Dawson_Creek',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Denver',
                'America/Denver',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Detroit',
                'America/Detroit',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Dominica',
                'America/Dominica',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Edmonton',
                'America/Edmonton',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Eirunepe',
                'America/Eirunepe',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/El_Salvador',
                'America/El_Salvador',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Fortaleza',
                'America/Fortaleza',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Glace_Bay',
                'America/Glace_Bay',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Godthab',
                'America/Godthab',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Goose_Bay',
                'America/Goose_Bay',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Grand_Turk',
                'America/Grand_Turk',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Grenada',
                'America/Grenada',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Guadeloupe',
                'America/Guadeloupe',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Guatemala',
                'America/Guatemala',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Guayaquil',
                'America/Guayaquil',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Guyana',
                'America/Guyana',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Halifax',
                'America/Halifax',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Havana',
                'America/Havana',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Hermosillo',
                'America/Hermosillo',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Indiana/Indianapolis',
                'America/Indiana/Indianapolis',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Indiana/Knox',
                'America/Indiana/Knox',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Indiana/Marengo',
                'America/Indiana/Marengo',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Indiana/Petersburg',
                'America/Indiana/Petersburg',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Indiana/Tell_City',
                'America/Indiana/Tell_City',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Indiana/Vevay',
                'America/Indiana/Vevay',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Indiana/Vincennes',
                'America/Indiana/Vincennes',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Indiana/Winamac',
                'America/Indiana/Winamac',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Inuvik',
                'America/Inuvik',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Iqaluit',
                'America/Iqaluit',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Jamaica',
                'America/Jamaica',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Juneau',
                'America/Juneau',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Kentucky/Louisville',
                'America/Kentucky/Louisville',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Kentucky/Monticello',
                'America/Kentucky/Monticello',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Kralendijk',
                'America/Kralendijk',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/La_Paz',
                'America/La_Paz',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Lima',
                'America/Lima',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Los_Angeles',
                'America/Los_Angeles',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Lower_Princes',
                'America/Lower_Princes',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Maceio',
                'America/Maceio',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Managua',
                'America/Managua',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Manaus',
                'America/Manaus',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Marigot',
                'America/Marigot',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Martinique',
                'America/Martinique',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Matamoros',
                'America/Matamoros',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Mazatlan',
                'America/Mazatlan',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Menominee',
                'America/Menominee',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Merida',
                'America/Merida',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Metlakatla',
                'America/Metlakatla',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Mexico_City',
                'America/Mexico_City',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Miquelon',
                'America/Miquelon',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Moncton',
                'America/Moncton',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Monterrey',
                'America/Monterrey',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Montevideo',
                'America/Montevideo',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Montreal',
                'America/Montreal',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Montserrat',
                'America/Montserrat',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Nassau',
                'America/Nassau',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/New_York',
                'America/New_York',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Nipigon',
                'America/Nipigon',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Nome',
                'America/Nome',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Noronha',
                'America/Noronha',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/North_Dakota/Beulah',
                'America/North_Dakota/Beulah',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/North_Dakota/Center',
                'America/North_Dakota/Center',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/North_Dakota/New_Salem',
                'America/North_Dakota/New_Salem',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Ojinaga',
                'America/Ojinaga',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Panama',
                'America/Panama',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Pangnirtung',
                'America/Pangnirtung',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Paramaribo',
                'America/Paramaribo',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Phoenix',
                'America/Phoenix',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Port_of_Spain',
                'America/Port_of_Spain',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Port-au-Prince',
                'America/Port-au-Prince',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Porto_Velho',
                'America/Porto_Velho',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Puerto_Rico',
                'America/Puerto_Rico',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Rainy_River',
                'America/Rainy_River',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Rankin_Inlet',
                'America/Rankin_Inlet',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Recife',
                'America/Recife',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Regina',
                'America/Regina',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Resolute',
                'America/Resolute',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Rio_Branco',
                'America/Rio_Branco',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Santa_Isabel',
                'America/Santa_Isabel',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Santarem',
                'America/Santarem',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Santiago',
                'America/Santiago',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Santo_Domingo',
                'America/Santo_Domingo',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Sao_Paulo',
                'America/Sao_Paulo',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Scoresbysund',
                'America/Scoresbysund',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Shiprock',
                'America/Shiprock',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Sitka',
                'America/Sitka',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/St_Barthelemy',
                'America/St_Barthelemy',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/St_Johns',
                'America/St_Johns',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/St_Kitts',
                'America/St_Kitts',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/St_Lucia',
                'America/St_Lucia',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/St_Thomas',
                'America/St_Thomas',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/St_Vincent',
                'America/St_Vincent',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Swift_Current',
                'America/Swift_Current',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Tegucigalpa',
                'America/Tegucigalpa',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Thule',
                'America/Thule',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Thunder_Bay',
                'America/Thunder_Bay',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Tijuana',
                'America/Tijuana',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Toronto',
                'America/Toronto',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Tortola',
                'America/Tortola',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Vancouver',
                'America/Vancouver',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Whitehorse',
                'America/Whitehorse',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Winnipeg',
                'America/Winnipeg',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Yakutat',
                'America/Yakutat',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Yellowknife',
                'America/Yellowknife',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Antarctica/Casey',
                'Antarctica/Casey',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Antarctica/Davis',
                'Antarctica/Davis',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Antarctica/DumontDUrville',
                'Antarctica/DumontDUrville',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Antarctica/Macquarie',
                'Antarctica/Macquarie',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Antarctica/Mawson',
                'Antarctica/Mawson',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Antarctica/McMurdo',
                'Antarctica/McMurdo',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Antarctica/Palmer',
                'Antarctica/Palmer',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Antarctica/Rothera',
                'Antarctica/Rothera',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Antarctica/South_Pole',
                'Antarctica/South_Pole',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Antarctica/Syowa',
                'Antarctica/Syowa',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Antarctica/Vostok',
                'Antarctica/Vostok',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Arctic/Longyearbyen',
                'Arctic/Longyearbyen',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Aden',
                'Asia/Aden',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Almaty',
                'Asia/Almaty',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Amman',
                'Asia/Amman',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Anadyr',
                'Asia/Anadyr',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Aqtau',
                'Asia/Aqtau',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Aqtobe',
                'Asia/Aqtobe',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Ashgabat',
                'Asia/Ashgabat',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Baghdad',
                'Asia/Baghdad',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Bahrain',
                'Asia/Bahrain',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Baku',
                'Asia/Baku',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Bangkok',
                'Asia/Bangkok',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Beirut',
                'Asia/Beirut',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Bishkek',
                'Asia/Bishkek',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Brunei',
                'Asia/Brunei',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Choibalsan',
                'Asia/Choibalsan',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Chongqing',
                'Asia/Chongqing',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Colombo',
                'Asia/Colombo',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Damascus',
                'Asia/Damascus',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Dhaka',
                'Asia/Dhaka',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Dili',
                'Asia/Dili',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Dubai',
                'Asia/Dubai',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Dushanbe',
                'Asia/Dushanbe',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Gaza',
                'Asia/Gaza',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Harbin',
                'Asia/Harbin',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Hebron',
                'Asia/Hebron',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Ho_Chi_Minh',
                'Asia/Ho_Chi_Minh',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Hong_Kong',
                'Asia/Hong_Kong',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Hovd',
                'Asia/Hovd',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Irkutsk',
                'Asia/Irkutsk',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Jakarta',
                'Asia/Jakarta',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Jayapura',
                'Asia/Jayapura',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Jerusalem',
                'Asia/Jerusalem',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Kabul',
                'Asia/Kabul',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Kamchatka',
                'Asia/Kamchatka',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Karachi',
                'Asia/Karachi',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Kashgar',
                'Asia/Kashgar',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Kathmandu',
                'Asia/Kathmandu',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Kolkata',
                'Asia/Kolkata',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Krasnoyarsk',
                'Asia/Krasnoyarsk',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Kuala_Lumpur',
                'Asia/Kuala_Lumpur',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Kuching',
                'Asia/Kuching',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Kuwait',
                'Asia/Kuwait',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Macau',
                'Asia/Macau',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Magadan',
                'Asia/Magadan',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Makassar',
                'Asia/Makassar',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Manila',
                'Asia/Manila',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Muscat',
                'Asia/Muscat',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Nicosia',
                'Asia/Nicosia',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Novokuznetsk',
                'Asia/Novokuznetsk',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Novosibirsk',
                'Asia/Novosibirsk',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Omsk',
                'Asia/Omsk',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Oral',
                'Asia/Oral',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Phnom_Penh',
                'Asia/Phnom_Penh',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Pontianak',
                'Asia/Pontianak',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Pyongyang',
                'Asia/Pyongyang',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Qatar',
                'Asia/Qatar',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Qyzylorda',
                'Asia/Qyzylorda',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Rangoon',
                'Asia/Rangoon',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Riyadh',
                'Asia/Riyadh',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Sakhalin',
                'Asia/Sakhalin',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Samarkand',
                'Asia/Samarkand',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Seoul',
                'Asia/Seoul',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Shanghai',
                'Asia/Shanghai',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Singapore',
                'Asia/Singapore',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Taipei',
                'Asia/Taipei',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Tashkent',
                'Asia/Tashkent',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Tbilisi',
                'Asia/Tbilisi',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Tehran',
                'Asia/Tehran',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Thimphu',
                'Asia/Thimphu',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Tokyo',
                'Asia/Tokyo',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Ulaanbaatar',
                'Asia/Ulaanbaatar',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Urumqi',
                'Asia/Urumqi',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Vientiane',
                'Asia/Vientiane',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Vladivostok',
                'Asia/Vladivostok',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Yakutsk',
                'Asia/Yakutsk',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Yekaterinburg',
                'Asia/Yekaterinburg',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Yerevan',
                'Asia/Yerevan',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Atlantic/Azores',
                'Atlantic/Azores',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Atlantic/Bermuda',
                'Atlantic/Bermuda',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Atlantic/Canary',
                'Atlantic/Canary',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Atlantic/Cape_Verde',
                'Atlantic/Cape_Verde',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Atlantic/Faroe',
                'Atlantic/Faroe',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Atlantic/Madeira',
                'Atlantic/Madeira',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Atlantic/Reykjavik',
                'Atlantic/Reykjavik',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Atlantic/South_Georgia',
                'Atlantic/South_Georgia',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Atlantic/St_Helena',
                'Atlantic/St_Helena',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Atlantic/Stanley',
                'Atlantic/Stanley',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Australia/Adelaide',
                'Australia/Adelaide',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Australia/Brisbane',
                'Australia/Brisbane',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Australia/Broken_Hill',
                'Australia/Broken_Hill',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Australia/Currie',
                'Australia/Currie',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Australia/Darwin',
                'Australia/Darwin',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Australia/Eucla',
                'Australia/Eucla',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Australia/Hobart',
                'Australia/Hobart',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Australia/Lindeman',
                'Australia/Lindeman',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Australia/Lord_Howe',
                'Australia/Lord_Howe',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Australia/Melbourne',
                'Australia/Melbourne',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Australia/Perth',
                'Australia/Perth',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Australia/Sydney',
                'Australia/Sydney',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Amsterdam',
                'Europe/Amsterdam',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Andorra',
                'Europe/Andorra',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Athens',
                'Europe/Athens',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Belgrade',
                'Europe/Belgrade',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Berlin',
                'Europe/Berlin',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Bratislava',
                'Europe/Bratislava',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Brussels',
                'Europe/Brussels',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Bucharest',
                'Europe/Bucharest',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Budapest',
                'Europe/Budapest',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Chisinau',
                'Europe/Chisinau',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Copenhagen',
                'Europe/Copenhagen',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Dublin',
                'Europe/Dublin',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Gibraltar',
                'Europe/Gibraltar',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Guernsey',
                'Europe/Guernsey',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Helsinki',
                'Europe/Helsinki',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Isle_of_Man',
                'Europe/Isle_of_Man',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Istanbul',
                'Europe/Istanbul',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Jersey',
                'Europe/Jersey',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Kaliningrad',
                'Europe/Kaliningrad',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Kiev',
                'Europe/Kiev',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Lisbon',
                'Europe/Lisbon',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Ljubljana',
                'Europe/Ljubljana',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/London',
                'Europe/London',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Luxembourg',
                'Europe/Luxembourg',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Madrid',
                'Europe/Madrid',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Malta',
                'Europe/Malta',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Mariehamn',
                'Europe/Mariehamn',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Minsk',
                'Europe/Minsk',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Monaco',
                'Europe/Monaco',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Moscow',
                'Europe/Moscow',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Oslo',
                'Europe/Oslo',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Paris',
                'Europe/Paris',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Podgorica',
                'Europe/Podgorica',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Prague',
                'Europe/Prague',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Riga',
                'Europe/Riga',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Rome',
                'Europe/Rome',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Samara',
                'Europe/Samara',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/San_Marino',
                'Europe/San_Marino',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Sarajevo',
                'Europe/Sarajevo',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Simferopol',
                'Europe/Simferopol',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Skopje',
                'Europe/Skopje',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Sofia',
                'Europe/Sofia',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Stockholm',
                'Europe/Stockholm',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Tallinn',
                'Europe/Tallinn',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Tirane',
                'Europe/Tirane',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Uzhgorod',
                'Europe/Uzhgorod',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Vaduz',
                'Europe/Vaduz',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Vatican',
                'Europe/Vatican',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Vienna',
                'Europe/Vienna',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Vilnius',
                'Europe/Vilnius',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Volgograd',
                'Europe/Volgograd',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Warsaw',
                'Europe/Warsaw',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Zagreb',
                'Europe/Zagreb',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Zaporozhye',
                'Europe/Zaporozhye',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Zurich',
                'Europe/Zurich',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Indian/Antananarivo',
                'Indian/Antananarivo',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Indian/Chagos',
                'Indian/Chagos',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Indian/Christmas',
                'Indian/Christmas',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Indian/Cocos',
                'Indian/Cocos',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Indian/Comoro',
                'Indian/Comoro',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Indian/Kerguelen',
                'Indian/Kerguelen',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Indian/Mahe',
                'Indian/Mahe',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Indian/Maldives',
                'Indian/Maldives',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Indian/Mauritius',
                'Indian/Mauritius',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Indian/Mayotte',
                'Indian/Mayotte',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Indian/Reunion',
                'Indian/Reunion',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Apia',
                'Pacific/Apia',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Auckland',
                'Pacific/Auckland',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Chatham',
                'Pacific/Chatham',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Chuuk',
                'Pacific/Chuuk',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Easter',
                'Pacific/Easter',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Efate',
                'Pacific/Efate',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Enderbury',
                'Pacific/Enderbury',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Fakaofo',
                'Pacific/Fakaofo',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Fiji',
                'Pacific/Fiji',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Funafuti',
                'Pacific/Funafuti',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Galapagos',
                'Pacific/Galapagos',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Gambier',
                'Pacific/Gambier',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Guadalcanal',
                'Pacific/Guadalcanal',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Guam',
                'Pacific/Guam',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Honolulu',
                'Pacific/Honolulu',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Johnston',
                'Pacific/Johnston',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Kiritimati',
                'Pacific/Kiritimati',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Kosrae',
                'Pacific/Kosrae',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Kwajalein',
                'Pacific/Kwajalein',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Majuro',
                'Pacific/Majuro',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Marquesas',
                'Pacific/Marquesas',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Midway',
                'Pacific/Midway',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Nauru',
                'Pacific/Nauru',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Niue',
                'Pacific/Niue',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Norfolk',
                'Pacific/Norfolk',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Noumea',
                'Pacific/Noumea',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Pago_Pago',
                'Pacific/Pago_Pago',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Palau',
                'Pacific/Palau',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Pitcairn',
                'Pacific/Pitcairn',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Pohnpei',
                'Pacific/Pohnpei',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Port_Moresby',
                'Pacific/Port_Moresby',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Rarotonga',
                'Pacific/Rarotonga',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Saipan',
                'Pacific/Saipan',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Tahiti',
                'Pacific/Tahiti',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Tarawa',
                'Pacific/Tarawa',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Tongatapu',
                'Pacific/Tongatapu',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Wake',
                'Pacific/Wake',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Wallis',
                'Pacific/Wallis',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

-- RHEL 8
insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Abidjan',
                'Africa/Abidjan',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Accra',
                'Africa/Accra',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Addis_Ababa',
                'Africa/Addis_Ababa',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Algiers',
                'Africa/Algiers',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Asmara',
                'Africa/Asmara',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Bamako',
                'Africa/Bamako',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Bangui',
                'Africa/Bangui',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Banjul',
                'Africa/Banjul',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Bissau',
                'Africa/Bissau',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Blantyre',
                'Africa/Blantyre',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Brazzaville',
                'Africa/Brazzaville',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Bujumbura',
                'Africa/Bujumbura',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Cairo',
                'Africa/Cairo',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Casablanca',
                'Africa/Casablanca',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Ceuta',
                'Africa/Ceuta',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Conakry',
                'Africa/Conakry',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Dakar',
                'Africa/Dakar',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Dar_es_Salaam',
                'Africa/Dar_es_Salaam',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Djibouti',
                'Africa/Djibouti',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Douala',
                'Africa/Douala',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/El_Aaiun',
                'Africa/El_Aaiun',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Freetown',
                'Africa/Freetown',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Gaborone',
                'Africa/Gaborone',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Harare',
                'Africa/Harare',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Johannesburg',
                'Africa/Johannesburg',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Juba',
                'Africa/Juba',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Kampala',
                'Africa/Kampala',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Khartoum',
                'Africa/Khartoum',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Kigali',
                'Africa/Kigali',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Kinshasa',
                'Africa/Kinshasa',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Lagos',
                'Africa/Lagos',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Libreville',
                'Africa/Libreville',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Lome',
                'Africa/Lome',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Luanda',
                'Africa/Luanda',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Lubumbashi',
                'Africa/Lubumbashi',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Lusaka',
                'Africa/Lusaka',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Malabo',
                'Africa/Malabo',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Maputo',
                'Africa/Maputo',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Maseru',
                'Africa/Maseru',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Mbabane',
                'Africa/Mbabane',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Mogadishu',
                'Africa/Mogadishu',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Monrovia',
                'Africa/Monrovia',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Nairobi',
                'Africa/Nairobi',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Ndjamena',
                'Africa/Ndjamena',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Niamey',
                'Africa/Niamey',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Nouakchott',
                'Africa/Nouakchott',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Ouagadougou',
                'Africa/Ouagadougou',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Porto-Novo',
                'Africa/Porto-Novo',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Sao_Tome',
                'Africa/Sao_Tome',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Tripoli',
                'Africa/Tripoli',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Tunis',
                'Africa/Tunis',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Windhoek',
                'Africa/Windhoek',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Adak',
                'America/Adak',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Anchorage',
                'America/Anchorage',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Anguilla',
                'America/Anguilla',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Antigua',
                'America/Antigua',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Araguaina',
                'America/Araguaina',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Argentina/Buenos_Aires',
                'America/Argentina/Buenos_Aires',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Argentina/Catamarca',
                'America/Argentina/Catamarca',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Argentina/Cordoba',
                'America/Argentina/Cordoba',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Argentina/Jujuy',
                'America/Argentina/Jujuy',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Argentina/La_Rioja',
                'America/Argentina/La_Rioja',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Argentina/Mendoza',
                'America/Argentina/Mendoza',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Argentina/Rio_Gallegos',
                'America/Argentina/Rio_Gallegos',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Argentina/Salta',
                'America/Argentina/Salta',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Argentina/San_Juan',
                'America/Argentina/San_Juan',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Argentina/San_Luis',
                'America/Argentina/San_Luis',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Argentina/Tucuman',
                'America/Argentina/Tucuman',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Argentina/Ushuaia',
                'America/Argentina/Ushuaia',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Aruba',
                'America/Aruba',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Asuncion',
                'America/Asuncion',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Atikokan',
                'America/Atikokan',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Bahia',
                'America/Bahia',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Bahia_Banderas',
                'America/Bahia_Banderas',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Barbados',
                'America/Barbados',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Belem',
                'America/Belem',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Belize',
                'America/Belize',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Blanc-Sablon',
                'America/Blanc-Sablon',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Boa_Vista',
                'America/Boa_Vista',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Bogota',
                'America/Bogota',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Boise',
                'America/Boise',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Cambridge_Bay',
                'America/Cambridge_Bay',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Campo_Grande',
                'America/Campo_Grande',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Cancun',
                'America/Cancun',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Caracas',
                'America/Caracas',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Cayenne',
                'America/Cayenne',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Cayman',
                'America/Cayman',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Chicago',
                'America/Chicago',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Chihuahua',
                'America/Chihuahua',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Costa_Rica',
                'America/Costa_Rica',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Creston',
                'America/Creston',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Cuiaba',
                'America/Cuiaba',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Curacao',
                'America/Curacao',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Danmarkshavn',
                'America/Danmarkshavn',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Dawson',
                'America/Dawson',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Dawson_Creek',
                'America/Dawson_Creek',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Denver',
                'America/Denver',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Detroit',
                'America/Detroit',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Dominica',
                'America/Dominica',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Edmonton',
                'America/Edmonton',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Eirunepe',
                'America/Eirunepe',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/El_Salvador',
                'America/El_Salvador',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Fortaleza',
                'America/Fortaleza',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Glace_Bay',
                'America/Glace_Bay',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Godthab',
                'America/Godthab',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Goose_Bay',
                'America/Goose_Bay',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Grand_Turk',
                'America/Grand_Turk',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Grenada',
                'America/Grenada',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Guadeloupe',
                'America/Guadeloupe',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Guatemala',
                'America/Guatemala',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Guayaquil',
                'America/Guayaquil',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Guyana',
                'America/Guyana',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Halifax',
                'America/Halifax',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Havana',
                'America/Havana',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Hermosillo',
                'America/Hermosillo',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Indiana/Indianapolis',
                'America/Indiana/Indianapolis',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Indiana/Knox',
                'America/Indiana/Knox',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Indiana/Marengo',
                'America/Indiana/Marengo',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Indiana/Petersburg',
                'America/Indiana/Petersburg',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Indiana/Tell_City',
                'America/Indiana/Tell_City',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Indiana/Vevay',
                'America/Indiana/Vevay',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Indiana/Vincennes',
                'America/Indiana/Vincennes',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Indiana/Winamac',
                'America/Indiana/Winamac',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Inuvik',
                'America/Inuvik',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Iqaluit',
                'America/Iqaluit',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Jamaica',
                'America/Jamaica',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Juneau',
                'America/Juneau',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Kentucky/Louisville',
                'America/Kentucky/Louisville',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Kentucky/Monticello',
                'America/Kentucky/Monticello',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Kralendijk',
                'America/Kralendijk',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/La_Paz',
                'America/La_Paz',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Lima',
                'America/Lima',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Los_Angeles',
                'America/Los_Angeles',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Lower_Princes',
                'America/Lower_Princes',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Maceio',
                'America/Maceio',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Managua',
                'America/Managua',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Manaus',
                'America/Manaus',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Marigot',
                'America/Marigot',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Martinique',
                'America/Martinique',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Matamoros',
                'America/Matamoros',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Mazatlan',
                'America/Mazatlan',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Menominee',
                'America/Menominee',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Merida',
                'America/Merida',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Metlakatla',
                'America/Metlakatla',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Mexico_City',
                'America/Mexico_City',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Miquelon',
                'America/Miquelon',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Moncton',
                'America/Moncton',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Monterrey',
                'America/Monterrey',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Montevideo',
                'America/Montevideo',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Montreal',
                'America/Montreal',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Montserrat',
                'America/Montserrat',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Nassau',
                'America/Nassau',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/New_York',
                'America/New_York',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Nipigon',
                'America/Nipigon',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Nome',
                'America/Nome',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Noronha',
                'America/Noronha',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/North_Dakota/Beulah',
                'America/North_Dakota/Beulah',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/North_Dakota/Center',
                'America/North_Dakota/Center',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/North_Dakota/New_Salem',
                'America/North_Dakota/New_Salem',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Ojinaga',
                'America/Ojinaga',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Panama',
                'America/Panama',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Pangnirtung',
                'America/Pangnirtung',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Paramaribo',
                'America/Paramaribo',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Phoenix',
                'America/Phoenix',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Port_of_Spain',
                'America/Port_of_Spain',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Port-au-Prince',
                'America/Port-au-Prince',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Porto_Velho',
                'America/Porto_Velho',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Puerto_Rico',
                'America/Puerto_Rico',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Rainy_River',
                'America/Rainy_River',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Rankin_Inlet',
                'America/Rankin_Inlet',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Recife',
                'America/Recife',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Regina',
                'America/Regina',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Resolute',
                'America/Resolute',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Rio_Branco',
                'America/Rio_Branco',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Santa_Isabel',
                'America/Santa_Isabel',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Santarem',
                'America/Santarem',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Santiago',
                'America/Santiago',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Santo_Domingo',
                'America/Santo_Domingo',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Sao_Paulo',
                'America/Sao_Paulo',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Scoresbysund',
                'America/Scoresbysund',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Shiprock',
                'America/Shiprock',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Sitka',
                'America/Sitka',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/St_Barthelemy',
                'America/St_Barthelemy',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/St_Johns',
                'America/St_Johns',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/St_Kitts',
                'America/St_Kitts',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/St_Lucia',
                'America/St_Lucia',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/St_Thomas',
                'America/St_Thomas',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/St_Vincent',
                'America/St_Vincent',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Swift_Current',
                'America/Swift_Current',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Tegucigalpa',
                'America/Tegucigalpa',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Thule',
                'America/Thule',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Thunder_Bay',
                'America/Thunder_Bay',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Tijuana',
                'America/Tijuana',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Toronto',
                'America/Toronto',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Tortola',
                'America/Tortola',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Vancouver',
                'America/Vancouver',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Whitehorse',
                'America/Whitehorse',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Winnipeg',
                'America/Winnipeg',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Yakutat',
                'America/Yakutat',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Yellowknife',
                'America/Yellowknife',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Antarctica/Casey',
                'Antarctica/Casey',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Antarctica/Davis',
                'Antarctica/Davis',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Antarctica/DumontDUrville',
                'Antarctica/DumontDUrville',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Antarctica/Macquarie',
                'Antarctica/Macquarie',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Antarctica/Mawson',
                'Antarctica/Mawson',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Antarctica/McMurdo',
                'Antarctica/McMurdo',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Antarctica/Palmer',
                'Antarctica/Palmer',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Antarctica/Rothera',
                'Antarctica/Rothera',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Antarctica/South_Pole',
                'Antarctica/South_Pole',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Antarctica/Syowa',
                'Antarctica/Syowa',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Antarctica/Vostok',
                'Antarctica/Vostok',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Arctic/Longyearbyen',
                'Arctic/Longyearbyen',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Aden',
                'Asia/Aden',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Almaty',
                'Asia/Almaty',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Amman',
                'Asia/Amman',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Anadyr',
                'Asia/Anadyr',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Aqtau',
                'Asia/Aqtau',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Aqtobe',
                'Asia/Aqtobe',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Ashgabat',
                'Asia/Ashgabat',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Baghdad',
                'Asia/Baghdad',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Bahrain',
                'Asia/Bahrain',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Baku',
                'Asia/Baku',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Bangkok',
                'Asia/Bangkok',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Beirut',
                'Asia/Beirut',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Bishkek',
                'Asia/Bishkek',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Brunei',
                'Asia/Brunei',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Choibalsan',
                'Asia/Choibalsan',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Chongqing',
                'Asia/Chongqing',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Colombo',
                'Asia/Colombo',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Damascus',
                'Asia/Damascus',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Dhaka',
                'Asia/Dhaka',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Dili',
                'Asia/Dili',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Dubai',
                'Asia/Dubai',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Dushanbe',
                'Asia/Dushanbe',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Gaza',
                'Asia/Gaza',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Harbin',
                'Asia/Harbin',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Hebron',
                'Asia/Hebron',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Ho_Chi_Minh',
                'Asia/Ho_Chi_Minh',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Hong_Kong',
                'Asia/Hong_Kong',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Hovd',
                'Asia/Hovd',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Irkutsk',
                'Asia/Irkutsk',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Jakarta',
                'Asia/Jakarta',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Jayapura',
                'Asia/Jayapura',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Jerusalem',
                'Asia/Jerusalem',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Kabul',
                'Asia/Kabul',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Kamchatka',
                'Asia/Kamchatka',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Karachi',
                'Asia/Karachi',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Kashgar',
                'Asia/Kashgar',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Kathmandu',
                'Asia/Kathmandu',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Kolkata',
                'Asia/Kolkata',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Krasnoyarsk',
                'Asia/Krasnoyarsk',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Kuala_Lumpur',
                'Asia/Kuala_Lumpur',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Kuching',
                'Asia/Kuching',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Kuwait',
                'Asia/Kuwait',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Macau',
                'Asia/Macau',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Magadan',
                'Asia/Magadan',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Makassar',
                'Asia/Makassar',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Manila',
                'Asia/Manila',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Muscat',
                'Asia/Muscat',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Nicosia',
                'Asia/Nicosia',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Novokuznetsk',
                'Asia/Novokuznetsk',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Novosibirsk',
                'Asia/Novosibirsk',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Omsk',
                'Asia/Omsk',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Oral',
                'Asia/Oral',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Phnom_Penh',
                'Asia/Phnom_Penh',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Pontianak',
                'Asia/Pontianak',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Pyongyang',
                'Asia/Pyongyang',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Qatar',
                'Asia/Qatar',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Qyzylorda',
                'Asia/Qyzylorda',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Rangoon',
                'Asia/Rangoon',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Riyadh',
                'Asia/Riyadh',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Sakhalin',
                'Asia/Sakhalin',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Samarkand',
                'Asia/Samarkand',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Seoul',
                'Asia/Seoul',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Shanghai',
                'Asia/Shanghai',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Singapore',
                'Asia/Singapore',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Taipei',
                'Asia/Taipei',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Tashkent',
                'Asia/Tashkent',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Tbilisi',
                'Asia/Tbilisi',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Tehran',
                'Asia/Tehran',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Thimphu',
                'Asia/Thimphu',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Tokyo',
                'Asia/Tokyo',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Ulaanbaatar',
                'Asia/Ulaanbaatar',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Urumqi',
                'Asia/Urumqi',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Vientiane',
                'Asia/Vientiane',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Vladivostok',
                'Asia/Vladivostok',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Yakutsk',
                'Asia/Yakutsk',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Yekaterinburg',
                'Asia/Yekaterinburg',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Yerevan',
                'Asia/Yerevan',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Atlantic/Azores',
                'Atlantic/Azores',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Atlantic/Bermuda',
                'Atlantic/Bermuda',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Atlantic/Canary',
                'Atlantic/Canary',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Atlantic/Cape_Verde',
                'Atlantic/Cape_Verde',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Atlantic/Faroe',
                'Atlantic/Faroe',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Atlantic/Madeira',
                'Atlantic/Madeira',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Atlantic/Reykjavik',
                'Atlantic/Reykjavik',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Atlantic/South_Georgia',
                'Atlantic/South_Georgia',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Atlantic/St_Helena',
                'Atlantic/St_Helena',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Atlantic/Stanley',
                'Atlantic/Stanley',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Australia/Adelaide',
                'Australia/Adelaide',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Australia/Brisbane',
                'Australia/Brisbane',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Australia/Broken_Hill',
                'Australia/Broken_Hill',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Australia/Currie',
                'Australia/Currie',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Australia/Darwin',
                'Australia/Darwin',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Australia/Eucla',
                'Australia/Eucla',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Australia/Hobart',
                'Australia/Hobart',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Australia/Lindeman',
                'Australia/Lindeman',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Australia/Lord_Howe',
                'Australia/Lord_Howe',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Australia/Melbourne',
                'Australia/Melbourne',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Australia/Perth',
                'Australia/Perth',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Australia/Sydney',
                'Australia/Sydney',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Amsterdam',
                'Europe/Amsterdam',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Andorra',
                'Europe/Andorra',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Athens',
                'Europe/Athens',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Belgrade',
                'Europe/Belgrade',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Berlin',
                'Europe/Berlin',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Bratislava',
                'Europe/Bratislava',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Brussels',
                'Europe/Brussels',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Bucharest',
                'Europe/Bucharest',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Budapest',
                'Europe/Budapest',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Chisinau',
                'Europe/Chisinau',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Copenhagen',
                'Europe/Copenhagen',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Dublin',
                'Europe/Dublin',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Gibraltar',
                'Europe/Gibraltar',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Guernsey',
                'Europe/Guernsey',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Helsinki',
                'Europe/Helsinki',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Isle_of_Man',
                'Europe/Isle_of_Man',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Istanbul',
                'Europe/Istanbul',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Jersey',
                'Europe/Jersey',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Kaliningrad',
                'Europe/Kaliningrad',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Kiev',
                'Europe/Kiev',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Lisbon',
                'Europe/Lisbon',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Ljubljana',
                'Europe/Ljubljana',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/London',
                'Europe/London',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Luxembourg',
                'Europe/Luxembourg',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Madrid',
                'Europe/Madrid',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Malta',
                'Europe/Malta',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Mariehamn',
                'Europe/Mariehamn',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Minsk',
                'Europe/Minsk',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Monaco',
                'Europe/Monaco',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Moscow',
                'Europe/Moscow',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Oslo',
                'Europe/Oslo',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Paris',
                'Europe/Paris',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Podgorica',
                'Europe/Podgorica',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Prague',
                'Europe/Prague',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Riga',
                'Europe/Riga',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Rome',
                'Europe/Rome',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Samara',
                'Europe/Samara',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/San_Marino',
                'Europe/San_Marino',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Sarajevo',
                'Europe/Sarajevo',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Simferopol',
                'Europe/Simferopol',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Skopje',
                'Europe/Skopje',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Sofia',
                'Europe/Sofia',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Stockholm',
                'Europe/Stockholm',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Tallinn',
                'Europe/Tallinn',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Tirane',
                'Europe/Tirane',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Uzhgorod',
                'Europe/Uzhgorod',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Vaduz',
                'Europe/Vaduz',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Vatican',
                'Europe/Vatican',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Vienna',
                'Europe/Vienna',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Vilnius',
                'Europe/Vilnius',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Volgograd',
                'Europe/Volgograd',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Warsaw',
                'Europe/Warsaw',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Zagreb',
                'Europe/Zagreb',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Zaporozhye',
                'Europe/Zaporozhye',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Zurich',
                'Europe/Zurich',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Indian/Antananarivo',
                'Indian/Antananarivo',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Indian/Chagos',
                'Indian/Chagos',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Indian/Christmas',
                'Indian/Christmas',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Indian/Cocos',
                'Indian/Cocos',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Indian/Comoro',
                'Indian/Comoro',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Indian/Kerguelen',
                'Indian/Kerguelen',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Indian/Mahe',
                'Indian/Mahe',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Indian/Maldives',
                'Indian/Maldives',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Indian/Mauritius',
                'Indian/Mauritius',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Indian/Mayotte',
                'Indian/Mayotte',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Indian/Reunion',
                'Indian/Reunion',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Apia',
                'Pacific/Apia',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Auckland',
                'Pacific/Auckland',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Chatham',
                'Pacific/Chatham',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Chuuk',
                'Pacific/Chuuk',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Easter',
                'Pacific/Easter',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Efate',
                'Pacific/Efate',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Enderbury',
                'Pacific/Enderbury',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Fakaofo',
                'Pacific/Fakaofo',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Fiji',
                'Pacific/Fiji',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Funafuti',
                'Pacific/Funafuti',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Galapagos',
                'Pacific/Galapagos',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Gambier',
                'Pacific/Gambier',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Guadalcanal',
                'Pacific/Guadalcanal',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Guam',
                'Pacific/Guam',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Honolulu',
                'Pacific/Honolulu',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Johnston',
                'Pacific/Johnston',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Kiritimati',
                'Pacific/Kiritimati',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Kosrae',
                'Pacific/Kosrae',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Kwajalein',
                'Pacific/Kwajalein',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Majuro',
                'Pacific/Majuro',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Marquesas',
                'Pacific/Marquesas',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Midway',
                'Pacific/Midway',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Nauru',
                'Pacific/Nauru',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Niue',
                'Pacific/Niue',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Norfolk',
                'Pacific/Norfolk',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Noumea',
                'Pacific/Noumea',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Pago_Pago',
                'Pacific/Pago_Pago',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Palau',
                'Pacific/Palau',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Pitcairn',
                'Pacific/Pitcairn',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Pohnpei',
                'Pacific/Pohnpei',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Port_Moresby',
                'Pacific/Port_Moresby',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Rarotonga',
                'Pacific/Rarotonga',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Saipan',
                'Pacific/Saipan',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Tahiti',
                'Pacific/Tahiti',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Tarawa',
                'Pacific/Tarawa',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Tongatapu',
                'Pacific/Tongatapu',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Wake',
                'Pacific/Wake',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Wallis',
                'Pacific/Wallis',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

-- RHEL 9
insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Abidjan',
                'Africa/Abidjan',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Accra',
                'Africa/Accra',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Addis_Ababa',
                'Africa/Addis_Ababa',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Algiers',
                'Africa/Algiers',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Asmara',
                'Africa/Asmara',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Bamako',
                'Africa/Bamako',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Bangui',
                'Africa/Bangui',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Banjul',
                'Africa/Banjul',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Bissau',
                'Africa/Bissau',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Blantyre',
                'Africa/Blantyre',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Brazzaville',
                'Africa/Brazzaville',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Bujumbura',
                'Africa/Bujumbura',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Cairo',
                'Africa/Cairo',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Casablanca',
                'Africa/Casablanca',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Ceuta',
                'Africa/Ceuta',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Conakry',
                'Africa/Conakry',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Dakar',
                'Africa/Dakar',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Dar_es_Salaam',
                'Africa/Dar_es_Salaam',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Djibouti',
                'Africa/Djibouti',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Douala',
                'Africa/Douala',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/El_Aaiun',
                'Africa/El_Aaiun',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Freetown',
                'Africa/Freetown',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Gaborone',
                'Africa/Gaborone',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Harare',
                'Africa/Harare',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Johannesburg',
                'Africa/Johannesburg',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Juba',
                'Africa/Juba',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Kampala',
                'Africa/Kampala',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Khartoum',
                'Africa/Khartoum',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Kigali',
                'Africa/Kigali',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Kinshasa',
                'Africa/Kinshasa',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Lagos',
                'Africa/Lagos',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Libreville',
                'Africa/Libreville',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Lome',
                'Africa/Lome',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Luanda',
                'Africa/Luanda',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Lubumbashi',
                'Africa/Lubumbashi',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Lusaka',
                'Africa/Lusaka',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Malabo',
                'Africa/Malabo',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Maputo',
                'Africa/Maputo',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Maseru',
                'Africa/Maseru',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Mbabane',
                'Africa/Mbabane',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Mogadishu',
                'Africa/Mogadishu',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Monrovia',
                'Africa/Monrovia',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Nairobi',
                'Africa/Nairobi',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Ndjamena',
                'Africa/Ndjamena',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Niamey',
                'Africa/Niamey',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Nouakchott',
                'Africa/Nouakchott',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Ouagadougou',
                'Africa/Ouagadougou',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Porto-Novo',
                'Africa/Porto-Novo',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Sao_Tome',
                'Africa/Sao_Tome',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Tripoli',
                'Africa/Tripoli',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Tunis',
                'Africa/Tunis',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Windhoek',
                'Africa/Windhoek',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Adak',
                'America/Adak',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Anchorage',
                'America/Anchorage',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Anguilla',
                'America/Anguilla',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Antigua',
                'America/Antigua',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Araguaina',
                'America/Araguaina',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Argentina/Buenos_Aires',
                'America/Argentina/Buenos_Aires',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Argentina/Catamarca',
                'America/Argentina/Catamarca',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Argentina/Cordoba',
                'America/Argentina/Cordoba',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Argentina/Jujuy',
                'America/Argentina/Jujuy',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Argentina/La_Rioja',
                'America/Argentina/La_Rioja',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Argentina/Mendoza',
                'America/Argentina/Mendoza',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Argentina/Rio_Gallegos',
                'America/Argentina/Rio_Gallegos',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Argentina/Salta',
                'America/Argentina/Salta',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Argentina/San_Juan',
                'America/Argentina/San_Juan',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Argentina/San_Luis',
                'America/Argentina/San_Luis',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Argentina/Tucuman',
                'America/Argentina/Tucuman',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Argentina/Ushuaia',
                'America/Argentina/Ushuaia',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Aruba',
                'America/Aruba',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Asuncion',
                'America/Asuncion',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Atikokan',
                'America/Atikokan',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Bahia',
                'America/Bahia',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Bahia_Banderas',
                'America/Bahia_Banderas',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Barbados',
                'America/Barbados',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Belem',
                'America/Belem',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Belize',
                'America/Belize',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Blanc-Sablon',
                'America/Blanc-Sablon',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Boa_Vista',
                'America/Boa_Vista',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Bogota',
                'America/Bogota',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Boise',
                'America/Boise',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Cambridge_Bay',
                'America/Cambridge_Bay',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Campo_Grande',
                'America/Campo_Grande',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Cancun',
                'America/Cancun',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Caracas',
                'America/Caracas',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Cayenne',
                'America/Cayenne',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Cayman',
                'America/Cayman',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Chicago',
                'America/Chicago',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Chihuahua',
                'America/Chihuahua',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Costa_Rica',
                'America/Costa_Rica',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Creston',
                'America/Creston',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Cuiaba',
                'America/Cuiaba',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Curacao',
                'America/Curacao',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Danmarkshavn',
                'America/Danmarkshavn',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Dawson',
                'America/Dawson',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Dawson_Creek',
                'America/Dawson_Creek',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Denver',
                'America/Denver',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Detroit',
                'America/Detroit',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Dominica',
                'America/Dominica',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Edmonton',
                'America/Edmonton',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Eirunepe',
                'America/Eirunepe',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/El_Salvador',
                'America/El_Salvador',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Fortaleza',
                'America/Fortaleza',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Glace_Bay',
                'America/Glace_Bay',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Godthab',
                'America/Godthab',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Goose_Bay',
                'America/Goose_Bay',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Grand_Turk',
                'America/Grand_Turk',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Grenada',
                'America/Grenada',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Guadeloupe',
                'America/Guadeloupe',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Guatemala',
                'America/Guatemala',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Guayaquil',
                'America/Guayaquil',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Guyana',
                'America/Guyana',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Halifax',
                'America/Halifax',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Havana',
                'America/Havana',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Hermosillo',
                'America/Hermosillo',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Indiana/Indianapolis',
                'America/Indiana/Indianapolis',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Indiana/Knox',
                'America/Indiana/Knox',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Indiana/Marengo',
                'America/Indiana/Marengo',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Indiana/Petersburg',
                'America/Indiana/Petersburg',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Indiana/Tell_City',
                'America/Indiana/Tell_City',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Indiana/Vevay',
                'America/Indiana/Vevay',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Indiana/Vincennes',
                'America/Indiana/Vincennes',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Indiana/Winamac',
                'America/Indiana/Winamac',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Inuvik',
                'America/Inuvik',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Iqaluit',
                'America/Iqaluit',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Jamaica',
                'America/Jamaica',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Juneau',
                'America/Juneau',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Kentucky/Louisville',
                'America/Kentucky/Louisville',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Kentucky/Monticello',
                'America/Kentucky/Monticello',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Kralendijk',
                'America/Kralendijk',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/La_Paz',
                'America/La_Paz',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Lima',
                'America/Lima',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Los_Angeles',
                'America/Los_Angeles',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Lower_Princes',
                'America/Lower_Princes',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Maceio',
                'America/Maceio',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Managua',
                'America/Managua',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Manaus',
                'America/Manaus',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Marigot',
                'America/Marigot',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Martinique',
                'America/Martinique',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Matamoros',
                'America/Matamoros',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Mazatlan',
                'America/Mazatlan',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Menominee',
                'America/Menominee',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Merida',
                'America/Merida',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Metlakatla',
                'America/Metlakatla',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Mexico_City',
                'America/Mexico_City',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Miquelon',
                'America/Miquelon',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Moncton',
                'America/Moncton',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Monterrey',
                'America/Monterrey',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Montevideo',
                'America/Montevideo',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Montreal',
                'America/Montreal',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Montserrat',
                'America/Montserrat',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Nassau',
                'America/Nassau',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/New_York',
                'America/New_York',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Nipigon',
                'America/Nipigon',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Nome',
                'America/Nome',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Noronha',
                'America/Noronha',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/North_Dakota/Beulah',
                'America/North_Dakota/Beulah',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/North_Dakota/Center',
                'America/North_Dakota/Center',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/North_Dakota/New_Salem',
                'America/North_Dakota/New_Salem',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Ojinaga',
                'America/Ojinaga',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Panama',
                'America/Panama',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Pangnirtung',
                'America/Pangnirtung',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Paramaribo',
                'America/Paramaribo',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Phoenix',
                'America/Phoenix',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Port_of_Spain',
                'America/Port_of_Spain',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Port-au-Prince',
                'America/Port-au-Prince',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Porto_Velho',
                'America/Porto_Velho',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Puerto_Rico',
                'America/Puerto_Rico',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Rainy_River',
                'America/Rainy_River',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Rankin_Inlet',
                'America/Rankin_Inlet',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Recife',
                'America/Recife',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Regina',
                'America/Regina',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Resolute',
                'America/Resolute',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Rio_Branco',
                'America/Rio_Branco',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Santa_Isabel',
                'America/Santa_Isabel',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Santarem',
                'America/Santarem',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Santiago',
                'America/Santiago',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Santo_Domingo',
                'America/Santo_Domingo',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Sao_Paulo',
                'America/Sao_Paulo',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Scoresbysund',
                'America/Scoresbysund',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Shiprock',
                'America/Shiprock',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Sitka',
                'America/Sitka',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/St_Barthelemy',
                'America/St_Barthelemy',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/St_Johns',
                'America/St_Johns',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/St_Kitts',
                'America/St_Kitts',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/St_Lucia',
                'America/St_Lucia',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/St_Thomas',
                'America/St_Thomas',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/St_Vincent',
                'America/St_Vincent',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Swift_Current',
                'America/Swift_Current',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Tegucigalpa',
                'America/Tegucigalpa',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Thule',
                'America/Thule',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Thunder_Bay',
                'America/Thunder_Bay',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Tijuana',
                'America/Tijuana',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Toronto',
                'America/Toronto',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Tortola',
                'America/Tortola',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Vancouver',
                'America/Vancouver',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Whitehorse',
                'America/Whitehorse',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Winnipeg',
                'America/Winnipeg',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Yakutat',
                'America/Yakutat',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Yellowknife',
                'America/Yellowknife',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Antarctica/Casey',
                'Antarctica/Casey',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Antarctica/Davis',
                'Antarctica/Davis',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Antarctica/DumontDUrville',
                'Antarctica/DumontDUrville',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Antarctica/Macquarie',
                'Antarctica/Macquarie',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Antarctica/Mawson',
                'Antarctica/Mawson',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Antarctica/McMurdo',
                'Antarctica/McMurdo',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Antarctica/Palmer',
                'Antarctica/Palmer',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Antarctica/Rothera',
                'Antarctica/Rothera',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Antarctica/South_Pole',
                'Antarctica/South_Pole',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Antarctica/Syowa',
                'Antarctica/Syowa',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Antarctica/Vostok',
                'Antarctica/Vostok',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Arctic/Longyearbyen',
                'Arctic/Longyearbyen',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Aden',
                'Asia/Aden',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Almaty',
                'Asia/Almaty',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Amman',
                'Asia/Amman',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Anadyr',
                'Asia/Anadyr',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Aqtau',
                'Asia/Aqtau',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Aqtobe',
                'Asia/Aqtobe',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Ashgabat',
                'Asia/Ashgabat',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Baghdad',
                'Asia/Baghdad',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Bahrain',
                'Asia/Bahrain',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Baku',
                'Asia/Baku',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Bangkok',
                'Asia/Bangkok',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Beirut',
                'Asia/Beirut',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Bishkek',
                'Asia/Bishkek',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Brunei',
                'Asia/Brunei',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Choibalsan',
                'Asia/Choibalsan',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Chongqing',
                'Asia/Chongqing',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Colombo',
                'Asia/Colombo',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Damascus',
                'Asia/Damascus',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Dhaka',
                'Asia/Dhaka',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Dili',
                'Asia/Dili',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Dubai',
                'Asia/Dubai',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Dushanbe',
                'Asia/Dushanbe',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Gaza',
                'Asia/Gaza',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Harbin',
                'Asia/Harbin',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Hebron',
                'Asia/Hebron',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Ho_Chi_Minh',
                'Asia/Ho_Chi_Minh',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Hong_Kong',
                'Asia/Hong_Kong',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Hovd',
                'Asia/Hovd',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Irkutsk',
                'Asia/Irkutsk',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Jakarta',
                'Asia/Jakarta',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Jayapura',
                'Asia/Jayapura',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Jerusalem',
                'Asia/Jerusalem',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Kabul',
                'Asia/Kabul',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Kamchatka',
                'Asia/Kamchatka',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Karachi',
                'Asia/Karachi',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Kashgar',
                'Asia/Kashgar',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Kathmandu',
                'Asia/Kathmandu',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Kolkata',
                'Asia/Kolkata',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Krasnoyarsk',
                'Asia/Krasnoyarsk',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Kuala_Lumpur',
                'Asia/Kuala_Lumpur',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Kuching',
                'Asia/Kuching',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Kuwait',
                'Asia/Kuwait',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Macau',
                'Asia/Macau',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Magadan',
                'Asia/Magadan',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Makassar',
                'Asia/Makassar',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Manila',
                'Asia/Manila',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Muscat',
                'Asia/Muscat',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Nicosia',
                'Asia/Nicosia',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Novokuznetsk',
                'Asia/Novokuznetsk',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Novosibirsk',
                'Asia/Novosibirsk',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Omsk',
                'Asia/Omsk',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Oral',
                'Asia/Oral',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Phnom_Penh',
                'Asia/Phnom_Penh',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Pontianak',
                'Asia/Pontianak',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Pyongyang',
                'Asia/Pyongyang',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Qatar',
                'Asia/Qatar',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Qyzylorda',
                'Asia/Qyzylorda',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Rangoon',
                'Asia/Rangoon',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Riyadh',
                'Asia/Riyadh',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Sakhalin',
                'Asia/Sakhalin',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Samarkand',
                'Asia/Samarkand',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Seoul',
                'Asia/Seoul',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Shanghai',
                'Asia/Shanghai',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Singapore',
                'Asia/Singapore',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Taipei',
                'Asia/Taipei',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Tashkent',
                'Asia/Tashkent',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Tbilisi',
                'Asia/Tbilisi',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Tehran',
                'Asia/Tehran',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Thimphu',
                'Asia/Thimphu',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Tokyo',
                'Asia/Tokyo',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Ulaanbaatar',
                'Asia/Ulaanbaatar',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Urumqi',
                'Asia/Urumqi',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Vientiane',
                'Asia/Vientiane',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Vladivostok',
                'Asia/Vladivostok',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Yakutsk',
                'Asia/Yakutsk',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Yekaterinburg',
                'Asia/Yekaterinburg',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Yerevan',
                'Asia/Yerevan',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Atlantic/Azores',
                'Atlantic/Azores',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Atlantic/Bermuda',
                'Atlantic/Bermuda',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Atlantic/Canary',
                'Atlantic/Canary',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Atlantic/Cape_Verde',
                'Atlantic/Cape_Verde',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Atlantic/Faroe',
                'Atlantic/Faroe',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Atlantic/Madeira',
                'Atlantic/Madeira',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Atlantic/Reykjavik',
                'Atlantic/Reykjavik',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Atlantic/South_Georgia',
                'Atlantic/South_Georgia',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Atlantic/St_Helena',
                'Atlantic/St_Helena',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Atlantic/Stanley',
                'Atlantic/Stanley',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Australia/Adelaide',
                'Australia/Adelaide',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Australia/Brisbane',
                'Australia/Brisbane',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Australia/Broken_Hill',
                'Australia/Broken_Hill',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Australia/Currie',
                'Australia/Currie',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Australia/Darwin',
                'Australia/Darwin',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Australia/Eucla',
                'Australia/Eucla',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Australia/Hobart',
                'Australia/Hobart',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Australia/Lindeman',
                'Australia/Lindeman',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Australia/Lord_Howe',
                'Australia/Lord_Howe',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Australia/Melbourne',
                'Australia/Melbourne',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Australia/Perth',
                'Australia/Perth',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Australia/Sydney',
                'Australia/Sydney',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Amsterdam',
                'Europe/Amsterdam',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Andorra',
                'Europe/Andorra',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Athens',
                'Europe/Athens',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Belgrade',
                'Europe/Belgrade',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Berlin',
                'Europe/Berlin',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Bratislava',
                'Europe/Bratislava',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Brussels',
                'Europe/Brussels',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Bucharest',
                'Europe/Bucharest',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Budapest',
                'Europe/Budapest',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Chisinau',
                'Europe/Chisinau',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Copenhagen',
                'Europe/Copenhagen',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Dublin',
                'Europe/Dublin',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Gibraltar',
                'Europe/Gibraltar',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Guernsey',
                'Europe/Guernsey',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Helsinki',
                'Europe/Helsinki',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Isle_of_Man',
                'Europe/Isle_of_Man',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Istanbul',
                'Europe/Istanbul',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Jersey',
                'Europe/Jersey',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Kaliningrad',
                'Europe/Kaliningrad',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Kiev',
                'Europe/Kiev',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Lisbon',
                'Europe/Lisbon',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Ljubljana',
                'Europe/Ljubljana',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/London',
                'Europe/London',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Luxembourg',
                'Europe/Luxembourg',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Madrid',
                'Europe/Madrid',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Malta',
                'Europe/Malta',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Mariehamn',
                'Europe/Mariehamn',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Minsk',
                'Europe/Minsk',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Monaco',
                'Europe/Monaco',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Moscow',
                'Europe/Moscow',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Oslo',
                'Europe/Oslo',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Paris',
                'Europe/Paris',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Podgorica',
                'Europe/Podgorica',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Prague',
                'Europe/Prague',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Riga',
                'Europe/Riga',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Rome',
                'Europe/Rome',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Samara',
                'Europe/Samara',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/San_Marino',
                'Europe/San_Marino',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Sarajevo',
                'Europe/Sarajevo',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Simferopol',
                'Europe/Simferopol',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Skopje',
                'Europe/Skopje',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Sofia',
                'Europe/Sofia',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Stockholm',
                'Europe/Stockholm',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Tallinn',
                'Europe/Tallinn',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Tirane',
                'Europe/Tirane',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Uzhgorod',
                'Europe/Uzhgorod',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Vaduz',
                'Europe/Vaduz',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Vatican',
                'Europe/Vatican',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Vienna',
                'Europe/Vienna',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Vilnius',
                'Europe/Vilnius',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Volgograd',
                'Europe/Volgograd',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Warsaw',
                'Europe/Warsaw',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Zagreb',
                'Europe/Zagreb',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Zaporozhye',
                'Europe/Zaporozhye',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Zurich',
                'Europe/Zurich',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Indian/Antananarivo',
                'Indian/Antananarivo',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Indian/Chagos',
                'Indian/Chagos',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Indian/Christmas',
                'Indian/Christmas',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Indian/Cocos',
                'Indian/Cocos',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Indian/Comoro',
                'Indian/Comoro',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Indian/Kerguelen',
                'Indian/Kerguelen',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Indian/Mahe',
                'Indian/Mahe',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Indian/Maldives',
                'Indian/Maldives',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Indian/Mauritius',
                'Indian/Mauritius',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Indian/Mayotte',
                'Indian/Mayotte',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Indian/Reunion',
                'Indian/Reunion',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Apia',
                'Pacific/Apia',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Auckland',
                'Pacific/Auckland',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Chatham',
                'Pacific/Chatham',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Chuuk',
                'Pacific/Chuuk',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Easter',
                'Pacific/Easter',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Efate',
                'Pacific/Efate',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Enderbury',
                'Pacific/Enderbury',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Fakaofo',
                'Pacific/Fakaofo',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Fiji',
                'Pacific/Fiji',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Funafuti',
                'Pacific/Funafuti',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Galapagos',
                'Pacific/Galapagos',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Gambier',
                'Pacific/Gambier',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Guadalcanal',
                'Pacific/Guadalcanal',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Guam',
                'Pacific/Guam',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Honolulu',
                'Pacific/Honolulu',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Johnston',
                'Pacific/Johnston',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Kiritimati',
                'Pacific/Kiritimati',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Kosrae',
                'Pacific/Kosrae',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Kwajalein',
                'Pacific/Kwajalein',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Majuro',
                'Pacific/Majuro',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Marquesas',
                'Pacific/Marquesas',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Midway',
                'Pacific/Midway',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Nauru',
                'Pacific/Nauru',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Niue',
                'Pacific/Niue',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Norfolk',
                'Pacific/Norfolk',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Noumea',
                'Pacific/Noumea',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Pago_Pago',
                'Pacific/Pago_Pago',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Palau',
                'Pacific/Palau',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Pitcairn',
                'Pacific/Pitcairn',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Pohnpei',
                'Pacific/Pohnpei',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Port_Moresby',
                'Pacific/Port_Moresby',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Rarotonga',
                'Pacific/Rarotonga',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Saipan',
                'Pacific/Saipan',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Tahiti',
                'Pacific/Tahiti',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Tarawa',
                'Pacific/Tarawa',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Tongatapu',
                'Pacific/Tongatapu',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Wake',
                'Pacific/Wake',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Wallis',
                'Pacific/Wallis',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        );

commit;
07070100000025000081B400000000000000000000000167AE111400000574000000000000000000000000000000000000004200000000susemanager-schema/common/data/rhnKickstartVirtualizationType.sql --
-- Copyright (c) 2008--2010 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
-- data for rhnKickstartVirtualizationType


insert into rhnKickstartVirtualizationType (id, name, label)
     values (sequence_nextval('rhn_kvt_id_seq'), 'Para-Virtualized Host', 'para_host');

insert into rhnKickstartVirtualizationType (id, name, label)
    values (sequence_nextval('rhn_kvt_id_seq'), 'KVM Virtualized Guest', 'qemu');

insert into rhnKickstartVirtualizationType (id, name, label)
    values (sequence_nextval('rhn_kvt_id_seq'), 'XEN Fully-Virtualized Guest', 'xenfv');

insert into rhnKickstartVirtualizationType (id, name, label)
    values (sequence_nextval('rhn_kvt_id_seq'), 'XEN Para-Virtualized Guest', 'xenpv');

insert into rhnKickstartVirtualizationType (id, name, label)
    values (sequence_nextval('rhn_kvt_id_seq'),  'None', 'none');
07070100000026000081B400000000000000000000000167AE111400000313000000000000000000000000000000000000003D00000000susemanager-schema/common/data/rhnOrgChannelSettingsType.sql  --
-- Copyright (c) 2008--2013 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--

insert into rhnOrgChannelSettingsType ( id, label )
	values ( sequence_nextval('rhn_ocstngs_type_id_seq'), 'not_globally_subscribable' );

commit;

 07070100000027000081B400000000000000000000000167AE111400002264000000000000000000000000000000000000003200000000susemanager-schema/common/data/rhnPackageArch.sql --
-- Copyright (c) 2008--2014 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--

insert into rhnPackageArch (id, label, name, arch_type_id) values
(sequence_nextval('rhn_package_arch_id_seq'), 'noarch', 'noarch', lookup_arch_type('rpm'));
insert into rhnPackageArch (id, label, name, arch_type_id) values
(sequence_nextval('rhn_package_arch_id_seq'), 'i386', 'i386', lookup_arch_type('rpm'));
insert into rhnPackageArch (id, label, name, arch_type_id) values
(sequence_nextval('rhn_package_arch_id_seq'), 'i486', 'i486', lookup_arch_type('rpm'));
insert into rhnPackageArch (id, label, name, arch_type_id) values
(sequence_nextval('rhn_package_arch_id_seq'), 'i586', 'i586', lookup_arch_type('rpm'));
insert into rhnPackageArch (id, label, name, arch_type_id) values
(sequence_nextval('rhn_package_arch_id_seq'), 'i686', 'i686', lookup_arch_type('rpm'));
insert into rhnPackageArch (id, label, name, arch_type_id) values
(sequence_nextval('rhn_package_arch_id_seq'), 'alpha', 'alpha', lookup_arch_type('rpm'));
insert into rhnPackageArch (id, label, name, arch_type_id) values
(sequence_nextval('rhn_package_arch_id_seq'), 'alphaev6', 'alphaev6', lookup_arch_type('rpm'));
insert into rhnPackageArch (id, label, name, arch_type_id) values
(sequence_nextval('rhn_package_arch_id_seq'), 'ia64', 'ia64', lookup_arch_type('rpm'));
insert into rhnPackageArch (id, label, name, arch_type_id) values
(sequence_nextval('rhn_package_arch_id_seq'), 'sparc', 'sparc', lookup_arch_type('rpm'));
insert into rhnPackageArch (id, label, name, arch_type_id) values
(sequence_nextval('rhn_package_arch_id_seq'), 'sparcv9', 'sparcv9', lookup_arch_type('rpm'));
insert into rhnPackageArch (id, label, name, arch_type_id) values
(sequence_nextval('rhn_package_arch_id_seq'), 'sparc64', 'sparc64', lookup_arch_type('rpm'));
insert into rhnPackageArch (id, label, name, arch_type_id) values
(sequence_nextval('rhn_package_arch_id_seq'), 'src', 'src', lookup_arch_type('rpm'));
insert into rhnPackageArch (id, label, name, arch_type_id) values
(sequence_nextval('rhn_package_arch_id_seq'), 's390', 's390', lookup_arch_type('rpm'));
insert into rhnPackageArch (id, label, name, arch_type_id) values
(sequence_nextval('rhn_package_arch_id_seq'), 'athlon', 'athlon', lookup_arch_type('rpm'));
insert into rhnPackageArch (id, label, name, arch_type_id) values
(sequence_nextval('rhn_package_arch_id_seq'), 's390x', 's390x', lookup_arch_type('rpm'));
insert into rhnPackageArch (id, label, name, arch_type_id) values
(sequence_nextval('rhn_package_arch_id_seq'), 'ppc', 'ppc', lookup_arch_type('rpm'));
insert into rhnPackageArch (id, label, name, arch_type_id) values
(sequence_nextval('rhn_package_arch_id_seq'), 'ppc64', 'ppc64', lookup_arch_type('rpm'));
insert into rhnPackageArch (id, label, name, arch_type_id) values
(sequence_nextval('rhn_package_arch_id_seq'), 'ppc64le', 'ppc64le', lookup_arch_type('rpm'));
insert into rhnPackageArch (id, label, name, arch_type_id) values
(sequence_nextval('rhn_package_arch_id_seq'), 'pSeries', 'pSeries', lookup_arch_type('rpm'));
insert into rhnPackageArch (id, label, name, arch_type_id) values
(sequence_nextval('rhn_package_arch_id_seq'), 'iSeries', 'iSeries', lookup_arch_type('rpm'));
insert into rhnPackageArch (id, label, name, arch_type_id) values
(sequence_nextval('rhn_package_arch_id_seq'), 'x86_64', 'x86_64', lookup_arch_type('rpm'));
insert into rhnPackageArch (id, label, name, arch_type_id) values
(sequence_nextval('rhn_package_arch_id_seq'), 'ppc64iseries', 'ppc64iseries', lookup_arch_type('rpm'));
insert into rhnPackageArch (id, label, name, arch_type_id) values
(sequence_nextval('rhn_package_arch_id_seq'), 'ppc64pseries', 'ppc64pseries', lookup_arch_type('rpm'));
insert into rhnPackageArch (id, label, name, arch_type_id) values
(sequence_nextval('rhn_package_arch_id_seq'), 'tar', 'TAR archive', lookup_arch_type('tar'));
insert into rhnPackageArch (id, label, name, arch_type_id) values
(sequence_nextval('rhn_package_arch_id_seq'), 'ia32e', 'EM64T', lookup_arch_type('rpm'));
insert into rhnPackageArch (id, label, name, arch_type_id) values
(sequence_nextval('rhn_package_arch_id_seq'), 'amd64', 'AMD64', lookup_arch_type('rpm'));
insert into rhnPackageArch (id, label, name, arch_type_id) values
(sequence_nextval('rhn_package_arch_id_seq'), 'aarch64', 'AArch64', lookup_arch_type('rpm'));
insert into rhnPackageArch (id, label, name, arch_type_id) values
(sequence_nextval('rhn_package_arch_id_seq'), 'armv7hnl', 'ARMv7hnl', lookup_arch_type('rpm'));
insert into rhnPackageArch (id, label, name, arch_type_id) values
(sequence_nextval('rhn_package_arch_id_seq'), 'armv7hl', 'ARMv7hl', lookup_arch_type('rpm'));
insert into rhnPackageArch (id, label, name, arch_type_id) values
(sequence_nextval('rhn_package_arch_id_seq'), 'armv7l', 'ARMv7l', lookup_arch_type('rpm'));
insert into rhnPackageArch (id, label, name, arch_type_id) values
(sequence_nextval('rhn_package_arch_id_seq'), 'armv6hl', 'ARMv6hl', lookup_arch_type('rpm'));
insert into rhnPackageArch (id, label, name, arch_type_id) values
(sequence_nextval('rhn_package_arch_id_seq'), 'armv6l', 'ARMv6l', lookup_arch_type('rpm'));
insert into rhnPackageArch (id, label, name, arch_type_id) values
(sequence_nextval('rhn_package_arch_id_seq'), 'armv5tel', 'ARMv5tel', lookup_arch_type('rpm'));

insert into rhnPackageArch (id, label, name, arch_type_id) values 
( sequence_nextval('rhn_package_arch_id_seq'), 'nosrc', 'nosrc', lookup_arch_type('rpm') );

insert into rhnPackageArch (id, label, name, arch_type_id) values
(sequence_nextval('rhn_package_arch_id_seq'), 'all-deb', 'all-deb', lookup_arch_type('deb'));
insert into rhnPackageArch (id, label, name, arch_type_id) values
(sequence_nextval('rhn_package_arch_id_seq'), 'i386-deb', 'i386-deb', lookup_arch_type('deb'));
insert into rhnPackageArch (id, label, name, arch_type_id) values
(sequence_nextval('rhn_package_arch_id_seq'), 'alpha-deb', 'alpha-deb', lookup_arch_type('deb'));
insert into rhnPackageArch (id, label, name, arch_type_id) values
(sequence_nextval('rhn_package_arch_id_seq'), 'ia64-deb', 'ia64-deb', lookup_arch_type('deb'));
insert into rhnPackageArch (id, label, name, arch_type_id) values
(sequence_nextval('rhn_package_arch_id_seq'), 'sparc-deb', 'sparc-deb', lookup_arch_type('deb'));
insert into rhnPackageArch (id, label, name, arch_type_id) values
(sequence_nextval('rhn_package_arch_id_seq'), 'src-deb', 'src-deb', lookup_arch_type('deb'));
insert into rhnPackageArch (id, label, name, arch_type_id) values
(sequence_nextval('rhn_package_arch_id_seq'), 's390-deb', 's390-deb', lookup_arch_type('deb'));
insert into rhnPackageArch (id, label, name, arch_type_id) values
(sequence_nextval('rhn_package_arch_id_seq'), 'powerpc-deb', 'powerpc-deb', lookup_arch_type('deb'));
insert into rhnPackageArch (id, label, name, arch_type_id) values
(sequence_nextval('rhn_package_arch_id_seq'), 'arm-deb', 'arm-deb', lookup_arch_type('deb'));
insert into rhnPackageArch (id, label, name, arch_type_id) values
(sequence_nextval('rhn_package_arch_id_seq'), 'armhf-deb', 'armhf-deb', lookup_arch_type('deb'));
insert into rhnPackageArch (id, label, name, arch_type_id) values
(sequence_nextval('rhn_package_arch_id_seq'), 'mips-deb', 'mips-deb', lookup_arch_type('deb'));
insert into rhnPackageArch (id, label, name, arch_type_id) values
(sequence_nextval('rhn_package_arch_id_seq'), 'amd64-deb', 'AMD64-deb', lookup_arch_type('deb'));
insert into rhnPackageArch (id, label, name, arch_type_id) values
(sequence_nextval('rhn_package_arch_id_seq'), 'arm64-deb', 'ARM64-deb', lookup_arch_type('deb'));
insert into rhnPackageArch (id, label, name, arch_type_id) values
(sequence_nextval('rhn_package_arch_id_seq'), 'armel-deb', 'armel-deb', lookup_arch_type('deb'));
insert into rhnPackageArch (id, label, name, arch_type_id) values
(sequence_nextval('rhn_package_arch_id_seq'), 'riscv64-deb', 'riscv64-deb', lookup_arch_type('deb'));
insert into rhnPackageArch (id, label, name, arch_type_id) values
(sequence_nextval('rhn_package_arch_id_seq'), 'ppc64el-deb', 'ppc64el-deb', lookup_arch_type('deb'));
insert into rhnPackageArch (id, label, name, arch_type_id) values
(sequence_nextval('rhn_package_arch_id_seq'), 's390x-deb', 's390x-deb', lookup_arch_type('deb'));

commit;

07070100000028000081B400000000000000000000000167AE11140000032F000000000000000000000000000000000000003300000000susemanager-schema/common/data/rhnPackageGroup.sql    --
-- Copyright (c) 2008--2013 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--
-- data for rhnPackageGroup

insert into rhnPackageGroup values (sequence_nextval('rhn_package_group_id_seq'),'NoGroup',
        current_timestamp,current_timestamp);

commit;

 07070100000029000081B400000000000000000000000167AE11140000644B000000000000000000000000000000000000003100000000susemanager-schema/common/data/rhnPackageKey.sql  --
-- Copyright (c) 2008--2017 Red Hat, Inc.
-- Copyright (c) 2010--2021 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--
--

-- Red Hat
insert into rhnPackageKey (id, key_id, key_type_id, provider_id) (select sequence_nextval('rhn_pkey_id_seq'), '5326810137017186', lookup_package_key_type('gpg'), lookup_package_provider('Red Hat Inc.') from dual where not exists (select 1 from rhnPackageKey where key_id = '5326810137017186'));

insert into rhnPackageKey (id, key_id, key_type_id, provider_id) (select sequence_nextval('rhn_pkey_id_seq'), '219180cddb42a60e', lookup_package_key_type('gpg'), lookup_package_provider('Red Hat Inc.') from dual where not exists (select 1 from rhnPackageKey where key_id = '219180cddb42a60e'));

insert into rhnPackageKey (id, key_id, key_type_id, provider_id) (select sequence_nextval('rhn_pkey_id_seq'), '5054e4a45a6340b3', lookup_package_key_type('gpg'), lookup_package_provider('Red Hat Inc.') from dual where not exists (select 1 from rhnPackageKey where key_id = '5054e4a45a6340b3'));

-- RHEL 6
insert into rhnPackageKey (id, key_id, key_type_id, provider_id) (select sequence_nextval('rhn_pkey_id_seq'), '199e2f91fd431d51', lookup_package_key_type('gpg'), lookup_package_provider('Red Hat Inc.') from dual where not exists (select 1 from rhnPackageKey where key_id = '199e2f91fd431d51'));

-- Fedora
insert into rhnPackageKey (id, key_id, key_type_id, provider_id) (select sequence_nextval('rhn_pkey_id_seq'), 'b44269d04f2a6fd2', lookup_package_key_type('gpg'), lookup_package_provider('Fedora') from dual where not exists (select 1 from rhnPackageKey where key_id = 'b44269d04f2a6fd2'));

insert into rhnPackageKey (id, key_id, key_type_id, provider_id) (select sequence_nextval('rhn_pkey_id_seq'), '1dc5c758d22e77f2', lookup_package_key_type('gpg'), lookup_package_provider('Fedora') from dual where not exists (select 1 from rhnPackageKey where key_id = '1dc5c758d22e77f2'));

-- Fedora 12
insert into rhnPackageKey (id, key_id, key_type_id, provider_id) (select sequence_nextval('rhn_pkey_id_seq'), '9d1cc34857bbccba', lookup_package_key_type('gpg'), lookup_package_provider('Fedora') from dual where not exists (select 1 from rhnPackageKey where key_id = '9d1cc34857bbccba'));
-- Fedora 13
insert into rhnPackageKey (id, key_id, key_type_id, provider_id) (select sequence_nextval('rhn_pkey_id_seq'), '7edc6ad6e8e40fde', lookup_package_key_type('gpg'), lookup_package_provider('Fedora') from dual where not exists (select 1 from rhnPackageKey where key_id = '7edc6ad6e8e40fde'));
-- Fedora 14
insert into rhnPackageKey (id, key_id, key_type_id, provider_id) (select sequence_nextval('rhn_pkey_id_seq'), '421caddb97a1071f', lookup_package_key_type('gpg'), lookup_package_provider('Fedora') from dual where not exists (select 1 from rhnPackageKey where key_id = '421caddb97a1071f'));
-- Fedora 15
insert into rhnPackageKey (id, key_id, key_type_id, provider_id) (select sequence_nextval('rhn_pkey_id_seq'), 'b4ebf579069c8460', lookup_package_key_type('gpg'), lookup_package_provider('Fedora') from dual where not exists (select 1 from rhnPackageKey where key_id = 'b4ebf579069c8460'));
-- Fedora 16
insert into rhnPackageKey (id, key_id, key_type_id, provider_id) (select sequence_nextval('rhn_pkey_id_seq'), '067f00b6a82ba4b7', lookup_package_key_type('gpg'), lookup_package_provider('Fedora') from dual where not exists (select 1 from rhnPackageKey where key_id = '067f00b6a82ba4b7'));
-- Fedora 17
insert into rhnPackageKey (id, key_id, key_type_id, provider_id) (select sequence_nextval('rhn_pkey_id_seq'), '50e94c991aca3465', lookup_package_key_type('gpg'), lookup_package_provider('Fedora') from dual where not exists (select 1 from rhnPackageKey where key_id = '50e94c991aca3465'));
-- Fedora 18
insert into rhnPackageKey (id, key_id, key_type_id, provider_id) (select sequence_nextval('rhn_pkey_id_seq'), '0983129322b3b81a', lookup_package_key_type('gpg'), lookup_package_provider('Fedora') from dual where not exists (select 1 from rhnPackageKey where key_id = '0983129322b3b81a'));
-- Fedora 19
insert into rhnPackageKey (id, key_id, key_type_id, provider_id) (select sequence_nextval('rhn_pkey_id_seq'), '07477e65fb4b18e6', lookup_package_key_type('gpg'), lookup_package_provider('Fedora') from dual where not exists (select 1 from rhnPackageKey where key_id = '07477e65fb4b18e6'));
-- Fedora 20
insert into rhnPackageKey (id, key_id, key_type_id, provider_id) (select sequence_nextval('rhn_pkey_id_seq'), '2eb161fa246110c1', lookup_package_key_type('gpg'), lookup_package_provider('Fedora') from dual where not exists (select 1 from rhnPackageKey where key_id = '2eb161fa246110c1'));
-- Fedora 20 (secondary)
insert into rhnPackageKey (id, key_id, key_type_id, provider_id) (select sequence_nextval('rhn_pkey_id_seq'), 'dbeae2e4efe550f5', lookup_package_key_type('gpg'), lookup_package_provider('Fedora') from dual where not exists (select 1 from rhnPackageKey where key_id = 'dbeae2e4efe550f5'));
-- Fedora 21
insert into rhnPackageKey (id, key_id, key_type_id, provider_id) (select sequence_nextval('rhn_pkey_id_seq'), '89ad4e8795a43f54', lookup_package_key_type('gpg'), lookup_package_provider('Fedora') from dual where not exists (select 1 from rhnPackageKey where key_id = '89ad4e8795a43f54'));
-- Fedora 21 (secondary)
insert into rhnPackageKey (id, key_id, key_type_id, provider_id) (select sequence_nextval('rhn_pkey_id_seq'), '636dea19a0a7badb', lookup_package_key_type('gpg'), lookup_package_provider('Fedora') from dual where not exists (select 1 from rhnPackageKey where key_id = '636dea19a0a7badb'));
-- Fedora 22
insert into rhnPackageKey (id, key_id, key_type_id, provider_id) (select sequence_nextval('rhn_pkey_id_seq'), '11adc0948e1431d5', lookup_package_key_type('gpg'), lookup_package_provider('Fedora') from dual where not exists (select 1 from rhnPackageKey where key_id = '11adc0948e1431d5'));
-- Fedora 22 (secondary)
insert into rhnPackageKey (id, key_id, key_type_id, provider_id) (select sequence_nextval('rhn_pkey_id_seq'), 'd8d1fa8ca29cb19c', lookup_package_key_type('gpg'), lookup_package_provider('Fedora') from dual where not exists (select 1 from rhnPackageKey where key_id = 'd8d1fa8ca29cb19c'));
-- Fedora 23
insert into rhnPackageKey (id, key_id, key_type_id, provider_id) (select sequence_nextval('rhn_pkey_id_seq'), '32474cf834ec9cba', lookup_package_key_type('gpg'), lookup_package_provider('Fedora') from dual where not exists (select 1 from rhnPackageKey where key_id = '32474cf834ec9cba'));
-- Fedora 23 (secondary)
insert into rhnPackageKey (id, key_id, key_type_id, provider_id) (select sequence_nextval('rhn_pkey_id_seq'), 'b4bb871c873529b8', lookup_package_key_type('gpg'), lookup_package_provider('Fedora') from dual where not exists (select 1 from rhnPackageKey where key_id = 'b4bb871c873529b8'));
-- Fedora 24
insert into rhnPackageKey (id, key_id, key_type_id, provider_id) (select sequence_nextval('rhn_pkey_id_seq'), '73bde98381b46521', lookup_package_key_type('gpg'), lookup_package_provider('Fedora') from dual where not exists (select 1 from rhnPackageKey where key_id = '73bde98381b46521'));
-- Fedora 24 (secondary)
insert into rhnPackageKey (id, key_id, key_type_id, provider_id) (select sequence_nextval('rhn_pkey_id_seq'), 'b8635eeb030d5aed', lookup_package_key_type('gpg'), lookup_package_provider('Fedora') from dual where not exists (select 1 from rhnPackageKey where key_id = 'b8635eeb030d5aed'));
-- Fedora 25
insert into rhnPackageKey (id, key_id, key_type_id, provider_id) values
(sequence_nextval('rhn_pkey_id_seq'), 'FDB19C98', lookup_package_key_type('gpg'), lookup_package_provider('Fedora'));
-- Fedora 26
insert into rhnPackageKey (id, key_id, key_type_id, provider_id) values
(sequence_nextval('rhn_pkey_id_seq'), '64DAB85D', lookup_package_key_type('gpg'), lookup_package_provider('Fedora'));
-- Fedora 27
insert into rhnPackageKey (id, key_id, key_type_id, provider_id) values
(sequence_nextval('rhn_pkey_id_seq'), 'F5282EE4', lookup_package_key_type('gpg'), lookup_package_provider('Fedora'));
-- Fedora 28
insert into rhnPackageKey (id, key_id, key_type_id, provider_id) values
(sequence_nextval('rhn_pkey_id_seq'), '9DB62FB1', lookup_package_key_type('gpg'), lookup_package_provider('Fedora'));
-- Fedora 29
insert into rhnPackageKey (id, key_id, key_type_id, provider_id) values
(sequence_nextval('rhn_pkey_id_seq'), '429476B4', lookup_package_key_type('gpg'), lookup_package_provider('Fedora'));

-- CentOS
insert into rhnPackageKey (id, key_id, key_type_id, provider_id) (select sequence_nextval('rhn_pkey_id_seq'), 'a8a447dce8562897', lookup_package_key_type('gpg'), lookup_package_provider('CentOS') from dual where not exists (select 1 from rhnPackageKey where key_id = 'a8a447dce8562897'));

insert into rhnPackageKey (id, key_id, key_type_id, provider_id) (select sequence_nextval('rhn_pkey_id_seq'), '2802e89216ff0e46', lookup_package_key_type('gpg'), lookup_package_provider('CentOS') from dual where not exists (select 1 from rhnPackageKey where key_id = '2802e89216ff0e46'));

insert into rhnPackageKey (id, key_id, key_type_id, provider_id) (select sequence_nextval('rhn_pkey_id_seq'), 'a53d0bab443e1821', lookup_package_key_type('gpg'), lookup_package_provider('CentOS') from dual where not exists (select 1 from rhnPackageKey where key_id = 'a53d0bab443e1821'));

insert into rhnPackageKey (id, key_id, key_type_id, provider_id) (select sequence_nextval('rhn_pkey_id_seq'), '7049e44d025e513b', lookup_package_key_type('gpg'), lookup_package_provider('CentOS') from dual where not exists (select 1 from rhnPackageKey where key_id = '7049e44d025e513b'));
-- CentOS 6
insert into rhnPackageKey (id, key_id, key_type_id, provider_id) (select sequence_nextval('rhn_pkey_id_seq'), '0946fca2c105b9de', lookup_package_key_type('gpg'), lookup_package_provider('CentOS') from dual where not exists (select 1 from rhnPackageKey where key_id = '0946fca2c105b9de'));
-- CentOS 7
insert into rhnPackageKey (id, key_id, key_type_id, provider_id) (select sequence_nextval('rhn_pkey_id_seq'), '24c6a8a7f4a80eb5', lookup_package_key_type('gpg'), lookup_package_provider('CentOS') from dual where not exists (select 1 from rhnPackageKey where key_id = '24c6a8a7f4a80eb5'));
-- CentOS-Official
insert into rhnPackageKey (id, key_id, key_type_id, provider_id) (select sequence_nextval('rhn_pkey_id_seq'), '05b555b38483c65d', lookup_package_key_type('gpg'), lookup_package_provider('CentOS') from dual where not exists (select 1 from rhnPackageKey where key_id = '05b555b38483c65d'));

-- Scientific Linux
insert into rhnPackageKey (id, key_id, key_type_id, provider_id) (select sequence_nextval('rhn_pkey_id_seq'), '25dbef78a7048f8d', lookup_package_key_type('gpg'), lookup_package_provider('Scientific Linux') from dual where not exists (select 1 from rhnPackageKey where key_id = '25dbef78a7048f8d'));
-- Scientific Linux 6
insert into rhnPackageKey (id, key_id, key_type_id, provider_id) (select sequence_nextval('rhn_pkey_id_seq'), '915d75e09b1fd350', lookup_package_key_type('gpg'), lookup_package_provider('Scientific Linux') from dual where not exists (select 1 from rhnPackageKey where key_id = '915d75e09b1fd350'));
insert into rhnPackageKey (id, key_id, key_type_id, provider_id) (select sequence_nextval('rhn_pkey_id_seq'), 'b0b4183f192a7d7d', lookup_package_key_type('gpg'), lookup_package_provider('Scientific Linux') from dual where not exists (select 1 from rhnPackageKey where key_id = 'b0b4183f192a7d7d'));


-- Oracle EL
insert into rhnPackageKey (id, key_id, key_type_id, provider_id) (select sequence_nextval('rhn_pkey_id_seq'), '66ced3de1e5e0159', lookup_package_key_type('gpg'), lookup_package_provider('Oracle Inc.') from dual where not exists (select 1 from rhnPackageKey where key_id = '66ced3de1e5e0159'));

insert into rhnPackageKey (id, key_id, key_type_id, provider_id) (select sequence_nextval('rhn_pkey_id_seq'), '2e2bcdbcb38a8516', lookup_package_key_type('gpg'), lookup_package_provider('Oracle Inc.') from dual where not exists (select 1 from rhnPackageKey where key_id = '2e2bcdbcb38a8516'));

insert into rhnPackageKey (id, key_id, key_type_id, provider_id) (select sequence_nextval('rhn_pkey_id_seq'), '72f97b74ec551f03', lookup_package_key_type('gpg'), lookup_package_provider('Oracle Inc.') from dual where not exists (select 1 from rhnPackageKey where key_id = '72f97b74ec551f03'));

insert into rhnPackageKey (id, key_id, key_type_id, provider_id) (select sequence_nextval('rhn_pkey_id_seq'), '82562ea9ad986da3', lookup_package_key_type('gpg'), lookup_package_provider('Oracle Inc.') from dual where not exists (select 1 from rhnPackageKey where key_id = '82562ea9ad986da3'));

insert into rhnPackageKey (id, key_id, key_type_id, provider_id) (select sequence_nextval('rhn_pkey_id_seq'), 'bc4d06a08d8b756f', lookup_package_key_type('gpg'), lookup_package_provider('Oracle Inc.') from dual where not exists (select 1 from rhnPackageKey where key_id = 'bc4d06a08d8b756f'));

insert into rhnPackageKey (id, key_id, key_type_id, provider_id) (select sequence_nextval('rhn_pkey_id_seq'), 'a7dd07088b4efbe6', lookup_package_key_type('gpg'), lookup_package_provider('Oracle Inc.') from dual where not exists (select 1 from rhnPackageKey where key_id = 'a7dd07088b4efbe6'));

-- Novell
insert into rhnPackageKey (id, key_id, key_type_id, provider_id) (select sequence_nextval('rhn_pkey_id_seq'), '2afe16421d061a62', lookup_package_key_type('gpg'), lookup_package_provider('Novell Inc.') from dual where not exists (select 1 from rhnPackageKey where key_id = '2afe16421d061a62'));

insert into rhnPackageKey (id, key_id, key_type_id, provider_id) (select sequence_nextval('rhn_pkey_id_seq'), '14c28bc97e2e3b05', lookup_package_key_type('gpg'), lookup_package_provider('Novell Inc.') from dual where not exists (select 1 from rhnPackageKey where key_id = '14c28bc97e2e3b05'));

insert into rhnPackageKey (id, key_id, key_type_id, provider_id) (select sequence_nextval('rhn_pkey_id_seq'), '478a32e8a1912208', lookup_package_key_type('gpg'), lookup_package_provider('Novell Inc.') from dual where not exists (select 1 from rhnPackageKey where key_id = '478a32e8a1912208'));

insert into rhnPackageKey (id, key_id, key_type_id, provider_id) (select sequence_nextval('rhn_pkey_id_seq'), '73d25d630dfb3188', lookup_package_key_type('gpg'), lookup_package_provider('Novell Inc.') from dual where not exists (select 1 from rhnPackageKey where key_id = '73d25d630dfb3188'));

insert into rhnPackageKey (id, key_id, key_type_id, provider_id) (select sequence_nextval('rhn_pkey_id_seq'), '044adaee04881839', lookup_package_key_type('gpg'), lookup_package_provider('Novell Inc.') from dual where not exists (select 1 from rhnPackageKey where key_id = '044adaee04881839'));

insert into rhnPackageKey (id, key_id, key_type_id, provider_id) (select sequence_nextval('rhn_pkey_id_seq'), '57da9a6804a29db0', lookup_package_key_type('gpg'), lookup_package_provider('Novell Inc.') from dual where not exists (select 1 from rhnPackageKey where key_id = '57da9a6804a29db0'));

-- SUSE
insert into rhnPackageKey (id, key_id, key_type_id, provider_id) (select sequence_nextval('rhn_pkey_id_seq'), 'a84edae89c800aca', lookup_package_key_type('gpg'), lookup_package_provider('SUSE LLC') from dual where not exists (select 1 from rhnPackageKey where key_id = 'a84edae89c800aca'));

insert into rhnPackageKey (id, key_id, key_type_id, provider_id) (select sequence_nextval('rhn_pkey_id_seq'), 'e3a5c360307e3d54', lookup_package_key_type('gpg'), lookup_package_provider('SUSE LLC') from dual where not exists (select 1 from rhnPackageKey where key_id = 'e3a5c360307e3d54'));

insert into rhnPackageKey (id, key_id, key_type_id, provider_id) (select sequence_nextval('rhn_pkey_id_seq'), '6c74ce73b37b98a9', lookup_package_key_type('gpg'), lookup_package_provider('SUSE LLC') from dual where not exists (select 1 from rhnPackageKey where key_id = '6c74ce73b37b98a9'));

insert into rhnPackageKey (id, key_id, key_type_id, provider_id) (select sequence_nextval('rhn_pkey_id_seq'), '70af9e8139db7c82', lookup_package_key_type('gpg'), lookup_package_provider('SUSE LLC') from dual where not exists (select 1 from rhnPackageKey where key_id = '70af9e8139db7c82'));

insert into rhnPackageKey (id, key_id, key_type_id, provider_id) (select sequence_nextval('rhn_pkey_id_seq'), '5eaf444450a3dd1c', lookup_package_key_type('gpg'), lookup_package_provider('SUSE LLC') from dual where not exists (select 1 from rhnPackageKey where key_id = '5eaf444450a3dd1c'));

insert into rhnPackageKey (id, key_id, key_type_id, provider_id) (select sequence_nextval('rhn_pkey_id_seq'), '8efe1bc4d4ade9c3', lookup_package_key_type('gpg'), lookup_package_provider('SUSE LLC') from dual where not exists (select 1 from rhnPackageKey where key_id = '8efe1bc4d4ade9c3'));

insert into rhnPackageKey (id, key_id, key_type_id, provider_id) (select sequence_nextval('rhn_pkey_id_seq'), '97a636db0bad8ecc', lookup_package_key_type('gpg'), lookup_package_provider('SUSE LLC') from dual where not exists (select 1 from rhnPackageKey where key_id = '97a636db0bad8ecc'));

insert into rhnPackageKey (id, key_id, key_type_id, provider_id) (select sequence_nextval('rhn_pkey_id_seq'), 'f74f09bc3fa1d6ce', lookup_package_key_type('gpg'), lookup_package_provider('SUSE LLC') from dual where not exists (select 1 from rhnPackageKey where key_id = 'f74f09bc3fa1d6ce'));

insert into rhnPackageKey (id, key_id, key_type_id, provider_id) (select sequence_nextval('rhn_pkey_id_seq'), 'a1bfc02bd588dc46', lookup_package_key_type('gpg'), lookup_package_provider('SUSE LLC') from dual where not exists (select 1 from rhnPackageKey where key_id = 'a1bfc02bd588dc46'));

insert into rhnPackageKey (id, key_id, key_type_id, provider_id) (select sequence_nextval('rhn_pkey_id_seq'), '46dfa05c6f5da62b', lookup_package_key_type('gpg'), lookup_package_provider('SUSE LLC') from dual where not exists (select 1 from rhnPackageKey where key_id = '46dfa05c6f5da62b'));

insert into rhnPackageKey (id, key_id, key_type_id, provider_id) (select sequence_nextval('rhn_pkey_id_seq'), '09461c70af5425f7', lookup_package_key_type('gpg'), lookup_package_provider('SUSE LLC') from dual where not exists (select 1 from rhnPackageKey where key_id = '09461c70af5425f7'));

-- openSUSE

insert into rhnPackageKey (id, key_id, key_type_id, provider_id) (select sequence_nextval('rhn_pkey_id_seq'), 'b88b2fd43dbdc284', lookup_package_key_type('gpg'), lookup_package_provider('openSUSE') from dual where not exists (select 1 from rhnPackageKey where key_id = 'b88b2fd43dbdc284'));

insert into rhnPackageKey (id, key_id, key_type_id, provider_id) (select sequence_nextval('rhn_pkey_id_seq'), '9c214d4065176565', lookup_package_key_type('gpg'), lookup_package_provider('openSUSE') from dual where not exists (select 1 from rhnPackageKey where key_id = '9c214d4065176565'));

insert into rhnPackageKey (id, key_id, key_type_id, provider_id) (select sequence_nextval('rhn_pkey_id_seq'), '3c90731ed78c6b69', lookup_package_key_type('gpg'), lookup_package_provider('openSUSE') from dual where not exists (select 1 from rhnPackageKey where key_id = '3c90731ed78c6b69'));

insert into rhnPackageKey (id, key_id, key_type_id, provider_id) (select sequence_nextval('rhn_pkey_id_seq'), '35a2f86e29b700a4', lookup_package_key_type('gpg'), lookup_package_provider('openSUSE') from dual where not exists (select 1 from rhnPackageKey where key_id = '35a2f86e29b700a4'));

insert into rhnPackageKey (id, key_id, key_type_id, provider_id) (select sequence_nextval('rhn_pkey_id_seq'), '8a49eb0325db7ae0', lookup_package_key_type('gpg'), lookup_package_provider('openSUSE') from dual where not exists (select 1 from rhnPackageKey where key_id = '8a49eb0325db7ae0'));

-- Liberty / SLES-ES

insert into rhnPackageKey (id, key_id, key_type_id, provider_id) (select sequence_nextval('rhn_pkey_id_seq'), '8055f0400182b964', lookup_package_key_type('gpg'), lookup_package_provider('SUSE LLC') from dual where not exists (select 1 from rhnPackageKey where key_id = '8055f0400182b964'));

insert into rhnPackageKey (id, key_id, key_type_id, provider_id) (select sequence_nextval('rhn_pkey_id_seq'), '177086fab0f9c64f', lookup_package_key_type('gpg'), lookup_package_provider('SUSE LLC') from dual where not exists (select 1 from rhnPackageKey where key_id = '177086fab0f9c64f'));


-- Spacewalk
insert into rhnPackageKey (id, key_id, key_type_id, provider_id) (select sequence_nextval('rhn_pkey_id_seq'), '95423d4e430a1c35', lookup_package_key_type('gpg'), lookup_package_provider('Spacewalk') from dual where not exists (select 1 from rhnPackageKey where key_id = '95423d4e430a1c35'));
insert into rhnPackageKey (id, key_id, key_type_id, provider_id) (select sequence_nextval('rhn_pkey_id_seq'), 'ed635379b3892132', lookup_package_key_type('gpg'), lookup_package_provider('Spacewalk') from dual where not exists (select 1 from rhnPackageKey where key_id = 'ed635379b3892132'));
insert into rhnPackageKey (id, key_id, key_type_id, provider_id) (select sequence_nextval('rhn_pkey_id_seq'), '0e646f68863a853d', lookup_package_key_type('gpg'), lookup_package_provider('Spacewalk') from dual where not exists (select 1 from rhnPackageKey where key_id = '0e646f68863a853d'));
insert into rhnPackageKey (id, key_id, key_type_id, provider_id) (select sequence_nextval('rhn_pkey_id_seq'), '41605346066e5810', lookup_package_key_type('gpg'), lookup_package_provider('Spacewalk') from dual where not exists (select 1 from rhnPackageKey where key_id = '41605346066e5810'));
insert into rhnPackageKey (id, key_id, key_type_id, provider_id) (select sequence_nextval('rhn_pkey_id_seq'), 'dcc981cdb8002de1', lookup_package_key_type('gpg'), lookup_package_provider('Spacewalk') from dual where not exists (select 1 from rhnPackageKey where key_id = 'dcc981cdb8002de1'));


-- EPEL 5
insert into rhnPackageKey (id, key_id, key_type_id, provider_id) (select sequence_nextval('rhn_pkey_id_seq'), '119cc036217521f6', lookup_package_key_type('gpg'), lookup_package_provider('EPEL') from dual where not exists (select 1 from rhnPackageKey where key_id = '119cc036217521f6'));
-- EPEL 6
insert into rhnPackageKey (id, key_id, key_type_id, provider_id) (select sequence_nextval('rhn_pkey_id_seq'), '3b49df2a0608b895', lookup_package_key_type('gpg'), lookup_package_provider('EPEL') from dual where not exists (select 1 from rhnPackageKey where key_id = '3b49df2a0608b895'));
-- EPEL 7
insert into rhnPackageKey (id, key_id, key_type_id, provider_id) (select sequence_nextval('rhn_pkey_id_seq'), '6a2faea2352c64e5', lookup_package_key_type('gpg'), lookup_package_provider('EPEL') from dual where not exists (select 1 from rhnPackageKey where key_id = '6a2faea2352c64e5'));
--EPEL 8
insert into rhnPackageKey (id, key_id, key_type_id, provider_id) (select sequence_nextval('rhn_pkey_id_seq'), '21ea45ab2f86d6a1', lookup_package_key_type('gpg'), lookup_package_provider('EPEL') from dual where not exists (select 1 from rhnPackageKey where key_id = '21ea45ab2f86d6a1'));

-- Aliyun Linux 2.1903
insert into rhnPackageKey (id, key_id, key_type_id, provider_id) (select sequence_nextval('rhn_pkey_id_seq'), 'eb801c41873141a8', lookup_package_key_type('gpg'), lookup_package_provider('Alibaba') from dual where not exists (select 1 from rhnPackageKey where key_id = 'eb801c41873141a8'));

-- Uyuni
insert into rhnPackageKey (id, key_id, key_type_id, provider_id) (select sequence_nextval('rhn_pkey_id_seq'), '972e5d6c0d20833e', lookup_package_key_type('gpg'), lookup_package_provider('Uyuni') from dual where not exists (select 1 from rhnPackageKey where key_id = '972e5d6c0d20833e'));

-- Alma Linux 8
insert into rhnPackageKey (id, key_id, key_type_id, provider_id) (select sequence_nextval('rhn_pkey_id_seq'), '488fcf7c3abb34f8', lookup_package_key_type('gpg'), lookup_package_provider('AlmaLinux') from dual where not exists (select 1 from rhnPackageKey where key_id = '488fcf7c3abb34f8'));

insert into rhnPackageKey (id, key_id, key_type_id, provider_id) (select sequence_nextval('rhn_pkey_id_seq'), '2ae81e8aced7258b', lookup_package_key_type('gpg'), lookup_package_provider('AlmaLinux') from dual where not exists (select 1 from rhnPackageKey where key_id = '2ae81e8aced7258b'));

-- Alma Linux 9
insert into rhnPackageKey (id, key_id, key_type_id, provider_id) (select sequence_nextval('rhn_pkey_id_seq'), 'd36cb86cb86b3716', lookup_package_key_type('gpg'), lookup_package_provider('AlmaLinux') from dual where not exists (select 1 from rhnPackageKey where key_id = 'd36cb86cb86b3716'));


-- Amazon Linux 2
insert into rhnPackageKey (id, key_id, key_type_id, provider_id) (select sequence_nextval('rhn_pkey_id_seq'), '11cf1f95c87f5b1a', lookup_package_key_type('gpg'), lookup_package_provider('Amazon') from dual where not exists (select 1 from rhnPackageKey where key_id = '11cf1f95c87f5b1a'));

-- Rocky Linux 8
insert into rhnPackageKey (id, key_id, key_type_id, provider_id) (select sequence_nextval('rhn_pkey_id_seq'), '15af5dac6d745a60', lookup_package_key_type('gpg'), lookup_package_provider('Rocky Linux') from dual where not exists (select 1 from rhnPackageKey where key_id = '15af5dac6d745a60'));

commit;

 0707010000002A000081B400000000000000000000000167AE111400000435000000000000000000000000000000000000003500000000susemanager-schema/common/data/rhnPackageKeyType.sql  --
-- Copyright (c) 2008--2013 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--

insert into rhnPackageKeyType (id, label) values
(sequence_nextval('rhn_package_key_type_id_seq'), 'gpg' );
insert into rhnPackageKeyType (id, label) values
(sequence_nextval('rhn_package_key_type_id_seq'), 'pgp' );
insert into rhnPackageKeyType (id, label) values
(sequence_nextval('rhn_package_key_type_id_seq'), 'rsa' );
insert into rhnPackageKeyType (id, label) values
(sequence_nextval('rhn_package_key_type_id_seq'), 'dsa' );



commit;

   0707010000002B000081B400000000000000000000000167AE11140000094F000000000000000000000000000000000000003600000000susemanager-schema/common/data/rhnPackageProvider.sql --
-- Copyright (c) 2008--2012 Red Hat, Inc.
-- Copyright (c) 2010--2021 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--

insert into rhnPackageProvider (id, name) values
(sequence_nextval('rhn_package_provider_id_seq'), 'Red Hat Inc.' );
insert into rhnPackageProvider (id, name) values
(sequence_nextval('rhn_package_provider_id_seq'), 'Fedora' );
insert into rhnPackageProvider (id, name) values
(sequence_nextval('rhn_package_provider_id_seq'), 'CentOS' );
insert into rhnPackageProvider (id, name) values
(sequence_nextval('rhn_package_provider_id_seq'), 'Scientific Linux' );
insert into rhnPackageProvider (id, name) values
(sequence_nextval('rhn_package_provider_id_seq'), 'SUSE LLC' );
insert into rhnPackageProvider (id, name) values
(sequence_nextval('rhn_package_provider_id_seq'), 'openSUSE' );
insert into rhnPackageProvider (id, name) values
(sequence_nextval('rhn_package_provider_id_seq'), 'Oracle Inc.' );
insert into rhnPackageProvider (id, name) values
(sequence_nextval('rhn_package_provider_id_seq'), 'Spacewalk' );
insert into rhnPackageProvider (id, name) values
(sequence_nextval('rhn_package_provider_id_seq'), 'EPEL' );
insert into rhnPackageProvider (id, name) values
(sequence_nextval('rhn_package_provider_id_seq'), 'Novell Inc.' );
insert into rhnPackageProvider (id, name) values
(sequence_nextval('rhn_package_provider_id_seq'), 'Uyuni' );
insert into rhnPackageProvider (id, name) values
(sequence_nextval('rhn_package_provider_id_seq'), 'Alibaba' );
insert into rhnPackageProvider (id, name) values
(sequence_nextval('rhn_package_provider_id_seq'), 'AlmaLinux' );
insert into rhnPackageProvider (id, name) values
(sequence_nextval('rhn_package_provider_id_seq'), 'Amazon' );
insert into rhnPackageProvider (id, name) values
(sequence_nextval('rhn_package_provider_id_seq'), 'Rocky Linux' );

commit;
 0707010000002C000081B400000000000000000000000167AE1114000003C4000000000000000000000000000000000000003B00000000susemanager-schema/common/data/rhnPackageSyncBlacklist.sql    --
-- Copyright (c) 2008--2013 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--

insert into rhnPackageSyncBlacklist (package_name_id)
	values (lookup_package_name('gpg-pubkey'));

insert into rhnPackageSyncBlacklist (package_name_id)
	values (lookup_package_name('rhns-ca-cert'));

insert into rhnPackageSyncBlacklist (package_name_id)
	values (lookup_package_name('rhn-org-trusted-ssl-cert'));

commit;

0707010000002D000081B400000000000000000000000167AE111400006BD2000000000000000000000000000000000000003F00000000susemanager-schema/common/data/rhnPackageUpgradeArchCompat.sql    --
-- Copyright (c) 2010--2014 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--
--
--

insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('noarch'), LOOKUP_PACKAGE_ARCH('noarch'), current_timestamp, current_timestamp);

insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('i386'), LOOKUP_PACKAGE_ARCH('noarch'), current_timestamp, current_timestamp);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('i386'), LOOKUP_PACKAGE_ARCH('i386'), current_timestamp, current_timestamp);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('noarch'), LOOKUP_PACKAGE_ARCH('i386'), current_timestamp, current_timestamp);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('i486'), LOOKUP_PACKAGE_ARCH('noarch'), current_timestamp, current_timestamp);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('i486'), LOOKUP_PACKAGE_ARCH('i486'), current_timestamp, current_timestamp);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('noarch'), LOOKUP_PACKAGE_ARCH('i486'), current_timestamp, current_timestamp);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('i586'), LOOKUP_PACKAGE_ARCH('noarch'), current_timestamp, current_timestamp);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('i586'), LOOKUP_PACKAGE_ARCH('i586'), current_timestamp, current_timestamp);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('noarch'), LOOKUP_PACKAGE_ARCH('i586'), current_timestamp, current_timestamp);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('i686'), LOOKUP_PACKAGE_ARCH('noarch'), current_timestamp, current_timestamp);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('i686'), LOOKUP_PACKAGE_ARCH('i686'), current_timestamp, current_timestamp);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('noarch'), LOOKUP_PACKAGE_ARCH('i686'), current_timestamp, current_timestamp);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('alpha'), LOOKUP_PACKAGE_ARCH('noarch'), current_timestamp, current_timestamp);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('alpha'), LOOKUP_PACKAGE_ARCH('alpha'), current_timestamp, current_timestamp);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('noarch'), LOOKUP_PACKAGE_ARCH('alpha'), current_timestamp, current_timestamp);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('alphaev6'), LOOKUP_PACKAGE_ARCH('noarch'), current_timestamp, current_timestamp);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('alphaev6'), LOOKUP_PACKAGE_ARCH('alphaev6'), current_timestamp, current_timestamp);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('noarch'), LOOKUP_PACKAGE_ARCH('alphaev6'), current_timestamp, current_timestamp);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('ia64'), LOOKUP_PACKAGE_ARCH('noarch'), current_timestamp, current_timestamp);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('ia64'), LOOKUP_PACKAGE_ARCH('ia64'), current_timestamp, current_timestamp);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('noarch'), LOOKUP_PACKAGE_ARCH('ia64'), current_timestamp, current_timestamp);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('sparc'), LOOKUP_PACKAGE_ARCH('noarch'), current_timestamp, current_timestamp);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('sparc'), LOOKUP_PACKAGE_ARCH('sparc'), current_timestamp, current_timestamp);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('noarch'), LOOKUP_PACKAGE_ARCH('sparc'), current_timestamp, current_timestamp);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('sparcv9'), LOOKUP_PACKAGE_ARCH('noarch'), current_timestamp, current_timestamp);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('sparcv9'), LOOKUP_PACKAGE_ARCH('sparcv9'), current_timestamp, current_timestamp);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('noarch'), LOOKUP_PACKAGE_ARCH('sparcv9'), current_timestamp, current_timestamp);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('sparc64'), LOOKUP_PACKAGE_ARCH('noarch'), current_timestamp, current_timestamp);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('sparc64'), LOOKUP_PACKAGE_ARCH('sparc64'), current_timestamp, current_timestamp);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('noarch'), LOOKUP_PACKAGE_ARCH('sparc64'), current_timestamp, current_timestamp);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('s390'), LOOKUP_PACKAGE_ARCH('noarch'), current_timestamp, current_timestamp);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('s390'), LOOKUP_PACKAGE_ARCH('s390'), current_timestamp, current_timestamp);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('noarch'), LOOKUP_PACKAGE_ARCH('s390'), current_timestamp, current_timestamp);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('athlon'), LOOKUP_PACKAGE_ARCH('noarch'), current_timestamp, current_timestamp);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('athlon'), LOOKUP_PACKAGE_ARCH('athlon'), current_timestamp, current_timestamp);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('noarch'), LOOKUP_PACKAGE_ARCH('athlon'), current_timestamp, current_timestamp);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('s390x'), LOOKUP_PACKAGE_ARCH('noarch'), current_timestamp, current_timestamp);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('s390x'), LOOKUP_PACKAGE_ARCH('s390x'), current_timestamp, current_timestamp);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('noarch'), LOOKUP_PACKAGE_ARCH('s390x'), current_timestamp, current_timestamp);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('ppc'), LOOKUP_PACKAGE_ARCH('noarch'), current_timestamp, current_timestamp);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('ppc'), LOOKUP_PACKAGE_ARCH('ppc'), current_timestamp, current_timestamp);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('noarch'), LOOKUP_PACKAGE_ARCH('ppc'), current_timestamp, current_timestamp);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('ppc64'), LOOKUP_PACKAGE_ARCH('noarch'), current_timestamp, current_timestamp);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('ppc64'), LOOKUP_PACKAGE_ARCH('ppc64'), current_timestamp, current_timestamp);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('noarch'), LOOKUP_PACKAGE_ARCH('ppc64le'), current_timestamp, current_timestamp);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('ppc64le'), LOOKUP_PACKAGE_ARCH('ppc64le'), current_timestamp, current_timestamp);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('ppc64le'), LOOKUP_PACKAGE_ARCH('noarch'), current_timestamp, current_timestamp);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('noarch'), LOOKUP_PACKAGE_ARCH('ppc64'), current_timestamp, current_timestamp);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('pSeries'), LOOKUP_PACKAGE_ARCH('noarch'), current_timestamp, current_timestamp);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('pSeries'), LOOKUP_PACKAGE_ARCH('pSeries'), current_timestamp, current_timestamp);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('noarch'), LOOKUP_PACKAGE_ARCH('pSeries'), current_timestamp, current_timestamp);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('iSeries'), LOOKUP_PACKAGE_ARCH('noarch'), current_timestamp, current_timestamp);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('iSeries'), LOOKUP_PACKAGE_ARCH('iSeries'), current_timestamp, current_timestamp);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('noarch'), LOOKUP_PACKAGE_ARCH('iSeries'), current_timestamp, current_timestamp);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('x86_64'), LOOKUP_PACKAGE_ARCH('noarch'), current_timestamp, current_timestamp);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('x86_64'), LOOKUP_PACKAGE_ARCH('x86_64'), current_timestamp, current_timestamp);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('noarch'), LOOKUP_PACKAGE_ARCH('x86_64'), current_timestamp, current_timestamp);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('ppc64iseries'), LOOKUP_PACKAGE_ARCH('noarch'), current_timestamp, current_timestamp);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('ppc64iseries'), LOOKUP_PACKAGE_ARCH('ppc64iseries'), current_timestamp, current_timestamp);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('noarch'), LOOKUP_PACKAGE_ARCH('ppc64iseries'), current_timestamp, current_timestamp);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('ppc64pseries'), LOOKUP_PACKAGE_ARCH('noarch'), current_timestamp, current_timestamp);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('ppc64pseries'), LOOKUP_PACKAGE_ARCH('ppc64pseries'), current_timestamp, current_timestamp);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('noarch'), LOOKUP_PACKAGE_ARCH('ppc64pseries'), current_timestamp, current_timestamp);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('noarch'), LOOKUP_PACKAGE_ARCH('armv7l'), current_timestamp, current_timestamp);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('armv7l'), LOOKUP_PACKAGE_ARCH('armv7l'), current_timestamp, current_timestamp);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('armv7l'), LOOKUP_PACKAGE_ARCH('noarch'), current_timestamp, current_timestamp);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('noarch'), LOOKUP_PACKAGE_ARCH('armv6hl'), current_timestamp, current_timestamp);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('armv6hl'), LOOKUP_PACKAGE_ARCH('armv6hl'), current_timestamp, current_timestamp);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('armv6hl'), LOOKUP_PACKAGE_ARCH('noarch'), current_timestamp, current_timestamp);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('noarch'), LOOKUP_PACKAGE_ARCH('armv6l'), current_timestamp, current_timestamp);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('armv6l'), LOOKUP_PACKAGE_ARCH('armv6l'), current_timestamp, current_timestamp);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('armv6l'), LOOKUP_PACKAGE_ARCH('noarch'), current_timestamp, current_timestamp);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('noarch'), LOOKUP_PACKAGE_ARCH('armv5tel'), current_timestamp, current_timestamp);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('armv5tel'), LOOKUP_PACKAGE_ARCH('armv5tel'), current_timestamp, current_timestamp);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('armv5tel'), LOOKUP_PACKAGE_ARCH('noarch'), current_timestamp, current_timestamp);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('noarch'), LOOKUP_PACKAGE_ARCH('armv7hl'), current_timestamp, current_timestamp);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('armv7hl'), LOOKUP_PACKAGE_ARCH('armv7hl'), current_timestamp, current_timestamp);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('armv7hl'), LOOKUP_PACKAGE_ARCH('noarch'), current_timestamp, current_timestamp);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('noarch'), LOOKUP_PACKAGE_ARCH('armv7hnl'), current_timestamp, current_timestamp);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('armv7hnl'), LOOKUP_PACKAGE_ARCH('armv7hnl'), current_timestamp, current_timestamp);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('armv7hnl'), LOOKUP_PACKAGE_ARCH('noarch'), current_timestamp, current_timestamp);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('noarch'), LOOKUP_PACKAGE_ARCH('aarch64'), current_timestamp, current_timestamp);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('aarch64'), LOOKUP_PACKAGE_ARCH('aarch64'), current_timestamp, current_timestamp);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('aarch64'), LOOKUP_PACKAGE_ARCH('noarch'), current_timestamp, current_timestamp);

insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('tar'), LOOKUP_PACKAGE_ARCH('tar'), current_timestamp, current_timestamp);

insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('ia32e'), LOOKUP_PACKAGE_ARCH('noarch'), current_timestamp, current_timestamp);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('ia32e'), LOOKUP_PACKAGE_ARCH('ia32e'), current_timestamp, current_timestamp);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('noarch'), LOOKUP_PACKAGE_ARCH('ia32e'), current_timestamp, current_timestamp);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('amd64'), LOOKUP_PACKAGE_ARCH('noarch'), current_timestamp, current_timestamp);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('amd64'), LOOKUP_PACKAGE_ARCH('amd64'), current_timestamp, current_timestamp);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('noarch'), LOOKUP_PACKAGE_ARCH('amd64'), current_timestamp, current_timestamp);

insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('all-deb'), LOOKUP_PACKAGE_ARCH('all-deb'), current_timestamp, current_timestamp);

insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('i386-deb'), LOOKUP_PACKAGE_ARCH('all-deb'), current_timestamp, current_timestamp);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('i386-deb'), LOOKUP_PACKAGE_ARCH('i386-deb'), current_timestamp, current_timestamp);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('all-deb'), LOOKUP_PACKAGE_ARCH('i386-deb'), current_timestamp, current_timestamp);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('alpha-deb'), LOOKUP_PACKAGE_ARCH('all-deb'), current_timestamp, current_timestamp);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('alpha-deb'), LOOKUP_PACKAGE_ARCH('alpha-deb'), current_timestamp, current_timestamp);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('all-deb'), LOOKUP_PACKAGE_ARCH('alpha-deb'), current_timestamp, current_timestamp);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('ia64-deb'), LOOKUP_PACKAGE_ARCH('all-deb'), current_timestamp, current_timestamp);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('ia64-deb'), LOOKUP_PACKAGE_ARCH('ia64-deb'), current_timestamp, current_timestamp);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('all-deb'), LOOKUP_PACKAGE_ARCH('ia64-deb'), current_timestamp, current_timestamp);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('sparc-deb'), LOOKUP_PACKAGE_ARCH('all-deb'), current_timestamp, current_timestamp);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('sparc-deb'), LOOKUP_PACKAGE_ARCH('sparc-deb'), current_timestamp, current_timestamp);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('all-deb'), LOOKUP_PACKAGE_ARCH('sparc-deb'), current_timestamp, current_timestamp);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('src-deb'), LOOKUP_PACKAGE_ARCH('src-deb'), current_timestamp, current_timestamp);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('s390-deb'), LOOKUP_PACKAGE_ARCH('all-deb'), current_timestamp, current_timestamp);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('s390-deb'), LOOKUP_PACKAGE_ARCH('s390-deb'), current_timestamp, current_timestamp);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('all-deb'), LOOKUP_PACKAGE_ARCH('s390-deb'), current_timestamp, current_timestamp);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('powerpc-deb'), LOOKUP_PACKAGE_ARCH('all-deb'), current_timestamp, current_timestamp);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('powerpc-deb'), LOOKUP_PACKAGE_ARCH('powerpc-deb'), current_timestamp, current_timestamp);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('all-deb'), LOOKUP_PACKAGE_ARCH('powerpc-deb'), current_timestamp, current_timestamp);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('arm-deb'), LOOKUP_PACKAGE_ARCH('all-deb'), current_timestamp, current_timestamp);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('arm-deb'), LOOKUP_PACKAGE_ARCH('arm-deb'), current_timestamp, current_timestamp);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('all-deb'), LOOKUP_PACKAGE_ARCH('arm-deb'), current_timestamp, current_timestamp);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('armhf-deb'), LOOKUP_PACKAGE_ARCH('all-deb'), current_timestamp, current_timestamp);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('all-deb'), LOOKUP_PACKAGE_ARCH('armhf-deb'), current_timestamp, current_timestamp);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('armhf-deb'), LOOKUP_PACKAGE_ARCH('armhf-deb'), current_timestamp, current_timestamp);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('mips-deb'), LOOKUP_PACKAGE_ARCH('all-deb'), current_timestamp, current_timestamp);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('mips-deb'), LOOKUP_PACKAGE_ARCH('mips-deb'), current_timestamp, current_timestamp);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('all-deb'), LOOKUP_PACKAGE_ARCH('mips-deb'), current_timestamp, current_timestamp);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('amd64-deb'), LOOKUP_PACKAGE_ARCH('all-deb'), current_timestamp, current_timestamp);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('amd64-deb'), LOOKUP_PACKAGE_ARCH('amd64-deb'), current_timestamp, current_timestamp);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('all-deb'), LOOKUP_PACKAGE_ARCH('amd64-deb'), current_timestamp, current_timestamp);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('arm64-deb'), LOOKUP_PACKAGE_ARCH('all-deb'), current_timestamp, current_timestamp);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('arm64-deb'), LOOKUP_PACKAGE_ARCH('arm64-deb'), current_timestamp, current_timestamp);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('all-deb'), LOOKUP_PACKAGE_ARCH('arm64-deb'), current_timestamp, current_timestamp);

commit;

  0707010000002E000081B400000000000000000000000167AE11140000038A000000000000000000000000000000000000003600000000susemanager-schema/common/data/rhnPushClientState.sql --
-- Copyright (c) 2008--2013 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--

insert into rhnPushClientState (id, label, name)
    values (sequence_nextval('rhn_pclient_state_id_seq'), 'online', 'online');
insert into rhnPushClientState (id, label, name)
    values (sequence_nextval('rhn_pclient_state_id_seq'), 'offline', 'offline');

commit;
  0707010000002F000081B400000000000000000000000167AE1114000005F1000000000000000000000000000000000000003C00000000susemanager-schema/common/data/rhnSGTypeBaseAddonCompat.sql   --
-- Copyright (c) 2008 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--

insert into rhnSGTypeBaseAddonCompat (base_id, addon_id)
values (lookup_sg_type('enterprise_entitled'),
        lookup_sg_type('virtualization_host'));

insert into rhnSGTypeBaseAddonCompat (base_id, addon_id)
values (lookup_sg_type('salt_entitled'),
        lookup_sg_type('virtualization_host'));

insert into rhnSGTypeBaseAddonCompat (base_id, addon_id)
values (lookup_sg_type('salt_entitled'),
        lookup_sg_type('container_build_host'));

insert into rhnSGTypeBaseAddonCompat (base_id, addon_id)
values (lookup_sg_type('salt_entitled'),
        lookup_sg_type('osimage_build_host'));

insert into rhnSGTypeBaseAddonCompat (base_id, addon_id)
values (lookup_sg_type('salt_entitled'),
        lookup_sg_type('monitoring_entitled'));

insert into rhnSGTypeBaseAddonCompat (base_id, addon_id)
values (lookup_sg_type('salt_entitled'),
        lookup_sg_type('ansible_control_node'));

commit;
   07070100000030000081B400000000000000000000000167AE111400001DE0000000000000000000000000000000000000003100000000susemanager-schema/common/data/rhnServerArch.sql  --
-- Copyright (c) 2008--2015 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--

insert into rhnServerArch (id, label, name, arch_type_id) values
(sequence_nextval('rhn_server_arch_id_seq'), 'i386-redhat-linux', 'i386', lookup_arch_type('rpm'));
insert into rhnServerArch (id, label, name, arch_type_id) values
(sequence_nextval('rhn_server_arch_id_seq'), 'i386-debian-linux', 'i386 Debian', lookup_arch_type('deb'));

insert into rhnServerArch (id, label, name, arch_type_id) values
(sequence_nextval('rhn_server_arch_id_seq'), 'i486-redhat-linux', 'i486', lookup_arch_type('rpm'));

insert into rhnServerArch (id, label, name, arch_type_id) values
(sequence_nextval('rhn_server_arch_id_seq'), 'i586-redhat-linux', 'i586', lookup_arch_type('rpm'));

insert into rhnServerArch (id, label, name, arch_type_id) values
(sequence_nextval('rhn_server_arch_id_seq'), 'i686-redhat-linux', 'i686', lookup_arch_type('rpm'));


insert into rhnServerArch (id, label, name, arch_type_id) values
(sequence_nextval('rhn_server_arch_id_seq'), 'athlon-redhat-linux', 'athlon', lookup_arch_type('rpm'));

insert into rhnServerArch (id, label, name, arch_type_id) values
(sequence_nextval('rhn_server_arch_id_seq'), 'alpha-redhat-linux', 'alpha', lookup_arch_type('rpm'));
insert into rhnServerArch (id, label, name, arch_type_id) values
(sequence_nextval('rhn_server_arch_id_seq'), 'alpha-debian-linux', 'alpha Debian', lookup_arch_type('deb'));

insert into rhnServerArch (id, label, name, arch_type_id) values
(sequence_nextval('rhn_server_arch_id_seq'), 'alphaev6-redhat-linux', 'alphaev6', lookup_arch_type('rpm'));

insert into rhnServerArch (id, label, name, arch_type_id) values
(sequence_nextval('rhn_server_arch_id_seq'), 'ia64-redhat-linux', 'ia64', lookup_arch_type('rpm'));
insert into rhnServerArch (id, label, name, arch_type_id) values
(sequence_nextval('rhn_server_arch_id_seq'), 'ia64-debian-linux', 'ia64 Debian', lookup_arch_type('deb'));

insert into rhnServerArch (id, label, name, arch_type_id) values
(sequence_nextval('rhn_server_arch_id_seq'), 'sparc-redhat-linux', 'sparc', lookup_arch_type('rpm'));
insert into rhnServerArch (id, label, name, arch_type_id) values
(sequence_nextval('rhn_server_arch_id_seq'), 'sparc-debian-linux', 'sparc Debian', lookup_arch_type('deb'));

insert into rhnServerArch (id, label, name, arch_type_id) values
(sequence_nextval('rhn_server_arch_id_seq'), 'sparcv9-redhat-linux', 'sparcv9', lookup_arch_type('rpm'));

insert into rhnServerArch (id, label, name, arch_type_id) values
(sequence_nextval('rhn_server_arch_id_seq'), 'sparc64-redhat-linux', 'sparc64', lookup_arch_type('rpm'));

insert into rhnServerArch (id, label, name, arch_type_id) values
(sequence_nextval('rhn_server_arch_id_seq'), 's390-redhat-linux', 's390', lookup_arch_type('rpm'));
insert into rhnServerArch (id, label, name, arch_type_id) values
(sequence_nextval('rhn_server_arch_id_seq'), 's390-debian-linux', 's390 Debian', lookup_arch_type('deb'));

insert into rhnServerArch (id, label, name, arch_type_id) values
(sequence_nextval('rhn_server_arch_id_seq'), 's390x-redhat-linux', 's390x', lookup_arch_type('rpm'));

insert into rhnServerArch (id, label, name, arch_type_id) values
(sequence_nextval('rhn_server_arch_id_seq'), 'ppc-redhat-linux', 'ppc', lookup_arch_type('rpm'));

insert into rhnServerArch (id, label, name, arch_type_id) values
(sequence_nextval('rhn_server_arch_id_seq'), 'aarch64-redhat-linux', 'aarch64', lookup_arch_type('rpm'));

insert into rhnServerArch (id, label, name, arch_type_id) values
(sequence_nextval('rhn_server_arch_id_seq'), 'armv7l-redhat-linux', 'armv7l', lookup_arch_type('rpm'));

insert into rhnServerArch (id, label, name, arch_type_id) values
(sequence_nextval('rhn_server_arch_id_seq'), 'armv5tejl-redhat-linux', 'armv5tejl', lookup_arch_type('rpm'));

insert into rhnServerArch (id, label, name, arch_type_id) values
(sequence_nextval('rhn_server_arch_id_seq'), 'armv6l-redhat-linux', 'armv6l', lookup_arch_type('rpm'));

insert into rhnServerArch (id, label, name, arch_type_id) values
(sequence_nextval('rhn_server_arch_id_seq'), 'armv6hl-redhat-linux', 'armv6hl', lookup_arch_type('rpm'));

insert into rhnServerArch (id, label, name, arch_type_id) values
(sequence_nextval('rhn_server_arch_id_seq'), 'powerpc-debian-linux', 'powerpc Debian', lookup_arch_type('deb'));

insert into rhnServerArch (id, label, name, arch_type_id) values
(sequence_nextval('rhn_server_arch_id_seq'), 'ppc64-redhat-linux', 'ppc64', lookup_arch_type('rpm'));

insert into rhnServerArch (id, label, name, arch_type_id) values
(sequence_nextval('rhn_server_arch_id_seq'), 'ppc64le-redhat-linux', 'ppc64le', lookup_arch_type('rpm'));

insert into rhnServerArch (id, label, name, arch_type_id) values
(sequence_nextval('rhn_server_arch_id_seq'), 'pSeries-redhat-linux', 'pSeries', lookup_arch_type('rpm'));

insert into rhnServerArch (id, label, name, arch_type_id) values
(sequence_nextval('rhn_server_arch_id_seq'), 'iSeries-redhat-linux', 'iSeries', lookup_arch_type('rpm'));

insert into rhnServerArch (id, label, name, arch_type_id) values
(sequence_nextval('rhn_server_arch_id_seq'), 'x86_64-redhat-linux', 'x86_64', lookup_arch_type('rpm'));

insert into rhnServerArch (id, label, name, arch_type_id) values
(sequence_nextval('rhn_server_arch_id_seq'), 'ppc64iseries-redhat-linux', 'ppc64iseries', lookup_arch_type('rpm'));

insert into rhnServerArch (id, label, name, arch_type_id) values
(sequence_nextval('rhn_server_arch_id_seq'), 'ppc64pseries-redhat-linux', 'ppc64pseries', lookup_arch_type('rpm'));

insert into rhnServerArch (id, label, name, arch_type_id) values
(sequence_nextval('rhn_server_arch_id_seq'), 'ia32e-redhat-linux', 'EM64T', lookup_arch_type('rpm'));

insert into rhnServerArch (id, label, name, arch_type_id) values
(sequence_nextval('rhn_server_arch_id_seq'), 'amd64-redhat-linux', 'AMD64', lookup_arch_type('rpm'));
insert into rhnServerArch (id, label, name, arch_type_id) values
(sequence_nextval('rhn_server_arch_id_seq'), 'amd64-debian-linux', 'AMD64 Debian', lookup_arch_type('deb'));

insert into rhnServerArch (id, label, name, arch_type_id) values
(sequence_nextval('rhn_server_arch_id_seq'), 'arm-debian-linux', 'arm Debian', lookup_arch_type('deb'));

insert into rhnServerArch (id, label, name, arch_type_id) values
(sequence_nextval('rhn_server_arch_id_seq'), 'armv6l-debian-linux', 'arm Debian', lookup_arch_type('deb'));

insert into rhnServerArch (id, label, name, arch_type_id) values
(sequence_nextval('rhn_server_arch_id_seq'), 'mips-debian-linux', 'mips Debian', lookup_arch_type('deb'));

insert into rhnServerArch (id, label, name, arch_type_id) values
(sequence_nextval('rhn_server_arch_id_seq'), 'armv7l-debian-linux', 'arm Debian', lookup_arch_type('deb'));

insert into rhnServerArch (id, label, name, arch_type_id) values
(sequence_nextval('rhn_server_arch_id_seq'), 'cloud', 'cloud', lookup_arch_type('rpm'));

insert into rhnServerArch (id, label, name, arch_type_id) values
(sequence_nextval('rhn_server_arch_id_seq'), 'arm64-debian-linux', 'ARM64 Debian', lookup_arch_type('deb'));

commit;

07070100000031000081B400000000000000000000000167AE111400001C3C000000000000000000000000000000000000003E00000000susemanager-schema/common/data/rhnServerChannelArchCompat.sql --
-- Copyright (c) 2008--2015 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--

insert into rhnServerChannelArchCompat (server_arch_id, channel_arch_id) values
(LOOKUP_SERVER_ARCH('i386-redhat-linux'), LOOKUP_CHANNEL_ARCH('channel-ia32'));

insert into rhnServerChannelArchCompat (server_arch_id, channel_arch_id) values
(LOOKUP_SERVER_ARCH('i486-redhat-linux'), LOOKUP_CHANNEL_ARCH('channel-ia32'));

insert into rhnServerChannelArchCompat (server_arch_id, channel_arch_id) values
(LOOKUP_SERVER_ARCH('i586-redhat-linux'), LOOKUP_CHANNEL_ARCH('channel-ia32'));

insert into rhnServerChannelArchCompat (server_arch_id, channel_arch_id) values
(LOOKUP_SERVER_ARCH('i686-redhat-linux'), LOOKUP_CHANNEL_ARCH('channel-ia32'));

insert into rhnServerChannelArchCompat (server_arch_id, channel_arch_id) values
(LOOKUP_SERVER_ARCH('athlon-redhat-linux'), LOOKUP_CHANNEL_ARCH('channel-ia32'));

insert into rhnServerChannelArchCompat (server_arch_id, channel_arch_id) values
(LOOKUP_SERVER_ARCH('alpha-redhat-linux'), LOOKUP_CHANNEL_ARCH('channel-alpha'));

insert into rhnServerChannelArchCompat (server_arch_id, channel_arch_id) values
(LOOKUP_SERVER_ARCH('alphaev6-redhat-linux'), LOOKUP_CHANNEL_ARCH('channel-alpha'));

insert into rhnServerChannelArchCompat (server_arch_id, channel_arch_id) values
(LOOKUP_SERVER_ARCH('ia64-redhat-linux'), LOOKUP_CHANNEL_ARCH('channel-ia64'));

insert into rhnServerChannelArchCompat (server_arch_id, channel_arch_id) values
(LOOKUP_SERVER_ARCH('sparc-redhat-linux'), LOOKUP_CHANNEL_ARCH('channel-sparc'));

insert into rhnServerChannelArchCompat (server_arch_id, channel_arch_id) values
(LOOKUP_SERVER_ARCH('sparcv9-redhat-linux'), LOOKUP_CHANNEL_ARCH('channel-sparc'));

insert into rhnServerChannelArchCompat (server_arch_id, channel_arch_id) values
(LOOKUP_SERVER_ARCH('sparc64-redhat-linux'), LOOKUP_CHANNEL_ARCH('channel-sparc'));

insert into rhnServerChannelArchCompat (server_arch_id, channel_arch_id) values
(LOOKUP_SERVER_ARCH('s390-redhat-linux'), LOOKUP_CHANNEL_ARCH('channel-s390'));

insert into rhnServerChannelArchCompat (server_arch_id, channel_arch_id) values
(LOOKUP_SERVER_ARCH('s390x-redhat-linux'), LOOKUP_CHANNEL_ARCH('channel-s390x'));

insert into rhnServerChannelArchCompat (server_arch_id, channel_arch_id) values
(LOOKUP_SERVER_ARCH('pSeries-redhat-linux'), LOOKUP_CHANNEL_ARCH('channel-pSeries'));

insert into rhnServerChannelArchCompat (server_arch_id, channel_arch_id) values
(LOOKUP_SERVER_ARCH('iSeries-redhat-linux'), LOOKUP_CHANNEL_ARCH('channel-iSeries'));

insert into rhnServerChannelArchCompat (server_arch_id, channel_arch_id) values
(LOOKUP_SERVER_ARCH('x86_64-redhat-linux'), LOOKUP_CHANNEL_ARCH('channel-x86_64'));

insert into rhnServerChannelArchCompat (server_arch_id, channel_arch_id) values
(LOOKUP_SERVER_ARCH('ia32e-redhat-linux'), LOOKUP_CHANNEL_ARCH('channel-x86_64'));

insert into rhnServerChannelArchCompat (server_arch_id, channel_arch_id) values
(LOOKUP_SERVER_ARCH('amd64-redhat-linux'), LOOKUP_CHANNEL_ARCH('channel-x86_64'));

insert into rhnServerChannelArchCompat (server_arch_id, channel_arch_id) values
(LOOKUP_SERVER_ARCH('ppc64iseries-redhat-linux'), LOOKUP_CHANNEL_ARCH('channel-ppc'));

insert into rhnServerChannelArchCompat (server_arch_id, channel_arch_id) values
(LOOKUP_SERVER_ARCH('ppc64pseries-redhat-linux'), LOOKUP_CHANNEL_ARCH('channel-ppc'));

insert into rhnServerChannelArchCompat (server_arch_id, channel_arch_id) values
(LOOKUP_SERVER_ARCH('aarch64-redhat-linux'), LOOKUP_CHANNEL_ARCH('channel-aarch64'));

insert into rhnServerChannelArchCompat (server_arch_id, channel_arch_id) values
(LOOKUP_SERVER_ARCH('armv7l-redhat-linux'), LOOKUP_CHANNEL_ARCH('channel-armhfp'));

insert into rhnServerChannelArchCompat (server_arch_id, channel_arch_id) values
(LOOKUP_SERVER_ARCH('armv7l-redhat-linux'), LOOKUP_CHANNEL_ARCH('channel-arm'));

insert into rhnServerChannelArchCompat (server_arch_id, channel_arch_id) values
(LOOKUP_SERVER_ARCH('armv5tejl-redhat-linux'), LOOKUP_CHANNEL_ARCH('channel-arm'));

insert into rhnServerChannelArchCompat (server_arch_id, channel_arch_id) values
(LOOKUP_SERVER_ARCH('armv6l-redhat-linux'), LOOKUP_CHANNEL_ARCH('channel-arm'));

insert into rhnServerChannelArchCompat (server_arch_id, channel_arch_id) values
(LOOKUP_SERVER_ARCH('armv6hl-redhat-linux'), LOOKUP_CHANNEL_ARCH('channel-arm'));

insert into rhnServerChannelArchCompat (server_arch_id, channel_arch_id) values
(LOOKUP_SERVER_ARCH('i386-debian-linux'), LOOKUP_CHANNEL_ARCH('channel-ia32-deb'));

insert into rhnServerChannelArchCompat (server_arch_id, channel_arch_id) values
(LOOKUP_SERVER_ARCH('alpha-debian-linux'), LOOKUP_CHANNEL_ARCH('channel-alpha-deb'));

insert into rhnServerChannelArchCompat (server_arch_id, channel_arch_id) values
(LOOKUP_SERVER_ARCH('ia64-debian-linux'), LOOKUP_CHANNEL_ARCH('channel-ia64-deb'));

insert into rhnServerChannelArchCompat (server_arch_id, channel_arch_id) values
(LOOKUP_SERVER_ARCH('sparc-debian-linux'), LOOKUP_CHANNEL_ARCH('channel-sparc-deb'));

insert into rhnServerChannelArchCompat (server_arch_id, channel_arch_id) values
(LOOKUP_SERVER_ARCH('s390-debian-linux'), LOOKUP_CHANNEL_ARCH('channel-s390-deb'));

insert into rhnServerChannelArchCompat (server_arch_id, channel_arch_id) values
(LOOKUP_SERVER_ARCH('powerpc-debian-linux'), LOOKUP_CHANNEL_ARCH('channel-powerpc-deb'));

insert into rhnServerChannelArchCompat (server_arch_id, channel_arch_id) values
(LOOKUP_SERVER_ARCH('amd64-debian-linux'), LOOKUP_CHANNEL_ARCH('channel-amd64-deb'));

insert into rhnServerChannelArchCompat (server_arch_id, channel_arch_id) values
(LOOKUP_SERVER_ARCH('arm-debian-linux'), LOOKUP_CHANNEL_ARCH('channel-arm-deb'));

insert into rhnServerChannelArchCompat (server_arch_id, channel_arch_id) values
(LOOKUP_SERVER_ARCH('armv6l-debian-linux'), LOOKUP_CHANNEL_ARCH('channel-arm-deb'));

insert into rhnServerChannelArchCompat (server_arch_id, channel_arch_id) values
(LOOKUP_SERVER_ARCH('mips-debian-linux'), LOOKUP_CHANNEL_ARCH('channel-mips-deb'));

insert into rhnServerChannelArchCompat (server_arch_id, channel_arch_id) values
(LOOKUP_SERVER_ARCH('ppc64-redhat-linux'), LOOKUP_CHANNEL_ARCH('channel-ppc'));

insert into rhnServerChannelArchCompat (server_arch_id, channel_arch_id) values
(LOOKUP_SERVER_ARCH('ppc64le-redhat-linux'), LOOKUP_CHANNEL_ARCH('channel-ppc64le'));

insert into rhnServerChannelArchCompat (server_arch_id, channel_arch_id) values
(LOOKUP_SERVER_ARCH('armv7l-debian-linux'), LOOKUP_CHANNEL_ARCH('channel-arm-deb'));

insert into rhnServerChannelArchCompat (server_arch_id, channel_arch_id) values
(LOOKUP_SERVER_ARCH('arm64-debian-linux'), LOOKUP_CHANNEL_ARCH('channel-arm64-deb'));

commit;

07070100000032000081B400000000000000000000000167AE111400000CE7000000000000000000000000000000000000003600000000susemanager-schema/common/data/rhnServerGroupType.sql --
-- Copyright (c) 2008--2013 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--
-- data for rhnServerGroupType

-- enterprise_entitled type --------------------------------------------------

insert into rhnServerGroupType (id, label, name, permanent, is_base)
        values (sequence_nextval('rhn_servergroup_type_seq'),
                'enterprise_entitled', 'Spacewalk Management Entitled Servers', 
                'Y', 'Y'
        );

-- virtualization_host type ----------------------------------------------------

insert into rhnServerGroupType ( id, label, name, permanent, is_base)
   values ( sequence_nextval('rhn_servergroup_type_seq'),
      'virtualization_host', 'Virtualization Host Entitled Servers',
      'N', 'N'
   );

--  bootstrap_entitled type ----------------------------------------------------

insert into rhnServerGroupType ( id, label, name, permanent, is_base)
   values ( sequence_nextval('rhn_servergroup_type_seq'),
      'bootstrap_entitled', 'Bootstrap Entitled Servers',
      'Y', 'Y'
   );

--  salt_entitled type ---------------------------------------------------------

insert into rhnServerGroupType (id, label, name, permanent, is_base)
   values (sequence_nextval('rhn_servergroup_type_seq'),
      'salt_entitled', 'Salt Management Entitled Servers',
      'Y', 'Y'
   );

-- foreign_entitled type ---------------------------------------------------------

insert into rhnServerGroupType ( id, label, name, permanent, is_base)
   values ( sequence_nextval('rhn_servergroup_type_seq'),
      'foreign_entitled', 'Foreign Entitled Servers',
      'Y', 'Y'
   );

-- container_build_host type ----------------------------------------------------

insert into rhnServerGroupType ( id, label, name, permanent, is_base)
   values ( sequence_nextval('rhn_servergroup_type_seq'),
      'container_build_host', 'Container Build Host',
      'N', 'N'
   );

-- osimage_build_host type ----------------------------------------------------

insert into rhnServerGroupType ( id, label, name, permanent, is_base)
   values ( sequence_nextval('rhn_servergroup_type_seq'),
      'osimage_build_host', 'OS Image Build Host',
      'N', 'N'
   );

-- monitoring_entitled type ----------------------------------------------------

insert into rhnServerGroupType (id, label, name, permanent, is_base)
   values (sequence_nextval('rhn_servergroup_type_seq'),
      'monitoring_entitled', 'Monitoring',
      'N', 'N'
   );

-- ansible_control_node type ---------------------------------------------------

insert into rhnServerGroupType ( id, label, name, permanent, is_base)
   values ( sequence_nextval('rhn_servergroup_type_seq'),
      'ansible_control_node', 'Ansible Control Node',
      'N', 'N'
   );

commit;
 07070100000033000081B400000000000000000000000167AE111400003FC4000000000000000000000000000000000000003D00000000susemanager-schema/common/data/rhnServerGroupTypeFeature.sql  --
-- Copyright (c) 2008--2010 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--

insert into rhnServerGroupTypeFeature (server_group_type_id, feature_id,
                                       created, modified)
values (lookup_sg_type('enterprise_entitled'), lookup_feature_type('ftr_package_updates'),
        current_timestamp,current_timestamp);
insert into rhnServerGroupTypeFeature (server_group_type_id, feature_id,
                                       created, modified)
values (lookup_sg_type('enterprise_entitled'), lookup_feature_type('ftr_package_lock'),
        current_timestamp,current_timestamp);
insert into rhnServerGroupTypeFeature (server_group_type_id, feature_id,
                                       created, modified)
values (lookup_sg_type('enterprise_entitled'), lookup_feature_type('ftr_errata_updates'),
        current_timestamp,current_timestamp);
insert into rhnServerGroupTypeFeature (server_group_type_id, feature_id,
                                       created, modified)
values (lookup_sg_type('enterprise_entitled'), lookup_feature_type('ftr_hardware_refresh'),
        current_timestamp,current_timestamp);
insert into rhnServerGroupTypeFeature (server_group_type_id, feature_id,
                                       created, modified)
values (lookup_sg_type('enterprise_entitled'), lookup_feature_type('ftr_package_refresh'),
        current_timestamp,current_timestamp);
insert into rhnServerGroupTypeFeature (server_group_type_id, feature_id,
                                       created, modified)
values (lookup_sg_type('enterprise_entitled'), lookup_feature_type('ftr_package_remove'),
        current_timestamp,current_timestamp);
insert into rhnServerGroupTypeFeature (server_group_type_id, feature_id,
                                       created, modified)
values (lookup_sg_type('enterprise_entitled'), lookup_feature_type('ftr_auto_errata_updates'),
        current_timestamp,current_timestamp);
insert into rhnServerGroupTypeFeature (server_group_type_id, feature_id,
                                       created, modified)
values (lookup_sg_type('enterprise_entitled'), lookup_feature_type('ftr_system_grouping'),
        current_timestamp,current_timestamp);
insert into rhnServerGroupTypeFeature (server_group_type_id, feature_id,
                                       created, modified)
values (lookup_sg_type('enterprise_entitled'), lookup_feature_type('ftr_package_verify'),
        current_timestamp,current_timestamp);
insert into rhnServerGroupTypeFeature (server_group_type_id, feature_id,
                                       created, modified)
values (lookup_sg_type('enterprise_entitled'), lookup_feature_type('ftr_profile_compare'),
        current_timestamp,current_timestamp);
insert into rhnServerGroupTypeFeature (server_group_type_id, feature_id,
                                       created, modified)
values (lookup_sg_type('enterprise_entitled'), lookup_feature_type('ftr_proxy_capable'),
        current_timestamp,current_timestamp);
insert into rhnServerGroupTypeFeature (server_group_type_id, feature_id,
                                       created, modified)
values (lookup_sg_type('enterprise_entitled'), lookup_feature_type('ftr_sat_capable'),
        current_timestamp,current_timestamp);
insert into rhnServerGroupTypeFeature (server_group_type_id, feature_id,
                                       created, modified)
values (lookup_sg_type('enterprise_entitled'), lookup_feature_type('ftr_reboot'),
        current_timestamp,current_timestamp);
insert into rhnServerGroupTypeFeature (server_group_type_id, feature_id,
                                       created, modified)
values (lookup_sg_type('enterprise_entitled'), lookup_feature_type('ftr_satellite_applet'),
        current_timestamp,current_timestamp);
insert into rhnServerGroupTypeFeature (server_group_type_id, feature_id,
                                       created, modified)
values (lookup_sg_type('enterprise_entitled'), lookup_feature_type('ftr_osa_bus'),
        current_timestamp,current_timestamp);
insert into rhnServerGroupTypeFeature (server_group_type_id, feature_id,
                                       created, modified)
values (lookup_sg_type('enterprise_entitled'), lookup_feature_type('ftr_daily_summary'),
        current_timestamp,current_timestamp);

insert into rhnServerGroupTypeFeature (server_group_type_id, feature_id,
                                       created, modified)
values (lookup_sg_type('enterprise_entitled'), lookup_feature_type('ftr_kickstart'),
        current_timestamp,current_timestamp);

insert into rhnServerGroupTypeFeature (server_group_type_id, feature_id,
                                       created, modified)
values (lookup_sg_type('enterprise_entitled'), lookup_feature_type('ftr_config'),
        current_timestamp,current_timestamp);
insert into rhnServerGroupTypeFeature (server_group_type_id, feature_id,
                                       created, modified)
values (lookup_sg_type('enterprise_entitled'), lookup_feature_type('ftr_custom_info'),
        current_timestamp,current_timestamp);
insert into rhnServerGroupTypeFeature (server_group_type_id, feature_id,
                                       created, modified)
values (lookup_sg_type('enterprise_entitled'), lookup_feature_type('ftr_delta_action'),
        current_timestamp,current_timestamp);
insert into rhnServerGroupTypeFeature (server_group_type_id, feature_id,
                                       created, modified)
values (lookup_sg_type('enterprise_entitled'), lookup_feature_type('ftr_snapshotting'),
        current_timestamp,current_timestamp);
insert into rhnServerGroupTypeFeature (server_group_type_id, feature_id,
                                       created, modified)
values (lookup_sg_type('enterprise_entitled'), lookup_feature_type('ftr_agent_smith'),
        current_timestamp,current_timestamp);
insert into rhnServerGroupTypeFeature (server_group_type_id, feature_id,
                                       created, modified)
values (lookup_sg_type('enterprise_entitled'), lookup_feature_type('ftr_remote_command'),
        current_timestamp,current_timestamp);

insert into rhnServerGroupTypeFeature (server_group_type_id, feature_id,
                                       created, modified)
values (lookup_sg_type('enterprise_entitled'), lookup_feature_type('ftr_channel_membership'),
        current_timestamp,current_timestamp);

insert into rhnServerGroupTypeFeature (server_group_type_id, feature_id,
                                       created, modified)
values (lookup_sg_type('enterprise_entitled'), lookup_feature_type('ftr_channel_config_subscription'),
        current_timestamp,current_timestamp);

insert into rhnServerGroupTypeFeature (server_group_type_id, feature_id,
                                       created, modified)
values (lookup_sg_type('enterprise_entitled'), lookup_feature_type('ftr_channel_deploy_diff'),
        current_timestamp,current_timestamp);

insert into rhnServerGroupTypeFeature (server_group_type_id, feature_id,
                                       created, modified)
values (lookup_sg_type('enterprise_entitled'), lookup_feature_type('ftr_tag_system'),
        current_timestamp,current_timestamp);

insert into rhnServerGroupTypeFeature (server_group_type_id, feature_id,
                                       created, modified)
values (lookup_sg_type('enterprise_entitled'), lookup_feature_type('ftr_power_management'),
        current_timestamp,current_timestamp);

insert into rhnServerGroupTypeFeature (server_group_type_id, feature_id,
                                       created, modified)
values (lookup_sg_type('enterprise_entitled'), lookup_feature_type('ftr_system_preferences'),
        current_timestamp,current_timestamp);

insert into rhnServerGroupTypeFeature (server_group_type_id, feature_id,
                                       created, modified)
values (lookup_sg_type('enterprise_entitled'), lookup_feature_type('ftr_system_custom_values'),
        current_timestamp,current_timestamp);

insert into rhnServerGroupTypeFeature (server_group_type_id, feature_id,
                                       created, modified)
values (lookup_sg_type('enterprise_entitled'), lookup_feature_type('ftr_add_rm_addon_type'),
        current_timestamp,current_timestamp);

insert into rhnServerGroupTypeFeature (server_group_type_id, feature_id,
                                       created, modified)
values (lookup_sg_type('enterprise_entitled'), lookup_feature_type('ftr_system_lock'),
        current_timestamp,current_timestamp);

insert into rhnServerGroupTypeFeature (server_group_type_id, feature_id,
                                       created, modified)
values (lookup_sg_type('enterprise_entitled'), lookup_feature_type('ftr_system_audit'),
        current_timestamp,current_timestamp);

insert into rhnServerGroupTypeFeature (server_group_type_id, feature_id,
                                       created, modified)
values (lookup_sg_type('bootstrap_entitled'), lookup_feature_type('ftr_kickstart'),
        current_timestamp,current_timestamp);

insert into rhnServerGroupTypeFeature (server_group_type_id, feature_id,
                                       created, modified)
values (lookup_sg_type('bootstrap_entitled'), lookup_feature_type('ftr_power_management'),
        current_timestamp,current_timestamp);

insert into rhnServerGroupTypeFeature (server_group_type_id, feature_id,
                                       created, modified)
values (lookup_sg_type('bootstrap_entitled'), lookup_feature_type('ftr_system_grouping'),
        current_timestamp,current_timestamp);

-- salt entitlement features

insert into rhnServerGroupTypeFeature (server_group_type_id, feature_id,
                                       created, modified)
values (lookup_sg_type('salt_entitled'), lookup_feature_type('ftr_package_updates'),
        current_timestamp,current_timestamp);

insert into rhnServerGroupTypeFeature (server_group_type_id, feature_id,
                                       created, modified)
values (lookup_sg_type('salt_entitled'), lookup_feature_type('ftr_package_lock'),
        current_timestamp,current_timestamp);

insert into rhnServerGroupTypeFeature (server_group_type_id, feature_id,
                                       created, modified)
values (lookup_sg_type('salt_entitled'), lookup_feature_type('ftr_package_refresh'),
        current_timestamp,current_timestamp);

insert into rhnServerGroupTypeFeature (server_group_type_id, feature_id,
                                       created, modified)
values (lookup_sg_type('salt_entitled'), lookup_feature_type('ftr_package_remove'),
        current_timestamp,current_timestamp);

insert into rhnServerGroupTypeFeature (server_group_type_id, feature_id,
                                       created, modified)
values (lookup_sg_type('salt_entitled'), lookup_feature_type('ftr_profile_compare'),
        current_timestamp,current_timestamp);

insert into rhnServerGroupTypeFeature (server_group_type_id, feature_id,
                                       created, modified)
values (lookup_sg_type('salt_entitled'), lookup_feature_type('ftr_errata_updates'),
        current_timestamp,current_timestamp);

insert into rhnServerGroupTypeFeature (server_group_type_id, feature_id,
                                       created, modified)
values (lookup_sg_type('salt_entitled'), lookup_feature_type('ftr_auto_errata_updates'),
        current_timestamp,current_timestamp);

insert into rhnServerGroupTypeFeature (server_group_type_id, feature_id,
                                       created, modified)
values (lookup_sg_type('salt_entitled'), lookup_feature_type('ftr_daily_summary'),
        current_timestamp,current_timestamp);

insert into rhnServerGroupTypeFeature (server_group_type_id, feature_id,
                                       created, modified)
values (lookup_sg_type('salt_entitled'), lookup_feature_type('ftr_custom_info'),
        current_timestamp,current_timestamp);

insert into rhnServerGroupTypeFeature (server_group_type_id, feature_id,
                                       created, modified)
values (lookup_sg_type('salt_entitled'), lookup_feature_type('ftr_system_grouping'),
        current_timestamp,current_timestamp);

insert into rhnServerGroupTypeFeature (server_group_type_id, feature_id,
                                       created, modified)
values (lookup_sg_type('salt_entitled'), lookup_feature_type('ftr_reboot'),
        current_timestamp,current_timestamp);

insert into rhnServerGroupTypeFeature (server_group_type_id, feature_id,
                                       created, modified)
values (lookup_sg_type('salt_entitled'), lookup_feature_type('ftr_agent_smith'),
        current_timestamp,current_timestamp);

insert into rhnServerGroupTypeFeature (server_group_type_id, feature_id,
                                       created, modified)
values (lookup_sg_type('salt_entitled'), lookup_feature_type('ftr_remote_command'),
        current_timestamp,current_timestamp);

insert into rhnServerGroupTypeFeature (server_group_type_id, feature_id,
                                       created, modified)
values (lookup_sg_type('salt_entitled'), lookup_feature_type('ftr_hardware_refresh'),
        current_timestamp,current_timestamp);

insert into rhnServerGroupTypeFeature (server_group_type_id, feature_id,
                                       created, modified)
values (lookup_sg_type('salt_entitled'), lookup_feature_type('ftr_channel_membership'),
        current_timestamp,current_timestamp);
insert into rhnServerGroupTypeFeature (server_group_type_id, feature_id,
                                       created, modified)
values (lookup_sg_type('salt_entitled'), lookup_feature_type('ftr_channel_config_subscription'),
        current_timestamp,current_timestamp);
insert into rhnServerGroupTypeFeature (server_group_type_id, feature_id,
                                       created, modified)
values (lookup_sg_type('salt_entitled'), lookup_feature_type('ftr_channel_deploy_diff'),
        current_timestamp,current_timestamp);

insert into rhnServerGroupTypeFeature (server_group_type_id, feature_id,
                                       created, modified)
values (lookup_sg_type('salt_entitled'), lookup_feature_type('ftr_system_preferences'),
        current_timestamp,current_timestamp);

insert into rhnServerGroupTypeFeature (server_group_type_id, feature_id,
                                       created, modified)
values (lookup_sg_type('salt_entitled'), lookup_feature_type('ftr_system_custom_values'),
        current_timestamp,current_timestamp);

insert into rhnServerGroupTypeFeature (server_group_type_id, feature_id,
                                       created, modified)
values (lookup_sg_type('salt_entitled'), lookup_feature_type('ftr_system_audit'),
        current_timestamp,current_timestamp);

insert into rhnServerGroupTypeFeature (server_group_type_id, feature_id,
                                       created, modified)
values (lookup_sg_type('salt_entitled'), lookup_feature_type('ftr_kickstart'),
        current_timestamp,current_timestamp);

insert into rhnServerGroupTypeFeature (server_group_type_id, feature_id,
                                       created, modified)
values (lookup_sg_type('salt_entitled'), lookup_feature_type('ftr_power_management'),
        current_timestamp,current_timestamp);

insert into rhnServerGroupTypeFeature (server_group_type_id, feature_id,
                                       created, modified)
values (lookup_sg_type('salt_entitled'), lookup_feature_type('ftr_config'),
        current_timestamp,current_timestamp);
07070100000034000081B400000000000000000000000167AE111400005D31000000000000000000000000000000000000003E00000000susemanager-schema/common/data/rhnServerPackageArchCompat.sql --
-- Copyright (c) 2008--2015 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--

insert into rhnServerPackageArchCompat
(server_arch_id, package_arch_id, preference) values
(LOOKUP_SERVER_ARCH('i386-redhat-linux'), LOOKUP_PACKAGE_ARCH('i386'), 0);

insert into rhnServerPackageArchCompat
(server_arch_id, package_arch_id, preference) values
(LOOKUP_SERVER_ARCH('i386-redhat-linux'), LOOKUP_PACKAGE_ARCH('noarch'), 1000);

insert into rhnServerPackageArchCompat
(server_arch_id, package_arch_id, preference) values
(LOOKUP_SERVER_ARCH('i386-debian-linux'), LOOKUP_PACKAGE_ARCH('i386-deb'), 0);

insert into rhnServerPackageArchCompat
(server_arch_id, package_arch_id, preference) values
(LOOKUP_SERVER_ARCH('i386-debian-linux'), LOOKUP_PACKAGE_ARCH('all-deb'), 1000);

insert into rhnServerPackageArchCompat
(server_arch_id, package_arch_id, preference) values
(LOOKUP_SERVER_ARCH('i486-redhat-linux'), LOOKUP_PACKAGE_ARCH('i486'), 0);

insert into rhnServerPackageArchCompat
(server_arch_id, package_arch_id, preference) values
(LOOKUP_SERVER_ARCH('i486-redhat-linux'), LOOKUP_PACKAGE_ARCH('i386'), 10);

insert into rhnServerPackageArchCompat
(server_arch_id, package_arch_id, preference) values
(LOOKUP_SERVER_ARCH('i486-redhat-linux'), LOOKUP_PACKAGE_ARCH('noarch'), 1000);

insert into rhnServerPackageArchCompat
(server_arch_id, package_arch_id, preference) values
(LOOKUP_SERVER_ARCH('i586-redhat-linux'), LOOKUP_PACKAGE_ARCH('i586'), 0);

insert into rhnServerPackageArchCompat
(server_arch_id, package_arch_id, preference) values
(LOOKUP_SERVER_ARCH('i586-redhat-linux'), LOOKUP_PACKAGE_ARCH('i486'), 10);

insert into rhnServerPackageArchCompat
(server_arch_id, package_arch_id, preference) values
(LOOKUP_SERVER_ARCH('i586-redhat-linux'), LOOKUP_PACKAGE_ARCH('i386'), 20);

insert into rhnServerPackageArchCompat
(server_arch_id, package_arch_id, preference) values
(LOOKUP_SERVER_ARCH('i586-redhat-linux'), LOOKUP_PACKAGE_ARCH('noarch'), 1000);

insert into rhnServerPackageArchCompat
(server_arch_id, package_arch_id, preference) values
(LOOKUP_SERVER_ARCH('i686-redhat-linux'), LOOKUP_PACKAGE_ARCH('i686'), 0);

insert into rhnServerPackageArchCompat
(server_arch_id, package_arch_id, preference) values
(LOOKUP_SERVER_ARCH('i686-redhat-linux'), LOOKUP_PACKAGE_ARCH('i586'), 10);

insert into rhnServerPackageArchCompat
(server_arch_id, package_arch_id, preference) values
(LOOKUP_SERVER_ARCH('i686-redhat-linux'), LOOKUP_PACKAGE_ARCH('i486'), 20);

insert into rhnServerPackageArchCompat
(server_arch_id, package_arch_id, preference) values
(LOOKUP_SERVER_ARCH('i686-redhat-linux'), LOOKUP_PACKAGE_ARCH('i386'), 30);

insert into rhnServerPackageArchCompat
(server_arch_id, package_arch_id, preference) values
(LOOKUP_SERVER_ARCH('i686-redhat-linux'), LOOKUP_PACKAGE_ARCH('noarch'), 1000);


insert into rhnServerPackageArchCompat
(server_arch_id, package_arch_id, preference) values
(LOOKUP_SERVER_ARCH('aarch64-redhat-linux'), LOOKUP_PACKAGE_ARCH('aarch64'), 0);
insert into rhnServerPackageArchCompat
(server_arch_id, package_arch_id, preference) values
(LOOKUP_SERVER_ARCH('aarch64-redhat-linux'), LOOKUP_PACKAGE_ARCH('noarch'), 1000);


insert into rhnServerPackageArchCompat
(server_arch_id, package_arch_id, preference) values
(LOOKUP_SERVER_ARCH('armv7l-redhat-linux'), LOOKUP_PACKAGE_ARCH('armv7hnl'), 0);

insert into rhnServerPackageArchCompat
(server_arch_id, package_arch_id, preference) values
(LOOKUP_SERVER_ARCH('armv7l-redhat-linux'), LOOKUP_PACKAGE_ARCH('armv7hl'), 10);

insert into rhnServerPackageArchCompat
(server_arch_id, package_arch_id, preference) values
(LOOKUP_SERVER_ARCH('armv7l-redhat-linux'), LOOKUP_PACKAGE_ARCH('armv7l'), 20);

insert into rhnServerPackageArchCompat
(server_arch_id, package_arch_id, preference) values
(LOOKUP_SERVER_ARCH('armv7l-redhat-linux'), LOOKUP_PACKAGE_ARCH('armv6hl'), 25);

insert into rhnServerPackageArchCompat
(server_arch_id, package_arch_id, preference) values
(LOOKUP_SERVER_ARCH('armv7l-redhat-linux'), LOOKUP_PACKAGE_ARCH('armv6l'), 30);

insert into rhnServerPackageArchCompat
(server_arch_id, package_arch_id, preference) values
(LOOKUP_SERVER_ARCH('armv7l-redhat-linux'), LOOKUP_PACKAGE_ARCH('armv5tel'), 40);

insert into rhnServerPackageArchCompat
(server_arch_id, package_arch_id, preference) values
(LOOKUP_SERVER_ARCH('armv7l-redhat-linux'), LOOKUP_PACKAGE_ARCH('noarch'), 1000);


insert into rhnServerPackageArchCompat
(server_arch_id, package_arch_id, preference) values
(LOOKUP_SERVER_ARCH('armv5tejl-redhat-linux'), LOOKUP_PACKAGE_ARCH('armv5tel'), 0);

insert into rhnServerPackageArchCompat
(server_arch_id, package_arch_id, preference) values
(LOOKUP_SERVER_ARCH('armv5tejl-redhat-linux'), LOOKUP_PACKAGE_ARCH('noarch'), 1000);


insert into rhnServerPackageArchCompat
(server_arch_id, package_arch_id, preference) values
(LOOKUP_SERVER_ARCH('armv6l-redhat-linux'), LOOKUP_PACKAGE_ARCH('armv6l'), 0);

insert into rhnServerPackageArchCompat
(server_arch_id, package_arch_id, preference) values
(LOOKUP_SERVER_ARCH('armv6l-redhat-linux'), LOOKUP_PACKAGE_ARCH('armv5tel'), 10);

insert into rhnServerPackageArchCompat
(server_arch_id, package_arch_id, preference) values
(LOOKUP_SERVER_ARCH('armv6l-redhat-linux'), LOOKUP_PACKAGE_ARCH('noarch'), 1000);


insert into rhnServerPackageArchCompat
(server_arch_id, package_arch_id, preference) values
(LOOKUP_SERVER_ARCH('armv6hl-redhat-linux'), LOOKUP_PACKAGE_ARCH('armv6hl'), 0);

insert into rhnServerPackageArchCompat
(server_arch_id, package_arch_id, preference) values
(LOOKUP_SERVER_ARCH('armv6hl-redhat-linux'), LOOKUP_PACKAGE_ARCH('armv6l'), 10);

insert into rhnServerPackageArchCompat
(server_arch_id, package_arch_id, preference) values
(LOOKUP_SERVER_ARCH('armv6hl-redhat-linux'), LOOKUP_PACKAGE_ARCH('armv5tel'), 20);

insert into rhnServerPackageArchCompat
(server_arch_id, package_arch_id, preference) values
(LOOKUP_SERVER_ARCH('armv6hl-redhat-linux'), LOOKUP_PACKAGE_ARCH('noarch'), 1000);



insert into rhnServerPackageArchCompat
(server_arch_id, package_arch_id, preference) values
(LOOKUP_SERVER_ARCH('athlon-redhat-linux'), LOOKUP_PACKAGE_ARCH('athlon'), 0);

insert into rhnServerPackageArchCompat
(server_arch_id, package_arch_id, preference) values
(LOOKUP_SERVER_ARCH('athlon-redhat-linux'), LOOKUP_PACKAGE_ARCH('i686'), 10);

insert into rhnServerPackageArchCompat
(server_arch_id, package_arch_id, preference) values
(LOOKUP_SERVER_ARCH('athlon-redhat-linux'), LOOKUP_PACKAGE_ARCH('i586'), 20);

insert into rhnServerPackageArchCompat
(server_arch_id, package_arch_id, preference) values
(LOOKUP_SERVER_ARCH('athlon-redhat-linux'), LOOKUP_PACKAGE_ARCH('i486'), 30);

insert into rhnServerPackageArchCompat
(server_arch_id, package_arch_id, preference) values
(LOOKUP_SERVER_ARCH('athlon-redhat-linux'), LOOKUP_PACKAGE_ARCH('i386'), 40);

insert into rhnServerPackageArchCompat
(server_arch_id, package_arch_id, preference) values
(LOOKUP_SERVER_ARCH('athlon-redhat-linux'), LOOKUP_PACKAGE_ARCH('noarch'), 1000);

insert into rhnServerPackageArchCompat
(server_arch_id, package_arch_id, preference) values
(LOOKUP_SERVER_ARCH('alpha-redhat-linux'), LOOKUP_PACKAGE_ARCH('alpha'), 0);

insert into rhnServerPackageArchCompat
(server_arch_id, package_arch_id, preference) values
(LOOKUP_SERVER_ARCH('alpha-redhat-linux'), LOOKUP_PACKAGE_ARCH('noarch'), 1000);

insert into rhnServerPackageArchCompat
(server_arch_id, package_arch_id, preference) values
(LOOKUP_SERVER_ARCH('alpha-debian-linux'), LOOKUP_PACKAGE_ARCH('alpha-deb'), 0);

insert into rhnServerPackageArchCompat
(server_arch_id, package_arch_id, preference) values
(LOOKUP_SERVER_ARCH('alpha-debian-linux'), LOOKUP_PACKAGE_ARCH('all-deb'), 1000);

insert into rhnServerPackageArchCompat
(server_arch_id, package_arch_id, preference) values
(LOOKUP_SERVER_ARCH('alphaev6-redhat-linux'), LOOKUP_PACKAGE_ARCH('alphaev6'), 0);

insert into rhnServerPackageArchCompat
(server_arch_id, package_arch_id, preference) values
(LOOKUP_SERVER_ARCH('alphaev6-redhat-linux'), LOOKUP_PACKAGE_ARCH('alpha'), 10);

insert into rhnServerPackageArchCompat
(server_arch_id, package_arch_id, preference) values
(LOOKUP_SERVER_ARCH('alphaev6-redhat-linux'), LOOKUP_PACKAGE_ARCH('noarch'), 1000);

insert into rhnServerPackageArchCompat
(server_arch_id, package_arch_id, preference) values
(LOOKUP_SERVER_ARCH('ia64-redhat-linux'), LOOKUP_PACKAGE_ARCH('ia64'), 0);

insert into rhnServerPackageArchCompat
(server_arch_id, package_arch_id, preference) values
(LOOKUP_SERVER_ARCH('ia64-redhat-linux'), LOOKUP_PACKAGE_ARCH('i386'), 100);

insert into rhnServerPackageArchCompat
(server_arch_id, package_arch_id, preference) values
(LOOKUP_SERVER_ARCH('ia64-redhat-linux'), LOOKUP_PACKAGE_ARCH('i486'), 200);

insert into rhnServerPackageArchCompat
(server_arch_id, package_arch_id, preference) values
(LOOKUP_SERVER_ARCH('ia64-redhat-linux'), LOOKUP_PACKAGE_ARCH('i586'), 300);

insert into rhnServerPackageArchCompat
(server_arch_id, package_arch_id, preference) values
(LOOKUP_SERVER_ARCH('ia64-redhat-linux'), LOOKUP_PACKAGE_ARCH('i686'), 400);

insert into rhnServerPackageArchCompat
(server_arch_id, package_arch_id, preference) values
(LOOKUP_SERVER_ARCH('ia64-redhat-linux'), LOOKUP_PACKAGE_ARCH('noarch'), 1000);

insert into rhnServerPackageArchCompat
(server_arch_id, package_arch_id, preference) values
(LOOKUP_SERVER_ARCH('ia64-debian-linux'), LOOKUP_PACKAGE_ARCH('ia64-deb'), 0);

insert into rhnServerPackageArchCompat
(server_arch_id, package_arch_id, preference) values
(LOOKUP_SERVER_ARCH('ia64-debian-linux'), LOOKUP_PACKAGE_ARCH('i386-deb'), 100);

insert into rhnServerPackageArchCompat
(server_arch_id, package_arch_id, preference) values
(LOOKUP_SERVER_ARCH('ia64-debian-linux'), LOOKUP_PACKAGE_ARCH('all-deb'), 1000);

insert into rhnServerPackageArchCompat
(server_arch_id, package_arch_id, preference) values
(LOOKUP_SERVER_ARCH('sparc-redhat-linux'), LOOKUP_PACKAGE_ARCH('sparc'), 0);

insert into rhnServerPackageArchCompat
(server_arch_id, package_arch_id, preference) values
(LOOKUP_SERVER_ARCH('sparc-redhat-linux'), LOOKUP_PACKAGE_ARCH('noarch'), 1000);

insert into rhnServerPackageArchCompat
(server_arch_id, package_arch_id, preference) values
(LOOKUP_SERVER_ARCH('sparc-debian-linux'), LOOKUP_PACKAGE_ARCH('sparc-deb'), 0);

insert into rhnServerPackageArchCompat
(server_arch_id, package_arch_id, preference) values
(LOOKUP_SERVER_ARCH('sparc-debian-linux'), LOOKUP_PACKAGE_ARCH('all-deb'), 1000);

insert into rhnServerPackageArchCompat
(server_arch_id, package_arch_id, preference) values
(LOOKUP_SERVER_ARCH('sparcv9-redhat-linux'), LOOKUP_PACKAGE_ARCH('sparcv9'), 0);

insert into rhnServerPackageArchCompat
(server_arch_id, package_arch_id, preference) values
(LOOKUP_SERVER_ARCH('sparcv9-redhat-linux'), LOOKUP_PACKAGE_ARCH('sparc'), 10);

insert into rhnServerPackageArchCompat
(server_arch_id, package_arch_id, preference) values
(LOOKUP_SERVER_ARCH('sparcv9-redhat-linux'), LOOKUP_PACKAGE_ARCH('noarch'), 1000);

insert into rhnServerPackageArchCompat
(server_arch_id, package_arch_id, preference) values
(LOOKUP_SERVER_ARCH('sparc64-redhat-linux'), LOOKUP_PACKAGE_ARCH('sparc64'), 0);

insert into rhnServerPackageArchCompat
(server_arch_id, package_arch_id, preference) values
(LOOKUP_SERVER_ARCH('sparc64-redhat-linux'), LOOKUP_PACKAGE_ARCH('sparcv9'), 10);

insert into rhnServerPackageArchCompat
(server_arch_id, package_arch_id, preference) values
(LOOKUP_SERVER_ARCH('sparc64-redhat-linux'), LOOKUP_PACKAGE_ARCH('sparc'), 20);

insert into rhnServerPackageArchCompat
(server_arch_id, package_arch_id, preference) values
(LOOKUP_SERVER_ARCH('sparc64-redhat-linux'), LOOKUP_PACKAGE_ARCH('noarch'), 1000);

insert into rhnServerPackageArchCompat
(server_arch_id, package_arch_id, preference) values
(LOOKUP_SERVER_ARCH('s390-redhat-linux'), LOOKUP_PACKAGE_ARCH('s390'), 0);

insert into rhnServerPackageArchCompat
(server_arch_id, package_arch_id, preference) values
(LOOKUP_SERVER_ARCH('s390-redhat-linux'), LOOKUP_PACKAGE_ARCH('noarch'), 1000);

insert into rhnServerPackageArchCompat
(server_arch_id, package_arch_id, preference) values
(LOOKUP_SERVER_ARCH('s390-debian-linux'), LOOKUP_PACKAGE_ARCH('s390-deb'), 0);

insert into rhnServerPackageArchCompat
(server_arch_id, package_arch_id, preference) values
(LOOKUP_SERVER_ARCH('s390-debian-linux'), LOOKUP_PACKAGE_ARCH('all-deb'), 1000);

insert into rhnServerPackageArchCompat
(server_arch_id, package_arch_id, preference) values
(LOOKUP_SERVER_ARCH('s390x-redhat-linux'), LOOKUP_PACKAGE_ARCH('s390x'), 0);

insert into rhnServerPackageArchCompat
(server_arch_id, package_arch_id, preference) values
(LOOKUP_SERVER_ARCH('s390x-redhat-linux'), LOOKUP_PACKAGE_ARCH('s390'), 10);

insert into rhnServerPackageArchCompat
(server_arch_id, package_arch_id, preference) values
(LOOKUP_SERVER_ARCH('s390x-redhat-linux'), LOOKUP_PACKAGE_ARCH('noarch'), 1000);


insert into rhnServerPackageArchCompat
(server_arch_id, package_arch_id, preference) values
(LOOKUP_SERVER_ARCH('ppc-redhat-linux'), LOOKUP_PACKAGE_ARCH('ppc'), 0);

insert into rhnServerPackageArchCompat
(server_arch_id, package_arch_id, preference) values
(LOOKUP_SERVER_ARCH('ppc-redhat-linux'), LOOKUP_PACKAGE_ARCH('noarch'), 1000);

insert into rhnServerPackageArchCompat
(server_arch_id, package_arch_id, preference) values
(LOOKUP_SERVER_ARCH('powerpc-debian-linux'), LOOKUP_PACKAGE_ARCH('powerpc-deb'), 0);

insert into rhnServerPackageArchCompat
(server_arch_id, package_arch_id, preference) values
(LOOKUP_SERVER_ARCH('powerpc-debian-linux'), LOOKUP_PACKAGE_ARCH('all-deb'), 1000);

insert into rhnServerPackageArchCompat
(server_arch_id, package_arch_id, preference) values
(LOOKUP_SERVER_ARCH('arm-debian-linux'), LOOKUP_PACKAGE_ARCH('arm-deb'), 0);

insert into rhnServerPackageArchCompat
(server_arch_id, package_arch_id, preference) values
(LOOKUP_SERVER_ARCH('arm-debian-linux'), LOOKUP_PACKAGE_ARCH('all-deb'), 1000);

insert into rhnServerPackageArchCompat
(server_arch_id, package_arch_id, preference) values
(LOOKUP_SERVER_ARCH('armv6l-debian-linux'), LOOKUP_PACKAGE_ARCH('armhf-deb'), 0);

insert into rhnServerPackageArchCompat
(server_arch_id, package_arch_id, preference) values
(LOOKUP_SERVER_ARCH('armv6l-debian-linux'), LOOKUP_PACKAGE_ARCH('all-deb'), 1000);

insert into rhnServerPackageArchCompat
(server_arch_id, package_arch_id, preference) values
(LOOKUP_SERVER_ARCH('mips-debian-linux'), LOOKUP_PACKAGE_ARCH('mips-deb'), 0);

insert into rhnServerPackageArchCompat
(server_arch_id, package_arch_id, preference) values
(LOOKUP_SERVER_ARCH('mips-debian-linux'), LOOKUP_PACKAGE_ARCH('all-deb'), 1000);

insert into rhnServerPackageArchCompat
(server_arch_id, package_arch_id, preference) values
(LOOKUP_SERVER_ARCH('ppc64-redhat-linux'), LOOKUP_PACKAGE_ARCH('ppc64'), 0);

insert into rhnServerPackageArchCompat
(server_arch_id, package_arch_id, preference) values
(LOOKUP_SERVER_ARCH('ppc64-redhat-linux'), LOOKUP_PACKAGE_ARCH('ppc'), 10);

insert into rhnServerPackageArchCompat
(server_arch_id, package_arch_id, preference) values
(LOOKUP_SERVER_ARCH('ppc64-redhat-linux'), LOOKUP_PACKAGE_ARCH('noarch'), 1000);

insert into rhnServerPackageArchCompat
(server_arch_id, package_arch_id, preference) values
(LOOKUP_SERVER_ARCH('ppc64le-redhat-linux'), LOOKUP_PACKAGE_ARCH('ppc64le'), 0);

insert into rhnServerPackageArchCompat
(server_arch_id, package_arch_id, preference) values
(LOOKUP_SERVER_ARCH('ppc64le-redhat-linux'), LOOKUP_PACKAGE_ARCH('noarch'), 1000);

insert into rhnServerPackageArchCompat
(server_arch_id, package_arch_id, preference) values
(LOOKUP_SERVER_ARCH('pSeries-redhat-linux'), LOOKUP_PACKAGE_ARCH('pSeries'), 0);

insert into rhnServerPackageArchCompat
(server_arch_id, package_arch_id, preference) values
(LOOKUP_SERVER_ARCH('pSeries-redhat-linux'), LOOKUP_PACKAGE_ARCH('ppc64'), 10);

insert into rhnServerPackageArchCompat
(server_arch_id, package_arch_id, preference) values
(LOOKUP_SERVER_ARCH('pSeries-redhat-linux'), LOOKUP_PACKAGE_ARCH('ppc'), 20);

insert into rhnServerPackageArchCompat
(server_arch_id, package_arch_id, preference) values
(LOOKUP_SERVER_ARCH('pSeries-redhat-linux'), LOOKUP_PACKAGE_ARCH('noarch'), 1000);

insert into rhnServerPackageArchCompat
(server_arch_id, package_arch_id, preference) values
(LOOKUP_SERVER_ARCH('iSeries-redhat-linux'), LOOKUP_PACKAGE_ARCH('iSeries'), 0);

insert into rhnServerPackageArchCompat
(server_arch_id, package_arch_id, preference) values
(LOOKUP_SERVER_ARCH('iSeries-redhat-linux'), LOOKUP_PACKAGE_ARCH('ppc64'), 10);

insert into rhnServerPackageArchCompat
(server_arch_id, package_arch_id, preference) values
(LOOKUP_SERVER_ARCH('iSeries-redhat-linux'), LOOKUP_PACKAGE_ARCH('ppc'), 20);

insert into rhnServerPackageArchCompat
(server_arch_id, package_arch_id, preference) values
(LOOKUP_SERVER_ARCH('iSeries-redhat-linux'), LOOKUP_PACKAGE_ARCH('noarch'), 1000);

insert into rhnServerPackageArchCompat
(server_arch_id, package_arch_id, preference) values
(LOOKUP_SERVER_ARCH('x86_64-redhat-linux'), LOOKUP_PACKAGE_ARCH('x86_64'), 0);

insert into rhnServerPackageArchCompat
(server_arch_id, package_arch_id, preference) values
(LOOKUP_SERVER_ARCH('x86_64-redhat-linux'), LOOKUP_PACKAGE_ARCH('athlon'), 100);

insert into rhnServerPackageArchCompat
(server_arch_id, package_arch_id, preference) values
(LOOKUP_SERVER_ARCH('x86_64-redhat-linux'), LOOKUP_PACKAGE_ARCH('i686'), 110);

insert into rhnServerPackageArchCompat
(server_arch_id, package_arch_id, preference) values
(LOOKUP_SERVER_ARCH('x86_64-redhat-linux'), LOOKUP_PACKAGE_ARCH('i586'), 120);

insert into rhnServerPackageArchCompat
(server_arch_id, package_arch_id, preference) values
(LOOKUP_SERVER_ARCH('x86_64-redhat-linux'), LOOKUP_PACKAGE_ARCH('i486'), 130);

insert into rhnServerPackageArchCompat
(server_arch_id, package_arch_id, preference) values
(LOOKUP_SERVER_ARCH('x86_64-redhat-linux'), LOOKUP_PACKAGE_ARCH('i386'), 140);

insert into rhnServerPackageArchCompat
(server_arch_id, package_arch_id, preference) values
(LOOKUP_SERVER_ARCH('x86_64-redhat-linux'), LOOKUP_PACKAGE_ARCH('noarch'), 1000);

insert into rhnServerPackageArchCompat
(server_arch_id, package_arch_id, preference) values
(LOOKUP_SERVER_ARCH('amd64-redhat-linux'), LOOKUP_PACKAGE_ARCH('amd64'), 0);

insert into rhnServerPackageArchCompat
(server_arch_id, package_arch_id, preference) values
(LOOKUP_SERVER_ARCH('amd64-redhat-linux'), LOOKUP_PACKAGE_ARCH('x86_64'), 50);

insert into rhnServerPackageArchCompat
(server_arch_id, package_arch_id, preference) values
(LOOKUP_SERVER_ARCH('amd64-redhat-linux'), LOOKUP_PACKAGE_ARCH('athlon'), 100);

insert into rhnServerPackageArchCompat
(server_arch_id, package_arch_id, preference) values
(LOOKUP_SERVER_ARCH('amd64-redhat-linux'), LOOKUP_PACKAGE_ARCH('i686'), 110);

insert into rhnServerPackageArchCompat
(server_arch_id, package_arch_id, preference) values
(LOOKUP_SERVER_ARCH('amd64-redhat-linux'), LOOKUP_PACKAGE_ARCH('i586'), 120);

insert into rhnServerPackageArchCompat
(server_arch_id, package_arch_id, preference) values
(LOOKUP_SERVER_ARCH('amd64-redhat-linux'), LOOKUP_PACKAGE_ARCH('i486'), 130);

insert into rhnServerPackageArchCompat
(server_arch_id, package_arch_id, preference) values
(LOOKUP_SERVER_ARCH('amd64-redhat-linux'), LOOKUP_PACKAGE_ARCH('i386'), 140);

insert into rhnServerPackageArchCompat
(server_arch_id, package_arch_id, preference) values
(LOOKUP_SERVER_ARCH('amd64-redhat-linux'), LOOKUP_PACKAGE_ARCH('noarch'), 1000);

insert into rhnServerPackageArchCompat
(server_arch_id, package_arch_id, preference) values
(LOOKUP_SERVER_ARCH('amd64-debian-linux'), LOOKUP_PACKAGE_ARCH('amd64-deb'), 0);

insert into rhnServerPackageArchCompat
(server_arch_id, package_arch_id, preference) values
(LOOKUP_SERVER_ARCH('amd64-debian-linux'), LOOKUP_PACKAGE_ARCH('i386-deb'), 140);

insert into rhnServerPackageArchCompat
(server_arch_id, package_arch_id, preference) values
(LOOKUP_SERVER_ARCH('amd64-debian-linux'), LOOKUP_PACKAGE_ARCH('all-deb'), 1000);

insert into rhnServerPackageArchCompat
(server_arch_id, package_arch_id, preference) values
(LOOKUP_SERVER_ARCH('ia32e-redhat-linux'), LOOKUP_PACKAGE_ARCH('ia32e'), 0);

insert into rhnServerPackageArchCompat
(server_arch_id, package_arch_id, preference) values
(LOOKUP_SERVER_ARCH('ia32e-redhat-linux'), LOOKUP_PACKAGE_ARCH('x86_64'), 50);

insert into rhnServerPackageArchCompat
(server_arch_id, package_arch_id, preference) values
(LOOKUP_SERVER_ARCH('ia32e-redhat-linux'), LOOKUP_PACKAGE_ARCH('athlon'), 100);

insert into rhnServerPackageArchCompat
(server_arch_id, package_arch_id, preference) values
(LOOKUP_SERVER_ARCH('ia32e-redhat-linux'), LOOKUP_PACKAGE_ARCH('i686'), 110);

insert into rhnServerPackageArchCompat
(server_arch_id, package_arch_id, preference) values
(LOOKUP_SERVER_ARCH('ia32e-redhat-linux'), LOOKUP_PACKAGE_ARCH('i586'), 120);

insert into rhnServerPackageArchCompat
(server_arch_id, package_arch_id, preference) values
(LOOKUP_SERVER_ARCH('ia32e-redhat-linux'), LOOKUP_PACKAGE_ARCH('i486'), 130);

insert into rhnServerPackageArchCompat
(server_arch_id, package_arch_id, preference) values
(LOOKUP_SERVER_ARCH('ia32e-redhat-linux'), LOOKUP_PACKAGE_ARCH('i386'), 140);

insert into rhnServerPackageArchCompat
(server_arch_id, package_arch_id, preference) values
(LOOKUP_SERVER_ARCH('ia32e-redhat-linux'), LOOKUP_PACKAGE_ARCH('noarch'), 1000);


insert into rhnServerPackageArchCompat
(server_arch_id, package_arch_id, preference) values
(LOOKUP_SERVER_ARCH('ppc64iseries-redhat-linux'), LOOKUP_PACKAGE_ARCH('ppc64iseries'), 0);

insert into rhnServerPackageArchCompat
(server_arch_id, package_arch_id, preference) values
(LOOKUP_SERVER_ARCH('ppc64iseries-redhat-linux'), LOOKUP_PACKAGE_ARCH('ppc64'), 10);

insert into rhnServerPackageArchCompat
(server_arch_id, package_arch_id, preference) values
(LOOKUP_SERVER_ARCH('ppc64iseries-redhat-linux'), LOOKUP_PACKAGE_ARCH('ppc'), 20);

insert into rhnServerPackageArchCompat
(server_arch_id, package_arch_id, preference) values
(LOOKUP_SERVER_ARCH('ppc64iseries-redhat-linux'), LOOKUP_PACKAGE_ARCH('noarch'), 1000);

insert into rhnServerPackageArchCompat
(server_arch_id, package_arch_id, preference) values
(LOOKUP_SERVER_ARCH('ppc64pseries-redhat-linux'), LOOKUP_PACKAGE_ARCH('ppc64pseries'), 0);

insert into rhnServerPackageArchCompat
(server_arch_id, package_arch_id, preference) values
(LOOKUP_SERVER_ARCH('ppc64pseries-redhat-linux'), LOOKUP_PACKAGE_ARCH('ppc64'), 10);

insert into rhnServerPackageArchCompat
(server_arch_id, package_arch_id, preference) values
(LOOKUP_SERVER_ARCH('ppc64pseries-redhat-linux'), LOOKUP_PACKAGE_ARCH('ppc'), 20);

insert into rhnServerPackageArchCompat
(server_arch_id, package_arch_id, preference) values
(LOOKUP_SERVER_ARCH('ppc64pseries-redhat-linux'), LOOKUP_PACKAGE_ARCH('noarch'), 1000);

insert into rhnServerPackageArchCompat
(server_arch_id, package_arch_id, preference) values
(LOOKUP_SERVER_ARCH('armv7l-debian-linux'), LOOKUP_PACKAGE_ARCH('armhf-deb'), 0);

insert into rhnServerPackageArchCompat
(server_arch_id, package_arch_id, preference) values
(LOOKUP_SERVER_ARCH('arm64-debian-linux'), LOOKUP_PACKAGE_ARCH('arm64-deb'), 0);

insert into rhnServerPackageArchCompat
(server_arch_id, package_arch_id, preference) values
(LOOKUP_SERVER_ARCH('arm64-debian-linux'), LOOKUP_PACKAGE_ARCH('all-deb'), 1000);

commit;

   07070100000035000081B400000000000000000000000167AE1114000003C1000000000000000000000000000000000000003800000000susemanager-schema/common/data/rhnServerProfileType.sql   --
-- Copyright (c) 2008--2013 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--

insert into rhnServerProfileType(id, label, name) values (
	sequence_nextval('rhn_sproftype_id_seq'), 'normal',
	'A normal server profile');

insert into rhnServerProfileType(id, label, name) values (
	sequence_nextval('rhn_sproftype_id_seq'), 'sync_profile',
	'A server profile associated with a package sync');

commit;
   07070100000036000081B400000000000000000000000167AE11140000A61D000000000000000000000000000000000000004200000000susemanager-schema/common/data/rhnServerServerGroupArchCompat.sql --
-- Copyright (c) 2008--2015 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--

-- insert 
-- into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
-- values (lookup_server_arch(''), lookup_sg_type(''));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('i386-redhat-linux'), 
            lookup_sg_type('enterprise_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('i386-debian-linux'),
            lookup_sg_type('enterprise_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('i486-redhat-linux'), 
            lookup_sg_type('enterprise_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('i586-redhat-linux'), 
            lookup_sg_type('enterprise_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('i686-redhat-linux'), 
            lookup_sg_type('enterprise_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('athlon-redhat-linux'), 
            lookup_sg_type('enterprise_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('alpha-redhat-linux'), 
            lookup_sg_type('enterprise_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('alpha-debian-linux'),
            lookup_sg_type('enterprise_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('alphaev6-redhat-linux'), 
            lookup_sg_type('enterprise_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('ia64-redhat-linux'), 
            lookup_sg_type('enterprise_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('ia64-debian-linux'),
            lookup_sg_type('enterprise_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('sparc-redhat-linux'), 
            lookup_sg_type('enterprise_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('sparc-debian-linux'),
            lookup_sg_type('enterprise_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('sparcv9-redhat-linux'), 
            lookup_sg_type('enterprise_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('sparc64-redhat-linux'), 
            lookup_sg_type('enterprise_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('s390-redhat-linux'), 
            lookup_sg_type('enterprise_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
        values (lookup_server_arch('aarch64-redhat-linux'),
            lookup_sg_type('enterprise_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
        values (lookup_server_arch('armv7l-redhat-linux'),
            lookup_sg_type('enterprise_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
        values (lookup_server_arch('armv5tejl-redhat-linux'),
            lookup_sg_type('enterprise_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
        values (lookup_server_arch('armv6l-redhat-linux'),
            lookup_sg_type('enterprise_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
        values (lookup_server_arch('armv6hl-redhat-linux'),
            lookup_sg_type('enterprise_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('s390-debian-linux'),
            lookup_sg_type('enterprise_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('s390x-redhat-linux'), 
            lookup_sg_type('enterprise_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('ppc-redhat-linux'), 
            lookup_sg_type('enterprise_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('powerpc-debian-linux'),
            lookup_sg_type('enterprise_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('ppc64-redhat-linux'), 
            lookup_sg_type('enterprise_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
    values (lookup_server_arch('ppc64le-redhat-linux'),
            lookup_sg_type('enterprise_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('pSeries-redhat-linux'), 
            lookup_sg_type('enterprise_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('iSeries-redhat-linux'), 
            lookup_sg_type('enterprise_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('x86_64-redhat-linux'), 
            lookup_sg_type('enterprise_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('ia32e-redhat-linux'), 
            lookup_sg_type('enterprise_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('amd64-redhat-linux'), 
            lookup_sg_type('enterprise_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('amd64-debian-linux'),
            lookup_sg_type('enterprise_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('arm64-debian-linux'),
            lookup_sg_type('enterprise_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('ppc64iseries-redhat-linux'), 
            lookup_sg_type('enterprise_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('ppc64pseries-redhat-linux'), 
            lookup_sg_type('enterprise_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('arm-debian-linux'),
            lookup_sg_type('enterprise_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('armv6l-debian-linux'),
            lookup_sg_type('enterprise_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('mips-debian-linux'),
            lookup_sg_type('enterprise_entitled'));

-- virtualization_host* compatibilities --

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type)
    values (lookup_server_arch('i386-redhat-linux'),
            lookup_sg_type('virtualization_host'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type)
    values (lookup_server_arch('i386-debian-linux'),
            lookup_sg_type('virtualization_host'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type)
    values (lookup_server_arch('i486-redhat-linux'), 
            lookup_sg_type('virtualization_host'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type)
    values (lookup_server_arch('i586-redhat-linux'), 
            lookup_sg_type('virtualization_host'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type)
    values (lookup_server_arch('i686-redhat-linux'), 
            lookup_sg_type('virtualization_host'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type)
    values (lookup_server_arch('athlon-redhat-linux'),
            lookup_sg_type('virtualization_host'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type)
    values (lookup_server_arch('amd64-redhat-linux'),
            lookup_sg_type('virtualization_host'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type)
    values (lookup_server_arch('amd64-debian-linux'),
            lookup_sg_type('virtualization_host'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type)
    values (lookup_server_arch('arm64-debian-linux'),
            lookup_sg_type('virtualization_host'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type)
    values (lookup_server_arch('ia64-redhat-linux'),
            lookup_sg_type('virtualization_host'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type)
    values (lookup_server_arch('ia64-debian-linux'),
            lookup_sg_type('virtualization_host'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type)
    values (lookup_server_arch('ia32e-redhat-linux'),
            lookup_sg_type('virtualization_host'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type)
    values (lookup_server_arch('s390-redhat-linux'),
            lookup_sg_type('virtualization_host'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
        values (lookup_server_arch('aarch64-redhat-linux'),
            lookup_sg_type('virtualization_host'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
        values (lookup_server_arch('armv7l-redhat-linux'),
            lookup_sg_type('virtualization_host'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
        values (lookup_server_arch('armv5tejl-redhat-linux'),
            lookup_sg_type('virtualization_host'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
        values (lookup_server_arch('armv6l-redhat-linux'),
            lookup_sg_type('virtualization_host'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
        values (lookup_server_arch('armv6hl-redhat-linux'),
            lookup_sg_type('virtualization_host'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type)
    values (lookup_server_arch('s390-debian-linux'),
            lookup_sg_type('virtualization_host'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type)
    values (lookup_server_arch('s390x-redhat-linux'),
            lookup_sg_type('virtualization_host'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type)
    values (lookup_server_arch('ppc-redhat-linux'),
            lookup_sg_type('virtualization_host'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type)
    values (lookup_server_arch('powerpc-debian-linux'),
            lookup_sg_type('virtualization_host'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type)
    values (lookup_server_arch('ppc64-redhat-linux'),
            lookup_sg_type('virtualization_host'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type)
    values (lookup_server_arch('ppc64le-redhat-linux'),
            lookup_sg_type('virtualization_host'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type)
    values (lookup_server_arch('x86_64-redhat-linux'),
            lookup_sg_type('virtualization_host'));

-- bootstrap entitlements

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('i386-redhat-linux'), 
            lookup_sg_type('bootstrap_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('i386-debian-linux'),
            lookup_sg_type('bootstrap_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('i486-redhat-linux'), 
            lookup_sg_type('bootstrap_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('i586-redhat-linux'), 
            lookup_sg_type('bootstrap_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('i686-redhat-linux'), 
            lookup_sg_type('bootstrap_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('athlon-redhat-linux'), 
            lookup_sg_type('bootstrap_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('alpha-redhat-linux'), 
            lookup_sg_type('bootstrap_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('alpha-debian-linux'),
            lookup_sg_type('bootstrap_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('alphaev6-redhat-linux'), 
            lookup_sg_type('bootstrap_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('ia64-redhat-linux'), 
            lookup_sg_type('bootstrap_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('ia64-debian-linux'),
            lookup_sg_type('bootstrap_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('sparc-redhat-linux'), 
            lookup_sg_type('bootstrap_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('sparc-debian-linux'),
            lookup_sg_type('bootstrap_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('sparcv9-redhat-linux'), 
            lookup_sg_type('bootstrap_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('sparc64-redhat-linux'), 
            lookup_sg_type('bootstrap_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('s390-redhat-linux'), 
            lookup_sg_type('bootstrap_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
        values (lookup_server_arch('armv7l-redhat-linux'),
            lookup_sg_type('bootstrap_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
        values (lookup_server_arch('armv5tejl-redhat-linux'),
            lookup_sg_type('bootstrap_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
        values (lookup_server_arch('armv6l-redhat-linux'),
            lookup_sg_type('bootstrap_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('s390-debian-linux'),
            lookup_sg_type('bootstrap_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('s390x-redhat-linux'), 
            lookup_sg_type('bootstrap_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('ppc-redhat-linux'), 
            lookup_sg_type('bootstrap_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('powerpc-debian-linux'),
            lookup_sg_type('bootstrap_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('ppc64-redhat-linux'), 
            lookup_sg_type('bootstrap_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
    values (lookup_server_arch('ppc64le-redhat-linux'),
            lookup_sg_type('bootstrap_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('pSeries-redhat-linux'), 
            lookup_sg_type('bootstrap_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('iSeries-redhat-linux'), 
            lookup_sg_type('bootstrap_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('x86_64-redhat-linux'), 
            lookup_sg_type('bootstrap_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('ia32e-redhat-linux'), 
            lookup_sg_type('bootstrap_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('amd64-redhat-linux'), 
            lookup_sg_type('bootstrap_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('amd64-debian-linux'),
            lookup_sg_type('bootstrap_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('arm64-debian-linux'),
            lookup_sg_type('bootstrap_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('ppc64iseries-redhat-linux'), 
            lookup_sg_type('bootstrap_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('ppc64pseries-redhat-linux'), 
            lookup_sg_type('bootstrap_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('arm-debian-linux'),
            lookup_sg_type('bootstrap_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('mips-debian-linux'),
            lookup_sg_type('bootstrap_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
    values (lookup_server_arch('armv7l-debian-linux'),
	    lookup_sg_type('enterprise_entitled'));

-- salt entitlement

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('i386-redhat-linux'),
            lookup_sg_type('salt_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('i386-debian-linux'),
            lookup_sg_type('salt_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('i486-redhat-linux'),
            lookup_sg_type('salt_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('i586-redhat-linux'),
            lookup_sg_type('salt_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('i686-redhat-linux'),
            lookup_sg_type('salt_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('athlon-redhat-linux'),
            lookup_sg_type('salt_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('alpha-redhat-linux'),
            lookup_sg_type('salt_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('alpha-debian-linux'),
            lookup_sg_type('salt_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('alphaev6-redhat-linux'),
            lookup_sg_type('salt_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('ia64-redhat-linux'),
            lookup_sg_type('salt_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('ia64-debian-linux'),
            lookup_sg_type('salt_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('sparc-redhat-linux'),
            lookup_sg_type('salt_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('sparc-debian-linux'),
            lookup_sg_type('salt_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('sparcv9-redhat-linux'),
            lookup_sg_type('salt_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('sparc64-redhat-linux'),
            lookup_sg_type('salt_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('s390-redhat-linux'),
            lookup_sg_type('salt_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
        values (lookup_server_arch('aarch64-redhat-linux'),
            lookup_sg_type('salt_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
        values (lookup_server_arch('armv7l-redhat-linux'),
            lookup_sg_type('salt_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
        values (lookup_server_arch('armv5tejl-redhat-linux'),
            lookup_sg_type('salt_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
        values (lookup_server_arch('armv6l-redhat-linux'),
            lookup_sg_type('salt_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
        values (lookup_server_arch('armv6hl-redhat-linux'),
            lookup_sg_type('salt_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('s390-debian-linux'),
            lookup_sg_type('salt_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('s390x-redhat-linux'),
            lookup_sg_type('salt_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('ppc-redhat-linux'),
            lookup_sg_type('salt_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('powerpc-debian-linux'),
            lookup_sg_type('salt_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('ppc64-redhat-linux'),
            lookup_sg_type('salt_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
    values (lookup_server_arch('ppc64le-redhat-linux'),
            lookup_sg_type('salt_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('pSeries-redhat-linux'),
            lookup_sg_type('salt_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('iSeries-redhat-linux'),
            lookup_sg_type('salt_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('x86_64-redhat-linux'),
            lookup_sg_type('salt_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('ia32e-redhat-linux'),
            lookup_sg_type('salt_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('amd64-redhat-linux'),
            lookup_sg_type('salt_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('amd64-debian-linux'),
            lookup_sg_type('salt_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('arm64-debian-linux'),
            lookup_sg_type('salt_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('ppc64iseries-redhat-linux'),
            lookup_sg_type('salt_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('ppc64pseries-redhat-linux'),
            lookup_sg_type('salt_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('arm-debian-linux'),
            lookup_sg_type('salt_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('armv6l-debian-linux'),
            lookup_sg_type('salt_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('mips-debian-linux'),
            lookup_sg_type('salt_entitled'));

-- foreign system entitlement

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('i386-redhat-linux'),
            lookup_sg_type('foreign_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('i386-debian-linux'),
            lookup_sg_type('foreign_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('i486-redhat-linux'),
            lookup_sg_type('foreign_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('i586-redhat-linux'),
            lookup_sg_type('foreign_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('i686-redhat-linux'),
            lookup_sg_type('foreign_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('athlon-redhat-linux'),
            lookup_sg_type('foreign_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('alpha-redhat-linux'),
            lookup_sg_type('foreign_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('alpha-debian-linux'),
            lookup_sg_type('foreign_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('alphaev6-redhat-linux'),
            lookup_sg_type('foreign_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('ia64-redhat-linux'),
            lookup_sg_type('foreign_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('ia64-debian-linux'),
            lookup_sg_type('foreign_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('sparc-redhat-linux'),
            lookup_sg_type('foreign_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('sparc-debian-linux'),
            lookup_sg_type('foreign_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('sparcv9-redhat-linux'),
            lookup_sg_type('foreign_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('sparc64-redhat-linux'),
            lookup_sg_type('foreign_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('s390-redhat-linux'),
            lookup_sg_type('foreign_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
        values (lookup_server_arch('aarch64-redhat-linux'),
            lookup_sg_type('foreign_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
        values (lookup_server_arch('armv7l-redhat-linux'),
            lookup_sg_type('foreign_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
        values (lookup_server_arch('armv5tejl-redhat-linux'),
            lookup_sg_type('foreign_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
        values (lookup_server_arch('armv6l-redhat-linux'),
            lookup_sg_type('foreign_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
        values (lookup_server_arch('armv6hl-redhat-linux'),
            lookup_sg_type('foreign_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('s390-debian-linux'),
            lookup_sg_type('foreign_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('s390x-redhat-linux'),
            lookup_sg_type('foreign_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('ppc-redhat-linux'),
            lookup_sg_type('foreign_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('powerpc-debian-linux'),
            lookup_sg_type('foreign_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('ppc64-redhat-linux'),
            lookup_sg_type('foreign_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
    values (lookup_server_arch('ppc64le-redhat-linux'),
            lookup_sg_type('foreign_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('pSeries-redhat-linux'),
            lookup_sg_type('foreign_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('iSeries-redhat-linux'),
            lookup_sg_type('foreign_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('x86_64-redhat-linux'),
            lookup_sg_type('foreign_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('ia32e-redhat-linux'),
            lookup_sg_type('foreign_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('amd64-redhat-linux'),
            lookup_sg_type('foreign_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('amd64-debian-linux'),
            lookup_sg_type('foreign_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('arm64-debian-linux'),
            lookup_sg_type('foreign_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('ppc64iseries-redhat-linux'),
            lookup_sg_type('foreign_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('ppc64pseries-redhat-linux'),
            lookup_sg_type('foreign_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('arm-debian-linux'),
            lookup_sg_type('foreign_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('armv6l-debian-linux'),
            lookup_sg_type('foreign_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('mips-debian-linux'),
            lookup_sg_type('foreign_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('cloud'),
            lookup_sg_type('foreign_entitled'));

-- container_build_host* compatibilities --

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type)
    values (lookup_server_arch('i386-redhat-linux'),
            lookup_sg_type('container_build_host'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type)
    values (lookup_server_arch('i386-debian-linux'),
            lookup_sg_type('container_build_host'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type)
    values (lookup_server_arch('i486-redhat-linux'),
            lookup_sg_type('container_build_host'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type)
    values (lookup_server_arch('i586-redhat-linux'),
            lookup_sg_type('container_build_host'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type)
    values (lookup_server_arch('i686-redhat-linux'),
            lookup_sg_type('container_build_host'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type)
    values (lookup_server_arch('athlon-redhat-linux'),
            lookup_sg_type('container_build_host'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type)
    values (lookup_server_arch('amd64-redhat-linux'),
            lookup_sg_type('container_build_host'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type)
    values (lookup_server_arch('amd64-debian-linux'),
            lookup_sg_type('container_build_host'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type)
    values (lookup_server_arch('arm64-debian-linux'),
            lookup_sg_type('container_build_host'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type)
    values (lookup_server_arch('ia64-redhat-linux'),
            lookup_sg_type('container_build_host'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type)
    values (lookup_server_arch('ia64-debian-linux'),
            lookup_sg_type('container_build_host'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type)
    values (lookup_server_arch('ia32e-redhat-linux'),
            lookup_sg_type('container_build_host'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type)
    values (lookup_server_arch('s390-redhat-linux'),
            lookup_sg_type('container_build_host'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type)
    values (lookup_server_arch('s390-debian-linux'),
            lookup_sg_type('container_build_host'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type)
    values (lookup_server_arch('s390x-redhat-linux'),
            lookup_sg_type('container_build_host'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type)
    values (lookup_server_arch('ppc-redhat-linux'),
            lookup_sg_type('container_build_host'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type)
    values (lookup_server_arch('powerpc-debian-linux'),
            lookup_sg_type('container_build_host'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type)
    values (lookup_server_arch('ppc64-redhat-linux'),
            lookup_sg_type('container_build_host'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type)
    values (lookup_server_arch('ppc64le-redhat-linux'),
            lookup_sg_type('container_build_host'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type)
    values (lookup_server_arch('x86_64-redhat-linux'),
            lookup_sg_type('container_build_host'));

-- currently not supported
-- insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
--         values (lookup_server_arch('aarch64-redhat-linux'),
--             lookup_sg_type('container_build_host'));

-- insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
--         values (lookup_server_arch('armv7l-redhat-linux'),
--             lookup_sg_type('container_build_host'));

-- insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
--         values (lookup_server_arch('armv5tejl-redhat-linux'),
--             lookup_sg_type('container_build_host'));

-- insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
--         values (lookup_server_arch('armv6l-redhat-linux'),
--             lookup_sg_type('container_build_host'));

-- insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
--         values (lookup_server_arch('armv6hl-redhat-linux'),
--             lookup_sg_type('container_build_host'));

-- osimage_build_host* compatibilities --

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type)
    values (lookup_server_arch('amd64-redhat-linux'),
            lookup_sg_type('osimage_build_host'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type)
    values (lookup_server_arch('x86_64-redhat-linux'),
            lookup_sg_type('osimage_build_host'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type)
    values (lookup_server_arch('ppc64le-redhat-linux'),
            lookup_sg_type('osimage_build_host'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type)
    values (lookup_server_arch('aarch64-redhat-linux'),
            lookup_sg_type('osimage_build_host'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type)
    values (lookup_server_arch('s390x-redhat-linux'),
            lookup_sg_type('osimage_build_host'));

-- monitoring_entitled compatibilities

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type)
    values (lookup_server_arch('amd64-redhat-linux'),
            lookup_sg_type('monitoring_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type)
    values (lookup_server_arch('x86_64-redhat-linux'),
            lookup_sg_type('monitoring_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type)
    values (lookup_server_arch('amd64-debian-linux'),
            lookup_sg_type('monitoring_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type)
    values (lookup_server_arch('arm64-debian-linux'),
            lookup_sg_type('monitoring_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type)
    values (lookup_server_arch('ppc64le-redhat-linux'),
            lookup_sg_type('monitoring_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type)
    values (lookup_server_arch('aarch64-redhat-linux'),
            lookup_sg_type('monitoring_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type)
    values (lookup_server_arch('s390x-redhat-linux'),
            lookup_sg_type('monitoring_entitled'));

-- ansible_control_node system entitlement

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('x86_64-redhat-linux'),
            lookup_sg_type('ansible_control_node'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('amd64-redhat-linux'),
            lookup_sg_type('ansible_control_node'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('ppc64le-redhat-linux'),
            lookup_sg_type('ansible_control_node'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('aarch64-redhat-linux'),
            lookup_sg_type('ansible_control_node'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('s390x-redhat-linux'),
            lookup_sg_type('ansible_control_node'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('amd64-debian-linux'),
            lookup_sg_type('ansible_control_node'));

commit;
   07070100000037000081B400000000000000000000000167AE111400000711000000000000000000000000000000000000003C00000000susemanager-schema/common/data/rhnSnapshotInvalidReason.sql   --
-- Copyright (c) 2008--2013 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--

insert into rhnSnapshotInvalidReason (id, label, name)
	values (sequence_nextval('rhn_ssinvalid_id_seq'), 'channel_removed',
		'A channel this snapshot was associated with no longer exists');

insert into rhnSnapshotInvalidReason (id, label, name)
	values (sequence_nextval('rhn_ssinvalid_id_seq'), 'channel_modified',
		'A channel this snapshot is associated with has been modified');

insert into rhnSnapshotInvalidReason (id, label, name)
	values (sequence_nextval('rhn_ssinvalid_id_seq'), 'sg_removed',
		'A server group this snapshot was associated with no longer exists');

insert into rhnSnapshotInvalidReason (id, label, name)
	values (sequence_nextval('rhn_ssinvalid_id_seq'), 'ns_removed',
		'A namespace this snapshot was associated with no longer exists');

insert into rhnSnapshotInvalidReason (id, label, name)
	values (sequence_nextval('rhn_ssinvalid_id_seq'), 'cr_removed',
		'A config revision this snapshot was associated with no longer exists');

insert into rhnSnapshotInvalidReason (id, label, name)
	values (sequence_nextval('rhn_ssinvalid_id_seq'), 'cc_removed',
		'A config channel this snapshot was associated with no longer exists');

commit;

   07070100000038000081B400000000000000000000000167AE1114000020A4000000000000000000000000000000000000003100000000susemanager-schema/common/data/rhnTaskoBunch.sql  --
-- Copyright (c) 2010--2016 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


INSERT INTO rhnTaskoBunch (id, name, description, org_bunch)
             VALUES (sequence_nextval('rhn_tasko_bunch_id_seq'), 'daily-status-bunch', 'Sends daily report', null);

INSERT INTO rhnTaskoBunch (id, name, description, org_bunch)
             VALUES (sequence_nextval('rhn_tasko_bunch_id_seq'), 'sat-sync-bunch', 'Runs satellite-sync
Parameters:
- list parameter lists channels
- channel parameter specifies channel to be synced
- without parameter runs satellite-sync without parameters', 'Y');

INSERT INTO rhnTaskoBunch (id, name, description, org_bunch)
             VALUES (sequence_nextval('rhn_tasko_bunch_id_seq'), 'clear-taskologs-bunch', 'Clears taskomatic run log history
Parameters:
- days parameter specifies age of logs to be kept
- without parameter default value will be used', null);

INSERT INTO rhnTaskoBunch (id, name, description, org_bunch)
             VALUES (sequence_nextval('rhn_tasko_bunch_id_seq'), 'cobbler-sync-bunch', 'Applies any cobbler configuration changes', null);

INSERT INTO rhnTaskoBunch (id, name, description, org_bunch)
             VALUES (sequence_nextval('rhn_tasko_bunch_id_seq'), 'compare-configs-bunch', 'Schedules a comparison of config files on all systems', null);

INSERT INTO rhnTaskoBunch (id, name, description, org_bunch)
             VALUES (sequence_nextval('rhn_tasko_bunch_id_seq'), 'session-cleanup-bunch', 'Deletes expired rows from the PXTSessions table to keep it from growing too large', null);

INSERT INTO rhnTaskoBunch (id, name, description, org_bunch)
             VALUES (sequence_nextval('rhn_tasko_bunch_id_seq'), 'sandbox-cleanup-bunch', 'Clean up sandbox', null);

INSERT INTO rhnTaskoBunch (id, name, description, org_bunch)
             VALUES (sequence_nextval('rhn_tasko_bunch_id_seq'), 'repo-sync-bunch', 'Used for syncing repos to a channel', 'Y');

INSERT INTO rhnTaskoBunch (id, name, description, org_bunch)
             VALUES (sequence_nextval('rhn_tasko_bunch_id_seq'), 'package-cleanup-bunch', 'Cleans up orphaned packages', null);

INSERT INTO rhnTaskoBunch (id, name, description, org_bunch)
             VALUES (sequence_nextval('rhn_tasko_bunch_id_seq'), 'kickstartfile-sync-bunch', 'Syncs kickstart profiles that were generated using the wizard', null);

INSERT INTO rhnTaskoBunch (id, name, description, org_bunch)
             VALUES (sequence_nextval('rhn_tasko_bunch_id_seq'), 'kickstart-cleanup-bunch', 'Cleans up stale Kickstarts', null);

INSERT INTO rhnTaskoBunch (id, name, description, org_bunch)
             VALUES (sequence_nextval('rhn_tasko_bunch_id_seq'), 'errata-queue-bunch', 'Processes errata', null);

INSERT INTO rhnTaskoBunch (id, name, description, org_bunch)
             VALUES (sequence_nextval('rhn_tasko_bunch_id_seq'), 'errata-cache-bunch', 'Performs errata cache recalc for a given server or channel', null);

INSERT INTO rhnTaskoBunch (id, name, description, org_bunch)
             VALUES (sequence_nextval('rhn_tasko_bunch_id_seq'), 'channel-repodata-bunch', 'Generates channel repodata', null);

INSERT INTO rhnTaskoBunch (id, name, description, org_bunch)
             VALUES (sequence_nextval('rhn_tasko_bunch_id_seq'), 'cleanup-data-bunch', 'Cleans up orphaned and outdated data', null);

INSERT INTO rhnTaskoBunch (id, name, description, org_bunch)
             VALUES (sequence_nextval('rhn_tasko_bunch_id_seq'), 'ssh-push-bunch', 'Push scheduled actions to clients via SSH', null);

INSERT INTO rhnTaskoBunch (id, name, description, org_bunch)
             VALUES (sequence_nextval('rhn_tasko_bunch_id_seq'), 'cve-server-channels-bunch', 'Generate data required for performing CVE audit queries', null);

INSERT INTO rhnTaskoBunch (id, name, description, org_bunch)
             VALUES (sequence_nextval('rhn_tasko_bunch_id_seq'), 'reboot-action-cleanup-bunch', 'invalidate reboot actions which never finish', null);

INSERT INTO rhnTaskoBunch (id, name, description, org_bunch)
             VALUES (sequence_nextval('rhn_tasko_bunch_id_seq'), 'mgr-sync-refresh-bunch', 'Refresh data about channels, products and subscriptions', null);

INSERT INTO rhnTaskoBunch (id, name, description, org_bunch)
             VALUES (sequence_nextval('rhn_tasko_bunch_id_seq'), 'auto-errata-bunch', 'Schedule automatic errata update actions', null);

INSERT INTO rhnTaskoBunch (id, name, description, org_bunch)
             VALUES (sequence_nextval('rhn_tasko_bunch_id_seq'), 'gatherer-matcher-bunch', 'Schedule running gatherer', null);

INSERT INTO rhnTaskoBunch (id, name, description, org_bunch)
             VALUES (sequence_nextval('rhn_tasko_bunch_id_seq'), 'uuid-cleanup-bunch', 'purge orphaned uuid records', null);

INSERT INTO rhnTaskoBunch (id, name, description, org_bunch)
             VALUES (sequence_nextval('rhn_tasko_bunch_id_seq'), 'minion-action-cleanup-bunch', 'Cleanup actions for Minions', null);

INSERT INTO rhnTaskoBunch (id, name, description, org_bunch)
             VALUES (sequence_nextval('rhn_tasko_bunch_id_seq'), 'token-cleanup-bunch', 'Cleanup expired channel tokens', null);

INSERT INTO rhnTaskoBunch (id, name, description, org_bunch)
   VALUES (sequence_nextval('rhn_tasko_bunch_id_seq'), 'minion-action-executor-bunch', 'Execute actions on Minions', null);

INSERT INTO rhnTaskoBunch (id, name, description, org_bunch)
   VALUES (sequence_nextval('rhn_tasko_bunch_id_seq'), 'minion-action-chain-executor-bunch', 'Execute action chains on Minions', null);

INSERT INTO rhnTaskoBunch (id, name, description, org_bunch)
   VALUES (sequence_nextval('rhn_tasko_bunch_id_seq'), 'minion-action-chain-cleanup-bunch', 'Cleanup actions chains for Minions', null);

INSERT INTO rhnTaskoBunch (id, name, description, org_bunch)
   VALUES (sequence_nextval('rhn_tasko_bunch_id_seq'), 'notifications-cleanup-bunch', 'Cleanup expired notification messages', null);

INSERT INTO rhnTaskoBunch (id, name, description, org_bunch)
   VALUES (sequence_nextval('rhn_tasko_bunch_id_seq'), 'minion-checkin-bunch', 'Perform a regular check-in on minions', null);

INSERT INTO RhnTaskoBunch (id, name, description, org_bunch)
   VALUES (sequence_nextval('rhn_tasko_bunch_id_seq'), 'recurring-action-executor-bunch', 'Schedules actions for minion/group/org', null);

INSERT INTO rhnTaskoBunch (id, name, description, org_bunch)
   VALUES (sequence_nextval('rhn_tasko_bunch_id_seq'), 'ssh-minion-action-executor-bunch', 'Execute actions on SSH Minions', null);

INSERT INTO rhnTaskoBunch (id, name, description, org_bunch)
   VALUES (sequence_nextval('rhn_tasko_bunch_id_seq'), 'mgr-forward-registration-bunch', 'Forward registrations to SUSE Customer Center', null);

INSERT INTO rhnTaskoBunch (id, name, description, org_bunch)
VALUES (sequence_nextval('rhn_tasko_bunch_id_seq'), 'update-payg-data-bunch', 'Runs update-payg-data
Parameters:
- integer parameter payg instance ID
- without parameter updates data for all instances', null);

INSERT INTO rhnTaskoBunch (id, name, description, org_bunch)
   VALUES (sequence_nextval('rhn_tasko_bunch_id_seq'), 'mgr-update-reporting-bunch', 'Update Reporting DB with current data', null);

INSERT INTO rhnTaskoBunch (id, name, description, org_bunch)
VALUES (sequence_nextval('rhn_tasko_bunch_id_seq'), 'mgr-update-reporting-hub-bunch', 'Update Reporting DB with data from other susemanager servers', null);

INSERT INTO rhnTaskoBunch (id, name, description, org_bunch)
VALUES (sequence_nextval('rhn_tasko_bunch_id_seq'), 'system-profile-refresh-bunch', 'Refresh System Profiles of all registered servers', null);

INSERT INTO rhnTaskoBunch (id, name, description, org_bunch)
VALUES (sequence_nextval('rhn_tasko_bunch_id_seq'), 'payg-dimension-computation-bunch', 'Compute the dimensions data required for PAYG billing', null);

commit;
07070100000039000081B400000000000000000000000167AE11140000261E000000000000000000000000000000000000003400000000susemanager-schema/common/data/rhnTaskoSchedule.sql   --
-- Copyright (c) 2010--2016 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

-- Top of every minute
INSERT INTO rhnTaskoSchedule (id, job_label, bunch_id, active_from, cron_expr)
    VALUES(sequence_nextval('rhn_tasko_schedule_id_seq'), 'errata-queue-default',
        (SELECT id FROM rhnTaskoBunch WHERE name='errata-queue-bunch'),
        current_timestamp, '0 * * * * ?');

INSERT INTO rhnTaskoSchedule (id, job_label, bunch_id, active_from, cron_expr)
    VALUES(sequence_nextval('rhn_tasko_schedule_id_seq'), 'cobbler-sync-default',
        (SELECT id FROM rhnTaskoBunch WHERE name='cobbler-sync-bunch'),
        current_timestamp, '0 0/5 * * * ?');

INSERT INTO rhnTaskoSchedule (id, job_label, bunch_id, active_from, cron_expr)
    VALUES(sequence_nextval('rhn_tasko_schedule_id_seq'), 'channel-repodata-default',
        (SELECT id FROM rhnTaskoBunch WHERE name='channel-repodata-bunch'),
        current_timestamp, '0 * * * * ?');

INSERT INTO rhnTaskoSchedule (id, job_label, bunch_id, active_from, cron_expr)
    VALUES(sequence_nextval('rhn_tasko_schedule_id_seq'), 'errata-cache-default',
        (SELECT id FROM rhnTaskoBunch WHERE name='errata-cache-bunch'),
        current_timestamp, '0 * * * * ?');

INSERT INTO rhnTaskoSchedule (id, job_label, bunch_id, active_from, cron_expr)
    VALUES (sequence_nextval('rhn_tasko_schedule_id_seq'), 'ssh-push-default',
        (SELECT id FROM rhnTaskoBunch WHERE name='ssh-push-bunch'),
        current_timestamp, '0 * * * * ?');

-- Every 10 minutes

INSERT INTO rhnTaskoSchedule (id, job_label, bunch_id, active_from, cron_expr)
    VALUES(sequence_nextval('rhn_tasko_schedule_id_seq'), 'package-cleanup-default',
        (SELECT id FROM rhnTaskoBunch WHERE name='package-cleanup-bunch'),
        current_timestamp, '0 0/10 * * * ?');

INSERT INTO rhnTaskoSchedule (id, job_label, bunch_id, active_from, cron_expr)
    VALUES(sequence_nextval('rhn_tasko_schedule_id_seq'), 'kickstart-cleanup-default',
        (SELECT id FROM rhnTaskoBunch WHERE name='kickstart-cleanup-bunch'),
        current_timestamp, '0 0/10 * * * ?');

INSERT INTO rhnTaskoSchedule (id, job_label, bunch_id, active_from, cron_expr)
    VALUES(sequence_nextval('rhn_tasko_schedule_id_seq'), 'kickstartfile-sync-default',
        (SELECT id FROM rhnTaskoBunch WHERE name='kickstartfile-sync-bunch'),
        current_timestamp, '0 0/10 * * * ?');

INSERT INTO rhnTaskoSchedule (id, job_label, bunch_id, active_from, cron_expr)
    VALUES(sequence_nextval('rhn_tasko_schedule_id_seq'), 'auto-errata-default',
        (SELECT id FROM rhnTaskoBunch WHERE name='auto-errata-bunch'),
        current_timestamp, '0 5/10 * * * ?');

INSERT INTO rhnTaskoSchedule (id, job_label, bunch_id, active_from, cron_expr)
VALUES(sequence_nextval('rhn_tasko_schedule_id_seq'), 'update-payg-default',
       (SELECT id FROM rhnTaskoBunch WHERE name='update-payg-data-bunch'),
       current_timestamp, '0 0/10 * * * ?');

-- Every 15 minutes

INSERT INTO rhnTaskoSchedule (id, job_label, bunch_id, active_from, cron_expr)
    VALUES(sequence_nextval('rhn_tasko_schedule_id_seq'), 'session-cleanup-default',
        (SELECT id FROM rhnTaskoBunch WHERE name='session-cleanup-bunch'),
        current_timestamp, '0 0/15 * * * ?');

INSERT INTO rhnTaskoSchedule (id, job_label, bunch_id, active_from, cron_expr)
    VALUES(sequence_nextval('rhn_tasko_schedule_id_seq'), 'mgr-forward-registration-default',
        (SELECT id FROM rhnTaskoBunch WHERE name='mgr-forward-registration-bunch'),
        current_timestamp, '0 0/15 * * * ?');

-- Every hour

INSERT INTO rhnTaskoSchedule (id, job_label, bunch_id, active_from, cron_expr)
VALUES (sequence_nextval('rhn_tasko_schedule_id_seq'), 'payg-dimension-computation-default',
        (SELECT id FROM rhnTaskoBunch WHERE name='payg-dimension-computation-bunch'),
        current_timestamp, '0 45 * * * ?');

INSERT INTO rhnTaskoSchedule (id, job_label, bunch_id, active_from, cron_expr)
    VALUES(sequence_nextval('rhn_tasko_schedule_id_seq'), 'uuid-cleanup-default',
        (SELECT id FROM rhnTaskoBunch WHERE name='uuid-cleanup-bunch'),
        current_timestamp, '0 0 * * * ?');

INSERT INTO rhnTaskoSchedule (id, job_label, bunch_id, active_from, cron_expr)
    VALUES (sequence_nextval('rhn_tasko_schedule_id_seq'), 'minion-action-chain-cleanup-default',
        (SELECT id FROM rhnTaskoBunch WHERE name='minion-action-chain-cleanup-bunch'),
        current_timestamp, '0 0 * * * ?');

INSERT INTO rhnTaskoSchedule (id, job_label, bunch_id, active_from, cron_expr)
    VALUES(sequence_nextval('rhn_tasko_schedule_id_seq'), 'reboot-action-cleanup-default',
        (SELECT id FROM rhnTaskoBunch WHERE name='reboot-action-cleanup-bunch'),
        current_timestamp, '0 0 * * * ?');

INSERT INTO rhnTaskoSchedule (id, job_label, bunch_id, active_from, cron_expr)
    VALUES (sequence_nextval('rhn_tasko_schedule_id_seq'), 'minion-checkin-default',
        (SELECT id FROM rhnTaskoBunch WHERE name='minion-checkin-bunch'),
        current_timestamp, '0 0 * * * ?');

-- Once a day at 4:05:00 AM (beware of 2AM cronjobs)

INSERT INTO rhnTaskoSchedule (id, job_label, bunch_id, active_from, cron_expr)
    VALUES(sequence_nextval('rhn_tasko_schedule_id_seq'), 'sandbox-cleanup-default',
        (SELECT id FROM rhnTaskoBunch WHERE name='sandbox-cleanup-bunch'),
        current_timestamp, '0 5 4 ? * *');

-- Once a day at 11:00 PM

INSERT INTO rhnTaskoSchedule (id, job_label, bunch_id, active_from, cron_expr)
    VALUES(sequence_nextval('rhn_tasko_schedule_id_seq'), 'daily-status-default',
        (SELECT id FROM rhnTaskoBunch WHERE name='daily-status-bunch'),
        current_timestamp, '0 0 23 ? * *');

INSERT INTO rhnTaskoSchedule (id, job_label, bunch_id, active_from, cron_expr)
    VALUES(sequence_nextval('rhn_tasko_schedule_id_seq'), 'compare-configs-default',
        (SELECT id FROM rhnTaskoBunch WHERE name='compare-configs-bunch'),
        current_timestamp, '0 0 23 ? * *');

INSERT INTO rhnTaskoSchedule (id, job_label, bunch_id, active_from, cron_expr)
    VALUES(sequence_nextval('rhn_tasko_schedule_id_seq'), 'clear-taskologs-default',
        (SELECT id FROM rhnTaskoBunch WHERE name='clear-taskologs-bunch'),
        current_timestamp, '0 0 23 ? * *');

INSERT INTO rhnTaskoSchedule (id, job_label, bunch_id, active_from, cron_expr)
    VALUES(sequence_nextval('rhn_tasko_schedule_id_seq'), 'cleanup-data-default',
        (SELECT id FROM rhnTaskoBunch WHERE name='cleanup-data-bunch'),
        current_timestamp, '0 0 23 ? * *');

INSERT INTO rhnTaskoSchedule (id, job_label, bunch_id, active_from, cron_expr)
    VALUES (sequence_nextval('rhn_tasko_schedule_id_seq'), 'cve-server-channels-default',
        (SELECT id FROM rhnTaskoBunch WHERE name='cve-server-channels-bunch'),
        current_timestamp, '0 0 23 ? * *');

-- Once a day at 00:00

INSERT INTO rhnTaskoSchedule (id, job_label, bunch_id, active_from, cron_expr)
    VALUES (sequence_nextval('rhn_tasko_schedule_id_seq'), 'minion-action-cleanup-default',
        (SELECT id FROM rhnTaskoBunch WHERE name='minion-action-cleanup-bunch'),
        current_timestamp, '0 0 0 * * ?');

INSERT INTO rhnTaskoSchedule (id, job_label, bunch_id, active_from, cron_expr)
    VALUES (sequence_nextval('rhn_tasko_schedule_id_seq'), 'mgr-sync-refresh-default',
        (SELECT id FROM rhnTaskoBunch WHERE name='mgr-sync-refresh-bunch'),
        current_timestamp, '0 0 0 ? * *');

INSERT INTO rhnTaskoSchedule (id, job_label, bunch_id, active_from, cron_expr)
    VALUES (sequence_nextval('rhn_tasko_schedule_id_seq'), 'gatherer-matcher-default',
        (SELECT id FROM rhnTaskoBunch WHERE name='gatherer-matcher-bunch'),
        current_timestamp, '0 0 0 ? * *');

INSERT INTO rhnTaskoSchedule (id, job_label, bunch_id, active_from, cron_expr)
    VALUES (sequence_nextval('rhn_tasko_schedule_id_seq'), 'token-cleanup-default',
        (SELECT id FROM rhnTaskoBunch WHERE name='token-cleanup-bunch'),
        current_timestamp, '0 0 0 ? * *');

INSERT INTO rhnTaskoSchedule (id, job_label, bunch_id, active_from, cron_expr)
    VALUES (sequence_nextval('rhn_tasko_schedule_id_seq'), 'notifications-cleanup-default',
        (SELECT id FROM rhnTaskoBunch WHERE name='notifications-cleanup-bunch'),
        current_timestamp, '0 0 0 ? * *');

INSERT INTO rhnTaskoSchedule (id, job_label, bunch_id, active_from, cron_expr)
    VALUES (sequence_nextval('rhn_tasko_schedule_id_seq'), 'update-reporting-default',
        (SELECT id FROM rhnTaskoBunch WHERE name='mgr-update-reporting-bunch'),
        current_timestamp, '0 0 0 ? * *');

INSERT INTO rhnTaskoSchedule (id, job_label, bunch_id, active_from, cron_expr)
VALUES (sequence_nextval('rhn_tasko_schedule_id_seq'), 'update-reporting-hub-default',
        (SELECT id FROM rhnTaskoBunch WHERE name='mgr-update-reporting-hub-bunch'),
        current_timestamp, '0 30 1 ? * *');

-- Once a month at the 2nd Saturday at 5am

INSERT INTO rhnTaskoSchedule (id, job_label, bunch_id, active_from, cron_expr)
VALUES (sequence_nextval('rhn_tasko_schedule_id_seq'), 'system-profile-refresh-default',
        (SELECT id FROM rhnTaskoBunch WHERE name='system-profile-refresh-bunch'),
        current_timestamp, '0 0 5 ? * SAT#2');

commit;
  0707010000003A000081B400000000000000000000000167AE11140000201D000000000000000000000000000000000000003000000000susemanager-schema/common/data/rhnTaskoTask.sql   --
-- Copyright (c) 2010--2016 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


INSERT INTO rhnTaskoTask (id, name, class)
         VALUES (sequence_nextval('rhn_tasko_task_id_seq'), 'repo-sync', 'com.redhat.rhn.taskomatic.task.RepoSyncTask');

INSERT INTO rhnTaskoTask (id, name, class)
         VALUES (sequence_nextval('rhn_tasko_task_id_seq'), 'ubuntu-errata', 'com.redhat.rhn.taskomatic.task.UbuntuErrataTask');

INSERT INTO rhnTaskoTask (id, name, class)
         VALUES (sequence_nextval('rhn_tasko_task_id_seq'), 'satellite-sync', 'com.redhat.rhn.taskomatic.task.SatSyncTask');

INSERT INTO rhnTaskoTask (id, name, class)
         VALUES (sequence_nextval('rhn_tasko_task_id_seq'), 'kickstartfile-sync', 'com.redhat.rhn.taskomatic.task.KickstartFileSyncTask');

INSERT INTO rhnTaskoTask (id, name, class)
         VALUES (sequence_nextval('rhn_tasko_task_id_seq'), 'kickstart-cleanup', 'com.redhat.rhn.taskomatic.task.KickstartCleanup');

INSERT INTO rhnTaskoTask (id, name, class)
         VALUES (sequence_nextval('rhn_tasko_task_id_seq'), 'errata-cache', 'com.redhat.rhn.taskomatic.task.ErrataCacheTask');

INSERT INTO rhnTaskoTask (id, name, class)
         VALUES (sequence_nextval('rhn_tasko_task_id_seq'), 'errata-queue', 'com.redhat.rhn.taskomatic.task.ErrataQueue');

INSERT INTO rhnTaskoTask (id, name, class)
         VALUES (sequence_nextval('rhn_tasko_task_id_seq'), 'errata-mailer', 'com.redhat.rhn.taskomatic.task.ErrataMailer');

INSERT INTO rhnTaskoTask (id, name, class)
         VALUES (sequence_nextval('rhn_tasko_task_id_seq'), 'sandbox-cleanup', 'com.redhat.rhn.taskomatic.task.SandboxCleanup');

INSERT INTO rhnTaskoTask (id, name, class)
         VALUES (sequence_nextval('rhn_tasko_task_id_seq'), 'session-cleanup', 'com.redhat.rhn.taskomatic.task.SessionCleanup');

INSERT INTO rhnTaskoTask (id, name, class)
         VALUES (sequence_nextval('rhn_tasko_task_id_seq'), 'channel-repodata', 'com.redhat.rhn.taskomatic.task.ChannelRepodata');

INSERT INTO rhnTaskoTask (id, name, class)
         VALUES (sequence_nextval('rhn_tasko_task_id_seq'), 'package-cleanup', 'com.redhat.rhn.taskomatic.task.PackageCleanup');

INSERT INTO rhnTaskoTask (id, name, class)
         VALUES (sequence_nextval('rhn_tasko_task_id_seq'), 'cobbler-sync', 'com.redhat.rhn.taskomatic.task.CobblerSyncTask');

INSERT INTO rhnTaskoTask (id, name, class)
         VALUES (sequence_nextval('rhn_tasko_task_id_seq'), 'daily-summary', 'com.redhat.rhn.taskomatic.task.DailySummary');

INSERT INTO rhnTaskoTask (id, name, class)
         VALUES (sequence_nextval('rhn_tasko_task_id_seq'), 'summary-population', 'com.redhat.rhn.taskomatic.task.SummaryPopulation');

INSERT INTO rhnTaskoTask (id, name, class)
         VALUES (sequence_nextval('rhn_tasko_task_id_seq'), 'compare-config-files', 'com.redhat.rhn.taskomatic.task.CompareConfigFilesTask');

INSERT INTO rhnTaskoTask (id, name, class)
         VALUES (sequence_nextval('rhn_tasko_task_id_seq'), 'clear-log-history', 'com.redhat.rhn.taskomatic.task.ClearLogHistory');

INSERT INTO rhnTaskoTask (id, name, class)
         VALUES (sequence_nextval('rhn_tasko_task_id_seq'), 'cleanup-packagechangelog-data', 'com.redhat.rhn.taskomatic.task.ChangeLogCleanUp');

INSERT INTO rhnTaskoTask (id, name, class)
         VALUES (sequence_nextval('rhn_tasko_task_id_seq'), 'ssh-push', 'com.redhat.rhn.taskomatic.task.SSHPush');

INSERT INTO rhnTaskoTask (id, name, class)
         VALUES (sequence_nextval('rhn_tasko_task_id_seq'), 'cve-server-channels', 'com.redhat.rhn.taskomatic.task.CVEServerChannels');

INSERT INTO rhnTaskoTask (id, name, class)
         VALUES (sequence_nextval('rhn_tasko_task_id_seq'), 'reboot-action-cleanup', 'com.redhat.rhn.taskomatic.task.RebootActionCleanup');

INSERT INTO rhnTaskoTask (id, name, class)
         VALUES (sequence_nextval('rhn_tasko_task_id_seq'), 'mgr-sync-refresh', 'com.redhat.rhn.taskomatic.task.MgrSyncRefresh');

INSERT INTO rhnTaskoTask (id, name, class)
         VALUES (sequence_nextval('rhn_tasko_task_id_seq'), 'auto-errata', 'com.redhat.rhn.taskomatic.task.AutoErrataTask');

INSERT INTO rhnTaskoTask (id, name, class)
         VALUES (sequence_nextval('rhn_tasko_task_id_seq'), 'gatherer', 'com.redhat.rhn.taskomatic.task.gatherer.GathererJob');

INSERT INTO rhnTaskoTask (id, name, class)
         VALUES (sequence_nextval('rhn_tasko_task_id_seq'), 'matcher', 'com.redhat.rhn.taskomatic.task.matcher.MatcherJob');

INSERT INTO rhnTaskoTask (id, name, class)
         VALUES (sequence_nextval('rhn_tasko_task_id_seq'), 'uuid-cleanup', 'com.redhat.rhn.taskomatic.task.UuidCleanup');

INSERT INTO rhnTaskoTask (id, name, class)
         VALUES (sequence_nextval('rhn_tasko_task_id_seq'), 'minion-action-cleanup', 'com.redhat.rhn.taskomatic.task.MinionActionCleanup');

INSERT INTO rhnTaskoTask (id, name, class)
         VALUES (sequence_nextval('rhn_tasko_task_id_seq'), 'token-cleanup', 'com.redhat.rhn.taskomatic.task.TokenCleanup');

INSERT INTO rhnTaskoTask (id, name, class)
   VALUES (sequence_nextval('rhn_tasko_task_id_seq'), 'minion-action-executor', 'com.redhat.rhn.taskomatic.task.MinionActionExecutor');

INSERT INTO rhnTaskoTask (id, name, class)
   VALUES (sequence_nextval('rhn_tasko_task_id_seq'), 'minion-action-chain-executor', 'com.redhat.rhn.taskomatic.task.MinionActionChainExecutor');

INSERT INTO rhnTaskoTask (id, name, class)
   VALUES (sequence_nextval('rhn_tasko_task_id_seq'), 'minion-action-chain-cleanup', 'com.redhat.rhn.taskomatic.task.MinionActionChainCleanup');

INSERT INTO rhnTaskoTask (id, name, class)
   VALUES (sequence_nextval('rhn_tasko_task_id_seq'), 'notifications-cleanup', 'com.redhat.rhn.taskomatic.task.NotificationsCleanup');

INSERT INTO rhnTaskoTask (id, name, class)
   VALUES (sequence_nextval('rhn_tasko_task_id_seq'), 'minion-checkin', 'com.redhat.rhn.taskomatic.task.MinionCheckin');

INSERT INTO rhnTaskoTask (id, name, class)
   VALUES (sequence_nextval('rhn_tasko_task_id_seq'), 'recurring-action-executor', 'com.redhat.rhn.taskomatic.task.RecurringActionJob');

INSERT INTO rhnTaskoTask (id, name, class)
   VALUES (sequence_nextval('rhn_tasko_task_id_seq'), 'ssh-minion-action-executor', 'com.redhat.rhn.taskomatic.task.SSHMinionActionExecutor');

INSERT INTO rhnTaskoTask (id, name, class)
   VALUES (sequence_nextval('rhn_tasko_task_id_seq'), 'channel-modular-data-cleanup', 'com.redhat.rhn.taskomatic.task.ModularDataCleanup');

INSERT INTO rhnTaskoTask (id, name, class)
   VALUES (sequence_nextval('rhn_tasko_task_id_seq'), 'mgr-forward-registration', 'com.redhat.rhn.taskomatic.task.ForwardRegistrationTask');

INSERT INTO rhnTaskoTask (id, name, class)
VALUES (sequence_nextval('rhn_tasko_task_id_seq'), 'update-payg-auth', 'com.redhat.rhn.taskomatic.task.payg.PaygUpdateAuthTask');

INSERT INTO rhnTaskoTask (id, name, class)
VALUES (sequence_nextval('rhn_tasko_task_id_seq'), 'update-payg-hosts', 'com.redhat.rhn.taskomatic.task.payg.PaygUpdateHostsTask');

INSERT INTO rhnTaskoTask (id, name, class)
   VALUES (sequence_nextval('rhn_tasko_task_id_seq'), 'mgr-update-reporting', 'com.redhat.rhn.taskomatic.task.ReportDbUpdateTask');

INSERT INTO rhnTaskoTask (id, name, class)
VALUES (sequence_nextval('rhn_tasko_task_id_seq'), 'mgr-update-reporting-hub', 'com.redhat.rhn.taskomatic.task.HubReportDbUpdateTask');

INSERT INTO rhnTaskoTask (id, name, class)
VALUES (sequence_nextval('rhn_tasko_task_id_seq'), 'system-profile-refresh', 'com.redhat.rhn.taskomatic.task.SystemProfileRefreshTask');

INSERT INTO rhnTaskoTask (id, name, class)
VALUES (sequence_nextval('rhn_tasko_task_id_seq'), 'payg-dimension-computation', 'com.redhat.rhn.taskomatic.task.payg.PaygComputeDimensionsTask');

commit;
   0707010000003B000081B400000000000000000000000167AE111400004210000000000000000000000000000000000000003400000000susemanager-schema/common/data/rhnTaskoTemplate.sql   --
-- Copyright (c) 2010--2016 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


INSERT INTO rhnTaskoTemplate (id, bunch_id, task_id, ordering, start_if)
             VALUES (sequence_nextval('rhn_tasko_template_id_seq'),
                        (SELECT id FROM rhnTaskoBunch WHERE name='daily-status-bunch'),
                        (SELECT id FROM rhnTaskoTask WHERE name='summary-population'),
                        0,
                        null);

INSERT INTO rhnTaskoTemplate (id, bunch_id, task_id, ordering, start_if)
             VALUES (sequence_nextval('rhn_tasko_template_id_seq'),
                         (SELECT id FROM rhnTaskoBunch WHERE name='daily-status-bunch'),
                         (SELECT id FROM rhnTaskoTask WHERE name='daily-summary'),
                         1,
                         'FINISHED');

INSERT INTO rhnTaskoTemplate (id, bunch_id, task_id, ordering, start_if)
             VALUES (sequence_nextval('rhn_tasko_template_id_seq'),
                        (SELECT id FROM rhnTaskoBunch WHERE name='sat-sync-bunch'),
                        (SELECT id FROM rhnTaskoTask WHERE name='satellite-sync'),
                        0,
                        null);

INSERT INTO rhnTaskoTemplate (id, bunch_id, task_id, ordering, start_if)
             VALUES (sequence_nextval('rhn_tasko_template_id_seq'),
                        (SELECT id FROM rhnTaskoBunch WHERE name='clear-taskologs-bunch'),
                        (SELECT id FROM rhnTaskoTask WHERE name='clear-log-history'),
                        0,
                        null);

INSERT INTO rhnTaskoTemplate (id, bunch_id, task_id, ordering, start_if)
             VALUES (sequence_nextval('rhn_tasko_template_id_seq'),
                        (SELECT id FROM rhnTaskoBunch WHERE name='cobbler-sync-bunch'),
                        (SELECT id FROM rhnTaskoTask WHERE name='cobbler-sync'),
                        0,
                        null);

INSERT INTO rhnTaskoTemplate (id, bunch_id, task_id, ordering, start_if)
             VALUES (sequence_nextval('rhn_tasko_template_id_seq'),
                        (SELECT id FROM rhnTaskoBunch WHERE name='compare-configs-bunch'),
                        (SELECT id FROM rhnTaskoTask WHERE name='compare-config-files'),
                        0,
                        null);

INSERT INTO rhnTaskoTemplate (id, bunch_id, task_id, ordering, start_if)
             VALUES (sequence_nextval('rhn_tasko_template_id_seq'),
                        (SELECT id FROM rhnTaskoBunch WHERE name='session-cleanup-bunch'),
                        (SELECT id FROM rhnTaskoTask WHERE name='session-cleanup'),
                        0,
                        null);

INSERT INTO rhnTaskoTemplate (id, bunch_id, task_id, ordering, start_if)
             VALUES (sequence_nextval('rhn_tasko_template_id_seq'),
                        (SELECT id FROM rhnTaskoBunch WHERE name='sandbox-cleanup-bunch'),
                        (SELECT id FROM rhnTaskoTask WHERE name='sandbox-cleanup'),
                        0,
                        null);

INSERT INTO rhnTaskoTemplate (id, bunch_id, task_id, ordering, start_if)
             VALUES (sequence_nextval('rhn_tasko_template_id_seq'),
                        (SELECT id FROM rhnTaskoBunch WHERE name='repo-sync-bunch'),
                        (SELECT id FROM rhnTaskoTask WHERE name='repo-sync'),
                        0,
                        null);

INSERT INTO rhnTaskoTemplate (id, bunch_id, task_id, ordering, start_if)
             VALUES (sequence_nextval('rhn_tasko_template_id_seq'),
                        (SELECT id FROM rhnTaskoBunch WHERE name='repo-sync-bunch'),
                        (SELECT id FROM rhnTaskoTask WHERE name='ubuntu-errata'),
                        1,
                        'FINISHED');

INSERT INTO rhnTaskoTemplate (id, bunch_id, task_id, ordering, start_if)
             VALUES (sequence_nextval('rhn_tasko_template_id_seq'),
                        (SELECT id FROM rhnTaskoBunch WHERE name='package-cleanup-bunch'),
                        (SELECT id FROM rhnTaskoTask WHERE name='package-cleanup'),
                        0,
                        null);

INSERT INTO rhnTaskoTemplate (id, bunch_id, task_id, ordering, start_if)
             VALUES (sequence_nextval('rhn_tasko_template_id_seq'),
                        (SELECT id FROM rhnTaskoBunch WHERE name='kickstartfile-sync-bunch'),
                        (SELECT id FROM rhnTaskoTask WHERE name='kickstartfile-sync'),
                        0,
                        null);

INSERT INTO rhnTaskoTemplate (id, bunch_id, task_id, ordering, start_if)
             VALUES (sequence_nextval('rhn_tasko_template_id_seq'),
                        (SELECT id FROM rhnTaskoBunch WHERE name='kickstart-cleanup-bunch'),
                        (SELECT id FROM rhnTaskoTask WHERE name='kickstart-cleanup'),
                        0,
                        null);

INSERT INTO rhnTaskoTemplate (id, bunch_id, task_id, ordering, start_if)
             VALUES (sequence_nextval('rhn_tasko_template_id_seq'),
                        (SELECT id FROM rhnTaskoBunch WHERE name='errata-queue-bunch'),
                        (SELECT id FROM rhnTaskoTask WHERE name='errata-queue'),
                        0,
                        null);

INSERT INTO rhnTaskoTemplate (id, bunch_id, task_id, ordering, start_if)
             VALUES (sequence_nextval('rhn_tasko_template_id_seq'),
                        (SELECT id FROM rhnTaskoBunch WHERE name='channel-repodata-bunch'),
                        (SELECT id FROM rhnTaskoTask WHERE name='channel-repodata'),
                        0,
                        null);

INSERT INTO rhnTaskoTemplate (id, bunch_id, task_id, ordering, start_if)
             VALUES (sequence_nextval('rhn_tasko_template_id_seq'),
                        (SELECT id FROM rhnTaskoBunch WHERE name='errata-cache-bunch'),
                        (SELECT id FROM rhnTaskoTask WHERE name='errata-cache'),
                        0,
                        null);

INSERT INTO rhnTaskoTemplate (id, bunch_id, task_id, ordering, start_if)
             VALUES (sequence_nextval('rhn_tasko_template_id_seq'),
                        (SELECT id FROM rhnTaskoBunch WHERE name='errata-cache-bunch'),
                        (SELECT id FROM rhnTaskoTask WHERE name='errata-mailer'),
                        1,
                        'FINISHED');

INSERT INTO rhnTaskoTemplate (id, bunch_id, task_id, ordering, start_if)
             VALUES (sequence_nextval('rhn_tasko_template_id_seq'),
                        (SELECT id FROM rhnTaskoBunch WHERE name='cleanup-data-bunch'),
                        (SELECT id FROM rhnTaskoTask WHERE name='cleanup-packagechangelog-data'),
                        0,
                        null);

INSERT INTO rhnTaskoTemplate (id, bunch_id, task_id, ordering, start_if)
             VALUES (sequence_nextval('rhn_tasko_template_id_seq'),
                        (SELECT id FROM rhnTaskoBunch WHERE name='reboot-action-cleanup-bunch'),
                        (SELECT id FROM rhnTaskoTask WHERE name='reboot-action-cleanup'),
                        0,
                        null);

INSERT INTO rhnTaskoTemplate (id, bunch_id, task_id, ordering, start_if)
             VALUES (sequence_nextval('rhn_tasko_template_id_seq'),
                        (SELECT id FROM rhnTaskoBunch WHERE name='ssh-push-bunch'),
                        (SELECT id FROM rhnTaskoTask WHERE name='ssh-push'),
                        0,
                        null);

INSERT INTO rhnTaskoTemplate (id, bunch_id, task_id, ordering, start_if)
             VALUES (sequence_nextval('rhn_tasko_template_id_seq'),
                        (SELECT id FROM rhnTaskoBunch WHERE name='cve-server-channels-bunch'),
                        (SELECT id FROM rhnTaskoTask WHERE name='cve-server-channels'),
                        0,
                        null);

INSERT INTO rhnTaskoTemplate (id, bunch_id, task_id, ordering, start_if)
             VALUES (sequence_nextval('rhn_tasko_template_id_seq'),
                        (SELECT id FROM rhnTaskoBunch WHERE name='auto-errata-bunch'),
                        (SELECT id FROM rhnTaskoTask WHERE name='auto-errata'),
                        0,
                        null);

INSERT INTO rhnTaskoTemplate (id, bunch_id, task_id, ordering, start_if)
             VALUES (sequence_nextval('rhn_tasko_template_id_seq'),
                        (SELECT id FROM rhnTaskoBunch WHERE name='mgr-sync-refresh-bunch'),
                        (SELECT id FROM rhnTaskoTask WHERE name='mgr-sync-refresh'),
                        0,
                        null);

INSERT INTO rhnTaskoTemplate (id, bunch_id, task_id, ordering, start_if)
             VALUES (sequence_nextval('rhn_tasko_template_id_seq'),
                        (SELECT id FROM rhnTaskoBunch WHERE name='gatherer-matcher-bunch'),
                        (SELECT id FROM rhnTaskoTask WHERE name='gatherer'),
                        0,
                        null);

INSERT INTO rhnTaskoTemplate (id, bunch_id, task_id, ordering, start_if)
             VALUES (sequence_nextval('rhn_tasko_template_id_seq'),
                        (SELECT id FROM rhnTaskoBunch WHERE name='gatherer-matcher-bunch'),
                        (SELECT id FROM rhnTaskoTask WHERE name='matcher'),
                        1,
                        'FINISHED');

INSERT INTO rhnTaskoTemplate (id, bunch_id, task_id, ordering, start_if)
             VALUES (sequence_nextval('rhn_tasko_template_id_seq'),
                        (SELECT id FROM rhnTaskoBunch WHERE name='uuid-cleanup-bunch'),
                        (SELECT id FROM rhnTaskoTask WHERE name='uuid-cleanup'),
                        0,
                        null);

INSERT INTO rhnTaskoTemplate (id, bunch_id, task_id, ordering, start_if)
             VALUES (sequence_nextval('rhn_tasko_template_id_seq'),
                        (SELECT id FROM rhnTaskoBunch WHERE name='minion-action-cleanup-bunch'),
                        (SELECT id FROM rhnTaskoTask WHERE name='minion-action-cleanup'),
                        0,
                        null);

INSERT INTO rhnTaskoTemplate (id, bunch_id, task_id, ordering, start_if)
             VALUES (sequence_nextval('rhn_tasko_template_id_seq'),
                        (SELECT id FROM rhnTaskoBunch WHERE name='token-cleanup-bunch'),
                        (SELECT id FROM rhnTaskoTask WHERE name='token-cleanup'),
                        0,
                        null);

INSERT INTO rhnTaskoTemplate (id, bunch_id, task_id, ordering, start_if)
             VALUES (sequence_nextval('rhn_tasko_template_id_seq'),
                        (SELECT id FROM rhnTaskoBunch WHERE name='minion-action-executor-bunch'),
                        (SELECT id FROM rhnTaskoTask WHERE name='minion-action-executor'),
                        0,
                        null);

INSERT INTO rhnTaskoTemplate (id, bunch_id, task_id, ordering, start_if)
            VALUES (sequence_nextval('rhn_tasko_template_id_seq'),
                        (SELECT id FROM rhnTaskoBunch WHERE name='minion-action-chain-executor-bunch'),
                        (SELECT id FROM rhnTaskoTask WHERE name='minion-action-chain-executor'),
                        0,
                        null);

INSERT INTO rhnTaskoTemplate (id, bunch_id, task_id, ordering, start_if)
            VALUES (sequence_nextval('rhn_tasko_template_id_seq'),
                        (SELECT id FROM rhnTaskoBunch WHERE name='minion-action-chain-cleanup-bunch'),
                        (SELECT id FROM rhnTaskoTask WHERE name='minion-action-chain-cleanup'),
                        0,
                        null);

INSERT INTO rhnTaskoTemplate (id, bunch_id, task_id, ordering, start_if)
            VALUES (sequence_nextval('rhn_tasko_template_id_seq'),
                        (SELECT id FROM rhnTaskoBunch WHERE name='notifications-cleanup-bunch'),
                        (SELECT id FROM rhnTaskoTask WHERE name='notifications-cleanup'),
                        0,
                        null);

INSERT INTO rhnTaskoTemplate (id, bunch_id, task_id, ordering, start_if)
            VALUES (sequence_nextval('rhn_tasko_template_id_seq'),
                        (SELECT id FROM rhnTaskoBunch WHERE name='minion-checkin-bunch'),
                        (SELECT id FROM rhnTaskoTask WHERE name='minion-checkin'),
                        0,
                        null);

INSERT INTO rhnTaskoTemplate (id, bunch_id, task_id, ordering, start_if)
            VALUES (sequence_nextval('rhn_tasko_template_id_seq'),
                        (SELECT id FROM rhnTaskoBunch WHERE name='recurring-action-executor-bunch'),
                        (SELECT id FROM rhnTaskoTask WHERE name='recurring-action-executor'),
                        0,
                        null);

INSERT INTO rhnTaskoTemplate (id, bunch_id, task_id, ordering, start_if)
            VALUES (sequence_nextval('rhn_tasko_template_id_seq'),
                        (SELECT id FROM rhnTaskoBunch WHERE name='ssh-minion-action-executor-bunch'),
                        (SELECT id FROM rhnTaskoTask WHERE name='ssh-minion-action-executor'),
                        0,
                        null);

INSERT INTO rhnTaskoTemplate (id, bunch_id, task_id, ordering, start_if)
            VALUES (sequence_nextval('rhn_tasko_template_id_seq'),
                        (SELECT id FROM rhnTaskoBunch WHERE name='cleanup-data-bunch'),
                        (SELECT id FROM rhnTaskoTask WHERE name='channel-modular-data-cleanup'),
                        1,
                        null);

INSERT INTO rhnTaskoTemplate (id, bunch_id, task_id, ordering, start_if)
            VALUES (sequence_nextval('rhn_tasko_template_id_seq'),
                        (SELECT id FROM rhnTaskoBunch WHERE name='mgr-forward-registration-bunch'),
                        (SELECT id FROM rhnTaskoTask WHERE name='mgr-forward-registration'),
                        0,
                        null);

INSERT INTO rhnTaskoTemplate (id, bunch_id, task_id, ordering, start_if)
            VALUES (sequence_nextval('rhn_tasko_template_id_seq'),
                        (SELECT id FROM rhnTaskoBunch WHERE name = 'update-payg-data-bunch'),
                        (SELECT id FROM rhnTaskoTask WHERE name = 'update-payg-auth'),
                        0,
                        null);

INSERT INTO rhnTaskoTemplate (id, bunch_id, task_id, ordering, start_if)
            VALUES (sequence_nextval('rhn_tasko_template_id_seq'),
                        (SELECT id FROM rhnTaskoBunch WHERE name = 'update-payg-data-bunch'),
                        (SELECT id FROM rhnTaskoTask WHERE name = 'update-payg-hosts'),
                        1,
                        null);

INSERT INTO rhnTaskoTemplate (id, bunch_id, task_id, ordering, start_if)
            VALUES (sequence_nextval('rhn_tasko_template_id_seq'),
                        (SELECT id FROM rhnTaskoBunch WHERE name='mgr-update-reporting-bunch'),
                        (SELECT id FROM rhnTaskoTask WHERE name='mgr-update-reporting'),
                        0,
                        null);

INSERT INTO rhnTaskoTemplate (id, bunch_id, task_id, ordering, start_if)
            VALUES (sequence_nextval('rhn_tasko_template_id_seq'),
                    (SELECT id FROM rhnTaskoBunch WHERE name='mgr-update-reporting-hub-bunch'),
                    (SELECT id FROM rhnTaskoTask WHERE name='mgr-update-reporting-hub'),
                    0,
                    null);

INSERT INTO rhnTaskoTemplate (id, bunch_id, task_id, ordering, start_if)
            VALUES (sequence_nextval('rhn_tasko_template_id_seq'),
                    (SELECT id FROM rhnTaskoBunch WHERE name='system-profile-refresh-bunch'),
                    (SELECT id FROM rhnTaskoTask WHERE name='system-profile-refresh'),
                    0,
                    null);

INSERT INTO rhnTaskoTemplate (id, bunch_id, task_id, ordering, start_if)
            VALUES (sequence_nextval('rhn_tasko_template_id_seq'),
                    (SELECT id FROM rhnTaskoBunch WHERE name='payg-dimension-computation-bunch'),
                    (SELECT id FROM rhnTaskoTask WHERE name='payg-dimension-computation'),
                    0,
                    null);

commit;
0707010000003C000081B400000000000000000000000167AE1114000003F0000000000000000000000000000000000000003700000000susemanager-schema/common/data/rhnTemplateCategory.sql    --
-- Copyright (c) 2008--2010 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
-- data for rhnTemplateCategory

INSERT INTO rhnTemplateCategory (id, label, description) 
     VALUES (sequence_nextval('rhn_template_cat_id_seq'), 'org_strings', 'Organization specific strings.');

INSERT INTO rhnTemplateCategory (id, label, description)
     VALUES (sequence_nextval('rhn_template_cat_id_seq'), 'email_strings', 'Strings appearing in e-mail sent to users.');
0707010000003D000081B400000000000000000000000167AE1114000005A8000000000000000000000000000000000000003500000000susemanager-schema/common/data/rhnTemplateString.sql  --
-- Copyright (c) 2008--2010 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
-- data for rhnTemplateString

INSERT INTO rhnTemplateString (id, category_id, label, value, description) 
     VALUES (sequence_nextval('rhn_template_str_id_seq'),
             (SELECT TC.id 
                FROM rhnTemplateCategory TC
	       WHERE TC.label = 'email_strings'),
	     'email_footer', '-' || '-the SUSE Manager Team', 'Footer for SUSE Manager e-mail');

INSERT INTO rhnTemplateString (id, category_id, label, value, description) 
     VALUES (sequence_nextval('rhn_template_str_id_seq'),
             (SELECT TC.id 
                FROM rhnTemplateCategory TC
	       WHERE TC.label = 'email_strings'),
	     'email_account_info', '
Account Information:
  Your SUSE Manager login:         <login />
  Your SUSE Manager email address: <email-address />', 'Account info lines for SUSE Manager e-mail');

0707010000003E000081B400000000000000000000000167AE111400002005000000000000000000000000000000000000002F00000000susemanager-schema/common/data/rhnTimezone.sql    --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
-- data for rhnTimezone

insert into rhnTimezone
  (id, olson_name, display_name)
values
  (sequence_nextval('rhn_timezone_id_seq'),
   'Australia/Brisbane', 'Australia (Eastern Standard)');


insert into rhnTimezone
  (id, olson_name, display_name)
values
  (sequence_nextval('rhn_timezone_id_seq'),
   'Australia/Sydney', 'Australia (Eastern Daylight)');


insert into rhnTimezone
  (id, olson_name, display_name)
values
  (sequence_nextval('rhn_timezone_id_seq'),
   'Asia/Tokyo', 'Japan');


insert into rhnTimezone
  (id, olson_name, display_name)
values
  (sequence_nextval('rhn_timezone_id_seq'),
   'Asia/Seoul', 'Korea');


insert into rhnTimezone
  (id, olson_name, display_name)
values
  (sequence_nextval('rhn_timezone_id_seq'),
   'Australia/Perth', 'Australia (Western)');


insert into rhnTimezone
  (id, olson_name, display_name)
values
  (sequence_nextval('rhn_timezone_id_seq'),
   'Europe/Moscow', 'Russia (Moscow)');


insert into rhnTimezone
  (id, olson_name, display_name)
values
  (sequence_nextval('rhn_timezone_id_seq'),
   'Europe/Bucharest', 'Europe (Eastern)');


insert into rhnTimezone
  (id, olson_name, display_name)
values
  (sequence_nextval('rhn_timezone_id_seq'),
   'Europe/Paris', 'Europe (Central)');


insert into rhnTimezone
  (id, olson_name, display_name)
values
  (sequence_nextval('rhn_timezone_id_seq'),
   'GMT', 'Greenwich Mean Time');


insert into rhnTimezone
  (id, olson_name, display_name)
values
  (sequence_nextval('rhn_timezone_id_seq'),
   'America/St_Johns', 'Canada (Newfoundland)');


insert into rhnTimezone
  (id, olson_name, display_name)
values
  (sequence_nextval('rhn_timezone_id_seq'),
   'America/Halifax', 'Canada (Atlantic)');


insert into rhnTimezone
  (id, olson_name, display_name)
values
  (sequence_nextval('rhn_timezone_id_seq'),
   'America/New_York', 'United States (Eastern)');

insert into rhnTimezone
  (id, olson_name, display_name)
values
  (sequence_nextval('rhn_timezone_id_seq'),
   'America/Indianapolis', 'United States (Indiana)');

insert into rhnTimezone
  (id, olson_name, display_name)
values
  (sequence_nextval('rhn_timezone_id_seq'),
   'America/Chicago', 'United States (Central)');

insert into rhnTimezone
  (id, olson_name, display_name)
values
  (sequence_nextval('rhn_timezone_id_seq'),
   'America/Regina', 'Canada (Regina)');


insert into rhnTimezone
  (id, olson_name, display_name)
values
  (sequence_nextval('rhn_timezone_id_seq'),
   'America/Denver', 'United States (Mountain)');


insert into rhnTimezone
  (id, olson_name, display_name)
values
  (sequence_nextval('rhn_timezone_id_seq'),
   'America/Phoenix', 'United States (Arizona)');

insert into rhnTimezone
  (id, olson_name, display_name)
values
  (sequence_nextval('rhn_timezone_id_seq'),
   'America/Los_Angeles', 'United States (Pacific)');


insert into rhnTimezone
  (id, olson_name, display_name)
values
  (sequence_nextval('rhn_timezone_id_seq'),
   'America/Anchorage', 'United States (Alaska)');

insert into rhnTimezone
  (id, olson_name, display_name)
values
  (sequence_nextval('rhn_timezone_id_seq'),
   'America/Santiago', 'Chile (Continental)');

insert into rhnTimezone
  (id, olson_name, display_name)
values
  (sequence_nextval('rhn_timezone_id_seq'),
   'Pacific/Honolulu', 'United States (Hawaii)');

insert into rhnTimezone
  (id, olson_name, display_name)
values
  (sequence_nextval('rhn_timezone_id_seq'),
   'Pacific/Enderbury', 'Tonga');

insert into rhnTimezone
  (id, olson_name, display_name)
values
  (sequence_nextval('rhn_timezone_id_seq'),
   'Pacific/Wallis', 'New Zealand (Wallis)');

insert into rhnTimezone
  (id, olson_name, display_name)
values
  (sequence_nextval('rhn_timezone_id_seq'),
   'Pacific/Auckland', 'New Zealand (Auckland)');

insert into rhnTimezone
  (id, olson_name, display_name)
values
  (sequence_nextval('rhn_timezone_id_seq'),
   'Pacific/Norfolk', 'Norfolk Island');

insert into rhnTimezone
  (id, olson_name, display_name)
values
  (sequence_nextval('rhn_timezone_id_seq'),
   'Pacific/Guadalcanal', 'Micronesia');

insert into rhnTimezone
  (id, olson_name, display_name)
values
  (sequence_nextval('rhn_timezone_id_seq'),
   'Australia/Darwin', 'Australia (Central/Darwin)');

insert into rhnTimezone
  (id, olson_name, display_name)
values
  (sequence_nextval('rhn_timezone_id_seq'),
   'Asia/Jakarta', 'Thailand');

insert into rhnTimezone
  (id, olson_name, display_name)
values
  (sequence_nextval('rhn_timezone_id_seq'),
   'Indian/Cocos', 'Burma');

insert into rhnTimezone
  (id, olson_name, display_name)
values
  (sequence_nextval('rhn_timezone_id_seq'),
   'Indian/Chagos', 'Bangladesh');

insert into rhnTimezone
  (id, olson_name, display_name)
values
  (sequence_nextval('rhn_timezone_id_seq'),
   'Asia/Katmandu', 'Nepal');

insert into rhnTimezone
  (id, olson_name, display_name)
values
  (sequence_nextval('rhn_timezone_id_seq'),
   'Asia/Calcutta', 'India (Calcutta)');

insert into rhnTimezone
  (id, olson_name, display_name)
values
  (sequence_nextval('rhn_timezone_id_seq'),
   'Indian/Maldives', 'Pakistan');

insert into rhnTimezone
  (id, olson_name, display_name)
values
  (sequence_nextval('rhn_timezone_id_seq'),
   'Asia/Kabul', 'Afghanistan');

insert into rhnTimezone
  (id, olson_name, display_name)
values
  (sequence_nextval('rhn_timezone_id_seq'),
   'Asia/Riyadh', 'Saudi Arabia');

insert into rhnTimezone
  (id, olson_name, display_name)
values
  (sequence_nextval('rhn_timezone_id_seq'),
   'Asia/Tehran', 'Iran');

insert into rhnTimezone
  (id, olson_name, display_name)
values
  (sequence_nextval('rhn_timezone_id_seq'),
   'Indian/Mauritius', 'Russia (Samara)');

insert into rhnTimezone
  (id, olson_name, display_name)
values
  (sequence_nextval('rhn_timezone_id_seq'),
   'Atlantic/Azores', 'Azores');

insert into rhnTimezone
  (id, olson_name, display_name)
values
  (sequence_nextval('rhn_timezone_id_seq'),
   'Atlantic/South_Georgia', 'Sandwich Islands');

insert into rhnTimezone
  (id, olson_name, display_name)
values
  (sequence_nextval('rhn_timezone_id_seq'),
   'Pacific/Easter', 'Chile (Easter Island)');

insert into rhnTimezone
  (id, olson_name, display_name)
values
  (sequence_nextval('rhn_timezone_id_seq'),
   'Pacific/Midway', 'Midway');

insert into rhnTimezone
  (id, olson_name, display_name)
values
  (sequence_nextval('rhn_timezone_id_seq'),
   'America/Sao_Paulo', 'Brazil');


insert into rhnTimezone
  (id, olson_name, display_name)
values
  (sequence_nextval('rhn_timezone_id_seq'),
   'GB', 'Great Britain');

insert into rhnTimezone
  (id, olson_name, display_name)
values
  (sequence_nextval('rhn_timezone_id_seq'),
   'GB-Eire', 'Ireland');

insert into rhnTimezone
  (id, olson_name, display_name)
values
  (sequence_nextval('rhn_timezone_id_seq'),
   'Africa/Johannesburg', 'South Africa (Johannesburg)');

insert into rhnTimezone
  (id, olson_name, display_name)
values
  (sequence_nextval('rhn_timezone_id_seq'),
   'Australia/Adelaide', 'Australia Central (Adelaide)');

insert into rhnTimezone
  (id, olson_name, display_name)
values
  (sequence_nextval('rhn_timezone_id_seq'),
   'Asia/Jerusalem', 'Israel');

insert into rhnTimezone
  (id, olson_name, display_name)
values
  (sequence_nextval('rhn_timezone_id_seq'),
   'Asia/Singapore', 'Singapore');

insert into rhnTimezone
  (id, olson_name, display_name)
values
  (sequence_nextval('rhn_timezone_id_seq'),
   'Asia/Kuala_Lumpur', 'Malaysia');

insert into rhnTimezone
  (id, olson_name, display_name)
values
  (sequence_nextval('rhn_timezone_id_seq'),
   'Asia/Shanghai', 'China');

commit;
   0707010000003F000081B400000000000000000000000167AE111400000374000000000000000000000000000000000000003B00000000susemanager-schema/common/data/rhnTransactionOperation.sql    --
-- Copyright (c) 2008--2013 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--
-- data for rhnTransactionOperation

insert into rhnTransactionOperation (id, label) values (1,'insert');
insert into rhnTransactionOperation (id, label) values (2,'delete');
insert into rhnTransactionOperation (id, label) values (3,'upgrade');

07070100000040000081B400000000000000000000000167AE1114000006D1000000000000000000000000000000000000003400000000susemanager-schema/common/data/rhnUserGroupType.sql   --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--
-- data for rhnUserGroupType

insert into rhnUserGroupType (id, label, name) values (
	sequence_nextval('rhn_usergroup_type_seq'),
	'satellite_admin',
	'SUSE Manager Administrator'
);

insert into rhnUserGroupType (id, label, name) values (
	sequence_nextval('rhn_usergroup_type_seq'),
	'org_admin',
	'Organization Administrator'
);

insert into rhnUserGroupType (id, label, name) values (
	sequence_nextval('rhn_usergroup_type_seq'),
	'channel_admin',
	'Channel Administrator'
);

insert into rhnUserGroupType (id, label, name) values (
	sequence_nextval('rhn_usergroup_type_seq'),
	'config_admin',
	'Configuration Administrator'
);

insert into rhnUserGroupType (id, label, name) values (
	sequence_nextval('rhn_usergroup_type_seq'),
	'system_group_admin',
	'System Group Administrator'
);

insert into rhnUserGroupType (id, label, name) values (
	sequence_nextval('rhn_usergroup_type_seq'),
	'activation_key_admin',
	'Activation Key Administrator'
);

insert into rhnUserGroupType (id, label, name) values (
	sequence_nextval('rhn_usergroup_type_seq'),
	'image_admin',
	'Image Administrator'
);

commit;
   07070100000041000081B400000000000000000000000167AE1114000001B3000000000000000000000000000000000000003200000000susemanager-schema/common/data/rhnVersionInfo.pre --
-- this populates rhnVersionInfo.  It needs to be run through sed
-- during build.  see Makefile.schema
--

DELETE FROM rhnVersionInfo
WHERE label = 'schema' and
      name_id = lookup_package_name(SCHEMA_NAME);

INSERT INTO rhnVersionInfo
(
    label,
    name_id,
    evr_id
)
( SELECT 'schema',
         lookup_package_name(SCHEMA_NAME),
         lookup_evr(NULL, SCHEMA_VERSION , SCHEMA_RELEASE, 'rpm' )
  FROM dual
);
commit;

 07070100000042000081B400000000000000000000000167AE11140000068C000000000000000000000000000000000000003F00000000susemanager-schema/common/data/rhnVirtualInstanceEventType.sql    --
-- Copyright (c) 2008--2010 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
-- data for rhnVirtualInstanceEventType

insert into rhnVirtualInstanceEventType (id, name, label) values (sequence_nextval('rhn_viet_id_seq'), 'Create', 'create');
insert into rhnVirtualInstanceEventType (id, name, label) values (sequence_nextval('rhn_viet_id_seq'), 'Destroy', 'destroy');
insert into rhnVirtualInstanceEventType (id, name, label) values (sequence_nextval('rhn_viet_id_seq'), 'Shutdown', 'shutdown');
insert into rhnVirtualInstanceEventType (id, name, label) values (sequence_nextval('rhn_viet_id_seq'), 'Pause', 'pause');
insert into rhnVirtualInstanceEventType (id, name, label) values (sequence_nextval('rhn_viet_id_seq'), 'Unpause', 'unpause');
insert into rhnVirtualInstanceEventType (id, name, label) values (sequence_nextval('rhn_viet_id_seq'), 'Migrate', 'migrate');
insert into rhnVirtualInstanceEventType (id, name, label) values (sequence_nextval('rhn_viet_id_seq'), 'Vcpu-Set', 'vcpu-set');
insert into rhnVirtualInstanceEventType (id, name, label) values (sequence_nextval('rhn_viet_id_seq'), 'Mem-Set', 'mem-set');
07070100000043000081B400000000000000000000000167AE111400000969000000000000000000000000000000000000003B00000000susemanager-schema/common/data/rhnVirtualInstanceState.sql    --
-- Copyright (c) 2008--2010 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
-- data for rhnVirtualInstanceState

insert into rhnVirtualInstanceState (id, name, label) values (sequence_nextval('rhn_vis_id_seq'), 'Unknown', 'unknown');
insert into rhnVirtualInstanceState (id, name, label) values (sequence_nextval('rhn_vis_id_seq'), 'Running', 'running');
insert into rhnVirtualInstanceState (id, name, label) values (sequence_nextval('rhn_vis_id_seq'), 'Stopped', 'stopped');
insert into rhnVirtualInstanceState (id, name, label) values (sequence_nextval('rhn_vis_id_seq'), 'Crashed', 'crashed');
insert into rhnVirtualInstanceState (id, name, label) values (sequence_nextval('rhn_vis_id_seq'), 'Paused', 'paused');
insert into rhnVirtualInstanceState (id, name, label) values (sequence_nextval('rhn_vis_id_seq'), 'Powering On', 'powering_on');
insert into rhnVirtualInstanceState (id, name, label) values (sequence_nextval('rhn_vis_id_seq'), 'Shutting Down', 'shutting_down');
insert into rhnVirtualInstanceState (id, name, label) values (sequence_nextval('rhn_vis_id_seq'), 'Powering Off', 'powering_off');
insert into rhnVirtualInstanceState (id, name, label) values (sequence_nextval('rhn_vis_id_seq'), 'Pausing', 'pausing');
insert into rhnVirtualInstanceState (id, name, label) values (sequence_nextval('rhn_vis_id_seq'), 'Suspending', 'suspending');
insert into rhnVirtualInstanceState (id, name, label) values (sequence_nextval('rhn_vis_id_seq'), 'Suspended', 'suspended');
insert into rhnVirtualInstanceState (id, name, label) values (sequence_nextval('rhn_vis_id_seq'), 'Resuming', 'resuming');
insert into rhnVirtualInstanceState (id, name, label) values (sequence_nextval('rhn_vis_id_seq'), 'Resetting', 'resetting');
insert into rhnVirtualInstanceState (id, name, label) values (sequence_nextval('rhn_vis_id_seq'), 'Migrating', 'migrating');

   07070100000044000081B400000000000000000000000167AE1114000009B0000000000000000000000000000000000000003A00000000susemanager-schema/common/data/rhnVirtualInstanceType.sql --
-- Copyright (c) 2008--2010 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
-- data for rhnVirtualInstanceType


insert into rhnVirtualInstanceType (id, name, label)
     values (sequence_nextval('rhn_vit_id_seq'), 'Fully Virtualized', 'fully_virtualized');

insert into rhnVirtualInstanceType (id, name, label)
     values (sequence_nextval('rhn_vit_id_seq'), 'Para-Virtualized', 'para_virtualized');

insert into rhnVirtualInstanceType (id, name, label)
      values (sequence_nextval('rhn_vit_id_seq'), 'KVM/QEMU', 'qemu');

insert into rhnVirtualInstanceType (id, name, label) 
    values (sequence_nextval('rhn_vit_id_seq'), 'VMware', 'vmware');

insert into rhnVirtualInstanceType (id, name, label) 
    values (sequence_nextval('rhn_vit_id_seq'), 'Hyper-V', 'hyperv');

insert into rhnVirtualInstanceType (id, name, label) 
    values (sequence_nextval('rhn_vit_id_seq'), 'Virtage', 'virtage');

insert into rhnVirtualInstanceType (id, name, label)
    values (sequence_nextval('rhn_vit_id_seq'), 'VirtualBox', 'virtualbox');

insert into rhnVirtualInstanceType (id, name, label)
    values (sequence_nextval('rhn_vit_id_seq'), 'Azure', 'azure');

insert into rhnVirtualInstanceType (id, name, label)
    values (sequence_nextval('rhn_vit_id_seq'), 'Amazon EC2', 'aws');

insert into rhnVirtualInstanceType (id, name, label)
    values (sequence_nextval('rhn_vit_id_seq'), 'Amazon EC2/Nitro', 'aws_nitro');

insert into rhnVirtualInstanceType (id, name, label)
    values (sequence_nextval('rhn_vit_id_seq'), 'Amazon EC2/Xen', 'aws_xen');

insert into rhnVirtualInstanceType (id, name, label)
    values (sequence_nextval('rhn_vit_id_seq'), 'Google CE', 'gce');

insert into rhnVirtualInstanceType (id, name, label)
    values (sequence_nextval('rhn_vit_id_seq'), 'Nutanix AHV', 'nutanix');

insert into rhnVirtualInstanceType (id, name, label)
    values (sequence_nextval('rhn_vit_id_seq'), 'VirtualPC', 'virtualpc');
07070100000045000081B400000000000000000000000167AE111400000368000000000000000000000000000000000000003C00000000susemanager-schema/common/data/rhnWebContactChangeState.sql   --
-- Copyright (c) 2008--2013 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--
insert into rhnWebContactChangeState (id, label) values (sequence_nextval('rhn_wcon_change_state_seq'), 'enabled');
insert into rhnWebContactChangeState (id, label) values (sequence_nextval('rhn_wcon_change_state_seq'), 'disabled');

07070100000046000081B400000000000000000000000167AE111400000768000000000000000000000000000000000000003A00000000susemanager-schema/common/data/rhnXccdfRuleresultType.sql --
-- Copyright (c) 2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

insert into rhnXccdfRuleresultType values (1, 'P', 'pass',
    'The target system satisfied all the conditions of the xccdf:Rule.');
insert into rhnXccdfRuleresultType values (2, 'F', 'fail',
    'The target system did not satisfy all the conditions of the xccdf:Rule');
insert into rhnXccdfRuleresultType values (3, 'E', 'error',
    'The checking engine could not complete the evaluation, therefore the status of compliance is uncertain.');
insert into rhnXccdfRuleresultType values (4, 'U', 'unknown',
    'The testing tool encountered some problem and the result is unknown.');
insert into rhnXccdfRuleresultType values (5, 'N', 'notapplicable',
    'The xccdf:Rule was not applicable to the target.');
insert into rhnXccdfRuleresultType values (6, 'K', 'notchecked',
    'The xccdf:Rule was not evaluated by the checking engine; xccdf:check was either unspecified or unsupported.');
insert into rhnXccdfRuleresultType values (7, 'S', 'notselected',
    'The xccdf:Rule was not selected in the profile.');
insert into rhnXccdfRuleresultType values (8, 'I', 'informational',
    'The xccdf:Rule was not checked; it is not a compliance category.');
insert into rhnXccdfRuleresultType values (9, 'X', 'fixed',
    'The xccdf:Rule had failed, but was then fixed by tool.');
07070100000047000081B400000000000000000000000167AE111400000377000000000000000000000000000000000000003600000000susemanager-schema/common/data/suseImageStoreType.sql --
-- Copyright (c) 2017 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

insert into suseImageStoreType (id, label, name) values
	(sequence_nextval('suse_imgstore_type_id_seq'), 'registry', 'Registry');

insert into suseImageStoreType (id, label, name) values
	(sequence_nextval('suse_imgstore_type_id_seq'), 'os_image', 'OS Image');

commit;
 07070100000048000081B400000000000000000000000167AE11140000068D000000000000000000000000000000000000003500000000susemanager-schema/common/data/suseInternalState.sql  --
-- Copyright (c) 2023 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
INSERT INTO suseInternalState (id, name, label)
         VALUES (1, 'certs', 'Certificates');

INSERT INTO suseInternalState (id, name, label)
         VALUES (2, 'channels', 'Channels');

INSERT INTO suseInternalState (id, name, label)
         VALUES (3, 'hardware.profileupdate', 'Hardware Profile Update');

INSERT INTO suseInternalState (id, name, label)
         VALUES (4, 'packages', 'Packages');

INSERT INTO suseInternalState (id, name, label)
         VALUES (5, 'packages.profileupdate', 'Package Profile Update');

INSERT INTO suseInternalState (id, name, label)
         VALUES (6, 'uptodate', 'Update System');

INSERT INTO suseInternalState (id, name, label)
         VALUES (7, 'util.syncbeacons', 'Sync Beacons');

INSERT INTO suseInternalState (id, name, label)
         VALUES (8, 'util.syncall', 'Sync All');

INSERT INTO suseInternalState (id, name, label)
         VALUES (9, 'util.syncgrains', 'Sync Grains');

INSERT INTO suseInternalState (id, name, label)
         VALUES (10, 'util.syncmodules', 'Sync Modules');

INSERT INTO suseInternalState (id, name, label)
         VALUES (11, 'util.syncstates', 'Sync States');

INSERT INTO suseInternalState (id, name, label)
         VALUES (12, 'update-salt', 'Update Salt');
   07070100000049000081B400000000000000000000000167AE11140000033E000000000000000000000000000000000000003800000000susemanager-schema/common/data/susePackageStateType.sql   --
-- Copyright (c) 2015 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

insert into susePackageStateType (id, label) values (0, 'installed');
insert into susePackageStateType (id, label) values (1, 'removed');
insert into susePackageStateType (id, label) values (2, 'purged');
commit;
  0707010000004A000081B400000000000000000000000167AE111400000328000000000000000000000000000000000000003B00000000susemanager-schema/common/data/suseServerContactMethod.sql    --
-- Copyright (c) 2013 SUSE
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--

insert into suseServerContactMethod (id, label, name, rank) values
	(0, 'default', 'server.contact-method.default', 0);
insert into suseServerContactMethod (id, label, name, rank) values
	(1, 'ssh-push', 'server.contact-method.ssh-push', 10);
insert into suseServerContactMethod (id, label, name, rank) values
	(2, 'ssh-push-tunnel', 'server.contact-method.ssh-push-tunnel', 20);

0707010000004B000081B400000000000000000000000167AE1114000002FE000000000000000000000000000000000000003D00000000susemanager-schema/common/data/suseVersionConstraintType.sql  --
-- Copyright (c) 2015 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

insert into suseVersionConstraintType (id, label) values (0, 'latest');
insert into suseVersionConstraintType (id, label) values (1, 'any');
commit;
  0707010000004C000081B400000000000000000000000167AE11140000705D000000000000000000000000000000000000003300000000susemanager-schema/common/data/valid_countries.sql    --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--

insert into valid_countries(code,short_name,name) values ('AD','Andorra','Principality of Andorra');
insert into valid_countries(code,short_name,name) values ('AE','United Arab Emirates','United Arab Emirates');
insert into valid_countries(code,short_name,name) values ('AF','Afghanistan','Islamic State of Afghanistan');
insert into valid_countries(code,short_name,name) values ('AG','Antigua and Barbuda','Antigua and Barbuda (includes Redonda)');
insert into valid_countries(code,short_name,name) values ('AI','Anguilla','Anguilla');
insert into valid_countries(code,short_name,name) values ('AL','Albania','Republic of Albania');
insert into valid_countries(code,short_name,name) values ('AM','Armenia','Republic of Armenia');
insert into valid_countries(code,short_name,name) values ('AN','Netherlands Antilles','Netherlands Antilles (includes Bonaire, Curacao, Saba, St. Eustatius, and Southern St. Martin)');
insert into valid_countries(code,short_name,name) values ('AO','Angola','Republic of Angola');
insert into valid_countries(code,short_name,name) values ('AQ','Antarctica','Territory south of 60 degrees south latitude');
insert into valid_countries(code,short_name,name) values ('AR','Argentina','Argentine Republic');
insert into valid_countries(code,short_name,name) values ('AS','American Samoa','American Samoa');
insert into valid_countries(code,short_name,name) values ('AT','Austria','Republic of Austria');
insert into valid_countries(code,short_name,name) values ('AU','Australia','Australia (includes Lord Howe Island, Macquarie Islands, Ashmore Islands and Cartier Island, and Coral Sea Islands are Australian external territories)');
insert into valid_countries(code,short_name,name) values ('AW','Aruba','Aruba');
insert into valid_countries(code,short_name,name) values ('AZ','Azerbaijan','Azerbaijani Republic');
insert into valid_countries(code,short_name,name) values ('BA','Bosnia and Herzegovina','Republic of Bosnia and Herzegovina');
insert into valid_countries(code,short_name,name) values ('BB','Barbados','Barbados');
insert into valid_countries(code,short_name,name) values ('BD','Bangladesh','Bangladesh');
insert into valid_countries(code,short_name,name) values ('BE','Belgium','Kingdom of Belgium');
insert into valid_countries(code,short_name,name) values ('BF','Burkina Faso','Burma see Myanmar');
insert into valid_countries(code,short_name,name) values ('BG','Bulgaria','Republic of Bulgaria');
insert into valid_countries(code,short_name,name) values ('BH','Bahrain','State of Bahrain');
insert into valid_countries(code,short_name,name) values ('BI','Burundi','Republic of Burundi');
insert into valid_countries(code,short_name,name) values ('BJ','Benin','Republic of Benin');
insert into valid_countries(code,short_name,name) values ('BM','Bermuda','Bermuda');
insert into valid_countries(code,short_name,name) values ('BN','Brunei Darussalam','Brunei Darussalam');
insert into valid_countries(code,short_name,name) values ('BO','Bolivia','Republic of Bolivia');
insert into valid_countries(code,short_name,name) values ('BR','Brazil','Federative Republic of Brazil (includes Rocas, Fernando de Noronha Archipelago, Trindade, Ilhas Martim Vaz, and Sao Pedro e Sao Paulo)');
insert into valid_countries(code,short_name,name) values ('BS','Bahamas','Commonwealth of the Bahamas (Turks and Caicos Islands not included)');
insert into valid_countries(code,short_name,name) values ('BT','Bhutan','Kingdom of Bhutan');
insert into valid_countries(code,short_name,name) values ('BV','Bouvet Island','Bouvet Island (also called Bouvetoya)');
insert into valid_countries(code,short_name,name) values ('BW','Botswana','Republic of Botswana');
insert into valid_countries(code,short_name,name) values ('BY','Belarus','Republic of Belarus');
insert into valid_countries(code,short_name,name) values ('BZ','Belize','Belize');
insert into valid_countries(code,short_name,name) values ('CA','Canada','Canada');
insert into valid_countries(code,short_name,name) values ('CC','Cocos (Keeling) Islands','Cocos (Keeling) Islands');
insert into valid_countries(code,short_name,name) values ('CF','Central African Republic','Central African Republic');
insert into valid_countries(code,short_name,name) values ('CG','Congo','Republic of the Congo');
insert into valid_countries(code,short_name,name) values ('CH','Switzerland','Swiss Confederation');
insert into valid_countries(code,short_name,name) values ('CI','Cote d''Ivoire','Republic of Cote d''Ivoire');
insert into valid_countries(code,short_name,name) values ('CK','Cook Islands','Cook Islands');
insert into valid_countries(code,short_name,name) values ('CL','Chile','Republic of Chile (includes Easter Island, Juan Fernandez Islands, San Felix and Sala y Gomez)');
insert into valid_countries(code,short_name,name) values ('CM','Cameroon','Republic of Cameroon');
insert into valid_countries(code,short_name,name) values ('CN','China','People''s Republic of China');
insert into valid_countries(code,short_name,name) values ('CO','Colombia','Republic of Colombia (includes San Andres y Providencia, Malpelo Island, Roncador Bank, Serrana Bank and Serranilla Bank)');
insert into valid_countries(code,short_name,name) values ('CR','Costa Rica','Republic of Costa Rica (includes Cocos Island)');
insert into valid_countries(code,short_name,name) values ('CU','Cuba','Republic of Cuba');
insert into valid_countries(code,short_name,name) values ('CV','Cape Verde','Republic of Cape Verde (includes Boa Vista, Brava, Fogo, Maio, Sal,  Santo Antao, Sao Nicolau, Sao Tiago and Sao Vicente)');
insert into valid_countries(code,short_name,name) values ('CX','Christmas Island','Australian Christmas Island');
insert into valid_countries(code,short_name,name) values ('CY','Cyprus','Republic of Cyprus');
insert into valid_countries(code,short_name,name) values ('CZ','Czech Republic','Czech Republic');
insert into valid_countries(code,short_name,name) values ('DE','Germany','Federal Republic of Germany');
insert into valid_countries(code,short_name,name) values ('DJ','Djibouti','Republic of Djibouti');
insert into valid_countries(code,short_name,name) values ('DK','Denmark','Kingdom of Denmark');
insert into valid_countries(code,short_name,name) values ('DM','Dominica','Commonwealth of Dominica');
insert into valid_countries(code,short_name,name) values ('DO','Dominican Republic','Dominican Republic');
insert into valid_countries(code,short_name,name) values ('DZ','Algeria','People''s Democratic Republic of Algeria');
insert into valid_countries(code,short_name,name) values ('EC','Ecuador','Republic of Ecuador (includes Galapagos Islands (Archipelago de Colon))');
insert into valid_countries(code,short_name,name) values ('EE','Estonia','Republic of Estonia');
insert into valid_countries(code,short_name,name) values ('EG','Egypt','Arab Republic of Egypt');
insert into valid_countries(code,short_name,name) values ('EH','Western Sahara','Western Sahara');
insert into valid_countries(code,short_name,name) values ('ER','Eritrea','Eritrea');
insert into valid_countries(code,short_name,name) values ('ES','Spain','Kingdom of Spain');
insert into valid_countries(code,short_name,name) values ('ET','Ethiopia','Ethiopia');
insert into valid_countries(code,short_name,name) values ('FI','Finland','Republic of Finland');
insert into valid_countries(code,short_name,name) values ('FJ','Fiji','Fiji');
insert into valid_countries(code,short_name,name) values ('FK','Falkland Islands (Malvinas)','Falkland Islands (Malvinas) (includes West Falkland, and East Falkland)');
insert into valid_countries(code,short_name,name) values ('FM','Micronesia (Federated States of)','Caroline Islands except Palau (includes Yap, Chuuk, Pohnpei, Kosrae)');
insert into valid_countries(code,short_name,name) values ('FO','Faroe Islands','Faroe Islands');
insert into valid_countries(code,short_name,name) values ('FR','France','French Republic');
insert into valid_countries(code,short_name,name) values ('FX','France, Metropolitan','France, Metropolitan');
insert into valid_countries(code,short_name,name) values ('GA','Gabon','Gabonese Republic');
insert into valid_countries(code,short_name,name) values ('GB','United Kingdom','United Kingdom of Great Britain and Northern Ireland (includes Orkney Islands and Shetland Island)');
insert into valid_countries(code,short_name,name) values ('GD','Grenada','Grenada (includes Southern Grenadine Islands)');
insert into valid_countries(code,short_name,name) values ('GE','Georgia','Republic of Georgia');
insert into valid_countries(code,short_name,name) values ('GF','French Guiana','Department of Guiana');
insert into valid_countries(code,short_name,name) values ('GH','Ghana','Republic of Ghana');
insert into valid_countries(code,short_name,name) values ('GI','Gibraltar','Gibraltar');
insert into valid_countries(code,short_name,name) values ('GL','Greenland','Greenland');
insert into valid_countries(code,short_name,name) values ('GM','Gambia','Republic of the Gambia');
insert into valid_countries(code,short_name,name) values ('GN','Guinea','Republic of Guinea');
insert into valid_countries(code,short_name,name) values ('GP','Guadeloupe','Department of Guadeloupe (includes Grande Terre, Basse Terre, Marie Galante, Les Saintes, Iles de la Petite Terre, Desirade, Saint-Barthelemy, and Northern St. Martin)');
insert into valid_countries(code,short_name,name) values ('GQ','Equatorial Guinea','Republic of Equatorial Guinea (includes Rio Muni, Bioko, Annobon, Corisco, Elobey Chico, and Elobey Grande)');
insert into valid_countries(code,short_name,name) values ('GR','Greece','Hellenic Republic (includes Aegean Islands, Ionian Islands, Dodecanese Islands, Crete, and Mount Athos autonomous area)');
insert into valid_countries(code,short_name,name) values ('GS','South Georgia and the South Sandwich Island','South Georgia and the South Sandwich Island');
insert into valid_countries(code,short_name,name) values ('GT','Guatemala','Republic of Guatemala');
insert into valid_countries(code,short_name,name) values ('GU','Guam','Guam');
insert into valid_countries(code,short_name,name) values ('GW','Guinea-Bissau','Republic of Guinea-Bissau');
insert into valid_countries(code,short_name,name) values ('GY','Guyana','Republic of Guyana');
insert into valid_countries(code,short_name,name) values ('HK','Hong Kong','Hong Kong (also called Hisiangkang, or Xianggang)');
insert into valid_countries(code,short_name,name) values ('HM','Heard Island and McDonald Islands','Heard Island and McDonald Islands');
insert into valid_countries(code,short_name,name) values ('HN','Honduras','Republic of Honduras (includes Swan Islands)');
insert into valid_countries(code,short_name,name) values ('HR','Croatia','Republic of Croatia');
insert into valid_countries(code,short_name,name) values ('HT','Haiti','Republic of Haiti');
insert into valid_countries(code,short_name,name) values ('HU','Hungary','Republic of Hungary');
insert into valid_countries(code,short_name,name) values ('ID','Indonesia','Republic of Indonesia');
insert into valid_countries(code,short_name,name) values ('IE','Ireland','Ireland');
insert into valid_countries(code,short_name,name) values ('IL','Israel','State of Israel');
insert into valid_countries(code,short_name,name) values ('IN','India','Republic of India (includes Amindivis, Laccadives, Minicoy, Andaman Islands, Nicobar Islands, and Sikkim)');
insert into valid_countries(code,short_name,name) values ('IO','British Indian Ocean Territory','Chagos Archipelago');
insert into valid_countries(code,short_name,name) values ('IQ','Iraq','Republic of Iraq');
insert into valid_countries(code,short_name,name) values ('IR','Iran (Islamic Republic of)','Islamic Republic of Iran');
insert into valid_countries(code,short_name,name) values ('IS','Iceland','Republic of Iceland');
insert into valid_countries(code,short_name,name) values ('IT','Italy','Italian Republic');
insert into valid_countries(code,short_name,name) values ('JM','Jamaica','Jamaica (includes Morant Cays, and Pedro Cays)');
insert into valid_countries(code,short_name,name) values ('JO','Jordan','Hashemite Kingdom of Jordan');
insert into valid_countries(code,short_name,name) values ('JP','Japan','Japan');
insert into valid_countries(code,short_name,name) values ('KE','Kenya','Republic of Kenya');
insert into valid_countries(code,short_name,name) values ('KG','Kyrgyzstan','Kyrgyz Republic');
insert into valid_countries(code,short_name,name) values ('KH','Cambodia','Kingdom of Cambodia');
insert into valid_countries(code,short_name,name) values ('KI','Kiribati','Kiribati (includes Fanning Island, Washington Island, and Christmas Island (all in the Line Islands), Ocean Island, Phoenix Islands (Birnie, Gardner, Hull, McKean, Phoenix, Sydney, Canton and Enderbury))');
insert into valid_countries(code,short_name,name) values ('KM','Comoros','Islamic Federal Republic of the Comoros (includes Anjouan, Grande Comore, Moheli, and other islands)');
insert into valid_countries(code,short_name,name) values ('KN','Saint Kitts and Nevis','Saint Kitts and Nevis');
insert into valid_countries(code,short_name,name) values ('KP','Korea, Democratic People''s Republic of','Korea, Democratic People''s Republic of');
insert into valid_countries(code,short_name,name) values ('KR','Korea, Republic of','Korea, Republic of');
insert into valid_countries(code,short_name,name) values ('KW','Kuwait','State of Kuwait');
insert into valid_countries(code,short_name,name) values ('KY','Cayman Islands','Cayman Islands (includes Grand Cayman, Cayman Brac and Little Cayman)');
insert into valid_countries(code,short_name,name) values ('KZ','Kazakhstan','Republic of Kazakhstan');
insert into valid_countries(code,short_name,name) values ('LA','Lao People''s Democratic Republic','Lao People''s Democratic Republic');
insert into valid_countries(code,short_name,name) values ('LB','Lebanon','Lebanese Republic');
insert into valid_countries(code,short_name,name) values ('LC','Saint Lucia','Saint Lucia');
insert into valid_countries(code,short_name,name) values ('LI','Liechtenstein','Principality of Liechtenstein');
insert into valid_countries(code,short_name,name) values ('LK','Sri Lanka','Democratic Socialist Republic of Sri Lanka');
insert into valid_countries(code,short_name,name) values ('LR','Liberia','Republic of Liberia');
insert into valid_countries(code,short_name,name) values ('LS','Lesotho','Kingdom of Lesotho');
insert into valid_countries(code,short_name,name) values ('LT','Latin America','Latin America');
insert into valid_countries(code,short_name,name) values ('LU','Luxembourg','Grand Duchy of Luxembourg');
insert into valid_countries(code,short_name,name) values ('LV','Latvia','Republic of Latvia');
insert into valid_countries(code,short_name,name) values ('LX','Lithuania','Republic of Lithuania');
insert into valid_countries(code,short_name,name) values ('LY','Libyan Arab Jamahiriya','Socialist People''s Libyan Arab Jamahiriya');
insert into valid_countries(code,short_name,name) values ('MA','Morocco','Kingdom of Morocco');
insert into valid_countries(code,short_name,name) values ('MC','Monaco','Principality of Monaco');
insert into valid_countries(code,short_name,name) values ('MD','Moldova, Republic of','Republic of Moldova');
insert into valid_countries(code,short_name,name) values ('MG','Madagascar','Republic of Madagascar');
insert into valid_countries(code,short_name,name) values ('MH','Marshall Islands','Republic of the Marshall Islands');
insert into valid_countries(code,short_name,name) values ('MK','Macedonia','Macedonia, the Former Yugoslav Republic of');
insert into valid_countries(code,short_name,name) values ('ML','Mali','Republic of Mali');
insert into valid_countries(code,short_name,name) values ('MM','Myanmar','Union of Myanmar');
insert into valid_countries(code,short_name,name) values ('MN','Mongolia','Mongolia');
insert into valid_countries(code,short_name,name) values ('MO','Macau','Macau (also called Ao-men)');
insert into valid_countries(code,short_name,name) values ('MP','Northern Mariana Islands','Commonwealth of the Northern Mariana Islands except Guam');
insert into valid_countries(code,short_name,name) values ('MQ','Martinique','Department of Martinique');
insert into valid_countries(code,short_name,name) values ('MR','Mauritania','Islamic Republic of Mauritania');
insert into valid_countries(code,short_name,name) values ('MS','Montserrat','Montserrat');
insert into valid_countries(code,short_name,name) values ('MT','Malta','Republic of Malta');
insert into valid_countries(code,short_name,name) values ('MU','Mauritius','Republic of Mauritius (includes Rodrigues, Agalega Islands, and Cargados Carajos)');
insert into valid_countries(code,short_name,name) values ('MV','Maldives','Republic of Maldives');
insert into valid_countries(code,short_name,name) values ('MW','Malawi','Republic of Malawi');
insert into valid_countries(code,short_name,name) values ('MX','Mexico','United Mexican States');
insert into valid_countries(code,short_name,name) values ('MY','Malaysia','Malaysia (includes Peninsular Malaysia, Sabah, and Sarawak)');
insert into valid_countries(code,short_name,name) values ('MZ','Mozambique','Republic of Mozambique');
insert into valid_countries(code,short_name,name) values ('NA','Namibia','Republic of Namibia');
insert into valid_countries(code,short_name,name) values ('NC','New Caledonia','New Caledonia (includes Isle of Pines, Loyalty Islands, Huon Islands,  Belep Archipelago, Chesterfield Islands, and Walpole)');
insert into valid_countries(code,short_name,name) values ('NE','Niger','Republic of the Niger');
insert into valid_countries(code,short_name,name) values ('NF','Norfolk Island','Norfolk Island');
insert into valid_countries(code,short_name,name) values ('NG','Nigeria','Federal Republic of Nigeria');
insert into valid_countries(code,short_name,name) values ('NI','Nicaragua','Republic of Nicaragua');
insert into valid_countries(code,short_name,name) values ('NL','Netherlands','Kingdom of the Netherlands');
insert into valid_countries(code,short_name,name) values ('NO','Norway','Kingdom of Norway');
insert into valid_countries(code,short_name,name) values ('NP','Nepal','Kingdom of Nepal');
insert into valid_countries(code,short_name,name) values ('NR','Nauru','Republic of Nauru');
insert into valid_countries(code,short_name,name) values ('NU','Niue','Niue');
insert into valid_countries(code,short_name,name) values ('NZ','New Zealand','New Zealand (includes Antipodes Islands, Auckland Islands, Bounty Islands, Campbell Islands, Kermadec Islands, Chatham Islands, and Snares Islands)');
insert into valid_countries(code,short_name,name) values ('OM','Oman','Sultanate of Oman');
insert into valid_countries(code,short_name,name) values ('PA','Panama','Republic of Panama');
insert into valid_countries(code,short_name,name) values ('PE','Peru','Republic of Peru');
insert into valid_countries(code,short_name,name) values ('PF','French Polynesia','French Polynesia (includes Society Archipelago, Tuamotu Archipelago, Marquezas Islands, Bambier Islands, Austral Islands, and Clipperton Island)');
insert into valid_countries(code,short_name,name) values ('PG','Papua New Guinea','Papua New Guinea (includes Bismarck and Louisiade Archipelagos, Admiralty Islands, d''Entrecasteaux Islands, Northern Solomon Islands, Trobriand Islands, New Britain, New Ireland, Woodlark, and associated islands)');
insert into valid_countries(code,short_name,name) values ('PH','Philippines','Republic of the Philippines');
insert into valid_countries(code,short_name,name) values ('PK','Pakistan','Islamic Republic of Pakistan');
insert into valid_countries(code,short_name,name) values ('PL','Poland','Republic of Poland');
insert into valid_countries(code,short_name,name) values ('PM','Saint Pierre and Miquelon','Territorial collectivity of St. Pierre and Miquelon');
insert into valid_countries(code,short_name,name) values ('PN','Pitcairn','Pitcairn (includes Henderson, Ducie, and Oeno)');
insert into valid_countries(code,short_name,name) values ('PR','Puerto Rico','Puerto Rico');
insert into valid_countries(code,short_name,name) values ('PT','Portugal','Portuguese Republic');
insert into valid_countries(code,short_name,name) values ('PW','Palau','Republic of Palau');
insert into valid_countries(code,short_name,name) values ('PY','Paraguay','Republic of Paraguay');
insert into valid_countries(code,short_name,name) values ('QA','Qatar','State of Qatar');
insert into valid_countries(code,short_name,name) values ('RE','Reunion','Department of Reunion');
insert into valid_countries(code,short_name,name) values ('RO','Romania','Romania');
insert into valid_countries(code,short_name,name) values ('RS','Serbia','Republic of Serbia');
insert into valid_countries(code,short_name,name) values ('RU','Russian Federation','Russian Federation');
insert into valid_countries(code,short_name,name) values ('RW','Rwanda','Rwandese Republic');
insert into valid_countries(code,short_name,name) values ('SA','Saudi Arabia','Kingdom of Saudi Arabia');
insert into valid_countries(code,short_name,name) values ('SB','Solomon Islands','Solomon Islands (includes Southern Solomon Islands, primarily Guadalcanal, Malaita, San Cristobal, Santa Isabel, Choiseul)');
insert into valid_countries(code,short_name,name) values ('SC','Seychelles','Republic of Seychelles (includes Alphonse, Bijoutier, St. Francois Islands, St. Pierre Islet, Cosmoledo Islands, Amirantes, Aldabra, Farquhar, and Desroches)');
insert into valid_countries(code,short_name,name) values ('SD','Sudan','Republic of the Sudan');
insert into valid_countries(code,short_name,name) values ('SG','Singapore','Singapore');
insert into valid_countries(code,short_name,name) values ('SH','Saint Helena','Saint Helena (includes Ascension, Gough Island, Inaccessible, Nightingale Islands, and Tristan da Cunha)');
insert into valid_countries(code,short_name,name) values ('SI','Slovenia','Republic of Slovenia');
insert into valid_countries(code,short_name,name) values ('SJ','Svalbard and Jan Mayen Islands','Svalbard and Jan Mayen Islands (includes Bear Island)');
insert into valid_countries(code,short_name,name) values ('SK','Slovakia','Slovak Republic');
insert into valid_countries(code,short_name,name) values ('SL','Sierra Leone','Republic of Sierra Leone');
insert into valid_countries(code,short_name,name) values ('SM','San Marino','Republic of San Marino');
insert into valid_countries(code,short_name,name) values ('SN','Senegal','Republic of Senegal');
insert into valid_countries(code,short_name,name) values ('SO','Somalia','Somali Democratic Republic');
insert into valid_countries(code,short_name,name) values ('SR','Suriname','Republic of Suriname');
insert into valid_countries(code,short_name,name) values ('ST','Sao Tome and Principe','Democratic Republic of Sao Tome and Principe');
insert into valid_countries(code,short_name,name) values ('SV','El Salvador','Republic of El Salvador');
insert into valid_countries(code,short_name,name) values ('SY','Syrian Arab Republic','Syrian Arab Republic');
insert into valid_countries(code,short_name,name) values ('SZ','Swaziland','Kingdom of Swaziland');
insert into valid_countries(code,short_name,name) values ('TC','Turks and Caicos Islands','Turks and Caicos Islands');
insert into valid_countries(code,short_name,name) values ('TD','Chad','Republic of Chad');
insert into valid_countries(code,short_name,name) values ('TF','French Southern Territories','French Southern Territories (includes Kerguelen Islands, Amsterdam, St. Paul, Crozet Islands)');
insert into valid_countries(code,short_name,name) values ('TG','Togo','Togolese Republic');
insert into valid_countries(code,short_name,name) values ('TH','Thailand','Kingdom of Thailand');
insert into valid_countries(code,short_name,name) values ('TJ','Tajikistan','Republic of Tajikistan');
insert into valid_countries(code,short_name,name) values ('TK','Tokelau','Tokelau');
insert into valid_countries(code,short_name,name) values ('TM','Turkmenistan','Turkmenistan');
insert into valid_countries(code,short_name,name) values ('TN','Tunisia','Republic of Tunisia');
insert into valid_countries(code,short_name,name) values ('TO','Tonga','Kingdom of Tonga');
insert into valid_countries(code,short_name,name) values ('TP','East Timor','East Timor (includes the exclave of Oe-Cussi)');
insert into valid_countries(code,short_name,name) values ('TR','Turkey','Republic of Turkey');
insert into valid_countries(code,short_name,name) values ('TT','Trinidad and Tobago','Republic of Trinidad and Tobago');
insert into valid_countries(code,short_name,name) values ('TV','Tuvalu','Tuvalu (includes Funafuti, Nanumanga, Nui, Nanomea, Nurakita, Niutao, Nukufetau, Nukulaelae, and Vaitupu)');
insert into valid_countries(code,short_name,name) values ('TW','Taiwan, Republic of China','Taiwan, Republic of China');
insert into valid_countries(code,short_name,name) values ('TZ','Tanzania, United Republic of','United Republic of Tanzania (includes Zanzibar and Pemba)');
insert into valid_countries(code,short_name,name) values ('UA','Ukraine','Ukraine');
insert into valid_countries(code,short_name,name) values ('UG','Uganda','Republic of Uganda');
insert into valid_countries(code,short_name,name) values ('UM','United States Minor Outlying Islands','United States Minor Outlying Islands (includes i.a. Baker Island, Howland Island, Jarvis Island, Johnston Atoll, Kingman Reef, Midway Islands,  Palmyra Islands, and Wake Island)');
insert into valid_countries(code,short_name,name) values ('US','United States','United States of America');
insert into valid_countries(code,short_name,name) values ('UY','Uruguay','Eastern Republic of Uruguay');
insert into valid_countries(code,short_name,name) values ('UZ','Uzbekistan','Republic of Uzbekistan');
insert into valid_countries(code,short_name,name) values ('VA','Vatican City State (Holy See)','Vatican City State (Holy See)');
insert into valid_countries(code,short_name,name) values ('VC','Saint Vincent and the Grenadines','Saint Vincent and the Grenadines (includes Northern Grenadine Islands)');
insert into valid_countries(code,short_name,name) values ('VE','Venezuela','Republic of Venezuela');
insert into valid_countries(code,short_name,name) values ('VG','Virgin Islands (British)','Virgin Islands (British) (includes Anegada, Jost Van Dyke, Tortola, and Virgin Gorda)');
insert into valid_countries(code,short_name,name) values ('VI','Virgin Islands (U.S.)','Virgin Islands of the United States (includes Saint Croix, Saint John, and Saint Thomas)');
insert into valid_countries(code,short_name,name) values ('VN','Viet Nam','Socialist Republic of Viet Nam');
insert into valid_countries(code,short_name,name) values ('VU','Vanuatu','Republic of Vanuatu');
insert into valid_countries(code,short_name,name) values ('WF','Wallis and Futuna Islands','Wallis and Futuna Islands (includes Iles Wallis (Uvea), and Iles de Hoorn (Futuna and Alofi))');
insert into valid_countries(code,short_name,name) values ('WS','Samoa','Independent State of Western Samoa');
insert into valid_countries(code,short_name,name) values ('YE','Yemen','Republic of Yemen (includes Perim, Kamaran, Socotra, and associated islands)');
insert into valid_countries(code,short_name,name) values ('YT','Mayotte','Territorial collectivity of Mayotte (includes Grande-Terre, and Pamandzi)');
insert into valid_countries(code,short_name,name) values ('YU','Yugoslavia','Federal Republic of Yugoslavia');
insert into valid_countries(code,short_name,name) values ('ZA','South Africa','Republic of South Africa (includes Walvis Bay, Marion Island, and Prince  Edward Island)');
insert into valid_countries(code,short_name,name) values ('ZM','Zambia','Republic of Zambia');
insert into valid_countries(code,short_name,name) values ('ZR','Zaire','Republic of Zaire');
insert into valid_countries(code,short_name,name) values ('ZW','Zimbabwe','Republic of Zimbabwe');
insert into valid_countries(code,short_name,name) values ('SE','Sweden','Kingom of Sweden');

commit;

   0707010000004D000081B400000000000000000000000167AE1114000000A1000000000000000000000000000000000000003300000000susemanager-schema/common/data/web_contact_all.sql    INSERT INTO web_contact_all (id, org_id, login)
    VALUES (-1, null, 'SETUP');
INSERT INTO web_contact_all (id, org_id, login)
    VALUES (-2, null, 'CLIENT');
   0707010000004E000081B400000000000000000000000167AE1114000003FE000000000000000000000000000000000000003300000000susemanager-schema/common/data/web_user_prefix.sql    --
-- Copyright (c) 2008 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--

insert into WEB_USER_PREFIX values (' ');
insert into WEB_USER_PREFIX values ('.');
insert into WEB_USER_PREFIX values ('Mr.');
insert into WEB_USER_PREFIX values ('Mrs.');
insert into WEB_USER_PREFIX values ('Miss');
insert into WEB_USER_PREFIX values ('Ms.');
insert into WEB_USER_PREFIX values ('Dr.');
insert into WEB_USER_PREFIX values ('Hr.');
insert into WEB_USER_PREFIX values ('Sr.');

  0707010000004F000081B400000000000000000000000167AE111400000352000000000000000000000000000000000000003600000000susemanager-schema/common/data/web_user_site_type.sql --
-- Copyright (c) 2008--2013 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--

insert into WEB_USER_SITE_TYPE VALUES('M', 'MARKET');
insert into WEB_USER_SITE_TYPE VALUES('B', 'BILL_TO');
insert into WEB_USER_SITE_TYPE VALUES('S', 'SHIP_TO');
insert into WEB_USER_SITE_TYPE VALUES('R', 'SERVICE');

  07070100000050000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000002100000000susemanager-schema/common/tables  07070100000051000081B400000000000000000000000167AE1114000004D2000000000000000000000000000000000000003100000000susemanager-schema/common/tables/PXTSessions.sql  --
-- Copyright (c) 2008--2011 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE PXTSessions
(
    id           NUMERIC,
    web_user_id  NUMERIC
                     CONSTRAINT pxtsessions_user
                         REFERENCES web_contact (id)
                         ON DELETE CASCADE,
    expires      NUMERIC
                     DEFAULT (0) NOT NULL,
    value        VARCHAR(4000) NOT NULL
)


;

CREATE INDEX PXTSessions_user
    ON PXTSessions (web_user_id)
    
    ;

CREATE INDEX PXTSessions_expires
    ON PXTSessions (expires)
    
    ;

CREATE SEQUENCE pxt_id_seq;

ALTER TABLE PXTSessions
    ADD CONSTRAINT pxt_sessions_pk PRIMARY KEY (id)
    
    ;

  07070100000052000081B400000000000000000000000167AE11140000035B000000000000000000000000000000000000002900000000susemanager-schema/common/tables/log.sql  --
-- Copyright (c) 2013 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE log
(
    id NUMERIC NOT NULL
        CONSTRAINT log_id_pk PRIMARY KEY,
    stamp TIMESTAMPTZ,
    user_id NUMERIC
        CONSTRAINT log_user_id_fk
            REFERENCES web_contact_all(id)
)

;

CREATE SEQUENCE log_seq;
 07070100000053000081B400000000000000000000000167AE111400000916000000000000000000000000000000000000002F00000000susemanager-schema/common/tables/rhnAction.sql    --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnAction
(
    id               NUMERIC NOT NULL
                         CONSTRAINT rhn_action_pk PRIMARY KEY
                         ,
    org_id           NUMERIC NOT NULL
                         CONSTRAINT rhn_action_oid_fk
                             REFERENCES web_customer (id)
                             ON DELETE CASCADE,
    action_type      NUMERIC NOT NULL
                         CONSTRAINT rhn_action_at_fk
                             REFERENCES rhnActionType (id),
    name             VARCHAR(128),
    scheduler        NUMERIC
                         CONSTRAINT rhn_action_scheduler_fk
                             REFERENCES web_contact (id)
                             ON DELETE SET NULL,
    earliest_action  TIMESTAMPTZ NOT NULL,
    version          NUMERIC
                         DEFAULT (0) NOT NULL,
    archived         NUMERIC
                         DEFAULT (0) NOT NULL
                         CONSTRAINT rhn_action_archived_ck
                             CHECK (archived in (0, 1)),
    prerequisite     NUMERIC
                         CONSTRAINT rhn_action_prereq_fk
                             REFERENCES rhnAction (id)
                             ON DELETE CASCADE,
    created          TIMESTAMPTZ
                         DEFAULT (current_timestamp) NOT NULL,
    modified         TIMESTAMPTZ
                         DEFAULT (current_timestamp) NOT NULL
)

;

CREATE INDEX rhn_action_oid_idx
    ON rhnAction (org_id)
    
    ;

CREATE INDEX rhn_action_scheduler_idx
    ON rhnAction (scheduler)
    
    ;

CREATE INDEX rhn_action_prereq_id_idx
    ON rhnAction (prerequisite, id)
    
    ;

CREATE SEQUENCE rhn_event_id_seq;

  07070100000054000081B400000000000000000000000167AE111400000624000000000000000000000000000000000000003A00000000susemanager-schema/common/tables/rhnActionApplyStates.sql --
-- Copyright (c) 2016 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

CREATE TABLE rhnActionApplyStates
(
    id               NUMERIC NOT NULL
                         CONSTRAINT rhn_act_apply_states_id_pk PRIMARY KEY,
    action_id        NUMERIC NOT NULL
                         CONSTRAINT rhn_act_apply_states_act_fk
                             REFERENCES rhnAction (id)
                             ON DELETE CASCADE,
    states           VARCHAR(1024),
    pillars          TEXT,
    test             CHAR(1)
                         DEFAULT ('N') NOT NULL
                         CONSTRAINT rhn_act_apply_states_test_ck
                             CHECK (test in ('Y','N')),
    created          TIMESTAMPTZ
                         DEFAULT (current_timestamp) NOT NULL,
    modified         TIMESTAMPTZ
                         DEFAULT (current_timestamp) NOT NULL
)

;

CREATE UNIQUE INDEX rhn_act_apply_states_aid_idx
    ON rhnActionApplyStates (action_id)
    ;

CREATE SEQUENCE rhn_act_apply_states_id_seq;

07070100000055000081B400000000000000000000000167AE1114000005AA000000000000000000000000000000000000004000000000susemanager-schema/common/tables/rhnActionApplyStatesResult.sql   --
-- Copyright (c) 2016 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

CREATE TABLE rhnActionApplyStatesResult
(
    server_id              NUMERIC NOT NULL
                               CONSTRAINT rhn_apply_states_result_sid_fk
                                   REFERENCES rhnServer (id)
                                   ON DELETE CASCADE,
    action_apply_states_id NUMERIC NOT NULL
                               CONSTRAINT rhn_apply_states_result_aid_fk
                                   REFERENCES rhnActionApplyStates (id)
                                   ON DELETE CASCADE,
    output                 BYTEA,
    return_code            NUMERIC NOT NULL
)

;

CREATE UNIQUE INDEX rhn_apply_states_result_sa_uq
    ON rhnActionApplyStatesResult (server_id, action_apply_states_id);

CREATE INDEX rhn_apply_states_result_ad_idx
    ON rhnActionApplyStatesResult (action_apply_states_id)
    ;

  07070100000056000081B400000000000000000000000167AE111400000492000000000000000000000000000000000000003400000000susemanager-schema/common/tables/rhnActionChain.sql   --
-- Copyright (c) 2014 SUSE
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
--

CREATE TABLE rhnActionChain
(
    id          NUMERIC        NOT NULL
                    CONSTRAINT rhn_action_chain_id_pk PRIMARY KEY,
    label       VARCHAR(256) NOT NULL,
    dispatched  CHAR(1)
                   DEFAULT ('N') NOT NULL
                   CONSTRAINT rhn_actionchain_dispatched_ck
                       CHECK (dispatched in ('Y','N')),
    user_id     NUMERIC        NOT NULL
                    CONSTRAINT rhn_actionchain_uid_fk
                        REFERENCES web_contact (id)
                        ON DELETE CASCADE,
    created     TIMESTAMPTZ          DEFAULT(CURRENT_TIMESTAMP) NOT NULL,
    modified    TIMESTAMPTZ          DEFAULT(CURRENT_TIMESTAMP) NOT NULL
)

;

CREATE SEQUENCE rhn_actionchain_id_seq;
  07070100000057000081B400000000000000000000000167AE111400000517000000000000000000000000000000000000003900000000susemanager-schema/common/tables/rhnActionChainEntry.sql  --
-- Copyright (c) 2014 SUSE
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
--

CREATE TABLE rhnActionChainEntry
(
    actionchain_id NUMERIC NOT NULL
        CONSTRAINT rhn_actchainent_acid_fk
            REFERENCES rhnActionChain (id)
            ON DELETE CASCADE,
    action_id      NUMERIC
        CONSTRAINT rhn_actchainent_aid_fk
            REFERENCES rhnAction (id)
            ON DELETE CASCADE,
    server_id      NUMERIC NOT NULL
        CONSTRAINT rhn_actchainent_sid_fk
            REFERENCES rhnServer(id)
            ON DELETE CASCADE,
    sort_order     NUMERIC NOT NULL,
    created        TIMESTAMPTZ DEFAULT(CURRENT_TIMESTAMP) NOT NULL,
    modified       TIMESTAMPTZ DEFAULT(CURRENT_TIMESTAMP) NOT NULL,
    CONSTRAINT rhn_actchainent_cid_sid_so_uq UNIQUE 
        (actionchain_id, server_id, sort_order)
    DEFERRABLE INITIALLY DEFERRED
)

;

CREATE UNIQUE INDEX rhn_actchainent_aid_uq
    ON rhnActionChainEntry(action_id)
    ;
 07070100000058000081B400000000000000000000000167AE11140000077E000000000000000000000000000000000000003C00000000susemanager-schema/common/tables/rhnActionConfigChannel.sql   --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnActionConfigChannel
(
    action_id          NUMERIC NOT NULL
                           CONSTRAINT rhn_actioncc_aid_fk
                               REFERENCES rhnAction (id)
                               ON DELETE CASCADE,
    server_id          NUMERIC NOT NULL
                           CONSTRAINT rhn_actioncc_sid_fk
                               REFERENCES rhnServer (id),
    config_channel_id  NUMERIC NOT NULL
                           CONSTRAINT rhn_actioncc_ccid_fk
                               REFERENCES rhnConfigChannel (id)
                               ON DELETE CASCADE,
    created            TIMESTAMPTZ
                           DEFAULT (current_timestamp) NOT NULL,
    modified           TIMESTAMPTZ
                           DEFAULT (current_timestamp) NOT NULL
)

;

CREATE UNIQUE INDEX rhn_actioncc_aid_sid_uq
    ON rhnActionConfigChannel (action_id, server_id)
    ;

CREATE INDEX rhn_actioncc_sid_idx
    ON rhnActionConfigChannel (server_id)
    ;

CREATE INDEX rhn_act_cc_ccid_idx
    ON rhnActionConfigChannel (config_channel_id)
    ;

ALTER TABLE rhnActionConfigChannel
    ADD CONSTRAINT rhn_actioncc_sid_aid_fk FOREIGN KEY (server_id, action_id)
    REFERENCES rhnServerAction (server_id, action_id)
        ON DELETE CASCADE;

  07070100000059000081B400000000000000000000000167AE11140000056A000000000000000000000000000000000000003900000000susemanager-schema/common/tables/rhnActionConfigDate.sql  --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnActionConfigDate
(
    action_id        NUMERIC NOT NULL
                         CONSTRAINT rhn_actioncd_aid_fk
                             REFERENCES rhnAction (id)
                             ON DELETE CASCADE,
    start_date       TIMESTAMPTZ NOT NULL,
    end_date         TIMESTAMPTZ,
    import_contents  CHAR(1) NOT NULL
                         CONSTRAINT rhn_actioncd_file_ic_ck
                             CHECK (import_contents in ('Y','N')),
    created          TIMESTAMPTZ
                         DEFAULT (current_timestamp) NOT NULL,
    modified         TIMESTAMPTZ
                         DEFAULT (current_timestamp) NOT NULL
)

;

CREATE UNIQUE INDEX rhn_actioncd_aid_uq
    ON rhnActionConfigDate (action_id)
    ;

  0707010000005A000081B400000000000000000000000167AE111400000515000000000000000000000000000000000000003D00000000susemanager-schema/common/tables/rhnActionConfigDateFile.sql  --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnActionConfigDateFile
(
    action_id  NUMERIC NOT NULL
                   CONSTRAINT rhn_actioncd_file_aid_fk
                       REFERENCES rhnAction (id)
                       ON DELETE CASCADE,
    file_name  VARCHAR(512) NOT NULL,
    file_type  CHAR(1) NOT NULL
                   CONSTRAINT rhn_actioncd_file_ft_ck
                       CHECK (file_type in ('W','B')),
    created    TIMESTAMPTZ
                   DEFAULT (current_timestamp) NOT NULL,
    modified   TIMESTAMPTZ
                   DEFAULT (current_timestamp) NOT NULL
)

;

CREATE INDEX rhn_actioncd_file_aid_fn_idx
    ON rhnActionConfigDateFile (action_id, file_name)
    ;

   0707010000005B000081B400000000000000000000000167AE111400000800000000000000000000000000000000000000003D00000000susemanager-schema/common/tables/rhnActionConfigFileName.sql  --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnActionConfigFileName
(
    action_id            NUMERIC NOT NULL,
    server_id            NUMERIC NOT NULL,
    config_file_name_id  NUMERIC NOT NULL
                             CONSTRAINT rhn_actioncf_name_cfnid_fk
                                 REFERENCES rhnConfigFileName (id),
    config_revision_id   NUMERIC
                             CONSTRAINT rhn_actioncf_name_crid_fk
                                 REFERENCES rhnConfigRevision (id)
                                 ON DELETE SET NULL,
    failure_id           NUMERIC
                             CONSTRAINT rhn_actioncf_failure_id_fk
                                 REFERENCES rhnConfigFileFailure (id),
    created              TIMESTAMPTZ
                             DEFAULT (current_timestamp) NOT NULL,
    modified             TIMESTAMPTZ
                             DEFAULT (current_timestamp) NOT NULL
)

;

CREATE UNIQUE INDEX rhn_actioncf_name_asc_uq
    ON rhnActionConfigFileName (action_id, server_id, config_file_name_id)
    ;

CREATE INDEX rhn_actioncf_name_sid_idx
    ON rhnActionConfigFileName (server_id)
    ;

CREATE INDEX rhn_act_cnfg_fn_crid_idx
    ON rhnActionConfigFileName (config_revision_id)
    ;

ALTER TABLE rhnActionConfigFileName
    ADD CONSTRAINT rhn_actioncf_name_aid_sid_fk FOREIGN KEY (server_id, action_id)
    REFERENCES rhnServerAction (server_id, action_id)
        ON DELETE CASCADE;

0707010000005C000081B400000000000000000000000167AE111400000840000000000000000000000000000000000000003D00000000susemanager-schema/common/tables/rhnActionConfigRevision.sql  --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnActionConfigRevision
(
    id                  NUMERIC NOT NULL
                            CONSTRAINT rhn_actioncr_id_pk PRIMARY KEY
                            ,
    action_id           NUMERIC NOT NULL
                            CONSTRAINT rhn_actioncr_aid_fk
                                REFERENCES rhnAction (id)
                                ON DELETE CASCADE,
    server_id           NUMERIC NOT NULL
                            CONSTRAINT rhn_actioncr_sid_fk
                                REFERENCES rhnServer (id),
    config_revision_id  NUMERIC NOT NULL
                            CONSTRAINT rhn_actioncr_crid_fk
                                REFERENCES rhnConfigRevision (id)
                                ON DELETE CASCADE,
    failure_id          NUMERIC
                            CONSTRAINT rhn_actioncr_failid_fk
                                REFERENCES rhnConfigFileFailure (id),
    created             TIMESTAMPTZ
                            DEFAULT (current_timestamp) NOT NULL,
    modified            TIMESTAMPTZ
                            DEFAULT (current_timestamp) NOT NULL
)

;

CREATE UNIQUE INDEX rhn_actioncr_aid_sid_crid_uq
    ON rhnActionConfigRevision (action_id, server_id, config_revision_id)
    ;

CREATE INDEX rhn_actioncr_sid_idx
    ON rhnActionConfigRevision (server_id)
    ;

CREATE INDEX rhn_act_cr_crid_idx
    ON rhnActionConfigRevision (config_revision_id)
    ;

CREATE SEQUENCE rhn_actioncr_id_seq;

0707010000005D000081B400000000000000000000000167AE111400000526000000000000000000000000000000000000004300000000susemanager-schema/common/tables/rhnActionConfigRevisionResult.sql    --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnActionConfigRevisionResult
(
    action_config_revision_id  NUMERIC NOT NULL
                                   CONSTRAINT rhn_actioncfr_acrid_fk
                                       REFERENCES rhnActionConfigRevision (id)
                                       ON DELETE CASCADE,
    result                     BYTEA,
    created                    TIMESTAMPTZ
                                   DEFAULT (current_timestamp) NOT NULL,
    modified                   TIMESTAMPTZ
                                   DEFAULT (current_timestamp) NOT NULL
)

;

CREATE UNIQUE INDEX rhn_actioncfr_acrid_uq
    ON rhnActionConfigRevisionResult (action_config_revision_id)
    ;

  0707010000005E000081B400000000000000000000000167AE111400000516000000000000000000000000000000000000003B00000000susemanager-schema/common/tables/rhnActionDaemonConfig.sql    --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnActionDaemonConfig
(
    action_id  NUMERIC NOT NULL
                   CONSTRAINT rhn_actiondc_aid_fk
                       REFERENCES rhnAction (id)
                       ON DELETE CASCADE,
    interval   NUMERIC NOT NULL,
    restart    CHAR(1)
                   DEFAULT ('Y') NOT NULL
                   CONSTRAINT rhn_actiondc_rest_ck
                       CHECK (restart in ('Y','N')),
    created    TIMESTAMPTZ
                   DEFAULT (current_timestamp) NOT NULL,
    modified   TIMESTAMPTZ
                   DEFAULT (current_timestamp) NOT NULL
)

;

CREATE UNIQUE INDEX rhn_actiondc_aid_uq
    ON rhnActionDaemonConfig (action_id)
    ;

  0707010000005F000081B400000000000000000000000167AE1114000006DA000000000000000000000000000000000000003200000000susemanager-schema/common/tables/rhnActionDup.sql --
-- Copyright (c) 2012, Novell Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--


CREATE TABLE rhnActionDup
(
    id                  NUMERIC NOT NULL
                            CONSTRAINT rhn_actiondup_id_pk PRIMARY KEY
                            ,
    action_id           NUMERIC NOT NULL
                            CONSTRAINT rhn_actiondup_aid_fk
                            REFERENCES rhnAction (id)
                            ON DELETE CASCADE,
    dry_run             CHAR(1)
                            DEFAULT ('N') NOT NULL
                            CONSTRAINT rhn_actiondup_dr_ck
                                CHECK (dry_run in ('Y','N')),
    full_update         CHAR(1)
                            DEFAULT ('Y') NOT NULL
                            CONSTRAINT rhn_actiondup_fu_ck
                                CHECK (full_update in ('Y','N')),
    allow_vendor_change CHAR(1)
                            DEFAULT ('N') NOT NULL
                            CONSTRAINT rhn_actiondup_avc_ck
                                CHECK (allow_vendor_change in ('Y','N')),
    missing_successors  VARCHAR(512),
    created   TIMESTAMPTZ
                  DEFAULT (current_timestamp) NOT NULL,
    modified  TIMESTAMPTZ
                  DEFAULT (current_timestamp) NOT NULL
)

;

CREATE UNIQUE INDEX rhn_actiondup_aid_uq
ON rhnActionDup (action_id)
;

CREATE SEQUENCE rhn_actiondup_id_seq;
  07070100000060000081B400000000000000000000000167AE1114000005AA000000000000000000000000000000000000003900000000susemanager-schema/common/tables/rhnActionDupChannel.sql  --
-- Copyright (c) 2012, Novell Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--


CREATE TABLE rhnActionDupChannel
(
    action_dup_id       NUMERIC NOT NULL
                            CONSTRAINT rhn_actdupchan_dupid_fk
                            REFERENCES rhnActionDup (id)
                            ON DELETE CASCADE,
    channel_id          NUMERIC NOT NULL
                            CONSTRAINT rhn_actdupchan_chanid_fk
                            REFERENCES rhnChannel (id)
                            ON DELETE CASCADE,
    task                CHAR(1)
                            DEFAULT ('S') NOT NULL
                            CONSTRAINT rhn_actdupchan_task_ck
                                CHECK (task in ('S','U')),
    created   TIMESTAMPTZ
                  DEFAULT (current_timestamp) NOT NULL,
    modified  TIMESTAMPTZ
                  DEFAULT (current_timestamp) NOT NULL
)

;

CREATE UNIQUE INDEX rhn_actdupchan_aid_cid_uq
    ON rhnActionDupChannel (action_dup_id, channel_id)
    ;

CREATE INDEX rhn_actdupchan_cid_idx
    ON rhnActionDupChannel (channel_id)
    ;

  07070100000061000081B400000000000000000000000167AE111400000572000000000000000000000000000000000000003900000000susemanager-schema/common/tables/rhnActionDupProduct.sql  --
-- Copyright (c) 2012, Novell Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--


CREATE TABLE rhnActionDupProduct
(
    action_dup_id       NUMERIC NOT NULL
                            CONSTRAINT rhn_actdupchanprof_dupid_fk
                            REFERENCES rhnActionDup (id)
                            ON DELETE CASCADE,
    from_pdid           NUMERIC NOT NULL
                            CONSTRAINT rhn_actdupchanprod_fpdid_fk
                            REFERENCES suseProducts (id)
                            ON DELETE CASCADE,
    to_pdid             NUMERIC NOT NULL
                            CONSTRAINT rhn_actdupchanprod_tpdid_fk
                            REFERENCES suseProducts (id)
                            ON DELETE CASCADE,
    created   TIMESTAMPTZ
                  DEFAULT (current_timestamp) NOT NULL,
    modified  TIMESTAMPTZ
                  DEFAULT (current_timestamp) NOT NULL
)

;

CREATE UNIQUE INDEX rhn_actdupchan_aid_pdids_uq
    ON rhnActionDupProduct (action_dup_id, from_pdid, to_pdid)
    ;

  07070100000062000081B400000000000000000000000167AE1114000004AA000000000000000000000000000000000000003B00000000susemanager-schema/common/tables/rhnActionErrataUpdate.sql    --
-- Copyright (c) 2008--2011 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnActionErrataUpdate
(
    action_id  NUMERIC NOT NULL
                   CONSTRAINT rhn_act_eu_act_fk
                       REFERENCES rhnAction (id)
                       ON DELETE CASCADE,
    errata_id  NUMERIC NOT NULL
                   CONSTRAINT rhn_act_eu_err_fk
                       REFERENCES rhnErrata (id)
                       ON DELETE CASCADE
)

;

CREATE UNIQUE INDEX rhn_act_eu_aid_eid_uq
    ON rhnActionErrataUpdate (action_id, errata_id)
    ;

CREATE INDEX rhn_act_eu_eid_idx
    ON rhnActionErrataUpdate (errata_id)
    ;

  07070100000063000081B400000000000000000000000167AE11140000060E000000000000000000000000000000000000003900000000susemanager-schema/common/tables/rhnActionImageBuild.sql  --
-- Copyright (c) 2017 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

CREATE TABLE rhnActionImageBuild
(
    id               NUMERIC NOT NULL
                         CONSTRAINT rhn_act_image_build_id_pk PRIMARY KEY,
    action_id        NUMERIC NOT NULL
                         CONSTRAINT rhn_act_image_build_act_fk
                             REFERENCES rhnAction (id)
                             ON DELETE CASCADE,
    image_profile_id NUMERIC
                         CONSTRAINT rhn_act_image_build_ip_fk
                             REFERENCES suseImageProfile (profile_id)
                             ON DELETE SET NULL,
    version          VARCHAR(128),
    created          TIMESTAMPTZ
                         DEFAULT (current_timestamp) NOT NULL,
    modified         TIMESTAMPTZ
                         DEFAULT (current_timestamp) NOT NULL
)

;

CREATE UNIQUE INDEX rhn_act_image_build_aid_idx
    ON rhnActionImageBuild (action_id)
    ;

CREATE SEQUENCE rhn_act_image_build_id_seq;

  07070100000064000081B400000000000000000000000167AE111400000550000000000000000000000000000000000000003F00000000susemanager-schema/common/tables/rhnActionImageBuildResult.sql    --
-- Copyright (c) 2017 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

CREATE TABLE rhnActionImageBuildResult
(
    server_id              NUMERIC NOT NULL
                               CONSTRAINT rhn_image_build_result_sid_fk
                                   REFERENCES rhnServer (id)
                                   ON DELETE CASCADE,
    action_image_build_id NUMERIC NOT NULL
                               CONSTRAINT rhn_image_build_result_aid_fk
                                   REFERENCES rhnActionImageBuild (id)
                                   ON DELETE CASCADE
)

;

CREATE UNIQUE INDEX rhn_image_build_result_sa_uq
    ON rhnActionImageBuildResult (server_id, action_image_build_id);

CREATE INDEX rhn_image_build_result_ad_idx
    ON rhnActionImageBuildResult (action_image_build_id)
    ;

07070100000065000081B400000000000000000000000167AE1114000004CB000000000000000000000000000000000000003A00000000susemanager-schema/common/tables/rhnActionImageDeploy.sql --
-- Copyright (c) 2012 Novell
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

CREATE TABLE rhnActionImageDeploy
(
    id            NUMERIC NOT NULL
                  CONSTRAINT rhn_aid_id_pk PRIMARY KEY
                  ,
    action_id     NUMERIC NOT NULL
                      CONSTRAINT rhn_act_idp_act_fk
                      REFERENCES rhnAction (id)
                      ON DELETE CASCADE,
    vcpus         NUMERIC NOT NULL,
    mem_kb        NUMERIC NOT NULL,
    bridge_device VARCHAR(32),
    download_url  VARCHAR(256) NOT NULL,
    proxy_server  VARCHAR(64),
    proxy_user    VARCHAR(32),
    proxy_pass    VARCHAR(64)
)

;

CREATE SEQUENCE rhn_action_image_deploy_id_seq;
 07070100000066000081B400000000000000000000000167AE11140000064F000000000000000000000000000000000000003B00000000susemanager-schema/common/tables/rhnActionImageInspect.sql    --
-- Copyright (c) 2017 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

CREATE TABLE rhnActionImageInspect
(
    id               NUMERIC NOT NULL
                         CONSTRAINT rhn_act_image_inspect_id_pk PRIMARY KEY,
    action_id        NUMERIC NOT NULL
                         CONSTRAINT rhn_act_image_inspect_act_fk
                             REFERENCES rhnAction (id)
                             ON DELETE CASCADE,
    image_store_id NUMERIC
                         CONSTRAINT rhn_act_image_inspect_is_fk
                             REFERENCES suseImageStore (id)
                             ON DELETE SET NULL,
    build_action_id	NUMERIC,
    version          VARCHAR(128),
    name             VARCHAR(128),
    created          TIMESTAMPTZ
                         DEFAULT (current_timestamp) NOT NULL,
    modified         TIMESTAMPTZ
                         DEFAULT (current_timestamp) NOT NULL
)

;

CREATE UNIQUE INDEX rhn_act_image_inspect_aid_idx
    ON rhnActionImageInspect (action_id)
    ;

CREATE SEQUENCE rhn_act_image_inspect_id_seq;
 07070100000067000081B400000000000000000000000167AE11140000055C000000000000000000000000000000000000004100000000susemanager-schema/common/tables/rhnActionImageInspectResult.sql  --
-- Copyright (c) 2017 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

CREATE TABLE rhnActionImageInspectResult
(
    server_id              NUMERIC NOT NULL
                               CONSTRAINT rhn_image_inspect_res_sid_fk
                                   REFERENCES rhnServer (id)
                                   ON DELETE CASCADE,
    action_image_inspect_id NUMERIC NOT NULL
                               CONSTRAINT rhn_image_inspect_res_aid_fk
                                   REFERENCES rhnActionImageInspect (id)
                                   ON DELETE CASCADE
)

;

CREATE UNIQUE INDEX rhn_image_inspect_result_sa_uq
    ON rhnActionImageInspectResult (server_id, action_image_inspect_id);

CREATE INDEX rhn_image_inspect_res_ad_idx
    ON rhnActionImageInspectResult (action_image_inspect_id)
    ;
07070100000068000081B400000000000000000000000167AE1114000006C5000000000000000000000000000000000000003800000000susemanager-schema/common/tables/rhnActionKickstart.sql   --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnActionKickstart
(
    id                  NUMERIC NOT NULL,
    action_id           NUMERIC NOT NULL
                            CONSTRAINT rhn_actionks_aid_fk
                                REFERENCES rhnAction (id)
                                ON DELETE CASCADE,
    append_string       VARCHAR(1024),
    kickstart_host      VARCHAR(256),
    static_device       VARCHAR(32),
    cobbler_system_name VARCHAR(256),
    upgrade             CHAR(1) DEFAULT ('N') NOT NULL
                            CONSTRAINT rhn_actionks_up_ck
                                CHECK (upgrade in ('Y', 'N')),
    created             TIMESTAMPTZ
                            DEFAULT (current_timestamp) NOT NULL,
    modified            TIMESTAMPTZ
                            DEFAULT (current_timestamp) NOT NULL
)

;

CREATE UNIQUE INDEX rhn_actionks_aid_uq
    ON rhnActionKickstart (action_id)
    ;

CREATE INDEX rhn_actionks_id_idx
    ON rhnActionKickstart (id)
    ;

CREATE SEQUENCE rhn_actionks_id_seq;

ALTER TABLE rhnActionKickstart
    ADD CONSTRAINT rhn_actionks_id_pk PRIMARY KEY (id);

   07070100000069000081B400000000000000000000000167AE1114000005B0000000000000000000000000000000000000004000000000susemanager-schema/common/tables/rhnActionKickstartFileList.sql   --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnActionKickstartFileList
(
    action_ks_id  NUMERIC NOT NULL
                      CONSTRAINT rhn_actionksfl_askid_fk
                          REFERENCES rhnActionKickstart (id)
                          ON DELETE CASCADE,
    file_list_id  NUMERIC NOT NULL
                      CONSTRAINT rhn_actionksfl_flid_fk
                          REFERENCES rhnFileList (id)
                          ON DELETE CASCADE,
    created       TIMESTAMPTZ
                      DEFAULT (current_timestamp) NOT NULL,
    modified      TIMESTAMPTZ
                      DEFAULT (current_timestamp) NOT NULL
)

;

CREATE UNIQUE INDEX rhn_actionksfl_aksid_flid_uq
    ON rhnActionKickstartFileList (action_ks_id, file_list_id)
    ;

CREATE INDEX rhn_actionksfl_flid_idx
    ON rhnActionKickstartFileList (file_list_id)
    ;

0707010000006A000081B400000000000000000000000167AE11140000081E000000000000000000000000000000000000003D00000000susemanager-schema/common/tables/rhnActionKickstartGuest.sql  --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnActionKickstartGuest
(
    id                   NUMERIC NOT NULL,
    action_id            NUMERIC NOT NULL
                             CONSTRAINT rhn_actionks_xenguest_aid_fk
                                 REFERENCES rhnAction (id)
                                 ON DELETE CASCADE,
    append_string        VARCHAR(1024),
    ks_session_id        NUMERIC
                             CONSTRAINT rhn_actionks_xenguest_ksid_fk
                                 REFERENCES rhnKickstartSession (id)
                                 ON DELETE CASCADE,
    guest_name           VARCHAR(256),
    mem_kb               NUMERIC,
    vcpus                NUMERIC,
    disk_gb              NUMERIC,
    cobbler_system_name  VARCHAR(256),
    disk_path            VARCHAR(256),
    virt_bridge          VARCHAR(256),
    kickstart_host       VARCHAR(256),
    created              TIMESTAMPTZ
                             DEFAULT (current_timestamp) NOT NULL,
    modified             TIMESTAMPTZ
                             DEFAULT (current_timestamp) NOT NULL,
    mac_address          VARCHAR(17)
)

;

CREATE UNIQUE INDEX rhn_actionks_xenguest_aid_uq
    ON rhnActionKickstartGuest (action_id)
    ;

CREATE INDEX rhn_actionks_xenguest_id_idx
    ON rhnActionKickstartGuest (id)
    ;

CREATE SEQUENCE rhn_actionks_xenguest_id_seq;

ALTER TABLE rhnActionKickstartGuest
    ADD CONSTRAINT rhn_actionks_xenguest_id_pk PRIMARY KEY (id);

  0707010000006B000081B400000000000000000000000167AE1114000006FE000000000000000000000000000000000000003600000000susemanager-schema/common/tables/rhnActionPackage.sql --
-- Copyright (c) 2008--2010 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnActionPackage
(
    id               NUMERIC NOT NULL
                         CONSTRAINT rhn_act_p_id_pk PRIMARY KEY
                         ,
    action_id        NUMERIC NOT NULL
                         CONSTRAINT rhn_act_p_act_fk
                             REFERENCES rhnAction (id)
                             ON DELETE CASCADE,
    parameter        VARCHAR(128)
                         DEFAULT ('upgrade') NOT NULL
                         CONSTRAINT rhn_act_p_param_ck
                             CHECK (parameter IN ('upgrade', 'install', 'remove', 'downgrade', 'lock')),
    name_id          NUMERIC NOT NULL
                         CONSTRAINT rhn_act_p_name_fk
                             REFERENCES rhnPackageName (id),
    evr_id           NUMERIC
                         CONSTRAINT rhn_act_p_evr_fk
                             REFERENCES rhnPackageEvr (id),
    package_arch_id  NUMERIC
                         CONSTRAINT rhn_act_p_paid_fk
                             REFERENCES rhnPackageArch (id)
)

;

CREATE INDEX rhn_act_p_aid_idx
    ON rhnActionPackage (action_id)
    
    ;

CREATE SEQUENCE rhn_act_p_id_seq;

  0707010000006C000081B400000000000000000000000167AE1114000004C4000000000000000000000000000000000000004000000000susemanager-schema/common/tables/rhnActionPackageAnswerfile.sql   --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnActionPackageAnswerfile
(
    action_package_id  NUMERIC NOT NULL
                           CONSTRAINT rhn_act_p_af_apid_fk
                               REFERENCES rhnActionPackage (id)
                               ON DELETE CASCADE,
    answerfile         BYTEA,
    created            TIMESTAMPTZ
                           DEFAULT (current_timestamp) NOT NULL,
    modified           TIMESTAMPTZ
                           DEFAULT (current_timestamp) NOT NULL
)


;

CREATE INDEX rhn_act_p_af_aid_idx
    ON rhnActionPackageAnswerfile (action_package_id)
    
    ;

0707010000006D000081B400000000000000000000000167AE1114000004A1000000000000000000000000000000000000003B00000000susemanager-schema/common/tables/rhnActionPackageDelta.sql    --
-- Copyright (c) 2008 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnActionPackageDelta
(
    action_id         NUMERIC NOT NULL
                          CONSTRAINT rhn_act_pd_aid_fk
                              REFERENCES rhnAction (id)
                              ON DELETE CASCADE,
    package_delta_id  NUMERIC NOT NULL
                          CONSTRAINT rhn_act_pd_pdid_fk
                              REFERENCES rhnPackageDelta (id)
                              ON DELETE CASCADE
)

;

CREATE UNIQUE INDEX rhn_act_pd_aid_pdid_idx
    ON rhnActionPackageDelta (action_id, package_delta_id)
    
    ;

   0707010000006E000081B400000000000000000000000167AE11140000053D000000000000000000000000000000000000003D00000000susemanager-schema/common/tables/rhnActionPackageDetails.sql  --
-- Copyright (c) 2021 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnActionPackageDetails
(
    id         NUMERIC NOT NULL
               CONSTRAINT rhn_actionpd_id_pk PRIMARY KEY,
    action_id  NUMERIC NOT NULL
                   CONSTRAINT rhn_act_eu_act_fk
                       REFERENCES rhnAction (id)
                       ON DELETE CASCADE,
    allow_vendor_change  CHAR(1) DEFAULT ('N') NOT NULL 
    CONSTRAINT rhn_actdet_avc_ck CHECK (allow_vendor_change in ('Y','N')),

    created   TIMESTAMPTZ
                  DEFAULT (current_timestamp) NOT NULL,
    modified  TIMESTAMPTZ
                  DEFAULT (current_timestamp) NOT NULL
);


CREATE UNIQUE INDEX rhn_act_eud_aid_uq
    ON rhnActionPackageDetails (action_id);

CREATE SEQUENCE rhn_actiondpd_id_seq;
   0707010000006F000081B400000000000000000000000167AE11140000076E000000000000000000000000000000000000004400000000susemanager-schema/common/tables/rhnActionPackageRemovalFailure.sql   --
-- Copyright (c) 2008 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnActionPackageRemovalFailure
(
    server_id      NUMERIC NOT NULL
                       CONSTRAINT rhn_apr_failure_sid_fk
                           REFERENCES rhnServer (id),
    action_id      NUMERIC NOT NULL
                       CONSTRAINT rhn_apr_failure_aid_fk
                           REFERENCES rhnAction (id)
                           ON DELETE CASCADE,
    name_id        NUMERIC NOT NULL
                       CONSTRAINT rhn_apr_failure_nid_fk
                           REFERENCES rhnPackageName (id),
    evr_id         NUMERIC NOT NULL
                       CONSTRAINT rhn_apr_failure_eid_fk
                           REFERENCES rhnPackageEVR (id),
    capability_id  NUMERIC NOT NULL
                       CONSTRAINT rhn_apr_failure_capid_fk
                           REFERENCES rhnPackageCapability (id),
    flags          NUMERIC NOT NULL,
    suggested      NUMERIC
                       CONSTRAINT rhn_apr_failure_suggested_fk
                           REFERENCES rhnPackageName (id),
    sense          NUMERIC NOT NULL
)

;

CREATE INDEX rhn_apr_failure_aid_sid_idx
    ON rhnActionPackageRemovalFailure (action_id, server_id)
    ;

CREATE INDEX rhn_apr_failure_sid_idx
    ON rhnActionPackageRemovalFailure (server_id)
    ;

  07070100000070000081B400000000000000000000000167AE11140000071F000000000000000000000000000000000000003700000000susemanager-schema/common/tables/rhnActionPlaybook.sql    --
-- Copyright (c) 2021 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

CREATE TABLE rhnActionPlaybook
(
    id                  NUMERIC NOT NULL
                            CONSTRAINT rhn_action_playbook_id_pk
                                PRIMARY KEY,
    action_id           NUMERIC NOT NULL
                            CONSTRAINT rhn_action_playbook_aid_fk
                                REFERENCES rhnAction (id)
                                ON DELETE CASCADE,
    playbook_path       VARCHAR(1024) NOT NULL,
    inventory_path      VARCHAR(1024),
    test_mode           CHAR(1) DEFAULT ('N') NOT NULL
                            CONSTRAINT rhn_action_playbook_testmode_ck
                                CHECK (test_mode IN ('Y', 'N')),
    flush_cache         CHAR(1) DEFAULT ('N') NOT NULL
                            CONSTRAINT rhn_action_playbook_flushcache_ck
                                CHECK (flush_cache IN ('Y', 'N')),
    created             TIMESTAMPTZ
                            DEFAULT (current_timestamp) NOT NULL,
    modified            TIMESTAMPTZ
                            DEFAULT (current_timestamp) NOT NULL
)
;

CREATE UNIQUE INDEX rhn_act_playbook_aid_uq
    ON rhnActionPlaybook (action_id);

CREATE SEQUENCE rhn_act_playbook_id_seq;

 07070100000071000081B400000000000000000000000167AE11140000050E000000000000000000000000000000000000003300000000susemanager-schema/common/tables/rhnActionScap.sql    --
-- Copyright (c) 2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnActionScap
(
    id               NUMERIC NOT NULL
                         CONSTRAINT rhn_act_scap_id_pk PRIMARY KEY
                         ,
    action_id        NUMERIC NOT NULL
                         CONSTRAINT rhn_act_scap_act_fk
                             REFERENCES rhnAction (id)
                             ON DELETE CASCADE,
    path             VARCHAR(2048) NOT NULL,
    ovalfiles        VARCHAR(8192),
    parameters       BYTEA
)


;

CREATE UNIQUE INDEX rhn_act_scap_aid_idx
    ON rhnActionScap (action_id)
    
    ;

CREATE INDEX rhn_act_scap_path_idx
    ON rhnActionScap (path)
    
    ;

CREATE SEQUENCE rhn_act_scap_id_seq;
  07070100000072000081B400000000000000000000000167AE111400000559000000000000000000000000000000000000003500000000susemanager-schema/common/tables/rhnActionScript.sql  --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnActionScript
(
    id         NUMERIC NOT NULL
                   CONSTRAINT rhn_actscript_id_pk PRIMARY KEY
                   ,
    action_id  NUMERIC NOT NULL
                   CONSTRAINT rhn_actscript_aid_fk
                       REFERENCES rhnAction (id)
                       ON DELETE CASCADE,
    username   VARCHAR(32) NOT NULL,
    groupname  VARCHAR(32) NOT NULL,
    script     BYTEA,
    timeout    NUMERIC,
    created    TIMESTAMPTZ
                   DEFAULT (current_timestamp) NOT NULL,
    modified   TIMESTAMPTZ
                   DEFAULT (current_timestamp) NOT NULL
)


;

CREATE UNIQUE INDEX rhn_actscript_aid_uq_idx
    ON rhnActionScript (action_id)
    ;

CREATE SEQUENCE rhn_actscript_id_seq;

   07070100000073000081B400000000000000000000000167AE1114000003C9000000000000000000000000000000000000003500000000susemanager-schema/common/tables/rhnActionStatus.sql  --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnActionStatus
(
    id        NUMERIC NOT NULL
                  CONSTRAINT rhn_action_status_pk PRIMARY KEY
                  ,
    name      VARCHAR(16),
    created   TIMESTAMPTZ
                  DEFAULT (current_timestamp) NOT NULL,
    modified  TIMESTAMPTZ
                  DEFAULT (current_timestamp) NOT NULL
)

;

   07070100000074000081B400000000000000000000000167AE11140000059A000000000000000000000000000000000000003A00000000susemanager-schema/common/tables/rhnActionSubChannels.sql --
-- Copyright (c) 2018 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

CREATE TABLE rhnActionSubChannels (
    id                  NUMERIC NOT NULL
                            CONSTRAINT rhn_actionsubscrch_id_pk PRIMARY KEY,
    action_id           NUMERIC NOT NULL
                            CONSTRAINT rhn_actionsubscrch_aid_fk
                            REFERENCES rhnAction (id)
                            ON DELETE CASCADE,
    base_channel_id     NUMERIC
                            CONSTRAINT rhn_actionsubscrch_base_ch_fk
                            REFERENCES rhnChannel (id)
                            ON DELETE CASCADE,
    created             TIMESTAMPTZ
                            DEFAULT (CURRENT_TIMESTAMP) NOT NULL,
    modified            TIMESTAMPTZ
                            DEFAULT (CURRENT_TIMESTAMP) NOT NULL
)

;

CREATE SEQUENCE RHN_ACT_SUBSCR_CHNLS_ID_SEQ;  07070100000075000081B400000000000000000000000167AE11140000045C000000000000000000000000000000000000003E00000000susemanager-schema/common/tables/rhnActionSubChannelsList.sql --
-- Copyright (c) 2018 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

CREATE TABLE rhnActionSubChannelsList (
    subscribe_channels_id
                        NUMERIC NOT NULL
                            CONSTRAINT rhn_actionsubscrchls_det_fk
                            REFERENCES rhnActionSubChannels (id)
                            ON DELETE CASCADE,
    channel_id          NUMERIC NOT NULL
                            CONSTRAINT rhn_actionsubscrchls_ch_fk
                            REFERENCES rhnChannel (id)
                            ON DELETE CASCADE
)

;
07070100000076000081B400000000000000000000000167AE11140000046D000000000000000000000000000000000000004000000000susemanager-schema/common/tables/rhnActionSubChannelsTokens.sql   --
-- Copyright (c) 2018 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

CREATE TABLE rhnActionSubChannelsTokens (
    subscribe_channels_id
                        NUMERIC NOT NULL
                            CONSTRAINT rhn_actionsubscrchtok_det_fk
                            REFERENCES rhnActionSubChannels (id)
                            ON DELETE CASCADE,
    token_id            NUMERIC NOT NULL
                            CONSTRAINT rhn_actionsubscrchtok_tok_fk
                            REFERENCES suseChannelAccessToken (id)
                            ON DELETE CASCADE
)

;
   07070100000077000081B400000000000000000000000167AE111400000690000000000000000000000000000000000000003300000000susemanager-schema/common/tables/rhnActionType.sql    --
-- Copyright (c) 2008--2010 Red Hat, Inc.
-- Copyright (c) 2020 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnActionType
(
    id                NUMERIC NOT NULL
                          CONSTRAINT rhn_action_type_pk PRIMARY KEY,
    label             VARCHAR(48) NOT NULL,
    name              VARCHAR(100) NOT NULL,
    trigger_snapshot  CHAR(1)
                          DEFAULT ('N') NOT NULL
                          CONSTRAINT rhn_action_type_trigsnap_ck
                              CHECK (trigger_snapshot in ('Y','N')),
    unlocked_only     CHAR(1)
                          DEFAULT ('N') NOT NULL
                          CONSTRAINT rhn_action_type_unlck_ck
                              CHECK (unlocked_only in ('Y','N')),
    maintenance_mode_only CHAR(1)
                          DEFAULT ('N') NOT NULL
                          CONSTRAINT rhn_action_type_mtmode_ck
                              CHECK (maintenance_mode_only in ('Y','N'))
)
;

CREATE UNIQUE INDEX rhn_action_type_label_uq
    ON rhnActionType (label);

CREATE UNIQUE INDEX rhn_action_type_name_uq
    ON rhnActionType (name);

07070100000078000081B400000000000000000000000167AE111400000488000000000000000000000000000000000000003900000000susemanager-schema/common/tables/rhnActionVirtCreate.sql  --
-- Copyright (c) 2018 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

CREATE TABLE rhnActionVirtCreate
(
    action_id            NUMERIC NOT NULL
                             CONSTRAINT rhn_action_virt_create_aid_fk
                                 REFERENCES rhnAction (id)
                                 ON DELETE CASCADE
                             CONSTRAINT rhn_action_virt_create_aid_pk
                                 PRIMARY KEY,
    uuid                 VARCHAR(128),
    details              TEXT
)

;

CREATE UNIQUE INDEX rhn_action_virt_create_aid_uq
    ON rhnActionVirtCreate (action_id)
    ;
07070100000079000081B400000000000000000000000167AE1114000004B8000000000000000000000000000000000000003900000000susemanager-schema/common/tables/rhnActionVirtDelete.sql  --
-- Copyright (c) 2018 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnActionVirtDelete
(
    action_id  NUMERIC NOT NULL
                   CONSTRAINT rhn_avdl_aid_fk
                       REFERENCES rhnAction (id)
                       ON DELETE CASCADE,
    uuid       VARCHAR(128) NOT NULL,
    created    TIMESTAMPTZ
                   DEFAULT (current_timestamp) NOT NULL,
    modified   TIMESTAMPTZ
                   DEFAULT (current_timestamp) NOT NULL
)

;

CREATE UNIQUE INDEX rhn_avdl_aid_uq
    ON rhnActionVirtDelete (action_id)
    ;

ALTER TABLE rhnActionVirtDelete
    ADD CONSTRAINT rhn_avdl_aid_pk PRIMARY KEY (action_id);

0707010000007A000081B400000000000000000000000167AE1114000004C3000000000000000000000000000000000000003A00000000susemanager-schema/common/tables/rhnActionVirtDestroy.sql --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnActionVirtDestroy
(
    action_id  NUMERIC NOT NULL
                   CONSTRAINT rhn_avd_aid_fk
                       REFERENCES rhnAction (id)
                       ON DELETE CASCADE,
    uuid       VARCHAR(128) NOT NULL,
    created    TIMESTAMPTZ
                   DEFAULT (current_timestamp) NOT NULL,
    modified   TIMESTAMPTZ
                   DEFAULT (current_timestamp) NOT NULL
)

;

CREATE UNIQUE INDEX rhn_avd_aid_uq
    ON rhnActionVirtDestroy (action_id)
    ;

ALTER TABLE rhnActionVirtDestroy
    ADD CONSTRAINT rhn_avd_aid_pk PRIMARY KEY (action_id);

 0707010000007B000081B400000000000000000000000167AE111400000416000000000000000000000000000000000000003A00000000susemanager-schema/common/tables/rhnActionVirtMigrate.sql --
-- Copyright (c) 2021 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

CREATE TABLE rhnActionVirtMigrate
(
    action_id  NUMERIC NOT NULL
                   CONSTRAINT rhn_virt_guest_migrate_aid_fk
                       REFERENCES rhnAction (id)
                       ON DELETE CASCADE
                   CONSTRAINT rhn_action_virt_guest_migrate_aid_pk
                       PRIMARY KEY,
    uuid       VARCHAR(128) NOT NULL,
    primitive  VARCHAR(128),
    target     VARCHAR(128) NOT NULL
)
;
  0707010000007C000081B400000000000000000000000167AE1114000004B1000000000000000000000000000000000000004000000000susemanager-schema/common/tables/rhnActionVirtNetworkCreate.sql   --
-- Copyright (c) 2021 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

CREATE TABLE rhnActionVirtNetworkCreate
(
    action_id            NUMERIC NOT NULL
                             CONSTRAINT rhn_action_virt_network_create_aid_fk
                                 REFERENCES rhnAction (id)
                                 ON DELETE CASCADE
                             CONSTRAINT rhn_action_virt_network_create_aid_pk
                                 PRIMARY KEY,
    network_name         VARCHAR(256),
    definition           VARCHAR(2048)
)
;

CREATE UNIQUE INDEX rhn_action_virt_network_create_aid_uq
    ON rhnActionVirtNetworkCreate (action_id);
   0707010000007D000081B400000000000000000000000167AE1114000004CB000000000000000000000000000000000000004500000000susemanager-schema/common/tables/rhnActionVirtNetworkStateChange.sql  --
-- Copyright (c) 2020 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

CREATE TABLE rhnActionVirtNetworkStateChange
(
    action_id            NUMERIC NOT NULL
                             CONSTRAINT rhn_action_virt_network_state_change_aid_fk
                                 REFERENCES rhnAction (id)
                                 ON DELETE CASCADE
                             CONSTRAINT rhn_action_virt_network_state_change_aid_pk
                                 PRIMARY KEY,
    network_name         VARCHAR(256),
    state                VARCHAR(10)
)
;

CREATE UNIQUE INDEX rhn_action_virt_network_state_change_aid_uq
    ON rhnActionVirtNetworkStateChange (action_id);
 0707010000007E000081B400000000000000000000000167AE1114000006B1000000000000000000000000000000000000003D00000000susemanager-schema/common/tables/rhnActionVirtPoolCreate.sql  --
-- Copyright (c) 2020 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

CREATE TABLE rhnActionVirtPoolCreate
(
    action_id            NUMERIC NOT NULL
                             CONSTRAINT rhn_action_virt_pool_create_aid_fk
                                 REFERENCES rhnAction (id)
                                 ON DELETE CASCADE
                             CONSTRAINT rhn_action_virt_pool_create_aid_pk
                                 PRIMARY KEY,
    pool_name            VARCHAR(256),
    uuid                 VARCHAR(128),
    type                 VARCHAR(25),
    target               VARCHAR(256),
    autostart            CHAR(1)
                            DEFAULT ('Y') NOT NULL
                            CONSTRAINT rhn_avpcreate_autostart_ck
                                CHECK (autostart in ('Y','N')),
    permission_mode                 VARCHAR(4),
    permission_owner                VARCHAR(10),
    permission_group                VARCHAR(10),
    permission_seclabel             VARCHAR(256),
    source               VARCHAR(2048)
)
;

CREATE UNIQUE INDEX rhn_action_virt_pool_create_aid_uq
    ON rhnActionVirtPoolCreate (action_id);

   0707010000007F000081B400000000000000000000000167AE111400000548000000000000000000000000000000000000003D00000000susemanager-schema/common/tables/rhnActionVirtPoolDelete.sql  --
-- Copyright (c) 2020 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

CREATE TABLE rhnActionVirtPoolDelete
(
    action_id            NUMERIC NOT NULL
                             CONSTRAINT rhn_action_virt_pool_delete_aid_fk
                                 REFERENCES rhnAction (id)
                                 ON DELETE CASCADE
                             CONSTRAINT rhn_action_virt_pool_delete_aid_pk
                                 PRIMARY KEY,
    pool_name            VARCHAR(256),
    purge                CHAR(1)
                            DEFAULT ('Y') NOT NULL
                            CONSTRAINT rhn_avpdelete_purge_ck
                                CHECK (purge in ('Y','N'))
)
;

CREATE UNIQUE INDEX rhn_action_virt_pool_delete_aid_uq
    ON rhnActionVirtPoolDelete (action_id);
07070100000080000081B400000000000000000000000167AE111400000484000000000000000000000000000000000000003E00000000susemanager-schema/common/tables/rhnActionVirtPoolRefresh.sql --
-- Copyright (c) 2020 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

CREATE TABLE rhnActionVirtPoolRefresh
(
    action_id            NUMERIC NOT NULL
                             CONSTRAINT rhn_action_virt_pool_refresh_aid_fk
                                 REFERENCES rhnAction (id)
                                 ON DELETE CASCADE
                             CONSTRAINT rhn_action_virt_pool_refresh_aid_pk
                                 PRIMARY KEY,
    pool_name            VARCHAR(256)
)
;

CREATE UNIQUE INDEX rhn_action_virt_pool_refresh_aid_uq
    ON rhnActionVirtPoolRefresh (action_id)
    ;
07070100000081000081B400000000000000000000000167AE111400000475000000000000000000000000000000000000003C00000000susemanager-schema/common/tables/rhnActionVirtPoolStart.sql   --
-- Copyright (c) 2020 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

CREATE TABLE rhnActionVirtPoolStart
(
    action_id            NUMERIC NOT NULL
                             CONSTRAINT rhn_action_virt_pool_start_aid_fk
                                 REFERENCES rhnAction (id)
                                 ON DELETE CASCADE
                             CONSTRAINT rhn_action_virt_pool_start_aid_pk
                                 PRIMARY KEY,
    pool_name            VARCHAR(256)
)
;

CREATE UNIQUE INDEX rhn_action_virt_pool_start_aid_uq
    ON rhnActionVirtPoolStart (action_id);
   07070100000082000081B400000000000000000000000167AE111400000470000000000000000000000000000000000000003B00000000susemanager-schema/common/tables/rhnActionVirtPoolStop.sql    --
-- Copyright (c) 2020 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

CREATE TABLE rhnActionVirtPoolStop
(
    action_id            NUMERIC NOT NULL
                             CONSTRAINT rhn_action_virt_pool_stop_aid_fk
                                 REFERENCES rhnAction (id)
                                 ON DELETE CASCADE
                             CONSTRAINT rhn_action_virt_pool_stop_aid_pk
                                 PRIMARY KEY,
    pool_name            VARCHAR(256)
)
;

CREATE UNIQUE INDEX rhn_action_virt_pool_stop_aid_uq
    ON rhnActionVirtPoolStop (action_id);
07070100000083000081B400000000000000000000000167AE111400000577000000000000000000000000000000000000003900000000susemanager-schema/common/tables/rhnActionVirtReboot.sql  --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnActionVirtReboot
(
    action_id  NUMERIC NOT NULL
                   CONSTRAINT rhn_avreboot_aid_fk
                       REFERENCES rhnAction (id)
                       ON DELETE CASCADE,
    uuid       VARCHAR(128) NOT NULL,
    force      CHAR(1)
                   DEFAULT ('N') NOT NULL
                   CONSTRAINT rhn_avreboot_force_ck
                       CHECK (force in ('Y','N')),
    created    TIMESTAMPTZ
                   DEFAULT (current_timestamp) NOT NULL,
    modified   TIMESTAMPTZ
                   DEFAULT (current_timestamp) NOT NULL
)

;

CREATE UNIQUE INDEX rhn_avreboot_aid_uq
    ON rhnActionVirtReboot (action_id)
    ;

ALTER TABLE rhnActionVirtReboot
    ADD CONSTRAINT rhn_avreboot_aid_pk PRIMARY KEY (action_id);

 07070100000084000081B400000000000000000000000167AE1114000004AF000000000000000000000000000000000000003A00000000susemanager-schema/common/tables/rhnActionVirtRefresh.sql --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnActionVirtRefresh
(
    action_id  NUMERIC NOT NULL
                   CONSTRAINT rhn_avrefresh_aid_fk
                       REFERENCES rhnAction (id)
                       ON DELETE CASCADE,
    created    TIMESTAMPTZ
                   DEFAULT (current_timestamp) NOT NULL,
    modified   TIMESTAMPTZ
                   DEFAULT (current_timestamp) NOT NULL
)

;

CREATE UNIQUE INDEX rhn_avrefresh_aid_uq
    ON rhnActionVirtRefresh (action_id)
    ;

ALTER TABLE rhnActionVirtRefresh
    ADD CONSTRAINT rhn_avrefresh_aid_pk PRIMARY KEY (action_id);

 07070100000085000081B400000000000000000000000167AE1114000004CF000000000000000000000000000000000000003900000000susemanager-schema/common/tables/rhnActionVirtResume.sql  --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnActionVirtResume
(
    action_id  NUMERIC NOT NULL
                   CONSTRAINT rhn_avresume_aid_fk
                       REFERENCES rhnAction (id)
                       ON DELETE CASCADE,
    uuid       VARCHAR(128) NOT NULL,
    created    TIMESTAMPTZ
                   DEFAULT (current_timestamp) NOT NULL,
    modified   TIMESTAMPTZ
                   DEFAULT (current_timestamp) NOT NULL
)

;

CREATE UNIQUE INDEX rhn_avresume_aid_uq
    ON rhnActionVirtResume (action_id)
    ;

ALTER TABLE rhnActionVirtResume
    ADD CONSTRAINT rhn_avresume_aid_pk PRIMARY KEY (action_id);

 07070100000086000081B400000000000000000000000167AE11140000052D000000000000000000000000000000000000004100000000susemanager-schema/common/tables/rhnActionVirtSchedulePoller.sql  --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnActionVirtSchedulePoller
(
    action_id  NUMERIC NOT NULL
                   CONSTRAINT rhn_avsp_aid_fk
                       REFERENCES rhnAction (id)
                       ON DELETE CASCADE,
    minute     NUMERIC,
    hour       NUMERIC,
    dom        NUMERIC,
    month      NUMERIC,
    dow        NUMERIC,
    created    TIMESTAMPTZ
                   DEFAULT (current_timestamp) NOT NULL,
    modified   TIMESTAMPTZ
                   DEFAULT (current_timestamp) NOT NULL
)

;

CREATE UNIQUE INDEX rhn_avsp_aid_uq
    ON rhnActionVirtSchedulePoller (action_id)
    ;

ALTER TABLE rhnActionVirtSchedulePoller
    ADD CONSTRAINT rhn_avsp_aid_pk PRIMARY KEY (action_id);

   07070100000087000081B400000000000000000000000167AE1114000004ED000000000000000000000000000000000000003C00000000susemanager-schema/common/tables/rhnActionVirtSetMemory.sql   --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnActionVirtSetMemory
(
    action_id  NUMERIC NOT NULL
                   CONSTRAINT rhn_avsm_aid_fk
                       REFERENCES rhnAction (id)
                       ON DELETE CASCADE,
    uuid       VARCHAR(128) NOT NULL,
    memory     NUMERIC NOT NULL,
    created    TIMESTAMPTZ
                   DEFAULT (current_timestamp) NOT NULL,
    modified   TIMESTAMPTZ
                   DEFAULT (current_timestamp) NOT NULL
)

;

CREATE UNIQUE INDEX rhn_avsm_aid_uq
    ON rhnActionVirtSetMemory (action_id)
    ;

ALTER TABLE rhnActionVirtSetMemory
    ADD CONSTRAINT rhn_avsm_aid_pk PRIMARY KEY (action_id);

   07070100000088000081B400000000000000000000000167AE111400000585000000000000000000000000000000000000003B00000000susemanager-schema/common/tables/rhnActionVirtShutdown.sql    --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnActionVirtShutdown
(
    action_id  NUMERIC NOT NULL
                   CONSTRAINT rhn_avshutdown_aid_fk
                       REFERENCES rhnAction (id)
                       ON DELETE CASCADE,
    uuid       VARCHAR(128) NOT NULL,
    force      CHAR(1)
                   DEFAULT ('N') NOT NULL
                   CONSTRAINT rhn_avshutdown_force_ck
                       CHECK (force in ('Y','N')),
    created    TIMESTAMPTZ
                   DEFAULT (current_timestamp) NOT NULL,
    modified   TIMESTAMPTZ
                   DEFAULT (current_timestamp) NOT NULL
)

;

CREATE UNIQUE INDEX rhn_avshutdown_aid_uq
    ON rhnActionVirtShutdown (action_id)
    ;

ALTER TABLE rhnActionVirtShutdown
    ADD CONSTRAINT rhn_avshutdown_aid_pk PRIMARY KEY (action_id);

   07070100000089000081B400000000000000000000000167AE11140000043E000000000000000000000000000000000000003800000000susemanager-schema/common/tables/rhnActionVirtStart.sql   --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnActionVirtStart
(
    action_id  NUMERIC NOT NULL,
    uuid       VARCHAR(128) NOT NULL,
    created    TIMESTAMPTZ
                   DEFAULT (current_timestamp) NOT NULL,
    modified   TIMESTAMPTZ
                   DEFAULT (current_timestamp) NOT NULL
)

;

CREATE UNIQUE INDEX rhn_avstart_aid_uq
    ON rhnActionVirtStart (action_id)
    ;

ALTER TABLE rhnActionVirtStart
    ADD CONSTRAINT rhn_avstart_aid_pk PRIMARY KEY (action_id);

  0707010000008A000081B400000000000000000000000167AE1114000004D5000000000000000000000000000000000000003A00000000susemanager-schema/common/tables/rhnActionVirtSuspend.sql --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnActionVirtSuspend
(
    action_id  NUMERIC NOT NULL
                   CONSTRAINT rhn_avsuspend_aid_fk
                       REFERENCES rhnAction (id)
                       ON DELETE CASCADE,
    uuid       VARCHAR(128) NOT NULL,
    created    TIMESTAMPTZ
                   DEFAULT (current_timestamp) NOT NULL,
    modified   TIMESTAMPTZ
                   DEFAULT (current_timestamp) NOT NULL
)

;

CREATE UNIQUE INDEX rhn_avsuspend_aid_uq
    ON rhnActionVirtSuspend (action_id)
    ;

ALTER TABLE rhnActionVirtSuspend
    ADD CONSTRAINT rhn_avsuspend_aid_pk PRIMARY KEY (action_id);

   0707010000008B000081B400000000000000000000000167AE1114000004E1000000000000000000000000000000000000003700000000susemanager-schema/common/tables/rhnActionVirtVcpu.sql    --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnActionVirtVcpu
(
    action_id  NUMERIC NOT NULL
                   CONSTRAINT rhn_avcpu_aid_fk
                       REFERENCES rhnAction (id)
                       ON DELETE CASCADE,
    uuid       VARCHAR(128) NOT NULL,
    vcpu       NUMERIC NOT NULL,
    created    TIMESTAMPTZ
                   DEFAULT (current_timestamp) NOT NULL,
    modified   TIMESTAMPTZ
                   DEFAULT (current_timestamp) NOT NULL
)

;

CREATE UNIQUE INDEX rhn_avcpu_aid_uq
    ON rhnActionVirtVcpu (action_id)
    ;

ALTER TABLE rhnActionVirtVcpu
    ADD CONSTRAINT rhn_avcpu_aid_pk PRIMARY KEY (action_id);

   0707010000008C000081B400000000000000000000000167AE111400000495000000000000000000000000000000000000003C00000000susemanager-schema/common/tables/rhnActionVirtVolDelete.sql   -- Copyright (c) 2020 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

CREATE TABLE rhnActionVirtVolDelete
(
    action_id            NUMERIC NOT NULL
                             CONSTRAINT rhn_action_virt_vol_delete_aid_fk
                                 REFERENCES rhnAction (id)
                                 ON DELETE CASCADE
                             CONSTRAINT rhn_action_virt_vol_delete_aid_pk
                                 PRIMARY KEY,
    pool_name            VARCHAR(256),
    volume_name          VARCHAR(256)
);

CREATE UNIQUE INDEX rhn_action_virt_delete_aid_uq
    ON rhnActionVirtVolDelete (action_id);

   0707010000008D000081B400000000000000000000000167AE1114000006BA000000000000000000000000000000000000003600000000susemanager-schema/common/tables/rhnActivationKey.sql --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnActivationKey
(
    token          VARCHAR(48) NOT NULL
                       CONSTRAINT rhn_act_key_token_uq UNIQUE,
    reg_token_id   NUMERIC NOT NULL
                       CONSTRAINT rhn_act_key_reg_tid_fk
                           REFERENCES rhnRegToken (id)
                           ON DELETE CASCADE,
    ks_session_id  NUMERIC
                       CONSTRAINT rhn_act_key_ks_sid_fk
                           REFERENCES rhnKickstartSession (id)
                           ON DELETE CASCADE,
    created        TIMESTAMPTZ
                       DEFAULT (current_timestamp) NOT NULL,
    modified       TIMESTAMPTZ
                       DEFAULT (current_timestamp) NOT NULL,
    bootstrap      CHAR(1)
                       DEFAULT ('N') NOT NULL
                       CONSTRAINT rhn_act_key_bootstrap_ck
                           CHECK (bootstrap in ('Y', 'N'))
)

;

CREATE INDEX rhn_act_key_kssid_rtid_idx
    ON rhnActivationKey (ks_session_id, reg_token_id)
    
    ;

CREATE INDEX rhn_act_key_rtid_idx
    ON rhnActivationKey (reg_token_id)
    
    ;

  0707010000008E000081B400000000000000000000000167AE1114000004B6000000000000000000000000000000000000003100000000susemanager-schema/common/tables/rhnArchType.sql  --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnArchType
(
    id        NUMERIC NOT NULL
                  CONSTRAINT rhn_archtype_id_pk PRIMARY KEY
                  ,
    label     VARCHAR(64) NOT NULL,
    name      VARCHAR(128) NOT NULL,
    created   TIMESTAMPTZ
                  DEFAULT (current_timestamp) NOT NULL,
    modified  TIMESTAMPTZ
                  DEFAULT (current_timestamp) NOT NULL
)

;

CREATE INDEX rhn_archtype_label_id_idx
    ON rhnArchType (label, id)
    ;

CREATE SEQUENCE rhn_archtype_id_seq;

ALTER TABLE rhnArchType
    ADD CONSTRAINT rhn_archtype_label_uq UNIQUE (label);

  0707010000008F000081B400000000000000000000000167AE111400000527000000000000000000000000000000000000003800000000susemanager-schema/common/tables/rhnArchTypeActions.sql   --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnArchTypeActions
(
    arch_type_id    NUMERIC NOT NULL
                        CONSTRAINT rhn_archtypeacts_atid_fk
                            REFERENCES rhnArchType (id),
    action_style    VARCHAR(64) NOT NULL,
    action_type_id  NUMERIC NOT NULL
                        CONSTRAINT rhn_archtypeacts_actid_fk
                            REFERENCES rhnActionType (id),
    created         TIMESTAMPTZ
                        DEFAULT (current_timestamp) NOT NULL,
    modified        TIMESTAMPTZ
                        DEFAULT (current_timestamp) NOT NULL
)

;

CREATE UNIQUE INDEX rhn_archtypeacts_atid_as_uq
    ON rhnArchTypeActions (arch_type_id, action_style)
    ;

 07070100000090000081B400000000000000000000000167AE111400000369000000000000000000000000000000000000002C00000000susemanager-schema/common/tables/rhnCVE.sql   --
-- Copyright (c) 2008 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnCVE
(
    id    NUMERIC NOT NULL
              CONSTRAINT rhn_cve_id_pk PRIMARY KEY
              ,
    name  VARCHAR(20) NOT NULL
)

;

CREATE UNIQUE INDEX rhn_cve_name_uq
    ON rhnCVE (name)
    ;

CREATE SEQUENCE rhn_cve_id_seq;

   07070100000091000081B400000000000000000000000167AE111400000EDB000000000000000000000000000000000000003000000000susemanager-schema/common/tables/rhnChannel.sql   --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnChannel
(
    id                  NUMERIC NOT NULL
                            CONSTRAINT rhn_channel_id_pk PRIMARY KEY
                            ,
    parent_channel      NUMERIC
                            CONSTRAINT rhn_channel_parent_ch_fk
                                REFERENCES rhnChannel (id),
    org_id              NUMERIC
                            CONSTRAINT rhn_channel_org_fk
                                REFERENCES web_customer (id),
    channel_arch_id     NUMERIC NOT NULL
                            CONSTRAINT rhn_channel_caid_fk
                                REFERENCES rhnChannelArch (id),
    label               VARCHAR(128) NOT NULL,
    basedir             VARCHAR(256) NOT NULL,
    name                VARCHAR(256) NOT NULL,
    summary             VARCHAR(500) NOT NULL,
    description         VARCHAR(4000),
    product_name_id     NUMERIC
                            CONSTRAINT rhn_channel_product_name_ch_fk
                                REFERENCES rhnProductName (id),
    gpg_check           CHAR(1)
                            DEFAULT ('Y') NOT NULL
                            CONSTRAINT rhn_channel_gc_ck
                                CHECK (gpg_check in ('Y', 'N')),
    gpg_key_url         VARCHAR(256),
    gpg_key_id          VARCHAR(14),
    gpg_key_fp          VARCHAR(50),
    end_of_life         TIMESTAMPTZ,
    checksum_type_id    NUMERIC CONSTRAINT rhn_channel_checksum_fk
                                REFERENCES rhnChecksumType(id),
    receiving_updates   CHAR(1)
                            DEFAULT ('Y') NOT NULL
                            CONSTRAINT rhn_channel_ru_ck
                                CHECK (receiving_updates in ('Y', 'N')),
    last_modified       TIMESTAMPTZ
                            DEFAULT (current_timestamp) NOT NULL,
    last_synced         TIMESTAMPTZ,
    channel_product_id  NUMERIC
                            CONSTRAINT rhn_channel_cpid_fk
                                REFERENCES rhnChannelProduct (id),
    channel_access      VARCHAR(10)
                            DEFAULT ('private'),
    maint_name          VARCHAR(128),
    maint_email         VARCHAR(128),
    maint_phone         VARCHAR(128),
    support_policy      VARCHAR(256),
    update_tag          VARCHAR(128),
    installer_updates   CHAR(1)
                            DEFAULT ('N') NOT NULL
                            CONSTRAINT rhn_channel_instup_ck
                                CHECK (installer_updates in ('Y', 'N')),
    created             TIMESTAMPTZ
                            DEFAULT (current_timestamp) NOT NULL,
    modified            TIMESTAMPTZ
                            DEFAULT (current_timestamp) NOT NULL
)

;

CREATE UNIQUE INDEX rhn_channel_label_uq
    ON rhnChannel (label)
    ;

CREATE UNIQUE INDEX rhn_channel_name_uq
    ON rhnChannel (name)
    ;

CREATE INDEX rhn_channel_org_idx
    ON rhnChannel (org_id, id)
    
    ;

CREATE INDEX rhn_channel_parent_id_idx
    ON rhnChannel (parent_channel, id)
    
    ;

CREATE INDEX rhn_channel_access_idx
    ON rhnChannel (channel_access)
    
    ;

CREATE SEQUENCE rhn_channel_id_seq START WITH 101;

 07070100000092000081B400000000000000000000000167AE111400000582000000000000000000000000000000000000003400000000susemanager-schema/common/tables/rhnChannelArch.sql   --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnChannelArch
(
    id            NUMERIC NOT NULL,
    label         VARCHAR(64) NOT NULL,
    arch_type_id  NUMERIC NOT NULL
                      CONSTRAINT rhn_carch_atid_fk
                          REFERENCES rhnArchType (id),
    name          VARCHAR(64) NOT NULL,
    created       TIMESTAMPTZ
                      DEFAULT (current_timestamp) NOT NULL,
    modified      TIMESTAMPTZ
                      DEFAULT (current_timestamp) NOT NULL
)

;

CREATE SEQUENCE rhn_channel_arch_id_seq START WITH 500;

ALTER TABLE rhnChannelArch
    ADD CONSTRAINT rhn_carch_id_pk PRIMARY KEY (id);

ALTER TABLE rhnChannelArch
    ADD CONSTRAINT rhn_carch_label_uq UNIQUE (label)
    ;

ALTER TABLE rhnChannelArch
    ADD CONSTRAINT rhn_carch_name_uq UNIQUE (name)
    ;
  07070100000093000081B400000000000000000000000167AE1114000005E0000000000000000000000000000000000000003600000000susemanager-schema/common/tables/rhnChannelCloned.sql --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnChannelCloned
(
    original_id  NUMERIC NOT NULL
                     CONSTRAINT rhn_channelclone_fcid_fk
                         REFERENCES rhnChannel (id)
                         ON DELETE CASCADE,
    id           NUMERIC NOT NULL
                     CONSTRAINT rhn_channelclone_tcid_fk
                         REFERENCES rhnChannel (id)
                         ON DELETE CASCADE,
    created      TIMESTAMPTZ
                     DEFAULT (current_timestamp) NOT NULL,
    modified     TIMESTAMPTZ
                     DEFAULT (current_timestamp) NOT NULL
)

;

CREATE INDEX rhn_channelclone_fcid_tcid_idx
    ON rhnChannelCloned (original_id, id)
    ;

ALTER TABLE rhnChannelCloned
    ADD CONSTRAINT rhn_channelclone_fcid_tcid_uq UNIQUE (original_id, id);

ALTER TABLE rhnChannelCloned
    ADD CONSTRAINT rhn_channelclone_id_pk PRIMARY KEY (id);

07070100000094000081B400000000000000000000000167AE111400000684000000000000000000000000000000000000003500000000susemanager-schema/common/tables/rhnChannelComps.sql  --
-- Copyright (c) 2008--2018 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnChannelComps
(
    id                 NUMERIC NOT NULL
                           CONSTRAINT rhn_channelcomps_id_pk PRIMARY KEY,
    channel_id         NUMERIC NOT NULL
                           CONSTRAINT rhn_channelcomps_cid_fk
                               REFERENCES rhnChannel (id)
                               ON DELETE CASCADE,
    relative_filename  VARCHAR(256) NOT NULL,
    last_modified      TIMESTAMPTZ
                           DEFAULT (current_timestamp) NOT NULL,
    created            TIMESTAMPTZ
                           DEFAULT (current_timestamp) NOT NULL,
    modified           TIMESTAMPTZ
                           DEFAULT (current_timestamp) NOT NULL,
    comps_type_id      NUMERIC NOT NULL
                          CONSTRAINT rhn_channelcomps_comps_type_fk
                               REFERENCES rhnCompsType(id)
)

;

CREATE UNIQUE INDEX rhn_channelcomps_cid_ctype_uq
    ON rhnChannelComps (channel_id, comps_type_id)
    ;

CREATE SEQUENCE rhn_channelcomps_id_seq START WITH 101;

07070100000095000081B400000000000000000000000167AE111400000554000000000000000000000000000000000000003D00000000susemanager-schema/common/tables/rhnChannelContentSource.sql  --
-- Copyright (c) 2010--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--
--
--
--
CREATE TABLE rhnChannelContentSource
(
    source_id     NUMERIC NOT NULL
                         CONSTRAINT rhn_ccs_src_id_fk
                             REFERENCES rhnContentSource (id)
                             ON DELETE CASCADE,
    channel_id    NUMERIC NOT NULL
                         CONSTRAINT rhn_ccs_cid_fk
                             REFERENCES rhnChannel (id)
                             ON DELETE CASCADE,
    created          TIMESTAMPTZ
                         DEFAULT (current_timestamp) NOT NULL,
    modified         TIMESTAMPTZ
                         DEFAULT (current_timestamp) NOT NULL
)

;

ALTER TABLE rhnChannelContentSource
    ADD CONSTRAINT rhn_ccs_uq UNIQUE (source_id, channel_id)
    ;
07070100000096000081B400000000000000000000000167AE11140000053C000000000000000000000000000000000000003600000000susemanager-schema/common/tables/rhnChannelErrata.sql --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnChannelErrata
(
    channel_id  NUMERIC NOT NULL
                    CONSTRAINT rhn_ce_cid_fk
                        REFERENCES rhnChannel (id)
                        ON DELETE CASCADE,
    errata_id   NUMERIC NOT NULL
                    CONSTRAINT rhn_ce_eid_fk
                        REFERENCES rhnErrata (id)
                        ON DELETE CASCADE,
    created     TIMESTAMPTZ
                    DEFAULT (current_timestamp) NOT NULL,
    modified    TIMESTAMPTZ
                    DEFAULT (current_timestamp) NOT NULL
)

;

CREATE UNIQUE INDEX rhn_ce_ce_uq
    ON rhnChannelErrata (channel_id, errata_id)
    ;

CREATE INDEX rhn_ce_eid_idx
    ON rhnChannelErrata (errata_id)
    ;

07070100000097000081B400000000000000000000000167AE1114000005B5000000000000000000000000000000000000003600000000susemanager-schema/common/tables/rhnChannelFamily.sql --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnChannelFamily
(
    id           NUMERIC NOT NULL
                     CONSTRAINT rhn_channel_family_id_pk PRIMARY KEY
                     ,
    org_id       NUMERIC
                     CONSTRAINT rhn_channel_family_org_fk
                         REFERENCES web_customer (id)
                         ON DELETE CASCADE,
    name         VARCHAR(128) NOT NULL,
    label        VARCHAR(128) NOT NULL,
    created      TIMESTAMPTZ
                     DEFAULT (current_timestamp) NOT NULL,
    modified     TIMESTAMPTZ
                     DEFAULT (current_timestamp) NOT NULL
)

;

CREATE UNIQUE INDEX rhn_channel_family_label_uq
    ON rhnChannelFamily (label)
    ;

CREATE UNIQUE INDEX rhn_channel_family_name_uq
    ON rhnChannelFamily (name)
    ;

CREATE SEQUENCE rhn_channel_family_id_seq START WITH 1000;

   07070100000098000081B400000000000000000000000167AE111400000599000000000000000000000000000000000000003D00000000susemanager-schema/common/tables/rhnChannelFamilyMembers.sql  --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnChannelFamilyMembers
(
    channel_id         NUMERIC NOT NULL
                           CONSTRAINT rhn_cf_members_c_fk
                               REFERENCES rhnChannel (id)
                               ON DELETE CASCADE,
    channel_family_id  NUMERIC NOT NULL
                           CONSTRAINT rhn_cf_family_fk
                               REFERENCES rhnChannelFamily (id),
    created            TIMESTAMPTZ
                           DEFAULT (current_timestamp) NOT NULL,
    modified           TIMESTAMPTZ
                           DEFAULT (current_timestamp) NOT NULL
)

;

CREATE UNIQUE INDEX rhn_cf_c_uq
    ON rhnChannelFamilyMembers (channel_id)
    ;

CREATE INDEX rhn_cf_member_cf_c_idx
    ON rhnChannelFamilyMembers (channel_family_id, channel_id)
    
    ;

   07070100000099000081B400000000000000000000000167AE1114000006B0000000000000000000000000000000000000003D00000000susemanager-schema/common/tables/rhnChannelNewestPackage.sql  --
-- Copyright (c) 2008--2010 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnChannelNewestPackage
(
    channel_id       NUMERIC NOT NULL
                         CONSTRAINT rhn_cnp_cid_fk
                             REFERENCES rhnChannel (id)
                             ON DELETE CASCADE,
    name_id          NUMERIC NOT NULL
                         CONSTRAINT rhn_cnp_nid_fk
                             REFERENCES rhnPackageName (id),
    evr_id           NUMERIC NOT NULL
                         CONSTRAINT rhn_cnp_eid_fk
                             REFERENCES rhnPackageEVR (id),
    package_arch_id  NUMERIC NOT NULL
                         CONSTRAINT rhn_cnp_paid_fk
                             REFERENCES rhnPackageArch (id),
    package_id       NUMERIC NOT NULL
                         CONSTRAINT rhn_cnp_pid_fk
                             REFERENCES rhnPackage (id)
                             ON DELETE CASCADE
)

;


CREATE INDEX rhn_cnp_pid_idx
    ON rhnChannelNewestPackage (package_id)
    ;

ALTER TABLE rhnChannelNewestPackage
    ADD CONSTRAINT rhn_cnp_cid_nid_uq UNIQUE (channel_id, name_id, package_arch_id);

0707010000009A000081B400000000000000000000000167AE111400000450000000000000000000000000000000000000004200000000susemanager-schema/common/tables/rhnChannelNewestPackageAudit.sql --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnChannelNewestPackageAudit
(
    refresh_time  TIMESTAMPTZ
                      DEFAULT (current_timestamp) NOT NULL,
    channel_id    NUMERIC NOT NULL
                      CONSTRAINT rhn_cnp_at_cid_fk
                          REFERENCES rhnChannel (id)
                          ON DELETE CASCADE,
    caller        VARCHAR(256) NOT NULL
)

;

CREATE INDEX rhn_cnp_a_t_all_idx
    ON rhnChannelNewestPackageAudit (channel_id, refresh_time, caller)
    ;

0707010000009B000081B400000000000000000000000167AE11140000051D000000000000000000000000000000000000003700000000susemanager-schema/common/tables/rhnChannelPackage.sql    --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnChannelPackage
(
    channel_id  NUMERIC NOT NULL
                    CONSTRAINT rhn_cp_cid_fk
                        REFERENCES rhnChannel (id)
                        ON DELETE CASCADE,
    package_id  NUMERIC NOT NULL
                    CONSTRAINT rhn_cp_pid_fk
                        REFERENCES rhnPackage (id),
    created     TIMESTAMPTZ
                    DEFAULT (current_timestamp) NOT NULL,
    modified    TIMESTAMPTZ
                    DEFAULT (current_timestamp) NOT NULL
)

;

CREATE UNIQUE INDEX rhn_cp_cp_uq
    ON rhnChannelPackage (channel_id, package_id)
    ;

CREATE INDEX rhn_cp_pid_idx
    ON rhnChannelPackage (package_id)
    
    ;

   0707010000009C000081B400000000000000000000000167AE111400000583000000000000000000000000000000000000004100000000susemanager-schema/common/tables/rhnChannelPackageArchCompat.sql  --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnChannelPackageArchCompat
(
    channel_arch_id  NUMERIC NOT NULL
                         CONSTRAINT rhn_cp_ac_caid_fk
                             REFERENCES rhnChannelArch (id),
    package_arch_id  NUMERIC NOT NULL
                         CONSTRAINT rhn_cp_ac_paid_fk
                             REFERENCES rhnPackageArch (id),
    created          TIMESTAMPTZ
                         DEFAULT (current_timestamp) NOT NULL,
    modified         TIMESTAMPTZ
                         DEFAULT (current_timestamp) NOT NULL
)

;

CREATE INDEX rhn_cp_ac_caid_paid
    ON rhnChannelPackageArchCompat (channel_arch_id, package_arch_id)
    ;

ALTER TABLE rhnChannelPackageArchCompat
    ADD CONSTRAINT rhn_cp_ac_caid_paid_uq UNIQUE (channel_arch_id, package_arch_id);

 0707010000009D000081B400000000000000000000000167AE1114000005AC000000000000000000000000000000000000003A00000000susemanager-schema/common/tables/rhnChannelPermission.sql --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnChannelPermission
(
    channel_id  NUMERIC NOT NULL
                    CONSTRAINT rhn_cperm_cidffk
                        REFERENCES rhnChannel (id)
                        ON DELETE CASCADE,
    user_id     NUMERIC NOT NULL
                    CONSTRAINT rhn_cperm_uid_fk
                        REFERENCES web_contact (id)
                        ON DELETE CASCADE,
    role_id     NUMERIC NOT NULL
                    CONSTRAINT rhn_cperm_rid_fk
                        REFERENCES rhnChannelPermissionRole (id),
    created     TIMESTAMPTZ
                    DEFAULT (current_timestamp) NOT NULL,
    modified    TIMESTAMPTZ
                    DEFAULT (current_timestamp) NOT NULL
)

;

CREATE UNIQUE INDEX rhn_cperm_cid_uid_rid_idx
    ON rhnChannelPermission (channel_id, user_id, role_id)
    ;

0707010000009E000081B400000000000000000000000167AE11140000050E000000000000000000000000000000000000003E00000000susemanager-schema/common/tables/rhnChannelPermissionRole.sql --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnChannelPermissionRole
(
    id           NUMERIC NOT NULL,
    label        VARCHAR(32) NOT NULL,
    description  VARCHAR(128) NOT NULL,
    created      TIMESTAMPTZ
                     DEFAULT (current_timestamp) NOT NULL,
    modified     TIMESTAMPTZ
                     DEFAULT (current_timestamp) NOT NULL
)

;

CREATE INDEX rhn_cperm_role_label_id_idx
    ON rhnChannelPermissionRole (label, id)
    ;

CREATE SEQUENCE rhn_cperm_role_id_seq;

ALTER TABLE rhnChannelPermissionRole
    ADD CONSTRAINT rhn_cperm_role_id_pk PRIMARY KEY (id)
    ;

ALTER TABLE rhnChannelPermissionRole
    ADD CONSTRAINT rhn_cperm_role_label_uq UNIQUE (label);

  0707010000009F000081B400000000000000000000000167AE11140000052F000000000000000000000000000000000000003700000000susemanager-schema/common/tables/rhnChannelProduct.sql    --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnChannelProduct
(
    id        NUMERIC NOT NULL
                  CONSTRAINT rhn_channelprod_id_pk PRIMARY KEY
                  ,
    product   VARCHAR(256) NOT NULL,
    version   VARCHAR(64) NOT NULL,
    beta      CHAR(1)
                  DEFAULT ('N') NOT NULL
                  CONSTRAINT rhn_channelprod_beta_ck
                      CHECK (beta in ('Y', 'N')),
    created   TIMESTAMPTZ
                  DEFAULT (current_timestamp) NOT NULL,
    modified  TIMESTAMPTZ
                  DEFAULT (current_timestamp) NOT NULL
)

;

CREATE UNIQUE INDEX rhn_channelprod_p_v_b_uq
    ON rhnChannelProduct (product, version, beta)
    ;

CREATE SEQUENCE rhn_channelprod_id_seq;

 070701000000A0000081B400000000000000000000000167AE11140000058A000000000000000000000000000000000000003500000000susemanager-schema/common/tables/rhnChannelTrust.sql  --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnChannelTrust
(
    channel_id    NUMERIC NOT NULL
                      CONSTRAINT rhn_channel_trust_cid_fk
                          REFERENCES rhnChannel (id)
                          ON DELETE CASCADE,
    org_trust_id  NUMERIC NOT NULL
                      CONSTRAINT rhn_channel_trust_otid_fk
                          REFERENCES web_customer (id)
                          ON DELETE CASCADE,
    created       TIMESTAMPTZ
                      DEFAULT (current_timestamp) NOT NULL,
    modified      TIMESTAMPTZ
                      DEFAULT (current_timestamp) NOT NULL
)

;

CREATE UNIQUE INDEX rhn_channel_trust_cid_uq
    ON rhnChannelTrust (channel_id, org_trust_id)
    ;

CREATE INDEX rhn_channel_trust_org_trust
    ON rhnChannelTrust (org_trust_id)
    ;

  070701000000A1000081B400000000000000000000000167AE1114000004A2000000000000000000000000000000000000003100000000susemanager-schema/common/tables/rhnChecksum.sql  --
-- Copyright (c) 2009--2010 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--
--
-- The checksum associated with a package/file/etc...

create table
rhnChecksum
(
        id              NUMERIC not null
                        constraint rhnChecksum_pk primary key,
        checksum_type_id        NUMERIC not null
                        constraint rhnChecksum_typeid_fk
                        references rhnChecksumType(id),
        checksum        VARCHAR(128) not null
)
        
;

alter table rhnChecksum add constraint rhnChecksum_chsum_uq
        unique (checksum, checksum_type_id)
        ;

CREATE SEQUENCE rhnChecksum_seq;
  070701000000A2000081B400000000000000000000000167AE1114000004C0000000000000000000000000000000000000003500000000susemanager-schema/common/tables/rhnChecksumType.sql  --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--

CREATE TABLE rhnChecksumType
(
    id           NUMERIC NOT NULL
                     CONSTRAINT rhn_checksumtype_id_pk PRIMARY KEY
                     ,
    label        VARCHAR(32) NOT NULL,
    description  VARCHAR(64) NOT NULL,
    created      TIMESTAMPTZ DEFAULT (current_timestamp) NOT NULL,
    modified     TIMESTAMPTZ DEFAULT (current_timestamp) NOT NULL
)

;

CREATE INDEX rhn_checksumtype_label_id_idx
    ON rhnChecksumType( label, id )
    ;

ALTER TABLE rhnChecksumType
    ADD CONSTRAINT rhn_checksumtype_label_uq UNIQUE (label);

CREATE SEQUENCE rhn_checksum_id_seq;

070701000000A3000081B400000000000000000000000167AE11140000056A000000000000000000000000000000000000003F00000000susemanager-schema/common/tables/rhnChildChannelArchCompat.sql    --
-- Copyright (c) 2014 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnChildChannelArchCompat
(
    parent_arch_id  NUMERIC NOT NULL
                         CONSTRAINT rhn_ccac_paid_fk
                             REFERENCES rhnChannelArch (id),
    child_arch_id  NUMERIC NOT NULL
                         CONSTRAINT rhn_ccac_caid_fk
                             REFERENCES rhnChannelArch (id),
    created          TIMESTAMPTZ
                         DEFAULT (current_timestamp) NOT NULL,
    modified         TIMESTAMPTZ
                         DEFAULT (current_timestamp) NOT NULL
)

;

CREATE INDEX rhn_ccac_paid_caid
    ON rhnChildChannelArchCompat (parent_arch_id, child_arch_id)
    ;

ALTER TABLE rhnChildChannelArchCompat
    ADD CONSTRAINT rhn_ccac_paid_caid_uq UNIQUE (parent_arch_id, child_arch_id);

  070701000000A4000081B400000000000000000000000167AE111400000558000000000000000000000000000000000000003900000000susemanager-schema/common/tables/rhnClientCapability.sql  --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnClientCapability
(
    server_id           NUMERIC NOT NULL
                            CONSTRAINT rhn_clientcap_sid_fk
                                REFERENCES rhnServer (id),
    capability_name_id  NUMERIC NOT NULL
                            CONSTRAINT rhn_clientcap_cap_nid_fk
                                REFERENCES rhnClientCapabilityName (id),
    version             VARCHAR(32) NOT NULL,
    created             TIMESTAMPTZ
                            DEFAULT (current_timestamp) NOT NULL,
    modified            TIMESTAMPTZ
                            DEFAULT (current_timestamp) NOT NULL
)

;

CREATE UNIQUE INDEX rhn_clientcap_sid_cap_uq
    ON rhnClientCapability (server_id, capability_name_id)
    ;

070701000000A5000081B400000000000000000000000167AE111400000388000000000000000000000000000000000000003D00000000susemanager-schema/common/tables/rhnClientCapabilityName.sql  --
-- Copyright (c) 2008 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnClientCapabilityName
(
    id    NUMERIC NOT NULL
              CONSTRAINT rhn_clientcapnam_id_pk PRIMARY KEY
              ,
    name  VARCHAR(32) NOT NULL
              CONSTRAINT rhn_clientcapnam_name_unq UNIQUE
)

;

CREATE SEQUENCE rhn_client_capname_id_seq;

070701000000A6000081B400000000000000000000000167AE111400000339000000000000000000000000000000000000003200000000susemanager-schema/common/tables/rhnCompsType.sql --
-- Copyright (c) 2018 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

CREATE TABLE rhnCompsType
(
  id      NUMERIC NOT NULL
              CONSTRAINT rhn_comps_type_id_pk primary key,
  label   VARCHAR(32) NOT NULL
              CONSTRAINT rhn_comps_type_type_uq UNIQUE
);
   070701000000A7000081B400000000000000000000000167AE111400000647000000000000000000000000000000000000003600000000susemanager-schema/common/tables/rhnConfigChannel.sql --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnConfigChannel
(
    id                NUMERIC NOT NULL
                          CONSTRAINT rhn_confchan_id_pk PRIMARY KEY
                          ,
    org_id            NUMERIC NOT NULL
                          CONSTRAINT rhn_confchan_oid_fk
                              REFERENCES web_customer (id),
    confchan_type_id  NUMERIC NOT NULL
                          CONSTRAINT rhn_confchan_ctid_fk
                              REFERENCES rhnConfigChannelType (id),
    name              VARCHAR(128) NOT NULL,
    label             VARCHAR(64) NOT NULL,
    description       VARCHAR(1024) NOT NULL,
    created           TIMESTAMPTZ
                          DEFAULT (current_timestamp) NOT NULL,
    modified          TIMESTAMPTZ
                          DEFAULT (current_timestamp) NOT NULL
)

;

CREATE UNIQUE INDEX rhn_confchan_oid_label_type_uq
    ON rhnConfigChannel (org_id, label, confchan_type_id)
    ;

CREATE SEQUENCE rhn_confchan_id_seq;

 070701000000A8000081B400000000000000000000000167AE11140000051E000000000000000000000000000000000000003A00000000susemanager-schema/common/tables/rhnConfigChannelType.sql --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnConfigChannelType
(
    id        NUMERIC NOT NULL
                  CONSTRAINT rhn_confchantype_id_pk PRIMARY KEY
                  ,
    label     VARCHAR(64) NOT NULL,
    name      VARCHAR(64) NOT NULL,
    priority  NUMERIC
                  DEFAULT (0) NOT NULL,
    created   TIMESTAMPTZ
                  DEFAULT (current_timestamp) NOT NULL,
    modified  TIMESTAMPTZ
                  DEFAULT (current_timestamp) NOT NULL
)

;

CREATE INDEX rhn_confchantype_label_id_idx
    ON rhnConfigChannelType (label, id)
    ;

CREATE SEQUENCE rhn_confchantype_id_seq;

ALTER TABLE rhnConfigChannelType
    ADD CONSTRAINT rhn_confchantype_label_uq UNIQUE (label);

  070701000000A9000081B400000000000000000000000167AE1114000005A2000000000000000000000000000000000000003600000000susemanager-schema/common/tables/rhnConfigContent.sql --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnConfigContent
(
    id         NUMERIC NOT NULL
                   CONSTRAINT rhn_confcontent_id_pk PRIMARY KEY
                   ,
    contents   BYTEA,
    file_size  NUMERIC,
    checksum_id NUMERIC NOT NULL
                  CONSTRAINT rhn_confcontent_chsum_fk
                  REFERENCES rhnChecksum (id),
    is_binary  CHAR(1)
                   DEFAULT ('N') NOT NULL
                   CONSTRAINT rhn_confcontent_isbin_ck
                       CHECK (is_binary in ('Y','N')),
    delim_start          VARCHAR(16) NOT NULL,
    delim_end            VARCHAR(16) NOT NULL,
    created    TIMESTAMPTZ
                   DEFAULT (current_timestamp) NOT NULL,
    modified   TIMESTAMPTZ
                   DEFAULT (current_timestamp) NOT NULL
)


;

CREATE SEQUENCE rhn_confcontent_id_seq;

  070701000000AA000081B400000000000000000000000167AE1114000007F0000000000000000000000000000000000000003300000000susemanager-schema/common/tables/rhnConfigFile.sql    --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnConfigFile
(
    id                         NUMERIC NOT NULL
                                   CONSTRAINT rhn_conffile_id_pk PRIMARY KEY
                                   ,
    config_channel_id          NUMERIC NOT NULL
                                   CONSTRAINT rhn_conffile_ccid_fk
                                       REFERENCES rhnConfigChannel (id),
    config_file_name_id        NUMERIC NOT NULL
                                   CONSTRAINT rhn_conffile_cfnid_fk
                                       REFERENCES rhnConfigFileName (id),
    latest_config_revision_id  NUMERIC,
    state_id                   NUMERIC NOT NULL
                                   CONSTRAINT rhn_conffile_sid_fk
                                       REFERENCES rhnConfigFileState (id),
    created                    TIMESTAMPTZ
                                   DEFAULT (current_timestamp) NOT NULL,
    modified                   TIMESTAMPTZ
                                   DEFAULT (current_timestamp) NOT NULL
)

;

CREATE INDEX rhn_conffile_cc_cfn_s_idx
    ON rhnConfigFile (config_channel_id, config_file_name_id, state_id)
    ;

CREATE INDEX rhn_cnf_fl_lcrid_idx
    ON rhnConfigFile (latest_config_revision_id)
    ;

CREATE SEQUENCE rhn_conffile_id_seq;

ALTER TABLE rhnConfigFile
    ADD CONSTRAINT rhn_conffile_ccid_cfnid_uq UNIQUE (config_channel_id, config_file_name_id);

070701000000AB000081B400000000000000000000000167AE1114000004D0000000000000000000000000000000000000003A00000000susemanager-schema/common/tables/rhnConfigFileFailure.sql --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnConfigFileFailure
(
    id        NUMERIC NOT NULL
                  CONSTRAINT rhn_conffile_fail_id_pk PRIMARY KEY
                  ,
    label     VARCHAR(64) NOT NULL
                  CONSTRAINT rhn_conffile_fail_label_uq UNIQUE
                  ,
    name      VARCHAR(256) NOT NULL
                  CONSTRAINT rhn_conffile_fail_name_uq UNIQUE
                  ,
    created   TIMESTAMPTZ
                  DEFAULT (current_timestamp) NOT NULL,
    modified  TIMESTAMPTZ
                  DEFAULT (current_timestamp) NOT NULL
)

;

CREATE SEQUENCE rhn_conffile_failure_id_seq;

070701000000AC000081B400000000000000000000000167AE111400000451000000000000000000000000000000000000003700000000susemanager-schema/common/tables/rhnConfigFileName.sql    --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnConfigFileName
(
    id        NUMERIC NOT NULL,
    path      VARCHAR(1024) NOT NULL,
    created   TIMESTAMPTZ
                  DEFAULT (current_timestamp) NOT NULL,
    modified  TIMESTAMPTZ
                  DEFAULT (current_timestamp) NOT NULL
)

;

CREATE UNIQUE INDEX rhn_cfname_path_uq
    ON rhnConfigFileName (path)
    ;

CREATE SEQUENCE rhn_cfname_id_seq;

ALTER TABLE rhnConfigFileName
    ADD CONSTRAINT rhn_cfname_id_pk PRIMARY KEY (id)
    ;

   070701000000AD000081B400000000000000000000000167AE111400000475000000000000000000000000000000000000003800000000susemanager-schema/common/tables/rhnConfigFileState.sql   --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnConfigFileState
(
    id        NUMERIC NOT NULL
                  CONSTRAINT rhn_cfstate_id_pk PRIMARY KEY
                  ,
    label     VARCHAR(32) NOT NULL,
    name      VARCHAR(256) NOT NULL,
    created   TIMESTAMPTZ
                  DEFAULT (current_timestamp) NOT NULL,
    modified  TIMESTAMPTZ
                  DEFAULT (current_timestamp) NOT NULL
)

;

CREATE UNIQUE INDEX rhn_cfstate_label_id_uq
    ON rhnConfigFileState (label, id)
    ;

CREATE SEQUENCE rhn_cfstate_id_seq;

   070701000000AE000081B400000000000000000000000167AE1114000003FB000000000000000000000000000000000000003700000000susemanager-schema/common/tables/rhnConfigFileType.sql    --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnConfigFileType
(
    id        NUMERIC NOT NULL
                  CONSTRAINT rhn_conffiletype_id_pk PRIMARY KEY
                  ,
    label     VARCHAR(64) NOT NULL,
    name      VARCHAR(256) NOT NULL,
    created   TIMESTAMPTZ
                  DEFAULT (current_timestamp) NOT NULL,
    modified  TIMESTAMPTZ
                  DEFAULT (current_timestamp) NOT NULL
)

;

 070701000000AF000081B400000000000000000000000167AE11140000031D000000000000000000000000000000000000003F00000000susemanager-schema/common/tables/rhnConfigFile_foreignkeys.sql    --
-- Copyright (c) 2008 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


ALTER TABLE rhnConfigFile
    ADD CONSTRAINT rhn_conffile_lcrid_fk FOREIGN KEY (latest_config_revision_id)
    REFERENCES rhnConfigRevision (id)
        ON DELETE SET NULL;

   070701000000B0000081B400000000000000000000000167AE1114000004F2000000000000000000000000000000000000003300000000susemanager-schema/common/tables/rhnConfigInfo.sql    --
-- Copyright (c) 2008--2017 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnConfigInfo
(
    id           NUMERIC NOT NULL
                     CONSTRAINT rhn_confinfo_id_pk PRIMARY KEY
                     ,
    username     VARCHAR(32),
    groupname    VARCHAR(32),
    filemode     NUMERIC,
    symlink_target_filename_id NUMERIC
                    CONSTRAINT rhn_confinfo_symlink_fk
                        REFERENCES rhnConfigFileName (id),
    created      TIMESTAMPTZ
                     DEFAULT (current_timestamp) NOT NULL,
    modified     TIMESTAMPTZ
                     DEFAULT (current_timestamp) NOT NULL,
    selinux_ctx  VARCHAR(64)
)

;

CREATE SEQUENCE rhn_confinfo_id_seq;

  070701000000B1000081B400000000000000000000000167AE1114000008B6000000000000000000000000000000000000003700000000susemanager-schema/common/tables/rhnConfigRevision.sql    --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnConfigRevision
(
    id                   NUMERIC NOT NULL
                             CONSTRAINT rhn_confrevision_id_pk PRIMARY KEY
                             ,
    revision             NUMERIC NOT NULL,
    config_file_id       NUMERIC NOT NULL
                             CONSTRAINT rhn_confrevision_cfid_fk
                                 REFERENCES rhnConfigFile (id),
    config_content_id    NUMERIC 
                             CONSTRAINT rhn_confrevision_ccid_fk
                                 REFERENCES rhnConfigContent (id),
    config_info_id       NUMERIC NOT NULL
                             CONSTRAINT rhn_confrevision_ciid_fk
                                 REFERENCES rhnConfigInfo (id),
    created              TIMESTAMPTZ
                             DEFAULT (current_timestamp) NOT NULL,
    modified             TIMESTAMPTZ
                             DEFAULT (current_timestamp) NOT NULL,
    config_file_type_id  NUMERIC
                             DEFAULT (1) NOT NULL
                             CONSTRAINT rhn_conf_rev_cfti_fk
                                 REFERENCES rhnConfigFileType (id),
    changed_by_id        NUMERIC
                             DEFAULT (null)
                             CONSTRAINT rhn_confrevision_cid_fk
                                 REFERENCES web_contact (id)
)

;

CREATE UNIQUE INDEX rhn_confrevision_cfid_rev_uq
    ON rhnConfigRevision (config_file_id, revision)
    ;

CREATE INDEX rhn_confrevision_ccid_idx
    ON rhnConfigRevision (config_content_id)
    ;

CREATE SEQUENCE rhn_confrevision_id_seq;

  070701000000B2000081B400000000000000000000000167AE11140000046F000000000000000000000000000000000000003600000000susemanager-schema/common/tables/rhnConfiguration.sql --
-- Copyright (c) 2014 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

CREATE TABLE rhnConfiguration
(
    key                     VARCHAR(64) NOT NULL
                                CONSTRAINT rhnConfig_key_pk PRIMARY KEY,
    description             VARCHAR(512) NOT NULL,
    value                   VARCHAR(512),
    default_value           VARCHAR(512),
    created                 TIMESTAMPTZ
                                DEFAULT (current_timestamp) NOT NULL,
    modified                TIMESTAMPTZ
                                DEFAULT (current_timestamp) NOT NULL
)

;
 070701000000B3000081B400000000000000000000000167AE111400000714000000000000000000000000000000000000003600000000susemanager-schema/common/tables/rhnContentSource.sql --
-- Copyright (c) 2008--2017 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--
--
--
--

create table
rhnContentSource
(
        id		NUMERIC NOT NULL
			constraint rhn_cs_id_pk primary key,
        org_id		NUMERIC
			constraint rhn_cs_org_fk
                                references web_customer (id),
        type_id         NUMERIC NOT NULL
                        constraint rhn_cs_type_fk
                                references rhnContentSourceType(id),
        source_url      VARCHAR(2048) NOT NULL,
        label           VARCHAR(128) NOT NULL,
        metadata_signed CHAR(1)
                            DEFAULT ('Y') NOT NULL
                            CONSTRAINT rhn_cs_ms_ck
                                CHECK (metadata_signed in ( 'Y' , 'N' )),
        created         TIMESTAMPTZ default(current_timestamp) NOT NULL,
        modified        TIMESTAMPTZ default(current_timestamp) NOT NULL
)

  ;


create sequence rhn_chan_content_src_id_seq start with 500;

CREATE UNIQUE INDEX rhn_cs_label_uq
    ON rhnContentSource(COALESCE(org_id, 0), label)
    ;
CREATE UNIQUE INDEX rhn_cs_repo_uq
    ON rhnContentSource(COALESCE(org_id, 0), type_id, source_url,
                        (case when label like 'manifest_%' then 1 else 0 end))
    ;

070701000000B4000081B400000000000000000000000167AE111400000559000000000000000000000000000000000000003C00000000susemanager-schema/common/tables/rhnContentSourceFilter.sql   --
-- Copyright (c) 2008--2017 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--
--
--
--

create table
rhnContentSourceFilter
(
        id		NUMERIC NOT NULL
			constraint rhn_csf_id_pk primary key,
        source_id		NUMERIC
			constraint rhn_csf_source_fk
                                references rhnContentSource (id) on delete cascade,
        sort_order	NUMERIC NOT NULL,
        flag            VARCHAR(1) NOT NULL
                        check (flag in ('+','-')),
        filter          VARCHAR(4000) NOT NULL,
        created         TIMESTAMPTZ default(current_timestamp) NOT NULL,
        modified        TIMESTAMPTZ default(current_timestamp) NOT NULL
)

  ;


create sequence rhn_csf_id_seq start with 500;

CREATE UNIQUE INDEX rhn_csf_sid_so_uq
    ON rhnContentSourceFilter (source_id, sort_order)
    ;

   070701000000B5000081B400000000000000000000000167AE111400000583000000000000000000000000000000000000003900000000susemanager-schema/common/tables/rhnContentSourceSsl.sql  --
-- Copyright (c) 2017 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnContentSourceSsl
(
	content_source_id NUMERIC not null
		constraint rhn_csssl_csid_fk references rhnContentSource(id) on delete cascade,
	ssl_ca_cert_id NUMERIC not null
		constraint rhn_csssl_cacertid_fk references rhnCryptoKey(id) on delete cascade,
	ssl_client_cert_id NUMERIC
		constraint rhn_csssl_clcertid_fk references rhnCryptoKey(id) on delete cascade,
	ssl_client_key_id NUMERIC
		constraint rhn_csssl_clkeyid_fk references rhnCryptoKey(id) on delete cascade,
	constraint rhn_csssl_client_chk check(ssl_client_key_id is null or ssl_client_cert_id is not null),
	created TIMESTAMPTZ default(current_timestamp) not null,
	modified TIMESTAMPTZ default(current_timestamp) not null
)

;

CREATE INDEX rhn_csssl_cs
    ON rhnContentSourceSsl (content_source_id)
    ;
 070701000000B6000081B400000000000000000000000167AE11140000040E000000000000000000000000000000000000003A00000000susemanager-schema/common/tables/rhnContentSourceType.sql --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--

create table
rhnContentSourceType
(
	id		NUMERIC NOT NULL
                        constraint rhn_cst_id_pk primary key,
	label		VARCHAR(32) NOT NULL
                        constraint rhn_cst_label_uq unique,
	created		TIMESTAMPTZ default(current_timestamp) NOT NULL,
	modified	TIMESTAMPTZ default(current_timestamp) NOT NULL
) 

  ;

create sequence rhn_content_source_type_id_seq start with 500;

  070701000000B7000081B400000000000000000000000167AE1114000007A6000000000000000000000000000000000000002C00000000susemanager-schema/common/tables/rhnCpu.sql   --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnCpu
(
    id           NUMERIC NOT NULL
                     CONSTRAINT rhn_cpu_id_pk PRIMARY KEY
                     ,
    server_id    NUMERIC NOT NULL
                     CONSTRAINT rhn_cpu_server_fk
                         REFERENCES rhnServer (id),
    cpu_arch_id  NUMERIC NOT NULL
                     CONSTRAINT rhn_cpu_caid_fk
                         REFERENCES rhnCpuArch (id),
    bogomips     VARCHAR(16),
    cache        VARCHAR(16),
    family       VARCHAR(32),
    MHz          VARCHAR(16),
    stepping     VARCHAR(16),
    flags        VARCHAR(2048),
    model        VARCHAR(64),
    version      VARCHAR(32),
    vendor       VARCHAR(32),
    nrcpu        NUMERIC
                     DEFAULT (1),
    nrsocket     NUMERIC
                     DEFAULT (1),
    nrcore       NUMERIC
                     DEFAULT (1),
    nrthread     NUMERIC
                     DEFAULT (1),
    acpiVersion  VARCHAR(64),
    apic         VARCHAR(32),
    apmVersion   VARCHAR(32),
    chipset      VARCHAR(64),
    created      TIMESTAMPTZ
                     DEFAULT (current_timestamp) NOT NULL,
    modified     TIMESTAMPTZ
                     DEFAULT (current_timestamp) NOT NULL
)

;

CREATE UNIQUE INDEX rhn_cpu_server_id_uq
    ON rhnCpu (server_id)
    
    ;

CREATE SEQUENCE rhn_cpu_id_seq;

  070701000000B8000081B400000000000000000000000167AE11140000057B000000000000000000000000000000000000002D00000000susemanager-schema/common/tables/rhnFile.sql  --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnFile
(
    id         NUMERIC NOT NULL
                   CONSTRAINT rhn_file_id_pk PRIMARY KEY
                   ,
    org_id     NUMERIC
                   CONSTRAINT rhn_file_oid_fk
                       REFERENCES web_customer (id)
                       ON DELETE CASCADE,
    file_size  NUMERIC NOT NULL,
    checksum_id NUMERIC NOT NULL
                   CONSTRAINT rhn_file_chsum_fk
                       REFERENCES rhnChecksum (id),
    path       VARCHAR(1000) NOT NULL,
    created    TIMESTAMPTZ
                   DEFAULT (current_timestamp) NOT NULL,
    modified   TIMESTAMPTZ
                   DEFAULT (current_timestamp) NOT NULL
)

;

CREATE UNIQUE INDEX rhn_file_path_uq
    ON rhnFile (path)
    ;

CREATE SEQUENCE rhn_file_id_seq;

 070701000000B9000081B400000000000000000000000167AE1114000004C8000000000000000000000000000000000000003000000000susemanager-schema/common/tables/rhnCpuArch.sql   --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnCpuArch
(
    id        NUMERIC NOT NULL,
    label     VARCHAR(64) NOT NULL,
    name      VARCHAR(64) NOT NULL,
    created   TIMESTAMPTZ
                  DEFAULT (current_timestamp) NOT NULL,
    modified  TIMESTAMPTZ
                  DEFAULT (current_timestamp) NOT NULL
)

;

CREATE INDEX rhn_cpuarch_id_l_n_idx
    ON rhnCpuArch (id, label, name)
    ;

CREATE SEQUENCE rhn_cpu_arch_id_seq START WITH 200;

ALTER TABLE rhnCpuArch
    ADD CONSTRAINT rhn_cpuarch_id_pk PRIMARY KEY (id);

ALTER TABLE rhnCpuArch
    ADD CONSTRAINT rhn_cpuarch_label_uq UNIQUE (label)
    ;

070701000000BA000081B400000000000000000000000167AE111400000568000000000000000000000000000000000000003200000000susemanager-schema/common/tables/rhnCryptoKey.sql --
-- Copyright (c) 2008 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnCryptoKey
(
    id                  NUMERIC NOT NULL
                            CONSTRAINT rhn_cryptokey_id_pk PRIMARY KEY
                            ,
    org_id              NUMERIC
                            CONSTRAINT rhn_cryptokey_oid_fk
                                REFERENCES web_customer (id)
                                ON DELETE CASCADE,
    description         VARCHAR(1024) NOT NULL,
    crypto_key_type_id  NUMERIC NOT NULL
                            CONSTRAINT rhn_cryptokey_cktid_fk
                                REFERENCES rhnCryptoKeyType (id),
    key                 BYTEA
)

;

CREATE UNIQUE INDEX rhn_cryptokey_oid_desc_uq
    ON rhnCryptoKey (org_id, description)
    ;

CREATE SEQUENCE rhn_cryptokey_id_seq;

070701000000BB000081B400000000000000000000000167AE1114000004CA000000000000000000000000000000000000003B00000000susemanager-schema/common/tables/rhnCryptoKeyKickstart.sql    --
-- Copyright (c) 2008--2010 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnCryptoKeyKickstart
(
    crypto_key_id  NUMERIC NOT NULL
                       CONSTRAINT rhn_ckey_ks_ckid_fk
                           REFERENCES rhnCryptoKey (id)
                           ON DELETE CASCADE,
    ksdata_id      NUMERIC NOT NULL
                       CONSTRAINT rhn_ckey_ks_ksd_fk
                           REFERENCES rhnKSData (id)
                           ON DELETE CASCADE
)

;

CREATE UNIQUE INDEX rhn_ckey_ks_uq
    ON rhnCryptoKeyKickstart (crypto_key_id, ksdata_id)
    ;

CREATE INDEX rhn_ckey_ks_idx
    ON rhnCryptoKeyKickstart (ksdata_id)
    ;

  070701000000BC000081B400000000000000000000000167AE1114000004F4000000000000000000000000000000000000003600000000susemanager-schema/common/tables/rhnCryptoKeyType.sql --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnCryptoKeyType
(
    id           NUMERIC NOT NULL
                     CONSTRAINT rhn_cryptokeytype_id_pk PRIMARY KEY
                     ,
    label        VARCHAR(32) NOT NULL,
    description  VARCHAR(256) NOT NULL,
    created      TIMESTAMPTZ
                     DEFAULT (current_timestamp) NOT NULL,
    modified     TIMESTAMPTZ
                     DEFAULT (current_timestamp) NOT NULL
)

;

CREATE INDEX rhn_cryptokeytype_label_id_idx
    ON rhnCryptoKeyType (label, id)
    ;

CREATE SEQUENCE rhn_cryptokeytype_id_seq;

ALTER TABLE rhnCryptoKeyType
    ADD CONSTRAINT rhn_cryptokeytype_label_uq UNIQUE (label);

070701000000BD000081B400000000000000000000000167AE111400000759000000000000000000000000000000000000003600000000susemanager-schema/common/tables/rhnCustomDataKey.sql --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnCustomDataKey
(
    id                NUMERIC NOT NULL
                          CONSTRAINT rhn_cdatakey_pk PRIMARY KEY,
    org_id            NUMERIC NOT NULL
                          CONSTRAINT rhn_cdatakey_oid_fk
                              REFERENCES web_customer (id)
                              ON DELETE CASCADE,
    label             VARCHAR(64) NOT NULL,
    description       VARCHAR(4000) NOT NULL,
    created_by        NUMERIC
                          CONSTRAINT rhn_cdatakey_cb_fk
                              REFERENCES web_contact (id)
                              ON DELETE SET NULL,
    last_modified_by  NUMERIC
                          CONSTRAINT rhn_cdatakey_lmb_fk
                              REFERENCES web_contact (id)
                              ON DELETE SET NULL,
    created           TIMESTAMPTZ
                          DEFAULT (current_timestamp) NOT NULL,
    modified          TIMESTAMPTZ
                          DEFAULT (current_timestamp) NOT NULL
)

;

CREATE INDEX rhn_cdatakey_oid_label_id_idx
    ON rhnCustomDataKey (org_id, label, id)
    ;

CREATE SEQUENCE rhn_cdatakey_id_seq;

ALTER TABLE rhnCustomDataKey
    ADD CONSTRAINT rhn_cdatakey_oid_label_uq UNIQUE (org_id, label);

   070701000000BE000081B400000000000000000000000167AE11140000046B000000000000000000000000000000000000003A00000000susemanager-schema/common/tables/rhnDailySummaryQueue.sql --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnDailySummaryQueue
(
    org_id    NUMERIC NOT NULL
                  CONSTRAINT rhn_dsqueue_oid_fk
                      REFERENCES web_customer (id),
    created   TIMESTAMPTZ
                  DEFAULT (current_timestamp) NOT NULL,
    modified  TIMESTAMPTZ
                  DEFAULT (current_timestamp) NOT NULL
)

;

CREATE INDEX rhn_dsqueue_oid_idx
    ON rhnDailySummaryQueue (org_id)
    ;

ALTER TABLE rhnDailySummaryQueue
    ADD CONSTRAINT rhn_dsqueue_oid_uq UNIQUE (org_id);

 070701000000BF000081B400000000000000000000000167AE11140000064A000000000000000000000000000000000000002F00000000susemanager-schema/common/tables/rhnDevice.sql    --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnDevice
(
    id           NUMERIC NOT NULL
                     CONSTRAINT rhn_device_id_pk PRIMARY KEY
                     ,
    server_id    NUMERIC NOT NULL
                     CONSTRAINT rhn_device_sid_fk
                         REFERENCES rhnServer (id)
                         ON DELETE CASCADE,
    class        VARCHAR(16),
    bus          VARCHAR(16),
    detached     NUMERIC,
    device       VARCHAR(256),
    driver       VARCHAR(256),
    description  VARCHAR(256),
    pcitype      NUMERIC
                     DEFAULT (-1),
    prop1        VARCHAR(256),
    prop2        VARCHAR(256),
    prop3        VARCHAR(256),
    prop4        VARCHAR(256),
    created      TIMESTAMPTZ
                     DEFAULT (current_timestamp) NOT NULL,
    modified     TIMESTAMPTZ
                     DEFAULT (current_timestamp) NOT NULL
)

;

CREATE INDEX rhn_device_server_id_idx
    ON rhnDevice (server_id)
    
    ;

CREATE SEQUENCE rhn_hw_dev_id_seq;

  070701000000C0000081B400000000000000000000000167AE111400000585000000000000000000000000000000000000003700000000susemanager-schema/common/tables/rhnDistChannelMap.sql    --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnDistChannelMap
(
    id               NUMERIC NOT NULL
                        CONSTRAINT rhn_dcm_id_pk PRIMARY KEY,
    os               VARCHAR(64) NOT NULL,
    release          VARCHAR(64) NOT NULL,
    channel_arch_id  NUMERIC NOT NULL
                         CONSTRAINT rhn_dcm_caid_fk
                             REFERENCES rhnChannelArch (id),
    channel_id       NUMERIC NOT NULL
                         CONSTRAINT rhn_dcm_cid_fk
                             REFERENCES rhnChannel (id)
                             ON DELETE CASCADE,
    org_id           NUMERIC
                        CONSTRAINT rhn_dcm_oid_fk
                            REFERENCES web_customer (id)
                            ON DELETE CASCADE
)

;

CREATE SEQUENCE rhn_dcm_id_seq;

   070701000000C1000081B400000000000000000000000167AE111400000C69000000000000000000000000000000000000002F00000000susemanager-schema/common/tables/rhnErrata.sql    --
-- Copyright (c) 2008--2017 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnErrata
(
    id                NUMERIC NOT NULL
                          CONSTRAINT rhn_errata_id_pk PRIMARY KEY
                          ,
    advisory          VARCHAR(100) NOT NULL,
    advisory_type     VARCHAR(32) NOT NULL
                          CONSTRAINT rhn_errata_adv_type_ck
                              CHECK (advisory_type in ('Bug Fix Advisory',
                                                       'Product Enhancement Advisory',
                                                       'Security Advisory')),
    advisory_name     VARCHAR(100) NOT NULL,
    advisory_rel      NUMERIC NOT NULL,
    advisory_status   VARCHAR(32) NOT NULL DEFAULT('final')
                          CONSTRAINT rhn_errata_adv_status_ck
                              CHECK (advisory_status in ('final', 'stable', 'testing',
                                                         'pending', 'retracted')),
    product           VARCHAR(64) NOT NULL,
    description       VARCHAR(4000),
    synopsis          VARCHAR(4000) NOT NULL,
    topic             VARCHAR(4000),
    solution          VARCHAR(4000) NOT NULL,
    rights            VARCHAR(100),
    issue_date        TIMESTAMPTZ
                          DEFAULT (current_timestamp) NOT NULL,
    update_date       TIMESTAMPTZ
                          DEFAULT (current_timestamp) NOT NULL,
    refers_to         VARCHAR(4000),
    notes             VARCHAR(4000),
    org_id            NUMERIC
                          CONSTRAINT rhn_errata_oid_fk
                              REFERENCES web_customer (id)
                              ON DELETE CASCADE,
    locally_modified  CHAR(1)
                          CONSTRAINT rhn_errata_lm_ck
                              CHECK (locally_modified in ('Y','N')),
    errata_from       VARCHAR(127),
    created           TIMESTAMPTZ
                          DEFAULT (current_timestamp) NOT NULL,
    modified          TIMESTAMPTZ
                          DEFAULT (current_timestamp) NOT NULL,
    last_modified     TIMESTAMPTZ
                          DEFAULT (current_timestamp) NOT NULL,
    severity_id       NUMERIC
                          CONSTRAINT rhn_errata_sevid_fk
                              REFERENCES rhnErrataSeverity (id)
)

;

-- unique index definitions has been moved to
-- {oracle,postgres}/tables/rhnErrata_index.sql

CREATE INDEX rhn_errata_udate_index
    ON rhnErrata (update_date)
    ;

CREATE INDEX rhn_errata_syn_index
    ON rhnErrata ( synopsis )
    ;

CREATE SEQUENCE rhn_errata_id_seq;

   070701000000C2000081B400000000000000000000000167AE1114000004AF000000000000000000000000000000000000003600000000susemanager-schema/common/tables/rhnErrataBuglist.sql --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnErrataBuglist
(
    errata_id  NUMERIC NOT NULL
                   CONSTRAINT rhn_errata_buglist_errata_fk
                       REFERENCES rhnErrata (id)
                       ON DELETE CASCADE,
    bug_id     NUMERIC NOT NULL,
    summary    VARCHAR(4000),
    href       VARCHAR(255),
    created    TIMESTAMPTZ
                   DEFAULT (current_timestamp) NOT NULL,
    modified   TIMESTAMPTZ
                   DEFAULT (current_timestamp) NOT NULL
)

;

CREATE UNIQUE INDEX rhn_err_bug_list_uq
    ON rhnErrataBuglist (errata_Id, bug_Id)
    ;

 070701000000C3000081B400000000000000000000000167AE11140000050E000000000000000000000000000000000000003200000000susemanager-schema/common/tables/rhnErrataCVE.sql --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnErrataCVE
(
    errata_id  NUMERIC NOT NULL
                   CONSTRAINT rhn_err_cve_eid_fk
                       REFERENCES rhnErrata (id)
                       ON DELETE CASCADE,
    cve_id     NUMERIC NOT NULL
                   CONSTRAINT rhn_err_cve_cid_fk
                       REFERENCES rhnCVE (id),
    created    TIMESTAMPTZ
                   DEFAULT (current_timestamp) NOT NULL,
    modified   TIMESTAMPTZ
                   DEFAULT (current_timestamp) NOT NULL
)

;

CREATE UNIQUE INDEX rhn_err_cve_eid_cid_uq
    ON rhnErrataCVE (errata_id, cve_id)
    ;

CREATE INDEX rhn_err_cve_cid_idx
    ON rhnErrataCVE (cve_id)
    
    ;

  070701000000C4000081B400000000000000000000000167AE1114000005D5000000000000000000000000000000000000003500000000susemanager-schema/common/tables/rhnErrataCloned.sql  --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnErrataCloned
(
    original_id  NUMERIC NOT NULL
                     CONSTRAINT rhn_errataclone_feid_fk
                         REFERENCES rhnErrata (id)
                         ON DELETE CASCADE,
    id           NUMERIC NOT NULL
                     CONSTRAINT rhn_errataclone_teid_fk
                         REFERENCES rhnErrata (id)
                         ON DELETE CASCADE,
    created      TIMESTAMPTZ
                     DEFAULT (current_timestamp) NOT NULL,
    modified     TIMESTAMPTZ
                     DEFAULT (current_timestamp) NOT NULL
)

;

CREATE INDEX rhn_errataclone_feid_teid_idx
    ON rhnErrataCloned (original_id, id)
    ;

ALTER TABLE rhnErrataCloned
    ADD CONSTRAINT rhn_errataclone_feid_teid_uq UNIQUE (original_id, id);

ALTER TABLE rhnErrataCloned
    ADD CONSTRAINT rhn_errataclone_id_pk PRIMARY KEY (id);

   070701000000C5000081B400000000000000000000000167AE1114000006D6000000000000000000000000000000000000003300000000susemanager-schema/common/tables/rhnErrataFile.sql    --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnErrataFile
(
    id         NUMERIC NOT NULL,
    errata_id  NUMERIC NOT NULL
                   CONSTRAINT rhn_erratafile_errata_fk
                       REFERENCES rhnErrata (id)
                       ON DELETE CASCADE,
    type       NUMERIC NOT NULL
                   CONSTRAINT rhn_erratafile_type_fk
                       REFERENCES rhnErrataFileType (id),
    checksum_id NUMERIC NOT NULL
                   CONSTRAINT rhn_erratafile_chsum_fk
                       REFERENCES rhnChecksum (id),
    filename   VARCHAR(4000) NOT NULL,
    created    TIMESTAMPTZ
                   DEFAULT (current_timestamp) NOT NULL,
    modified   TIMESTAMPTZ
                   DEFAULT (current_timestamp) NOT NULL
)

;

CREATE INDEX rhn_erratafile_id_idx
    ON rhnErrataFile (id)
    ;

CREATE INDEX rhn_erratafile_eid_file_idx
    ON rhnErrataFile (errata_id, filename)
    ;

CREATE SEQUENCE rhn_erratafile_id_seq;

ALTER TABLE rhnErrataFile
    ADD CONSTRAINT rhn_erratafile_id_pk PRIMARY KEY (id);

ALTER TABLE rhnErrataFile
    ADD CONSTRAINT rhn_erratafile_eid_file_uq UNIQUE (errata_id, filename);

  070701000000C6000081B400000000000000000000000167AE111400000603000000000000000000000000000000000000003A00000000susemanager-schema/common/tables/rhnErrataFileChannel.sql --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnErrataFileChannel
(
    channel_id      NUMERIC NOT NULL
                        CONSTRAINT rhn_efilec_cid_fk
                            REFERENCES rhnChannel (id)
                            ON DELETE CASCADE,
    errata_file_id  NUMERIC NOT NULL
                        CONSTRAINT rhn_efilec_eid_fk
                            REFERENCES rhnErrataFile (id)
                            ON DELETE CASCADE,
    created         TIMESTAMPTZ
                        DEFAULT (current_timestamp) NOT NULL,
    modified        TIMESTAMPTZ
                        DEFAULT (current_timestamp) NOT NULL
)

;

CREATE INDEX rhn_efilec_efid_cid_idx
    ON rhnErrataFileChannel (errata_file_id, channel_id)
    ;

CREATE INDEX rhn_efilec_cid_idx
    ON rhnErrataFileChannel (channel_id)
    ;

ALTER TABLE rhnErrataFileChannel
    ADD CONSTRAINT rhn_efilec_efid_cid_uq UNIQUE (errata_file_id, channel_id);

 070701000000C7000081B400000000000000000000000167AE1114000005F6000000000000000000000000000000000000003A00000000susemanager-schema/common/tables/rhnErrataFilePackage.sql --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnErrataFilePackage
(
    package_id      NUMERIC NOT NULL
                        CONSTRAINT rhn_efilep_pid_fk
                            REFERENCES rhnPackage (id)
                            ON DELETE CASCADE,
    errata_file_id  NUMERIC NOT NULL
                        CONSTRAINT rhn_efilep_fileid_fk
                            REFERENCES rhnErrataFile (id)
                            ON DELETE CASCADE,
    created         TIMESTAMPTZ
                        DEFAULT (current_timestamp) NOT NULL,
    modified        TIMESTAMPTZ
                        DEFAULT (current_timestamp) NOT NULL
)

;

CREATE INDEX rhn_efilep_efid_pid_idx
    ON rhnErrataFilePackage (errata_file_id, package_id)
    ;

CREATE INDEX rhn_efilep_pid_idx
    ON rhnErrataFilePackage (package_id)
    ;

ALTER TABLE rhnErrataFilePackage
    ADD CONSTRAINT rhn_efilep_efid_uq UNIQUE (errata_file_id);

  070701000000C8000081B400000000000000000000000167AE1114000005C2000000000000000000000000000000000000004000000000susemanager-schema/common/tables/rhnErrataFilePackageSource.sql   --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnErrataFilePackageSource
(
    package_id      NUMERIC NOT NULL
                        CONSTRAINT rhn_efileps_pid_fk
                            REFERENCES rhnPackageSource (id)
                            ON DELETE CASCADE,
    errata_file_id  NUMERIC NOT NULL
                        CONSTRAINT rhn_efileps_fileid_fk
                            REFERENCES rhnErrataFile (id)
                            ON DELETE CASCADE,
    created         TIMESTAMPTZ
                        DEFAULT (current_timestamp) NOT NULL,
    modified        TIMESTAMPTZ
                        DEFAULT (current_timestamp) NOT NULL
)

;

CREATE INDEX rhn_efileps_efid_pid_idx
    ON rhnErrataFilePackageSource (errata_file_id, package_id)
    ;

ALTER TABLE rhnErrataFilePackageSource
    ADD CONSTRAINT rhn_efileps_efid_uq UNIQUE (errata_file_id);

  070701000000C9000081B400000000000000000000000167AE11140000045E000000000000000000000000000000000000003700000000susemanager-schema/common/tables/rhnErrataFileType.sql    --
-- Copyright (c) 2008 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnErrataFileType
(
    id     NUMERIC NOT NULL,
    label  VARCHAR(128) NOT NULL
)

;

CREATE INDEX rhn_erratafile_type_id_idx
    ON rhnErrataFileType (id)
    ;

CREATE INDEX rhn_erratafile_type_label_idx
    ON rhnErrataFileType (label)
    ;

CREATE SEQUENCE rhn_erratafile_type_id_seq;

ALTER TABLE rhnErrataFileType
    ADD CONSTRAINT rhn_erratafile_type_id_pk PRIMARY KEY (id);

ALTER TABLE rhnErrataFileType
    ADD CONSTRAINT rhn_erratafile_type_label_uq UNIQUE (label);

  070701000000CA000081B400000000000000000000000167AE1114000004B7000000000000000000000000000000000000003600000000susemanager-schema/common/tables/rhnErrataKeyword.sql --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnErrataKeyword
(
    errata_id  NUMERIC NOT NULL
                   CONSTRAINT rhn_err_keyword_eid_fk
                       REFERENCES rhnErrata (id)
                       ON DELETE CASCADE,
    keyword    VARCHAR(64),
    created    TIMESTAMPTZ
                   DEFAULT (current_timestamp) NOT NULL,
    modified   TIMESTAMPTZ
                   DEFAULT (current_timestamp) NOT NULL
)

;

CREATE UNIQUE INDEX rhn_err_keyword_eid_uq
    ON rhnErrataKeyword (keyword, errata_id)
    ;

CREATE INDEX rhn_errkw_eid_idx
    ON rhnErrataKeyword (errata_id)
    ;

 070701000000CB000081B400000000000000000000000167AE111400000690000000000000000000000000000000000000004000000000susemanager-schema/common/tables/rhnErrataNotificationQueue.sql   --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnErrataNotificationQueue
(
    errata_id    NUMERIC NOT NULL
                     CONSTRAINT rhn_enqueue_eid_fk
                         REFERENCES rhnErrata (id)
                         ON DELETE CASCADE,
    org_id       NUMERIC NOT NULL
                     CONSTRAINT rhn_enqueue_oid_fk
                         REFERENCES web_customer (id)
                         ON DELETE CASCADE,
    next_action  TIMESTAMPTZ
                     DEFAULT (current_timestamp),
    channel_id   NUMERIC NOT NULL
                     CONSTRAINT rhn_enqueue_cid_fk
                         REFERENCES rhnChannel(id)
                         ON DELETE cascade,
    created      TIMESTAMPTZ
                     DEFAULT (current_timestamp) NOT NULL,
    modified     TIMESTAMPTZ
                     DEFAULT (current_timestamp) NOT NULL
)

;

CREATE INDEX rhn_enqueue_na_idx
    ON rhnErrataNotificationQueue (next_action)
    ;

ALTER TABLE rhnErrataNotificationQueue
    ADD CONSTRAINT rhn_enqueue_eoid_uq UNIQUE (errata_id, channel_id, org_id);

070701000000CC000081B400000000000000000000000167AE11140000055B000000000000000000000000000000000000003600000000susemanager-schema/common/tables/rhnErrataPackage.sql --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnErrataPackage
(
    errata_id   NUMERIC NOT NULL
                    CONSTRAINT rhn_err_pkg_eid_fk
                        REFERENCES rhnErrata (id)
                        ON DELETE CASCADE,
    package_id  NUMERIC NOT NULL
                    CONSTRAINT rhn_err_pkg_pid_fk
                        REFERENCES rhnPackage (id)
                        ON DELETE CASCADE,
    created     TIMESTAMPTZ
                    DEFAULT (current_timestamp) NOT NULL,
    modified    TIMESTAMPTZ
                    DEFAULT (current_timestamp) NOT NULL
)

;

CREATE UNIQUE INDEX rhn_err_pkg_eid_pid_uq
    ON rhnErrataPackage (errata_id, package_id)
    ;

CREATE INDEX rhn_err_pkg_pid_idx
    ON rhnErrataPackage (package_id)
    
    ;

 070701000000CD000081B400000000000000000000000167AE11140000056F000000000000000000000000000000000000003400000000susemanager-schema/common/tables/rhnErrataQueue.sql   --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnErrataQueue
(
    errata_id    NUMERIC NOT NULL
                     CONSTRAINT rhn_equeue_eid_fk
                         REFERENCES rhnErrata (id)
                         ON DELETE CASCADE,
    channel_id   NUMERIC NOT NULL
                     CONSTRAINT rhn_equeue_cid_fk
                         REFERENCES rhnChannel(id)
                         ON DELETE CASCADE,
    next_action  TIMESTAMPTZ,
    created      TIMESTAMPTZ
                     DEFAULT (current_timestamp) NOT NULL,
    modified     TIMESTAMPTZ
                     DEFAULT (current_timestamp) NOT NULL
)

;

CREATE INDEX rhn_equeue_eid_idx
    ON rhnErrataQueue (errata_id)
    ;

CREATE INDEX rhn_equeue_na_eid_idx
    ON rhnErrataQueue (next_action, errata_id)
    ;


 070701000000CE000081B400000000000000000000000167AE11140000032B000000000000000000000000000000000000003700000000susemanager-schema/common/tables/rhnErrataSeverity.sql    --
-- Copyright (c) 2008 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnErrataSeverity
(
    id     NUMERIC NOT NULL
               CONSTRAINT rhn_errata_sev_id_pk PRIMARY KEY,
    rank   NUMERIC NOT NULL,
    label  VARCHAR(40) NOT NULL
)

;

 070701000000CF000081B400000000000000000000000167AE111400000388000000000000000000000000000000000000003200000000susemanager-schema/common/tables/rhnException.sql --
-- Copyright (c) 2008 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnException
(
    id       NUMERIC NOT NULL
                 CONSTRAINT rhn_exc_id_pk PRIMARY KEY
                 ,
    label    VARCHAR(128) NOT NULL,
    message  VARCHAR(2000) NOT NULL
)

;

CREATE UNIQUE INDEX rhn_exc_label_uq
    ON rhnException (label)
    ;

070701000000D0000081B400000000000000000000000167AE111400000452000000000000000000000000000000000000003000000000susemanager-schema/common/tables/rhnFeature.sql   --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnFeature
(
    id        NUMERIC
                  CONSTRAINT rhn_feature_id PRIMARY KEY
                  ,
    label     VARCHAR(32) NOT NULL,
    name      VARCHAR(64) NOT NULL,
    created   TIMESTAMPTZ
                  DEFAULT (current_timestamp) NOT NULL,
    modified  TIMESTAMPTZ
                  DEFAULT (current_timestamp) NOT NULL
)

;

CREATE UNIQUE INDEX rhn_feature_label_uq_idx
    ON rhnFeature (label)
    ;

CREATE SEQUENCE rhn_feature_seq;

  070701000000D1000081B400000000000000000000000167AE111400000588000000000000000000000000000000000000003500000000susemanager-schema/common/tables/rhnFileDownload.sql  --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnFileDownload
(
    file_id       NUMERIC NOT NULL
                      CONSTRAINT rhn_filedl_fid_fk
                          REFERENCES rhnFile (id),
    location      VARCHAR(2000) NOT NULL,
    token         VARCHAR(48),
    requestor_ip  VARCHAR(15) NOT NULL,
    start_time    TIMESTAMPTZ
                      DEFAULT (current_timestamp) NOT NULL,
    user_id       NUMERIC
                      CONSTRAINT rhn_filedl_uid_fk
                          REFERENCES web_contact (id)
                          ON DELETE SET NULL
)

;

CREATE INDEX rhn_filedl_uid_fid_idx
    ON rhnFileDownload (user_id, file_id)
    ;

CREATE INDEX rhn_filedl_token_idx
    ON rhnFileDownload (token)
    ;

CREATE INDEX rhn_filedl_start_idx
    ON rhnFileDownload (start_time)
    ;

070701000000D2000081B400000000000000000000000167AE1114000004CB000000000000000000000000000000000000003100000000susemanager-schema/common/tables/rhnFileList.sql  --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnFileList
(
    id        NUMERIC NOT NULL
                  CONSTRAINT rhn_filelist_id_pk PRIMARY KEY
                  ,
    label     VARCHAR(128) NOT NULL,
    org_id    NUMERIC NOT NULL
                  CONSTRAINT rhn_filelist_oid_fk
                      REFERENCES web_customer (id),
    created   TIMESTAMPTZ
                  DEFAULT (current_timestamp) NOT NULL,
    modified  TIMESTAMPTZ
                  DEFAULT (current_timestamp) NOT NULL
)

;

CREATE UNIQUE INDEX rhn_filelist_oid_l_uq
    ON rhnFileList (org_id, label)
    ;

CREATE SEQUENCE rhn_filelist_id_seq;

 070701000000D3000081B400000000000000000000000167AE111400000567000000000000000000000000000000000000003800000000susemanager-schema/common/tables/rhnFileListMembers.sql   --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnFileListMembers
(
    file_list_id         NUMERIC NOT NULL
                             CONSTRAINT rhn_flmembers_flid_fk
                                 REFERENCES rhnFileList (id)
                                 ON DELETE CASCADE,
    config_file_name_id  NUMERIC NOT NULL
                             CONSTRAINT rhn_flmembers_cfnid_fk
                                 REFERENCES rhnConfigFileName (id),
    created              TIMESTAMPTZ
                             DEFAULT (current_timestamp) NOT NULL,
    modified             TIMESTAMPTZ
                             DEFAULT (current_timestamp) NOT NULL
)

;

CREATE UNIQUE INDEX rhn_flmembers_flid_cfnid_uq
    ON rhnFileListMembers (file_list_id, config_file_name_id)
    ;

 070701000000D4000081B400000000000000000000000167AE111400000394000000000000000000000000000000000000003500000000susemanager-schema/common/tables/rhnFileLocation.sql  --
-- Copyright (c) 2008 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnFileLocation
(
    file_id   NUMERIC NOT NULL
                  CONSTRAINT rhn_fileloc_fid_fk
                      REFERENCES rhnFile (id),
    location  VARCHAR(128) NOT NULL
)

;

CREATE UNIQUE INDEX rhn_fileloc_file_loc_uq
    ON rhnFileLocation (file_id, location)
    ;

070701000000D5000081B400000000000000000000000167AE1114000001A5000000000000000000000000000000000000003200000000susemanager-schema/common/tables/rhnISSMaster.sql create table rhnIssMaster (
    id NUMERIC not null constraint rhn_iss_master_id_pk primary key,
    label VARCHAR(256) not null constraint rhn_iss_master_label_uq unique,
    created TIMESTAMPTZ default (current_timestamp) not null,
    is_current_master char(1) default 'N' not null constraint rhn_issm_master_yn check (is_current_master in ('Y', 'N')),
    ca_cert VARCHAR(1024)
);

create sequence rhn_issmaster_seq;
   070701000000D6000081B400000000000000000000000167AE1114000001FB000000000000000000000000000000000000003600000000susemanager-schema/common/tables/rhnISSMasterOrgs.sql create table rhnIssMasterOrgs (
    id NUMERIC not null constraint rhn_issmasterorgs_id_pk primary key,
    master_id NUMERIC not null
        constraint rhn_issmasterorgs_cid_fk references rhnIssMaster(id) on delete cascade,
    master_org_id NUMERIC not null,
    master_org_name VARCHAR(512) not null,
    local_org_id NUMERIC
        constraint rhn_issmasterorgs_lid_fk references web_customer(id),
    created TIMESTAMPTZ default (current_timestamp) not null
);

create sequence rhn_issmasterorgs_seq;
 070701000000D7000081B400000000000000000000000167AE111400000214000000000000000000000000000000000000003100000000susemanager-schema/common/tables/rhnISSSlave.sql  
create table rhnISSSlave (
	id NUMERIC not null constraint rhn_isss_id_pk primary key,
	slave VARCHAR(512) not null constraint rhn_isss_name_uq unique,
	enabled char(1) default 'Y' not null
		constraint rhn_isss_enabled_yn check (enabled in ( 'Y', 'N' )),
	allow_all_orgs char(1) default 'Y' not null 
		constraint rhn_isss_allorgs_yn check (allow_all_orgs in ( 'Y', 'N' )),
	created TIMESTAMPTZ default (current_timestamp) not null,
	modified TIMESTAMPTZ default (current_timestamp) not null
);

create sequence rhn_issslave_seq;
070701000000D8000081B400000000000000000000000167AE11140000012A000000000000000000000000000000000000003500000000susemanager-schema/common/tables/rhnISSSlaveOrgs.sql  
create table rhnISSSlaveOrgs (
	slave_id NUMERIC not null constraint rhn_isssorg_sid_fk references rhnISSSlave(id) on delete cascade,
	org_id NUMERIC not null constraint rhn_isssorg_oid_fk references web_customer(id) on delete cascade,
	created TIMESTAMPTZ default (current_timestamp) not null
);
  070701000000D9000081B400000000000000000000000167AE1114000005E3000000000000000000000000000000000000003900000000susemanager-schema/common/tables/rhnImageNeededCache.sql  --
-- Copyright (c) 2017 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
--

CREATE TABLE rhnImageNeededCache
(
    image_id    NUMERIC NOT NULL
                    CONSTRAINT rhn_inc_iid_fk
                        REFERENCES suseImageInfo (id)
                        ON DELETE CASCADE,
    errata_id   NUMERIC
                    CONSTRAINT rhn_inc_eid_fk
                        REFERENCES rhnErrata (id)
                        ON DELETE CASCADE,
    package_id  NUMERIC NOT NULL
                    CONSTRAINT rhn_inc_pid_fk
                        REFERENCES rhnPackage (id)
                        ON DELETE CASCADE,
    channel_id   NUMERIC
                    CONSTRAINT rhn_inc_cid_fk
                        REFERENCES rhnChannel (id)
                        ON DELETE CASCADE
)


;

CREATE INDEX rhn_inc_pid_idx
    ON rhnImageNeededCache (package_id)
    
    
    ;

CREATE INDEX rhn_inc_eid_idx
    ON rhnImageNeededCache (errata_id)
    
    ;

CREATE INDEX rhn_inc_cid_idx
    ON rhnImageNeededCache (channel_id)
    
    ;

CREATE INDEX rhn_inc_ipeid_idx
    ON rhnImageNeededCache (image_id, package_id, errata_id)
    
    
    ;
 070701000000DA000081B400000000000000000000000167AE111400000342000000000000000000000000000000000000003400000000susemanager-schema/common/tables/rhnIndexerWork.sql   --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnIndexerWork
(
    object_type    VARCHAR(40) NOT NULL,
    last_id        NUMERIC NOT NULL,
    last_modified  TIMESTAMPTZ
                       DEFAULT (current_timestamp) NOT NULL
)

;

  070701000000DB000081B400000000000000000000000167AE11140000038B000000000000000000000000000000000000003100000000susemanager-schema/common/tables/rhnInfoPane.sql  --
-- Copyright (c) 2008 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnInfoPane
(
    id     NUMERIC
               CONSTRAINT rhn_info_pane_id_pk PRIMARY KEY,
    label  VARCHAR(64) NOT NULL,
    acl    VARCHAR(4000)
)

;

CREATE UNIQUE INDEX rhn_info_pane_labl_uq
    ON rhnInfoPane (label)
    ;

CREATE SEQUENCE rhn_info_pane_id_seq;

 070701000000DC000081B400000000000000000000000167AE111400000E4A000000000000000000000000000000000000002F00000000susemanager-schema/common/tables/rhnKSData.sql    --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnKSData
(
    id              NUMERIC NOT NULL
                        CONSTRAINT rhn_ks_id_pk PRIMARY KEY
                        ,
    ks_type         VARCHAR(8) NOT NULL,
    org_id          NUMERIC NOT NULL
                        CONSTRAINT rhn_ks_oid_fk
                            REFERENCES web_customer (id)
                            ON DELETE CASCADE,
    is_org_default  CHAR(1)
                        DEFAULT ('N') NOT NULL
                        CONSTRAINT rhn_ks_default_ck
                            CHECK (is_org_default in ('Y','N')),
    label           VARCHAR(64) NOT NULL,
    comments        VARCHAR(4000),
    active          CHAR(1)
                        DEFAULT ('Y') NOT NULL
                        CONSTRAINT rhn_ks_active_ck
                            CHECK (active in ('Y','N')),
    postLog         CHAR(1)
                        DEFAULT ('N') NOT NULL
                        CONSTRAINT rhn_ks_post_log_ck
                            CHECK (postLog in ('Y','N')),
    preLog          CHAR(1)
                        DEFAULT ('N') NOT NULL
                        CONSTRAINT rhn_ks_pre_log_ck
                            CHECK (preLog in ('Y','N')),
    kscfg           CHAR(1)
                        DEFAULT ('N') NOT NULL
                        CONSTRAINT rhn_ks_cfg_save_ck
                            CHECK (kscfg in ('Y','N')),
    cobbler_id      VARCHAR(64),
    pre             BYTEA,
    post            BYTEA,
    nochroot_post   BYTEA,
    partition_data   BYTEA,
    static_device   VARCHAR(32),
    kernel_params   VARCHAR(2048),
    verboseup2date  CHAR(1)
                        DEFAULT ('N') NOT NULL
                        CONSTRAINT rhn_ks_verbose_up2date_ck
                            CHECK (verboseup2date in ('Y','N')),
    nonchrootpost   CHAR(1)
                        DEFAULT ('N') NOT NULL
                        CONSTRAINT rhn_ks_nonchroot_post_ck
                            CHECK (nonchrootpost in ('Y','N')),
    no_base         CHAR(1)
                        DEFAULT ('N') NOT NULL
                        CONSTRAINT rhn_ks_nobase_ck
                            CHECK (no_base in ( 'Y' , 'N' )),
    ignore_missing  CHAR(1)
                        DEFAULT ('N') NOT NULL
                        CONSTRAINT rhn_ks_ignore_missing_ck
                            CHECK (ignore_missing in ( 'Y' , 'N' )),
    created         TIMESTAMPTZ
                        DEFAULT (current_timestamp) NOT NULL,
    modified        TIMESTAMPTZ
                        DEFAULT (current_timestamp) NOT NULL,
    update_type     VARCHAR(7) DEFAULT ('none') NOT NULL
                        CONSTRAINT rhn_ks_update_type
			    CHECK (update_type in ('all', 'red_hat', 'none')),
    CONSTRAINT rhn_ks_type_ck
        CHECK (ks_type in ('wizard','raw'))
)

;

CREATE INDEX rhn_ks_oid_label_id_idx
    ON rhnKSData (org_id, label, id)
    ;

CREATE SEQUENCE rhn_ks_id_seq;

ALTER TABLE rhnKSData
    ADD CONSTRAINT rhn_ks_oid_label_uq UNIQUE (org_id, label);

  070701000000DD000081B400000000000000000000000167AE11140000047B000000000000000000000000000000000000003600000000susemanager-schema/common/tables/rhnKSInstallType.sql --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnKSInstallType
(
    id        NUMERIC NOT NULL
                  CONSTRAINT rhn_ksinstalltype_id_pk PRIMARY KEY
                  ,
    label     VARCHAR(32) NOT NULL,
    name      VARCHAR(64) NOT NULL,
    created   TIMESTAMPTZ
                  DEFAULT (current_timestamp) NOT NULL,
    modified  TIMESTAMPTZ
                  DEFAULT (current_timestamp) NOT NULL
)

;

CREATE UNIQUE INDEX rhn_ksinstalltype_label_uq
    ON rhnKSInstallType (label)
    ;

CREATE SEQUENCE rhn_ksinstalltype_id_seq;

 070701000000DE000081B400000000000000000000000167AE1114000005FA000000000000000000000000000000000000003300000000susemanager-schema/common/tables/rhnKSTreeFile.sql    --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnKSTreeFile
(
    kstree_id          NUMERIC NOT NULL
                           CONSTRAINT rhn_kstreefile_kid_fk
                               REFERENCES rhnKickstartableTree (id)
                               ON DELETE CASCADE,
    relative_filename  VARCHAR(256) NOT NULL,
    checksum_id        NUMERIC NOT NULL
                          CONSTRAINT rhn_kstreefile_chsum_fk
                           REFERENCES rhnChecksum (id),
    file_size          NUMERIC NOT NULL,
    last_modified      TIMESTAMPTZ
                           DEFAULT (current_timestamp) NOT NULL,
    created            TIMESTAMPTZ
                           DEFAULT (current_timestamp) NOT NULL,
    modified           TIMESTAMPTZ
                           DEFAULT (current_timestamp) NOT NULL
)

;

CREATE UNIQUE INDEX rhn_kstreefile_kid_rfn_uq
    ON rhnKSTreeFile (kstree_id, relative_filename)
    ;

  070701000000DF000081B400000000000000000000000167AE11140000046A000000000000000000000000000000000000003300000000susemanager-schema/common/tables/rhnKSTreeType.sql    --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnKSTreeType
(
    id        NUMERIC NOT NULL
                  CONSTRAINT rhn_kstreetype_id_pk PRIMARY KEY
                  ,
    label     VARCHAR(32) NOT NULL,
    name      VARCHAR(64) NOT NULL,
    created   TIMESTAMPTZ
                  DEFAULT (current_timestamp) NOT NULL,
    modified  TIMESTAMPTZ
                  DEFAULT (current_timestamp) NOT NULL
)

;

CREATE UNIQUE INDEX rhn_kstreetype_label_uq
    ON rhnKSTreeType (label)
    ;

CREATE SEQUENCE rhn_kstree_type_seq;

  070701000000E0000081B400000000000000000000000167AE11140000050B000000000000000000000000000000000000003E00000000susemanager-schema/common/tables/rhnKickstartChildChannel.sql --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnKickstartChildChannel
(
    channel_id  NUMERIC NOT NULL
                    CONSTRAINT rhn_ks_cc_cid_fk
                        REFERENCES rhnChannel (id)
                        ON DELETE CASCADE,
    ksdata_id   NUMERIC NOT NULL
                    CONSTRAINT rhn_ks_cc_ksd_fk
                        REFERENCES rhnKSData (id)
                        ON DELETE CASCADE,
    created     TIMESTAMPTZ
                    DEFAULT (current_timestamp) NOT NULL,
    modified    TIMESTAMPTZ
                    DEFAULT (current_timestamp) NOT NULL
)

;

CREATE UNIQUE INDEX rhn_ks_cc_uq
    ON rhnKickstartChildChannel (channel_id, ksdata_id)
    ;

 070701000000E1000081B400000000000000000000000167AE111400000635000000000000000000000000000000000000003900000000susemanager-schema/common/tables/rhnKickstartCommand.sql  --
-- Copyright (c) 2008--2017 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnKickstartCommand
(
    id                  NUMERIC
                            CONSTRAINT rhn_kscommand_id_pk PRIMARY KEY
                            ,
    kickstart_id        NUMERIC NOT NULL
                            CONSTRAINT rhn_kscommand_ksid_fk
                                REFERENCES rhnKSData (id)
                                ON DELETE CASCADE,
    ks_command_name_id  NUMERIC NOT NULL
                            CONSTRAINT rhn_kscommand_kcnid_fk
                                REFERENCES rhnKickstartCommandName (id),
    arguments           VARCHAR(2048),
    created             TIMESTAMPTZ
                            DEFAULT (current_timestamp) NOT NULL,
    modified            TIMESTAMPTZ
                            DEFAULT (current_timestamp) NOT NULL,
    custom_position     NUMERIC
)

;

CREATE INDEX rhn_kscommand_ksid_idx
    ON rhnKickstartCommand (kickstart_id)
    ;

CREATE SEQUENCE rhn_kscommand_id_seq;

   070701000000E2000081B400000000000000000000000167AE1114000005CF000000000000000000000000000000000000003D00000000susemanager-schema/common/tables/rhnKickstartCommandName.sql  --
-- Copyright (c) 2008--2010 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnKickstartCommandName
(
    id              NUMERIC NOT NULL
                        CONSTRAINT rhn_kscommandname_id_pk PRIMARY KEY
                        ,
    name            VARCHAR(128) NOT NULL,
    uses_arguments  CHAR(1) NOT NULL
                        CONSTRAINT rhn_kscommandname_uses_args_ck
                            CHECK (uses_arguments in ('Y','N')),
    sort_order      NUMERIC NOT NULL,
    required        CHAR(1)
                        DEFAULT ('N') NOT NULL
                        CONSTRAINT rhn_kscommandname_reqrd_ck
                            CHECK ( required in ('Y', 'N') )
)

;

CREATE INDEX rhn_kscommandname_name_id_idx
    ON rhnKickstartCommandName (name, id)
    ;

CREATE SEQUENCE rhn_kscommandname_id_seq;

ALTER TABLE rhnKickstartCommandName
    ADD CONSTRAINT rhn_kscommandname_name_uq UNIQUE (name);

 070701000000E3000081B400000000000000000000000167AE11140000058C000000000000000000000000000000000000004100000000susemanager-schema/common/tables/rhnKickstartDefaultRegToken.sql  --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnKickstartDefaultRegToken
(
    kickstart_id  NUMERIC NOT NULL
                      CONSTRAINT rhn_ksdrt_ksid_fk
                          REFERENCES rhnKSData (id)
                          ON DELETE CASCADE,
    regtoken_id   NUMERIC NOT NULL
                      CONSTRAINT rhn_ksdrt_rtid_fk
                          REFERENCES rhnRegToken (id)
                          ON DELETE CASCADE,
    created       TIMESTAMPTZ
                      DEFAULT (current_timestamp) NOT NULL,
    modified      TIMESTAMPTZ
                      DEFAULT (current_timestamp) NOT NULL
)

;

CREATE INDEX rhn_ksdrt_ksid_rtid_idx
    ON rhnKickstartDefaultRegToken (kickstart_id, regtoken_id)
    ;

CREATE INDEX rhn_ksdrt_rtid_idx
    ON rhnKickstartDefaultRegToken (regtoken_id)
    ;

070701000000E4000081B400000000000000000000000167AE11140000090D000000000000000000000000000000000000003A00000000susemanager-schema/common/tables/rhnKickstartDefaults.sql --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnKickstartDefaults
(
    kickstart_id         NUMERIC NOT NULL
                             CONSTRAINT rhn_ksd_ksid_uq UNIQUE
                             CONSTRAINT rhn_ksd_ksid_fk
                                 REFERENCES rhnKSData (id)
                                 ON DELETE CASCADE,
    kstree_id            NUMERIC NOT NULL
                             CONSTRAINT rhn_ksd_kstid_fk
                                 REFERENCES rhnKickstartableTree (id)
                                 ON DELETE CASCADE,
    server_profile_id    NUMERIC
                             CONSTRAINT rhn_ksd_spid_fk
                                 REFERENCES rhnServerProfile (id)
                                 ON DELETE SET NULL,
    cfg_management_flag  CHAR(1)
                             DEFAULT ('Y') NOT NULL
                             CONSTRAINT rhn_ksd_cmf_ck
                                 CHECK (cfg_management_flag in ('Y','N')),
    remote_command_flag  CHAR(1)
                             DEFAULT ('N') NOT NULL
                             CONSTRAINT rhn_ksd_rmf_ck
                                 CHECK (remote_command_flag in ('Y','N')),
    virtualization_type  NUMERIC NOT NULL
                             CONSTRAINT rhn_ksd_kvt_fk
                                 REFERENCES rhnKickstartVirtualizationType (id)
                                 ON DELETE SET NULL,
    created              TIMESTAMPTZ
                             DEFAULT (current_timestamp) NOT NULL,
    modified             TIMESTAMPTZ
                             DEFAULT (current_timestamp) NOT NULL
)

;

CREATE INDEX rhn_ksd_kstid_idx
    ON rhnKickstartDefaults (kstree_id)
    ;

   070701000000E5000081B400000000000000000000000167AE111400000612000000000000000000000000000000000000003900000000susemanager-schema/common/tables/rhnKickstartIPRange.sql  --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnKickstartIPRange
(
    kickstart_id  NUMERIC NOT NULL
                      CONSTRAINT rhn_ksip_ksid_fk
                          REFERENCES rhnKSData (id)
                          ON DELETE CASCADE,
    org_id        NUMERIC NOT NULL
                      CONSTRAINT rhn_ksip_oid_fk
                          REFERENCES web_customer (id)
                          ON DELETE CASCADE,
    min           NUMERIC NOT NULL,
    max           NUMERIC NOT NULL,
    created       TIMESTAMPTZ
                      DEFAULT (current_timestamp) NOT NULL,
    modified      TIMESTAMPTZ
                      DEFAULT (current_timestamp) NOT NULL
)

;

CREATE INDEX rhn_ksip_kickstart_id_idx
    ON rhnKickstartIPRange (kickstart_id)
    ;

CREATE INDEX rhn_ksip_org_id_idx
    ON rhnKickstartIPRange (org_id)
    ;

ALTER TABLE rhnKickstartIPRange
    ADD CONSTRAINT rhn_ksip_oid_min_max_uq UNIQUE (org_id, min, max);

  070701000000E6000081B400000000000000000000000167AE1114000005CE000000000000000000000000000000000000003900000000susemanager-schema/common/tables/rhnKickstartPackage.sql  --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnKickstartPackage
(
    kickstart_id     NUMERIC NOT NULL
                         CONSTRAINT rhn_kspackage_ksid_fk
                             REFERENCES rhnKSData (id)
                             ON DELETE CASCADE,
    package_name_id  NUMERIC NOT NULL
                         CONSTRAINT rhn_kspackage_pnid_fk
                             REFERENCES rhnPackageName (id),
    position         NUMERIC NOT NULL,
    created          TIMESTAMPTZ
                         DEFAULT (current_timestamp) NOT NULL,
    modified         TIMESTAMPTZ
                         DEFAULT (current_timestamp) NOT NULL
)

;

ALTER TABLE rhnKickstartPackage
    ADD CONSTRAINT rhn_kspackage_pos_uq UNIQUE (kickstart_id, position)
    ;

ALTER TABLE rhnKickstartPackage
    ADD CONSTRAINT rhn_kspackage_name_uq UNIQUE (kickstart_id, package_name_id)
    ;

  070701000000E7000081B400000000000000000000000167AE1114000005B3000000000000000000000000000000000000004200000000susemanager-schema/common/tables/rhnKickstartPreserveFileList.sql --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnKickstartPreserveFileList
(
    kickstart_id  NUMERIC NOT NULL
                      CONSTRAINT rhn_kspreservefl_ksid_fk
                          REFERENCES rhnKSData (id)
                          ON DELETE CASCADE,
    file_list_id  NUMERIC NOT NULL
                      CONSTRAINT rhn_kspreservefl_flid_fk
                          REFERENCES rhnFileList (id)
                          ON DELETE CASCADE,
    created       TIMESTAMPTZ
                      DEFAULT (current_timestamp) NOT NULL,
    modified      TIMESTAMPTZ
                      DEFAULT (current_timestamp) NOT NULL
)

;

CREATE UNIQUE INDEX rhn_kspreservefl_ksid_flid_uq
    ON rhnKickstartPreserveFileList (kickstart_id, file_list_id)
    ;

CREATE INDEX rhn_kspreservefl_flid_idx
    ON rhnKickstartPreserveFileList (file_list_id)
    ;

 070701000000E8000081B400000000000000000000000167AE11140000090C000000000000000000000000000000000000003800000000susemanager-schema/common/tables/rhnKickstartScript.sql   --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnKickstartScript
(
    id            NUMERIC NOT NULL,
    script_name   VARCHAR(40),
    kickstart_id  NUMERIC NOT NULL
                      CONSTRAINT rhn_ksscript_ksid_fk
                          REFERENCES rhnKSData (id)
                          ON DELETE CASCADE,
    position      NUMERIC NOT NULL,
    script_type   VARCHAR(4) NOT NULL
                      CONSTRAINT rhn_ksscript_st_ck
                          CHECK (script_type in ('pre','post')),
    chroot        CHAR(1)
                      DEFAULT ('Y') NOT NULL
                      CONSTRAINT rhn_ksscript_chroot_ck
                          CHECK (chroot in ('Y','N')),
    error_on_fail CHAR(1)
                      DEFAULT ('N') not NULL
                      CONSTRAINT rhn_ksscript_erroronfail_ck
                          CHECK (error_on_fail in ('Y','N')),
    raw_script    CHAR(1)
                      DEFAULT ('Y') NOT NULL
                      CONSTRAINT rhn_ksscript_rawscript_ck
                          CHECK (raw_script in ('Y','N')),
    interpreter   VARCHAR(80),
    data          BYTEA,
    created       TIMESTAMPTZ
                      DEFAULT (current_timestamp) NOT NULL,
    modified      TIMESTAMPTZ
                      DEFAULT (current_timestamp) NOT NULL
)

;

CREATE INDEX rhn_ksscript_id_idx
    ON rhnKickstartScript (id)
    ;

CREATE INDEX rhn_ksscript_ksid_pos_idx
    ON rhnKickstartScript (kickstart_id, position)
    ;

CREATE SEQUENCE rhn_ksscript_id_seq;

ALTER TABLE rhnKickstartScript
    ADD CONSTRAINT rhn_ksscript_id_pk PRIMARY KEY (id);

ALTER TABLE rhnKickstartScript
    ADD CONSTRAINT rhn_ksscript_ksid_pos_uq UNIQUE (kickstart_id, position);

070701000000E9000081B400000000000000000000000167AE111400001000000000000000000000000000000000000000003900000000susemanager-schema/common/tables/rhnKickstartSession.sql  --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnKickstartSession
(
    id                   NUMERIC NOT NULL
                             CONSTRAINT rhn_ks_session_id_pk PRIMARY KEY
                             ,
    kickstart_id         NUMERIC
                             CONSTRAINT rhn_ks_session_ksid_fk
                                 REFERENCES rhnKSData (id)
                                 ON DELETE CASCADE,
    kickstart_mode       VARCHAR(32),
    kstree_id            NUMERIC
                             CONSTRAINT rhn_ks_session_kstid_fk
                                 REFERENCES rhnKickstartableTree (id)
                                 ON DELETE SET NULL,
    org_id               NUMERIC NOT NULL
                             CONSTRAINT rhn_ks_session_oid_fk
                                 REFERENCES web_customer (id)
                                 ON DELETE CASCADE,
    scheduler            NUMERIC
                             CONSTRAINT rhn_ks_session_sched_fk
                                 REFERENCES web_contact (id)
                                 ON DELETE SET NULL,
    old_server_id        NUMERIC
                             CONSTRAINT rhn_ks_session_osid_fk
                                 REFERENCES rhnServer (id),
    new_server_id        NUMERIC
                             CONSTRAINT rhn_ks_session_nsid_fk
                                 REFERENCES rhnServer (id),
    host_server_id       NUMERIC
                             CONSTRAINT rhn_ks_session_hsid_fk
                                 REFERENCES rhnServer (id)
                                 ON DELETE CASCADE,
    action_id            NUMERIC
                             CONSTRAINT rhn_ks_session_aid_fk
                                 REFERENCES rhnAction (id)
                                 ON DELETE SET NULL,
    state_id             NUMERIC NOT NULL
                             CONSTRAINT rhn_ks_session_ksssid_fk
                                 REFERENCES rhnKickstartSessionState (id),
    server_profile_id    NUMERIC
                             CONSTRAINT rhn_ks_session_spid_fk
                                 REFERENCES rhnServerProfile (id)
                                 ON DELETE SET NULL,
    last_action          TIMESTAMPTZ
                             DEFAULT (current_timestamp) NOT NULL,
    package_fetch_count  NUMERIC
                             DEFAULT (0) NOT NULL,
    last_file_request    VARCHAR(2048),
    system_rhn_host      VARCHAR(256),
    kickstart_from_host  VARCHAR(256),
    deploy_configs       CHAR(1)
                             DEFAULT ('N') NOT NULL,
    virtualization_type  NUMERIC NOT NULL
                             CONSTRAINT rhn_kss_kvt_fk
                                 REFERENCES rhnKickstartVirtualizationType (id)
                                 ON DELETE SET NULL,
    client_ip            VARCHAR(15),
    created              TIMESTAMPTZ
                             DEFAULT (current_timestamp) NOT NULL,
    modified             TIMESTAMPTZ
                             DEFAULT (current_timestamp) NOT NULL
)

;

CREATE INDEX rhn_ks_session_oid_idx
    ON rhnKickstartSession (org_id)
    ;

CREATE INDEX rhn_ks_session_osid_aid_idx
    ON rhnKickstartSession (old_server_id, action_id)
    ;

CREATE INDEX rhn_ks_session_nsid_idx
    ON rhnKickstartSession (new_server_id)
    ;

CREATE INDEX rhn_ks_session_hsid_idx
    ON rhnKickstartSession (host_server_id)
    ;

CREATE SEQUENCE rhn_ks_session_id_seq;

070701000000EA000081B400000000000000000000000167AE1114000007B5000000000000000000000000000000000000004000000000susemanager-schema/common/tables/rhnKickstartSessionHistory.sql   --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnKickstartSessionHistory
(
    id                    NUMERIC NOT NULL
                              CONSTRAINT rhn_ks_sessionhist_id_pk PRIMARY KEY
                              ,
    kickstart_session_id  NUMERIC NOT NULL
                              CONSTRAINT rhn_ks_sessionhist_ksid_fk
                                  REFERENCES rhnKickstartSession (id)
                                  ON DELETE CASCADE,
    action_id             NUMERIC
                              CONSTRAINT rhn_ks_sessionhist_aid_fk
                                  REFERENCES rhnAction (id)
                                  ON DELETE SET NULL,
    state_id              NUMERIC NOT NULL
                              CONSTRAINT rhn_ks_sessionhist_stat_fk
                                  REFERENCES rhnKickstartSessionState (id),
    time                  TIMESTAMPTZ
                              DEFAULT (current_timestamp) NOT NULL,
    message               VARCHAR(4000),
    created               TIMESTAMPTZ
                              DEFAULT (current_timestamp) NOT NULL,
    modified              TIMESTAMPTZ
                              DEFAULT (current_timestamp) NOT NULL
)

;

CREATE INDEX rhn_ks_sessionhist_ksid_idx
    ON rhnKickstartSessionHistory (kickstart_session_id)
    ;

CREATE SEQUENCE rhn_ks_sessionhist_id_seq;

   070701000000EB000081B400000000000000000000000167AE1114000004D9000000000000000000000000000000000000003E00000000susemanager-schema/common/tables/rhnKickstartSessionState.sql --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnKickstartSessionState
(
    id           NUMERIC NOT NULL
                     CONSTRAINT rhn_ks_session_state_id_pk PRIMARY KEY
                     ,
    label        VARCHAR(64) NOT NULL,
    name         VARCHAR(128) NOT NULL,
    description  VARCHAR(1024) NOT NULL,
    created      TIMESTAMPTZ
                     DEFAULT (current_timestamp) NOT NULL,
    modified     TIMESTAMPTZ
                     DEFAULT (current_timestamp) NOT NULL
)

;

CREATE UNIQUE INDEX rhn_ks_session_state_label_uq
    ON rhnKickstartSessionState (label)
    ;

CREATE SEQUENCE rhn_ks_session_state_id_seq;

   070701000000EC000081B400000000000000000000000167AE1114000004F4000000000000000000000000000000000000003A00000000susemanager-schema/common/tables/rhnKickstartTimezone.sql --
-- Copyright (c) 2008 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnKickstartTimezone
(
    id            NUMERIC NOT NULL
                      CONSTRAINT rhn_ks_timezone_pk PRIMARY KEY
                      ,
    label         VARCHAR(128) NOT NULL,
    name          VARCHAR(128) NOT NULL,
    install_type  NUMERIC NOT NULL
                      CONSTRAINT rhn_ks_timezone_it_fk
                          REFERENCES rhnKSInstallType (id)
)

;

CREATE UNIQUE INDEX rhn_ks_timezone_it_label_uq
    ON rhnKickstartTimezone (install_type, label)
    ;

CREATE UNIQUE INDEX rhn_ks_timezone_it_name_uq
    ON rhnKickstartTimezone (install_type, name)
    ;

CREATE SEQUENCE rhn_ks_timezone_id_seq;

070701000000ED000081B400000000000000000000000167AE111400000457000000000000000000000000000000000000004400000000susemanager-schema/common/tables/rhnKickstartVirtualizationType.sql   --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnKickstartVirtualizationType
(
    id        NUMERIC NOT NULL
                  CONSTRAINT rhn_kvt_id_pk PRIMARY KEY
                  ,
    name      VARCHAR(128) NOT NULL,
    label     VARCHAR(128) NOT NULL
                  CONSTRAINT rhn_kvt_label_unq UNIQUE,
    created   TIMESTAMPTZ
                  DEFAULT (current_timestamp) NOT NULL,
    modified  TIMESTAMPTZ
                  DEFAULT (current_timestamp) NOT NULL
)

;

CREATE SEQUENCE rhn_kvt_id_seq;

 070701000000EE000081B400000000000000000000000167AE1114000008A6000000000000000000000000000000000000003A00000000susemanager-schema/common/tables/rhnKickstartableTree.sql --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnKickstartableTree
(
    id              NUMERIC NOT NULL,
    org_id          NUMERIC
                        CONSTRAINT rhn_kstree_oid_fk
                            REFERENCES web_customer (id)
                            ON DELETE CASCADE,
    label           VARCHAR(64) NOT NULL,
    base_path       VARCHAR(256) NOT NULL,
    channel_id      NUMERIC NOT NULL
                        CONSTRAINT rhn_kstree_cid_fk
                            REFERENCES rhnChannel (id)
                            ON DELETE CASCADE,
    cobbler_id      VARCHAR(64),
    cobbler_xen_id  VARCHAR(64),
    boot_image      VARCHAR(128)
                        DEFAULT ('spacewalk-koan'),
    kstree_type     NUMERIC NOT NULL
                        CONSTRAINT rhn_kstree_kstreetype_fk
                            REFERENCES rhnKSTreeType (id),
    install_type    NUMERIC NOT NULL
                        CONSTRAINT rhn_kstree_it_fk
                            REFERENCES rhnKSInstallType (id),
    kernel_options       VARCHAR(2048),
    kernel_options_post  VARCHAR(2048),
    last_modified   TIMESTAMPTZ
                        DEFAULT (current_timestamp) NOT NULL,
    created         TIMESTAMPTZ
                        DEFAULT (current_timestamp) NOT NULL,
    modified        TIMESTAMPTZ
                        DEFAULT (current_timestamp) NOT NULL
)

;

CREATE UNIQUE INDEX rhn_kstree_oid_label_uq
    ON rhnKickstartableTree (org_id, label)
    ;

CREATE SEQUENCE rhn_kstree_id_seq;

ALTER TABLE rhnKickstartableTree
    ADD CONSTRAINT rhn_kstree_id_pk PRIMARY KEY (id)
    ;

  070701000000EF000081B400000000000000000000000167AE111400000613000000000000000000000000000000000000003700000000susemanager-schema/common/tables/rhnLockedPackages.sql    --
-- Copyright (c) 2013 SUSE.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnLockedPackages
(
    pkg_id           NUMERIC NOT NULL
                         REFERENCES rhnPackage (id)
                             ON DELETE CASCADE,
    server_id        NUMERIC NOT NULL
                         REFERENCES rhnServer (id)
                             ON DELETE CASCADE,
    name_id          NUMERIC NOT NULL
                         REFERENCES rhnPackageName (id),
    evr_id           NUMERIC NOT NULL
                         REFERENCES rhnPackageEVR (id),
    arch_id          NUMERIC
                         REFERENCES rhnPackageArch (id),
    pending          CHAR(1) DEFAULT ('L')
                         CONSTRAINT rhn_lockedpackages_pending_ck
                           CHECK (pending in ('L', 'U'))
)

;

CREATE INDEX rhn_lp_pkg_id_idx
    ON rhnLockedPackages (pkg_id)
    
    ;
CREATE UNIQUE INDEX rhn_lp_snep_uq
    ON rhnLockedPackages (server_id, name_id, evr_id, arch_id)
    
    ;
 070701000000F0000081B400000000000000000000000167AE111400000596000000000000000000000000000000000000003B00000000susemanager-schema/common/tables/rhnOrgAdminManagement.sql    --
-- Copyright (c) 2015 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

CREATE TABLE rhnOrgAdminManagement
(
    org_id                  NUMERIC NOT NULL
                                CONSTRAINT rhn_orgadm_mngt_fk
                                    REFERENCES web_customer (id)
                                    ON DELETE CASCADE,
    enabled                 CHAR(1)
                                DEFAULT ('Y') NOT NULL
                                CONSTRAINT rhn_orgadm_mngt_enabled_ck
                                    CHECK (enabled in ('Y', 'N')),
    created                 TIMESTAMPTZ
                                DEFAULT (current_timestamp) NOT NULL,
    modified                TIMESTAMPTZ
                                DEFAULT (current_timestamp) NOT NULL
)

;

CREATE UNIQUE INDEX rhn_orgadm_mngt_org_id
    on rhnOrgAdminManagement (org_id)
        ;
  070701000000F1000081B400000000000000000000000167AE1114000005C9000000000000000000000000000000000000003B00000000susemanager-schema/common/tables/rhnOrgChannelSettings.sql    --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnOrgChannelSettings
(
    org_id      NUMERIC NOT NULL
                    CONSTRAINT rhn_orgcsettings_oid_fk
                        REFERENCES web_customer (id)
                        ON DELETE CASCADE,
    channel_id  NUMERIC NOT NULL
                    CONSTRAINT rhn_orgcsettings_cid_fk
                        REFERENCES rhnChannel (id)
                        ON DELETE CASCADE,
    setting_id  NUMERIC NOT NULL
                    CONSTRAINT rhn_orgcsettings_sid_fk
                        REFERENCES rhnOrgChannelSettingsType (id),
    created     TIMESTAMPTZ
                    DEFAULT (current_timestamp) NOT NULL,
    modified    TIMESTAMPTZ
                    DEFAULT (current_timestamp) NOT NULL
)

;

CREATE UNIQUE INDEX rhn_orgcsettings_oid_cid_uq
    ON rhnOrgChannelSettings (org_id, channel_id, setting_id)
    ;

   070701000000F2000081B400000000000000000000000167AE111400000450000000000000000000000000000000000000003F00000000susemanager-schema/common/tables/rhnOrgChannelSettingsType.sql    --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnOrgChannelSettingsType
(
    id        NUMERIC NOT NULL
                  CONSTRAINT rhn_ocstngs_type_id_pk PRIMARY KEY,
    label     VARCHAR(32) NOT NULL,
    created   TIMESTAMPTZ
                  DEFAULT (current_timestamp) NOT NULL,
    modified  TIMESTAMPTZ
                  DEFAULT (current_timestamp) NOT NULL
)

;

CREATE INDEX rhn_ocstngs_type_l_id_idx
    ON rhnOrgChannelSettingsType (label, id)
    ;

CREATE SEQUENCE rhn_ocstngs_type_id_seq;

070701000000F3000081B400000000000000000000000167AE111400000B8B000000000000000000000000000000000000003900000000susemanager-schema/common/tables/rhnOrgConfiguration.sql  --
-- Copyright (c) 2013--2015 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

create table rhnOrgConfiguration
(
    org_id                     NUMERIC not null
                                   constraint rhn_org_conf_org_id_fk
                                   references web_customer(id)
                                   on delete cascade,
    staging_content_enabled    char(1)
                                   default ('N') not null
                                   constraint rhn_org_conf_stage_content_chk
                                   check (staging_content_enabled in ('Y', 'N')),
    errata_emails_enabled      char(1)
                                    default ('Y') not null
                                    constraint rhn_org_conf_errata_emails_chk
                                    check (errata_emails_enabled in ('Y', 'N')),
    scapfile_upload_enabled    char(1)
                                   default ('N') not null
                                   constraint rhn_org_conf_scap_upload_chk
                                   check (scapfile_upload_enabled in ('Y', 'N')),
    clm_sync_patches           char(1)
                                   default ('Y') not null
                                   constraint rhn_org_conf_clm_sync_patches
                                   check (clm_sync_patches in ('Y', 'N')),
    scap_file_sizelimit        NUMERIC
                                   default(2097152) not null
                                   constraint rhn_org_conf_scap_szlmt_chk
                                   check (scap_file_sizelimit >= 0),
    scap_retention_period_days NUMERIC
                                   default(90)
                                   constraint rhn_org_conf_scap_reten_chk
                                   check (scap_retention_period_days >= 0),
    create_default_sg          char(1)
                                    default('N') not null
                                    constraint rhn_org_cong_deforg_chk
                                    check (create_default_sg in ('Y', 'N')),
    created                    TIMESTAMPTZ
                                   default (current_timestamp) not null,
    modified                   TIMESTAMPTZ
                                   default (current_timestamp) not null
)

;

create unique index rhn_org_conf_org_id
    on rhnOrgConfiguration (org_id)
    ;
 070701000000F4000081B400000000000000000000000167AE11140000041A000000000000000000000000000000000000003C00000000susemanager-schema/common/tables/rhnOrgErrataCacheQueue.sql   --
-- Copyright (c) 2008--2011 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnOrgErrataCacheQueue
(
    org_id        NUMERIC NOT NULL
                      CONSTRAINT rhn_oecq_oid_fk
                          REFERENCES web_customer (id)
                          ON DELETE CASCADE,
    server_count  NUMERIC NOT NULL,
    processed     NUMERIC
                      DEFAULT (0) NOT NULL
)


;

CREATE UNIQUE INDEX rhn_oecq_oid_uq
    ON rhnOrgErrataCacheQueue (org_id)
    
    ;

  070701000000F5000081B400000000000000000000000167AE1114000005B2000000000000000000000000000000000000003B00000000susemanager-schema/common/tables/rhnOrgExtGroupMapping.sql    --
-- Copyright (c) 2014 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnOrgExtGroupMapping
(
    id        NUMERIC NOT NULL
                  CONSTRAINT rhn_orgextgroupmap_id_pk PRIMARY KEY
                  ,
    ext_group_id       NUMERIC NOT NULL
                  constraint rhn_orgextgroupmap_eg_fk
                  references rhnUserExtGroup(id)
                  on delete cascade,
    server_group_id    NUMERIC NOT NULL
                  constraint rhn_orgextgroupmap_sg_fk
                  references rhnServerGroup(id)
                  on delete cascade,
    created   TIMESTAMPTZ
                  DEFAULT (current_timestamp) NOT NULL,
    modified  TIMESTAMPTZ
                  DEFAULT (current_timestamp) NOT NULL
)

;

CREATE UNIQUE INDEX rhn_orgextgroupmap_es_uq
    ON rhnOrgExtGroupMapping (ext_group_id, server_group_id)
    ;

CREATE SEQUENCE rhn_orgextgroupmap_seq;
  070701000000F6000081B400000000000000000000000167AE111400000DAF000000000000000000000000000000000000003000000000susemanager-schema/common/tables/rhnPackage.sql   --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnPackage
(
    id               NUMERIC NOT NULL
                         CONSTRAINT rhn_package_id_pk PRIMARY KEY
                         ,
    org_id           NUMERIC
                         CONSTRAINT rhn_package_oid_fk
                             REFERENCES web_customer (id)
                             ON DELETE CASCADE,
    name_id          NUMERIC NOT NULL
                         CONSTRAINT rhn_package_nid_fk
                             REFERENCES rhnPackageName (id),
    evr_id           NUMERIC NOT NULL
                         CONSTRAINT rhn_package_eid_fk
                             REFERENCES rhnPackageEvr (id),
    package_arch_id  NUMERIC NOT NULL
                         CONSTRAINT rhn_package_paid_fk
                             REFERENCES rhnPackageArch (id),
    package_group    NUMERIC
                         CONSTRAINT rhn_package_group_fk
                             REFERENCES rhnPackageGroup (id),
    rpm_version      VARCHAR(16),
    description      VARCHAR(4000),
    summary          VARCHAR(4000),
    package_size     NUMERIC NOT NULL,
    payload_size     NUMERIC,
    installed_size   NUMERIC,
    build_host       VARCHAR(256),
    build_time       timestamp,
    source_rpm_id    NUMERIC
                         CONSTRAINT rhn_package_srcrpmid_fk
                             REFERENCES rhnSourceRPM (id),
    checksum_id      NUMERIC NOT NULL
                         CONSTRAINT rhn_package_chsum_fk
                             REFERENCES rhnChecksum (id),
    vendor           VARCHAR(64),
    payload_format   VARCHAR(32),
    compat           NUMERIC(1)
                         DEFAULT (0)
                         CONSTRAINT rhn_package_compat_check
                             CHECK (compat in ( 1 , 0 )),
    path             VARCHAR(1000),
    header_sig       VARCHAR(64),
    copyright        VARCHAR(128),
    cookie           VARCHAR(128),
    is_ptf           BOOLEAN DEFAULT (FALSE),
    is_part_of_ptf   BOOLEAN DEFAULT (FALSE),
    last_modified    TIMESTAMPTZ
                         DEFAULT (current_timestamp) NOT NULL,
    created          TIMESTAMPTZ
                         DEFAULT (current_timestamp) NOT NULL,
    modified         TIMESTAMPTZ
                         DEFAULT (current_timestamp) NOT NULL,
    header_start     NUMERIC
                         DEFAULT (-1) NOT NULL,
    header_end       NUMERIC
                         DEFAULT (-1) NOT NULL
)

;

CREATE INDEX rhn_package_oid_id_idx
    ON rhnPackage (org_id, id)
    
    ;

CREATE INDEX rhn_package_nid_id_idx
    ON rhnPackage (name_id, id)
    
    ;

CREATE INDEX rhn_package_nid_evrid_idx
    ON rhnPackage (name_id, evr_id);

CREATE SEQUENCE rhn_package_id_seq;

CREATE INDEX rhn_package_is_ptf_idx ON rhnPackage (is_ptf);
CREATE INDEX rhn_package_is_part_of_ptf_idx ON rhnPackage (is_part_of_ptf);
 070701000000F7000081B400000000000000000000000167AE11140000057A000000000000000000000000000000000000003400000000susemanager-schema/common/tables/rhnPackageArch.sql   --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnPackageArch
(
    id            NUMERIC NOT NULL,
    label         VARCHAR(64) NOT NULL,
    name          VARCHAR(64) NOT NULL,
    arch_type_id  NUMERIC NOT NULL
                      CONSTRAINT rhn_parch_atid_fk
                          REFERENCES rhnArchType (id),
    created       TIMESTAMPTZ
                      DEFAULT (current_timestamp) NOT NULL,
    modified      TIMESTAMPTZ
                      DEFAULT (current_timestamp) NOT NULL
)

;

CREATE INDEX rhn_parch_id_l_n_idx
    ON rhnPackageArch (id, label, name)
    ;

CREATE SEQUENCE rhn_package_arch_id_seq START WITH 100;

ALTER TABLE rhnPackageArch
    ADD CONSTRAINT rhn_parch_id_pk PRIMARY KEY (id);

ALTER TABLE rhnPackageArch
    ADD CONSTRAINT rhn_parch_label_uq UNIQUE (label);

  070701000000F8000081B400000000000000000000000167AE111400000500000000000000000000000000000000000000003600000000susemanager-schema/common/tables/rhnPackageBreaks.sql --
-- Copyright (c) 2010 Novell
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
--


CREATE TABLE rhnPackageBreaks
(
    package_id     NUMERIC NOT NULL
                       CONSTRAINT rhn_pkg_brks_package_fk
                           REFERENCES rhnPackage (id)
                           ON DELETE CASCADE,
    capability_id  NUMERIC NOT NULL
                       CONSTRAINT rhn_pkg_brks_capability_fk
                           REFERENCES rhnPackageCapability (id),
    sense          NUMERIC
                       DEFAULT (0) NOT NULL,
    created        TIMESTAMPTZ
                       DEFAULT (current_timestamp) NOT NULL,
    modified       TIMESTAMPTZ
                       DEFAULT (current_timestamp) NOT NULL
)

;

CREATE UNIQUE INDEX rhn_pkg_brks_pid_cid_s_uq
    ON rhnPackageBreaks (package_id, capability_id, sense)
    ;

CREATE INDEX rhn_pkg_brks_cid_idx
    ON rhnPackageBreaks (capability_id)
    
    ;

070701000000F9000081B400000000000000000000000167AE111400000486000000000000000000000000000000000000003A00000000susemanager-schema/common/tables/rhnPackageCapability.sql --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnPackageCapability
(
    id        NUMERIC NOT NULL
                  CONSTRAINT rhn_pkg_capability_id_pk PRIMARY KEY
                  ,
    name      TEXT NOT NULL,
    version   VARCHAR(512),
    created   TIMESTAMPTZ
                  DEFAULT (current_timestamp) NOT NULL,
    modified  TIMESTAMPTZ
                  DEFAULT (current_timestamp) NOT NULL
)

;

-- unique index definitions has been moved to
-- {oracle,postgres}/tables/rhnPackageCapability_index.sql

CREATE SEQUENCE rhn_pkg_capability_id_seq;

  070701000000FA000081B400000000000000000000000167AE111400000453000000000000000000000000000000000000003D00000000susemanager-schema/common/tables/rhnPackageChangeLogData.sql  --
-- Copyright (c) 2010--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

CREATE TABLE rhnPackageChangeLogData
(
    id          NUMERIC NOT NULL
                    CONSTRAINT rhn_pkg_cld_id_pk PRIMARY KEY
                    ,
    name        VARCHAR(128) NOT NULL,
    text        TEXT NOT NULL,
    time        TIMESTAMPTZ NOT NULL,
    created     TIMESTAMPTZ
                    DEFAULT (current_timestamp) NOT NULL
)

;

CREATE INDEX rhn_pkg_cld_nt_idx
    ON rhnPackageChangeLogData (name, time)
    
    ;

CREATE SEQUENCE rhn_pkg_cld_id_seq;

 070701000000FB000081B400000000000000000000000167AE111400000603000000000000000000000000000000000000003C00000000susemanager-schema/common/tables/rhnPackageChangeLogRec.sql   --
-- Copyright (c) 2010--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnPackageChangeLogRec
(
    id          NUMERIC NOT NULL
                    CONSTRAINT rhn_pkg_clr_id_pk PRIMARY KEY
                    ,
    package_id  NUMERIC NOT NULL
                    CONSTRAINT rhn_pkg_clr_pid_fk
                        REFERENCES rhnPackage (id)
                        ON DELETE CASCADE,
    changelog_data_id  NUMERIC NOT NULL
                    CONSTRAINT rhn_pkg_clr_cld_fk
                        REFERENCES rhnPackageChangeLogData (id),
    created     TIMESTAMPTZ
                    DEFAULT (current_timestamp) NOT NULL,
    modified    TIMESTAMPTZ
                    DEFAULT (current_timestamp) NOT NULL
)

;

CREATE UNIQUE INDEX rhn_pkg_clr_pid_cld_uq
    ON rhnPackageChangeLogRec (package_id, changelog_data_id)
    
    ;

CREATE INDEX rhn_pkg_clr_cld_uq
    ON rhnPackageChangeLogRec (changelog_data_id)
    
    ;

CREATE SEQUENCE rhn_pkg_cl_id_seq;

 070701000000FC000081B400000000000000000000000167AE1114000005D6000000000000000000000000000000000000003900000000susemanager-schema/common/tables/rhnPackageConflicts.sql  --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnPackageConflicts
(
    package_id     NUMERIC NOT NULL
                       CONSTRAINT rhn_pkg_conflicts_package_fk
                           REFERENCES rhnPackage (id)
                           ON DELETE CASCADE,
    capability_id  NUMERIC NOT NULL
                       CONSTRAINT rhn_pkg_conflicts_cap_fk
                           REFERENCES rhnPackageCapability (id),
    sense          NUMERIC
                       DEFAULT (0) NOT NULL,
    created        TIMESTAMPTZ
                       DEFAULT (current_timestamp) NOT NULL,
    modified       TIMESTAMPTZ
                       DEFAULT (current_timestamp) NOT NULL
)

;

CREATE UNIQUE INDEX rhn_pkg_confl_pid_cid_s_uq
    ON rhnPackageConflicts (package_id, capability_id, sense)
    ;

CREATE INDEX rhn_pkg_conflicts_cid_idx
    ON rhnPackageConflicts (capability_id)
    
    ;

  070701000000FD000081B400000000000000000000000167AE11140000045E000000000000000000000000000000000000003500000000susemanager-schema/common/tables/rhnPackageDelta.sql  --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnPackageDelta
(
    id        NUMERIC NOT NULL,
    label     VARCHAR(32) NOT NULL,
    created   TIMESTAMPTZ
                  DEFAULT (current_timestamp) NOT NULL,
    modified  TIMESTAMPTZ
                  DEFAULT (current_timestamp) NOT NULL
)

;

CREATE INDEX rhn_packagedelta_label_id_idx
    ON rhnPackageDelta (label, id)
    ;

CREATE SEQUENCE rhn_packagedelta_id_seq;

ALTER TABLE rhnPackageDelta
    ADD CONSTRAINT rhn_packagedelta_id_pk PRIMARY KEY (id)
    ;

  070701000000FE000081B400000000000000000000000167AE1114000004BB000000000000000000000000000000000000003C00000000susemanager-schema/common/tables/rhnPackageDeltaElement.sql   --
-- Copyright (c) 2008 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnPackageDeltaElement
(
    package_delta_id        NUMERIC NOT NULL
                                CONSTRAINT rhn_pdelement_pdid_fk
                                    REFERENCES rhnPackageDelta (id)
                                    ON DELETE CASCADE,
    transaction_package_id  NUMERIC NOT NULL
                                CONSTRAINT rhn_pdelement_tpid_fk
                                    REFERENCES rhnTransactionPackage (id)
)

;

CREATE UNIQUE INDEX rhn_pdelement_pdid_tpid_uq
    ON rhnPackageDeltaElement (package_delta_id, transaction_package_id)
    ;

 070701000000FF000081B400000000000000000000000167AE11140000042B000000000000000000000000000000000000003300000000susemanager-schema/common/tables/rhnPackageEVR.sql    --
-- Copyright (c) 2008 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnPackageEVR
(
    id       NUMERIC NOT NULL
                 CONSTRAINT rhn_pe_id_pk PRIMARY KEY,
    epoch    VARCHAR(16),
    version  VARCHAR(512) NOT NULL,
    release  VARCHAR(512) NOT NULL,
    evr      EVR_T NOT NULL,
    type     varchar(10) generated always as ((evr).type) stored
)

;

-- unique index definitions has been moved to
-- {oracle,postgres}/tables/rhnPackageEVR_index.sql

CREATE SEQUENCE rhn_pkg_evr_seq;

 07070100000100000081B400000000000000000000000167AE111400000500000000000000000000000000000000000000003800000000susemanager-schema/common/tables/rhnPackageEnhances.sql   --
-- Copyright (c) 2013 Novell
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
--

CREATE TABLE rhnPackageEnhances
(
    package_id     NUMERIC NOT NULL
                       CONSTRAINT rhn_pkg_enh_package_fk
                           REFERENCES rhnPackage (id)
                           ON DELETE CASCADE,
    capability_id  NUMERIC NOT NULL
                       CONSTRAINT rhn_pkg_enh_capability_fk
                           REFERENCES rhnPackageCapability (id),
    sense          NUMERIC
                       DEFAULT (0) NOT NULL,
    created        TIMESTAMPTZ
                       DEFAULT (current_timestamp) NOT NULL,
    modified       TIMESTAMPTZ
                       DEFAULT (current_timestamp) NOT NULL
)

;

CREATE UNIQUE INDEX rhn_pkg_enh_pid_cid_s_uq
    ON rhnPackageEnhances (package_id, capability_id, sense)
    ;

CREATE INDEX rhn_pkg_enh_cid_idx
    ON rhnPackageEnhances (capability_id)
    
    ;
07070100000101000081B400000000000000000000000167AE1114000003B5000000000000000000000000000000000000003800000000susemanager-schema/common/tables/rhnPackageExtraTag.sql   --
-- Copyright (c) 2019 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--

CREATE TABLE rhnPackageExtraTag
(
    package_id  NUMERIC NOT NULL
                    CONSTRAINT rhn_pkg_extratags_pid_fk
                       REFERENCES rhnPackage (id)
                       ON DELETE CASCADE,
    key_id      NUMERIC NOT NULL
                       REFERENCES rhnPackageExtraTagKey (id)
                       ON DELETE CASCADE,
    value       VARCHAR(2048) NOT NULL,
    created     TIMESTAMPTZ
                    DEFAULT (current_timestamp) NOT NULL,
    primary key (package_id, key_id)
)
;
   07070100000102000081B400000000000000000000000167AE111400000347000000000000000000000000000000000000003B00000000susemanager-schema/common/tables/rhnPackageExtraTagKey.sql    --
-- Copyright (c) 2019 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--

CREATE TABLE rhnPackageExtraTagKey
(
    id          NUMERIC NOT NULL
                    CONSTRAINT rhn_pkg_extra_tags_keys_id_pk PRIMARY KEY,
    name        VARCHAR(256) NOT NULL,
    created     TIMESTAMPTZ
                    DEFAULT (current_timestamp) NOT NULL
)
;

CREATE SEQUENCE rhn_package_extra_tags_keys_id_seq;

CREATE UNIQUE INDEX rhn_pkg_extra_tag_key_idx
    ON rhnPackageExtraTagKey (name); 07070100000103000081B400000000000000000000000167AE1114000007BE000000000000000000000000000000000000003400000000susemanager-schema/common/tables/rhnPackageFile.sql   --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnPackageFile
(
    package_id     NUMERIC NOT NULL
                       CONSTRAINT rhn_package_file_pid_fk
                           REFERENCES rhnPackage (id)
                           ON DELETE CASCADE,
    capability_id  NUMERIC NOT NULL
                       CONSTRAINT rhn_package_file_cid_fk
                           REFERENCES rhnPackageCapability (id),
    device         NUMERIC NOT NULL,
    inode          NUMERIC NOT NULL,
    file_mode      NUMERIC NOT NULL,
    username       VARCHAR(32) NOT NULL,
    groupname      VARCHAR(32) NOT NULL,
    rdev           NUMERIC NOT NULL,
    file_size      NUMERIC NOT NULL,
    mtime          TIMESTAMPTZ NOT NULL,
    checksum_id    NUMERIC
                      CONSTRAINT rhn_package_file_chsum_fk
                          REFERENCES rhnChecksum (id),
    linkto         VARCHAR(256),
    flags          NUMERIC NOT NULL,
    verifyflags    NUMERIC NOT NULL,
    lang           VARCHAR(32),
    created        TIMESTAMPTZ
                       DEFAULT (current_timestamp) NOT NULL,
    modified       TIMESTAMPTZ
                       DEFAULT (current_timestamp) NOT NULL
)

;

CREATE UNIQUE INDEX rhn_package_file_pid_cid_uq
    ON rhnPackageFile (package_id, capability_id)
    ;

CREATE INDEX rhn_package_file_cid_idx
    ON rhnPackageFile (capability_id)
    
    ;

  07070100000104000081B400000000000000000000000167AE11140000036D000000000000000000000000000000000000003F00000000susemanager-schema/common/tables/rhnPackageFileDeleteQueue.sql    --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnPackageFileDeleteQueue
(
    path     VARCHAR(1000),
    created  TIMESTAMPTZ
                 DEFAULT (current_timestamp) NOT NULL
)

;

ALTER TABLE rhnPackageFileDeleteQueue
    ADD CONSTRAINT rhn_pfdqueue_path_uq UNIQUE (path);

   07070100000105000081B400000000000000000000000167AE111400000454000000000000000000000000000000000000003500000000susemanager-schema/common/tables/rhnPackageGroup.sql  --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnPackageGroup
(
    id        NUMERIC NOT NULL
                  CONSTRAINT rhn_package_group_id_pk PRIMARY KEY
                  ,
    name      VARCHAR(100) NOT NULL,
    created   TIMESTAMPTZ
                  DEFAULT (current_timestamp) NOT NULL,
    modified  TIMESTAMPTZ
                  DEFAULT (current_timestamp) NOT NULL
)

;

CREATE UNIQUE INDEX rhn_package_group_name_uq
    ON rhnPackageGroup (name)
    ;

CREATE SEQUENCE rhn_package_group_id_seq;

07070100000106000081B400000000000000000000000167AE11140000057F000000000000000000000000000000000000003300000000susemanager-schema/common/tables/rhnPackageKey.sql    --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnPackageKey
(
    id           NUMERIC NOT NULL,
    key_id       VARCHAR(64) NOT NULL,
    key_type_id  NUMERIC NOT NULL
                     CONSTRAINT rhn_pkey_type_id_prid_fk
                         REFERENCES rhnPackageKeyType (id),
    provider_id  NUMERIC
                     CONSTRAINT rhn_pkey_prid_fk
                         REFERENCES rhnPackageProvider (id),
    created      TIMESTAMPTZ
                     DEFAULT (current_timestamp) NOT NULL,
    modified     TIMESTAMPTZ
                     DEFAULT (current_timestamp) NOT NULL
)
;

CREATE SEQUENCE rhn_pkey_id_seq START WITH 100;

ALTER TABLE rhnPackageKey
    ADD CONSTRAINT rhn_pkey_id_pk PRIMARY KEY (id);

ALTER TABLE rhnPackageKey
    ADD CONSTRAINT rhn_pkey_keyid_uq UNIQUE (key_id);

 07070100000107000081B400000000000000000000000167AE1114000004E4000000000000000000000000000000000000003E00000000susemanager-schema/common/tables/rhnPackageKeyAssociation.sql --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnPackageKeyAssociation
(
    package_id  NUMERIC NOT NULL
                    CONSTRAINT rhn_pkeya_pid_fk
                        REFERENCES rhnPackage (id)
                        ON DELETE CASCADE,
    key_id      NUMERIC NOT NULL
                    CONSTRAINT rhn_pkeya_kid_fk
                        REFERENCES rhnPackageKey (id),
    created     TIMESTAMPTZ
                    DEFAULT (current_timestamp) NOT NULL,
    modified    TIMESTAMPTZ
                    DEFAULT (current_timestamp) NOT NULL
)
;

CREATE UNIQUE INDEX rhn_pkeya_pk_uq
    ON rhnPackageKeyAssociation (package_id, key_id)
    ;

07070100000108000081B400000000000000000000000167AE1114000004C9000000000000000000000000000000000000003700000000susemanager-schema/common/tables/rhnPackageKeyType.sql    --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnPackageKeyType
(
    id        NUMERIC NOT NULL,
    label     VARCHAR(64) NOT NULL,
    created   TIMESTAMPTZ
                  DEFAULT (current_timestamp) NOT NULL,
    modified  TIMESTAMPTZ
                  DEFAULT (current_timestamp) NOT NULL
)
;

CREATE INDEX rhn_pkg_key_type_id_n_idx
    ON rhnPackageKeyType (id, label)
    ;

CREATE SEQUENCE rhn_package_key_type_id_seq START WITH 100;

ALTER TABLE rhnPackageKeyType
    ADD CONSTRAINT rhn_pkg_key_type_id_pk PRIMARY KEY (id);

ALTER TABLE rhnPackageKeyType
    ADD CONSTRAINT rhn_pkg_key_type_label_uq UNIQUE (label);

   07070100000109000081B400000000000000000000000167AE111400000583000000000000000000000000000000000000003500000000susemanager-schema/common/tables/rhnPackageNEVRA.sql  --
-- Copyright (c) 2008--2010 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnPackageNEVRA
(
    id               NUMERIC NOT NULL
                         CONSTRAINT rhn_pkgnevra_id_pk PRIMARY KEY
                         ,
    name_id          NUMERIC NOT NULL
                         CONSTRAINT rhn_pkgnevra_nid_fk
                             REFERENCES rhnPackageName (id),
    evr_id           NUMERIC NOT NULL
                         CONSTRAINT rhn_pkgnevra_eid_fk
                             REFERENCES rhnPackageEVR (id),
    package_arch_id  NUMERIC
                         CONSTRAINT rhn_pkgnevra_paid_fk
                             REFERENCES rhnPackageArch (id)
)

;

CREATE SEQUENCE rhn_pkgnevra_id_seq;

ALTER TABLE rhnPackageNEVRA
    ADD CONSTRAINT rhn_pkgnevra_nid_eid_paid_uq UNIQUE (name_id, evr_id, package_arch_id);

 0707010000010A000081B400000000000000000000000167AE11140000037A000000000000000000000000000000000000003400000000susemanager-schema/common/tables/rhnPackageName.sql   --
-- Copyright (c) 2008 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnPackageName
(
    id    NUMERIC NOT NULL
              CONSTRAINT rhn_pn_id_pk PRIMARY KEY
              ,
    name  VARCHAR(256) NOT NULL
)

;

CREATE UNIQUE INDEX rhn_pn_name_uq
    ON rhnPackageName (name)
    ;

CREATE SEQUENCE rhn_pkg_name_seq;

  0707010000010B000081B400000000000000000000000167AE1114000005D6000000000000000000000000000000000000003900000000susemanager-schema/common/tables/rhnPackageObsoletes.sql  --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnPackageObsoletes
(
    package_id     NUMERIC NOT NULL
                       CONSTRAINT rhn_pkg_obsoletes_package_fk
                           REFERENCES rhnPackage (id)
                           ON DELETE CASCADE,
    capability_id  NUMERIC NOT NULL
                       CONSTRAINT rhn_pkg_obsoletes_cap_fk
                           REFERENCES rhnPackageCapability (id),
    sense          NUMERIC
                       DEFAULT (0) NOT NULL,
    created        TIMESTAMPTZ
                       DEFAULT (current_timestamp) NOT NULL,
    modified       TIMESTAMPTZ
                       DEFAULT (current_timestamp) NOT NULL
)

;

CREATE UNIQUE INDEX rhn_pkg_obsol_pid_cid_s_uq
    ON rhnPackageObsoletes (package_id, capability_id, sense)
    ;

CREATE INDEX rhn_pkg_obsoletes_cid_idx
    ON rhnPackageObsoletes (capability_id)
    
    ;

  0707010000010C000081B400000000000000000000000167AE11140000050C000000000000000000000000000000000000003A00000000susemanager-schema/common/tables/rhnPackagePredepends.sql --
-- Copyright (c) 2010 Novell
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
--


CREATE TABLE rhnPackagePredepends
(
    package_id     NUMERIC NOT NULL
                       CONSTRAINT rhn_pkg_pdep_package_fk
                           REFERENCES rhnPackage (id)
                           ON DELETE CASCADE,
    capability_id  NUMERIC NOT NULL
                       CONSTRAINT rhn_pkg_pdep_capability_fk
                           REFERENCES rhnPackageCapability (id),
    sense          NUMERIC
                       DEFAULT (0) NOT NULL,
    created        TIMESTAMPTZ
                       DEFAULT (current_timestamp) NOT NULL,
    modified       TIMESTAMPTZ
                       DEFAULT (current_timestamp) NOT NULL
)

;

CREATE UNIQUE INDEX rhn_pkg_pdep_pid_cid_s_uq
    ON rhnPackagePredepends (package_id, capability_id, sense)
    ;

CREATE INDEX rhn_pkg_pdep_cid_idx
    ON rhnPackagePredepends (capability_id)
    
    ;

0707010000010D000081B400000000000000000000000167AE1114000004CA000000000000000000000000000000000000003800000000susemanager-schema/common/tables/rhnPackageProvider.sql   --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnPackageProvider
(
    id        NUMERIC NOT NULL,
    name      VARCHAR(64) NOT NULL,
    created   TIMESTAMPTZ
                  DEFAULT (current_timestamp) NOT NULL,
    modified  TIMESTAMPTZ
                  DEFAULT (current_timestamp) NOT NULL
)
;

CREATE INDEX rhn_pkg_provider_id_n_idx
    ON rhnPackageProvider (id, name)
    ;

CREATE SEQUENCE rhn_package_provider_id_seq START WITH 100;

ALTER TABLE rhnPackageProvider
    ADD CONSTRAINT rhn_pkg_provider_id_pk PRIMARY KEY (id);

ALTER TABLE rhnPackageProvider
    ADD CONSTRAINT rhn_pkg_provider_name_uq UNIQUE (name);

  0707010000010E000081B400000000000000000000000167AE1114000005D3000000000000000000000000000000000000003800000000susemanager-schema/common/tables/rhnPackageProvides.sql   --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnPackageProvides
(
    package_id     NUMERIC NOT NULL
                       CONSTRAINT rhn_pkg_provides_package_fk
                           REFERENCES rhnPackage (id)
                           ON DELETE CASCADE,
    capability_id  NUMERIC NOT NULL
                       CONSTRAINT rhn_pkg_provides_capability_fk
                           REFERENCES rhnPackageCapability (id),
    sense          NUMERIC
                       DEFAULT (0) NOT NULL,
    created        TIMESTAMPTZ
                       DEFAULT (current_timestamp) NOT NULL,
    modified       TIMESTAMPTZ
                       DEFAULT (current_timestamp) NOT NULL
)

;

CREATE UNIQUE INDEX rhn_pkg_prov_cid_pid_s_uq
    ON rhnPackageProvides (capability_id, package_id, sense)
    ;

CREATE INDEX rhn_pkg_provides_pid_idx
    ON rhnPackageProvides (package_id)
    
    ;

 0707010000010F000081B400000000000000000000000167AE111400000508000000000000000000000000000000000000003A00000000susemanager-schema/common/tables/rhnPackageRecommends.sql --
-- Copyright (c) 2010 Novell
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
--


CREATE TABLE rhnPackageRecommends
(
    package_id     NUMERIC NOT NULL
                       CONSTRAINT rhn_pkg_rec_package_fk
                           REFERENCES rhnPackage (id)
                           ON DELETE CASCADE,
    capability_id  NUMERIC NOT NULL
                       CONSTRAINT rhn_pkg_rec_capability_fk
                           REFERENCES rhnPackageCapability (id),
    sense          NUMERIC
                       DEFAULT (0) NOT NULL,
    created        TIMESTAMPTZ
                       DEFAULT (current_timestamp) NOT NULL,
    modified       TIMESTAMPTZ
                       DEFAULT (current_timestamp) NOT NULL
)

;

CREATE UNIQUE INDEX rhn_pkg_rec_pid_cid_s_uq
    ON rhnPackageRecommends (package_id, capability_id, sense)
    ;

CREATE INDEX rhn_pkg_rec_cid_idx
    ON rhnPackageRecommends (capability_id)
    
    ;

07070100000110000081B400000000000000000000000167AE1114000004BC000000000000000000000000000000000000003800000000susemanager-schema/common/tables/rhnPackageRepoData.sql   --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnPackageRepodata
(
    package_id  NUMERIC NOT NULL
                    CONSTRAINT rhnPackageRepodata_pk
                        PRIMARY KEY
                    CONSTRAINT rhn_pkey_rd_pid_fk
                        REFERENCES rhnPackage (id)
                        ON DELETE CASCADE,
    primary_xml     BYTEA, -- primary is a reserved word :{
    filelist    BYTEA, 
    other       BYTEA,
    created     TIMESTAMPTZ
                    DEFAULT (current_timestamp) NOT NULL,
    modified    TIMESTAMPTZ
                    DEFAULT (current_timestamp) NOT NULL
)
;

07070100000111000081B400000000000000000000000167AE1114000005D5000000000000000000000000000000000000003800000000susemanager-schema/common/tables/rhnPackageRequires.sql   --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnPackageRequires
(
    package_id     NUMERIC NOT NULL
                       CONSTRAINT rhn_pkg_requires_package_fk
                           REFERENCES rhnPackage (id)
                           ON DELETE CASCADE,
    capability_id  NUMERIC NOT NULL
                       CONSTRAINT rhn_pkg_requires_capability_fk
                           REFERENCES rhnPackageCapability (id),
    sense          NUMERIC
                       DEFAULT (0) NOT NULL,
    created        TIMESTAMPTZ
                       DEFAULT (current_timestamp) NOT NULL,
    modified       TIMESTAMPTZ
                       DEFAULT (current_timestamp) NOT NULL
)

;

CREATE UNIQUE INDEX rhn_pkg_req_pid_cid_s_uq
    ON rhnPackageRequires (package_id, capability_id, sense)
    ;

CREATE INDEX rhn_pkg_requires_cid_idx
    ON rhnPackageRequires (capability_id)
    
    ;

   07070100000112000081B400000000000000000000000167AE1114000008F3000000000000000000000000000000000000003600000000susemanager-schema/common/tables/rhnPackageSource.sql --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnPackageSource
(
    id             NUMERIC NOT NULL
                       CONSTRAINT rhn_pkgsrc_id_pk PRIMARY KEY
                       ,
    org_id         NUMERIC
                       CONSTRAINT rhn_pkgsrc_oid_fk
                           REFERENCES web_customer (id)
                           ON DELETE CASCADE,
    source_rpm_id  NUMERIC NOT NULL
                       CONSTRAINT rhn_pkgsrc_srid_fk
                           REFERENCES rhnSourceRPM (id),
    package_group  NUMERIC NOT NULL
                       CONSTRAINT rhn_pkgsrc_group_fk
                           REFERENCES rhnPackageGroup (id),
    rpm_version    VARCHAR(16) NOT NULL,
    payload_size   NUMERIC NOT NULL,
    build_host     VARCHAR(256) NOT NULL,
    build_time     TIMESTAMPTZ NOT NULL,
    sigchecksum_id NUMERIC NOT NULL
                      CONSTRAINT rhn_pkgsrc_sigchsum_fk
                          REFERENCES rhnChecksum (id),
    vendor         VARCHAR(64) NOT NULL,
    cookie         VARCHAR(128) NOT NULL,
    path           VARCHAR(1000),
    checksum_id    NUMERIC NOT NULL
                      CONSTRAINT rhn_pkgsrc_chsum_fk
                          REFERENCES rhnChecksum (id),
    package_size   NUMERIC NOT NULL,
    last_modified  TIMESTAMPTZ
                       DEFAULT (current_timestamp) NOT NULL,
    created        TIMESTAMPTZ
                       DEFAULT (current_timestamp) NOT NULL,
    modified       TIMESTAMPTZ
                       DEFAULT (current_timestamp) NOT NULL
)

;

CREATE UNIQUE INDEX rhn_pkgsrc_srid_oid_uq
    ON rhnPackageSource (source_rpm_id, org_id)
    ;

CREATE SEQUENCE rhn_package_source_id_seq;

 07070100000113000081B400000000000000000000000167AE111400000506000000000000000000000000000000000000003800000000susemanager-schema/common/tables/rhnPackageSuggests.sql   --
-- Copyright (c) 2010 Novell
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
--


CREATE TABLE rhnPackageSuggests
(
    package_id     NUMERIC NOT NULL
                       CONSTRAINT rhn_pkg_sugg_package_fk
                           REFERENCES rhnPackage (id)
                           ON DELETE CASCADE,
    capability_id  NUMERIC NOT NULL
                       CONSTRAINT rhn_pkg_sugg_capability_fk
                           REFERENCES rhnPackageCapability (id),
    sense          NUMERIC
                       DEFAULT (0) NOT NULL,
    created        TIMESTAMPTZ
                       DEFAULT (current_timestamp) NOT NULL,
    modified       TIMESTAMPTZ
                       DEFAULT (current_timestamp) NOT NULL
)

;

CREATE UNIQUE INDEX rhn_pkg_sugg_pid_cid_s_uq
    ON rhnPackageSuggests (package_id, capability_id, sense)
    ;

CREATE INDEX rhn_pkg_sugg_cid_idx
    ON rhnPackageSuggests (capability_id)
    
    ;

  07070100000114000081B400000000000000000000000167AE11140000050F000000000000000000000000000000000000003B00000000susemanager-schema/common/tables/rhnPackageSupplements.sql    --
-- Copyright (c) 2010 Novell
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
--


CREATE TABLE rhnPackageSupplements
(
    package_id     NUMERIC NOT NULL
                       CONSTRAINT rhn_pkg_supp_package_fk
                           REFERENCES rhnPackage (id)
                           ON DELETE CASCADE,
    capability_id  NUMERIC NOT NULL
                       CONSTRAINT rhn_pkg_supp_capability_fk
                           REFERENCES rhnPackageCapability (id),
    sense          NUMERIC
                       DEFAULT (0) NOT NULL,
    created        TIMESTAMPTZ
                       DEFAULT (current_timestamp) NOT NULL,
    modified       TIMESTAMPTZ
                       DEFAULT (current_timestamp) NOT NULL
)

;

CREATE UNIQUE INDEX rhn_pkg_supp_pid_cid_s_uq
    ON rhnPackageSupplements (package_id, capability_id, sense)
    ;

CREATE INDEX rhn_pkg_supp_cid_idx
    ON rhnPackageSupplements (capability_id)
    
    ;

 07070100000115000081B400000000000000000000000167AE111400000593000000000000000000000000000000000000003D00000000susemanager-schema/common/tables/rhnPackageSyncBlacklist.sql  --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnPackageSyncBlacklist
(
    package_name_id  NUMERIC NOT NULL
                         CONSTRAINT rhn_packagesyncbl_pnid_fk
                             REFERENCES rhnPackageName (id),
    org_id           NUMERIC
                         CONSTRAINT rhn_packagesyncbl_oid_fk
                             REFERENCES web_customer (id)
                             ON DELETE CASCADE,
    created          TIMESTAMPTZ
                         DEFAULT (current_timestamp) NOT NULL,
    modified         TIMESTAMPTZ
                         DEFAULT (current_timestamp) NOT NULL
)

;

CREATE UNIQUE INDEX rhn_packagesyncbl_pnid_oid_uq
    ON rhnPackageSyncBlacklist (package_name_id, org_id)
    ;

CREATE INDEX rhn_packagesyncbl_oid_idx
    ON rhnPackageSyncBlacklist (org_id)
    
    ;

 07070100000116000081B400000000000000000000000167AE111400000519000000000000000000000000000000000000004100000000susemanager-schema/common/tables/rhnPackageUpgradeArchCompat.sql  --
-- Copyright (c) 2010--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnPackageUpgradeArchCompat
(
    package_arch_id   NUMERIC NOT NULL
                         CONSTRAINT rhn_puac_paid_fk
                             REFERENCES rhnPackageArch (id),
    package_upgrade_arch_id NUMERIC NOT NULL
                         CONSTRAINT rhn_puac_pauid_fk
                             REFERENCES rhnPackageArch (id),
    created          TIMESTAMPTZ
                         DEFAULT (current_timestamp) NOT NULL,
    modified         TIMESTAMPTZ
                         DEFAULT (current_timestamp) NOT NULL
)

;

CREATE UNIQUE INDEX rhn_puac_pa_pua_uq
    ON rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id)
    ;
   07070100000117000081B400000000000000000000000167AE1114000005A6000000000000000000000000000000000000003D00000000susemanager-schema/common/tables/rhnPrivateChannelFamily.sql  --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnPrivateChannelFamily
(
    channel_family_id  NUMERIC NOT NULL
                           CONSTRAINT rhn_privcf_cfid_fk
                               REFERENCES rhnChannelFamily (id),
    org_id             NUMERIC NOT NULL
                           CONSTRAINT rhn_privcf_oid_fk
                               REFERENCES web_customer (id)
                               ON DELETE CASCADE,
    created            TIMESTAMPTZ
                           DEFAULT (current_timestamp) NOT NULL,
    modified           TIMESTAMPTZ
                           DEFAULT (current_timestamp) NOT NULL
)

;

CREATE UNIQUE INDEX rhn_privcf_oid_cfid_uq
    ON rhnPrivateChannelFamily (org_id, channel_family_id)
    ;

CREATE INDEX rhn_cfperm_cfid_idx
    ON rhnPrivateChannelFamily (channel_family_id)
    
    ;

  07070100000118000081B400000000000000000000000167AE1114000004B5000000000000000000000000000000000000003400000000susemanager-schema/common/tables/rhnProductName.sql   --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnProductName
(
    id        NUMERIC NOT NULL
                  CONSTRAINT rhn_productname_id_pk PRIMARY KEY,
    label     VARCHAR(128) NOT NULL,
    name      VARCHAR(128) NOT NULL,
    created   TIMESTAMPTZ
                  DEFAULT (current_timestamp) NOT NULL,
    modified  TIMESTAMPTZ
                  DEFAULT (current_timestamp) NOT NULL
)

;

CREATE UNIQUE INDEX rhn_productname_label_uq
    ON rhnProductName (label);

CREATE UNIQUE INDEX rhn_productname_name_uq
    ON rhnProductName (name);

CREATE SEQUENCE rhn_productname_id_seq START WITH 101;

   07070100000119000081B400000000000000000000000167AE1114000004C9000000000000000000000000000000000000003700000000susemanager-schema/common/tables/rhnProvisionState.sql    --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnProvisionState
(
    id           NUMERIC NOT NULL
                     CONSTRAINT rhn_provstate_id_pk PRIMARY KEY,
    label        VARCHAR(32) NOT NULL,
    description  VARCHAR(256) NOT NULL,
    created      TIMESTAMPTZ
                     DEFAULT (current_timestamp) NOT NULL,
    modified     TIMESTAMPTZ
                     DEFAULT (current_timestamp) NOT NULL
)

;

CREATE INDEX rhn_provstate_l_id_idx
    ON rhnProvisionState (label, id)
    ;

CREATE SEQUENCE rhn_provstate_id_seq;

ALTER TABLE rhnProvisionState
    ADD CONSTRAINT rhn_provstate_l_uq UNIQUE (label);

   0707010000011A000081B400000000000000000000000167AE1114000004DE000000000000000000000000000000000000003200000000susemanager-schema/common/tables/rhnProxyInfo.sql --
-- Copyright (c) 2008 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnProxyInfo
(
    server_id     NUMERIC NOT NULL
                      CONSTRAINT rhn_proxy_info_sid_fk
                          REFERENCES rhnServer (id),
    proxy_evr_id  NUMERIC
                      CONSTRAINT rhn_proxy_info_peid_fk
                          REFERENCES rhnPackageEVR (id),
    ssh_port      NUMERIC,
    created             TIMESTAMPTZ
                            DEFAULT (current_timestamp) NOT NULL,
    modified            TIMESTAMPTZ
                            DEFAULT (current_timestamp) NOT NULL
)

;

CREATE UNIQUE INDEX rhn_proxy_info_sid_unq
    ON rhnProxyInfo (server_id);

  0707010000011B000081B400000000000000000000000167AE111400000466000000000000000000000000000000000000003C00000000susemanager-schema/common/tables/rhnPublicChannelFamily.sql   --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnPublicChannelFamily
(
    channel_family_id  NUMERIC NOT NULL
                           CONSTRAINT rhn_pubcf_cfid_fk
                               REFERENCES rhnChannelFamily (id),
    created            TIMESTAMPTZ
                           DEFAULT (current_timestamp) NOT NULL,
    modified           TIMESTAMPTZ
                           DEFAULT (current_timestamp) NOT NULL
)

;

CREATE UNIQUE INDEX rhn_pubcf_co_uq
    ON rhnPublicChannelFamily (channel_family_id)
    ;

  0707010000011C000081B400000000000000000000000167AE111400000622000000000000000000000000000000000000003300000000susemanager-schema/common/tables/rhnPushClient.sql    --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnPushClient
(
    id                 NUMERIC NOT NULL
                           CONSTRAINT rhn_pclient_id_pk PRIMARY KEY
                           ,
    name               VARCHAR(64) NOT NULL,
    server_id          NUMERIC NOT NULL,
    jabber_id          VARCHAR(128),
    shared_key         VARCHAR(64) NOT NULL,
    state_id           NUMERIC NOT NULL
                           REFERENCES rhnPushClientState (id),
    next_action_time   TIMESTAMPTZ,
    last_message_time  TIMESTAMPTZ,
    last_ping_time     TIMESTAMPTZ,
    created            TIMESTAMPTZ
                           DEFAULT (current_timestamp) NOT NULL,
    modified           TIMESTAMPTZ
                           DEFAULT (current_timestamp) NOT NULL
)

;

CREATE UNIQUE INDEX rhn_pclient_name_uq
    ON rhnPushClient (name)
    ;

CREATE UNIQUE INDEX rhn_pclient_sid_uq
    ON rhnPushClient (server_id)
    ;

CREATE SEQUENCE rhn_pclient_id_seq;

  0707010000011D000081B400000000000000000000000167AE1114000004D6000000000000000000000000000000000000003800000000susemanager-schema/common/tables/rhnPushClientState.sql   --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnPushClientState
(
    id        NUMERIC NOT NULL
                  CONSTRAINT rhn_pclient_state_id_pk PRIMARY KEY
                  ,
    label     VARCHAR(64) NOT NULL,
    name      VARCHAR(256) NOT NULL,
    created   TIMESTAMPTZ
                  DEFAULT (current_timestamp) NOT NULL,
    modified  TIMESTAMPTZ
                  DEFAULT (current_timestamp) NOT NULL
)

;

CREATE UNIQUE INDEX rhn_pclient_state_label_uq
    ON rhnPushClientState (label)
    ;

CREATE UNIQUE INDEX rhn_pclient_state_name_uq
    ON rhnPushClientState (name)
    ;

CREATE SEQUENCE rhn_pclient_state_id_seq;

  0707010000011E000081B400000000000000000000000167AE11140000057A000000000000000000000000000000000000003700000000susemanager-schema/common/tables/rhnPushDispatcher.sql    --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnPushDispatcher
(
    id            NUMERIC NOT NULL
                      CONSTRAINT rhn_pushdispatch_id_pk PRIMARY KEY
                      ,
    jabber_id     VARCHAR(128) NOT NULL,
    password      VARCHAR(32),
    last_checkin  TIMESTAMPTZ
                      DEFAULT (current_timestamp) NOT NULL,
    hostname      VARCHAR(256) NOT NULL,
    created       TIMESTAMPTZ
                      DEFAULT (current_timestamp) NOT NULL,
    modified      TIMESTAMPTZ
                      DEFAULT (current_timestamp) NOT NULL
)

;

CREATE INDEX rhn_pushdispatch_jid_id_idx
    ON rhnPushDispatcher (jabber_id, id)
    ;

CREATE SEQUENCE rhn_pushdispatch_id_seq;

ALTER TABLE rhnPushDispatcher
    ADD CONSTRAINT rhn_pushdispatch_jid_uq UNIQUE (jabber_id);

  0707010000011F000081B400000000000000000000000167AE1114000004D3000000000000000000000000000000000000002C00000000susemanager-schema/common/tables/rhnRam.sql   --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnRam
(
    id         NUMERIC NOT NULL
                   CONSTRAINT rhn_ram_id_pk PRIMARY KEY
                   ,
    server_id  NUMERIC NOT NULL
                   CONSTRAINT rhn_ram_server_fk
                       REFERENCES rhnServer (id),
    ram        NUMERIC NOT NULL,
    swap       NUMERIC NOT NULL,
    created    TIMESTAMPTZ
                   DEFAULT (current_timestamp) NOT NULL,
    modified   TIMESTAMPTZ
                   DEFAULT (current_timestamp) NOT NULL
)

;

CREATE UNIQUE INDEX rhn_ram_sid_uq
    ON rhnRam (server_id)
    
    ;

CREATE SEQUENCE rhn_ram_id_seq;

 07070100000120000081B400000000000000000000000167AE111400000863000000000000000000000000000000000000003100000000susemanager-schema/common/tables/rhnRegToken.sql  --
-- Copyright (c) 2008--2010 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnRegToken
(
    id              NUMERIC NOT NULL
                        CONSTRAINT rhn_reg_token_pk PRIMARY KEY,
    org_id          NUMERIC NOT NULL
                        CONSTRAINT rhn_reg_token_oid_fk
                            REFERENCES web_customer (id)
                            ON DELETE CASCADE,
    user_id         NUMERIC
                        CONSTRAINT rhn_reg_token_uid_fk
                            REFERENCES web_contact (id)
                            ON DELETE SET NULL,
    server_id       NUMERIC
                        CONSTRAINT rhn_reg_token_sid_fk
                            REFERENCES rhnServer (id),
    note            VARCHAR(2048) NOT NULL,
    usage_limit     NUMERIC
                        DEFAULT (0),
    disabled        NUMERIC
                        DEFAULT (0) NOT NULL,
    deploy_configs  CHAR(1)
                        DEFAULT ('Y') NOT NULL
                        CONSTRAINT rhn_reg_token_deployconfs_ck
                            CHECK (deploy_configs in ('Y','N')),
    contact_method_id NUMERIC
                        DEFAULT (0) NOT NULL
                        CONSTRAINT rhn_reg_token_cmid_fk
                            REFERENCES suseServerContactMethod (id)
)

;

CREATE INDEX rhn_reg_token_org_id_idx
    ON rhnRegToken (org_id, id)
    
    ;

CREATE INDEX rhn_reg_token_uid_idx
    ON rhnRegToken (user_id)
    
    ;

CREATE INDEX rhn_reg_token_sid_idx
    ON rhnRegToken (server_id)
    
    ;

CREATE SEQUENCE rhn_reg_token_seq;

 07070100000121000081B400000000000000000000000167AE111400000461000000000000000000000000000000000000003900000000susemanager-schema/common/tables/rhnRegTokenChannels.sql  --
-- Copyright (c) 2008 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnRegTokenChannels
(
    token_id    NUMERIC NOT NULL
                    CONSTRAINT rhn_reg_tok_chn_id_fk
                        REFERENCES rhnRegToken (id)
                        ON DELETE CASCADE,
    channel_id  NUMERIC NOT NULL
                    CONSTRAINT rhn_reg_tok_chn_sgs_fk
                        REFERENCES rhnChannel (id)
                        ON DELETE CASCADE
)

;

CREATE UNIQUE INDEX rhn_reg_tok_chn_uq
    ON rhnRegTokenChannels (token_id, channel_id)
    ;

   07070100000122000081B400000000000000000000000167AE111400000554000000000000000000000000000000000000003F00000000susemanager-schema/common/tables/rhnRegTokenConfigChannels.sql    --
-- Copyright (c) 2008 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnRegTokenConfigChannels
(
    token_id           NUMERIC NOT NULL
                           CONSTRAINT rhn_regtok_confchan_tid_fk
                               REFERENCES rhnRegToken (id)
                               ON DELETE CASCADE,
    config_channel_id  NUMERIC NOT NULL
                           CONSTRAINT rhn_regtok_confchan_ccid_fk
                               REFERENCES rhnConfigChannel (id)
                               ON DELETE CASCADE,
    position           NUMERIC NOT NULL
)

;

CREATE UNIQUE INDEX rhn_regtok_confchan_t_cc_uq
    ON rhnRegTokenConfigChannels (token_id, config_channel_id)
    ;

CREATE INDEX rhn_regtok_confchan_ccid_idx
    ON rhnRegTokenConfigChannels (config_channel_id)
    ;

07070100000123000081B400000000000000000000000167AE1114000004DD000000000000000000000000000000000000003C00000000susemanager-schema/common/tables/rhnRegTokenEntitlement.sql   --
-- Copyright (c) 2008 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnRegTokenEntitlement
(
    reg_token_id          NUMERIC NOT NULL
                              CONSTRAINT rhn_reg_tok_ent_rtid_fk
                                  REFERENCES rhnRegToken (id)
                                  ON DELETE CASCADE,
    server_group_type_id  NUMERIC NOT NULL
                              CONSTRAINT rhn_reg_tok_ent_sgtid_fk
                                  REFERENCES rhnServerGroupType (id)
                                  ON DELETE CASCADE
)

;

CREATE UNIQUE INDEX rhn_rte_rtid_sgtid_uq_idx
    ON rhnRegTokenEntitlement (reg_token_id, server_group_type_id)
    
    ;

   07070100000124000081B400000000000000000000000167AE11140000053E000000000000000000000000000000000000003600000000susemanager-schema/common/tables/rhnResetPassword.sql --
-- Copyright (c) 2015 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnResetPassword
(
    id            NUMERIC NOT NULL
                      CONSTRAINT rhn_rstpwd_id_pk primary key,
    user_id       NUMERIC NOT NULL
                      CONSTRAINT rhn_rstpwd_uid_fk REFERENCES web_contact (id)
                      ON DELETE CASCADE,
    token         VARCHAR(64) NOT NULL
                      CONSTRAINT rhn_rstpwd_token_uq UNIQUE,
    is_valid      char(1) DEFAULT ('Y') NOT NULL
                      CONSTRAINT rhn_rstpwd_is_valid_ck CHECK (is_valid IN ('Y', 'N')),
    created       TIMESTAMPTZ DEFAULT (current_timestamp) NOT NULL,
    modified      TIMESTAMPTZ DEFAULT (current_timestamp) NOT NULL
);

CREATE SEQUENCE rhn_reset_password_id_seq START WITH 500;
  07070100000125000081B400000000000000000000000167AE11140000048E000000000000000000000000000000000000003700000000susemanager-schema/common/tables/rhnRegTokenGroups.sql    --
-- Copyright (c) 2008 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnRegTokenGroups
(
    token_id         NUMERIC NOT NULL
                         CONSTRAINT rhn_reg_tok_grp_id_fk
                             REFERENCES rhnRegToken (id)
                             ON DELETE CASCADE,
    server_group_id  NUMERIC NOT NULL
                         CONSTRAINT rhn_reg_tok_grp_sgs_fk
                             REFERENCES rhnServerGroup (id)
                             ON DELETE CASCADE
)

;

CREATE UNIQUE INDEX rhn_reg_tok_grp_uq
    ON rhnRegTokenGroups (token_id, server_group_id)
    ;

  07070100000126000081B400000000000000000000000167AE1114000004C9000000000000000000000000000000000000003B00000000susemanager-schema/common/tables/rhnRegTokenOrgDefault.sql    --
-- Copyright (c) 2008 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnRegTokenOrgDefault
(
    org_id        NUMERIC NOT NULL
                      CONSTRAINT rhn_reg_token_def_oid_fk
                          REFERENCES web_customer (id)
                          ON DELETE CASCADE,
    reg_token_id  NUMERIC
                      CONSTRAINT rhn_reg_token_def_tokid_fk
                          REFERENCES rhnRegToken (id)
                          ON DELETE CASCADE
)

;

CREATE UNIQUE INDEX rhn_reg_token_def_org_id_idx
    ON rhnRegTokenOrgDefault (org_id);

CREATE INDEX rhn_reg_token_def_uid_idx
    ON rhnRegTokenOrgDefault (reg_token_id, org_id);

   07070100000127000081B400000000000000000000000167AE11140000057C000000000000000000000000000000000000003900000000susemanager-schema/common/tables/rhnRegTokenPackages.sql  --
-- Copyright (c) 2008--2010 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnRegTokenPackages
(
    id        NUMERIC NOT NULL
                  CONSTRAINT rhn_reg_tok_pkg_id_pk PRIMARY KEY,
    token_id  NUMERIC NOT NULL
                  CONSTRAINT rhn_reg_tok_pkg_id_fk
                      REFERENCES rhnRegToken (id)
                      ON DELETE CASCADE,
    name_id   NUMERIC NOT NULL
                  CONSTRAINT rhn_reg_tok_pkg_sgs_fk
                      REFERENCES rhnPackageName (id)
                      ON DELETE CASCADE,
    arch_id   NUMERIC
                  CONSTRAINT rhn_reg_tok_pkg_aid_fk
                      REFERENCES rhnPackageArch (id)
                      ON DELETE CASCADE
)

;

CREATE INDEX rhn_reg_tok_pkg_nid_idx
    ON rhnRegtokenPackages (name_id)
    ;

CREATE SEQUENCE rhn_reg_tok_pkg_id_seq;

07070100000128000081B400000000000000000000000167AE11140000055D000000000000000000000000000000000000003A00000000susemanager-schema/common/tables/rhnReleaseChannelMap.sql --
-- Copyright (c) 2008--2010 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnReleaseChannelMap
(
    product          VARCHAR(64) NOT NULL,
    version          VARCHAR(64) NOT NULL,
    release          VARCHAR(64) NOT NULL,
    channel_arch_id  NUMERIC NOT NULL
                     CONSTRAINT rhn_rcm_caid_fk
                        REFERENCES rhnChannelArch (id),
    channel_id       NUMERIC NOT NULL
                     CONSTRAINT rhn_rcm_cid_fk
                        REFERENCES rhnChannel (id)
                        ON DELETE CASCADE
)

;

CREATE INDEX rhn_rcm_prod_ver_rel_caid_idx
    ON rhnReleaseChannelMap (product, version, release, channel_arch_id)
    ;

ALTER TABLE rhnReleaseChannelMap
    ADD CONSTRAINT rhn_rcm_pva_def_uniq
    UNIQUE (product, version, channel_arch_id, release);
   07070100000129000081B400000000000000000000000167AE1114000004F2000000000000000000000000000000000000003700000000susemanager-schema/common/tables/rhnRepoRegenQueue.sql    --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnRepoRegenQueue
(
    id              NUMERIC
                        CONSTRAINT rhn_reporegenq_id_pk PRIMARY KEY,
    channel_label   VARCHAR(128) NOT NULL,
    client          VARCHAR(128),
    reason          VARCHAR(128),
    force           CHAR(1),
    bypass_filters  CHAR(1),
    next_action     TIMESTAMPTZ
                        DEFAULT (current_timestamp),
    created         TIMESTAMPTZ
                        DEFAULT (current_timestamp) NOT NULL,
    modified        TIMESTAMPTZ
                        DEFAULT (current_timestamp) NOT NULL
)
;

CREATE SEQUENCE rhn_repo_regen_queue_id_seq START WITH 101;

  0707010000012A000081B400000000000000000000000167AE1114000003AE000000000000000000000000000000000000003E00000000susemanager-schema/common/tables/rhnSGTypeBaseAddonCompat.sql --
-- Copyright (c) 2008 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnSGTypeBaseAddonCompat
(
    base_id   NUMERIC NOT NULL
                  CONSTRAINT rhn_sgt_bac_bid_fk
                      REFERENCES rhnServerGroupType (id),
    addon_id  NUMERIC NOT NULL
                  CONSTRAINT rhn_sgt_bac_aid_fk
                      REFERENCES rhnServerGroupType (id)
)

;

  0707010000012B000081B400000000000000000000000167AE111400000D85000000000000000000000000000000000000002F00000000susemanager-schema/common/tables/rhnServer.sql    --
-- Copyright (c) 2008--2014 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnServer
(
    id                  NUMERIC NOT NULL
                            CONSTRAINT rhn_server_id_pk PRIMARY KEY
                            ,
    org_id              NUMERIC NOT NULL
                            CONSTRAINT rhn_server_oid_fk
                                REFERENCES web_customer (id)
                                ON DELETE CASCADE,
    digital_server_id   VARCHAR(1024) NOT NULL,
    server_arch_id      NUMERIC NOT NULL
                            CONSTRAINT rhn_server_said_fk
                                REFERENCES rhnServerArch (id),
    os                  VARCHAR(64) NOT NULL,
    release             VARCHAR(64) NOT NULL,
    name                VARCHAR(128),
    description         VARCHAR(256),
    info                VARCHAR(128),
    secret              VARCHAR(64) NOT NULL,
    creator_id          NUMERIC
                            CONSTRAINT rhn_server_creator_fk
                                REFERENCES web_contact (id)
                                ON DELETE SET NULL,
    auto_update         CHAR(1)
                            DEFAULT ('N') NOT NULL
                            CONSTRAINT rhn_server_update_ck
                                CHECK (auto_update in ('Y', 'N')),
    contact_method_id   NUMERIC
                            DEFAULT (0) NOT NULL
                            CONSTRAINT rhn_server_cmid_fk
                                REFERENCES suseServerContactMethod (id),
    running_kernel      VARCHAR(64),
    last_boot           NUMERIC
                            DEFAULT (0) NOT NULL,
    provision_state_id  NUMERIC
                            CONSTRAINT rhn_server_psid_fk
                                REFERENCES rhnProvisionState (id),
    channels_changed    TIMESTAMPTZ,
    cobbler_id          VARCHAR(64),
    machine_id          VARCHAR(256),
    hostname            VARCHAR(128),
    payg                CHAR(1) DEFAULT ('N') NOT NULL,
    maintenance_schedule_id NUMERIC
                            CONSTRAINT rhn_server_mtsched_id_fk
                                REFERENCES suseMaintenanceSchedule (id)
                                ON DELETE SET NULL,
    created             TIMESTAMPTZ
                            DEFAULT (current_timestamp) NOT NULL,
    modified            TIMESTAMPTZ
                            DEFAULT (current_timestamp) NOT NULL
)

;

CREATE UNIQUE INDEX rhn_server_dsid_uq
    ON rhnServer (digital_server_id)
    ;

CREATE INDEX rhn_server_oid_id_idx
    ON rhnServer (org_id, id)
    
    ;

CREATE INDEX rhn_server_created_id_idx
    ON rhnServer (created, id)
    
    ;

CREATE INDEX rhn_server_creator_idx
    ON rhnServer (creator_id)
    
    ;

CREATE INDEX rhn_server_hostname_idx
    ON rhnServer (hostname)
    
    ;

CREATE SEQUENCE rhn_server_id_seq START WITH 1000010000;
   0707010000012C000081B400000000000000000000000167AE11140000074B000000000000000000000000000000000000003500000000susemanager-schema/common/tables/rhnServerAction.sql  --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnServerAction
(
    server_id        NUMERIC NOT NULL
                         CONSTRAINT rhn_server_action_sid_fk
                             REFERENCES rhnServer (id),
    action_id        NUMERIC NOT NULL
                         CONSTRAINT rhn_server_action_aid_fk
                             REFERENCES rhnAction (id)
                             ON DELETE CASCADE,
    status           NUMERIC NOT NULL
                         CONSTRAINT rhn_server_action_status_fk
                             REFERENCES rhnActionStatus (id),
    result_code      NUMERIC,
    result_msg       TEXT,
    pickup_time      TIMESTAMPTZ,
    remaining_tries  NUMERIC
                         DEFAULT (5) NOT NULL,
    completion_time  TIMESTAMPTZ,
    created          TIMESTAMPTZ
                         DEFAULT (current_timestamp) NOT NULL,
    modified         TIMESTAMPTZ
                         DEFAULT (current_timestamp) NOT NULL
)

;

CREATE INDEX rhn_ser_act_sid_aid_s_idx
    ON rhnServerAction (server_id, action_id, status)
    ;

CREATE INDEX rhn_ser_act_aid_idx
    ON rhnServerAction (action_id)
    
    ;

ALTER TABLE rhnServerAction
    ADD CONSTRAINT rhn_server_action_sid_aid_uq UNIQUE (server_id, action_id);

 0707010000012D000081B400000000000000000000000167AE1114000005C2000000000000000000000000000000000000004200000000susemanager-schema/common/tables/rhnServerActionPackageResult.sql --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnServerActionPackageResult
(
    server_id          NUMERIC NOT NULL
                           CONSTRAINT rhn_sap_result_sid_fk
                               REFERENCES rhnServer (id),
    action_package_id  NUMERIC NOT NULL
                           CONSTRAINT rhn_sap_result_apid_fk
                               REFERENCES rhnActionPackage (id)
                               ON DELETE CASCADE,
    result_code        NUMERIC NOT NULL,
    stdout             BYTEA,
    stderr             BYTEA,
    created            TIMESTAMPTZ
                           DEFAULT (current_timestamp) NOT NULL,
    modified           TIMESTAMPTZ
                           DEFAULT (current_timestamp) NOT NULL
)


;

CREATE UNIQUE INDEX rhn_sap_result_sid_apid_uq
    ON rhnServerActionPackageResult (server_id, action_package_id)
    ;

  0707010000012E000081B400000000000000000000000167AE111400000661000000000000000000000000000000000000004100000000susemanager-schema/common/tables/rhnServerActionScriptResult.sql  --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnServerActionScriptResult
(
    server_id         NUMERIC NOT NULL
                          CONSTRAINT rhn_serveras_result_sid_fk
                              REFERENCES rhnServer (id),
    action_script_id  NUMERIC NOT NULL
                          CONSTRAINT rhn_serveras_result_asid_fk
                              REFERENCES rhnActionScript (id)
                              ON DELETE CASCADE,
    output            BYTEA,
    start_date        TIMESTAMPTZ NOT NULL,
    stop_date         TIMESTAMPTZ NOT NULL,
    return_code       NUMERIC NOT NULL,
    created           TIMESTAMPTZ
                          DEFAULT (current_timestamp) NOT NULL,
    modified          TIMESTAMPTZ
                          DEFAULT (current_timestamp) NOT NULL
)


;

CREATE UNIQUE INDEX rhn_serveras_result_sas_uq
    ON rhnServerActionScriptResult (server_id, action_script_id)
    ;

CREATE INDEX rhn_serveras_result_asid_idx
    ON rhnServerActionScriptResult (action_script_id)
    
    ;

   0707010000012F000081B400000000000000000000000167AE11140000087C000000000000000000000000000000000000004200000000susemanager-schema/common/tables/rhnServerActionVerifyMissing.sql --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnServerActionVerifyMissing
(
    server_id              NUMERIC NOT NULL
                               CONSTRAINT rhn_sactionvm_sid_fk
                                   REFERENCES rhnServer (id),
    action_id              NUMERIC NOT NULL
                               CONSTRAINT rhn_sactionvm_aid_fk
                                   REFERENCES rhnAction (id)
                                   ON DELETE CASCADE,
    package_name_id        NUMERIC NOT NULL
                               CONSTRAINT rhn_sactionvm_pnid_fk
                                   REFERENCES rhnPackageName (id),
    package_evr_id         NUMERIC NOT NULL
                               CONSTRAINT rhn_sactionvm_peid_fk
                                   REFERENCES rhnPackageevr (id),
    package_arch_id        NUMERIC NOT NULL
                               CONSTRAINT rhn_sactionvm_paid_fk
                                   REFERENCES rhnPackageArch (id),
    package_capability_id  NUMERIC NOT NULL
                               CONSTRAINT rhn_sactionvm_pcid_fk
                                   REFERENCES rhnPackageCapability (id),
    created                TIMESTAMPTZ
                               DEFAULT (current_timestamp) NOT NULL,
    modified               TIMESTAMPTZ
                               DEFAULT (current_timestamp) NOT NULL
)

;

CREATE UNIQUE INDEX rhn_sactionvm_sanec_uq
    ON rhnServerActionVerifyMissing (server_id, action_id, package_name_id, package_evr_id, package_arch_id, package_capability_id)
    ;

07070100000130000081B400000000000000000000000167AE111400000EF1000000000000000000000000000000000000004100000000susemanager-schema/common/tables/rhnServerActionVerifyResult.sql  --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnServerActionVerifyResult
(
    server_id              NUMERIC NOT NULL
                               CONSTRAINT rhn_sactionvr_sid_fk
                                   REFERENCES rhnServer (id),
    action_id              NUMERIC NOT NULL
                               CONSTRAINT rhn_sactionvr_aid_fk
                                   REFERENCES rhnAction (id)
                                   ON DELETE CASCADE,
    package_name_id        NUMERIC NOT NULL
                               CONSTRAINT rhn_sactionvr_pnid_fk
                                   REFERENCES rhnPackageName (id),
    package_evr_id         NUMERIC NOT NULL
                               CONSTRAINT rhn_sactionvr_peid_fk
                                   REFERENCES rhnPackageEVR (id),
    package_arch_id        NUMERIC NOT NULL
                               CONSTRAINT rhn_sactionvr_paid_fk
                                   REFERENCES rhnPackageArch (id),
    package_capability_id  NUMERIC NOT NULL
                               CONSTRAINT rhn_sactionvr_pcid_fk
                                   REFERENCES rhnPackageCapability (id),
    attribute              CHAR(1)
                               CONSTRAINT rhn_sactionvr_attr_ck
                                   CHECK (attribute in ('c','d','g','l','r')),
    size_differs           CHAR(1) NOT NULL
                               CONSTRAINT rhn_sactionvr_size_ck
                                   CHECK (size_differs in ('Y','N','?')),
    mode_differs           CHAR(1) NOT NULL
                               CONSTRAINT rhn_sactionvr_mode_ck
                                   CHECK (mode_differs in ('Y','N','?')),
    checksum_differs       CHAR(1) NOT NULL
                               CONSTRAINT rhn_sactionvr_chsum_ck
                                   CHECK (checksum_differs in ( 'Y' , 'N' , '?' )),
    devnum_differs         CHAR(1) NOT NULL
                               CONSTRAINT rhn_sactionvr_devnum_ck
                                   CHECK (devnum_differs in ('Y','N','?')),
    readlink_differs       CHAR(1) NOT NULL
                               CONSTRAINT rhn_sactionvr_readlink_ck
                                   CHECK (readlink_differs in ('Y','N','?')),
    uid_differs            CHAR(1) NOT NULL
                               CONSTRAINT rhn_sactionvr_uid_ck
                                   CHECK (uid_differs in ('Y','N','?')),
    gid_differs            CHAR(1) NOT NULL
                               CONSTRAINT rhn_sactionvr_gid_ck
                                   CHECK (gid_differs in ('Y','N','?')),
    mtime_differs          CHAR(1) NOT NULL
                               CONSTRAINT rhn_sactionvr_mtime_ck
                                   CHECK (mtime_differs in ('Y','N','?')),
    created                TIMESTAMPTZ
                               DEFAULT (current_timestamp) NOT NULL,
    modified               TIMESTAMPTZ
                               DEFAULT (current_timestamp) NOT NULL
)

;

CREATE UNIQUE INDEX rhn_sactionvr_sanec_uq
    ON rhnServerActionVerifyResult (server_id, action_id, package_name_id, package_evr_id, package_arch_id, package_capability_id)
    ;

   07070100000131000081B400000000000000000000000167AE111400000576000000000000000000000000000000000000003300000000susemanager-schema/common/tables/rhnServerArch.sql    --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnServerArch
(
    id            NUMERIC NOT NULL,
    label         VARCHAR(64) NOT NULL,
    name          VARCHAR(64) NOT NULL,
    arch_type_id  NUMERIC NOT NULL
                      CONSTRAINT rhn_sarch_atid_fk
                          REFERENCES rhnArchType (id),
    created       TIMESTAMPTZ
                      DEFAULT (current_timestamp) NOT NULL,
    modified      TIMESTAMPTZ
                      DEFAULT (current_timestamp) NOT NULL
)

;

CREATE INDEX rhn_sarch_id_l_n_idx
    ON rhnServerArch (id, label, name)
    ;

CREATE SEQUENCE rhn_server_arch_id_seq START WITH 1000;

ALTER TABLE rhnServerArch
    ADD CONSTRAINT rhn_sarch_id_pk PRIMARY KEY (id);

ALTER TABLE rhnServerArch
    ADD CONSTRAINT rhn_sarch_label_uq UNIQUE (label);

  07070100000132000081B400000000000000000000000167AE1114000004F3000000000000000000000000000000000000003600000000susemanager-schema/common/tables/rhnServerChannel.sql --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnServerChannel
(
    server_id   NUMERIC NOT NULL
                    CONSTRAINT rhn_sc_sid_fk
                        REFERENCES rhnServer (id),
    channel_id  NUMERIC NOT NULL
                    CONSTRAINT rhn_sc_cid_fk
                        REFERENCES rhnChannel (id),
    created     TIMESTAMPTZ
                    DEFAULT (current_timestamp) NOT NULL,
    modified    TIMESTAMPTZ
                    DEFAULT (current_timestamp) NOT NULL
)

;

CREATE UNIQUE INDEX rhn_sc_sid_cid_uq
    ON rhnServerChannel (server_id, channel_id)
    ;

CREATE INDEX rhn_sc_cid_idx
    ON rhnServerChannel (channel_id)
    
    ;

 07070100000133000081B400000000000000000000000167AE111400000558000000000000000000000000000000000000004000000000susemanager-schema/common/tables/rhnServerChannelArchCompat.sql   --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnServerChannelArchCompat
(
    server_arch_id   NUMERIC NOT NULL
                         CONSTRAINT rhn_sc_ac_said_fk
                             REFERENCES rhnServerArch (id),
    channel_arch_id  NUMERIC NOT NULL
                         CONSTRAINT rhn_sc_ac_caid_fk
                             REFERENCES rhnChannelArch (id),
    created          TIMESTAMPTZ
                         DEFAULT (current_timestamp) NOT NULL,
    modified         TIMESTAMPTZ
                         DEFAULT (current_timestamp) NOT NULL
)

;

CREATE INDEX rhn_sc_ac_caid_paid
    ON rhnServerChannelArchCompat (server_arch_id, channel_arch_id)
    ;

CREATE INDEX rhn_sc_ac_caid
    ON rhnServerChannelArchCompat (channel_arch_id)
    ;

07070100000134000081B400000000000000000000000167AE1114000005C6000000000000000000000000000000000000003C00000000susemanager-schema/common/tables/rhnServerConfigChannel.sql   --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnServerConfigChannel
(
    server_id          NUMERIC NOT NULL
                           CONSTRAINT rhn_servercc_sid_fk
                               REFERENCES rhnServer (id),
    config_channel_id  NUMERIC NOT NULL
                           CONSTRAINT rhn_servercc_ccid_fk
                               REFERENCES rhnConfigChannel (id)
                               ON DELETE CASCADE,
    position           NUMERIC,
    created            TIMESTAMPTZ
                           DEFAULT (current_timestamp) NOT NULL,
    modified           TIMESTAMPTZ
                           DEFAULT (current_timestamp) NOT NULL
)

;

CREATE UNIQUE INDEX rhn_servercc_sid_ccid_uq
    ON rhnServerConfigChannel (server_id, config_channel_id)
    ;

CREATE INDEX rhn_servercc_ccid_idx
    ON rhnServerConfigChannel (config_channel_id)
    ;

  07070100000135000081B400000000000000000000000167AE1114000006E0000000000000000000000000000000000000003E00000000susemanager-schema/common/tables/rhnServerCustomDataValue.sql --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnServerCustomDataValue
(
    server_id         NUMERIC NOT NULL
                          CONSTRAINT rhn_scdv_sid_fk
                              REFERENCES rhnServer (id),
    key_id            NUMERIC NOT NULL
                          CONSTRAINT rhn_scdv_kid_fk
                              REFERENCES rhnCustomDataKey (id),
    value             VARCHAR(4000),
    created_by        NUMERIC
                          CONSTRAINT rhn_scdv_cb_fk
                              REFERENCES web_contact (id)
                              ON DELETE SET NULL,
    last_modified_by  NUMERIC
                          CONSTRAINT rhn_scdv_lmb_fk
                              REFERENCES web_contact (id)
                              ON DELETE SET NULL,
    created           TIMESTAMPTZ
                          DEFAULT (current_timestamp) NOT NULL,
    modified          TIMESTAMPTZ
                          DEFAULT (current_timestamp) NOT NULL
)

;

CREATE UNIQUE INDEX rhn_scdv_sid_kid_uq
    ON rhnServerCustomDataValue (server_id, key_id);

CREATE INDEX rhn_scdv_kid_idx
    ON rhnServerCustomDataValue (key_id);

07070100000136000081B400000000000000000000000167AE1114000005D1000000000000000000000000000000000000003200000000susemanager-schema/common/tables/rhnServerDMI.sql --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnServerDMI
(
    id            NUMERIC NOT NULL
                      CONSTRAINT rhn_server_dmi_pk PRIMARY KEY
                      ,
    server_id     NUMERIC NOT NULL
                      CONSTRAINT rhn_server_dmi_sid_fk
                          REFERENCES rhnServer (id),
    vendor        VARCHAR(256),
    system        VARCHAR(256),
    product       VARCHAR(256),
    bios_vendor   VARCHAR(256),
    bios_version  VARCHAR(256),
    bios_release  VARCHAR(256),
    asset         VARCHAR(256),
    board         VARCHAR(256),
    created       TIMESTAMPTZ
                      DEFAULT (current_timestamp) NOT NULL,
    modified      TIMESTAMPTZ
                      DEFAULT (current_timestamp) NOT NULL
)

;

CREATE UNIQUE INDEX rhn_server_dmi_sid_uq
    ON rhnServerDMI (server_id)
    
    ;

CREATE SEQUENCE rhn_server_dmi_id_seq;

   07070100000137000081B400000000000000000000000167AE1114000004B8000000000000000000000000000000000000003400000000susemanager-schema/common/tables/rhnServerEvent.sql   --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnServerEvent
(
    id         NUMERIC NOT NULL
                   CONSTRAINT rhn_se_id_pk PRIMARY KEY
                   ,
    server_id  NUMERIC NOT NULL
                   CONSTRAINT rhn_se_server_id_fk
                       REFERENCES rhnServer (id),
    details    VARCHAR(4000) NOT NULL,
    created    TIMESTAMPTZ
                   DEFAULT (current_timestamp) NOT NULL,
    modified   TIMESTAMPTZ
                   DEFAULT (current_timestamp) NOT NULL
)

;

CREATE INDEX rhn_se_idx
    ON rhnServerEvent (server_id)
    ;

CREATE SEQUENCE rhn_se_id_seq;

07070100000138000081B400000000000000000000000167AE11140000050A000000000000000000000000000000000000003300000000susemanager-schema/common/tables/rhnServerFQDN.sql    --
-- Copyright (c) 2017 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.

CREATE TABLE rhnServerFQDN
(
    id         NUMERIC NOT NULL
                   CONSTRAINT rhn_serverfqdn_id_pk PRIMARY KEY
                   ,
    name       VARCHAR(253) NOT NULL,
    server_id  NUMERIC NOT NULL
                   CONSTRAINT rhn_serverfqdn_sid_fk
                       REFERENCES rhnServer (id),
    is_primary CHAR(1) DEFAULT ('N') NOT NULL,
    created    TIMESTAMPTZ
                   DEFAULT (current_timestamp) NOT NULL,
    modified   TIMESTAMPTZ
                   DEFAULT (current_timestamp) NOT NULL
)

;

CREATE SEQUENCE rhn_serverfqdn_id_seq;

CREATE UNIQUE INDEX rhn_server_fqdn_name_id_idx
    ON rhnServerFQDN (name, server_id)
    
    ;

  07070100000139000081B400000000000000000000000167AE1114000006C1000000000000000000000000000000000000003400000000susemanager-schema/common/tables/rhnServerGroup.sql   --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnServerGroup
(
    id               NUMERIC NOT NULL
                         CONSTRAINT rhn_servergroup_id_pk PRIMARY KEY
                         ,
    name             VARCHAR(64) NOT NULL,
    description      VARCHAR(1024) NOT NULL,
    current_members  NUMERIC
                         DEFAULT (0) NOT NULL,
    group_type       NUMERIC
                         CONSTRAINT rhn_servergroup_type_fk
                             REFERENCES rhnServerGroupType (id),
    org_id           NUMERIC NOT NULL
                         CONSTRAINT rhn_servergroup_oid_fk
                             REFERENCES web_customer (id)
                             ON DELETE CASCADE,
    created          TIMESTAMPTZ
                         DEFAULT (current_timestamp) NOT NULL,
    modified         TIMESTAMPTZ
                         DEFAULT (current_timestamp) NOT NULL
)

;

CREATE UNIQUE INDEX rhn_servergroup_oid_name_uq
    ON rhnServerGroup (org_id, name)
    ;

CREATE INDEX rhn_sg_type_id_idx
    ON rhnServerGroup (group_type, id)
    
    ;

CREATE SEQUENCE rhn_server_group_id_seq;

   0707010000013A000081B400000000000000000000000167AE111400000559000000000000000000000000000000000000003B00000000susemanager-schema/common/tables/rhnServerGroupMembers.sql    --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnServerGroupMembers
(
    server_id        NUMERIC NOT NULL
                         CONSTRAINT rhn_sg_members_fk
                             REFERENCES rhnServer (id),
    server_group_id  NUMERIC NOT NULL
                         CONSTRAINT rhn_sg_groups_fk
                             REFERENCES rhnServerGroup (id),
    created          TIMESTAMPTZ
                         DEFAULT (current_timestamp) NOT NULL,
    modified         TIMESTAMPTZ
                         DEFAULT (current_timestamp) NOT NULL
)

;

CREATE UNIQUE INDEX rhn_sgmembers_sid_sgid_uq
    ON rhnServerGroupMembers (server_id, server_group_id)
    ;

CREATE INDEX rhn_sgmembers_sgid_idx
    ON rhnServerGroupMembers (server_group_id)
    
    ;

   0707010000013B000081B400000000000000000000000167AE1114000005EA000000000000000000000000000000000000003800000000susemanager-schema/common/tables/rhnServerGroupType.sql   --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnServerGroupType
(
    id         NUMERIC NOT NULL
                   CONSTRAINT rhn_servergrouptype_id_pk PRIMARY KEY
                   ,
    label      VARCHAR(32) NOT NULL,
    name       VARCHAR(64) NOT NULL,
    created    TIMESTAMPTZ
                   DEFAULT (current_timestamp) NOT NULL,
    modified   TIMESTAMPTZ
                   DEFAULT (current_timestamp) NOT NULL,
    permanent  CHAR
                   DEFAULT ('Y') NOT NULL
                   CONSTRAINT rhn_servergrouptype_perm_ck
                       CHECK (permanent in ('Y','N')),
    is_base    CHAR
                   DEFAULT ('Y') NOT NULL
                   CONSTRAINT rhn_servergrouptype_isbase_ck
                       CHECK (is_base in ('Y','N'))
)

;

CREATE UNIQUE INDEX rhn_servergrouptype_label_uq
    ON rhnServerGroupType (label)
    ;

CREATE SEQUENCE rhn_servergroup_type_seq;

  0707010000013C000081B400000000000000000000000167AE11140000053F000000000000000000000000000000000000003F00000000susemanager-schema/common/tables/rhnServerGroupTypeFeature.sql    --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnServerGroupTypeFeature
(
    server_group_type_id  NUMERIC NOT NULL
                              CONSTRAINT rhn_sgt_sgid_fk
                                  REFERENCES rhnServerGroupType (id),
    feature_id            NUMERIC NOT NULL
                              CONSTRAINT rhn_sgt_fid_fk
                                  REFERENCES rhnFeature (id),
    created               TIMESTAMPTZ
                              DEFAULT (current_timestamp) NOT NULL,
    modified              TIMESTAMPTZ
                              DEFAULT (current_timestamp) NOT NULL
)

;

CREATE UNIQUE INDEX rhn_sgt_feat_sgtid_fid_uq_idx
    ON rhnServerGroupTypeFeature (server_group_type_id, feature_id)
    ;

 0707010000013D000081B400000000000000000000000167AE1114000004DC000000000000000000000000000000000000003600000000susemanager-schema/common/tables/rhnServerHistory.sql --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnServerHistory
(
    id         NUMERIC NOT NULL
                   CONSTRAINT rhn_serverhistory_id_pk PRIMARY KEY
                   ,
    server_Id  NUMERIC NOT NULL
                   CONSTRAINT rhn_serverhistory_sid_fk
                       REFERENCES rhnServer (id),
    summary    VARCHAR(256) NOT NULL,
    details    VARCHAR(4000),
    created    TIMESTAMPTZ
                   DEFAULT (current_timestamp) NOT NULL,
    modified   TIMESTAMPTZ
                   DEFAULT (current_timestamp) NOT NULL
)

;

CREATE INDEX rhn_server_hist_server_id_idx
    ON rhnServerHistory (server_id)
    ;

0707010000013E000081B400000000000000000000000167AE111400000424000000000000000000000000000000000000003300000000susemanager-schema/common/tables/rhnServerInfo.sql    --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnServerInfo
(
    server_id        NUMERIC NOT NULL
                         CONSTRAINT rhn_server_info_sid_fk
                             REFERENCES rhnServer (id),
    checkin          TIMESTAMPTZ
                         DEFAULT (current_timestamp),
    checkin_counter  NUMERIC
                         DEFAULT (0)
)


;

CREATE UNIQUE INDEX rhn_server_info_sid_unq
    ON rhnServerInfo (server_id)
    
    ;

0707010000013F000081B400000000000000000000000167AE11140000057F000000000000000000000000000000000000003A00000000susemanager-schema/common/tables/rhnServerInstallInfo.sql --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnServerInstallInfo
(
    id              NUMERIC NOT NULL
                        CONSTRAINT rhn_server_install_info_id_pk PRIMARY KEY
                        ,
    server_id       NUMERIC NOT NULL
                        CONSTRAINT rhn_server_install_info_sid_fk
                            REFERENCES rhnServer (id),
    install_method  VARCHAR(32) NOT NULL,
    iso_status      NUMERIC,
    mediasum        VARCHAR(64),
    created         TIMESTAMPTZ
                        DEFAULT (current_timestamp) NOT NULL,
    modified        TIMESTAMPTZ
                        DEFAULT (current_timestamp) NOT NULL
)

;

CREATE UNIQUE INDEX rhn_server_install_info_sid_uq
    ON rhnServerInstallInfo (server_id)
    ;

CREATE SEQUENCE rhn_server_install_info_id_seq;

 07070100000140000081B400000000000000000000000167AE1114000005C3000000000000000000000000000000000000003700000000susemanager-schema/common/tables/rhnServerLocation.sql    --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnServerLocation
(
    id         NUMERIC NOT NULL
                   CONSTRAINT rhn_serverlocation_id_pk PRIMARY KEY
                   ,
    server_id  NUMERIC NOT NULL
                   CONSTRAINT rhn_serverlocation_sid_fk
                       REFERENCES rhnServer (id),
    machine    VARCHAR(64),
    rack       VARCHAR(64),
    room       VARCHAR(32),
    building   VARCHAR(128),
    address1   VARCHAR(128),
    address2   VARCHAR(128),
    city       VARCHAR(128),
    state      VARCHAR(60),
    country    CHAR(2),
    created    TIMESTAMPTZ
                   DEFAULT (current_timestamp) NOT NULL,
    modified   TIMESTAMPTZ
                   DEFAULT (current_timestamp) NOT NULL
)

;

CREATE UNIQUE INDEX rhn_serverlocation_sid_uq
    ON rhnServerLocation (server_id)
    ;

CREATE SEQUENCE rhn_server_loc_id_seq;

 07070100000141000081B400000000000000000000000167AE1114000004DB000000000000000000000000000000000000003300000000susemanager-schema/common/tables/rhnServerLock.sql    --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnServerLock
(
    server_id  NUMERIC NOT NULL
                   CONSTRAINT rhn_server_lock_sid_fk
                       REFERENCES rhnServer (id),
    locker_id  NUMERIC
                   CONSTRAINT rhn_server_lock_lid_fk
                       REFERENCES web_contact (id)
                       ON DELETE SET NULL,
    reason     VARCHAR(4000),
    created    TIMESTAMPTZ
                   DEFAULT (current_timestamp) NOT NULL
)

;

CREATE UNIQUE INDEX rhn_server_lock_sid_unq
    ON rhnServerLock (server_id)
    ;

CREATE INDEX rhn_server_lock_lid_unq
    ON rhnServerLock (locker_id)
    ;

 07070100000142000081B400000000000000000000000167AE1114000006FF000000000000000000000000000000000000003A00000000susemanager-schema/common/tables/rhnServerNeededCache.sql --
-- Copyright (c) 2008--2013 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnServerNeededCache
(
    server_id   NUMERIC NOT NULL
                    CONSTRAINT rhn_sncp_sid_fk
                        REFERENCES rhnServer (id)
                        ON DELETE CASCADE,
    errata_id   NUMERIC
                    CONSTRAINT rhn_sncp_eid_fk
                        REFERENCES rhnErrata (id)
                        ON DELETE CASCADE,
    package_id  NUMERIC NOT NULL
                    CONSTRAINT rhn_sncp_pid_fk
                        REFERENCES rhnPackage (id)
                        ON DELETE CASCADE,
    channel_id   NUMERIC
                    CONSTRAINT rhn_sncp_cid_fk
                        REFERENCES rhnChannel (id)
                        ON DELETE CASCADE
)


;

CREATE INDEX rhn_snc_pid_idx
    ON rhnServerNeededCache (package_id)
    
    
    ;

CREATE INDEX rhn_snc_eid_idx
    ON rhnServerNeededCache (errata_id)
    
    ;

CREATE INDEX rhn_snc_cid_idx
    ON rhnServerNeededCache (channel_id)
    
    ;

CREATE INDEX rhn_snc_seid_idx
    ON rhnServerNeededCache (server_id, errata_id);

CREATE INDEX rhn_snc_speid_idx
    ON rhnServerNeededCache (server_id, package_id, errata_id)
    
    
    ;
 07070100000143000081B400000000000000000000000167AE111400000538000000000000000000000000000000000000003A00000000susemanager-schema/common/tables/rhnServerNetAddress4.sql --
-- Copyright (c) 2011--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnServerNetAddress4
(
    interface_id  NUMERIC NOT NULL
                   CONSTRAINT rhn_srv_net_iaddress4_iid_fk
                       REFERENCES rhnServerNetInterface (id)
                       ON DELETE CASCADE,
    address    VARCHAR(64),
    netmask    VARCHAR(64),
    broadcast  VARCHAR(64),
    created    TIMESTAMPTZ
                   DEFAULT (current_timestamp) NOT NULL,
    modified   TIMESTAMPTZ
                   DEFAULT (current_timestamp) NOT NULL
)

;

CREATE INDEX rhn_srv_net_addr4_iid_addr_idx
    ON rhnServerNetAddress4 (interface_id, address)
    ;

ALTER TABLE rhnServerNetAddress4
    ADD CONSTRAINT rhn_srv_net_addr4_iid_addr_uq UNIQUE (interface_id, address);
07070100000144000081B400000000000000000000000167AE111400000544000000000000000000000000000000000000003A00000000susemanager-schema/common/tables/rhnServerNetAddress6.sql --
-- Copyright (c) 2011--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnServerNetAddress6
(
    interface_id  NUMERIC NOT NULL
                   CONSTRAINT rhn_srv_net_iaddress6_iid_fk
                       REFERENCES rhnServerNetInterface (id)
                       ON DELETE CASCADE,
    address    VARCHAR(45),
    netmask    VARCHAR(49),
    scope      VARCHAR(64),
    created    TIMESTAMPTZ
                   DEFAULT (current_timestamp) NOT NULL,
    modified   TIMESTAMPTZ
                   DEFAULT (current_timestamp) NOT NULL
)

;

CREATE INDEX rhn_srv_net_ad6_iid_sc_ad_idx
    ON rhnServerNetAddress6 (interface_id, scope, address)
    ;

ALTER TABLE rhnServerNetAddress6
    ADD CONSTRAINT rhn_srv_net_ad6_iid_sc_ad_uq UNIQUE (interface_id, scope, address);
07070100000145000081B400000000000000000000000167AE111400000619000000000000000000000000000000000000003B00000000susemanager-schema/common/tables/rhnServerNetInterface.sql    --
-- Copyright (c) 2008 -- 2011 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnServerNetInterface
(
    id         NUMERIC NOT NULL
                   CONSTRAINT rhn_srv_net_iface_id_pk PRIMARY KEY
                       ,
    server_id  NUMERIC NOT NULL
                   CONSTRAINT rhn_srv_net_iface_sid_fk
                       REFERENCES rhnServer (id),
    name       VARCHAR(32) NOT NULL,
    hw_addr    VARCHAR(96),
    module     VARCHAR(128),
    is_primary VARCHAR(1),
    created    TIMESTAMPTZ
                   DEFAULT (current_timestamp) NOT NULL,
    modified   TIMESTAMPTZ
                   DEFAULT (current_timestamp) NOT NULL
)

;

CREATE INDEX rhn_srv_net_iface_sid_name_idx
    ON rhnServerNetInterface (server_id, name)
    ;

CREATE INDEX rhn_srv_net_iface_hw_addr_idx
    ON rhnServerNetInterface (hw_addr)
    ;

ALTER TABLE rhnServerNetInterface
    ADD CONSTRAINT rhn_srv_net_iface_sid_name_uq UNIQUE (server_id, name);

CREATE SEQUENCE rhn_srv_net_iface_id_seq;
   07070100000146000081B400000000000000000000000167AE1114000005FE000000000000000000000000000000000000003400000000susemanager-schema/common/tables/rhnServerNotes.sql   --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnServerNotes
(
    id         NUMERIC NOT NULL
                   CONSTRAINT rhn_servernotes_id_pk PRIMARY KEY
                   ,
    creator    NUMERIC
                   CONSTRAINT rhn_servernotes_creator_fk
                       REFERENCES web_contact (id)
                       ON DELETE SET NULL,
    server_id  NUMERIC NOT NULL
                   CONSTRAINT rhn_servernotes_sid_fk
                       REFERENCES rhnServer (id),
    subject    VARCHAR(80) NOT NULL,
    note       VARCHAR(4000),
    created    TIMESTAMPTZ
                   DEFAULT (current_timestamp) NOT NULL,
    modified   TIMESTAMPTZ
                   DEFAULT (current_timestamp) NOT NULL
)

;

CREATE INDEX rhn_servernotes_sid_idx
    ON rhnServerNotes (server_id)
    
    ;

CREATE INDEX rhn_servernotes_creator_idx
    ON rhnServerNotes (creator)
    
    ;

CREATE SEQUENCE rhn_server_note_id_seq;

  07070100000147000081B400000000000000000000000167AE1114000005C7000000000000000000000000000000000000003600000000susemanager-schema/common/tables/rhnServerPackage.sql --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnServerPackage
(
    server_id        NUMERIC NOT NULL
                         REFERENCES rhnServer (id)
                             ON DELETE CASCADE,
    name_id          NUMERIC NOT NULL
                         REFERENCES rhnPackageName (id),
    evr_id           NUMERIC NOT NULL
                         REFERENCES rhnPackageEVR (id),
    package_arch_id  NUMERIC
                         REFERENCES rhnPackageArch (id),
    created          TIMESTAMPTZ
                         DEFAULT (current_timestamp) NOT NULL,
    installtime      TIMESTAMPTZ
)


;

CREATE UNIQUE INDEX rhn_sp_snep_uq
    ON rhnServerPackage (server_id, name_id, evr_id, package_arch_id)
    
    ;

CREATE INDEX rhn_sp_sien_idx
    ON rhnServerPackage USING btree (server_id, installtime, evr_id, name_id);

CREATE SEQUENCE rhn_server_package_id_seq;

 07070100000148000081B400000000000000000000000167AE11140000068D000000000000000000000000000000000000004000000000susemanager-schema/common/tables/rhnServerPackageArchCompat.sql   --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnServerPackageArchCompat
(
    server_arch_id   NUMERIC NOT NULL
                         CONSTRAINT rhn_sp_ac_said_fk
                             REFERENCES rhnServerArch (id),
    package_arch_id  NUMERIC NOT NULL
                         CONSTRAINT rhn_sp_ac_paid_fk
                             REFERENCES rhnPackageArch (id),
    preference       NUMERIC NOT NULL,
    created          TIMESTAMPTZ
                         DEFAULT (current_timestamp) NOT NULL,
    modified         TIMESTAMPTZ
                         DEFAULT (current_timestamp) NOT NULL
)

;

CREATE INDEX rhn_sp_ac_said_paid_pref
    ON rhnServerPackageArchCompat (server_arch_id, package_arch_id, preference)
    ;

CREATE INDEX rhn_sp_ac_paid_pref
    ON rhnServerPackageArchCompat (package_arch_id)
    ;

ALTER TABLE rhnServerPackageArchCompat
    ADD CONSTRAINT rhn_sp_ac_said_paid_uq UNIQUE (server_arch_id, package_arch_id);

ALTER TABLE rhnServerPackageArchCompat
    ADD CONSTRAINT rhn_sp_ac_pref_said_uq UNIQUE (preference, server_arch_id)
    ;

   07070100000149000081B400000000000000000000000167AE1114000005AE000000000000000000000000000000000000003300000000susemanager-schema/common/tables/rhnServerPath.sql    --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnServerPath
(
    server_id        NUMERIC NOT NULL
                         CONSTRAINT rhn_serverpath_sid_fk
                             REFERENCES rhnServer (id),
    proxy_server_id  NUMERIC NOT NULL
                         CONSTRAINT rhn_serverpath_psid_fk
                             REFERENCES rhnServer (id),
    position         NUMERIC NOT NULL,
    hostname         VARCHAR(256) NOT NULL,
    created          TIMESTAMPTZ
                         DEFAULT (current_timestamp) NOT NULL,
    modified         TIMESTAMPTZ
                         DEFAULT (current_timestamp) NOT NULL,

    CONSTRAINT rhn_serverpath_sid_pos UNIQUE
        (server_id, position) DEFERRABLE INITIALLY DEFERRED
)

;

CREATE UNIQUE INDEX rhn_serverpath_psid_sid_uq
    ON rhnServerPath (proxy_server_id, server_id)
    ;

  0707010000014A000081B400000000000000000000000167AE11140000056F000000000000000000000000000000000000003F00000000susemanager-schema/common/tables/rhnServerPreserveFileList.sql    --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnServerPreserveFileList
(
    server_id     NUMERIC NOT NULL
                      CONSTRAINT rhn_serverpfl_ksid_fk
                          REFERENCES rhnServer (id),
    file_list_id  NUMERIC NOT NULL
                      CONSTRAINT rhn_serverpfl_flid_fk
                          REFERENCES rhnFileList (id)
                          ON DELETE CASCADE,
    created       TIMESTAMPTZ
                      DEFAULT (current_timestamp) NOT NULL,
    modified      TIMESTAMPTZ
                      DEFAULT (current_timestamp) NOT NULL
)

;

CREATE UNIQUE INDEX rhn_serverpfl_ksid_flid_uq
    ON rhnServerPreserveFileList (server_id, file_list_id)
    ;

CREATE INDEX rhn_serverpfl_flid_idx
    ON rhnServerPreserveFileList (file_list_id)
    ;

 0707010000014B000081B400000000000000000000000167AE1114000007A0000000000000000000000000000000000000003600000000susemanager-schema/common/tables/rhnServerProfile.sql --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnServerProfile
(
    id               NUMERIC NOT NULL,
    org_id           NUMERIC NOT NULL
                         CONSTRAINT rhn_server_profile_oid_fk
                             REFERENCES web_customer (id)
                             ON DELETE CASCADE,
    base_channel     NUMERIC NOT NULL
                         CONSTRAINT rhn_server_profile_bcid_fk
                             REFERENCES rhnChannel (id),
    name             VARCHAR(128),
    description      VARCHAR(256),
    info             VARCHAR(128),
    profile_type_id  NUMERIC NOT NULL
                         CONSTRAINT rhn_server_profile_ptype_fk
                             REFERENCES rhnServerProfileType (id),
    created          TIMESTAMPTZ
                         DEFAULT (current_timestamp) NOT NULL,
    modified         TIMESTAMPTZ
                         DEFAULT (current_timestamp) NOT NULL
)

;

CREATE UNIQUE INDEX rhn_server_profile_noid_uq
    ON rhnServerProfile (org_id, name)
    ;

CREATE INDEX rhn_sprofile_id_oid_bc_idx
    ON rhnServerProfile (id, org_id, base_channel)
    ;

CREATE INDEX rhn_server_profile_bc_idx
    ON rhnServerProfile (base_channel)
    
    ;

CREATE SEQUENCE rhn_server_profile_id_seq;

ALTER TABLE rhnServerProfile
    ADD CONSTRAINT rhn_server_profile_id_pk PRIMARY KEY (id);

0707010000014C000081B400000000000000000000000167AE1114000005C1000000000000000000000000000000000000003D00000000susemanager-schema/common/tables/rhnServerProfilePackage.sql  --
-- Copyright (c) 2008 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnServerProfilePackage
(
    server_profile_id  NUMERIC NOT NULL
                           CONSTRAINT rhn_sprofile_spid_fk
                               REFERENCES rhnServerProfile (id)
                               ON DELETE CASCADE,
    name_id            NUMERIC NOT NULL
                           CONSTRAINT rhn_sprofile_nid_fk
                               REFERENCES rhnPackageName (id),
    evr_id             NUMERIC NOT NULL
                           CONSTRAINT rhn_sprofile_evrid_fk
                               REFERENCES rhnPackageEvr (id),
    package_arch_id    NUMERIC
                           CONSTRAINT rhn_sprofile_package_fk
                               REFERENCES rhnPackageArch (id)
)

;

CREATE INDEX rhn_sprof_sp_sne_idx
    ON rhnServerProfilePackage (server_profile_id, name_id, evr_id)
    
    ;

   0707010000014D000081B400000000000000000000000167AE1114000004D4000000000000000000000000000000000000003A00000000susemanager-schema/common/tables/rhnServerProfileType.sql --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnServerProfileType
(
    id        NUMERIC NOT NULL
                  CONSTRAINT rhn_sproftype_id_pk PRIMARY KEY
                  ,
    label     VARCHAR(64) NOT NULL,
    name      VARCHAR(64) NOT NULL,
    created   TIMESTAMPTZ
                  DEFAULT (current_timestamp) NOT NULL,
    modified  TIMESTAMPTZ
                  DEFAULT (current_timestamp) NOT NULL
)

;

CREATE INDEX rhn_sproftype_label_id_idx
    ON rhnServerProfileType (label, id)
    ;

CREATE SEQUENCE rhn_sproftype_id_seq;

ALTER TABLE rhnServerProfileType
    ADD CONSTRAINT rhn_sproftype_label_uq UNIQUE (label);

0707010000014E000081B400000000000000000000000167AE111400000594000000000000000000000000000000000000004400000000susemanager-schema/common/tables/rhnServerServerGroupArchCompat.sql   --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnServerServerGroupArchCompat
(
    server_arch_id     NUMERIC NOT NULL
                           CONSTRAINT rhn_ssg_ac_said_fk
                               REFERENCES rhnServerArch (id),
    server_group_type  NUMERIC NOT NULL
                           CONSTRAINT rhn_ssg_ac_sgt_fk
                               REFERENCES rhnServerGroupType (id),
    created            TIMESTAMPTZ
                           DEFAULT (current_timestamp) NOT NULL,
    modified           TIMESTAMPTZ
                           DEFAULT (current_timestamp) NOT NULL
)

;

CREATE UNIQUE INDEX rhn_ssg_ac_said_sgt_uq
    ON rhnServerServerGroupArchCompat (server_arch_id, server_group_type)
    ;

CREATE INDEX rhn_ssg_ac_sgt_idx
    ON rhnServerServerGroupArchCompat (server_group_type)
    
    ;

0707010000014F000081B400000000000000000000000167AE11140000048D000000000000000000000000000000000000003800000000susemanager-schema/common/tables/rhnServerTokenRegs.sql   --
-- Copyright (c) 2008--2010 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnServerTokenRegs
(
    token_id   NUMERIC NOT NULL
                   CONSTRAINT rhn_srv_reg_tok_tid_fk
                       REFERENCES rhnRegToken (id)
                       ON DELETE CASCADE,
    server_id  NUMERIC NOT NULL
                   CONSTRAINT rhn_srv_reg_tok_sid_fk
                       REFERENCES rhnServer (id)
)

;

CREATE INDEX rhn_srv_reg_tok_ts_idx
    ON rhnServerTokenRegs (token_id, server_id)
    
    ;

CREATE INDEX RHN_SRVR_TKN_RGS_SID_IDX
    ON rhnServerTokenRegs (server_id)
    
    ;

   07070100000150000081B400000000000000000000000167AE1114000003EF000000000000000000000000000000000000003300000000susemanager-schema/common/tables/rhnServerUuid.sql    --
-- Copyright (c) 2008 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnServerUuid
(
    server_id  NUMERIC NOT NULL
                   CONSTRAINT rhn_server_uuid_sid_fk
                       REFERENCES rhnServer (id),
    uuid       VARCHAR(36) NOT NULL
)

;

CREATE UNIQUE INDEX rhn_server_uuid_sid_unq
    ON rhnServerUuid (server_id)
    ;

CREATE UNIQUE INDEX rhn_serveruuid_uuid_sid_unq
    ON rhnServerUUID (uuid, server_id)
    ;

 07070100000151000081B400000000000000000000000167AE1114000003D2000000000000000000000000000000000000002C00000000susemanager-schema/common/tables/rhnSet.sql   --
-- Copyright (c) 2008--2017 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnSet
(
    user_id        NUMERIC NOT NULL
                       CONSTRAINT rhn_set_user_fk
                           REFERENCES web_contact (id)
                           ON DELETE CASCADE,
    label          VARCHAR(32) NOT NULL,
    element        NUMERIC NOT NULL,
    element_two    NUMERIC,
    element_three  NUMERIC
)


;

  07070100000152000081B400000000000000000000000167AE11140000062C000000000000000000000000000000000000003100000000susemanager-schema/common/tables/rhnSnapshot.sql  --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnSnapshot
(
    id         NUMERIC NOT NULL
                   CONSTRAINT rhn_snapshot_id_pk PRIMARY KEY
                   ,
    org_id     NUMERIC NOT NULL
                   CONSTRAINT rhn_snapshot_oid_fk
                       REFERENCES web_customer (id),
    invalid    NUMERIC
                   CONSTRAINT rhn_snapshot_invalid_fk
                       REFERENCES rhnSnapshotInvalidReason (id),
    reason     VARCHAR(4000) NOT NULL,
    server_id  NUMERIC NOT NULL
                   CONSTRAINT rhn_snapshot_sid_fk
                       REFERENCES rhnServer (id),
    created    TIMESTAMPTZ
                   DEFAULT (current_timestamp) NOT NULL,
    modified   TIMESTAMPTZ
                   DEFAULT (current_timestamp) NOT NULL
)

;

CREATE INDEX rhn_snapshot_sid_idx
    ON rhnSnapshot (server_id)
    
    ;

CREATE INDEX rhn_snapshot_oid_idx
    ON rhnSnapshot (org_id)
    
    ;

CREATE SEQUENCE rhn_snapshot_id_seq;

07070100000153000081B400000000000000000000000167AE111400000494000000000000000000000000000000000000003800000000susemanager-schema/common/tables/rhnSnapshotChannel.sql   --
-- Copyright (c) 2008 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnSnapshotChannel
(
    snapshot_id  NUMERIC NOT NULL
                     CONSTRAINT rhn_snapchan_sid_fk
                         REFERENCES rhnSnapshot (id)
                         ON DELETE CASCADE,
    channel_id   NUMERIC NOT NULL
                     CONSTRAINT rhn_snapchan_cid_fk
                         REFERENCES rhnChannel (id)
)

;

CREATE UNIQUE INDEX rhn_snapchan_sid_cid_uq
    ON rhnSnapshotChannel (snapshot_id, channel_id)
    ;

CREATE INDEX rhn_snapshot_cid_idx
    ON rhnSnapshotChannel (channel_id)
    
    ;

07070100000154000081B400000000000000000000000167AE1114000005B7000000000000000000000000000000000000003E00000000susemanager-schema/common/tables/rhnSnapshotConfigChannel.sql --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnSnapshotConfigChannel
(
    snapshot_id        NUMERIC NOT NULL
                           CONSTRAINT rhn_snapshotcc_sid_fk
                               REFERENCES rhnSnapshot (id)
                               ON DELETE CASCADE,
    config_channel_id  NUMERIC NOT NULL
                           CONSTRAINT rhn_snapshotcc_ccid_fk
                               REFERENCES rhnConfigChannel (id),
    created            TIMESTAMPTZ
                           DEFAULT (current_timestamp) NOT NULL,
    modified           TIMESTAMPTZ
                           DEFAULT (current_timestamp) NOT NULL
)

;

CREATE UNIQUE INDEX rhn_snapshotcc_sid_ccid_uq
    ON rhnSnapshotConfigChannel (snapshot_id, config_channel_id)
    ;

CREATE INDEX rhn_snpsht_cc_ccid_idx
    ON rhnSnapshotConfigChannel (config_channel_id)
    ;

 07070100000155000081B400000000000000000000000167AE1114000005C3000000000000000000000000000000000000003F00000000susemanager-schema/common/tables/rhnSnapshotConfigRevision.sql    --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnSnapshotConfigRevision
(
    snapshot_id         NUMERIC NOT NULL
                            CONSTRAINT rhn_snapshotcr_sid_fk
                                REFERENCES rhnSnapshot (id)
                                ON DELETE CASCADE,
    config_revision_id  NUMERIC NOT NULL
                            CONSTRAINT rhn_snapshotcr_crid_fk
                                REFERENCES rhnConfigRevision (id),
    created             TIMESTAMPTZ
                            DEFAULT (current_timestamp) NOT NULL,
    modified            TIMESTAMPTZ
                            DEFAULT (current_timestamp) NOT NULL
)

;

CREATE UNIQUE INDEX rhn_snapshotcr_sid_crid_uq
    ON rhnSnapshotConfigRevision (snapshot_id, config_revision_id)
    ;

CREATE INDEX rhn_sscr_crid_idx
    ON rhnSnapshotConfigRevision (config_revision_id)
    ;

 07070100000156000081B400000000000000000000000167AE111400000480000000000000000000000000000000000000003E00000000susemanager-schema/common/tables/rhnSnapshotInvalidReason.sql --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnSnapshotInvalidReason
(
    id        NUMERIC NOT NULL
                  CONSTRAINT rhn_ssinvalid_id_pk PRIMARY KEY
                  ,
    label     VARCHAR(32) NOT NULL,
    name      VARCHAR(128) NOT NULL,
    created   TIMESTAMPTZ
                  DEFAULT (current_timestamp) NOT NULL,
    modified  TIMESTAMPTZ
                  DEFAULT (current_timestamp) NOT NULL
)

;

CREATE UNIQUE INDEX rhn_ssinvalid_label_uq
    ON rhnSnapshotInvalidReason (label)
    ;

CREATE SEQUENCE rhn_ssinvalid_id_seq;

07070100000157000081B400000000000000000000000167AE111400000451000000000000000000000000000000000000003800000000susemanager-schema/common/tables/rhnSnapshotPackage.sql   --
-- Copyright (c) 2008--2010 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnSnapshotPackage
(
    snapshot_id  NUMERIC NOT NULL
                     CONSTRAINT rhn_snapshotpkg_sid_fk
                         REFERENCES rhnSnapshot (id)
                         ON DELETE CASCADE,
    nevra_id     NUMERIC NOT NULL
                     CONSTRAINT rhn_snapshotpkg_nid_fk
                         REFERENCES rhnPackageNevra (id)
)

;

CREATE UNIQUE INDEX rhn_snapshotpkg_sid_nid_uq
    ON rhnSnapshotPackage (snapshot_id, nevra_id)
    ;

   07070100000158000081B400000000000000000000000167AE1114000004D0000000000000000000000000000000000000003C00000000susemanager-schema/common/tables/rhnSnapshotServerGroup.sql   --
-- Copyright (c) 2008 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnSnapshotServerGroup
(
    snapshot_id      NUMERIC NOT NULL
                         CONSTRAINT rhn_snapshotsg_sid_fk
                             REFERENCES rhnSnapshot (id)
                             ON DELETE CASCADE,
    server_group_id  NUMERIC NOT NULL
                         CONSTRAINT rhn_snapshotsg_sgid_fk
                             REFERENCES rhnServerGroup (id)
)

;

CREATE UNIQUE INDEX rhn_snapshotsg_sid_sgid_uq
    ON rhnSnapshotServerGroup (snapshot_id, server_group_id)
    ;

CREATE INDEX rhn_snapshotsg_sgid_idx
    ON rhnSnapshotServerGroup (server_group_id)
    ;

07070100000159000081B400000000000000000000000167AE1114000005E6000000000000000000000000000000000000003400000000susemanager-schema/common/tables/rhnSnapshotTag.sql   --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnSnapshotTag
(
    snapshot_id  NUMERIC NOT NULL
                     CONSTRAINT rhn_st_ssid_fk
                         REFERENCES rhnSnapshot (id)
                         ON DELETE CASCADE,
    tag_id       NUMERIC NOT NULL
                     CONSTRAINT rhn_st_tid_fk
                         REFERENCES rhnTag (id),
    server_id    NUMERIC
                     CONSTRAINT rhn_st_sid_fk
                         REFERENCES rhnServer (id),
    created      TIMESTAMPTZ
                     DEFAULT (current_timestamp) NOT NULL,
    modified     TIMESTAMPTZ
                     DEFAULT (current_timestamp) NOT NULL
)

;

CREATE UNIQUE INDEX rhn_ss_tag_ssid_tid_uq
    ON rhnSnapshotTag (snapshot_id, tag_id);

CREATE UNIQUE INDEX rhn_ss_tag_sid_tid_uq
    ON rhnSnapshotTag (server_id, tag_id);

CREATE INDEX rhn_ss_tag_tid_idx
    ON rhnSnapshotTag (tag_id);

  0707010000015A000081B400000000000000000000000167AE111400000383000000000000000000000000000000000000003200000000susemanager-schema/common/tables/rhnSourceRPM.sql --
-- Copyright (c) 2008 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnSourceRPM
(
    id    NUMERIC NOT NULL
              CONSTRAINT rhn_sourceRPM_id_pk PRIMARY KEY
              ,
    name  VARCHAR(256) NOT NULL
)

;

CREATE UNIQUE INDEX rhn_srpm_name_uq
    ON rhnSourceRPM (name)
    ;

CREATE SEQUENCE rhn_sourcerpm_id_seq;

 0707010000015B000081B400000000000000000000000167AE1114000004B0000000000000000000000000000000000000003500000000susemanager-schema/common/tables/rhnSsmOperation.sql  --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnSsmOperation
(
    id           NUMERIC NOT NULL
                     CONSTRAINT rhn_ssmop_id_pk PRIMARY KEY
                     ,
    user_id      NUMERIC NOT NULL
                     CONSTRAINT rhn_ssmop_user_fk
                         REFERENCES web_contact (id)
                         ON DELETE CASCADE,
    description  VARCHAR(256) NOT NULL,
    status       VARCHAR(32) NOT NULL,
    started      TIMESTAMPTZ NOT NULL,
    modified     TIMESTAMPTZ
                     DEFAULT (current_timestamp) NOT NULL
)
;

CREATE SEQUENCE rhn_ss_op_seq;

0707010000015C000081B400000000000000000000000167AE11140000043C000000000000000000000000000000000000003B00000000susemanager-schema/common/tables/rhnSsmOperationServer.sql    --
-- Copyright (c) 2008 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

CREATE TABLE rhnSsmOperationServer
(
    operation_id  NUMERIC
                      CONSTRAINT rhn_ssmops_ssmop_fk
                          REFERENCES rhnSsmOperation (id)
                          ON DELETE CASCADE,
    server_id     NUMERIC
                      CONSTRAINT rhn_ssmops_ser_fk
                          REFERENCES rhnServer (id)
                          ON DELETE CASCADE,
    note          VARCHAR(256)
                      DEFAULT NULL
)
;0707010000015D000081B400000000000000000000000167AE1114000005A0000000000000000000000000000000000000003900000000susemanager-schema/common/tables/rhnSystemMigrations.sql  --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnSystemMigrations
(
    org_id_to    NUMERIC
                     CONSTRAINT rhn_sys_mig_oidto_fk
                         REFERENCES web_customer (id)
                         ON DELETE SET NULL,
    org_id_from  NUMERIC
                     CONSTRAINT rhn_sys_mig_oidfrm_fk
                         REFERENCES web_customer (id)
                         ON DELETE SET NULL,
    server_id    NUMERIC NOT NULL
                     CONSTRAINT rhn_sys_mig_sid_fk
                         REFERENCES rhnServer (id)
                         ON DELETE CASCADE,
    migrated     TIMESTAMPTZ
                     DEFAULT (current_timestamp) NOT NULL
)

;

CREATE INDEX rsm_org_id_to_idx
    ON rhnSystemMigrations (org_id_to);

CREATE INDEX rsm_org_id_from_idx
    ON rhnSystemMigrations (org_id_from);

0707010000015E000081B400000000000000000000000167AE111400000519000000000000000000000000000000000000002C00000000susemanager-schema/common/tables/rhnTag.sql   --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnTag
(
    id        NUMERIC NOT NULL
                  CONSTRAINT rhn_tag_id_pk PRIMARY KEY,
    name_id   NUMERIC NOT NULL
                  CONSTRAINT rhn_tag_nid_fk
                      REFERENCES rhnTagName (id),
    org_id    NUMERIC NOT NULL
                  CONSTRAINT rhn_tag_oid_fk
                      REFERENCES web_customer (id)
                      ON DELETE CASCADE,
    created   TIMESTAMPTZ
                  DEFAULT (current_timestamp) NOT NULL,
    modified  TIMESTAMPTZ
                  DEFAULT (current_timestamp) NOT NULL
)

;

CREATE UNIQUE INDEX rhn_tag_oid_nid_uq
    ON rhnTag (org_id, name_id);

CREATE SEQUENCE rhn_tag_id_seq;

   0707010000015F000081B400000000000000000000000167AE111400000416000000000000000000000000000000000000003000000000susemanager-schema/common/tables/rhnTagName.sql   --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnTagName
(
    id        NUMERIC NOT NULL
                  CONSTRAINT rhn_tn_id_pk PRIMARY KEY,
    name      VARCHAR(128) NOT NULL,
    created   TIMESTAMPTZ
                  DEFAULT (current_timestamp) NOT NULL,
    modified  TIMESTAMPTZ
                  DEFAULT (current_timestamp) NOT NULL
)

;

CREATE UNIQUE INDEX rhn_tn_name_uq
    ON rhnTagName (name);

CREATE SEQUENCE rhn_tagname_id_seq;

  07070100000160000081B400000000000000000000000167AE11140000054F000000000000000000000000000000000000003200000000susemanager-schema/common/tables/rhnTaskQueue.sql --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnTaskQueue
(
    id         NUMERIC NOT NULL
                   CONSTRAINT rhn_task_queue_id_pk PRIMARY KEY,
    org_id     NUMERIC NOT NULL
                   CONSTRAINT rhn_task_queue_org_id_fk
                       REFERENCES web_customer (id)
                       ON DELETE CASCADE,
    task_name      VARCHAR(64) NOT NULL,
    task_data      NUMERIC,
    priority       NUMERIC
                   DEFAULT (0),
    earliest       TIMESTAMPTZ
                   DEFAULT (current_timestamp) NOT NULL
)
;

CREATE INDEX rhn_task_queue_org_task_idx
    ON rhnTaskQueue (org_id, task_name);

CREATE INDEX rhn_task_queue_earliest
    ON rhnTaskQueue (earliest);

CREATE SEQUENCE rhn_task_queue_id_seq START WITH 1;
 07070100000161000081B400000000000000000000000167AE111400000467000000000000000000000000000000000000003300000000susemanager-schema/common/tables/rhnTaskoBunch.sql    --
-- Copyright (c) 2010--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnTaskoBunch
(
    id          NUMERIC NOT NULL
                    CONSTRAINT rhn_tasko_bunch_id_pk PRIMARY KEY,
    name        VARCHAR(80) NOT NULL
                    CONSTRAINT tasko_bunch_name_uq UNIQUE,
    description VARCHAR(200),
    org_bunch   VARCHAR(1),
    created     TIMESTAMPTZ
                    DEFAULT (current_timestamp) NOT NULL,
    modified    TIMESTAMPTZ
                    DEFAULT (current_timestamp) NOT NULL
)
;

CREATE SEQUENCE rhn_tasko_bunch_id_seq;
 07070100000162000081B400000000000000000000000167AE1114000005C1000000000000000000000000000000000000003100000000susemanager-schema/common/tables/rhnTaskoRun.sql  --
-- Copyright (c) 2010--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnTaskoRun
(
    id              NUMERIC NOT NULL
                        CONSTRAINT rhn_tasko_run_id_pk PRIMARY KEY,
    template_id     NUMERIC NOT NULL
                        CONSTRAINT rhn_tasko_run_template_fk
                        REFERENCES rhnTaskoTemplate (id),
    schedule_id     NUMERIC NOT NULL
                        CONSTRAINT rhn_tasko_run_schedule_fk
                        REFERENCES rhnTaskoSchedule (id)
                        ON DELETE CASCADE,
    org_id          NUMERIC,
    start_time      TIMESTAMPTZ,
    end_time        TIMESTAMPTZ,
    status          VARCHAR(12),
    created         TIMESTAMPTZ
                        DEFAULT (current_timestamp) NOT NULL,
    modified        TIMESTAMPTZ
                        DEFAULT (current_timestamp) NOT NULL
)
;

CREATE SEQUENCE rhn_tasko_run_id_seq;
   07070100000163000081B400000000000000000000000167AE11140000054F000000000000000000000000000000000000003600000000susemanager-schema/common/tables/rhnTaskoSchedule.sql --
-- Copyright (c) 2010--2014 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnTaskoSchedule
(
    id              NUMERIC NOT NULL
                        CONSTRAINT rhn_tasko_schedule_id_pk PRIMARY KEY,
    job_label       VARCHAR(50) NOT NULL,
    bunch_id        NUMERIC NOT NULL
                        CONSTRAINT rhn_tasko_schedule_bunch_fk
                        REFERENCES rhnTaskoBunch (id),
    org_id          NUMERIC,
    active_from     TIMESTAMPTZ,
    active_till     TIMESTAMPTZ,
    cron_expr       VARCHAR(120),
    data            BYTEA,
    created         TIMESTAMPTZ
                        DEFAULT (current_timestamp) NOT NULL,
    modified        TIMESTAMPTZ
                        DEFAULT (current_timestamp) NOT NULL
)
;

CREATE SEQUENCE rhn_tasko_schedule_id_seq;
 07070100000164000081B400000000000000000000000167AE111400000442000000000000000000000000000000000000003200000000susemanager-schema/common/tables/rhnTaskoTask.sql --
-- Copyright (c) 2010--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnTaskoTask
(
    id        NUMERIC NOT NULL
                  CONSTRAINT rhn_tasko_task_id_pk PRIMARY KEY,
    name      VARCHAR(80) NOT NULL
                  CONSTRAINT rhn_tasko_task_name_uq UNIQUE,
    class     VARCHAR(120) NOT NULL,
    created   TIMESTAMPTZ
                  DEFAULT (current_timestamp) NOT NULL,
    modified  TIMESTAMPTZ
                  DEFAULT (current_timestamp) NOT NULL
)
;

CREATE SEQUENCE rhn_tasko_task_id_seq;
  07070100000165000081B400000000000000000000000167AE11140000059A000000000000000000000000000000000000003600000000susemanager-schema/common/tables/rhnTaskoTemplate.sql --
-- Copyright (c) 2010--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnTaskoTemplate
(
    id          NUMERIC NOT NULL
                    CONSTRAINT rhn_tasko_template_id_pk PRIMARY KEY,
    bunch_id    NUMERIC NOT NULL
                    CONSTRAINT rhn_tasko_template_bunch_fk
                    REFERENCES rhnTaskoBunch (id),
    task_id     NUMERIC NOT NULL
                    CONSTRAINT rhn_tasko_template_task_fk
                    REFERENCES rhnTaskoTask (id),
    ordering    NUMERIC NOT NULL,
    start_if    VARCHAR(10),
    created     TIMESTAMPTZ
                    DEFAULT (current_timestamp) NOT NULL,
    modified    TIMESTAMPTZ
                    DEFAULT (current_timestamp) NOT NULL
)
;

CREATE SEQUENCE rhn_tasko_template_id_seq;

ALTER TABLE rhnTaskoTemplate
    ADD CONSTRAINT tasko_template_ordering_uq UNIQUE (bunch_id, ordering);
  07070100000166000081B400000000000000000000000167AE111400000549000000000000000000000000000000000000003900000000susemanager-schema/common/tables/rhnTemplateCategory.sql  --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnTemplateCategory
(
    id           NUMERIC NOT NULL,
    label        VARCHAR(64) NOT NULL,
    description  VARCHAR(512) NOT NULL,
    created      TIMESTAMPTZ
                     DEFAULT (current_timestamp) NOT NULL,
    modified     TIMESTAMPTZ
                     DEFAULT (current_timestamp) NOT NULL
)

;

CREATE INDEX rhn_template_cat_id_idx
    ON rhnTemplateCategory (id)
    ;

CREATE INDEX rhn_template_cat_label_id_idx
    ON rhnTemplateCategory (label, id)
    ;

CREATE SEQUENCE rhn_template_cat_id_seq;

ALTER TABLE rhnTemplateCategory
    ADD CONSTRAINT rhn_template_cat_id_pk PRIMARY KEY (id);

ALTER TABLE rhnTemplateCategory
    ADD CONSTRAINT rhn_template_cat_label_uq UNIQUE (label);

   07070100000167000081B400000000000000000000000167AE111400000627000000000000000000000000000000000000003700000000susemanager-schema/common/tables/rhnTemplateString.sql    --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnTemplateString
(
    id           NUMERIC NOT NULL,
    category_id  NUMERIC NOT NULL
                     CONSTRAINT rhn_template_str_cid_fk
                         REFERENCES rhnTemplateCategory (id),
    label        VARCHAR(64) NOT NULL,
    value        VARCHAR(4000),
    description  VARCHAR(512) NOT NULL,
    created      TIMESTAMPTZ
                     DEFAULT (current_timestamp) NOT NULL,
    modified     TIMESTAMPTZ
                     DEFAULT (current_timestamp) NOT NULL
)

;

CREATE INDEX rhn_template_str_icl_idx
    ON rhnTemplateString (id, category_id, label)
    ;

CREATE INDEX rhn_template_str_cid_label_idx
    ON rhnTemplateString (category_id, label)
    ;

CREATE SEQUENCE rhn_template_str_id_seq;

ALTER TABLE rhnTemplateString
    ADD CONSTRAINT rhn_template_str_id_pk PRIMARY KEY (id);

ALTER TABLE rhnTemplateString
    ADD CONSTRAINT rhn_template_str_cid_label_uq UNIQUE (category_id, label);

 07070100000168000081B400000000000000000000000167AE111400000468000000000000000000000000000000000000003100000000susemanager-schema/common/tables/rhnTimezone.sql  --
-- Copyright (c) 2008 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnTimezone
(
    id            NUMERIC NOT NULL,
    olson_name    VARCHAR(128) NOT NULL,
    display_name  VARCHAR(128) NOT NULL
)

;

CREATE INDEX rhn_timezone_id_idx
    ON rhnTimezone (id)
    ;

CREATE UNIQUE INDEX rhn_timezone_olson_uq
    ON rhnTimezone (olson_name);

CREATE UNIQUE INDEX rhn_timezone_display_uq
    ON rhnTimezone (display_name);

CREATE SEQUENCE rhn_timezone_id_seq START WITH 7000;

ALTER TABLE rhnTimezone
    ADD CONSTRAINT rhn_timezone_id_pk PRIMARY KEY (id);

07070100000169000081B400000000000000000000000167AE111400000442000000000000000000000000000000000000003000000000susemanager-schema/common/tables/rhnTinyURL.sql   --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnTinyURL
(
    token    VARCHAR(64) NOT NULL,
    url      VARCHAR(512) NOT NULL,
    enabled  VARCHAR(1) NOT NULL
                 CONSTRAINT rhn_tu_enabled_ck
                     CHECK (enabled in ('Y','N')),
    created  TIMESTAMPTZ
                 DEFAULT (current_timestamp) NOT NULL,
    expires  TIMESTAMPTZ
                 DEFAULT (current_timestamp) NOT NULL
)

;

CREATE UNIQUE INDEX rhn_tu_token_uq
    ON rhnTinyURL (token)
    ;

  0707010000016A000081B400000000000000000000000167AE11140000047B000000000000000000000000000000000000003D00000000susemanager-schema/common/tables/rhnTransactionOperation.sql  --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnTransactionOperation
(
    id        NUMERIC NOT NULL
                  CONSTRAINT rhn_transop_id_pk PRIMARY KEY
                  ,
    label     VARCHAR(32) NOT NULL
                  CONSTRAINT rhn_transop_label_uq UNIQUE
                  ,
    created   TIMESTAMPTZ
                  DEFAULT (current_timestamp) NOT NULL,
    modified  TIMESTAMPTZ
                  DEFAULT (current_timestamp) NOT NULL
)

;

CREATE INDEX rhn_transop_label_id_idx
    ON rhnTransactionOperation (label, id)
    ;

 0707010000016B000081B400000000000000000000000167AE111400000630000000000000000000000000000000000000003B00000000susemanager-schema/common/tables/rhnTransactionPackage.sql    --
-- Copyright (c) 2008 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnTransactionPackage
(
    id               NUMERIC NOT NULL
                         CONSTRAINT rhn_transpack_id_pk PRIMARY KEY
                         ,
    operation        NUMERIC NOT NULL
                         CONSTRAINT rhn_transpack_op_fk
                             REFERENCES rhnTransactionOperation (id),
    name_id          NUMERIC NOT NULL
                         CONSTRAINT rhn_transpack_nid_fk
                             REFERENCES rhnPackageName (id),
    evr_id           NUMERIC NOT NULL
                         CONSTRAINT rhn_transpack_eid_fk
                             REFERENCES rhnPackageEVR (id),
    package_arch_id  NUMERIC
                         CONSTRAINT rhn_transpack_paid_fk
                             REFERENCES rhnPackageArch (id)
)

;

CREATE UNIQUE INDEX rhn_transpack_onea_uq
    ON rhnTransactionPackage (operation, name_id, evr_id, package_arch_id)
    ;

CREATE SEQUENCE rhn_transpack_id_seq;

0707010000016C000081B400000000000000000000000167AE11140000052D000000000000000000000000000000000000003400000000susemanager-schema/common/tables/rhnTrustedOrgs.sql   --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnTrustedOrgs
(
    org_id        NUMERIC NOT NULL
                      CONSTRAINT rhn_trusted_orgs_oid_fk
                          REFERENCES web_customer (id)
                          ON DELETE CASCADE,
    org_trust_id  NUMERIC NOT NULL
                      CONSTRAINT rhn_trusted_orgs_otid_fk
                          REFERENCES web_customer (id)
                          ON DELETE CASCADE,
    created       TIMESTAMPTZ
                      DEFAULT (current_timestamp) NOT NULL,
    modified      TIMESTAMPTZ
                      DEFAULT (current_timestamp) NOT NULL
)

;

CREATE UNIQUE INDEX rhn_trusted_orgs_oid_uq
    ON rhnTrustedOrgs (org_id, org_trust_id)
    ;

   0707010000016D000081B400000000000000000000000167AE1114000004F5000000000000000000000000000000000000004000000000susemanager-schema/common/tables/rhnUserDefaultSystemGroups.sql   --
-- Copyright (c) 2008--2010 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnUserDefaultSystemGroups
(
    user_id          NUMERIC NOT NULL
                         CONSTRAINT rhn_udsg_uid_fk
                             REFERENCES web_contact (id)
                             ON DELETE CASCADE,
    system_group_id  NUMERIC NOT NULL
                         CONSTRAINT rhn_udsg_cidffk
                             REFERENCES rhnServerGroup (id)
                             ON DELETE CASCADE
)

;

CREATE UNIQUE INDEX rhn_udsg_uid_sgid_idx
    ON rhnUserDefaultSystemGroups (user_id, system_group_id)
    ;

CREATE INDEX rhn_udsg_sgid_idx
    ON rhnUserDefaultSystemGroups (system_group_id)
    ;

   0707010000016E000081B400000000000000000000000167AE111400000513000000000000000000000000000000000000003500000000susemanager-schema/common/tables/rhnUserExtGroup.sql  --
-- Copyright (c) 2014 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnUserExtGroup
(
    id        NUMERIC NOT NULL
                  CONSTRAINT rhn_userExtGroup_id_pk PRIMARY KEY
                  ,
    org_id    NUMERIC
                DEFAULT NULL
                CONSTRAINT rhn_userExtGroup_oid_fk
                    REFERENCES web_customer (id)
                    ON DELETE CASCADE,
    label     VARCHAR(512) NOT NULL,
    created   TIMESTAMPTZ
                  DEFAULT (current_timestamp) NOT NULL,
    modified  TIMESTAMPTZ
                  DEFAULT (current_timestamp) NOT NULL
)

;

CREATE UNIQUE INDEX rhn_userextgroup_label_oid_uq
    ON rhnUserExtGroup (label, org_id)
    ;

CREATE SEQUENCE rhn_userextgroup_seq;
 0707010000016F000081B400000000000000000000000167AE1114000005C2000000000000000000000000000000000000003C00000000susemanager-schema/common/tables/rhnUserExtGroupMapping.sql   --
-- Copyright (c) 2014 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnUserExtGroupMapping
(
    id        NUMERIC NOT NULL
                  CONSTRAINT rhn_userExtGroupMap_id_pk PRIMARY KEY
                  ,
    ext_group_id        NUMERIC NOT NULL
                  constraint rhn_userextgroupmap_e_fk
                  references rhnUserExtGroup(id)
                  on delete cascade,
    int_group_type_id        NUMERIC NOT NULL
                  constraint rhn_userextgroupmap_i_fk
                  references rhnUserGroupType(id)
                  on delete cascade,
    created   TIMESTAMPTZ
                  DEFAULT (current_timestamp) NOT NULL,
    modified  TIMESTAMPTZ
                  DEFAULT (current_timestamp) NOT NULL
)

;

CREATE UNIQUE INDEX rhn_userextgroupmap_ei_uq
    ON rhnUserExtGroupMapping (ext_group_id, int_group_type_id)
    ;

CREATE SEQUENCE rhn_userextgroupmap_seq;
  07070100000170000081B400000000000000000000000167AE111400000702000000000000000000000000000000000000003200000000susemanager-schema/common/tables/rhnUserGroup.sql --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnUserGroup
(
    id               NUMERIC NOT NULL
                         CONSTRAINT rhn_user_group_pk PRIMARY KEY
                         ,
    name             VARCHAR(64) NOT NULL,
    description      VARCHAR(1024) NOT NULL,
    max_members      NUMERIC,
    current_members  NUMERIC
                         DEFAULT (0) NOT NULL,
    group_type       NUMERIC NOT NULL
                         CONSTRAINT rhn_usergroup_type_fk
                             REFERENCES rhnUserGroupType (id),
    org_id           NUMERIC NOT NULL
                         CONSTRAINT rhn_user_group_org_fk
                             REFERENCES web_customer (id)
                             ON DELETE CASCADE,
    created          TIMESTAMPTZ
                         DEFAULT (current_timestamp) NOT NULL,
    modified         TIMESTAMPTZ
                         DEFAULT (current_timestamp) NOT NULL
)

;

CREATE UNIQUE INDEX rhn_ug_oid_name_uq
    ON rhnUserGroup (org_id, name)
    ;

CREATE INDEX rhn_ug_org_id_type_idx
    ON rhnUserGroup (group_type, id)
    
    ;

ALTER TABLE rhnUserGroup
ADD CONSTRAINT rhn_ug_oid_gt_uq
UNIQUE (org_id, group_type)
;

  07070100000171000081B400000000000000000000000167AE11140000063B000000000000000000000000000000000000003900000000susemanager-schema/common/tables/rhnUserGroupMembers.sql  --
-- Copyright (c) 2008--2014 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnUserGroupMembers
(
    user_id        NUMERIC NOT NULL
                       CONSTRAINT rhn_ugmembers_uid_fk
                           REFERENCES web_contact (id)
                           ON DELETE CASCADE,
    user_group_id  NUMERIC NOT NULL
                       CONSTRAINT rhn_ugmembers_ugid_fk
                           REFERENCES rhnUserGroup (id),
    temporary      CHAR(1)
                        DEFAULT ('N') NOT NULL
                        CONSTRAINT rhn_ugmembers_t_ck
                            CHECK (temporary in ('Y', 'N')),
    created        TIMESTAMPTZ
                       DEFAULT (current_timestamp) NOT NULL,
    modified       TIMESTAMPTZ
                       DEFAULT (current_timestamp) NOT NULL
)

;

CREATE UNIQUE INDEX rhn_ugmembers_uid_ugid_temp_uq
    ON rhnUserGroupMembers (user_id, user_group_id, temporary)
    ;

CREATE INDEX rhn_ugmembers_ugid_idx
    ON rhnUserGroupMembers (user_group_id)
    
    ;

 07070100000172000081B400000000000000000000000167AE1114000004D6000000000000000000000000000000000000003600000000susemanager-schema/common/tables/rhnUserGroupType.sql --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnUserGroupType
(
    id        NUMERIC NOT NULL
                  CONSTRAINT rhn_userGroupType_id_pk PRIMARY KEY
                  ,
    label     VARCHAR(64) NOT NULL,
    name      VARCHAR(64) NOT NULL,
    created   TIMESTAMPTZ
                  DEFAULT (current_timestamp) NOT NULL,
    modified  TIMESTAMPTZ
                  DEFAULT (current_timestamp) NOT NULL
)

;

CREATE INDEX rhn_usergrouptype_label_id_idx
    ON rhnUserGroupType (label, id)
    ;

CREATE SEQUENCE rhn_usergroup_type_seq;

ALTER TABLE rhnUserGroupType
    ADD CONSTRAINT rhn_usergrouptype_label_uq UNIQUE (label);

  07070100000173000081B400000000000000000000000167AE111400000297000000000000000000000000000000000000003C00000000susemanager-schema/common/tables/rhnUserGroup_sequences.sql   --
-- Copyright (c) 2008 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE SEQUENCE rhn_user_group_id_seq;

 07070100000174000081B400000000000000000000000167AE111400000FEA000000000000000000000000000000000000003100000000susemanager-schema/common/tables/rhnUserInfo.sql  --
-- Copyright (c) 2008--2015 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnUserInfo
(
    user_id                 NUMERIC NOT NULL
                                CONSTRAINT rhn_user_info_user_fk
                                    REFERENCES web_contact (id)
                                    ON DELETE CASCADE,
    no_clear_sets           NUMERIC
                                DEFAULT (0) NOT NULL,
    page_size               NUMERIC
                                DEFAULT (20) NOT NULL,
    email_notify            NUMERIC
                                DEFAULT (1) NOT NULL,
    tasko_notify            CHAR(1)
                                DEFAULT ('Y') NOT NULL
                                CONSTRAINT rhn_user_info_tasko_ck
                                    CHECK (tasko_notify in ('Y', 'N')),
    bad_email               NUMERIC
                                DEFAULT (0) NOT NULL,
    tz_offset               NUMERIC
                                DEFAULT (-5) NOT NULL
                                CONSTRAINT rhn_user_info_tzoffset_ck
                                    CHECK (tz_offset >= -11 and tz_offset <= 13),
    timezone_id             NUMERIC
                                CONSTRAINT rhn_user_info_tzid_fk
                                    REFERENCES rhnTimezone (id)
                                    ON DELETE CASCADE,
    show_applied_errata     CHAR(1)
                                DEFAULT ('N') NOT NULL
                                CONSTRAINT rhn_user_info_sea_ck
                                    CHECK (show_applied_errata in ('Y','N')),
    show_system_group_list  CHAR(1)
                                DEFAULT ('N') NOT NULL
                                CONSTRAINT rhn_user_info_ssgl_ck
                                    CHECK (show_system_group_list in ('Y','N')),
    agreed_to_terms         CHAR(1)
                                DEFAULT ('N') NOT NULL
                                CONSTRAINT rhn_user_info_agreed_ck
                                    CHECK (agreed_to_terms in ('Y','N')),
    use_pam_authentication  CHAR(1)
                                DEFAULT ('N') NOT NULL
                                CONSTRAINT rhn_user_info_pam_ck
                                    CHECK (use_pam_authentication in ('Y','N')),
    last_logged_in          TIMESTAMPTZ,
    agreed_to_ws_terms      CHAR(1)
                                CONSTRAINT rhn_user_info_ws_ck
                                    CHECK (agreed_to_ws_terms is null or agreed_to_ws_terms in ('Y','N')),
    agreed_to_es_terms      CHAR(1)
                                CONSTRAINT rhn_user_info_es_ck
                                    CHECK (agreed_to_es_terms is null or agreed_to_es_terms in ('Y','N')),
    created                 TIMESTAMPTZ
                                DEFAULT (current_timestamp) NOT NULL,
    modified                TIMESTAMPTZ
                                DEFAULT (current_timestamp) NOT NULL,
    preferred_locale        VARCHAR(8),
    preferred_docs_locale   VARCHAR(8),
    csv_separator           CHAR(1)
                                DEFAULT (',') NOT NULL
                                CONSTRAINT rhn_user_info_csv_ck
                                    CHECK (csv_separator in (',',';')),
    web_theme               VARCHAR(32)
)

;

CREATE INDEX rhn_user_info_uid_email_idx
    ON rhnUserInfo (user_id, email_notify)
    ;

ALTER TABLE rhnUserInfo
    ADD CONSTRAINT rhn_user_info_uid_uq UNIQUE (user_id);

  07070100000175000081B400000000000000000000000167AE11140000044A000000000000000000000000000000000000003500000000susemanager-schema/common/tables/rhnUserInfoPane.sql  --
-- Copyright (c) 2008 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnUserInfoPane
(
    user_id  NUMERIC NOT NULL
                 CONSTRAINT rhn_usr_info_pane_uid_fk
                     REFERENCES web_contact (id)
                     ON DELETE CASCADE,
    pane_id  NUMERIC NOT NULL
                 CONSTRAINT rhn_usr_info_pane_pid_fk
                     REFERENCES rhnInfoPane (id)
                     ON DELETE CASCADE
)

;

CREATE UNIQUE INDEX rhnusrinfopane_uid_pid_uq
    ON rhnUserInfoPane (user_id, pane_id)
    ;

  07070100000176000081B400000000000000000000000167AE1114000003FF000000000000000000000000000000000000003500000000susemanager-schema/common/tables/rhnUserReserved.sql  --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnUserReserved
(
    login     VARCHAR(64) NOT NULL,
    login_uc  VARCHAR(64) NOT NULL,
    password  VARCHAR(38) NOT NULL,
    created   TIMESTAMPTZ
                  DEFAULT (current_timestamp) NOT NULL,
    modified  TIMESTAMPTZ
                  DEFAULT (current_timestamp) NOT NULL
)

;

CREATE UNIQUE INDEX rhn_user_res_login_uc_uq
    ON rhnUserReserved (login_uc)
    ;

 07070100000177000081B400000000000000000000000167AE1114000005B0000000000000000000000000000000000000003D00000000susemanager-schema/common/tables/rhnUserServerGroupPerms.sql  --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnUserServerGroupPerms
(
    user_id          NUMERIC NOT NULL
                         CONSTRAINT rhn_usgp_user_fk
                             REFERENCES web_contact (id)
                             ON DELETE CASCADE,
    server_group_id  NUMERIC NOT NULL
                         CONSTRAINT rhn_usgp_server_fk
                             REFERENCES rhnServerGroup (id)
                             ON DELETE CASCADE,
    created          TIMESTAMPTZ
                         DEFAULT (current_timestamp) NOT NULL,
    modified         TIMESTAMPTZ
                         DEFAULT (current_timestamp) NOT NULL
)

;

CREATE UNIQUE INDEX rhn_usgp_u_sg_p_uq
    ON rhnUserServerGroupPerms (user_id, server_group_id)
    ;

CREATE INDEX rhn_usgp_sg_idx
    ON rhnUserServerGroupPerms (server_group_id)
    
    ;

07070100000178000081B400000000000000000000000167AE11140000044D000000000000000000000000000000000000003800000000susemanager-schema/common/tables/rhnUserServerPerms.sql   --
-- Copyright (c) 2008 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnUserServerPerms
(
    user_id    NUMERIC NOT NULL
                   CONSTRAINT rhn_usperms_uid_fk
                       REFERENCES web_contact (id),
    server_id  NUMERIC NOT NULL
                   CONSTRAINT rhn_usperms_sid_fk
                       REFERENCES rhnServer (id)
)

;

CREATE UNIQUE INDEX rhn_usperms_uid_sid_uq
    ON rhnUserServerPerms (user_id, server_id)
    ;

CREATE INDEX rhn_usperms_sid_idx
    ON rhnUserServerPerms (server_id)
    ;

   07070100000179000081B400000000000000000000000167AE11140000058A000000000000000000000000000000000000003800000000susemanager-schema/common/tables/rhnUserServerPrefs.sql   --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnUserServerPrefs
(
    user_id    NUMERIC NOT NULL
                   CONSTRAINT rhn_userServerPrefs_uid_fk
                       REFERENCES web_contact (id)
                       ON DELETE CASCADE,
    server_id  NUMERIC NOT NULL
                   CONSTRAINT rhn_userServerPrefs_sid_fk
                       REFERENCES rhnServer (id),
    name       VARCHAR(64) NOT NULL,
    value      VARCHAR(1) NOT NULL,
    created    TIMESTAMPTZ
                   DEFAULT (current_timestamp) NOT NULL,
    modified   TIMESTAMPTZ
                   DEFAULT (current_timestamp) NOT NULL
)

;

CREATE UNIQUE INDEX rhn_usprefs_uid_sid_n_uq
    ON rhnUserServerPrefs (user_id, server_id, name)
    ;

CREATE INDEX rhn_usprefs_sid_idx
    ON rhnUserServerPrefs (server_id)
    
    ;

  0707010000017A000081B400000000000000000000000167AE1114000004C3000000000000000000000000000000000000003400000000susemanager-schema/common/tables/rhnVersionInfo.sql   --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnVersionInfo
(
    label     VARCHAR(64) NOT NULL,
    name_id   NUMERIC NOT NULL
                  CONSTRAINT rhn_versioninfo_nid_fk
                      REFERENCES rhnPackageName (id),
    evr_id    NUMERIC NOT NULL
                  CONSTRAINT rhn_versioninfo_eid_fk
                      REFERENCES rhnPackageEVR (id),
    created   TIMESTAMPTZ
                  DEFAULT (current_timestamp) NOT NULL,
    modified  TIMESTAMPTZ
                  DEFAULT (current_timestamp) NOT NULL
)

;

CREATE UNIQUE INDEX rhn_versioninfo_label_uq
    ON rhnVersionInfo (label)
    ;

 0707010000017B000081B400000000000000000000000167AE111400000698000000000000000000000000000000000000003800000000susemanager-schema/common/tables/rhnVirtualInstance.sql   --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnVirtualInstance
(
    id                 NUMERIC NOT NULL
                           CONSTRAINT rhn_vi_id_pk PRIMARY KEY
                           ,
    host_system_id     NUMERIC
                           CONSTRAINT rhn_vi_hsi_fk
                               REFERENCES rhnServer (id),
    virtual_system_id  NUMERIC
                           CONSTRAINT rhn_vi_vsi_fk
                               REFERENCES rhnServer (id),
    uuid               VARCHAR(128),
    confirmed          NUMERIC(1)
                           DEFAULT (1) NOT NULL,
    created            TIMESTAMPTZ
                           DEFAULT (current_timestamp) NOT NULL,
    modified           TIMESTAMPTZ
                           DEFAULT (current_timestamp) NOT NULL
)

;

CREATE INDEX rhn_vi_hsid_vsid_idx
    ON rhnVirtualInstance (host_system_id, virtual_system_id)
    ;

CREATE INDEX rhn_vi_vsid_idx
    ON rhnVirtualInstance (virtual_system_id)
    ;

CREATE INDEX rhn_vi_uuid_idx
    ON rhnVirtualInstance (uuid)
    ;

CREATE SEQUENCE rhn_vi_id_seq;

0707010000017C000081B400000000000000000000000167AE1114000008F2000000000000000000000000000000000000004000000000susemanager-schema/common/tables/rhnVirtualInstanceEventLog.sql   --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnVirtualInstanceEventLog
(
    id                    NUMERIC NOT NULL
                              CONSTRAINT rhn_viel_id_pk PRIMARY KEY
                              ,
    virtual_instance_id   NUMERIC
                              CONSTRAINT rhn_viel_vii_fk
                                  REFERENCES rhnVirtualInstance (id)
                                  ON DELETE CASCADE,
    event_type            NUMERIC NOT NULL
                              CONSTRAINT rhn_viel_et_fk
                                  REFERENCES rhnVirtualInstanceEventType (id),
    event_metadata        VARCHAR(4000),
    old_state             NUMERIC NOT NULL
                              CONSTRAINT rhn_viel_old_state_fk
                                  REFERENCES rhnVirtualInstanceState (id),
    new_state             NUMERIC NOT NULL
                              CONSTRAINT rhn_viel_new_state_fk
                                  REFERENCES rhnVirtualInstanceState (id),
    old_memory_size_k     NUMERIC,
    new_memory_size_k     NUMERIC,
    old_vcpus             NUMERIC,
    new_vcpus             NUMERIC,
    old_host_system_id    NUMERIC,
    new_host_system_id    NUMERIC,
    old_host_system_name  VARCHAR(128),
    new_host_system_name  VARCHAR(128),
    local_timestamp       TIMESTAMPTZ NOT NULL,
    created               TIMESTAMPTZ
                              DEFAULT (current_timestamp) NOT NULL,
    modified              TIMESTAMPTZ
                              DEFAULT (current_timestamp) NOT NULL
)

;

CREATE INDEX rhn_viel_vii_idx
    ON rhnVirtualInstanceEventLog (virtual_instance_id)
    ;

CREATE SEQUENCE rhn_viel_id_seq;

  0707010000017D000081B400000000000000000000000167AE111400000420000000000000000000000000000000000000004100000000susemanager-schema/common/tables/rhnVirtualInstanceEventType.sql  --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnVirtualInstanceEventType
(
    id        NUMERIC NOT NULL
                  CONSTRAINT rhn_viet_id_pk PRIMARY KEY
                  ,
    name      VARCHAR(128) NOT NULL,
    label     VARCHAR(128) NOT NULL,
    created   TIMESTAMPTZ
                  DEFAULT (current_timestamp) NOT NULL,
    modified  TIMESTAMPTZ
                  DEFAULT (current_timestamp) NOT NULL
)

;

CREATE SEQUENCE rhn_viet_id_seq;

0707010000017E000081B400000000000000000000000167AE11140000061D000000000000000000000000000000000000003C00000000susemanager-schema/common/tables/rhnVirtualInstanceInfo.sql   --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnVirtualInstanceInfo
(
    name           VARCHAR(128),
    instance_id    NUMERIC NOT NULL
                       CONSTRAINT rhn_vii_viid_fk
                           REFERENCES rhnVirtualInstance (id)
                           ON DELETE CASCADE,
    instance_type  NUMERIC NOT NULL
                       CONSTRAINT rhn_vii_it_fk
                           REFERENCES rhnVirtualInstanceType (id),
    memory_size    NUMERIC,
    vcpus          NUMERIC,
    state          NUMERIC NOT NULL
                       CONSTRAINT rhn_vii_state_fk
                           REFERENCES rhnVirtualInstanceState (id),
    created        TIMESTAMPTZ
                       DEFAULT (current_timestamp) NOT NULL,
    modified       TIMESTAMPTZ
                       DEFAULT (current_timestamp) NOT NULL
)

;

CREATE UNIQUE INDEX rhn_vii_viid_uq
    ON rhnVirtualInstanceInfo (instance_id)
    ;

CREATE SEQUENCE rhn_vii_id_seq;

   0707010000017F000081B400000000000000000000000167AE1114000004E2000000000000000000000000000000000000004200000000susemanager-schema/common/tables/rhnVirtualInstanceInstallLog.sql --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnVirtualInstanceInstallLog
(
    id             NUMERIC NOT NULL
                       CONSTRAINT rhn_viil_id_pk PRIMARY KEY
                       ,
    log_message    VARCHAR(4000) NOT NULL,
    ks_session_id  NUMERIC
                       CONSTRAINT rhn_viil_ks_sid_fk
                           REFERENCES rhnKickstartSession (id)
                           ON DELETE CASCADE,
    created        TIMESTAMPTZ
                       DEFAULT (current_timestamp) NOT NULL,
    modified       TIMESTAMPTZ
                       DEFAULT (current_timestamp) NOT NULL
)

;

CREATE SEQUENCE rhn_viil_id_seq;

  07070100000180000081B400000000000000000000000167AE11140000046E000000000000000000000000000000000000003D00000000susemanager-schema/common/tables/rhnVirtualInstanceState.sql  --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnVirtualInstanceState
(
    id        NUMERIC NOT NULL
                  CONSTRAINT rhn_vis_id_pk PRIMARY KEY
                  ,
    name      VARCHAR(128) NOT NULL,
    label     VARCHAR(128) NOT NULL,
    created   TIMESTAMPTZ
                  DEFAULT (current_timestamp) NOT NULL,
    modified  TIMESTAMPTZ
                  DEFAULT (current_timestamp) NOT NULL
)

;

CREATE UNIQUE INDEX rhn_vis_lbl_id_idx
    ON rhnVirtualInstanceState (label, id);

CREATE SEQUENCE rhn_vis_id_seq;

  07070100000181000081B400000000000000000000000167AE11140000046B000000000000000000000000000000000000003C00000000susemanager-schema/common/tables/rhnVirtualInstanceType.sql   --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnVirtualInstanceType
(
    id        NUMERIC NOT NULL
                  CONSTRAINT rhn_vit_id_pk PRIMARY KEY
                  ,
    name      VARCHAR(128) NOT NULL,
    label     VARCHAR(128) NOT NULL,
    created   TIMESTAMPTZ
                  DEFAULT (current_timestamp) NOT NULL,
    modified  TIMESTAMPTZ
                  DEFAULT (current_timestamp) NOT NULL
)

;

CREATE UNIQUE INDEX rhn_vit_lbl_id_uq
    ON rhnVirtualInstanceType (label, id);

CREATE SEQUENCE rhn_vit_id_seq;

 07070100000182000081B400000000000000000000000167AE111400000406000000000000000000000000000000000000003700000000susemanager-schema/common/tables/rhnVisibleObjects.sql    --
-- Copyright (c) 2008 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnVisibleObjects
(
    pxt_session_id  NUMERIC NOT NULL,
    object_id       NUMERIC NOT NULL,
    object_type     VARCHAR(40) NOT NULL,
    CONSTRAINT rhn_vis_objs_sess_fk FOREIGN KEY (pxt_session_id)
        REFERENCES PXTSessions (id)
            ON DELETE CASCADE
)

;

CREATE UNIQUE INDEX rhn_vis_objs_sess_obj_type_idx
    ON rhnVisibleObjects (pxt_session_id, object_id, object_type);

  07070100000183000081B400000000000000000000000167AE11140000065B000000000000000000000000000000000000003C00000000susemanager-schema/common/tables/rhnWebContactChangeLog.sql   --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnWebContactChangeLog
(
    id                   NUMERIC
                             CONSTRAINT rhn_wcon_cl_id_pk PRIMARY KEY,
    web_contact_id       NUMERIC NOT NULL
                             CONSTRAINT rhn_wcon_cl_wcon_id_fk
                                 REFERENCES web_contact (id)
                                 ON DELETE CASCADE,
    web_contact_from_id  NUMERIC
                             CONSTRAINT rhn_wcon_cl_wcon_from_id_fk
                                 REFERENCES web_contact (id)
                                 ON DELETE SET NULL,
    change_state_id      NUMERIC NOT NULL
                             CONSTRAINT rhn_wcon_cl_csid_fk
                                 REFERENCES rhnWebContactChangeState (id),
    date_completed       TIMESTAMPTZ
                             DEFAULT (current_timestamp) NOT NULL
)

;

CREATE INDEX rhn_wcon_disabled_wcon_id_idx
    ON rhnWebContactChangeLog (web_contact_id)
    ;

CREATE SEQUENCE rhn_wcon_disabled_seq;

 07070100000184000081B400000000000000000000000167AE111400000340000000000000000000000000000000000000003E00000000susemanager-schema/common/tables/rhnWebContactChangeState.sql --
-- Copyright (c) 2008 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnWebContactChangeState
(
    id     NUMERIC
               CONSTRAINT rhn_cont_change_state_id_pk PRIMARY KEY,
    label  VARCHAR(32) NOT NULL
)


;

CREATE SEQUENCE rhn_wcon_change_state_seq;

07070100000185000081B400000000000000000000000167AE1114000003FC000000000000000000000000000000000000003700000000susemanager-schema/common/tables/rhnXccdfBenchmark.sql    --
-- Copyright (c) 2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

CREATE TABLE rhnXccdfBenchmark
(
    id            NUMERIC NOT NULL
                      CONSTRAINT rhn_xccdf_benchmark_id_pk PRIMARY KEY
                      ,
    identifier    VARCHAR(120) NOT NULL,
    version       VARCHAR(80) NOT NULL
)

;

CREATE UNIQUE INDEX rhn_xccdf_benchmark_iv_uq
    ON rhnXccdfBenchmark (identifier, version)
    
    ;

CREATE SEQUENCE rhn_xccdf_benchmark_id_seq;
07070100000186000081B400000000000000000000000167AE111400000474000000000000000000000000000000000000003300000000susemanager-schema/common/tables/rhnXccdfIdent.sql    --
-- Copyright (c) 2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

CREATE TABLE rhnXccdfIdent
(
    id              NUMERIC NOT NULL
                        CONSTRAINT rhn_xccdf_ident_id_pk PRIMARY KEY
                        ,
    identsystem_id  NUMERIC NOT NULL
                        CONSTRAINT rhn_xccdf_ident_system_fk
                            REFERENCES rhnXccdfIdentsystem (id),
    identifier      VARCHAR (255) NOT NULL
)

;

CREATE UNIQUE INDEX rhn_xccdf_ident_isi_uq
    ON rhnXccdfIdent (identsystem_id, identifier)
    
    ;

CREATE SEQUENCE rhn_xccdf_ident_id_seq;
07070100000187000081B400000000000000000000000167AE1114000003B6000000000000000000000000000000000000003900000000susemanager-schema/common/tables/rhnXccdfIdentSystem.sql  --
-- Copyright (c) 2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

CREATE TABLE rhnXccdfIdentSystem
(
    id      NUMERIC NOT NULL
                CONSTRAINT rhn_xccdf_identsytem_id_pk PRIMARY KEY
                ,
    system  VARCHAR(80) NOT NULL
)

;

CREATE UNIQUE INDEX rhn_xccdf_identsystem_id_uq
    ON rhnXccdfIdentsystem (system)
    
    ;

CREATE SEQUENCE rhn_xccdf_identsytem_id_seq;
  07070100000188000081B400000000000000000000000167AE1114000003F1000000000000000000000000000000000000003500000000susemanager-schema/common/tables/rhnXccdfProfile.sql  --
-- Copyright (c) 2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

CREATE TABLE rhnXccdfProfile
(
    id            NUMERIC NOT NULL
                      CONSTRAINT rhn_xccdf_profile_id_pk PRIMARY KEY
                      ,
    identifier    VARCHAR(120) NOT NULL,
    title         VARCHAR(120) NOT NULL
)

;

CREATE UNIQUE INDEX rhn_xccdf_profile_it_uq
    ON rhnXccdfProfile (identifier, title)
    
    ;

CREATE SEQUENCE rhn_xccdf_profile_id_seq;
   07070100000189000081B400000000000000000000000167AE1114000004B0000000000000000000000000000000000000003A00000000susemanager-schema/common/tables/rhnXccdfRuleIdentMap.sql --
-- Copyright (c) 2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

CREATE TABLE rhnXccdfRuleIdentMap
(
    rresult_id    NUMERIC NOT NULL
                      CONSTRAINT rhn_xccdf_rim_rresult_fk
                          REFERENCES rhnXccdfRuleresult (id)
                          ON DELETE CASCADE,
    ident_id      NUMERIC NOT NULL
                      CONSTRAINT rhn_xccdf_rim_ident_fk
                          REFERENCES rhnXccdfIdent (id)
)

;

CREATE UNIQUE INDEX rhn_xccdf_rim_ri_uq
    ON rhnXccdfRuleIdentMap (rresult_id, ident_id)
    
    ;

CREATE INDEX rhn_xccdf_rim_ident_idx
    ON rhnXccdfRuleIdentMap (ident_id)
    
    ;
0707010000018A000081B400000000000000000000000167AE11140000050D000000000000000000000000000000000000003800000000susemanager-schema/common/tables/rhnXccdfRuleresult.sql   --
-- Copyright (c) 2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

CREATE TABLE rhnXccdfRuleresult
(
    id            NUMERIC NOT NULL
                      CONSTRAINT rhn_xccdf_rresult_id_pk PRIMARY KEY
                      ,
    testresult_id NUMERIC NOT NULL
                      CONSTRAINT rhn_xccdf_rresult_tresult_fk
                          REFERENCES rhnXccdfTestresult (id)
                          ON DELETE CASCADE,
    result_id     NUMERIC NOT NULL
                      CONSTRAINT rhn_xccdf_rresult_result_fk
                          REFERENCES rhnXccdfRuleresultType (id)
)

;

CREATE INDEX rhn_xccdf_rresult_tresult_idx
    ON rhnXccdfRuleresult (testresult_id)
    
    ;

CREATE SEQUENCE rhn_xccdf_rresult_id_seq;
   0707010000018B000081B400000000000000000000000167AE1114000003F2000000000000000000000000000000000000003C00000000susemanager-schema/common/tables/rhnXccdfRuleresultType.sql   --
-- Copyright (c) 2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

CREATE TABLE rhnXccdfRuleresultType
(
    id            NUMERIC NOT NULL
                      CONSTRAINT rhn_xccdf_rresult_t_id_pk PRIMARY KEY
                      ,
    abbreviation  CHAR(1) NOT NULL,
    label         VARCHAR(16) NOT NULL,
    description   VARCHAR(120) NOT NULL
)

;

CREATE UNIQUE INDEX rhn_xccdf_rresult_t_label_uq
    ON rhnXccdfRuleresultType (label)
    
    ;
  0707010000018C000081B400000000000000000000000167AE111400000705000000000000000000000000000000000000003800000000susemanager-schema/common/tables/rhnXccdfTestresult.sql   --
-- Copyright (c) 2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

CREATE TABLE rhnXccdfTestresult
(
    id             NUMERIC NOT NULL
                       CONSTRAINT rhn_xccdf_tresult_id_pk PRIMARY KEY
                       ,
    server_id      NUMERIC NOT NULL
                       CONSTRAINT rhn_xccdf_tresult_srvr_fk
                           REFERENCES rhnServer (id)
                           ON DELETE CASCADE,
    action_scap_id NUMERIC NOT NULL
                       CONSTRAINT rhn_xccdf_tresult_act_fk
                           REFERENCES rhnActionScap (id)
                           ON DELETE CASCADE,
    benchmark_id   NUMERIC NOT NULL
                       CONSTRAINT rhn_xccdf_tresult_bench_fk
                           REFERENCES rhnXccdfBenchmark (id),
    profile_id     NUMERIC NOT NULL
                       CONSTRAINT rhn_xccdf_tresult_profile_fk
                           REFERENCES rhnXccdfProfile (id),
    identifier     VARCHAR(120) NOT NULL,
    start_time     TIMESTAMPTZ,
    end_time       TIMESTAMPTZ NOT NULL,
    errors         BYTEA
)


;

CREATE UNIQUE INDEX rhn_xccdf_tresult_sa_uq
    ON rhnXccdfTestresult (server_id, action_scap_id)
    
    ;

CREATE SEQUENCE rhn_xccdf_tresult_id_seq;
   0707010000018D000081B400000000000000000000000167AE111400000316000000000000000000000000000000000000003500000000susemanager-schema/common/tables/suseAnsiblePath.sql  
CREATE TABLE suseAnsiblePath(

    id NUMERIC NOT NULL
        CONSTRAINT suse_ansible_path_id_pk PRIMARY KEY,

    server_id NUMERIC NOT NULL
        CONSTRAINT suse_ansible_path_sid_fk
        REFERENCES rhnServer(id)
        ON DELETE CASCADE,

    path VARCHAR(1024) NOT NULL,

    type VARCHAR(16) NOT NULL
        CONSTRAINT suse_ansible_path_type_ck
        CHECK (type in ('inventory', 'playbook')),

    created     TIMESTAMPTZ
        DEFAULT (current_timestamp) NOT NULL,

    modified    TIMESTAMPTZ
        DEFAULT (current_timestamp) NOT NULL
);

CREATE SEQUENCE suse_ansible_path_seq;

CREATE UNIQUE INDEX suse_ansible_path_type_uq
    ON suseAnsiblePath(server_id, path, type);

CREATE UNIQUE INDEX suse_ansible_type_path_uq
    ON suseAnsiblePath(server_id, type, path);

  0707010000018E000081B400000000000000000000000167AE111400000587000000000000000000000000000000000000003900000000susemanager-schema/common/tables/suseCVEImageChannel.sql  --
-- Copyright (c) 2017 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

CREATE TABLE suseCVEImageChannel
(
    image_info_id    NUMERIC NOT NULL
                     CONSTRAINT suse_cveimg_iid_fk
                         REFERENCES suseImageInfo (id)
                         ON DELETE CASCADE,
    channel_id   NUMERIC NOT NULL
                     CONSTRAINT suse_cveimg_cid_fk
                         REFERENCES rhnChannel (id)
                         ON DELETE CASCADE,
    channel_rank NUMERIC NOT NULL,
    created   TIMESTAMPTZ
                  DEFAULT (current_timestamp) NOT NULL,
    modified  TIMESTAMPTZ
                  DEFAULT (current_timestamp) NOT NULL
)

;

CREATE UNIQUE INDEX suse_cveimg_iid_cid_uq
    ON suseCVEImageChannel (image_info_id, channel_id)
    ;

CREATE INDEX suse_cveimg_cid_idx
    ON suseCVEImageChannel (channel_id)
    
    ;

 0707010000018F000081B400000000000000000000000167AE111400000517000000000000000000000000000000000000003600000000susemanager-schema/common/tables/suseCloudRmtHost.sql --
-- Copyright (c) 2021 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

CREATE TABLE suseCloudRmtHost
(
    id               NUMERIC                                 NOT NULL
        CONSTRAINT suseCloudRmtHost_pk PRIMARY KEY,
    hostname         VARCHAR(255)                            NOT NULL,
    ip_address       VARCHAR(39)                             NOT NULL,
    ssl_cert         text,
    created          TIMESTAMPTZ DEFAULT (current_timestamp) NOT NULL,
    modified         TIMESTAMPTZ DEFAULT (current_timestamp) NOT NULL,
    payg_ssh_data_id NUMERIC                                 NOT NULL,
    CONSTRAINT payg_ssh_data_id_fk
        FOREIGN KEY (payg_ssh_data_id) REFERENCES susePaygSshData (id)
);

CREATE SEQUENCE susecloudrmthost_id_seq; 07070100000190000081B400000000000000000000000167AE111400000576000000000000000000000000000000000000003A00000000susemanager-schema/common/tables/suseCVEServerChannel.sql --
-- Copyright (c) 2013 SUSE
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

CREATE TABLE suseCVEServerChannel
(
    server_id    NUMERIC NOT NULL
                     CONSTRAINT suse_cvesc_sid_fk
                         REFERENCES rhnServer (id)
                         ON DELETE CASCADE,
    channel_id   NUMERIC NOT NULL
                     CONSTRAINT suse_cvesc_cid_fk
                         REFERENCES rhnChannel (id)
                         ON DELETE CASCADE,
    channel_rank NUMERIC NOT NULL,
    created   TIMESTAMPTZ
                  DEFAULT (current_timestamp) NOT NULL,
    modified  TIMESTAMPTZ
                  DEFAULT (current_timestamp) NOT NULL
)

;

CREATE UNIQUE INDEX suse_cvesc_sid_cid_uq
    ON suseCVEServerChannel (server_id, channel_id)
    ;

CREATE INDEX suse_cvesc_cid_idx
    ON suseCVEServerChannel (channel_id)
    
    ;

  07070100000191000081B400000000000000000000000167AE111400000534000000000000000000000000000000000000003C00000000susemanager-schema/common/tables/suseChannelAccessToken.sql   --
-- Copyright (c) 2017 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

CREATE TABLE suseChannelAccessToken
(
    id               NUMERIC NOT NULL
                         CONSTRAINT suse_chan_access_token_id_pk PRIMARY KEY,
    minion_id        NUMERIC
                         CONSTRAINT suse_chan_access_token_mid_fk
                             REFERENCES suseMinionInfo (server_id)
                             ON DELETE SET NULL,
    token            VARCHAR(4000) NOT NULL,
    created          TIMESTAMPTZ NOT NULL,
    expiration       TIMESTAMPTZ NOT NULL,
    valid            CHAR(1) DEFAULT ('N') NOT NULL CHECK (valid in ('Y', 'N'))
)

;

CREATE SEQUENCE suse_chan_access_token_id_seq;

CREATE UNIQUE INDEX suse_accesstoken_token_uq
    ON suseChannelAccessToken (token);
07070100000192000081B400000000000000000000000167AE11140000051C000000000000000000000000000000000000004300000000susemanager-schema/common/tables/suseChannelAccessTokenChannel.sql    --
-- Copyright (c) 2017 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

CREATE TABLE suseChannelAccessTokenChannel
(
    token_id    NUMERIC NOT NULL
                    CONSTRAINT suse_catc_tid_fk
                        REFERENCES suseChannelAccessToken (id)
                        ON DELETE CASCADE,
    channel_id  NUMERIC NOT NULL
                    CONSTRAINT suse_catc_cid_fk
                        REFERENCES rhnChannel (id)
                        ON DELETE CASCADE,
    created     TIMESTAMPTZ
                    DEFAULT (current_timestamp) NOT NULL,
    modified    TIMESTAMPTZ
                    DEFAULT (current_timestamp) NOT NULL
)

;

CREATE UNIQUE INDEX suse_catc_tid_cid_uq
    ON suseChannelAccessTokenChannel (token_id, channel_id)
    ;
07070100000193000081B400000000000000000000000167AE11140000084D000000000000000000000000000000000000003900000000susemanager-schema/common/tables/suseChannelTemplate.sql  --
-- Copyright (c) 2024 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--

CREATE TABLE
suseChannelTemplate
(
    id                     BIGINT CONSTRAINT suse_chantpl_id_pk PRIMARY KEY
                                  GENERATED ALWAYS AS IDENTITY,
    product_id             NUMERIC NOT NULL
                                  CONSTRAINT suse_chantpl_pid_fk
                                  REFERENCES suseProducts (id)
                                  ON DELETE CASCADE,
    root_product_id        NUMERIC NOT NULL
                                  CONSTRAINT suse_chantpl_rpid_fk
                                  REFERENCES suseProducts (id)
                                  ON DELETE CASCADE,
    repo_id                NUMERIC NOT NULL
                                  CONSTRAINT suse_chantpl_rid_fk
                                  REFERENCES suseSCCRepository (id)
                                  ON DELETE CASCADE,
    channel_label          VARCHAR(128) NOT NULL,
    parent_channel_label   VARCHAR(128),
    channel_name           VARCHAR(256) NOT NULL,
    mandatory              BOOLEAN DEFAULT FALSE NOT NULL,
    update_tag             VARCHAR(128),
    gpg_key_url            VARCHAR(256),
    gpg_key_id             VARCHAR(14),
    gpg_key_fp             VARCHAR(50),
    created                TIMESTAMPTZ
                           DEFAULT (current_timestamp) NOT NULL,
    modified               TIMESTAMPTZ
                           DEFAULT (current_timestamp) NOT NULL
);

CREATE UNIQUE INDEX suse_chantpl_pid_rpid_rid_uq
ON suseChannelTemplate (product_id, root_product_id, repo_id);

CREATE INDEX suse_chantpl_rpid_idx
ON suseChannelTemplate (root_product_id);

CREATE INDEX suse_chantpl_chl_idx
ON suseChannelTemplate (channel_label);
   07070100000194000081B400000000000000000000000167AE1114000006BA000000000000000000000000000000000000003C00000000susemanager-schema/common/tables/suseContentEnvironment.sql   --
-- Copyright (c) 2018 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

CREATE TABLE suseContentEnvironment(
    id          NUMERIC NOT NULL
                    CONSTRAINT suse_ct_env_id_pk PRIMARY KEY,
    project_id  NUMERIC
                    CONSTRAINT suse_ct_env_pid_fk
                        REFERENCES suseContentProject(id)
                        ON DELETE CASCADE,
    label       VARCHAR(16) NOT NULL,
    name        VARCHAR(128) NOT NULL,
    description TEXT,
    version     NUMERIC,
    next_env_id NUMERIC
                    CONSTRAINT suse_ct_env_nid_fk
                        REFERENCES suseContentEnvironment(id),
    created     TIMESTAMPTZ
                    DEFAULT (current_timestamp) NOT NULL,
    modified    TIMESTAMPTZ
                    DEFAULT (current_timestamp) NOT NULL

)

;

CREATE SEQUENCE suse_ct_env_seq;

CREATE UNIQUE INDEX suse_ct_env_pid_lbl_uq
    ON suseContentEnvironment(project_id, label);

CREATE UNIQUE INDEX suse_ct_env_pid_name_uq
    ON suseContentEnvironment(project_id, name);

-- conflict with hibernate way to update things
-- CREATE UNIQUE INDEX suse_ct_env_nid_uq
--     ON suseContentEnvironment(next_env_id);
  07070100000195000081B400000000000000000000000167AE11140000057F000000000000000000000000000000000000004200000000susemanager-schema/common/tables/suseContentEnvironmentTarget.sql --
-- Copyright (c) 2018 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

CREATE TABLE suseContentEnvironmentTarget(
    id         NUMERIC NOT NULL
                   CONSTRAINT suse_ct_env_tgt_id_pk PRIMARY KEY,
    env_id     NUMERIC
                   CONSTRAINT suse_ct_env_tgt_eid_fk
                       REFERENCES suseContentEnvironment(id)
                       ON DELETE CASCADE,
    type       VARCHAR(16) NOT NULL,
    status     VARCHAR(32) NOT NULL DEFAULT 'NEW',
    channel_id NUMERIC
                   CONSTRAINT suse_ct_env_tgt_chanid_fk
                       REFERENCES rhnChannel(id),
    built_time TIMESTAMPTZ
)

;

CREATE SEQUENCE suse_ct_env_tgt_seq;

CREATE UNIQUE INDEX suse_ct_env_tgt_env_cid_uq
    ON suseContentEnvironmentTarget(env_id, channel_id);

CREATE INDEX suse_ct_env_tgt_type
    ON suseContentEnvironmentTarget(type);

 07070100000196000081B400000000000000000000000167AE1114000005BE000000000000000000000000000000000000003700000000susemanager-schema/common/tables/suseContentFilter.sql    --
-- Copyright (c) 2018 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

CREATE TABLE suseContentFilter(
    id       NUMERIC NOT NULL
                 CONSTRAINT suse_ct_filter_id_pk PRIMARY KEY,
    org_id   NUMERIC NOT NULL
                 CONSTRAINT suse_ct_project_oid_fk
                     REFERENCES web_customer(id)
                     ON DELETE CASCADE,
    type     VARCHAR(16) NOT NULL,
    rule     VARCHAR(16) NOT NULL,
    name     VARCHAR(128) NOT NULL,
    matcher  VARCHAR(32) NOT NULL,
    field    VARCHAR(32) NOT NULL,
    value    VARCHAR(128),
    created  TIMESTAMPTZ
                 DEFAULT (current_timestamp) NOT NULL,
    modified TIMESTAMPTZ
                 DEFAULT (current_timestamp) NOT NULL

)

;

CREATE SEQUENCE suse_ct_filter_seq;

CREATE UNIQUE INDEX suse_ct_filter_org_name_uq
    ON suseContentFilter(org_id, name);

CREATE INDEX suse_ct_filter_type
    ON suseContentFilter(type);
  07070100000197000081B400000000000000000000000167AE111400000503000000000000000000000000000000000000003E00000000susemanager-schema/common/tables/suseContentFilterProject.sql --
-- Copyright (c) 2018 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

CREATE TABLE suseContentFilterProject(
    id         NUMERIC NOT NULL
                   CONSTRAINT suse_ct_f_p_id_pk PRIMARY KEY,
    filter_id  NUMERIC NOT NULL
                   CONSTRAINT suse_ct_filter_fid_fk
                       REFERENCES suseContentFilter(id)
                       ON DELETE CASCADE,
    project_id NUMERIC NOT NULL
                   CONSTRAINT suse_ct_filter_pid_fk
                       REFERENCES suseContentProject(id)
                       ON DELETE CASCADE,
    state      VARCHAR(16)
)

;

CREATE SEQUENCE suse_ct_f_p_seq;

CREATE UNIQUE INDEX suse_ct_filter_project_uq
    ON suseContentFilterProject(filter_id, project_id);
 07070100000198000081B400000000000000000000000167AE111400000598000000000000000000000000000000000000003800000000susemanager-schema/common/tables/suseContentProject.sql   --
-- Copyright (c) 2018 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

CREATE TABLE suseContentProject(
    id          NUMERIC NOT NULL
                    CONSTRAINT suse_ct_project_id_pk PRIMARY KEY,
    name        VARCHAR(128) NOT NULL,
    org_id      NUMERIC NOT NULL
                    CONSTRAINT suse_ct_project_oid_fk
                    REFERENCES web_customer(id)
                    ON DELETE CASCADE,
    label       VARCHAR(24) NOT NULL,
    description TEXT,
    first_env_id NUMERIC,
    created     TIMESTAMPTZ
                    DEFAULT (current_timestamp) NOT NULL,
    modified    TIMESTAMPTZ
                    DEFAULT (current_timestamp) NOT NULL

)

;

CREATE SEQUENCE suse_ct_project_seq;

CREATE UNIQUE INDEX suse_ct_project_lblid_uq
    ON suseContentProject(label);

CREATE UNIQUE INDEX suse_ct_prj_nameid_oid_uq
    ON suseContentProject(org_id, name);

07070100000199000081B400000000000000000000000167AE111400000580000000000000000000000000000000000000004400000000susemanager-schema/common/tables/suseContentProjectHistoryEntry.sql   --
-- Copyright (c) 2018 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

CREATE TABLE suseContentProjectHistoryEntry(
    id         NUMERIC NOT NULL
                   CONSTRAINT suse_ct_prj_hist_id_pk PRIMARY KEY,
    project_id NUMERIC NOT NULL
                   CONSTRAINT suse_ct_prj_hist_prjid_fk
                       REFERENCES suseContentProject(id)
                       ON DELETE CASCADE,
    message    TEXT,
    version    NUMERIC NOT NULL,
    created    TIMESTAMPTZ
                   DEFAULT (current_timestamp) NOT NULL,
    user_id    NUMERIC
                   CONSTRAINT suse_ct_prj_hist_uid_fk
                       REFERENCES web_contact (id)
                       ON DELETE SET NULL
)

;

CREATE SEQUENCE suse_ct_prj_hist_seq;

CREATE UNIQUE INDEX suse_ct_prj_hist_pid_ver_uq
    ON suseContentProjectHistoryEntry(project_id, version);
0707010000019A000081B400000000000000000000000167AE111400000594000000000000000000000000000000000000003E00000000susemanager-schema/common/tables/suseContentProjectSource.sql --
-- Copyright (c) 2018 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

CREATE TABLE suseContentProjectSource(
    id         NUMERIC NOT NULL
                   CONSTRAINT suse_ct_prj_src_id_pk PRIMARY KEY,
    type       VARCHAR(16) NOT NULL,
    state      VARCHAR(16) NOT NULL,
    position   NUMERIC,
    project_id NUMERIC NOT NULL
                   CONSTRAINT suse_ct_prj_src_prjid_fk
                       REFERENCES suseContentProject(id)
                       ON DELETE CASCADE,
    channel_id NUMERIC
                   CONSTRAINT suse_ct_prj_src_chanid_fk
                       REFERENCES rhnChannel(id)
                       ON DELETE CASCADE
)

;

CREATE SEQUENCE suse_ct_prj_src_seq;

CREATE UNIQUE INDEX suse_ct_prj_src_pid_cid_uq
    ON suseContentProjectSource(project_id, channel_id);

CREATE INDEX suse_ct_prj_src_type
    ON suseContentProjectSource(type);
0707010000019B000081B400000000000000000000000167AE1114000000A5000000000000000000000000000000000000003F00000000susemanager-schema/common/tables/suseContentProject_alters.sql    ALTER TABLE suseContentProject
  ADD CONSTRAINT suse_ct_project_fenvid_fk
  FOREIGN KEY (first_env_id)
  REFERENCES suseContentEnvironment(id)
  ON DELETE SET NULL;
   0707010000019C000081B400000000000000000000000167AE111400000A92000000000000000000000000000000000000003500000000susemanager-schema/common/tables/suseCredentials.sql  --
-- Copyright (c) 2012 Novell
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

CREATE TABLE suseCredentials
(
    id                  NUMERIC NOT NULL
                            CONSTRAINT suse_credentials_pk PRIMARY KEY,
    user_id             NUMERIC NULL
                            CONSTRAINT suse_credentials_user_fk
                            REFERENCES web_contact (id)
                            ON DELETE CASCADE,
    type                VARCHAR(128) DEFAULT ('scc') NOT NULL
                             CONSTRAINT rhn_type_ck
                             CHECK (type IN ('scc', 'vhm', 'registrycreds', 'cloudrmt', 'reportcreds', 'rhui')),
    url                 VARCHAR(256),
    username            VARCHAR(64),
    password            VARCHAR(4096),
    created             TIMESTAMPTZ DEFAULT (current_timestamp) NOT NULL,
    modified            TIMESTAMPTZ DEFAULT (current_timestamp) NOT NULL,
    extra_auth          bytea,
    payg_ssh_data_id    NUMERIC
                            CONSTRAINT suse_credentials_payg_ssh_data_id_fk REFERENCES susePaygSshData (id)
);

ALTER TABLE susecredentials
    ADD CONSTRAINT suse_credentials_payg_ssh_data_id_uq UNIQUE (payg_ssh_data_id);

ALTER TABLE susecredentials
    ADD CONSTRAINT cred_type_check CHECK (
        CASE type
            WHEN 'scc' THEN
                username is not null and username <> ''
                    and password is not null and password <> ''
            WHEN 'cloudrmt' THEN
                username is not null and username <> ''
                    and password is not null and password <> ''
                    and url is not null and url <> ''
            WHEN 'vhm' THEN
                username is not null and username <> ''
                    and password is not null and password <> ''
            WHEN 'registrycreds' THEN
                username is not null and username <> ''
                    and password is not null and password <> ''
            WHEN 'reportcreds' THEN
                username is not null and username <> ''
                    and password is not null and password <> ''
        END
    );

CREATE SEQUENCE suse_credentials_id_seq;
  0707010000019D000081B400000000000000000000000167AE111400000353000000000000000000000000000000000000003800000000susemanager-schema/common/tables/suseDeltaImageInfo.sql   CREATE TABLE suseDeltaImageInfo
(
    source_image_id NUMERIC NOT NULL
                     CONSTRAINT suse_deltaimg_source_fk
                     REFERENCES suseImageInfo (id) ON DELETE CASCADE,

    target_image_id NUMERIC NOT NULL
                     CONSTRAINT suse_deltaimg_target_fk
                     REFERENCES suseImageInfo (id) ON DELETE CASCADE,

    pillar_id       NUMERIC
                     CONSTRAINT suse_deltaimg_pillar_fk
                       REFERENCES suseSaltPillar (id)
                       ON DELETE SET NULL,

    file           TEXT NOT NULL,

    created        TIMESTAMPTZ
                     DEFAULT (current_timestamp) NOT NULL,
    modified       TIMESTAMPTZ
                     DEFAULT (current_timestamp) NOT NULL,

    CONSTRAINT suse_delta_image_info_pk PRIMARY KEY (source_image_id, target_image_id)
);

 0707010000019E000081B400000000000000000000000167AE111400000378000000000000000000000000000000000000003B00000000susemanager-schema/common/tables/suseDockerfileProfile.sql    --
-- Copyright (c) 2017 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

CREATE TABLE suseDockerfileProfile
(
    profile_id  NUMERIC NOT NULL
                  CONSTRAINT suse_dockfileprof_prid_fk
                     REFERENCES suseImageProfile (profile_id)
                     ON DELETE CASCADE,
    path        VARCHAR(1024) NOT NULL
)

;
0707010000019F000081B400000000000000000000000167AE1114000002F8000000000000000000000000000000000000002E00000000susemanager-schema/common/tables/suseEula.sql --
-- Copyright (c) 2014 SUSE LINUX Products GmbH, Nuernberg, Germany.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--


CREATE TABLE suseEula
(
    id          NUMERIC NOT NULL
                    CONSTRAINT suse_eula_id_pk PRIMARY KEY,
    text        BYTEA,
    checksum    VARCHAR(64) NOT NULL
)

;

CREATE SEQUENCE suse_eula_id_seq;

CREATE UNIQUE INDEX suse_eula_checksum
    on suseEula (checksum)
    ;

070701000001A0000081B400000000000000000000000167AE11140000049D000000000000000000000000000000000000003B00000000susemanager-schema/common/tables/suseImageBuildHistory.sql    --
-- Copyright (c) 2017 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

CREATE TABLE suseImageBuildHistory
(
    id             NUMERIC NOT NULL
                     CONSTRAINT suse_bldhst_id_pk PRIMARY KEY,
    image_info_id  NUMERIC NOT NULL,
    revision_num   NUMERIC NOT NULL,
    created        TIMESTAMPTZ
                     DEFAULT (current_timestamp) NOT NULL,
    modified       TIMESTAMPTZ
                     DEFAULT (current_timestamp) NOT NULL,
    CONSTRAINT suse_bldhst_imginfo_fk FOREIGN KEY (image_info_id)
        REFERENCES suseImageInfo (id) ON DELETE CASCADE
)

;

CREATE SEQUENCE suse_img_buildhistory_id_seq;
   070701000001A1000081B400000000000000000000000167AE1114000007D0000000000000000000000000000000000000003E00000000susemanager-schema/common/tables/suseImageCustomDataValue.sql --
-- Copyright (c) 2017 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

CREATE TABLE suseImageCustomDataValue
(
    id                NUMERIC NOT NULL
                          CONSTRAINT suse_icdv_id_pk PRIMARY KEY,
    image_info_id     NUMERIC NOT NULL
                          CONSTRAINT suse_icdv_prid_fk
                              REFERENCES suseImageInfo (id)
                              ON DELETE CASCADE,
    key_id            NUMERIC NOT NULL
                          CONSTRAINT suse_icdv_kid_fk
                              REFERENCES rhnCustomDataKey (id)
                              ON DELETE CASCADE,
    value             VARCHAR(4000),
    created_by        NUMERIC
                          CONSTRAINT suse_icdv_cb_fk
                              REFERENCES web_contact (id)
                              ON DELETE SET NULL,
    last_modified_by  NUMERIC
                          CONSTRAINT suse_icdv_lmb_fk
                              REFERENCES web_contact (id)
                              ON DELETE SET NULL,
    created           TIMESTAMPTZ
                          DEFAULT (current_timestamp) NOT NULL,
    modified          TIMESTAMPTZ
                          DEFAULT (current_timestamp) NOT NULL
)

;

CREATE UNIQUE INDEX suse_icdv_imgid_kid_uq
    ON suseImageCustomDataValue (image_info_id, key_id);

CREATE INDEX suse_icdv_kid_idx
    ON suseImageCustomDataValue (key_id);

CREATE SEQUENCE suse_icdv_id_seq;
070701000001A2000081B400000000000000000000000167AE111400000572000000000000000000000000000000000000003300000000susemanager-schema/common/tables/suseImageFile.sql    --
-- Copyright (c) 2022 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE suseImageFile
(
    id             NUMERIC NOT NULL
                     CONSTRAINT suse_imgfile_fileid_pk PRIMARY KEY,
    image_info_id  NUMERIC NOT NULL,
    file           TEXT NOT NULL,
    type           VARCHAR(16) NOT NULL,
    external       CHAR(1) DEFAULT ('N') NOT NULL,
    checksum_id    NUMERIC
                     CONSTRAINT suse_fileinfo_chsum_fk
                     REFERENCES rhnChecksum (id),
    created        TIMESTAMPTZ
                     DEFAULT (current_timestamp) NOT NULL,
    modified       TIMESTAMPTZ
                     DEFAULT (current_timestamp) NOT NULL,

    CONSTRAINT suse_imgfile_imginfo_fk FOREIGN KEY (image_info_id)
        REFERENCES suseImageInfo (id) ON DELETE CASCADE
);

CREATE SEQUENCE suse_image_file_id_seq;
  070701000001A3000081B400000000000000000000000167AE111400000B02000000000000000000000000000000000000003300000000susemanager-schema/common/tables/suseImageInfo.sql    --
-- Copyright (c) 2017 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

CREATE TABLE suseImageInfo
(
    id             NUMERIC NOT NULL
                     CONSTRAINT suse_imginfo_imgid_pk PRIMARY KEY,
    name           VARCHAR(128) NOT NULL,
    version        VARCHAR(128),
    image_type     VARCHAR(32) NOT NULL,
    checksum_id    NUMERIC
                     CONSTRAINT suse_imginfo_chsum_fk
                       REFERENCES rhnChecksum (id),
    image_arch_id  NUMERIC NOT NULL
                       CONSTRAINT suse_imginfo_said_fk
                           REFERENCES rhnServerArch (id),
    curr_revision_num   NUMERIC,
    org_id         NUMERIC NOT NULL
                     CONSTRAINT suse_imginfo_oid_fk
                       REFERENCES web_customer (id)
                       ON DELETE CASCADE,
    build_action_id     NUMERIC,
    inspect_action_id   NUMERIC,
    profile_id     NUMERIC
                     CONSTRAINT suse_imginfo_pid_fk
                       REFERENCES suseImageProfile (profile_id)
                       ON DELETE SET NULL,
    store_id       NUMERIC
                      CONSTRAINT suse_imginfo_sid_fk
                         REFERENCES suseImageStore (id)
                         ON DELETE SET NULL,
    build_server_id  NUMERIC
                      CONSTRAINT suse_imginfo_bsid_fk
                         REFERENCES suseMinionInfo (server_id)
                         ON DELETE SET NULL,
    external_image CHAR(1) DEFAULT ('N') NOT NULL,

    obsolete       CHAR(1) DEFAULT ('N') NOT NULL,

    built          CHAR(1) DEFAULT ('N') NOT NULL,

    pillar_id      NUMERIC
                     CONSTRAINT suse_imginfo_pillar_fk
                       REFERENCES suseSaltPillar (id)
                       ON DELETE SET NULL,
    log            TEXT,

    created        TIMESTAMPTZ
                     DEFAULT (current_timestamp) NOT NULL,
    modified       TIMESTAMPTZ
                     DEFAULT (current_timestamp) NOT NULL,
    CONSTRAINT suse_imginfo_bldaid_fk FOREIGN KEY (build_action_id)
        REFERENCES rhnAction (id) ON DELETE SET NULL,
    CONSTRAINT suse_imginfo_insaid_fk FOREIGN KEY (inspect_action_id)
        REFERENCES rhnAction (id) ON DELETE SET NULL
)

;

CREATE SEQUENCE suse_imginfo_imgid_seq;
  070701000001A4000081B400000000000000000000000167AE111400000408000000000000000000000000000000000000003A00000000susemanager-schema/common/tables/suseImageInfoChannel.sql --
-- Copyright (c) 2017 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--
CREATE TABlE suseImageInfoChannel (
    channel_id      NUMERIC NOT NULL
                        CONSTRAINT suse_imginfoc_cid_fk
                        REFERENCES rhnChannel (id)
                        ON DELETE CASCADE,
    image_info_id   NUMERIC NOT NULL
                        CONSTRAINT suse_imginfoc_iiid_fk
                        REFERENCES suseImageInfo (id)
                        ON DELETE CASCADE
);
070701000001A5000081B400000000000000000000000167AE111400000408000000000000000000000000000000000000004300000000susemanager-schema/common/tables/suseImageInfoInstalledProduct.sql    --
-- Copyright (c) 2017 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
--

create table
suseImageInfoInstalledProduct
(
    image_info_id         NUMERIC
                            CONSTRAINT suse_iiip_ii_id_fk
                            REFERENCES suseImageInfo (id)
                            ON DELETE CASCADE
                            not null,
    installed_product_id  NUMERIC
                            CONSTRAINT suse_iiip_ip_id_fk
                            REFERENCES suseInstalledProduct (id)
                            not null
);

CREATE UNIQUE INDEX suse_iiip_inprod_uq
    ON suseImageInfoInstalledProduct (image_info_id, installed_product_id)
    ;
070701000001A6000081B400000000000000000000000167AE11140000055D000000000000000000000000000000000000003A00000000susemanager-schema/common/tables/suseImageInfoPackage.sql --
-- Copyright (c) 2017 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--
CREATE TABLE suseImageInfoPackage
(
    image_info_id    NUMERIC NOT NULL
                         REFERENCES suseImageInfo (id)
                             ON DELETE CASCADE,
    name_id          NUMERIC NOT NULL
                         REFERENCES rhnPackageName (id),
    evr_id           NUMERIC NOT NULL
                         REFERENCES rhnPackageEVR (id),
    package_arch_id  NUMERIC
                         REFERENCES rhnPackageArch (id),
    created          TIMESTAMPTZ
                         DEFAULT (current_timestamp) NOT NULL,
    installtime      TIMESTAMPTZ
)


;

CREATE UNIQUE INDEX suse_ip_inep_uq
    ON suseImageInfoPackage (image_info_id, name_id, evr_id, package_arch_id)
    
    ;

CREATE SEQUENCE suse_image_package_id_seq;
   070701000001A7000081B400000000000000000000000167AE1114000006A4000000000000000000000000000000000000003600000000susemanager-schema/common/tables/suseImageProfile.sql --
-- Copyright (c) 2017 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

CREATE TABLE suseImageProfile
(
    profile_id     NUMERIC NOT NULL
                     CONSTRAINT suse_imgprof_prid_pk PRIMARY KEY,
    label          VARCHAR(128) NOT NULL,
    org_id         NUMERIC NOT NULL
                     CONSTRAINT suse_imgprof_oid_fk
                       REFERENCES web_customer (id)
                       ON DELETE CASCADE,
    token_id       NUMERIC
                     CONSTRAINT suse_imgprof_tk_fk
                       REFERENCES rhnRegToken (id)
                       ON DELETE SET NULL,
    image_type     VARCHAR(32) NOT NULL,
    target_store_id NUMERIC NOT NULL
                      CONSTRAINT suse_imgprof_tsid_fk
                         REFERENCES suseImageStore (id)
                         ON DELETE CASCADE,
    created        TIMESTAMPTZ
                     DEFAULT (current_timestamp) NOT NULL,
    modified       TIMESTAMPTZ
                     DEFAULT (current_timestamp) NOT NULL
)

;

CREATE UNIQUE INDEX suse_imgprof_oid_label_uq
    ON suseImageProfile (org_id, label)
        ;

CREATE SEQUENCE suse_imgprof_prid_seq;
070701000001A8000081B400000000000000000000000167AE1114000004A2000000000000000000000000000000000000003900000000susemanager-schema/common/tables/suseImageRepoDigest.sql  --
-- Copyright (c) 2017 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

CREATE TABLE suseImageRepoDigest
(
    id             NUMERIC NOT NULL
                     CONSTRAINT suse_rdigest_id_pk PRIMARY KEY,
    image_info_id    NUMERIC NOT NULL,
    repo_digest    VARCHAR(255) NOT NULL,
    created        TIMESTAMPTZ
                     DEFAULT (current_timestamp) NOT NULL,
    modified       TIMESTAMPTZ
                     DEFAULT (current_timestamp) NOT NULL,
    CONSTRAINT suse_rdigest_imginfo_fk FOREIGN KEY (image_info_id)
        REFERENCES suseImageInfo (id) ON DELETE CASCADE
)

;

CREATE SEQUENCE suse_img_repodigest_id_seq;
  070701000001A9000081B400000000000000000000000167AE1114000006A8000000000000000000000000000000000000003400000000susemanager-schema/common/tables/suseImageStore.sql   --
-- Copyright (c) 2017 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

CREATE TABLE suseImageStore
(
    id             NUMERIC NOT NULL
                     CONSTRAINT suse_imgstore_id_pk PRIMARY KEY,
    label          VARCHAR(128) NOT NULL,
    uri            VARCHAR(512) NOT NULL,
    store_type_id  NUMERIC NOT NULL
                     CONSTRAINT suse_imgstore_type_fk
                       REFERENCES suseImageStoreType (id)
                       ON DELETE CASCADE,
    org_id         NUMERIC NOT NULL
                     CONSTRAINT suse_imgstore_oid_fk
                       REFERENCES web_customer (id)
                       ON DELETE CASCADE,
    creds_id       NUMERIC
                     CONSTRAINT suse_imgstore_creds_fk
                       REFERENCES suseCredentials (id)
                       ON DELETE SET NULL,
    created        TIMESTAMPTZ
                     DEFAULT (current_timestamp) NOT NULL,
    modified       TIMESTAMPTZ
                     DEFAULT (current_timestamp) NOT NULL
)

;

CREATE UNIQUE INDEX suse_imgstore_oid_label_uq
    ON suseImageStore (org_id, label)
        ;

CREATE SEQUENCE suse_imgstore_id_seq;
070701000001AA000081B400000000000000000000000167AE111400000415000000000000000000000000000000000000003800000000susemanager-schema/common/tables/suseImageStoreType.sql   --
-- Copyright (c) 2017 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

CREATE TABLE suseImageStoreType
(
    id     NUMERIC NOT NULL
                 CONSTRAINT suse_imgstore_type_id_pk PRIMARY KEY,
    label  VARCHAR(128) NOT NULL,
    name   VARCHAR(128) NOT NULL
)

;

CREATE UNIQUE INDEX suse_imgstore_type_label_uq
    ON suseImageStoreType (label)
        ;

CREATE UNIQUE INDEX suse_imgstore_type_name_uq
    ON suseImageStoreType (name)
        ;

CREATE SEQUENCE suse_imgstore_type_id_seq;
   070701000001AB000081B400000000000000000000000167AE111400000409000000000000000000000000000000000000003A00000000susemanager-schema/common/tables/suseInstalledProduct.sql --
-- Copyright (c) 2010 Novell
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
--

create table
suseInstalledProduct
(
    id            NUMERIC        not null PRIMARY KEY,
    name          VARCHAR(256) not null,
    version       VARCHAR(256),
    arch_type_id  NUMERIC
                  CONSTRAINT suse_installed_product_aid_fk
                  REFERENCES rhnPackageArch (id),
    release       VARCHAR(256),
    is_baseproduct CHAR(1) DEFAULT ('N') NOT NULL,
    created   TIMESTAMPTZ
                  DEFAULT (current_timestamp) NOT NULL,
    modified  TIMESTAMPTZ
                  DEFAULT (current_timestamp) NOT NULL
);

CREATE SEQUENCE suse_inst_pr_id_seq START WITH 100;
   070701000001AC000081B400000000000000000000000167AE111400000292000000000000000000000000000000000000003700000000susemanager-schema/common/tables/suseInternalState.sql    --
-- Copyright (c) 2023 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
CREATE TABLE suseInternalState
(
  id                NUMERIC NOT NULL
                    CONSTRAINT suse_internal_state_id_pk PRIMARY KEY,
  name              VARCHAR(128) NOT NULL,
  label             VARCHAR(128) NOT NULL
);
  070701000001AD000081B400000000000000000000000167AE11140000038A000000000000000000000000000000000000003500000000susemanager-schema/common/tables/suseKiwiProfile.sql  --
-- Copyright (c) 2018 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

CREATE TABLE suseKiwiProfile
(
    profile_id  NUMERIC NOT NULL
                  CONSTRAINT suse_kiwi_prid_fk
                     REFERENCES suseImageProfile (profile_id)
                     ON DELETE CASCADE,
    path        VARCHAR(1024) NOT NULL,
    kiwi_options VARCHAR(1024)
)

;
  070701000001AE000081B400000000000000000000000167AE11140000043D000000000000000000000000000000000000003D00000000susemanager-schema/common/tables/suseMaintenanceCalendar.sql  --
-- Copyright (c) 2020 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--

CREATE TABLE suseMaintenanceCalendar
(
  id          NUMERIC NOT NULL
              CONSTRAINT suse_mtcal_id_pk PRIMARY KEY,
  org_id      NUMERIC NOT NULL
              CONSTRAINT suse_mtcal_oid_fk
              REFERENCES web_customer(id)
              ON DELETE CASCADE,
  label       VARCHAR(128) NOT NULL,
  url         VARCHAR(1024),
  ical        TEXT NOT NULL,
  created     TIMESTAMPTZ
              DEFAULT (current_timestamp) NOT NULL,
  modified    TIMESTAMPTZ
              DEFAULT (current_timestamp) NOT NULL
);

CREATE SEQUENCE suse_mtcal_id_seq;

CREATE UNIQUE INDEX suse_mtcal_oid_label_uq
  ON suseMaintenanceCalendar(org_id, label);

   070701000001AF000081B400000000000000000000000167AE1114000004C8000000000000000000000000000000000000003D00000000susemanager-schema/common/tables/suseMaintenanceSchedule.sql  --
-- Copyright (c) 2020 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--

CREATE TABLE suseMaintenanceSchedule
(
  id          NUMERIC NOT NULL
              CONSTRAINT suse_mtsched_id_pk PRIMARY KEY,
  org_id      NUMERIC NOT NULL
              CONSTRAINT suse_mtsched_oid_fk
              REFERENCES web_customer(id)
              ON DELETE CASCADE,
  name        VARCHAR(128) NOT NULL,
  sched_type  VARCHAR(10) NOT NULL,
  ical_id     NUMERIC
              CONSTRAINT suse_mtsched_icid_fk
              REFERENCES suseMaintenanceCalendar(id)
              ON DELETE SET NULL,
  created     TIMESTAMPTZ
              DEFAULT (current_timestamp) NOT NULL,
  modified    TIMESTAMPTZ
              DEFAULT (current_timestamp) NOT NULL
);

CREATE SEQUENCE suse_mtsched_id_seq;

CREATE UNIQUE INDEX suse_mtsched_oid_name_uq
  ON suseMaintenanceSchedule(org_id, name);

070701000001B0000081B400000000000000000000000167AE1114000002B5000000000000000000000000000000000000003500000000susemanager-schema/common/tables/suseManagerInfo.sql  --
-- Copyright (c) 2018 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

CREATE TABLE suseManagerInfo
(
    last_mgr_sync_refresh   TIMESTAMPTZ
)

;
   070701000001B1000081B400000000000000000000000167AE111400000156000000000000000000000000000000000000003800000000susemanager-schema/common/tables/suseMatcherRunData.sql   CREATE TABLE suseMatcherRunData (
    id             NUMERIC NOT NULL
                   CONSTRAINT suse_matcher_run_data_pk PRIMARY KEY,
    inputBinary BYTEA,
    outputBinary BYTEA,
    subscriptionReportBinary BYTEA,
    messageReportBinary BYTEA,
    unmatchedProductReportBinary BYTEA
);

CREATE SEQUENCE suse_matcher_run_data_id_seq;

  070701000001B2000081B400000000000000000000000167AE111400000509000000000000000000000000000000000000003000000000susemanager-schema/common/tables/suseMdData.sql   --
-- Copyright (c) 2012 Novell
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
--

create table
suseMdData
(
    channel_id        NUMERIC
                      CONSTRAINT susemddata_chn_id_fk
                      REFERENCES rhnChannel (id)
                      ON DELETE CASCADE,
    package_id        NUMERIC
                      CONSTRAINT susemddata_pkg_id_fk
                      REFERENCES rhnPackage (id)
                      On DELETE CASCADE,
    keyword_id        NUMERIC
                      CONSTRAINT susemdkeyword_id_fk
                      REFERENCES suseMdKeyword (id),
    created   TIMESTAMPTZ
                  DEFAULT (current_timestamp) NOT NULL,
    modified  TIMESTAMPTZ
                  DEFAULT (current_timestamp) NOT NULL
)

;

CREATE UNIQUE INDEX susemddata_chn_pkg_key_uq
ON suseMdData (channel_id, package_id, keyword_id)
;

CREATE INDEX susemddata_chn_pkg_idx
ON suseMdData (channel_id, package_id)
;

   070701000001B3000081B400000000000000000000000167AE11140000033B000000000000000000000000000000000000003300000000susemanager-schema/common/tables/suseMdKeyword.sql    --
-- Copyright (c) 2012 Novell
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
--

create table
suseMdKeyword
(
    id                NUMERIC PRIMARY KEY,
    label             varchar(128) NOT NULL,
    created   TIMESTAMPTZ
                  DEFAULT (current_timestamp) NOT NULL,
    modified  TIMESTAMPTZ
                  DEFAULT (current_timestamp) NOT NULL
)

;

CREATE SEQUENCE suse_mdkeyword_id_seq;

CREATE UNIQUE INDEX susemdkeyword_label_uq
ON suseMdKeyword (label);
 070701000001B4000081B400000000000000000000000167AE111400000580000000000000000000000000000000000000003700000000susemanager-schema/common/tables/suseMgrServerInfo.sql    --
-- Copyright (c) 2022 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--

CREATE TABLE suseMgrServerInfo
(
    server_id          NUMERIC NOT NULL
                           CONSTRAINT suse_mgr_info_sid_fk
                               REFERENCES rhnServer (id),
    mgr_evr_id         NUMERIC
                           CONSTRAINT suse_mgr_info_peid_fk
                               REFERENCES rhnPackageEVR (id),
    report_db_cred_id  NUMERIC
                           CONSTRAINT suse_mgr_info_creds_fk
                               REFERENCES suseCredentials (id)
                               ON DELETE SET NULL,
    report_db_name     VARCHAR(128),
    report_db_host     VARCHAR(256),
    report_db_port     NUMERIC DEFAULT (5432) NOT NULL,
    report_db_last_synced TIMESTAMPTZ,
    created            TIMESTAMPTZ
                           DEFAULT (current_timestamp) NOT NULL,
    modified           TIMESTAMPTZ
                           DEFAULT (current_timestamp) NOT NULL,
    CONSTRAINT suse_mgr_info_sid_uq UNIQUE (server_id)
)
;
070701000001B5000081B400000000000000000000000167AE111400000620000000000000000000000000000000000000003400000000susemanager-schema/common/tables/suseMinionInfo.sql   --
-- Copyright (c) 2016 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

CREATE TABLE suseMinionInfo
(
    server_id             NUMERIC NOT NULL
                              CONSTRAINT suse_minion_info_sid_fk
                                  REFERENCES rhnServer (id)
                                  ON DELETE CASCADE,
    minion_id             VARCHAR(256) NOT NULL,
    os_family             VARCHAR(32),
    kernel_live_version   VARCHAR(255),
    ssh_push_port         NUMERIC,
    reboot_required_after TIMESTAMPTZ,
    uname                 VARCHAR,
    container_runtime     VARCHAR,
    created   TIMESTAMPTZ
                  DEFAULT (current_timestamp) NOT NULL,
    modified  TIMESTAMPTZ
                  DEFAULT (current_timestamp) NOT NULL
)

;

CREATE INDEX suse_minion_info_sid_idx
    ON suseMinionInfo (server_id)
    ;

ALTER TABLE suseMinionInfo
    ADD CONSTRAINT rhn_minion_info_sid_uq UNIQUE (server_id);

ALTER TABLE suseMinionInfo
    ADD CONSTRAINT rhn_minion_info_miid_uq UNIQUE (minion_id);
070701000001B6000081B400000000000000000000000167AE11140000014E000000000000000000000000000000000000003D00000000susemanager-schema/common/tables/suseNotificationMessage.sql  CREATE TABLE suseNotificationMessage
(
  id                NUMERIC NOT NULL
                        CONSTRAINT suse_notifmess_pk PRIMARY KEY,
  type              VARCHAR(32) NOT NULL,
  data              TEXT NOT NULL,
  created           TIMESTAMPTZ default(current_timestamp) NOT NULL
);

CREATE SEQUENCE suse_notif_message_id_seq;
  070701000001B7000081B400000000000000000000000167AE1114000004B3000000000000000000000000000000000000003A00000000susemanager-schema/common/tables/suseOrgStateRevision.sql --
-- Copyright (c) 2016 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

CREATE TABLE suseOrgStateRevision
(
    org_id         NUMERIC NOT NULL
                          CONSTRAINT suse_server_group_rev_sid_fk
                              REFERENCES web_customer (id)
                              ON DELETE CASCADE,
    state_revision_id NUMERIC NOT NULL
                          CONSTRAINT suse_server_group_rev_id_fk
                              REFERENCES suseStateRevision (id)
                              ON DELETE CASCADE
)

;

ALTER TABLE suseOrgStateRevision
    ADD CONSTRAINT suse_server_org_rev_id_sid_uq UNIQUE (org_id, state_revision_id);
 070701000001B8000081B400000000000000000000000167AE11140000047B000000000000000000000000000000000000003500000000susemanager-schema/common/tables/susePackageEula.sql  --
-- Copyright (c) 2014 SUSE LINUX Products GmbH, Nuernberg, Germany.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
--

CREATE TABLE
susePackageEula
(
    package_id        NUMERIC
                      CONSTRAINT susepackageeula_pkg_id_fk
                      REFERENCES rhnPackage (id)
                      On DELETE CASCADE,
    eula_id           NUMERIC
                      CONSTRAINT susepackageeula_id_fk
                      REFERENCES suseEula (id),
    created   TIMESTAMPTZ
                  DEFAULT (current_timestamp) NOT NULL,
    modified  TIMESTAMPTZ
                  DEFAULT (current_timestamp) NOT NULL
)

;

CREATE UNIQUE INDEX susepackageeula_pkg_eula_uq
ON susePackageEula (package_id, eula_id)
;

CREATE INDEX susepackageeula_pkg_idx
ON susePackageEula (package_id)
;

 070701000001B9000081B400000000000000000000000167AE11140000048F000000000000000000000000000000000000003C00000000susemanager-schema/common/tables/susePackageProductFile.sql   --
-- Copyright (c) 2011 Novell
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
--

create table
susePackageProductFile
(
    package_id numeric        not null
                             CONSTRAINT sppf_pid_fk
                             REFERENCES rhnPackage (id)
                             ON DELETE CASCADE,
    prodfile_id numeric        not null
                             CONSTRAINT sppf_pfid_fk
                             REFERENCES suseProductFile (id),
    created   TIMESTAMPTZ
                  DEFAULT (current_timestamp) NOT NULL,
    modified  TIMESTAMPTZ
                  DEFAULT (current_timestamp) NOT NULL
)

;

CREATE UNIQUE INDEX sppf_pi_pi_uq
    ON susePackageProductFile (package_id, prodfile_id)
    ;

CREATE INDEX sppf_pid_idx
    ON susePackageProductFile (package_id)
    
    ;

 070701000001BA000081B400000000000000000000000167AE1114000007AA000000000000000000000000000000000000003600000000susemanager-schema/common/tables/susePackageState.sql --
-- Copyright (c) 2015 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

CREATE TABLE susePackageState
(
    id                    NUMERIC NOT NULL
                              CONSTRAINT suse_pkg_state_id_pk PRIMARY KEY,
    name_id               NUMERIC NOT NULL
                              CONSTRAINT suse_pkg_state_nid_fk
                                  REFERENCES rhnPackageName (id),
    evr_id                NUMERIC
                              CONSTRAINT suse_pkg_state_eid_fk
                                  REFERENCES rhnPackageEVR (id),
    package_arch_id       NUMERIC
                              CONSTRAINT suse_pkg_state_paid_fk
                                  REFERENCES rhnPackageArch (id),
    state_revision_id     NUMERIC NOT NULL
                              CONSTRAINT suse_pkg_state_srid_fk
                                  REFERENCES suseStateRevision (id),
    package_state_type_id NUMERIC NOT NULL
                              CONSTRAINT suse_pkg_state_pstid_fk
                                  REFERENCES susePackageStateType (id),
    version_constraint_id NUMERIC NOT NULL
                              CONSTRAINT suse_pkg_state_vcid_fk
                                  REFERENCES suseVersionConstraintType (id)
)

;

CREATE SEQUENCE suse_pkg_state_id_seq;

ALTER TABLE susePackageState
    ADD CONSTRAINT suse_pkg_state_nid_srid_uq UNIQUE (name_id, state_revision_id);
  070701000001BB000081B400000000000000000000000167AE111400000316000000000000000000000000000000000000003A00000000susemanager-schema/common/tables/susePackageStateType.sql --
-- Copyright (c) 2015 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

CREATE TABLE susePackageStateType
(
    id        NUMERIC NOT NULL
                  CONSTRAINT suse_pkgstatetype_id_pk PRIMARY KEY,
    label     VARCHAR(32) NOT NULL
)

;
  070701000001BC000081B400000000000000000000000167AE111400000369000000000000000000000000000000000000004200000000susemanager-schema/common/tables/susePaygDimensionComputation.sql --
-- Copyright (c) 2023 SUSE
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--

CREATE TABLE susePaygDimensionComputation
(
    id                   NUMERIC NOT NULL
                            CONSTRAINT susePaygDimensionComputation_pk PRIMARY KEY,
    timestamp            TIMESTAMPTZ DEFAULT (current_timestamp) NOT NULL,
    success              BOOLEAN
);

CREATE SEQUENCE susePaygDimensionComputation_id_seq;

CREATE INDEX susePaygDimensionComputation_timestamp_idx
    ON susePaygDimensionComputation (timestamp DESC);
   070701000001BD000081B400000000000000000000000167AE111400000397000000000000000000000000000000000000003D00000000susemanager-schema/common/tables/susePaygDimensionResult.sql  --
-- Copyright (c) 2023 SUSE
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--

CREATE TABLE susePaygDimensionResult
(
    id                NUMERIC NOT NULL
                          CONSTRAINT susePaygDimensionResult_id_pk PRIMARY KEY,
    computation_id    NUMERIC NOT NULL
                          CONSTRAINT susePaygDimensionResult_computation_fk
                              REFERENCES susePaygDimensionComputation (id),
    dimension         billing_dimension_t NOT NULL,
    count             NUMERIC NOT NULL
);

CREATE SEQUENCE susePaygDimensionResult_id_seq;
 070701000001BE000081B400000000000000000000000167AE11140000050A000000000000000000000000000000000000003500000000susemanager-schema/common/tables/susePaygProduct.sql  --
-- Copyright (c) 2023 SUSE
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--

CREATE TABLE susePaygProduct
(
    id                          NUMERIC NOT NULL
                                CONSTRAINT susePaygProduct_pk PRIMARY KEY,
    credentials_id              NUMERIC NOT NULL
                                CONSTRAINT susePaygProduct_credentials_id_fk
                                REFERENCES suseCredentials (id)
                                ON DELETE CASCADE,
    name                        VARCHAR(256),
    version                     VARCHAR(256),
    arch                        VARCHAR(256),
    created                     TIMESTAMPTZ DEFAULT (current_timestamp) NOT NULL,
    modified                    TIMESTAMPTZ DEFAULT (current_timestamp) NOT NULL
);

CREATE SEQUENCE susePaygProduct_id_seq;

CREATE UNIQUE INDEX susePaygProduct_credentials_product_uq
    ON susePaygProduct (credentials_id, name, version, arch);
  070701000001BF000081B400000000000000000000000167AE11140000063A000000000000000000000000000000000000003500000000susemanager-schema/common/tables/susePaygSshData.sql  --
-- Copyright (c) 2021 SUSE
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--

CREATE TABLE susePaygSshData
(
    id                   NUMERIC                                 NOT NULL
        CONSTRAINT susePaygSshData_pk PRIMARY KEY,
    description          VARCHAR(255),
    host                 VARCHAR(255)                            NOT NULL,
    port                 NUMERIC,
    username             VARCHAR(32)                             NOT NULL,
    password             VARCHAR(32),
    key                  text,
    key_password         VARCHAR(32),
    bastion_host         VARCHAR(255),
    bastion_port         NUMERIC,
    bastion_username     VARCHAR(32),
    bastion_password     VARCHAR(32),
    bastion_key          text,
    bastion_key_password VARCHAR(32),
    status               CHAR(1) DEFAULT ('P')               NOT NULL
        CONSTRAINT suse_payg_ssh_data_status_ck
            CHECK (status in ('P', 'E', 'S')),
    error_message       text,
    created              TIMESTAMPTZ DEFAULT (current_timestamp) NOT NULL,
    modified             TIMESTAMPTZ DEFAULT (current_timestamp) NOT NULL
);

CREATE SEQUENCE susePaygSshData_id_seq;

CREATE UNIQUE INDEX susePaygSshData_host_uq
    ON susePaygSshData (host);  070701000001C0000081B400000000000000000000000167AE1114000003F2000000000000000000000000000000000000003C00000000susemanager-schema/common/tables/susePinnedSubscription.sql   --
-- Copyright (c) 2015 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

CREATE TABLE susePinnedSubscription
(
    id               NUMERIC NOT NULL
                       CONSTRAINT suse_pinsub_id_pk PRIMARY KEY
                       ,
    system_id        NUMERIC NOT NULL,
    subscription_id  NUMERIC NOT NULL
)

;

CREATE UNIQUE INDEX suse_pinsub_sid_oid_uq
    ON susePinnedSubscription (system_id, subscription_id)
    ;

CREATE SEQUENCE suse_pinsub_id_seq;
  070701000001C1000081B400000000000000000000000167AE11140000059F000000000000000000000000000000000000003800000000susemanager-schema/common/tables/suseProductChannel.sql   --
-- Copyright (c) 2010-2012 Novell
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
--

create table
suseProductChannel
(
    id NUMERIC NOT NULL
        CONSTRAINT suse_product_channel_id_pk PRIMARY KEY,
    product_id NUMERIC        not null
                             CONSTRAINT spc_pid_fk
                             REFERENCES suseProducts (id)
                             ON DELETE CASCADE,
    channel_id NUMERIC        not null
                             CONSTRAINT spc_rhn_cid_fk
                             REFERENCES rhnChannel (id)
                             ON DELETE CASCADE,
    mandatory  CHAR(1)       DEFAULT ('N') NOT NULL
                             CONSTRAINT spc_mand_ck
                             CHECK (mandatory in ('Y', 'N')),
    created   TIMESTAMPTZ
                  DEFAULT (current_timestamp) NOT NULL,
    modified  TIMESTAMPTZ
                  DEFAULT (current_timestamp) NOT NULL
);

CREATE SEQUENCE suse_product_channel_id_seq;

CREATE UNIQUE INDEX suseproductchannel_product_id_channel_id_uq
ON suseProductChannel (product_id, channel_id);
 070701000001C2000081B400000000000000000000000167AE1114000005F3000000000000000000000000000000000000003A00000000susemanager-schema/common/tables/suseProductExtension.sql --
-- Copyright (c) 2016--2018 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
--


create table
suseProductExtension
(
    base_pdid   NUMERIC not null
                  CONSTRAINT suse_prdext_bpid_fk
                  REFERENCES suseProducts (id)
                  ON DELETE CASCADE,
    ext_pdid    NUMERIC not null
                  CONSTRAINT suse_prdext_epid_fk
                  REFERENCES suseProducts (id)
                  ON DELETE CASCADE,
    root_pdid   NUMERIC not null
                  CONSTRAINT suse_prdext_rootid_fk
                  REFERENCES suseProducts (id)
                  ON DELETE CASCADE,
    recommended CHAR(1) DEFAULT ('N') NOT NULL
                  CONSTRAINT suse_prdext_rec_ck
                  CHECK (recommended in ('Y', 'N')),
    created   TIMESTAMPTZ
                  DEFAULT (current_timestamp) NOT NULL,
    modified  TIMESTAMPTZ
                  DEFAULT (current_timestamp) NOT NULL
);

CREATE INDEX prdext_bpid_idx
ON suseProductExtension (base_pdid)
;

CREATE INDEX prdext_epid_idx
ON suseProductExtension (ext_pdid)
;

CREATE UNIQUE INDEX prdext_ber_id_uq
ON suseProductExtension (base_pdid, ext_pdid, root_pdid)
;
 070701000001C3000081B400000000000000000000000167AE11140000048B000000000000000000000000000000000000003500000000susemanager-schema/common/tables/suseProductFile.sql  --
-- Copyright (c) 2011 Novell
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
--
create table suseProductFile
(
  id              NUMERIC NOT NULL PRIMARY KEY,
  name            VARCHAR(256) NOT NULL,
  evr_id          NUMERIC NOT NULL
                         CONSTRAINT suse_prod_file_eid_fk
                         REFERENCES rhnpackageevr (id),
  package_arch_id NUMERIC NOT NULL
                         CONSTRAINT suse_prod_file_paid_fk
                         REFERENCES rhnpackagearch (id),
  vendor          VARCHAR(256),
  summary         VARCHAR(4000),
  description     VARCHAR(4000),
  created   TIMESTAMPTZ
                DEFAULT (current_timestamp) NOT NULL,
  modified  TIMESTAMPTZ
                DEFAULT (current_timestamp) NOT NULL
);

CREATE SEQUENCE suse_prod_file_id_seq START WITH 100;

 070701000001C4000081B400000000000000000000000167AE1114000005D3000000000000000000000000000000000000003200000000susemanager-schema/common/tables/suseProducts.sql --
-- Copyright (c) 2010-2012 Novell
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
--


create table
suseProducts
(
    id            NUMERIC        not null PRIMARY KEY,
    name          VARCHAR(256) not null,
    version       VARCHAR(256),
    friendly_name VARCHAR(256),
    description   VARCHAR(4000),
    arch_type_id  NUMERIC
                  CONSTRAINT suse_products_aid_fk
                  REFERENCES rhnPackageArch (id),
    release       VARCHAR(256),
    product_id    NUMERIC NOT NULL,
    channel_family_id NUMERIC
                        CONSTRAINT suse_products_cfid_fk
                        REFERENCES rhnChannelFamily (id)
                        ON DELETE SET NULL,
    base          CHAR(1) DEFAULT ('N') NOT NULL,
    free          CHAR(1) DEFAULT ('N') NOT NULL,
    release_stage VARCHAR(10) DEFAULT ('released') NOT NULL,
    created   TIMESTAMPTZ
                  DEFAULT (current_timestamp) NOT NULL,
    modified  TIMESTAMPTZ
                  DEFAULT (current_timestamp) NOT NULL
);

CREATE SEQUENCE suse_products_id_seq START WITH 100;

CREATE UNIQUE INDEX suseprod_pdid_uq
ON suseProducts (product_id)
;
 070701000001C5000081B400000000000000000000000167AE1114000007DD000000000000000000000000000000000000004000000000susemanager-schema/common/tables/suseProfileCustomDataValue.sql   --
-- Copyright (c) 2017 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

CREATE TABLE suseProfileCustomDataValue
(
    id                NUMERIC NOT NULL
                          CONSTRAINT suse_pcdv_id_pk PRIMARY KEY,
    profile_id        NUMERIC NOT NULL
                          CONSTRAINT suse_pcdv_prid_fk
                              REFERENCES suseImageProfile (profile_id)
                              ON DELETE CASCADE,
    key_id            NUMERIC NOT NULL
                          CONSTRAINT suse_pcdv_kid_fk
                              REFERENCES rhnCustomDataKey (id)
                              ON DELETE CASCADE,
    value             VARCHAR(4000),
    created_by        NUMERIC
                          CONSTRAINT suse_pcdv_cb_fk
                              REFERENCES web_contact (id)
                              ON DELETE SET NULL,
    last_modified_by  NUMERIC
                          CONSTRAINT suse_pcdv_lmb_fk
                              REFERENCES web_contact (id)
                              ON DELETE SET NULL,
    created           TIMESTAMPTZ
                          DEFAULT (current_timestamp) NOT NULL,
    modified          TIMESTAMPTZ
                          DEFAULT (current_timestamp) NOT NULL
)

;

CREATE UNIQUE INDEX suse_pcdv_prid_kid_uq
    ON suseProfileCustomDataValue (profile_id, key_id);

CREATE INDEX suse_pcdv_kid_idx
    ON suseProfileCustomDataValue (key_id);

CREATE SEQUENCE suse_pcdv_id_seq;
   070701000001C6000081B400000000000000000000000167AE11140000081A000000000000000000000000000000000000003900000000susemanager-schema/common/tables/suseRecurringAction.sql  --
-- Copyright (c) 2020 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

CREATE TABLE suseRecurringAction
(
  id                NUMERIC NOT NULL
                    CONSTRAINT suse_recurring_action_id_pk PRIMARY KEY,
  target_type       VARCHAR(32) NOT NULL,
  action_type       VARCHAR(32) NOT NULL,
  name              VARCHAR(256) NOT NULL,
  cron_expr         VARCHAR(120) NOT NULL,
  minion_id         NUMERIC
                    CONSTRAINT suse_rec_action_minion_fk
                      REFERENCES suseMinionInfo(server_id)
                      ON DELETE CASCADE,
  group_id          NUMERIC
                    CONSTRAINT suse_rec_action_group_fk
                      REFERENCES rhnServerGroup(id)
                      ON DELETE CASCADE,
  org_id            NUMERIC
                    CONSTRAINT suse_rec_action_org_fk
                      REFERENCES web_customer(id)
                      ON DELETE CASCADE,
  creator_id        NUMERIC
                    CONSTRAINT suse_rec_action_creator_fk
                      REFERENCES web_contact(id)
                      ON DELETE CASCADE,
  active            CHAR(1) DEFAULT ('Y') NOT NULL,
  created           TIMESTAMP WITH TIME ZONE
                      DEFAULT (current_timestamp)
                      NOT NULL,
  modified          TIMESTAMP WITH TIME ZONE
                      DEFAULT (current_timestamp)
                      NOT NULL
);

CREATE SEQUENCE suse_recurring_action_id_seq;

CREATE INDEX suse_rec_action_type
    ON suseRecurringAction(target_type);

  070701000001C7000081B400000000000000000000000167AE111400000332000000000000000000000000000000000000003C00000000susemanager-schema/common/tables/suseRecurringHighstate.sql   --
-- Copyright (c) 2023 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
CREATE TABLE suseRecurringHighstate
(
  rec_id            NUMERIC NOT NULL
                    CONSTRAINT suse_recurring_highstate_id_pk PRIMARY KEY
                    CONSTRAINT suse_recurring_action_highstate_id_fk
                      REFERENCES suseRecurringAction(id)
                      ON DELETE CASCADE,
  test_mode         CHAR(1) NOT NULL
                    DEFAULT 'N'
);
  070701000001C8000081B400000000000000000000000167AE111400000326000000000000000000000000000000000000003800000000susemanager-schema/common/tables/suseRecurringState.sql   --
-- Copyright (c) 2023 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
CREATE TABLE suseRecurringState
(
  rec_id            NUMERIC NOT NULL
                    CONSTRAINT suse_recurring_state_id_pk PRIMARY KEY
                    CONSTRAINT suse_recurring_action_state_id_fk
                      REFERENCES suseRecurringAction(id)
                      ON DELETE CASCADE,
  test_mode         CHAR(1) NOT NULL
                    DEFAULT 'N'
);
  070701000001C9000081B400000000000000000000000167AE111400000688000000000000000000000000000000000000003E00000000susemanager-schema/common/tables/suseRecurringStateConfig.sql --
-- Copyright (c) 2023 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
CREATE TABLE suseRecurringStateConfig
(
  id                NUMERIC NOT NULL
                    CONSTRAINT suse_recurring_state_config_id_pk PRIMARY KEY,
  rec_id            NUMERIC NOT NULL
                    CONSTRAINT suse_recurring_state_config_state_id_fk
                      REFERENCES suseRecurringState(rec_id)
                      ON DELETE CASCADE,
  state_id          NUMERIC
                    CONSTRAINT suse_recurring_state_intstate_id_fk
                      REFERENCES suseInternalState(id)
                      ON DELETE CASCADE,
  confchan_id       NUMERIC
                    CONSTRAINT suse_recurring_state_confchan_id_fk
                      REFERENCES rhnConfigChannel(id)
                      ON DELETE CASCADE,
  position          NUMERIC NOT NULL,
  CONSTRAINT suse_rec_state_conf_rec_id_pos_uq UNIQUE (rec_id, position)
);

CREATE SEQUENCE suse_recurring_state_config_id_seq;

CREATE UNIQUE INDEX suse_rec_state_conf_rec_id_state_id_uq
  ON suseRecurringStateConfig(rec_id, state_id)
  WHERE confchan_id IS NULL AND state_id IS NOT NULL;

CREATE UNIQUE INDEX suse_rec_state_conf_rec_id_confchan_id_uq
  ON suseRecurringStateConfig(rec_id, confchan_id)
  WHERE state_id IS NULL AND confchan_id IS NOT NULL;
070701000001CA000081B400000000000000000000000167AE11140000060F000000000000000000000000000000000000003600000000susemanager-schema/common/tables/suseSCCOrderItem.sql --
-- Copyright (c) 2015 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

CREATE TABLE suseSCCOrderItem
(
    id             NUMERIC NOT NULL
                     CONSTRAINT suse_sccorder_id_pk
                     PRIMARY KEY,
    scc_id         NUMERIC NOT NULL,
    credentials_id NUMERIC
                       CONSTRAINT suse_sccorder_credsid_fk
                       REFERENCES suseCredentials (id)
                       ON DELETE CASCADE,
    sku            VARCHAR(256),
    start_date     TIMESTAMPTZ,
    end_date       TIMESTAMPTZ,
    quantity       NUMERIC DEFAULT(0),
    subscription_id NUMERIC NOT NULL,
    created        TIMESTAMPTZ
                       DEFAULT (current_timestamp) NOT NULL,
    modified       TIMESTAMPTZ
                       DEFAULT (current_timestamp) NOT NULL
)

;

CREATE UNIQUE INDEX suse_sccorder_sccid_uq
    ON suseSCCOrderItem (scc_id);

CREATE INDEX suse_sccorder_subid_idx
    ON suseSCCOrderItem (subscription_id);

CREATE SEQUENCE suse_sccorder_id_seq;
 070701000001CB000081B400000000000000000000000167AE1114000006FC000000000000000000000000000000000000003500000000susemanager-schema/common/tables/suseSCCRegCache.sql  --
-- Copyright (c) 2021 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE suseSCCRegCache
(
    id               NUMERIC
                         CONSTRAINT suse_sccregcache_id_pk
			 PRIMARY KEY,
    server_id        NUMERIC NULL
                         CONSTRAINT suse_sccregcache_sid_fk
                             REFERENCES rhnServer (id)
			 ON DELETE SET NULL,
    scc_reg_required char(1)
                         DEFAULT ('N') not null
                         CONSTRAINT suse_sccregcache_reg_ck
                             CHECK (scc_reg_required IN ('Y', 'N')),
    scc_id                 NUMERIC,
    scc_login              VARCHAR(64),
    scc_passwd             VARCHAR(64),
    scc_regerror_timestamp TIMESTAMPTZ,
    creds_id       NUMERIC NULL
                       CONSTRAINT suse_sccregcache_credsid_fk
                       REFERENCES suseCredentials (id),
---                    ON DELETE DO NOTHING !
    created        TIMESTAMPTZ
                       DEFAULT (current_timestamp) NOT NULL,
    modified       TIMESTAMPTZ
                       DEFAULT (current_timestamp) NOT NULL
);

CREATE INDEX suse_sccregcache_sid_idx
    ON suseSCCRegCache (server_id);

CREATE SEQUENCE suse_sccregcache_id_seq;
070701000001CC000081B400000000000000000000000167AE1114000006F0000000000000000000000000000000000000003700000000susemanager-schema/common/tables/suseSCCRepository.sql    --
-- Copyright (c) 2014--2018 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

CREATE TABLE suseSCCRepository
(
    id             NUMERIC NOT NULL PRIMARY KEY,
    scc_id         NUMERIC NOT NULL,
    autorefresh    CHAR(1) NOT NULL
                       CONSTRAINT suse_sccrepo_ck
                       CHECK (autorefresh in ('Y', 'N')),
    name           VARCHAR(256) NOT NULL,
    distro_target  VARCHAR(256) NULL,
    description    VARCHAR(2048) NOT NULL,
    url            VARCHAR(2048) NOT NULL,
    signed         CHAR(1) DEFAULT ('N') NOT NULL
                           CONSTRAINT suse_sccrepo_sig_ck
                           CHECK (signed in ('Y', 'N')),
    installer_updates CHAR(1) DEFAULT ('N') NOT NULL
                           CONSTRAINT suse_sccrepo_instup_ck
                           CHECK (installer_updates in ('Y', 'N')),
    created        TIMESTAMPTZ
                       DEFAULT (current_timestamp) NOT NULL,
    modified       TIMESTAMPTZ
                       DEFAULT (current_timestamp) NOT NULL
)

;

CREATE SEQUENCE suse_sccrepository_id_seq;

CREATE UNIQUE INDEX suse_sccrepo_sccid_uq
    ON suseSCCRepository (scc_id);

CREATE INDEX suse_sccrepo_url_idx
    ON suseSCCRepository (url);
070701000001CD000081B400000000000000000000000167AE111400000628000000000000000000000000000000000000003B00000000susemanager-schema/common/tables/suseSCCRepositoryAuth.sql    --
-- Copyright (c) 2018 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

CREATE TABLE suseSCCRepositoryAuth
(
    id             NUMERIC NOT NULL PRIMARY KEY,
    repo_id        NUMERIC NOT NULL
                       CONSTRAINT suse_sccrepoauth_rid_fk
		       REFERENCES suseSCCRepository (id),
--                     NO ON DELETE !
    credentials_id NUMERIC NULL
                       CONSTRAINT suse_sccrepo_credsid_fk
                       REFERENCES suseCredentials (id),
--                     NO ON DELETE !,
    source_id      NUMERIC NULL
                         CONSTRAINT suse_sccrepo_src_id_fk
                             REFERENCES rhnContentSource (id)
                             ON DELETE SET NULL,
    auth_type      VARCHAR(10) NOT NULL,
    auth           VARCHAR(4000) NULL,
    created        TIMESTAMPTZ
                       DEFAULT (current_timestamp) NOT NULL,
    modified       TIMESTAMPTZ
                       DEFAULT (current_timestamp) NOT NULL
)

;

CREATE SEQUENCE suse_sccrepoauth_id_seq;
070701000001CE000081B400000000000000000000000167AE1114000006B4000000000000000000000000000000000000003900000000susemanager-schema/common/tables/suseSCCSubscription.sql  --
-- Copyright (c) 2015 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

CREATE TABLE suseSCCSubscription
(
    id             NUMERIC NOT NULL
                     CONSTRAINT suse_sccsub_id_pk
                     PRIMARY KEY,
    scc_id         NUMERIC NOT NULL,
    credentials_id NUMERIC
                       CONSTRAINT suse_sccsub_credsid_fk
                       REFERENCES suseCredentials (id)
                       ON DELETE CASCADE,
    name           VARCHAR(256),
    starts_at      TIMESTAMPTZ,
    expires_at     TIMESTAMPTZ,
    status         VARCHAR(20),
    regcode        VARCHAR(256) NOT NULL,
    subtype        VARCHAR(20) NOT NULL,
    system_limit   NUMERIC DEFAULT(0) NOT NULL,
    created        TIMESTAMPTZ
                       DEFAULT (current_timestamp) NOT NULL,
    modified       TIMESTAMPTZ
                       DEFAULT (current_timestamp) NOT NULL
)

;

CREATE UNIQUE INDEX suse_sccsub_sccid_uq
    ON suseSCCSubscription (scc_id);

CREATE INDEX suse_sccsub_starts_at_idx
    ON suseSCCSubscription (starts_at);

CREATE INDEX suse_sccsub_expires_at_idx
    ON suseSCCSubscription (expires_at);

CREATE SEQUENCE suse_sccsub_id_seq;
070701000001CF000081B400000000000000000000000167AE111400000411000000000000000000000000000000000000004000000000susemanager-schema/common/tables/suseSCCSubscriptionProduct.sql   --
-- Copyright (c) 2015 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

CREATE TABLE suseSCCSubscriptionProduct
(
    subscription_id  NUMERIC NOT NULL
                     CONSTRAINT suse_sccsubprod_subid_fk
                     REFERENCES suseSCCSubscription (id)
                     ON DELETE CASCADE,
    product_id       NUMERIC NOT NULL
                     CONSTRAINT suse_sccsubprod_prdid_fk
                     REFERENCES suseProducts (id)
                     ON DELETE CASCADE
)

;

   070701000001D0000081B400000000000000000000000167AE1114000007CF000000000000000000000000000000000000003400000000susemanager-schema/common/tables/suseSaltPillar.sql   --
-- Copyright (c) 2021 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

CREATE TABLE suseSaltPillar
(
    id NUMERIC NOT NULL
        CONSTRAINT suse_salt_pillar_id_pk PRIMARY KEY,
    server_id NUMERIC
              CONSTRAINT suse_salt_pillar_sid_fk
              REFERENCES rhnServer (id)
              ON DELETE CASCADE,
    group_id NUMERIC
             CONSTRAINT suse_salt_pillar_gid_fk
             REFERENCES rhnServerGroup (id)
             ON DELETE CASCADE,
    org_id NUMERIC
           CONSTRAINT suse_salt_pillar_oid_fk
           REFERENCES web_customer (id)
           ON DELETE CASCADE,
    category VARCHAR NOT NULL,
    pillar JSONB NOT NULL,
    UNIQUE (server_id, category),
    UNIQUE (group_id, category),
    UNIQUE (org_id, category),
    CONSTRAINT suse_salt_pillar_only_one_target CHECK (
      ( server_id is not null and group_id is null and org_id is null ) or
      ( server_id is null and group_id is not null and org_id is null ) or
      ( server_id is null and group_id is null and org_id is not null ) or
      ( server_id is null and group_id is null and org_id is null)
    )
);

CREATE SEQUENCE suse_salt_pillar_id_seq;

CREATE INDEX suse_salt_pillar_server_id_idx ON suseSaltPillar (server_id);

CREATE INDEX suse_salt_pillar_group_id_idx ON suseSaltPillar (group_id);

CREATE INDEX suse_salt_pillar_org_id_idx ON suseSaltPillar (org_id);

CREATE INDEX suse_salt_pillar_category_idx ON suseSaltPillar (category);
 070701000001D1000081B400000000000000000000000167AE11140000036C000000000000000000000000000000000000003D00000000susemanager-schema/common/tables/suseServerContactMethod.sql  --
-- Copyright (c) 2013 SUSE
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--

CREATE TABLE suseServerContactMethod
(
    id        NUMERIC NOT NULL
                  CONSTRAINT suse_cont_meth_id_pk PRIMARY KEY
                  ,
    label     VARCHAR(64) NOT NULL,
    name      VARCHAR(128) NOT NULL,
    rank      NUMERIC NOT NULL
)

;

CREATE INDEX suse_cont_meth_label_id_idx
    ON suseServerContactMethod (label, id)
    ;

ALTER TABLE suseServerContactMethod
    ADD CONSTRAINT suse_cont_meth_label_uq UNIQUE (label);

070701000001D2000081B400000000000000000000000167AE1114000004C6000000000000000000000000000000000000004200000000susemanager-schema/common/tables/suseServerGroupStateRevision.sql --
-- Copyright (c) 2016 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

CREATE TABLE suseServerGroupStateRevision
(
    group_id         NUMERIC NOT NULL
                          CONSTRAINT suse_server_group_gr_id_fk
                              REFERENCES rhnServerGroup (id)
                              ON DELETE CASCADE,
    state_revision_id NUMERIC NOT NULL
                          CONSTRAINT suse_server_group_sr_id_fk
                              REFERENCES suseStateRevision (id)
                              ON DELETE CASCADE
)

;

ALTER TABLE suseServerGroupStateRevision
    ADD CONSTRAINT suse_server_group_rev_grid_uq UNIQUE (group_id, state_revision_id);
  070701000001D3000081B400000000000000000000000167AE111400000505000000000000000000000000000000000000004000000000susemanager-schema/common/tables/suseServerInstalledProduct.sql   --
-- Copyright (c) 2010-2012 Novell
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
--

create table
suseServerInstalledProduct
(
    rhn_server_id     NUMERIC
                      CONSTRAINT suseserver_ip_rhns_id_fk
                      REFERENCES rhnServer (id)
                      ON DELETE CASCADE
                      not null,
    suse_installed_product_id   NUMERIC
                                CONSTRAINT ssip_sip_id_fk
                                REFERENCES suseInstalledProduct (id)
                                not null,
    created   TIMESTAMPTZ
                  DEFAULT (current_timestamp) NOT NULL,
    modified  TIMESTAMPTZ
                  DEFAULT (current_timestamp) NOT NULL
);

CREATE UNIQUE INDEX suse_srv_inprod_uq
    ON suseServerInstalledProduct (rhn_server_id, suse_installed_product_id)
    ;

CREATE INDEX suse_srv_inprod_pkg_idx
    ON suseServerInstalledProduct (rhn_server_id)
    
    ;

   070701000001D4000081B400000000000000000000000167AE11140000037E000000000000000000000000000000000000003B00000000susemanager-schema/common/tables/suseServerSAPWorkload.sql    --
-- Copyright (c) 2025 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

CREATE TABLE suseServerSAPWorkload (
    id BIGINT CONSTRAINT suse_sap_workload_id_pk PRIMARY KEY GENERATED ALWAYS AS IDENTITY,
    sap_system_id VARCHAR NOT NULL,
    instance_type VARCHAR NOT NULL,
    server_id NUMERIC NOT NULL REFERENCES rhnServer(id) ON DELETE CASCADE
);
  070701000001D5000081B400000000000000000000000167AE1114000004BC000000000000000000000000000000000000003D00000000susemanager-schema/common/tables/suseServerStateRevision.sql  --
-- Copyright (c) 2015 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

CREATE TABLE suseServerStateRevision
(
    server_id         NUMERIC NOT NULL
                          CONSTRAINT suse_server_state_rev_sid_fk
                              REFERENCES rhnServer (id)
                              ON DELETE CASCADE,
    state_revision_id NUMERIC NOT NULL
                          CONSTRAINT suse_server_state_rev_id_fk
                              REFERENCES suseStateRevision (id)
                              ON DELETE CASCADE
)

;

ALTER TABLE suseServerStateRevision
    ADD CONSTRAINT suse_server_state_rev_srev_uq UNIQUE (server_id, state_revision_id);
070701000001D6000081B400000000000000000000000167AE111400000468000000000000000000000000000000000000004200000000susemanager-schema/common/tables/suseServerVirtualHostManager.sql --
-- Copyright (c) 2015 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--

CREATE TABLE suseServerVirtualHostManager
(
    server_id     NUMERIC
                    CONSTRAINT suse_server_vhms_sid_fk
                    REFERENCES rhnServer (id)
                    ON DELETE SET NULL,
    vhmserver_id  NUMERIC NOT NULL
                    CONSTRAINT suse_server_vhms_vhmsid_fk
                    REFERENCES suseVirtualHostManager (id)
                    ON DELETE CASCADE,
    node_id       NUMERIC
                    CONSTRAINT suse_svhm_nodeinfo_fk
                    REFERENCES suseVirtualHostManagerNodeInfo (id)
                    ON DELETE SET NULL
)

;

CREATE UNIQUE INDEX suse_svhm_sid_vhmid_uq
ON suseServerVirtualHostManager (server_id, vhmserver_id)
;

070701000001D7000081B400000000000000000000000167AE111400000452000000000000000000000000000000000000003700000000susemanager-schema/common/tables/suseStateRevision.sql    --
-- Copyright (c) 2015 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

CREATE TABLE suseStateRevision
(
    id               NUMERIC NOT NULL
                         CONSTRAINT suse_state_revision_id_pk PRIMARY KEY,
    creator_id       NUMERIC
                         CONSTRAINT suse_state_revision_cid_fk
                             REFERENCES web_contact (id)
                             ON DELETE SET NULL,
    created          TIMESTAMPTZ
                         DEFAULT (current_timestamp) NOT NULL
)

;

CREATE SEQUENCE suse_state_revision_id_seq;
  070701000001D8000081B400000000000000000000000167AE1114000004BF000000000000000000000000000000000000004400000000susemanager-schema/common/tables/suseStateRevisionConfigChannel.sql   --
-- Copyright (c) 2016 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

CREATE TABLE suseStateRevisionConfigChannel
(
    state_revision_id NUMERIC NOT NULL
                          CONSTRAINT suse_cfgchn_state_rev_id_fk
                              REFERENCES suseStateRevision (id)
                              ON DELETE CASCADE,
    config_channel_id NUMERIC NOT NULL
                          CONSTRAINT suse_state_rev_cfgchn_id_fk
                              REFERENCES rhnConfigChannel (id)
                              ON DELETE CASCADE,
    position NUMERIC,
    CONSTRAINT suse_state_rev_id_cfgchn_id_uq UNIQUE (state_revision_id, config_channel_id)
)

;
 070701000001D9000081B400000000000000000000000167AE111400000473000000000000000000000000000000000000003500000000susemanager-schema/common/tables/suseUpgradePath.sql  --
-- Copyright (c) 2012 Novell
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
--


create table
suseUpgradePath
(
    from_pdid     NUMERIC not null
                  CONSTRAINT suse_upgpath_fromid_fk
                  REFERENCES suseProducts (id)
                  ON DELETE CASCADE,
    to_pdid       NUMERIC not null
                  CONSTRAINT suse_upgpath_toid_fk
                  REFERENCES suseProducts (id)
                  ON DELETE CASCADE,
    created   TIMESTAMPTZ
                  DEFAULT (current_timestamp) NOT NULL,
    modified  TIMESTAMPTZ
                  DEFAULT (current_timestamp) NOT NULL
);

CREATE INDEX suseupgpath_fromid_idx
ON suseUpgradePath (from_pdid)
;

CREATE UNIQUE INDEX suseupgradepath_from_pdid_to_pdid_uq
ON suseUpgradePath (from_pdid, to_pdid);
 070701000001DA000081B400000000000000000000000167AE1114000002B7000000000000000000000000000000000000003A00000000susemanager-schema/common/tables/suseUserNotification.sql CREATE TABLE suseUserNotification
(
    id              NUMERIC NOT NULL
                        CONSTRAINT suse_user_notif_pk PRIMARY KEY, 
    user_id         NUMERIC NOT NULL
                        CONSTRAINT suse_user_notif_uid_fk
                        REFERENCES web_contact (id)
                        ON DELETE CASCADE,
    message_id      NUMERIC NOT NULL
                        CONSTRAINT suse_user_notif_mid_fk
                        REFERENCES suseNotificationMessage (id)
                        ON DELETE CASCADE,
    read            CHAR(1) DEFAULT ('N') NOT NULL,
    CONSTRAINT suse_notif_uid_mid_uq UNIQUE (user_id, message_id)
);

CREATE SEQUENCE suse_user_notif_id_seq;
 070701000001DB000081B400000000000000000000000167AE1114000003DB000000000000000000000000000000000000003300000000susemanager-schema/common/tables/suseVHMConfig.sql    --
-- Copyright (c) 2015 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--

CREATE TABLE suseVHMConfig
(
    id          NUMERIC NOT NULL
                CONSTRAINT suse_vhm_config_id_pk PRIMARY KEY,
    virtual_host_manager_id NUMERIC NOT NULL
                    CONSTRAINT suse_vhmc_vhms_fk
                    REFERENCES suseVirtualHostManager (id)
                    ON DELETE CASCADE,
    parameter   VARCHAR(1024) NOT NULL,
    value       VARCHAR(1024),
    CONSTRAINT suse_vhmc_id_para_uq UNIQUE (virtual_host_manager_id, parameter)
            DEFERRABLE INITIALLY DEFERRED
)

;

CREATE SEQUENCE suse_vhm_config_id_seq;

 070701000001DC000081B400000000000000000000000167AE11140000031C000000000000000000000000000000000000003F00000000susemanager-schema/common/tables/suseVersionConstraintType.sql    --
-- Copyright (c) 2015 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

CREATE TABLE suseVersionConstraintType
(
    id        NUMERIC NOT NULL
                  CONSTRAINT suse_verconstrtype_id_pk PRIMARY KEY,
    label     VARCHAR(32) NOT NULL
)

;
070701000001DD000081B400000000000000000000000167AE1114000004F5000000000000000000000000000000000000003C00000000susemanager-schema/common/tables/suseVirtualHostManager.sql   --
-- Copyright (c) 2015 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--

CREATE TABLE suseVirtualHostManager
(
    id          NUMERIC NOT NULL
                    CONSTRAINT suse_vhms_id_pk PRIMARY KEY,
    org_id      NUMERIC NOT NULL
                    CONSTRAINT suse_vhms_oid_fk
                    REFERENCES web_customer (id)
                    ON DELETE CASCADE,
    label       VARCHAR(128) NOT NULL,
    gatherer_module     VARCHAR(50) NOT NULL,
    cred_id     NUMERIC
                    CONSTRAINT suse_vhms_creds_fk
                    REFERENCES suseCredentials (id)
                    ON DELETE SET NULL,
    created     TIMESTAMPTZ
                    DEFAULT (current_timestamp) NOT NULL,
    modified    TIMESTAMPTZ
                    DEFAULT (current_timestamp) NOT NULL
)

;

CREATE UNIQUE INDEX suse_vhm_label_uq
ON suseVirtualHostManager (label)
;

CREATE SEQUENCE suse_vhms_id_seq;

   070701000001DE000081B400000000000000000000000167AE111400000491000000000000000000000000000000000000004400000000susemanager-schema/common/tables/suseVirtualHostManagerNodeInfo.sql   --
-- Copyright (c) 2015 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--

CREATE TABLE suseVirtualHostManagerNodeInfo
(
    id            NUMERIC NOT NULL
                    CONSTRAINT suse_vhmnode_id_pk PRIMARY KEY,
    identifier    VARCHAR(1024) NOT NULL,
    name          VARCHAR(128),
    node_arch_id  NUMERIC
                    CONSTRAINT rhn_vhmnodeinf_said_fk
                    REFERENCES rhnServerArch (id),
    cpu_sockets   NUMERIC,
    cpu_cores     NUMERIC,
    ram           NUMERIC,
    os            VARCHAR(64) NOT NULL,
    os_version    VARCHAR(64) NOT NULL,
    created       TIMESTAMPTZ
                      DEFAULT (current_timestamp) NOT NULL,
    modified      TIMESTAMPTZ
                      DEFAULT (current_timestamp) NOT NULL
)

;

CREATE SEQUENCE suse_vhm_nodeinfo_id_seq;

   070701000001DF000081B400000000000000000000000167AE1114000043DC000000000000000000000000000000000000002D00000000susemanager-schema/common/tables/tables.deps  #
# Copyright (c) 2008--2018 Red Hat, Inc.
#
# This software is licensed to you under the GNU General Public License,
# version 2 (GPLv2). There is NO WARRANTY for this software, express or
# implied, including the implied warranties of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
# along with this software; if not, see
# http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
#
# Dependencies for table objects in this (namespace) directory.
# See: ../../README for details.
# No TABS, PLEASE!
#

path = . class

log                            :: web_contact_all
PXTSessions                    :: web_contact
rhnAction                      :: rhnActionType web_customer web_contact
rhnActionApplyStates           :: rhnAction
rhnActionApplyStatesResult     :: rhnActionApplyStates rhnServer
rhnActionImageBuild            :: rhnAction suseImageProfile
rhnActionImageBuildResult      :: rhnActionImageBuild rhnServer
rhnActionInspect               :: rhnAction suseImageStore
rhnActionImageInspectResult    :: rhnActionInspect rhnServer
rhnActionScript                :: rhnAction
rhnActionConfigChannel         :: rhnServerAction rhnConfigChannel
rhnActionConfigDate            :: rhnAction
rhnActionConfigDateFile        :: rhnAction
rhnActionConfigFileName        :: rhnServerAction rhnConfigFileName rhnConfigFileFailure \
                                  rhnConfigRevision
rhnActionConfigRevision        :: rhnAction rhnServer rhnConfigRevision rhnConfigFileFailure
rhnActionConfigRevisionResult  :: rhnActionConfigRevision
rhnActionDaemonConfig          :: rhnAction
rhnActionDup                   :: rhnAction rhnServer
rhnActionDupChannel            :: rhnAction rhnChannel
rhnActionDupProduct            :: rhnAction suseProducts
rhnActionErrataUpdate          :: rhnAction rhnErrata
rhnActionImageDeploy           :: rhnAction
rhnActionKickstart             :: rhnAction rhnKickstartableTree
rhnActionKickstartFileList     :: rhnActionKickstart rhnFileList
rhnActionKickstartGuest        :: rhnActionKickstart rhnKickstartSession rhnKickstartableTree
rhnActionPackage               :: rhnPackage rhnPackageName rhnPackageArch rhnAction
rhnActionPackageAnswerfile     :: rhnActionPackage
rhnActionPackageDelta          :: rhnPackageDelta
rhnActionPackageRemovalFailure :: rhnServer rhnAction rhnPackageName \
                                  rhnPackageEVR rhnPackageCapability
rhnActivationKey               :: rhnRegToken rhnKickstartSession
rhnArchTypeActions             :: rhnArchType rhnActionType
rhnChannel                     :: web_customer rhnChannelArch rhnChannelProduct \
                                  rhnProductName rhnChecksum
rhnChannelArch                 :: rhnArchType
rhnChannelComps                :: rhnChannel rhnCompsType
rhnChannelCloned               :: rhnChannelComps
rhnChannelErrata               :: rhnChannel rhnErrata
rhnChannelFamily               :: web_customer
rhnChannelFamilyMembers        :: rhnChannel rhnChannelFamily
rhnPrivateChannelFamily        :: web_customer rhnChannelFamily
rhnPublicChannelFamily         :: rhnChannelFamily
rhnChannelPackage              :: rhnChannel rhnPackage
rhnChannelPackageArchCompat    :: rhnPackageArch rhnChannelArch
rhnChannelPermission           :: rhnChannelPermissionRole rhnChannel web_contact
rhnChannelTrust                :: rhnChannel
rhnChannelContentSource        :: rhnChannel rhnContentSourceType rhnContentSource
rhnChecksum                    :: rhnChecksumType
rhnClientCapability            :: rhnClientCapabilityName
rhnConfigContent               :: rhnChecksum
rhnConfigFile                  :: rhnConfigChannel rhnConfigFileState rhnConfigFileName
rhnConfigFile_foreignkeys      :: rhnConfigRevision
rhnConfigChannel               :: web_customer rhnConfigChannelType
rhnConfigRevision              :: rhnConfigFile rhnConfigInfo rhnConfigContent rhnConfigFileType
rhnContentSourceSsl            :: rhnContentSource rhnCryptoKey
rhnCpu                         :: rhnServer rhnCpuArch
rhnCryptoKey                   :: rhnCryptoKeyType
rhnCryptoKeyKickstart          :: rhnCryptoKey rhnKSData
rhnDevice                      :: rhnServer
rhnDistChannelMap              :: rhnChannel rhnChannelArch
rhnErrata                      :: rhnChecksum web_customer rhnErrataSeverity
rhnErrataBuglist               :: rhnErrata
rhnErrataCVE                   :: rhnErrata rhnCVE
rhnErrataFile                  :: rhnChecksum rhnErrata rhnErrataFileType
rhnErrataFileChannel           :: rhnChannel rhnErrataFile rhnChannelErrata
rhnErrataFilePackage           :: rhnPackage rhnErrataFile rhnErrataPackage
rhnErrataFilePackageSource     :: rhnErrataFile rhnPackageSource rhnErrataPackage
rhnErrataKeyword               :: rhnErrata
rhnErrataPackage               :: rhnPackage rhnErrata
rhnFile                        :: web_customer rhnChecksum
rhnFileLocation                :: rhnFile
rhnImageNeededCache            :: web_customer suseImageInfo rhnErrata rhnChannel
rhnKSData                      :: web_customer
rhnKickstartableTree           :: rhnChannel rhnKSTreeType web_customer \
                                  rhnKSInstallType
rhnKickstartCommand            :: rhnKSData rhnKickstartCommandName
rhnKickstartDefaults           :: rhnKSData rhnKickstartableTree rhnServerProfile \
                                  rhnKickstartVirtualizationType
rhnKickstartDefaultRegToken    :: rhnKSData rhnRegToken
rhnKickstartPreserveFileList   :: rhnKSData rhnFileList
rhnKickstartScript             :: rhnKSData
rhnKickstartSession            :: rhnKSData web_customer rhnServer rhnAction \
                                  rhnKickstartSessionState rhnServerProfile \
                                  rhnKickstartVirtualizationType
rhnKickstartSessionHistory     :: rhnKickstartSession rhnKickstartSessionState
rhnKSTreeFile                  :: rhnKickstartableTree rhnChannelErrata rhnErrata \
                                  rhnChecksum
rhnKickstartTimezone           :: rhnKSInstallType
rhnServerNetAddress4           :: rhnServerNetInterface
rhnServerNetAddress6           :: rhnServerNetInterface
rhnOrgChannelSettings          :: web_customer rhnChannel rhnOrgChannelSettingsType
rhnOrgErrataCacheQueue         :: web_customer
rhnOrgExtGroupMapping          :: rhnUserExtGroup rhnServerGroup
rhnPackage                     :: rhnPackageName rhnPackageEVR rhnPackageArch \
                                  rhnPackageGroup rhnSourceRPM web_customer \
                                  rhnChecksum
rhnPackageArch                 :: rhnArchType
rhnPackageDeltaElement         :: rhnPackageDelta rhnTransactionPackage
rhnPackageEVR                  :: evr_t
rhnPackageChangeLogRec         :: rhnPackage rhnPackageChangeLogData
rhnPackageConflicts            :: rhnPackage rhnPackageCapability
rhnPackageFile                 :: rhnChecksum rhnPackage rhnPackageCapability
rhnPackageKeyAssociation       :: rhnPackageKey rhnPackage
rhnPackageKey                  :: rhnPackageKeyType rhnPackageProvider
rhnPackageObsoletes            :: rhnPackage rhnPackageCapability
rhnPackageNEVRA                :: rhnPackageName rhnPackageEVR rhnPackageArch
rhnPackageProvides             :: rhnPackage rhnPackageCapability
rhnPackageRequires             :: rhnPackage rhnPackageCapability
rhnPackageSuggests             :: rhnPackage rhnPackageCapability
rhnPackageSupplements          :: rhnPackage rhnPackageCapability
rhnPackageEnhances             :: rhnPackage rhnPackageCapability
rhnPackageRecommends           :: rhnPackage rhnPackageCapability
rhnPackageBreaks               :: rhnPackage rhnPackageCapability
rhnPackagePredepends           :: rhnPackage rhnPackageCapability
rhnPackageSource               :: web_customer rhnSourceRPM rhnFile rhnPackageGroup \
                                  rhnChecksum
rhnPackageSyncBlacklist        :: rhnPackageName web_customer
rhnPackageExtraTagKey          :: rhnPackage
rhnPackageExtraTag             :: rhnPackage rhnPackageExtraTagKey
rhnProxyInfo                   :: rhnServer
rhnPushClient                  :: rhnServer rhnPushClientState
rhnRam                         :: rhnServer
rhnRegToken                    :: rhnServerGroupType suseServerContactMethod
rhnRegTokenChannels            :: rhnRegToken rhnChannel
rhnRegTokenConfigChannels      :: rhnRegToken rhnConfigChannel
rhnRegTokenEntitlement         :: rhnRegToken rhnServerGroupType
rhnRegTokenGroups              :: rhnRegToken rhnServerGroup
rhnRegTokenPackages            :: rhnRegToken rhnPackageName

rhnServer                      :: rhnServerArch web_contact web_customer \
                                  rhnProvisionState suseServerContactMethod \
                                  suseMaintenanceSchedule
rhnServerAction                :: rhnServer rhnAction rhnActionStatus
rhnServerActionPackageResult   :: rhnActionPackage
rhnServerActionScriptResult    :: rhnActionScript rhnServer
rhnServerArch                  :: rhnArchType
rhnServerChannel               :: rhnServer rhnChannel
rhnServerChannelArchCompat     :: rhnServerArch rhnChannelArch
rhnServerConfigChannel         :: rhnServer rhnConfigChannel
rhnServerCustomDataValue       :: rhnCustomDataKey
rhnServerDMI                   :: rhnServer
rhnServerFQDN                  :: rhnServer
rhnServerGroup                 :: rhnServerGroupType web_customer
rhnServerGroupMembers          :: rhnServer rhnServerGroup
rhnServerGroupTypeFeature      :: rhnFeature rhnServerGroupType
rhnServerHistory               :: rhnServer
rhnServerInfo                  :: rhnServer
rhnServerUuid                  :: rhnServer
rhnServerInstallInfo           :: rhnServer
rhnServerLocation              :: rhnServer
rhnServerNeededCache           :: web_customer rhnServer rhnErrata rhnChannel
rhnServerNotes                 :: rhnServer web_contact
rhnServerPackage               :: rhnServer rhnPackageArch rhnPackageName rhnPackageEVR
rhnServerPackageArchCompat     :: rhnPackageArch rhnServerArch
rhnServerPath                  :: rhnServer
rhnServerPreserveFileList      :: rhnServer rhnFileList
rhnServerProfile               :: web_customer rhnChannel rhnServerProfileType
rhnServerProfilePackage        :: rhnServerProfile rhnPackageName rhnPackageEVR
rhnServerTokenRegs             :: rhnRegToken rhnServer
rhnServerServerGroupArchCompat :: rhnServerGroupType rhnServerArch
rhnSet                         :: web_contact
rhnSGTypeBaseAddonCompat       :: rhnServerGroupType
rhnSnapshot                    :: web_customer rhnSnapshotInvalidReason
rhnSnapshotChannel             :: rhnSnapshot rhnChannel
rhnSnapshotConfigChannel       :: rhnSnapshot rhnConfigChannel
rhnSnapshotConfigRevision      :: rhnSnapshot rhnConfigRevision
rhnSnapshotPackage             :: rhnSnapshot
rhnSnapshotServerGroup         :: rhnServerGroup rhnSnapshot
rhnSnapshotTag                 :: rhnSnapshot rhnTag
rhnSsmOperationServer          :: rhnSsmOperation
rhnTag                         :: rhnTagName web_customer
rhnTaskoRun                    :: rhnTaskoTemplate rhnTaskoSchedule
rhnTaskoSchedule               :: rhnTaskoBunch
rhnTaskoTemplate               :: rhnTaskoBunch rhnTaskoTask
rhnTransactionPackage          :: rhnTransactionOperation rhnPackageArch \
                                  rhnPackageEVR rhnPackageName
rhnUserExtGroup                :: web_customer
rhnUserExtGroupMapping         :: rhnUserExtGroup rhnUserGroupType
rhnUserGroupMembers            :: web_contact rhnUserGroup
rhnUserGroup                   :: web_customer rhnUserGroupType
rhnUserInfo                    :: web_contact rhnTimezone
rhnUserInfoPane                :: rhnInfoPane web_contact
rhnUserServerGroupPerms        :: web_contact rhnServerGroup
rhnUserServerPerms             :: web_contact rhnServer
rhnUserServerPrefs             :: web_contact rhnServer
rhnVersionInfo                 :: rhnPackageName rhnPackageEVR
rhnVirtualInstance             :: rhnServer
rhnVirtualInstanceInfo         :: rhnVirtualInstance rhnVirtualInstanceType \
                                  rhnVirtualInstanceState
rhnVirtualInstanceInstallLog   :: rhnKickstartSession
rhnVirtualInstanceEventLog     :: rhnVirtualInstance rhnVirtualInstanceEventType \
                                  rhnVirtualInstanceState
rhnVisibleObjects              :: PXTSessions
rhnWebContactChangeLog         :: rhnWebContactChangeState
rhnActionChain                 :: web_contact
rhnActionChainEntry            :: rhnActionChain rhnAction rhnServer
rhnActionSubChannels           :: rhnAction rhnChannel
rhnActionSubChannelsList       :: rhnActionSubChannels rhnChannel
rhnActionSubChannelsTokens     :: suseChannelAccessToken rhnActionSubChannels
suseChannelAccessToken         :: suseMinionInfo
suseChannelAccessTokenChannel  :: suseChannelAccessToken rhnChannel
suseContentProject             :: web_customer
suseContentProject_alters      :: suseContentEnvironment
suseContentProjectSource       :: suseContentProject rhnChannel
suseContentProjectHistoryEntry :: suseContentProject web_contact
suseContentFilter              :: web_customer
suseContentFilterProject       :: suseContentProject suseContentFilter
suseContentEnvironment         :: suseContentProject
suseContentEnvironmentTarget   :: suseContentEnvironment rhnChannel
suseCredentials                :: web_contact susePaygSshData
suseCloudRmtHost               :: susePaygSshData
suseCVEImageChannel            :: suseImageInfo rhnChannel
suseCVEServerChannel           :: rhnServer rhnChannel
suseDockerfileProfile          :: suseImageProfile
suseKiwiProfile                :: suseImageProfile
suseProfileCustomDataValue     :: rhnCustomDataKey suseImageProfile web_contact
suseImageCustomDataValue       :: rhnCustomDataKey suseImageInfo web_contact
suseImageInfo                  :: rhnServerAction suseImageProfile suseImageStore suseMinionInfo \
                                  rhnChecksum suseSaltPillar
suseImageInfoPackage           :: suseImageInfo rhnPackageName rhnPackageEVR rhnPackageArch
suseImageInfoChannel           :: suseImageInfo rhnChannel
suseImageInfoInstalledProduct  :: suseInstalledProduct suseImageInfo
suseImageProfile               :: rhnRegTokenChannels web_customer suseImageStore
suseImageStore                 :: suseCredentials web_customer suseImageStoreType
suseMaintenanceCalendar        :: web_customer
suseMaintenanceSchedule        :: web_customer suseMaintenanceCalendar
suseMgrServerInfo              :: rhnServer rhnPackageEVR suseCredentials
suseMinionInfo                 :: rhnServer
suseInstalledProduct           :: rhnPackageArch
suseMdData                     :: rhnChannel rhnPackage suseMdKeyword
susePackageEula                :: rhnPackage suseEula
susePackageProductFile         :: suseProductFile rhnPackage
susePackageState               :: rhnPackageName rhnPackageEVR rhnPackageArch suseStateRevision \
                                  susePackageStateType suseVersionConstraintType
suseProducts                   :: rhnPackageArch rhnChannelFamily
suseProductChannel             :: suseProducts rhnChannel
suseProductExtension           :: suseProducts
suseChannelTemplate            :: suseProducts suseSCCRepository
suseSaltPillar                 :: rhnServer rhnServerGroup web_customer
suseSCCOrderItem               :: suseCredentials
suseSCCRegCache                :: suseCredentials rhnServer
suseSCCRepositoryAuth          :: suseCredentials rhnContentSource
suseSCCSubscription            :: suseCredentials
suseSCCSubscriptionProduct     :: suseSCCSubscription suseProducts
suseServerInstalledProduct     :: rhnServer suseInstalledProduct
suseServerStateRevision        :: rhnServer suseStateRevision
susePinnedSubscription         :: rhnServer
suseStateRevision              :: web_contact
suseUpgradePath                :: suseProducts
suseServerVirtualHostManager   :: rhnServer suseVirtualHostManager suseVirtualHostManagerNodeInfo
suseVHMConfig                  :: suseVirtualHostManager
suseVirtualHostManager         :: web_customer suseCredentials rhnServerGroup
suseServerGroupStateRevision   :: rhnServerGroup suseStateRevision
suseOrgStateRevision           :: web_customer suseStateRevision
web_contact                    :: web_customer
web_contact_all                :: web_contact
web_user_contact_permission    :: web_contact
web_user_site_info             :: web_contact web_user_site_type
web_user_personal_info         :: web_contact web_user_prefix
rhnActionScap                  :: rhnAction
rhnXccdfIdent                  :: rhnXccdfIdentSystem
rhnXccdfRuleresult             :: rhnXccdfTestresult rhnXccdfIdent rhnXccdfRuleresultType
rhnXccdfTestresult             :: rhnServer rhnActionScap rhnXccdfBenchmark rhnXccdfProfile
rhnXccdfRuleIdentMap           :: rhnXccdfRuleresult
rhnISSSlaveOrgs                :: rhnISSSlave web_customer
rhnISSMasterOrgs               :: rhnISSMaster web_customer
rhnChildChannelArchCompat      :: rhnChannelArch
rhnResetPassword               :: web_contact
suseUserNotification           :: suseNotificationMessage web_contact
suseRecurringAction            :: web_customer web_contact rhnServerGroup suseMinionInfo
suseAnsiblePath                :: rhnServer
rhnActionPlaybook              :: rhnAction
susePaygDimensionResult        :: billing_dimension_t susePaygDimensionComputation
070701000001E0000081B400000000000000000000000167AE111400000340000000000000000000000000000000000000003500000000susemanager-schema/common/tables/valid_countries.sql  --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE valid_countries
(
    code        VARCHAR(2) NOT NULL
                    CONSTRAINT valid_countries_pk PRIMARY KEY,
    short_name  VARCHAR(80) NOT NULL,
    name        VARCHAR(240)
)

;

070701000001E1000081B400000000000000000000000167AE1114000007E4000000000000000000000000000000000000003100000000susemanager-schema/common/tables/web_contact.sql  --
-- Copyright (c) 2008--2014 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE web_contact
(
    id                 NUMERIC
                           CONSTRAINT web_contact_pk PRIMARY KEY
                           ,
    org_id             NUMERIC NOT NULL
                           CONSTRAINT web_contact_org_fk
                               REFERENCES web_customer (id),
    login              VARCHAR(64) NOT NULL,
    login_uc           VARCHAR(64) NOT NULL
                           CONSTRAINT web_contact_login_uc_unq UNIQUE
                           ,
    password           VARCHAR(110) NOT NULL,
    created            TIMESTAMPTZ
                           DEFAULT (current_timestamp) NOT NULL,
    modified           TIMESTAMPTZ
                           DEFAULT (current_timestamp) NOT NULL,
    oracle_contact_id  NUMERIC
                           CONSTRAINT web_contact_ocid_unq UNIQUE
                           ,
    ignore_flag        CHAR(1)
                           DEFAULT ('N') NOT NULL
                           CONSTRAINT web_contact_ignore_ck
                               CHECK (ignore_flag in ('N','Y')),
    read_only          char(1)
                           default ('N') not null
                           constraint web_contact_ro_ck
                               check (read_only in ('Y', 'N'))
)


;

CREATE INDEX web_contact_oid_id
    ON web_contact (org_id, id)
    ;

CREATE SEQUENCE web_contact_id_seq;

070701000001E2000081B400000000000000000000000167AE11140000035F000000000000000000000000000000000000003500000000susemanager-schema/common/tables/web_contact_all.sql  --
-- Copyright (c) 2013 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE web_contact_all
(
    id                 NUMERIC
                           CONSTRAINT web_contact_all_pk PRIMARY KEY
                           ,
    org_id             NUMERIC,
    login              VARCHAR(64) NOT NULL
)
;
 070701000001E3000081B400000000000000000000000167AE1114000004E4000000000000000000000000000000000000003200000000susemanager-schema/common/tables/web_customer.sql --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE web_customer
(
    id                            NUMERIC NOT NULL
                                      CONSTRAINT web_customer_id_pk PRIMARY KEY
                                      ,
    name                          VARCHAR(128) NOT NULL,
    created                       TIMESTAMPTZ
                                      DEFAULT (current_timestamp) NOT NULL,
    modified                      TIMESTAMPTZ
                                      DEFAULT (current_timestamp) NOT NULL
)


;

CREATE UNIQUE INDEX web_customer_name_uq_idx
    ON web_customer (name)
    ;

CREATE SEQUENCE web_customer_id_seq;

070701000001E4000081B400000000000000000000000167AE111400000681000000000000000000000000000000000000004100000000susemanager-schema/common/tables/web_user_contact_permission.sql  --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE web_user_contact_permission
(
    web_user_id  NUMERIC NOT NULL
                     CONSTRAINT contperm_wbuserid_fk
                         REFERENCES web_contact (id)
                         ON DELETE CASCADE,
    email        CHAR(1)
                     DEFAULT ('N')
                     CONSTRAINT wucp_email_ck
                         CHECK (email in ('Y','N')),
    mail         CHAR(1)
                     DEFAULT ('N')
                     CONSTRAINT wucp_mail_ck
                         CHECK (mail in ('Y','N')),
    call         CHAR(1)
                     DEFAULT ('N')
                     CONSTRAINT wucp_call_ck
                         CHECK (call in ('Y','N')),
    fax          CHAR(1)
                     DEFAULT ('N')
                     CONSTRAINT wucp_fax_ck
                         CHECK (fax in ('Y','N')),
    created      TIMESTAMPTZ
                     DEFAULT (current_timestamp) NOT NULL,
    modified     TIMESTAMPTZ
                     DEFAULT (current_timestamp) NOT NULL
)

;

   070701000001E5000081B400000000000000000000000167AE111400000821000000000000000000000000000000000000003C00000000susemanager-schema/common/tables/web_user_personal_info.sql   --
-- Copyright (c) 2008--2014 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE web_user_personal_info
(
    web_user_id        NUMERIC NOT NULL
                           CONSTRAINT personal_info_web_user_id_fk
                               REFERENCES web_contact (id)
                               ON DELETE CASCADE,
    prefix             VARCHAR(12)
                           DEFAULT (' ') NOT NULL
                           CONSTRAINT wupi_prefix_fk
                               REFERENCES web_user_prefix (text),
    first_names        VARCHAR(128) NOT NULL,
    last_name          VARCHAR(128) NOT NULL,
    genqual            VARCHAR(12),
    parent_company     VARCHAR(128),
    company            VARCHAR(128),
    title              VARCHAR(128),
    phone              VARCHAR(128),
    fax                VARCHAR(128),
    email              VARCHAR(128),
    email_uc           VARCHAR(128),
    pin                NUMERIC,
    created            TIMESTAMPTZ
                           DEFAULT (current_timestamp) NOT NULL,
    modified           TIMESTAMPTZ
                           DEFAULT (current_timestamp) NOT NULL,
    first_names_ol     VARCHAR(128),
    last_name_ol       VARCHAR(128),
    genqual_ol         VARCHAR(12),
    parent_company_ol  VARCHAR(128),
    company_ol         VARCHAR(128),
    title_ol           VARCHAR(128)
)

;

CREATE INDEX wupi_email_uc_idx
    ON web_user_personal_info (email_uc);

CREATE INDEX wupi_user_id_idx
    ON web_user_personal_info (web_user_id);
   070701000001E6000081B400000000000000000000000167AE1114000002E4000000000000000000000000000000000000003500000000susemanager-schema/common/tables/web_user_prefix.sql  --
-- Copyright (c) 2008 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE web_user_prefix
(
    text  VARCHAR(12) NOT NULL
              CONSTRAINT wup_text_pk PRIMARY KEY
)

;

070701000001E7000081B400000000000000000000000167AE111400000A5F000000000000000000000000000000000000003800000000susemanager-schema/common/tables/web_user_site_info.sql   --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE web_user_site_info
(
    id                  NUMERIC NOT NULL
                            CONSTRAINT wusi_id_pk PRIMARY KEY,
    web_user_id         NUMERIC
                            CONSTRAINT wusi_wuid_fk
                                REFERENCES web_contact (id)
                                ON DELETE CASCADE,
    email               VARCHAR(128),
    email_uc            VARCHAR(128),
    alt_first_names     VARCHAR(128),
    alt_last_name       VARCHAR(128),
    address1            VARCHAR(128) NOT NULL,
    address2            VARCHAR(128),
    address3            VARCHAR(128),
    address4            VARCHAR(128),
    city                VARCHAR(128) NOT NULL,
    state               VARCHAR(64),
    zip                 VARCHAR(64),
    country             CHAR(2) NOT NULL,
    phone               VARCHAR(32),
    fax                 VARCHAR(32),
    url                 VARCHAR(128),
    is_po_box           CHAR(1)
                            DEFAULT ('0')
                            CONSTRAINT wusi_ipb_ck
                                CHECK (is_po_box in ('1','0')),
    type                CHAR(1)
                            CONSTRAINT wusi_type_fk
                                REFERENCES web_user_site_type (type),
    oracle_site_id      VARCHAR(32),
    notes               VARCHAR(2000),
    created             TIMESTAMPTZ
                            DEFAULT (current_timestamp),
    modified            TIMESTAMPTZ
                            DEFAULT (current_timestamp),
    alt_first_names_ol  VARCHAR(128),
    alt_last_name_ol    VARCHAR(128),
    address1_ol         VARCHAR(128),
    address2_ol         VARCHAR(128),
    address3_ol         VARCHAR(128),
    city_ol             VARCHAR(128),
    state_ol            VARCHAR(32),
    zip_ol              VARCHAR(32)
)

;

CREATE INDEX web_user_site_info_wuid
    ON web_user_site_info (web_user_id);

CREATE INDEX wusi_email_uc_idx
    ON web_user_site_info (email_uc);

CREATE SEQUENCE web_user_site_info_id_seq;

 070701000001E8000081B400000000000000000000000167AE111400000319000000000000000000000000000000000000003800000000susemanager-schema/common/tables/web_user_site_type.sql   --
-- Copyright (c) 2008 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE web_user_site_type
(
    type         CHAR(1) NOT NULL
                     CONSTRAINT wust_type_pk PRIMARY KEY,
    description  VARCHAR(64) NOT NULL
)

;

   070701000001E9000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000002000000000susemanager-schema/common/views   070701000001EA000081B400000000000000000000000167AE1114000005E3000000000000000000000000000000000000003600000000susemanager-schema/common/views/rhnActionOverview.sql --
-- Copyright (c) 2008 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
CREATE OR REPLACE VIEW
rhnActionOverview
(
	org_id,
	action_id,
	type_id,
	type_name,
	name,
    	scheduler,
	scheduler_login,
	earliest_action,
	total_count,
	successful_count,
	failed_count,
	in_progress_count,
	archived
)
AS
SELECT    A.org_id,
	  A.id,
	  AT.id,
	  AT.name,
	  A.name,
	  A.scheduler,
	  U.login,
	  A.earliest_action,
	  (SELECT COUNT(*) FROM rhnServerAction WHERE action_id = A.id),
	  (SELECT COUNT(*) FROM rhnServerAction WHERE action_id = A.id AND status = 2), -- XXX: don''t hard code status here :)
	  (SELECT COUNT(*) FROM rhnServerAction WHERE action_id = A.id AND status = 3),
	  (SELECT COUNT(*) FROM rhnServerAction WHERE action_id = A.id AND status NOT IN (2, 3)),
	  A.archived
FROM
	  rhnActionType AT,
	  rhnAction A
		left outer join
          web_contact U
		on A.scheduler = U.id
WHERE A.action_type = AT.id
ORDER BY  A.earliest_action;

 070701000001EB000081B400000000000000000000000167AE1114000005BD000000000000000000000000000000000000003900000000susemanager-schema/common/views/rhnAvailableChannels.sql  --
-- Copyright (c) 2008--2010 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
-- tricky view.  it explodes to a full cartesian product when
-- not queried via org_id, so DO NOT DO THAT :)

create or replace view
rhnAvailableChannels
(
    	org_id,
	channel_id,
	channel_depth,
	channel_name,
	channel_arch_id,
	padded_name,
        last_modified,
        channel_label,
	parent_or_self_label,
	parent_or_self_id 
)
as
select
     ct.org_id,
     ct.id,
     CT.depth,
     CT.name,
     CT.channel_arch_id,
     CT.padded_name,
     CT.last_modified,
     CT.label,
     CT.parent_or_self_label,
     CT.parent_or_self_id
from
     rhnOrgChannelTreeView CT
UNION ALL
select
     ct.org_id,
     ct.id,
     CT.depth,
     CT.name,
     CT.channel_arch_id,
     CT.padded_name,
     CT.last_modified,
     CT.label,
     CT.parent_or_self_label,
     CT.parent_or_self_id
from
     rhnSharedChannelTreeView CT
;

   070701000001EC000081B400000000000000000000000167AE1114000003D1000000000000000000000000000000000000003000000000susemanager-schema/common/views/rhnCDDevice.sql   --
-- Copyright (c) 2008 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
create or replace view 
rhnCDDevice
(id, server_Id, class, bus, detached, device, driver, 
description, dev_host, dev_id, dev_channel, dev_lun, pcitype)
as select 
	d.id,
	d.server_Id,
	d.class,
	d.bus,
	d.detached,
	d.device,
	d.driver,
	d.description,
	d.prop1,
	d.prop2,
	d.prop3,
	d.prop4,
	d.pcitype
from rhndevice d
where d.class = 'CDROM';

   070701000001ED000081B400000000000000000000000167AE111400000388000000000000000000000000000000000000004000000000susemanager-schema/common/views/rhnChannelFamilyPermissions.sql   --
-- Copyright (c) 2008--2010 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--

create or replace view rhnChannelFamilyPermissions as
	select	channel_family_id,
		to_number(null, null) as org_id,
		created,
		modified
	from	rhnPublicChannelFamily
	union
	select	channel_family_id,
		org_id,
		created,
		modified
	from	rhnPrivateChannelFamily;

070701000001EE000081B400000000000000000000000167AE1114000009F2000000000000000000000000000000000000004000000000susemanager-schema/common/views/rhnChannelNewestPackageView.sql   --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--
--
--
--
-- this is much more readable with ts=4, enjoy!

create or replace view
rhnChannelNewestPackageView
as
SELECT channel_id,
       name_id,
       evr_id,
       package_arch_id,
       package_id
FROM (
      SELECT channel_id,
             name_id,
             evr_id,
             package_arch_id,
             build_time,
             max(package_id) as package_id,
             ROW_NUMBER() OVER(PARTITION BY name_id, channel_id, package_arch_id ORDER BY build_time DESC) rn
      FROM (
            SELECT m.channel_id          as channel_id,
                   p.name_id             as name_id,
                   p.evr_id              as evr_id,
                   m.package_arch_id     as package_arch_id,
                   p.id                  as package_id,
                   p.build_time          as build_time
            FROM (select max(pe.evr) AS max_evr,
                         cp.channel_id,
                         p.name_id,
                         p.package_arch_id
                    from rhnPackageEVR                           pe,
                         susePackageExcludingPartOfPtf            p,
                         suseChannelPackageRetractedStatusView   cp
                   where p.evr_id = pe.id
                     and cp.package_id = p.id
                     and NOT cp.is_retracted
                   group by cp.channel_id, p.name_id, p.package_arch_id) m,
                 rhnPackageEVR       pe,
                 rhnPackage          p,
                 rhnChannelPackage   chp
            WHERE m.max_evr = pe.evr
                AND m.name_id = p.name_id
                AND m.package_arch_id = p.package_arch_id
                AND p.evr_id = pe.id
                AND chp.package_id = p.id
                AND chp.channel_id = m.channel_id
      ) latest_packages
      group by channel_id, name_id, evr_id, package_arch_id, build_time
) n
WHERE rn = 1;
  070701000001EF000081B400000000000000000000000167AE1114000004B1000000000000000000000000000000000000003A00000000susemanager-schema/common/views/rhnChannelPermissions.sql --
-- Copyright (c) 2008 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--

create or replace view
rhnChannelPermissions
(
    org_id, channel_id
)
as
select distinct org_id, channel_id
 from ( select privcf.org_id,
               cfm.channel_id
        from   rhnChannelFamilyMembers cfm,
               rhnPrivateChannelFamily privcf
        where  privcf.channel_family_id = cfm.channel_family_id
       union all
       select  u.org_id, cfm.channel_id
       from    web_contact u,
               rhnChannelFamilyMembers cfm,
               rhnPublicChannelFamily pubcf
       where   pubcf.channel_family_id = cfm.channel_family_id
) S;

   070701000001F0000081B400000000000000000000000167AE11140000065F000000000000000000000000000000000000003700000000susemanager-schema/common/views/rhnChannelTreeView.sql    --
-- Copyright (c) 2008 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--

CREATE OR REPLACE VIEW rhnChannelTreeView
(
        id,
        depth,
	name,
        padded_name,
	channel_arch_id,
        last_modified,
        label,
	parent_or_self_label,
	parent_or_self_id,
	end_of_life
)
AS
select * from (
	select	c.id			as id,
		1			as depth,
		c.name			as name,
		'  ' || c.name		as padded_name,
		c.channel_arch_id	as channel_arch_id,
		c.last_modified		as last_modified,
		c.label			as label,
		c.label			as parent_or_self_label,
		c.id			as parent_or_self_id,
		c.end_of_life		as end_of_life
	from	rhnChannel		c
	where	c.parent_channel is null
	union
	select	c.id			as id,
		2			as depth,
		c.name			as name,
		'' || c.name		as padded_name,
		c.channel_arch_id 	as channel_arch_id,
		c.last_modified		as last_modified,
		c.label			as label,
		pc.label		as parent_or_self_label,
		pc.id			as parent_or_self_id,
		c.end_of_life		as end_of_life
	from	rhnChannel		pc,
		rhnChannel		c
	where	c.parent_channel = pc.id
) S order by parent_or_self_label, parent_or_self_id;

 070701000001F1000081B400000000000000000000000167AE111400000337000000000000000000000000000000000000003400000000susemanager-schema/common/views/rhnChecksumView.sql   --
-- Copyright (c) 2009--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--

create or replace view rhnChecksumView 
as
select c.id,
       ct.label checksum_type,
       c.checksum
  from rhnChecksum c
  left join rhnChecksumType ct
    on c.checksum_type_id = ct.id;

 070701000001F2000081B400000000000000000000000167AE1114000004A1000000000000000000000000000000000000003700000000susemanager-schema/common/views/rhnEntitledServers.sql    --
-- Copyright (c) 2008 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--

create or replace view
rhnEntitledServers
as
select distinct
    S.id,
    S.org_id,
    S.digital_server_id,
    S.server_arch_id,
    S.os,
    S.release,
    S.name,
    S.description,
    S.info,
    S.secret
from
    rhnServerGroup SG,
    rhnServerGroupType SGT,
    rhnServerGroupMembers SGM,
    rhnServer S
where
    S.id = SGM.server_id
and SG.id = SGM.server_group_id
and SGT.label IN ('enterprise_entitled', 'bootstrap_entitled',
                  'salt_entitled', 'foreign_entitled')
and SG.group_type = SGT.id
and SG.org_id = S.org_id
;

   070701000001F3000081B400000000000000000000000167AE111400000477000000000000000000000000000000000000003000000000susemanager-schema/common/views/rhnHWDevice.sql   --
-- Copyright (c) 2008 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
-- ######## HARDWARE #########
create or replace view 
rhnHWDevice
(id, server_Id, class, bus, detached, device, driver, 
description, vendor_id, device_id, subvendor_Id, subdevice_Id, pcitype)
as
select 
	d.id,
	d.server_Id,
	d.class,
	d.bus,
	d.detached,
	d.device,
	d.driver,
	d.description,
	d.prop1,
	d.prop2,
	d.prop3,
	d.prop4,
	d.pcitype
from rhnDevice d
where d.class in ('AUDIO', 'MODEM', 'MOUSE', 'NETWORK', 
	        'SCSI', 'OTHER', 'USB', 'VIDEO', 'CAPTURE',
		'SCANNER', 'TAPE', 'RAID', 'SOCKET');

 070701000001F4000081B400000000000000000000000167AE1114000002DB000000000000000000000000000000000000003B00000000susemanager-schema/common/views/rhnImageErrataTypeView.sql    --
-- Copyright (c) 2017 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--

CREATE OR REPLACE VIEW rhnImageErrataTypeView
(
    	image_id,
	errata_id,
	errata_type
)
AS
SELECT
    	INEC.image_id,
	INEC.errata_id,
	E.advisory_type
FROM    rhnErrata E,
    	rhnImageNeededErrataCache INEC
WHERE   E.id = INEC.errata_id
GROUP BY INEC.image_id, INEC.errata_id, E.advisory_type
;

 070701000001F5000081B400000000000000000000000167AE11140000024A000000000000000000000000000000000000003E00000000susemanager-schema/common/views/rhnImageNeededErrataCache.sql --
-- Copyright (c) 2017 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
--
create or replace view
rhnImageNeededErrataCache
(
    image_id,
    errata_id
)
as
select
   distinct image_id, errata_id
   from rhnImageNeededCache;

  070701000001F6000081B400000000000000000000000167AE11140000028C000000000000000000000000000000000000003F00000000susemanager-schema/common/views/rhnImageNeededPackageCache.sql    --
-- Copyright (c) 2017 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
--
create or replace view
rhnImageNeededPackageCache
(
    image_id,
    package_id,
    errata_id
)
as
select
	image_id,
	package_id,
	max(errata_id) as errata_id
	from rhnImageNeededCache
	group by image_id, package_id;
070701000001F7000081B400000000000000000000000167AE11140000039F000000000000000000000000000000000000004300000000susemanager-schema/common/views/rhnOrgChannelFamilyPermissions.sql    --
-- Copyright (c) 2008--2010 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--

create or replace view rhnOrgChannelFamilyPermissions as
	select	pcf.channel_family_id,
		u.org_id as org_id,
		pcf.created,
		pcf.modified
	from	rhnPublicChannelFamily pcf,
		web_contact u
	union
	select	channel_family_id,
		org_id,
		created,
		modified
	from	rhnPrivateChannelFamily;

 070701000001F8000081B400000000000000000000000167AE1114000007C7000000000000000000000000000000000000003A00000000susemanager-schema/common/views/rhnOrgChannelTreeView.sql --
-- Copyright (c) 2008 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--

CREATE OR REPLACE VIEW rhnOrgChannelTreeView
(
	org_id,
        id,
        depth,
	name,
        padded_name,
	channel_arch_id,
        last_modified,
        label,
	parent_or_self_label,
	parent_or_self_id,
	end_of_life
)
AS
select * from (
	select	cfp.org_id		as org_id,
		c.id			as id,
		1			as depth,
		c.name			as name,
		'  ' || c.name		as padded_name,
		c.channel_arch_id	as channel_arch_id,
		c.last_modified		as last_modified,
		c.label			as label,
		c.label			as parent_or_self_label,
		c.id			as parent_or_self_id,
		c.end_of_life		as end_of_life
	from	rhnChannel		c,
		rhnChannelFamilyMembers cfm,
		rhnOrgChannelFamilyPermissions cfp
	where	cfp.channel_family_id = cfm.channel_family_id
		and cfm.channel_id = c.id
		and c.parent_channel is null
	union
	select	cfp.org_id		as org_id,
		c.id			as id,
		2			as depth,
		c.name			as name,
		'' || c.name		as padded_name,
		c.channel_arch_id 	as channel_arch_id,
		c.last_modified		as last_modified,
		c.label			as label,
		pc.label		as parent_or_self_label,
		pc.id			as parent_or_self_id,
		c.end_of_life		as end_of_life
	from	rhnChannel		pc,
		rhnChannel		c,
		rhnChannelFamilyMembers	cfm,
		rhnOrgChannelFamilyPermissions cfp
	where	cfp.channel_family_id = cfm.channel_family_id
		and cfm.channel_id = c.id
		and c.parent_channel = pc.id
) s order by parent_or_self_label, parent_or_self_id;

 070701000001F9000081B400000000000000000000000167AE11140000072C000000000000000000000000000000000000003900000000susemanager-schema/common/views/rhnOrgDistChannelMap.sql  --
-- Copyright (c) 2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--
--
--
CREATE OR REPLACE VIEW
rhnOrgDistChannelMap
(
    id,
    for_org_id,
    org_id,
    os,
    release,
    channel_arch_id,
    channel_id
)
AS
SELECT CASE WHEN dcm_o.org_id IS NOT NULL THEN dcm_o.id ELSE dcm_n.id END id,
        o.id as for_org_id,
        dcm_o.org_id,
        CASE WHEN dcm_o.org_id IS NOT NULL THEN dcm_o.os ELSE dcm_n.os END os,
        CASE WHEN dcm_o.org_id IS NOT NULL THEN dcm_o.release ELSE dcm_n.release END as release,
        CASE WHEN dcm_o.org_id IS NOT NULL THEN dcm_o.channel_arch_id ELSE dcm_n.channel_arch_id END as channel_arch_id,
        CASE WHEN dcm_o.org_id IS NOT NULL THEN dcm_o.channel_id ELSE dcm_n.channel_id END as channel_id
FROM web_customer o
    JOIN (SELECT DISTINCT release, channel_arch_id from rhnDistChannelMap) dcm ON 1 = 1
    LEFT JOIN rhnDistChannelMap dcm_n ON dcm_n.org_id IS NULL
        AND dcm_n.release = dcm.release
        AND dcm_n.channel_arch_id = dcm.channel_arch_id
    LEFT JOIN rhnDistChannelMap dcm_o ON dcm_o.org_id = o.id
        AND dcm_o.release = dcm.release
        AND dcm_o.channel_arch_id = dcm.channel_arch_id
WHERE (dcm_o.channel_id IS NOT NULL OR dcm_n.channel_id IS NOT NULL)
ORDER BY org_id, release, channel_arch_id;
070701000001FA000081B400000000000000000000000167AE1114000003D2000000000000000000000000000000000000003100000000susemanager-schema/common/views/rhnOrgErrata.sql  --
-- Copyright (c) 2008 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
-- a view to list all errata valid for an org.
-- in other words, errata from pub channels and their channels
create or replace view
rhnOrgErrata
(
    	org_id,
	errata_id,
	channel_id
)
as
select
    ac.org_id,
    ce.errata_id,
    ac.channel_id
from
    rhnChannelErrata ce,
    rhnAvailableChannels ac
where
    ce.channel_id = ac.channel_id
;

  070701000001FB000081B400000000000000000000000167AE111400000425000000000000000000000000000000000000003800000000susemanager-schema/common/views/rhnPackageChangeLog.sql   --
-- Copyright (c) 2010 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


create view rhnPackageChangeLog
as
select rhnPackageChangeLogRec.id,
	rhnPackageChangeLogRec.package_id,
	rhnPackageChangeLogRec.changelog_data_id,
	rhnPackageChangeLogData.name,
	rhnPackageChangeLogData.text,
	rhnPackageChangeLogData.time,
	rhnPackageChangeLogRec.created,
	rhnPackageChangeLogRec.modified
from rhnPackageChangeLogRec, rhnPackageChangeLogData
where rhnPackageChangeLogRec.changelog_data_id = rhnPackageChangeLogData.id;

   070701000001FC000081B400000000000000000000000167AE1114000007BC000000000000000000000000000000000000004100000000susemanager-schema/common/views/rhnServerEntitlementPhysical.sql  --
-- Copyright (c) 2008--2013 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--

create or replace view
rhnServerEntitlementPhysical
(
   server_id,
   server_group_id,
   server_group_type_id,
   label,
   permanent,
   is_base,
   modified
)
as
select
   distinct
   sgm.server_id,
   sg.id,
   sgt.id,
   sgt.label,
   sgt.permanent,
   sgt.is_base,
   sgm.modified
from
   rhnServerGroupType sgt,
   rhnServerGroup sg,
   rhnServerGroupMembers sgm
where
   sg.id = sgm.server_group_id
   and sg.group_type = sgt.id
   and not exists (
        select 1
        from
            rhnServerGroup sg2,
            rhnServerGroupMembers sgm2,
            rhnVirtualInstance vi
        where
            vi.virtual_system_id = sgm.server_id
            and vi.host_system_id = sgm2.server_id
            and sgm2.server_group_id = sg2.id
            and sg2.group_type = sg.group_type
            and exists (
                select 1
                from
                    rhnServerGroupType sgt3,
                    rhnServerGroup sg3,
                    rhnServerGroupMembers sgm3
                where
                    sgm3.server_id = sgm2.server_id
                    and sgm3.server_group_id = sg3.id
                    and sg3.group_type = sgt3.id
                    and sgt3.label in ('virtualization_host',
                                       'virtualization_host_platform')
                )
        );

070701000001FD000081B400000000000000000000000167AE1114000003F1000000000000000000000000000000000000003D00000000susemanager-schema/common/views/rhnServerEntitlementView.sql  --
-- Copyright (c) 2008 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--

create or replace view
rhnServerEntitlementView
(
   server_id,
   server_group_type_id,
   label,
   permanent,
   is_base
)
as
select
   distinct
   sgm.server_id,
   sgt.id,
   sgt.label,
   sgt.permanent,
   sgt.is_base
from
   rhnServerGroupType sgt,
   rhnServerGroup sg,
   rhnServerGroupMembers sgm
where
   sg.id = sgm.server_group_id
   and sg.group_type = sgt.id;

   070701000001FE000081B400000000000000000000000167AE111400000799000000000000000000000000000000000000004000000000susemanager-schema/common/views/rhnServerEntitlementVirtual.sql   --
-- Copyright (c) 2008--2013 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--

create or replace view
rhnServerEntitlementVirtual
(
   server_id,
   server_group_id,
   server_group_type_id,
   label,
   permanent,
   is_base
)
as
select
   distinct
   sgm.server_id,
   sg.id,
   sgt.id,
   sgt.label,
   sgt.permanent,
   sgt.is_base
from
   rhnServerGroupType sgt,
   rhnServerGroup sg,
   rhnServerGroupMembers sgm
where
   sg.id = sgm.server_group_id
   and sg.group_type = sgt.id
   and exists (
        select 1
        from
            rhnServerGroup sg2,
            rhnServerGroupMembers sgm2,
            rhnVirtualInstance vi
        where
            vi.virtual_system_id = sgm.server_id
            and vi.host_system_id = sgm2.server_id
            and sgm2.server_group_id = sg2.id
            and sg2.group_type = sg.group_type
            and exists (
                select 1
                from
                    rhnServerGroupType sgt3,
                    rhnServerGroup sg3,
                    rhnServerGroupMembers sgm3
                where
                    sgm3.server_id = sgm2.server_id
                    and sgm3.server_group_id = sg3.id
                    and sg3.group_type = sgt3.id
                    and sgt3.label in ('virtualization_host',
                                       'virtualization_host_platform')
                )
        );

   070701000001FF000081B400000000000000000000000167AE1114000003AA000000000000000000000000000000000000003C00000000susemanager-schema/common/views/rhnServerErrataTypeView.sql   --
-- Copyright (c) 2008 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--

CREATE OR REPLACE VIEW rhnServerErrataTypeView
(
    	server_id,
	errata_id,
	errata_type
)
AS
SELECT
    	SNEC.server_id,
	SNEC.errata_id,
	E.advisory_type
FROM    rhnErrata E,
    	rhnServerNeededErrataCache SNEC
WHERE   E.id = SNEC.errata_id
GROUP BY SNEC.server_id, SNEC.errata_id, E.advisory_type
;

  07070100000200000081B400000000000000000000000167AE1114000003D7000000000000000000000000000000000000003A00000000susemanager-schema/common/views/rhnServerFeaturesView.sql --
-- Copyright (c) 2008 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--

create or replace view
rhnServerFeaturesView
(
   server_id,
   label
)
as
select
   distinct
   sgm.server_id,
   f.label
from
   rhnFeature f,
   rhnServerGroupTypeFeature sgtf,
   rhnServerGroupMembers sgm,
   rhnServerGroup sg
where
   sg.id = sgm.server_group_id
   and sgtf.feature_id = f.id
   and sg.group_type = sgtf.server_group_type_id
;

 07070100000201000081B400000000000000000000000167AE111400000417000000000000000000000000000000000000003D00000000susemanager-schema/common/views/rhnServerGroupMembership.sql  --
-- Copyright (c) 2008 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--


CREATE OR REPLACE VIEW rhnServerGroupMembership (
         ORG_ID, SERVER_ID, GROUP_ID, GROUP_NAME, GROUP_TYPE, CURRENT_MEMBERS
)
AS
SELECT   SG.org_id, SGM.server_id, SG.id, SG.name, SGT.label, SG.current_members
  FROM
	 rhnServerGroupMembers SGM
             right join
    	 rhnServerGroup SG on (SG.id = SGM.server_group_id)
             left join
         rhnServerGroupType SGT on (SG.group_type = SGT.id)
;

 07070100000202000081B400000000000000000000000167AE111400000C5F000000000000000000000000000000000000003B00000000susemanager-schema/common/views/rhnServerGroupOverview.sql    --
-- Copyright (c) 2008--2015 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
CREATE OR REPLACE VIEW rhnServerGroupOverview (
         ORG_ID, SECURITY_ERRATA, BUG_ERRATA, ENHANCEMENT_ERRATA, GROUP_ID, GROUP_NAME, GROUP_ADMINS, SERVER_COUNT, MODIFIED
)
AS
  SELECT SG.org_id,
         (SELECT COUNT(distinct E.id)
            FROM rhnErrata E,
                 rhnServerNeededErrataCache SNEC,
                 rhnServerGroupMembers SGM
           WHERE E.advisory_type = 'Security Advisory'
                 and SNEC.errata_id = e.id
                 and SNEC.server_id = sgm.server_id
                 and sgm.server_group_id = sg.id
                 AND EXISTS ( SELECT 1
                              FROM rhnServerFeaturesView SFV
                              WHERE SFV.server_id = SGM.server_id
                                    AND SFV.label = 'ftr_system_grouping')),
         (SELECT COUNT(distinct E.id)
            FROM rhnErrata E,
                 rhnServerNeededErrataCache SNEC,
                 rhnServerGroupMembers SGM
           WHERE E.advisory_type = 'Bug Fix Advisory'
                 and SNEC.errata_id = e.id
                 and SNEC.server_id = sgm.server_id
                 and sgm.server_group_id = sg.id
                 AND EXISTS ( SELECT 1
                              FROM rhnServerFeaturesView SFV
                              WHERE SFV.server_id = SGM.server_id
                                    AND SFV.label = 'ftr_system_grouping')),
         (SELECT COUNT(distinct E.id)
            FROM rhnErrata E,
                 rhnServerNeededErrataCache SNEC,
                 rhnServerGroupMembers SGM
           WHERE E.advisory_type = 'Product Enhancement Advisory'
                 and SNEC.errata_id = e.id
                 and SNEC.server_id = sgm.server_id
                 and sgm.server_group_id = sg.id
                 AND EXISTS ( SELECT 1
                              FROM rhnServerFeaturesView SFV
                              WHERE SFV.server_id = SGM.server_id
                                    AND SFV.label = 'ftr_system_grouping')),
         SG.id, SG.name,
         (SELECT COUNT(*) FROM rhnUserManagedServerGroups UMSG WHERE UMSG.server_group_id = SG.id),
         (SELECT COUNT(*) FROM rhnServerGroupMembers SGM WHERE SGM.server_group_id = SG.id
                 AND EXISTS ( SELECT 1
                              FROM rhnServerFeaturesView SFV
                              WHERE SFV.server_id = SGM.server_id
                                    AND SFV.label = 'ftr_system_grouping')),
         CURRENT_TIMESTAMP
    FROM rhnServerGroup SG;

 07070100000203000081B400000000000000000000000167AE111400000315000000000000000000000000000000000000003F00000000susemanager-schema/common/views/rhnServerNeededErrataCache.sql    --
-- Copyright (c) 2008 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
create or replace view
rhnServerNeededErrataCache
(
    server_id, 
    errata_id
)
as
select
   distinct  server_id, errata_id 
   from rhnServerNeededCache;

   07070100000204000081B400000000000000000000000167AE1114000004EE000000000000000000000000000000000000003E00000000susemanager-schema/common/views/rhnServerOutdatedPackages.sql --
-- Copyright (c) 2008--2015 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--

CREATE OR REPLACE VIEW
rhnServerOutdatedPackages
(
    server_id,
    package_name_id,
    package_evr_id,    
    package_arch_id,
    package_nvre,
    errata_id,
    errata_advisory
)
AS
SELECT DISTINCT SNC.server_id,
       P.name_id,
       P.evr_id,
       P.package_arch_id,
       PN.name || '-' || evr_t_as_vre_simple( PE.evr ),
       E.id,
       E.advisory
  FROM rhnPackageName PN,
       rhnPackageEVR PE,
       rhnPackage P,
       rhnServerNeededCache SNC
         left outer join
        rhnErrata E
          on SNC.errata_id = E.id
 WHERE SNC.package_id = P.id
   AND P.name_id = PN.id
   AND P.evr_id = PE.id;

  07070100000205000081B400000000000000000000000167AE111400000F18000000000000000000000000000000000000003600000000susemanager-schema/common/views/rhnServerOverview.sql --
-- Copyright (c) 2008--2013 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--
--
--

create or replace view
rhnServerOverview
(
    org_id,
    server_id,
    server_name,
    modified,
    server_admins,
    group_count,
    channel_id,
    channel_labels,
    history_count,
    security_errata,
    bug_errata,
    enhancement_errata,
    outdated_packages,
	config_files_with_differences,
    last_checkin_days_ago,
    last_checkin,
    pending_updates,
    os,
    release,
    server_arch_name,
    locked,
    proxy_id,
    mgr_server_id
)
as
select
    s.org_id, s.id, s.name, s.modified,
    ( select count(user_id) from rhnUserServerPerms ap
      where server_id = s.id ),
    ( select count(server_group_id) from rhnVisibleServerGroupMembers
      where server_id = s.id ),
    ( select C.id
        from rhnChannel C,
	     rhnServerChannel SC
       where SC.server_id = S.id
         and SC.channel_id = C.id
	 and C.parent_channel IS NULL),
    coalesce(( select C.name
        from rhnChannel C,
	     rhnServerChannel SC
       where SC.server_id = S.id
         and SC.channel_id = C.id
	 and C.parent_channel IS NULL), '(none)'),
    ( select count(id) from rhnServerHistory
      where
            server_id = S.id),
    ( select count(*) from rhnServerErrataTypeView setv
      where
            setv.server_id = s.id
        and setv.errata_type = 'Security Advisory'),
    ( select count(*) from rhnServerErrataTypeView setv
      where
            setv.server_id = s.id
        and setv.errata_type = 'Bug Fix Advisory'),
    ( select count(*) from rhnServerErrataTypeView setv
      where
            setv.server_id = s.id
        and setv.errata_type = 'Product Enhancement Advisory'),
    ( select count(distinct p.name_id) from rhnPackage p, rhnServerNeededCache snc
      where
             snc.server_id = S.id
	 and p.id = snc.package_id
	 ),
    ( select count(*)
        from rhnActionConfigRevision ACR
             INNER JOIN rhnActionConfigRevisionResult ACRR on ACR.id = ACRR.action_config_revision_id
       where ACR.server_id = S.id
         and ACR.action_id = (
              select MAX(rA.id)
                from rhnAction rA
                     INNER JOIN rhnServerAction rSA on rSA.action_id = rA.id
                     INNER JOIN rhnActionStatus rAS on rAS.id = rSA.status
                     INNER JOIN rhnActionType rAT on rAT.id = rA.action_type
               where rSA.server_id = S.id
                 and rAS.name in ('Completed', 'Failed')
                 and rAT.label = 'configfiles.diff'
         )
         and ACR.failure_id is null
         and ACRR.result is not null
        ),
    ( select date_diff_in_days(checkin, current_timestamp) from rhnServerInfo where server_id = S.id ),
    ( select TO_CHAR(checkin, 'YYYY-MM-DD HH24:MI:SS') from rhnServerInfo where server_id = S.id ),
    ( select count(1)
        from rhnServerAction
       where server_id = S.id
         and status in (0, 1)),
    os,
    release,
    ( select name from rhnServerArch where id = s.server_arch_id),
    coalesce((select 1 from rhnServerLock SL WHERE SL.server_id = S.id), 0),
    ( select pxy.server_Id from rhnProxyInfo pxy where pxy.server_id = S.id),
    ( select mgrs.server_Id from suseMgrServerInfo mgrs where mgrs.server_id = S.id)
from
    rhnServer S
;
07070100000206000081B400000000000000000000000167AE11140000062B000000000000000000000000000000000000003D00000000susemanager-schema/common/views/rhnSharedChannelTreeView.sql  --
-- Copyright (c) 2008 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--

CREATE OR REPLACE VIEW RHNSHAREDCHANNELTREEVIEW
(
  ORG_ID,
  ID,
  DEPTH,
  NAME,
  PADDED_NAME,
  CHANNEL_ARCH_ID,
  LAST_MODIFIED,
  LABEL,
  PARENT_OR_SELF_LABEL,
  PARENT_OR_SELF_ID,
  END_OF_LIFE
)
AS
SELECT * FROM (
  SELECT
    C.ORG_TRUST_ID AS ORG_ID,
    C.ID,
    1 AS DEPTH,
    C.NAME,
    '  '||C.NAME AS PADDED_NAME,
    C.CHANNEL_ARCH_ID,
    C.LAST_MODIFIED,
    C.LABEL,
    C.LABEL AS PARENT_OR_SELF_LABEL,
    C.ID AS PARENT_OR_SELF_ID,
    C.END_OF_LIFE
  FROM RHNSHAREDCHANNELVIEW C
  WHERE C.PARENT_CHANNEL IS NULL
  UNION
  SELECT
    C.ORG_TRUST_ID AS ORG_ID,
    C.ID,
    2 AS DEPTH,
    c.name,
    ''||C.NAME AS PADDED_NAME,
    C.CHANNEL_ARCH_ID,
    C.LAST_MODIFIED,
    C.LABEL,
    PC.LABEL AS PARENT_OR_SELF_LABEL,
    PC.ID AS PARENT_OR_SELF_ID,
    C.END_OF_LIFE
  FROM RHNCHANNEL PC,
       RHNSHAREDCHANNELVIEW C
  WHERE C.PARENT_CHANNEL = PC.ID
) SHARRED
ORDER BY PARENT_OR_SELF_LABEL, PARENT_OR_SELF_ID;

 07070100000207000081B400000000000000000000000167AE111400000427000000000000000000000000000000000000003900000000susemanager-schema/common/views/rhnSharedChannelView.sql  CREATE OR REPLACE VIEW RHNSHAREDCHANNELVIEW
AS
SELECT 
   CH.ID,
   CH.PARENT_CHANNEL,
   CH.ORG_ID,
   CH.CHANNEL_ARCH_ID,
   CH.LABEL,
   CH.BASEDIR,
   CH.NAME,
   CH.SUMMARY,
   CH.DESCRIPTION,
   CH.PRODUCT_NAME_ID,
   CH.GPG_KEY_URL,
   CH.GPG_KEY_ID,
   CH.GPG_KEY_FP,
   CH.END_OF_LIFE,
   CH.RECEIVING_UPDATES,
   CH.LAST_MODIFIED,
   CH.CHANNEL_PRODUCT_ID,
   CH.CREATED,
   CH.MODIFIED,
   CH.CHANNEL_ACCESS,
   TR.ORG_TRUST_ID
FROM RHNCHANNEL CH,
     RHNTRUSTEDORGS TR
WHERE CH.ORG_ID = TR.ORG_ID AND
      CH.CHANNEL_ACCESS = 'public'
UNION
SELECT
   CH.ID,
   CH.PARENT_CHANNEL,
   CH.ORG_ID,
   CH.CHANNEL_ARCH_ID,
   CH.LABEL,
   CH.BASEDIR,
   CH.NAME,
   CH.SUMMARY,
   CH.DESCRIPTION,
   CH.PRODUCT_NAME_ID,
   CH.GPG_KEY_URL,
   CH.GPG_KEY_ID,
   CH.GPG_KEY_FP,
   CH.END_OF_LIFE,
   CH.RECEIVING_UPDATES,
   CH.LAST_MODIFIED,
   CH.CHANNEL_PRODUCT_ID,
   CH.CREATED,
   CH.MODIFIED,
   CH.CHANNEL_ACCESS,
   TR.ORG_TRUST_ID
FROM RHNCHANNEL CH,
     RHNCHANNELTRUST TR
WHERE CH.ID = TR.CHANNEL_ID AND
      CH.CHANNEL_ACCESS = 'protected'
;

 07070100000208000081B400000000000000000000000167AE1114000003B7000000000000000000000000000000000000003500000000susemanager-schema/common/views/rhnStorageDevice.sql  --
-- Copyright (c) 2008 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
create or replace view 
rhnStorageDevice
(id, server_Id, class, bus, detached, device, driver, 
description, physical, logical, pcitype)
as select 
	d.id,
	d.server_Id,
	d.class,
	d.bus,
	d.detached,
	d.device,
	d.driver,
	d.description,
	d.prop1,
	d.prop2,
	d.pcitype
from rhnDevice d
where d.class in ('HD', 'FLOPPY');

 07070100000209000081B400000000000000000000000167AE111400000782000000000000000000000000000000000000003A00000000susemanager-schema/common/views/rhnUserActionOverview.sql --
-- Copyright (c) 2008 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--
-- rhnActionOverview, but on a per-user basis.

-- invoke as:
--
-- select	*
-- from		rhnUserActionOverview
-- where	org_id = :oid
--		and user_id = :uid;
--

create or replace view rhnUserActionOverview as
select	ao.org_id                                       as org_id,
	usp.user_id                                     as user_id,
    	ao.action_id                                    as id,
	ao.type_name                                    as type_name,
        ao.scheduler                                    as scheduler,
	ao.earliest_action                              as earliest_action,
	coalesce( ao.name, ao.type_name )		as action_name,
	sa.status					as action_status_id,
	astat.name                                      as action_status,
	count(sa.action_id)				as tally,
	ao.archived                                     as archived
from    rhnActionOverview ao
        left join rhnServerAction sa on ao.action_id = sa.action_id
        left join rhnActionStatus astat on sa.status = astat.id
        left join rhnUserServerPerms usp on sa.server_id = usp.server_id
group by ao.org_id,
	 usp.user_id,
	 ao.action_id,
	 ao.type_name,
	 ao.scheduler,
	 ao.earliest_action,
	 coalesce( ao.name, ao.type_name ),
	 sa.status,
	 astat.name,
	 ao.archived
order by earliest_action;

  0707010000020A000081B400000000000000000000000167AE111400000487000000000000000000000000000000000000003E00000000susemanager-schema/common/views/rhnUserChannelFamilyPerms.sql --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--

create or replace view rhnUserChannelFamilyPerms as
	select	pcf.channel_family_id,
		u.org_id as org_id,
		u.id as user_id,
		pcf.created,
		pcf.modified
	from	rhnPublicChannelFamily pcf,
		web_contact u
	where	pcf.channel_family_id not in (
			select priv.channel_family_id
			from rhnPrivateChannelFamily priv
			where u.org_id = priv.org_id
		)
	union
	select	pcf.channel_family_id,
		u.org_id,
		u.id as user_id,
		pcf.created,
		pcf.modified
	from	rhnPrivateChannelFamily pcf,
		web_contact u
	where	u.org_id = pcf.org_id;

 0707010000020B000081B400000000000000000000000167AE1114000007FE000000000000000000000000000000000000003B00000000susemanager-schema/common/views/rhnUserChannelTreeView.sql    --
-- Copyright (c) 2008 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--

CREATE OR REPLACE VIEW rhnUserChannelTreeView
(
	user_id,
	org_id,
        id,
        depth,
	name,
        padded_name,
	channel_arch_id,
        last_modified,
        label,
	parent_or_self_label,
	parent_or_self_id,
	end_of_life
)
AS
select * from (
	select	cfp.user_id		as user_id,
		cfp.org_id		as org_id,
		c.id			as id,
		1			as depth,
		c.name			as name,
		'  ' || c.name		as padded_name,
		c.channel_arch_id	as channel_arch_id,
		c.last_modified		as last_modified,
		c.label			as label,
		c.label			as parent_or_self_label,
		c.id			as parent_or_self_id,
		c.end_of_life		as end_of_life
	from	rhnChannel		c,
		rhnChannelFamilyMembers cfm,
		rhnUserChannelFamilyPerms cfp
	where	cfp.channel_family_id = cfm.channel_family_id
		and cfm.channel_id = c.id
		and c.parent_channel is null
	union
	select	cfp.user_id		as user_id,
		cfp.org_id		as org_id,
		c.id			as id,
		2			as depth,
		c.name			as name,
		'' || c.name		as padded_name,
		c.channel_arch_id 	as channel_arch_id,
		c.last_modified		as last_modified,
		c.label			as label,
		pc.label		as parent_or_self_label,
		pc.id			as parent_or_self_id,
		c.end_of_life		as end_of_life
	from	rhnChannel		pc,
		rhnChannel		c,
		rhnChannelFamilyMembers	cfm,
		rhnUserChannelFamilyPerms cfp
	where	cfp.channel_family_id = cfm.channel_family_id
		and cfm.channel_id = c.id
		and c.parent_channel = pc.id
) S order by parent_or_self_label, parent_or_self_id;

  0707010000020C000081B400000000000000000000000167AE111400000459000000000000000000000000000000000000003F00000000susemanager-schema/common/views/rhnUserManagedServerGroups.sql    --
-- Copyright (c) 2008 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
-- Overview of users in an org
--
--

create or replace view
rhnUserManagedServerGroups (
    user_id, server_group_id
)
as
select user_id, server_group_id from rhnUserServerGroupPerms
union
select wc.id, sg.id
  from rhnServerGroup sg,
       rhnUserGroup ug,
       rhnUserGroupMembers ugm,
       web_contact wc
 where wc.org_id = sg.org_id
   and wc.id = ugm.user_id
   and ugm.user_group_id = ug.id
   and ug.group_type = (select id from rhnUserGroupType where label = 'org_admin')
;

   0707010000020D000081B400000000000000000000000167AE11140000053E000000000000000000000000000000000000004000000000susemanager-schema/common/views/rhnUserReceiveNotifications.sql   --
-- Copyright (c) 2010 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--
--
--
--

create or replace view rhnUserReceiveNotifications
as
    select wc.org_id, usp.user_id, usp.server_id
    from rhnUserServerPerms usp
    left join rhnWebContactDisabled wcd
        on usp.user_id = wcd.id
    join web_contact wc
        on usp.user_id = wc.id
    join rhnUserInfo ui
        on usp.user_id = ui.user_id
        and ui.email_notify = 1
    join web_user_personal_info upi
        on usp.user_id = upi.web_user_id
        and upi.email is not null
    left join rhnUserServerPrefs uspr
        on uspr.server_id = usp.server_id
        and usp.user_id = uspr.user_id
        and uspr.name = 'receive_notifications'
        and value='0'
    where uspr.server_id is null
    and wcd.id is null;
  0707010000020E000081B400000000000000000000000167AE111400000427000000000000000000000000000000000000003C00000000susemanager-schema/common/views/rhnUserServerPermsDupes.sql   --
-- Copyright (c) 2008 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--

create or replace view rhnUserServerPermsDupes as
select	usg.user_id,
	sgm.server_id
from	rhnServerGroupMembers sgm,
	rhnUserServerGroupPerms usg
where	usg.server_group_id = sgm.server_group_id
union all
select	ugm.user_id, s.id
from	rhnServer s,
	rhnUserGroup ug,
	rhnUserGroupMembers ugm,
	rhnUserGroupType ugt
where	ugt.label = 'org_admin'
	and ugm.user_group_id = ug.id
	and ug.group_type = ugt.id
	and ug.org_id = s.org_id;

 0707010000020F000081B400000000000000000000000167AE11140000039E000000000000000000000000000000000000003400000000susemanager-schema/common/views/rhnUserTypeBase.sql   --
-- Copyright (c) 2008 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
create or replace view rhnUserTypeBase (
       user_id, type_id, type_label, type_name
)
AS
select distinct
    ugm.user_id, ugt.id, ugt.label, ugt.name
from   
    rhnUserGroupMembers ugm, rhnUserGroupType ugt, rhnUserGroup ug
where   
    ugm.user_group_id = ug.id
and ugt.id = ug.group_type;

  07070100000210000081B400000000000000000000000167AE111400000559000000000000000000000000000000000000003A00000000susemanager-schema/common/views/rhnUsersInOrgOverview.sql --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
create or replace view rhnUsersInOrgOverview as
select    
	u.org_id					as org_id,
	u.id						as user_id,
	u.login						as user_login,
	pi.first_names					as user_first_name,
	pi.last_name					as user_last_name,
	u.modified					as user_modified,
    	(	select	count(server_id)
		from	rhnUserServerPerms sp
		where	sp.user_id = u.id)
							as server_count,
	(	select	count(server_group_id)
		from	rhnUserManagedServerGroups umsg
		where	umsg.user_id = u.id and exists (
			select	1
			from	rhnVisibleServerGroup sg
			where	sg.id = umsg.server_group_id))
							as server_group_count,
	coalesce(rhn_user.role_names(u.id), '(normal user)') as role_names
from	web_user_personal_info pi, 
	web_contact u 
where
	u.id = pi.web_user_id;

   07070100000211000081B400000000000000000000000167AE111400000423000000000000000000000000000000000000004000000000susemanager-schema/common/views/rhnVisServerGroupMembership.sql   --
-- Copyright (c) 2008 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
CREATE OR REPLACE VIEW rhnVisServerGroupMembership (
         ORG_ID, SERVER_ID, GROUP_ID, GROUP_NAME, GROUP_TYPE, CURRENT_MEMBERS
)
AS
SELECT   SG.org_id, SGM.server_id, SG.id, SG.name, SGT.label, SG.current_members
  FROM
	 rhnServerGroupMembers SGM
            right outer join
    	 rhnVisibleServerGroup SG on (SG.id = SGM.server_group_id)
            left outer join
         rhnServerGroupType SGT on (SG.group_type = SGT.id)
;

 07070100000212000081B400000000000000000000000167AE1114000002EC000000000000000000000000000000000000003A00000000susemanager-schema/common/views/rhnVisibleServerGroup.sql --
-- Copyright (c) 2008 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
CREATE OR REPLACE VIEW
rhnVisibleServerGroup
AS
  SELECT *
    FROM rhnServerGroup SG
   WHERE SG.group_type IS NULL;

07070100000213000081B400000000000000000000000167AE111400000340000000000000000000000000000000000000004100000000susemanager-schema/common/views/rhnVisibleServerGroupMembers.sql  --
-- Copyright (c) 2008 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
CREATE OR REPLACE VIEW
rhnVisibleServerGroupMembers
AS
  SELECT SGM.*
    FROM rhnServerGroup SG,
         rhnServerGroupMembers SGM
   WHERE SGM.server_group_id = SG.id
     AND SG.group_type IS NULL;

07070100000214000081B400000000000000000000000167AE111400000501000000000000000000000000000000000000003A00000000susemanager-schema/common/views/rhnWebContactDisabled.sql --
-- Copyright (c) 2008--2014 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--
create or replace view
rhnWebContactDisabled
as
select
   wcon.id,
   wcon.org_id,
   wcon.login,
   wcon.login_uc,
   wcon.password,
   wcon.oracle_contact_id,
   wcon.created,
   wcon.modified,
   wcon.ignore_flag
from
   rhnWebContactChangeLog   wccl,
   rhnWebContactChangeState wccs,
   web_contact              wcon
where wccl.change_state_id = wccs.id
   and wccs.label = 'disabled'
   and wccl.web_contact_id = wcon.id
   and wccl.date_completed =
              (select max(wccl_exists.date_completed)
                 from rhnWebContactChangeLog   wccl_exists
                where wccl.web_contact_id = wccl_exists.web_contact_id);

   07070100000215000081B400000000000000000000000167AE1114000003CE000000000000000000000000000000000000003900000000susemanager-schema/common/views/rhnWebContactEnabled.sql  --
-- Copyright (c) 2008--2014 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

create or replace view
rhnWebContactEnabled
as
select
   wcon.id,
   wcon.org_id,
   wcon.login,
   wcon.login_uc,
   wcon.password,
   wcon.oracle_contact_id,
   wcon.created,
   wcon.modified,
   wcon.ignore_flag,
   wcon.read_only
from
   web_contact wcon left join rhnWebContactDisabled wcond on wcond.id = wcon.id
   where wcond.id is null;
  07070100000216000081B400000000000000000000000167AE111400000298000000000000000000000000000000000000004A00000000susemanager-schema/common/views/suseChannelPackageRetractedStatusView.sql --
-- Similar as rhnChannelPackage, but enhanced with the 'is_retracted' status if
-- given package is part of a retracted patch in the channel.
--

CREATE OR REPLACE VIEW suseChannelPackageRetractedStatusView AS
 SELECT
    cp.channel_id,
    cp.package_id,
    CASE
        WHEN (EXISTS ( SELECT 1
           FROM rhnchannelerrata ce
             JOIN rhnerrata e ON ce.errata_id = e.id
             JOIN rhnerratapackage ep ON ep.errata_id = e.id
          WHERE e.advisory_status::text = 'retracted'::text AND ce.channel_id = cp.channel_id AND ep.package_id = cp.package_id)) THEN true
        ELSE false
    END AS is_retracted
   FROM rhnchannelpackage cp;

07070100000217000081B400000000000000000000000167AE1114000010B7000000000000000000000000000000000000003C00000000susemanager-schema/common/views/suseChannelUserRoleView.sql   --
-- Copyright (c) 2018 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--

CREATE OR REPLACE VIEW
suseChannelUserRoleView
AS
  SELECT
    combination.channel_id,
    combination.user_id,
    combination.role,
    combination.user_org_id AS org_id,
    combination.parent_channel_id,
    CASE
      -- if channel is in an org trusted by the user's org, and if the channel itself is shared between the two, then user can subscribe it
      WHEN combination.role = 'subscribe' AND sharedChannels.is_shared_channel IS NOT NULL
        THEN NULL
      -- otherwise, if channel is not in user's org, then user can't manage it
      WHEN combination.role = 'manage' AND combination.channel_org_id IS NULL OR combination.channel_org_id <> combination.user_org_id
        THEN 'channel_not_owned'
      -- otherwise, if channel is in a family without permissions for the user's org, then user can't subscribe it
      WHEN combination.role = 'subscribe' AND channelPermissions.is_channel_available IS NULL
        THEN 'channel_not_available'
      -- otherwise, if channel is in a family without permissions for the user's org, then user can't subscribe it
      WHEN adminUsers.is_admin_user IS NOT NULL
        THEN NULL
      -- otherwise, if channel does not have the "not_globally_subscribable" bit set, user can subscribe it
      WHEN combination.role = 'subscribe' AND notGloballySubscribableChannels.is_not_globally_subscribable IS NULL
        THEN NULL
      -- otherwise, user might have an explicit permission on this channel
      WHEN explicitPermissions.has_explicit_permission IS NOT NULL
        THEN NULL
        -- otherwise, user can't either manage nor subscribe the channel
        ELSE 'direct_permission'
    END AS deny_reason
    FROM
      (SELECT
          c.id AS channel_id,
          c.org_id AS channel_org_id,
          c.parent_channel AS parent_channel_id,
          u.id AS user_id,
          u.org_id AS user_org_id,
          r.label AS role
          FROM rhnChannel c, web_contact u, rhnChannelPermissionRole r
      ) combination
     LEFT JOIN 
       (SELECT DISTINCT s.org_trust_id, s.id, 1 AS is_shared_channel
        FROM rhnSharedChannelView s) sharedChannels
     ON (sharedChannels.id = combination.channel_id AND sharedChannels.org_trust_id = combination.user_org_id)
     LEFT JOIN
       (SELECT DISTINCT cfp.org_id, cfm.channel_id, 1 AS is_channel_available
        FROM rhnChannelFamilyMembers cfm
          JOIN rhnOrgChannelFamilyPermissions cfp ON cfp.channel_family_id = cfm.channel_family_id) channelPermissions
     ON (combination.user_org_id = channelPermissions.org_id AND channelPermissions.channel_id = combination.channel_id)
     LEFT JOIN
       (SELECT DISTINCT m.user_id, 1 AS is_admin_user
        FROM rhnUserGroupMembers m
          JOIN rhnUserGroup g ON g.id = m.user_group_id
          JOIN rhnUserGroupType t ON t.id = g.group_type
        WHERE t.label = 'channel_admin' OR t.label = 'org_admin') adminUsers
     ON (adminUsers.user_id = combination.user_id)
     LEFT JOIN
       (SELECT DISTINCT ocs.channel_id, ocs.org_id, 1 AS is_not_globally_subscribable
        FROM rhnOrgChannelSettings ocs
          JOIN rhnOrgChannelSettingsType ocst ON ocst.id = ocs.setting_id
        WHERE ocst.label = 'not_globally_subscribable') notGloballySubscribableChannels
     ON (notGloballySubscribableChannels.channel_id = combination.channel_id AND notGloballySubscribableChannels.org_id = combination.user_org_id)
     LEFT JOIN
       (SELECT cpr.label, cp.channel_id, cp.user_id, 1 AS has_explicit_permission
        FROM rhnChannelPermission cp
          JOIN rhnChannelPermissionRole cpr ON cpr.id = cp.role_id) explicitPermissions
     ON (explicitPermissions.channel_id = combination.channel_id AND explicitPermissions.user_id = combination.user_id AND explicitPermissions.label = combination.role)
    -- ORDER BY channel_id, user_id, role, result
;
 07070100000218000081B400000000000000000000000167AE1114000007A0000000000000000000000000000000000000003600000000susemanager-schema/common/views/suseImageOverview.sql --
-- Copyright (c) 2017 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--

create or replace view
suseImageOverview
(
    org_id,
    image_id,
    image_name,
    image_version,
    image_type,
    checksum_id,
    modified,
    image_arch_name,
    build_action_id,
    inspect_action_id,
    profile_id,
    store_id,
    build_server_id,
    curr_revision_num,
    external_image,
    obsolete,
    built,
    security_errata,
    bug_errata,
    enhancement_errata,
    outdated_packages,
    installed_packages
)
as
select
    i.org_id, i.id, i.name, i.version, i.image_type, i.checksum_id, i.modified,
    ( select name from rhnServerArch where id = i.image_arch_id), i.build_action_id,
    i.inspect_action_id, i.profile_id, i.store_id, i.build_server_id, i.curr_revision_num,
    i.external_image, i.obsolete, i.built,
    ( select count(*) from rhnImageErrataTypeView ietv
      where
            ietv.image_id = i.id
        and ietv.errata_type = 'Security Advisory'),
    ( select count(*) from rhnImageErrataTypeView ietv
      where
            ietv.image_id = i.id
        and ietv.errata_type = 'Bug Fix Advisory'),
    ( select count(*) from rhnImageErrataTypeView ietv
      where
            ietv.image_id = i.id
        and ietv.errata_type = 'Product Enhancement Advisory'),
    ( select count(distinct p.name_id) from rhnPackage p, rhnImageNeededPackageCache inpc
      where
            inpc.image_id = i.id
        and p.id = inpc.package_id),
    (select count(*) from suseImageInfoPackage iip
     where
            iip.image_info_id = i.id)
from
    suseImageInfo i
;
07070100000219000081B400000000000000000000000167AE1114000000CB000000000000000000000000000000000000004200000000susemanager-schema/common/views/susePackageExcludingPartOfPtf.sql --
-- Returns the packages excluding those that are part of a PTF
--

CREATE OR REPLACE VIEW susePackageExcludingPartOfPtf AS
  SELECT pkg.*
    FROM rhnpackage pkg
   WHERE pkg.is_part_of_ptf = FALSE
;
 0707010000021A000081B400000000000000000000000167AE11140000025A000000000000000000000000000000000000004C00000000susemanager-schema/common/views/suseServerChannelsRetractedPackagesView.sql   --
-- Returns the retracted packages (no matter if installed or not installed)
-- from channels of given server.
--

CREATE OR REPLACE VIEW suseServerChannelsRetractedPackagesView AS
 SELECT DISTINCT p.id AS pid,
    s.id AS sid
   FROM rhnserver s
     JOIN rhnserverchannel sc ON s.id = sc.server_id
     JOIN rhnchannel c ON c.id = sc.channel_id
     JOIN rhnchannelerrata ce ON ce.channel_id = c.id
     JOIN rhnerrata e ON e.id = ce.errata_id
     JOIN rhnerratapackage ep ON ep.errata_id = e.id
     JOIN rhnpackage p ON p.id = ep.package_id
  WHERE e.advisory_status::text = 'retracted'::text;

  0707010000021B000081B400000000000000000000000167AE111400001921000000000000000000000000000000000000002B00000000susemanager-schema/common/views/views.deps    #
# Copyright (c) 2008--2015 Red Hat, Inc.
#
# This software is licensed to you under the GNU General Public License,
# version 2 (GPLv2). There is NO WARRANTY for this software, express or
# implied, including the implied warranties of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
# along with this software; if not, see
# http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
#
# Dependencies for view objects in this (namespace) directory.
# See: ../../README for details.
# No TABS, PLEASE!
#

path = . tables procs packages

rhnActionOverview                :: rhnAction rhnActionType web_contact
rhnAvailableChannels             :: rhnServer \
                                    rhnServerChannel \
                                    rhnOrgChannelTreeView \
                                    rhnSharedChannelTreeView \
                                    rhn_channel.pks 
rhnCDDevice                      :: rhnDevice
rhnChannelFamilyPermissions      :: rhnPublicChannelFamily \
                                    rhnPrivateChannelFamily
rhnChannelPermissions            :: rhnChannelFamilyMembers rhnPrivateChannelFamily \
                                    rhnPublicChannelFamily web_contact
rhnChannelTreeView               :: rhnChannel rhnChannelFamilyMembers \
                                    rhnChannelFamilyPermissions
rhnChecksumView                  :: rhnChecksum rhnChecksumType
rhnEntitledServers               :: rhnServerGroup rhnServerGroupType \
                                    rhnServerGroupMembers rhnServer
rhnHWDevice                      :: rhnDevice
rhnOrgChannelTreeView            :: rhnChannel rhnChannelFamilyMembers \
                                    rhnOrgChannelFamilyPermissions
rhnOrgDistChannelMap             :: rhnDistChannelMap
rhnOrgErrata                     :: rhnChannelErrata  rhnAvailableChannels
rhnPackageUpgradeArchCompat      :: rhnPackageArch
rhnServerErrataTypeView          :: rhnErrata rhnServerNeededErrataCache
rhnImageErrataTypeView           :: rhnErrata rhnImageNeededErrataCache
rhnServerFeaturesView            :: rhnFeature rhnServerGroupTypeFeature \
                                    rhnServerGroupMembers rhnServerGroup 
rhnServerGroupMembership         :: rhnServerGroupType rhnServerGroupMembers \
                                    rhnServerGroup
rhnServerOutdatedPackages        :: rhnServerNeededCache rhnErrata \
                                    rhnPackageName rhnPackageEVR rhnPackage
rhnStorageDevice                 :: rhnDevice
rhnUserChannelTreeView           :: rhnChannel rhnChannelFamilyMembers \
                                    rhnUserChannelFamilyPerms
rhnUserManagedServerGroups       :: rhnServerGroup rhnServerGroupType \
                                    rhnUserGroup rhnUserGroupMembers web_contact
rhnUserServerPermsDupes          :: rhnServerGroupMembers rhnUserGroup \
                                    rhnUserServerGroupPerms rhnUserGroupType \
                                    rhnUserGroupMembers rhnServer
rhnUserTypeBase                  :: rhnUserGroupMembers rhnUserGroupType \
                                    rhnUserGroup
rhnUsersInOrgOverview            :: rhnUserServerPerms web_contact \
                                    rhnUserManagedServerGroups \
                                    rhnVisibleServerGroup \
                                    web_user_personal_info rhn_user.pkb
rhnVisServerGroupMembership      :: rhnServerGroupType rhnServerGroupMembers \
                                    rhnVisibleServerGroup
rhnVisibleServerGroup            :: rhnServerGroup
rhnVisibleServerGroupMembers     :: rhnServerGroup rhnServerGroupMembers
rhnWebContactDisabled            :: rhnWebContactChangeLog rhnWebContactChangeState web_contact
rhnSharedChannelView             :: rhnChannel rhnChannelTrust rhnTrustedOrgs
rhnSharedChannelTreeView         :: rhnSharedChannelView
rhnUserActionOverview            :: rhnActionStatus rhnUserServerPerms rhnServerAction \
                                    rhnActionOverview 
rhnPackageChangeLog              :: rhnPackageChangeLogData rhnPackageChangeLogRec
rhnUserReceiveNotifications      :: rhnUserServerPerms rhnWebContactDisabled web_contact \
                                    rhnUserInfo web_user_personal_info rhnUserServerPrefs
rhnServerOverview                :: rhnUserServerPerms \
                                    rhnChannel rhnVisibleServerGroupMembers \
                                    rhnServerChannel rhnServerHistory \
                                    rhnPackage \
                                    rhnServerErrataTypeView \
                                    rhn_entitlements.pks
suseImageOverview                :: rhnChannel suseImageInfoChannel rhnPackage \
                                    rhnImageNeededPackageCache rhnImageErrataTypeView
rhnServerGroupOverview           :: rhnErrata rhnUserManagedServerGroups \
                                    rhnServerGroupMembers rhnServerGroup rhnServerFeaturesView
rhnUserChannelFamilyPerms        :: rhnPrivateChannelFamily \
                                    rhnPublicChannelFamily web_contact
rhnWebContactEnabled             :: web_contact rhnWebContactDisabled
rhnOrgChannelFamilyPermissions   :: rhnPublicChannelFamily web_contact \
                                    rhnPrivateChannelFamily
suseChannelUserRoleView          :: rhnSharedChannelView \
                                    rhnChannelFamilyMembers \
                                    rhnOrgChannelFamilyPermissions \
                                    rhnUserGroupMembers \
                                    rhnUserGroup \
                                    rhnUserGroupType \
                                    rhnOrgChannelSettings \
                                    rhnOrgChannelSettingsType \
                                    rhnChannelPermission \
                                    rhnChannelPermissionRole
rhnChannelNewestPackageView      :: suseChannelPackageRetractedStatusView \
                                    susePackageExcludingPartOfPtf
suseChannelPackageRetractedStatusView :: rhnChannelPackage rhnChannelErrata rhnErrataPackage
suseServerChannelsRetractedPackagesView :: rhnServerChannel rhnChannelErrata rhnErrataPackage
susePackageExcludingPartOfPtf :: rhnPackageCapability rhnPackageProvides rhnPackage
   0707010000021C000081B400000000000000000000000167AE11140000022B000000000000000000000000000000000000001F00000000susemanager-schema/gendrop.sql    -- Generate all drop staements for the current schema
--
-- $Id$

set pagesize 10000

select 'whenever sqlerror exit failure' from dual
union
select
    'drop ' || lower(object_type) || ' ' || lower(object_name) || ';' DROP_STATEMENT
from
    user_objects
where
    lower(object_type) not in ('table', 'index', 'trigger', 'lob')
UNION
select
    'drop ' || lower(object_type) || ' ' || lower(object_name) || ' cascade constraints;'
    DROP_STATEMENT
from
    user_objects
where
    lower(object_type) = 'table'
    and object_name not like '%$%';

quit;
 0707010000021D000041FD00000000000000000000000367AE111400000000000000000000000000000000000000000000001700000000susemanager-schema/lib    0707010000021E000041FD00000000000000000000000367AE111400000000000000000000000000000000000000000000002100000000susemanager-schema/lib/Spacewalk  0707010000021F000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000002F00000000susemanager-schema/lib/Spacewalk/SchemaUpgrade    07070100000220000081B400000000000000000000000167AE1114000007DE000000000000000000000000000000000000003900000000susemanager-schema/lib/Spacewalk/SchemaUpgrade/MainDb.pm  #  Copyright (c) 2022 SUSE LLC
#
#  This software is licensed to you under the GNU General Public License,
#  version 2 (GPLv2). There is NO WARRANTY for this software, express or
#  implied, including the implied warranties of MERCHANTABILITY or FITNESS
#  FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
#  along with this software; if not, see
#  http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
#
#  Red Hat trademarks are not licensed under GPLv2. No permission is
#  granted to use or replicate Red Hat trademarks that are incorporated
#  in this software or its documentation.

package Spacewalk::SchemaUpgrade::MainDb;

use strict;
use warnings FATAL => 'all';

use constant {
    DB_NAME => 'postgres',
    UPGRADE_PREFIX   => 'schema',
    BACKEND_PROPERTY => 'db_backend',
};

sub get_schema_version_query {
    return "
     SELECT pn.name || '-' || (pe.evr).version || '-' || (pe.evr).release
       FROM rhnVersionInfo vi
               INNER JOIN rhnPackageName pn ON vi.name_id = pn.id
               INNER JOIN rhnPackageEVR pe ON vi.evr_id = pe.id
      WHERE vi.label = 'schema';
";
}

sub get_migration_dir_query {
    return "
     SELECT label
       FROM rhnVersionInfo
      WHERE label LIKE 'schema-from%'
   ORDER BY label DESC;
";
}

sub update_migration_dir {
    shift if $_[0] eq __PACKAGE__;
    my ($migration_dir) = @_;

    return "
     UPDATE rhnVersionInfo
        SET label = '$migration_dir'
                , modified = current_timestamp
      WHERE label = 'schema';
";
}

sub insert_version_info {
    shift if $_[0] eq __PACKAGE__;
    my ($schema_name, $schema_version, $schema_release) = @_;

    return "
INSERT INTO rhnVersionInfo( label, name_id, evr_id, created, modified )
     VALUES ('schema'
                , lookup_package_name('$schema_name')
                , lookup_evr(null, '$schema_version' , '$schema_release', 'rpm' )
                , current_timestamp
                , current_timestamp
            );
     COMMIT;
";
}

1;
  07070100000221000081B400000000000000000000000167AE1114000006D4000000000000000000000000000000000000003B00000000susemanager-schema/lib/Spacewalk/SchemaUpgrade/ReportDb.pm    #  Copyright (c) 2022 SUSE LLC
#
#  This software is licensed to you under the GNU General Public License,
#  version 2 (GPLv2). There is NO WARRANTY for this software, express or
#  implied, including the implied warranties of MERCHANTABILITY or FITNESS
#  FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
#  along with this software; if not, see
#  http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
#
#  Red Hat trademarks are not licensed under GPLv2. No permission is
#  granted to use or replicate Red Hat trademarks that are incorporated
#  in this software or its documentation.

package Spacewalk::SchemaUpgrade::ReportDb;

use strict;
use warnings FATAL => 'all';

use constant {
    DB_NAME => 'reportdb',
    UPGRADE_PREFIX   => 'reportdb-schema',
    BACKEND_PROPERTY => 'report_db_backend',
};

sub get_schema_version_query {
    return "
     SELECT name || '-' || version || '-' || release
       FROM versioninfo
      WHERE label = 'schema';
";
}

sub get_migration_dir_query {
    return "
     SELECT label
       FROM versioninfo
      WHERE label LIKE 'schema-from%'
   ORDER BY label DESC;
";
}

sub update_migration_dir {
    shift if $_[0] eq __PACKAGE__;
    my ($migration_dir) = @_;

    return "
     UPDATE versioninfo
        SET label = '$migration_dir'
                , modified = current_timestamp
      WHERE label = 'schema';
";
}

sub insert_version_info {
    shift if $_[0] eq __PACKAGE__;
    my ($schema_name, $schema_version, $schema_release) = @_;

    return "
INSERT INTO versioninfo( label, name, version, release )
     VALUES ('schema'
                , '$schema_name'
                , '$schema_version'
                , '$schema_release'
            );
     COMMIT;
";
}

1;
07070100000222000041FD00000000000000000000000B67AE111400000000000000000000000000000000000000000000001C00000000susemanager-schema/postgres   07070100000223000081B400000000000000000000000167AE1114000005A2000000000000000000000000000000000000002500000000susemanager-schema/postgres/Makefile  #
# Copyright (c) 2008--2012 Red Hat, Inc.
#
# This software is licensed to you under the GNU General Public License,
# version 2 (GPLv2). There is NO WARRANTY for this software, express or
# implied, including the implied warranties of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
# along with this software; if not, see
# http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
#
# Make used to build the postgres schema.
#
# Arguments:
#
#   SQLUSER - The psql connect information.
#             (default: spacewalk).
#
# It uses the following tools:
#
#   blend    - A tool used to process the .deps files to produce
#              the main.sql.  It will inject the contents of a file
#              named "start.sql" at the beginning if it exits.
#

ifndef SQLUSER
SQLUSER := spacewalk
endif

STYLE   := postgres
DIRS    := class tables procs packages views triggers data synonyms quartz/tables quartz/data
BLEND   := ../blend -as $(STYLE)
REPLTBS := sed -re "s/\[\[[^]]+\]\]/$(TBS)/g"
MKFILES := $(shell find . -mindepth 2 -maxdepth 2 -name Makefile)


main : tables views data
	$(BLEND) $(DIRS)

devel : main
	$(BLEND) $(DIRS)
	$(REPLTBS) main.sql > devel.sql

tables :
	$(MAKE) -C $@

data :
	$(MAKE) -C $@

views :
	$(MAKE) -C $@

install : main
	sqlplus $(SQLUSER) @main

clean :
	@rm -f main.sql
	@$(foreach m,$(MKFILES),$(MAKE) -C $(dir $(m)) $@;)

.PHONY: clean tables data views
  07070100000224000081B400000000000000000000000167AE11140000016E000000000000000000000000000000000000002300000000susemanager-schema/postgres/README    Load postgresql schema using main.sql, run from the postgresql directory:

    psql -d spacewalk -f main.sql -q -v ON_ERROR_STOP=

And to cleanup the database, use a combination of drop + create, like so:

    dropdb spacewalk ; createdb spacewalk && createlang plpgsql spacewalk

Note: In future, the above cleanup process will be changed to drop just the schema.

  07070100000225000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000002200000000susemanager-schema/postgres/class 07070100000226000081B400000000000000000000000167AE111400000055000000000000000000000000000000000000003A00000000susemanager-schema/postgres/class/billing_dimension_t.sql CREATE TYPE billing_dimension_t AS ENUM (
    'managed_systems',
    'monitoring'
);
   07070100000227000081B400000000000000000000000167AE111400000244000000000000000000000000000000000000002D00000000susemanager-schema/postgres/class/class.deps  #
# Copyright (c) 2008 Red Hat, Inc.
#
# This software is licensed to you under the GNU General Public License,
# version 2 (GPLv2). There is NO WARRANTY for this software, express or
# implied, including the implied warranties of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
# along with this software; if not, see
# http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
#
# Dependencies for class objects in this (namespace) directory.
# See: ../../README for details.
# No TABS, PLEASE!
#

path = . packages

evr_t :: rpm.pks
07070100000228000081B400000000000000000000000167AE1114000011EA000000000000000000000000000000000000002C00000000susemanager-schema/postgres/class/evr_t.sql   --
-- Copyright (c) 2008--2013 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

create type evr_t as (
        epoch           varchar(16),
        version         varchar(512),
        release         varchar(512),
        type            varchar(10)
);

create or replace function evr_t(e varchar, v varchar, r varchar, t varchar)
returns evr_t as $$
select row($1,$2,$3,$4)::evr_t
$$ language sql;

create or replace function evr_t_compare( a evr_t, b evr_t )
returns int as $$
begin
  if a.type = b.type then
      if a.type = 'rpm' then
        return rpm.vercmp(a.epoch, a.version, a.release, b.epoch, b.version, b.release);
      elsif a.type = 'deb' then
        return deb.debvercmp(a.epoch, a.version, a.release, b.epoch, b.version, b.release);
      else
        raise EXCEPTION 'unknown evr type (using rpm) -> %', a.type;
      end if;
  else
     raise NOTICE 'comparing incompatible evr types. Using %', a.type;
     if a.type = 'deb' then
       return -1;
     else
       return 1;
     end if;
  end if;
end;
$$ language plpgsql immutable strict;

create or replace function evr_t_lt( a evr_t, b evr_t )
returns boolean as $$
begin
  return evr_t_compare( a, b ) < 0;
end;
$$ language plpgsql immutable strict;

create or replace function evr_t_le( a evr_t, b evr_t )
returns boolean as $$
begin
  return evr_t_compare( a, b ) <= 0;
end;
$$ language plpgsql immutable strict;

create or replace function evr_t_eq( a evr_t, b evr_t )
returns boolean as $$
begin
  return evr_t_compare( a, b ) = 0;
end;
$$ language plpgsql immutable strict;

create or replace function evr_t_ne( a evr_t, b evr_t )
returns boolean as $$
begin
  return evr_t_compare( a, b ) != 0;
end;
$$ language plpgsql immutable strict;

create or replace function evr_t_ge( a evr_t, b evr_t )
returns boolean as $$
begin
  return evr_t_compare( a, b ) >= 0;
end;
$$ language plpgsql immutable strict;

create or replace function evr_t_gt( a evr_t, b evr_t )
returns boolean as $$
begin
  return evr_t_compare( a, b ) > 0;
end;
$$ language plpgsql immutable strict;

create operator < (
  leftarg = evr_t,
  rightarg = evr_t,
  procedure = evr_t_lt,
  commutator = >,
  negator = >=,
  restrict = scalarltsel,
  join = scalarltjoinsel
);

create operator <= (
  leftarg = evr_t,
  rightarg = evr_t,
  procedure = evr_t_le,
  commutator = >=,
  negator = >,
  restrict = scalarltsel,
  join = scalarltjoinsel
);

create operator = (
  leftarg = evr_t,
  rightarg = evr_t,
  procedure = evr_t_eq,
  commutator = =,
  negator = <>,
  restrict = eqsel,
  join = eqjoinsel
);

create operator >= (
  leftarg = evr_t,
  rightarg = evr_t,
  procedure = evr_t_ge,
  commutator = <=,
  negator = <,
  restrict = scalargtsel,
  join = scalargtjoinsel
);

create operator > (
  leftarg = evr_t,
  rightarg = evr_t,
  procedure = evr_t_gt,
  commutator = <,
  negator = <=,
  restrict = scalargtsel,
  join = scalargtjoinsel
);

create operator <> (
  leftarg = evr_t,
  rightarg = evr_t,
  procedure = evr_t_ne,
  commutator = <>,
  negator = =,
  restrict = eqsel,
  join = eqjoinsel
);


create operator class evr_t_ops
default for type evr_t using btree as
  operator 1 <,
  operator 2 <=,
  operator 3 =,
  operator 4 >=,
  operator 5 >,
  function 1 evr_t_compare( evr_t, evr_t )
;

create or replace function evr_t_as_vre( a evr_t ) returns varchar as $$
begin
  return a.version || '-' || a.release || ':' || coalesce(a.epoch, '');
end;
$$ language plpgsql immutable strict;

create or replace function evr_t_as_vre_simple( a evr_t ) returns varchar as $$
declare
  vre_out VARCHAR(256);
begin
  vre_out := a.version || '-' || a.release;
  if a.epoch is not null
  then
    vre_out := vre_out || ':' || a.epoch;
  end if;
  return vre_out;
end;
$$ language plpgsql immutable strict;

create or replace function evr_t_larger(a evr_t, b evr_t)
returns evr_t
as $$
begin
  if a > b
  then
    return a;
  else
    return b;
  end if;
end;
$$ language plpgsql immutable strict;

create aggregate max (
  sfunc=evr_t_larger,
  basetype=evr_t,
  stype=evr_t
);
  07070100000229000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000002100000000susemanager-schema/postgres/data  0707010000022A000081B400000000000000000000000167AE11140000026E000000000000000000000000000000000000002A00000000susemanager-schema/postgres/data/Makefile #
# Copyright (c) 2008--2012 Red Hat, Inc.
#
# This software is licensed to you under the GNU General Public License,
# version 2 (GPLv2). There is NO WARRANTY for this software, express or
# implied, including the implied warranties of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
# along with this software; if not, see
# http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
#

COMMON = ../../common/data

common :
	rm -rf common
	mkdir common
	for i in $(COMMON)/* ; do sed 's/\\n/\\\\n/g' $$i > common/$${i##*/} ; done

clean :
	rm -rf common

.PHONY : common clean
  0707010000022B000081B400000000000000000000000167AE1114000001ED000000000000000000000000000000000000003000000000susemanager-schema/postgres/data/reschedule.sql   --
-- Copyright (c) 2014 SUSE LLC.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--

select randomize_bunch_schedule('mgr-sync-refresh-default');
   0707010000022C000081B400000000000000000000000167AE1114000009BA000000000000000000000000000000000000002400000000susemanager-schema/postgres/end.sql   --
-- Copyright (c) 2010--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

--
-- empty varchars are not allowed for the oracle-postgres compatibility
-- create constraints on all varchar columns (all tables for the current user)
-- and returns number of errors during processing (if not 0 then
-- check the pgsql log -- usually /var/lib/pgsql/data/pg_log -- for errors)
--
create or replace function create_varnull_constriants() returns integer as $$
declare
    tabs record;
    total integer default 0;
begin

    for tabs in select 
        c.relname as "tab",
        a.attname as "col"
    from
        pg_catalog.pg_attribute a
        left outer join pg_catalog.pg_class c on a.attrelid = c.oid 
    where
        -- skip system columns
        a.attnum > 0
        -- skip dropped columns
        and not a.attisdropped
        -- filter only varchars
        and a.atttypid = 1043
        -- skip cols that already has this constraint
        and not exists (
            select 1 from pg_catalog.pg_constraint 
            where conname = 'vn_' || c.relname || '_' || a.attname
        )
        -- filter only tables owned by current user
        and a.attrelid in (
            select c.oid from pg_catalog.pg_class c
            where relkind = 'r' and pg_catalog.pg_table_is_visible(c.oid) and relowner = (
                select oid from pg_catalog.pg_roles where rolname = current_user
            )
        ) loop
        begin
            -- create constraint
            execute 'alter table ' || tabs.tab || ' add constraint vn_' ||
                tabs.tab || '_' || tabs.col || ' check (' || tabs.col || ' <> '''')';
            -- count them
        exception when others then
            total = total + 1;
            raise warning '% unable to create constraint for %.%', now(), tabs.tab, tabs.col;
        end;
    end loop;

    return total;
end;
$$ language plpgsql;

select create_varnull_constriants();


  0707010000022D000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000002500000000susemanager-schema/postgres/packages  0707010000022E000081B400000000000000000000000167AE111400001820000000000000000000000000000000000000002D00000000susemanager-schema/postgres/packages/deb.pkb  -- oracle equivalent source sha1 539cb03eb177b7e87992701071488bbb32bb0624
create schema if not exists deb;

--update pg_setting
update pg_settings set setting = 'deb,' || setting where name = 'search_path';

-- Debian version comparison
-- See: https://www.debian.org/doc/debian-policy/ch-controlfields.html#version
-- See: https://salsa.debian.org/dpkg-team/dpkg/blob/master/lib/dpkg/version.c#L140

CREATE OR REPLACE FUNCTION lastIndexOf(needle text, haystack text)
RETURNS integer AS $$
    DECLARE
        rc INTEGER;
    BEGIN
     rc := length(haystack) - position(needle in reverse(haystack));
     if rc = length(haystack) then rc = -1; end if;
     return rc;
    END;
$$ language 'plpgsql';

create or replace function isdigit(ch CHAR)
    RETURNS BOOLEAN as $$
    BEGIN
        if ascii(ch) between ascii('0') and ascii('9')
        then
            return TRUE;
        end if;
        return FALSE;
    END ;
$$ language 'plpgsql';


create or replace FUNCTION isalpha(ch CHAR)
    RETURNS BOOLEAN as $$
    BEGIN
        if ascii(ch) between ascii('a') and ascii('z') or
            ascii(ch) between ascii('A') and ascii('Z')
        then
            return TRUE;
        end if;
        return FALSE;
    END;
$$ language 'plpgsql';

create or replace FUNCTION charAt(str IN VARCHAR, pos IN INTEGER)
    RETURNS CHARACTER as $$
    BEGIN
        return SUBSTR(str, pos + 1, 1);
    END;
$$ language 'plpgsql';

create or replace function deborder(c INTEGER)
    RETURNS INTEGER as $$
    BEGIN
        if deb.isdigit(chr(c)) then return 0; end if;
        if deb.isalpha(chr(c)) then return c; end if;
        if c = ascii('~') then return -1; end if;
        if c != 0 then return c + 256; end if;
        return 0;
    END ;
$$ language 'plpgsql';

create or replace FUNCTION verrevcmp(a1 IN VARCHAR, b1 IN VARCHAR)
    RETURNS INTEGER as $$
    DECLARE
        a VARCHAR;
        b VARCHAR;
        i INTEGER := 0;
        j INTEGER := 0;
    BEGIN
        IF a1 IS NULL then a := ''; end if;
        IF b1 IS NULL then b := ''; end if;
        a := a1;
        b := b1;
        WHILE (i < LENGTH(a)) or (j < LENGTH(b))
        LOOP
            DECLARE
                firstDiff INTEGER := 0;
            BEGIN
                while ((i < LENGTH(a)) and not deb.isdigit(deb.charAt(a,i))) or ((j < LENGTH(b)) and not deb.isdigit(deb.charAt(b,j)))
                LOOP
                DECLARE
                    ac INTEGER;
                    bc INTEGER;
                BEGIN
                    if i >= length(a)
                    then
                        ac := 0;
                    else
                        ac := deb.deborder(ascii(deb.charAt(a, i)));
                    end if;
                    if j >= length(b)
                    then
                        bc := 0;
                    else
                        bc := deb.deborder(ascii(deb.charAt(b, j)));
                    end if;
                    if ac != bc then return ac-bc; end if;
                    i := i + 1;
                    j := j + 1;
                END;
                END LOOP;
                while (i < length(a)) and (deb.charAt(a, i) = '0')
                LOOP
                    i := i + 1;
                END LOOP;
                while (j < length(b)) and (deb.charAt(b, j) = '0')
                LOOP
                    j := j + 1;
                END LOOP;
                WHILE (i < LENGTH(a)) and (j < LENGTH(b)) and (deb.isdigit(deb.charAt(a,i))) and (deb.isdigit(deb.charAt(b, j)))
                LOOP
                    if firstDiff = 0 then firstDiff := ascii(deb.charAt(a, i)) - ascii(deb.charAt(b, j)); end if;
                    i := i + 1;
                    j := j + 1;
                END LOOP;
                IF (i < LENGTH(a)) and (deb.isdigit(deb.charAt(a,i))) then return 1; end if;
                IF (j < LENGTH(b)) and (deb.isdigit(deb.charAt(b,j))) then return -1; end if;
                IF firstDiff != 0 then return firstDiff; end if;
            END;
        END LOOP;
        RETURN 0;
    END;
$$ language 'plpgsql';

create or replace FUNCTION debstrcmp (o1 IN VARCHAR, o2 IN VARCHAR)
    RETURNS INTEGER as $$
    declare
        version1 VARCHAR := o1;
        version2 VARCHAR := o2;
        revision1 VARCHAR;
        revision2 VARCHAR;
        rc INTEGER;
        rv INTEGER;
    BEGIN
        IF deb.lastIndexOf('-', version1) > 0
        then
            revision1 := SUBSTR(version1, POSITION('-' IN version1) + 1);
            version1 := SUBSTR(version1, 0, POSITION('-' IN version1));
        end if;
        IF deb.lastIndexOf('-',version2) > 0
        then
            revision2 := SUBSTR(version2, POSITION('-' IN version2) + 1);
            version2 := SUBSTR(version2, 0, POSITION('-' IN version2));
        end if;
        rc := deb.verrevcmp(version1, version2);
        if rc > 0 then return 1; end if;
        if rc < 0 then return -1; end if;
        if rc = 0
        then
            rv := deb.verrevcmp(revision1, revision2);
            if rv > 0 then return 1; end if;
            if rv < 0 then return -1; end if;
            return 0;
        end if;
    END;
$$ language 'plpgsql';

create or replace FUNCTION debvercmp(
        e1 VARCHAR, v1 VARCHAR, r1 VARCHAR,
        e2 VARCHAR, v2 VARCHAR, r2 VARCHAR)
    RETURNS INTEGER as $$
    declare
        rc INTEGER;
          ep1 INTEGER;
          ep2 INTEGER;
          BEGIN
            if e1 is null or e1 = '' then
              ep1 := 0;
            else
              ep1 := e1::integer;
            end if;
            if e2 is null or e2 = '' then
              ep2 := 0;
            else
              ep2 := e2::integer;
            end if;
            -- Epochs are non-null; compare them
            if ep1 < ep2 then return -1; end if;
            if ep1 > ep2 then return 1; end if;
            rc := deb.debstrcmp(v1, v2);
            if rc != 0 then return rc; end if;
           return deb.debstrcmp(r1, r2);
         END;
         $$ language 'plpgsql';

-- restore the original setting
update pg_settings set setting = overlay( setting placing '' from 1 for (length('deb')+1) ) where name = 'search_path';
0707010000022F000081B400000000000000000000000167AE111400000EBB000000000000000000000000000000000000003300000000susemanager-schema/postgres/packages/packages.deps    #
# Copyright (c) 2008--2012 Red Hat, Inc.
#
# This software is licensed to you under the GNU General Public License,
# version 2 (GPLv2). There is NO WARRANTY for this software, express or
# implied, including the implied warranties of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
# along with this software; if not, see
# http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
#
# Dependencies for package objects in this (namespace) directory.
# See: ../../README for details.
# No TABS, PLEASE!
#

path = . tables views procs

rhn_cache.pkb           :: rhnUserServerPerms rhnUserServerPermsDupes \
                           rhnUserServerGroupPerms rhnUserGroupType \
                           rhnUserGroupMembers rhnServerGroup rhnUserGroup
rhn_channel.pkb         :: rhnChannel rhn_exception.pks rhnServer rhnServerChannel \
                           rhnChannelFamilyPermissions queue_server queue_image \
                           rhnChannelFamilyMembers suseImageInfoChannel \
                           rhnChannelNewestPackage rhnChannelNewestPackageView \
                           rhnPublicChannelFamily rhnOrgChannelFamilyPermissions \
                           rhnChannelPackage rhnChannelErrata rhnSnapshotChannel \
                           rhnServerUuid rhnChannelPermissions rhnServerEntitlementView \
                           rhnSharedChannelView \
                           rhnOrgDistChannelMap \
                           rhn_user.pks
rhn_channel.pks         :: rhnChannel rhnOrgChannelFamilyPermissions \
                           rhnServerChannel
rhn_config.pkb          :: rhnSnapshot rhnSnapshotConfigRevision lookup_functions \
                           rhnConfigRevision rhnConfigRevision rhnConfigFile \
                           rhnConfigChannel rhnConfigContent \
                           rhnConfigFileState
rhn_config_channel.pkb  :: rhnConfigChannelType rhnConfigChannel \
                           rhnServerConfigChannel rhnConfigRevision rhnConfigFile \
                           rhnConfigFileName
rhn_entitlements.pkb    :: rhnServerGroupType rhnServerGroup rhnServerGroupMembers \
                           rhnServer rhnUserGroupType \
                           rhnUserGroupMembers \
                           rhnUserGroup rhnChannelFamilyMembers rhnServerChannel \
                           rhnOrgChannelFamilyPermissions \
                           rhnServerServerGroupArchCompat rhnPrivateChannelFamily \
                           rhnServerEntitlementPhysical
rhn_entitlements.pks    :: rhnServerGroupType
rhn_exception.pkb       :: rhnException
rhn_exception.pks       :: rhnException
rhn_org.pkb             :: rhn_entitlements.pks \
                           rhn_exception.pks rhn_server.pks delete_server \
                           rhnServer rhnServerGroupType rhnServerGroup \
                           web_contact web_customer
rhn_org.pks             :: rhnServerGroupType rhnServerGroup
rhn_server.pkb          :: rhnServerChannel rhnConfigFileName \
                           rhnServerGroupMembers rhnServerPackage rhnServer \
                           rhnServerCustomDataValue rhnCustomDataKey \
                           rhnUserManagedServerGroups rhnServerEntitlementVirtual \
                           suseMgrServerInfo rhnProxyInfo \
                           lookup_functions lookup_first_matching_cf \
                           set_ks_session_history_message \
                           rhnPackage rhnChannelNewestPackage \
                           rhnPackageEVR rhnChannelPackage rhnErrataPackage \
                           rhnChannelErrata rhnPackageUpgradeArchCompat \
                           susePackageExcludingPartOfPtf
 07070100000230000081B400000000000000000000000167AE11140000108E000000000000000000000000000000000000003300000000susemanager-schema/postgres/packages/rhn_cache.pkb    -- oracle equivalent source sha1 5299b0825394420433f1f6b11d77c757659f2d8a
--
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--

--create schema rhn_cache;

-- setup search_path so that these functions are created in appropriate schema.
update pg_settings set setting = 'rhn_cache,' || setting where name = 'search_path';

create or replace function update_perms_for_server(
                server_id_in in numeric
        ) returns void
        as
        $$
begin
                -- delete rows which are no more valid
		delete from rhnUserServerPerms p
                      where server_id = server_id_in
                        and user_id not in (select user_id
                                              from rhnUserServerPermsDupes d
                                             where p.server_id = d.server_id);
                -- insert newly added rows
		insert into rhnUserServerPerms(user_id, server_id) (
			select distinct user_id, server_id_in
				   from	rhnUserServerPermsDupes d
                                  where server_id = server_id_in
                                    and user_id not in (
                                                select user_id
                                                  from rhnUserServerPerms p
                                                 where p.server_id = d.server_id)
			);
end ;
$$
language plpgsql;


create or replace function update_perms_for_user(
                user_id_in in numeric
        ) returns void
        as
        $$
begin
                -- first delete rows which are not in rhnUserServerPermsDupes
                delete from rhnUserServerPerms up
                 where user_id = user_id_in
                   and not exists (
                       select 1
                         from rhnUserServerPermsDupes uspd
                        where uspd.user_id = up.user_id
                          and uspd.server_id = up.server_id);

                -- then insert rest of rows from rhnUserServerPermsDupes
                insert into rhnUserServerPerms (user_id, server_id)
                       select distinct user_id_in, server_id
                         from rhnUserServerPermsDupes uspd
                        where uspd.user_id = user_id_in
                          and not exists (
                              select 1
                                from rhnUserServerPerms usp
                               where usp.user_id = user_id_in
                                 and usp.server_id = uspd.server_id);
end;
$$ language plpgsql;

	-- this means a server got added or removed, so we
	-- can't key off of a server anywhere.
create or replace function update_perms_for_server_group(
                server_group_id_in in numeric
        ) returns void 
as
$$
declare
       users cursor for
			-- org admins aren't affected, so don't test for them
			select	usgp.user_id id
			from	rhnUserServerGroupPerms usgp
			where	usgp.server_group_id = server_group_id_in
				and not exists (
					select	1
					from	rhnUserGroup ug,
							rhnUserGroupMembers ugm,
							rhnServerGroup sg,
							rhnUserGroupType ugt
					where	ugt.label = 'org_admin'
                                                and ugt.id = ug.group_type
						and sg.id = server_group_id_in
						and ugm.user_id = usgp.user_id
						and ug.org_id = sg.org_id
						and ugm.user_group_id = ug.id
					);
begin
	for u in users loop
		perform rhn_cache.update_perms_for_user(u.id);
	end loop;
end;
$$ language plpgsql;

-- restore the original setting
update pg_settings set setting = overlay( setting placing '' from 1 for (length('rhn_cache')+1) ) where name = 'search_path';
  07070100000231000081B400000000000000000000000167AE1114000002DD000000000000000000000000000000000000003300000000susemanager-schema/postgres/packages/rhn_cache.pks    -- oracle equivalent source sha1 8a5b855728098bedcce2c5f4d7a04d6ce79bfef4
--
-- Copyright (c) 2008--2015 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--

create schema rhn_cache;

   07070100000232000081B400000000000000000000000167AE1114000071F8000000000000000000000000000000000000003500000000susemanager-schema/postgres/packages/rhn_channel.pkb  -- oracle equivalent source sha1 31306ef50aaa30b52c7dd02adcb94ab66de8fb25
--
-- Copyright (c) 2008--2018 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--
--
--
--

-- create schema rhn_channel;

--update pg_setting
update pg_settings set setting = 'rhn_channel,' || setting where name = 'search_path';

    -- this "emulates" cursor server_base_subscriptions defined in oracle/rhn_channel.pks
    create or replace function server_base_subscriptions(server_id_in NUMERIC)
    returns boolean as $$
    begin
      return exists(SELECT C.id FROM rhnChannel C, rhnServerChannel SC
		    WHERE C.id = SC.channel_id
		      AND SC.server_id = server_id_in
		      AND C.parent_channel IS NULL);
    end$$ language plpgsql;

    -- this "emulates" cursor server_base_subscriptions defined in oracle/rhn_channel.pks
    create or replace function check_server_subscription(server_id_in NUMERIC, channel_id_in NUMERIC)
    returns boolean as $$
    begin
      return exists(SELECT channel_id FROM rhnServerChannel WHERE server_id = server_id_in AND channel_id = channel_id_in);
    end$$ language plpgsql;


    CREATE OR REPLACE FUNCTION subscribe_server(server_id_in IN NUMERIC, channel_id_in NUMERIC, immediate_in NUMERIC default 1, user_id_in in numeric default null) returns void
    AS $$
    declare
        channel_parent_val      rhnChannel.parent_channel%TYPE;
        parent_subscribed       BOOLEAN;
        server_has_base_chan    BOOLEAN;
        server_already_in_chan  BOOLEAN;
        channel_family_id_val   NUMERIC;
        allowed                 numeric;
    BEGIN
        if user_id_in is not null then
            allowed := rhn_channel.user_role_check(channel_id_in, user_id_in, 'subscribe');
        else
            allowed := 1;
        end if;

        if allowed = 0 then
            perform rhn_exception.raise_exception('no_subscribe_permissions');
        end if;
        
        server_already_in_chan := rhn_channel.check_server_subscription(server_id_in, channel_id_in);

        IF server_already_in_chan
        THEN
            RETURN;
        END IF;

        SELECT parent_channel INTO channel_parent_val FROM rhnChannel WHERE id = channel_id_in;

        IF channel_parent_val IS NOT NULL
        THEN
            -- child channel; if attempting to cross-subscribe a child to the wrong base, silently ignore
            parent_subscribed := rhn_channel.check_server_subscription(server_id_in, channel_parent_val);

            IF NOT parent_subscribed
            THEN
                RETURN;
            END IF;
        ELSE
            -- base channel
            server_has_base_chan := rhn_channel.server_base_subscriptions(server_id_in);

            IF server_has_base_chan
            THEN
                perform rhn_exception.raise_exception('channel_server_one_base');
            END IF;
        END IF;

        channel_family_id_val := rhn_channel.family_for_channel(channel_id_in);
        IF channel_family_id_val IS NULL
        THEN
            perform rhn_exception.raise_exception('channel_subscribe_no_family');
        END IF;

        insert into rhnServerHistory (id,server_id,summary,details) (
            select  nextval('rhn_event_id_seq'),
                    server_id_in,
                    'subscribed to channel ' || SUBSTR(c.label, 0, 106),
                    c.label
            from    rhnChannel c
            where   c.id = channel_id_in
        );

        INSERT INTO rhnServerChannel (server_id, channel_id) VALUES (server_id_in, channel_id_in);

        perform queue_server(server_id_in, immediate_in);

        update rhnServer
           set channels_changed = current_timestamp
         where id = server_id_in;
    END$$ language plpgsql;

    create or replace function guess_server_base(
        server_id_in in numeric
    ) RETURNS numeric as $$
    declare
        server_cursor cursor for
            select s.server_arch_id, s.release, s.org_id
              from rhnServer s
             where s.id = server_id_in;
    -- Cursor that fetches all the possible base channels for a
    -- (server_arch_id, release, org_id) combination
        base_channel_cursor cursor(
                release_in varchar,
                server_arch_id_in numeric,
                org_id_in numeric
        ) for
                select distinct c.*
                from    rhnOrgDistChannelMap                       odcm,
                                rhnServerChannelArchCompat      scac,
                                rhnChannel                                      c
                where   c.parent_channel is null
                        and c.id = odcm.channel_id
                        and c.channel_arch_id = odcm.channel_arch_id
                        and odcm.release = release_in
                        and odcm.for_org_id = org_id_in
                        and scac.server_arch_id = server_arch_id_in
                        and scac.channel_arch_id = c.channel_arch_id;

    begin
        for s in server_cursor loop
            for channel in base_channel_cursor(s.release,
                s.server_arch_id, s.org_id)
            loop
                return channel.id;
            end loop;
        end loop;
        -- Server not found, or no base channel applies to it
        return null;
    end$$ language plpgsql;

    -- Private function
    create or replace function normalize_server_arch(server_arch_in in varchar)
    returns varchar
    as $$
    declare
        suffix VARCHAR(128) := '-redhat-linux';
    begin
        if server_arch_in is NULL then
            return NULL;
        end if;
        if position('-' IN server_arch_in) > 0
        then
            -- Suffix already present
            return server_arch_in;
        end if;
        return server_arch_in || suffix;
    end$$ language plpgsql;

    --
    -- Raises:
    --   server_arch_not_found
    --   no_subscribe_permissions
    create or replace function base_channel_for_release_arch(
        release_in in varchar,
        server_arch_in in varchar,
        org_id_in in numeric default -1,
        user_id_in in numeric default null
    ) returns numeric as $$
    declare
        server_arch varchar(256) := rhn_channel.normalize_server_arch(server_arch_in);
        server_arch_id numeric;
    begin
        -- Look up the server arch
            select id
              into server_arch_id
              from rhnServerArch
             where label = server_arch;
            if not found then
                perform rhn_exception.raise_exception('server_arch_not_found');
            end if;

        return rhn_channel.base_channel_rel_archid(release_in, server_arch_id,
            org_id_in, user_id_in);
    end$$ language plpgsql;

    create or replace function base_channel_rel_archid(
        release_in in varchar,
        server_arch_id_in in numeric,
        org_id_in in numeric default -1,
        user_id_in in numeric default null
    ) returns numeric as $$
    declare
        denied_channel_id numeric := null;
        valid_org_id numeric := org_id_in;
        valid_user_id numeric := user_id_in;
        channel_subscribable numeric;
    -- Cursor that fetches all the possible base channels for a
    -- (server_arch_id, release, org_id) combination
        base_channel_cursor cursor(
                release_in varchar,
                server_arch_id_in numeric,
                org_id_in numeric
        ) for
                select distinct c.*
                from    rhnOrgDistChannelMap                       odcm,
                                rhnServerChannelArchCompat      scac,
                                rhnChannel                                      c
                where   c.parent_channel is null
                        and c.id = odcm.channel_id
                        and c.channel_arch_id = odcm.channel_arch_id
                        and odcm.release = release_in
                        and odcm.for_org_id = org_id_in
                        and scac.server_arch_id = server_arch_id_in
                        and scac.channel_arch_id = c.channel_arch_id;

    begin
        if org_id_in = -1 and user_id_in is not null then
            -- Get the org id from the user id

                select org_id
                  into valid_org_id
                  from web_contact
                 where id = user_id_in;

                if not found then
                    -- User doesn't exist
                    -- XXX Only list public stuff for now
                    valid_user_id := null;
                    valid_org_id := -1;
                end if;
        end if;

        for c in base_channel_cursor(release_in, server_arch_id_in, valid_org_id)
        loop
            -- This row is a possible match
            if valid_user_id is null then
                -- User ID not specified, so no user to channel permissions to
                -- check
                return c.id;
            end if;

            -- Check user to channel permissions
            select rhn_channel.loose_user_role_check(c.id, user_id_in, 'subscribe')
              into channel_subscribable;

            if channel_subscribable = 1 then
                return c.id;
            end if;

            -- Base channel exists, but is not subscribable; keep trying
            denied_channel_id := c.id;
        end loop;

        if denied_channel_id is not null then
            perform rhn_exception.raise_exception('no_subscribe_permissions');
        end if;
        -- No base channel applies
        return NULL;
    end$$ language plpgsql;

    CREATE OR REPLACE FUNCTION clear_subscriptions(server_id_in IN NUMERIC, deleting_server IN NUMERIC default 0) returns void
    AS $$
    declare
        server_channels cursor(server_id_in numeric) for
                select  s.org_id, sc.channel_id, cfm.channel_family_id
                from    rhnServer s,
                        rhnServerChannel sc,
                        rhnChannelFamilyMembers cfm
                where   s.id = server_id_in
                        and s.id = sc.server_id
                        and sc.channel_id = cfm.channel_id
                order by cfm.channel_family_id;
        last_channel_family_id rhnChannelFamilyMembers.channel_family_id%type := -1;
        last_channel_org_id    rhnServer.org_id%type := -1;
    BEGIN
        for channel in server_channels(server_id_in)
        loop
                perform rhn_channel.unsubscribe_server(server_id_in, channel.channel_id, 1, 1, deleting_server);
        end loop;
    END$$ language plpgsql;

    CREATE OR REPLACE FUNCTION unsubscribe_server(server_id_in IN NUMERIC, channel_id_in NUMERIC, immediate_in NUMERIC default 1, unsubscribe_children_in numeric default 0,
                                 deleting_server in numeric default 0) returns void
    AS $$
    declare
        channel_family_id_val   NUMERIC;
        server_org_id_val       NUMERIC;
        server_already_in_chan  BOOLEAN;
        channel_family_is_proxy cursor(channel_family_id_in numeric) for
                select  1
                from    rhnChannelFamily
                where   id = channel_family_id_in
                    and label = 'SMP';
        channel_family_is_satellite cursor(channel_family_id_in numeric) for
                select  1
                from    rhnChannelFamily
                where   id = channel_family_id_in
                    and label IN ('SMS', 'SMS-X86', 'SMS-Z', 'SMS-PPC');
        child record;
    BEGIN
        -- In PostgreSQL recursion with opened cursors is not allowed so we use
        -- FOR IN SELECT form which is ok.
        FOR child IN select  c.id
                from    rhnChannel                      c,
                                rhnServerChannel        sc
                where   1=1
                        and c.parent_channel = channel_id_in
                        and c.id = sc.channel_id
                        and sc.server_id = server_id_in
        LOOP
            if unsubscribe_children_in = 1 then
                perform rhn_channel.unsubscribe_server(server_id_in,
                                                       child.id,
                                                       immediate_in,
                                                       unsubscribe_children_in,
                                                       deleting_server);
            else
                perform rhn_exception.raise_exception('channel_unsubscribe_child_exists');
            end if;
        END LOOP;

        server_already_in_chan := rhn_channel.check_server_subscription(server_id_in, channel_id_in);

        IF NOT server_already_in_chan
        THEN
            RETURN;
        END IF;

   if deleting_server = 0 then
      insert into rhnServerHistory (id,server_id,summary,details) (
          select  nextval('rhn_event_id_seq'),
                server_id_in,
             'unsubscribed from channel ' || SUBSTR(c.label, 0, 106),
             c.label
          from    rhnChannel c
          where   c.id = channel_id_in
      );
   end if;

   DELETE FROM rhnServerChannel WHERE server_id = server_id_in AND channel_id = channel_id_in;

   if deleting_server = 0 then
        perform queue_server(server_id_in, immediate_in);

        update rhnServer
           set channels_changed = current_timestamp
         where id = server_id_in;
   end if;

        channel_family_id_val := rhn_channel.family_for_channel(channel_id_in);
        IF channel_family_id_val IS NULL
        THEN
            perform rhn_exception.raise_exception('channel_unsubscribe_no_family');
        END IF;

        for ignore in channel_family_is_satellite(channel_family_id_val) loop
                delete from suseMgrServerInfo where server_id = server_id_in;
        end loop;

        for ignore in channel_family_is_proxy(channel_family_id_val) loop
                delete from rhnProxyInfo where server_id = server_id_in;
        end loop;
        SELECT org_id INTO server_org_id_val
          FROM rhnServer
         WHERE id = server_id_in;

    END$$ language plpgsql;

    CREATE OR REPLACE FUNCTION family_for_channel(channel_id_in IN NUMERIC)
    RETURNS NUMERIC
    AS $$
    declare
        channel_family_id_val NUMERIC;
    BEGIN
        SELECT channel_family_id INTO channel_family_id_val
          FROM rhnChannelFamilyMembers
         WHERE channel_id = channel_id_in;

        IF NOT FOUND THEN
          RETURN NULL;
        END IF;

        RETURN channel_family_id_val;
    END$$ language plpgsql;

    create or replace function unsubscribe_server_from_family(server_id_in in numeric,
                                             channel_family_id_in in numeric)
    returns void
    as $$
    begin
        delete
        from    rhnServerChannel rsc
        where   rsc.server_id = server_id_in
            and channel_id in (
                select  rcfm.channel_id
                from    rhnChannelFamilyMembers rcfm
                where   rcfm.channel_family_id = channel_family_id_in);
    end$$ language plpgsql;

    create or replace function get_org_id(channel_id_in in numeric)
    returns numeric
    as $$
    declare
        org_id_out numeric;
    begin
        select org_id into strict org_id_out
            from rhnChannel
            where id = channel_id_in;

            return org_id_out;
    end$$ language plpgsql;

    create or replace function get_cfam_org_access(cfam_id_in in numeric, org_id_in in numeric)
    returns numeric
    as $$
    begin
      if exists(
                        select  1
                        from    rhnOrgChannelFamilyPermissions cfp
                        where   cfp.org_id = org_id_in
      ) then
                return 1;
      else
                return 0;
      end if;
    end$$ language plpgsql;

    create or replace function get_org_access(channel_id_in in numeric, org_id_in in numeric)
    returns integer
    as $$
    begin
        -- the idea: if we get past this query,
        -- the org has access to the channel, else not
        if exists(
        select 1
          from rhnChannelFamilyMembers CFM,
               rhnOrgChannelFamilyPermissions CFP
         where cfp.org_id = org_id_in
           and CFM.channel_family_id = CFP.channel_family_id
           and CFM.channel_id = channel_id_in)
        then
          return 1;
        else
          return 0;
        end if;
    end$$ language plpgsql;

    create or replace function rhn_channel.user_role_check(channel_id_in in numeric, user_id_in in numeric, role_in in varchar)
    returns numeric
    as $$
    declare
        result NUMERIC;
    begin
        SELECT
          INTO result
          CASE
            WHEN suseChannelUserRoleView.deny_reason IS NULL THEN 1
            ELSE 0
            END
          FROM suseChannelUserRoleView
          WHERE channel_id = channel_id_in AND
            user_id = user_id_in AND
            role = role_in;

         if result IS NULL then
           result := 0;
         end if;

         RETURN result;
    end$$ language plpgsql;

    --
    -- For multiorg phase II, this function simply checks to see if the user's
    -- has a trust relationship that includes this channel by id.
    --
    create or replace function shared_user_role_check(channel_id in numeric, user_id in numeric, role in varchar)
    returns numeric
    as $$
    declare
      n numeric;
      oid numeric;
    begin
      oid := rhn_user.get_org_id(user_id);
      select 1 into n
      from rhnSharedChannelView s
      where s.id = channel_id and s.org_trust_id = oid;

      if not found then
        return 0;
      end if;

      return 1;
    end$$ language plpgsql;

    -- same as above, but returns 1 if user_id_in is null
    -- This is useful in queries where user_id is not specified
    create or replace function loose_user_role_check(channel_id_in in numeric, user_id_in in numeric, role_in in varchar)
    returns numeric
    as $$
    begin
        if user_id_in is null then
            return 1;
        end if;
        return rhn_channel.user_role_check(channel_id_in, user_id_in, role_in);
    end$$ language plpgsql;

    -- directly checks the table, no inferred permissions
    create or replace function direct_user_role_check(channel_id_in in numeric, user_id_in in numeric, role_in in varchar)
    returns numeric
    as $$
    declare
        throwaway numeric;
    begin
        -- the idea: if we get past this query, the user has the role, else no
        select 1 into throwaway
          from rhnChannelPermissionRole CPR,
               rhnChannelPermission CP
         where CP.user_id = user_id_in
           and CP.channel_id = channel_id_in
           and CPR.label = role_in
           and CP.role_id = CPR.id;

      if not found then
        return 0;
      end if;

      return 1;
    end$$ language plpgsql;

    -- check if an org has a certain setting
    create or replace function org_channel_setting(channel_id_in in numeric, org_id_in in numeric, setting_in in varchar)
    returns numeric
    as $$
    declare
        throwaway numeric;
    begin
        -- the idea: if we get past this query, the org has the setting
        select 1 into throwaway
          from rhnOrgChannelSettingsType OCST,
               rhnOrgChannelSettings OCS
         where OCS.org_id = org_id_in
           and OCS.channel_id = channel_id_in
           and OCST.label = setting_in
           and OCS.setting_id = OCST.id;

      if not found then
        return 0;
      end if;

      return 1;
    end$$ language plpgsql;

    CREATE OR REPLACE FUNCTION channel_priority(channel_id_in IN numeric)
    RETURNS numeric
    AS $$
    declare
         channel_name varchar(256);
         priority numeric;
         end_of_life_val timestamptz;
         org_id_val numeric;
    BEGIN

        select name, end_of_life, org_id
        into channel_name, end_of_life_val, org_id_val
        from rhnChannel
        where id = channel_id_in;

        if end_of_life_val is not null then
          return -400;
        end if;

        if channel_name like 'Red Hat Enterprise Linux%' or channel_name like 'RHEL%' then
          priority := 1000;
          if channel_name not like '%Beta%' then
            priority := priority + 1000;
          end if;

          priority := priority +
            case
              when channel_name like '%v. 5%' then 600
              when channel_name like '%v. 4%' then 500
              when channel_name like '%v. 3%' then 400
              when channel_name like '%v. 2%' then 300
              when channel_name like '%v. 1%' then 200
              else 0
            end;

          priority := priority +
            case
              when channel_name like 'Red Hat Enterprise Linux (v. 5%' then 60
              when (channel_name like '%AS%' and channel_name not like '%Extras%') then 50
              when (channel_name like '%ES%' and channel_name not like '%Extras%') then 40
              when (channel_name like '%WS%' and channel_name not like '%Extras%') then 30
              when (channel_name like '%Desktop%' and channel_name not like '%Extras%') then 20
              when channel_name like '%Extras%' then 10
              else 0
            end;

          priority := priority +
            case
              when channel_name like '%)' then 5
              else 0
            end;

          priority := priority +
            case
              when channel_name like '%32-bit x86%' then 4
              when channel_name like '%64-bit Intel Itanium%' then 3
              when channel_name like '%64-bit AMD64/Intel EM64T%' then 2
              else 0
            end;
        elsif channel_name like 'Red Hat Desktop%' then
            priority := 900;

            if channel_name not like '%Beta%' then
               priority := priority + 50;
            end if;

          priority := priority +
            case
              when channel_name like '%v. 4%' then 40
              when channel_name like '%v. 3%' then 30
              when channel_name like '%v. 2%' then 20
              when channel_name like '%v. 1%' then 10
              else 0
            end;

          priority := priority +
            case
              when channel_name like '%32-bit x86%' then 4
              when channel_name like '%64-bit Intel Itanium%' then 3
              when channel_name like '%64-bit AMD64/Intel EM64T%' then 2
              else 0
            end;

        elsif org_id_val is not null then
          priority := 600;
        else
          priority := 500;
        end if;

      return -priority;

    end$$ language plpgsql;

    -- this could certainly be optimized to do updates if needs be
    create or replace function refresh_newest_package(channel_id_in in numeric,
                                      caller_in in varchar default '(unknown)',
                                      package_name_id_in in numeric default null)
    returns void
    as $$
    -- procedure refreshes rows for name_id = package_name_id_in or
    -- all rows if package_name_id_in is null
    begin
        delete from rhnChannelNewestPackage
              where channel_id = channel_id_in
                and (package_name_id_in is null
                     or name_id = package_name_id_in);
        insert into rhnChannelNewestPackage
                (channel_id, name_id, evr_id, package_id, package_arch_id)
                (select channel_id,
                        name_id, evr_id,
                        package_id, package_arch_id
                   from rhnChannelNewestPackageView
                  where channel_id = channel_id_in
                    and (package_name_id_in is null
                         or name_id = package_name_id_in)
                );
        insert into rhnChannelNewestPackageAudit (channel_id, caller)
             values (channel_id_in, caller_in);
        update rhnChannel
           set last_modified = greatest(current_timestamp,
                                        last_modified + interval '1 second')
         where id = channel_id_in;
    end$$ language plpgsql;

   create or replace function update_channel ( channel_id_in in numeric, invalidate_ss in numeric default 0,
                              date_to_use in timestamptz default current_timestamp ) returns void
   as $$
   declare
   channel_last_modified timestamptz;
   last_modified_value timestamptz;

   snapshots cursor for
   select  snapshot_id id
   from    rhnSnapshotChannel
   where   channel_id = channel_id_in;

   begin

      select last_modified
      into channel_last_modified
      from rhnChannel
      where id = channel_id_in;

      last_modified_value := date_to_use;

      if last_modified_value <= channel_last_modified then
          last_modified_value := last_modified_value + interval '1 second';
      end if;

      update rhnChannel set last_modified = last_modified_value
      where id = channel_id_in;

      if invalidate_ss = 1 then
        for snapshot in snapshots loop
            update rhnSnapshot
            set invalid = lookup_snapshot_invalid_reason('channel_modified')
            where id = snapshot.id;
        end loop;
      end if;

   end$$ language plpgsql;

   create or replace function update_channels_by_package ( package_id_in in numeric, date_to_use in timestamptz default current_timestamp ) returns void
   as $$
   declare
   channels cursor for
   select channel_id
   from rhnChannelPackage
   where package_id = package_id_in
   order by channel_id;

   begin
      for channel in channels loop
         -- we want to invalidate the snapshot assocated with the channel when we
         -- do this b/c we know we've added or removed or packages
         perform rhn_channel.update_channel ( channel.channel_id, 1, date_to_use );
      end loop;
   end$$ language plpgsql;


   create or replace function update_channels_by_errata ( errata_id_in numeric, date_to_use in timestamptz default current_timestamp ) returns void
   as $$
   declare
   channels cursor for
   select channel_id
   from rhnChannelErrata
   where errata_id = errata_id_in
   order by channel_id;

   begin
      for channel in channels loop
         -- we won't invalidate snapshots, b/c just changing the errata associated with
         -- a channel shouldn't invalidate snapshots
         perform rhn_channel.update_channel ( channel.channel_id, 0, date_to_use );
      end loop;
   end$$ language plpgsql;

   create or replace function update_needed_cache(channel_id_in in numeric) returns void
   as $$
   declare
   server record;
   image record;
   begin
      -- we intentionaly do a loop here instead of one huge select
      -- b/c we want to break update into smaller transaction to unblock other sessions
      -- querying rhnServerNeededCache
      for server in (
                select sc.server_id as id
                  from rhnServerChannel sc
                 where sc.channel_id = channel_id_in
                 order by id asc
      ) loop
         perform queue_server(server.id, 0); -- NOT IMMEDIATE
      end loop;
      for image in (
        select ic.image_info_id as id
          from suseImageInfoChannel ic
         where ic.channel_id = channel_id_in
        order by id asc
      ) loop
         perform queue_image(image.id, 0);
      end loop;
   end$$ language plpgsql;

    create or replace function set_comps(channel_id_in in numeric, path_in in varchar, comps_type_id_in in numeric, timestamp_in in varchar) returns void
    as $$
    declare
    row record;
    begin
        for row in (
            select relative_filename, last_modified
            from rhnChannelComps
            where channel_id = channel_id_in
            and comps_type_id = comps_type_id_in
            ) loop
            if row.relative_filename = path_in
                and row.last_modified = to_timestamp(timestamp_in, 'YYYYMMDDHH24MISS') then
                return;
            end if;
        end loop;
        delete from rhnChannelComps
        where channel_id = channel_id_in and comps_type_id = comps_type_id_in;
        insert into rhnChannelComps (id, channel_id, relative_filename, comps_type_id, last_modified, created, modified)
        values (sequence_nextval('rhn_channelcomps_id_seq'), channel_id_in, path_in, comps_type_id_in, to_timestamp(timestamp_in, 'YYYYMMDDHH24MISS'), current_timestamp, current_timestamp);
    end$$ language plpgsql;

-- restore the original setting
update pg_settings set setting = overlay( setting placing '' from 1 for (length('rhn_channel')+1) ) where name = 'search_path';
07070100000233000081B400000000000000000000000167AE111400000067000000000000000000000000000000000000003500000000susemanager-schema/postgres/packages/rhn_channel.pks  -- oracle equivalent source sha1 e86b918dfa87e9b95dac190315277eb86162bbca

create schema rhn_channel;

 07070100000234000081B400000000000000000000000167AE111400001875000000000000000000000000000000000000003400000000susemanager-schema/postgres/packages/rhn_config.pkb   -- oracle equivalent source sha1 08b203f536190084578c2fbf6dc1845d7945e3fd
--
-- Copyright (c) 2008--2015 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--

-- setup search_path so that these functions are created in appropriate schema.
update pg_settings set setting = 'rhn_config,' || setting where name = 'search_path';


	-- just a stub for now
create or replace function prune_org_configs (
		org_id_in in numeric,
		total_in in numeric
	)
returns void
as $$	
begin
end;
$$ LANGUAGE 'plpgsql';


	create or replace function insert_revision (
		revision_in in numeric,
		config_file_id_in in numeric,
		config_content_id_in in numeric,
		config_info_id_in in numeric,
		config_file_type_id_in in numeric default 1
	) returns numeric as $$
               declare
		retval numeric;

	begin
      
		insert into rhnConfigRevision(id, revision, config_file_id,
				config_content_id, config_info_id, config_file_type_id
			) values (
				nextval('rhn_confrevision_id_seq'), revision_in, config_file_id_in,
				config_content_id_in, config_info_id_in, config_file_type_id_in
			)
			returning id into retval;

		return retval;
	end$$ language 'plpgsql';

	create or replace function delete_revision (
		config_revision_id_in in numeric,
		org_id_in in numeric default -1
	) returns void as $$
	declare
		cfid numeric;
		ccid numeric;
		latest_crid numeric;
		others numeric := 0;
	begin
		select	cr.config_content_id
		into	ccid
		from	rhnConfigRevision cr
		where	cr.id = config_revision_id_in;

		-- right now this will set rhnActionConfigFileName.config_revision_id
		-- to null, and will remove an entry from rhnActionConfigRevision.
		-- might we want to prune and/or kill the action in some way?  maybe
		-- mark it failed or something?
                -- this delete also triggers rhn_confrevision_del_trig() which
                -- a) updates rhnSnapshot.invalid to 'cr_removed'
                -- and b) deletes snapshots from rhnSnapshotConfigRevision
		delete from rhnConfigRevision where id = config_revision_id_in;

		-- now prune away content if there aren't any other revisions pointing
		-- at it
		select count(*)
                  into others
                  from rhnConfigRevision
                 where config_content_id = ccid;
		if others = 0 then
			delete from rhnConfigContent where id = ccid;
		end if;

		-- now make sure rhnConfigFile points at a valid revision;
		-- if there isn't one, we're deleting it, _unless_ org_id_in is
		-- >= 0, in which case we're in the delete trigger anyway
		if org_id_in < 0 then
			select	cf.latest_config_revision_id,
					cf.id
			into latest_crid,
					cfid
			from rhnConfigFile cf,
					rhnConfigRevision cr
			where cr.id = config_revision_id_in
				and cr.config_file_id = cf.id;

			if latest_crid = config_revision_id_in then
				latest_crid := rhn_config.get_latest_revision(cfid);
				if latest_crid is not null then
					update rhnConfigFile set latest_config_revision_id = latest_crid
						where id = cfid;
				else
					delete from rhnConfigFile where id = cfid;
				end if;
			end if;

		end if;

	end ;
$$ LANGUAGE 'plpgsql';

	create or replace function get_latest_revision (
		config_file_id_in in numeric
		) 
		returns numeric as $$
		declare 
 		revision1 record;
		begin
		for revision1 in 
			select cr.id 
			from rhnConfigRevision cr
			where cr.config_file_id = config_file_id_in
			order by revision desc
		loop
			return revision1.id;
		end loop;
		return null;
end;
$$ LANGUAGE 'plpgsql';

	create or replace function insert_file (
		config_channel_id_in in numeric,
		name_in in varchar
	) returns numeric as $$
		declare
		retval numeric;
	begin
		select nextval('rhn_conffile_id_seq')
		into retval;

		insert into rhnConfigFile(id, config_channel_id, config_file_name_id, 
				state_id
			) (
				select retval,
						config_channel_id_in,
						lookup_config_filename(name_in),
						id
				from rhnConfigFileState
				where label = 'alive'
			);

		return retval;
	end;
$$ LANGUAGE 'plpgsql';

	create or replace function delete_file (
		config_file_id_in in numeric
	) returns void as $$
declare
revision record;
			
	begin
		for revision in 
		select cr.id, cc.org_id
			from rhnConfigChannel cc,
					rhnConfigRevision cr,
					rhnConfigFile cf
			where cf.id = config_file_id_in
				and cf.config_channel_id = cc.id
				and cr.config_file_id = cf.id
		
                loop
			perform rhn_config.delete_revision(revision.id, revision.org_id);
		end loop;
		delete from rhnConfigFile where id = config_file_id_in;
	end;
$$ LANGUAGE 'plpgsql';

	create or replace function insert_channel (
		org_id_in in numeric,
		type_in in varchar,
		name_in in varchar,
		label_in in varchar,
		description_in in varchar
	) returns numeric as $$
declare
		retval numeric;
	begin
		select nextval ('rhn_confchan_id_seq')
		into retval;

		insert into rhnConfigChannel(id, org_id, confchan_type_id,
				name, label, description
			) (
				select	retval,
						org_id_in,
						cct.id,
						name_in,
						label_in,
						description_in
				from rhnConfigChannelType cct
				where label = type_in
			);
		return retval;
	end;
$$ LANGUAGE 'plpgsql';

	create or replace function delete_channel (
		config_channel_id_in in numeric
	) returns void as $$
declare
	config_file record;		
	begin
		for config_file in 
		select id
			from rhnConfigFile
			where config_channel_id = config_channel_id_in
                loop
                    perform rhn_config.delete_file(config_file.id);
		end loop;
		delete from rhnConfigChannel where id = config_channel_id_in;

end;
$$ LANGUAGE 'plpgsql';

update pg_settings set setting = overlay( setting placing '' from 1 for (length('rhn_config')+1) ) where name = 'search_path';
   07070100000235000081B400000000000000000000000167AE1114000002DB000000000000000000000000000000000000003400000000susemanager-schema/postgres/packages/rhn_config.pks   -- oracle equivalent source sha1 6644a944afed27bc6adededc3a2132fe1f840178
--
-- Copyright (c) 2008--2015 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--

create schema rhn_config;

 07070100000236000081B400000000000000000000000167AE111400001275000000000000000000000000000000000000003C00000000susemanager-schema/postgres/packages/rhn_config_channel.pkb   -- oracle equivalent source sha1 ba04438c0afe4d458a358ffe3f806a867308168d

-- setup search_path so that these functions are created in appropriate schema.
update pg_settings set setting = 'rhn_config_channel,' || setting where name = 'search_path';  

CREATE OR REPLACE FUNCTION action_diff_revision_status(action_config_revision_id_in numeric)
RETURNS VARCHAR
        -- result_is_null obviously wants NVL2, but stupid 8.1.7.3.0 doesn't
        -- have that.  Or case.  So we're using union, instead.
   AS $$
   DECLARE
   failure_reason  VARCHAR(4000);
   result_is_null  numeric;
   result_exists  numeric;
BEGIN
   select extant,is_null,reason
   into   result_exists,result_is_null,failure_reason
   from(SELECT ACRR.ACTION_CONFIG_REVISION_ID AS EXTANT,1 AS IS_NULL, -- NVL2(ACRR.result, 0, 1),
                       CFF.NAME AS REASON
      FROM RHNACTIONCONFIGREVISION ACR LEFT OUTER JOIN RHNACTIONCONFIGREVISIONRESULT ACRR ON ACR.ID = ACRR.ACTION_CONFIG_REVISION_ID  LEFT OUTER JOIN RHNCONFIGFILEFAILURE CFF ON ACR.FAILURE_ID = CFF.ID 
      WHERE ACR.ID = action_config_revision_id_in AND ACRR.RESULT is null
      union all
      SELECT ACRR.ACTION_CONFIG_REVISION_ID AS EXTANT,0 AS IS_NULL, -- NVL2(ACRR.result, 0, 1),
                       CFF.NAME AS REASON
      FROM RHNACTIONCONFIGREVISION ACR LEFT OUTER JOIN RHNACTIONCONFIGREVISIONRESULT ACRR ON ACR.ID = ACRR.ACTION_CONFIG_REVISION_ID  LEFT OUTER JOIN RHNCONFIGFILEFAILURE CFF ON ACR.FAILURE_ID = CFF.ID 
      WHERE ACR.ID = action_config_revision_id_in AND ACRR.RESULT is not null) AS SWT_TABAL;
   IF failure_reason IS NOT NULL
   THEN
      RETURN failure_reason;
   END IF;

   IF result_exists IS NOT NULL
   THEN
      IF result_is_null = 1
      THEN
         RETURN 'No differences';
      END IF;
      RETURN 'Differences exist';
   END IF;

   RETURN NULL;
END; 
$$ LANGUAGE plpgsql;

CREATE OR REPLACE FUNCTION get_user_chan_access(config_channel_id_in IN NUMERIC, user_id_in IN NUMERIC)
    RETURNS NUMERIC as $$
    Declare
        server_id NUMERIC;
        org_matches NUMERIC;
        global_channel VARCHAR(30);
        any_visible_servers_subscribed NUMERIC;
    BEGIN

          SELECT 1 INTO org_matches
            FROM rhnConfigChannel CC,
                 web_contact WC
           WHERE WC.id = user_id_in
             AND CC.id = config_channel_id_in
             AND WC.org_id = CC.org_id;

          IF NOT FOUND THEN
            RETURN 0;
          END IF;

        global_channel := 'unknown';
        SELECT CCT.label INTO global_channel
          FROM rhnConfigChannel CC,
               rhnConfigChannelType CCT
         WHERE CC.id = config_channel_id_in
           AND CCT.id = CC.confchan_type_id;

        IF (rhn_user.check_role_implied(user_id_in, 'config_admin') = 1) AND (global_channel IN ('normal', 'state'))
        THEN
            RETURN 1;
        END IF;

          SELECT 1 INTO any_visible_servers_subscribed
            FROM DUAL
           WHERE EXISTS (
             SELECT SCC.server_id
               FROM rhnServerConfigChannel SCC,
                    rhnUserServerPermsDupes USPD
              WHERE USPD.user_id = user_id_in
                AND USPD.server_id = SCC.server_id
                AND SCC.config_channel_id = config_channel_id_in
           );

          IF NOT FOUND 
            THEN RETURN 0;
          END IF;

        RETURN any_visible_servers_subscribed;

    END ;
   $$ language 'plpgsql';

CREATE OR REPLACE FUNCTION get_user_revision_access(config_revision_id_in IN NUMERIC, user_id_in IN NUMERIC)
    RETURNS NUMERIC AS $$
    DECLARE
        config_channel_id NUMERIC;
     BEGIN

        SELECT CF.config_channel_id INTO config_channel_id
          FROM rhnConfigFile CF,
               rhnConfigRevision CR
         WHERE CF.id = CR.config_file_id
           AND CR.id = config_revision_id_in;

          if not found then
           RETURN 0;
          end if;

        RETURN rhn_config_channel.get_user_chan_access(config_channel_id, user_id_in);
    END;
    $$ language 'plpgsql';


    CREATE OR REPLACE FUNCTION get_user_file_access(config_file_id_in IN NUMERIC, user_id_in IN NUMERIC)
    RETURNS NUMERIC as $$
    declare
        config_channel_id NUMERIC;
    BEGIN

        SELECT CF.config_channel_id INTO config_channel_id
          FROM rhnConfigFile CF
         WHERE CF.id = config_file_id_in;

        IF NOT FOUND THEN
          RETURN 0;
        END IF;

        RETURN rhn_config_channel.get_user_chan_access(config_channel_id, user_id_in);
    END ;
    $$ language 'plpgsql';


-- restore the original setting
update pg_settings set setting = overlay( setting placing '' from 1 for (length('rhn_config_channel')+1) ) where name = 'search_path';
   07070100000237000081B400000000000000000000000167AE11140000006E000000000000000000000000000000000000003C00000000susemanager-schema/postgres/packages/rhn_config_channel.pks   -- oracle equivalent source sha1 e3f079f5a9086bbabf76c0c247386af71fd4fe8f

create schema rhn_config_channel;

  07070100000238000081B400000000000000000000000167AE1114000032A7000000000000000000000000000000000000003A00000000susemanager-schema/postgres/packages/rhn_entitlements.pkb -- oracle equivalent source sha1 0690aebc316b2ea8195ae4804ec450d5d301057c
--
-- Copyright (c) 2008--2015 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

-- create schema rhn_entitlements;

-- setup search_path so that these functions are created in appropriate schema.
update pg_settings set setting = 'rhn_entitlements,' || setting where name = 'search_path';

   create or replace function find_compatible_sg (
      server_id_in in numeric,
      type_label_in in varchar
   )
   returns numeric
as $$
    declare
      servergroups cursor for
         select sg.id
           from rhnServerGroupType             sgt,
                rhnServerGroup                 sg,
                rhnServer                     s,
                rhnServerServerGroupArchCompat ssgac
          where s.id = server_id_in
            and s.org_id = sg.org_id
            and sgt.label = type_label_in
            and sg.group_type = sgt.id
            and ssgac.server_group_type = sgt.id
            and ssgac.server_arch_id = s.server_arch_id
            and not exists (
                     select 1
                      from rhnServerGroupMembers sgm
                     where sgm.server_group_id = sg.id
                       and sgm.server_id = s.id);


   begin
      for servergroup in servergroups loop
         return servergroup.id;
      end loop;

      --no servergroup found
      return NULL;
   end$$
language plpgsql;


    create or replace function entitlement_grants_service (
        entitlement_in in varchar,
        service_level_in in varchar
    ) returns numeric
as $$
    begin
        if service_level_in = 'management' then
            if entitlement_in = 'enterprise_entitled' or entitlement_in = 'salt_entitled' then
                return 1;
            else
                return 0;
            end if;
        elsif service_level_in = 'updates' then
            return 1;
        else
            return 0;
        end if;
    end$$
language plpgsql;

   create or replace function can_entitle_server (
      server_id_in   in numeric,
      type_label_in  in varchar
   )
   returns numeric
as $$
    declare
      addon_servergroups cursor (base_label_in varchar,
                                 addon_label_in varchar) for
         select
            addon_id
         from
            rhnSGTypeBaseAddonCompat
         where base_id = lookup_sg_type (base_label_in)
           and addon_id = lookup_sg_type (addon_label_in);

      previous_ent        varchar[];
      is_base_in          char   := 'N';
      is_base_current     char   := 'N';
      i                   numeric := 0;
      sgid                numeric := 0;

   begin

      previous_ent := rhn_entitlements.get_server_entitlement(server_id_in);
      RAISE NOTICE 'can_entitle_server - % - % prev ents: %', server_id_in, type_label_in, previous_ent;

      select distinct is_base
      into is_base_in
      from rhnServerGroupType
      where label = type_label_in;

      if array_upper(previous_ent, 1) is null or array_upper(previous_ent, 1) = 0 then
         if is_base_in = 'Y' then
            sgid := rhn_entitlements.find_compatible_sg (server_id_in, type_label_in);
            if sgid is not null then
              -- rhn_server.insert_into_servergroup (server_id_in, sgid);
              return 1;
            else
              -- rhn_exception.raise_exception ('invalid_base_entitlement');
              RAISE NOTICE 'invalid_base_entitlement - no compatible server group';
              return 0;
            end if;
         else
            -- rhn_exception.raise_exception ('invalid_base_entitlement');
            RAISE NOTICE 'invalid_base_entitlement - not a base entitlement';
            return 0;
         end if;

      -- there are previous ents, first make sure we're not trying to entitle a base ent
      elsif is_base_in = 'Y' then
         -- rhn_exception.raise_exception ('invalid_addon_entitlement');
         RAISE NOTICE 'invalid_addon_entitlement - found another base';
         return 0;

      -- it must be an addon, so proceed with the entitlement
      else

         -- find the servers base ent
         is_base_current := 'N';
         i := 0;
         while is_base_current = 'N' and i < array_upper(previous_ent, 1)
         loop
            i := i + 1;
            select is_base
            into is_base_current
            from rhnServerGroupType
            where label = previous_ent[i];
         end loop;

         -- never found a base ent, that would be strange
         if is_base_current  = 'N' then
            -- rhn_exception.raise_exception ('invalid_base_entitlement');
            RAISE NOTICE 'invalid_base_entitlement - never found a base';
            return 0;
         end if;

         -- this for loop verifies the validity of the addon path
         for addon_servergroup in addon_servergroups  (previous_ent[i], type_label_in) loop
            -- find an appropriate sgid for the addon and entitle the server
            sgid := rhn_entitlements.find_compatible_sg (server_id_in, type_label_in);
            if sgid is not null then
               -- rhn_server.insert_into_servergroup (server_id_in, sgid);
               return 1;
            else
               -- rhn_exception.raise_exception ('invalid_addon_entitlement');
               RAISE NOTICE 'invalid_addon_entitlement - no server group found';
               return 0;
            end if;
         end loop;

      end if;
      RAISE NOTICE 'final error';
      return 0;

   end$$
language plpgsql;

   create or replace function can_switch_base (
      server_id_in   in    integer,
      type_label_in  in    varchar
   )
   returns numeric
as $$
   declare
      type_label_in_is_base   char(1);
      sgid                    numeric;

   begin

       select is_base into type_label_in_is_base
       from rhnServerGroupType
       where label = type_label_in;

       if not found then
          perform rhn_exception.raise_exception ( 'invalid_entitlement' );
       end if;

      if type_label_in_is_base = 'N' then
         perform rhn_exception.raise_exception ( 'invalid_entitlement' );
      else
         sgid := rhn_entitlements.find_compatible_sg ( server_id_in,
                                                       type_label_in );
         if sgid is not null then
           return 1;
         else
           return 0;
         end if;
      end if;

   end$$
language plpgsql;

    create or replace function entitle_server (
        server_id_in in numeric,
        type_label_in in varchar
    ) returns void
as $$
    declare
      sgid  numeric := 0;

    begin

      if rhn_entitlements.can_entitle_server(server_id_in,
                                             type_label_in) = 1 then
         sgid := rhn_entitlements.find_compatible_sg (server_id_in,
                                                      type_label_in);
         if sgid is not null then
            insert into rhnServerHistory ( id, server_id, summary, details )
            values ( nextval('rhn_event_id_seq'), server_id_in,
                     'added system entitlement ',
                      case type_label_in
                       when 'enterprise_entitled' then 'Management'
                       when 'bootstrap_entitled' then 'Bootstrap'
                       when 'salt_entitled' then 'Salt'
                       when 'foreign_entitled' then 'Foreign'
                       when 'virtualization_host' then 'Virtualization'
                       when 'container_build_host' then 'Container'
                       when 'osimage_build_host' then 'OS Image'
                       when 'monitoring_entitled' then 'Monitoring'
                       when 'ansible_control_node' then 'Ansible'
                      end  );

            perform rhn_server.insert_into_servergroup (server_id_in, sgid);

         else
            perform rhn_exception.raise_exception ('no_available_server_group');
         end if;
      else
         perform rhn_exception.raise_exception ('invalid_entitlement');
      end if;
   end$$
language plpgsql;

    create or replace function remove_server_entitlement (
        server_id_in in numeric,
        type_label_in in varchar
    ) returns void
as $$
    declare
      group_id numeric;
      type_is_base char;
    begin

        select  sg.id, sgt.is_base
        into group_id, type_is_base
        from    rhnServerGroupType sgt,
            rhnServerGroup sg,
                rhnServerGroupMembers sgm,
                rhnServer s
        where   s.id = server_id_in
            and s.id = sgm.server_id
            and sgm.server_group_id = sg.id
            and sg.org_id = s.org_id
            and sgt.label = type_label_in
            and sgt.id = sg.group_type;

        if not found then
          perform rhn_exception.raise_exception('invalid_server_group_member');
        end if;

      if ( type_is_base = 'Y' ) then
         -- unentitle_server should handle everything, don't really need to do anything else special here
         perform rhn_entitlements.unentitle_server ( server_id_in );
      else

         insert into rhnServerHistory ( id, server_id, summary, details )
         values ( nextval('rhn_event_id_seq'), server_id_in,
                  'removed system entitlement ',
                   case type_label_in
                    when 'enterprise_entitled' then 'Management'
                    when 'bootstrap_entitled' then 'Bootstrap'
                    when 'salt_entitled' then 'Salt'
                    when 'foreign_entitled' then 'Foreign'
                    when 'virtualization_host' then 'Virtualization'
                    when 'container_build_host' then 'Container'
                    when 'osimage_build_host' then 'OS Image'
                    when 'ansible_control_node' then 'Ansible'
                   end  );

         perform rhn_server.delete_from_servergroup(server_id_in, group_id);

      end if;

    end$$
language plpgsql;

    create or replace function unentitle_server (
        server_id_in in numeric
    ) returns void
as $$
    declare
      servergroups cursor for
         select distinct sgt.label, sg.id server_group_id
         from  rhnServerGroupType sgt,
               rhnServerGroup sg,
               rhnServer s,
               rhnServerGroupMembers sgm
         where s.id = server_id_in
            and s.org_id = sg.org_id
            and sg.group_type = sgt.id
            and sgm.server_group_id = sg.id
            and sgm.server_id = s.id;

   begin

      for servergroup in servergroups loop

         insert into rhnServerHistory ( id, server_id, summary, details )
         values ( nextval('rhn_event_id_seq'), server_id_in,
                  'removed system entitlement ',
                   case servergroup.label
                    when 'enterprise_entitled' then 'Management'
                    when 'bootstrap_entitled' then 'Bootstrap'
                    when 'salt_entitled' then 'Salt'
                    when 'foreign_entitled' then 'Foreign'
                    when 'virtualization_host' then 'Virtualization'
                    when 'container_build_host' then 'Container'
                    when 'osimage_build_host' then 'OS Image'
                    when 'ansible_control_node' then 'Ansible'
                   end  );

         perform rhn_server.delete_from_servergroup(server_id_in,
                                            servergroup.server_group_id );
      end loop;

   end$$
language plpgsql;


    create or replace function get_server_entitlement (
        server_id_in in numeric
    ) returns varchar[]
as $$
    declare
        server_groups cursor for
            select  sgt.label
            from    rhnServerGroupType      sgt,
                    rhnServerGroup          sg,
                    rhnServerGroupMembers   sgm
            where   1=1
                and sgm.server_id = server_id_in
                and sg.id = sgm.server_group_id
                and sgt.id = sg.group_type;

         ent_array varchar[];

    begin

      ent_array := '{}';

      for sg in server_groups loop
         ent_array := ent_array || sg.label;
      end loop;

      return ent_array;

    end$$
language plpgsql;

-- restore the original setting
update pg_settings set setting = overlay( setting placing '' from 1 for (length('rhn_entitlements')+1) ) where name = 'search_path';
 07070100000239000081B400000000000000000000000167AE1114000002DF000000000000000000000000000000000000003A00000000susemanager-schema/postgres/packages/rhn_entitlements.pks -- oracle equivalent source sha1 0beb45dbb379c8fa5eb11f5c3ea974feebc37de3
--
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

create schema rhn_entitlements;

 0707010000023A000081B400000000000000000000000167AE1114000009B2000000000000000000000000000000000000003700000000susemanager-schema/postgres/packages/rhn_exception.pkb    -- oracle equivalent source sha1 de1cc9f13819c6084b4d7ac8f769631b7ddd90d2
--
-- Copyright (c) 2008--2010 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

-- create schema rhn_exception;

-- setup search_path so that these functions are created in appropriate schema.
update pg_settings set setting = 'rhn_exception,' || setting where name = 'search_path';

    CREATE OR REPLACE FUNCTION lookup_exception(exception_label_in IN VARCHAR, exception_id_out OUT NUMERIC, exception_message_out OUT VARCHAR)
    AS
    $$
    DECLARE
         exc RECORD;
    BEGIN

        SELECT id, label, message INTO exc
          FROM rhnException
         WHERE label = exception_label_in;

        IF NOT FOUND
        THEN
            RAISE EXCEPTION 'Unable to lookup exception with label (%)',
                  exception_label_in;
        END IF;

        exception_id_out := exc.id;
        exception_message_out := '(' || exc.label || ') - ' || exc.message;
    END;
$$
LANGUAGE PLPGSQL;


    CREATE OR REPLACE FUNCTION raise_exception(exception_label_in IN VARCHAR) RETURNS VOID
    AS
    $$
    DECLARE
	exc_rec	RECORD;
    BEGIN
        exc_rec := rhn_exception.lookup_exception(exception_label_in);
        
        RAISE EXCEPTION '% : %',
          exc_rec.exception_id_out,
          exc_rec.exception_message_out;
    END;
    $$
    LANGUAGE PLPGSQL;

    create or replace function raise_exception_val(exception_label_in in varchar, val_in in numeric) returns void
    as
    $$
    DECLARE
	exc_rec	RECORD;
    BEGIN
        exc_rec := rhn_exception.lookup_exception(exception_label_in);
        
        RAISE EXCEPTION '% : % (%)',
          exc_rec.exception_id_out,
          exc_rec.exception_message_out,
          val_in;
    end;
    $$
    language plpgsql;


-- restore the original setting
update pg_settings set setting = overlay( setting placing '' from 1 for (length('rhn_exception')+1) ) where name = 'search_path';
  0707010000023B000081B400000000000000000000000167AE1114000002DC000000000000000000000000000000000000003700000000susemanager-schema/postgres/packages/rhn_exception.pks    -- oracle equivalent source sha1 a6840b2a9d77d1a0e0a2d92794d5cecb7de9563a
--
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

create schema rhn_exception;

0707010000023C000081B400000000000000000000000167AE111400001C7B000000000000000000000000000000000000003100000000susemanager-schema/postgres/packages/rhn_org.pkb  -- oracle equivalent source sha1 18b26199f630d46ba7ce6fc32763078538aee3cb
--
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--

-- create schema rhn_org;

-- setup search_path so that these functions are created in appropriate schema.
update pg_settings set setting = 'rhn_org,' || setting where name = 'search_path';


create or replace function delete_org (
        org_id_in in numeric
    ) returns void
    as
    $$
    declare
        users cursor for
        select id
        from web_contact
        where org_id = org_id_in;

        servers cursor (org_id_in numeric) for
        select  id
        from    rhnServer
        where   org_id = org_id_in;

        config_channels cursor for
        select id
        from rhnConfigChannel
        where org_id = org_id_in;

        custom_channels cursor for
        select  id
        from    rhnChannel
        where   org_id = org_id_in;

        errata cursor for
        select  id
        from    rhnErrata
        where   org_id = org_id_in;

    begin

        if org_id_in = 1 then
            perform rhn_exception.raise_exception('cannot_delete_base_org');
        end if;

        -- Delete all users.
        for u in users loop
            perform rhn_org.delete_user(u.id, 1);
        end loop;

        -- Delete all servers.
        for s in servers(org_id_in) loop
            perform delete_server(s.id);
        end loop;

        -- Delete all config channels.
        for c in config_channels loop
            perform rhn_config.delete_channel(c.id);
        end loop;

        -- Delete all custom channels.
        for cc in custom_channels loop
          delete from rhnServerChannel where channel_id = cc.id;
          delete from rhnServerProfilePackage where server_profile_id in (
            select id from rhnServerProfile where base_channel = cc.id
          );
          delete from rhnServerProfile where base_channel = cc.id;
        end loop;

        -- Delete all errata packages 
        for e in errata loop
            delete from rhnErrataPackage where errata_id = e.id;
        end loop;

        -- Clean up tables where we don't have a cascading delete.
        delete from rhnChannel where org_id = org_id_in;
        delete from rhnDailySummaryQueue where org_id = org_id_in;
        delete from rhnFileList where org_id = org_id_in;
        delete from rhnServerGroup where org_id = org_id_in;
        delete from rhnContentSource where org_id = org_id_in;

        -- Delete the org.
        delete from web_customer where id = org_id_in;

    end;
    $$
    language plpgsql;

create or replace function delete_user(user_id_in in numeric, deleting_org in numeric default 0) returns void 
    as
    $$
    declare
    servergroups_needing_admins cursor for
            select    usgp.server_group_id    server_group_id
            from    rhnUserServerGroupPerms    usgp
            where    1=1
                and usgp.user_id = user_id_in
                and not exists (
                    select    1
                    from    rhnUserServerGroupPerms    sq_usgp
                    where    1=1
                        and sq_usgp.server_group_id = usgp.server_group_id
                        and    sq_usgp.user_id != user_id_in
                );
        users            numeric;
        our_org_id        numeric;
        other_users        numeric;
        other_org_admin    numeric;
        other_user_id  numeric;
        is_admin       numeric;
    begin
        select    wc.org_id
        into    our_org_id
        from    web_contact wc
        where    id = user_id_in;

        -- find any other users
        begin
            select    id, 1
            into    other_user_id, other_users
            from    web_contact
            where    1=1
                and org_id = our_org_id
                and id != user_id_in
                limit 1;
        exception
            when no_data_found then
                other_users := 0;
        end;

        -- now do org admin stuff
        if other_users != 0 then
            -- is user admin?
            select  count(1)
             into   is_admin
            from    rhnUserGroupType    ugt,
                    rhnUserGroup        ug,
                    rhnUserGroupMembers    ugm
            where    ugm.user_id = user_id_in
                and ugm.user_group_id = ug.id
                and ug.group_type = ugt.id
                and ugt.label = 'org_admin';
            if is_admin > 0 then
                begin
                    select    new_ugm.user_id
                    into    other_org_admin
                    from    rhnUserGroupMembers    new_ugm,
                            rhnUserGroupType    ugt,
                            rhnUserGroup        ug,
                            rhnUserGroupMembers    ugm
                    where    ugm.user_id = user_id_in
                        and ugm.user_group_id = ug.id
                        and ug.group_type = ugt.id
                        and ugt.label = 'org_admin'
                        and ug.id = new_ugm.user_group_id
                        and new_ugm.user_id != user_id_in
                        limit 1;
                exception
                    when no_data_found then
                        -- If we're deleting the org, we don't want to raise
                        -- the exception.
                        if deleting_org = 0 then
                           perform rhn_exception.raise_exception('cannot_delete_user');
                        end if;
                end;

                for sg in servergroups_needing_admins loop
                   perform rhn_user.add_servergroup_perm(other_org_admin,
                        sg.server_group_id);
                end loop;
            end if;
        end if;

        -- and now things for every user
        delete from rhnUserServerPerms where user_id = user_id_in;
        update rhnConfigRevision
           set changed_by_id = NULL
         where changed_by_id = user_id_in;
        if other_users != 0 then
            update        rhnRegToken
                set        user_id = coalesce(other_org_admin, other_user_id)
                where    org_id = our_org_id
                    and user_id = user_id_in;
        end if;

        begin
            delete from web_contact where id = user_id_in;
        exception
            when others then
               perform rhn_exception.raise_exception('cannot_delete_user');
        end;
        return;

        end;
        $$
        language plpgsql;


-- restore the original setting
update pg_settings set setting = overlay( setting placing '' from 1 for (length('rhn_org')+1) ) where name = 'search_path';
 0707010000023D000081B400000000000000000000000167AE1114000002D8000000000000000000000000000000000000003100000000susemanager-schema/postgres/packages/rhn_org.pks  -- oracle equivalent source sha1 f19b747e0d9e2f2db3745679cdb0397e2be64650
--
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--

create schema rhn_org;

0707010000023E000081B400000000000000000000000167AE111400005042000000000000000000000000000000000000003400000000susemanager-schema/postgres/packages/rhn_server.pkb   -- oracle equivalent source sha1 87bc50785a1b2a5e639cdc7371aa5c1b435adaa2
--
-- Copyright (c) 2008--2014 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--
--
--
--

-- create schema rhn_server;

--update pg_setting
update pg_settings set setting = 'rhn_server,' || setting where name = 'search_path';

    create or replace function system_service_level(
    	server_id_in in numeric,
	service_level_in in varchar
    ) returns numeric as $$
    declare
    ents cursor is
      select label from rhnServerEntitlementView
      where server_id = server_id_in;

    retval numeric := 0;

    begin
         for ent in ents loop
            retval := rhn_entitlements.entitlement_grants_service (ent.label, service_level_in);
            if retval = 1 then
               return retval;
            end if;
         end loop;

         return retval;

    end$$ language plpgsql;


    create or replace function can_change_base_channel(server_id_in IN NUMERIC)
    returns numeric
    as $$
    declare
    	throwaway numeric;
    begin
    	-- the idea: if we get past this query, the server is
	-- neither sat nor proxy, so base channel is changeable

	select 1 into throwaway
	  from rhnServer S
	 where S.id = server_id_in
	   and not exists (select 1 from suseMgrServerInfo SI where SI.server_id = S.id)
	   and not exists (select 1 from rhnProxyInfo PI where PI.server_id = S.id);

        if not found then
	    return 0;
        end if;

	return 1;
    end$$ language plpgsql;

    create or replace function set_custom_value(
    	server_id_in in numeric,
	user_id_in in numeric,
	key_label_in in varchar,
	value_in in varchar
    ) returns void
    as $$
    declare
    	key_id_val numeric;
    begin
    	select CDK.id into strict key_id_val
	  from rhnCustomDataKey CDK,
	       rhnServer S
	 where S.id = server_id_in
	   and S.org_id = CDK.org_id
	   and CDK.label = key_label_in;

	begin
	    insert into rhnServerCustomDataValue (server_id, key_id, value, created_by, last_modified_by)
	    values (server_id_in, key_id_val, value_in, user_id_in, user_id_in);
	exception
	    when UNIQUE_VIOLATION
	    	then
		update rhnServerCustomDataValue
		   set value = value_in,
		       last_modified_by = user_id_in
		 where server_id = server_id_in
		   and key_id = key_id_val;
	end;

    end$$ language plpgsql;

    create or replace function bulk_set_custom_value(
    	key_label_in in varchar,
	value_in in varchar,
	set_label_in in varchar,
	set_uid_in in numeric
    )
    returns integer
    as $$
    declare
        i integer;
        server record;
    begin
        i := 0;
        for server in (
           SELECT user_id, label, element, element_two
	     FROM rhnSet
	    WHERE label = set_label_in
	      AND user_id = set_uid_in
	) loop
	    if rhn_server.system_service_level(server.element, 'management') = 1 then
	    	perform rhn_server.set_custom_value(server.element, set_uid_in, key_label_in, value_in);
            i := i + 1;
	    end if;
	end loop;
    return i;
    end$$ language plpgsql;

    create or replace function bulk_snapshot_tag(
    	org_id_in in numeric,
        tagname_in in varchar,
	set_label_in in varchar,
	set_uid_in in numeric
    ) returns void
    as $$
    declare
        server record;
    	snapshot_id numeric;
    begin
        for server in (
           SELECT user_id, label, element, element_two
	     FROM rhnSet
	    WHERE label = set_label_in
	      AND user_id = set_uid_in
	    ) loop
	    if rhn_server.system_service_level(server.element, 'management') = 1 then
	    	    select max(id) into snapshot_id
	    	    from rhnSnapshot
	    	    where server_id = server.element;

	    	    if snapshot_id is null then
		    	perform rhn_server.snapshot_server(server.element, 'tagging system:  ' || tagname_in);

			select max(id) into snapshot_id
			from rhnSnapshot
			where server_id = server.element;
		    end if;

		-- now have a snapshot_id to work with...
		begin
		    perform rhn_server.tag_snapshot(snapshot_id, org_id_in, tagname_in);
		exception
		    when UNIQUE_VIOLATION
		    	then
			-- do nothing, be forgiving...
			null;
		end;
	    end if;
	end loop;
    end$$ language plpgsql;

    create or replace function tag_delete(
    	server_id_in in numeric,
	tag_id_in in numeric
    ) returns void
    as $$
    declare
    	snapshots cursor is
		select	snapshot_id
		from	rhnSnapshotTag
		where	tag_id = tag_id_in;
	tag_id_tmp numeric;
    begin
    	select	id into tag_id_tmp
	from	rhnTag
	where	id = tag_id_in
	for update;

	delete
		from	rhnSnapshotTag
		where	server_id = server_id_in
			and tag_id = tag_id_in;
	for snapshot in snapshots loop
		return;
	end loop;
	delete
		from rhnTag
		where id = tag_id_in;
    end$$ language plpgsql;

    create or replace function tag_snapshot(
        snapshot_id_in in numeric,
	org_id_in in numeric,
	tagname_in in varchar
    ) returns void
    as $$
    begin
    	insert into rhnSnapshotTag (snapshot_id, server_id, tag_id)
	select snapshot_id_in, server_id, lookup_tag(org_id_in, tagname_in)
	from rhnSnapshot
	where id = snapshot_id_in;
    end$$ language plpgsql;

    create or replace function bulk_snapshot(
    	reason_in in varchar,
	set_label_in in varchar,
	set_uid_in in numeric
    ) returns void
    as $$
    declare
        server record;
    begin
        for server in (
           SELECT user_id, label, element, element_two
	     FROM rhnSet
	    WHERE label = set_label_in
	      AND user_id = set_uid_in
	    ) loop
	    if rhn_server.system_service_level(server.element, 'management') = 1 then
	    	perform rhn_server.snapshot_server(server.element, reason_in);
	    end if;
	end loop;
    end$$ language plpgsql;

    create or replace function snapshot_server(
    	server_id_in in numeric,
	reason_in in varchar
    ) returns void
    as $$
    declare
    	snapshot_id_v numeric;
	revisions cursor is
		select distinct
			cr.id
		from	rhnConfigRevision	cr,
			rhnConfigFileName	cfn,
			rhnConfigFile		cf,
			rhnConfigChannel	cc,
			rhnServerConfigChannel	scc
		where	1=1
			and scc.server_id = server_id_in
			and scc.config_channel_id = cc.id
			and cc.id = cf.config_channel_id
			and cf.id = cr.config_file_id
			and cr.id = cf.latest_config_revision_id
			and cf.config_file_name_id = cfn.id
			and cf.id = lookup_first_matching_cf(scc.server_id, cfn.path);
	locked integer;
    begin
    	select nextval('rhn_snapshot_id_seq') into snapshot_id_v;

	insert into rhnSnapshot (id, org_id, server_id, reason) (
		select	snapshot_id_v,
			s.org_id,
			server_id_in,
			reason_in
		from	rhnServer s
		where	s.id = server_id_in
	);
	insert into rhnSnapshotChannel (snapshot_id, channel_id) (
		select	snapshot_id_v, sc.channel_id
		from	rhnServerChannel sc
		where	sc.server_id = server_id_in
	);
	insert into rhnSnapshotServerGroup (snapshot_id, server_group_id) (
		select	snapshot_id_v, sgm.server_group_id
		from	rhnServerGroupMembers sgm
		where	sgm.server_id = server_id_in
	);
        locked := 0;
        <<iloop>>
        while true loop
            begin
                insert into rhnPackageNEVRA (id, name_id, evr_id, package_arch_id)
                select nextval('rhn_pkgnevra_id_seq'), sp.name_id, sp.evr_id, sp.package_arch_id
                from rhnServerPackage sp
                where sp.server_id = server_id_in
                        and not exists
                        (select 1
                                from rhnPackageNEVRA nevra
                                where nevra.name_id = sp.name_id
                                        and nevra.evr_id = sp.evr_id
                                        and (nevra.package_arch_id = sp.package_arch_id
                                            or (nevra.package_arch_id is null
                                                and sp.package_arch_id is null)));
                exit iloop;
            exception when unique_violation then
                if locked = 1 then
                    raise;
                else
                    lock table rhnPackageNEVRA in exclusive mode;
                    locked := 1;
                end if;
            end;
        end loop;
	insert into rhnSnapshotPackage (snapshot_id, nevra_id) (
                select distinct snapshot_id_v, nevra.id
                from    rhnServerPackage sp, rhnPackageNEVRA nevra
                where   sp.server_id = server_id_in
                        and nevra.name_id = sp.name_id
                        and nevra.evr_id = sp.evr_id
                        and (nevra.package_arch_id = sp.package_arch_id
                            or (nevra.package_arch_id is null
                                and sp.package_arch_id is null))
	);

	insert into rhnSnapshotConfigChannel ( snapshot_id, config_channel_id ) (
		select	snapshot_id_v, scc.config_channel_id
		from	rhnServerConfigChannel scc
		where	server_id = server_id_in
	);

	for revision in revisions loop
		insert into rhnSnapshotConfigRevision (
				snapshot_id, config_revision_id
			) values (
				snapshot_id_v, revision.id
			);
	end loop;
    end$$ language plpgsql;

    create or replace function remove_action(
    	server_id_in in numeric,
	action_id_in in numeric
    ) returns void
    as $$
    declare
    	-- this really wants "nulls last", but 8.1.7.3.0 sucks ass.
	-- instead, we make a local table that holds our
	-- list of ids with null prereqs.  There's surely a better way
	-- (an array instead of a table maybe?  who knows...)
	-- but I've got code to do this handy that I can look at ;)
    	chained_actions cursor is
                with recursive r(id, prerequisite) as (
			select	id, prerequisite
			from	rhnAction
			where id = action_id_in
		union all
			select	r1.id, r1.prerequisite
			from	rhnAction r1, r
			where r.id = r1.prerequisite
		)
		select * from r
		order by prerequisite desc;
	sessions cursor is
		select	s.id
		from	rhnKickstartSession s
		where	server_id_in in (s.old_server_id, s.new_server_id)
			and s.action_id = action_id_in
			and not exists (
				select	1
				from	rhnKickstartSessionState ss
				where	ss.id = s.state_id
					and ss.label in ('failed','complete')
			);
	chain_ends numeric[];
	i numeric;
	prereq numeric := 1;
    begin
	select	prerequisite
	into	prereq
	from	rhnAction
	where	id = action_id_in;

	if prereq is not null then
		perform rhn_exception.raise_exception('action_is_child');
	end if;

        chain_ends := '{}';
	i := 1;
	for action in chained_actions loop
		if action.prerequisite is null then
			chain_ends[i] := action.id;
			i := i + 1;
		else
			delete from rhnServerAction
				where server_id = server_id_in
				and action_id = action.id;
		end if;
	end loop;

	delete from rhnServerAction
		where server_id = server_id_in
		and action_id = any(chain_ends);

	for s in sessions loop
		update rhnKickstartSession
			set 	state_id = (
					select	id
					from	rhnKickstartSessionState
					where	label = 'failed'
				),
				action_id = null
			where	id = s.id;
		perform set_ks_session_history_message(s.id, 'failed', 'Kickstart cancelled due to action removal');
	end loop;
    end$$ language plpgsql;

    create or replace function check_user_access(server_id_in in numeric, user_id_in in numeric)
    returns numeric
    as $$
    declare
    	has_access numeric;
    begin
    	-- first check; if this returns no rows, then the server/user are in different orgs, and we bail
        select 1 into has_access
	  from rhnServer S,
	       web_contact wc
	 where wc.org_id = s.org_id
	   and s.id = server_id_in
	   and wc.id = user_id_in;

        if not found then
          return 0;
        end if;

	-- okay, so they're in the same org.  if we have an org admin, they get a free pass
    	if rhn_user.check_role(user_id_in, 'org_admin') = 1
	then
	    return 1;
	end if;

    	select 1 into has_access
	  from rhnServerGroupMembers SGM,
	       rhnUserServerGroupPerms USG
	 where SGM.server_group_id = USG.server_group_id
	   and SGM.server_id = server_id_in
	   and USG.user_id = user_id_in;

        if not found then
          return 0;
        end if;

	return 1;
    end$$ language plpgsql;

    create or replace function insert_into_servergroup (
		server_id_in in numeric,
		server_group_id_in in numeric
    ) returns void
    as $$
    declare
		group_type numeric;
	begin
		-- this will rowlock the servergroup we're trying to change;
		-- we probably need to lock the other one, but I think the chances
		-- of it being a real issue are very small for now...
		select	sg.group_type
		into	group_type
		from	rhnServerGroup sg
		where	sg.id = server_group_id_in
		for update of sg;

		insert into rhnServerGroupMembers(server_id, server_group_id)
		values (server_id_in, server_group_id_in);

		update rhnServerGroup
		set current_members = current_members + 1
		where id = server_group_id_in;

		if group_type is null then
			perform rhn_cache.update_perms_for_server_group(server_group_id_in);
		end if;

		return;
	end$$ language plpgsql;

	create or replace function insert_into_servergroup_maybe (
		server_id_in in numeric,
		server_group_id_in in numeric
	) returns numeric as $$
    declare
		retval numeric := 0;
		servergroups cursor is
			select	s.id	server_id,
					sg.id	server_group_id
			from	rhnServerGroup	sg,
					rhnServer		s
			where	s.id = server_id_in
				and sg.id = server_group_id_in
				and s.org_id = sg.org_id
				and not exists (
					select	1
					from	rhnServerGroupMembers sgm
					where	sgm.server_id = s.id
						and sgm.server_group_id = sg.id
				);
	begin
		for sgm in servergroups loop
			perform rhn_server.insert_into_servergroup(sgm.server_id, sgm.server_group_id);
			retval := retval + 1;
		end loop;
		return retval;
	end$$ language plpgsql;

	create or replace function insert_set_into_servergroup (
		server_group_id_in in numeric,
		user_id_in in numeric,
		set_label_in in varchar
	) returns void
        as $$
    declare
		servers cursor is
			select	st.element	id
			from	rhnSet		st
			where	st.user_id = user_id_in
				and st.label = set_label_in
				and exists (
					select	1
					from	rhnUserManagedServerGroups umsg
					where	umsg.server_group_id = server_group_id_in
						and umsg.user_id = user_id_in
					)
				and not exists (
					select	1
					from	rhnServerGroupMembers sgm
					where	sgm.server_id = st.element
						and sgm.server_group_id = server_group_id_in
				);
	begin
		for s in servers loop
			perform rhn_server.insert_into_servergroup(s.id, server_group_id_in);
		end loop;
	end$$ language plpgsql;

    create or replace function delete_from_servergroup (
    	server_id_in in numeric,
	server_group_id_in in numeric
    ) returns void
    as $$
    declare

		oid numeric;
		label varchar;
		group_type numeric;
	begin
		select	sg.group_type, sg.org_id
		into	group_type,	oid
		from	rhnServerGroupMembers	sgm,
			rhnServerGroup		sg
		where	sg.id = server_group_id_in
		and 	sg.id = sgm.server_group_id
		and 	sgm.server_id = server_id_in
		for update of sg;

		if not found then
			perform rhn_exception.raise_exception('server_not_in_group');
		end if;

		delete from rhnServerGroupMembers
		where server_group_id = server_group_id_in
		and	server_id = server_id_in;

		update rhnServerGroup
		set current_members = current_members - 1
		where id = server_group_id_in;

		-- do group_type is null first
		if group_type is null then
			perform rhn_cache.update_perms_for_server_group(server_group_id_in);
		end if;

	end$$ language plpgsql;

	create or replace function delete_set_from_servergroup (
		server_group_id_in in numeric,
		user_id_in in numeric,
		set_label_in in varchar
	) returns void
        as $$
        declare
		servergroups cursor is
			select	sgm.server_id, sgm.server_group_id
			from	rhnSet st,
					rhnServerGroupMembers sgm
			where	sgm.server_group_id = server_group_id_in
				and st.user_id = user_id_in
				and st.label = set_label_in
				and sgm.server_id = st.element
				and exists (
					select	1
					from	rhnUserManagedServerGroups usgp
					where	usgp.server_group_id = server_group_id_in
						and usgp.user_id = user_id_in
				);
	begin
		for sgm in servergroups loop
			perform rhn_server.delete_from_servergroup(sgm.server_id, server_group_id_in);
		end loop;
	end$$ language plpgsql;

	create or replace function clear_servergroup (
		server_group_id_in in numeric
	) returns void
        as $$
        declare
		servers cursor is
			select	sgm.server_id	id
			from	rhnServerGroupMembers sgm
			where	sgm.server_group_id = server_group_id_in;
	begin
		for s in servers loop
			perform rhn_server.delete_from_servergroup(s.id, server_group_id_in);
		end loop;
	end$$ language plpgsql;

	create or replace function delete_from_org_servergroups (
		server_id_in in numeric
	) returns void
        as $$
        declare
		servergroups cursor is
			select	sgm.server_group_id id
			from	rhnServerGroup sg,
					rhnServerGroupMembers sgm
			where	sgm.server_id = server_id_in
				and sgm.server_group_id = sg.id
				and sg.group_type is null;
	begin
		for sg in servergroups loop
			perform rhn_server.delete_from_servergroup(server_id_in, sg.id);
		end loop;
	end$$ language plpgsql;

	create or replace function get_ip_address (
		server_id_in in numeric
	) returns varchar as $$
        declare
		interfaces cursor is
			select	ni.name as name, na4.address as address
			from	rhnServerNetInterface ni,
			        rhnServerNetAddress4 na4
			where	server_id = server_id_in
		                and ni.id = na4.interface_id
				and na4.address != '127.0.0.1';
		addresses cursor is
			select	address ip_addr
			from	rhnServerNetInterface
      			left join rhnServerNetAddress4
      			on rhnServerNetInterface.id = rhnServerNetAddress4.interface_id
			where	server_id = server_id_in
				and address != '127.0.0.1'
				and is_primary = 'Y';
	begin
		for addr in addresses loop
			return addr.ip_addr;
		end loop;
		for iface in interfaces loop
			return iface.address;
		end loop;
		return NULL;
	end$$ language plpgsql;

    create or replace function update_needed_cache(
        server_id_in in numeric
	) returns void as $$
    begin
      delete from rhnServerNeededCache
        where server_id = server_id_in;
      insert into rhnServerNeededCache
             (server_id, errata_id, package_id, channel_id)
        (select distinct sp.server_id, x.errata_id, p.id, x.channel_id
           FROM (SELECT sp_sp.server_id, sp_sp.name_id,
		        sp_sp.package_arch_id, max(sp_pe.evr) AS max_evr
                   FROM rhnServerPackage sp_sp
                   join rhnPackageEvr sp_pe ON sp_pe.id = sp_sp.evr_id
                  GROUP BY sp_sp.server_id, sp_sp.name_id, sp_sp.package_arch_id) sp
           join susePackageExcludingPartOfPtf p ON p.name_id = sp.name_id
           join rhnPackageEvr pe ON pe.id = p.evr_id AND (sp.max_evr).type = (pe.evr).type AND sp.max_evr < pe.evr
           join rhnPackageUpgradeArchCompat puac
	            ON puac.package_arch_id = sp.package_arch_id
		    AND puac.package_upgrade_arch_id = p.package_arch_id
           join rhnServerChannel sc ON sc.server_id = sp.server_id
           join rhnChannelPackage cp ON cp.package_id = p.id
	            AND cp.channel_id = sc.channel_id
           left join (SELECT ep.errata_id, ce.channel_id, ep.package_id
                        FROM rhnChannelErrata ce
                        join rhnErrataPackage ep
			         ON ep.errata_id = ce.errata_id
			join rhnServerChannel sc_sc
			         ON sc_sc.channel_id = ce.channel_id
		       WHERE sc_sc.server_id = server_id_in) x
             ON x.channel_id = sc.channel_id AND x.package_id = cp.package_id
	   left join rhnErrata e on x.errata_id = e.id
          where sp.server_id = server_id_in
            and (x.errata_id IS NULL or e.advisory_status != 'retracted')); -- packages which are part of a retracted errata should not be installed
	end$$ language plpgsql;
-- restore the original setting
update pg_settings set setting = overlay( setting placing '' from 1 for (length('rhn_server')+1) ) where name = 'search_path';
  0707010000023F000081B400000000000000000000000167AE111400000066000000000000000000000000000000000000003400000000susemanager-schema/postgres/packages/rhn_server.pks   -- oracle equivalent source sha1 71ba832ba3762b06fab61ce6ae1035ca0e6fef54

create schema rhn_server;

  07070100000240000081B400000000000000000000000167AE1114000014F3000000000000000000000000000000000000003200000000susemanager-schema/postgres/packages/rhn_user.pkb -- oracle equivalent source sha1 98b987747d62806810341a5c56981bf16069c68e
--
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--

-- create schema rhn_user;

-- setup search_path so that these functions are created in appropriate schema.
update pg_settings set setting = 'rhn_user,' || setting where name = 'search_path';

create or replace function
check_role(user_id_in in numeric, role_in in varchar)
    returns numeric as $$
    declare
    	throwaway numeric;
    begin
    	-- the idea: if we get past this query, the org has the setting, else catch the exception and return 0
	select 1 into throwaway
	  from rhnUserGroupType UGT,
	       rhnUserGroup UG,
	       rhnUserGroupMembers UGM
	 where UGM.user_id = user_id_in
	   and UGM.user_group_id = UG.id
	   and UG.group_type = UGT.id
	   and UGT.label = role_in;

        if not found then
            return 0;
        end if;

	return 1;
    end;
$$ language plpgsql;

create or replace
    function check_role_implied(user_id_in in numeric, role_in in varchar)
    returns numeric as $$
    declare
    	throwaway numeric;
    begin
    	-- if the user directly has the role, they win
    	if rhn_user.check_role(user_id_in, role_in) = 1
	then
	    return 1;
    	end if;

	-- config_admin and channel_admin are automatically implied for org admins	
	if role_in = 'config_admin' and rhn_user.check_role(user_id_in, 'org_admin') = 1
	then
	    return 1;
	end if;

	if role_in = 'channel_admin' and rhn_user.check_role(user_id_in, 'org_admin') = 1
	then
	    return 1;
	end if;

	if role_in = 'image_admin' and rhn_user.check_role(user_id_in, 'org_admin') = 1
	then
	    return 1;
	end if;

	return 0;
    end;
$$ language plpgsql;

create or replace
    function get_org_id(user_id_in in numeric)
    returns numeric as $$
    declare
    	org_id_out numeric;
    begin
    	select org_id into org_id_out
	  from web_contact
	 where id = user_id_in;
	 
	return org_id_out;
    end;
$$ language plpgsql;

create or replace
	function add_servergroup_perm(
		user_id_in in numeric,
		server_group_id_in in numeric
	) returns void as $$
        declare
            okay record;
	begin
		for okay in
			select	1
			from	rhnServerGroup sg,
					web_contact u
			where	u.id = user_id_in
				and sg.id = server_group_id_in
				and sg.org_id = u.org_id
                loop
		insert into rhnUserServerGroupPerms(user_id, server_group_id)
				values (user_id_in, server_group_id_in);
			perform rhn_cache.update_perms_for_user(user_id_in);
			return;
		end loop;
		perform rhn_exception.raise_exception('usgp_different_orgs');
	exception when UNIQUE_VIOLATION then
		perform rhn_exception.raise_exception('usgp_already_allowed');
	end;
$$ language plpgsql;

create or replace
	function add_to_usergroup(
		user_id_in in numeric,
		user_group_id_in in numeric
	) returns void as $$
        declare
            ugr record;
	begin
		insert into rhnUserGroupMembers(user_id, user_group_id)
			values (user_id_in, user_group_id_in);

		for ugr in
			select	user_group_id_in
			from	rhnUserGroup		ug,
					rhnUserGroupType	ugt
			where	ugt.label in ('org_admin') -- and server_group_admin ?
				and ugr.id = user_group_id_in
				and ugr.group_type = ugt.id
                 loop
			perform rhn_cache.update_perms_for_user(user_id_in);
			return;
		end loop;
	end;
$$ language plpgsql;

create or replace
	function remove_from_usergroup(
		user_id_in in numeric,
		user_group_id_in in numeric
	) returns void as $$
        declare
            ugr record;
	begin
		-- we only do anything if you're really in the group, because
		-- testing is significantly cheaper than rebuilding the user's
		-- cache for no reason.
		for ugr in
			select	label
			from	rhnUserGroupType	ugt,
					rhnUserGroupMembers	ugm,
					rhnUserGroup		ug
			where	1=1
				and ug.id = user_group_id_in
				and ugm.user_group_id = user_group_id_in
				and ug.group_type = ugt.id
				and ugm.user_id = user_id_in
                 loop
			delete from rhnUserGroupMembers
				where	user_id = user_id_in
					and user_group_id = user_group_id_in;
			if ugr.label in ('org_admin') then
				perform rhn_cache.update_perms_for_user(user_id_in);
			end if;
		end loop;
	end;
$$ language plpgsql;

create or replace
        function role_names (user_id_in in numeric)
	returns varchar
	as
$$
	declare
		rec record;
		tmp varchar(4000);
	begin
		for rec in (
			select type_name
			from rhnUserTypeBase
			where user_id = user_id_in
			order by type_id
			) loop
			if tmp is null then
				tmp := rec.type_name;
			else
				tmp := tmp || ', ' || rec.type_name;
			end if;
		end loop;
		return tmp;
	end;
$$ language plpgsql;

-- restore the original setting
update pg_settings set setting = overlay( setting placing '' from 1 for (length('rhn_user')+1) ) where name = 'search_path';
 07070100000241000081B400000000000000000000000167AE1114000002D9000000000000000000000000000000000000003200000000susemanager-schema/postgres/packages/rhn_user.pks -- oracle equivalent source sha1 501f9187c0aff6a80f1e803efcd7caee6c63cacc
--
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--

create schema rhn_user;

   07070100000242000081B400000000000000000000000167AE111400001D77000000000000000000000000000000000000002D00000000susemanager-schema/postgres/packages/rpm.pkb  -- oracle equivalent source sha1 539cb03eb177b7e87992701071488bbb32bb0624
-- create schema rpm;

--update pg_setting
update pg_settings set setting = 'rpm,' || setting where name = 'search_path';

create or replace function isdigit(ch CHAR)
    RETURNS BOOLEAN as $$
    BEGIN
        if ascii(ch) between ascii('0') and ascii('9')
        then
            return TRUE;
        end if;
        return FALSE;
    END ;
$$ language 'plpgsql';

    
    create or replace FUNCTION isalpha(ch CHAR)
    RETURNS BOOLEAN as $$
    BEGIN
        if ascii(ch) between ascii('a') and ascii('z') or 
            ascii(ch) between ascii('A') and ascii('Z')
        then
            return TRUE;
        end if;
        return FALSE;
    END;
$$ language 'plpgsql';


    create or replace FUNCTION isalphanum(ch CHAR)
    RETURNS BOOLEAN as $$ 
    BEGIN
        if ascii(ch) between ascii('a') and ascii('z') or 
            ascii(ch) between ascii('A') and ascii('Z') or
            ascii(ch) between ascii('0') and ascii('9')
        then
            return TRUE;
        end if;
        return FALSE;
    END;
    $$ language 'plpgsql';


    create or replace FUNCTION rpmstrcmp (string1 IN VARCHAR, string2 IN VARCHAR)
    RETURNS INTEGER as $$
    declare
        str1 VARCHAR := string1;
        str2 VARCHAR := string2;
        digits VARCHAR(10) := '0123456789';
        lc_alpha VARCHAR(27) := 'abcdefghijklmnopqrstuvwxyz';
        uc_alpha VARCHAR(27) := 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
        alpha VARCHAR(54) := lc_alpha || uc_alpha;
        one VARCHAR;
        two VARCHAR;
        isnum BOOLEAN;
    BEGIN
        if str1 is NULL or str2 is NULL
        then
            RAISE EXCEPTION 'VALUE_ERROR.';
        end if;
      
        if str1 = str2
        then
            return 0;
        end if;
        one := str1;
        two := str2;

        <<segment_loop>>
        while one <> '' or two <> ''
        loop
            declare
                segm1 VARCHAR;
                segm2 VARCHAR;
                onechar CHAR(1);
                twochar CHAR(1);
            begin
                --raise notice 'Params: %, %',  one, two;
                -- Throw out all non-alphanum characters
                onechar := substr(one, 1, 1);
                twochar := substr(two, 1, 1);
                while one <> '' and not rpm.isalphanum(one) and onechar != '~' and onechar != '^'
                loop
                    one := substr(one, 2);
                end loop;
                while two <> '' and not rpm.isalphanum(two) and twochar != '~' and twochar != '^'
                loop
                    two := substr(two, 2);
                end loop;
                --raise notice 'new params: %, %', one, two;

                onechar := substr(one, 1, 1);
                twochar := substr(two, 1, 1);
                --raise notice 'new chars 1: %, %', onechar, twochar;
                /* handle the tilde separator, it sorts before everything else */
                if (onechar = '~' or twochar = '~')
                then
                    if (onechar != '~') then return 1; end if;
                    if (twochar != '~') then return -1; end if;
                    --raise notice 'passed tilde chars: %, %', onechar, twochar;
                    one := substr(one, 2);
                    two := substr(two, 2);
                    continue;
                end if;

                /*
                 * Handle caret separator. Concept is the same as tilde,
                 * except that if one of the strings ends (base version),
                 * the other is considered as higher version.
                 */
                onechar := substr(one, 1, 1);
                twochar := substr(two, 1, 1);
                --raise notice 'new chars 2: %, %', onechar, twochar;
                if (onechar = '^' or twochar = '^')
                then
                    if (one = '') then return -1; end if;
                    --raise notice 'passed caret chars 1: %, %', onechar, twochar;
                    if (two = '') then return 1; end if;
                    --raise notice 'passed caret chars 2: %, %', onechar, twochar;
                    if (onechar != '^') then return 1; end if;
                    --raise notice 'passed caret chars 3: %, %', onechar, twochar;
                    if (twochar != '^') then return -1; end if;
                    --raise notice 'passed caret chars 4: %, %', onechar, twochar;
                    one := substr(one, 2);
                    two := substr(two, 2);
                    continue;
                end if;

                if (not (one <> '' and two <> '')) then exit segment_loop; end if;

                str1 := one;
                str2 := two;
                if rpm.isdigit(str1) or rpm.isdigit(str2)
                then
                    str1 := ltrim(str1, digits);
                    str2 := ltrim(str2, digits);
                    isnum := true;
                else
                    str1 := ltrim(str1, alpha);
                    str2 := ltrim(str2, alpha);
                    isnum := false;
                end if;
                if str1 <> ''
                then segm1 := substr(one, 1, length(one) - length(str1));
                else segm1 := one;
                end if;

                if str2 <> ''
                then segm2 := substr(two, 1, length(two) - length(str2));
                else segm2 := two;
                end if;

                if isnum
                then
                    if segm1 = '' then return -1; end if;
                    if segm2 = '' then return 1; end if;

                    segm1 := ltrim(segm1, '0');
                    segm2 := ltrim(segm2, '0');

                    if segm1 = '' and segm2 <> ''
                    then
                        return -1;
                    end if;
                    if segm1 <> '' and segm2 = ''
                    then
                        return 1;
                    end if;
                    if length(segm1) < length(segm2) then return -1; end if;
                    if length(segm1) > length(segm2) then return 1; end if;
                end if;
                if segm1 < segm2 then return -1; end if;
                if segm1 > segm2 then return 1; end if;
               one := str1;
                two := str2;
            end;
        end loop segment_loop;
     
        if one = '' and two = '' then return 0; end if;
        if one = '' then return -1; end if;
        return 1;
    END ;
$$ language 'plpgsql';



   create or replace FUNCTION vercmp(
        e1 VARCHAR, v1 VARCHAR, r1 VARCHAR, 
        e2 VARCHAR, v2 VARCHAR, r2 VARCHAR)
    RETURNS INTEGER as $$
    declare
        rc INTEGER;
          ep1 INTEGER;
          ep2 INTEGER;
          BEGIN
            if e1 is null or e1 = '' then
              ep1 := 0;
            else
              ep1 := e1::integer;
            end if;
            if e2 is null or e2 = '' then
              ep2 := 0;
            else
              ep2 := e2::integer;
            end if;
            -- Epochs are non-null; compare them
            if ep1 < ep2 then return -1; end if;
            if ep1 > ep2 then return 1; end if;
            rc := rpm.rpmstrcmp(v1, v2);
            if rc != 0 then return rc; end if;
           return rpm.rpmstrcmp(r1, r2);
         END;
         $$ language 'plpgsql';

-- restore the original setting
update pg_settings set setting = overlay( setting placing '' from 1 for (length('rpm')+1) ) where name = 'search_path';

 07070100000243000081B400000000000000000000000167AE1114000002D7000000000000000000000000000000000000002D00000000susemanager-schema/postgres/packages/rpm.pks  -- oracle equivalent source sha1 1f8b5508a1d7ce29135f848b78b6564d005747b8
--
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--

create schema rpm;

 07070100000244000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000002200000000susemanager-schema/postgres/procs 07070100000245000081B400000000000000000000000167AE11140000002A000000000000000000000000000000000000003F00000000susemanager-schema/postgres/procs/add_column_if_not_exists.sql    -- This file is intentionally left empty.
  07070100000246000081B400000000000000000000000167AE111400002108000000000000000000000000000000000000003500000000susemanager-schema/postgres/procs/create_new_org.sql  --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--

create or replace function create_new_org
(
        name_in      in varchar,
        password_in  in varchar
        --org_id_out   out number
) returns numeric
as
$$
declare
        ug_type                 numeric;
        group_val               numeric;
        new_org_id              numeric;
        org_id_out		numeric;
begin

        select nextval('web_customer_id_seq') into new_org_id from dual;

        insert into web_customer (
                id, name
        ) values (
                new_org_id, name_in
        );

        select nextval('rhn_user_group_id_seq') into group_val from dual;

        select  id
        into    ug_type
        from    rhnUserGroupType
        where   label = 'org_admin';

        insert into rhnUserGroup (
                id, name,
                description,
                max_members, group_type, org_id
        ) values (
                group_val, 'Organization Administrators',
                'Organization Administrators for Org ' || name_in,
                NULL, ug_type, new_org_id
        );

        select nextval('rhn_user_group_id_seq') into group_val from dual;

        select  id
        into    ug_type
        from    rhnUserGroupType
        where   label = 'system_group_admin';

        insert into rhnUserGroup (
                id, name,
                description,
                max_members, group_type, org_id
        ) values (
                group_val, 'System Group Administrators',
                'System Group Administrators for Org ' || name_in,
                NULL, ug_type, new_org_id
        );


        select nextval('rhn_user_group_id_seq') into group_val from dual;

        select  id
        into    ug_type
        from    rhnUserGroupType
        where   label = 'activation_key_admin';

        insert into rhnUserGroup (
                id, name,
                description,
                max_members, group_type, org_id
        ) values (
                group_val, 'Activation Key Administrators',
                'Activation Key Administrators for Org ' || name_in,
                NULL, ug_type, new_org_id
        );

        select nextval('rhn_user_group_id_seq') into group_val from dual;

        select  id
        into    ug_type
        from    rhnUserGroupType
        where   label = 'channel_admin';

        insert into rhnUserGroup (
                id, name,
                description,
                max_members, group_type, org_id
        ) values (
                group_val, 'Channel Administrators',
                'Channel Administrators for Org ' || name_in,
                NULL, ug_type, new_org_id
        );

	if new_org_id = 1 then
            select nextval('rhn_user_group_id_seq') into group_val from dual;

            select  id
            into    ug_type
            from    rhnUserGroupType
            where   label = 'satellite_admin';

            insert into rhnUserGroup (
                    id, name,
                    description,
                    max_members, group_type, org_id
            ) values (
                    group_val, 'SUSE Manager Administrators',
                    'SUSE Manager Administrators for Org ' || name_in,
                    NULL, ug_type, new_org_id
            );
        end if;

        select nextval('rhn_user_group_id_seq') into group_val from dual;

        select  id
        into    ug_type
        from    rhnUserGroupType
        where   label = 'config_admin';

        insert into rhnUserGroup (
                id, name,
                description,
                max_members, group_type, org_id
        ) values (
                group_val, 'Configuration Administrators',
                'Configuration Administrators for Org ' || name_in,
                NULL, ug_type, new_org_id
        );

        select nextval('rhn_user_group_id_seq') into group_val from dual;

        select  id
        into    ug_type
        from    rhnUserGroupType
        where   label = 'image_admin';

        insert into rhnUserGroup (
                id, name,
                description,
                max_members, group_type, org_id
        ) values (
                group_val, 'Image Administrators',
                'Image Administrators for Org ' || name_in,
                NULL, ug_type, new_org_id
        );

        select nextval('rhn_user_group_id_seq') into group_val from dual;

        -- there aren't any users yet, so we don't need to update
        -- rhnUserServerPerms

        insert into rhnServerGroup
                ( id, name, description, group_type, org_id )
                select nextval('rhn_server_group_id_seq'), sgt.name, sgt.name,
                        sgt.id, new_org_id
                from rhnServerGroupType sgt
                where sgt.label = 'bootstrap_entitled';

        insert into rhnServerGroup
                ( id, name, description, group_type, org_id )
                select nextval('rhn_server_group_id_seq'), sgt.name, sgt.name,
                        sgt.id, new_org_id
                from rhnServerGroupType sgt
                where sgt.label = 'enterprise_entitled';

        insert into rhnServerGroup
                ( id, name, description, group_type, org_id )
                select nextval('rhn_server_group_id_seq'), sgt.name, sgt.name,
                        sgt.id, new_org_id
                from rhnServerGroupType sgt
                where sgt.label = 'salt_entitled';

        insert into rhnServerGroup
                ( id, name, description, group_type, org_id )
                select nextval('rhn_server_group_id_seq'), sgt.name, sgt.name,
                        sgt.id, new_org_id
                from rhnServerGroupType sgt
                where sgt.label = 'foreign_entitled';

        insert into rhnServerGroup
                ( id, name, description, group_type, org_id )
                select nextval('rhn_server_group_id_seq'), sgt.name, sgt.name,
                        sgt.id, new_org_id
                from rhnServerGroupType sgt
                where sgt.label = 'virtualization_host';

        insert into rhnServerGroup
                ( id, name, description, group_type, org_id )
                select nextval('rhn_server_group_id_seq'), sgt.name, sgt.name,
                        sgt.id, new_org_id
                from rhnServerGroupType sgt
                where sgt.label = 'container_build_host';

        insert into rhnServerGroup
                ( id, name, description, group_type, org_id )
                select nextval('rhn_server_group_id_seq'), sgt.name, sgt.name,
                        sgt.id, new_org_id
                from rhnServerGroupType sgt
                where sgt.label = 'osimage_build_host';

        insert into rhnServerGroup
                ( id, name, description, group_type, org_id )
                select nextval('rhn_server_group_id_seq'), sgt.name, sgt.name,
                        sgt.id, new_org_id
                from rhnServerGroupType sgt
                where sgt.label = 'monitoring_entitled';

        insert into rhnServerGroup
                ( id, name, description, group_type, org_id )
                select nextval('rhn_server_group_id_seq'), sgt.name, sgt.name,
                        sgt.id, new_org_id
                from rhnServerGroupType sgt
                where sgt.label = 'ansible_control_node';

        insert into suseImageStore (id, label, uri, store_type_id, org_id)
        values (
            nextval('suse_imgstore_id_seq'),
            'SUSE Manager OS Image Store',
            new_org_id || '/',
            (SELECT id FROM suseImageStoreType WHERE label = 'os_image'),
            new_org_id
        );

        org_id_out := new_org_id;

	-- Returning the value of OUT parameter
        return org_id_out;

end;
$$
language plpgsql;
07070100000247000081B400000000000000000000000167AE111400000E46000000000000000000000000000000000000003600000000susemanager-schema/postgres/procs/create_new_user.sql --
-- Copyright (c) 2008--2015 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--

create or replace function
create_new_user
(
    org_id_in           in numeric,
    login_in            in varchar,
    password_in         in varchar,
    oracle_contact_id_in in varchar,
    prefix_in           in varchar,
    first_names_in      in varchar,
    last_name_in        in varchar,
    genqual_in          in varchar,
    parent_company_in   in varchar,
    company_in          in varchar,
    title_in            in varchar,
    phone_in            in varchar,
    fax_in              in varchar,
    email_in            in varchar,
    pin_in              in numeric,
    first_names_ol_in   in varchar,
    last_name_ol_in     in varchar,
    address1_in         in varchar,
    address2_in         in varchar,
    address3_in         in varchar,
    city_in             in varchar,
    state_in            in varchar,
    zip_in              in varchar,
    country_in          in varchar,
    alt_first_names_in  in varchar,
    alt_last_name_in    in varchar,
    contact_call_in     varchar,
    contact_mail_in     varchar,
    contact_email_in    varchar,
    contact_fax_in      varchar
)
returns numeric
AS
$$
declare
    user_id_tmp             numeric;


    -- Would be using the below variables instead of the last four parameters
    contact_call_in_tmp     varchar := 'N';
    contact_mail_in_tmp     varchar := 'N';
    contact_email_in_tmp    varchar := 'N';
    contact_fax_in_tmp      varchar := 'N';
begin
    select nextval('web_contact_id_seq') into user_id_tmp;

    insert into web_contact
        (id, org_id, login, login_uc, password, oracle_contact_id)
    values
        (user_id_tmp, org_id_in, login_in, upper(login_in), password_in, oracle_contact_id_in::numeric);

    insert into web_user_contact_permission
        (web_user_id, call, mail, email, fax)
    values
        (user_id_tmp, contact_call_in_tmp, contact_mail_in_tmp, contact_email_in_tmp, contact_fax_in_tmp);

    insert into web_user_personal_info
        (web_user_id, prefix, first_names, last_name, genqual,
        parent_company, company, title, phone, fax, email, pin,
        first_names_ol, last_name_ol)
    values
        (user_id_tmp, prefix_in, first_names_in, last_name_in, genqual_in,
        parent_company_in, company_in, title_in, phone_in, fax_in, email_in, pin_in :: numeric,
        first_names_ol_in, last_name_ol_in);

    if address1_in != '.' then
        insert into web_user_site_info
            (id, web_user_id, email,
            address1, address2, address3,
            city, state, zip, country, phone, fax, type,
            alt_first_names, alt_last_name)
        values
            (nextval('web_user_site_info_id_seq'), user_id_tmp, email_in,
            address1_in, address2_in, address3_in,
            city_in, state_in, zip_in, country_in, phone_in, fax_in, 'M',
            alt_first_names_in, alt_last_name_in);
    end if;

    insert into rhnUserInfo
        (user_id)
    values
        (user_id_tmp);

    return user_id_tmp;
end;
$$
language plpgsql;


  07070100000248000081B400000000000000000000000167AE1114000004A4000000000000000000000000000000000000003900000000susemanager-schema/postgres/procs/create_pxt_session.sql  --
-- Copyright (c) 2008--2015 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--

create or replace function
create_pxt_session(p_web_user_id in numeric, p_expires in numeric, p_value in varchar)
returns numeric as $$
declare
	l_id numeric;
begin
    l_id := nextval( 'pxt_id_seq' );

    insert into PXTSessions (id, value, expires, web_user_id)
        values (l_id, p_value, p_expires, p_web_user_id)
        on conflict do nothing;

    select id
        into strict l_id
        from PXTSessions
        where value = p_value and expires = p_expires and web_user_id = p_web_user_id;

	  return l_id;
end;
$$ language plpgsql;
07070100000249000081B400000000000000000000000167AE11140000002A000000000000000000000000000000000000003F00000000susemanager-schema/postgres/procs/create_seq_if_not_exists.sql    -- This file is intentionally left empty.
  0707010000024A000081B400000000000000000000000167AE11140000002A000000000000000000000000000000000000004100000000susemanager-schema/postgres/procs/create_table_if_not_exists.sql  -- This file is intentionally left empty.
  0707010000024B000081B400000000000000000000000167AE1114000003EA000000000000000000000000000000000000003800000000susemanager-schema/postgres/procs/date_diff_in_days.sql   --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--
--
-- Diffs two timestamps (date2 - date1) and returns number of dates in the result.
-- If two timestamps are given it can return fraction digits in the same way
-- as Oracle does.
--

create or replace function date_diff_in_days(timestamptz, timestamptz)
returns numeric as
$$
select cast(extract(epoch from $2 - $1) / (60 * 60 * 24) as numeric)
$$ language sql immutable;
  0707010000024C000081B400000000000000000000000167AE11140000062E000000000000000000000000000000000000003500000000susemanager-schema/postgres/procs/delete_channel.sql  --
-- Copyright (c) 2008--2015 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--
-- This deletes a channel.  All codepaths which delete channels should hit this

create or replace
function delete_channel (
        channel_id_in in numeric
) returns void as
$$
begin
        delete from rhnChannelPackage where channel_id = channel_id_in;
        delete from rhnChannelErrata where channel_id = channel_id_in;
        delete from rhnServerChannel where channel_id = channel_id_in;
        delete from rhnRegTokenChannels where channel_id = channel_id_in;
        delete from rhnDistChannelMap where channel_id = channel_id_in;
        delete from rhnChannelFamilyMembers where channel_id = channel_id_in;
        delete from rhnServerProfilePackage where server_profile_id in (
            select id from rhnServerProfile where base_channel = channel_id_in
        );
        delete from rhnServerProfile where base_channel = channel_id_in;
        delete from rhnChannel where id = channel_id_in;
end;
$$ language plpgsql;


  0707010000024D000081B400000000000000000000000167AE111400000407000000000000000000000000000000000000003400000000susemanager-schema/postgres/procs/delete_errata.sql   --
-- Copyright (c) 2008--2015 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--
create or replace function
delete_errata (
        errata_id_in in numeric
) returns void as
$$
begin
        delete from rhnServerNeededCache where errata_id = errata_id_in;
        delete from rhnErrataFile where errata_id = errata_id_in;
        delete from rhnErrataPackage where errata_id = errata_id_in;
        delete from rhnErrata where id = errata_id_in;
end;

$$ language plpgsql;

 0707010000024E000081B400000000000000000000000167AE1114000027B1000000000000000000000000000000000000003400000000susemanager-schema/postgres/procs/delete_server.sql   --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--
--
--
-- This deletes a server.  All codepaths which delete servers should hit this
-- or delete_server_bulk()

create or replace
function delete_server (
        server_id_in in numeric
) returns void
as
$$
declare
         servergroups cursor for
                select  server_id, server_group_id
                from    rhnServerGroupMembers sgm
                where   sgm.server_id = server_id_in;

         configchannels cursor for
                select  cc.id
                from    rhnConfigChannel cc,
                        rhnConfigChannelType cct,
                        rhnServerConfigChannel scc
                where   1=1
                        and scc.server_id = server_id_in
                        and scc.config_channel_id = cc.id
                        -- these config channel types are reserved
                        -- for use by a single server, so we don't
                        -- need to check for other servers subscribed
                        and cct.label in
                                ('local_override','server_import')
                        and cct.id = cc.confchan_type_id;

begin
        -- filelists
        delete from rhnFileList where id in (
	select	spfl.file_list_id
	  from	rhnServerPreserveFileList spfl
	 where	spfl.server_id = server_id_in
			and not exists (
				select	1
				from	rhnServerPreserveFileList
				where	file_list_id = spfl.file_list_id
					and server_id != server_id_in
				union all
				select	1
				from	rhnKickstartPreserveFileList
				where	file_list_id = spfl.file_list_id
			)
        );

	for configchannel in configchannels loop
		perform rhn_config.delete_channel(configchannel.id);
	end loop;

	for sgm in servergroups loop
		perform rhn_server.delete_from_servergroup(
			sgm.server_id, sgm.server_group_id);
	end loop;


        -- we're handling this instead of letting an "on delete
        -- set null" do it so that we don't run the risk
        -- of setting off the triggers and killing us with a
        -- mutating table

        -- this is merge of two single updates:
        --  update ... set old_server_id = null where old_server_id = server_id_in;
        --  update ... set new_server_id = null where new_server_id = server_id_in;
        -- so we scan rhnKickstartSession table only once
        update rhnKickstartSession
                set old_server_id = case when old_server_id = server_id_in then null else old_server_id end,
                    new_server_id = case when new_server_id = server_id_in then null else new_server_id end
                where old_server_id = server_id_in
                   or new_server_id = server_id_in;

        perform rhn_channel.clear_subscriptions(server_id_in, 1);

        -- A little complicated here, but the goal is to
        -- delete records from rhnVirtualInstace only if we don't
        -- care about them anymore.  We don't care about records
        -- in rhnVirtualInstance if we are deleting the host
        -- system and the virtual system is already null, or
        -- vice-versa.  We *do* care about them if either the
        -- host or virtual system is still registered because we
        -- still want them to show up in the UI.
    -- If there's a newer row in rhnVirtualInstance with the same
    -- uuid, this guest must have been re-registered, so we can clean
    -- this data up.

        delete from rhnVirtualInstance vi
              where (host_system_id = server_id_in and virtual_system_id is null)
                 or (virtual_system_id = server_id_in and host_system_id is null)
                 or (vi.virtual_system_id = server_id_in and vi.modified < (select max(vi2.modified)
                    from rhnVirtualInstance vi2 where vi2.uuid = vi.uuid));

        -- this is merge of two single updates:
        --  update ... set host_system_id = null where host_system_id = server_id_in;
        --  update ... set virtual_system_id = null where virtual_system_id = server_id_in;
        -- so we scan rhnVirtualInstance table only once
        update rhnVirtualInstance
           set host_system_id = case when host_system_id = server_id_in then null else host_system_id end,
               virtual_system_id = case when virtual_system_id = server_id_in then null else virtual_system_id end
         where host_system_id = server_id_in
            or virtual_system_id = server_id_in;

        -- this is merge of two single updates:
        --  update ... set old_host_system_id = null when old_host_system_id = server_id_in;
        --  update ... set new_host_system_id = null when new_host_system_id = server_id_in;
        -- so we scan rhnVirtualInstanceEventLog table only once
        update rhnVirtualInstanceEventLog
           set old_host_system_id = case when old_host_system_id = server_id_in then null else old_host_system_id end,
               new_host_system_id = case when new_host_system_id = server_id_in then null else new_host_system_id end
         where old_host_system_id = server_id_in
            or new_host_system_id = server_id_in;

        -- archive related actions, only if they have no other servers assigned
        update rhnAction set archived = 1 where id in (
            select action_id from rhnServerAction sa
            where not exists (
                select server_id from rhnServerAction
                where action_id = sa.action_id and server_id != server_id_in
            )
        );

        -- We're deleting everything with a foreign key to rhnServer
        -- here, now.  I'm hoping this will help aleviate our deadlock
        -- problem.

        delete from rhnActionApplyStatesResult where server_id = server_id_in;
        delete from rhnActionConfigChannel where server_id = server_id_in;
        delete from rhnActionConfigRevision where server_id = server_id_in;
        delete from rhnActionPackageRemovalFailure where server_id = server_id_in;
        delete from rhnClientCapability where server_id = server_id_in;
        delete from rhnCpu where server_id = server_id_in;
        -- there's still a cascade here, because the constraint keeps the
        -- table locked for too long to rebuild it.  Ugh...
        delete from rhnDevice where server_id = server_id_in;
        delete from rhnProxyInfo where server_id = server_id_in;
        delete from rhnRam where server_id = server_id_in;
        delete from rhnRegToken where server_id = server_id_in;
        delete from suseMgrServerInfo where server_id = server_id_in;
        -- this cascades to rhnActionConfigChannel and rhnActionConfigFileName
        delete from rhnServerAction where server_id = server_id_in;
        delete from rhnServerActionPackageResult where server_id = server_id_in;
        delete from rhnServerActionScriptResult where server_id = server_id_in;
        delete from rhnServerActionVerifyResult where server_id = server_id_in;
        delete from rhnServerActionVerifyMissing where server_id = server_id_in;
        -- counts are handled above.  this should be a delete_ function.
        delete from rhnServerChannel where server_id = server_id_in;
        delete from rhnServerConfigChannel where server_id = server_id_in;
        delete from rhnServerCustomDataValue where server_id = server_id_in;
        delete from rhnServerDMI where server_id = server_id_in;
        delete from rhnServerEvent where server_id = server_id_in;
        delete from rhnServerFQDN where server_id = server_id_in;
        delete from rhnServerHistory where server_id = server_id_in;
        delete from rhnServerInfo where server_id = server_id_in;
        delete from rhnServerInstallInfo where server_id = server_id_in;
        delete from rhnServerLocation where server_id = server_id_in;
        delete from rhnServerLock where server_id = server_id_in;
        delete from rhnServerNeededCache where server_id = server_id_in;
        delete from rhnServerNotes where server_id = server_id_in;
        -- I'm not removing the foreign key from rhnServerPackage; that'll
        -- take forever.  Do the delete anyway.
        delete from rhnServerPackage where server_id = server_id_in;
        delete from rhnServerTokenRegs where server_id = server_id_in;
        delete from rhnSnapshotTag where server_id = server_id_in;
        -- this cascades to:
        --   rhnSnapshotChannel, rhnSnapshotConfigChannel, rhnSnapshotPackage,
        --   rhnSnapshotConfigRevision, rhnSnapshotServerGroup,
        --   rhnSnapshotTag.
        -- We may want to consider delete_snapshot() at some point, but
        --   I don't think we need to yet.
        delete from rhnSnapshot where server_id = server_id_in;
        delete from rhnUserServerPrefs where server_id = server_id_in;
        -- hrm, this one's interesting... we _probably_ should delete
        -- everything for the parent server_id when we delete the proxy,
        -- but we don't currently.
        delete from rhnServerPath where server_id_in in (server_id, proxy_server_id);
        delete from rhnUserServerPerms where server_id = server_id_in;

        delete from rhnServerNetInterface where server_id = server_id_in;

        delete from rhnServerUuid where server_id = server_id_in;

        delete from rhnPushClient where server_id = server_id_in;

        -- now get rhnServer itself.
        delete
        from    rhnServer
                where id = server_id_in;

        delete
        from    rhnSet
        where   label = 'system_list'
                and element = server_id_in;
end;
$$
language plpgsql;
   0707010000024F000081B400000000000000000000000167AE11140000045B000000000000000000000000000000000000003900000000susemanager-schema/postgres/procs/delete_server_bulk.sql  --
-- Copyright (c) 2008--2010 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
-- Revision 1.25  2004/11/01 17:53:03  pjones
-- bugzilla: 136124 -- Fix the "no data found" when deleting rhn_sat_cluster
--
--
--
--
-- This deletes a list of server. 
--

create or replace
function delete_server_bulk (
	user_id_in in numeric
)
returns void as
$$
declare
	rec record;
begin
	for rec in select s.element as id
			from	rhnSet s
			where	s.user_id = user_id_in
			and s.label = 'system_list'loop
		perform delete_server(rec.id);
	end loop;
end;
$$ language plpgsql;

 07070100000250000081B400000000000000000000000167AE111400000517000000000000000000000000000000000000003A00000000susemanager-schema/postgres/procs/does_user_have_role.sql --
-- Copyright (c) 2008--2015 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--
create or replace function
does_user_have_role
(
        user_id_in in numeric,
        role_in in varchar
)
returns numeric
as $$
declare
        org_admin       numeric;
begin
        select  1
        into    org_admin
        from
                rhnUserGroupType        ugt,
                rhnUserGroup            ug,
                rhnUserGroupMembers     ugm
        where   1=1
                and ugm.user_id = user_id_in
                and ugm.user_group_id = ug.id
                and ugt.label = role_in
                and ugt.id = ug.group_type;

        if not found then 
		return 0;
	end if;
        return org_admin;
end; $$ language plpgsql;

 07070100000251000081B400000000000000000000000167AE11140000002A000000000000000000000000000000000000003C00000000susemanager-schema/postgres/procs/drop_column_if_exists.sql   -- This file is intentionally left empty.
  07070100000252000081B400000000000000000000000167AE11140000002A000000000000000000000000000000000000004000000000susemanager-schema/postgres/procs/drop_constraint_if_exists.sql   -- This file is intentionally left empty.
  07070100000253000081B400000000000000000000000167AE11140000002A000000000000000000000000000000000000003500000000susemanager-schema/postgres/procs/drop_if_exists.sql  -- This file is intentionally left empty.
  07070100000254000081B400000000000000000000000167AE111400000310000000000000000000000000000000000000003100000000susemanager-schema/postgres/procs/empty_blob.sql  -- oracle equivalent source none
--
-- Copyright (c) 2009--2010 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--

create or replace function
empty_blob()
returns bytea
as
$$
begin
	return '';
end;
$$ language plpgsql
stable;

07070100000255000081B400000000000000000000000167AE111400000166000000000000000000000000000000000000004400000000susemanager-schema/postgres/procs/epoch_seconds_to_timestamp_tz.sql   --
-- Take seconds since epoch (January 1, 1970 UTC) and convert it
-- to time-zone'd timestamp. Mainly as compatibility with Oracle
-- which does not have the single-parameter to_timestamp.
--

create function epoch_seconds_to_timestamp_tz(secs in numeric)
returns timestamp with time zone
as
$$
begin
	return to_timestamp(secs);
end;
$$ language plpgsql;

  07070100000256000081B400000000000000000000000167AE1114000002FF000000000000000000000000000000000000003A00000000susemanager-schema/postgres/procs/get_hw_info_as_clob.sql 
create or replace function get_hw_info_as_clob(
	sid in rhnserver.id%TYPE,
	separator in varchar
)
returns text
as
$$
declare
	ret text;
	rec record;
begin
	for rec in (
		select m
		from (
			select 1 n, sum(nrcpu) || ' CPUs ' || coalesce(to_char(sum(nrsocket), 'FM999'), 'unknown') || ' Sockets' m
			from rhncpu where rhncpu.server_id = sid
			union all
			select 2, ni.name||' '||coalesce(na4.address,'')||'/'||coalesce(na4.netmask,'')||' '||ni.hw_addr val
			from rhnservernetinterface ni,
			     rhnServerNetAddress4 na4
			where ni.server_id = sid
			  and ni.id = na4.interface_id
			) X
		order by n, m
		) loop
		if ret is null then
			ret := rec.m;
		else
			ret := ret || separator || rec.m;
		end if;
	end loop;
	return ret;
end;
$$ language plpgsql;

 07070100000257000081B400000000000000000000000167AE11140000029A000000000000000000000000000000000000003600000000susemanager-schema/postgres/procs/insert_checksum.sql 
create or replace function
insert_checksum(checksum_type_in in varchar, checksum_in in varchar)
returns numeric
as
$$
declare
    checksum_id     numeric;
begin
    checksum_id := nextval('rhnchecksum_seq');

    insert into rhnChecksum (id, checksum_type_id, checksum)
      values (
          checksum_id,
          (select id from rhnChecksumType where label = checksum_type_in),
          checksum_in
      )
      on conflict do nothing;

    select c.id
        into strict checksum_id
        from rhnChecksumView c
        where c.checksum = checksum_in and
            c.checksum_type = checksum_type_in;

    return checksum_id;
end;
$$ language plpgsql;
  07070100000258000081B400000000000000000000000167AE1114000001E1000000000000000000000000000000000000003F00000000susemanager-schema/postgres/procs/insert_client_capability.sql    
create or replace function
insert_client_capability(name_in in varchar)
returns numeric
as $$
declare
    cap_name_id     numeric;
begin
    cap_name_id := nextval('rhn_client_capname_id_seq');

    insert into rhnClientCapabilityName(id, name)
        values (cap_name_id, name_in)
        on conflict do nothing;

    select id
        into strict cap_name_id
        from rhnclientcapabilityname
        where name = name_in;

    return cap_name_id;
end;
$$ language plpgsql;
   07070100000259000081B400000000000000000000000167AE1114000001B8000000000000000000000000000000000000003D00000000susemanager-schema/postgres/procs/insert_config_filename.sql  
create or replace function
insert_config_filename(name_in in varchar)
returns numeric as
$$
declare
    name_id     numeric;
begin
    name_id := nextval('rhn_cfname_id_seq');

    insert into rhnConfigFileName (id, path)
        values (name_id, name_in)
        on conflict do nothing;

    select id
        into strict name_id
        from rhnconfigfilename
        where path = name_in;

    return name_id;
end;
$$ language plpgsql;
0707010000025A000081B400000000000000000000000167AE11140000049B000000000000000000000000000000000000003900000000susemanager-schema/postgres/procs/insert_config_info.sql  
create or replace function
insert_config_info(
    username_in     in varchar,
    groupname_in    in varchar,
    filemode_in     in numeric,
    selinux_ctx_in  in varchar,
    symlink_target_id in numeric
)
returns numeric
as
$$
declare
    config_info_id    numeric;
begin
    config_info_id := nextval('rhn_confinfo_id_seq');

    insert into rhnConfigInfo (id, username, groupname, filemode, selinux_ctx, symlink_target_filename_id)
        values (config_info_id, username_in, groupname_in, filemode_in, selinux_ctx_in, symlink_target_id)
        on conflict do nothing;

    select id
      into config_info_id
      from rhnConfigInfo
      where (username = username_in or (username is null and username_in is null))
        and (groupname = groupname_in or (groupname is null and groupname_in is null))
        and (filemode = filemode_in or (filemode is null and filemode_in is null))
        and (selinux_ctx = selinux_ctx_in or (selinux_ctx is null and selinux_ctx_in is null))
        and (symlink_target_filename_id = symlink_target_id or (symlink_target_filename_id is null and symlink_target_id is null));

    return config_info_id;
end;
$$ language plpgsql;
 0707010000025B000081B400000000000000000000000167AE111400000193000000000000000000000000000000000000003100000000susemanager-schema/postgres/procs/insert_cve.sql  
create or replace function
insert_cve(name_in in varchar)
returns numeric
as $$
declare
    name_id     numeric;
begin
    name_id := nextval('rhn_cve_id_seq');

    insert into rhnCVE (id, name)
        values (name_id, name_in)
        on conflict do nothing;

    select id
        into strict name_id
        from rhnCVE
        where name = name_in;

    return name_id;
end;
$$ language plpgsql;
 0707010000025C000081B400000000000000000000000167AE111400000276000000000000000000000000000000000000003100000000susemanager-schema/postgres/procs/insert_evr.sql  
create or replace function
insert_evr(e_in in varchar, v_in in varchar, r_in in varchar, t_in in varchar)
returns numeric
as
$$
declare
    evr_id  numeric;
begin
    evr_id := nextval('rhn_pkg_evr_seq');

    insert into rhnPackageEVR(id, epoch, version, release, evr)
        values (evr_id, e_in, v_in, r_in, evr_t(e_in, v_in, r_in, t_in))
        on conflict do nothing;

    select id
        into strict evr_id
        from rhnPackageEVR
        where ((epoch is null and e_in is null) or (epoch = e_in)) and
           version = v_in and release = r_in and (evr).type = t_in;

    return evr_id;
end;
$$ language plpgsql;
  0707010000025D000081B400000000000000000000000167AE1114000001CE000000000000000000000000000000000000003800000000susemanager-schema/postgres/procs/insert_md_keyword.sql   
create or replace function
insert_md_keyword(label_in in varchar)
returns numeric
as
$$
declare
    md_keyword_id numeric;
begin
    md_keyword_id := nextval('suse_mdkeyword_id_seq');

    insert into suseMdKeyword (id, label)
        values (md_keyword_id, label_in)
        on conflict do nothing;

    select id
        into strict md_keyword_id
        from suseMdKeyword
        where label = label_in;

    return md_keyword_id;
end;
$$ language plpgsql;
  0707010000025E000081B400000000000000000000000167AE1114000002E8000000000000000000000000000000000000004000000000susemanager-schema/postgres/procs/insert_package_capability.sql   
create or replace function
insert_package_capability(name_in in varchar, version_in in varchar default null)
returns numeric
as
$$
declare
    name_id numeric;
begin
    name_id := nextval('rhn_pkg_capability_id_seq');

    insert into rhnPackageCapability(id, name, version)
        values (name_id, name_in, version_in)
        on conflict do nothing;

    if version_in is null then
        select id
            into strict name_id
            from rhnpackagecapability
            where name = name_in and version is null;
    else
        select id
            into strict name_id
            from rhnpackagecapability
            where name = name_in and version = version_in;
    end if;

    return name_id;
end;
$$ language plpgsql;
0707010000025F000081B400000000000000000000000167AE1114000001B0000000000000000000000000000000000000003B00000000susemanager-schema/postgres/procs/insert_package_delta.sql    
create or replace function
insert_package_delta(n_in in varchar)
returns numeric
as
$$
declare
    name_id     numeric;
begin
    name_id := nextval('rhn_packagedelta_id_seq');

    insert into rhnPackageDelta(id, label)
        values (name_id, n_in)
        on conflict do nothing;

    select id
        into strict name_id
        from rhnpackagedelta
        where label = n_in;

    return name_id;
end;
$$ language plpgsql;
07070100000260000081B400000000000000000000000167AE1114000001C5000000000000000000000000000000000000003B00000000susemanager-schema/postgres/procs/insert_package_group.sql    
create or replace function
insert_package_group(name_in in varchar)
returns numeric
as
$$
declare
    package_id   numeric;
begin
    package_id := nextval('rhn_package_group_id_seq');

    insert into rhnPackageGroup(id, name)
        values (package_id, name_in)
        on conflict do nothing;

    select id
        into strict package_id
        from rhnPackageGroup
        where name = name_in;

    return package_id;
end;
$$ language plpgsql;
   07070100000261000081B400000000000000000000000167AE1114000001AD000000000000000000000000000000000000003A00000000susemanager-schema/postgres/procs/insert_package_name.sql 
create or replace function
insert_package_name(name_in in varchar)
returns numeric
as
$$
declare
    name_id     numeric;
begin
    name_id := nextval('rhn_pkg_name_seq');

    insert into rhnPackageName(id, name)
        values (name_id, name_in)
        on conflict do nothing;

    select id
        into strict name_id
        from rhnPackageName
        where name = name_in;

    return name_id;
end;
$$ language plpgsql;
   07070100000262000081B400000000000000000000000167AE11140000030A000000000000000000000000000000000000003B00000000susemanager-schema/postgres/procs/insert_package_nevra.sql    -- This file is intentionally left empty.

create or replace function
insert_package_nevra(
        name_id_in in numeric,
        evr_id_in in numeric,
        package_arch_id_in in numeric
) returns numeric
as
$$
declare
    nevra_id numeric;
begin
    nevra_id := nextval('rhn_pkgnevra_id_seq');

    insert into rhnPackageNEVRA(id, name_id, evr_id, package_arch_id)
        values (nevra_id, name_id_in, evr_id_in, package_arch_id_in)
        on conflict do nothing;

    select id
        into strict nevra_id
        from rhnPackageNEVRA
        where name_id = name_id_in and evr_id = evr_id_in and
            (package_arch_id = package_arch_id_in or
            (package_arch_id is null and package_arch_id_in is null));

    return nevra_id;
end;
$$ language plpgsql;
  07070100000263000081B400000000000000000000000167AE1114000001B4000000000000000000000000000000000000003900000000susemanager-schema/postgres/procs/insert_source_name.sql  
create or replace function
insert_source_name(name_in in varchar)
returns numeric
as
$$
declare
    source_id   numeric;
begin
    source_id := nextval('rhn_sourcerpm_id_seq');

    insert into rhnSourceRPM(id, name)
        values (source_id, name_in)
        on conflict do nothing;

    select id
        into strict source_id
        from rhnSourceRPM
        where name = name_in;

    return source_id;
end;
$$ language plpgsql;
07070100000264000081B400000000000000000000000167AE1114000001F1000000000000000000000000000000000000003100000000susemanager-schema/postgres/procs/insert_tag.sql  
create or replace function
insert_tag(org_id_in in numeric, tag_name_id_in in numeric)
returns numeric
as $$
declare
    tag_id  numeric;
begin
    tag_id := nextval('rhn_tag_id_seq');

    insert into rhnTag(id, org_id, name_id)
        values (tag_id, org_id_in, tag_name_id_in)
        on conflict do nothing;

    select id
        into strict tag_id
        from rhnTag
        where org_id = org_id_in and
            name_id = tag_name_id_in;

    return tag_id;
end;
$$ language plpgsql;
   07070100000265000081B400000000000000000000000167AE11140000019F000000000000000000000000000000000000003600000000susemanager-schema/postgres/procs/insert_tag_name.sql 
create or replace function
insert_tag_name(name_in in varchar)
returns numeric
as
$$
declare
    name_id numeric;
begin
    name_id := nextval('rhn_tagname_id_seq');

    insert into rhnTagName(id, name)
        values (name_id, name_in)
        on conflict do nothing;

    select id
        into strict name_id
        from rhnTagName
        where name = name_in;

    return name_id;
end;
$$ language plpgsql;
 07070100000266000081B400000000000000000000000167AE1114000002F8000000000000000000000000000000000000004100000000susemanager-schema/postgres/procs/insert_transaction_package.sql  
create or replace function
insert_transaction_package(
    o_id_in      in numeric,
    n_id_in      in numeric,
    e_id_in      in numeric,
    p_arch_id_in in numeric
)
returns numeric
as
$$
declare
    tp_id       numeric;
begin
    tp_id := nextval('rhn_transpack_id_seq');

    insert into rhnTransactionPackage (id, operation, name_id, evr_id, package_arch_id)
        values (tp_id, o_id_in, n_id_in, e_id_in, p_arch_id_in)
        on conflict do nothing;

    select id
        into strict tp_id
        from rhnTransactionPackage
     where operation = o_id_in and name_id = n_id_in and evr_id = e_id_in and
        (package_arch_id = p_arch_id_in or (p_arch_id_in is null and package_arch_id is null));

    return tp_id;
end;
$$ language plpgsql;
07070100000267000081B400000000000000000000000167AE111400000263000000000000000000000000000000000000003D00000000susemanager-schema/postgres/procs/insert_xccdf_benchmark.sql  -- This file is intentionally left empty.

create or replace function
insert_xccdf_benchmark(identifier_in in varchar, version_in in varchar)
returns numeric
as
$$
declare
    benchmark_id numeric;
begin
    benchmark_id := nextval('rhn_xccdf_benchmark_id_seq');

    insert into rhnXccdfBenchmark (id, identifier, version)
        values (benchmark_id, identifier_in, version_in)
        on conflict do nothing;

    select id
        into strict benchmark_id
        from rhnXccdfBenchmark
        where identifier = identifier_in and version = version_in;

    return benchmark_id;
end;
$$ language plpgsql;
 07070100000268000081B400000000000000000000000167AE111400000250000000000000000000000000000000000000003900000000susemanager-schema/postgres/procs/insert_xccdf_ident.sql  
create or replace function
insert_xccdf_ident(ident_sys_id_in in numeric, identifier_in in varchar)
returns numeric
as
$$
declare
    xccdf_ident_id numeric;
begin
    xccdf_ident_id := nextval('rhn_xccdf_ident_id_seq');

    insert into rhnXccdfIdent (id, identsystem_id, identifier)
        values (xccdf_ident_id, ident_sys_id_in, identifier_in)
        on conflict do nothing;

    select id
        into strict xccdf_ident_id
        from rhnXccdfIdent
        where identsystem_id = ident_sys_id_in and identifier = identifier_in;

    return xccdf_ident_id;
end;
$$ language plpgsql;
07070100000269000081B400000000000000000000000167AE1114000001E8000000000000000000000000000000000000004000000000susemanager-schema/postgres/procs/insert_xccdf_ident_system.sql   
create or replace function
insert_xccdf_ident_system(system_in in varchar)
returns numeric
as
$$
declare
    ident_sys_id numeric;
begin
    ident_sys_id := nextval('rhn_xccdf_identsytem_id_seq');

    insert into rhnXccdfIdentSystem (id, system)
        values (ident_sys_id, system_in)
        on conflict do nothing;

    select id
        into strict ident_sys_id
        from rhnXccdfIdentSystem
        where system = system_in;

    return ident_sys_id;
end;
$$ language plpgsql;
0707010000026A000081B400000000000000000000000167AE111400000216000000000000000000000000000000000000003B00000000susemanager-schema/postgres/procs/insert_xccdf_profile.sql    
create or replace function
insert_xccdf_profile(identifier_in in varchar, title_in in varchar)
returns numeric
as
$$
declare
    profile_id numeric;
begin
    profile_id := nextval('rhn_xccdf_profile_id_seq');

    insert into rhnXccdfProfile (id, identifier, title)
        values (profile_id, identifier_in, title_in)
        on conflict do nothing;

    select id
        into profile_id
        from rhnXccdfProfile
        where identifier = identifier_in and title = title_in;

    return profile_id;
end;
$$ language plpgsql;
  0707010000026B000081B400000000000000000000000167AE111400000D23000000000000000000000000000000000000002C00000000susemanager-schema/postgres/procs/instr.sql   -- oracle equivalent source none
--
-- Copyright (c) 2009--2010 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--
--
--
--

CREATE OR REPLACE FUNCTION instr(varchar, varchar) RETURNS integer AS $$
DECLARE
    pos integer;
BEGIN
    pos:= instr($1, $2, 1);
    RETURN pos;
END;
$$ LANGUAGE plpgsql STRICT IMMUTABLE;


CREATE OR REPLACE FUNCTION instr(string varchar, string_to_search varchar, beg_index integer)
RETURNS integer AS $$
DECLARE
    pos integer NOT NULL DEFAULT 0;
    temp_str varchar;
    beg integer;
    length integer;
    ss_length integer;
BEGIN
    IF beg_index > 0 THEN
        temp_str := substring(string FROM beg_index);
        pos := position(string_to_search IN temp_str);

        IF pos = 0 THEN
            RETURN 0;
        ELSE
            RETURN pos + beg_index - 1;
        END IF;
    ELSE
        ss_length := char_length(string_to_search);
        length := char_length(string);
        beg := length + beg_index - ss_length + 2;

        WHILE beg > 0 LOOP
            temp_str := substring(string FROM beg FOR ss_length);
            pos := position(string_to_search IN temp_str);

            IF pos > 0 THEN
                RETURN beg;
            END IF;

            beg := beg - 1;
        END LOOP;

        RETURN 0;
    END IF;
END;
$$ LANGUAGE plpgsql STRICT IMMUTABLE;


CREATE OR REPLACE FUNCTION instr(string varchar, string_to_search varchar,
                      beg_index integer, occur_index integer)
RETURNS integer AS $$
DECLARE
    pos integer NOT NULL DEFAULT 0;
    occur_number integer NOT NULL DEFAULT 0;
    temp_str varchar;
    beg integer;
    i integer;
    length integer;
    ss_length integer;
BEGIN
    IF beg_index > 0 THEN
        beg := beg_index;
        temp_str := substring(string FROM beg_index);

        FOR i IN 1..occur_index LOOP
            pos := position(string_to_search IN temp_str);

            IF i = 1 THEN
                beg := beg + pos - 1;
            ELSE
                beg := beg + pos;
            END IF;

            temp_str := substring(string FROM beg + 1);
        END LOOP;

        IF pos = 0 THEN
            RETURN 0;
        ELSE
            RETURN beg;
        END IF;
    ELSE
        ss_length := char_length(string_to_search);
        length := char_length(string);
        beg := length + beg_index - ss_length + 2;

        WHILE beg > 0 LOOP
            temp_str := substring(string FROM beg FOR ss_length);
            pos := position(string_to_search IN temp_str);

            IF pos > 0 THEN
                occur_number := occur_number + 1;

                IF occur_number = occur_index THEN
                    RETURN beg;
                END IF;
            END IF;

            beg := beg - 1;
        END LOOP;

        RETURN 0;
    END IF;
END;
$$ LANGUAGE plpgsql STRICT IMMUTABLE;
 0707010000026C000081B400000000000000000000000167AE1114000003CF000000000000000000000000000000000000003700000000susemanager-schema/postgres/procs/lookup_arch_type.sql    --
-- Copyright (c) 2008--2015 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--

create or replace function
lookup_arch_type(label_in in varchar)
returns numeric
as
$$
declare
	arch_type_id numeric;
begin
	select id into arch_type_id from rhnArchType where label = label_in;

	if not found then
		perform rhn_exception.raise_exception('arch_type_not_found');
	end if;

	return arch_type_id;
end;
$$ language plpgsql;
 0707010000026D000081B400000000000000000000000167AE11140000037B000000000000000000000000000000000000003600000000susemanager-schema/postgres/procs/lookup_cf_state.sql --
-- Copyright (c) 2008--2015 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--

create or replace function
lookup_cf_state(
	label_in in varchar
) returns numeric 
as
$$
declare
	state_id numeric;
begin
	select	id
	into	state_id
	from	rhnConfigFileState
	where	label = label_in;

	return state_id;
end;
$$
language plpgsql
stable;

 0707010000026E000081B400000000000000000000000167AE111400000415000000000000000000000000000000000000003A00000000susemanager-schema/postgres/procs/lookup_channel_arch.sql --
-- Copyright (c) 2008--2015 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--
CREATE OR REPLACE FUNCTION
LOOKUP_CHANNEL_ARCH(label_in IN VARCHAR)
RETURNS NUMERIC 
AS $$
DECLARE
        channel_arch_id         NUMERIC;
BEGIN
        SELECT id
          INTO channel_arch_id
          FROM rhnChannelArch
         WHERE label = label_in;

	IF NOT FOUND THEN 
		perform rhn_exception.raise_exception('channel_arch_not_found');
	END IF;

	return channel_arch_id;
END;
$$ LANGUAGE plpgsql;
   0707010000026F000081B400000000000000000000000167AE111400000902000000000000000000000000000000000000003600000000susemanager-schema/postgres/procs/lookup_checksum.sql --
-- Copyright (c) 2010 - 2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

create or replace function
lookup_checksum(checksum_type_in in varchar, checksum_in in varchar)
returns numeric
as
$$
declare
    checksum_id     numeric;
begin
    if checksum_in is null then
        return null;
    end if;

    select c.id
      into checksum_id
      from rhnChecksumView c
     where c.checksum = checksum_in and
           c.checksum_type = checksum_type_in;

    if not found then
        -- HACK: insert is isolated in own function in order to be able to declare this function immutable
        -- Postgres optimizes immutable functions calls but those are compatible with the contract of lookup_\*
        -- see https://www.postgresql.org/docs/9.6/xfunc-volatility.html
        return insert_checksum(checksum_type_in, checksum_in);
    end if;

    return checksum_id;
end;
$$ language plpgsql immutable;

-- NOTE: This is intentionally not thread safe! You must lock rhnChecksum
-- if you are going to use this procedure!
create or replace function
lookup_checksum_fast(checksum_type_in in varchar, checksum_in in varchar)
returns numeric
as
$$
declare
    checksum_id     numeric;
begin
    if checksum_in is null then
        return null;
    end if;

    select c.id
      into checksum_id
      from rhnChecksumView c
     where c.checksum = checksum_in and
           c.checksum_type = checksum_type_in;

    if not found then
        checksum_id := nextval('rhnchecksum_seq');
        insert into rhnChecksum (id, checksum_type_id, checksum) values (
            checksum_id,
            (select id from rhnChecksumType where label = checksum_type_in),
            checksum_in);
    end if;

    return checksum_id;
end;
$$ language plpgsql;
  07070100000270000081B400000000000000000000000167AE111400000515000000000000000000000000000000000000003F00000000susemanager-schema/postgres/procs/lookup_client_capability.sql    --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 

create or replace function
lookup_client_capability(name_in in varchar)
returns numeric
as $$
declare
    cap_name_id     numeric;
begin
    select id
      into cap_name_id
      from rhnclientcapabilityname
     where name = name_in;

    if not found then
        -- HACK: insert is isolated in own function in order to be able to declare this function immutable
        -- Postgres optimizes immutable functions calls but those are compatible with the contract of lookup_\*
        -- see https://www.postgresql.org/docs/9.6/xfunc-volatility.html
        return insert_client_capability(name_in);
    end if;

    return cap_name_id;
end;
$$ language plpgsql immutable;
   07070100000271000081B400000000000000000000000167AE1114000004FD000000000000000000000000000000000000003D00000000susemanager-schema/postgres/procs/lookup_config_filename.sql  --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.

create or replace function
lookup_config_filename(name_in in varchar)
returns numeric as
$$
declare
    name_id     numeric;
begin
    select id
      into name_id
      from rhnconfigfilename
     where path = name_in;

    if not found then
        -- HACK: insert is isolated in own function in order to be able to declare this function immutable
        -- Postgres optimizes immutable functions calls but those are compatible with the contract of lookup_\*
        -- see https://www.postgresql.org/docs/9.6/xfunc-volatility.html
        return insert_config_filename(name_in);
    end if;

    return name_id;
end;
$$ language plpgsql immutable;
   07070100000272000081B400000000000000000000000167AE11140000079F000000000000000000000000000000000000003900000000susemanager-schema/postgres/procs/lookup_config_info.sql  --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

create or replace function
lookup_config_info(
    username_in     in varchar,
    groupname_in    in varchar,
    filemode_in     in numeric,
    selinux_ctx_in  in varchar,
    symlink_target_id in numeric
)
returns numeric
as
$$
declare
    config_info_id    numeric;
begin
    select id
      into config_info_id
      from rhnConfigInfo
      where (username = username_in or (username is null and username_in is null))
        and (groupname = groupname_in or (groupname is null and groupname_in is null))
        and (filemode = filemode_in or (filemode is null and filemode_in is null))
        and (selinux_ctx = selinux_ctx_in or (selinux_ctx is null and selinux_ctx_in is null))
        and (symlink_target_filename_id = symlink_target_id or (symlink_target_filename_id is null and symlink_target_id is null));

    if not found then
        -- HACK: insert is isolated in own function in order to be able to declare this function immutable
        -- Postgres optimizes immutable functions calls but those are compatible with the contract of lookup_\*
        -- see https://www.postgresql.org/docs/9.6/xfunc-volatility.html
        return insert_config_info(username_in, groupname_in, filemode_in, selinux_ctx_in, symlink_target_id);
    end if;

    return config_info_id;
end;
$$ language plpgsql immutable;
 07070100000273000081B400000000000000000000000167AE1114000004DA000000000000000000000000000000000000003100000000susemanager-schema/postgres/procs/lookup_cve.sql  --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.

create or replace function
lookup_cve(name_in in varchar)
returns numeric
as $$
declare
    name_id     numeric;
begin
    select id
      into name_id
      from rhnCVE
     where name = name_in;

    if not found then
        -- HACK: insert is isolated in own function in order to be able to declare this function immutable
        -- Postgres optimizes immutable functions calls but those are compatible with the contract of lookup_\*
        -- see https://www.postgresql.org/docs/9.6/xfunc-volatility.html
        return insert_cve(name_in);
    end if;

    return name_id;
end;
$$ language plpgsql immutable;
  07070100000274000081B400000000000000000000000167AE111400000429000000000000000000000000000000000000003D00000000susemanager-schema/postgres/procs/lookup_erratafile_type.sql  --
-- Copyright (c) 2008--2015 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

create or replace function
lookup_erratafile_type (
        label_in in varchar
) returns numeric as
$$
declare
        erratafile_type_id numeric;
begin
        select  id
        into    erratafile_type_id
        from    rhnErrataFileType
        where   label = label_in;

	if not found then
		perform rhn_exception.raise_exception('erratafile_type_not_found');
	end if;

        return erratafile_type_id;
end;
$$ language plpgsql;
   07070100000275000081B400000000000000000000000167AE11140000059D000000000000000000000000000000000000003100000000susemanager-schema/postgres/procs/lookup_evr.sql  --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.

create or replace function
lookup_evr(e_in in varchar, v_in in varchar, r_in in varchar, t_in in varchar)
returns numeric
as
$$
declare
    evr_id  numeric;
begin
    select id
      into evr_id
      from rhnPackageEVR
     where ((epoch is null and e_in is null) or (epoch = e_in)) and
           version = v_in and
           release = r_in and
           (evr).type = t_in;

    if not found then
        -- HACK: insert is isolated in own function in order to be able to declare this function immutable
        -- Postgres optimizes immutable functions calls but those are compatible with the contract of lookup_\*
        -- see https://www.postgresql.org/docs/9.6/xfunc-volatility.html
        return insert_evr(e_in, v_in, r_in, t_in);
    end if;

    return evr_id;
end;
$$ language plpgsql immutable;
   07070100000276000081B400000000000000000000000167AE1114000003DD000000000000000000000000000000000000003A00000000susemanager-schema/postgres/procs/lookup_feature_type.sql --
-- Copyright (c) 2008--2013 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--

create or replace function
lookup_feature_type(label_in in varchar)
returns numeric 
as
$$
declare
	feature_id numeric;
begin
	select	id
	into	feature_id
	from  rhnFeature 	
	where	label = label_in;

	if not found then
            perform rhn_exception.raise_exception('invalid_feature');
	end if;

	return feature_id;
end;
$$
language plpgsql
stable;

   07070100000277000081B400000000000000000000000167AE1114000009C1000000000000000000000000000000000000003F00000000susemanager-schema/postgres/procs/lookup_first_matching_cf.sql    --
-- Copyright (c) 2008--2015 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--

-- This finds the first valid instance of a path in a server's config channels
--
-- We could probably change this to a view if we need it to be a bit faster,
-- but right now it's a relatively uncommon code path, so I'm going to be
-- lazy and do it the easy way


create or replace function
lookup_first_matching_cf (
        server_id_in in numeric,
        path_in in varchar
) returns numeric 
as
$$
declare
        retval numeric := -1;
begin
        begin
                select  a.cfid
                into    retval
                from    (
                        select  b.cfid
                                
                        from (
                                -- We don't need to test latest any more,
                                -- because we're not looking for a revision at
                                -- all, just the file with the right path
                                select  cf.id as cfid
                                from    rhnConfigFile           cf,
                                        rhnConfigFileName       cfn,
                                        rhnConfigChannel        cc,
                                        rhnServerConfigChannel  scc
                                where   scc.server_id = server_id_in
                                        and scc.config_channel_id = cc.id
                                        and cc.id = cf.config_channel_id
                                        and cf.state_id != lookup_cf_state('dead')
                                        and cfn.path = path_in
                                        and cf.config_file_name_id = cfn.id
                                order by scc.position asc
                                ) b
                        ) a

                 LIMIT 1;
        
        return retval;
end;
end;
$$ language plpgsql;
   07070100000278000081B400000000000000000000000167AE11140000043D000000000000000000000000000000000000003800000000susemanager-schema/postgres/procs/lookup_md_keyword.sql   --
-- Copyright (c) 2012 Novell
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--

create or replace function
lookup_md_keyword(label_in in varchar)
returns numeric
as
$$
declare
    md_keyword_id numeric;
begin
    select id
      into md_keyword_id
      from suseMdKeyword
     where label = label_in;

    if not found then
        -- HACK: insert is isolated in own function in order to be able to declare this function immutable
        -- Postgres optimizes immutable functions calls but those are compatible with the contract of lookup_\*
        -- see https://www.postgresql.org/docs/9.6/xfunc-volatility.html
        return insert_md_keyword(label_in);
    end if;

    return md_keyword_id;
end;
$$ language plpgsql immutable;
   07070100000279000081B400000000000000000000000167AE111400000464000000000000000000000000000000000000003A00000000susemanager-schema/postgres/procs/lookup_package_arch.sql --
-- Copyright (c) 2008--2015 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--

CREATE OR REPLACE FUNCTION
LOOKUP_PACKAGE_ARCH(label_in IN VARCHAR)
RETURNS NUMERIC
AS
$$
DECLARE
        package_arch_id         NUMERIC;
BEGIN
   if label_in is null then
      return null;
   end if;

        SELECT id
          INTO package_arch_id
          FROM rhnPackageArch
         WHERE label = label_in;

        IF NOT FOUND THEN
		perform rhn_exception.raise_exception('package_arch_not_found');
        END IF;

       RETURN package_arch_id;

END;
$$
LANGUAGE plpgsql;
0707010000027A000081B400000000000000000000000167AE1114000009BD000000000000000000000000000000000000004000000000susemanager-schema/postgres/procs/lookup_package_capability.sql   --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 

create or replace function
lookup_package_capability(name_in in varchar, version_in in varchar default null)
returns numeric
as
$$
declare
    name_id numeric;
begin
    if version_in is null then
        select id
          into name_id
          from rhnpackagecapability
         where name = name_in and
               version is null;
    else
        select id
          into name_id
          from rhnpackagecapability
         where name = name_in and
               version = version_in;
    end if;

    if not found then
        -- HACK: insert is isolated in own function in order to be able to declare this function immutable
        -- Postgres optimizes immutable functions calls but those are compatible with the contract of lookup_\*
        -- see https://www.postgresql.org/docs/9.6/xfunc-volatility.html
        return insert_package_capability(name_in, version_in);
    end if;

    return name_id;
end;
$$ language plpgsql immutable;

-- Note: intentionally not thread-safe! You must aquire a write lock on the
-- rhnPackageCapability tabel if you are going to use this proc!
create or replace function lookup_package_capability_fast(name_in in varchar, version_in in varchar default null)
returns numeric
as
$$
declare
    name_id numeric;
begin
    if version_in is null then
        select id
          into name_id
          from rhnpackagecapability
         where name = name_in and
               version is null;
    else
        select id
          into name_id
          from rhnpackagecapability
         where name = name_in and
               version = version_in;
    end if;

    if not found then
        name_id := nextval('rhn_pkg_capability_id_seq');
        insert into rhnPackageCapability(id, name, version) values (
               name_id, name_in, version_in);
    end if;

    return name_id;
end;
$$ language plpgsql;
   0707010000027B000081B400000000000000000000000167AE1114000004F1000000000000000000000000000000000000003B00000000susemanager-schema/postgres/procs/lookup_package_delta.sql    --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 

create or replace function
lookup_package_delta(n_in in varchar)
returns numeric
as
$$
declare
    name_id     numeric;
begin
    select id
      into name_id
      from rhnPackageDelta
     where label = n_in;

    if not found then
        -- HACK: insert is isolated in own function in order to be able to declare this function immutable
        -- Postgres optimizes immutable functions calls but those are compatible with the contract of lookup_\*
        -- see https://www.postgresql.org/docs/9.6/xfunc-volatility.html
        return insert_package_delta(n_in);
    end if;

    return name_id;
end;
$$ language plpgsql immutable;
   0707010000027C000081B400000000000000000000000167AE111400000500000000000000000000000000000000000000003B00000000susemanager-schema/postgres/procs/lookup_package_group.sql    --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 

create or replace function
lookup_package_group(name_in in varchar)
returns numeric
as
$$
declare
    package_id   numeric;
begin
    select id
      into package_id
      from rhnPackageGroup
     where name = name_in;

    if not found then
        -- HACK: insert is isolated in own function in order to be able to declare this function immutable
        -- Postgres optimizes immutable functions calls but those are compatible with the contract of lookup_\*
        -- see https://www.postgresql.org/docs/9.6/xfunc-volatility.html
        return insert_package_group(name_in);
    end if;

    return package_id;
end;
$$ language plpgsql immutable;
0707010000027D000081B400000000000000000000000167AE1114000003F9000000000000000000000000000000000000003E00000000susemanager-schema/postgres/procs/lookup_package_key_type.sql --
-- Copyright (c) 2008--2015 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--

create or replace function
lookup_package_key_type(label_in in varchar)
returns numeric
as
$$
declare
	package_key_type_id numeric;
begin
	select id into package_key_type_id from rhnPackageKeyType where label = label_in;

	if not found then
		perform rhn_exception.raise_exception('package_key_type_not_found');
	end if;

	return package_key_type_id;
end;
$$
language plpgsql;

   0707010000027E000081B400000000000000000000000167AE11140000056A000000000000000000000000000000000000003A00000000susemanager-schema/postgres/procs/lookup_package_name.sql --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 

create or replace function
lookup_package_name(name_in in varchar, ignore_null in numeric default 0)
returns numeric
as
$$
declare
    name_id     numeric;
begin
    if ignore_null = 1 and name_in is null then
        return null;
    end if;

    select id
      into name_id
      from rhnPackageName
     where name = name_in;

    if not found then
        -- HACK: insert is isolated in own function in order to be able to declare this function immutable
        -- Postgres optimizes immutable functions calls but those are compatible with the contract of lookup_\*
        -- see https://www.postgresql.org/docs/9.6/xfunc-volatility.html
        return insert_package_name(name_in);
    end if;

    return name_id;
end;
$$ language plpgsql immutable;
  0707010000027F000081B400000000000000000000000167AE11140000069B000000000000000000000000000000000000003B00000000susemanager-schema/postgres/procs/lookup_package_nevra.sql    --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 

create or replace function
lookup_package_nevra(
        name_id_in in numeric,
        evr_id_in in numeric,
        package_arch_id_in in numeric,
        ignore_null_name in numeric default 0
) returns numeric
as
$$
declare
    nevra_id numeric;
begin
    if ignore_null_name = 1 and name_id_in is null then
        return null;
    end if;

    select id
      into nevra_id
      from rhnPackageNEVRA
     where name_id = name_id_in and
           evr_id = evr_id_in and
           (package_arch_id = package_arch_id_in or
            (package_arch_id is null and package_arch_id_in is null));

    if not found then
        -- HACK: insert is isolated in own function in order to be able to declare this function immutable
        -- Postgres optimizes immutable functions calls but those are compatible with the contract of lookup_\*
        -- see https://www.postgresql.org/docs/9.6/xfunc-volatility.html
        return insert_package_nevra(name_id_in, evr_id_in, package_arch_id_in);
    end if;

    return nevra_id;
end;
$$ language plpgsql immutable;
 07070100000280000081B400000000000000000000000167AE1114000003F7000000000000000000000000000000000000003E00000000susemanager-schema/postgres/procs/lookup_package_provider.sql --
-- Copyright (c) 2008--2015 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--

create or replace function
lookup_package_provider(name_in in varchar)
returns numeric
as
$$
declare
	package_provider_id numeric;
begin
	select id into package_provider_id from rhnPackageProvider where name = name_in;

	if not found then
		perform rhn_exception.raise_exception('package_provider_not_found');
	end if;

	return package_provider_id;
end;
$$ language plpgsql;

 07070100000281000081B400000000000000000000000167AE111400000426000000000000000000000000000000000000003900000000susemanager-schema/postgres/procs/lookup_server_arch.sql  --
-- Copyright (c) 2008--2015 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--

CREATE OR REPLACE FUNCTION
LOOKUP_SERVER_ARCH(label_in IN VARCHAR)
RETURNS NUMERIC
AS
$$
DECLARE
        server_arch_id          NUMERIC;
BEGIN
        SELECT id
          INTO server_arch_id
          FROM rhnServerArch
         WHERE label = label_in;

         IF NOT FOUND THEN
		perform rhn_exception.raise_exception('server_arch_not_found');
         END IF;

        RETURN server_arch_id;
END;
$$ LANGUAGE PLPGSQL;
  07070100000282000081B400000000000000000000000167AE111400000443000000000000000000000000000000000000003500000000susemanager-schema/postgres/procs/lookup_sg_type.sql  --
-- Copyright (c) 2008--2015 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--


create or replace function
lookup_sg_type(label_in in varchar)
returns numeric
as
$$
declare
        server_group_type_id numeric;
begin
        select  id
        into    server_group_type_id
        from    rhnServerGroupType sgt
        where   label = label_in;

        if not found then
		perform rhn_exception.raise_exception('invalid_server_group');
        end if;

        return server_group_type_id;
          
end;
$$ language plpgsql;


 07070100000283000081B400000000000000000000000167AE11140000045C000000000000000000000000000000000000004500000000susemanager-schema/postgres/procs/lookup_snapshot_invalid_reason.sql  --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--


CREATE OR REPLACE FUNCTION
lookup_snapshot_invalid_reason(label_in IN VARCHAR)
RETURNS NUMERIC
AS
$$
DECLARE
        snapshot_invalid_reason_id numeric;
BEGIN
        SELECT id
          INTO snapshot_invalid_reason_id
          FROM rhnSnapshotInvalidReason
         WHERE label = label_in;

         IF NOT FOUND THEN
		PERFORM rhn_exception.raise_exception('invalid_snapshot_invalid_reason');
         END IF;

	RETURN snapshot_invalid_reason_id;
END;
$$ LANGUAGE PLPGSQL;
07070100000284000081B400000000000000000000000167AE1114000004F6000000000000000000000000000000000000003900000000susemanager-schema/postgres/procs/lookup_source_name.sql  --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 

create or replace function
lookup_source_name(name_in in varchar)
returns numeric
as
$$
declare
    source_id   numeric;
begin
    select id
      into source_id
      from rhnSourceRPM
     where name = name_in;

    if not found then
        -- HACK: insert is isolated in own function in order to be able to declare this function immutable
        -- Postgres optimizes immutable functions calls but those are compatible with the contract of lookup_\*
        -- see https://www.postgresql.org/docs/9.6/xfunc-volatility.html
        return insert_source_name(name_in);
    end if;

    return source_id;
end;
$$ language plpgsql immutable;
  07070100000285000081B400000000000000000000000167AE11140000056B000000000000000000000000000000000000003100000000susemanager-schema/postgres/procs/lookup_tag.sql  --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 

create or replace function
lookup_tag(org_id_in in numeric, name_in in varchar)
returns numeric
as $$
declare
    tag_id  numeric;
    tag_name_id numeric;
begin
    tag_name_id := lookup_tag_name(name_in);

    select id
      into tag_id
      from rhnTag
     where org_id = org_id_in and
           name_id = tag_name_id;

    if not found then
        -- HACK: insert is isolated in own function in order to be able to declare this function immutable
        -- Postgres optimizes immutable functions calls but those are compatible with the contract of lookup_\*
        -- see https://www.postgresql.org/docs/9.6/xfunc-volatility.html
        return insert_tag(org_id_in, tag_name_id);
    end if;

    return tag_id;
end;
$$ language plpgsql immutable;
 07070100000286000081B400000000000000000000000167AE1114000004E6000000000000000000000000000000000000003600000000susemanager-schema/postgres/procs/lookup_tag_name.sql --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 

create or replace function
lookup_tag_name(name_in in varchar)
returns numeric
as
$$
declare
    name_id numeric;
begin
    select id
      into name_id
      from rhnTagName
     where name = name_in;

    if not found then
        -- HACK: insert is isolated in own function in order to be able to declare this function immutable
        -- Postgres optimizes immutable functions calls but those are compatible with the contract of lookup_\*
        -- see https://www.postgresql.org/docs/9.6/xfunc-volatility.html
        return insert_tag_name(name_in);
    end if;

    return name_id;
end;
$$ language plpgsql immutable;
  07070100000287000081B400000000000000000000000167AE111400000925000000000000000000000000000000000000004100000000susemanager-schema/postgres/procs/lookup_transaction_package.sql  --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 

create or replace function
lookup_transaction_package(
    o_in in varchar,
    n_in in varchar,
    e_in in varchar,
    v_in in varchar,
    r_in in varchar,
    a_in in varchar)
returns numeric
as
$$
declare
    o_id        numeric;
    n_id        numeric;
    e_id        numeric;
    p_arch_id   numeric;
    tp_id       numeric;
    type        varchar;
begin
    select id
      into o_id
      from rhnTransactionOperation
     where label = o_in;

    if not found then
        perform rhn_exception.raise_exception('invalid_transaction_operation');
    end if;

    n_id := lookup_package_name(n_in);
    p_arch_id := null;

    if a_in is not null then
        p_arch_id := lookup_package_arch(a_in);
        select t.label into type from rhnpackagearch pa join rhnarchtype t
         on t.id = pa.arch_type_id where pa.id = p_arch_id;
    else
	-- currently only used with kickstart and this is supported for Red Hat only
	type := 'rpm';
    end if;

    e_id := lookup_evr(e_in, v_in, r_in, type);

    select id
      into tp_id
      from rhnTransactionPackage
     where operation = o_id and
           name_id = n_id and
           evr_id = e_id and
           (package_arch_id = p_arch_id or (p_arch_id is null and package_arch_id is null));

    if not found then
        -- HACK: insert is isolated in own function in order to be able to declare this function immutable
        -- Postgres optimizes immutable functions calls but those are compatible with the contract of lookup_\*
        -- see https://www.postgresql.org/docs/9.6/xfunc-volatility.html
        return insert_transaction_package(o_id, n_id, e_id, p_arch_id);
    end if;
    return tp_id;
end;
$$ language plpgsql immutable;
   07070100000288000081B400000000000000000000000167AE111400000559000000000000000000000000000000000000003D00000000susemanager-schema/postgres/procs/lookup_xccdf_benchmark.sql  --
-- Copyright (c) 2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

create or replace function
lookup_xccdf_benchmark(identifier_in in varchar, version_in in varchar)
returns numeric
as
$$
declare
    benchmark_id numeric;
begin
    select id
      into benchmark_id
      from rhnXccdfBenchmark
     where identifier = identifier_in and version = version_in;

    if not found then
        -- HACK: insert is isolated in own function in order to be able to declare this function immutable
        -- Postgres optimizes immutable functions calls but those are compatible with the contract of lookup_\*
        -- see https://www.postgresql.org/docs/9.6/xfunc-volatility.html
        return insert_xccdf_benchmark(identifier_in, version_in);
    end if;

    return benchmark_id;
end;
$$ language plpgsql immutable;
   07070100000289000081B400000000000000000000000167AE11140000063A000000000000000000000000000000000000003900000000susemanager-schema/postgres/procs/lookup_xccdf_ident.sql  --
-- Copyright (c) 2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.

create or replace function
lookup_xccdf_ident(system_in in varchar, identifier_in in varchar)
returns numeric
as
$$
declare
    xccdf_ident_id numeric;
    ident_sys_id numeric;
begin
    select id
      into ident_sys_id
      from rhnXccdfIdentSystem
     where system = system_in;

    if not found then
        -- HACK: insert is isolated in own function in order to be able to declare this function immutable
        -- Postgres optimizes immutable functions calls but those are compatible with the contract of lookup_\*
        -- see https://www.postgresql.org/docs/9.6/xfunc-volatility.html
        ident_sys_id := insert_xccdf_ident_system(system_in);
    end if;

    select id
      into xccdf_ident_id
      from rhnXccdfIdent
     where identsystem_id = ident_sys_id and identifier = identifier_in;

    if not found then
        return insert_xccdf_ident(ident_sys_id, identifier_in);
    end if;

    return xccdf_ident_id;
end;
$$ language plpgsql immutable;
  0707010000028A000081B400000000000000000000000167AE111400000545000000000000000000000000000000000000003B00000000susemanager-schema/postgres/procs/lookup_xccdf_profile.sql    --
-- Copyright (c) 2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

create or replace function
lookup_xccdf_profile(identifier_in in varchar, title_in in varchar)
returns numeric
as
$$
declare
    profile_id numeric;
begin
    select id
      into profile_id
      from rhnXccdfProfile
     where identifier = identifier_in and title = title_in;

    if not found then
        -- HACK: insert is isolated in own function in order to be able to declare this function immutable
        -- Postgres optimizes immutable functions calls but those are compatible with the contract of lookup_\*
        -- see https://www.postgresql.org/docs/9.6/xfunc-volatility.html
        return insert_xccdf_profile(identifier_in, title_in);
    end if;

    return profile_id;
end;
$$ language plpgsql immutable;
   0707010000028B000081B400000000000000000000000167AE1114000000D1000000000000000000000000000000000000003C00000000susemanager-schema/postgres/procs/no_operation_trig_fun.sql   -- oracle equivalent source none

create function no_operation_trig_fun()
returns trigger as
$$
begin
	raise exception 'Permission denied: % is not allowed on %', TG_OP, TG_RELNAME;
end;
$$ language plpgsql;

   0707010000028C000081B400000000000000000000000167AE11140000041A000000000000000000000000000000000000003600000000susemanager-schema/postgres/procs/numtodsinterval.sql -- oracle equivalent source none
--
-- Copyright (c) 2010 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--

create or replace function numtodsinterval(num_in in numeric, type_in in varchar)
returns interval
as
$$
begin
  if type_in = any(array['second', 'hour', 'minute', 'day']) then
    return num_in || ' ' || type_in;
  else
    raise exception 'Function numtodsinterval only supports conversion from [second, hour, minte, day], not from [%].', type_in;
  end if;
end;
$$ language plpgsql
stable;
  0707010000028D000081B400000000000000000000000167AE111400000329000000000000000000000000000000000000002A00000000susemanager-schema/postgres/procs/nvl.sql -- oracle equivalent source none
--
-- Copyright (c) 2010 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--
--
--
--


create or replace
function nvl(input varchar, replace_with varchar) returns varchar
as $$
	SELECT COALESCE(NULLIF($1,''), $2);
$$
LANGUAGE SQL;
   0707010000028E000081B400000000000000000000000167AE1114000004C9000000000000000000000000000000000000003500000000susemanager-schema/postgres/procs/pg_dblink_exec.sql  -- oracle equivalent source none
--
-- Copyright (c) 2012 - 2013 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.

create or replace function pg_dblink_exec(in_sql in varchar) returns void as
$$
declare
    conn text[];
begin
    if in_sql is null then
	raise 'pg_dblink_exec in_sql is null';
    end if;
    conn := dblink_get_connections();
    if conn is NULL or NOT(conn @> '{at_conn}') then
        perform dblink_connect('at_conn', 'dbname=' || current_database() || ' port=' || coalesce(inet_server_port(), '5432'));
    end if;
    begin
        perform dblink_exec('at_conn', in_sql, true);
    exception when others then
        raise;
    end;
end;
$$
language plpgsql;
   0707010000028F000081B400000000000000000000000167AE111400001C57000000000000000000000000000000000000002D00000000susemanager-schema/postgres/procs/procs.deps  #
# Copyright (c) 2008--2012 Red Hat, Inc.
#
# This software is licensed to you under the GNU General Public License,
# version 2 (GPLv2). There is NO WARRANTY for this software, express or
# implied, including the implied warranties of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
# along with this software; if not, see
# http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
#
# Dependencies for stored procedure/function objects
# in this (namespace) directory.
#
# See: ../../README for details.
# No TABS, PLEASE!
#

path = . tables views packages class

create_new_org                  :: web_customer rhnUserGroupType rhnUserGroup
create_new_user                 :: web_contact web_user_contact_permission \
                                   web_user_personal_info web_user_site_info \
                                   rhnUserInfo
create_pxt_session              :: pg_dblink_exec \
                                   PXTSessions
delete_server                   :: rhn_channel.pks rhn_config.pks \
                                   rhn_config.pks rhn_server.pks rhn_entitlements.pks \
                                   rhn_server.pks \
                                   rhnSet rhnServer web_contact \
                                   rhnConfigChannel rhnConfigChannelType \
                                   rhnServerConfigChannel rhnServerGroupMembers \
                                   rhnServerPreserveFileList rhnFileList \
                                   rhnKickstartSession rhnActionConfigChannel \
                                   rhnActionConfigRevision rhnClientCapability \
                                   rhnActionPackageRemovalFailure rhnCpu \
                                   rhnDevice \
                                   rhnProxyInfo rhnRam rhnRegToken \
                                   suseMgrServerInfo rhnServerAction \
                                   rhnServerAction rhnServerActionPackageResult \
                                   rhnServerActionScriptResult rhnServerChannel \
                                   rhnServerActionVerifyResult rhnServerDMI \
                                   rhnServerActionVerifyMissing \
                                   rhnServerConfigChannel \
                                   rhnServerCustomDataValue rhnServerEvent \
                                   rhnServerFQDN \
                                   rhnServerHistory rhnServerInfo rhnServerLock \
                                   rhnServerInstallInfo rhnServerLocation \
                                   rhnServerNeededErrataCache \
                                   rhnServerNotes rhnServerPackage rhnSnapshot \
                                   rhnServerTokenRegs rhnSnapshotTag \
                                   rhnUserServerPrefs \
                                   rhnServerPath rhnServerPath \
                                   rhnServerNetInterface \
                                   rhnServerEntitlementView \
                                   rhnActionApplyStatesResult
delete_server_bulk              :: delete_server
does_user_have_role             :: rhnUserGroup rhnUserGroupMembers rhnUserGroupType
lookup_arch_type                :: data/rhnArchType rhn_exception.pks
lookup_channel_arch             :: rhn_exception.pks data/rhnException rhnChannelArch \
                                   data/rhnChannelArch
lookup_client_capability        :: rhnClientCapabilityName pg_dblink_exec
lookup_cf_state                 :: rhnConfigFileState
lookup_config_filename          :: pg_dblink_exec
lookup_config_info              :: pg_dblink_exec
lookup_cve                      :: rhnCVE pg_dblink_exec
lookup_erratafile_type          :: rhnErrataFileType data/rhnErrataFileType
lookup_evr                      :: rhnPackageEVR pg_dblink_exec
lookup_feature_type             :: rhnFeature
lookup_first_matching_cf        :: rhnConfigFile rhnConfigChannel \
                                   rhnServerConfigChannel lookup_cf_state \
                                   rhnConfigFileName
lookup_functions                :: lookup_evr lookup_package_name \
                                   lookup_package_nevra lookup_package_group \
                                   lookup_source_name lookup_channel_arch \
                                   lookup_server_arch lookup_package_arch \
                                   lookup_package_capability \
                                   lookup_erratafile_type \
                                   lookup_snapshot_invalid_reason \
                                   lookup_tag_name lookup_sg_type \
                                   lookup_tag lookup_arch_type
lookup_checksum                 :: pg_dblink_exec
lookup_md_keyword               :: pg_dblink_exec suseMdKeyword
lookup_package_arch             :: rhn_exception.pks data/rhnException rhnPackageArch \
                                   data/rhnPackageArch
lookup_package_capability       :: rhnPackageCapability
lookup_package_delta            :: rhnPackageDelta
lookup_package_name             :: rhnPackageName pg_dblink_exec
lookup_package_provider         :: rhnPackageProvider
lookup_package_key_type         :: rhnPackageKeyType
lookup_package_nevra            :: rhnPackageNEVRA pg_dblink_exec
lookup_package_group            :: rhnPackageGroup pg_dblink_exec
lookup_server_arch              :: rhn_exception.pks data/rhnException rhnServerArch \
                                   data/rhnServerArch
lookup_sg_type                  :: rhnServerGroupType
lookup_snapshot_invalid_reason  :: rhnSnapshotInvalidReason
lookup_source_name              :: rhnSourceRPM pg_dblink_exec
lookup_tag                      :: rhnTag lookup_tag_name pg_dblink_exec
lookup_tag_name                 :: rhnTagName pg_dblink_exec
lookup_transaction_package      :: rhnTransactionOperation lookup_package_name \
                                   lookup_evr lookup_package_arch \
                                   rhnTransactionPackage rhn_exception.pks \
                                   pg_dblink_exec
lookup_xccdf_benchmark          :: rhnXccdfBenchmark pg_dblink_exec
lookup_xccdf_ident              :: rhnXccdfIdentSystem \
                                   rhnXccdfIdent \
                                   pg_dblink_exec
lookup_xccdf_profile            :: rhnXccdfProfile \
                                   pg_dblink_exec
queue_server                    :: rhnTaskQueue rhnServer \
                                   rhn_server.update_needed_cache
queue_image                     :: rhnTaskQueue suseImageInfo \
                                   update_image_needed_cache

set_ks_session_history_message  :: rhnKickstartSessionState \
                                   rhnKickstartSessionHistory
get_hw_info_as_clob             :: rhnCpu rhnServerNetInterface
randomize_bunch_schedule        :: rhnTaskoSchedule
update_image_needed_cache       :: suseImageInfoChannel suseImageInfoPackage \
                                   suseImageInfo rhnPackage rhnPackageEVR \
                                   rhnChannelPackage rhnErrataPackage \
                                   rhnChannelErrata rhnPackageUpgradeArchCompat
 07070100000290000081B400000000000000000000000167AE111400000511000000000000000000000000000000000000003200000000susemanager-schema/postgres/procs/queue_image.sql --
-- Copyright (c) 2017 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
--

CREATE OR REPLACE FUNCTION
queue_image(image_id_in IN NUMERIC, immediate_in IN NUMERIC DEFAULT 1)
RETURNS VOID
AS
$$
DECLARE
    org_id_tmp NUMERIC;
BEGIN
    IF immediate_in > 0
    THEN
          PERFORM update_image_needed_cache(image_id_in);
    ELSE
          SELECT org_id INTO STRICT org_id_tmp FROM suseImageInfo WHERE id = image_id_in;

          INSERT
            INTO rhnTaskQueue
                 (id, org_id, task_name, task_data)
          SELECT nextval('rhn_task_queue_id_seq'),
                 org_id_tmp,
                 'update_image_errata_cache',
                 image_id_in
          WHERE NOT EXISTS
            (SELECT 1 FROM rhnTaskQueue
               WHERE org_id = org_id_tmp
               AND task_name = 'update_image_errata_cache'
               AND task_data = image_id_in
            );
    END IF;
END;
$$ LANGUAGE plpgsql;
   07070100000291000081B400000000000000000000000167AE1114000006BF000000000000000000000000000000000000003300000000susemanager-schema/postgres/procs/queue_server.sql    --
-- Copyright (c) 2008--2015 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--

-- the next two views are basically the same.  the first, though, has an outer join to
-- the errata stuff, in case there are packages the server needs that haven't been
-- errata'd (ie, the fringe case)


CREATE OR REPLACE FUNCTION
queue_server(server_id_in IN NUMERIC, immediate_in IN NUMERIC DEFAULT 1)
RETURNS VOID
AS
$$
DECLARE
    org_id_tmp NUMERIC;
BEGIN
    IF immediate_in > 0
    THEN
          PERFORM rhn_server.update_needed_cache(server_id_in);
    ELSE
          SELECT org_id INTO STRICT org_id_tmp
          FROM rhnServer WHERE id = server_id_in;

          INSERT
            INTO rhnTaskQueue
                 (id, org_id, task_name, task_data)
          SELECT nextval('rhn_task_queue_id_seq'),
                 org_id_tmp,
                 'update_server_errata_cache',
                 server_id_in
          WHERE NOT EXISTS
            (SELECT 1 FROM rhnTaskQueue
               WHERE org_id = org_id_tmp
               AND task_name = 'update_server_errata_cache'
               AND task_data = server_id_in
            );
    END IF;
END;
$$ LANGUAGE plpgsql;
 07070100000292000081B400000000000000000000000167AE1114000003C0000000000000000000000000000000000000003F00000000susemanager-schema/postgres/procs/randomize_bunch_schedule.sql    --
-- Copyright (c) 2014 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--

CREATE OR REPLACE FUNCTION
RANDOMIZE_BUNCH_SCHEDULE(label_in IN VARCHAR)
RETURNS void
AS
$$
DECLARE
        new_hour          NUMERIC;
        new_minute        NUMERIC;
BEGIN
        SELECT floor(random()*6)
          INTO new_hour
          FROM dual;

        SELECT floor(random()*59)
          INTO new_minute
          FROM dual;

        UPDATE rhnTaskoSchedule
           SET cron_expr = (select '0 ' || new_minute || ' ' || new_hour || ' ? * *' from dual)
         WHERE job_label = label_in;
END;
$$ LANGUAGE PLPGSQL;

07070100000293000081B400000000000000000000000167AE11140000007C000000000000000000000000000000000000003700000000susemanager-schema/postgres/procs/sequence_currval.sql    create or replace function
sequence_currval( seq_name regclass ) returns bigint as
$$
	select currval($1);
$$ language sql;
07070100000294000081B400000000000000000000000167AE11140000007C000000000000000000000000000000000000003700000000susemanager-schema/postgres/procs/sequence_nextval.sql    create or replace function
sequence_nextval( seq_name regclass ) returns bigint as
$$
	select nextval($1);
$$ language sql;
07070100000295000081B400000000000000000000000167AE111400000914000000000000000000000000000000000000004500000000susemanager-schema/postgres/procs/set_ks_session_history_message.sql  --
-- Copyright (c) 2008--2015 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--

-- this seems like maybe it should have action_id as well?
-- maybe optional?

create or replace function
set_ks_session_history_message (
        kickstart_session_id_in in numeric,
        state_label_in in varchar,
        message_in in varchar
) returns void as
$$
declare
        states cursor is
                select  id
                from    rhnKickstartSessionState
                where   label = state_label_in;

                
		history_items cursor (state_id_in numeric) is
                select  id
                from    rhnKickstartSessionHistory
                where   kickstart_session_id = kickstart_session_id_in
                        and state_id = state_id_in
                order by time desc;

                id_states_curs numeric;
                id_history_items_curs numeric;
                
begin
	for id_states_curs in states
        loop
		for id_history_items_curs in history_items(id_states_curs.id)
                loop
                        update rhnKickstartSessionHistory
                                set message = message_in
                                where id = id_history_items_curs.id;
                        return;
                end loop;

                insert into rhnKickstartSessionHistory (
                                id, kickstart_session_id, state_id, message
                        ) values (
                                nextval('rhn_ks_sessionhist_id_seq'),
                                kickstart_session_id_in,
                                id_states_cursor,
                                message_in
                        );
                return;
        end loop;
end;
$$
language plpgsql;

07070100000296000081B400000000000000000000000167AE1114000009B5000000000000000000000000000000000000004000000000susemanager-schema/postgres/procs/update_image_needed_cache.sql   --
-- Copyright (c) 2017 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--

create or replace function
update_image_needed_cache(image_id_in in numeric)
returns void as $$
declare
  update_lock numeric;
begin
  select id into update_lock from suseImageInfo where id = image_id_in for update;
  delete from rhnImageNeededCache
   where image_id = image_id_in;
  insert into rhnImageNeededCache
         (image_id, errata_id, package_id, channel_id)
    (select distinct ip.image_info_id, x.errata_id, p.id, x.channel_id
       FROM (SELECT ip_ip.image_info_id, ip_ip.name_id,
                    ip_ip.package_arch_id, max(ip_pe.evr) AS max_evr
               FROM suseImageInfoPackage ip_ip
               join rhnPackageEvr ip_pe ON ip_pe.id = ip_ip.evr_id
              GROUP BY ip_ip.image_info_id, ip_ip.name_id, ip_ip.package_arch_id) ip
       join rhnPackage p ON p.name_id = ip.name_id
       join rhnPackageEvr pe ON pe.id = p.evr_id
                AND (ip.max_evr).type = (pe.evr).type AND ip.max_evr < pe.evr
       join rhnPackageUpgradeArchCompat puac
                ON puac.package_arch_id = ip.package_arch_id
                AND puac.package_upgrade_arch_id = p.package_arch_id
       join suseImageInfoChannel ic ON ic.image_info_id = ip.image_info_id
       join rhnChannelPackage cp ON cp.package_id = p.id
                AND cp.channel_id = ic.channel_id
       left join (SELECT ep.errata_id, ce.channel_id, ep.package_id
                    FROM rhnChannelErrata ce
                    join rhnErrataPackage ep
                             ON ep.errata_id = ce.errata_id
                    join suseImageInfoChannel ic_ic
                             ON ic_ic.channel_id = ce.channel_id
                   WHERE ic_ic.image_info_id = image_id_in) x
         ON x.channel_id = ic.channel_id
                AND x.package_id = cp.package_id
       left join rhnErrata e on x.errata_id = e.id
      where ip.image_info_id = image_id_in
        and (x.errata_id IS NULL or e.advisory_status != 'retracted')); -- packages which are part of a retracted errata should not be installed
end;
$$
language plpgsql;
   07070100000297000041FD00000000000000000000000467AE111400000000000000000000000000000000000000000000002300000000susemanager-schema/postgres/quartz    07070100000298000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000002800000000susemanager-schema/postgres/quartz/data   07070100000299000081B400000000000000000000000167AE1114000001BD000000000000000000000000000000000000003100000000susemanager-schema/postgres/quartz/data/qrtz.sql  -- Thanks to Patrick Lightbody for submitting this...
--
-- In your Quartz properties file, you'll need to set
-- org.quartz.jobStore.driverDelegateClass = org.quartz.impl.jdbcjobstore.PostgreSQLDelegate

INSERT INTO qrtz_locks values('TRIGGER_ACCESS');
INSERT INTO qrtz_locks values('JOB_ACCESS');
INSERT INTO qrtz_locks values('CALENDAR_ACCESS');
INSERT INTO qrtz_locks values('STATE_ACCESS');
INSERT INTO qrtz_locks values('MISFIRE_ACCESS');
   0707010000029A000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000002A00000000susemanager-schema/postgres/quartz/tables 0707010000029B000081B400000000000000000000000167AE111400001C19000000000000000000000000000000000000003300000000susemanager-schema/postgres/quartz/tables/qrtz.sql    -- Thanks to Patrick Lightbody for submitting this...
--
-- In your Quartz properties file, you'll need to set
-- org.quartz.jobStore.driverDelegateClass = org.quartz.impl.jdbcjobstore.PostgreSQLDelegate
-- MAKE SURE ANY QUARTZ UPGRADES ARE DONE IN A WAY - DROP ALL & CREATE ALL
-- (our schema differ skips checking quartz constrains because of missing contraint names)

CREATE TABLE qrtz_job_details
  (
    JOB_NAME  VARCHAR(200) NOT NULL,
    JOB_GROUP VARCHAR(200) NOT NULL,
    DESCRIPTION VARCHAR(250) NULL,
    JOB_CLASS_NAME   VARCHAR(250) NOT NULL,
    IS_DURABLE BOOL NOT NULL,
    IS_NONCONCURRENT BOOL NOT NULL,
    IS_UPDATE_DATA BOOL NOT NULL,
    REQUESTS_RECOVERY BOOL NOT NULL,
    JOB_DATA BYTEA NULL,
    SCHED_NAME VARCHAR(120) NOT NULL DEFAULT 'TestScheduler',
    PRIMARY KEY (SCHED_NAME,JOB_NAME,JOB_GROUP)
);

CREATE TABLE qrtz_triggers
  (
    TRIGGER_NAME VARCHAR(200) NOT NULL,
    TRIGGER_GROUP VARCHAR(200) NOT NULL,
    JOB_NAME  VARCHAR(200) NOT NULL,
    JOB_GROUP VARCHAR(200) NOT NULL,
    DESCRIPTION VARCHAR(250) NULL,
    NEXT_FIRE_TIME BIGINT NULL,
    PREV_FIRE_TIME BIGINT NULL,
    PRIORITY INTEGER NULL,
    TRIGGER_STATE VARCHAR(16) NOT NULL,
    TRIGGER_TYPE VARCHAR(8) NOT NULL,
    START_TIME BIGINT NOT NULL,
    END_TIME BIGINT NULL,
    CALENDAR_NAME VARCHAR(200) NULL,
    MISFIRE_INSTR SMALLINT NULL,
    JOB_DATA BYTEA NULL,
    SCHED_NAME VARCHAR(120) NOT NULL DEFAULT 'TestScheduler',
    PRIMARY KEY (SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP),
    FOREIGN KEY (SCHED_NAME,JOB_NAME,JOB_GROUP)
	REFERENCES QRTZ_JOB_DETAILS(SCHED_NAME,JOB_NAME,JOB_GROUP)
);

CREATE TABLE qrtz_simple_triggers
  (
    TRIGGER_NAME VARCHAR(200) NOT NULL,
    TRIGGER_GROUP VARCHAR(200) NOT NULL,
    REPEAT_COUNT BIGINT NOT NULL,
    REPEAT_INTERVAL BIGINT NOT NULL,
    TIMES_TRIGGERED BIGINT NOT NULL,
    SCHED_NAME VARCHAR(120) NOT NULL DEFAULT 'TestScheduler',
    PRIMARY KEY (SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP),
    FOREIGN KEY (SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP)
	REFERENCES QRTZ_TRIGGERS(SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP)
);

CREATE TABLE qrtz_cron_triggers
  (
    TRIGGER_NAME VARCHAR(200) NOT NULL,
    TRIGGER_GROUP VARCHAR(200) NOT NULL,
    CRON_EXPRESSION VARCHAR(120) NOT NULL,
    TIME_ZONE_ID VARCHAR(80),
    SCHED_NAME VARCHAR(120) NOT NULL DEFAULT 'TestScheduler',
    PRIMARY KEY (SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP),
    FOREIGN KEY (SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP)
	REFERENCES QRTZ_TRIGGERS(SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP)
);

CREATE TABLE qrtz_simprop_triggers
 (
    SCHED_NAME VARCHAR(120) NOT NULL,
    TRIGGER_NAME VARCHAR(200) NOT NULL,
    TRIGGER_GROUP VARCHAR(200) NOT NULL,
    STR_PROP_1 VARCHAR(512) NULL,
    STR_PROP_2 VARCHAR(512) NULL,
    STR_PROP_3 VARCHAR(512) NULL,
    INT_PROP_1 INT NULL,
    INT_PROP_2 INT NULL,
    LONG_PROP_1 BIGINT NULL,
    LONG_PROP_2 BIGINT NULL,
    DEC_PROP_1 NUMERIC(13,4) NULL,
    DEC_PROP_2 NUMERIC(13,4) NULL,
    BOOL_PROP_1 BOOL NULL,
    BOOL_PROP_2 BOOL NULL,
    PRIMARY KEY (SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP),
    FOREIGN KEY (SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP)
    REFERENCES QRTZ_TRIGGERS(SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP)
);

CREATE TABLE qrtz_blob_triggers
  (
    TRIGGER_NAME VARCHAR(200) NOT NULL,
    TRIGGER_GROUP VARCHAR(200) NOT NULL,
    BLOB_DATA BYTEA NULL,
    SCHED_NAME VARCHAR(120) NOT NULL DEFAULT 'TestScheduler',
    PRIMARY KEY (SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP),
    FOREIGN KEY (SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP)
        REFERENCES QRTZ_TRIGGERS(SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP)
);

CREATE TABLE qrtz_calendars
  (
    CALENDAR_NAME  VARCHAR(200) NOT NULL,
    CALENDAR BYTEA NOT NULL,
    SCHED_NAME VARCHAR(120) NOT NULL DEFAULT 'TestScheduler',
    PRIMARY KEY (SCHED_NAME,CALENDAR_NAME)
);


CREATE TABLE qrtz_paused_trigger_grps
  (
    TRIGGER_GROUP  VARCHAR(200) NOT NULL,
    SCHED_NAME VARCHAR(120) NOT NULL DEFAULT 'TestScheduler',
    PRIMARY KEY (SCHED_NAME,TRIGGER_GROUP)
);

CREATE TABLE qrtz_fired_triggers
  (
    ENTRY_ID VARCHAR(95) NOT NULL,
    TRIGGER_NAME VARCHAR(200) NOT NULL,
    TRIGGER_GROUP VARCHAR(200) NOT NULL,
    INSTANCE_NAME VARCHAR(200) NOT NULL,
    FIRED_TIME BIGINT NOT NULL,
    PRIORITY INTEGER NOT NULL,
    STATE VARCHAR(16) NOT NULL,
    JOB_NAME VARCHAR(200) NULL,
    JOB_GROUP VARCHAR(200) NULL,
    IS_NONCONCURRENT BOOL NOT NULL,
    REQUESTS_RECOVERY BOOL NULL,
    SCHED_NAME VARCHAR(120) NOT NULL DEFAULT 'TestScheduler',
    SCHED_TIME BIGINT NOT NULL,
    PRIMARY KEY (SCHED_NAME,ENTRY_ID)
);

CREATE TABLE qrtz_scheduler_state
  (
    INSTANCE_NAME VARCHAR(200) NOT NULL,
    LAST_CHECKIN_TIME BIGINT NOT NULL,
    CHECKIN_INTERVAL BIGINT NOT NULL,
    SCHED_NAME VARCHAR(120) NOT NULL DEFAULT 'TestScheduler',
    PRIMARY KEY (SCHED_NAME,INSTANCE_NAME)
);

CREATE TABLE qrtz_locks
  (
    LOCK_NAME  VARCHAR(40) NOT NULL,
    SCHED_NAME VARCHAR(120) NOT NULL DEFAULT 'TestScheduler',
    PRIMARY KEY (SCHED_NAME,LOCK_NAME)
);

create index idx_qrtz_ft_inst_job_req_rcvry on qrtz_fired_triggers(SCHED_NAME,INSTANCE_NAME,REQUESTS_RECOVERY);
create index idx_qrtz_ft_j_g on qrtz_fired_triggers(SCHED_NAME,JOB_NAME,JOB_GROUP);
create index idx_qrtz_ft_jg on qrtz_fired_triggers(SCHED_NAME,JOB_GROUP);
create index idx_qrtz_ft_job_group on qrtz_fired_triggers(JOB_GROUP);
create index idx_qrtz_ft_job_name on qrtz_fired_triggers(JOB_NAME);
create index idx_qrtz_ft_job_req_recovery on qrtz_fired_triggers(REQUESTS_RECOVERY);
create index idx_qrtz_ft_t_g on qrtz_fired_triggers(SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP);
create index idx_qrtz_ft_tg on qrtz_fired_triggers(SCHED_NAME,TRIGGER_GROUP);
create index idx_qrtz_ft_trig_group on qrtz_fired_triggers(TRIGGER_GROUP);
create index idx_qrtz_ft_trig_inst_name on qrtz_fired_triggers(SCHED_NAME,INSTANCE_NAME);
create index idx_qrtz_ft_trig_name on qrtz_fired_triggers(TRIGGER_NAME);
create index idx_qrtz_ft_trig_nm_gp on qrtz_fired_triggers(TRIGGER_NAME,TRIGGER_GROUP);
create index idx_qrtz_j_grp on qrtz_job_details(SCHED_NAME,JOB_GROUP);
create index idx_qrtz_j_req_recovery on qrtz_job_details(SCHED_NAME,REQUESTS_RECOVERY);
create index idx_qrtz_t_c on qrtz_triggers(SCHED_NAME,CALENDAR_NAME);
create index idx_qrtz_t_g on qrtz_triggers(SCHED_NAME,TRIGGER_GROUP);
create index idx_qrtz_t_j on qrtz_triggers(SCHED_NAME,JOB_NAME,JOB_GROUP);
create index idx_qrtz_t_jg on qrtz_triggers(SCHED_NAME,JOB_GROUP);
create index idx_qrtz_t_n_g_state on qrtz_triggers(SCHED_NAME,TRIGGER_GROUP,TRIGGER_STATE);
create index idx_qrtz_t_n_state on qrtz_triggers(SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP,TRIGGER_STATE);
create index idx_qrtz_t_next_fire_time on qrtz_triggers(SCHED_NAME,NEXT_FIRE_TIME);
create index idx_qrtz_t_nft_misfire on qrtz_triggers(SCHED_NAME,MISFIRE_INSTR,NEXT_FIRE_TIME);
create index idx_qrtz_t_nft_st on qrtz_triggers(SCHED_NAME,TRIGGER_STATE,NEXT_FIRE_TIME);
create index idx_qrtz_t_nft_st_misfire on qrtz_triggers(SCHED_NAME,MISFIRE_INSTR,NEXT_FIRE_TIME,TRIGGER_STATE);
create index idx_qrtz_t_nft_st_misfire_grp on qrtz_triggers(SCHED_NAME,MISFIRE_INSTR,NEXT_FIRE_TIME,TRIGGER_GROUP,TRIGGER_STATE);
create index idx_qrtz_t_state on qrtz_triggers(SCHED_NAME,TRIGGER_STATE);
   0707010000029C000081B400000000000000000000000167AE1114000002C5000000000000000000000000000000000000002600000000susemanager-schema/postgres/start.sql 
-- Copyright (c) 2010--2012 Red Hat, Inc.
-- Copyright (c) 2023 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

create extension dblink;
CREATE EXTENSION pgcrypto;
   0707010000029D000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000002500000000susemanager-schema/postgres/synonyms  0707010000029E000081B400000000000000000000000167AE111400000239000000000000000000000000000000000000003300000000susemanager-schema/postgres/synonyms/synonyms.deps    #
# Copyright (c) 2010--2012 Red Hat, Inc.
#
# This software is licensed to you under the GNU General Public License,
# version 2 (GPLv2). There is NO WARRANTY for this software, express or
# implied, including the implied warranties of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
# along with this software; if not, see
# http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
#
# Dependencies for synonym objects in this (namespace) directory.
# See: ../../README for details.
# No TABS, PLEASE!
#

path = . tables

   0707010000029F000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000002300000000susemanager-schema/postgres/tables    070701000002A0000081B400000000000000000000000167AE111400000245000000000000000000000000000000000000002C00000000susemanager-schema/postgres/tables/Makefile   #
# Copyright (c) 2008--2011 Red Hat, Inc.
#
# This software is licensed to you under the GNU General Public License,
# version 2 (GPLv2). There is NO WARRANTY for this software, express or
# implied, including the implied warranties of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
# along with this software; if not, see
# http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
#

COMMON := ../../common/tables

common :
	@rm -rf common
	@mkdir -p common
	@cp -p $(COMMON)/* common

clean :
	@rm -rf common

.PHONY : common clean
   070701000002A1000081B400000000000000000000000167AE11140000015B000000000000000000000000000000000000002C00000000susemanager-schema/postgres/tables/dual.sql   -- oracle equivalent source none

create table dual ( dummy char );

insert into dual values ( 'X' );

create or replace rule deny_insert_dual as on insert to dual do instead nothing;
create or replace rule deny_update_dual as on update to dual do instead nothing;
create or replace rule deny_delete_dual as on delete to dual do instead nothing;

 070701000002A2000081B400000000000000000000000167AE111400000418000000000000000000000000000000000000004000000000susemanager-schema/postgres/tables/rhnChannelPackage_alters.sql   -- oracle equivalent source none
--
-- Copyright (c) 2016 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

-- Set some postgres-specific parameters that can strongly affect performance
-- when cloning channels
ALTER TABLE rhnChannelPackage SET (autovacuum_vacuum_scale_factor = 0.0);
ALTER TABLE rhnChannelPackage SET (autovacuum_vacuum_threshold = 15);
ALTER TABLE rhnChannelPackage SET (autovacuum_analyze_scale_factor = 0.0);
ALTER TABLE rhnChannelPackage SET (autovacuum_analyze_threshold = 15);
070701000002A3000081B400000000000000000000000167AE1114000006D6000000000000000000000000000000000000003B00000000susemanager-schema/postgres/tables/rhnConfigInfo_index.sql    --
-- Copyright (c) 2016--2017 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--
-- FOUR CASES:
-- u|g|f-not  link-null selinux-null
-- u|g|f-not  link-null selinux-not
-- u|g|f null link-not  selinux-not
-- u|g|f null link-not  selinux-null

create unique index rhn_confinfo_ugf_uq
    on rhnConfigInfo (username, groupname, filemode)
 where username is not null and groupname is not null and filemode is not null and selinux_ctx is null and symlink_target_filename_id is null;

create unique index rhn_confinfo_ugf_se_uq
    on rhnConfigInfo (username, groupname, filemode, selinux_ctx)
 where username is not null and groupname is not null and filemode is not null and selinux_ctx is not null and symlink_target_filename_id is null;

create unique index rhn_confinfo_s_uq
    on rhnConfigInfo (symlink_target_filename_id)
 where username is null and groupname is null and filemode is null and selinux_ctx is null and symlink_target_filename_id is not null;

create unique index rhn_confinfo_s_se_uq
    on rhnConfigInfo (symlink_target_filename_id, selinux_ctx)
 where username is null and groupname is null and filemode is null and selinux_ctx is not null and symlink_target_filename_id is not null;
  070701000002A4000081B400000000000000000000000167AE1114000004BA000000000000000000000000000000000000004100000000susemanager-schema/postgres/tables/rhnContentSourceSsl_index.sql  --
-- Copyright (c) 2017 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

CREATE UNIQUE INDEX rhn_csssl_ca_uq
    ON rhnContentSourceSsl (content_source_id, ssl_ca_cert_id)
    WHERE ssl_client_cert_id IS NULL AND ssl_client_key_id IS NULL;

CREATE UNIQUE INDEX rhn_csssl_ca_cert_uq
    ON rhnContentSourceSsl (content_source_id, ssl_ca_cert_id, ssl_client_cert_id)
    WHERE ssl_client_cert_id IS NOT NULL AND ssl_client_key_id IS NULL;

CREATE UNIQUE INDEX rhn_csssl_ca_cert_key_uq
    ON rhnContentSourceSsl (content_source_id, ssl_ca_cert_id, ssl_client_cert_id, ssl_client_key_id)
    WHERE ssl_client_cert_id IS NOT NULL AND ssl_client_key_id IS NOT NULL;
  070701000002A5000081B400000000000000000000000167AE11140000036E000000000000000000000000000000000000003F00000000susemanager-schema/postgres/tables/rhnDistChannelMap_index.sql    --
-- Copyright (c) 2014 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

create unique index rhn_dcm_rel_caid_oid_uq_idx
    on rhnDistChannelMap (release, channel_arch_id, org_id)
 where org_id is not null;

create unique index rhn_dcm_rel_caid_uq_idx
    on rhnDistChannelMap (release, channel_arch_id)
 where org_id is null;

  070701000002A6000081B400000000000000000000000167AE111400000407000000000000000000000000000000000000003700000000susemanager-schema/postgres/tables/rhnErrata_index.sql    --
-- Copyright (c) 2017 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

CREATE UNIQUE INDEX rhn_errata_advname_uq
    ON rhnErrata (advisory_name)
 WHERE org_id IS NULL;

CREATE UNIQUE INDEX rhn_errata_advname_org_uq
    ON rhnErrata (advisory_name, org_id)
 WHERE org_id IS NOT NULL;

CREATE UNIQUE INDEX rhn_errata_adv_uq
    ON rhnErrata (advisory)
 WHERE org_id IS NULL;

CREATE UNIQUE INDEX rhn_errata_adv_org_uq
    ON rhnErrata (advisory, org_id)
 WHERE org_id IS NOT NULL;
 070701000002A7000081B400000000000000000000000167AE11140000009B000000000000000000000000000000000000003A00000000susemanager-schema/postgres/tables/rhnISSMaster_index.sql -- functional index for rhnISSMaster

create unique index rhn_issm_only_one_default on rhnISSMaster
    (is_current_master) where is_current_master = 'Y';
 070701000002A8000081B400000000000000000000000167AE1114000003FF000000000000000000000000000000000000004200000000susemanager-schema/postgres/tables/rhnPackageCapability_index.sql --
-- Copyright (c) 2017 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

CREATE UNIQUE INDEX rhn_pkg_cap_name_version_uq
    ON rhnPackageCapability USING btree (sha512(replace(name, E'\\', E'\\\\')::bytea), version)
 WHERE version IS NOT NULL;

CREATE UNIQUE INDEX rhn_pkg_cap_name_uq
    ON rhnPackageCapability USING btree (sha512(replace(name, E'\\', E'\\\\')::bytea))
 WHERE version IS NULL;

CREATE INDEX rhn_pkg_cap_name_idx
    ON rhnPackageCapability USING HASH (name);
 070701000002A9000081B400000000000000000000000167AE111400000358000000000000000000000000000000000000003B00000000susemanager-schema/postgres/tables/rhnPackageEVR_index.sql    --
-- Copyright (c) 2017 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

create unique index rhn_pe_v_r_e_uq
    on rhnpackageevr (version, release, epoch, ((evr).type))
 where epoch is not null;

create unique index rhn_pe_v_r_uq
    on rhnpackageevr (version, release, ((evr).type))
 where epoch is null;
070701000002AA000081B400000000000000000000000167AE111400000089000000000000000000000000000000000000003B00000000susemanager-schema/postgres/tables/rhnServerFQDN_index.sql    -- function index for rhnServerFQDN

CREATE UNIQUE INDEX rhn_srv_fqdn_prim_fqdn
  ON rhnServerFQDN
  (server_id) where is_primary = 'Y';
   070701000002AB000081B400000000000000000000000167AE1114000000A5000000000000000000000000000000000000004300000000susemanager-schema/postgres/tables/rhnServerNetInterface_index.sql    -- function index for rhnServerNetInterface

CREATE UNIQUE INDEX rhn_srv_net_iface_prim_iface
  ON rhnServerNetInterface
  (server_id) where is_primary is not null;
   070701000002AC000081B400000000000000000000000167AE111400000088000000000000000000000000000000000000003700000000susemanager-schema/postgres/tables/rhnServer_index.sql    -- functional index for rhnISSMaster

CREATE UNIQUE INDEX rhn_server_maid_uq
  ON rhnServer
  (machine_id) where machine_id is not null;070701000002AD000081B400000000000000000000000167AE111400000516000000000000000000000000000000000000003400000000susemanager-schema/postgres/tables/rhnSet_index.sql   --
-- Copyright (c) 2017 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

CREATE UNIQUE INDEX rhn_set_user_label_elem_unq
    ON rhnSet (user_id, label, element)
    WHERE element_two IS NULL AND element_three IS NULL;

CREATE UNIQUE INDEX rhn_set_user_label_elem_elem2_unq
    ON rhnSet (user_id, label, element, element_two)
    WHERE element_two IS NOT NULL AND element_three IS NULL;

CREATE UNIQUE INDEX rhn_set_user_label_elem_elem3_unq
    ON rhnSet (user_id, label, element, element_three)
    WHERE element_two IS NULL AND element_three IS NOT NULL;

CREATE UNIQUE INDEX rhn_set_user_label_elem_elem2_elem3_unq
    ON rhnSet (user_id, label, element, element_two, element_three)
    WHERE element_two IS NOT NULL AND element_three IS NOT NULL;

  070701000002AE000081B400000000000000000000000167AE11140000047B000000000000000000000000000000000000004100000000susemanager-schema/postgres/tables/suseRecurringAction_index.sql  -- oracle equivalent source none
--
-- Copyright (c) 2020 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

CREATE UNIQUE INDEX suse_rec_action_name_minion_uq
    ON suseRecurringAction(name, minion_id)
    WHERE group_id IS NULL AND org_id IS NULL AND minion_id IS NOT NULL;

CREATE UNIQUE INDEX suse_rec_action_name_grp_uq
    ON suseRecurringAction(name, group_id)
    WHERE minion_id IS NULL AND org_id IS NULL AND group_id IS NOT NULL;

CREATE UNIQUE INDEX suse_rec_action_name_org_uq
    ON suseRecurringAction(name, org_id)
    WHERE minion_id IS NULL AND group_id IS NULL AND org_id IS NOT NULL;

 070701000002AF000081B400000000000000000000000167AE111400000111000000000000000000000000000000000000003500000000susemanager-schema/postgres/tables/suseSaltEvent.sql  -- oracle equivalent source none

CREATE TABLE suseSaltEvent (
  id SERIAL PRIMARY KEY,
  minion_id CHARACTER VARYING(256),
  data TEXT NOT NULL,
  queue NUMERIC NOT NULL
);

CREATE INDEX suse_salt_event_minion_id_idx
  ON suseSaltEvent (queue, minion_id NULLS FIRST, id);
   070701000002B0000081B400000000000000000000000167AE111400000236000000000000000000000000000000000000002F00000000susemanager-schema/postgres/tables/tables.deps    #
# Copyright (c) 2008--2012 Red Hat, Inc.
#
# This software is licensed to you under the GNU General Public License,
# version 2 (GPLv2). There is NO WARRANTY for this software, express or
# implied, including the implied warranties of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
# along with this software; if not, see
# http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
#
# Dependencies for table objects in this (namespace) directory.
# See: ../../README for details.
# No TABS, PLEASE!
#

path = . class

  070701000002B1000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000002500000000susemanager-schema/postgres/triggers  070701000002B2000081B400000000000000000000000167AE111400000121000000000000000000000000000000000000003300000000susemanager-schema/postgres/triggers/rhnAction.sql    
create or replace function rhn_action_mod_trig_fun() returns trigger as
$$
begin
	new.modified := current_timestamp;
	return new;
end;
$$ language plpgsql;

create trigger
rhn_action_mod_trig
before insert or update on rhnAction
for each row
execute procedure rhn_action_mod_trig_fun();

   070701000002B3000081B400000000000000000000000167AE111400000149000000000000000000000000000000000000003E00000000susemanager-schema/postgres/triggers/rhnActionApplyStates.sql 
create or replace function rhn_act_apply_states_mod_trig_fun() returns trigger as
$$
begin
	new.modified := current_timestamp;
	return new;
end;
$$ language plpgsql;

create trigger
rhn_act_apply_states_mod_trig
before insert or update on rhnActionApplyStates
for each row
execute procedure rhn_act_apply_states_mod_trig_fun();
   070701000002B4000081B400000000000000000000000167AE111400000312000000000000000000000000000000000000003800000000susemanager-schema/postgres/triggers/rhnActionChain.sql   --
-- Copyright (c) 2014 SUSE
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
--
CREATE OR REPLACE FUNCTION rhn_actionchain_mod_trig_fun() RETURNS TRIGGER
    AS
    $$
    BEGIN
        new.modified := current_timestamp;
        RETURN new;
    END;
    $$
    LANGUAGE PLPGSQL;

CREATE TRIGGER rhn_actionchain_mod_trig
    BEFORE INSERT OR UPDATE ON rhnActionChain
    FOR EACH ROW
    EXECUTE PROCEDURE rhn_actionchain_mod_trig_fun();
  070701000002B5000081B400000000000000000000000167AE111400000317000000000000000000000000000000000000003D00000000susemanager-schema/postgres/triggers/rhnActionChainEntry.sql  --
-- Copyright (c) 2014 SUSE
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
--
CREATE OR REPLACE FUNCTION rhn_actchainent_mod_trig_fun() RETURNS TRIGGER
    AS
    $$
    BEGIN
        new.modified := current_timestamp;
        RETURN new;
    END;
    $$
    LANGUAGE PLPGSQL;

CREATE TRIGGER rhn_actchainent_mod_trig
    BEFORE INSERT OR UPDATE ON rhnActionChainEntry
    FOR EACH ROW
    EXECUTE PROCEDURE rhn_actchainent_mod_trig_fun();
 070701000002B6000081B400000000000000000000000167AE111400000134000000000000000000000000000000000000004000000000susemanager-schema/postgres/triggers/rhnActionConfigChannel.sql   
create or replace function rhn_actioncc_mod_trig_fun() returns trigger as
$$
begin
	new.modified := current_timestamp;
	return new;
end;
$$ language plpgsql;

create trigger
rhn_actioncc_mod_trig
before insert or update on rhnActionConfigChannel
for each row
execute procedure rhn_actioncc_mod_trig_fun();

070701000002B7000081B400000000000000000000000167AE111400000131000000000000000000000000000000000000003D00000000susemanager-schema/postgres/triggers/rhnActionConfigDate.sql  
create or replace function rhn_actioncd_mod_trig_fun() returns trigger as
$$
begin
	new.modified := current_timestamp;
	return new;
end;
$$ language plpgsql;

create trigger
rhn_actioncd_mod_trig
before insert or update on rhnActionConfigDate
for each row
execute procedure rhn_actioncd_mod_trig_fun();

   070701000002B8000081B400000000000000000000000167AE11140000014B000000000000000000000000000000000000004100000000susemanager-schema/postgres/triggers/rhnActionConfigDateFile.sql  
create or replace function rhn_actioncd_file_mod_trig_fun() returns trigger as
$$
begin
        new.modified := current_timestamp;
	return new;
end;
$$ language plpgsql;

create trigger
rhn_actioncd_file_mod_trig
before insert or update on rhnActionConfigDateFile
for each row
execute procedure rhn_actioncd_file_mod_trig_fun();

 070701000002B9000081B400000000000000000000000167AE111400000144000000000000000000000000000000000000004100000000susemanager-schema/postgres/triggers/rhnActionConfigFileName.sql  
create or replace function rhn_actioncf_name_mod_trig_fun() returns trigger as
$$
begin
	new.modified := current_timestamp;
	return new;
end;
$$ language plpgsql;

create trigger
rhn_actioncf_name_mod_trig
before insert or update on rhnActionConfigFileName
for each row
execute procedure rhn_actioncf_name_mod_trig_fun();

070701000002BA000081B400000000000000000000000167AE111400000135000000000000000000000000000000000000004100000000susemanager-schema/postgres/triggers/rhnActionConfigRevision.sql  
create or replace function rhn_actioncr_mod_trig_fun() returns trigger as
$$
begin
	new.modified := current_timestamp;
	return new;
end;
$$ language plpgsql;

create trigger
rhn_actioncr_mod_trig
before insert or update on rhnActionConfigRevision
for each row
execute procedure rhn_actioncr_mod_trig_fun();

   070701000002BB000081B400000000000000000000000167AE11140000013D000000000000000000000000000000000000004700000000susemanager-schema/postgres/triggers/rhnActionConfigRevisionResult.sql    
create or replace function rhn_actioncfr_mod_trig_fun() returns trigger as
$$
begin
	new.modified := current_timestamp;
	return new;
end;
$$ language plpgsql;

create trigger
rhn_actioncfr_mod_trig
before insert or update on rhnActionConfigRevisionResult
for each row
execute procedure rhn_actioncfr_mod_trig_fun();
   070701000002BC000081B400000000000000000000000167AE111400000133000000000000000000000000000000000000003F00000000susemanager-schema/postgres/triggers/rhnActionDaemonConfig.sql    
create or replace function rhn_actiondc_mod_trig_fun() returns trigger as
$$
begin
	new.modified := current_timestamp;
	return new;
end;
$$ language plpgsql;

create trigger
rhn_actiondc_mod_trig
before insert or update on rhnActionDaemonConfig
for each row
execute procedure rhn_actiondc_mod_trig_fun();

 070701000002BD000081B400000000000000000000000167AE11140000012C000000000000000000000000000000000000003600000000susemanager-schema/postgres/triggers/rhnActionDup.sql create or replace function rhn_actiondup_mod_trig_fun() returns trigger as
$$
begin
	new.modified := current_timestamp;
	return new;
end;
$$ language plpgsql;

create trigger
rhn_actiondup_mod_trig
before insert or update on rhnActionDup
for each row
execute procedure rhn_actiondup_mod_trig_fun();

070701000002BE000081B400000000000000000000000167AE11140000013F000000000000000000000000000000000000003D00000000susemanager-schema/postgres/triggers/rhnActionDupChannel.sql  create or replace function rhn_actiondupchan_mod_trig_fun() returns trigger as
$$
begin
	new.modified := current_timestamp;
	return new;
end;
$$ language plpgsql;

create trigger
rhn_actiondupchan_mod_trig
before insert or update on rhnActionDupChannel
for each row
execute procedure rhn_actiondupchan_mod_trig_fun();

 070701000002BF000081B400000000000000000000000167AE11140000013F000000000000000000000000000000000000003D00000000susemanager-schema/postgres/triggers/rhnActionDupProduct.sql  create or replace function rhn_actiondupprod_mod_trig_fun() returns trigger as
$$
begin
	new.modified := current_timestamp;
	return new;
end;
$$ language plpgsql;

create trigger
rhn_actiondupprod_mod_trig
before insert or update on rhnActionDupProduct
for each row
execute procedure rhn_actiondupprod_mod_trig_fun();

 070701000002C0000081B400000000000000000000000167AE111400000136000000000000000000000000000000000000003C00000000susemanager-schema/postgres/triggers/rhnActionKickstart.sql   
create or replace function rhn_actionks_mod_trig_fun() returns trigger as
$$
begin
	new.modified := current_timestamp;
	return new;
end;
$$ language plpgsql;

create trigger       
rhn_actionks_mod_trig
before insert or update on rhnActionKickstart
for each row
execute procedure rhn_actionks_mod_trig_fun();
  070701000002C1000081B400000000000000000000000167AE11140000013E000000000000000000000000000000000000004400000000susemanager-schema/postgres/triggers/rhnActionKickstartFileList.sql   
create or replace function rhn_actionksfl_mod_trig_fun() returns trigger as
$$
begin
	new.modified := current_timestamp;
	return new;
end;
$$ language plpgsql;

create trigger
rhn_actionksfl_mod_trig
before insert or update on rhnActionKickstartFileList
for each row
execute procedure rhn_actionksfl_mod_trig_fun();

  070701000002C2000081B400000000000000000000000167AE11140000014F000000000000000000000000000000000000004100000000susemanager-schema/postgres/triggers/rhnActionKickstartGuest.sql  
create or replace function rhn_actionks_xenguest_mod_trig_fun() returns trigger as
$$
begin
	new.modified := current_timestamp;
	return new;
end;
$$ language plpgsql;

create trigger
rhn_actionks_xenguest_mod_trig
before insert or update on rhnActionKickstartGuest
for each row
execute procedure rhn_actionks_xenguest_mod_trig_fun();
 070701000002C3000081B400000000000000000000000167AE111400000137000000000000000000000000000000000000004400000000susemanager-schema/postgres/triggers/rhnActionPackageAnswerfile.sql   
create or replace function rhn_act_p_af_mod_trig_fun() returns trigger as
$$
begin
	new.modified := current_timestamp;
	return new;
end;
$$ language plpgsql;

create trigger
rhn_act_p_af_mod_trig
before insert or update on rhnActionPackageAnswerfile
for each row
execute procedure rhn_act_p_af_mod_trig_fun();
 070701000002C4000081B400000000000000000000000167AE111400000158000000000000000000000000000000000000004100000000susemanager-schema/postgres/triggers/rhnActionPackageDetails.sql  create or replace function rhn_actionpackagedetails_mod_trig_fun() returns trigger as
$$
begin
	new.modified := current_timestamp;
	return new;
end;
$$ language plpgsql;

create trigger
rhn_actionpackagedetails_mod_trig
before insert or update on rhnActionPackageDetails
for each row
execute procedure rhn_actionpackagedetails_mod_trig_fun();

070701000002C5000081B400000000000000000000000167AE11140000012F000000000000000000000000000000000000003900000000susemanager-schema/postgres/triggers/rhnActionScript.sql  
create or replace function rhn_actscript_mod_trig_fun() returns trigger as
$$
begin
	new.modified := current_timestamp;
	return new;
end;
$$ language plpgsql;

create trigger
rhn_actscript_mod_trig
before insert or update on rhnActionScript
for each row
execute procedure rhn_actscript_mod_trig_fun();
 070701000002C6000081B400000000000000000000000167AE1114000003C8000000000000000000000000000000000000003900000000susemanager-schema/postgres/triggers/rhnActionStatus.sql  
--
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--


create or replace function rhn_action_statusmod_trig_fun() returns trigger as
$$
begin
        new.modified := current_timestamp;
        return new;
end;
$$ language plpgsql;

create trigger
rhn_action_statusmod_trig
before insert or update on rhnActionStatus
for each row
execute procedure rhn_action_statusmod_trig_fun();


070701000002C7000081B400000000000000000000000167AE1114000002F3000000000000000000000000000000000000003E00000000susemanager-schema/postgres/triggers/rhnActionSubChannels.sql 
--
-- Copyright (c) 2018 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
--

create or replace function rhn_actionsbscrch_mod_trig_fun() returns trigger as
$$
begin
	new.modified := current_timestamp;
	return new;
end;
$$ language plpgsql;

create trigger
rhn_actionsbscrch_mod_trig
before insert or update on rhnActionSubChannels
for each row
execute procedure rhn_actionsbscrch_mod_trig_fun();

 070701000002C8000081B400000000000000000000000167AE111400000124000000000000000000000000000000000000003D00000000susemanager-schema/postgres/triggers/rhnActionVirtDelete.sql  create or replace function rhn_avdl_mod_trig_fun() returns trigger as
$$
begin
	new.modified := current_timestamp;
	return new;
end;
$$ language plpgsql;

create trigger
rhn_avdl_mod_trig
before insert or update on rhnActionVirtDelete
for each row
execute procedure rhn_avdl_mod_trig_fun();

070701000002C9000081B400000000000000000000000167AE111400000123000000000000000000000000000000000000003E00000000susemanager-schema/postgres/triggers/rhnActionVirtDestroy.sql 
create or replace function rhn_avd_mod_trig_fun() returns trigger as
$$
begin
	new.modified := current_timestamp;
	return new;
end;
$$ language plpgsql;

create trigger
rhn_avd_mod_trig
before insert or update on rhnActionVirtDestroy
for each row
execute procedure rhn_avd_mod_trig_fun();

 070701000002CA000081B400000000000000000000000167AE111400000131000000000000000000000000000000000000003D00000000susemanager-schema/postgres/triggers/rhnActionVirtReboot.sql  
create or replace function rhn_avreboot_mod_trig_fun() returns trigger as
$$
begin
	new.modified := current_timestamp;
	return new;
end;
$$ language plpgsql;

create trigger
rhn_avreboot_mod_trig
before insert or update on rhnActionVirtReboot
for each row
execute procedure rhn_avreboot_mod_trig_fun();

   070701000002CB000081B400000000000000000000000167AE111400000135000000000000000000000000000000000000003E00000000susemanager-schema/postgres/triggers/rhnActionVirtRefresh.sql 
create or replace function rhn_avrefresh_mod_trig_fun() returns trigger as
$$
begin
	new.modified := current_timestamp;
	return new;
end;
$$ language plpgsql;

create trigger
rhn_avrefresh_mod_trig
before insert or update on rhnActionVirtRefresh
for each row
execute procedure rhn_avrefresh_mod_trig_fun();

   070701000002CC000081B400000000000000000000000167AE111400000139000000000000000000000000000000000000003D00000000susemanager-schema/postgres/triggers/rhnActionVirtResume.sql  
create or replace function rhn_avresume_mod_trig_fun()  returns trigger as
$$
begin
        new.modified := current_timestamp;
	return new;
end;
$$ language plpgsql;

create trigger
rhn_avresume_mod_trig
before insert or update on rhnActionVirtResume
for each row
execute procedure rhn_avresume_mod_trig_fun();

   070701000002CD000081B400000000000000000000000167AE111400000133000000000000000000000000000000000000004500000000susemanager-schema/postgres/triggers/rhnActionVirtSchedulePoller.sql  
create or replace function rhn_avsp_mod_trig_fun() returns trigger as
$$
begin
        new.modified := current_timestamp;
	return new;
end;
$$ language plpgsql;

create trigger
rhn_avsp_mod_trig
before insert or update on rhnActionVirtSchedulePoller
for each row
execute procedure rhn_avsp_mod_trig_fun();
 070701000002CE000081B400000000000000000000000167AE11140000012F000000000000000000000000000000000000004000000000susemanager-schema/postgres/triggers/rhnActionVirtSetMemory.sql   
create or replace function rhn_avsm_mod_trig_fun() returns trigger as
$$
begin
        new.modified := current_timestamp;
	return new;
end;
$$ language plpgsql;

create trigger
rhn_avsm_mod_trig
before insert or update on rhnActionVirtSetMemory
for each row
execute procedure rhn_avsm_mod_trig_fun();

 070701000002CF000081B400000000000000000000000167AE111400000140000000000000000000000000000000000000003F00000000susemanager-schema/postgres/triggers/rhnActionVirtShutdown.sql    
create or replace function rhn_avshutdown_mod_trig_fun() returns trigger as
$$
begin
        new.modified := current_timestamp;
	return new;
end;
$$ language plpgsql;

create trigger
rhn_avshutdown_mod_trig
before insert or update on rhnActionVirtShutdown
for each row
execute procedure rhn_avshutdown_mod_trig_fun();

070701000002D0000081B400000000000000000000000167AE111400000134000000000000000000000000000000000000003C00000000susemanager-schema/postgres/triggers/rhnActionVirtStart.sql   
create or replace function rhn_avstart_mod_trig_fun() returns trigger as
$$
begin
        new.modified := current_timestamp;
	return new;
end;
$$ language plpgsql;

create trigger
rhn_avstart_mod_trig
before insert or update on rhnActionVirtStart
for each row
execute procedure rhn_avstart_mod_trig_fun();

070701000002D1000081B400000000000000000000000167AE11140000013C000000000000000000000000000000000000003E00000000susemanager-schema/postgres/triggers/rhnActionVirtSuspend.sql 
create or replace function rhn_avsuspend_mod_trig_fun() returns trigger as
$$
begin
        new.modified := current_timestamp;
	return new;
end;
$$ language plpgsql;

create trigger
rhn_avsuspend_mod_trig
before insert or update on rhnActionVirtSuspend
for each row
execute procedure rhn_avsuspend_mod_trig_fun();

070701000002D2000081B400000000000000000000000167AE11140000012C000000000000000000000000000000000000003B00000000susemanager-schema/postgres/triggers/rhnActionVirtVcpu.sql    
create or replace function rhn_avcpu_mod_trig_fun() returns trigger as
$$
begin
        new.modified := current_timestamp;
	return new;
end;
$$ language plpgsql;

create trigger
rhn_avcpu_mod_trig
before insert or update on rhnActionVirtVcpu
for each row
execute procedure rhn_avcpu_mod_trig_fun();
070701000002D3000081B400000000000000000000000167AE11140000012A000000000000000000000000000000000000003A00000000susemanager-schema/postgres/triggers/rhnActivationKey.sql 
create or replace function rhn_act_key_mod_trig_fun() returns trigger as
$$
begin
	new.modified := current_timestamp;
	return new;
end;
$$ language plpgsql;

create trigger
rhn_act_key_mod_trig
before insert or update on rhnActivationKey
for each row
execute procedure rhn_act_key_mod_trig_fun();
  070701000002D4000081B400000000000000000000000167AE111400000137000000000000000000000000000000000000003500000000susemanager-schema/postgres/triggers/rhnArchType.sql  
create or replace function rhn_archtype_mod_trig_fun() returns trigger as
$$
begin
        new.modified := current_timestamp;
        return new;
end;
$$ language plpgsql;

create trigger
rhn_archtype_mod_trig
before insert or update on rhnArchType
for each row
execute procedure rhn_archtype_mod_trig_fun();

 070701000002D5000081B400000000000000000000000167AE11140000013B000000000000000000000000000000000000003C00000000susemanager-schema/postgres/triggers/rhnArchTypeActions.sql   
create or replace function rhn_archtypeacts_mod_trig_fun() returns trigger as
$$
begin
	new.modified := current_timestamp;
	return new;
end;
$$ language plpgsql;

create trigger
rhn_archtypeacts_mod_trig
before insert or update on rhnArchTypeActions
for each row
execute procedure rhn_archtypeacts_mod_trig_fun();
 070701000002D6000081B400000000000000000000000167AE111400000BA7000000000000000000000000000000000000003400000000susemanager-schema/postgres/triggers/rhnChannel.sql   
--
-- Copyright (c) 2008--2015 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--

create or replace function rhn_channel_mod_trig_fun() returns trigger as
$$
begin
	new.last_modified := current_timestamp;
	-- this is a really bad way of saying "if all we''re
        -- changing is the date"
        if tg_op='UPDATE' then
                if (old.id is distinct from new.id) or
                  (old.parent_channel is distinct from new.parent_channel) or
                  (old.org_id is distinct from new.org_id) or
                  (old.channel_arch_id is distinct from new.channel_arch_id) or
                  (old.label is distinct from new.label) or
                  (old.basedir is distinct from new.basedir) or
                  (old.name is distinct from new.name) or
                  (old.summary is distinct from new.summary) or
                  (old.description is distinct from new.description) then
                        new.modified := current_timestamp;
                end if;
        end if;
	return new;
	
end;
$$ language plpgsql;



create trigger
rhn_channel_mod_trig
before insert or update on rhnChannel
for each row
execute procedure rhn_channel_mod_trig_fun();


create or replace function rhn_channel_del_trig_fun() returns trigger as
$$
declare
        snapshot_curs_id	numeric;
begin
        for snapshot_curs_id in
                select  snapshot_id
                from    rhnSnapshotChannel
                where   channel_id = old.id
	loop
		update rhnSnapshot
                        set invalid = lookup_snapshot_invalid_reason('channel_removed')
                        where id = snapshot_curs_id;
                delete from rhnSnapshotChannel
                        where snapshot_id = snapshot_curs_id
                                and channel_id = old.id;
	end loop;

	return old;
	
end;
$$ language plpgsql;


create trigger
rhn_channel_del_trig
before delete on rhnChannel
for each row
execute procedure rhn_channel_del_trig_fun();


create or replace function rhn_channel_access_trig_fun() returns trigger as
$$
begin
   if old.channel_access = 'protected' and
      new.channel_access is distinct from 'protected'
   then
      delete from rhnChannelTrust where channel_id = old.id;
   end if;
   return null;
end;
$$ language plpgsql;



create trigger 
rhn_channel_access_trig
after update on rhnChannel
for each row
execute procedure rhn_channel_access_trig_fun();

 070701000002D7000081B400000000000000000000000167AE111400000131000000000000000000000000000000000000003800000000susemanager-schema/postgres/triggers/rhnChannelArch.sql   

create or replace function rhn_carch_mod_trig_fun() returns trigger as
$$
begin
        new.modified := current_timestamp;
        return new;
end;
$$ language plpgsql;

create trigger
rhn_carch_mod_trig
before insert or update on rhnChannelArch
for each row
execute procedure rhn_carch_mod_trig_fun();
   070701000002D8000081B400000000000000000000000167AE1114000005FB000000000000000000000000000000000000003A00000000susemanager-schema/postgres/triggers/rhnChannelCloned.sql --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

create or replace function rhn_channel_cloned_comps_trig_fun() returns trigger
as
$$
begin
	new.modified := current_timestamp;

	if tg_op = 'INSERT' then
		-- if there are not comps in the cloned channel by now,
		-- we shall clone comps from the original channel
		insert into rhnChannelComps
			( id, channel_id, comps_type_id, relative_filename,
				last_modified, created, modified )
		select nextval('rhn_channelcomps_id_seq'), new.id, comps_type_id, relative_filename,
				last_modified, current_timestamp, current_timestamp
		from rhnChannelComps
		where channel_id = new.original_id
			and not exists (
				select 1
				from rhnChannelComps x
				where x.channel_id = new.id
			);
	end if;
        return new;
end;
$$
language plpgsql;


create trigger
rhn_channel_cloned_comps_trig
before insert or update on rhnChannelCloned
for each row
execute procedure rhn_channel_cloned_comps_trig_fun();
 070701000002D9000081B400000000000000000000000167AE11140000028D000000000000000000000000000000000000003900000000susemanager-schema/postgres/triggers/rhnChannelComps.sql  


create or replace function rhn_channelcomps_mod_trig_fun() returns trigger as
$$
begin
        new.modified := current_timestamp;

        if tg_op='UPDATE' then
          if new.last_modified = old.last_modified or
             new.last_modified is null then
		new.last_modified := current_timestamp;
          end if;
        else
          if new.last_modified is null then
		new.last_modified := current_timestamp;
          end if;
        end if;

        return new;
end;
$$ language plpgsql;

create trigger
rhn_channelcomps_mod_trig
before insert or update on rhnChannelComps
for each row
execute procedure rhn_channelcomps_mod_trig_fun();

   070701000002DA000081B400000000000000000000000167AE11140000014E000000000000000000000000000000000000003A00000000susemanager-schema/postgres/triggers/rhnChannelErrata.sql 
create or replace function rhn_channel_errata_mod_trig_fun() returns trigger as
$$
begin
        new.modified := current_timestamp;

        return new;
end;
$$ language plpgsql;

create trigger
rhn_channel_errata_mod_trig
before insert or update on rhnChannelErrata
for each row
execute procedure rhn_channel_errata_mod_trig_fun();
  070701000002DB000081B400000000000000000000000167AE11140000014E000000000000000000000000000000000000003A00000000susemanager-schema/postgres/triggers/rhnChannelFamily.sql 
create or replace function rhn_channel_family_mod_trig_fun() returns trigger as
$$
begin
        new.modified := current_timestamp;

        return new;
end;
$$ language plpgsql;

create trigger
rhn_channel_family_mod_trig
before insert or update on rhnChannelFamily
for each row
execute procedure rhn_channel_family_mod_trig_fun();
  070701000002DC000081B400000000000000000000000167AE111400000147000000000000000000000000000000000000004100000000susemanager-schema/postgres/triggers/rhnChannelFamilyMembers.sql  

create or replace function rhn_cf_member_mod_trig_fun() returns trigger as
$$
begin
        new.modified := current_timestamp;

        return new;
end;
$$ language plpgsql;

create trigger
rhn_cf_member_mod_trig
before insert or update on rhnChannelFamilyMembers
for each row
execute procedure rhn_cf_member_mod_trig_fun();
 070701000002DD000081B400000000000000000000000167AE1114000003DA000000000000000000000000000000000000003B00000000susemanager-schema/postgres/triggers/rhnChannelPackage.sql    --
-- Copyright (c) 2008--2015 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
-- triggers for rhnChannelPackage

create or replace function rhn_channel_package_mod_trig_fun() returns trigger as
$$
begin
	new.modified := current_timestamp;
	return new;
end;
$$ language plpgsql;

create trigger
rhn_channel_package_mod_trig
before insert or update on rhnChannelPackage
for each row
execute procedure rhn_channel_package_mod_trig_fun();
  070701000002DE000081B400000000000000000000000167AE11140000013E000000000000000000000000000000000000004500000000susemanager-schema/postgres/triggers/rhnChannelPackageArchCompat.sql  
create or replace function rhn_cp_ac_mod_trig_fun() returns trigger as
$$
begin
        new.modified := current_timestamp;

        return new;
end;
$$ language plpgsql;

create trigger
rhn_cp_ac_mod_trig
before insert or update on rhnChannelPackageArchCompat
for each row
execute procedure rhn_cp_ac_mod_trig_fun();
  070701000002DF000081B400000000000000000000000167AE111400000137000000000000000000000000000000000000003E00000000susemanager-schema/postgres/triggers/rhnChannelPermission.sql 
create or replace function rhn_cperm_mod_trig_fun() returns trigger as
$$
begin
        new.modified := current_timestamp;

        return new;
end;
$$ language plpgsql;

create trigger
rhn_cperm_mod_trig
before insert or update on rhnChannelPermission
for each row
execute procedure rhn_cperm_mod_trig_fun();
 070701000002E0000081B400000000000000000000000167AE11140000014A000000000000000000000000000000000000004200000000susemanager-schema/postgres/triggers/rhnChannelPermissionRole.sql 
create or replace function rhn_cperm_role_mod_trig_fun() returns trigger as
$$
begin
        new.modified := current_timestamp;

        return new;
end;
$$ language plpgsql;

create trigger
rhn_cperm_role_mod_trig
before insert or update on rhnChannelPermissionRole
for each row
execute procedure rhn_cperm_role_mod_trig_fun();
  070701000002E1000081B400000000000000000000000167AE1114000003A6000000000000000000000000000000000000003900000000susemanager-schema/postgres/triggers/rhnChecksumType.sql  --
-- Copyright (c) 2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

create or replace function rhn_checksumtype_mod_trig_fun() returns trigger as
$$
begin
	new.modified := current_timestamp;
	return new;
end;
$$ language plpgsql;

create trigger
rhn_checksumtype_mod_trig
before insert or update on rhnChecksumType
for each row
execute procedure rhn_checksumtype_mod_trig_fun();

  070701000002E2000081B400000000000000000000000167AE111400000142000000000000000000000000000000000000003D00000000susemanager-schema/postgres/triggers/rhnClientCapability.sql  
create or replace function rhn_clientcap_mod_trig_fun() returns trigger as
$$
begin
        new.modified := current_timestamp;

        return new;
end;
$$ language plpgsql;

create trigger
rhn_clientcap_mod_trig
before insert or update on rhnClientCapability
for each row
execute procedure rhn_clientcap_mod_trig_fun();
  070701000002E3000081B400000000000000000000000167AE1114000006F7000000000000000000000000000000000000003A00000000susemanager-schema/postgres/triggers/rhnConfigChannel.sql 
--
-- Copyright (c) 2008--2015 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--
create or replace function rhn_confchan_mod_trig_fun() returns trigger as
$$
begin
	new.modified := current_timestamp;
	return new;
end;
$$ language plpgsql;



create trigger 
rhn_confchan_mod_trig
before insert or update on rhnConfigChannel
for each row
execute procedure rhn_confchan_mod_trig_fun();


create or replace function rhn_confchan_del_trig_fun() returns trigger as
$$
declare
        snapshot_curs_id numeric;
begin
        for snapshot_curs_id in
                select  snapshot_id as id
                from    rhnSnapshotConfigChannel
                where   config_channel_id = old.id
	loop
		update rhnSnapshot
                        set invalid = lookup_snapshot_invalid_reason('cc_removed')
                        where id = snapshot_curs_id;
                delete from rhnSnapshotConfigChannel
                        where snapshot_id = snapshot_curs_id
                                and config_channel_id = old.id;
		
	end loop;

	return old;
	        
end;
$$ language plpgsql;


create trigger 
rhn_confchan_del_trig
before delete on rhnConfigChannel
for each row
execute procedure rhn_confchan_del_trig_fun();

 070701000002E4000081B400000000000000000000000167AE11140000014C000000000000000000000000000000000000003E00000000susemanager-schema/postgres/triggers/rhnConfigChannelType.sql 
create or replace function rhn_confchantype_mod_trig_fun() returns trigger as
$$
begin
        new.modified := current_timestamp;
        return new;
end;
$$ language plpgsql;

create trigger
rhn_confchantype_mod_trig
before insert or update on rhnConfigChannelType
for each row
execute procedure rhn_confchantype_mod_trig_fun();

070701000002E5000081B400000000000000000000000167AE111400000145000000000000000000000000000000000000003A00000000susemanager-schema/postgres/triggers/rhnConfigContent.sql 
create or replace function rhn_confcontent_mod_trig_fun() returns trigger as
$$
begin
        new.modified := current_timestamp;

        return new;
end;
$$ language plpgsql;

create trigger
rhn_confcontent_mod_trig
before insert or update on rhnConfigContent
for each row
execute procedure rhn_confcontent_mod_trig_fun();
   070701000002E6000081B400000000000000000000000167AE111400000139000000000000000000000000000000000000003700000000susemanager-schema/postgres/triggers/rhnConfigFile.sql    
create or replace function rhn_conffile_mod_trig_fun() returns trigger as
$$
begin
        new.modified := current_timestamp;

        return new;
end;
$$ language plpgsql;

create trigger
rhn_conffile_mod_trig
before insert or update on rhnConfigFile
for each row
execute procedure rhn_conffile_mod_trig_fun();
   070701000002E7000081B400000000000000000000000167AE11140000014F000000000000000000000000000000000000003E00000000susemanager-schema/postgres/triggers/rhnConfigFileFailure.sql 
create or replace function rhn_conffile_fail_mod_trig_fun() returns trigger as
$$
begin
        new.modified := current_timestamp;
        return new;
end;
$$ language plpgsql;

create trigger
rhn_conffile_fail_mod_trig
before insert or update on rhnConfigFileFailure
for each row
execute procedure rhn_conffile_fail_mod_trig_fun();

 070701000002E8000081B400000000000000000000000167AE111400000137000000000000000000000000000000000000003B00000000susemanager-schema/postgres/triggers/rhnConfigFileName.sql    
create or replace function rhn_cfname_mod_trig_fun() returns trigger as
$$
begin
        new.modified := current_timestamp;
        return new;
end;
$$ language plpgsql;

create trigger
rhn_cfname_mod_trig
before insert or update on rhnConfigFileName
for each row
execute procedure rhn_cfname_mod_trig_fun();

 070701000002E9000081B400000000000000000000000167AE11140000013B000000000000000000000000000000000000003C00000000susemanager-schema/postgres/triggers/rhnConfigFileState.sql   
create or replace function rhn_cfstate_mod_trig_fun() returns trigger as
$$
begin
        new.modified := current_timestamp;

        return new;
end;
$$ language plpgsql;

create trigger
rhn_cfstate_mod_trig
before insert or update on rhnConfigFileState
for each row
execute procedure rhn_cfstate_mod_trig_fun();
 070701000002EA000081B400000000000000000000000167AE111400000149000000000000000000000000000000000000003B00000000susemanager-schema/postgres/triggers/rhnConfigFileType.sql    
create or replace function rhn_conffiletype_mod_trig_fun() returns trigger as
$$
begin
        new.modified := current_timestamp;

        return new;
end;
$$ language plpgsql;

create trigger
rhn_conffiletype_mod_trig
before insert or update on rhnConfigFileType
for each row
execute procedure rhn_conffiletype_mod_trig_fun();
   070701000002EB000081B400000000000000000000000167AE111400000139000000000000000000000000000000000000003700000000susemanager-schema/postgres/triggers/rhnConfigInfo.sql    
create or replace function rhn_confinfo_mod_trig_fun() returns trigger as
$$
begin
        new.modified := current_timestamp;

        return new;
end;
$$ language plpgsql;

create trigger
rhn_confinfo_mod_trig
before insert or update on rhnConfigInfo
for each row
execute procedure rhn_confinfo_mod_trig_fun();
   070701000002EC000081B400000000000000000000000167AE111400000649000000000000000000000000000000000000003B00000000susemanager-schema/postgres/triggers/rhnConfigRevision.sql    --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--


create or replace function rhn_confrevision_mod_trig_func() returns trigger as
$$
begin
	new.modified := current_timestamp;
	return new;
end;
$$ language plpgsql;


create trigger
rhn_confrevision_mod_trig
before insert or update on rhnConfigRevision
for each row
execute procedure rhn_confrevision_mod_trig_func();

create or replace function rhn_confrevision_del_trig_fun() returns trigger 
as
$$
declare
        cr_removed numeric := lookup_snapshot_invalid_reason('cr_removed');
begin
        update rhnSnapshot as s
           set invalid = cr_removed
          from rhnSnapshotConfigRevision as scr
         where s.id = scr.snapshot_id
           and scr.config_revision_id = old.id;
        delete from rhnSnapshotConfigRevision
         where config_revision_id = old.id;
        return old;
end;
$$ language plpgsql;


create trigger
rhn_confrevision_del_trig
before delete on rhnConfigRevision
for each row
execute procedure rhn_confrevision_del_trig_fun();
   070701000002ED000081B400000000000000000000000167AE11140000039C000000000000000000000000000000000000003A00000000susemanager-schema/postgres/triggers/rhnConfiguration.sql --
-- Copyright (c) 2014 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

create or replace function rhn_conf_mod_trig_fun() returns trigger as
$$
begin
        new.modified := current_timestamp;
        return new;
end;
$$ language plpgsql;

create trigger
rhn_conf_mod_trig
before insert or update on rhnConfiguration
for each row
execute procedure rhn_conf_mod_trig_fun();
070701000002EE000081B400000000000000000000000167AE1114000003B3000000000000000000000000000000000000003D00000000susemanager-schema/postgres/triggers/rhnContentSourceSsl.sql  --
-- Copyright (c) 2017 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


create or replace function rhn_cont_source_ssl_mod_trig_fun() returns trigger as
$$
begin
	new.modified := current_timestamp;
	return new;
end;
$$ language plpgsql;

create trigger
rhn_cont_source_ssl_mod_trig
before insert or update on rhnContentSourceSsl
for each row
execute procedure rhn_cont_source_ssl_mod_trig_fun();
 070701000002EF000081B400000000000000000000000167AE111400000327000000000000000000000000000000000000003000000000susemanager-schema/postgres/triggers/rhnCpu.sql   
create or replace function rhn_cpu_mod_trig_fun() returns trigger as
$$
begin
        new.modified := current_timestamp;

        return new;
end;
$$ language plpgsql;


create trigger
rhn_cpu_mod_trig
before insert or update on rhnCpu
for each row
execute procedure rhn_cpu_mod_trig_fun();

create or replace function rhn_cpu_up_trig_fun() returns trigger as
$$
begin
        update suseSCCRegCache
           set scc_reg_required = 'Y'
         where server_id = new.server_id;
	return new;
end;
$$ language plpgsql;

create trigger
rhn_cpu_up_trig
after update on rhnCpu
for each row
when (OLD.nrcpu is distinct from NEW.nrcpu OR OLD.nrsocket is distinct from NEW.nrsocket OR OLD.nrcore is distinct from NEW.nrcore OR OLD.nrthread is distinct from NEW.nrthread)
execute procedure rhn_cpu_up_trig_fun();
 070701000002F0000081B400000000000000000000000167AE111400000134000000000000000000000000000000000000003400000000susemanager-schema/postgres/triggers/rhnCpuArch.sql   
create or replace function rhn_cpuarch_mod_trig_fun() returns trigger as
$$
begin
        new.modified := current_timestamp;

        return new;
end;
$$ language plpgsql;


create trigger
rhn_cpuarch_mod_trig
before insert or update on rhnCpuArch
for each row
execute procedure rhn_cpuarch_mod_trig_fun();
070701000002F1000081B400000000000000000000000167AE11140000014C000000000000000000000000000000000000003A00000000susemanager-schema/postgres/triggers/rhnCryptoKeyType.sql 
create or replace function rhn_cryptokeytype_mod_trig_fun() returns trigger as
$$
begin
        new.modified := current_timestamp;

        return new;
end;
$$ language plpgsql;

create trigger
rhn_cryptokeytype_mod_trig
before insert or update on rhnCryptoKeyType
for each row
execute procedure rhn_cryptokeytype_mod_trig_fun();

070701000002F2000081B400000000000000000000000167AE11140000013E000000000000000000000000000000000000003A00000000susemanager-schema/postgres/triggers/rhnCustomDataKey.sql 

create or replace function rhn_cdatakey_mod_trig_fun() returns trigger as
$$
begin
        new.modified := current_timestamp;

        return new;
end;
$$ language plpgsql;

create trigger
rhn_cdatakey_mod_trig
before insert or update on rhnCustomDataKey
for each row
execute procedure rhn_cdatakey_mod_trig_fun();

  070701000002F3000081B400000000000000000000000167AE111400000132000000000000000000000000000000000000003300000000susemanager-schema/postgres/triggers/rhnDevice.sql    

create or replace function rhn_device_mod_trig_fun() returns trigger as
$$
begin
        new.modified := current_timestamp;

        return new;
end;
$$ language plpgsql;

create trigger
rhn_device_mod_trig
before insert or update on rhnDevice
for each row
execute procedure rhn_device_mod_trig_fun();


  070701000002F4000081B400000000000000000000000167AE1114000003EC000000000000000000000000000000000000003B00000000susemanager-schema/postgres/triggers/rhnDistChannelMap.sql    --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

create or replace function rhn_dist_channel_map_mod_trig_fun() returns trigger as
$$
begin
    if new.id is null then
        new.id := nextval('rhn_dcm_id_seq');
    end if;
    return new;
end;
$$ language plpgsql;

create trigger
rhn_dist_channel_map_mod_trig
before insert or update on rhnDistChannelMap
for each row
execute procedure rhn_dist_channel_map_mod_trig_fun();
070701000002F5000081B400000000000000000000000167AE1114000005C6000000000000000000000000000000000000003300000000susemanager-schema/postgres/triggers/rhnErrata.sql    
--
-- Copyright (c) 2008--2015 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--

create or replace function rhn_errata_ins_trig_fun() returns trigger
as
$$
begin
     if ( new.last_modified is null ) then
        new.last_modified := current_timestamp;
     end if;

     new.modified := current_timestamp;

     return new;
end;
$$ language plpgsql;

create trigger
rhn_errata_ins_trig
before insert on rhnErrata
for each row
execute procedure rhn_errata_ins_trig_fun();


create or replace function rhn_errata_upd_trig_fun() returns trigger
as
$$
begin
     if ( new.last_modified = old.last_modified ) or
        ( new.last_modified is null )  then
        new.last_modified := current_timestamp;
     end if;

     new.modified := current_timestamp;

     return new;
end;
$$ language plpgsql;

create trigger
rhn_errata_upd_trig
before update on rhnErrata
for each row
execute procedure rhn_errata_upd_trig_fun();
  070701000002F6000081B400000000000000000000000167AE11140000014F000000000000000000000000000000000000003A00000000susemanager-schema/postgres/triggers/rhnErrataBuglist.sql 
create or replace function rhn_errata_buglist_mod_trig_fun() returns trigger as
$$
begin
        new.modified := current_timestamp;

        return new;
end;
$$ language plpgsql;

create trigger
rhn_errata_buglist_mod_trig
before insert or update on rhnErrataBuglist
for each row
execute procedure rhn_errata_buglist_mod_trig_fun();

 070701000002F7000081B400000000000000000000000167AE11140000012F000000000000000000000000000000000000003600000000susemanager-schema/postgres/triggers/rhnErrataCVE.sql 
create or replace function rhn_errata_cve_mod_trig_fun() returns trigger as
$$
begin
	new.modified := current_timestamp;
	return new;
end;
$$ language plpgsql;

create trigger
rhn_errata_cve_mod_trig
before insert or update on rhnErrataCVE
for each row
execute procedure rhn_errata_cve_mod_trig_fun();
 070701000002F8000081B400000000000000000000000167AE111400000145000000000000000000000000000000000000003900000000susemanager-schema/postgres/triggers/rhnErrataCloned.sql  
create or replace function rhn_errataclone_mod_trig_fun() returns trigger as
$$
begin
        new.modified := current_timestamp;

        return new;
end;
$$ language plpgsql;

create trigger
rhn_errataclone_mod_trig
before insert or update on rhnErrataCloned
for each row
execute procedure rhn_errataclone_mod_trig_fun();

   070701000002F9000081B400000000000000000000000167AE111400000133000000000000000000000000000000000000003700000000susemanager-schema/postgres/triggers/rhnErrataFile.sql    
create or replace function rhn_errata_file_mod_trig_fun() returns trigger as
$$
begin
	new.modified := current_timestamp;
	return new;
end;
$$ language plpgsql;

create trigger
rhn_errata_file_mod_trig
before insert or update on rhnErrataFile
for each row
execute procedure rhn_errata_file_mod_trig_fun();
 070701000002FA000081B400000000000000000000000167AE11140000012B000000000000000000000000000000000000003E00000000susemanager-schema/postgres/triggers/rhnErrataFileChannel.sql 
create or replace function rhn_efilec_mod_trig_fun() returns trigger as
$$
begin
	new.modified := current_timestamp;
	return new;
end;
$$ language plpgsql;

create trigger
rhn_efilec_mod_trig
before insert or update on rhnErrataFileChannel
for each row
execute procedure rhn_efilec_mod_trig_fun();
 070701000002FB000081B400000000000000000000000167AE11140000012C000000000000000000000000000000000000003E00000000susemanager-schema/postgres/triggers/rhnErrataFilePackage.sql 
create or replace function rhn_efilep_mod_trig_fun() returns trigger as
$$
begin
	new.modified := current_timestamp;
	return new;
end;
$$ language plpgsql;

create trigger
rhn_efilep_mod_trig
before insert or update on rhnErrataFilePackage
for each row
execute procedure rhn_efilep_mod_trig_fun();

070701000002FC000081B400000000000000000000000167AE111400000134000000000000000000000000000000000000004400000000susemanager-schema/postgres/triggers/rhnErrataFilePackageSource.sql   
create or replace function rhn_efileps_mod_trig_fun() returns trigger as
$$
begin
	new.modified := current_timestamp;
	return new;
end;
$$ language plpgsql;

create trigger
rhn_efileps_mod_trig
before insert or update on rhnErrataFilePackageSource
for each row
execute procedure rhn_efileps_mod_trig_fun();
070701000002FD000081B400000000000000000000000167AE11140000013F000000000000000000000000000000000000003A00000000susemanager-schema/postgres/triggers/rhnErrataKeyword.sql 
create or replace function rhn_errata_keyword_mod_trig_fun() returns trigger as
$$
begin
	new.modified := current_timestamp;
	return new;
end;
$$ language plpgsql;

create trigger
rhn_errata_keyword_mod_trig
before insert or update on rhnErrataKeyword
for each row
execute procedure rhn_errata_keyword_mod_trig_fun();
 070701000002FE000081B400000000000000000000000167AE111400000134000000000000000000000000000000000000004400000000susemanager-schema/postgres/triggers/rhnErrataNotificationQueue.sql   
create or replace function rhn_enqueue_mod_trig_fun() returns trigger as
$$
begin
	new.modified := current_timestamp;
	return new;
end;
$$ language plpgsql;

create trigger
rhn_enqueue_mod_trig
before insert or update on rhnErrataNotificationQueue
for each row
execute procedure rhn_enqueue_mod_trig_fun();
070701000002FF000081B400000000000000000000000167AE11140000051B000000000000000000000000000000000000003A00000000susemanager-schema/postgres/triggers/rhnErrataPackage.sql 
--
-- Copyright (c) 2008--2015 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
-- 
--
--
-- triggers for rhnErrataPackage

create or replace function rhn_errata_package_mod_trig_fun() returns trigger
as
$$
begin
        if tg_op='INSERT' or tg_op='UPDATE' then
                new.modified := current_timestamp;
	        return new;
        end if;
        if tg_op='DELETE' then
                update rhnErrata
                set last_modified = current_timestamp
                where rhnErrata.id in ( old.errata_id );
	        return old;
        end if;
end;
$$ language plpgsql;




create trigger
rhn_errata_package_mod_trig
before insert or update or delete on rhnErrataPackage
for each row
execute procedure rhn_errata_package_mod_trig_fun();


 07070100000300000081B400000000000000000000000167AE11140000013F000000000000000000000000000000000000003500000000susemanager-schema/postgres/triggers/rhnFileList.sql  
create or replace function rhn_filelist_mod_trig_fun() returns trigger as
$$
begin
        new.modified := current_timestamp;
        
        return new;
end;
$$ language plpgsql;

create trigger
rhn_filelist_mod_trig
before insert or update on rhnFileList
for each row
execute procedure rhn_filelist_mod_trig_fun();
 07070100000301000081B400000000000000000000000167AE111400000149000000000000000000000000000000000000003C00000000susemanager-schema/postgres/triggers/rhnFileListMembers.sql   
create or replace function rhn_flmembers_mod_trig_fun() returns trigger as
$$
begin
        new.modified := current_timestamp;
        
        return new;
end;
$$ language plpgsql;

create trigger
rhn_flmembers_mod_trig
before insert or update on rhnFileListMembers
for each row
execute procedure rhn_flmembers_mod_trig_fun();
   07070100000302000081B400000000000000000000000167AE11140000012B000000000000000000000000000000000000003300000000susemanager-schema/postgres/triggers/rhnKSData.sql    
create or replace function rhn_ks_mod_trig_fun() returns trigger as
$$
begin
       new.modified := current_timestamp;
        
        return new;
end;
$$ language plpgsql;

create trigger
rhn_ks_mod_trig
before insert or update on rhnKSData
for each row
execute procedure rhn_ks_mod_trig_fun();

 07070100000303000081B400000000000000000000000167AE111400000153000000000000000000000000000000000000003A00000000susemanager-schema/postgres/triggers/rhnKSInstallType.sql 
create or replace function rhn_ksinstalltype_mod_trig_fun() returns trigger as
$$
begin
       new.modified := current_timestamp;
        
        return new;
end;
$$ language plpgsql;

create trigger
rhn_ksinstalltype_mod_trig
before insert or update on rhnKSInstallType
for each row
execute procedure rhn_ksinstalltype_mod_trig_fun();

 07070100000304000081B400000000000000000000000167AE111400000284000000000000000000000000000000000000003700000000susemanager-schema/postgres/triggers/rhnKSTreeFile.sql    
create or replace function rhn_kstreefile_mod_trig_fun() returns trigger as
$$
begin
        new.modified := current_timestamp;

        if tg_op='UPDATE' then
          if new.last_modified = old.last_modified or
             new.last_modified is null then
		new.last_modified := current_timestamp;
          end if;
        else
          if new.last_modified is null then
		new.last_modified := current_timestamp;
          end if;
        end if;

        return new;
end;
$$ language plpgsql;

create trigger
rhn_kstreefile_mod_trig
before insert or update on rhnKSTreeFile
for each row
execute procedure rhn_kstreefile_mod_trig_fun();


07070100000305000081B400000000000000000000000167AE111400000143000000000000000000000000000000000000004200000000susemanager-schema/postgres/triggers/rhnKickstartChildChannel.sql 
create or replace function rhn_ks_cc_mod_trig_fun() returns trigger as
$$
begin
       new.modified := current_timestamp;
        
        return new;
end;
$$ language plpgsql;

create trigger
rhn_ks_cc_mod_trig
before insert or update on rhnKickstartChildChannel
for each row
execute procedure rhn_ks_cc_mod_trig_fun();

 07070100000306000081B400000000000000000000000167AE11140000014B000000000000000000000000000000000000003D00000000susemanager-schema/postgres/triggers/rhnKickstartCommand.sql  
create or replace function rhn_kscommand_mod_trig_fun() returns trigger as
$$
begin
       new.modified := current_timestamp;
        
        return new;
end;
$$ language plpgsql;

create trigger
rhn_kscommand_mod_trig
before insert or update on rhnKickstartCommand
for each row
execute procedure rhn_kscommand_mod_trig_fun();


 07070100000307000081B400000000000000000000000167AE111400000146000000000000000000000000000000000000004500000000susemanager-schema/postgres/triggers/rhnKickstartDefaultRegToken.sql  
create or replace function rhn_ksdrt_mod_trig_fun() returns trigger as
$$
begin
       new.modified := current_timestamp;
        
        return new;
end;
$$ language plpgsql;

create trigger
rhn_ksdrt_mod_trig
before insert or update on rhnKickstartDefaultRegToken
for each row
execute procedure rhn_ksdrt_mod_trig_fun();

  07070100000308000081B400000000000000000000000167AE111400000139000000000000000000000000000000000000003E00000000susemanager-schema/postgres/triggers/rhnKickstartDefaults.sql 
create or replace function rhn_ksd_mod_trig_fun() returns trigger as
$$
begin
       new.modified := current_timestamp;
        
        return new;
end;
$$ language plpgsql;

create trigger
rhn_ksd_mod_trig
before insert or update on rhnKickstartDefaults
for each row
execute procedure rhn_ksd_mod_trig_fun();

   07070100000309000081B400000000000000000000000167AE11140000013D000000000000000000000000000000000000003D00000000susemanager-schema/postgres/triggers/rhnKickstartIPRange.sql  

create or replace function rhn_ksip_mod_trig_fun() returns trigger as
$$
begin
       new.modified := current_timestamp;
        
        return new;
end;
$$ language plpgsql;

create trigger
rhn_ksip_mod_trig
before insert or update on rhnKickstartIPRange
for each row
execute procedure rhn_ksip_mod_trig_fun();


   0707010000030A000081B400000000000000000000000167AE11140000014B000000000000000000000000000000000000003D00000000susemanager-schema/postgres/triggers/rhnKickstartPackage.sql  
create or replace function rhn_kspackage_mod_trig_fun() returns trigger as
$$
begin
       new.modified := current_timestamp;
        
        return new;
end;
$$ language plpgsql;

create trigger
rhn_kspackage_mod_trig
before insert or update on rhnKickstartPackage
for each row
execute procedure rhn_kspackage_mod_trig_fun();


 0707010000030B000081B400000000000000000000000167AE11140000015C000000000000000000000000000000000000004600000000susemanager-schema/postgres/triggers/rhnKickstartPreserveFileList.sql 
create or replace function rhn_kspreservefl_mod_trig_fun() returns trigger as
$$
begin
       new.modified := current_timestamp;
        
        return new;
end;
$$ language plpgsql;

create trigger
rhn_kspreservefl_mod_trig
before insert or update on rhnKickstartPreserveFileList
for each row
execute procedure rhn_kspreservefl_mod_trig_fun();

0707010000030C000081B400000000000000000000000167AE111400000130000000000000000000000000000000000000003C00000000susemanager-schema/postgres/triggers/rhnKickstartScript.sql   
create or replace function rhn_ksscript_mod_trig_fun() returns trigger as
$$
begin
	new.modified := current_timestamp;
	return new;
end;
$$ language plpgsql;

create trigger
rhn_ksscript_mod_trig
before insert or update on rhnKickstartScript
for each row
execute procedure rhn_ksscript_mod_trig_fun();

0707010000030D000081B400000000000000000000000167AE1114000008C6000000000000000000000000000000000000003D00000000susemanager-schema/postgres/triggers/rhnKickstartSession.sql  
--
-- Copyright (c) 2008--2015 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--


create or replace function rhn_ks_session_mod_trig_fun() returns trigger
as
$$
begin
        new.modified := current_timestamp;

        return new;
end;
$$ language plpgsql;

create trigger 
rhn_ks_session_mod_trig
before insert or update on rhnKickstartSession
for each row
execute procedure rhn_ks_session_mod_trig_fun();


create or replace function rhn_ks_session_history_trigger_fun() returns trigger
as
$$
begin
        if tg_op ='INSERT' then
                insert into rhnKickstartSessionHistory (
                                id, kickstart_session_id, action_id, state_id
                        ) values (
                                nextval('rhn_ks_sessionhist_id_seq'),
                                new.id,
                                new.action_id,
                                new.state_id
                        );
        end if;
        if tg_op ='UPDATE' then
          if new.state_id is distinct from old.state_id then
                insert into rhnKickstartSessionHistory (
                                id, kickstart_session_id, action_id, state_id
                        ) values (
                                nextval('rhn_ks_sessionhist_id_seq'),
                                new.id,
                                new.action_id,
                                new.state_id
                        );
          end if;
        end if;
        return new;
end;
$$ language plpgsql;




create trigger
rhn_ks_session_history_trigger
after insert or update on rhnKickstartSession
for each row
execute procedure rhn_ks_session_history_trigger_fun();


  0707010000030E000081B400000000000000000000000167AE111400000160000000000000000000000000000000000000004400000000susemanager-schema/postgres/triggers/rhnKickstartSessionHistory.sql   
create or replace function rhn_ks_sessionhist_mod_trig_fun() returns trigger as
$$
begin
       new.modified := current_timestamp;
        
        return new;
end;
$$ language plpgsql;

create trigger
rhn_ks_sessionhist_mod_trig
before insert or update on rhnKickstartSessionHistory
for each row
execute procedure rhn_ks_sessionhist_mod_trig_fun();

0707010000030F000081B400000000000000000000000167AE111400000164000000000000000000000000000000000000004200000000susemanager-schema/postgres/triggers/rhnKickstartSessionState.sql 
create or replace function rhn_ks_session_state_mod_trig_fun() returns trigger as
$$
begin
       new.modified := current_timestamp;
        
        return new;
end;
$$ language plpgsql;

create trigger
rhn_ks_session_state_mod_trig
before insert or update on rhnKickstartSessionState
for each row
execute procedure rhn_ks_session_state_mod_trig_fun();

07070100000310000081B400000000000000000000000167AE1114000007C1000000000000000000000000000000000000003E00000000susemanager-schema/postgres/triggers/rhnKickstartableTree.sql --
-- Copyright (c) 2008--2014 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

create or replace function rhn_kstree_mod_trig_fun() returns trigger as
$$
begin
        if tg_op='UPDATE' then
                -- Basically if we're changing something other than cobbler_id,
                -- cobbler_xen_id, and last_modified - or if last_modified is
                -- explicity set to null. Gets complicated because we have
                -- to allow for the possibility of the ids being null
                if ((not old.cobbler_id is null and new.cobbler_id = old.cobbler_id)
                        or (old.cobbler_id is null and new.cobbler_id is null))
                    and ((not old.cobbler_xen_id is null and new.cobbler_xen_id = old.cobbler_xen_id)
                        or (old.cobbler_xen_id is null and new.cobbler_xen_id is null))
                    and new.last_modified = old.last_modified
                    or new.last_modified is null
                then
                    new.last_modified := current_timestamp;
                end if;
        elseif tg_op='INSERT' and new.last_modified is null then
                new.last_modified := current_timestamp;
        end if;

        new.modified := current_timestamp;

        return new;
end;
$$ language plpgsql;

create trigger
rhn_kstree_mod_trig
before insert or update on rhnKickstartableTree
for each row
execute procedure rhn_kstree_mod_trig_fun();

   07070100000311000081B400000000000000000000000167AE111400000154000000000000000000000000000000000000003F00000000susemanager-schema/postgres/triggers/rhnOrgChannelSettings.sql    
create or replace function rhn_orgcsettings_mod_trig_fun() returns trigger as
$$
begin
       new.modified := current_timestamp;
        
       return new;
end;
$$ language plpgsql;

create trigger
rhn_orgcsettings_mod_trig
before insert or update on rhnOrgChannelSettings
for each row
execute procedure rhn_orgcsettings_mod_trig_fun();

07070100000312000081B400000000000000000000000167AE111400000167000000000000000000000000000000000000004300000000susemanager-schema/postgres/triggers/rhnOrgChannelSettingsType.sql    
create or replace function rhn_orgcsettings_type_mod_trig_fun() returns trigger as
$$
begin
       new.modified := current_timestamp;
        
       return new;
end;
$$ language plpgsql;

create trigger
rhn_orgcsettings_type_mod_trig
before insert or update on rhnOrgChannelSettingsType
for each row
execute procedure rhn_orgcsettings_type_mod_trig_fun();

 07070100000313000081B400000000000000000000000167AE1114000003AB000000000000000000000000000000000000003D00000000susemanager-schema/postgres/triggers/rhnOrgConfiguration.sql  --
-- Copyright (c) 2013 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

create or replace function rhn_org_conf_mod_trig_fun() returns trigger as
$$
begin
        new.modified := current_timestamp;
        return new;
end;
$$ language plpgsql;

create trigger
rhn_org_conf_mod_trig
before insert or update on rhnOrgConfiguration
for each row
execute procedure rhn_org_conf_mod_trig_fun();
 07070100000314000081B400000000000000000000000167AE11140000042A000000000000000000000000000000000000003F00000000susemanager-schema/postgres/triggers/rhnOrgExtGroupMapping.sql    --
-- Copyright (c) 2014 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

create or replace function rhn_userorgextgrmap_mod_trig_fun() returns trigger as
$$
begin
        if new.id is null then
            new.id := nextval('rhn_orgextgroupmap_seq');
        end if;
        new.modified := current_timestamp;
        return new;
end;
$$ language plpgsql;

create trigger
rhn_userorgextgrmap_mod_trig
before insert or update on rhnOrgExtGroupMapping
for each row
execute procedure rhn_userorgextgrmap_mod_trig_fun();
  07070100000315000081B400000000000000000000000167AE1114000009DF000000000000000000000000000000000000003400000000susemanager-schema/postgres/triggers/rhnPackage.sql   --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--

create or replace function rhn_package_mod_trig_fun() returns trigger as
$$
begin
    -- when we do a sat sync, we use last_modified to keep track
    -- of the upstream modification date.  So if we're setting
    -- it explicitly, don't override with sysdate.  But if we're
    -- not changing it, then this is a genuine update that needs
    -- tracking.
    --
    -- we're not using is_satellite() here instead, because we
    -- might want to use this to keep webdev in sync.
    if tg_op='UPDATE' then
      if new.last_modified = old.last_modified or
         new.last_modified is null then
           new.last_modified := current_timestamp;
      end if;
    else
      if new.last_modified is null then
           new.last_modified := current_timestamp;
      end if;
    end if;
    new.modified := current_timestamp;

    -- bz 619337 if we are updating the checksum, we need to
    -- update the last modified time on all the channels the package is in
    if tg_op='UPDATE' then
        if new.checksum_id != old.checksum_id then
            update rhnChannel
              set last_modified = current_timestamp
              where id in (select channel_id
                              from rhnChannelPackage
                              where package_id = new.id);
            insert into rhnRepoRegenQueue (id, CHANNEL_LABEL, REASON)
                   (select nextval('rhn_repo_regen_queue_id_seq'), C.label, 'checksum modification'
                    from rhnChannel C inner join
                         rhnChannelPackage CP on CP.channel_id = C.id
                    where CP.package_id = new.id);
            delete from rhnPackageRepodata where package_id = new.id;
        end if;
    end if;

    return new;
end;
$$ language plpgsql;

create trigger
rhn_package_mod_trig
before insert or update on rhnPackage
for each row
execute procedure rhn_package_mod_trig_fun();

 07070100000316000081B400000000000000000000000167AE111400000139000000000000000000000000000000000000003800000000susemanager-schema/postgres/triggers/rhnPackageArch.sql   
create or replace function rhn_parch_mod_trig_fun() returns trigger as
$$
begin
       new.modified := current_timestamp;
        
       return new;
end;
$$ language plpgsql;

create trigger
rhn_parch_mod_trig
before insert or update on rhnPackageArch
for each row
execute procedure rhn_parch_mod_trig_fun();


   07070100000317000081B400000000000000000000000167AE1114000002E4000000000000000000000000000000000000003A00000000susemanager-schema/postgres/triggers/rhnPackageBreaks.sql --
-- Copyright (c) 2010 Novell, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
--

create or replace function rhn_pkg_brks_mod_trig_fun() returns trigger as
$$
begin
	new.modified := current_timestamp;

	return new;
end;
$$ language plpgsql;

create trigger
rhn_pkg_brks_mod_trig
before insert or update on rhnPackageBreaks
for each row
execute procedure rhn_pkg_brks_mod_trig_fun();

07070100000318000081B400000000000000000000000167AE111400000159000000000000000000000000000000000000003E00000000susemanager-schema/postgres/triggers/rhnPackageCapability.sql 
create or replace function rhn_pkg_capability_mod_trig_fun() returns trigger as
$$
begin
       new.modified := current_timestamp;
        
       return new;
end;
$$ language plpgsql;

create trigger
rhn_pkg_capability_mod_trig
before insert or update on rhnPackageCapability
for each row
execute procedure rhn_pkg_capability_mod_trig_fun();

   07070100000319000081B400000000000000000000000167AE1114000003CA000000000000000000000000000000000000004000000000susemanager-schema/postgres/triggers/rhnPackageChangeLogRec.sql   --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

create or replace function rhn_package_clog_rec_mod_trig_fun() returns trigger as
$$
begin
       new.modified := current_timestamp;
       return new;
end;
$$ language plpgsql;

create trigger
rhn_package_clog_rec_mod_trig
before insert or update on rhnPackageChangeLogRec
for each row
execute procedure rhn_package_clog_rec_mod_trig_fun();
  0707010000031A000081B400000000000000000000000167AE111400000148000000000000000000000000000000000000003D00000000susemanager-schema/postgres/triggers/rhnPackageConflicts.sql  
create or replace function rhn_pkg_conflicts_mod_trig_fun() returns trigger as
$$
begin
	new.modified := current_timestamp;
       
	return new;
end;
$$ language plpgsql;

create trigger
rhn_pkg_conflicts_mod_trig
before insert or update on rhnPackageConflicts
for each row
execute procedure rhn_pkg_conflicts_mod_trig_fun();

0707010000031B000081B400000000000000000000000167AE11140000029F000000000000000000000000000000000000003000000000susemanager-schema/postgres/triggers/rhnRam.sql   
create or replace function rhn_ram_mod_trig_fun() returns trigger as
$$
begin
	new.modified := current_timestamp;
	       
	return new;
end;
$$ language plpgsql;

create trigger
rhn_ram_mod_trig
before insert or update on rhnRam
for each row
execute procedure rhn_ram_mod_trig_fun();

create or replace function rhn_ram_up_trig_fun() returns trigger as
$$
begin
        update suseSCCRegCache
           set scc_reg_required = 'Y'
         where server_id = new.server_id;
        return new;
end;
$$ language plpgsql;

create trigger
rhn_ram_up_trig
after update on rhnRam
for each row
when (OLD.ram is distinct from NEW.ram)
execute procedure rhn_ram_up_trig_fun();


 0707010000031C000081B400000000000000000000000167AE111400000142000000000000000000000000000000000000003900000000susemanager-schema/postgres/triggers/rhnPackageDelta.sql  

create or replace function rhn_packagedelta_mod_trig_fun() returns trigger as
$$
begin
	new.modified := current_timestamp;
       
	return new;
end;
$$ language plpgsql;

create trigger
rhn_packagedelta_mod_trig
before insert or update on rhnPackageDelta
for each row
execute procedure rhn_packagedelta_mod_trig_fun();

  0707010000031D000081B400000000000000000000000167AE1114000002E2000000000000000000000000000000000000003C00000000susemanager-schema/postgres/triggers/rhnPackageEnhances.sql   --
-- Copyright (c) 2013 Novell, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
--

create or replace function rhn_pkg_enh_mod_trig_fun() returns trigger as
$$
begin
	new.modified := current_timestamp;

	return new;
end;
$$ language plpgsql;

create trigger
rhn_pkg_enh_mod_trig
before insert or update on rhnPackageEnhances
for each row
execute procedure rhn_pkg_enh_mod_trig_fun();
  0707010000031E000081B400000000000000000000000167AE111400000080000000000000000000000000000000000000003700000000susemanager-schema/postgres/triggers/rhnPackageEvr.sql    
create trigger
rhn_pack_evr_no_updel_trig
before update or delete on rhnPackageEvr
execute procedure no_operation_trig_fun();

0707010000031F000081B400000000000000000000000167AE11140000013D000000000000000000000000000000000000003800000000susemanager-schema/postgres/triggers/rhnPackageFile.sql   
create or replace function rhn_packagefile_mod_trig_fun() returns trigger as
$$
begin
	new.modified := current_timestamp;
       
	return new;
end;
$$ language plpgsql;

create trigger
rhn_packagefile_mod_trig
before insert or update on rhnPackageFile
for each row
execute procedure rhn_packagefile_mod_trig_fun();

   07070100000320000081B400000000000000000000000167AE111400000144000000000000000000000000000000000000003900000000susemanager-schema/postgres/triggers/rhnPackageGroup.sql  
create or replace function rhn_package_group_mod_trig_fun() returns trigger as
$$
begin
	new.modified := current_timestamp;
       
	return new;
end;
$$ language plpgsql;

create trigger
rhn_package_group_mod_trig
before insert or update on rhnPackageGroup
for each row
execute procedure rhn_package_group_mod_trig_fun();

07070100000321000081B400000000000000000000000167AE111400000132000000000000000000000000000000000000003700000000susemanager-schema/postgres/triggers/rhnPackageKey.sql    


create or replace function rhn_pkg_gpg_mod_trig_fun() returns trigger as
$$
begin
	new.modified := current_timestamp;
       
	return new;
end;
$$ language plpgsql;

create trigger
rhn_pkg_gpg_mod_trig
before insert or update on rhnPackageKey
for each row
execute procedure rhn_pkg_gpg_mod_trig_fun();

  07070100000322000081B400000000000000000000000167AE111400000143000000000000000000000000000000000000003B00000000susemanager-schema/postgres/triggers/rhnPackageKeyType.sql    
create or replace function rhn_pkg_key_type_mod_trig_fun() returns trigger as
$$
begin
	new.modified := current_timestamp;
       
	return new;
end;
$$ language plpgsql;

create trigger
rhn_pkg_key_type_mod_trig
before insert or update on rhnPackageKeyType
for each row
execute procedure rhn_pkg_key_type_mod_trig_fun();

 07070100000323000081B400000000000000000000000167AE11140000014A000000000000000000000000000000000000003D00000000susemanager-schema/postgres/triggers/rhnPackageObsoletes.sql  

create or replace function rhn_pkg_obsoletes_mod_trig_fun() returns trigger as
$$
begin
	new.modified := current_timestamp;
       
	return new;
end;
$$ language plpgsql;

create trigger
rhn_pkg_obsoletes_mod_trig
before insert or update on rhnPackageObsoletes
for each row
execute procedure rhn_pkg_obsoletes_mod_trig_fun();


  07070100000324000081B400000000000000000000000167AE1114000002E8000000000000000000000000000000000000003E00000000susemanager-schema/postgres/triggers/rhnPackagePredepends.sql --
-- Copyright (c) 2010 Novell, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
--

create or replace function rhn_pkg_pdep_mod_trig_fun() returns trigger as
$$
begin
	new.modified := current_timestamp;

	return new;
end;
$$ language plpgsql;

create trigger
rhn_pkg_pdep_mod_trig
before insert or update on rhnPackagePredepends
for each row
execute procedure rhn_pkg_pdep_mod_trig_fun();

07070100000325000081B400000000000000000000000167AE111400000143000000000000000000000000000000000000003C00000000susemanager-schema/postgres/triggers/rhnPackageProvider.sql   
create or replace function rhn_pkg_provider_mod_trig_fun() returns trigger as
$$
begin
	new.modified := current_timestamp;
       
	return new;
end;
$$ language plpgsql;

create trigger
rhn_pkg_provider_mod_trig
before insert or update on rhnPackageProvider
for each row
execute procedure rhn_pkg_provider_mod_trig_fun();
 07070100000326000081B400000000000000000000000167AE111400000143000000000000000000000000000000000000003C00000000susemanager-schema/postgres/triggers/rhnPackageProvides.sql   
create or replace function rhn_pkg_provides_mod_trig_fun() returns trigger as
$$
begin
	new.modified := current_timestamp;
       
	return new;
end;
$$ language plpgsql;

create trigger
rhn_pkg_provides_mod_trig
before insert or update on rhnPackageProvides
for each row
execute procedure rhn_pkg_provides_mod_trig_fun();
 07070100000327000081B400000000000000000000000167AE1114000002E5000000000000000000000000000000000000003E00000000susemanager-schema/postgres/triggers/rhnPackageRecommends.sql --
-- Copyright (c) 2010 Novell, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
--

create or replace function rhn_pkg_rec_mod_trig_fun() returns trigger as
$$
begin
	new.modified := current_timestamp;

	return new;
end;
$$ language plpgsql;

create trigger
rhn_pkg_rec_mod_trig
before insert or update on rhnPackageRecommends
for each row
execute procedure rhn_pkg_rec_mod_trig_fun();

   07070100000328000081B400000000000000000000000167AE111400000144000000000000000000000000000000000000003C00000000susemanager-schema/postgres/triggers/rhnPackageRequires.sql   
create or replace function rhn_pkg_requires_mod_trig_fun() returns trigger as
$$
begin
	new.modified := current_timestamp;
       
	return new;
end;
$$ language plpgsql;

create trigger
rhn_pkg_requires_mod_trig
before insert or update on rhnPackageRequires
for each row
execute procedure rhn_pkg_requires_mod_trig_fun();

07070100000329000081B400000000000000000000000167AE111400000159000000000000000000000000000000000000003A00000000susemanager-schema/postgres/triggers/rhnPackageSource.sql 
create or replace function rhn_pkgsrc_mod_trig_fun() returns trigger as
$$
begin
	new.modified := current_timestamp;
	new.last_modified := current_timestamp;
       
	return new;
end;
$$ language plpgsql;

create trigger
rhn_pkgsrc_mod_trig
before insert or update on rhnPackageSource
for each row
execute procedure rhn_pkgsrc_mod_trig_fun();

   0707010000032A000081B400000000000000000000000167AE1114000002E6000000000000000000000000000000000000003C00000000susemanager-schema/postgres/triggers/rhnPackageSuggests.sql   --
-- Copyright (c) 2010 Novell, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
--

create or replace function rhn_pkg_sugg_mod_trig_fun() returns trigger as
$$
begin
	new.modified := current_timestamp;

	return new;
end;
$$ language plpgsql;

create trigger
rhn_pkg_sugg_mod_trig
before insert or update on rhnPackageSuggests
for each row
execute procedure rhn_pkg_sugg_mod_trig_fun();

  0707010000032B000081B400000000000000000000000167AE1114000002E9000000000000000000000000000000000000003F00000000susemanager-schema/postgres/triggers/rhnPackageSupplements.sql    --
-- Copyright (c) 2010 Novell, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
--

create or replace function rhn_pkg_supp_mod_trig_fun() returns trigger as
$$
begin
	new.modified := current_timestamp;

	return new;
end;
$$ language plpgsql;

create trigger
rhn_pkg_supp_mod_trig
before insert or update on rhnPackageSupplements
for each row
execute procedure rhn_pkg_supp_mod_trig_fun();

   0707010000032C000081B400000000000000000000000167AE11140000014C000000000000000000000000000000000000004100000000susemanager-schema/postgres/triggers/rhnPackageSyncBlacklist.sql  
create or replace function rhn_packagesyncbl_mod_trig_fun() returns trigger as
$$
begin
	new.modified := current_timestamp;
       
	return new;
end;
$$ language plpgsql;

create trigger
rhn_packagesyncbl_mod_trig
before insert or update on rhnPackageSyncBlacklist
for each row
execute procedure rhn_packagesyncbl_mod_trig_fun();

0707010000032D000081B400000000000000000000000167AE1114000003B8000000000000000000000000000000000000004100000000susemanager-schema/postgres/triggers/rhnPrivateChannelFamily.sql  
--
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--

create or replace function rhn_privcf_mod_trig_fun() returns trigger
as
$$
begin
    new.modified := current_timestamp;

    return new;
end;
$$
language plpgsql;


create trigger
rhn_privcf_mod_trig
before insert or update on rhnPrivateChannelFamily
for each row
execute procedure rhn_privcf_mod_trig_fun();



0707010000032E000081B400000000000000000000000167AE111400000137000000000000000000000000000000000000003800000000susemanager-schema/postgres/triggers/rhnProductName.sql   

create or replace function product_name_mod_trig_fun() returns trigger as
$$
begin
	new.modified := current_timestamp;
	       
	return new;
end;
$$ language plpgsql;

create trigger
product_name_mod_trig
before insert or update on rhnProductName
for each row
execute procedure product_name_mod_trig_fun();


 0707010000032F000081B400000000000000000000000167AE11140000013F000000000000000000000000000000000000003B00000000susemanager-schema/postgres/triggers/rhnProvisionState.sql    
create or replace function rhn_provstate_mod_trig_fun() returns trigger as
$$
begin
        new.modified := current_timestamp;
        return new;
end;
$$ language plpgsql;

create trigger
rhn_provstate_mod_trig
before insert or update on rhnProvisionState
for each row
execute procedure rhn_provstate_mod_trig_fun();
 07070100000330000081B400000000000000000000000167AE111400000305000000000000000000000000000000000000003600000000susemanager-schema/postgres/triggers/rhnProxyInfo.sql --
-- Copyright (c) 2022 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- triggers for suseImageInfo

CREATE OR REPLACE FUNCTION rhn_proxy_info_mod_trig_fun() RETURNS TRIGGER AS
$$
BEGIN
    new.modified := current_timestamp;
    return new;
END;
$$ LANGUAGE PLPGSQL;

CREATE TRIGGER rhn_proxy_info_mod_trig BEFORE INSERT OR UPDATE ON rhnProxyInfo
    FOR EACH ROW EXECUTE PROCEDURE rhn_proxy_info_mod_trig_fun();
   07070100000331000081B400000000000000000000000167AE111400000133000000000000000000000000000000000000003700000000susemanager-schema/postgres/triggers/rhnPushClient.sql    
create or replace function rhn_pclient_mod_trig_fun() returns trigger as
$$
begin
	new.modified := current_timestamp;
	       
	return new;
end;
$$ language plpgsql;

create trigger
rhn_pclient_mod_trig
before insert or update on rhnPushClient
for each row
execute procedure rhn_pclient_mod_trig_fun();



 07070100000332000081B400000000000000000000000167AE111400000148000000000000000000000000000000000000003C00000000susemanager-schema/postgres/triggers/rhnPushClientState.sql   
create or replace function rhn_pclient_state_mod_trig_fun() returns trigger as
$$
begin
	new.modified := current_timestamp;
	       
	return new;
end;
$$ language plpgsql;

create trigger
rhn_pclient_state_mod_trig
before insert or update on rhnPushClientState
for each row
execute procedure rhn_pclient_state_mod_trig_fun();

07070100000333000081B400000000000000000000000167AE111400000144000000000000000000000000000000000000003B00000000susemanager-schema/postgres/triggers/rhnPushDispatcher.sql    
create or replace function rhn_pushdispatch_mod_trig_fun() returns trigger as
$$
begin
	new.modified := current_timestamp;
	       
	return new;
end;
$$ language plpgsql;

create trigger
rhn_pushdispatch_mod_trig
before insert or update on rhnPushDispatcher
for each row
execute procedure rhn_pushdispatch_mod_trig_fun();

07070100000334000081B400000000000000000000000167AE1114000001A7000000000000000000000000000000000000003B00000000susemanager-schema/postgres/triggers/rhnRepoRegenQueue.sql    
create or replace function rhn_repo_regen_queue_mod_trig_fun() returns trigger as
$$
begin
	if new.id is null then
		new.id := nextval('rhn_repo_regen_queue_id_seq');
	end if;

	new.modified := current_timestamp;
	       
	return new;
end;
$$ language plpgsql;

create trigger
rhn_repo_regen_queue_mod_trig
before insert or update on rhnRepoRegenQueue
for each row
execute procedure rhn_repo_regen_queue_mod_trig_fun();


 07070100000335000081B400000000000000000000000167AE111400000135000000000000000000000000000000000000003A00000000susemanager-schema/postgres/triggers/rhnResetPassword.sql 
create or replace function rhn_rstpwd_mod_trig_fun() returns trigger as
$$
begin
        new.modified := current_timestamp;
        return new;
end;
$$ language plpgsql;

create trigger
rhn_rstpwd_mod_trig
before insert or update on rhnResetPassword
for each row
execute procedure rhn_rstpwd_mod_trig_fun();
   07070100000336000081B400000000000000000000000167AE1114000002CD000000000000000000000000000000000000003300000000susemanager-schema/postgres/triggers/rhnServer.sql    
create or replace function rhn_server_mod_trig_fun() returns trigger as
$$
begin
        new.modified := current_timestamp;
        return new;
end;
$$ language plpgsql;

create trigger
rhn_server_mod_trig
before insert or update on rhnServer
for each row
execute procedure rhn_server_mod_trig_fun();


create or replace function rhn_server_up_trig_fun() returns trigger as
$$
begin
	update suseSCCRegCache
	  set scc_reg_required = 'Y'
	where server_id = old.id;
       return new;
end;
$$ language plpgsql;

create trigger
rhn_server_up_trig
after update on rhnServer
for each row
when (OLD.hostname is distinct from NEW.hostname or OLD.payg is distinct from NEW.payg)
execute procedure rhn_server_up_trig_fun();

   07070100000337000081B400000000000000000000000167AE111400000391000000000000000000000000000000000000003900000000susemanager-schema/postgres/triggers/rhnServerAction.sql  
create or replace function rhn_server_action_mod_trig_fun() returns trigger as
$$
declare
        handle_status   numeric;
begin
        new.modified := current_timestamp;
        handle_status := 0;
        if TG_OP = 'UPDATE' then
                if new.status is distinct from old.status then
                        handle_status := 1;
                end if;
        else
                handle_status := 1;
        end if;

        if handle_status = 1 then
                if new.status = 1 then
                        new.pickup_time := current_timestamp;
                elsif new.status = 2 then
                        new.completion_time := current_timestamp;
                end if;
        end if;

        return new;
end;
$$ language plpgsql;

create trigger
rhn_server_action_mod_trig
before insert or update on rhnServerAction
for each row
execute procedure rhn_server_action_mod_trig_fun();

   07070100000338000081B400000000000000000000000167AE111400000149000000000000000000000000000000000000004600000000susemanager-schema/postgres/triggers/rhnServerActionPackageResult.sql 
create or replace function rhn_sap_result_mod_trig_fun() returns trigger as
$$
begin
	new.modified := current_timestamp;
	       
	return new;
end;
$$ language plpgsql;

create trigger
rhn_sap_result_mod_trig
before insert or update on rhnServerActionPackageResult
for each row
execute procedure rhn_sap_result_mod_trig_fun();

   07070100000339000081B400000000000000000000000167AE111400000157000000000000000000000000000000000000004500000000susemanager-schema/postgres/triggers/rhnServerActionScriptResult.sql  
create or replace function rhn_serveras_result_mod_trig_fun() returns trigger as
$$
begin
	new.modified := current_timestamp;
	       
	return new;
end;
$$ language plpgsql;

create trigger
rhn_serveras_result_mod_trig
before insert or update on rhnServerActionScriptResult
for each row
execute procedure rhn_serveras_result_mod_trig_fun();

 0707010000033A000081B400000000000000000000000167AE11140000013E000000000000000000000000000000000000004600000000susemanager-schema/postgres/triggers/rhnServerActionVerifyMissing.sql 
create or replace function rhn_sactionvm_mod_trig_fun() returns trigger as
$$
begin
	new.modified := current_timestamp;
 	return new;
end;
$$ language plpgsql;

create trigger
rhn_sactionvm_mod_trig
before insert or update on rhnServerActionVerifyMissing
for each row
execute procedure rhn_sactionvm_mod_trig_fun();

  0707010000033B000081B400000000000000000000000167AE11140000013C000000000000000000000000000000000000004500000000susemanager-schema/postgres/triggers/rhnServerActionVerifyResult.sql  
create or replace function rhn_sactionvr_mod_trig_fun() returns trigger as
$$
begin
	new.modified := current_timestamp;
 	return new;
end;
$$ language plpgsql;

create trigger
rhn_sactionvr_mod_trig
before insert or update on rhnServerActionVerifyResult
for each row
execute procedure rhn_sactionvr_mod_trig_fun();
0707010000033C000081B400000000000000000000000167AE111400000130000000000000000000000000000000000000003700000000susemanager-schema/postgres/triggers/rhnServerArch.sql    
create or replace function rhn_sarch_mod_trig_fun() returns trigger as
$$
begin
        new.modified := current_timestamp;
        return new;
end;
$$ language plpgsql;

create trigger
rhn_sarch_mod_trig
before insert or update on rhnServerArch
for each row
execute procedure rhn_sarch_mod_trig_fun();

0707010000033D000081B400000000000000000000000167AE1114000003CC000000000000000000000000000000000000003A00000000susemanager-schema/postgres/triggers/rhnServerChannel.sql 
--
-- Copyright (c) 2008--2015 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--


create or replace function rhn_server_channel_mod_trig_fun() returns trigger
as
$$
begin
        new.modified := current_timestamp;

	return new;
end;
$$
language plpgsql;


create trigger
rhn_server_channel_mod_trig
before insert or update on rhnServerChannel
for each row
execute procedure rhn_server_channel_mod_trig_fun();




0707010000033E000081B400000000000000000000000167AE111400000130000000000000000000000000000000000000004400000000susemanager-schema/postgres/triggers/rhnServerChannelArchCompat.sql   
create or replace function rhn_sc_ac_mod_trig_fun() returns trigger as
$$
begin
	new.modified := current_timestamp;
 	return new;
end;
$$ language plpgsql;

create trigger
rhn_sc_ac_mod_trig
before insert or update on rhnServerChannelArchCompat
for each row
execute procedure rhn_sc_ac_mod_trig_fun();

0707010000033F000081B400000000000000000000000167AE111400000136000000000000000000000000000000000000004000000000susemanager-schema/postgres/triggers/rhnServerConfigChannel.sql   
create or replace function rhn_servercc_mod_trig_fun() returns trigger as
$$
begin
	new.modified := current_timestamp;
 	return new;
end;
$$ language plpgsql;

create trigger
rhn_servercc_mod_trig
before insert or update on rhnServerConfigChannel
for each row
execute procedure rhn_servercc_mod_trig_fun();


  07070100000340000081B400000000000000000000000167AE11140000012B000000000000000000000000000000000000004200000000susemanager-schema/postgres/triggers/rhnServerCustomDataValue.sql 
create or replace function rhn_scdv_mod_trig_fun() returns trigger as
$$
begin
	new.modified := current_timestamp;
 	return new;
end;
$$ language plpgsql;

create trigger
rhn_scdv_mod_trig
before insert or update on rhnServerCustomDataValue
for each row
execute procedure rhn_scdv_mod_trig_fun();

 07070100000341000081B400000000000000000000000167AE111400000131000000000000000000000000000000000000003600000000susemanager-schema/postgres/triggers/rhnServerDMI.sql 
create or replace function rhn_server_dmi_mod_trig_fun() returns trigger as
$$
begin
	new.modified := current_timestamp;
 	return new;
end;
$$ language plpgsql;

create trigger
rhn_server_dmi_mod_trig
before insert or update on rhnServerDMI
for each row
execute procedure rhn_server_dmi_mod_trig_fun();

   07070100000342000081B400000000000000000000000167AE111400000397000000000000000000000000000000000000003800000000susemanager-schema/postgres/triggers/rhnServerEvent.sql   

--
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--

create or replace function rhn_se_mod_trig_fun() returns trigger as
$$
begin
    new.modified := current_timestamp;
    return new;
end;
$$ language plpgsql;

create trigger rhn_se_mod_trig
before insert or update
on rhnServerEvent
for each row
execute procedure rhn_se_mod_trig_fun();

 07070100000343000081B400000000000000000000000167AE111400000390000000000000000000000000000000000000003700000000susemanager-schema/postgres/triggers/rhnServerFQDN.sql    

--
-- Copyright (c) 2018 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

create or replace function rhn_sfqdn_mod_trig_fun() returns trigger as
$$
begin
    new.modified := current_timestamp;
    return new;
end;
$$ language plpgsql;

create trigger rhn_fqdn_mod_trig
before insert or update
on rhnServerFQDN
for each row
execute procedure rhn_sfqdn_mod_trig_fun();
07070100000344000081B400000000000000000000000167AE1114000009E5000000000000000000000000000000000000003800000000susemanager-schema/postgres/triggers/rhnServerGroup.sql   --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--

create or replace function rhn_server_group_mod_trig_fun() returns trigger 
as
$$

begin
        new.modified := current_timestamp;

        return new;
end;
$$ language plpgsql;


create trigger
rhn_server_group_mod_trig
before insert or update on rhnServerGroup
for each row
execute procedure rhn_server_group_mod_trig_fun();


CREATE OR REPLACE FUNCTION rhn_server_group_creation_fun() RETURNS TRIGGER
AS
$$
DECLARE
        org_admin_group      NUMERIC;
        org_id_val           NUMERIC;
BEGIN
        org_id_val := new.org_id;

        SELECT UG.id INTO org_admin_group
          FROM rhnUserGroup UG,
               rhnUserGroupType UGT
         WHERE UGT.label = 'org_admin'
           AND UGT.id = UG.group_type
           AND UG.org_id = org_id_val;

           IF NOT FOUND THEN
		PERFORM rhn_exception.raise_exception_val('no_org_admin_group', org_id_val);
           END IF;
        RETURN new;

END;
$$ LANGUAGE PLPGSQL;


CREATE TRIGGER
rhn_server_group_creation
AFTER INSERT ON rhnServerGroup
FOR EACH ROW
EXECUTE PROCEDURE rhn_server_group_creation_fun();



create or replace function rhn_sg_del_trig_fun() returns trigger
as
$$
declare
        snapshot_curs_id	numeric;
begin
	for snapshot_curs_id in
                select  snapshot_id
                from    rhnSnapshotServerGroup
                where   server_group_id = old.id
                order by snapshot_id
	loop
		update rhnSnapshot
                        set invalid = lookup_snapshot_invalid_reason('sg_removed')
                        where id = snapshot_curs_id;
                delete from rhnSnapshotServerGroup
                        where snapshot_id = snapshot_curs_id
                                and server_group_id = old.id;
		
	end loop;

	return old;
 end;
 $$
 language plpgsql;

create trigger
rhn_sg_del_trig
before delete on rhnServerGroup
for each row
execute procedure rhn_sg_del_trig_fun();
   07070100000345000081B400000000000000000000000167AE1114000006A2000000000000000000000000000000000000003F00000000susemanager-schema/postgres/triggers/rhnServerGroupMembers.sql    
--
-- Copyright (c) 2008--2015 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--
create or replace function rhn_sg_member_mod_trig_fun() returns trigger
as
$$
begin
        new.modified := current_timestamp;

        return new;
end;
$$
language plpgsql;


create trigger
rhn_sg_member_mod_trig
before insert or update on rhnServerGroupMembers
for each row
execute procedure rhn_sg_member_mod_trig_fun();

CREATE OR REPLACE FUNCTION rhn_server_group_org_mapping_fun() RETURNS TRIGGER
AS
$$
DECLARE
        same_org        NUMERIC;
BEGIN
    same_org := 0;

    SELECT 1 INTO same_org
    FROM rhnServer S, rhnServerGroup SG
    WHERE SG.org_id = S.org_id
    AND S.id = new.server_id
    AND SG.id = new.server_group_id;

    IF same_org = 0 THEN
        PERFORM rhn_exception.raise_exception('sgm_insert_diff_orgs');
    END IF;

    IF NOT FOUND THEN
        PERFORM rhn_exception.raise_exception('sgm_insert_diff_orgs');
    END IF;

    return new;
END;
$$
LANGUAGE PLPGSQL;

CREATE TRIGGER
rhn_server_group_org_mapping
BEFORE INSERT OR UPDATE ON rhnServerGroupMembers
FOR EACH ROW
EXECUTE PROCEDURE rhn_server_group_org_mapping_fun();
  07070100000346000081B400000000000000000000000167AE111400000140000000000000000000000000000000000000003A00000000susemanager-schema/postgres/triggers/rhnServerHistory.sql 

create or replace function rhn_serverhistory_mod_trig_fun() returns trigger as
$$
begin
	new.modified := current_timestamp;
 	return new;
end;
$$ language plpgsql;

create trigger
rhn_serverhistory_mod_trig
before insert or update on rhnServerHistory
for each row
execute procedure rhn_serverhistory_mod_trig_fun();


07070100000347000081B400000000000000000000000167AE1114000003E4000000000000000000000000000000000000003700000000susemanager-schema/postgres/triggers/rhnServerInfo.sql    

--
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--

create or replace function rhn_server_info_mod_trig_fun() returns trigger as
$$
begin
    if new.checkin is NULL
    then
        new.checkin := current_timestamp;
    end if;
    return new;
end;
$$ language plpgsql;

create trigger rhn_server_info_mod_trig
before insert or update
on rhnServerInfo
for each row
execute procedure rhn_server_info_mod_trig_fun();

07070100000348000081B400000000000000000000000167AE11140000013E000000000000000000000000000000000000003E00000000susemanager-schema/postgres/triggers/rhnServerInstallInfo.sql 

create or replace function rhn_s_inst_info_mod_trig_fun() returns trigger as
$$
begin
	new.modified := current_timestamp;
 	return new;
end;
$$ language plpgsql;

create trigger
rhn_s_inst_info_mod_trig
before insert or update on rhnServerInstallInfo
for each row
execute procedure rhn_s_inst_info_mod_trig_fun();


  07070100000349000081B400000000000000000000000167AE111400000143000000000000000000000000000000000000003B00000000susemanager-schema/postgres/triggers/rhnServerLocation.sql    
create or replace function rhn_serverlocation_mod_trig_fun() returns trigger as
$$
begin
	new.modified := current_timestamp;
 	return new;
end;
$$ language plpgsql;

create trigger
rhn_serverlocation_mod_trig
before insert or update on rhnServerLocation
for each row
execute procedure rhn_serverlocation_mod_trig_fun();


 0707010000034A000081B400000000000000000000000167AE111400000199000000000000000000000000000000000000003F00000000susemanager-schema/postgres/triggers/rhnServerNetInterface.sql    create or replace function rhn_srv_net_iface_mod_trig_fun() returns trigger as
$$
begin
    if new.id is null then
	new.id := nextval('rhn_srv_net_iface_id_seq');
    end if;
	new.modified := current_timestamp;
 	return new;
end;
$$ language plpgsql;

create trigger
rhn_srv_net_iface_mod_trig
before insert or update on rhnServerNetInterface
for each row
execute procedure rhn_srv_net_iface_mod_trig_fun();

   0707010000034B000081B400000000000000000000000167AE111400000136000000000000000000000000000000000000003800000000susemanager-schema/postgres/triggers/rhnServerNotes.sql   
create or replace function rhn_servernotes_mod_trig_fun() returns trigger as
$$
begin
	new.modified := current_timestamp;
 	return new;
end;
$$ language plpgsql;

create trigger
rhn_servernotes_mod_trig
before insert or update on rhnServerNotes
for each row
execute procedure rhn_servernotes_mod_trig_fun();

  0707010000034C000081B400000000000000000000000167AE111400000131000000000000000000000000000000000000004400000000susemanager-schema/postgres/triggers/rhnServerPackageArchCompat.sql   
create or replace function rhn_sp_ac_mod_trig_fun() returns trigger as
$$
begin
	new.modified := current_timestamp;
 	return new;
end;
$$ language plpgsql;

create trigger
rhn_sp_ac_mod_trig
before insert or update on rhnServerPackageArchCompat
for each row
execute procedure rhn_sp_ac_mod_trig_fun();


   0707010000034D000081B400000000000000000000000167AE111400000133000000000000000000000000000000000000003700000000susemanager-schema/postgres/triggers/rhnServerPath.sql    
create or replace function rhn_serverpath_mod_trig_fun() returns trigger as
$$
begin
	new.modified := current_timestamp;
 	return new;
end;
$$ language plpgsql;

create trigger
rhn_serverpath_mod_trig
before insert or update on rhnServerPath
for each row
execute procedure rhn_serverpath_mod_trig_fun();


 0707010000034E000081B400000000000000000000000167AE11140000013C000000000000000000000000000000000000004300000000susemanager-schema/postgres/triggers/rhnServerPreserveFileList.sql    
create or replace function rhn_serverpfl_mod_trig_fun() returns trigger as
$$
begin
	new.modified := current_timestamp;
 	return new;
end;
$$ language plpgsql;

create trigger
rhn_serverpfl_mod_trig
before insert or update on rhnServerPreserveFileList
for each row
execute procedure rhn_serverpfl_mod_trig_fun();


0707010000034F000081B400000000000000000000000167AE111400000138000000000000000000000000000000000000003E00000000susemanager-schema/postgres/triggers/rhnServerProfileType.sql 

create or replace function rhn_sproftype_mod_trig_fun() returns trigger as
$$
begin
	new.modified := current_timestamp;
 	return new;
end;
$$ language plpgsql;

create trigger
rhn_sproftype_mod_trig
before insert or update on rhnServerProfileType
for each row
execute procedure rhn_sproftype_mod_trig_fun();


07070100000350000081B400000000000000000000000167AE111400000139000000000000000000000000000000000000004800000000susemanager-schema/postgres/triggers/rhnServerServerGroupArchCompat.sql   
create or replace function rhn_ssg_ac_mod_trig_fun() returns trigger as
$$
begin
	new.modified := current_timestamp;
 	return new;
end;
$$ language plpgsql;

create trigger
rhn_ssg_ac_mod_trig
before insert or update on rhnServerServerGroupArchCompat
for each row
execute procedure rhn_ssg_ac_mod_trig_fun();



   07070100000351000081B400000000000000000000000167AE11140000015F000000000000000000000000000000000000003C00000000susemanager-schema/postgres/triggers/rhnSnapshotChannel.sql   
create or replace function rhn_snapchan_mod_trig_fun() returns trigger as
$$
begin
	update rhnSnapshot set modified = current_timestamp where id = new.snapshot_id;
 	return new;
end;
$$ language plpgsql;

create trigger
rhn_snapchan_mod_trig
before insert or update on rhnSnapshotChannel
for each row
execute procedure rhn_snapchan_mod_trig_fun();


 07070100000352000081B400000000000000000000000167AE11140000013D000000000000000000000000000000000000004200000000susemanager-schema/postgres/triggers/rhnSnapshotConfigChannel.sql 
create or replace function rhn_snapshotcc_mod_trig_fun() returns trigger as
$$
begin
	new.modified = current_timestamp;
 	return new;
end;
$$ language plpgsql;

create trigger
rhn_snapshotcc_mod_trig
before insert or update on rhnSnapshotConfigChannel
for each row
execute procedure rhn_snapshotcc_mod_trig_fun();


   07070100000353000081B400000000000000000000000167AE11140000013F000000000000000000000000000000000000004300000000susemanager-schema/postgres/triggers/rhnSnapshotConfigRevision.sql    

create or replace function rhn_snapshotcr_mod_trig_fun() returns trigger as
$$
begin
	new.modified = current_timestamp;
 	return new;
end;
$$ language plpgsql;

create trigger
rhn_snapshotcr_mod_trig
before insert or update on rhnSnapshotConfigRevision
for each row
execute procedure rhn_snapshotcr_mod_trig_fun();


 07070100000354000081B400000000000000000000000167AE11140000013A000000000000000000000000000000000000004200000000susemanager-schema/postgres/triggers/rhnSnapshotInvalidReason.sql 
create or replace function rhn_ssinvalid_mod_trig_fun() returns trigger as
$$
begin
	new.modified = current_timestamp;
 	return new;
end;
$$ language plpgsql;

create trigger
rhn_ssinvalid_mod_trig
before insert or update on rhnSnapshotInvalidReason
for each row
execute procedure rhn_ssinvalid_mod_trig_fun();


  07070100000355000081B400000000000000000000000167AE111400000169000000000000000000000000000000000000003C00000000susemanager-schema/postgres/triggers/rhnSnapshotPackage.sql   

create or replace function rhn_snapshotpkg_mod_trig_fun() returns trigger as
$$
begin
	update rhnSnapshot set modified = current_timestamp where id = new.snapshot_id;
 	return new;
end;
$$ language plpgsql;

create trigger
rhn_snapshotpkg_mod_trig
before insert or update on rhnSnapshotPackage
for each row
execute procedure rhn_snapshotpkg_mod_trig_fun();


   07070100000356000081B400000000000000000000000167AE11140000016A000000000000000000000000000000000000004000000000susemanager-schema/postgres/triggers/rhnSnapshotServerGroup.sql   

create or replace function rhn_snapshotsg_mod_trig_fun() returns trigger as
$$
begin
	update rhnSnapshot set modified = current_timestamp where id = new.snapshot_id;
 	return new;
end;
$$ language plpgsql;

create trigger
rhn_snapshotsg_mod_trig
before insert or update on rhnSnapshotServerGroup
for each row
execute procedure rhn_snapshotsg_mod_trig_fun();


  07070100000357000081B400000000000000000000000167AE111400000127000000000000000000000000000000000000003800000000susemanager-schema/postgres/triggers/rhnSnapshotTag.sql   
create or replace function rhn_ss_tag_mod_trig_fun() returns trigger as
$$
begin
	new.modified = current_timestamp;
 	return new;
end;
$$ language plpgsql;

create trigger
rhn_ss_tag_mod_trig
before insert or update on rhnSnapshotTag
for each row
execute procedure rhn_ss_tag_mod_trig_fun();


 07070100000358000081B400000000000000000000000167AE111400000125000000000000000000000000000000000000003900000000susemanager-schema/postgres/triggers/rhnSsmOperation.sql  
create or replace function rhn_ssmop_mod_trig_fun() returns trigger as
$$
begin
	new.modified = current_timestamp;
 	return new;
end;
$$ language plpgsql;

create trigger
rhn_ssmop_mod_trig
before insert or update on rhnSsmOperation
for each row
execute procedure rhn_ssmop_mod_trig_fun();


   07070100000359000081B400000000000000000000000167AE111400000116000000000000000000000000000000000000003000000000susemanager-schema/postgres/triggers/rhnTag.sql   
create or replace function rhn_tag_mod_trig_fun() returns trigger as
$$
begin
	new.modified = current_timestamp;
 	return new;
end;
$$ language plpgsql;

create trigger
rhn_tag_mod_trig
before insert or update on rhnTag
for each row
execute procedure rhn_tag_mod_trig_fun();


  0707010000035A000081B400000000000000000000000167AE111400000117000000000000000000000000000000000000003400000000susemanager-schema/postgres/triggers/rhnTagName.sql   
create or replace function rhn_tn_mod_trig_fun() returns trigger as
$$
begin
	new.modified = current_timestamp;
 	return new;
end;
$$ language plpgsql;

create trigger
rhn_tn_mod_trig
before insert or update on rhnTagName
for each row
execute procedure rhn_tn_mod_trig_fun();


 0707010000035B000081B400000000000000000000000167AE11140000013E000000000000000000000000000000000000003D00000000susemanager-schema/postgres/triggers/rhnTemplateCategory.sql  
create or replace function rhn_template_cat_mod_trig_fun() returns trigger as
$$
begin
	new.modified = current_timestamp;
 	return new;
end;
$$ language plpgsql;

create trigger
rhn_template_cat_mod_trig
before insert or update on rhnTemplateCategory
for each row
execute procedure rhn_template_cat_mod_trig_fun();


  0707010000035C000081B400000000000000000000000167AE11140000013C000000000000000000000000000000000000003B00000000susemanager-schema/postgres/triggers/rhnTemplateString.sql    
create or replace function rhn_template_str_mod_trig_fun() returns trigger as
$$
begin
	new.modified = current_timestamp;
 	return new;
end;
$$ language plpgsql;

create trigger
rhn_template_str_mod_trig
before insert or update on rhnTemplateString
for each row
execute procedure rhn_template_str_mod_trig_fun();


0707010000035D000081B400000000000000000000000167AE1114000003E7000000000000000000000000000000000000004100000000susemanager-schema/postgres/triggers/rhnTransactionOperation.sql  
--
-- Copyright (c) 2008--2015 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
-- triggers for rhnTransactionOperation


create or replace function rhn_transop_mod_trig_fun() returns trigger
as
$$
begin
        new.modified := current_timestamp;

        return new;
end;
$$
language plpgsql;



create trigger
rhn_transop_mod_trig
before insert or update on rhnTransactionOperation
for each row
execute procedure rhn_transop_mod_trig_fun();
 0707010000035E000081B400000000000000000000000167AE1114000003AA000000000000000000000000000000000000003900000000susemanager-schema/postgres/triggers/rhnUserExtGroup.sql  --
-- Copyright (c) 2014 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

create or replace function rhn_userextgr_mod_trig_fun() returns trigger as
$$
begin
        new.modified := current_timestamp;
        return new;
end;
$$ language plpgsql;

create trigger
rhn_userextgr_mod_trig
before insert or update on rhnUserExtGroup
for each row
execute procedure rhn_userextgr_mod_trig_fun();
  0707010000035F000081B400000000000000000000000167AE111400000423000000000000000000000000000000000000004000000000susemanager-schema/postgres/triggers/rhnUserExtGroupMapping.sql   --
-- Copyright (c) 2014 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

create or replace function rhn_userextgrmap_mod_trig_fun() returns trigger as
$$
begin
        if new.id is null then
            new.id := nextval('rhn_userextgroupmap_seq');
        end if;
        new.modified := current_timestamp;
        return new;
end;
$$ language plpgsql;

create trigger
rhn_userextgrmap_mod_trig
before insert or update on rhnUserExtGroupMapping
for each row
execute procedure rhn_userextgrmap_mod_trig_fun();
 07070100000360000081B400000000000000000000000167AE1114000003BE000000000000000000000000000000000000003600000000susemanager-schema/postgres/triggers/rhnUserGroup.sql 
--
-- Copyright (c) 2008--2015 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--

create or replace function rhn_user_group_mod_trig_fun() returns trigger
as
$$
begin
        new.modified := current_timestamp;

        return new;
end;
$$ language plpgsql;

create trigger
rhn_user_group_mod_trig
before insert or update on rhnUserGroup
for each row
execute procedure rhn_user_group_mod_trig_fun();

  07070100000361000081B400000000000000000000000167AE111400000AC8000000000000000000000000000000000000003D00000000susemanager-schema/postgres/triggers/rhnUserGroupMembers.sql  
--
-- Copyright (c) 2008--2015 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--
create or replace function rhn_ug_member_mod_trig_fun() returns trigger
as
$$
declare
        ug              rhnUserGroup%ROWTYPE;
begin
        new.modified := current_timestamp;

        if tg_op='INSERT'then
                select
                        * into ug
                from
                        rhnUserGroup
                where
                        id = new.user_group_id;

                if ug.max_members is not null and
                ug.current_members+1 > ug.max_members then
                        perform rhn_exception.raise_exception('usergroup_max_members');
                end if;

                update rhnUserGroup
                set current_members = current_members + 1
                where id = new.user_group_id;
        end if;

        return new;
end;
$$
language plpgsql;

create trigger
rhn_ug_member_mod_trig
before insert or update on rhnUserGroupMembers
for each row
execute procedure rhn_ug_member_mod_trig_fun();


CREATE OR REPLACE FUNCTION rhn_user_group_org_mapping_fun() RETURNS TRIGGER
AS
$$
DECLARE
        same_org        NUMERIC;
BEGIN
        same_org := 0;
        SELECT 1 INTO same_org
          FROM web_contact U, rhnUserGroup UG
         WHERE UG.org_id = U.org_id
           AND U.id = new.user_id
           AND UG.id = new.user_group_id;

        IF same_org = 0 THEN
          perform rhn_exception.raise_exception('ugm_different_orgs');
        END IF;

        IF NOT FOUND THEN 
		PERFORM rhn_exception.raise_exception('ugm_different_orgs');
        END IF;

	return new;

END;
$$
LANGUAGE PLPGSQL;


CREATE TRIGGER
rhn_user_group_org_mapping
BEFORE INSERT OR UPDATE ON rhnUserGroupMembers
FOR EACH ROW
EXECUTE PROCEDURE rhn_user_group_org_mapping_fun();


create or replace function rhn_ug_member_del_trig_fun() returns trigger
as
$$
begin
        update rhnUserGroup
        set current_members = current_members - 1
        where id = old.user_group_id;

        return old;
end;
$$
language plpgsql;

create trigger
rhn_ug_member_del_trig
before delete on rhnUserGroupMembers
for each row
execute procedure rhn_ug_member_del_trig_fun();

07070100000362000081B400000000000000000000000167AE1114000003DE000000000000000000000000000000000000003500000000susemanager-schema/postgres/triggers/rhnUserInfo.sql  
--
-- Copyright (c) 2008--2015 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--
-- triggers for rhnUserInfo updates
--

create or replace function rhn_user_info_mod_trig_fun() returns trigger
as
$$
begin
        new.modified := current_timestamp;

	return new;
end;
$$ language plpgsql;


create trigger
rhn_user_info_mod_trig
before insert or update on rhnUserInfo
for each row
execute procedure rhn_user_info_mod_trig_fun();




  07070100000363000081B400000000000000000000000167AE11140000012E000000000000000000000000000000000000003900000000susemanager-schema/postgres/triggers/rhnUserReserved.sql  
create or replace function rhn_user_res_mod_trig_fun() returns trigger as
$$
begin
	new.modified = current_timestamp;
 	return new;
end;
$$ language plpgsql;

create trigger
rhn_user_res_mod_trig
before insert or update on rhnUserreserved
for each row
execute procedure rhn_user_res_mod_trig_fun();


  07070100000364000081B400000000000000000000000167AE111400000155000000000000000000000000000000000000003C00000000susemanager-schema/postgres/triggers/rhnUserServerPrefs.sql   
create or replace function rhn_u_s_prefs_mod_trig_fun() returns trigger as
$$
begin
	new.modified = current_timestamp;
	new.value := upper (new.value);
 	return new;
end;
$$ language plpgsql;

create trigger
rhn_u_s_prefs_mod_trig
before insert or update on rhnUserServerPrefs
for each row
execute procedure rhn_u_s_prefs_mod_trig_fun();


   07070100000365000081B400000000000000000000000167AE111400000137000000000000000000000000000000000000003800000000susemanager-schema/postgres/triggers/rhnVersionInfo.sql   
create or replace function rhn_versioninfo_mod_trig_fun() returns trigger as
$$
begin
	new.modified = current_timestamp;

 	return new;
end;
$$ language plpgsql;

create trigger
rhn_versioninfo_mod_trig
before insert or update on rhnVersionInfo
for each row
execute procedure rhn_versioninfo_mod_trig_fun();


 07070100000366000081B400000000000000000000000167AE11140000078D000000000000000000000000000000000000003C00000000susemanager-schema/postgres/triggers/rhnVirtualInstance.sql   
--
-- Copyright (c) 2008--2016 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
-- 
--

create or replace function rhn_virtinst_mod_trig_fun() returns trigger
as
$$
begin
        new.modified := current_timestamp;

	return new;
end;
$$
language plpgsql;


create trigger
rhn_virtinst_mod_trig
before insert or update on rhnVirtualInstance
for each row
execute procedure rhn_virtinst_mod_trig_fun();

create or replace function rhn_virtinst_iud_trig_fun() returns trigger
as
$$
begin
        if tg_op='INSERT' or tg_op='UPDATE' then
                if new.host_system_id is not null and new.virtual_system_id is not null then
                        update suseSCCRegCache
                           set scc_reg_required = 'Y'
                         where server_id = new.host_system_id;
                end if;
                return new;
        end if;
        if tg_op='DELETE' then
                if old.host_system_id is not null and old.virtual_system_id is not null then
                        update suseSCCRegCache
                           set scc_reg_required = 'Y'
                         where server_id = old.host_system_id;
                end if;
                return old;
        end if;
end;
$$ language plpgsql;


create trigger
rhn_virtinst_iud_trig
after insert or update or delete on rhnVirtualInstance
execute procedure rhn_virtinst_iud_trig_fun();
   07070100000367000081B400000000000000000000000167AE111400000204000000000000000000000000000000000000004000000000susemanager-schema/postgres/triggers/rhnVirtualInstanceInfo.sql   create or replace function rhn_virtinst_info_iud_trig_fun() returns trigger as
$$
begin
        update suseSCCRegCache
           set scc_reg_required = 'Y'
         where server_id = (select virtual_system_id from rhnvirtualinstance WHERE id = new.instance_id);
        return new;
end;
$$ language plpgsql;

create trigger
rhn_virtinst_info_iud_trig
after update on rhnVirtualInstanceInfo
for each row
when (OLD.instance_type is distinct from NEW.instance_type)
execute procedure rhn_virtinst_info_iud_trig_fun();
07070100000368000081B400000000000000000000000167AE111400000149000000000000000000000000000000000000003900000000susemanager-schema/postgres/triggers/suseAnsiblePath.sql  CREATE OR REPLACE function suse_ansible_path_mod_trig_fun() RETURNS TRIGGER AS
$$
BEGIN
        new.modified := current_timestamp;
        RETURN new;
END;
$$ language plpgsql;

CREATE TRIGGER
suse_ansible_path_mod_trig
BEFORE INSERT OR UPDATE ON suseAnsiblePath
FOR EACH ROW
EXECUTE PROCEDURE suse_ansible_path_mod_trig_fun();

   07070100000369000081B400000000000000000000000167AE11140000048A000000000000000000000000000000000000003C00000000susemanager-schema/postgres/triggers/suseDeltaImageInfo.sql   --
-- Copyright (c) 2022 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- triggers for suseImageInfo

CREATE OR REPLACE FUNCTION suse_delta_image_info_mod_trig_fun() RETURNS TRIGGER AS
$$
BEGIN
	new.modified := current_timestamp;
	return new;
END;
$$ LANGUAGE PLPGSQL;

CREATE TRIGGER suse_delta_image_info_mod_trig BEFORE INSERT OR UPDATE ON suseDeltaImageInfo
  FOR EACH ROW EXECUTE PROCEDURE suse_delta_image_info_mod_trig_fun();

CREATE OR REPLACE FUNCTION suse_delta_image_info_image_removed_trig_fun() RETURNS TRIGGER AS $$
BEGIN
  DELETE FROM suseSaltPillar WHERE id = OLD.pillar_id;
  RETURN OLD;
END $$ LANGUAGE PLPGSQL;

CREATE TRIGGER suse_delta_image_info_image_removed_trig AFTER DELETE ON suseDeltaImageInfo
  FOR EACH ROW EXECUTE PROCEDURE suse_delta_image_info_image_removed_trig_fun();
  0707010000036A000081B400000000000000000000000167AE11140000049E000000000000000000000000000000000000003700000000susemanager-schema/postgres/triggers/suseImageInfo.sql    --
-- Copyright (c) 2017 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- triggers for suseImageInfo

create or replace function suse_imginfo_mod_trig_fun() returns trigger as
$$
begin
	new.modified := current_timestamp;
	return new;
end;
$$ language plpgsql;

create trigger
suse_imginfo_mod_trig
before insert or update on suseImageInfo
for each row
execute procedure suse_imginfo_mod_trig_fun();

CREATE OR REPLACE FUNCTION suse_image_info_image_removed_trig_fun() RETURNS TRIGGER AS $$
BEGIN
  DELETE FROM suseSaltPillar WHERE id = OLD.pillar_id;
  DELETE FROM suseSaltPillar WHERE category = concat('SyncedImage', OLD.id);
  RETURN OLD;
END $$ LANGUAGE PLPGSQL;

CREATE TRIGGER suse_image_info_image_removed_trig AFTER DELETE ON suseImageInfo
  FOR EACH ROW EXECUTE PROCEDURE suse_image_info_image_removed_trig_fun();
  0707010000036B000081B400000000000000000000000167AE1114000002FC000000000000000000000000000000000000003A00000000susemanager-schema/postgres/triggers/suseImageProfile.sql --
-- Copyright (c) 2017 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- triggers for suseImageProfile

create or replace function suse_imgprof_mod_trig_fun() returns trigger as
$$
begin
	new.modified := current_timestamp;
	return new;
end;
$$ language plpgsql;

create trigger
suse_imgprof_mod_trig
before insert or update on suseImageProfile
for each row
execute procedure suse_imgprof_mod_trig_fun();
0707010000036C000081B400000000000000000000000167AE1114000002FB000000000000000000000000000000000000003800000000susemanager-schema/postgres/triggers/suseImageStore.sql   --
-- Copyright (c) 2017 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- triggers for suseImageStore

create or replace function suse_imgstore_mod_trig_fun() returns trigger as
$$
begin
	new.modified := current_timestamp;
	return new;
end;
$$ language plpgsql;

create trigger
suse_imgstore_mod_trig
before insert or update on suseImageStore
for each row
execute procedure suse_imgstore_mod_trig_fun();
 0707010000036D000081B400000000000000000000000167AE111400000342000000000000000000000000000000000000003E00000000susemanager-schema/postgres/triggers/suseInstalledProduct.sql --
-- Copyright (c) 2010 Novell
-- Copyright (c) 2011 SUSE Linux Products GmbH
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
--
create or replace function suse_installed_product_mod_trig_fun() returns trigger
as
$$
begin
            new.modified := current_timestamp;

            return new;
end;
$$
language plpgsql;


create trigger
suseinstalledproduct_mod_trig
before insert or update on suseInstalledProduct
for each row
execute procedure suse_installed_product_mod_trig_fun();
  0707010000036E000081B400000000000000000000000167AE111400000304000000000000000000000000000000000000004100000000susemanager-schema/postgres/triggers/suseMaintenanceCalendar.sql  --
-- Copyright (c) 2020 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- triggers for suseMaintenanceCalendar

create or replace function suse_mtcal_mod_trig_fun() returns trigger as
$$
begin
	new.modified := current_timestamp;
	return new;
end;
$$ language plpgsql;

create trigger
suse_mtcal_mod_trig
before insert or update on suseMaintenanceCalendar
for each row
execute procedure suse_mtcal_mod_trig_fun();
0707010000036F000081B400000000000000000000000167AE11140000030A000000000000000000000000000000000000004100000000susemanager-schema/postgres/triggers/suseMaintenanceSchedule.sql  --
-- Copyright (c) 2020 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- triggers for suseMaintenanceSchedule

create or replace function suse_mtsched_mod_trig_fun() returns trigger as
$$
begin
	new.modified := current_timestamp;
	return new;
end;
$$ language plpgsql;

create trigger
suse_mtsched_mod_trig
before insert or update on suseMaintenanceSchedule
for each row
execute procedure suse_mtsched_mod_trig_fun();
  07070100000370000081B400000000000000000000000167AE1114000002E8000000000000000000000000000000000000003400000000susemanager-schema/postgres/triggers/suseMdData.sql   --
-- Copyright (c) 2012 Novell
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
--
create or replace function susemddata_mod_trig_fun() returns trigger
as
$$
begin
            new.modified := current_timestamp;

            return new;
end;
$$
language plpgsql;


create trigger
susemddata_mod_trig
before insert or update on suseMdData
for each row
execute procedure susemddata_mod_trig_fun();

07070100000371000081B400000000000000000000000167AE1114000002EB000000000000000000000000000000000000003700000000susemanager-schema/postgres/triggers/suseMdKeyword.sql    --
-- Copyright (c) 2012 Novell
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
--
create or replace function susemdkeyw_mod_trig_fun() returns trigger
as
$$
begin
            new.modified := current_timestamp;

            return new;
end;
$$
language plpgsql;


create trigger
susemdkeyw_mod_trig
before insert or update on suseMdKeyword
for each row
execute procedure susemdkeyw_mod_trig_fun();

 07070100000372000081B400000000000000000000000167AE11140000013A000000000000000000000000000000000000003B00000000susemanager-schema/postgres/triggers/suseMgrServerInfo.sql    
create or replace function suse_mgr_info_mod_trig_fun() returns trigger as
$$
begin
	new.modified := current_timestamp;
	       
	return new;
end;
$$ language plpgsql;

create trigger
suse_mgr_info_mod_trig
before insert or update on suseMgrServerInfo
for each row
execute procedure suse_mgr_info_mod_trig_fun();
  07070100000373000081B400000000000000000000000167AE111400000324000000000000000000000000000000000000003800000000susemanager-schema/postgres/triggers/suseMinionInfo.sql   CREATE OR REPLACE function suse_minion_info_mod_trig_fun() RETURNS TRIGGER AS
$$
BEGIN
        new.modified := current_timestamp;
        RETURN new;
END;
$$ language plpgsql;

CREATE TRIGGER
suse_minion_info_mod_trig
BEFORE INSERT OR UPDATE ON suseMinionInfo
FOR EACH ROW
EXECUTE PROCEDURE suse_minion_info_mod_trig_fun();

create or replace function suse_minion_info_up_trig_fun() returns trigger as
$$
begin
        update suseSCCRegCache
           set scc_reg_required = 'Y'
         where server_id = new.server_id;
	return new;
end;
$$ language plpgsql;

create trigger
suse_minion_info_up_trig
after update on suseMinionInfo
for each row
when (OLD.container_runtime is distinct from NEW.container_runtime OR OLD.uname is distinct from NEW.uname)
execute procedure suse_minion_info_up_trig_fun();
07070100000374000081B400000000000000000000000167AE111400000320000000000000000000000000000000000000004000000000susemanager-schema/postgres/triggers/susePackageProductFile.sql   --
-- Copyright (c) 2011 Novell
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- triggers for susePackageProductFile



create or replace function suse_pack_prod_file_mod_trig_fun() returns trigger as
$$
begin
	new.modified := current_timestamp;
	return new;
end;
$$ language plpgsql;



create trigger
suse_pack_prod_file_mod_trig
before insert or update on susePackageProductFile
for each row
execute procedure suse_pack_prod_file_mod_trig_fun();
07070100000375000081B400000000000000000000000167AE11140000033A000000000000000000000000000000000000003C00000000susemanager-schema/postgres/triggers/suseProductChannel.sql   --
-- Copyright (c) 2010 Novell
-- Copyright (c) 2011 SUSE Linux Products GmbH
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
--
create or replace function suse_product_channel_mod_trig_fun() returns trigger
as
$$
begin
            new.modified := current_timestamp;

            return new;
end;
$$
language plpgsql;


create trigger
suseproductchannel_mod_trig
before insert or update on suseProductChannel
for each row
execute procedure suse_product_channel_mod_trig_fun();
  07070100000376000081B400000000000000000000000167AE1114000002E9000000000000000000000000000000000000003E00000000susemanager-schema/postgres/triggers/suseProductExtension.sql --
-- Copyright (c) 2016 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
--
create or replace function suse_prdext_mod_trig_fun() returns trigger
as
$$
begin
        new.modified := current_timestamp;

        return new;
end;
$$
language plpgsql;


create trigger
prdext_mod_trig
before insert or update on suseProductExtension
for each row
execute procedure suse_prdext_mod_trig_fun();
   07070100000377000081B400000000000000000000000167AE11140000030C000000000000000000000000000000000000003900000000susemanager-schema/postgres/triggers/suseProductFile.sql  --
-- Copyright (c) 2011 Novell
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- triggers for suseProductFile



create or replace function suse_product_file_mod_trig_fun() returns trigger as
$$
begin
	new.modified := current_timestamp;
	return new;
end;
$$ language plpgsql;



create trigger
suse_product_file_mod_trig
before insert or update on suseProductFile
for each row
execute procedure suse_product_file_mod_trig_fun();
07070100000378000081B400000000000000000000000167AE111400000318000000000000000000000000000000000000003600000000susemanager-schema/postgres/triggers/suseProducts.sql --
-- Copyright (c) 2010 Novell
-- Copyright (c) 2011 SUSE Linux Products GmbH
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
--
create or replace function suse_products_mod_trig_fun() returns trigger
as
$$
begin
        new.modified := current_timestamp;

        return new;
end;
$$
language plpgsql;


create trigger
suseproducts_mod_trig
before insert or update on suseProducts
for each row
execute procedure suse_products_mod_trig_fun();
07070100000379000081B400000000000000000000000167AE111400000130000000000000000000000000000000000000004400000000susemanager-schema/postgres/triggers/suseProfileCustomDataValue.sql   
create or replace function suse_pcdv_mod_trig_fun() returns trigger as
$$
begin
	new.modified := current_timestamp;
 	return new;
end;
$$ language plpgsql;

create trigger
suse_pcdv_mod_trig
before insert or update on suseProfileCustomDataValue
for each row
execute procedure suse_pcdv_mod_trig_fun();

0707010000037A000081B400000000000000000000000167AE111400000145000000000000000000000000000000000000003900000000susemanager-schema/postgres/triggers/suseSCCRegCache.sql  
create or replace function suse_sccregcache_mod_trig_fun() returns trigger as
$$
begin
        new.modified = current_timestamp;
        return new;
end;
$$ language plpgsql;

create trigger
suse_sccregcache_mod_trig
before insert or update on suseSCCRegCache
for each row
execute procedure suse_sccregcache_mod_trig_fun();
   0707010000037B000081B400000000000000000000000167AE111400000603000000000000000000000000000000000000004400000000susemanager-schema/postgres/triggers/suseServerInstalledProduct.sql   --
-- Copyright (c) 2010 Novell
-- Copyright (c) 2011 SUSE Linux Products GmbH
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
--
create or replace function suse_srv_inst_prod_mod_trig_fun() returns trigger
as
$$
begin
            new.modified := current_timestamp;

            return new;
end;
$$
language plpgsql;


create trigger
susesrvinstprod_mod_trig
before insert or update on suseServerInstalledProduct
for each row
execute procedure suse_srv_inst_prod_mod_trig_fun();


create or replace function suse_srv_inst_prod_iud_trig_fun() returns trigger as
$$
begin
	if tg_op='INSERT' or tg_op='UPDATE' then
		update suseSCCRegCache
                   set scc_reg_required = 'Y'
                 where server_id = new.rhn_server_id;
                return new;
        end if;
        if tg_op='DELETE' then
                update suseSCCRegCache
                   set scc_reg_required = 'Y'
                 where server_id = old.rhn_server_id;
                return old;
        end if;
end;
$$ language plpgsql;

create trigger
susesrvinstprod_iud_trig
after insert or update or delete on suseServerInstalledProduct
for each row
execute procedure suse_srv_inst_prod_iud_trig_fun();
 0707010000037C000081B400000000000000000000000167AE111400000438000000000000000000000000000000000000003F00000000susemanager-schema/postgres/triggers/suseServerSAPWorkload.sql    --
-- Copyright (c) 2025 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--

create or replace function suse_server_sap_workload_up_trig_fun() returns trigger as
$$
begin
        if (TG_OP = 'DELETE') then
            update suseSCCRegCache
            set scc_reg_required = 'Y'
            where server_id = old.server_id;
            return null;
        else
            update suseSCCRegCache
            set scc_reg_required = 'Y'
            where server_id = new.server_id;
            return new;
        end if;
end;
$$ language plpgsql;

create trigger
suse_server_sap_workload_up_trig
after insert or update or delete on suseServerSAPWorkload
for each row
execute procedure suse_server_sap_workload_up_trig_fun();
0707010000037D000081B400000000000000000000000167AE111400000300000000000000000000000000000000000000003900000000susemanager-schema/postgres/triggers/suseUpgradePath.sql  --
-- Copyright (c) 2011-2012 SUSE Linux Products GmbH
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
--
create or replace function suse_upgpath_mod_trig_fun() returns trigger
as
$$
begin
        new.modified := current_timestamp;

        return new;
end;
$$
language plpgsql;


create trigger
suseupgpath_mod_trig
before insert or update on suseUpgradePath
for each row
execute procedure suse_upgpath_mod_trig_fun();
0707010000037E000081B400000000000000000000000167AE111400000300000000000000000000000000000000000000004000000000susemanager-schema/postgres/triggers/suseVirtualHostManager.sql   --
-- Copyright (c) 2015 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- triggers for suseVirtualHostManager

create or replace function suse_vhms_mod_trig_fun() returns trigger as
$$
begin
	new.modified := current_timestamp;
	return new;
end;
$$ language plpgsql;

create trigger
suse_vhms_mod_trig
before insert or update on suseVirtualHostManager
for each row
execute procedure suse_vhms_mod_trig_fun();
0707010000037F000081B400000000000000000000000167AE1114000006A8000000000000000000000000000000000000003300000000susemanager-schema/postgres/triggers/triggers.deps    #
# Copyright (c) 2008--2012 Red Hat, Inc.
#
# This software is licensed to you under the GNU General Public License,
# version 2 (GPLv2). There is NO WARRANTY for this software, express or
# implied, including the implied warranties of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
# along with this software; if not, see
# http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
#
# Dependencies for trigger objects in this (namespace) directory.
# See: ../../README for details.
# No TABS, PLEASE!
#

path = tables procs packages

rhnChannel                 :: rhnChannel lookup_functions rhnSnapshot rhnChannelTrust
rhnChannelPackage          :: rhnChannelPackage rhnSnapshot rhnChannel \
                              lookup_functions rhnSnapshotChannel
rhnConfigChannel           :: rhnConfigChannel rhnSnapshotConfigChannel \
                              rhnSnapshot lookup_functions
rhnConfigRevision          :: rhnConfigRevision rhnSnapshotConfigRevision \
                              rhnSnapshot lookup_functions \
                              rhnConfigContent rhnConfigChannel rhnConfigFile \
                              rhn_exception.pks
rhnErrata                  :: rhnChannel rhnChannelErrata
rhnKickstartSession        :: rhnKickstartSession rhnKickstartSessionHistory
rhnServerGroup             :: rhnUserGroup rhnUserGroupType rhn_exception \
                              lookup_functions rhnSnapshot rhnServerGroup \
                              rhnSnapshotServerGroup
rhnSnapshotConfigChannel   :: rhnSnapshot rhnConfigChannel
rhnUserInfo                :: rhnTimezone
web_contact                :: web_contact web_contact_all
07070100000380000081B400000000000000000000000167AE111400000591000000000000000000000000000000000000003500000000susemanager-schema/postgres/triggers/web_contact.sql  
--
-- Copyright (c) 2008--2015 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--

create or replace function web_contact_ins_trig_fun() returns trigger
as
$$
begin
        new.modified := current_timestamp;
        new.login_uc := UPPER(new.login);
        insert into web_contact_all (id, org_id, login)
            values (new.id, new.org_id, new.login);

        return new;
end;
$$
language plpgsql;

create trigger
web_contact_ins_trig
before insert on web_contact
for each row
execute procedure web_contact_ins_trig_fun();


create or replace function web_contact_upd_trig_fun() returns trigger
as
$$
begin
        new.modified := current_timestamp;
        new.login_uc := UPPER(new.login);

        return new;
end;
$$
language plpgsql;

create trigger
web_contact_upd_trig
before update on web_contact
for each row
execute procedure web_contact_upd_trig_fun();
   07070100000381000081B400000000000000000000000167AE111400000551000000000000000000000000000000000000003600000000susemanager-schema/postgres/triggers/web_customer.sql 
--
-- Copyright (c) 2008--2015 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--
-- update timestamp

create or replace function web_customer_mod_trig_fun() returns trigger
as
$$
begin
        new.modified := current_timestamp;

        return new;
end;
$$
language plpgsql;


create trigger
web_customer_mod_trig
before insert or update on web_customer
for each row
execute procedure web_customer_mod_trig_fun();


create or replace function web_customer_insert_trig_fun() returns trigger
as
$$
begin
	insert into rhnOrgConfiguration (org_id) values (new.id);
	insert into rhnOrgAdminManagement (org_id) values (new.id);

        return new;
end;
$$
language plpgsql;


create trigger
web_customer_insert_trig
after insert on web_customer
for each row
execute procedure web_customer_insert_trig_fun();
   07070100000382000081B400000000000000000000000167AE11140000013B000000000000000000000000000000000000004500000000susemanager-schema/postgres/triggers/web_user_contact_permission.sql  
create or replace function web_user_cp_timestamp_fun() returns trigger as
$$
begin
	new.modified = current_timestamp;

 	return new;
end;
$$ language plpgsql;

create trigger
web_user_cp_timestamp
before insert or update on web_user_contact_permission
for each row
execute procedure web_user_cp_timestamp_fun();


 07070100000383000081B400000000000000000000000167AE1114000003DD000000000000000000000000000000000000004000000000susemanager-schema/postgres/triggers/web_user_personal_info.sql   
--
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--
-- triggers for web_user_personal_info

create or replace function web_user_pi_timestamp_fun() returns trigger as
$$
begin
  new.modified := current_timestamp;

  return new;
end;
$$ language plpgsql;


create trigger
web_user_pi_timestamp
BEFORE INSERT OR UPDATE ON web_user_personal_info
FOR EACH ROW
execute procedure web_user_pi_timestamp_fun();
   07070100000384000081B400000000000000000000000167AE111400000159000000000000000000000000000000000000003C00000000susemanager-schema/postgres/triggers/web_user_site_info.sql   

create or replace function web_user_si_timestamp_fun() returns trigger as
$$
begin
	
	new.email_uc := upper(new.email);
	new.modified := current_timestamp;

 	return new;
end;
$$ language plpgsql;

create trigger
web_user_si_timestamp
before insert or update on web_user_site_info
for each row
execute procedure web_user_si_timestamp_fun();


   07070100000385000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000002200000000susemanager-schema/postgres/views 07070100000386000081B400000000000000000000000167AE111400000244000000000000000000000000000000000000002B00000000susemanager-schema/postgres/views/Makefile    #
# Copyright (c) 2008--2012 Red Hat, Inc.
#
# This software is licensed to you under the GNU General Public License,
# version 2 (GPLv2). There is NO WARRANTY for this software, express or
# implied, including the implied warranties of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
# along with this software; if not, see
# http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
#

COMMON := ../../common/views

common :
	@rm -rf common
	@mkdir -p common
	@cp -p $(COMMON)/* common

clean :
	@rm -rf common

.PHONY : common clean
07070100000387000081B400000000000000000000000167AE1114000001DE000000000000000000000000000000000000003700000000susemanager-schema/postgres/views/all_primary_keys.sql    
create or replace view all_primary_keys as
select
        ts.table_name              as table_name,
        ts.constraint_name         as constraint_name,
        ccu.column_name            as column_name
  from information_schema.table_constraints ts
  join information_schema.constraint_column_usage ccu
    on ts.table_name = ccu.table_name
   and ts.table_schema = ccu.table_schema
   and ts.constraint_name = ccu.constraint_name
 where ts.constraint_type = 'PRIMARY KEY';
  07070100000388000081B400000000000000000000000167AE1114000001BF000000000000000000000000000000000000003600000000susemanager-schema/postgres/views/all_tab_columns.sql -- oracle equivalent source none

create or replace view all_tab_columns
as
select
        table_name              as table_name,
        column_name             as column_name,
        ordinal_position        as column_id,
        data_type               as data_type,
        numeric_precision       as data_precision,
        character_maximum_length as data_length,
        substr(is_nullable,1,1) as nullable
from information_schema.columns;
 07070100000389000081FD00000000000000000000000167AE1114000019AE000000000000000000000000000000000000003100000000susemanager-schema/schema-source-sanity-check.pl  #!/usr/bin/perl

use strict;
use warnings FATAL => 'all';

use File::Find ();
use Getopt::Long ();
use Digest::SHA ();

my %files;
my $show_ignored = 0;
Getopt::Long::GetOptions('I' => \$show_ignored) or exit 9;

my @dirs = qw(common postgres upgrade);
if (scalar @ARGV > 0) {
  @dirs = @ARGV;
}

for my $dir (@dirs) {
        File::Find::find(sub {
                my $name = $File::Find::name;
                if ($name eq $dir) {
                        return;
                }
                if (not -f $_) {
                        return;
                }
                if (substr($name, 0, length($dir) + 1) ne "$dir/") {
                        die "In dir [$dir] we got [$name]\n";
                }
                if ($dir eq 'upgrade') {
                        my $generic = $name;
                        my $db = 'common';
                        if ($generic =~ /\.(oracle|postgresql)$/) {
                                die "Found DB specific files in [upgrade] dir"
                        }
                        $files{$db}{$generic} = $name;
                } else {
                        my $rname = substr($name, length($dir) + 1);
                        $files{$dir}{$rname} = $name;
                }
                }, $dir);
}

my $error = 0;

sub check_file_content {
        my $filename = shift;
        return if $filename =~ /^upgrade/;
        return if $filename =~ /qrtz\.sql$/;
        return if $filename =~ /dual\.sql$/;
        my ($type, $name) = ($filename =~ m!.*/(.+)/(.+?)(_foreignkeys)?\.(sql|pks|pkb)$!);
        return if not defined $type;
        return if $type eq 'class';
        return if $type eq 'packages';

        local *FILE;
        open FILE, '<', $filename or do {
                die "Error reading [$filename]: $!\n";
        };
        my $content;
        {
                local $/ = undef;
                $content = <FILE>;
        }
        close FILE;
        # print "[$filename] [$type] [$name]\n";
        if ($type eq 'tables') {
                if ($filename =~ '\w*_index.sql') {
                        $name =~ s/_index$//g;
                }
                elsif ($filename =~ '\w*_alters.sql') {
                        $name =~ s/_alters$//g;
                }
                if (not $content =~ /^(--.*\n
                                        |\s*\n
                                        |(create|alter|comment\s+on)\s+table\s+$name\b(?:[^;]|';')+;
                                        |create\s+(unique\s+)?index\s+\w+\s+on\s+$name[^;]+;
                                        |create\s+sequence[^;]+;
                                        |comment\s+on\s+column\s+$name\.[^;]+;
                                        )+$/ix) {
                        print "Bad $type content [$filename]\n";
                        $error = 1;
                }
        } elsif ($type eq 'views') {
                if (not $content =~ /^(--.*\n
                                        |\s*\n
                                        |create(\s+or\s+replace)?\s+view\s+$name\b[^;]+;
                                        )+$/ix) {
                        print "Bad $type content [$filename]\n";
                        $error = 1;
                }
        } elsif ($type eq 'data') {
                if (not $content =~ /^(--.*\n
                                        |\s*\n
                                        |insert\s+into\s+$name\b[^;]+(values|select)('[^;]+(;[^;]*)*'|[^';])+;
                                        |select\s+[^;()]+\(('[^;]+')*\);
                                        |begin\s+[^;()]+\(('[^;]+')*\);\s+end;\n\/
                                        |commit;
                                        )+$/ix) {
                        print "Bad $type content [$filename]\n";
                        $error = 1;
                }
        } elsif ($type eq 'procs') {
                if (not $content =~ m!^(--.*\n
                                        |\s*\n
                                        |create(\s+or\s+replace)?\s+(procedure|function)\s+$name\b
                                                ((?s:.+?);\n/\n
                                                |[^\$]+\$\$(?s:.+?)\s\$\$
                                                        \s+language\s+(plpgsql|sql)(\s+(strict\s+)?immutable|\s+stable)?;)
                                        |show\s+errors;?\n
                                        )+$!ix) {
                        print "Bad $type content [$filename]\n";
                        $error = 1;
                }
        } elsif ($type eq 'synonyms') {
                if (not $content =~ m!^(--.*\n
                                        |\s*\n
                                        |create(\s+or\s+replace)?\s+synonym\s+$name\b\s+for[^;]+;
                                        |create(\s+or\s+replace)?\s+synonym\s+${name}s?_recid_seq\s+for[^;]+;
                                        )+$!ix) {
                        print "Bad $type content [$filename]\n";
                        $error = 1;
                }
        } elsif ($type eq 'triggers') {
                if (not $content =~ m!^(?:--.*\n
                                        |\s*\n
                                        |create(?:\s+or\s+replace)?\s+function\s+(\w+)(?s:.+?)\s+language\s+plpgsql;
                                                \s+create(\s+or\s+replace)?\s+trigger[^;]+\s+on\s+$name\b[^;]+execute\s+procedure\s+\1\(\);
                                        |create(\s+or\s+replace)?\s+trigger[^;]+\s+on\s+$name\b[^;]+execute\s+procedure\s+no_operation_trig_fun\(\);
                                        |create(\s+or\s+replace)?\s+trigger[^;]+\s+on\s+$name\b(?s:.+?);\n/\n
                                        |show\s+errors;?\n
                                        )+$!ix) {
                        print "Bad $type content [$filename]\n";
                        $error = 1;
                }
        } else {
                print "Unknown type [$type] for [$filename]\n";
        }
}

for my $c (sort keys %{ $files{common} }) {
        next unless $c =~ /\.(sql|pks|pkb)$/;
        check_file_content($files{common}{$c});
        for my $o (qw( postgres )) {
                if (exists $files{$o}{$c}) {
                        print "Common file [$c] is also in $o\n";
                        $error = 1;
                }
        }
}

for my $c (sort keys %{ $files{postgres} }) {
        next unless $c =~ /\.(sql|pks|pkb)$/;
        check_file_content($files{postgres}{$c});
}

exit $error;

  0707010000038A000081FD00000000000000000000000167AE1114000048D0000000000000000000000000000000000000002C00000000susemanager-schema/spacewalk-schema-upgrade   #!/usr/bin/perl

use strict;
use warnings FATAL => 'all';

use Spacewalk::Setup ();
use IPC::Open3 ();
use File::Basename;
use Getopt::Long ();
use Pod::Usage ();

my $MIN_PG_DB_VERSION = 130001;
my $MAX_PG_DB_VERSION = 149999;
my $MIN_PG_DB_VERSION_STRING = "13";
my $MAX_PG_DB_VERSION_STRING = "14";
my $OS_VERSION_CHECK = 15.4;
my $OS_VERSION_MIN_DB_VERSION = 140000;
my $OS_VERSION_WANTED_DB_VERSION = "14";

my $config_file = Spacewalk::Setup::DEFAULT_RHN_CONF_LOCATION;

my ($skip_confirm, $reportdb, $help);

$skip_confirm = 0;
if (not Getopt::Long::GetOptions(
    'yes'      => \$skip_confirm,
    'reportdb' => \$reportdb,
    'help'     => => \$help
)) {
    Pod::Usage::pod2usage(0);
}

Pod::Usage::pod2usage(-verbose => 2) if $help;

if (not -e $config_file) {
        die "The config file [$config_file] does not seem to exist. Was Spacewalk configured yet?\n";
}

# Load the correct module for the type of database
my $db_specific = $reportdb ? "Spacewalk::SchemaUpgrade::ReportDb" : "Spacewalk::SchemaUpgrade::MainDb";

eval {
    (my $file = "$db_specific.pm") =~ s|::|/|g;
    require $file;
    $db_specific->import();
    1;
} or do {
    my $error = $@;
    die "Unable to import required module: $error";
};

my $SCHEMA_DIR = "/etc/sysconfig/rhn/" . $db_specific->DB_NAME;
my $SCHEMA_UPGRADE_DIR = "/etc/sysconfig/rhn/" . $db_specific->UPGRADE_PREFIX . "-upgrade";
my $SCHEMA_UPGRADE_LOGDIR = "/var/log/spacewalk/" . $db_specific->UPGRADE_PREFIX . "-upgrade";

my %options;
Spacewalk::Setup::read_config($config_file, \%options);
if (not defined $options{$db_specific->BACKEND_PROPERTY}) {
        die "Config file [$config_file] does not seem to have database backend info (" . $db_specific->BACKEND_PROPERTY . ") set.\n";
}

$ENV{NLS_LANG} = 'AMERICAN_AMERICA.UTF8';
$ENV{NLS_NUMERIC_CHARACTERS} = '.';

my $test = run_query("select '1' || '2' || '3' as testing from dual;");
if (not defined $test) {
        die "Connect to database was not successful.\n";
}
if ($test ne '123') {
        die "Test select from database did not give expected results.\n";
}

my $default_tablespace;
my $server_version = 0;
my $pg_version = "";
my $os_version = 0.0;
my $os_name = "";
my $isUyuni = 0;
$server_version = run_query("show server_version_num;");
$pg_version = run_query("show server_version;");

open(my $fh, '<:encoding(UTF-8)', "/etc/os-release") or die "Could not open file '/etc/os-release' $!";
while (my $row = <$fh>) {
    chomp $row;
    # Skip empty rows.
    if ($row eq "") {
        next;
    }
    my ($k,$v) = split(/=/, $row, 2);
    if ($k eq "VERSION_ID") {
        if ($v =~ /(\d+\.\d+)/) {
            $os_version = $1;
        }
    }
    elsif ($k eq "PRETTY_NAME") {
        $os_name = $v;
    }
    elsif ($k eq "ID" && $v =~ m/opensuse/) {
        $isUyuni = 1;
    }
}
close $fh;
if ($server_version < $MIN_PG_DB_VERSION) {
    print "\nRunning postgresql $pg_version is not supported. Minimal required version is $MIN_PG_DB_VERSION_STRING.\n\n";
    exit 1;
}
elsif($server_version > $MAX_PG_DB_VERSION) {
    print "\nRunning postgresql $pg_version is not supported. Maximal allowed version is $MAX_PG_DB_VERSION_STRING.\n\n";
    exit 1;
}
elsif($os_version >= $OS_VERSION_CHECK && $server_version < $OS_VERSION_MIN_DB_VERSION) {
    print "\nRunning postgresql $pg_version on $os_name is unsupported. Please migrate to postgresql $OS_VERSION_WANTED_DB_VERSION.\n\n";
    exit 1;
}

my $my_schema_version_out = `rpm -qf --qf '%{name} %{version} %{release}\n' $SCHEMA_DIR/schema-override 2> /dev/null`;
if ($?) { # the directory does not exists or is not owned by any rpm
        $my_schema_version_out = `rpm -qf --qf '%{name} %{version} %{release}\n' $SCHEMA_DIR/main.sql`;
}
my ($my_schema_name, $my_schema_version, $my_schema_release) = ($my_schema_version_out =~ /^(\S+)\s(\S+)\s(\S+)$/);
if (not defined $my_schema_release) {
        die "Failed to retrieve our schema package name and version.\n";
}

if ($ENV{SUMA_TEST_SCHEMA_VERSION}) {
    $my_schema_version = $ENV{SUMA_TEST_SCHEMA_VERSION};
}

my $target_schema = join '-', $my_schema_name, $my_schema_version, $my_schema_release;
(my $target_schema_norm = $target_schema) =~ s!^(.+-\d+(\.\d+)*-[a-zA-Z0-9]*)(\..*)*$!$1!;

my $schema_version = run_query($db_specific->get_schema_version_query());

if (not defined $schema_version) {
    my $migrationdir = run_query($db_specific->get_migration_dir_query());
    if (! defined $migrationdir or ! -d "$SCHEMA_UPGRADE_LOGDIR/$migrationdir") {
        die "No existing schema version info found in rhnVersionInfo.\n";
    }
    my @logfiles = sort {$b cmp $a} map { glob } "$SCHEMA_UPGRADE_LOGDIR/$migrationdir-to-*.log";
    my $lname = ((scalar(@logfiles) >= 1)?basename($logfiles[0]):"$migrationdir.log");
    print "Found unfinished schema migration\n";
    print "Try to continue schema migration\n";
    run_schema_upgrade("$SCHEMA_UPGRADE_LOGDIR/$migrationdir", $lname, $target_schema, $default_tablespace, $skip_confirm);

    exit;
}

my $regex = "^(uyuni|susemanager|spacewalk|satellite|rhn-satellite)-" . $db_specific->UPGRADE_PREFIX . "-";
if (not $schema_version =~ /$regex/) {
    die "Unknown schema name [$schema_version] found.\n";
}

my $start_schema = $schema_version;
(my $start_schema_norm = $start_schema) =~ s!^(.+-\d+(\.\d+)*-[a-zA-Z0-9]*)(\..*)*$!$1!;

print "Schema upgrade: [$start_schema] -> [$target_schema]\n";
if ($start_schema eq $target_schema) {
    warn "Your database schema already matches the schema package version [$target_schema].\n";
    exit;
}

my $foundtarget = 0;
my $retried = 0;
RETRY:

if (!$foundtarget) {
    print "Searching for upgrade path to: [$target_schema_norm]\n";
}

my %upgrade_path;
my @queue = ( $target_schema_norm );
while (@queue) {
    my $t = shift @queue;
    my @lookup = glob "$SCHEMA_UPGRADE_DIR/*-to-$t";
    for (@lookup) {
        $foundtarget = 1;
        s!^\Q$SCHEMA_UPGRADE_DIR/\E!!;
        s!-to-\Q$t\E$!!;
        ## print "  [$_] -> [$t]\n";
        if ($_ eq $start_schema_norm) {
            ## print "    -> start found.\n";
        }
        $upgrade_path{$_}{$t} = $upgrade_path{$t};
        push @queue, $_;
    }
}

if (!$foundtarget) {
    if (not $retried) {
        if ($target_schema_norm =~ s!^(.+-.+)-[a-zA-Z0-9]+(\.\d+)*$!$1!) {
            $retried++;
            goto RETRY;
        }
    }
    if ($retried) {
        my $trunc_version = 0;
        if ($target_schema_norm =~ s!^(.+-.+\..+)\.[^.-]+$!$1!) {
            $trunc_version = 1;
        }
        if ($trunc_version) {
            goto RETRY;
        }
    }
    die "Was not able to find upgrade path in directory [$SCHEMA_UPGRADE_DIR].\n";
}

$retried = 0;
RETRYSOURCE:

if ($start_schema eq $target_schema) {
    warn "Your database schema already matches the schema package version [$target_schema].\n";
    exit;
}
if ($start_schema_norm eq $target_schema_norm) {
    print "The schema version is the same, except for the dist tag.\n";
    $upgrade_path{$target_schema_norm} = undef;
}

print "Searching for start path:  [$start_schema_norm]\n";

if (not exists $upgrade_path{$start_schema_norm}) {
    if (not $retried) {
        if ($start_schema_norm =~ s!^(.+-.+)-\d+(\.\d+)*$!$1!) {
            $retried++;
            goto RETRYSOURCE;
        }
    }
    if ($retried) {
        my $trunc_version = 0;
        if (! $foundtarget && $target_schema_norm =~ s!^(.+-.+\..+)\.[^.-]+$!$1!) {
            $trunc_version = 1;
        }
        if ($trunc_version) {
            goto RETRYSOURCE;
        }
    }
    die "Was not able to find upgrade path in directory [$SCHEMA_UPGRADE_DIR].\n";
}


my @path = get_shortest_path($upgrade_path{$start_schema_norm}, $target_schema_norm);
print "The path: ", (join " -> ", map "[$_]", $start_schema_norm, @path), "\n";

mkdir "/var/log/spacewalk", 0755;
mkdir $SCHEMA_UPGRADE_LOGDIR, 0755;
if (not -e $SCHEMA_UPGRADE_LOGDIR) {
        die "Failed to create log directory [$SCHEMA_UPGRADE_LOGDIR]: $!\n";
}
system("/sbin/restorecon $SCHEMA_UPGRADE_LOGDIR 2>&1 > /dev/null");

my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday, $isdst) = localtime(time);
my $stamp = sprintf "%04d%02d%02d-%02d%02d%02d", $year + 1900, $mon + 1, $mday,
        $hour, $min, $sec;

my $start = $start_schema_norm;
my $migrationdir = "schema-from-$stamp";
my $in = $db_specific->update_migration_dir($migrationdir);
mkdir "$SCHEMA_UPGRADE_LOGDIR/$migrationdir", 0755;
if (not -e "$SCHEMA_UPGRADE_LOGDIR/$migrationdir") {
    die "Failed to create log directory [$SCHEMA_UPGRADE_LOGDIR/$migrationdir]: $!\n";
}
open(INIT, "> $SCHEMA_UPGRADE_LOGDIR/$migrationdir/00_0000-upgrade-start.sql") or
     rmdir_and_die("Cannot create upgrade-start file: $!", "$SCHEMA_UPGRADE_LOGDIR/$migrationdir");
print INIT $in."\n";
close INIT;

my $prenum = 0;
while (@path) {
    my $t = shift @path;
    my $dir = "$start-to-$t";
    if (not -e "$SCHEMA_UPGRADE_DIR/$dir") {
        rmdir_and_die("Directory [$SCHEMA_UPGRADE_DIR/$dir] was seen but is lost now.\n",
                      "$SCHEMA_UPGRADE_LOGDIR/$migrationdir");
    }
    if( $prenum > 98 )
    {
        # prevent overrun
        rmdir_and_die("Overrun: too many migrations", "$SCHEMA_UPGRADE_LOGDIR/$migrationdir");
    }

    my @files = match_overrides("$SCHEMA_UPGRADE_DIR/$dir/*.ref", "$SCHEMA_UPGRADE_DIR/$dir/*.{sql,ref}.$options{$db_specific->BACKEND_PROPERTY}");
    for (my $i = 0; $i < @files; $i++) {
        if ($files[$i] =~ /\.ref(\.$options{$db_specific->BACKEND_PROPERTY})?$/) {
            my @subfiles;
            local *REF;
            open REF, $files[$i] or rmdir_and_die("Error reading [$files[$i]]: $!\n", "$SCHEMA_UPGRADE_LOGDIR/$migrationdir");
            while (<REF>) {
                chomp;
                next if /^\s*(#|$)/;
                my @newsubfiles = match_overrides("$SCHEMA_UPGRADE_DIR/$_", "$SCHEMA_UPGRADE_DIR/$_.$options{$db_specific->BACKEND_PROPERTY}");
                if (not @newsubfiles) {
                    rmdir_and_die("Could not find any files matching [$_] from [$files[$i]]\n", "$SCHEMA_UPGRADE_LOGDIR/$migrationdir");
                }
                push @subfiles, @newsubfiles;
            }
            close REF;
            splice @files, $i, 1, @subfiles;
            $i--;
        }
    }

    for my $fullname (@files) {
        (my $name = $fullname) =~ s!^.*/!!;
        my $linkname = sprintf("%02d_%s", $prenum, $name);
        if( ! symlink("$fullname", "$SCHEMA_UPGRADE_LOGDIR/$migrationdir/$linkname") )
        {
            rmdir_and_die("Cannot create symlink: $!", "$SCHEMA_UPGRADE_LOGDIR/$migrationdir");
        }
    }
    # print $in;
    $start = $t;
    $prenum++;
}

my $endfile = "$SCHEMA_DIR/upgrade-end.sql";
$in = "";
local * END;
open END, '<', $endfile or rmdir_and_die("Error reading [$endfile]: $!\n", "$SCHEMA_UPGRADE_LOGDIR/$migrationdir");
{
local $/ = undef;
$in .= join '', <END>;
}
close END;

$in .= $db_specific->insert_version_info($my_schema_name, $my_schema_version, $my_schema_release);

local *SQL;
open SQL, "> $SCHEMA_UPGRADE_LOGDIR/$migrationdir/99_9999-upgrade-end.sql" or rmdir_and_die(
          "Error writing [$SCHEMA_UPGRADE_LOGDIR/$migrationdir/99_9999-upgrade-end.sql]: $!.\n",
          "$SCHEMA_UPGRADE_LOGDIR/$migrationdir");
print SQL $in;
close SQL;

my $lname = "$migrationdir-to-$start.log";
run_schema_upgrade("$SCHEMA_UPGRADE_LOGDIR/$migrationdir", $lname, $target_schema, $default_tablespace, $skip_confirm);

exit;

sub run_schema_upgrade
{
    my $dir = shift;
    my $logfilename = shift;
    my $target_schema = shift;
    my $default_tablespace = shift;
    my $skip_confirm = shift;

    die "Migration directory [$dir] does not exist." if(! -d "$dir");

    print "Planning to run schema upgrade with dir '$dir'\n";
    if (not $skip_confirm) {
        local $| = 1;
        READ_ENTER:
        print "Hit Enter to continue or Ctrl+C to interrupt: ";
        my $in = <STDIN>;
        chomp $in;
        if ($in ne '') {
                goto READ_ENTER;
        }
    }

    my $logfile = $SCHEMA_UPGRADE_LOGDIR . "/$logfilename";

    my $log;
    open $log, '>>', $logfile or die "Error writing logfile [$logfile]: $!\n";

    system("/sbin/restorecon $logfile 2>&1 > /dev/null");

    my ($s, $m, $h, $md, $mo, $y, $wd, $yd, $isds) = localtime(time);
    my $now = sprintf "%04d-%02d-%02d %02d:%02d:%02d", $y + 1900, $mo + 1, $md,
                      $h, $m, $s;

    print $log "================== started: $now ==================\n";
    print "Executing spacewalk-sql, the log is in [$logfile].\n";

    my @migrationfiles = sort map { glob } "$dir/*";
    my $filecount = scalar(@migrationfiles);
    my $counter = 0;
    $| = 1;
    foreach my $migfile (@migrationfiles) {
        $counter++;
        my $link = readlink($migfile);
        $link = $migfile if(! $link);
        my $fn = basename($link);
        my $td = basename(dirname($link));

        print STDOUT "($counter/$filecount) apply upgrade [$td/$fn]        ", "\r";
        my $ret = run_query_direkt("$td/$fn", $migfile, $log, $default_tablespace);
        if ($ret != 0)
        {
            print "\n";
            die "Upgrade failed, please see log [$logfile].\nYou can fix the failed migration in [$dir]\nand run spacewalk-schema-upgrade again\n";
        }
        unlink ($migfile);
    }
    print "\n";

    my $new_schema_version = run_query($db_specific->get_schema_version_query());
    if (not defined $new_schema_version) {
        die "Upgrade seems to have run OK yet new schema version is not in rhnVersionInfo.\n";
    }
    if ($new_schema_version ne $target_schema) {
        die <<EOF;
        Upgrade seems to have run OK yet new schema version is
        [$new_schema_version], not [$target_schema].
        Please run schema upgrade again.
EOF
    }
    rmdir "$dir";
    print "The database schema was upgraded to version [$target_schema].\n";
}

sub run_query {
    my ($command) = @_;
    $ENV{'LANG'} = 'C';

    my @params = ('--select-mode');
    push @params, '--reportdb' if $reportdb;
    push @params, '-';

    my $pid = IPC::Open3::open3(my $wfh, my $rfh, '>&STDERR',
                                'spacewalk-sql', @params) or return;

    print $wfh $command;
    print $wfh "\n";
    close $wfh;

    my $out;
    my $seen_dashes = 0;
    while (<$rfh>) {
        if (not defined $out and $seen_dashes) {
            $out = $_;
            last;
        }
        if (/---/) {
            $seen_dashes = 1;
        }
    }
    close $rfh;
    waitpid $pid, 0;
    if ($?) {
        return;
    }

    $out =~ s/^\s+|\s+$//g if defined $out;
    # psql print '----' even if no rows were selected
    $out = undef if defined $out && $out =~ /^\(0 rows\)$/;
    return $out;
}

sub run_query_direkt {
    my ($msg, $file, $log, $default_tablespace) = @_;

    my $sql = <<EOF;
    select '$msg' from dual;
EOF
    open(F, "< $file") or die "Cannot open file '$file': $!";
    my $f_in;
    {
        local $/ = undef;
        $f_in = <F>;
    }
    close F;
    $f_in =~ s!^--.*\n!!gm;
    $f_in =~ s!\[\[.*?\]\]|__.*?__!$default_tablespace!g if defined $default_tablespace;
    $sql .= $f_in;
    $sql .= <<EOF;
    commit;
EOF
    print $log "SQL> ";
    print $log "$sql\n";

    my @params = ('--select-mode-direct');
    push @params, '--reportdb' if $reportdb;
    push @params, '-';


    my $rfh;
    my $pid = IPC::Open3::open3(my $wfh, $rfh, $rfh,
              'spacewalk-sql', @params) or die "Cannot execute spacewalk-sql: $!";
    print $wfh $sql;
    print $wfh "\n";
    close $wfh;

    while (<$rfh>) {
        #print "$out";
        print $log $_;
    }
    close $rfh;
    waitpid $pid, 0;
    return ($? >> 8);
}

sub get_shortest_path {
    my ($hash, $target) = @_;
    my @out;
    for my $k (keys %$hash) {
        if ($k eq $target) {
            return $k;
        }
        my @k_out = ($k, get_shortest_path($hash->{$k}, $target));
        if (not @out || (@k_out and @k_out < @out)) {
            @out = @k_out;
        }
    }
    @out;
}

sub match_overrides {
    return sort map {-e "$_.override" ? "$_.override" : $_} grep { -e $_ } map { glob } @_;
}

sub rmdir_and_die {
    my $msg = shift || "Error";
    my $dir = shift || undef;

    if ($dir && -d $dir ) {
        opendir(DIR, $dir) and do {
            while( my $file = readdir(DIR) ) {
                next if ($file eq "." or $file eq "..");
                unlink($file);
            }
            closedir DIR;
        };
        unlink($dir);
    }
    die "$msg";
}

1;

=head1 NAME

spacewalk-schema-upgrade - utility for Spacewalk / Satellite schema upgrade

=head1 SYNOPSIS

B<spacewalk-schema-upgrade>
[B<-y>] [B<--reportdb>]

=head1 OPTIONS

=over 5

=item B<-y>

Proceed without asking for confirmation.

=item B<--reportdb>

Upgrade the local reporting database instead of the application database.

=back

=head1 DESCRIPTION

B<spacewalk-schema-upgrade> is utility for Spacewalk and Satellite database
schema upgrade. It can update both the application and the reporting
database.

Let's assume you're upgrading your Satellite or Spacewalk installation
from an earlier version and you are done with the package upgrade part
plus any other steps that were required for your installation to be ready
for schema upgrade. What B<spacewalk-schema-upgrade> will do for you at this
point is:

=over 5

=item

Read the database connection string from existing config file.

=item

Read the version of your current (i.e. old) schema from database.

=item

Find the schema version you are about to upgrade to (using an rpm query
command).

=item

Find shortest upgrade path between said schema versions.

=item

Ask the user for confirmation to proceed with the upgrade (can be overriden
with B<-y> switch).

=item

Proceed with the schema upgrade following the upgrade path found, putting
the output from executed sql scripts (including errors if any)
into F</var/log/spacewalk/schema-upgrade> (or into
F</var/log/spacewalk/schema-reportdb-upgrade> in case of the reporting
database). For this step it is important that you have spacewalk-sql
command in your PATH.

=back

=head1 FILES

=over 5

=item F</etc/sysconfig/rhn/schema-upgrade>,
F</etc/sysconfig/rhn/schema-reportdb-upgrade>

Directory containing directories with schema upgrade scripts (one directory for
every major upgrade step).

=item F</etc/rhn/rhn.conf>

Default configuration file containing database connection information.

=item F</var/log/spacewalk/schema-upgrade>,
F</var/log/spacewalk/schema-reportdb-upgrade>


Directory containing output from sql upgrade scripts.

=back

=head1 AUTHORS

Jan Pazdziora

=cut
0707010000038B000081FD00000000000000000000000167AE1114000017AC000000000000000000000000000000000000002100000000susemanager-schema/spacewalk-sql  #!/usr/bin/perl

use strict;
use warnings FATAL => 'all';

use Spacewalk::Setup ();
use IPC::Open3 ();
use Getopt::Long ();
use Cwd 'abs_path';

sub usage {
        die "Usage: $0 [-i | [ OPTIONS ] [sql-file-to-use.sql | - ]]\n    where possible OPTIONS are\n        --verbose\n        --reportdb\n        --select-mode or --select-mode-direct\n";
}

my ($verbose, $select_mode, $select_direct, $interactive, $reportdb);
if (not Getopt::Long::GetOptions(
        'verbose' => \$verbose,
        'select-mode' => \$select_mode,
        'select-mode-direct' => \$select_direct,
        'interactive' => \$interactive,
        'reportdb' => \$reportdb,
        )) {
        usage();
}

if ($interactive and ($select_direct or $select_mode)) {
        warn "Option --interactive cannot be used with --select-* options.\n";
        usage();
}
if ($select_mode and $select_direct) {
        warn "Options --select-mode and --select-mode-direct are exclusive.\n";
        usage();
}

if ($interactive) {
        if (@ARGV) {
                warn "In interactive mode, no input file is expected.\n";
                usage();
        }
} elsif (@ARGV != 1) {
        usage();
}

my $config_file = Spacewalk::Setup::DEFAULT_RHN_CONF_LOCATION;

if (not -e $config_file) {
        die "The config file [$config_file] does not seem to exist. Was Spacewalk configured yet?\n";
}

my %options;
Spacewalk::Setup::read_config($config_file, \%options);

if ($reportdb) {
    for my $n (qw( db_backend db_name db_user db_password db_host db_port db_ssl_enabled )) {
        $options{$n} = $options{'report_'.$n} if (defined $options{'report_'.$n});
    }
}

my @missing;
for my $n (qw( db_backend db_name db_user db_password )) {
        if (not defined $options{$n}) {
                push @missing, "Config file [$config_file] does not seem to have $n set.\n";
        }
}
if (@missing) {
        die join '', @missing;
}

my $filename = $ARGV[0];
if (defined $filename and $filename ne '-') {
        $filename = abs_path($filename);
}

chdir '/';

my ($pid, $wfh, $rfh);
if ($options{db_backend} eq 'postgresql') {
      my @command = ( 'psql', '-U', $options{db_user}, '-d', $options{db_name});
      if (defined $options{db_host} and $options{db_host}) {
              push @command, '-h', $options{db_host};
              if (defined $options{db_port} and $options{db_port}) {
                      push @command, '-p', $options{db_port};
              }
      }
      if (not $interactive) {
              push @command, ( '-v', 'ON_ERROR_STOP=ON', '-f', $filename );
      }
      $ENV{PGPASSWORD} = $options{db_password};
      if ($verbose) {
              print STDERR "Running: @command\n";
      }
      if ($interactive) {
              exec(@command) or die "young\n";
      }
      $ENV{PGOPTIONS} = '--client-min-messages=error -c standard_conforming_strings=on';
      if ($filename eq '-') {
              $wfh = '<&STDIN';
      }
      if ($select_direct) {
              exec(@command) or die "young\n";
      } else {
              $pid = IPC::Open3::open3($wfh, $rfh, '>&STDERR', @command) or return 2;
      }
      close $wfh;
} else {
      die "The config file [$config_file] specifies unknown db_backend [$options{db_backend}] \n";
}

if ($select_direct) {
        $| = 1;
}
my @out;
while (<$rfh>) {
        if ($select_direct) {
                print;
        } else {
                push @out, $_;
        }
}
close $rfh;
waitpid $pid, 0;
if ($?) {
        my $ret = $? >> 8;
        print STDERR @out;
        exit $ret;
} elsif ($select_mode) {
        print @out;
}
exit;

__END__

=head1 NAME

spacewalk-sql - utility for feeding SQL to Spacewalk's and Report database.

=head1 SYNOPSIS

    spacewalk-sql sql-file-to-use.sql
    spacewalk-sql - < sql-file-to-use.sql
    spacewalk-sql -i

    spacewalk-sql --verbose sql-file-to-use.sql
    spacewalk-sql --select-mode - < sql-file-to-use.sql
    spacewalk-sql --verbose --select-mode sql-file-to-use.sql
    spacewalk-sql --select-mode-direct sql-file-to-use.sql

    spacewalk-sql --interactive

=head1 OPTIONS

=over 5

=item --select-mode

By default, no output is printed to standard output because
B<spacewalk-sql> is primarily intended to feed DDL/DML to the
database, not do queries. With this option, upon successful
completion, the output will be printed to standard output. Note that
it will be in the native format.

=item --select-mode-direct

Variant of B<--select-mode> when the output is printed out
immediatelly, without waiting for successful result. This is useful
when you want to log the output and be able to watch it while
the command runs, for example with C<tail -f>.

Note that only one of B<--select-mode> and B<--select-mode-direct>
can be specified.

=item -i | --interactive

Start the interactive session.

This option cannot be used together with the B<--select-mode*>
options.

=item --reportdb
Use the report DB instead of the main spacewalk DB.

=item --verbose

If this option is used, the command which will be invoked including
any parameter is printed to standard error output, prior to it
execution. No quoting is done however, so it can only be used to get
rough idea about what is being called.

=back

=head1 DESCRIPTION

The B<spacewalk-sql> does the right thing for spacewalk databases.
It fetches the database backend type and the connect information from
Spacewalk config files, selects the correct command line tool, runs it
and feeds it the SQL from file specified as parameter. If single
hyphen sign (B<->) is used for the SQL file parameter, standard input
is used. If the B<-i> option is used, interactive session is started.

No output is printed upon successful operation unless B<--select-mode>.
If any error is reported, the error message and all output generated
is printed on the standard output.

The exit value is the exit value of the B<psql> or B<sqlplus>.

=head1 FILES

=over 5

=item F</etc/rhn/rhn.conf>

File which holds connect information for the Spacewalk database backend.

=back

=head1 AUTHORS

Jan Pazdziora

=cut


0707010000038C000081B400000000000000000000000167AE111400000030000000000000000000000000000000000000003000000000susemanager-schema/susemanager-schema-rpmlintrc   addFilter("suse-filelist-forbidden-sysconfig")

0707010000038D000081B400000000000000000000000167AE11140000F2FB000000000000000000000000000000000000002E00000000susemanager-schema/susemanager-schema.changes -------------------------------------------------------------------
Thu Feb 13 16:32:53 CET 2025 - rosuna@suse.com

- version 4.3.28-0
  * Execute the cobbler-sync-default task every 5 minutes by default
    (bsc#1219450)
  * Ensure reporting database uses lowercase usernames (bsc#1220494)
  * Rename table suseProductSCCRepository to the more meaningful
    name suseChannelTemplate
  * Add table and columns to store additional telemetry data
    (jsc#SUMA-406)

-------------------------------------------------------------------
Mon Sep 02 15:07:01 CEST 2024 - rosuna@suse.com

- version 4.3.27-0
  * Introduce new attributes to detect PTF packages (bsc#1225619)

-------------------------------------------------------------------
Thu Jun 06 17:05:43 CEST 2024 - rosuna@suse.com

- version 4.3.26-0
  * Update list of package GPG keys in the database

-------------------------------------------------------------------
Fri Apr 12 17:11:51 CEST 2024 - rosuna@suse.com

- version 4.3.25-0
  * Add update-salt to internal state table

-------------------------------------------------------------------
Tue Jan 23 14:15:01 CET 2024 - rosuna@suse.com

- version 4.3.24-1
  * Refactor susecredentials to support the new hierarchy
  * Improve performance of System (bsc#1211254)
  * Change schedule of system-profile-refresh to run on the 2nd Saturday
    of a month to not collide with normal working times (bsc#1215769)

-------------------------------------------------------------------
Fri Dec 15 12:42:01 CET 2023 - marina.latini@suse.com

- version 4.3.23-1
  * Revert adding unique index for rhnpackagechangelogdata table
    (bsc#1218027)

-------------------------------------------------------------------
Mon Nov 20 11:54:38 CET 2023 - rosuna@suse.com

- version 4.3.22-1
  * Drop special versioned schema files
  * Add unique index for rhnpackagechangelogdata table

-------------------------------------------------------------------
Mon Oct 09 17:50:35 CEST 2023 - marina.latini@suse.com

- version 4.3.21-1
  * Add index on server needed cache to improve performance for some queries (bsc#1211912)
  * Moved the Ubuntu errata processing in its own separate taskomatic
    task (bsc#1211145) 

-------------------------------------------------------------------
Tue Aug 29 15:40:55 CEST 2023 - marina.latini@suse.com

- version 4.3.20-1
  * Add new credentials type RHUI
  * Store the Pay-as-you-go products

-------------------------------------------------------------------
Tue Jun 27 16:22:24 CEST 2023 - marina.latini@suse.com

- version 4.3.19-1
  * Added pay-as-you-go dimension computation taskomatic job configuration
  * Added new tables to handle pay-as-you-go instances computations
  * Speedup old schema migration

-------------------------------------------------------------------
Mon Apr 24 09:14:00 CEST 2023 - jgonzalez@suse.com

- version 4.3.18-1
  * Recurring custom states
  * Added view to handle ptf packages and updated the procedures
    to refresh the updatable/installable packages
  * Fix update of sql function create_new_org
  * Filter CLM modular packages using release strings (bsc#1207814)

-------------------------------------------------------------------
Wed Feb 22 14:44:44 CET 2023 - jgonzalez@suse.com

- version 4.3.17-1
  * Remove rhnTaskoRun log paths
  * enhance CPU table by core and thread information
  * add trigger on cpu and virtual instance to re-sending
    virtualization information to SCC
  * Add 'none' matcher to CLM AppStream filters (bsc#1206817)

-------------------------------------------------------------------
Wed Jan 11 12:42:25 CET 2023 - jgonzalez@suse.com

- version 4.3.16-1
  * Remove legacy cluster_admin user group
  * add subscription warning info pane
  * Remove data related to RHEL below 6
  * Increase cron_expr varchar length to 120 in suseRecurringAction
    table (bsc#1205040)

-------------------------------------------------------------------
Tue Nov 15 16:54:35 UTC 2022 - marina.latini@suse.com

- version 4.3.15-1
  * added kickstart distribution data for RHEL 9
  * Fix previous 'Amazon EC2' schema upgrade script
    to prevent possible issues on schema upgrade.
  * Change 'Amazon EC2/KVM' to 'Amazon EC2/Nitro' (bsc#1203685)
  * Keep older module metadata files in database (bsc#1201893)
  * Fix setting of last modified date in channel clone procedure

-------------------------------------------------------------------
Mon Sep 26 12:23:06 UTC 2022 - marina.latini@suse.com

- version 4.3.14-1
  * Add subtypes for Amazon EC2 virtual instances (bsc#1195624)
  * Fix migration of image actions (bsc#1202272)
  * improve schema compatibility with Amazon RDS

-------------------------------------------------------------------
Wed Jul 27 14:11:40 CEST 2022 - jgonzalez@suse.com

- version 4.3.13-1
  * update GPG key urls in channels set by spacewalk-common-channels
  * add gpg key info to suseProductSCCRepository (bsc#1199984)
  * Move ImageSync pillars to database (bsc#1199157)

-------------------------------------------------------------------
Mon May 30 14:59:28 CEST 2022 - jgonzalez@suse.com

- version 4.3.12-1
  * Force a one-off VACUUM ANALYZE (bsc#1199985)

-------------------------------------------------------------------
Wed May 04 15:25:59 CEST 2022 - jgonzalez@suse.com

- version 4.3.11-1
  * Add missing_successors column to hold products without successors
  * Added Perl requirements.

-------------------------------------------------------------------
Tue Apr 19 12:12:19 CEST 2022 - jgonzalez@suse.com

- version 4.3.10-1
  * drop rhnSatelliteInfo and replace it with suseMgrServerInfo to
    store data about the reporting database settings
  * add checksum column for suseimagefile table
  * fix check on allowVendorChange
  * Store proxy SSH port in database

-------------------------------------------------------------------
Fri Mar 11 15:42:02 CET 2022 - jgonzalez@suse.com

- version 4.3.9-1
  * fix direct mode when calling reportdb
  * Improve image management
  * Store delta image info in the database
  * fix advisory status migration (bsc#1195765)
  * Corrected source URLs in spec file.

-------------------------------------------------------------------
Tue Feb 15 10:07:07 CET 2022 - jgonzalez@suse.com

- version 4.3.8-1
  * make tools aware of the reporting database
  * create taskomatic schedule to update report database
  * create susemanager-schema-utility RPM package
  * Replace not existing Asia/Beijing timezone with Asia/Shanghai (bsc#1194862)
  * Add created and modified fields to suseMinionInfo to make
    uyuni roster module cache validation more accurate
  * add ubuntu errata data and install handling
  * FIX error when an image profile / store is deleted
    during build / inspect action (bsc#1191597, bsc#1192150)
  * SLES PAYG client support on cloud

-------------------------------------------------------------------
Tue Jan 25 17:32:06 CET 2022 - jgonzalez@suse.com

- version 4.3.7-1
  * Rerun the migration from CentOS8 client tools to EL8 client
    tools, for users that workarounded the problem

-------------------------------------------------------------------
Mon Jan 24 17:02:22 CET 2022 - jgonzalez@suse.com

- version 4.3.6-1
  * Fix the migration for users that had CentOS 8 and/or Oracle
    Linux 8, and AlmaLinux 8 and/or Rocky Linux 8 as well

-------------------------------------------------------------------
Tue Jan 18 14:07:37 CET 2022 - jgonzalez@suse.com

- version 4.3.5-1
  * Continue with index migration when the expected indexes do not exist
    (bsc#1192566)
  * Add upgrade script to migrate pillar and formula data to database
  * Remove minion_pillars PL/SQL function
  * Force metadata files regeneration for Debian based repos
    to change the format of the repos to flat
  * Added rights column to rhnerrata to handle copyright information
  * Fix rhnChannelNewestPackageView in case there are duplicates (bsc#1193612)
  * Change rhnPackageCapability name data type to TEXT
  * Add support for custom SSH port for SSH minions
  * Fix changing of existing proxy path
  * Add pillars to Apply States action
  * require PostgreSQL14 on SUSE Linux Enteprise 15 SP4

-------------------------------------------------------------------
Fri Dec 03 12:32:54 CET 2021 - jgonzalez@suse.com

- version 4.3.4-1
  * Use Almalinux Mirror List
  * Use EL8 Client Tools for EL8 clones, as CentOS8 will be end of
    life by the end of the year

-------------------------------------------------------------------
Fri Nov 05 14:06:37 CET 2021 - jgonzalez@suse.com

- version 4.3.3-1
  * Add table to store salt pillars
  * Add 'flush_cache' flag to Ansible playbook execution action
    (bsc#1190405)
  * create unique index on package details action id (bsc#1190396, bsc#1190275)

-------------------------------------------------------------------
Fri Sep 17 12:16:58 CEST 2021 - jgonzalez@suse.com

- version 4.3.2-1
  * Support syncing patches with advisory status 'pending' (bsc#1190455)
  * allow Ansible Control Node entitlement for aarch64, ppc64le
    and s390x (bsc#1189799)
  * implement package locking for salt minions

-------------------------------------------------------------------
Mon Aug 09 11:10:15 CEST 2021 - jgonzalez@suse.com

- version 4.3.1-1
- Fix wrongly assigned entitlements due to system transfer (bsc#1188032)
- Force a one-off VACUUM ANALYZE
- Upgrade scripts idempotency fixes
- Simplify the VM creation action in DB
- Refresh virtual host pillar to clear the virtpoller beacon (bsc#1188393)
- Add Beijing timezone to selectable timezones (bsc#1188193)
- Add Rocky Linux 8 key and vendor
- Add 'test' flag to Ansible playbook actions
- Add Kiwi commandline options to Kiwi profile
- Handle virtual machines running on pacemaker cluster

-------------------------------------------------------------------
Fri Jun 18 15:20:08 CEST 2021 - jgonzalez@suse.com

- version 4.2.15-1
- Use the right URLs for the AlmaLinux 8 Uyuni client tools

-------------------------------------------------------------------
Mon May 24 18:32:50 CEST 2021 - jgonzalez@suse.com

- version 4.2.14-1
- Fix the migration issue to the latest schema version

-------------------------------------------------------------------
Mon May 24 12:41:06 CEST 2021 - jgonzalez@suse.com

- version 4.2.13-1
- Fix idempotency tests

-------------------------------------------------------------------
Mon May 10 17:46:22 CEST 2021 - jgonzalez@suse.com

- version 4.2.12-1
- AlmaLinux and Amazon Linux 2 Java enablement

-------------------------------------------------------------------
Wed May 05 16:43:35 CEST 2021 - jgonzalez@suse.com

- version 4.2.11-1
- DB schema to support forwarding data to SCC
- Rename SP to product migration
- Ansible integration: configure control node paths (playbooks and inventories)

-------------------------------------------------------------------
Fri Apr 16 13:29:49 CEST 2021 - jgonzalez@suse.com

- version 4.2.10-1
- DB schema & migrations for retracted patches
- Add support for Alibaba Cloud Linux 2
- Add EPEL 8 GPG key to database so the "content provider" of the package is showed corretly in the UI
- Raise length limit for kernel options (bsc#1182916)
- add rhnactiondetails table for handling allow vendor change for errata/install/upgrade actions
- add virtual network create action

-------------------------------------------------------------------
Fri Mar 05 15:44:38 CET 2021 - jgonzalez@suse.com

- version 4.2.9-1
- Add 'is_primary' column to rhnServerFqdn table
- Fix: increase password length in the database (bsc#1182687)

-------------------------------------------------------------------
Thu Feb 25 12:12:06 CET 2021 - jgonzalez@suse.com

- version 4.2.8-1
- Provide migration for rhnActionImageBuild
- Rename rhnVirtualInstanceInfo memory_size_k column
- Drop "pxt_session_cleanup" function (bsc#1180224)

-------------------------------------------------------------------
Fri Feb 12 14:35:19 CET 2021 - jgonzalez@suse.com

- version 4.2.7-1
- enable openscap auditing for salt systems in SSM (bsc#1157711)
- Removed "Software Crashes" feature

-------------------------------------------------------------------
Fri Jan 29 16:52:34 CET 2021 - jgonzalez@suse.com

- version 4.2.6-1
- Restore removed changelog entries

-------------------------------------------------------------------
Wed Jan 27 13:10:03 CET 2021 - jgonzalez@suse.com

- version 4.2.5-1
- Improve cleanup time after fixing Debian package version comparison (bsc#1181116)
- Update to postgresql13 (jsc#SLE-17030)
- Update CentOS6 URLs to use vault.centos.org
- Changed to versioned Python3 to SPEC file.
- Python3 port for blend tool
- add missing unique index on suse tables
- internal code cleanup (dropping unused table rhnErrataTmp)
- Fix Debian package version comparison
- Move dist upgrade SQL file to the correct directory so it gets picked up in schema upgrades (bsc#1179759)

-------------------------------------------------------------------
Thu Dec 03 13:58:08 CET 2020 - jgonzalez@suse.com

- version 4.2.4-1
- add the VirtualPC type in rhnVirtualInstanceType table(bsc#1178990)
- add new valid countries and timezones (jsc#PM-2081)
- Fix: Don't fail on empty os-release line.

-------------------------------------------------------------------
Wed Nov 25 12:30:54 CET 2020 - jgonzalez@suse.com

- version 4.2.3-1
- Add web_theme user preferences column (bsc#1178204)
- Add 'preferred_docs_locale' to UserInfo table
- add new column to rhnactiondup table for allowVendorChange flag
- Add cobbler-related fields in VM Creation action table
- Execute Salt SSH actions in parallel (bsc#1173199)
- Hotfix the modular RPMs release comparison
- show info message when applying schema upgrade
- Fix: handle version comparison corner cases in Ubuntu packages

-------------------------------------------------------------------
Mon Sep 21 18:42:16 CEST 2020 - jgonzalez@suse.com

- version 4.2.2-1
- Schema upgrade for Debian with ARM64v8+ (cpuach=aarch64, cpuarch=arm64) architecture

-------------------------------------------------------------------
Fri Sep 18 12:27:41 CEST 2020 - jgonzalez@suse.com

- version 4.2.1-1
- support installer update channels during autoinstallation
- Prevent a deadlock error involving delete_server and update_needed_cache (bsc#1173073)
- Add new states and types for virtual instances in order
  to support Nutanix AHV.
- implement Maintenance Windows
- add virtual network state change action
- Update package version to 4.2.0

-------------------------------------------------------------------
Thu Jul 23 13:36:46 CEST 2020 - jgonzalez@suse.com

- version 4.1.11-1
- Internal fixes to avoid problems with the idempotency tests

-------------------------------------------------------------------
Mon Jun 29 10:11:12 CEST 2020 - jgonzalez@suse.com

- version 4.1.10-1
- add new comps type mediaproducts (bsc#1173204)
- Fix: handle corner case of deb pkg compare version (bsc#1173201)

-------------------------------------------------------------------
Tue Jun 23 17:24:11 CEST 2020 - jgonzalez@suse.com

- version 4.1.9-1
- Add VM disk format support
- Enable osimage_build_host for additional architectures (bsc#1149101, bsc#1172076)

-------------------------------------------------------------------
Wed Jun 10 12:40:28 CEST 2020 - jgonzalez@suse.com

- version 4.1.8-1
- Add tables for cluster management
- Enable the monitoring entitlement for s390x (bsc#1172627)
- update package provider name
- add new gpg key ids for some package providers

-------------------------------------------------------------------
Wed May 20 11:05:12 CEST 2020 - jgonzalez@suse.com

- version 4.1.7-1
- fix the place for the virtualization pool actions schema upgrade scripts
- added an index to improve reposync performance
- Update schema for virtual volume delete action

-------------------------------------------------------------------
Mon Apr 13 09:46:40 CEST 2020 - jgonzalez@suse.com

- version 4.1.6-1
- run DB schema upgrade automatically on package update
- change notification data type to TEXT
- Update schema for virtualization pool actions

-------------------------------------------------------------------
Thu Mar 19 12:19:27 CET 2020 - jgonzalez@suse.com

- version 4.1.5-1
- Enable monitoring for ppc64le and aarch64 (bsc#1166613)

-------------------------------------------------------------------
Wed Mar 11 11:02:33 CET 2020 - jgonzalez@suse.com

- version 4.1.4-1
- Update schema and add migration script for 'Recurring Actions'
- Show proxy icon in system list
- drop oracle artefacts
- drop tables and data used for forwarding registrations to NCC

-------------------------------------------------------------------
Mon Feb 17 12:56:07 CET 2020 - jgonzalez@suse.com

- version 4.1.3-1
- Add new 'payg' attribute to rhnServer table

-------------------------------------------------------------------
Wed Jan 22 12:24:20 CET 2020 - jgonzalez@suse.com

- version 4.1.2-1
- enable re-activation keys for salt managed systems (bsc#1159012)
- generate metadata with empty vendor (bsc#1158480)
- Prevent SELECT INSTR error in Postgres logs every minute (bsc#1157034)
- Fix rhnActionVirtDelete when migrating from 3.2 to 4.0 (bsc#1158178)

-------------------------------------------------------------------
Wed Nov 27 17:07:32 CET 2019 - jgonzalez@suse.com

- version 4.1.1-1
- Migration paths from 4.0.15, 4.0.15 and 4.0.17 to 4.1.0
- Migration paths from 3.2.20 and 3.2.22 to 4.0.0
- Migration path from 3.2.21 to 4.0.0 (bsc#1155030)
- Fix: regression with Ubuntu version compare (bsc#1150113)
- Bump version to 4.1.0 (bsc#1154940)
- Fix in schema migration script when recreating the 'suseUserRoleView' (bsc#1151280)
- Fix: handle special deb package names (bsc#1150113)
- Refactor in suseChannelUserRoleView for retrieving the parent_channel_id (bsc#1151399)
- Add tables rhnPackageExtraTag and rhnPackageExtraTagKey
- Allow monitoring for Ubuntu systems
- Add new types needed for Azure, Amazon EC2 and Google CE
- Migrate login to Spark
- enable provisioning for salt clients
- Allow package changelog entries with more than 3000 characters (bsc#1144889)
- add caret sorting for rpm versioning
- allow repo and manifest sources with the same url
- improve performance for retrieving the user permissions on channels (bsc#1140644)

-------------------------------------------------------------------
Wed Jul 31 17:40:45 CEST 2019 - jgonzalez@suse.com

- version 4.0.13-1
- Drop no longer used 'allServerKeywordSinceReboot' view (fate#327780)
- Allow forcing off or resetting VMs
- fix schema migration for suseSCCRepositoryAuth (bsc#1136558)
- Add built time column to suseContentEnvironmentTarget

-------------------------------------------------------------------
Wed May 15 15:34:53 CEST 2019 - jgonzalez@suse.com

- version 4.0.12-1
- SPEC cleanup
- add a queue column to suseSaltEvent table to support processing of all salt events of a single minion on the same thread
- Add monitoring entitlement
- set max length for xccdf rule identifier to 255 to prevent internal server error (bsc#1125492)
- copy 3.2 schema migrations to 4.0 to be able to migrate from an older
  schema version to 4.0
- clean the susesccrepository table before modify it (bsc#1125456)

-------------------------------------------------------------------
Mon Apr 22 12:23:15 CEST 2019 - jgonzalez@suse.com

- version 4.0.11-1
- Add support for Salt batch execution mode
- Add a Taskomatic job to perform minion check-in regularly, drop use of Salt's Mine (bsc#1122837)
- changed regex in spacewalk-schema-upgrade to also match alnum characters in release

-------------------------------------------------------------------
Fri Mar 29 10:37:00 CET 2019 - jgonzalez@suse.com

- version 4.0.10-1
- Schema for the Content Management feature
- fix performance regression in inter-server-sync (bsc#1128781)

-------------------------------------------------------------------
Mon Mar 25 17:03:42 CET 2019 - jgonzalez@suse.com

- version 4.0.9-1
- upgrade xccdf ident data for changed table structure
- Set minion-action-cleanup run frequency from hourly to daily at midnight
- Archive orphan actions when a system is deleted and make them visible in the UI (bsc#1118213)

-------------------------------------------------------------------
Sat Mar 02 00:15:31 CET 2019 - jgonzalez@suse.com

- version 4.0.8-1
- removing invalid suse-openstack-cloud-6 and suse-packagehub-12-sp4 channel_labels (bsc#1125451)

-------------------------------------------------------------------
Wed Feb 27 13:17:04 CET 2019 - jgonzalez@suse.com

- version 4.0.7-1
- add missing schema upgrade paths
- Add virtual machine creation action

-------------------------------------------------------------------
Thu Jan 31 10:13:33 CET 2019 - jgonzalez@suse.com

- version 4.0.6-1
- Add missing migration paths

-------------------------------------------------------------------
Thu Jan 31 09:45:14 CET 2019 - jgonzalez@suse.com

- version 4.0.5-1
- remove wrong channel_family labels (bsc#1123189)
- Remove unused 'remove_servergroup_perm' stored procedure (bsc#1111810)

-------------------------------------------------------------------
Wed Jan 16 12:28:37 CET 2019 - jgonzalez@suse.com

- version 4.0.4-1
- change SCC sync backend to adapt quicker to SCC changes and improve
  speed of syncing metadata and checking for channel dependencies

-------------------------------------------------------------------
Mon Dec 17 14:45:07 CET 2018 - jgonzalez@suse.com

- version 4.0.3-1
- Add Uyuni GPG to the database
- Performance improvements in channel management functionalities (bsc#1114877)
- use a Salt engine to process return results (bsc#1099988)
- Automatic cleanup of notification messages after a configurable lifetime
- Add missing minion-action-chain-cleanup to db init scripts

-------------------------------------------------------------------
Fri Oct 26 10:51:55 CEST 2018 - jgonzalez@suse.com

- version 4.0.2-1
- Add index for HW address on network interface
- added kickstart distribution data for RHEL 8
- check valid postgresql database version
- Enable auto patch updates for Salt minions

-------------------------------------------------------------------
Fri Aug 10 15:45:07 CEST 2018 - jgonzalez@suse.com

- version 4.0.1-1
- Bump version to 4.0.0 (bsc#1104034)
- Enable system preferences for Salt minions (bsc#1098388)
- Fix copyright for the package specfile (bsc#1103696)
- Feat: add OS Image building with Kiwi FATE#322959 FATE#323057 FATE#323056
- copy missing action-chain schema migration to correct directory
  (bsc#1100760)
- Fix truncated result message of server actions (bsc#1039043)
- Fix config channels state revision inconsistency after migration (bsc#1094543)

-------------------------------------------------------------------
Tue Jun 05 10:22:49 CEST 2018 - jgonzalez@suse.com

- version 3.2.11-1
- Fix migration path between 3.1 and 3.2 (bsc#1095398)

-------------------------------------------------------------------
Wed May 23 09:02:48 CEST 2018 - jgonzalez@suse.com

- version 3.2.10-1
- Fix issue with "suse_img_repodigest_idx" index if multiple image
  tags (bsc#1090664)

-------------------------------------------------------------------
Thu May 17 08:41:37 CEST 2018 - jgonzalez@suse.com

- version 3.2.9-1
- Fix: migration from 3.0 to 3.1 related to rhnServerNetwork (bsc#1086996)

-------------------------------------------------------------------
Mon Apr 23 09:25:19 CEST 2018 - jgonzalez@suse.com

- version 3.2.8-1
- add SLE15 distribution (bsc#1090205)
- fix a race condition on lookup_evr (bsc#1090059)
- Clean up SUSE Studio credentials from the DB
- fix schema migration by creating correct not null column (bsc#1074642)
- fix invalid name for quartz migration file (bsc#1088870)
- fix migration error with not null column (bsc#1088818)

-------------------------------------------------------------------
Thu Mar 29 01:26:41 CEST 2018 - jgonzalez@suse.com

- version 3.2.7-1
- SLE15 support: recommended/required flag for products and channels
- remove update of not existing table (bsc#1087131)
- handle duplicate rhnserverpackage (bsc#1075345)

-------------------------------------------------------------------
Mon Mar 26 15:09:48 CEST 2018 - jgonzalez@suse.com

- version 3.2.6-1
- Enable upgrades from 3.1
- Allow scheduling the change of software channels as an action. The previous channels remain accessible
  to the registered system until the action is executed.
- handle duplicate serverpackage entries while fixing duplicate evr ids (bsc#1075345)
- Add Adelaide timezone to selectable timezones (bsc#1063891)
- Add schema migration to support Action Chain for Minions.
- Prevent migration failure when multiple empty file contents are present (bsc#1083706, bsc#1083937)

-------------------------------------------------------------------
Mon Mar 05 09:08:34 CET 2018 - jgonzalez@suse.com

- version 3.2.5-1
- support SLE15 product family
- remove clean section from spec (bsc#1083294)

-------------------------------------------------------------------
Wed Feb 28 10:13:24 CET 2018 - jgonzalez@suse.com

- version 3.2.4-1
- Make migration idempotent (bsc#1078749)
- Fix: schema with proper extension (bsc#1079820)
- 1542287 - purge records that would be violating unique constraint during fixup
- 1542287 - we don't have solaris table anymore
- 1541955 - Clone of an erratum doesn't have original erratum's severity

-------------------------------------------------------------------
Mon Feb 05 12:52:43 CET 2018 - jgonzalez@suse.com

- version 3.2.3-1
- Allow scheduling the change of software channels as an action.
  The previous channels remain accessible to the registered system
  until the action is executed.

-------------------------------------------------------------------
Fri Feb 02 13:05:40 CET 2018 - jgonzalez@suse.com

- version 3.2.2-1
- Migrate old custom states to state channels, assign systems to these new
  channels, delete old custom-state-to-system assignments, delete the custom
  states from the db; Before migrating, rename custom states with same name as
  existing configuration channel labels.
- Update queries for global channels
- Check if channel is already subscribed even before checking if parent channel is subscribed or not (bsc#1072797)
- support multiple FQDNs per system (bsc#1063419)
- avoid use of the potentially-slow rhnServerNeededPackageCache view

-------------------------------------------------------------------
Wed Jan 17 13:30:11 CET 2018 - jgonzalez@suse.com

- version 3.2.1-1
- Update to Quartz 2.3.0 (bsc#1049431)
- fix duplicate entries in channel listings
- handle nevra not found case while fixing duplicate evr ids (bsc#1074508)
- Added a script which will remove existing server locks against minions (bsc#1064258)
- Add column to store the 'test' option for state apply actions
- Adding initial version of web ui notifications

-------------------------------------------------------------------
Tue Nov 28 15:01:50 CET 2017 - jgonzalez@suse.com

- version 3.1.13-1
- Add Adelaide timezone to selectable timezones (bsc#1063891)
- Added new relationships for Salt config management
- Added new config channel type(state) and file type(sls)
- Enable 'Power Management' features on Salt minions.
- enablement of the package profile feature for minions
- re-create unique index on minion_id (bsc#1059568, bsc#1056358)
- increase max length of hardware address to 32 byte (bsc#989991)
- fix unique index for evr and capability and remove duplicates
  during migration (bsc#1058110)
- rhnServerNetwork refactoring (bsc#1063419)

-------------------------------------------------------------------
Thu Sep 14 17:36:43 CEST 2017 - mc@suse.de

- version 3.1.12-1
- provide schema upgrade path from 3.0.21 to 3.1

-------------------------------------------------------------------
Thu Sep 14 11:26:31 CEST 2017 - mc@suse.de

- version 3.1.11-1
- DB objects for Kubernetes integration

-------------------------------------------------------------------
Wed Aug 30 15:56:40 CEST 2017 - mc@suse.de

- version 3.1.10-1
- Backend for importing images
- Fix unsetting of image build host when a related action is deleted

-------------------------------------------------------------------
Tue Aug 08 11:43:14 CEST 2017 - fkobzik@suse.de

- version 3.1.9-1
- Adapt for the new gpgcheck flag for the channels

-------------------------------------------------------------------
Mon Jun 12 09:13:09 CEST 2017 - mc@suse.de

- version 3.1.8-1
- Correct overly-broad comparison in the fixup-functions
  Set ORA back to INDEX from CONSTRAINT (bsc#1043778)

-------------------------------------------------------------------
Mon May 29 16:06:25 CEST 2017 - mc@suse.de

- version 3.1.7-1
- support schema upgrade from 3.0.20 to 3.1
- add base column to suseProducts
- add channel_family_id column to suseProducts (bsc#1031716)
- Add inspect status and reinspect button to image overview page
- Teach Postgres to correctly-unique-ify rhnConfigInfo rows
- recreate possible missing data (bsc#1032798)
- add logging to can_entitle_server function to write out the reason of a
  failure (bsc#1032798)
- fix index behaviour on NULL org
- drop filters while deleting repository
- postgresql 8.4 doesn't support WITH and DELETE combination
- remove links between errata and files from different orgs
- allow sync of the same erratum to more orgs

-------------------------------------------------------------------
Wed May 03 16:08:05 CEST 2017 - michele.bologna@suse.com

- version 3.1.6-1
- Version 2.7.16-1
- take care that capability name exists (bsc#1035724)
- copy missing migrations from 3.0

-------------------------------------------------------------------
Mon Apr 03 15:02:02 CEST 2017 - mc@suse.de

- version 3.1.5-1
- DB: create suseCVEImageChannel table for CVE Audit on Images
- drop obsolete logging trigger if they still exist (bsc#1031266)
- rename image tag to image version
- fix constraint name in suseImageInfo
- fix removing images and profiles with custom values
- Add SQL scripts for scheduling in Quartz
- add number of installed packages to ImageOverview
- link ImageInfo checksum to Checksum table
- add registry credentials type during schema upgrade
- Some of monitoring data are not removed from DB
- connect 3.0 to 3.1 schema upgrade

-------------------------------------------------------------------
Tue Mar 07 14:50:03 CET 2017 - mc@suse.de

- version 3.1.4-1
- grant minions scap capability
- add modified trigger for suseImageInfo
- add table suseImageInfoInstalledProduct
- add image inspect action
- schema upgrade for suseImageOverview and ImageNeededChache views
- create views, tables and procs for counting available updates on images
- DB: move target store to image profile
- add image_admin to existing organizations
- Migrating Fedorahosted to GitHub
- show update message only when updating the schema package (bsc#1024456)
- Remove legacy audit logging database code
- fix deduplicate to work with more than two duplicates
- merge valid column migration with create table
- fix error on channel delete with tokens bsc#1024471
- save ssl in separate table again, now allow to have multiple ssl
  sets per content source
- Create token index
- Add AccessToken.valid column and use it to reject tokens

-------------------------------------------------------------------
Tue Feb 07 15:33:50 CET 2017 - michele.bologna@suse.com

- version 3.1.2.1-1
- drop index before it gets re-created and use if exists for postgres
  (bsc#1021381)

-------------------------------------------------------------------
Wed Jan 11 16:56:57 CET 2017 - michele.bologna@suse.com

- version 3.1.2-1
- Version 3.1.1

-------------------------------------------------------------------
Fri Dec 16 16:34:11 CET 2016 - michele.bologna@suse.com

- version 3.0.17-1
- Schema upgrade for live patching (FATE#319519)

-------------------------------------------------------------------
Mon Nov 07 10:49:32 CET 2016 - michele.bologna@suse.com

- version 3.0.16-1
- Create path for schema upgrade to 3.0
- Add table for storing product extensions

-------------------------------------------------------------------
Thu Oct 06 15:34:15 CEST 2016 - mc@suse.de

- version 3.0.15-1
- Add table for storing product extensions
- Add severity_id to rhnErrataTmp for consistency with rhnErrata
  (bsc#1000666)
- Fixing suseMinionInfo.sql to make 'osFamily' NULLABLE
- delete rhnContentSourceFilter before rhnContentSource (bsc#998380)
- Avoid a deadlock when deleting a server (bsc#969790)

-------------------------------------------------------------------
Mon Jul 18 14:12:49 CEST 2016 - jrenner@suse.com

- version 3.0.14-1
- Add missing power_management feature for bootstrap_entitlement systems
- Fix HW Refresh duplicate insert (bsc#971622)
- add taskomatic job to clean up minion actions
- provide seperate migration scripts for oracle
- shorten constaint names and fix syntax (FATE#320213)
- Remove duplicates from rhnChannelContentSource (bsc#976184)

-------------------------------------------------------------------
Tue May 24 15:55:53 CEST 2016 - kwalter@suse.com

- version 3.0.13-1
- move machine_id from suseMinionInfo to rhnServer table
- fix removing nonlinux entitlement during migration
- fix migrating and cleanup system types during migration (bsc#977465)
- Enable ftr_package_refresh for minions

-------------------------------------------------------------------
Wed Apr 06 08:43:47 CEST 2016 - mc@suse.de

- version 3.0.12-1
- change unique index to partial (bsc#973673)
- move sql to enable refresh hardware feature (bsc#972305)
- check ftr_hardware_refresh when showing 'Refresh Hardware' button
  (bsc#972305)
- trigger metadata generation for all channels (bsc#972972)

-------------------------------------------------------------------
Tue Mar 22 09:57:18 CET 2016 - mc@suse.de

- fix schema upgrade using if exists for dropping a sequence

-------------------------------------------------------------------
Mon Mar 21 17:40:17 CET 2016 - mc@suse.de

- version 3.0.11-1
- add missing database commit
- adding missing Oracle upgrade
- delete sync probe task
- sequnce rhn_org_entitlement_type_seq should be dropped
- drop unused tables/sequences/synonyms/etc.
- Rename DB migration file
- Add support for package removals on minions (DB changes)
- Enable 'ftr_package_updates' on minions
- support schema upgrade from schema 2.1.50.16 to 3.0.X
- fix schema upgrade from Beta2 to RC1 (bsc#971543)

-------------------------------------------------------------------
Wed Mar 09 11:33:06 CET 2016 - mc@suse.de

- version 3.0.10-1
- add tables for State Apply
- add tables for Subscription Pinning
- Declare the base entitlements permanent
- fixing upgrade on Oracle
- Allow null for the state names in the DB (meaning highstate)
- rename KSInstallTypes to SUSE Linux Enterprise
- db tables for minion state selection
- Rename 'unmatched systems' CSV report to 'unmatched products'
- add Chile to the list of timezones (bsc#959055)
- Add features to enable reboot and remote commands for salt minions
- enable system group ui for salt minions
- Use blob as a backing db type for MatcherRunData, assign name to the
  constraint, fix the migration script directory
- DB: Table for SubscriptionMatchingData
- When deleting a server, delete all associated rhnSet entries
- no need to lock table since we don't update entitlements

-------------------------------------------------------------------
Wed Jan 27 16:02:01 CET 2016 - mc@suse.de

- version 3.0.9-1
- Create suseMinionInfo table when migrating to 3.0 (bsc#963789)

-------------------------------------------------------------------
Tue Jan 26 14:09:42 CET 2016 - mc@suse.de

- version 3.0.8-1
- Fix the SCCOrderItem null quantity issue by dropping the 'not null'
  constraint
- Rename 'equal' to 'any' in the database
- schema: rename saltstack_entitled to salt_entitled
- Add the free flag to SUSEProduct
- move the migration for bsc#959055 fix into the right schema version
- add support for schema migration from 2.1 to 3.0
- add schema upgrade for bsc#959055 to susemanager-schema-3.0 migration
- add Chile to the list of timezones (bsc#959055)

-------------------------------------------------------------------
Sat Jan 16 11:37:29 CET 2016 - mc@suse.de

- version 3.0.7-1
- delete one more obsolete table

-------------------------------------------------------------------
Thu Jan 14 13:24:08 CET 2016 - mc@suse.de

- version 3.0.6-1
- Update copyright headers to 2016 for all new files
- Add 'ftr_errata_updates' to saltstack entitled systems
- Add MinionServer as subclass of Server
- purge duplicate uuid records during upgrade process
- Use public channel families for SUSE channels (bsc#958708)
- purge uuid records after deleting a system

-------------------------------------------------------------------
Wed Dec 16 11:22:39 CET 2015 - mc@suse.de

- version 3.0.5-1
- Add taskomatic task for running subscription matcher
- add caching table for order items
- add caching table for SCCSubscriptions
- create table susePinnedSubscription
- Fix unique constraint name (after column was renamed)
- enhance create_new_org to create the first org as well and
  drop create_first_org
- during installation insert default SSL crypto key with null org

-------------------------------------------------------------------
Thu Dec 10 17:54:52 CET 2015 - mc@suse.de

- version 3.0.4-1
 Initial sql to create the suseServerState table
- SQL files for package states
- get rid of pltcl by disabling upstream logging.

-------------------------------------------------------------------
Mon Nov 30 11:13:50 CET 2015 - mc@suse.de

- version 3.0.3-1
- avoid cascade at function dropping
- When deleting a server, delete all associated rhnSet entries, even if it was
  migrated to a different Org (bsc#950748)
- drop obsolete postgresql functions on schema_upgrade
- drop removed functions from rhn_channel and rhn_entitlements
- remove current_members and available_members from rhnAvailableChannels view
- Add new foreign and saltstack server groups during schema update
- Enlarge rhnServer.digital_server_id size to 1024 characters
- clear log_id also for postgresql DB

-------------------------------------------------------------------
Thu Oct 22 16:29:40 CEST 2015 - mc@suse.de

- version 3.0.2-1
- Fix license header
- Taskomatic job for gatherer
- add new foreign_entitled entitlement and migrations for it
- create a unique index on suseServerVirtualHostManager
- add new foreign_entitled entitlement
- Add migrations for Virtual Host Manager
- Add tables for Virtual Host Manager
- Set job to run every minute if old schedule still active (bsc#918994)
- adding on delete cascade to sppf_pid_fk (bsc#948238)

-------------------------------------------------------------------
Wed Oct 07 16:51:51 CEST 2015 - mc@suse.de

- version 3.0.1-1
- drop monitoring
- replace upstream subscription counting with new subscription
  matching (FATE#311619)
- integrate SaltStack for configuration management (FATE#312447)
- drop monitoring
- replace upstream subscription counting with new subscription
  matching (FATE#311619)
- integrate SaltStack for configuration management (FATE#312447)
- support password-recovery-tokens
- remove solaris support

-------------------------------------------------------------------
Sun Sep 27 14:42:36 CEST 2015 - mc@suse.de

- version 2.1.50.14-1
- Set errata-cache job to run every minute if old schedule still
  active (bsc#918994)

-------------------------------------------------------------------
Mon Jun 22 15:40:54 CEST 2015 - jrenner@suse.de

- version 2.1.50.13-1
- Fix rpm version compare in DB (bsc#927940)
- Prevent from inserting duplicate update_server_errata_cache tasks
- Move auto-errata updates into separate taskomatic task
- Do not ignore errata with same package version

-------------------------------------------------------------------
Tue Mar 31 14:43:34 CEST 2015 - mc@suse.de

- version 2.1.50.12-1
- Fix ORA-01403: no data found in update_needed_cache during re-registrations
- Avoid a deadlock when changing channel assignments (bsc#918549)
- update adding aarch64 support to fix 1.7 to 2.1 update (bsc#922468)
- delete cached metadata and regenerate them (bsc#920400)

-------------------------------------------------------------------
Tue Feb 03 12:08:01 CET 2015 - mc@suse.de

- version 2.1.50.11-1
- some values can be already present at the time of upgrade
- fix NPE by setting max_members to 0 instead of NULL (bsc#912035)
- SCCRepository: save SCC ID in the database as well
- SCCRepository: save to database with proper sequence
- Fix old migration for future reference (bsc#911180)
- Avoid NPE when migrating to SCC on Oracle migrated from 1.7 (bsc#911180)
- renamed package upgrade scripts to .sql
- fixed double-counting systems subscribed to more than one channel
- Getting rid of Tabs and trailing spaces

-------------------------------------------------------------------
Thu Dec 04 16:27:47 CET 2014 - mc@suse.de

- version 2.1.50.10-1
- fix migration script names to fix bare-metal registration (bsc#896109)
- add virt-host-plat entitlement mappings for new arches
- Create regular index instead and have one migration per DB (bsc#905072)
- Drop unique index on package ids (bsc#905072)
- drop unused column product_list in suseProducts table
- drop unused column channel_family_id in suseProducts

-------------------------------------------------------------------
Fri Nov 07 13:20:08 CET 2014 - mc@suse.de

- version 2.1.50.9-1
- add SLE12 distro targets to DB
- randomize mgr-sync refresh task schedule
- add aarch64 server to noarch package mapping

-------------------------------------------------------------------
Tue Oct 14 15:17:50 CEST 2014 - mc@suse.de

- version 2.1.50.8-1
- increase source_url column size to 2048
- fix evr_t schema upgrade (bnc#881111)
- Speed up satellite-sync by avoiding commonly-called dblink_exec
- rhnDistChannelMap index needs to handle nulls on postgresql
- allow null for user_id in suseCredentials
- add scc credential type

-------------------------------------------------------------------
Fri Sep 12 16:02:16 CEST 2014 - mc@suse.de

- version 2.1.50.7-1
- implement tilde compare for 1.0~beta1 in version numbers
- force character set and numerical separators to good known
  defaults.
- increase size of update_tag column
- fixing order of commands
- make config file deletion faster if there are lots of snapshots
- make future installs run ErrataCache task more often
- add Fedora 21 GPG keys
- add CentOS 7 GPG key
- Fix rhnKickstartableTree trigger, 'null = null' is not true in sql
- Add support to ppc64le arch
- add Korea to the list of timezones
- Allow evr_t to be compared with NULL in Oracle (bnc#881111)

-------------------------------------------------------------------
Tue Jun 17 10:06:46 CEST 2014 - jrenner@suse.de

- version 2.1.50.6-1
- Index for user_id on wupi table speeds up errata mailer
- Copy upstream schema migration to SUSE Manager schema upgrade

-------------------------------------------------------------------
Fri May 16 13:14:25 CEST 2014 - mc@suse.de

- version 2.1.50.5-1
- DB: update tables dep file
- Rename suseEulas table to suseEula.
- EULA support: fix constraint name
- DB: Added tables required by the SUSE EULA

-------------------------------------------------------------------
Thu May 08 16:55:05 CEST 2014 - mc@suse.de

- version 2.1.50.4-1
- move web_contact_log migration to pre Beta3
- rename schema migration directories to support Beta 3 to Beta4 migration
- add migration dir for latest 1.7 schema version to 2.1
- add SLE12 GPG Package Key

-------------------------------------------------------------------
Tue May 06 15:18:35 CEST 2014 - mc@suse.de

- version 2.1.50.3-1
- DB: backport fixes for web_contact triggers
- reset package to avoid ORA-0406* errors
- schema upgrade for web_contact_log
- Backporting fix for web_contact migration
- fixing web_contact upgrade script
- rhnActionChain.id: explicitly name the primary index constraint
- Schema bugfix: Oracle doesn't like empty lines

-------------------------------------------------------------------
Thu Mar 27 10:22:30 CET 2014 - fcastelli@suse.com

- version 2.1.50.2-1
- SUMA db migration: reflect changes made by bb84025a
- Extending cron_expr length to 120
- SUMA db migration: change size of cron_expr
- Extending cron_expr column within the rhnTaskoSchedule table
- SUMA DB migration: change size of web_contact-password
- Extend length of web_contact.password to 110
- Missing aarch64 in rhnServerArch
- SUMA db update migration: add support for aarch64
- Schema upgrade for ARM aarch64 architecture support
- Support for ARM aarch64 architecture
- SUMA db upgrade migrations: drop web_contact-old_password
- Drop web_contact.old_password column from schema

-------------------------------------------------------------------
Thu Feb 27 16:25:04 CET 2014 - fcastelli@suse.com

- version 2.1.50.1-1
- enable migration from 1.7 to 2.1
- increase length of rhnCVE name column
- fix invalid syntax for postgresql migration
- write insert of bootstrap entitlement in a way, that it can be called
  multiple times
- copy upstream schema migrations to SUSE Manager schema upgrade
- replacing view must have the same number of columns (in postgresql)
- updated rhnServerOutdatePackages to include arch
- rhnServerOutdatedPackages schema upgrade script
- improved performance of system.listLatestUpgradeablePackages and
  UpgradableList.do
- Merged upgrade migrations from master
- update rhnServer after queue_server to avoid a deadlock
- copy upstream schema migration to SUSE Manager schema upgrade
- fix ORA-01422 error when removing a channel
- copy upstream schema changes to SUSE Manager schema upgrade
- fix ORA-01403: no data found, when unsubscribing a system
- rename upgrade scripts to be included in schema upgrade
- fix ORA-01403: no data found, during system registration

-------------------------------------------------------------------
Fri Feb 14 10:23:24 CET 2014 - mc@suse.de

- version 2.1.43.2-1
- bugfix for locking rhnServerNeededCache table with oracle DB

-------------------------------------------------------------------
Thu Feb 13 15:15:12 CET 2014 - mc@suse.de

- version 2.1.43.1-1
- New tables and upgrade scripts added for Action chaining
- lock rhnServerNeededCache to avoid a db deadlock
- Add missing GMT+3 timezone as Saudi Arabia
- fix rhn_channel.update_needed_cache() deadlock
- avoid deadlocks when altering base channels via ssm
- Add missing timezone schema migration into 1.7 to 2.1 (bnc#862406)
- Fix GMT+3 timezone missing (bnc#862406)

-------------------------------------------------------------------
Fri Feb 07 13:23:08 CET 2014 - mc@suse.de

- version 2.1.39.1-1
- upgrade script for Fedora 20 GPG key
- rename one and add another rhnConfiguration key
- update rhnUserExtGroupMapping triggers
- increase length of rhnCVE name column
- Tables to have mapping from external groups to internal roles
  (rhnUserGroupType).
- introduce rhnConfiguration table
- Changed gpg keys so they match reality.
- Moved package lock schema changes to proper location

-------------------------------------------------------------------
Mon Jan 13 09:46:05 CET 2014 - mc@suse.de

- version 2.1.30.2-1
- add reboot action cleanup task (FATE#312591)
- add rhnLockedPackages table. (FATE#312359)
- changes to rhnActionType (FATE#312359)
- updated rhnActionPackage parameter constraint
  (FATE#312359)

-------------------------------------------------------------------
Mon Dec 09 17:02:58 CET 2013 - mc@suse.de

- version 2.1.30.1-1
- support bare-metal registration (FATE#312329)
- provide schema update to 2.1

-------------------------------------------------------------------
Wed Dec 04 09:49:35 CET 2013 - mc@suse.de

- version 1.7.56.22-2
- fix invalid syntax for postgresql migration

-------------------------------------------------------------------
Thu Nov 28 16:23:12 CET 2013 - mc@suse.de

- version 1.7.56.22-1
- fix oracle syntax and provide seperate update script for postgres DB
  (bnc#846436)
- Regenerate the metadata for rpm enhances dependency (bnc#846436)
- add support for enhances rpm weak dependency (schema) (bnc#846436)

-------------------------------------------------------------------
Fri Aug 23 11:23:47 CEST 2013 - mc@suse.de

- version 1.7.56.21-1
- removing bad initial condition from max(evr_t)

-------------------------------------------------------------------
Wed Aug 21 16:02:08 CEST 2013 - mc@suse.de

- version 1.7.56.20-1
- rpm version comparison function was broken for alphanumeric versions
- Make CSV separator configurable, schema (FATE#312907)
- CVE Audit schema (FATE#312907)
- prevents empty values (db_host, db_port) in rhn.conf
- regenerate repodata for all channels to get package installed size
  (bnc#825673)
- make mgr-register-bunch a common bunch (bnc#824361)

-------------------------------------------------------------------
Wed Jun 12 11:00:29 CEST 2013 - mc@suse.de

- version 1.7.56.19-1
- Don't create index if it already exists
- Don't drop rhn_ram_sid_idx if it does not exist.
- No line break at the end of the package summary (bnc#821968)
- fixed filename length in rhnErrataFileTmp
- switch deferred segment creation off during installation
- extend length of rhnPackageCapability.version

-------------------------------------------------------------------
Thu May  2 18:08:24 CEST 2013 - mc@suse.de

- version 1.7.56.18-2
- Fix table name typo in DB migration

-------------------------------------------------------------------
Thu Apr 04 15:16:41 CEST 2013 - mc@suse.de

- version 1.7.56.18-1
- Quote the password we pass to sqlplus so that special characters can be used.
- Support recovery of failed schema upgrades (FATE#314644)
- SSH Server Push (schema) (FATE#312909)

-------------------------------------------------------------------
Fri Feb 08 11:23:44 CET 2013 - mc@suse.de

- version 1.7.56.17-1
- rebrand help text for mail domain
- correct olson name for Australia Western timezone
- support for Australia EST/EDT timezones
- take care that all migrations will be applied (bnc#797890)
- fix schema upgrade for rhnPackageCapability (bnc#793415)

-------------------------------------------------------------------
Thu Nov 22 15:57:59 CET 2012 - jrenner@suse.de

- version 1.7.56.16-1
- fix timezone problem while comparing reboot needed dates with oracle DB
  (bnc#790305)
- fix unique constraint violation occuring during schema upgrade
- add new openSUSE gpg keyid (bnc#789817)
- update descriptions in rhnKickstartSessionState (bnc#780270)
- SP migration DB schema changes

-------------------------------------------------------------------
Mon Oct 01 09:39:56 CEST 2012 - mc@suse.de

- version 1.7.56.15-1
- create view allServerKeywordSinceReboot
- extending rhnPackageCapability.version.
- oracles sql parser doesn't like comments after semicolon
- fix unique constraint violation (bnc#780913)
- schema upgrade for rhnChannelNewestPackageView
- make list of newest packages unique

-------------------------------------------------------------------
Wed Aug 15 14:57:17 CEST 2012 - mc@suse.de

- version 1.7.56.14-1
- fix insert pxt session when not logged-in

-------------------------------------------------------------------
Mon Aug  6 09:47:02 CEST 2012 - mc@suse.de

- version 1.7.56.13-1
- add schema upgrade for SUSE Manager 1.7 Beta3 to RC1
- add schema upgrade for SUSE Manager 1.7 RC1 to GMC

-------------------------------------------------------------------
Thu Aug 02 16:53:31 CEST 2012 - mc@suse.de

- fix schema upgrade scripts
- Properly name the primary index constraint/index for rhnActionImageDeploy.
- provide schema migration to full version
- check if cleanup-data-bunch exists and create it if not (bnc#772620)
- Preventing whole SQL string from being NULL
- If by accident pg_dblink_exec is given NULL string (e.g concatenation of
  string and NULL in pgsql) it raises an error.

-------------------------------------------------------------------
Mon Jul 16 15:23:34 CEST 2012 - ug@suse.de

- version 1.7.56.12-1
- Add the PostgreSQL specific mad_address upgrade script.
- We mustn't serialize object into string in lookup_evr, we need to only create
  it once within the link.
- Allow user to set MAC Address when provisioning a virtual guest
- Make the resulting data order more deterministic.

-------------------------------------------------------------------
Wed Jul 11 10:34:50 CEST 2012 - ug@suse.de

- added mac_address column to rhnactionkickstartguest

-------------------------------------------------------------------
Mon Jun 25 10:25:52 CEST 2012 - mc@suse.de

- version 1.7.56.11-1
- Make the .postgresql schema upgrade script actually use the
  PostgreSQL syntax.

-------------------------------------------------------------------
Thu Jun 21 11:04:11 CEST 2012 - jrenner@suse.de

- version 1.7.56.10-1
- Add index on ident_id for better performance
- Add index on testresult_id for better performance.
- We cannot use markup in formatted text (synopsis).
- lookup_tag: schema upgrade
- lookup_tag: don't call lookup_tag_name twice
- remove rhnRedHatCanonVersion table during upgrade
- removed support for Red Hat Linux 6.2 and 7.[0123]
- Temporarily disable triggers during schema upgrades

-------------------------------------------------------------------
Thu May 31 10:48:40 CEST 2012 - mc@suse.de

- version 1.7.56.9-1
- get rid of out parameters in user_role_check_debug
- forgotten rhnPackageSource update
- Schema upgrade script for the rhn_versioninfo_nid_eid_uq drop.
- No need to enforce unique (name_id, evr_id) on rhnVersionInfo.
- Database migration files for studio integration (suseCredentialsType etc.)
- fix various issues in PG variant of rhn_channel.convert_to_fve
- Improve upgrade time_series data move
- Fix rhnPackageChangeLog upgrade logic.
- remove unused cursor
- store suse metadata keywords

-------------------------------------------------------------------
Tue May 29 17:43:10 CEST 2012 - mc@suse.de

- add missing schema migration for rhnErrataBuglistTmp
  (bnc#764544)

-------------------------------------------------------------------
Mon May 14 10:44:12 CEST 2012 - mc@suse.de

- version 1.7.56.8-1
- adding create_first_org upgrade scripts
- adding rhn_org upgrade scripts
- adding rhn_config upgrade scripts
- remove rhnOrgQuota and its usage
- remove rhn_schema package
- remove usage of rhn_quota package
- kickstartable tree shall be deleted together with the channel
- Remove unnecessary UNIQUE constraint (on user_id in suseCredentials)
- fix rhn_time_zone_names upgrade scripts
- dropping unused rhn_time_zone_names
- Fix credentials type ID to not be unique (studio integration)

-------------------------------------------------------------------
Fri May 11 11:44:25 CEST 2012 - mc@suse.de

- make values in suseProductChannel unique before adding a
  unique index (bnc#760306)

-------------------------------------------------------------------
Wed May 09 13:45:17 CEST 2012 - mc@suse.de

- version 1.7.56.7-1
- use persistent dblink connection
- Completely remove the image type from deployment action details
- rename suse_credentialstype index and sequence names (bnc#764532)
- fix table dependencies (bnc#764532)
- Normalize image types by creating new table suseImageType
  (bnc#764532)
- Normalize credentials types by creating new table
  suseCredentialsType (bnc#764532)

-------------------------------------------------------------------
Thu May 03 17:43:31 CEST 2012 - mc@suse.de

- version 1.7.56.6-1
- make columns unique before adding a unique index - copy from sw1.6

-------------------------------------------------------------------
Wed May 02 14:25:48 CEST 2012 - mc@suse.de

- version 1.7.56.5-1
- Update existing rhn_notification_formats with the new newlines
  matching Oracle.
- Using PostgreSQL version of rhn_org.delete_org in upgrade scripts.
- We cannot specify tablespace for PostgreSQL.

-------------------------------------------------------------------
Fri Apr 27 16:08:16 CEST 2012 - mc@suse.de

- version 1.7.56.4-1
- fixing postgresql schema and adding appropriate schema upgrade
  scripts
- remove rhnContentSource row when delete row in oracle pkg
- add unique constraint on rhnChannelArch.name
- make sure that rows are unique before creating unique index
- We need to use to_timestamp, so that we do not miss the hour-to-second part
  on PostgreSQL.
- Quote newlines to match the Oracle behaviour.
- assign number of free slots

-------------------------------------------------------------------
Fri Apr 20 15:38:41 CEST 2012 - mc@suse.de

- version 1.7.56.3-1
- Make the records in rhnPackageUpgradeArchCompat -- no need to have
  duplicates.
- bring the schema version as recorded in the database in sync with
  the installed rpms, even if the difference is just the dist tag.
- the Log Size actually checks Log Size Growth.
- fix PG lookup_transaction_package stored procedure
- fix procedure dependencies

-------------------------------------------------------------------
Fri Mar 30 15:16:13 CEST 2012 - mc@suse.de

- version 1.7.56.2-1
- copy spacewalk schema updates 1.3, 1.4, 1.5, 1.6, 1.7 to
  susemanager schema 1.7 update
- copy some current upstream schema migrations
- fix spacewalk-schema-upgrade tool

-------------------------------------------------------------------
Fri Mar 23 10:16:38 CET 2012 - mc@suse.de

- version to 1.2.74
- add indexes for suseServerInstalledProduct and suseProductChannel

-------------------------------------------------------------------
Wed Mar 21 18:12:33 CET 2012 - mc@suse.de

- version 1.7.56.1-1
- Bumping package version

-------------------------------------------------------------------
Thu Mar 15 17:17:28 CET 2012 - jrenner@suse.de

- Add support for studio image deployments

-------------------------------------------------------------------
Mon Dec 19 15:36:54 CET 2011 - mc@suse.de

- new tables for storing package products (bnc#644678)

--------------------------------------------------------------------
Thu Nov 24 12:35:34 CET 2011 - iartarisi@suse.cz

- allow setting VARCHAR2 size in CHARs and BYTEs explicitly

-------------------------------------------------------------------
Fri Sep 23 10:04:17 CEST 2011 - mc@suse.de

- add index on rhnPackage checksum_id

-------------------------------------------------------------------
Thu Sep  8 16:21:55 CEST 2011 - iartarisi@suse.cz

- set result_message SQL column size in CHARs instead of BYTEs
  (bnc#700016)

-------------------------------------------------------------------
Wed Aug 10 09:07:05 UTC 2011 - kkaempf@novell.com

- add sles-10-i686 and sles-10-i686 to suseostarget
  bnc#711429
- version to 1.2.73

-------------------------------------------------------------------
Mon Aug  8 16:36:27 CEST 2011 - ug@suse.de

- fixed syntax error in schema upgrade (bnc#711007)

-------------------------------------------------------------------
Wed Jul 20 13:48:34 CEST 2011 - iartarisi@suse.cz

- set result_message SQL column size in BYTEs instead of CHARs
  (bnc#700016)

-------------------------------------------------------------------
Wed Jun  8 15:31:43 CEST 2011 - mc@suse.de

- version to 1.2.72
- provide SLE 10 ostargets (fate#312377, bnc#693104)

-------------------------------------------------------------------
Fri Mar 25 14:51:16 CET 2011 - ug@suse.de

- version to 1.2.71

-------------------------------------------------------------------
Thu Mar 24 14:35:49 CET 2011 - mantel@suse.de

- more debranding of kickstart to auto installation

-------------------------------------------------------------------
Thu Mar 24 14:28:43 CET 2011 - mantel@suse.de

- fix schema updates; debrand initial values for rhnactiontype

-------------------------------------------------------------------
Thu Mar 24 12:22:45 CET 2011 - mantel@suse.de

- debrand errata to patch (bnc#670318)

-------------------------------------------------------------------
Wed Mar 16 10:52:10 CET 2011 - ug@suse.de

- debranding some text in the database (bnc#673810)

-------------------------------------------------------------------
Thu Mar 10 17:04:04 CET 2011 - ug@suse.de

- Registration of REHL4 clients fails due to incomplete
  database table (bnc#678110)

-------------------------------------------------------------------
Thu Feb 17 13:13:27 CET 2011 - mc@suse.de

- fix copyright
- fix checksums

-------------------------------------------------------------------
Thu Feb 17 12:14:43 CET 2011 - mantel@suse.de

- rename "Satellite Administrator" to "SUSE Manager Administrator"
  (bnc#662077)

-------------------------------------------------------------------
Thu Feb 10 11:17:14 CET 2011 - jrenner@suse.de

- fix subscribe_server subs handling (bnc#670551)

-------------------------------------------------------------------
Fri Jan 28 12:45:44 CET 2011 - ug@suse.de

- rhntemplatestring table data changed to SUSE Manager

-------------------------------------------------------------------
Mon Jan 17 16:30:10 CET 2011 - mc@suse.de

- rename sm-register to mgr-register

-------------------------------------------------------------------
Mon Jan 17 12:25:25 CET 2011 - mc@suse.de

- change suseServer ostarget to a foreign key to suseOSTarget(id)
- fix data for suseOSTarget

-------------------------------------------------------------------
Wed Jan 12 17:23:13 CET 2011 - mc@suse.de

- add suseOSTarget table

-------------------------------------------------------------------
Wed Jan 12 10:37:28 CET 2011 - mc@suse.de

- add RES GPG Key to DB

-------------------------------------------------------------------
Tue Jan 11 18:04:58 CET 2011 - mc@suse.de

- add SUSE and Novell GPG Keys to DB

-------------------------------------------------------------------
Wed Sep 15 12:22:26 CEST 2010 - mantel@suse.de

- fix post-build-checks

-------------------------------------------------------------------
Wed Sep 15 09:53:07 CEST 2010 - mantel@suse.de

- Initial release of spacewalk-schema

-------------------------------------------------------------------
 0707010000038E000081B400000000000000000000000167AE111400001501000000000000000000000000000000000000002B00000000susemanager-schema/susemanager-schema.spec    #
# spec file for package susemanager-schema
#
# Copyright (c) 2021 SUSE LLC
# Copyright (c) 2008-2018 Red Hat, Inc.
#
# All modifications and additions to the file contributed by third parties
# remain the property of their copyright owners, unless otherwise agreed
# upon. The license for this file, and modifications and additions to the
# file, is the same license as for the pristine package itself (unless the
# license for the pristine package is not an Open Source License, in which
# case the license is the MIT License). An "Open Source License" is a
# license that conforms to the Open Source Definition (Version 1.9)
# published by the Open Source Initiative.

# Please submit bugfixes or comments via https://bugs.opensuse.org/
#


%{!?fedora: %global sbinpath /sbin}%{?fedora: %global sbinpath %{_sbindir}}

Name:           susemanager-schema
Summary:        SQL schema for Spacewalk server
License:        GPL-2.0-only
Group:          Applications/Internet

Version:        4.3.28
Release:        0
Source0:        https://github.com/uyuni-project/uyuni/archive/%{name}-%{version}-0.tar.gz
Source1:        https://raw.githubusercontent.com/uyuni-project/uyuni/%{name}-%{version}-0/schema/spacewalk/%{name}-rpmlintrc

URL:            https://github.com/uyuni-project/uyuni
BuildArch:      noarch
BuildRoot:      %{_tmppath}/%{name}-%{version}-build

BuildRequires:  /usr/bin/pod2man
BuildRequires:  fdupes
BuildRequires:  python3
BuildRequires:  perl(Digest::SHA)
BuildRequires:  perl(File::Find)
BuildRequires:  perl-macros
Requires:       %{sbinpath}/restorecon
Requires:       %{name}-utility

Provides:       spacewalk-schema = %{version}
Obsoletes:      rhn-satellite-schema <= 5.1.0

%if 0%{?suse_version}
BuildRequires:  fdupes
%endif

%define rhnroot /etc/sysconfig/rhn/
%define postgres %{rhnroot}/postgres
%define spacewalk_folder Spacewalk
%define schema_upgrade_folder %{spacewalk_folder}/SchemaUpgrade

%description
susemanager-schema is the SQL schema for the SUSE Manager server.

%package sanity
Summary:        Schema source sanity check for Spacewalk database scripts
Group:          Applications/Internet

Requires:       perl(Digest::SHA)

%package utility
Summary:        Utility used by any DB schema in Spacewalk
Group:          Applications/Internet

%description sanity
Provides schema-source-sanity-check.pl script for external usage.

%description utility
Provides spacewalk-schema-upgrade and spacewalk-sql.

%prep

%setup -q

%build
make -f Makefile.schema SCHEMA=%{name} VERSION=%{version} RELEASE=%{release}
pod2man spacewalk-schema-upgrade spacewalk-schema-upgrade.1
pod2man spacewalk-sql spacewalk-sql.1

%install
install -m 0755 -d $RPM_BUILD_ROOT%{rhnroot}
install -m 0755 -d $RPM_BUILD_ROOT%{postgres}
install -m 0644 postgres/main.sql $RPM_BUILD_ROOT%{postgres}
install -m 0644 postgres/end.sql $RPM_BUILD_ROOT%{postgres}/upgrade-end.sql
install -m 0755 -d $RPM_BUILD_ROOT%{_bindir}
install -m 0755 spacewalk-schema-upgrade $RPM_BUILD_ROOT%{_bindir}
install -m 0755 -d $RPM_BUILD_ROOT%{perl_vendorlib}/%{schema_upgrade_folder}
install -m 0755 lib/%{schema_upgrade_folder}/MainDb.pm $RPM_BUILD_ROOT%{perl_vendorlib}/%{schema_upgrade_folder}
install -m 0755 lib/%{schema_upgrade_folder}/ReportDb.pm $RPM_BUILD_ROOT%{perl_vendorlib}/%{schema_upgrade_folder}

install -m 0755 spacewalk-sql $RPM_BUILD_ROOT%{_bindir}
install -m 0755 -d $RPM_BUILD_ROOT%{rhnroot}/schema-upgrade
( cd upgrade && tar cf - --exclude='*.sql' . | ( cd $RPM_BUILD_ROOT%{rhnroot}/schema-upgrade && tar xf - ) )
mkdir -p $RPM_BUILD_ROOT%{_mandir}/man1
cp -p spacewalk-schema-upgrade.1 $RPM_BUILD_ROOT%{_mandir}/man1
cp -p spacewalk-sql.1 $RPM_BUILD_ROOT%{_mandir}/man1

%if 0%{?suse_version}
mkdir -p $RPM_BUILD_ROOT/usr/share/susemanager/
install -m 0644 update-messages.txt $RPM_BUILD_ROOT/usr/share/susemanager/
%fdupes %{buildroot}/%{rhnroot}
%endif

install -m 755 schema-source-sanity-check.pl $RPM_BUILD_ROOT%{_bindir}/schema-source-sanity-check.pl
install -m 755 blend $RPM_BUILD_ROOT%{_bindir}/blend

%if 0%{?suse_version}
%post
if [ $1 -eq 2 ] ; then
    cp /usr/share/susemanager/update-messages.txt /var/adm/update-messages/%{name}-%{version}-%{release}
else
    # new install: empty messages are not shown
    touch /var/adm/update-messages/%{name}-%{version}-%{release}
fi
%endif

%posttrans
systemctl is-active --quiet uyuni-check-database.service && {
  echo "  Running DB schema upgrade. This may take a while."
  echo "  Call the following command to see progress: journalctl -f -u uyuni-check-database.service"
} ||:
systemctl try-restart uyuni-check-database.service ||:

%files
%defattr(-,root,root)
%dir %{rhnroot}
%{postgres}
%{rhnroot}/schema-upgrade
%if 0%{?suse_version}
%dir /usr/share/susemanager
/usr/share/susemanager/update-messages.txt
%ghost /var/adm/update-messages/%{name}-%{version}-%{release}
%endif

%files utility
%defattr(-,root,root)
%dir %{perl_vendorlib}/%{spacewalk_folder}
%dir %{perl_vendorlib}/%{schema_upgrade_folder}
%{perl_vendorlib}/%{schema_upgrade_folder}/MainDb.pm
%{perl_vendorlib}/%{schema_upgrade_folder}/ReportDb.pm
%{_bindir}/spacewalk-schema-upgrade
%{_bindir}/spacewalk-sql
%{_mandir}/man1/spacewalk-schema-upgrade*
%{_mandir}/man1/spacewalk-sql*

%files sanity
%defattr(-,root,root)
%attr(755,root,root) %{_bindir}/schema-source-sanity-check.pl
%attr(755,root,root) %{_bindir}/blend

%changelog
   0707010000038F000081B400000000000000000000000167AE1114000001BD000000000000000000000000000000000000002700000000susemanager-schema/update-messages.txt    
SUSE Manager Database Schema Update

This patch updates the database schema.
The patch will be applied automatically at the end
of the update.
In case of a failure, spacewalk services are stopped and cannot
be started until the issue is fixed.

For more information about the failure, enter:

systemctl status uyuni-check-database.service

When the schema update is applied successfully, start the
services again with:

spacewalk-service start
   07070100000390000041FD00000000000000000000014767AE111400000000000000000000000000000000000000000000001B00000000susemanager-schema/upgrade    07070100000391000081B400000000000000000000000167AE11140000009B000000000000000000000000000000000000002400000000susemanager-schema/upgrade/Makefile   
SQL_FILES  := $(shell ls *.sql)
POSTGRESQL_FILES  := $(addsuffix .postgresql,$(SQL_FILES))

all : $(POSTGRESQL_FILES)

%.sql.postgresql : %.sql
	ln $^ $@
 07070100000392000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000004C00000000susemanager-schema/upgrade/rhn-satellite-schema-5.1-to-spacewalk-schema-0.2   07070100000393000081B400000000000000000000000167AE1114000001D5000000000000000000000000000000000000007500000000susemanager-schema/upgrade/rhn-satellite-schema-5.1-to-spacewalk-schema-0.2/001-rhnServerArch_data-solaris-sun4v.sql  insert into rhnServerArch (id, label, name, arch_type_id) (
    select rhn_server_arch_id_seq.nextval,
           'sparc-sun4v-solaris',
           'Sparc Solaris',
           lookup_arch_type('sysv-solaris')
    from dual
    where not exists (
        select label, name, arch_type_id
        from rhnServerArch
        where label = 'sparc-sun4v-solaris' and
              name = 'Sparc Solaris' and
              arch_type_id = lookup_arch_type('sysv-solaris'))
);
   07070100000394000081B400000000000000000000000167AE1114000001E7000000000000000000000000000000000000007600000000susemanager-schema/upgrade/rhn-satellite-schema-5.1-to-spacewalk-schema-0.2/002-rhnPackageArch_data-solaris-sun4v.sql insert into rhnPackageArch (id, label, name, arch_type_id) (
    select rhn_package_arch_id_seq.nextval,
           'sparc.sun4v-solaris',
           'Sparc Solaris sun4v',
           lookup_arch_type('sysv-solaris')
    from dual
    where not exists (
        select id, label, name, arch_type_id
        from rhnPackageArch
        where label = 'sparc.sun4v-solaris' and
              name = 'Sparc Solaris sun4v'and
              arch_type_id = lookup_arch_type('sysv-solaris'))
);
 07070100000395000081B400000000000000000000000167AE1114000001E4000000000000000000000000000000000000008300000000susemanager-schema/upgrade/rhn-satellite-schema-5.1-to-spacewalk-schema-0.2/003-rhnChannelPackageArchCompat_data-solaris-sun4v.sql    insert into rhnChannelPackageArchCompat (channel_arch_id, package_arch_id) (
    select lookup_channel_arch('channel-sparc-sun-solaris'),
           lookup_package_arch('sparc.sun4v-solaris')
    from dual
    where not exists (
        select channel_arch_id, package_arch_id
        from rhnChannelPackageArchCompat
        where channel_arch_id = lookup_channel_arch('channel-sparc-sun-solaris') and
              package_arch_id = lookup_package_arch('sparc.sun4v-solaris')
	)
);
07070100000396000081B400000000000000000000000167AE111400000115000000000000000000000000000000000000007200000000susemanager-schema/upgrade/rhn-satellite-schema-5.1-to-spacewalk-schema-0.2/004-rhnCpuArch_data-solaris-sun4v.sql insert into rhnCpuArch (id, label, name) (
    select rhn_cpu_arch_id_seq.nextval,
           'sun4v',
           'sun4v'
    from dual
    where not exists (
        select label, name
        from rhnCpuArch
        where label = 'sun4v' and
              name = 'sun4v')
);
   07070100000397000081B400000000000000000000000167AE1114000001DD000000000000000000000000000000000000008200000000susemanager-schema/upgrade/rhn-satellite-schema-5.1-to-spacewalk-schema-0.2/005-rhnServerChannelArchCompat_data-solaris-sun4v.sql insert into rhnServerChannelArchCompat (server_arch_id, channel_arch_id) (
    select lookup_server_arch('sparc-sun4v-solaris'),
           lookup_channel_arch('channel-sparc-sun-solaris')
    from dual
    where not exists (
        select server_arch_id, channel_arch_id
        from rhnServerChannelArchCompat
        where server_arch_id = lookup_server_arch('sparc-sun4v-solaris') and
              channel_arch_id = lookup_channel_arch('channel-sparc-sun-solaris')
	)
);
   07070100000398000081B400000000000000000000000167AE11140000065C000000000000000000000000000000000000008200000000susemanager-schema/upgrade/rhn-satellite-schema-5.1-to-spacewalk-schema-0.2/006-rhnServerPackageArchCompat_data-solaris-sun4v.sql update rhnServerPackageArchCompat
set preference = 710
where server_arch_id = LOOKUP_SERVER_ARCH('sparc-sun4m-solaris')
	and package_arch_id = LOOKUP_PACKAGE_ARCH('noarch-solaris-patch-cluster');

update rhnServerPackageArchCompat
set preference = 610
where server_arch_id = LOOKUP_SERVER_ARCH('sparc-sun4m-solaris')
	and package_arch_id = LOOKUP_PACKAGE_ARCH('noarch-solaris-patch');

update rhnServerPackageArchCompat
set preference = 510
where server_arch_id = LOOKUP_SERVER_ARCH('sparc-sun4m-solaris')
	and package_arch_id = LOOKUP_PACKAGE_ARCH('noarch-solaris');

update rhnServerPackageArchCompat
set preference = 410
where server_arch_id = LOOKUP_SERVER_ARCH('sparc-sun4m-solaris')
	and package_arch_id = LOOKUP_PACKAGE_ARCH('sparc-solaris-patch-cluster');

update rhnServerPackageArchCompat
set preference = 310
where server_arch_id = LOOKUP_SERVER_ARCH('sparc-sun4m-solaris')
	and package_arch_id = LOOKUP_PACKAGE_ARCH('sparc-solaris-patch');

update rhnServerPackageArchCompat
set preference = 210
where server_arch_id = LOOKUP_SERVER_ARCH('sparc-sun4m-solaris')
	and package_arch_id = LOOKUP_PACKAGE_ARCH('sparc-solaris');

insert into rhnServerPackageArchCompat (server_arch_id, package_arch_id, preference)
    select lookup_server_arch('sparc-sun4m-solaris'),
           lookup_package_arch('sparc.sun4v-solaris'),
           100
    from dual
    where not exists (
        select 1
        from rhnServerPackageArchCompat
        where server_arch_id = lookup_server_arch('sparc-sun4m-solaris') and
              package_arch_id = lookup_package_arch('sparc.sun4v-solaris') and
              preference = 100
);
07070100000399000081B400000000000000000000000167AE111400000ECD000000000000000000000000000000000000008200000000susemanager-schema/upgrade/rhn-satellite-schema-5.1-to-spacewalk-schema-0.2/007-rhnServerPackageArchCompat_data-solaris-sun4v.sql insert into rhnServerPackageArchCompat (server_arch_id, package_arch_id, preference) (
    select lookup_server_arch('sparc-sun4v-solaris'), lookup_package_arch('sparc.sun4v-solaris'), 10
    from dual
    where not exists (
        select server_arch_id, package_arch_id, preference
        from rhnServerPackageArchCompat
        where server_arch_id = lookup_server_arch('sparc-sun4v-solaris') and
              package_arch_id = lookup_package_arch('sparc.sun4v-solaris') and
              preference = 10)
);

insert into rhnServerPackageArchCompat (server_arch_id, package_arch_id, preference) (
    select lookup_server_arch('sparc-sun4v-solaris'),
           lookup_package_arch('sparc-solaris'),
           100
    from dual
    where not exists (
        select server_arch_id, package_arch_id, preference
        from rhnServerPackageArchCompat
        where server_arch_id = lookup_server_arch('sparc-sun4v-solaris') and
              package_arch_id = lookup_package_arch('sparc-solaris') and
              preference = 100
	)
);

insert into rhnServerPackageArchCompat (server_arch_id, package_arch_id, preference) (
    select lookup_server_arch('sparc-sun4v-solaris'),
           lookup_package_arch('sparc-solaris-patch'),
           210
    from dual
    where not exists (
        select server_arch_id, package_arch_id, preference
        from rhnServerPackageArchCompat
        where server_arch_id = lookup_server_arch('sparc-sun4v-solaris') and
              package_arch_id = lookup_package_arch('sparc-solaris-patch') and
              preference = 210
    )
);

insert into rhnServerPackageArchCompat (server_arch_id, package_arch_id, preference) (
    select lookup_server_arch('sparc-sun4v-solaris'),
           lookup_package_arch('sparc-solaris-patch-cluster'),
           310
    from dual
    where not exists (
        select server_arch_id, package_arch_id, preference
        from rhnServerPackageArchCompat
        where server_arch_id = lookup_server_arch('sparc-sun4v-solaris') and
              package_arch_id = lookup_package_arch('sparc-solaris-patch-cluster') and
              preference = 310
    )
);

insert into rhnServerPackageArchCompat (server_arch_id, package_arch_id, preference) (
    select lookup_server_arch('sparc-sun4v-solaris'),
           lookup_package_arch('noarch-solaris'),
           410
    from dual
    where not exists (
        select server_arch_id, package_arch_id, preference
        from rhnServerPackageArchCompat
        where server_arch_id = lookup_server_arch('sparc-sun4v-solaris') and
              package_arch_id = lookup_package_arch('noarch-solaris') and
              preference = 410
    )
);

insert into rhnServerPackageArchCompat (server_arch_id, package_arch_id, preference) (
    select lookup_server_arch('sparc-sun4v-solaris'),
           lookup_package_arch('noarch-solaris-patch'),
           510
    from dual
    where not exists (
        select server_arch_id, package_arch_id, preference
        from rhnServerPackageArchCompat
        where server_arch_id = lookup_server_arch('sparc-sun4v-solaris') and
              package_arch_id = lookup_package_arch('noarch-solaris-patch') and
              preference = 510
    )
);

insert into rhnServerPackageArchCompat (server_arch_id, package_arch_id, preference) (
    select lookup_server_arch('sparc-sun4v-solaris'),
           lookup_package_arch('noarch-solaris-patch-cluster'),
           610
    from dual
    where not exists (
        select server_arch_id, package_arch_id, preference
        from rhnServerPackageArchCompat
        where server_arch_id = lookup_server_arch('sparc-sun4v-solaris') and
              package_arch_id = lookup_package_arch('noarch-solaris-patch-cluster') and
              preference = 610
    )
);
   0707010000039A000081B400000000000000000000000167AE1114000003BD000000000000000000000000000000000000008600000000susemanager-schema/upgrade/rhn-satellite-schema-5.1-to-spacewalk-schema-0.2/008-rhnServerServerGroupArchCompat_data-solaris-sun4v.sql insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type) (
    select lookup_server_arch('sparc-sun4v-solaris'), lookup_sg_type('enterprise_entitled')
    from dual
    where not exists (
        select server_arch_id,
               server_group_type
        from rhnServerServerGroupArchCompat
        where server_arch_id = lookup_server_arch('sparc-sun4v-solaris') and
              server_group_type = lookup_sg_type('enterprise_entitled')
    )
);

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type) (
    select lookup_server_arch('sparc-sun4v-solaris'), lookup_sg_type('provisioning_entitled')
    from dual
    where not exists (
        select server_arch_id,
               server_group_type
        from rhnServerServerGroupArchCompat
        where server_arch_id = lookup_server_arch('sparc-sun4v-solaris') and
              server_group_type = lookup_sg_type('provisioning_entitled')
    )
);
   0707010000039B000081B400000000000000000000000167AE1114000005B7000000000000000000000000000000000000008200000000susemanager-schema/upgrade/rhn-satellite-schema-5.1-to-spacewalk-schema-0.2/009-rhnServerPackageArchCompat_data-solaris-sun4u.sql insert into rhnServerPackageArchCompat (server_arch_id, package_arch_id, preference)
    select lookup_server_arch('sparc-sun4u-solaris'),
           lookup_package_arch('noarch-solaris'),
           410
    from dual
    where not exists (
        select 1
		from rhnServerPackageArchCompat
		where server_arch_id = lookup_server_arch('sparc-sun4u-solaris') and
		      package_arch_id = lookup_package_arch('noarch-solaris') and
		      preference = 410
        );

insert into rhnServerPackageArchCompat (server_arch_id, package_arch_id, preference)
    select lookup_server_arch('sparc-sun4u-solaris'),
           lookup_package_arch('noarch-solaris-patch'),
           510
    from dual
    where not exists (
        select 1
		from rhnServerPackageArchCompat
		where server_arch_id = lookup_server_arch('sparc-sun4u-solaris') and
		      package_arch_id = lookup_package_arch('noarch-solaris-patch') and
		      preference = 510
        );

insert into rhnServerPackageArchCompat (server_arch_id, package_arch_id, preference)
    select lookup_server_arch('sparc-sun4u-solaris'),
           lookup_package_arch('noarch-solaris-patch-cluster'),
           610
    from dual
    where not exists (
        select 1
        from rhnServerPackageArchCompat
        where server_arch_id = lookup_server_arch('sparc-sun4u-solaris') and
              package_arch_id = lookup_package_arch('noarch-solaris-patch-cluster') and
              preference = 610
    );
 0707010000039C000081B400000000000000000000000167AE111400000076000000000000000000000000000000000000007300000000susemanager-schema/upgrade/rhn-satellite-schema-5.1-to-spacewalk-schema-0.2/010-rhnKSInstallType_data-fedora_9.sql    insert into rhnKSInstallType (id, label, name)
	values (rhn_ksinstalltype_id_seq.nextval,
		'fedora_9','Fedora 9'
	);
  0707010000039D000081B400000000000000000000000167AE111400000097000000000000000000000000000000000000007A00000000susemanager-schema/upgrade/rhn-satellite-schema-5.1-to-spacewalk-schema-0.2/011-rhnKickstartCommandName_data-fedora_9.sql update rhnKickstartCommandName
set required = 'N'
where name = 'langsupport';

update rhnKickstartCommandName
set required = 'N'
where name = 'mouse';
 0707010000039E000081B400000000000000000000000167AE111400000161000000000000000000000000000000000000007300000000susemanager-schema/upgrade/rhn-satellite-schema-5.1-to-spacewalk-schema-0.2/012-rhnTemplateString_data-strings.sql    
update rhnTemplateString
set description = 'Footer for Spacewalk e-mail'
where label = 'email_footer';

update rhnTemplateString
set value = '
Account Information:
  Your Spacewalk login:         <login />
  Your Spacewalk email address: <email-address />', 
description = 'Account info lines for Spacewalk e-mail'
where label = 'email_account_info';

   0707010000039F000081B400000000000000000000000167AE11140000028E000000000000000000000000000000000000006C00000000susemanager-schema/upgrade/rhn-satellite-schema-5.1-to-spacewalk-schema-0.2/014-remove-db_change-tables.sql   
drop table db_change_history cascade constraints;
drop table db_change_history_output cascade constraints;
drop table db_change_ignore_errs cascade constraints;
drop table db_change_lock cascade constraints;
drop table db_change_resource_changes cascade constraints;
drop table db_change_resource_names cascade constraints;
drop table db_change_resource_types cascade constraints;
drop table db_change_resources cascade constraints;
drop table db_change_script cascade constraints;
drop table db_change_script_expanded cascade constraints;
drop table db_change_script_parsed cascade constraints;
drop table db_change_script_source cascade constraints;

  070701000003A0000081B400000000000000000000000167AE111400000037000000000000000000000000000000000000006900000000susemanager-schema/upgrade/rhn-satellite-schema-5.1-to-spacewalk-schema-0.2/020-1-rhnActionType-name.sql  
alter table rhnActionType
modify name varchar2(100);

 070701000003A1000081B400000000000000000000000167AE111400000240000000000000000000000000000000000000006C00000000susemanager-schema/upgrade/rhn-satellite-schema-5.1-to-spacewalk-schema-0.2/020-2-rhnActionType-strings.sql   
update rhnActionType
set name = 'Spacewalk Daemon Configuration'
where label = 'rhnsd.configure';

update rhnActionType
set name = 'Allows for rhn-applet use with an Spacewalk'
where label = 'rhn_applet.use_satellite';

update rhnActionType
set name = 'Subscribes a server to the Spacewalk Tools channel associated with its base channel.'
where label = 'kickstart_host.add_tools_channel';

update rhnActionType
set name = 'Subscribes a virtualization guest to the Spacewalk Tools channel associated with its base channel.'
where label = 'kickstart_guest.add_tools_channel';

070701000003A2000081B400000000000000000000000167AE11140000004D000000000000000000000000000000000000006800000000susemanager-schema/upgrade/rhn-satellite-schema-5.1-to-spacewalk-schema-0.2/021-rhnFAQClass-strings.sql   
update RHNFAQCLASS
set name = 'Using Spacewalk'
where label = 'using_rhn';

   070701000003A3000081B400000000000000000000000167AE111400000016000000000000000000000000000000000000006100000000susemanager-schema/upgrade/rhn-satellite-schema-5.1-to-spacewalk-schema-0.2/022-rhnFAQ-purge.sql  
delete from RHNFAQ;

  070701000003A4000081B400000000000000000000000167AE11140000D44A000000000000000000000000000000000000006300000000susemanager-schema/upgrade/rhn-satellite-schema-5.1-to-spacewalk-schema-0.2/023-rhnFAQ_satdata.sql    --
-- Copyright (c) 2008 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
-- $Id$
--
-- EXCLUDE: production

-- data for rhnFAQ in the satellite case

SET SQLBLANKLINES ON
SET SCAN OFF

INSERT INTO RHNFAQ ( ID, SUBJECT, DETAILS, PRIVATE, CREATED, MODIFIED, USAGE_COUNT,
CLASS_ID ) VALUES ( 
64, 'pvt: This message is being forwarded to customerservice@redhat.com', 'This message has been forwarded to customerservice@redhat.com.  That group handles all billing and purchasing related questions.'
, 1,  TO_Date( '10/02/2002 12:00:00 AM', 'MM/DD/YYYY HH:MI:SS AM'),  TO_Date( '05/12/2003 10:18:24 PM', 'MM/DD/YYYY HH:MI:SS AM')
, 22, 1); 
INSERT INTO RHNFAQ ( ID, SUBJECT, DETAILS, PRIVATE, CREATED, MODIFIED, USAGE_COUNT,
CLASS_ID ) VALUES ( 
65, 'I''m having trouble registering my Red Hat Enterprise Linux product.  Why?', 'Enterprise entitlements are required for use with Red Hat Enterprise Linux.

A customer who registers an Enterprise Linux system with Spacewalk without having any Enterprise Linux entitlements will receive an error message similar to:

"No public channels available for ("2.1AS'', ''i686'')"

In order to register your system, you first need to activate your Spacewalk Enterprise Linux entitlements at:

http://www.redhat.com/support

Use the product ID that came with your Red Hat Enterprise Linux product.
'
, 0,  TO_Date( '10/02/2002 12:00:00 AM', 'MM/DD/YYYY HH:MI:SS AM'),  TO_Date( '03/31/2003 09:26:12 AM', 'MM/DD/YYYY HH:MI:SS AM')
, 13, 7); 
INSERT INTO RHNFAQ ( ID, SUBJECT, DETAILS, PRIVATE, CREATED, MODIFIED, USAGE_COUNT,
CLASS_ID ) VALUES ( 
66, 'pvt: I bought service with Spacewalk, but it won''t let me use Priority FTP access.  Why not?vp'
, 'Instant ISO access is not the same as Priority FTP access; they are separate entities.  Customers who purchase Spacewalk service have Instant ISO access only.  Priority FTP access is available only to legacy users, and is in the process of being phased out.
'
, 1,  TO_Date( '10/02/2002 12:00:00 AM', 'MM/DD/YYYY HH:MI:SS AM'),  TO_Date( '04/24/2003 09:34:56 PM', 'MM/DD/YYYY HH:MI:SS AM')
, 6, 1); 
INSERT INTO RHNFAQ ( ID, SUBJECT, DETAILS, PRIVATE, CREATED, MODIFIED, USAGE_COUNT,
CLASS_ID ) VALUES ( 
67, 'How do I register a system for Spacewalk service on Red Hat Linux?', 'To register a system for Spacewalk service on Red Hat Linux please run "rhn_register". Refer to the Spacewalk User Guide (also available through the Help link at the Spacewalk website) for additional instructions.

Note: for Red Hat Linux 8.0 and later, please run "up2date --register" instead of "rhn_register".
'
, 0,  TO_Date( '10/02/2002 12:00:00 AM', 'MM/DD/YYYY HH:MI:SS AM'),  TO_Date( '04/16/2003 09:09:30 PM', 'MM/DD/YYYY HH:MI:SS AM')
, 19, 3); 
INSERT INTO RHNFAQ ( ID, SUBJECT, DETAILS, PRIVATE, CREATED, MODIFIED, USAGE_COUNT,
CLASS_ID ) VALUES ( 
25, 'The Spacewalk website and up2date do not agree on what errata is needed for my system.'
, 'You can refresh the profile package list by running "up2date -p" on the machine itself.  Alternatively, you can schedule this from the website by clicking on the system in the System List, choosing the Packages tab, and then clicking on the "Update Package List" button at the bottom of the page.
'
, 0,  TO_Date( '06/14/2002 12:00:00 AM', 'MM/DD/YYYY HH:MI:SS AM'),  TO_Date( '04/14/2003 09:24:01 PM', 'MM/DD/YYYY HH:MI:SS AM')
, 10, 6); 
INSERT INTO RHNFAQ ( ID, SUBJECT, DETAILS, PRIVATE, CREATED, MODIFIED, USAGE_COUNT,
CLASS_ID ) VALUES ( 
26, 'I had to re-install my system. How do I re-register and get my entitlement back?'
, 'You''ll need to re-register the client system if you haven''t already, and then move an entitlement to the new profile.

* Log into our website at:  https://rhn.redhat.com.
* Click on "Systems" in the top navigation bar, then the name of the old system in the System List.
* Click "delete system" on the top-right corner of the page.
* As root at the command line, delete the file /etc/sysconfig/rhn/systemid from your system.
* Run "rhn_register" (Red Hat Linux 7.x) or "up2date --register" (Red Hat Linux 8.0 and newer) on your system.
* Once the system is registered, log in at https://rhn.redhat.com.
* Click "Systems" in the top navigation bar, then "System Entitlements" on the left.
* Select the appropriate entitlement level for the new system and click "Update Entitlements."'
, 0,  TO_Date( '06/14/2002 12:00:00 AM', 'MM/DD/YYYY HH:MI:SS AM'),  TO_Date( '05/18/2003 09:42:55 PM', 'MM/DD/YYYY HH:MI:SS AM')
, 411, 5); 
INSERT INTO RHNFAQ ( ID, SUBJECT, DETAILS, PRIVATE, CREATED, MODIFIED, USAGE_COUNT,
CLASS_ID ) VALUES ( 
27, 'How can I request a new feature or improvement for the Spacewalk?', 'For technical requests, you can make a "Request for Enhancement" (RFE) at http://bugzilla.redhat.com/bugzilla.  The product is "Spacewalk" and the various components are prefaced by "Spacewalk/".  Please put "[RFE]" at the beginning of the summary line of your request.

If you would like to provide non-technical feedback to Spacewalk, please go to https://rhn.redhat.com/help/contact.pxt and follow the directions for "feedback".
'
, 0,  TO_Date( '06/14/2002 12:00:00 AM', 'MM/DD/YYYY HH:MI:SS AM'),  TO_Date( '05/18/2003 09:56:14 PM', 'MM/DD/YYYY HH:MI:SS AM')
, 74, 9); 
INSERT INTO RHNFAQ ( ID, SUBJECT, DETAILS, PRIVATE, CREATED, MODIFIED, USAGE_COUNT,
CLASS_ID ) VALUES ( 
28, 'Where do I report a bug in the Spacewalk website or update agent?', 'Bugs can be reported at http://bugzilla.redhat.com/bugzilla -- the product is "Spacewalk", and the various components are prefixed with "Spacewalk/".

Please be sure to read the FAQ and review all of the open bugs before submitting your bug.
'
, 0,  TO_Date( '06/14/2002 12:00:00 AM', 'MM/DD/YYYY HH:MI:SS AM'),  TO_Date( '05/15/2003 10:47:49 PM', 'MM/DD/YYYY HH:MI:SS AM')
, 45, 9); 
INSERT INTO RHNFAQ ( ID, SUBJECT, DETAILS, PRIVATE, CREATED, MODIFIED, USAGE_COUNT,
CLASS_ID ) VALUES ( 
30, 'What is the difference between i386, i586, and i686 packages?', 'i386 is a generic designation for all processors backwardly compatible with the Intel 80386; i586 is for all processors backwardly compatible with the Intel Pentium; and i686 is for Intel processors backwardly compatible with the Pentium Pro chip (Pentium II, III, IV, etc).  Only the kernel has i586 and i686 versions, and glibc has an i686 version.  up2date should automatically determine which versions of the kernel and glibc packages are appropriate for your systems.
'
, 0,  TO_Date( '06/14/2002 12:00:00 AM', 'MM/DD/YYYY HH:MI:SS AM'),  TO_Date( '04/15/2003 10:33:49 PM', 'MM/DD/YYYY HH:MI:SS AM')
, 8, 11); 
INSERT INTO RHNFAQ ( ID, SUBJECT, DETAILS, PRIVATE, CREATED, MODIFIED, USAGE_COUNT,
CLASS_ID ) VALUES ( 
1, 'What is Spacewalk?', 'Spacewalk is a systems support and management environment for Red Hat Linux systems and networks. For more information, please see the Spacewalk product information page:
http://www.redhat.com/software/rhn/products/

For individual systems and small networks, see http://www.redhat.com/software/rhn

For enterprise deployments, see http://www.redhat.com/software/rhen
'
, 0,  TO_Date( '03/07/2002 12:00:00 AM', 'MM/DD/YYYY HH:MI:SS AM'),  TO_Date( '05/14/2003 05:00:08 AM', 'MM/DD/YYYY HH:MI:SS AM')
, 26, 1); 
INSERT INTO RHNFAQ ( ID, SUBJECT, DETAILS, PRIVATE, CREATED, MODIFIED, USAGE_COUNT,
CLASS_ID ) VALUES ( 
3, 'Does Spacewalk only work on Linux? Which versions?', 'Yes. Spacewalk currently only supports versions of Red Hat Linux and Red Hat Enterprise Linux that are still active (have not yet reached End of Life status). For a list of currently maintained Red Hat versions, please go to http://www.redhat.com/apps/support/errata/

Please note that Red Hat''s Enterprise Network Monitoring Module does support different platforms. For more information, please go to http://www.redhat.com/software/rhen/system_mgmt/
'
, 0,  TO_Date( '03/07/2002 12:00:00 AM', 'MM/DD/YYYY HH:MI:SS AM'),  TO_Date( '03/31/2003 09:26:12 AM', 'MM/DD/YYYY HH:MI:SS AM')
, 4, 1); 
INSERT INTO RHNFAQ ( ID, SUBJECT, DETAILS, PRIVATE, CREATED, MODIFIED, USAGE_COUNT,
CLASS_ID ) VALUES ( 
5, 'I can''t find the Spacewalk Registration Client.  What is it and where do I find it?'
, 'The Spacewalk Registration Client steps you through the process of creating a user account if you do not already have one and registering your system by creating a System Profile. It can be started by using one of the following methods:

* On the GNOME desktop, go to the Main Menu Button (on the Panel) => Programs => System => Spacewalk.
* On the KDE desktop, go to the Main Menu Button (on the Panel) => System => Spacewalk
* At a shell prompt, type the command "rhn_register".

In Red Hat Linux 8.0 and newer, rhn_register exists as a mode of the up2date client, so:

* On the GNOME and KDE desktops, go to the Main Menu Button (on the Panel) => System Tools => Spacewalk. (If the system is unregistered, it will automatically launch in registration mode.)
* At a shell prompt (for example, an xterm or gnome-terminal), type the command "up2date --register".
'
, 0,  TO_Date( '03/07/2002 12:00:00 AM', 'MM/DD/YYYY HH:MI:SS AM'),  TO_Date( '05/19/2003 01:31:52 AM', 'MM/DD/YYYY HH:MI:SS AM')
, 126, 5); 
INSERT INTO RHNFAQ ( ID, SUBJECT, DETAILS, PRIVATE, CREATED, MODIFIED, USAGE_COUNT,
CLASS_ID ) VALUES ( 
7, 'I forgot my username and password. How do I access my account?', 'From the front page, click on the "Lost Password?" link, enter your username and email address, and then click the "Send Password" button.

If you have neither your username nor your password, enter your email address in the second field provided, and then click the "Send Account List" button.

If the email address matches the email address on file for your account, your information will be sent to you. If this does not work for you, please call our customer service desk at 1-866-2-RedHat.
'
, 0,  TO_Date( '03/07/2002 12:00:00 AM', 'MM/DD/YYYY HH:MI:SS AM'),  TO_Date( '04/16/2003 09:14:22 PM', 'MM/DD/YYYY HH:MI:SS AM')
, 16, 2); 
INSERT INTO RHNFAQ ( ID, SUBJECT, DETAILS, PRIVATE, CREATED, MODIFIED, USAGE_COUNT,
CLASS_ID ) VALUES ( 
8, 'What are the service levels for Spacewalk?', 'Spacewalk currently offers three levels of service: Spacewalk Demo Service, Spacewalk Update Service and Spacewalk Management Service.  For more details, go to http://www.redhat.com/software/rhn/offerings
'
, 0,  TO_Date( '03/07/2002 12:00:00 AM', 'MM/DD/YYYY HH:MI:SS AM'),  TO_Date( '05/08/2003 03:43:45 AM', 'MM/DD/YYYY HH:MI:SS AM')
, 50, 4); 
INSERT INTO RHNFAQ ( ID, SUBJECT, DETAILS, PRIVATE, CREATED, MODIFIED, USAGE_COUNT,
CLASS_ID ) VALUES ( 
69, 'pvt: You are sending packets to my machine! (Firewall log attached)', 'As you can see, the packets you are seeing are response packets coming from our host and port 443 to your machine.

These packets have the SYN/ACK flags set up. These types of packets are sent only in response to a connection request from your computer.

TCP uses a three-way handshake protocol to establish a connection:
* the client sends a SYN packet to the server requesting a connection
* the server acknowledges the request and sends back a SYN/ACK packet
* the client responds back with an ACK packet and the connection is established

Your firewall rules are not allowing the server responses to pass through.  The rhnsd daemon is initiating these requests. You have 2 choices:

* fix the firewall rules so you allow the reply packets to pass through and therefore allow your host to connect outside; or
* disable the rhnsd daemon: service rhnsd stop
'
, 1,  TO_Date( '10/02/2002 12:00:00 AM', 'MM/DD/YYYY HH:MI:SS AM'),  TO_Date( '03/31/2003 09:26:11 AM', 'MM/DD/YYYY HH:MI:SS AM')
, 3, 1); 
INSERT INTO RHNFAQ ( ID, SUBJECT, DETAILS, PRIVATE, CREATED, MODIFIED, USAGE_COUNT,
CLASS_ID ) VALUES ( 
125, 'pvt: no RHL support at rhn-help', 'This address is intended for support questions related only to Red Hat
Network. General Red Hat Linux support is not available from this address.

If you have not already done so, you can activate your product and receive advanced support at:

https://www.redhat.com/apps/support/

Even if you are not registered with Red Hat Support, you are welcome to browse
our documentation and online resources available at:

https://www.redhat.com/docs/

You may also get access to Tips, FAQs, and online HOWTOs to guide you through
Linux-related tasks if you start looking from our Support Resources Home Page
available at:

https://www.redhat.com/apps/support/resources/

The Red Hat mailing lists are also good venues for finding answers to your
questions. For more information on the Red Hat mailing lists, please see:

http://www.redhat.com/mailing-lists/

If you would like to report a bug or a problem with a component of the Red Hat Linux distribution, we encourage you to visit our bug tracking system and file a bug report at:

http://bugzilla.redhat.com/bugzilla
'
, 1,  TO_Date( '12/11/2002 12:00:00 AM', 'MM/DD/YYYY HH:MI:SS AM'),  TO_Date( '03/31/2003 09:26:12 AM', 'MM/DD/YYYY HH:MI:SS AM')
, 288, 1); 
INSERT INTO RHNFAQ ( ID, SUBJECT, DETAILS, PRIVATE, CREATED, MODIFIED, USAGE_COUNT,
CLASS_ID ) VALUES ( 
126, 'How do I change my Spacewalk password?', 'To change your password:

* Log in to the Spacewalk website with your existing username and password.
* If you are not at Your Spacewalk page, click its link in the top navigation bar.
* Click "Your Account" in the left navigation bar.
* Type your new password in both the Password and Password Confirmation fields.
* Click the "Update" button.
'
, 0,  TO_Date( '12/12/2002 12:00:00 AM', 'MM/DD/YYYY HH:MI:SS AM'),  TO_Date( '03/31/2003 09:26:12 AM', 'MM/DD/YYYY HH:MI:SS AM')
, 9, 2); 
INSERT INTO RHNFAQ ( ID, SUBJECT, DETAILS, PRIVATE, CREATED, MODIFIED, USAGE_COUNT,
CLASS_ID ) VALUES ( 
13, 'What is "rhnsd" and why is it running on my system?', '"rhnsd" is the Spacewalk Daemon. Every other hour, it sends a request to Spacewalk asking for any notifications or updates and works in coordination with Spacewalk to schedule automated tasks. It sends information to Spacewalk only requested by you. If you add a new system using the Spacewalk web interface, the next time the Spacewalk Daemon probes Spacewalk it receives a request to return the information you requested as part of your System Profile, such as what package versions are installed on your system.
'
, 0,  TO_Date( '03/07/2002 12:00:00 AM', 'MM/DD/YYYY HH:MI:SS AM'),  TO_Date( '04/08/2003 10:52:29 PM', 'MM/DD/YYYY HH:MI:SS AM')
, 9, 6); 
INSERT INTO RHNFAQ ( ID, SUBJECT, DETAILS, PRIVATE, CREATED, MODIFIED, USAGE_COUNT,
CLASS_ID ) VALUES ( 
15, 'My systems are not checking in.  What does that mean?', 'When the Spacewalk client connects to Spacewalk to see if there are any updates available, or if any actions have been scheduled, this is considered a checkin.

If you are seeing a message indicating that checkins are not happening, it means that the Spacewalk client on your system is not successfully reaching Spacewalk for some reason. Things to check:
* Make certain that your client is configured correctly.
* Make sure that your system can communicate with Spacewalk via SSL (port 443).  You may test this by running the following command from a shell prompt: telnet xmlrpc.rhn.redhat.com 443
* Make sure that the rhnsd daemon is activated and running.  You may ensure this by running the following commands:
chkconfig --level 345 rhnsd on
service rhnsd start

If these settings are correct and your system still is not checking in, the ''Repairing a corrupt rpm database'' faq at http://rhn.redhat.com/help/faq/technical_questions.pxt#227 , or get in touch with our technical support team.
'
, 0,  TO_Date( '03/07/2002 12:00:00 AM', 'MM/DD/YYYY HH:MI:SS AM'),  TO_Date( '05/14/2003 05:04:29 AM', 'MM/DD/YYYY HH:MI:SS AM')
, 151, 5); 
INSERT INTO RHNFAQ ( ID, SUBJECT, DETAILS, PRIVATE, CREATED, MODIFIED, USAGE_COUNT,
CLASS_ID ) VALUES ( 
17, 'Can I use Spacewalk to upgrade my Red Hat Linux kernel?', 'Yes. You must use Red Hat Update Agent version 2.5.4 or higher. If you choose the kernel packages and allow Spacewalk to install them to your system, it will modify your LILO or GRUB configuration file so that your system boots the new kernel the next time it is rebooted.
'
, 0,  TO_Date( '03/07/2002 12:00:00 AM', 'MM/DD/YYYY HH:MI:SS AM'),  TO_Date( '03/31/2003 09:26:12 AM', 'MM/DD/YYYY HH:MI:SS AM')
, 11, 5); 
INSERT INTO RHNFAQ ( ID, SUBJECT, DETAILS, PRIVATE, CREATED, MODIFIED, USAGE_COUNT,
CLASS_ID ) VALUES ( 
41, 'pvt: Updates to newer versions recommended by third-party security advisories.'
, 'We have released fixes for all known vulnerabilities you are mentioning.  Red Hat does not usually update to a new code base for the core applications and libraries if we have other options available. In the cases you have mentioned we choose to backport the security fixes to the code base we initially shipped to our customers. We do this in order to minimize the impact on the stability and the QA resources that both we and the customers invest in qualifying a particular release for a particular task.

The latest versions of those packages provided by Red Hat are not vulnerable to the issues you mention.
'
, 1,  TO_Date( '10/01/2002 12:00:00 AM', 'MM/DD/YYYY HH:MI:SS AM'),  TO_Date( '04/13/2003 11:31:22 PM', 'MM/DD/YYYY HH:MI:SS AM')
, 10, 1); 
INSERT INTO RHNFAQ ( ID, SUBJECT, DETAILS, PRIVATE, CREATED, MODIFIED, USAGE_COUNT,
CLASS_ID ) VALUES ( 
62, 'Is Red Hat Technical Support available in other languages besides English?', 'At this time, Spacewalk technical support is English only.
'
, 0,  TO_Date( '10/02/2002 12:00:00 AM', 'MM/DD/YYYY HH:MI:SS AM'),  TO_Date( '04/27/2003 10:32:41 PM', 'MM/DD/YYYY HH:MI:SS AM')
, 26, 4); 
INSERT INTO RHNFAQ ( ID, SUBJECT, DETAILS, PRIVATE, CREATED, MODIFIED, USAGE_COUNT,
CLASS_ID ) VALUES ( 
63, 'How do I download RPMs for a system without using up2date?', 'It is possible for Spacewalk users to download updated packages directly from the Spacewalk website without using up2date.

To download them:

* Log in to the Spacewalk web site.
* Click "Software" in the top navigation bar.
* Click the appropriate channel name.
* On the Channel Details page, click the "Packages" tab.
* Select the RPMs you want and click the "Download" button. You will be presented with a confirmation screen.
* Click "Download Selected Packages Now!"
* You will then be asked for the location to save the tar archive containing all the packages you selected.
* To extract the packages once the download is complete, run: tar -xvf rhn-packages.tar
'
, 0,  TO_Date( '10/02/2002 12:00:00 AM', 'MM/DD/YYYY HH:MI:SS AM'),  TO_Date( '03/31/2003 09:26:12 AM', 'MM/DD/YYYY HH:MI:SS AM')
, 9, 5); 
INSERT INTO RHNFAQ ( ID, SUBJECT, DETAILS, PRIVATE, CREATED, MODIFIED, USAGE_COUNT,
CLASS_ID ) VALUES ( 
31, 'The update agent wants to install an older version of a package.  Why?', 'This is probably because of the epoch number of the package.  RPM checks three things when it tries to determine whether a package is newer: epoch, version, and release, in that order.  A higher epoch number trumps both version and release.  To see the epoch number on an installed package, use the command:

rpm -q --queryformat "%{NAME}-%{VERSION}-%{RELEASE}:%{EPOCH}\n" packagename

The epoch is the number after the colon.  On the Spacewalk website, you can also see the epoch for the package on the Installed Packages list for the system, (again, the number after the colon).

Epoch numbers are used to preserve RPM''s concept of "newer" when package versions are changed inconveniently. The classic example of the need for an epoch is perl, which changed from version 5.00503 to 5.6, thereby breaking rpm''s segmented version comparison (i.e the integer 6 < 503, rather than 5.6 > 5.00503).

To keep the update agent from trying to update your package, add it to the package skip list (pkgSkipList) in your up2date configuration:

up2date --configure --nox

However, the package will still show up on your list of applicable errata.
'
, 0,  TO_Date( '06/14/2002 12:00:00 AM', 'MM/DD/YYYY HH:MI:SS AM'),  TO_Date( '04/06/2003 10:26:15 PM', 'MM/DD/YYYY HH:MI:SS AM')
, 7, 6); 
INSERT INTO RHNFAQ ( ID, SUBJECT, DETAILS, PRIVATE, CREATED, MODIFIED, USAGE_COUNT,
CLASS_ID ) VALUES ( 
32, 'pvt: Red Hat Linux support', 'This address is intended for support questions related only to Spacewalk. General Red Hat Linux support is not available from this address.  If you are registered with Red Hat Support, you may address your questions at:
http://www.redhat.com/support

If you have not already done so, you can activate your product and receive advanced support at:

https://www.redhat.com/apps/support/

Even if you are not registered with Red Hat Support, you are welcome to browse
our documentation and online resources available at:

https://www.redhat.com/docs/

You may also get access to Tips, FAQs, and online HOWTOs to guide you through
Linux-related tasks if you start looking from our Support Resources Home Page
available at:

https://www.redhat.com/apps/support/resources/

The Red Hat mailing lists are also good venues for finding answers to your
questions. For more information on the Red Hat mailing lists, please see:

http://www.redhat.com/mailing-lists/

If you would like to report a bug or a problem with a component of the Red Hat Linux distribution, we encourage you to visit our bug tracking system and file a bug report at:

http://bugzilla.redhat.com/bugzilla
'
, 1,  TO_Date( '06/22/2002 12:00:00 AM', 'MM/DD/YYYY HH:MI:SS AM'),  TO_Date( '05/19/2003 01:13:04 AM', 'MM/DD/YYYY HH:MI:SS AM')
, 768, 1); 
INSERT INTO RHNFAQ ( ID, SUBJECT, DETAILS, PRIVATE, CREATED, MODIFIED, USAGE_COUNT,
CLASS_ID ) VALUES ( 
33, 'How do I delete System Profiles?', 'In order to delete System Profiles from Spacewalk, you need to log in to the Spacewalk website at https://rhn.redhat.com.  Once logged in, click on the "Systems" link in the top navigation bar, which will take you to a list of the profiles you have registered with Spacewalk. (If you instead see System Groups, click "View Systems" near the top of the page.)

Click on the name of the profile you wish to delete from the service. This will bring up its System Details page. Click the "delete system" button at the top-right corner of the page. Then confirm that you wish to delete the profile.

The profile will be removed after confirmation.
'
, 0,  TO_Date( '06/24/2002 12:00:00 AM', 'MM/DD/YYYY HH:MI:SS AM'),  TO_Date( '05/12/2003 10:57:15 PM', 'MM/DD/YYYY HH:MI:SS AM')
, 89, 7); 
INSERT INTO RHNFAQ ( ID, SUBJECT, DETAILS, PRIVATE, CREATED, MODIFIED, USAGE_COUNT,
CLASS_ID ) VALUES ( 
36, 'pvt: Educational Channel', 'The educational channel and Red Hat educational initiative is currently undergoing some changes (all for the positive). Please stay tuned and periodically check the following websites for more information:

www.redhat.com
www.redhat.com/index2.html
www.redhat.com/software/rhn
'
, 1,  TO_Date( '08/20/2002 12:00:00 AM', 'MM/DD/YYYY HH:MI:SS AM'),  TO_Date( '03/31/2003 09:26:13 AM', 'MM/DD/YYYY HH:MI:SS AM')
, 14, 1); 
INSERT INTO RHNFAQ ( ID, SUBJECT, DETAILS, PRIVATE, CREATED, MODIFIED, USAGE_COUNT,
CLASS_ID ) VALUES ( 
35, 'An errata install fails with dependency errors, but dependencies are satisfied.  Why?'
, 'Sometimes the application of an errata from the Spacewalk web site will fail because the errata applies to packages that are set to be skipped in the local skip list for a system''s up2date client.  The error message in the history log will incorrectly cite a dependency problem.

To fix this problem, run:

up2date --configure

...as root from the client system, and remove the relevant packages from the skip list.  Rescheduling the errata should then work as expected.
'
, 0,  TO_Date( '08/20/2002 12:00:00 AM', 'MM/DD/YYYY HH:MI:SS AM'),  TO_Date( '05/13/2003 10:24:11 PM', 'MM/DD/YYYY HH:MI:SS AM')
, 23, 6); 
INSERT INTO RHNFAQ ( ID, SUBJECT, DETAILS, PRIVATE, CREATED, MODIFIED, USAGE_COUNT,
CLASS_ID ) VALUES ( 
249, 'Where can I see a copy of the SLA (Service Level Agreement) for Spacewalk Technical Support?'
, 'This can be viewed online at the following site:

http://www.redhat.com/services/techsupport/production/RHN_basic.html'
, 0,  TO_Date( '03/31/2003 11:55:25 AM', 'MM/DD/YYYY HH:MI:SS AM'),  TO_Date( '04/09/2003 11:00:32 PM', 'MM/DD/YYYY HH:MI:SS AM')
, 6, 4); 
INSERT INTO RHNFAQ ( ID, SUBJECT, DETAILS, PRIVATE, CREATED, MODIFIED, USAGE_COUNT,
CLASS_ID ) VALUES ( 
288, 'My system''s IP address and hostname have changed, but Spacewalk doesn''t reflect this. What should I do?'
, 'Spacewalk stores a profile for each registered system. In addition to properties set by the user during registration, this profile may contain various kinds of information about the system''s hardware, including processor type, networking addresses, and storage devices. This information can be found in the Spacewalk website:

1. Once logged in, click on Systems in the top navigation bar.
2. Click on the name of a system in one of the lists. (This may require leaving a System Groups view.)
3. In the System Details page, click the Hardware subtab. All of the hardware information Spacewalk has collected about your system will appear on the resulting page.
4. To update this information, click the Schedule Hardware Refresh button. The hardware profile will be updated at the system''s next connection to Spacewalk.'
, 0,  TO_Date( '04/22/2003 04:00:05 PM', 'MM/DD/YYYY HH:MI:SS AM'),  TO_Date( '04/23/2003 09:45:57 AM', 'MM/DD/YYYY HH:MI:SS AM')
, 0, 6); 
INSERT INTO RHNFAQ ( ID, SUBJECT, DETAILS, PRIVATE, CREATED, MODIFIED, USAGE_COUNT,
CLASS_ID ) VALUES ( 
290, 'Why does up2date tell me "Your system is fully updated" when the Spacewalk website lists updates for my system?'
, 'This error is likely caused by one of two problems: Either the system''s package profile on Spacewalk is out of date or up2date''s package exceptions list is preventing the updates from occurring.

Since updating the package profile is simplest, try this first. Log into the Spacewalk website, click "Systems" in the top navigation bar, and then click the name of the system. In the System Details page, click the "Packages" tab and then click the "Update Package List" button. The profile will be updated when the system next connects to Spacewalk. This should either remove the updates listed for your system or allow you to conduct the updates if they remain.

If this still does not resolve the error, check your package exceptions list, which enables you to identify packages to be exempt from updates. To ensure your settings are not preventing the updates, launch the Update Agent Configuration Tool by running the command:

up2date-config

In the tool, click the "Package Exceptions" tab and look for the packages listed as requiring updating.
To check the package skip list in the up2date configuration file, open the file /etc/sysconfig/rhn/up2date and look for the package entries under the pkgSkipList setting. To override the package exceptions and force an update of the entire system, run the command:

up2date -uf

If the packages aren''t updated, the Spacewalk website will continue to list them as outdated, regardless of their inclusion in the system''s package exceptions list.'
, 0,  TO_Date( '04/22/2003 06:32:03 PM', 'MM/DD/YYYY HH:MI:SS AM'),  TO_Date( '04/25/2003 08:04:45 PM', 'MM/DD/YYYY HH:MI:SS AM')
, 0, 6); 
INSERT INTO RHNFAQ ( ID, SUBJECT, DETAILS, PRIVATE, CREATED, MODIFIED, USAGE_COUNT,
CLASS_ID ) VALUES ( 
291, 'Why does Apache fail to restart after I update my Spacewalk Management Satellite Server?', 'Apache RPMs do not restart the httpd service upon installation. Therefore, after conducting a full update of an Spacewalk Management Satellite Server (such as with the command up2date -uf), Apache fails. The error will look something like:

[Mon Feb 10 11:50:12 2003] [notice] SIGHUP received.  Attempting to restart
Syntax error on line 214 of /etc/httpd/conf/httpd.conf: Cannot load /etc/httpd/modules/mod_log_config.so into server: /etc/httpd/modules/mod_log_config.so: undefined symbol: ap_escape_logitem

To resolve this, restart the httpd service.'
, 0,  TO_Date( '04/22/2003 08:27:51 PM', 'MM/DD/YYYY HH:MI:SS AM'),  TO_Date( '04/23/2003 09:48:30 AM', 'MM/DD/YYYY HH:MI:SS AM')
, 0, 7); 
INSERT INTO RHNFAQ ( ID, SUBJECT, DETAILS, PRIVATE, CREATED, MODIFIED, USAGE_COUNT,
CLASS_ID ) VALUES ( 
308, 'How do I resolve dropped connections during ISO downloads?', 'Red Hat recommends using the Curl open source tool for downloading ISO images. This tool enables you to resume downloads that have been interrupted. If you use Spacewalk and don''t currently have Curl, you may install it by running the command "up2date curl" from a shell prompt.

Once Curl is installed, at a shell prompt, cut and paste the URL for the ISO into the Curl command as follows:

[user@localhost home]$ curl -C - -O ''very_long_url''

The URL, which can be derived from the Easy ISOs page of the Spacewalk website, is very long because it contains session authentication information. Be sure to include the single quotation marks around it. The ''-C -'' option allows you to continue the download if it is interrupted, such as by a lost connection. The ''-O'' (the letter ''O'', not a zero) option will save the file with the same name as on the Spacewalk Servers.'
, 0,  TO_Date( '04/30/2003 07:02:36 PM', 'MM/DD/YYYY HH:MI:SS AM'),  TO_Date( '05/02/2003 11:41:21 AM', 'MM/DD/YYYY HH:MI:SS AM')
, 0, 5); 
INSERT INTO RHNFAQ ( ID, SUBJECT, DETAILS, PRIVATE, CREATED, MODIFIED, USAGE_COUNT,
CLASS_ID ) VALUES ( 
310, 'Why does the registration process prompt me for an organization ID if I don''t need one to register?'
, 'The organization ID is legacy from the days in which Spacewalk allowed users to request addition to an existing organization, which then required an Organization Administrator to approve the new user.

Now, the Spacewalk website allows Organization Administrators to create user accounts directly. Unfortunately, older versions of the registration tools (both rhn_register and up2date) still contain organization ID and password fields. You may disregard them.'
, 0,  TO_Date( '05/02/2003 08:51:09 PM', 'MM/DD/YYYY HH:MI:SS AM'),  TO_Date( '05/03/2003 09:07:56 AM', 'MM/DD/YYYY HH:MI:SS AM')
, 0, 3); 
INSERT INTO RHNFAQ ( ID, SUBJECT, DETAILS, PRIVATE, CREATED, MODIFIED, USAGE_COUNT,
CLASS_ID ) VALUES ( 
221, 'How do I get more legal information?', 'Please go to http://www.redhat.com/software/rhn/legal'
, 0,  TO_Date( '03/27/2003 06:47:21 PM', 'MM/DD/YYYY HH:MI:SS AM'),  TO_Date( '03/31/2003 09:26:11 AM', 'MM/DD/YYYY HH:MI:SS AM')
, 0, 8); 
INSERT INTO RHNFAQ ( ID, SUBJECT, DETAILS, PRIVATE, CREATED, MODIFIED, USAGE_COUNT,
CLASS_ID ) VALUES ( 
224, 'What is an ISO?', 'An ISO is an image file of the contents of a CD.

For example, by downloading the Red Hat Linux ISOs to your system, you can then burn a CD that will be identical to the Red Hat Linux CDs that are available in retail stores.'
, 0,  TO_Date( '03/28/2003 11:22:00 AM', 'MM/DD/YYYY HH:MI:SS AM'),  TO_Date( '04/16/2003 09:07:32 PM', 'MM/DD/YYYY HH:MI:SS AM')
, 0, 11); 
INSERT INTO RHNFAQ ( ID, SUBJECT, DETAILS, PRIVATE, CREATED, MODIFIED, USAGE_COUNT,
CLASS_ID ) VALUES ( 
225, 'What is Errata?', 'An Errata is a message about new updates for your system, usually accompanied by updated packages.

Spacewalk is a tool to update your system with these errata packages.'
, 0,  TO_Date( '03/28/2003 11:25:25 AM', 'MM/DD/YYYY HH:MI:SS AM'),  TO_Date( '04/16/2003 09:08:17 PM', 'MM/DD/YYYY HH:MI:SS AM')
, 0, 11); 
INSERT INTO RHNFAQ ( ID, SUBJECT, DETAILS, PRIVATE, CREATED, MODIFIED, USAGE_COUNT,
CLASS_ID ) VALUES ( 
227, 'How do I repair a corrupt RPM database?', 'Occasionally, the RPM database on a Red Hat Linux machine will become corrupt.  This usually happens when an RPM transaction is interrupted at a critical time.  Symptoms of this problem include one of the following programs not responding or freezing:

* up2date
* The Spacewalk alert notification tool (applet in the Gnome or KDE panel)
* rhn_check
* rpm

This problem can also cause a system to stop checking in with Spacewalk.

To fix this problem, run the following commands as root:

* kill all RPM processes (rhn_check, up2date, rpm, rhn-applet):
     $ ps -axwww | grep rhn_check
In the list of processes, the first number on each line is the PID.  For all PIDs listed except for the one associated with grep:
     $ kill -9 <PID>
Repeat the above steps for each of the programs listed.

* remove any RPM lock files (/var/lib/rpm/__db*):
     $ rm -rf /var/lib/rpm/__db*

* rebuild the rpm database:
     $ rpm --rebuilddb

If the above steps do not work, please contact technical support for more assistance.'
, 0,  TO_Date( '03/28/2003 11:34:34 AM', 'MM/DD/YYYY HH:MI:SS AM'),  TO_Date( '05/07/2003 11:31:57 PM', 'MM/DD/YYYY HH:MI:SS AM')
, 2, 6); 
INSERT INTO RHNFAQ ( ID, SUBJECT, DETAILS, PRIVATE, CREATED, MODIFIED, USAGE_COUNT,
CLASS_ID ) VALUES ( 
231, 'How do I move my Spacewalk entitlement to another machine?', 'All of the systems that you want to entitle, or un-entitle, must be registered with Spacewalk. Please see the FAQ question relating to registering new systems.

First Step - unentitle old system

1) Sign in with Spacewalk
2) Click on "Systems"
3) Click on "Systems Entitlements"
4) Change entitlement of old system to "none"
5) Click "Update Entitlements"

Next Step - entitle new system

From same screen, change the entitlement on the new system to the entitlement you would like to have. Click "Update Entitlements".'
, 0,  TO_Date( '03/28/2003 12:07:10 PM', 'MM/DD/YYYY HH:MI:SS AM'),  TO_Date( '05/14/2003 09:33:40 PM', 'MM/DD/YYYY HH:MI:SS AM')
, 2, 5); 
INSERT INTO RHNFAQ ( ID, SUBJECT, DETAILS, PRIVATE, CREATED, MODIFIED, USAGE_COUNT,
CLASS_ID ) VALUES ( 
230, 'I just upgraded my system. How do I re-register it with Spacewalk?', 'If you are running a version of Red Hat Linux 7.3 (or prior release), do the following:

1) Log in as root
2) Type "rhn_register"

If you are running a version of Red Hat Linux 8.0 (or later release), do the following:

1) Log in as root
2) Type "up2date --register"'
, 0,  TO_Date( '03/28/2003 12:01:49 PM', 'MM/DD/YYYY HH:MI:SS AM'),  TO_Date( '04/24/2003 10:47:23 PM', 'MM/DD/YYYY HH:MI:SS AM')
, 2, 5); 
INSERT INTO RHNFAQ ( ID, SUBJECT, DETAILS, PRIVATE, CREATED, MODIFIED, USAGE_COUNT,
CLASS_ID ) VALUES ( 
232, 'How do I get copies of the latest release notes for Spacewalk?', 'Click on the Help button in the upper right hand corner. Then click on Release Notes listed on the navigation bar on the left.'
, 0,  TO_Date( '03/28/2003 12:16:19 PM', 'MM/DD/YYYY HH:MI:SS AM'),  TO_Date( '03/31/2003 09:26:11 AM', 'MM/DD/YYYY HH:MI:SS AM')
, 0, 5); 
INSERT INTO RHNFAQ ( ID, SUBJECT, DETAILS, PRIVATE, CREATED, MODIFIED, USAGE_COUNT,
CLASS_ID ) VALUES ( 
70, 'pvt: Updating kernel and config files', 'Because of the wide range of changes and setups involved in the scenarios you describe we have chosen the conservative path in the default configuration.

We recommend that you upgrade the kernel on the boxes while you can observe the process (ie, running "up2date --force kernel" from the command line). The same goes for the packages which have config files DBmodified - please check the results of the upgrade process to make sure you will not have an interruption of service due to changed config files.

Once you have been through this process a few times and get a better feel for how Spacewalk handles your particular setup, you can decide to let Spacewalk perform these updates for you automatically.
'
, 1,  TO_Date( '10/02/2002 12:00:00 AM', 'MM/DD/YYYY HH:MI:SS AM'),  TO_Date( '04/14/2003 10:30:31 PM', 'MM/DD/YYYY HH:MI:SS AM')
, 26, 1); 
INSERT INTO RHNFAQ ( ID, SUBJECT, DETAILS, PRIVATE, CREATED, MODIFIED, USAGE_COUNT,
CLASS_ID ) VALUES ( 
73, 'pvt: I can''t get into ftp.redhat.com. Why?', '
Due to the popularity of Red Hat Linux 8.0, our ftp servers are currently heavily loaded, and are at their capacity. We apologize for any inconvenience this may cause.

If you are not able to log into the ftp.redhat.com ftp site, it is probably because the servers are serving the maximum number of users currently. You can try later, or better yet, try one of the many Red Hat mirror sites. They are listed at:

https://www.redhat.com/download/mirror.html
  '
, 1,  TO_Date( '10/02/2002 12:00:00 AM', 'MM/DD/YYYY HH:MI:SS AM'),  TO_Date( '04/24/2003 09:35:36 PM', 'MM/DD/YYYY HH:MI:SS AM')
, 3, 1); 
INSERT INTO RHNFAQ ( ID, SUBJECT, DETAILS, PRIVATE, CREATED, MODIFIED, USAGE_COUNT,
CLASS_ID ) VALUES ( 
82, 'Red Hat''s "GPG Key" - what is it and how do I install it?', 'The first time you run the graphical version of the Red Hat Update Agent, it prompts you to install the Red Hat GPG key. This key is required to authenticate the packages downloaded from Spacewalk. If you run the command line version the first time you start Red Hat Update Agent, you need to install the Red Hat GPG key manually; follow the instructions that up2date displays.'
, 0,  TO_Date( '10/17/2002 12:00:00 AM', 'MM/DD/YYYY HH:MI:SS AM'),  TO_Date( '05/06/2003 11:15:40 PM', 'MM/DD/YYYY HH:MI:SS AM')
, 10, 6); 
INSERT INTO RHNFAQ ( ID, SUBJECT, DETAILS, PRIVATE, CREATED, MODIFIED, USAGE_COUNT,
CLASS_ID ) VALUES ( 
124, 'pvt: no RHL support at rhn-feedback', 'This address is intended for feedback related only to Red Hat
Network. General Red Hat Linux support is not available from this address.
If you are registered with Red Hat Support, you may address your questions
at:
http://www.redhat.com/support

Even if you are not registered with Red Hat Support, you are welcome to browse
our documentation and online resources available at:

https://www.redhat.com/docs/

You may also get access to Tips, FAQs, and online HOWTOs to guide you through
Linux-related tasks if you start looking from our Support Resources Home Page
available at:

https://www.redhat.com/apps/support/resources/

The Red Hat mailing lists are also good venues for finding answers to your
questions. For more information on the Red Hat mailing lists, please see:

http://www.redhat.com/mailing-lists/

If you would like to report a bug or a problem with a component of the Red Hat Linux distribution, we encourage you to visit our bug tracking system and file a bug report at:

http://bugzilla.redhat.com/bugzilla'
, 1,  TO_Date( '12/11/2002 12:00:00 AM', 'MM/DD/YYYY HH:MI:SS AM'),  TO_Date( '03/31/2003 09:26:11 AM', 'MM/DD/YYYY HH:MI:SS AM')
, 10, 1); 
INSERT INTO RHNFAQ ( ID, SUBJECT, DETAILS, PRIVATE, CREATED, MODIFIED, USAGE_COUNT,
CLASS_ID ) VALUES ( 
191, 'pvt: I want to unsubscribe from the maillist !', 'To stop receiving mails from Spacewalk , please see below:

Use your Spacewalk account to login, then go to "Your Spacewalk"==>"Your preferences" .

The Your Preferences page allows you to configure Spacewalk options, including:

      Errata Email Notification — Determine whether you want to receive email every time an Errata Alert is applicable to one or more systems in your Spacewalk account.

      Spacewalk List Page Size — Maximum number of items that will appear in a list on a single page. If more items are in the list, clicking the Next button will display the next group of items. This preference applies to system lists, Errata lists, package lists, and so on.

      Time Zone — Set your time zone so that scheduled actions are scheduled according to the time in your time zone.

      Red Hat Contact Options — Identify what ways (email, phone, fax, or mail) Red Hat may contact you.

After making changes to any of these options, click the Save Preferences button on the bottom right-hand corner.
'
, 1,  TO_Date( '02/19/2003 08:20:46 PM', 'MM/DD/YYYY HH:MI:SS AM'),  TO_Date( '04/27/2003 11:53:51 PM', 'MM/DD/YYYY HH:MI:SS AM')
, 89, 1); 
INSERT INTO RHNFAQ ( ID, SUBJECT, DETAILS, PRIVATE, CREATED, MODIFIED, USAGE_COUNT,
CLASS_ID ) VALUES ( 
209, 'I can''t log in with my username or password.  What should I do?', 'First, please check to see if you are using the correct username and password (see answers to questions in this section). If you are using the correct username and password, please call customer service at 1-866-2-RedHat or contact them at customerservice@redhat.com'
, 0,  TO_Date( '03/27/2003 03:57:30 PM', 'MM/DD/YYYY HH:MI:SS AM'),  TO_Date( '03/31/2003 09:26:10 AM', 'MM/DD/YYYY HH:MI:SS AM')
, 0, 2); 
INSERT INTO RHNFAQ ( ID, SUBJECT, DETAILS, PRIVATE, CREATED, MODIFIED, USAGE_COUNT,
CLASS_ID ) VALUES ( 
228, 'pvt: How can I subscribe for Red Hat 9 now?', 'Red Hat Linux 9 ISOs will be available to paid subscribers starting March 31, 2003--a week before they will be available on redhat.com, in stores, or on Red Hat FTP. A paid subscription also gets you access to Spacewalk technical support, errata updates, priority access during peak times, and immediate email notification. It''s the quickest way to get Red Hat Linux 9.

Note: Spacewalk does not include printed documentation or Red Hat Linux Installation Support. If that''s what you''re looking for,  you can purchase Red Hat Linux 9 at redhat.com or at retail stores, available April 7, 2003. Red Hat Linux 9 or Red Hat Linux 9 Professional includes source code and documentation CDs, printed documentation manuals, installation support, and 1- or 2- month Update Subscription to Spacewalk.

For more informations please visit this page:
http://www.redhat.com/mktg/rh9iso/
'
, 1,  TO_Date( '03/25/2003 03:09:59 AM', 'MM/DD/YYYY HH:MI:SS AM'),  TO_Date( '04/06/2003 09:07:11 PM', 'MM/DD/YYYY HH:MI:SS AM')
, 9, 1); 
INSERT INTO RHNFAQ ( ID, SUBJECT, DETAILS, PRIVATE, CREATED, MODIFIED, USAGE_COUNT,
CLASS_ID ) VALUES ( 
208, 'I am new to Spacewalk. How do I create an account?', 'Go to http://rhn.redhat.com and click on the link that says "Create Account". From here, please follow the directions.'
, 0,  TO_Date( '03/27/2003 03:55:40 PM', 'MM/DD/YYYY HH:MI:SS AM'),  TO_Date( '03/31/2003 09:26:11 AM', 'MM/DD/YYYY HH:MI:SS AM')
, 0, 3); 
INSERT INTO RHNFAQ ( ID, SUBJECT, DETAILS, PRIVATE, CREATED, MODIFIED, USAGE_COUNT,
CLASS_ID ) VALUES ( 
210, 'How do I login to Spacewalk?', 'Go to http://rhn.redhat.com

From this page, enter in your username and password in the box. If you do not have your username and password, please see the FAQ relating to this.'
, 0,  TO_Date( '03/27/2003 03:59:43 PM', 'MM/DD/YYYY HH:MI:SS AM'),  TO_Date( '03/31/2003 09:26:11 AM', 'MM/DD/YYYY HH:MI:SS AM')
, 0, 3); 
INSERT INTO RHNFAQ ( ID, SUBJECT, DETAILS, PRIVATE, CREATED, MODIFIED, USAGE_COUNT,
CLASS_ID ) VALUES ( 
212, 'How do I contact Spacewalk?', 'To contact Spacewalk, please go to: http://www.redhat.com/software/rhn/contact'
, 0,  TO_Date( '03/27/2003 04:02:07 PM', 'MM/DD/YYYY HH:MI:SS AM'),  TO_Date( '03/31/2003 09:26:11 AM', 'MM/DD/YYYY HH:MI:SS AM')
, 0, 1); 
INSERT INTO RHNFAQ ( ID, SUBJECT, DETAILS, PRIVATE, CREATED, MODIFIED, USAGE_COUNT,
CLASS_ID ) VALUES ( 
215, 'How do I know when I need to update my system?', 'Once your system is registered on Spacewalk, a small icon will appear on your tool bar (Red Hat Linux 7.3 and higher). The icon will display either an exclamation point with red background (meaning that there is an update waiting to be downloaded) or a check mark with blue background (meaning that there are no updates waiting). If your icon portrays a question mark, it means that Spacewalk is not able to see your system.

By double clicking on the icon, this will activate Spacewalk update tool.'
, 0,  TO_Date( '03/27/2003 04:27:48 PM', 'MM/DD/YYYY HH:MI:SS AM'),  TO_Date( '03/31/2003 09:26:11 AM', 'MM/DD/YYYY HH:MI:SS AM')
, 0, 1); 
INSERT INTO RHNFAQ ( ID, SUBJECT, DETAILS, PRIVATE, CREATED, MODIFIED, USAGE_COUNT,
CLASS_ID ) VALUES ( 
217, 'Can I use Spacewalk to upgrade to a newer version of Red Hat Linux?', 'No. While Spacewalk always supports the latest version of Red Hat Linux, Spacewalk cannot be used today to upgrade your system from one version of Red Hat Linux to the next. You will need to do a CD based install. However, if you are a paid subscriber to Spacewalk (Update or Management), you have access to the new Red Hat Linux ISOs the moment they are made available. For more information, see http://www.redhat.com/software/rhn/offerings
'
, 0,  TO_Date( '03/27/2003 04:39:01 PM', 'MM/DD/YYYY HH:MI:SS AM'),  TO_Date( '03/31/2003 09:26:11 AM', 'MM/DD/YYYY HH:MI:SS AM')
, 0, 5); 
INSERT INTO RHNFAQ ( ID, SUBJECT, DETAILS, PRIVATE, CREATED, MODIFIED, USAGE_COUNT,
CLASS_ID ) VALUES ( 
219, 'What are the terms and conditions of Spacewalk?', 'To see a copy of the Spacewalk Terms and Conditions, please go to http://www.redhat.com/licenses/rhn.html'
, 0,  TO_Date( '03/27/2003 06:03:20 PM', 'MM/DD/YYYY HH:MI:SS AM'),  TO_Date( '03/31/2003 09:26:11 AM', 'MM/DD/YYYY HH:MI:SS AM')
, 0, 8); 
INSERT INTO RHNFAQ ( ID, SUBJECT, DETAILS, PRIVATE, CREATED, MODIFIED, USAGE_COUNT,
CLASS_ID ) VALUES ( 
23, 'How do I remove a pending action?', 'A pending action will be removed when there are no longer any systems scheduled for it.  For Demo or Update entitlements this will always be done on a per system basis:

* Log into the Spacewalk website.
* Click "Schedule" on the top navigation bar, then "Pending Actions" in the left navigation bar.
* Click on the numeral in the "In Progress" column of the row for the action you want to remove.
* Click on the desired system name.
* Click on the "Events" tab in the System Details navigation.
* Click on the "Pending" subtab.
* Select the event you wish to cancel, and click "Cancel Events"
* Click the "Cancel Selected Events" on the confirmation page.

For systems with Management entitlements, simply remove the systems from the action:

* Click "Schedule" on the top navigation bar, then "Pending Actions" in the left navigation bar.
* Click on the numeral in the "In Progress" column of the row for the action you want to remove.
* Select the systems for removal from the action and then click on the "Unschedule Action" button.
'
, 0,  TO_Date( '06/14/2002 12:00:00 AM', 'MM/DD/YYYY HH:MI:SS AM'),  TO_Date( '05/18/2003 09:53:59 PM', 'MM/DD/YYYY HH:MI:SS AM')
, 14, 7); 
INSERT INTO RHNFAQ ( ID, SUBJECT, DETAILS, PRIVATE, CREATED, MODIFIED, USAGE_COUNT,
CLASS_ID ) VALUES ( 
24, 'Why do scheduled kernel errata fail to install?', 'By default, the kernel packages are marked to be skipped by the update agent.  You can change this configuration by running:

up2date --configure --nox

...and changing or clearing the "pkgSkipList" parameter.  You should then be able to schedule your kernel update.
'
, 0,  TO_Date( '06/14/2002 12:00:00 AM', 'MM/DD/YYYY HH:MI:SS AM'),  TO_Date( '04/30/2003 04:21:47 AM', 'MM/DD/YYYY HH:MI:SS AM')
, 11, 6); 
INSERT INTO RHNFAQ ( ID, SUBJECT, DETAILS, PRIVATE, CREATED, MODIFIED, USAGE_COUNT,
CLASS_ID ) VALUES ( 
131, 'pvt: openssl packages', 'The latest releases of the OpenSSL packages from Red Hat include fixes for all known security vulnerabilities, including the various types of worms that float around.

Please remember that just upgrading the packages is not sufficient. You will have to restart at least your Apache server in order for the new libraries to be loaded by the running Apache process.

More details about the applicable OpenSSL errata can be found at:

https://rhn.redhat.com/errata/RHSA-2002-160.html
and
https://rhn.redhat.com/network/errata/errata_details.pxt?eid=1143
'
, 1,  TO_Date( '12/19/2002 07:33:20 PM', 'MM/DD/YYYY HH:MI:SS AM'),  TO_Date( '03/31/2003 09:26:10 AM', 'MM/DD/YYYY HH:MI:SS AM')
, 4, 1); 
INSERT INTO RHNFAQ ( ID, SUBJECT, DETAILS, PRIVATE, CREATED, MODIFIED, USAGE_COUNT,
CLASS_ID ) VALUES ( 
148, 'pvt: delayed response', 'Due to significant interest & volume in Spacewalk services, we have been unable to respond to your question in a timely manner.  We apologize for the delay and any inconvenience this delay may have caused you.  In response to your question, below is a response to your question.  If this solution does not resolve your issue, please resubmit with additional information.
'
, 1,  TO_Date( '02/05/2003 12:41:33 PM', 'MM/DD/YYYY HH:MI:SS AM'),  TO_Date( '04/03/2003 11:24:13 PM', 'MM/DD/YYYY HH:MI:SS AM')
, 39, 1); 
INSERT INTO RHNFAQ ( ID, SUBJECT, DETAILS, PRIVATE, CREATED, MODIFIED, USAGE_COUNT,
CLASS_ID ) VALUES ( 
168, 'pvt: New To Linux', 'This address is intended for support questions from paid subscribers and is related only to Spacewalk. General Red Hat Linux support is not available from this address.  If you are registered with Red Hat Support, you may address your questions at:
http://www.redhat.com/support

If you have not already done so, you can activate your product and receive advanced support at:

https://www.redhat.com/apps/support/

Even if you are not registered with Red Hat Support, you are welcome to browse
our documentation and online resources available at:

https://www.redhat.com/docs/

You may also get access to Tips, FAQs, and online HOWTOs to guide you through
Linux-related tasks if you start looking from our Support Resources Home Page
available at:

https://www.redhat.com/apps/support/resources/

The Red Hat mailing lists are also good venues for finding answers to your
questions. For more information on the Red Hat mailing lists, please see:

http://www.redhat.com/mailing-lists/

If you would like to report a bug or a problem with a component of the Red Hat Linux distribution, we encourage you to visit our bug tracking system and file a bug report at:

http://bugzilla.redhat.com/bugzilla
'
, 1,  TO_Date( '02/13/2003 04:23:15 AM', 'MM/DD/YYYY HH:MI:SS AM'),  TO_Date( '03/31/2003 09:26:10 AM', 'MM/DD/YYYY HH:MI:SS AM')
, 6, 1); 
INSERT INTO RHNFAQ ( ID, SUBJECT, DETAILS, PRIVATE, CREATED, MODIFIED, USAGE_COUNT,
CLASS_ID ) VALUES ( 
169, 'How do I change my email address?', 'To change your email:

* Log in to the Spacewalk website with your existing username and password.
* If you are not at Your Spacewalk page, click its link in the top navigation bar.
* Click "Your Account" in the left navigation bar.
* Click "Change Email"
* Type your new email in field.
* Click the "Send Verification" or "Update" button.'
, 0,  TO_Date( '02/13/2003 10:03:56 PM', 'MM/DD/YYYY HH:MI:SS AM'),  TO_Date( '04/13/2003 09:15:55 PM', 'MM/DD/YYYY HH:MI:SS AM')
, 16, 2); 
INSERT INTO RHNFAQ ( ID, SUBJECT, DETAILS, PRIVATE, CREATED, MODIFIED, USAGE_COUNT,
CLASS_ID ) VALUES ( 
170, 'pvt: How to entitle system in my Spacewalk', '* Once the system is registered, log in at https://rhn.redhat.com.
* Click "Systems" in the top navigation bar, then "System Entitlements" on the left.
* Select the appropriate entitlement level for the new system and click "Update Entitlements."'
, 1,  TO_Date( '02/13/2003 10:36:28 PM', 'MM/DD/YYYY HH:MI:SS AM'),  TO_Date( '05/15/2003 09:36:58 PM', 'MM/DD/YYYY HH:MI:SS AM')
, 54, 1); 
INSERT INTO RHNFAQ ( ID, SUBJECT, DETAILS, PRIVATE, CREATED, MODIFIED, USAGE_COUNT,
CLASS_ID ) VALUES ( 
188, 'pvt: system on a closed net , but still want to update', 'Spacewalk Management Satellite Server provides for local management of system profiles, thus allowing for completely disconnected operation from external networks.
More information, please follow this link:
https://rhn.redhat.com/info/purchase_info.pxt
'
, 1,  TO_Date( '02/18/2003 09:35:22 PM', 'MM/DD/YYYY HH:MI:SS AM'),  TO_Date( '04/07/2003 11:03:00 PM', 'MM/DD/YYYY HH:MI:SS AM')
, 8, 1); 
INSERT INTO RHNFAQ ( ID, SUBJECT, DETAILS, PRIVATE, CREATED, MODIFIED, USAGE_COUNT,
CLASS_ID ) VALUES ( 
189, 'What are the differences between Update, Management, and Demo Accounts?', 'Update service level subscriptions to Spacewalk allow individuals to register one or more systems, manage these systems independently, receive priority access to Spacewalk, and download Easy ISOs (full versions of Red Hat Linux). Update subscriptions are $60 per system and renew annually. Customers may receive also limited time (less than one year) Update subscriptions with the Red Hat Linux distribution products.

Management service level subscriptions to Spacewalk allow organizations to manage multiple systems, individually or in groups of systems. Management subscriptions efficiently combine the power and flexibility of fine-grained control with the scalability to support thousands of systems.

Demo refers to our complimentary service level. Any user may receive one Demo account with Spacewalk to receive notifications and system updates. Demo users are asked to take a short survey every 60 days in order to provide Red Hat with valued customer input and to validate that the account is still active. Please note that there can be only one demo account per email address.

Note: A Demo account does not provide guaranteed access to errata or bandwidth allocation during peak times, as these resources are reserved for paying subscribers. For this reason, Red Hat strongly recommends purchasing at least an Update service level if you are using your Linux system for home or business production use.

For more information, please follow this link:
http://www.redhat.com/software/rhn/offerings'
, 0,  TO_Date( '02/18/2003 10:53:18 PM', 'MM/DD/YYYY HH:MI:SS AM'),  TO_Date( '04/21/2003 12:08:01 PM', 'MM/DD/YYYY HH:MI:SS AM')
, 48, 4); 
INSERT INTO RHNFAQ ( ID, SUBJECT, DETAILS, PRIVATE, CREATED, MODIFIED, USAGE_COUNT,
CLASS_ID ) VALUES ( 
190, 'pvt:How can i delete my account in Spacewalk?', 'Sorry,you can not delete your account in Spacewalk now. But your account will be disabled if you do not accept the survey per 60 days.'
, 1,  TO_Date( '02/19/2003 04:22:18 AM', 'MM/DD/YYYY HH:MI:SS AM'),  TO_Date( '03/31/2003 09:26:10 AM', 'MM/DD/YYYY HH:MI:SS AM')
, 25, 1); 
COMMIT;
  070701000003A5000081B400000000000000000000000167AE111400000062000000000000000000000000000000000000006A00000000susemanager-schema/upgrade/rhn-satellite-schema-5.1-to-spacewalk-schema-0.2/024-rhnKSTreeType-strings.sql 
update rhnKSTreeType
set name = 'Spacewalk managed kickstart tree'
where label = 'rhn-managed';

  070701000003A6000081B400000000000000000000000167AE111400000143000000000000000000000000000000000000007500000000susemanager-schema/upgrade/rhn-satellite-schema-5.1-to-spacewalk-schema-0.2/025-rhnKickstartSessionState-strings.sql  
update rhnKickstartSessionState
set description = 'The system has downloaded the kickstart configuraton file from Spacewalk.'
where label = 'configuration_accessed';

update rhnKickstartSessionState
set description = 'The system has successfully registered with Spacewalk after kickstarting.'
where label = 'registered';

 070701000003A7000081B400000000000000000000000167AE111400000201000000000000000000000000000000000000007200000000susemanager-schema/upgrade/rhn-satellite-schema-5.1-to-spacewalk-schema-0.2/026-rhnOrgEntitlementType-strings.sql 
update rhnOrgEntitlementType
set name = 'Spacewalk Monitoring'
where label = 'rhn_monitor';

update rhnOrgEntitlementType
set name = 'Spacewalk Provisioning'
where label = 'rhn_provisioning';

update rhnOrgEntitlementType
set name = 'Spacewalk Non-Linux'
where label = 'rhn_nonlinux';

update rhnOrgEntitlementType
set name = 'Spacewalk Virtualization'
where label = 'rhn_virtualization';

update rhnOrgEntitlementType
set name = 'Spacewalk Virtualization Platform'
where label = 'rhn_virtualization_platform';

   070701000003A8000081B400000000000000000000000167AE1114000001C9000000000000000000000000000000000000006F00000000susemanager-schema/upgrade/rhn-satellite-schema-5.1-to-spacewalk-schema-0.2/027-rhnServerGroupType-strings.sql    
update rhnServerGroupType
set name = 'Spacewalk Update Entitled Servers'
where label = 'sw_mgr_entitled';

update rhnServerGroupType
set name = 'Spacewalk Management Entitled Servers'
where label = 'enterprise_entitled';

update rhnServerGroupType
set name = 'Spacewalk Provisioning Entitled Servers'
where label = 'provisioning_entitled';

update rhnServerGroupType
set name = 'Spacewalk Monitoring Entitled Servers'
where label = 'monitoring_entitled';

   070701000003A9000081B400000000000000000000000167AE111400000062000000000000000000000000000000000000007300000000susemanager-schema/upgrade/rhn-satellite-schema-5.1-to-spacewalk-schema-0.2/028-rhnTemplateString_data-strings.sql    
update rhnTemplateString
set value = '-' || '-the Spacewalk Team'
where label = 'email_footer';

  070701000003AA000081B400000000000000000000000167AE1114000000BD000000000000000000000000000000000000007200000000susemanager-schema/upgrade/rhn-satellite-schema-5.1-to-spacewalk-schema-0.2/029-rhnUserGroupType_data-strings.sql 
update rhnUserGroupType
set name = 'Spacewalk Support Administrator'
where label = 'rhn_support';

update rhnUserGroupType
set name = 'Spacewalk Superuser'
where label = 'rhn_superuser';

   070701000003AB000081B400000000000000000000000167AE1114000003C4000000000000000000000000000000000000007200000000susemanager-schema/upgrade/rhn-satellite-schema-5.1-to-spacewalk-schema-0.2/030-rhn_config_macro_data-strings.sql 
update rhn_config_macro
set description = 'Spacewalk administrator email'
where environment = 'LICENSE'
	and name = 'RHN_ADMIN_EMAIL';

update rhn_config_macro
set description = 'Spacewalk database name '
where environment = 'LICENSE'
	and name = 'RHN_DB_NAME';

update rhn_config_macro
set description = 'Spacewalk database password'
where environment = 'LICENSE'
	and name = 'RHN_DB_PASSWD';

update rhn_config_macro
set description = 'Spacewalk Database table owner'
where environment = 'LICENSE'
	and name = 'RHN_DB_TABLE_OWNER';

update rhn_config_macro
set description = 'Spacewalk database username'
where environment = 'LICENSE'
	and name = 'RHN_DB_USERNAME';

update rhn_config_macro
set description = 'Spacewalk hostname (FQDN)'
where environment = 'LICENSE'
	and name = 'RHN_SAT_HOSTNAME';

update rhn_config_macro
set description = 'Spacewalk webserver port (80 for http, 443 for https)'
where environment = 'LICENSE'
	and name = 'RHN_SAT_WEB_PORT';

070701000003AC000081B400000000000000000000000167AE1114000000BB000000000000000000000000000000000000007A00000000susemanager-schema/upgrade/rhn-satellite-schema-5.1-to-spacewalk-schema-0.2/031-rhn_notification_formats_data-strings.sql 
update rhn_notification_formats
set body_format = replace(body_format, 'RHN', 'Spacewalk')
where description in ( 'New Default (2.15)', 'New Default (2.18)' )
	and customer_id is null;

 070701000003AD000081B400000000000000000000000167AE11140000005C000000000000000000000000000000000000006000000000susemanager-schema/upgrade/rhn-satellite-schema-5.1-to-spacewalk-schema-0.2/032-rhn_command.sql   
alter table rhn_command
modify command_class default '/opt/home/nocpulse/libexec/plugin';

070701000003AE000081B400000000000000000000000167AE111400000070000000000000000000000000000000000000007400000000susemanager-schema/upgrade/rhn-satellite-schema-5.1-to-spacewalk-schema-0.2/033-rhn_command_queue_commands_data.sql   
update rhn_command_queue_commands
set command_line = '/opt/home/nocpulse/bin/scheduleEvents'
where recid = 1;

070701000003AF000081B400000000000000000000000167AE11140000005F000000000000000000000000000000000000007200000000susemanager-schema/upgrade/rhn-satellite-schema-5.1-to-spacewalk-schema-0.2/034-rhn_config_parameter_data.sql.sql 
update rhn_config_parameter
set value = '/opt' || value
where value like '/home/nocpulse/%';

 070701000003B0000081B400000000000000000000000167AE111400000028000000000000000000000000000000000000007000000000susemanager-schema/upgrade/rhn-satellite-schema-5.1-to-spacewalk-schema-0.2/035-check_email_uniqueness-drop.sql   
drop function check_email_uniqueness;

070701000003B1000081B400000000000000000000000167AE1114000000E8000000000000000000000000000000000000006B00000000susemanager-schema/upgrade/rhn-satellite-schema-5.1-to-spacewalk-schema-0.2/040-rhnPackage-index-nevra.sql    
drop index rhn_package_n_e_pa_o_uq;
drop index rhn_package_md5_nid_eid_oid_uq;

create unique index rhn_package_md5_oid_uq
	on rhnPackage(md5sum, org_id)
	tablespace [[2m_tbs]]
	storage( pctincrease 1 freelists 16 )
	initrans 32;

070701000003B2000081B400000000000000000000000167AE11140000068C000000000000000000000000000000000000006D00000000susemanager-schema/upgrade/rhn-satellite-schema-5.1-to-spacewalk-schema-0.2/041-rhnPackageProvider-nevra.sql  --
-- Copyright (c) 2008 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
-- $Id$
--

create table
rhnPackageProvider
(
	id		number
			constraint rhn_pkg_provider_id_nn not null,
	name		varchar2(64)
			constraint rhn_pkg_provider_key_nn not null,
	created		date default(sysdate)
			constraint rhn_pkg_provider_created_nn not null,
	modified	date default(sysdate)
			constraint rhn_pkg_provider_modified_nn not null
)
	storage ( freelists 16 )
	initrans 32;

create sequence rhn_package_provider_id_seq start with 100;

-- these must be in this order.
create index rhn_pkg_provider_id_n_idx
	on rhnPackageProvider(id,name)
	tablespace [[2m_tbs]]
	storage ( freelists 16 )
	initrans 32;
alter table rhnPackageProvider add constraint rhn_pkg_provider_id_pk primary key (id);
alter table rhnPackageProvider add constraint rhn_pkg_provider_name_uq unique ( name );



create or replace trigger
rhn_pkg_provider_mod_trig
before insert or update on rhnPackageProvider
for each row
begin
        :new.modified := sysdate;
end;
/

show errors

-- $Log$
-- Revision 1.1  2008/07/01 21:50:21  jsherrill
-- new package gpg tracking 
--
070701000003B3000081B400000000000000000000000167AE11140000068D000000000000000000000000000000000000006C00000000susemanager-schema/upgrade/rhn-satellite-schema-5.1-to-spacewalk-schema-0.2/042-rhnPackageKeyType-nevra.sql   --
-- Copyright (c) 2008 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
-- $Id$
--

create table
rhnPackageKeyType
(
	id		number
			constraint rhn_pkg_key_type_id_nn not null,
	label		varchar2(64)
			constraint rhn_pkg_key_type_label_nn not null,
	created		date default(sysdate)
			constraint rhn_pkg_key_type_created_nn not null,
	modified	date default(sysdate)
			constraint rhn_pkg_key_type_modified_nn not null
)
	storage ( freelists 16 )
	initrans 32;

create sequence rhn_package_key_type_id_seq start with 100;

-- these must be in this order.
create index rhn_pkg_key_type_id_n_idx
	on rhnPackageKeyType(id,label)
	tablespace [[2m_tbs]]
	storage ( freelists 16 )
	initrans 32;
alter table rhnPackageKeyType add constraint rhn_pkg_key_type_id_pk primary key (id);
alter table rhnPackageKeyType add constraint rhn_pkg_key_type_label_uq unique ( label );



create or replace trigger
rhn_pkg_key_type_mod_trig
before insert or update on rhnPackageKeyType
for each row
begin
        :new.modified := sysdate;
end;
/

show errors

-- $Log$
-- Revision 1.1  2008/07/01 21:50:21  jsherrill
-- new package key tracking 
--
   070701000003B4000081B400000000000000000000000167AE111400000779000000000000000000000000000000000000006800000000susemanager-schema/upgrade/rhn-satellite-schema-5.1-to-spacewalk-schema-0.2/043-rhnPackageKey-nevra.sql   --
-- Copyright (c) 2008 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
-- $Id$
--

create table
rhnPackageKey
(
	id		number
			constraint rhn_pkey_id_nn not null,
	key_id		varchar2(64)
			constraint rhn_pkey_key_nn not null,
	key_type_id	number
			constraint rhn_pkey_type_id_nn not null
                        constraint rhn_pkey_type_id_prid_fk
                                references rhnPackageKeyType(id),
	provider_id	number
                        constraint rhn_pkey_prid_fk
				references rhnPackageProvider(id),
	created		date default(sysdate)
			constraint rhn_pkey_created_nn not null,
	modified	date default(sysdate)
			constraint rhn_pkey_modified_nn not null
)
	storage ( freelists 16 )
	initrans 32;

create sequence rhn_pkey_id_seq start with 100;

-- these must be in this order.
create index rhn_pkey_id_k_pid_idx
	on rhnPackageKey(id,key_id,provider_id,key_type_id)
	tablespace [[2m_tbs]]
	storage ( freelists 16 )
	initrans 32;
alter table rhnPackageKey add constraint rhn_pkey_id_pk primary key (id);
alter table rhnPackageKey add constraint rhn_pkey_keyid_uq unique ( key_id );



create or replace trigger
rhn_pkg_gpg_mod_trig
before insert or update on rhnPackageKey
for each row
begin
        :new.modified := sysdate;
end;
/

show errors

-- $Log$
-- Revision 1.1  2008/07/01 21:50:21  jsherrill
-- new package key tracking 
--
   070701000003B5000081B400000000000000000000000167AE111400000547000000000000000000000000000000000000007300000000susemanager-schema/upgrade/rhn-satellite-schema-5.1-to-spacewalk-schema-0.2/044-rhnPackageKeyAssociation-nevra.sql    --
-- Copyright (c) 2008 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
-- $Id$
--/

create table
rhnPackageKeyAssociation
(
	package_id	number
			constraint rhn_pkeya_pid_nn not null 
			constraint rhn_pkeya_pid_fk
				references rhnPackage(id) on delete cascade,
	key_id	number
			constraint rhn_pkeya_kid_nn not null
			constraint rhn_pkeya_kid_fk
				references rhnPackageKey(id),
	created		date default (sysdate)
			constraint rhn_pkeya_created_nn not null,
	modified	date default (sysdate)
			constraint rhn_pkeya_modified_nn not null
)
	storage ( freelists 16 )
	initrans 32;

create unique index rhn_pkeya_pk_uq
	on rhnPackageKeyAssociation(package_id,key_id)
	tablespace [[64k_tbs]]
	storage ( freelists 16 )
	initrans 32;

-- Revision 1.1  2008/07/01 02:00:55  jlsherrill
-- initial add
 070701000003B6000081B400000000000000000000000167AE111400000436000000000000000000000000000000000000007200000000susemanager-schema/upgrade/rhn-satellite-schema-5.1-to-spacewalk-schema-0.2/045-lookup_package_key_type-nevra.sql --
-- Copyright (c) 2008 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
-- $Id$
--

create or replace function
lookup_package_key_type(label_in in varchar2)
return number
deterministic
is
	package_key_type_id number;
begin
	select id into package_key_type_id from rhnPackageKeyType where label = label_in;
	return package_key_type_id;
exception
	when no_data_found then
		rhn_exception.raise_exception('package_key_type_not_found');
end;
/
show errors

-- $Log$
-- Revision 1.1  2008/07/01 23:16:18  jsherrill
-- adding 
--
  070701000003B7000081B400000000000000000000000167AE111400000434000000000000000000000000000000000000007200000000susemanager-schema/upgrade/rhn-satellite-schema-5.1-to-spacewalk-schema-0.2/046-lookup_package_provider-nevra.sql --
-- Copyright (c) 2008 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
-- $Id$
--

create or replace function
lookup_package_provider(name_in in varchar2)
return number
deterministic
is
	package_provider_id number;
begin
	select id into package_provider_id from rhnPackageProvider where name = name_in;
	return package_provider_id;
exception
	when no_data_found then
		rhn_exception.raise_exception('package_provider_not_found');
end;
/
show errors

-- $Log$
-- Revision 1.1  2008/07/01 23:16:18  jsherrill
-- adding 
--
070701000003B8000081B400000000000000000000000167AE111400000465000000000000000000000000000000000000007100000000susemanager-schema/upgrade/rhn-satellite-schema-5.1-to-spacewalk-schema-0.2/047-rhnPackageKeyType_data-nevra.sql  --
-- Copyright (c) 2008 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
-- $Id$

insert into rhnPackageKeyType (id, label) values
(rhn_package_key_type_id_seq.nextval, 'gpg' );
insert into rhnPackageKeyType (id, label) values
(rhn_package_key_type_id_seq.nextval, 'pgp' );
insert into rhnPackageKeyType (id, label) values
(rhn_package_key_type_id_seq.nextval, 'rsa' );
insert into rhnPackageKeyType (id, label) values
(rhn_package_key_type_id_seq.nextval, 'dsa' );



commit;

-- $Log$
-- Revision 1.1  2008/07/02 23:42:28  jsherrill
-- Sequence; data to populate stuff
--

   070701000003B9000081B400000000000000000000000167AE11140000054B000000000000000000000000000000000000007200000000susemanager-schema/upgrade/rhn-satellite-schema-5.1-to-spacewalk-schema-0.2/048-rhnPackageProvider_data-nevra.sql --
-- Copyright (c) 2008 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
-- $Id$

insert into rhnPackageProvider (id, name) values
(rhn_package_provider_id_seq.nextval, 'Red Hat Inc.' );
insert into rhnPackageProvider (id, name) values
(rhn_package_provider_id_seq.nextval, 'Fedora' );
insert into rhnPackageProvider (id, name) values
(rhn_package_provider_id_seq.nextval, 'CentOS' );
insert into rhnPackageProvider (id, name) values
(rhn_package_provider_id_seq.nextval, 'Scientific Linux' );
insert into rhnPackageProvider (id, name) values
(rhn_package_provider_id_seq.nextval, 'Suse' );
insert into rhnPackageProvider (id, name) values
(rhn_package_provider_id_seq.nextval, 'Oracle Inc.' );




commit;

-- $Log$
-- Revision 1.1  2008/07/02 23:42:28  jsherrill
-- Sequence; data to populate stuff
--

 070701000003BA000081B400000000000000000000000167AE111400000B0C000000000000000000000000000000000000006D00000000susemanager-schema/upgrade/rhn-satellite-schema-5.1-to-spacewalk-schema-0.2/049-rhnPackageKey_data-nevra.sql  --
-- Copyright (c) 2008 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
-- $Id$

insert into rhnPackageKey (id, key_id, key_type_id, provider_id) values
(rhn_pkey_id_seq.nextval, '5326810137017186', lookup_package_key_type('gpg'), lookup_package_provider('Red Hat Inc.'));

insert into rhnPackageKey (id, key_id, key_type_id, provider_id) values
(rhn_pkey_id_seq.nextval, '219180cddb42a60e', lookup_package_key_type('gpg'), lookup_package_provider('Red Hat Inc.'));

insert into rhnPackageKey (id, key_id, key_type_id, provider_id) values
(rhn_pkey_id_seq.nextval, 'b44269d04f2a6fd2', lookup_package_key_type('gpg'), lookup_package_provider('Fedora'));

insert into rhnPackageKey (id, key_id, key_type_id, provider_id) values
(rhn_pkey_id_seq.nextval, 'a8a447dce8562897', lookup_package_key_type('gpg'), lookup_package_provider('CentOS'));

insert into rhnPackageKey (id, key_id, key_type_id, provider_id) values
(rhn_pkey_id_seq.nextval, '2802e89216ff0e46', lookup_package_key_type('gpg'), lookup_package_provider('CentOS'));

insert into rhnPackageKey (id, key_id, key_type_id, provider_id) values
(rhn_pkey_id_seq.nextval, 'a53d0bab443e1821', lookup_package_key_type('gpg'), lookup_package_provider('CentOS'));

insert into rhnPackageKey (id, key_id, key_type_id, provider_id) values
(rhn_pkey_id_seq.nextval, '7049e44d025e513b', lookup_package_key_type('gpg'), lookup_package_provider('CentOS'));

insert into rhnPackageKey (id, key_id, key_type_id, provider_id) values
(rhn_pkey_id_seq.nextval, '25dbef78a7048f8d', lookup_package_key_type('gpg'), lookup_package_provider('Scientific Linux'));

insert into rhnPackageKey (id, key_id, key_type_id, provider_id) values
(rhn_pkey_id_seq.nextval, '66ced3de1e5e0159', lookup_package_key_type('gpg'), lookup_package_provider('Oracle Inc.'));

insert into rhnPackageKey (id, key_id, key_type_id, provider_id) values
(rhn_pkey_id_seq.nextval, '2e2bcdbcb38a8516', lookup_package_key_type('gpg'), lookup_package_provider('Oracle Inc.'));

insert into rhnPackageKey (id, key_id, key_type_id, provider_id) values
(rhn_pkey_id_seq.nextval, 'a84edae89c800aca', lookup_package_key_type('gpg'), lookup_package_provider('Suse'));




commit;

-- $Log$
-- Revision 1.1  2008/07/02 23:42:28  jsherrill
-- Sequence; data to populate stuff
--

070701000003BB000081B400000000000000000000000167AE1114000000FF000000000000000000000000000000000000006C00000000susemanager-schema/upgrade/rhn-satellite-schema-5.1-to-spacewalk-schema-0.2/050-rhnException_data-nevra.sql   
insert into rhnException values (-20292, 'package_provider_not_found', 'The specified package provider could not be found.');

insert into rhnException values (-20293, 'package_key_type_not_found', 'The specified package key type could not be found.');

 070701000003BC000081B400000000000000000000000167AE111400000428000000000000000000000000000000000000007E00000000susemanager-schema/upgrade/rhn-satellite-schema-5.1-to-spacewalk-schema-0.2/051-lookup_package_key_type-non-deterministic.sql --
-- Copyright (c) 2008 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
-- $Id$
--

create or replace function
lookup_package_key_type(label_in in varchar2)
return number
is
	package_key_type_id number;
begin
	select id into package_key_type_id from rhnPackageKeyType where label = label_in;
	return package_key_type_id;
exception
	when no_data_found then
		rhn_exception.raise_exception('package_key_type_not_found');
end;
/
show errors

-- $Log$
-- Revision 1.1  2008/07/01 23:16:18  jsherrill
-- adding 
--
070701000003BD000081B400000000000000000000000167AE111400000426000000000000000000000000000000000000007E00000000susemanager-schema/upgrade/rhn-satellite-schema-5.1-to-spacewalk-schema-0.2/052-lookup_package_provider-non-deterministic.sql --
-- Copyright (c) 2008 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
-- $Id$
--

create or replace function
lookup_package_provider(name_in in varchar2)
return number
is
	package_provider_id number;
begin
	select id into package_provider_id from rhnPackageProvider where name = name_in;
	return package_provider_id;
exception
	when no_data_found then
		rhn_exception.raise_exception('package_provider_not_found');
end;
/
show errors

-- $Log$
-- Revision 1.1  2008/07/01 23:16:18  jsherrill
-- adding 
--
  070701000003BE000081B400000000000000000000000167AE111400000022000000000000000000000000000000000000006F00000000susemanager-schema/upgrade/rhn-satellite-schema-5.1-to-spacewalk-schema-0.2/053-1-rhnPackageSignature-drop.sql    
drop table rhnPackageSignature;

  070701000003BF000081B400000000000000000000000167AE111400000028000000000000000000000000000000000000007200000000susemanager-schema/upgrade/rhn-satellite-schema-5.1-to-spacewalk-schema-0.2/053-2-rhn_package_sig_id_seq-drop.sql 
drop sequence rhn_package_sig_id_seq;

070701000003C0000081B400000000000000000000000167AE111400000020000000000000000000000000000000000000006D00000000susemanager-schema/upgrade/rhn-satellite-schema-5.1-to-spacewalk-schema-0.2/054-1-rhnPackageSigType-drop.sql  
drop table rhnPackageSigType;

070701000003C1000081B400000000000000000000000167AE11140000002D000000000000000000000000000000000000007700000000susemanager-schema/upgrade/rhn-satellite-schema-5.1-to-spacewalk-schema-0.2/054-2-rhn_package_sig_type_id_seq-drop.sql    
drop sequence rhn_package_sig_type_id_seq;

   070701000003C2000081B400000000000000000000000167AE111400000025000000000000000000000000000000000000007300000000susemanager-schema/upgrade/rhn-satellite-schema-5.1-to-spacewalk-schema-0.2/055-0-rhnPackageChangeLog-sequence.sql    
create sequence rhn_pkg_cl_id_seq;

   070701000003C3000081B400000000000000000000000167AE11140000011F000000000000000000000000000000000000006D00000000susemanager-schema/upgrade/rhn-satellite-schema-5.1-to-spacewalk-schema-0.2/055-1-rhnPackageChangeLog-id.sql  
alter table rhnPackageChangelog
add id              number;
alter table rhnPackageChangelog
modify id
        constraint rhn_pkg_cl_id_nn not null novalidate
        constraint rhn_pkg_cl_id_pk primary key
                using index tablespace [[64k_tbs]]
                novalidate;

 070701000003C4000081B400000000000000000000000167AE1114000000D3000000000000000000000000000000000000007200000000susemanager-schema/upgrade/rhn-satellite-schema-5.1-to-spacewalk-schema-0.2/055-2-rhnPackageChangeLog-id-data.sql begin
  loop
      update rhnPackageChangelog
         set id = rhn_pkg_cl_id_seq.nextval
       where id is null and rownum <= 1000000;
  exit when sql%rowcount = 0;
      commit;
  end loop;
  commit;
end;
/

 070701000003C5000081B400000000000000000000000167AE11140000009E000000000000000000000000000000000000007600000000susemanager-schema/upgrade/rhn-satellite-schema-5.1-to-spacewalk-schema-0.2/055-3-rhnPackageChangeLog-id-not-null.sql 
alter table rhnPackageChangelog
modify
	constraint rhn_pkg_cl_id_nn validate;
alter table rhnPackageChangelog
modify
	constraint rhn_pkg_cl_id_pk validate;

  070701000003C6000081B400000000000000000000000167AE111400000D9C000000000000000000000000000000000000006F00000000susemanager-schema/upgrade/rhn-satellite-schema-5.1-to-spacewalk-schema-0.2/056-create_new_org-no-password.sql    --
-- Copyright (c) 2008--2013 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--

create or replace procedure
create_new_org
(
	name_in      in varchar2,
	password_in  in varchar2,
	org_id_out   out number
) is
	ug_type			number;
	group_val		number;
	new_org_id              number;
begin
    
        select web_customer_id_seq.nextval into new_org_id from dual;

	insert into web_customer (
		id, name,
		oracle_customer_id, oracle_customer_number,
		customer_type
	) values (
		new_org_id, name_in,
		new_org_id, new_org_id, 'B'
	);

	select rhn_user_group_id_seq.nextval into group_val from dual;

	select	id
	into	ug_type
	from	rhnUserGroupType
	where	label = 'org_admin';

	insert into rhnUserGroup (
		id, name,
		description,
		max_members, group_type, org_id
	) values (
		group_val, 'Organization Administrators',
		'Organization Administrators for Org ' || name_in,
		NULL, ug_type, new_org_id
	);

	select rhn_user_group_id_seq.nextval into group_val from dual;

	select	id
	into	ug_type
	from	rhnUserGroupType
	where	label = 'org_applicant';

	insert into rhnUserGroup (
		id, name,
		description,
		max_members, group_type, org_id
	) VALues (
		group_val, 'Organization Applicants',
		'Organization Applicants for Org ' || name_in,
		NULL, ug_type, new_org_id
	);

	select rhn_user_group_id_seq.nextval into group_val from dual;

	select	id
	into	ug_type
	from	rhnUserGroupType
	where	label = 'system_group_admin';

	insert into rhnUserGroup (
		id, name,
		description,
		max_members, group_type, org_id
	) values (
		group_val, 'System Group Administrators',
		'System Group Administrators for Org ' || name_in,
		NULL, ug_type, new_org_id
	);


	select rhn_user_group_id_seq.nextval into group_val from dual;

	select	id
	into	ug_type
	from	rhnUserGroupType
	where	label = 'activation_key_admin';

	insert into rhnUserGroup (
		id, name,
		description,
		max_members, group_type, org_id
	) values (
		group_val, 'Activation Key Administrators',
		'Activation Key Administrators for Org ' || name_in,
		NULL, ug_type, new_org_id
	);

	-- config admin is special; it gets created in
	-- rhn_entitlements.set_customer_provisioning instead.
	
	select rhn_user_group_id_seq.nextval into group_val from dual;

	select	id
	into	ug_type
	from	rhnUserGroupType
	where	label = 'channel_admin';

	insert into rhnUserGroup (
		id, name,
		description,
		max_members, group_type, org_id
	) values (
		group_val, 'Channel Administrators',
		'Channel Administrators for Org ' || name_in,
		NULL, ug_type, new_org_id
	);

	-- there aren't any users yet, so we don't need to update
	-- rhnUserServerPerms
        insert into rhnServerGroup 
		( id, name, description, max_members, group_type, org_id )
		select rhn_server_group_id_seq.nextval, sgt.name, sgt.name, 
			0, sgt.id, new_org_id
		from rhnServerGroupType sgt
		where sgt.label = 'sw_mgr_entitled';
	
	org_id_out := new_org_id;
		
end create_new_org;
/
show errors;

070701000003C7000081B400000000000000000000000167AE111400000FC3000000000000000000000000000000000000007100000000susemanager-schema/upgrade/rhn-satellite-schema-5.1-to-spacewalk-schema-0.2/057-create_first_org-no-password.sql  --
-- Copyright (c) 2008 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
-- $Id$
--
-- EXCLUDE: production
--
-- This creates an org with ID of 1, and errors if there already is one
--



create or replace procedure
create_first_org
(
	name_in in varchar2,
	password_in in varchar2
) is
	ug_type			number;
	group_val		number;
begin
	insert into web_customer (
		id, name,
		oracle_customer_id, oracle_customer_number,
		customer_type
	) values (
		1, name_in,
		1, 1, 'B'
	);

	select rhn_user_group_id_seq.nextval into group_val from dual;

	select	id
	into	ug_type
	from	rhnUserGroupType
	where	label = 'org_admin';

	insert into rhnUserGroup (
		id, name,
		description,
		max_members, group_type, org_id
	) values (
		group_val, 'Organization Administrators',
		'Organization Administrators for Org ' || name_in || ' (1)',
		NULL, ug_type, 1
	);

	select rhn_user_group_id_seq.nextval into group_val from dual;

	select	id
	into	ug_type
	from	rhnUserGroupType
	where	label = 'org_applicant';

	insert into rhnUserGroup (
		id, name,
		description,
		max_members, group_type, org_id
	) VALues (
		group_val, 'Organization Applicants',
		'Organization Applicants for Org ' || name_in || ' (1)',
		NULL, ug_type, 1
	);

	select rhn_user_group_id_seq.nextval into group_val from dual;

	select	id
	into	ug_type
	from	rhnUserGroupType
	where	label = 'system_group_admin';

	insert into rhnUserGroup (
		id, name,
		description,
		max_members, group_type, org_id
	) values (
		group_val, 'System Group Administrators',
		'System Group Administrators for Org ' || name_in || ' (1)',
		NULL, ug_type, 1
	);


	select rhn_user_group_id_seq.nextval into group_val from dual;

	select	id
	into	ug_type
	from	rhnUserGroupType
	where	label = 'activation_key_admin';

	insert into rhnUserGroup (
		id, name,
		description,
		max_members, group_type, org_id
	) values (
		group_val, 'Activation Key Administrators',
		'Activation Key Administrators for Org ' || name_in || ' (1)',
		NULL, ug_type, 1
	);

	-- config admin is special; it gets created in
	-- rhn_entitlements.set_customer_provisioning instead.
	
	select rhn_user_group_id_seq.nextval into group_val from dual;

	select	id
	into	ug_type
	from	rhnUserGroupType
	where	label = 'channel_admin';

	insert into rhnUserGroup (
		id, name,
		description,
		max_members, group_type, org_id
	) values (
		group_val, 'Channel Administrators',
		'Channel Administrators for Org ' || name_in || ' (1)',
		NULL, ug_type, 1
	);

	select rhn_user_group_id_seq.nextval into group_val from dual;

	select	id
	into	ug_type
	from	rhnUserGroupType
	where	label = 'satellite_admin';

	insert into rhnUserGroup (
		id, name,
		description,
		max_members, group_type, org_id
	) values (
		group_val, 'Satellite Administrators',
		'Satellite Administrators for Org ' || name_in || ' (1)',
		NULL, ug_type, 1
	);


	-- if they need more than 16GB, they'll call us and we'll whip
	-- out a "can be null" patch, which we should do for next
	-- version anyway.  (I thought we did that for this version?)
	insert into rhnOrgQuota(
		org_id, total
	) values (
		1, 1024*1024*1024*16
	);
	
	
	-- there aren't any users yet, so we don't need to update
	-- rhnUserServerPerms
        insert into rhnServerGroup 
		( id, name, description, max_members, group_type, org_id )
		select rhn_server_group_id_seq.nextval, sgt.name, sgt.name, 
			0, sgt.id, 1
		from rhnServerGroupType sgt
		where sgt.label = 'sw_mgr_entitled';
		
end create_first_org;
/
show errors;

 070701000003C8000081B400000000000000000000000167AE111400000031000000000000000000000000000000000000006F00000000susemanager-schema/upgrade/rhn-satellite-schema-5.1-to-spacewalk-schema-0.2/058-web_customer-drop-password.sql    
alter table web_customer
drop column password;

   070701000003C9000081B400000000000000000000000167AE11140000AF0C000000000000000000000000000000000000006E00000000susemanager-schema/upgrade/rhn-satellite-schema-5.1-to-spacewalk-schema-0.2/060-rhn_channel-deterministic.sql --
-- Copyright (c) 2008 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
-- $Id$
--

CREATE OR REPLACE
PACKAGE BODY rhn_channel
IS
	body_version varchar2(100) := '$Id$';

    -- Cursor that fetches all the possible base channels for a
    -- (server_arch_id, release, org_id) combination
	cursor	base_channel_cursor(
		release_in in varchar2,
		server_arch_id_in in number,
		org_id_in in number
	) return rhnChannel%ROWTYPE is
		select distinct c.*
		from	rhnDistChannelMap			dcm,
				rhnServerChannelArchCompat	scac,
				rhnChannel					c,
				rhnChannelPermissions		cp
		where	cp.org_id = org_id_in
			and cp.channel_id = c.id
			and c.parent_channel is null
			and c.id = dcm.channel_id
			and c.channel_arch_id = dcm.channel_arch_id
			and dcm.release = release_in
			and scac.server_arch_id = server_arch_id_in
			and scac.channel_arch_id = c.channel_arch_id;

    FUNCTION get_license_path(channel_id_in IN NUMBER)
    RETURN VARCHAR2
    IS
    	license_val VARCHAR2(1000);
    BEGIN
    	SELECT CFL.license_path INTO license_val
	  FROM rhnChannelFamilyLicense CFL, rhnChannelFamilyMembers CFM
	 WHERE CFM.channel_id = channel_id_in
	   AND CFM.channel_family_id = CFL.channel_family_id;
    
    	RETURN license_val;

    EXCEPTION
    	WHEN NO_DATA_FOUND
	    THEN
	    RETURN NULL;
    END get_license_path;


    PROCEDURE license_consent(channel_id_in IN NUMBER, user_id_in IN NUMBER, server_id_in IN NUMBER)
    IS
    	channel_family_id_val NUMBER;
    BEGIN
    	channel_family_id_val := rhn_channel.family_for_channel(channel_id_in);
	IF channel_family_id_val IS NULL
	THEN
	    rhn_exception.raise_exception('channel_subscribe_no_family');
	END IF;
	
	IF rhn_channel.get_license_path(channel_id_in) IS NULL
	THEN
	    rhn_exception.raise_exception('channel_consent_no_license');
	END IF;
	
	INSERT INTO rhnChannelFamilyLicenseConsent (channel_family_id, user_id, server_id)
	VALUES (channel_family_id_val, user_id_in, server_id_in);
    END license_consent;

    PROCEDURE subscribe_server(server_id_in IN NUMBER, channel_id_in NUMBER, immediate_in NUMBER := 1, user_id_in in number := null)
    IS
        channel_parent_val      rhnChannel.parent_channel%TYPE;
        parent_subscribed       BOOLEAN;
        server_has_base_chan    BOOLEAN;
	server_already_in_chan  BOOLEAN;
	channel_family_id_val   NUMBER;
	server_org_id_val       NUMBER;
	available_subscriptions NUMBER;
	consenting_user         NUMBER;
	allowed			number := 0;
    current_members_val     number;
    BEGIN
    	if user_id_in is not null then
		allowed := rhn_channel.user_role_check(channel_id_in, user_id_in, 'subscribe');
	else
		allowed := 1;
	end if;

	if allowed = 0 then
		rhn_exception.raise_exception('no_subscribe_permissions');
	end if;


        SELECT parent_channel INTO channel_parent_val FROM rhnChannel WHERE id = channel_id_in;

        IF channel_parent_val IS NOT NULL
        THEN    
	    -- child channel; if attempting to cross-subscribe a child to the wrong base, silently ignore
            parent_subscribed := FALSE;    

            FOR check_subscription IN check_server_subscription(server_id_in, channel_parent_val)
            LOOP
                parent_subscribed := TRUE;
            END LOOP check_subscription;
        
            IF NOT parent_subscribed
            THEN
    	    	RETURN;
            END IF;
        ELSE
	    -- base channel
            server_has_base_chan := FALSE;
            FOR base IN server_base_subscriptions(server_id_in)
            LOOP
                server_has_base_chan := TRUE;
            END LOOP base;
            
            IF server_has_base_chan
            THEN
                rhn_exception.raise_exception('channel_server_one_base');
            END IF;
        END IF;
    
        FOR check_subscription IN check_server_subscription(server_id_in, channel_id_in)
        LOOP
            server_already_in_chan := TRUE;
        END LOOP check_subscription;
    
        IF server_already_in_chan
        THEN
    	    RETURN;
        END IF;
	
	channel_family_id_val := rhn_channel.family_for_channel(channel_id_in);
	IF channel_family_id_val IS NULL
	THEN
	    rhn_exception.raise_exception('channel_subscribe_no_family');
	END IF;
	
	SELECT org_id INTO server_org_id_val
	  FROM rhnServer
	 WHERE id = server_id_in;
	 
    select current_members 
    into current_members_val
    from rhnPrivateChannelFamily
    where org_id = server_org_id_val and channel_family_id = channel_family_id_val
    for update of current_members;

	available_subscriptions := rhn_channel.available_family_subscriptions(channel_family_id_val, server_org_id_val);
	
	IF available_subscriptions IS NULL OR 
       available_subscriptions > 0 or
       can_server_consume_virt_channl(server_id_in, channel_family_id_val) = 1
	THEN
	
	    IF rhn_channel.get_license_path(channel_id_in) IS NOT NULL
	    THEN
	    	BEGIN
		
	    	SELECT user_id INTO consenting_user
		  FROM rhnChannelFamilyLicenseConsent
		 WHERE channel_family_id = channel_family_id_val
		   AND server_id = server_id_in;
		
		EXCEPTION
    	    	    WHEN NO_DATA_FOUND
		    	THEN
			    rhn_exception.raise_exception('channel_subscribe_no_consent');
		END;
	    END IF;
	
	    insert into rhnServerHistory (id,server_id,summary,details) (
	    	select	rhn_event_id_seq.nextval,
			server_id_in,
			'subscribed to channel ' || SUBSTR(c.label, 0, 106),
			c.label
		from	rhnChannel c
		where	c.id = channel_id_in
	    );
	    UPDATE rhnServer SET channels_changed = sysdate WHERE id = server_id_in;
            INSERT INTO rhnServerChannel (server_id, channel_id) VALUES (server_id_in, channel_id_in);

    	    rhn_channel.update_family_counts(channel_family_id_val, server_org_id_val);
    	    queue_server(server_id_in, immediate_in);
	ELSE
	    rhn_exception.raise_exception('channel_family_no_subscriptions');
	END IF;
	    
    END subscribe_server;
    
    function can_server_consume_virt_channl(
        server_id_in in number,
        family_id_in in number )
    return number
    is

        cursor server_virt_families is
            select vi.virtual_system_id, cfvsl.channel_family_id
            from
                rhnChannelFamilyVirtSubLevel cfvsl,
                rhnSGTypeVirtSubLevel sgtvsl,
                rhnVirtualInstance vi
            where
                vi.virtual_system_id = server_id_in 
                and sgtvsl.virt_sub_level_id = cfvsl.virt_sub_level_id
                and cfvsl.channel_family_id = family_id_in
                and exists (
                    select 1
                    from rhnServerEntitlementView sev
                    where vi.host_system_id = sev.server_id
                    and sev.server_group_type_id = sgtvsl.server_group_type_id );
    begin

        for server_virt_family in server_virt_families loop
            return 1;
        end loop;

        return 0;

    end;


    PROCEDURE bulk_subscribe_server(channel_id_in IN NUMBER, set_label_in IN VARCHAR2, set_uid_in IN NUMBER)
    IS
    BEGIN
        FOR server IN rhn_set.set_iterator(set_label_in, set_uid_in)
        LOOP
            rhn_channel.subscribe_server(server.element, channel_id_in, 0, set_uid_in);
        END LOOP server;
    END bulk_subscribe_server;

    PROCEDURE bulk_server_base_change(channel_id_in IN NUMBER, set_label_in IN VARCHAR2, set_uid_in IN NUMBER)
    IS
    BEGIN
        FOR server IN rhn_set.set_iterator(set_label_in, set_uid_in)
        LOOP
	    IF rhn_server.can_change_base_channel(server.element) = 1
	    THEN
                rhn_channel.clear_subscriptions(TO_NUMBER(server.element));
                rhn_channel.subscribe_server(server.element, channel_id_in, 0, set_uid_in);
            END IF;
        END LOOP server;
    END bulk_server_base_change;

    procedure bulk_server_basechange_from(
        set_label_in in varchar2,
        set_uid_in in number,
        old_channel_id_in in number,
        new_channel_id_in in number
    ) is
    cursor servers is
        select  sc.server_id id
        from    rhnChannel nc,
                rhnServerChannelArchCompat scac,
                rhnServer s,
                rhnChannel oc,
                rhnServerChannel sc,
                rhnSet st
        where   1=1
            -- first, find the servers we're looking for.
            and st.label = set_label_in
            and st.user_id = set_uid_in
            and st.element = sc.server_id
            -- now, filter out anything that's not in the
            -- old base channel.
            and sc.channel_id = old_channel_id_in
            and sc.channel_id = oc.id
            and oc.parent_channel is null
            -- now, see if it's compatible with the new base channel
            and nc.id = new_channel_id_in
            and nc.parent_channel is null
            and sc.server_id = s.id
            and s.server_arch_id = scac.server_arch_id
            and scac.channel_arch_id = nc.channel_arch_id;
    begin
        for s in servers loop
            insert into rhnSet (
                    user_id, label, element
                ) values (
                    set_uid_in,
                    set_label_in || 'basechange', 
                    s.id
                );
        end loop channel;
        bulk_server_base_change(new_channel_id_in,
                                set_label_in || 'basechange',
                                set_uid_in);
        delete from rhnSet
            where   label = set_label_in||'basechange'
                and user_id = set_uid_in;
    end bulk_server_basechange_from;

    procedure bulk_guess_server_base(
	set_label_in in varchar2,
	set_uid_in in number
    ) is
	channel_id number;
    begin
	for server in rhn_set.set_iterator(set_label_in, set_uid_in)
	loop
	    -- anything that doesn't work, we just ignore
	    begin
	    	if rhn_server.can_change_base_channel(server.element) = 1
		then
    	            channel_id := guess_server_base(TO_NUMBER(server.element));
	    	    rhn_channel.clear_subscriptions(TO_NUMBER(server.element));
	    	    rhn_channel.subscribe_server(TO_NUMBER(server.element), channel_id, 0, set_uid_in);
		end if;
	    exception when others then
	    	null;
	    end;
	end loop server;
    end;

    function guess_server_base(
    	server_id_in in number
    ) RETURN number is
	cursor server_cursor is
	    select s.server_arch_id, s.release, s.org_id
	      from rhnServer s
	     where s.id = server_id_in;
    begin
	for s in server_cursor loop
	    for channel in base_channel_cursor(s.release,
		s.server_arch_id, s.org_id) 
	    loop
		return channel.id;
	    end loop base_channel_cursor;
        end loop server_cursor;
	-- Server not found, or no base channel applies to it
        return null;
    end;

    -- Private function
    function normalize_server_arch(server_arch_in in varchar2)
    return varchar2
    deterministic
    is
	suffix VARCHAR2(128) := '-redhat-linux';
	suffix_len NUMBER := length(suffix);
    begin
	if server_arch_in is NULL then
	    return NULL;
	end if;
        if instr(server_arch_in, '-') > 0
	then
	    -- Suffix already present
	    return server_arch_in;
	end if;
	return server_arch_in || suffix;
    end normalize_server_arch;

    --
    --
    -- Raises: 
    --   server_arch_not_found
    --   no_subscribe_permissions
    function base_channel_for_release_arch(
	release_in in varchar2,
	server_arch_in in varchar2,
	org_id_in in number := -1,
	user_id_in in number := null
    ) return number is
	server_arch varchar2(256) := normalize_server_arch(server_arch_in);
	server_arch_id number;
    begin
	-- Look up the server arch
	begin
	    select id
	      into server_arch_id
	      from rhnServerArch
	     where label = server_arch;
	exception
	    when no_data_found then
		rhn_exception.raise_exception('server_arch_not_found');
	end;
	return base_channel_rel_archid(release_in, server_arch_id,
	    org_id_in, user_id_in);
    end base_channel_for_release_arch;

    function base_channel_rel_archid(
	release_in in varchar2,
	server_arch_id_in in number,
	org_id_in in number := -1,
	user_id_in in number := null
    ) return number is
	denied_channel_id number := null;
	valid_org_id number := org_id_in;
	valid_user_id number := user_id_in;
	channel_subscribable number;
    begin
	if org_id_in = -1 and user_id_in is not null then
	    -- Get the org id from the user id
	    begin
		select org_id
		  into valid_org_id
		  from web_contact
		 where id = user_id_in;
	    exception
		when no_data_found then
		    -- User doesn't exist
		    -- XXX Only list public stuff for now
		    valid_user_id := null;
		    valid_org_id := -1;
	    end;
	end if;

	for c in base_channel_cursor(release_in, server_arch_id_in, valid_org_id)
	loop
	    -- This row is a possible match
	    if valid_user_id is null then
		-- User ID not specified, so no user to channel permissions to
		-- check
		return c.id;
	    end if;

	    -- Check user to channel permissions
	    select loose_user_role_check(c.id, user_id_in, 'subscribe')
	      into channel_subscribable
	      from dual;

	    if channel_subscribable = 1 then
		return c.id;
	    end if;
		
	    -- Base channel exists, but is not subscribable; keep trying
	    denied_channel_id := c.id;
	end loop base_channel_fetch;
	
	if denied_channel_id is not null then
	    rhn_exception.raise_exception('no_subscribe_permissions');
	end if;
	-- No base channel applies
	return NULL;
    end base_channel_rel_archid;

    procedure bulk_guess_server_base_from(
	set_label_in in varchar2,
	set_uid_in in number,
	channel_id_in in number
    ) is
	cursor channels(server_id_in in number) is
	    select	rsc.channel_id
	    from	rhnServerChannel rsc,
			rhnChannel rc
	    where	server_id_in = rsc.server_id
			and rsc.channel_id = rc.id
			and rc.parent_channel is null;
    begin
	for server in rhn_set.set_iterator(set_label_in, set_uid_in)
	loop
	    for channel in channels(server.element)
	    loop
		if channel.channel_id = channel_id_in
		then
		    insert into rhnSet (user_id, label, element) values (set_uid_in, set_label_in || 'baseguess', server.element);
		end if;
	    end loop channel;
	end loop server;
	bulk_guess_server_base(set_label_in||'baseguess',set_uid_in);
	delete from rhnSet where label = set_label_in||'baseguess' and user_id = set_uid_in;
    end;


    PROCEDURE clear_subscriptions(server_id_in IN NUMBER, deleting_server IN NUMBER := 0 )
    IS
    	cursor server_channels(server_id_in in number) is
		select	s.org_id, sc.channel_id, cfm.channel_family_id
		from	rhnServer s,
			rhnServerChannel sc,
			rhnChannelFamilyMembers cfm
		where	s.id = server_id_in
			and s.id = sc.server_id
			and sc.channel_id = cfm.channel_id;
    BEGIN
    	for channel in server_channels(server_id_in)
	loop
		unsubscribe_server(server_id_in, channel.channel_id, 1, 1, deleting_server);
		rhn_channel.update_family_counts(channel.channel_family_id, channel.org_id);
	end loop channel;
    END clear_subscriptions;

    PROCEDURE unsubscribe_server(server_id_in IN NUMBER, channel_id_in NUMBER, immediate_in NUMBER := 1, unsubscribe_children_in number := 0,
                                 deleting_server IN NUMBER := 0 )
    IS
	channel_family_id_val   NUMBER;
	server_org_id_val       NUMBER;
	available_subscriptions NUMBER;	
	server_already_in_chan  BOOLEAN;
	cursor	channel_family_is_proxy(channel_family_id_in in number) is
		select	1
		from	rhnChannelFamily
		where	id = channel_family_id_in
		    and label = 'rhn-proxy';
	cursor	channel_family_is_satellite(channel_family_id_in in number) is
		select	1
		from	rhnChannelFamily
		where	id = channel_family_id_in
		    and label = 'rhn-satellite';
	-- this is *EXACTLY* like check_server_parent_membership, but if we recurse
	-- with the package-level one, we get a "cursor already open", so we need a
	-- copy on our call stack instead.  GROAN.
	cursor local_chk_server_parent_memb (
			server_id_in number,
			channel_id_in number ) is
		select	c.id
		from	rhnChannel			c,
				rhnServerChannel	sc
		where	1=1
			and c.parent_channel = channel_id_in
			and c.id = sc.channel_id
			and sc.server_id = server_id_in;
    BEGIN
        FOR child IN local_chk_server_parent_memb(server_id_in, channel_id_in)
        LOOP
	    if unsubscribe_children_in = 1 then
	    	unsubscribe_server(server_id_in => server_id_in,
								channel_id_in => child.id,
								immediate_in => immediate_in,
								unsubscribe_children_in => unsubscribe_children_in,
                        deleting_server => deleting_server);
	    else
	    	rhn_exception.raise_exception('channel_unsubscribe_child_exists');
	    end if;
        END LOOP child;
	
	server_already_in_chan := FALSE;
    
        FOR check_subscription IN check_server_subscription(server_id_in, channel_id_in)
        LOOP
            server_already_in_chan := TRUE;
        END LOOP check_subscription;
    
        IF NOT server_already_in_chan
        THEN
    	    RETURN;
        END IF;
	
   if deleting_server = 0 then 

      insert into rhnServerHistory (id,server_id,summary,details) (
          select  rhn_event_id_seq.nextval,
                server_id_in,
             'unsubscribed from channel ' || SUBSTR(c.label, 0, 106),
             c.label
          from    rhnChannel c
          where   c.id = channel_id_in
      );

   	UPDATE rhnServer SET channels_changed = sysdate WHERE id = server_id_in;
   end if;
	
   DELETE FROM rhnServerChannel WHERE server_id = server_id_in AND channel_id = channel_id_in;

   if deleting_server = 0 then 
     	queue_server(server_id_in, immediate_in);
   end if;

	channel_family_id_val := rhn_channel.family_for_channel(channel_id_in);
	IF channel_family_id_val IS NULL
	THEN
	    rhn_exception.raise_exception('channel_unsubscribe_no_family');
	END IF;

	for ignore in channel_family_is_satellite(channel_family_id_val) loop
		delete from rhnSatelliteInfo where server_id = server_id_in;
		delete from rhnSatelliteChannelFamily where server_id = server_id_in;
	end loop;

	for ignore in channel_family_is_proxy(channel_family_id_val) loop
		delete from rhnProxyInfo where server_id = server_id_in;
	end loop;

	DELETE FROM rhnChannelFamilyLicenseConsent
	 WHERE channel_family_id = channel_family_id_val
	   AND server_id = server_id_in;
			
	SELECT org_id INTO server_org_id_val
	  FROM rhnServer
	 WHERE id = server_id_in;
	 
	rhn_channel.update_family_counts(channel_family_id_val, server_org_id_val);
    END unsubscribe_server;

    PROCEDURE bulk_unsubscribe_server(channel_id_in IN NUMBER, set_label_in IN VARCHAR2, set_uid_in IN NUMBER)
    IS
    BEGIN
        FOR server IN rhn_set.set_iterator(set_label_in, set_uid_in)
        LOOP
            rhn_channel.unsubscribe_server(server.element, channel_id_in, 0);
        END LOOP server;
    END bulk_unsubscribe_server;

    FUNCTION family_for_channel(channel_id_in IN NUMBER)
    RETURN NUMBER
    IS
    	channel_family_id_val NUMBER;
    BEGIN
    	SELECT channel_family_id INTO channel_family_id_val
	  FROM rhnChannelFamilyMembers
         WHERE channel_id = channel_id_in;
	 
	RETURN channel_family_id_val;
    EXCEPTION
        WHEN NO_DATA_FOUND
	THEN
	    RETURN NULL;
    END family_for_channel;

    FUNCTION available_family_subscriptions(channel_family_id_in IN NUMBER, org_id_in IN NUMBER)
    RETURN NUMBER
    IS
    	cfp channel_family_perm_cursor%ROWTYPE;
    	current_members_val NUMBER;
	max_members_val     NUMBER;
	found               NUMBER;
    BEGIN
	IF NOT channel_family_perm_cursor%ISOPEN
	THEN
	    OPEN channel_family_perm_cursor(channel_family_id_in, org_id_in);
	END IF;

	FETCH channel_family_perm_cursor INTO cfp;
	
	WHILE channel_family_perm_cursor%FOUND
    	LOOP
	    found := 1;
	    
	    current_members_val := cfp.current_members;
	    max_members_val := cfp.max_members;
	    
	    FETCH channel_family_perm_cursor INTO cfp;
	END LOOP;

	IF channel_family_perm_cursor%ISOPEN
	THEN
	    CLOSE channel_family_perm_cursor;
	END IF;

    	-- not found: either the channel fam doesn't have an entry in cfp, or the org doesn't have access to it.
	-- either way, there are no available subscriptions
	
	IF found IS NULL
	THEN
	    RETURN 0;
	END IF;

	-- null max members?  in that case, pass it on; NULL means infinite			
	IF max_members_val IS NULL
	THEN
	    RETURN NULL;
	END IF;

	-- otherwise, return the delta	
	RETURN max_members_val - current_members_val;			
    END available_family_subscriptions;
    
    -- *******************************************************************
    -- FUNCTION: channel_family_current_members
    -- Calculates and returns the actual count of systems consuming
    --   physical channel subscriptions.
    -- Called by: update_family_counts 
    --            rhn_entitlements.repoll_virt_guest_entitlements
    -- *******************************************************************
    function channel_family_current_members(channel_family_id_in IN NUMBER,
                                            org_id_in IN NUMBER)
    return number
    is
        current_members_count number := 0;
    begin
        select	count(sc.server_id)
        into    current_members_count
        from	rhnChannelFamilyMembers cfm,
                rhnServerChannel sc,
                rhnServer s
        where	s.org_id = org_id_in
            and s.id = sc.server_id
            and cfm.channel_family_id = channel_family_id_in
            and cfm.channel_id = sc.channel_id
            and exists ( 
                select 1
                from rhnChannelFamilyServerPhysical cfsp
                where cfsp.CHANNEL_FAMILY_ID = channel_family_id_in
                    and cfsp.server_id = s.id
                );

        return current_members_count;
    end;        

    PROCEDURE update_family_counts(channel_family_id_in IN NUMBER, 
                                   org_id_in IN NUMBER)
    IS
    BEGIN
		update rhnPrivateChannelFamily
		set current_members = (
                channel_family_current_members(channel_family_id_in, org_id_in)
    		)
			where org_id = org_id_in
				and channel_family_id = channel_family_id_in;
    END update_family_counts;
    
    FUNCTION available_chan_subscriptions(channel_id_in IN NUMBER, 
                                          org_id_in IN NUMBER)
    RETURN NUMBER
    IS
	    channel_family_id_val NUMBER;
    BEGIN
    	SELECT channel_family_id INTO channel_family_id_val
	    FROM rhnChannelFamilyMembers
	    WHERE channel_id = channel_id_in;
	 
	    RETURN rhn_channel.available_family_subscriptions(
                           channel_family_id_val, org_id_in);
    END available_chan_subscriptions;

    -- *******************************************************************
    -- PROCEDURE: entitle_customer
    -- Creates a chan fam bucket, or sets max_members for an existing bucket
    -- Called by: rhn_ep.poll_customer_internal
    -- Calls: set_family_maxmembers + update_family_counts if the row
    --        already exists, else it creates it in rhnPrivateChannelFamily.
    -- *******************************************************************
    procedure entitle_customer(customer_id_in in number, 
                               channel_family_id_in in number, 
                               quantity_in in number)
    is
		cursor permissions is
			select	1
			from	rhnPrivateChannelFamily pcf
			where	pcf.org_id = customer_id_in
				and	pcf.channel_family_id = channel_family_id_in; 
    begin
		for perm in permissions loop
			set_family_maxmembers(
				customer_id_in,
				channel_family_id_in,
				quantity_in
			);
			rhn_channel.update_family_counts(
				channel_family_id_in,
				customer_id_in
			);
			return;
		end loop;
        
		insert into rhnPrivateChannelFamily pcf (
				channel_family_id, org_id, max_members, current_members
			) values (
				channel_family_id_in, customer_id_in, quantity_in, 0
			);
    end;

    -- *******************************************************************
    -- PROCEDURE: set_family_maxmembers
    -- Prunes an existing channel family bucket by unsubscribing the
    --   necessary servers and sets max_members.
    -- Called by: rhn_channel.entitle_customer
    -- Calls: unsubscribe_server_from_family
    -- *******************************************************************
    procedure set_family_maxmembers(customer_id_in in number, 
                                    channel_family_id_in in number, 
                                    quantity_in in number)
    is
        cursor servers is
            select  server_id from (
            select	rownum row_number, server_id, modified from (
                select  rcfsp.server_id,
                        rcfsp.modified
                from    rhnChannelFamilyServerPhysical rcfsp
                where   rcfsp.customer_id = customer_id_in
                    and rcfsp.channel_family_id = channel_family_id_in
                order by modified
            )
            where rownum > quantity_in
            );
    begin
	    -- prune subscribed servers
        for server in servers loop
            rhn_channel.unsubscribe_server_from_family(server.server_id, 
                                                       channel_family_id_in);
        end loop;

        update	rhnPrivateChannelFamily pcf
        set	pcf.max_members = quantity_in
        where	pcf.org_id = customer_id_in
            and pcf.channel_family_id = channel_family_id_in;
    end;

    procedure unsubscribe_server_from_family(server_id_in in number, 
                                             channel_family_id_in in number)
    is
    begin
        delete
        from	rhnServerChannel rsc
        where	rsc.server_id = server_id_in
            and channel_id in (
                select	rcfm.channel_id
                from	rhnChannelFamilyMembers rcfm
                where	rcfm.channel_family_id = channel_family_id_in);
    end;

    function get_org_id(channel_id_in in number)
    return number
    is
    	org_id_out number;
    begin
    	select org_id into org_id_out
	    from rhnChannel
	    where id = channel_id_in;
	 
	    return org_id_out;
    end get_org_id;
    
    function get_cfam_org_access(cfam_id_in in number, org_id_in in number)
    return number
    is
    	cursor	families is
			select	1
			from	rhnOrgChannelFamilyPermissions cfp
			where	cfp.org_id = org_id_in;
    begin
		-- the idea: if we get past this query, 
        -- the user has the role, else catch the exception and return 0
		for family in families loop
	    	return 1;
		end loop;
		return 0;
    end;

    function get_org_access(channel_id_in in number, org_id_in in number)
    return number
    is
    	throwaway number;
    begin
    	-- the idea: if we get past this query, 
        -- the org has access to the channel, else catch the exception and return 0
        select distinct 1 into throwaway
          from rhnChannelFamilyMembers CFM,
               rhnOrgChannelFamilyPermissions CFP
         where cfp.org_id = org_id_in
           and CFM.channel_family_id = CFP.channel_family_id
           and CFM.channel_id = channel_id_in
           and (CFP.max_members > 0 or CFP.max_members is null or CFP.org_id = 1);
           
        return 1;
        exception
            when no_data_found
            then
            return 0;
    end;
    
    -- check if a user has a given role, or if such a role is inferrable
    function user_role_check_debug(channel_id_in in number, 
                                   user_id_in in number, 
                                   role_in in varchar2, 
                                   reason_out out varchar2)
    return number
    is
    	org_id number;
    begin
    	org_id := rhn_user.get_org_id(user_id_in);
	
    	if role_in = 'manage' and 
           NVL(rhn_channel.get_org_id(channel_id_in), -1) <> org_id then
	        reason_out := 'channel_not_owned';
	       return 0;
	    end if;
	
    	if role_in = 'subscribe' and 
           rhn_channel.get_org_access(channel_id_in, org_id) = 0 then
	        reason_out := 'channel_not_available';
	        return 0;
	    end if;
	
    	-- channel admins have all roles
    	if rhn_user.check_role_implied(user_id_in, 'channel_admin') = 1 then
            reason_out := 'channel_admin';
            return 1;
	    end if;

	-- the subscribe permission is inferred 
    -- UNLESS the not_globally_subscribable flag is set	
	if role_in = 'subscribe'
	then
	    if rhn_channel.org_channel_setting(channel_id_in, 
                       org_id,
                       'not_globally_subscribable') = 0 then
	    	reason_out := 'globally_subscribable';
		    return 1;
	    end if;
	end if;
	
	-- all other roles (manage right now) are explicitly granted	
	reason_out := 'direct_permission';
	return rhn_channel.direct_user_role_check(channel_id_in, 
                                              user_id_in, role_in);
    end;
    
    -- same as above, but with no OUT param; useful in views, etc
    function user_role_check(channel_id_in in number, user_id_in in number, role_in in varchar2)
    return number
    is
  	throwaway varchar2(256);
    begin
    	return rhn_channel.user_role_check_debug(channel_id_in, user_id_in, role_in, throwaway);
    end;

    -- same as above, but returns 1 if user_id_in is null
    -- This is useful in queries where user_id is not specified
    function loose_user_role_check(channel_id_in in number, user_id_in in number, role_in in varchar2)
    return number
    is
    begin
        if user_id_in is null then
            return 1;
        end if;
        return user_role_check(channel_id_in, user_id_in, role_in);
    end loose_user_role_check;
    
    -- directly checks the table, no inferred permissions
    function direct_user_role_check(channel_id_in in number, user_id_in in number, role_in in varchar2)
    return number
    is
    	throwaway number;
    begin
    	-- the idea: if we get past this query, the user has the role, else catch the exception and return 0
	select 1 into throwaway
	  from rhnChannelPermissionRole CPR,
	       rhnChannelPermission CP
	 where CP.user_id = user_id_in
	   and CP.channel_id = channel_id_in
	   and CPR.label = role_in
	   and CP.role_id = CPR.id;
	   
	return 1;
    exception
    	when no_data_found
	    then
	    return 0;
    end;
    
    -- check if an org has a certain setting
    function org_channel_setting(channel_id_in in number, org_id_in in number, setting_in in varchar2)
    return number
    is
    	throwaway number;
    begin
    	-- the idea: if we get past this query, the org has the setting, else catch the exception and return 0
	select 1 into throwaway
	  from rhnOrgChannelSettingsType OCST,
	       rhnOrgChannelSettings OCS
	 where OCS.org_id = org_id_in
	   and OCS.channel_id = channel_id_in
	   and OCST.label = setting_in
	   and OCS.setting_id = OCST.id;
	   
	return 1;
    exception
    	when no_data_found
	    then
	    return 0;
    end;
    
    FUNCTION channel_priority(channel_id_in IN number) 
    RETURN number
    IS
         channel_name varchar2(64);
         priority number;
         end_of_life_val date;
         org_id_val number;
    BEGIN

        select name, end_of_life, org_id
        into channel_name, end_of_life_val, org_id_val
        from rhnChannel
        where id = channel_id_in;

        if end_of_life_val is not null then
          return -400;
        end if;

        if channel_name like 'Red Hat Enterprise Linux%' or channel_name like 'RHEL%' then
          priority := 1000;
          if channel_name not like '%Beta%' then
            priority := priority + 1000;
          end if;

          priority := priority +
            case
              when channel_name like '%v. 5%' then 600
              when channel_name like '%v. 4%' then 500
              when channel_name like '%v. 3%' then 400
              when channel_name like '%v. 2%' then 300
              when channel_name like '%v. 1%' then 200
              else 0
            end;

          priority := priority +
            case
              when channel_name like 'Red Hat Enterprise Linux (v. 5%' then 60
              when (channel_name like '%AS%' and channel_name not like '%Extras%') then 50
              when (channel_name like '%ES%' and channel_name not like '%Extras%') then 40
              when (channel_name like '%WS%' and channel_name not like '%Extras%') then 30
              when (channel_name like '%Desktop%' and channel_name not like '%Extras%') then 20
              when channel_name like '%Extras%' then 10
              else 0
            end; 

          priority := priority +
            case
              when channel_name like '%)' then 5
              else 0
            end;

          priority := priority +
            case
              when channel_name like '%32-bit x86%' then 4
              when channel_name like '%64-bit Intel Itanium%' then 3
              when channel_name like '%64-bit AMD64/Intel EM64T%' then 2
              else 0
            end;
        elsif channel_name like 'Red Hat Desktop%' then
            priority := 900;

            if channel_name not like '%Beta%' then
               priority := priority + 50;
            end if;
 
          priority := priority +
            case
              when channel_name like '%v. 4%' then 40
              when channel_name like '%v. 3%' then 30
              when channel_name like '%v. 2%' then 20
              when channel_name like '%v. 1%' then 10
              else 0
            end;
            
          priority := priority +
            case
              when channel_name like '%32-bit x86%' then 4
              when channel_name like '%64-bit Intel Itanium%' then 3
              when channel_name like '%64-bit AMD64/Intel EM64T%' then 2
              else 0
            end;
         
        elsif org_id_val is not null then
          priority := 600;
        else
          priority := 500;
        end if;
      
      return -priority;

    end channel_priority;

    -- right now this only does the accounting changes; the cascade
    -- actually does the rhnServerChannel delete.
    procedure delete_server_channels(server_id_in in number)
    is
    begin
	update	rhnPrivateChannelFamily
	set	current_members = current_members -1
	where	org_id in (
			select	org_id
			from	rhnServer
			where	id = server_id_in
		)
		and channel_family_id in (
			select	rcfm.channel_family_id
			from	rhnChannelFamilyMembers rcfm,
				rhnServerChannel rsc
			where	rsc.server_id = server_id_in
				and rsc.channel_id = rcfm.channel_id
                and not exists (
                    select 1
                    from
                        rhnChannelFamilyVirtSubLevel cfvsl,
                        rhnSGTypeVirtSubLevel sgtvsl,
                        rhnServerEntitlementView sev,
                        rhnVirtualInstance vi
                    where
                        -- system is a virtual instance
                        vi.virtual_system_id = server_id_in
                        and vi.host_system_id = sev.server_id
                        -- system's host has a virt ent
                        and sev.label in ('virtualization_host',
                                          'virtualization_host_platform')
                        and sev.server_group_type_id = 
                            sgtvsl.server_group_type_id
                        -- the host's virt ent grants a cf virt sub level
                        and sgtvsl.virt_sub_level_id = cfvsl.virt_sub_level_id
                        -- the cf is in that virt sub level
                        and cfvsl.channel_family_id = rcfm.channel_family_id
                    )
		);
    end;

	-- this could certainly be optimized to do updates if needs be
	procedure refresh_newest_package(channel_id_in in number, caller_in in varchar2 := '(unknown)')
	is
	begin
		delete from rhnChannelNewestPackage where channel_id = channel_id_in;
		insert into rhnChannelNewestPackage
			( channel_id, name_id, evr_id, package_id, package_arch_id ) 
			(	select	channel_id,
						name_id, evr_id,
						package_id, package_arch_id
				from	rhnChannelNewestPackageView
				where	channel_id = channel_id_in
			);
                insert into rhnChannelNewestPackageAudit (channel_id, caller)
                    values (channel_id_in, caller_in);
                update rhnChannel 
                    set last_modified = greatest(sysdate, last_modified + 1/86400)
                    where id = channel_id_in; 
	end;

   procedure update_channel ( channel_id_in in number, invalidate_ss in number := 0, 
                              date_to_use in date := sysdate )
   is

   channel_last_modified date;
   last_modified_value date;

   cursor snapshots is
   select  snapshot_id id
   from    rhnSnapshotChannel
   where   channel_id = channel_id_in;

   begin

      select last_modified
      into channel_last_modified
      from rhnChannel
      where id = channel_id_in;
  
      last_modified_value := date_to_use;

      if last_modified_value <= channel_last_modified then
          last_modified_value := last_modified_value + 1/86400;
      end if;

      update rhnChannel set last_modified = last_modified_value
      where id = channel_id_in;

      if invalidate_ss = 1 then 
        for snapshot in snapshots loop
            update rhnSnapshot
            set invalid = lookup_snapshot_invalid_reason('channel_modified')
            where id = snapshot.id;
        end loop;
      end if;

   end update_channel;

   procedure update_channels_by_package ( package_id_in in number, date_to_use in date := sysdate )
   is

   cursor channels is
   select channel_id
   from rhnChannelPackage
   where package_id = package_id_in
   order by channel_id;

   begin
      for channel in channels loop
         -- we want to invalidate the snapshot assocated with the channel when we
         -- do this b/c we know we've added or removed or packages
         rhn_channel.update_channel ( channel.channel_id, 1, date_to_use );
      end loop;
   end update_channels_by_package;

   
   procedure update_channels_by_errata ( errata_id_in number, date_to_use in date := sysdate )
   is

   cursor channels is
   select channel_id
   from rhnChannelErrata
   where errata_id = errata_id_in
   order by channel_id;

   begin
      for channel in channels loop
         -- we won't invalidate snapshots, b/c just changing the errata associated with
         -- a channel shouldn't invalidate snapshots
         rhn_channel.update_channel ( channel.channel_id, 0, date_to_use );
      end loop;
   end update_channels_by_errata;

END rhn_channel;
/
SHOW ERRORS

-- $Log$
-- Revision 1.75  2005/03/04 00:04:19  jslagle
-- bz #147617
-- Made Red Hat Desktop sort a little better.
--
-- Revision 1.74  2005/02/22 03:24:47  jslagle
-- bz #147617
-- Improve channel_priority function to order channels better.
--
-- Revision 1.73  2004/08/16 20:39:30  pjones
-- bugzilla: 129889 -- make bulk_server_basechange_from() actually work.
--
-- Revision 1.72  2004/04/14 00:09:24  pjones
-- bugzilla: 120761 -- split rhnChannelPermissions into two tables, eliminating
-- a frequent full table scan
--
-- Revision 1.71  2004/04/13 16:28:36  bretm
-- bugzilla:  119871
--
-- keep track of rhnServer.channels_changed through the pl/sql fns
--
-- Revision 1.70  2004/03/26 18:11:32  rbb
-- Bugzilla:  114057
--
-- Add a script to determine channel priority.
--
-- Revision 1.69  2004/02/17 20:16:52  pjones
-- bugzilla: none -- add cvs tags into the package as long as we're touching
-- it anyway
--
-- Revision 1.68  2004/02/17 20:05:38  pjones
-- bugzilla: 115782 -- make bulk_server_basechange_from() filter out servers
-- with arches incompatible with the target channel
--
-- Revision 1.67  2004/02/06 02:36:10  misa
-- Changed normalize_server_arch to allow for solaris arches
--
-- Revision 1.66  2003/11/13 16:58:34  cturner
-- make use of new rhn_user.check_role_implied call; pragmas broke, removed them for now since I have no idea how to fix them
--
-- Revision 1.65  2003/10/23 20:26:24  bretm
-- bugzilla:  none
--
-- note the channel label when we unsubscribe, too
--
-- Revision 1.64  2003/10/15 14:47:17  bretm
-- bugzilla:  none
--
-- add the channel label to the server history summary line when we log a channel change
--
-- Revision 1.63  2003/09/24 19:25:56  pjones
-- this wasn't the right fix, put it back
--
-- Revision 1.62  2003/09/24 17:42:19  pjones
-- bugzilla: none
--
-- limit our server base channel guess to channels with available permissions
--
-- Revision 1.61  2003/09/22 21:00:40  cturner
-- add method for easy acl check
--
-- Revision 1.60  2003/09/17 22:14:11  misa
-- bugzilla: 103639  Changes to allow me to move the base channel guess into plsql
--
-- Revision 1.59  2003/08/21 13:41:17  cturner
-- bugzilla: 99187.  properly test for satellite and proxy in bulk_guess_server_base; reorg code for better reuse
--
-- Revision 1.58  2003/07/24 16:46:22  cturner
-- bugzilla: 100723, the perm check was returning duplicates, so now it just calls the function it should have called anyway
--
-- Revision 1.57  2003/07/24 16:44:16  misa
-- bugzilla: none  A function more usable on the rhnapp side
--
-- Revision 1.56  2003/07/23 22:36:51  cturner
-- argh, max returns null even when now rows; use distinct.  how revolting
--
-- Revision 1.55  2003/07/23 22:01:31  cturner
-- oops, this one can return multiple rows; eliminate that in a lazy way
--
-- Revision 1.54  2003/07/23 21:59:19  cturner
-- rework how rhnUserChannel works; move to plsql for speed and maintenance
--
-- Revision 1.53  2003/07/21 17:49:12  pjones
-- bugzilla: none
--
-- add optional user for subscribe_server
--
-- Revision 1.52  2003/07/14 22:19:29  misa
-- bugzilla: none  Updating guess_base_channel to work more like the rhnapp server code
--
-- Revision 1.51  2003/06/26 22:09:04  pjones
-- bugzilla: none
--
-- log subscribe and unsubscribe
--
-- Revision 1.50  2003/06/05 19:31:15  pjones
-- bugzilla: 88278 -- make the cursor name smaller
--
-- Revision 1.49  2003/06/05 19:18:21  pjones
-- bugzilla: 88278
--
-- unsubscribe_server() opens the package-level cursor when it invokes itself,
-- so we're using a local copy instead.
--
-- Revision 1.48  2003/06/04 16:41:39  pjones
-- bugzilla: none
--
-- make bulk_guess_server_base() silently ignore unguessables
--
-- Revision 1.47  2003/06/04 16:27:03  pjones
-- bugzilla: 88822
--
-- eliminate the last outliers that remove things from channels without using
-- unsubscribe_server, I think.
--
-- Revision 1.46  2003/06/03 20:49:37  pjones
-- bugzilla: 88822
-- unsubscribing from rhn-satellite now clears rhnSatelliteChannelFamily
-- for the server in question
--
-- Revision 1.45  2003/06/02 20:41:45  pjones
-- bugzilla: none - fix rhnProxyInfo/rhnSatelliteInfo channel unsubscribe
-- problem.  Basicly, if you're out of the channel for any reason, you're
-- also out of rhnProxyInfo/rhnProxyInfo
--
-- Revision 1.44  2003/03/24 15:26:28  pjones
-- bugzilla: 85812
--
-- bulk_server_base_change silently ignores servers that are satellites
-- or proxies, as requested.
--
-- Revision 1.43  2003/02/26 20:28:17  pjones
-- rhn_channel.update_family_counts() in rhn_channel.entitle_customer()
-- the old codepath is:
--
-- ep ->
-- rhn_ep.entitlement_run_me() ->
-- rhn_ep.poll_customer() ->
-- rhn_channel.entitle_customer()
--
-- which doesn't change current_members, even though it may remove servers
-- from the family.
--
-- There's another bug here:  currently, we don't try to order forced
-- unsubscribes in any way; we just use
-- rhn_channel.unsubscribe_server_from_family .  If there are any child
-- channel subscriptions, this will leave them subscribed.  We really need
-- to iterate across the channels again, and subscribe any channel for which
-- there are no parent channel subscriptions.
--
-- Ugh.
--
-- Revision 1.42  2003/01/28 00:19:45  pjones
-- fix clear_subscriptions; AFAICT, this is only hit on the
-- bulk_server_base_change / bulk_server_base_guess codepaths, which puts
-- it infrequent enough that it could be our "bad count" culprit.
--
-- Revision 1.41  2003/01/14 19:51:45  pjones
-- make setting current_members on rhnChannelFamilyPermissions work when
-- a server is in more than one channel in a single family.
070701000003CA000081B400000000000000000000000167AE111400000539000000000000000000000000000000000000006E00000000susemanager-schema/upgrade/rhn-satellite-schema-5.1-to-spacewalk-schema-0.2/061-rhn_package-deterministic.sql --
-- Copyright (c) 2008 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
-- $Id$
--

CREATE OR REPLACE
PACKAGE rhn_package
IS
    CURSOR channel_occupancy_cursor(package_id_in IN NUMBER) IS
    SELECT C.id channel_id, C.name channel_name
      FROM rhnChannel C,
      	   rhnChannelPackage CP
     WHERE C.id = CP.channel_id
       AND CP.package_id = package_id_in
     ORDER BY C.name DESC;

    FUNCTION canonical_name(name_in IN VARCHAR2, evr_in IN EVR_T, 
    	                    arch_in IN VARCHAR2 := NULL)
      RETURN VARCHAR2
      DETERMINISTIC;

    FUNCTION channel_occupancy_string(package_id_in IN NUMBER, separator_in VARCHAR2 := ', ') 
      RETURN VARCHAR2;
      
END rhn_package;
/
SHOW ERRORS

-- $Log$
-- Revision 1.3  2002/05/10 22:08:23  pjones
-- id/log
--
   070701000003CB000081B400000000000000000000000167AE111400000663000000000000000000000000000000000000006E00000000susemanager-schema/upgrade/rhn-satellite-schema-5.1-to-spacewalk-schema-0.2/062-rpm.pks-non-deterministic.sql --
-- Copyright (c) 2008 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
-- $Id$
--
-- PL/SQL version of rpmvercompare
-- 

CREATE OR REPLACE PACKAGE rpm AS
    FUNCTION vercmp(
        e1 VARCHAR2, v1 VARCHAR2, r1 VARCHAR2, 
        e2 VARCHAR2, v2 VARCHAR2, r2 VARCHAR2)
    RETURN NUMBER
        DETERMINISTIC
        PARALLEL_ENABLE;
    PRAGMA RESTRICT_REFERENCES(vercmp, WNDS, RNDS);

    FUNCTION vercmpCounter
    return NUMBER
        PARALLEL_ENABLE;
    PRAGMA RESTRICT_REFERENCES(vercmpCounter, WNDS, RNDS);

    FUNCTION vercmpResetCounter
    return NUMBER
        PARALLEL_ENABLE;
    PRAGMA RESTRICT_REFERENCES(vercmpResetCounter, WNDS, RNDS);
    
END rpm;
/
SHOW ERRORS;

-- $Log$
-- Revision 1.4  2002/05/10 22:08:23  pjones
-- id/log
--
-- Revision 1.3  2002/04/02 23:19:44  misa
-- Added the comparison counter and assorted functions for handling it.
--
-- Revision 1.2  2002/03/21 20:21:24  misa
-- For some reason this doesn't work. I'll further investigate it.
--
-- Revision 1.1  2002/03/21 20:14:10  misa
-- The packaged version of the PL/SQL rpmvercmp
--
 070701000003CC000081B400000000000000000000000167AE111400002129000000000000000000000000000000000000006A00000000susemanager-schema/upgrade/rhn-satellite-schema-5.1-to-spacewalk-schema-0.2/063-rpm.pkb-deterministic.sql --
-- Copyright (c) 2008 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
-- $Id$
--
-- PL/SQL version of rpmvercompare

CREATE OR REPLACE PACKAGE BODY rpm AS
    vercmp_counter NUMBER := 0;

    FUNCTION isdigit(ch CHAR)
    RETURN BOOLEAN
    deterministic
    IS
    BEGIN
        if ascii(ch) between ascii('0') and ascii('9')
        then
            return TRUE;
        end if;
        return FALSE;
    END isdigit;

    
    FUNCTION isalpha(ch CHAR)
    RETURN BOOLEAN
    deterministic
    IS
    BEGIN
        if ascii(ch) between ascii('a') and ascii('z') or 
            ascii(ch) between ascii('A') and ascii('Z')
        then
            return TRUE;
        end if;
        return FALSE;
    END isalpha;


    FUNCTION isalphanum(ch CHAR)
    RETURN BOOLEAN
    deterministic
    IS
    BEGIN
        if ascii(ch) between ascii('a') and ascii('z') or 
            ascii(ch) between ascii('A') and ascii('Z') or
            ascii(ch) between ascii('0') and ascii('9')
        then
            return TRUE;
        end if;
        return FALSE;
    END isalphanum;


    FUNCTION rpmstrcmp (string1 IN VARCHAR2, string2 IN VARCHAR2)
    RETURN NUMBER
    deterministic
    IS
        digits CHAR(10) := '0123456789';
        lc_alpha CHAR(27) := 'abcdefghijklmnopqrstuvwxyz';
        uc_alpha CHAR(27) := 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
        alpha CHAR(54) := lc_alpha || uc_alpha;
        str1 VARCHAR2(32767) := string1;
        str2 VARCHAR2(32767) := string2;
        one VARCHAR2(32767);
        two VARCHAR2(32767);
        isnum BOOLEAN;
    BEGIN
        if str1 is NULL or str2 is NULL
        then
            raise VALUE_ERROR;
        end if;
        -- easy comparison to see if versions are identical
        if str1 = str2
        then
            return 0;
        end if;
        -- loop through each version segment of str1 and str2 and compare them
        one := str1;
        two := str2;

        <<segment_loop>>
        while one is not null and two is not null
        loop
            declare
                segm1 VARCHAR2(32767);
                segm2 VARCHAR2(32767);
            begin
                --DBMS_OUTPUT.PUT_LINE('Params: ' || one || ',' || two);
                -- Throw out all non-alphanum characters
                while one is not null and not isalphanum(one)
                loop
                    one := substr(one, 2);
                end loop;
                while two is not null and not isalphanum(two)
                loop
                    two := substr(two, 2);
                end loop;
                --DBMS_OUTPUT.PUT_LINE('new params: ' || one || ',' || two);

                str1 := one;
                str2 := two;

                /* grab first completely alpha or completely numeric segment */
                /* leave one and two pointing to the start of the alpha or numeric */
                /* segment and walk str1 and str2 to end of segment */
                
                if str1 is not null and isdigit(str1)
                then
                    str1 := ltrim(str1, digits);
                    str2 := ltrim(str2, digits);
                    isnum := true;
                else
                    str1 := ltrim(str1, alpha);
                    str2 := ltrim(str2, alpha);
                    isnum := false;
                end if;

                --DBMS_OUTPUT.PUT_LINE('Len: ' || length(str1) || ',' || length(str2));
                -- Oracle trats the length of an empty string as null
                if str1 is not null
                then segm1 := substr(one, 1, length(one) - length(str1));
                else segm1 := one;
                end if;
                    
                if str2 is not null
                then segm2 := substr(two, 1, length(two) - length(str2));
                else segm2 := two;
                end if;

                --DBMS_OUTPUT.PUT_LINE('Segments: ' || segm1 || ',' || segm2);
                --DBMS_OUTPUT.PUT_LINE('Rest: ' || str1 || ',' || str2);
                /* take care of the case where the two version segments are */
                /* different types: one numeric and one alpha */
                if segm1 is null then return -1; end if; /* arbitrary */
                if segm2 is null then
					if isnum then
						return 1;
					else
						return -1;
					end if;
				end if;

                if isnum
                then
                    /* this used to be done by converting the digit segments */
                    /* to ints using atoi() - it's changed because long */
                    /* digit segments can overflow an int - this should fix that. */

                    /* throw away any leading zeros - it's a number, right? */
                    segm1 := ltrim(segm1, '0');
                    segm2 := ltrim(segm2, '0');

                    /* whichever number has more digits wins */
                    -- length of empty string is null
                    if segm1 is null and segm2 is not null
                    then
                        return -1;
                    end if;
                    if segm1 is not null and segm2 is null
                    then
                        return 1;
                    end if;
                    if length(segm1) > length(segm2) then return 1; end if;
                    if length(segm2) > length(segm1) then return -1; end if;
                end if;
                
                /* strcmp will return which one is greater - even if the two */
                /* segments are alpha or if they are numeric.  don't return  */
                /* if they are equal because there might be more segments to */
                /* compare */
                
                if segm1 < segm2 then return -1; end if;
                if segm1 > segm2 then return 1; end if;

                one := str1;
                two := str2;
            end;
        end loop segment_loop;
        /* this catches the case where all numeric and alpha segments have */
        /* compared identically but the segment sepparating characters were */
        /* different */
        if one is null and two is null then return 0; end if;

        /* whichever version still has characters left over wins */
        if one is null then return -1; end if;
        return 1;
    END rpmstrcmp;


    FUNCTION vercmp(
        e1 VARCHAR2, v1 VARCHAR2, r1 VARCHAR2, 
        e2 VARCHAR2, v2 VARCHAR2, r2 VARCHAR2)
    RETURN NUMBER
    IS
        rc NUMBER;
    BEGIN
        DECLARE
          ep1 NUMBER;
          ep2 NUMBER;
          BEGIN
            vercmp_counter := vercmp_counter + 1;
            if e1 is null then
              ep1 := 0;
            else
              ep1 := TO_NUMBER(e1);
            end if;
            if e2 is null then
              ep2 := 0;
            else
              ep2 := TO_NUMBER(e2);
            end if;
            -- Epochs are non-null; compare them
            if ep1 < ep2 then return -1; end if;
            if ep1 > ep2 then return 1; end if;
            rc := rpmstrcmp(v1, v2);
            if rc != 0 then return rc; end if;
           return rpmstrcmp(r1, r2);
         END;

    END vercmp;

    FUNCTION vercmpCounter
    RETURN NUMBER
    IS
    BEGIN
        return vercmp_counter;
    END vercmpCounter;

    FUNCTION vercmpResetCounter
    RETURN NUMBER
    IS
        result NUMBER;
    BEGIN
        result := vercmp_counter;
        vercmp_counter := 0;
        return result;
    END vercmpResetCounter;
END rpm;
/
SHOW ERRORS;

-- $Log$
-- Revision 1.4  2003/09/02 18:03:50  pjones
-- bugzilla: none
--
-- our rpmvercmp doesn't match the "fixed" rpm way.  Does now.
--
-- Revision 1.3  2002/05/10 22:08:23  pjones
-- id/log
--
-- Revision 1.2  2002/04/02 23:19:44  misa
-- Added the comparison counter and assorted functions for handling it.
--
-- Revision 1.1  2002/03/21 20:14:10  misa
-- The packaged version of the PL/SQL rpmvercmp
--
   070701000003CD000081B400000000000000000000000167AE111400000480000000000000000000000000000000000000007400000000susemanager-schema/upgrade/rhn-satellite-schema-5.1-to-spacewalk-schema-0.2/064-channel_name_join-deterministic.sql   --
-- Copyright (c) 2008 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
-- $Id$
--

create or replace function
channel_name_join(sep_in in varchar2, ch_in in channel_name_t)
return varchar2
deterministic
is
	ret	varchar2(4000);
	i	binary_integer;
begin
	ret := '';
	i := ch_in.first;

	if i is null
	then
		return ret;
	end if;

	ret := ch_in(i);
	i := ch_in.next(i);

	while i is not null
	loop
		ret := ret || sep_in || ch_in(i);
		i := ch_in.next(i);
	end loop;

	return ret;
end;
/

-- $Log$
-- Revision 1.3  2002/05/13 22:53:38  pjones
-- cvs id/log
-- some (note enough) readability fixes
--
070701000003CE000081B400000000000000000000000167AE111400000489000000000000000000000000000000000000006A00000000susemanager-schema/upgrade/rhn-satellite-schema-5.1-to-spacewalk-schema-0.2/065-id_join-deterministic.sql --
-- Copyright (c) 2008 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
-- $Id$
--

CREATE OR REPLACE FUNCTION
ID_JOIN(sep_in IN VARCHAR2, ugi_in IN user_group_id_t)
RETURN VARCHAR2
deterministic
IS
	ret	VARCHAR2(4000);
	i	BINARY_INTEGER;
BEGIN
	ret := '';
	i := ugi_in.FIRST;

	IF i IS NULL
	THEN
		RETURN ret;
	END IF;

	ret := ugi_in(i);
	i := ugi_in.NEXT(i);

	WHILE i IS NOT NULL
	LOOP
		ret := ret || sep_in || ugi_in(i);
		i := ugi_in.NEXT(i);
	END LOOP;

	RETURN ret;
END;
/
SHOW ERRORS

-- $Log$
-- Revision 1.2  2002/05/13 22:53:38  pjones
-- cvs id/log
-- some (note enough) readability fixes
--
   070701000003CF000081B400000000000000000000000167AE11140000048F000000000000000000000000000000000000006D00000000susemanager-schema/upgrade/rhn-satellite-schema-5.1-to-spacewalk-schema-0.2/066-label_join-deterministic.sql  --
-- Copyright (c) 2008 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
-- $Id$
--

CREATE OR REPLACE FUNCTION
LABEL_JOIN(sep_in IN VARCHAR2, ugi_in IN user_group_label_t)
RETURN VARCHAR2
deterministic
IS
	ret	VARCHAR2(4000);
	i	BINARY_INTEGER;
BEGIN
	ret := '';
	i := ugi_in.FIRST;

	IF i IS NULL
	THEN
		RETURN ret;
	END IF;

	ret := ugi_in(i);
	i := ugi_in.NEXT(i);

	WHILE i IS NOT NULL
	LOOP
		ret := ret || sep_in || ugi_in(i);
		i := ugi_in.NEXT(i);
	END LOOP;

	RETURN ret;
END;
/
SHOW ERRORS

-- $Log$
-- Revision 1.2  2002/05/13 22:53:38  pjones
-- cvs id/log
-- some (note enough) readability fixes
--
 070701000003D0000081B400000000000000000000000167AE1114000004F6000000000000000000000000000000000000007A00000000susemanager-schema/upgrade/rhn-satellite-schema-5.1-to-spacewalk-schema-0.2/067-lookup_channel_arch-non-deterministic.sql --
-- Copyright (c) 2008 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
-- $Id$
--

CREATE OR REPLACE FUNCTION
LOOKUP_CHANNEL_ARCH(label_in IN VARCHAR2)
RETURN NUMBER
IS
	channel_arch_id		NUMBER;
BEGIN
	SELECT id
          INTO channel_arch_id
          FROM rhnChannelArch
         WHERE label = label_in;

	RETURN channel_arch_id;
EXCEPTION
        WHEN NO_DATA_FOUND THEN
            rhn_exception.raise_exception('channel_arch_not_found');
END;
/
SHOW ERRORS

-- $Log$
-- Revision 1.2  2004/02/20 18:08:51  pjones
-- bugzilla: none -- make lookup_*_arch.sql not autonomous since they never
-- insert
-- add changes files for nonlinux systems
--
-- Revision 1.1  2002/11/13 23:16:18  pjones
-- lookup_*_arch()
--
  070701000003D1000081B400000000000000000000000167AE11140000051A000000000000000000000000000000000000007F00000000susemanager-schema/upgrade/rhn-satellite-schema-5.1-to-spacewalk-schema-0.2/068-lookup_client_capability-non-deterministic.sql    --
-- Copyright (c) 2008 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
-- $Id$
--

CREATE OR REPLACE FUNCTION
LOOKUP_CLIENT_CAPABILITY(name_in IN VARCHAR2)
RETURN NUMBER
IS
	PRAGMA AUTONOMOUS_TRANSACTION;
	cap_name_id		NUMBER;
BEGIN
	SELECT id
          INTO cap_name_id
          FROM rhnClientCapabilityName
         WHERE name = name_in;

	RETURN cap_name_id;
EXCEPTION
        WHEN NO_DATA_FOUND THEN
            INSERT INTO rhnClientCapabilityName (id, name) 
                VALUES (rhn_client_capname_id_seq.nextval, name_in)
                RETURNING id INTO cap_name_id;
            COMMIT;
	RETURN cap_name_id;
END;
/
SHOW ERRORS

-- $Log$
-- Revision 1.1  2003/07/21 22:30:04  misa
-- bugzilla: none  Lookup function for capabilities
--
--
  070701000003D2000081B400000000000000000000000167AE1114000004EF000000000000000000000000000000000000007D00000000susemanager-schema/upgrade/rhn-satellite-schema-5.1-to-spacewalk-schema-0.2/069-lookup_config_filename-non-deterministic.sql  --
-- Copyright (c) 2008 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
-- $Id$
--

CREATE OR REPLACE FUNCTION
LOOKUP_CONFIG_FILENAME(name_in IN VARCHAR2)
RETURN NUMBER
IS
	PRAGMA AUTONOMOUS_TRANSACTION;
	name_id		NUMBER;
BEGIN
	SELECT id
          INTO name_id
          FROM rhnConfigFileName
         WHERE path = name_in;

	RETURN name_id;
EXCEPTION
        WHEN NO_DATA_FOUND THEN
            INSERT INTO rhnConfigFileName (id, path) 
                VALUES (rhn_cfname_id_seq.nextval, name_in)
                RETURNING id INTO name_id;
            COMMIT;
	RETURN name_id;
END;
/
SHOW ERRORS

-- $Log$
-- Revision 1.1  2003/07/31 16:55:34  cturner
-- lookup helper function and blob for configfiles
--
 070701000003D3000081B400000000000000000000000167AE11140000055A000000000000000000000000000000000000007100000000susemanager-schema/upgrade/rhn-satellite-schema-5.1-to-spacewalk-schema-0.2/070-lookup_cve-non-deterministic.sql  --
-- Copyright (c) 2008 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
-- $Id$
--

CREATE OR REPLACE FUNCTION
LOOKUP_CVE(name_in IN VARCHAR2)
RETURN NUMBER
IS
	PRAGMA AUTONOMOUS_TRANSACTION;
	name_id		NUMBER;
BEGIN
	SELECT id
          INTO name_id
          FROM rhnCve
         WHERE name = name_in;

	RETURN name_id;
EXCEPTION
        WHEN NO_DATA_FOUND THEN
            INSERT INTO rhnCve (id, name) 
                VALUES (rhn_cve_id_seq.nextval, name_in)
                RETURNING id INTO name_id;
            COMMIT;
	RETURN name_id;
END LOOKUP_CVE;
/
SHOW ERRORS

-- $Log$
-- Revision 1.2  2004/07/07 21:48:25  pjones
-- bugzilla: 123370 -- "end lookup_cve", to be consistent with the dbchange way
--
-- Revision 1.1  2004/07/07 17:27:36  bretm
-- bugzilla:  123370
--
-- lookup_cve utility function
--
--
  070701000003D4000081B400000000000000000000000167AE111400000588000000000000000000000000000000000000007100000000susemanager-schema/upgrade/rhn-satellite-schema-5.1-to-spacewalk-schema-0.2/071-lookup_evr-non-deterministic.sql  --
-- Copyright (c) 2008 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
-- $Id$
--

CREATE OR REPLACE FUNCTION
LOOKUP_EVR(e_in IN VARCHAR2, v_in IN VARCHAR2, r_in IN VARCHAR2)
RETURN NUMBER
IS
	PRAGMA AUTONOMOUS_TRANSACTION;
	evr_id		NUMBER;
BEGIN
	SELECT id INTO evr_id
          FROM rhnPackageEvr 
         WHERE ((epoch IS NULL and e_in IS NULL) OR (epoch = e_in)) 
           AND version = v_in AND release = r_in;
	  
	RETURN evr_id;
EXCEPTION
        WHEN NO_DATA_FOUND THEN
            INSERT INTO rhnPackageEvr (id, epoch, version, release, evr) 
            VALUES (rhn_pkg_evr_seq.nextval, e_in, v_in, r_in, 
                EVR_T(e_in, v_in, r_in))
            RETURNING id INTO evr_id;
        COMMIT;
	RETURN evr_id;
END;
/
SHOW ERRORS

-- $Log$
-- Revision 1.3  2002/05/13 22:53:38  pjones
-- cvs id/log
-- some (note enough) readability fixes
--
070701000003D5000081B400000000000000000000000167AE111400000531000000000000000000000000000000000000007A00000000susemanager-schema/upgrade/rhn-satellite-schema-5.1-to-spacewalk-schema-0.2/072-lookup_package_arch-non-deterministic.sql --
-- Copyright (c) 2008 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
-- $Id$
--

CREATE OR REPLACE FUNCTION
LOOKUP_PACKAGE_ARCH(label_in IN VARCHAR2)
RETURN NUMBER
IS
	package_arch_id		NUMBER;
BEGIN
   if label_in is null then
      return null;
   end if;

	SELECT id
          INTO package_arch_id
          FROM rhnPackageArch
         WHERE label = label_in;

	RETURN package_arch_id;
EXCEPTION
        WHEN NO_DATA_FOUND THEN
            rhn_exception.raise_exception('package_arch_not_found');
END;
/
SHOW ERRORS

-- $Log$
-- Revision 1.2  2004/02/20 18:08:51  pjones
-- bugzilla: none -- make lookup_*_arch.sql not autonomous since they never
-- insert
-- add changes files for nonlinux systems
--
-- Revision 1.1  2002/11/13 23:16:18  pjones
-- lookup_*_arch()
--
   070701000003D6000081B400000000000000000000000167AE1114000005E9000000000000000000000000000000000000008000000000susemanager-schema/upgrade/rhn-satellite-schema-5.1-to-spacewalk-schema-0.2/073-lookup_package_capability-non-deterministic.sql   --
-- Copyright (c) 2008 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
-- $Id$
--

CREATE OR REPLACE FUNCTION
LOOKUP_PACKAGE_CAPABILITY(name_in IN VARCHAR2, 
    version_in IN VARCHAR2 DEFAULT NULL)
RETURN NUMBER
IS
	PRAGMA AUTONOMOUS_TRANSACTION;
	name_id		NUMBER;
BEGIN
	IF version_in IS NULL THEN
		SELECT id
		  INTO name_id
		  FROM rhnPackageCapability
		 WHERE name = name_in
		   AND version IS NULL;
	ELSE
		SELECT id
		  INTO name_id
		  FROM rhnPackageCapability
		 WHERE name = name_in
		   AND version = version_in;
	END IF;
	RETURN name_id;
EXCEPTION
        WHEN NO_DATA_FOUND THEN
            INSERT INTO rhnPackageCapability (id, name, version) 
                VALUES (rhn_pkg_capability_id_seq.nextval, name_in, version_in)
                RETURNING id INTO name_id;
            COMMIT;
	RETURN name_id;
END;
/
SHOW ERRORS

-- $Log$
-- Revision 1.1  2003/03/03 16:46:51  misa
-- bugzilla: 83674  Reworked the schema for package removal
--
   070701000003D7000081B400000000000000000000000167AE1114000004B4000000000000000000000000000000000000007B00000000susemanager-schema/upgrade/rhn-satellite-schema-5.1-to-spacewalk-schema-0.2/074-lookup_package_delta-non-deterministic.sql    --
-- Copyright (c) 2008 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
-- $Id$
--

CREATE OR REPLACE FUNCTION
LOOKUP_PACKAGE_DELTA(n_in IN VARCHAR2)
RETURN NUMBER
IS
	PRAGMA AUTONOMOUS_TRANSACTION;
	name_id         NUMBER;
BEGIN
	SELECT id INTO name_id
	  FROM rhnPackageDelta
	 WHERE label = n_in;
	  
	RETURN name_id;
EXCEPTION
	WHEN NO_DATA_FOUND THEN
	    INSERT INTO rhnPackageDelta (id, label)
	    VALUES (rhn_packagedelta_id_seq.nextval, n_in)
	    RETURNING id INTO name_id;
	COMMIT;
	RETURN name_id;
END;
/
SHOW ERRORS

-- $Log$
-- Revision 1.1  2003/06/30 22:14:16  misa
-- bugzilla: none  Added a lookup function for package delta
--
--
070701000003D8000081B400000000000000000000000167AE111400000637000000000000000000000000000000000000007A00000000susemanager-schema/upgrade/rhn-satellite-schema-5.1-to-spacewalk-schema-0.2/075-lookup_package_name-non-deterministic.sql --
-- Copyright (c) 2008 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
-- $Id$
--

CREATE OR REPLACE FUNCTION
LOOKUP_PACKAGE_NAME(name_in IN VARCHAR2, ignore_null in number := 0)
RETURN NUMBER
IS
	PRAGMA AUTONOMOUS_TRANSACTION;
	name_id		NUMBER;
BEGIN
	if ignore_null = 1 and name_in is null then
		return null;
	end if;

	SELECT id
          INTO name_id
          FROM rhnPackageName 
         WHERE name = name_in;

	RETURN name_id;
EXCEPTION
        WHEN NO_DATA_FOUND THEN
            INSERT INTO rhnPackageName (id, name) 
                VALUES (rhn_pkg_name_seq.nextval, name_in)
                RETURNING id INTO name_id;
            COMMIT;
	RETURN name_id;
END;
/
SHOW ERRORS

-- $Log$
-- Revision 1.5  2003/02/28 19:58:35  pjones
-- api change for lookup_package_name
--
-- Revision 1.4  2003/02/28 19:27:32  pjones
-- make lookup_package_name return early null with null input
-- lookup_hw* in lookup_functions target
--
-- Revision 1.3  2002/05/13 22:53:38  pjones
-- cvs id/log
-- some (note enough) readability fixes
--
 070701000003D9000081B400000000000000000000000167AE1114000004F0000000000000000000000000000000000000007900000000susemanager-schema/upgrade/rhn-satellite-schema-5.1-to-spacewalk-schema-0.2/076-lookup_server_arch-non-deterministic.sql  --
-- Copyright (c) 2008 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
-- $Id$
--

CREATE OR REPLACE FUNCTION
LOOKUP_SERVER_ARCH(label_in IN VARCHAR2)
RETURN NUMBER
IS
	server_arch_id		NUMBER;
BEGIN
	SELECT id
          INTO server_arch_id
          FROM rhnServerArch
         WHERE label = label_in;

	RETURN server_arch_id;
EXCEPTION
        WHEN NO_DATA_FOUND THEN
            rhn_exception.raise_exception('server_arch_not_found');
END;
/
SHOW ERRORS

-- $Log$
-- Revision 1.2  2004/02/20 18:08:51  pjones
-- bugzilla: none -- make lookup_*_arch.sql not autonomous since they never
-- insert
-- add changes files for nonlinux systems
--
-- Revision 1.1  2002/11/13 23:16:18  pjones
-- lookup_*_arch()
--
070701000003DA000081B400000000000000000000000167AE1114000004C4000000000000000000000000000000000000008500000000susemanager-schema/upgrade/rhn-satellite-schema-5.1-to-spacewalk-schema-0.2/077-lookup_snapshot_invalid_reason-non-deterministic.sql  --
-- Copyright (c) 2008 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
-- $Id$
--

CREATE OR REPLACE FUNCTION
lookup_snapshot_invalid_reason(label_in IN VARCHAR2)
RETURN NUMBER
IS
	PRAGMA AUTONOMOUS_TRANSACTION;
	snapshot_invalid_reason_id number;
BEGIN
	SELECT id
          INTO snapshot_invalid_reason_id
          FROM rhnSnapshotInvalidReason
         WHERE label = label_in;

	RETURN snapshot_invalid_reason_id;
EXCEPTION
        WHEN NO_DATA_FOUND THEN
            rhn_exception.raise_exception('invalid_snapshot_invalid_reason');
END;
/
SHOW ERRORS

--
-- $Log$
-- Revision 1.1  2003/10/07 20:49:18  pjones
-- bugzilla: 106188
--
-- snapshot invalidation
--
070701000003DB000081B400000000000000000000000167AE111400000502000000000000000000000000000000000000007900000000susemanager-schema/upgrade/rhn-satellite-schema-5.1-to-spacewalk-schema-0.2/078-lookup_source_name-non-deterministic.sql  --
-- Copyright (c) 2008 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
-- $Id$
--

CREATE OR REPLACE FUNCTION
LOOKUP_SOURCE_NAME(name_in IN VARCHAR2)
RETURN NUMBER
IS
	PRAGMA AUTONOMOUS_TRANSACTION;
	source_id	NUMBER;
BEGIN
        select	id into source_id
        from	rhnSourceRPM 
        where	name = name_in;

        RETURN source_id;
EXCEPTION
        WHEN NO_DATA_FOUND THEN
            insert into rhnSourceRPM(id, name)
                    values (rhn_sourcerpm_id_seq.nextval, name_in)
                    returning id into source_id;
            COMMIT;
            RETURN source_id;
END;
/
SHOW ERRORS

-- $Log$
-- Revision 1.5  2002/05/13 22:53:38  pjones
-- cvs id/log
-- some (note enough) readability fixes
--
  070701000003DC000081B400000000000000000000000167AE11140000056D000000000000000000000000000000000000007100000000susemanager-schema/upgrade/rhn-satellite-schema-5.1-to-spacewalk-schema-0.2/079-lookup_tag-non-deterministic.sql  --
-- Copyright (c) 2008 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
-- $Id$
--

CREATE OR REPLACE FUNCTION
LOOKUP_TAG(org_id_in IN NUMBER, name_in IN VARCHAR2)
RETURN NUMBER
IS
	PRAGMA AUTONOMOUS_TRANSACTION;
	tag_id     NUMBER;
BEGIN
        select id into tag_id
	  from rhnTag
	 where org_id = org_id_in
	   and name_id = lookup_tag_name(name_in);

        RETURN tag_id;
EXCEPTION
        WHEN NO_DATA_FOUND THEN
            insert into rhnTag(id, org_id, name_id)
                    values (rhn_tag_id_seq.nextval, org_id_in, lookup_tag_name(name_in))
                    returning id into tag_id;
            COMMIT;
            RETURN tag_id;
END;
/
SHOW ERRORS

-- $Log$
-- Revision 1.1  2003/10/16 14:23:33  bretm
-- bugzilla:  107189
--
-- o  added server_id to rhnSnapshotTag
-- o  added lookup_tag(org_id, tagname)
--
   070701000003DD000081B400000000000000000000000167AE1114000004EF000000000000000000000000000000000000007600000000susemanager-schema/upgrade/rhn-satellite-schema-5.1-to-spacewalk-schema-0.2/080-lookup_tag_name-non-deterministic.sql --
-- Copyright (c) 2008 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
-- $Id$
--

CREATE OR REPLACE FUNCTION
LOOKUP_TAG_NAME(name_in IN VARCHAR2)
RETURN NUMBER
IS
	PRAGMA AUTONOMOUS_TRANSACTION;
	name_id     NUMBER;
BEGIN
        select id into name_id
	  from rhnTagName
	 where name = name_in;

        RETURN name_id;
EXCEPTION
        WHEN NO_DATA_FOUND THEN
            insert into rhnTagName(id, name)
                    values (rhn_tagname_id_seq.nextval, name_in)
                    returning id into name_id;
            COMMIT;
            RETURN name_id;
END;
/
SHOW ERRORS

-- $Log$
-- Revision 1.1  2003/10/15 20:29:53  bretm
-- bugzilla:  107189
--
-- 1st pass at snapshot tagging schema
--
 070701000003DE000081B400000000000000000000000167AE1114000008D5000000000000000000000000000000000000008100000000susemanager-schema/upgrade/rhn-satellite-schema-5.1-to-spacewalk-schema-0.2/081-lookup_transaction_package-non-deterministic.sql  --
-- Copyright (c) 2008 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
-- $Id$
--

CREATE OR REPLACE FUNCTION
LOOKUP_TRANSACTION_PACKAGE(o_in IN VARCHAR2, n_in IN VARCHAR2, 
    e_in IN VARCHAR2, v_in IN VARCHAR2, r_in IN VARCHAR2, a_in IN VARCHAR2)
RETURN NUMBER
IS
	PRAGMA AUTONOMOUS_TRANSACTION;
        o_id        NUMBER;
        n_id        NUMBER;
	e_id	    NUMBER;
        p_arch_id   NUMBER;
        tp_id       NUMBER;
BEGIN
	BEGIN
	    SELECT id
	      INTO o_id
	      FROM rhnTransactionOperation
	     WHERE label = o_in;
	EXCEPTION
	    WHEN NO_DATA_FOUND THEN
		rhn_exception.raise_exception('invalid_transaction_operation');
	END;

	SELECT LOOKUP_PACKAGE_NAME(n_in)
	  INTO n_id
	  FROM dual;

	SELECT LOOKUP_EVR(e_in, v_in, r_in)
	  INTO e_id
	  FROM dual;

	p_arch_id := NULL;
	IF a_in IS NOT NULL
	THEN
		SELECT LOOKUP_PACKAGE_ARCH(a_in)
		  INTO p_arch_id
		  FROM dual;
	END IF;

	SELECT id
	  INTO tp_id
	  FROM rhnTransactionPackage
	 WHERE operation = o_id
	   AND name_id = n_id
	   AND evr_id = e_id
	   AND (package_arch_id = p_arch_id OR (p_arch_id IS NULL AND package_arch_id IS NULL));
	RETURN tp_id;
EXCEPTION
        WHEN NO_DATA_FOUND THEN
	    INSERT INTO rhnTransactionPackage 
		(id, operation, name_id, evr_id, package_arch_id)
	    VALUES (rhn_transpack_id_seq.nextval, o_id, n_id, e_id, p_arch_id)
	    RETURNING id INTO tp_id;
	    COMMIT;
	    RETURN tp_id;
END;
/
SHOW ERRORS

-- $Log$
-- Revision 1.2  2003/07/09 16:29:33  cturner
-- update some strings and change lookup_transaction_package to throw an exception instead of SILENTLY RETURNING NULL
--
-- Revision 1.1  2003/07/01 14:52:35  misa
-- bugzilla: 90376  Need function to add transactions in the DB
--
   070701000003DF000081B400000000000000000000000167AE11140000048D000000000000000000000000000000000000006C00000000susemanager-schema/upgrade/rhn-satellite-schema-5.1-to-spacewalk-schema-0.2/082-name_join-deterministic.sql   --
-- Copyright (c) 2008 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
-- $Id$
--

CREATE OR REPLACE FUNCTION
NAME_JOIN(sep_in IN VARCHAR2, ugi_in IN user_group_name_t)
RETURN VARCHAR2
deterministic
IS
	ret	VARCHAR2(4000);
	i	BINARY_INTEGER;
BEGIN
	ret := '';
	i := ugi_in.FIRST;

	IF i IS NULL
	THEN
		RETURN ret;
	END IF;

	ret := ugi_in(i);
	i := ugi_in.NEXT(i);

	WHILE i IS NOT NULL
	LOOP
		ret := ret || sep_in || ugi_in(i);
		i := ugi_in.NEXT(i);
	END LOOP;

	RETURN ret;
END;
/
SHOW ERRORS

-- $Log$
-- Revision 1.2  2002/05/13 22:53:38  pjones
-- cvs id/log
-- some (note enough) readability fixes
--
   070701000003E0000081B400000000000000000000000167AE11140000036B000000000000000000000000000000000000007900000000susemanager-schema/upgrade/rhn-satellite-schema-5.1-to-spacewalk-schema-0.2/083-truncateCacheQueue-execute-immediate.sql  --
-- Copyright (c) 2008 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
-- $Id$
--

create or replace procedure  truncateCacheQueue as
begin
  execute immediate 'Truncate Table rhnOrgErrataCacheQueue';
end;
/

-- $Log$
-- Revision 1.2  2002/05/13 22:53:38  pjones
-- cvs id/log
-- some (note enough) readability fixes
--
 070701000003E1000081B400000000000000000000000167AE11140000037F000000000000000000000000000000000000007800000000susemanager-schema/upgrade/rhn-satellite-schema-5.1-to-spacewalk-schema-0.2/084-rhnServerNeededPackageCache-indexes.sql   
drop index rhn_snpc_pid_eid_sid_idx;
drop index rhn_snpc_sid_pid_eid_idx;
drop index rhn_snpc_eid_sid_pid_idx;
drop index rhn_snpc_oid_eid_sid_idx;

create index rhn_snpc_pid_idx
	on rhnServerNeededPackageCache(package_id)
	parallel
	tablespace [[128m_tbs]]
	storage ( pctincrease 1 freelists 16 )
	pctfree 10
	initrans 32
	nologging;
 
create index rhn_snpc_sid_idx
	on rhnServerNeededPackageCache(server_id)
	parallel
	tablespace [[128m_tbs]]
	storage ( pctincrease 1 freelists 16 )
	pctfree 10
	initrans 32
	nologging;
 
create index rhn_snpc_eid_idx
	on rhnServerNeededPackageCache(errata_id)
	parallel
	tablespace [[128m_tbs]]
	storage ( pctincrease 1 freelists 16 )
	pctfree 10
	initrans 32
	nologging;
 
create index rhn_snpc_oid_idx
	on rhnServerNeededPackageCache(org_id)
	parallel
	tablespace [[128m_tbs]]
	storage ( pctincrease 1 freelists 16 )
	pctfree 10
	initrans 32
	nologging;

 070701000003E2000081B400000000000000000000000167AE111400004F60000000000000000000000000000000000000006800000000susemanager-schema/upgrade/rhn-satellite-schema-5.1-to-spacewalk-schema-0.2/090-enable-row-movement.sql   
alter table PXTSessions enable row movement;
alter table demo_log enable row movement;
alter table rhnAction enable row movement;
alter table rhnActionConfigChannel enable row movement;
alter table rhnActionConfigDate enable row movement;
alter table rhnActionConfigDateFile enable row movement;
alter table rhnActionConfigFileName enable row movement;
alter table rhnActionConfigRevision enable row movement;
alter table rhnActionConfigRevisionResult enable row movement;
alter table rhnActionDaemonConfig enable row movement;
alter table rhnActionErrataUpdate enable row movement;
alter table rhnActionKickstart enable row movement;
alter table rhnActionKickstartFileList enable row movement;
alter table rhnActionKickstartGuest enable row movement;
alter table rhnActionPackage enable row movement;
alter table rhnActionPackageAnswerfile enable row movement;
alter table rhnActionPackageDelta enable row movement;
alter table rhnActionPackageOrder enable row movement;
alter table rhnActionPackageRemovalFailure enable row movement;
alter table rhnActionScript enable row movement;
alter table rhnActionStatus enable row movement;
alter table rhnActionTransactions enable row movement;
alter table rhnActionType enable row movement;
alter table rhnActionVirtDestroy enable row movement;
alter table rhnActionVirtReboot enable row movement;
alter table rhnActionVirtRefresh enable row movement;
alter table rhnActionVirtResume enable row movement;
alter table rhnActionVirtSchedulePoller enable row movement;
alter table rhnActionVirtSetMemory enable row movement;
alter table rhnActionVirtShutdown enable row movement;
alter table rhnActionVirtStart enable row movement;
alter table rhnActionVirtSuspend enable row movement;
alter table rhnActionVirtVcpu enable row movement;
alter table rhnActivationKey enable row movement;
alter table rhnAppInstallInstance enable row movement;
alter table rhnAppInstallSession enable row movement;
alter table rhnAppInstallSessionData enable row movement;
alter table rhnArchType enable row movement;
alter table rhnArchTypeActions enable row movement;
alter table rhnBeehivePathMap enable row movement;
alter table rhnBlacklistObsoletes enable row movement;
alter table rhnCVE enable row movement;
alter table rhnChannel enable row movement;
alter table rhnChannelArch enable row movement;
alter table rhnChannelCloned enable row movement;
alter table rhnChannelComps enable row movement;
alter table rhnChannelDownloads enable row movement;
alter table rhnChannelErrata enable row movement;
alter table rhnChannelFamily enable row movement;
alter table rhnChannelFamilyLicense enable row movement;
alter table rhnChannelFamilyLicenseConsent enable row movement;
alter table rhnChannelFamilyMembers enable row movement;
alter table rhnChannelFamilyVirtSubLevel enable row movement;
alter table rhnChannelNewestPackage enable row movement;
alter table rhnChannelNewestPackageAudit enable row movement;
alter table rhnChannelPackage enable row movement;
alter table rhnChannelPackageArchCompat enable row movement;
alter table rhnChannelParent enable row movement;
alter table rhnChannelPermission enable row movement;
alter table rhnChannelPermissionRole enable row movement;
alter table rhnChannelProduct enable row movement;
alter table rhnClientCapability enable row movement;
alter table rhnClientCapabilityName enable row movement;
alter table rhnConfigChannel enable row movement;
alter table rhnConfigChannelType enable row movement;
alter table rhnConfigContent enable row movement;
alter table rhnConfigFile enable row movement;
alter table rhnConfigFileFailure enable row movement;
alter table rhnConfigFileName enable row movement;
alter table rhnConfigFileState enable row movement;
alter table rhnConfigFileType enable row movement;
alter table rhnConfigInfo enable row movement;
alter table rhnConfigRevision enable row movement;
alter table rhnCpu enable row movement;
alter table rhnCpuArch enable row movement;
alter table rhnCryptoKey enable row movement;
alter table rhnCryptoKeyKickstart enable row movement;
alter table rhnCryptoKeyType enable row movement;
alter table rhnCustomDataKey enable row movement;
alter table rhnDaemonState enable row movement;
alter table rhnDailySummaryQueue enable row movement;
alter table rhnDevice enable row movement;
alter table rhnDistChannelMap enable row movement;
alter table rhnDownloadType enable row movement;
alter table rhnDownloads enable row movement;
alter table rhnEmailAddress enable row movement;
alter table rhnEmailAddressLog enable row movement;
alter table rhnEmailAddressState enable row movement;
alter table rhnEntitlementLog enable row movement;
alter table rhnErrata enable row movement;
alter table rhnErrataBuglist enable row movement;
alter table rhnErrataBuglistTmp enable row movement;
alter table rhnErrataCVE enable row movement;
alter table rhnErrataCloned enable row movement;
alter table rhnErrataClonedTmp enable row movement;
alter table rhnErrataFile enable row movement;
alter table rhnErrataFileChannel enable row movement;
alter table rhnErrataFileChannelTmp enable row movement;
alter table rhnErrataFilePackage enable row movement;
alter table rhnErrataFilePackageSource enable row movement;
alter table rhnErrataFilePackageTmp enable row movement;
alter table rhnErrataFileTmp enable row movement;
alter table rhnErrataFileType enable row movement;
alter table rhnErrataKeyword enable row movement;
alter table rhnErrataKeywordTmp enable row movement;
alter table rhnErrataNotificationQueue enable row movement;
alter table rhnErrataPackage enable row movement;
alter table rhnErrataPackageTmp enable row movement;
alter table rhnErrataQueue enable row movement;
alter table rhnErrataSeverity enable row movement;
alter table rhnErrataTmp enable row movement;
alter table rhnException enable row movement;
alter table rhnFAQ enable row movement;
alter table rhnFAQClass enable row movement;
alter table rhnFeature enable row movement;
alter table rhnFile enable row movement;
alter table rhnFileDownload enable row movement;
alter table rhnFileList enable row movement;
alter table rhnFileListMembers enable row movement;
alter table rhnFileLocation enable row movement;
alter table rhnGrailComponentChoices enable row movement;
alter table rhnGrailComponents enable row movement;
alter table rhnIndexerWork enable row movement;
alter table rhnInfoPane enable row movement;
alter table rhnKSData enable row movement;
alter table rhnKSInstallType enable row movement;
alter table rhnKSTreeFile enable row movement;
alter table rhnKSTreeType enable row movement;
alter table rhnKickstartChildChannel enable row movement;
alter table rhnKickstartCommand enable row movement;
alter table rhnKickstartCommandName enable row movement;
alter table rhnKickstartDefaultRegToken enable row movement;
alter table rhnKickstartDefaults enable row movement;
alter table rhnKickstartIPRange enable row movement;
alter table rhnKickstartPackage enable row movement;
alter table rhnKickstartPreserveFileList enable row movement;
alter table rhnKickstartScript enable row movement;
alter table rhnKickstartSession enable row movement;
alter table rhnKickstartSessionHistory enable row movement;
alter table rhnKickstartSessionState enable row movement;
alter table rhnKickstartTimezone enable row movement;
alter table rhnKickstartVirtualizationType enable row movement;
alter table rhnKickstartableTree enable row movement;
alter table rhnMessage enable row movement;
alter table rhnMessagePriority enable row movement;
alter table rhnMessageType enable row movement;
alter table rhnMonitor enable row movement;
alter table rhnMonitorGranularity enable row movement;
alter table rhnOrgChannelSettings enable row movement;
alter table rhnOrgChannelSettingsType enable row movement;
alter table rhnOrgEntitlementType enable row movement;
alter table rhnOrgEntitlements enable row movement;
alter table rhnOrgErrataCacheQueue enable row movement;
alter table rhnOrgInfo enable row movement;
alter table rhnOrgQuota enable row movement;
alter table rhnPackage enable row movement;
alter table rhnPackageArch enable row movement;
alter table rhnPackageCapability enable row movement;
alter table rhnPackageChangeLog enable row movement;
alter table rhnPackageConflicts enable row movement;
alter table rhnPackageDelta enable row movement;
alter table rhnPackageDeltaElement enable row movement;
alter table rhnPackageEVR enable row movement;
alter table rhnPackageFile enable row movement;
alter table rhnPackageFileDeleteQueue enable row movement;
alter table rhnPackageGroup enable row movement;
alter table rhnPackageNEVRA enable row movement;
alter table rhnPackageName enable row movement;
alter table rhnPackageObsoletes enable row movement;
alter table rhnPackageProvides enable row movement;
alter table rhnPackageRequires enable row movement;
alter table rhnPackageSense enable row movement;
alter table rhnPackageSenseMap enable row movement;
alter table rhnPackageSource enable row movement;
alter table rhnPackageSyncBlacklist enable row movement;
alter table rhnPathChannelMap enable row movement;
alter table rhnPrivateChannelFamily enable row movement;
alter table rhnProduct enable row movement;
alter table rhnProductChannel enable row movement;
alter table rhnProductLine enable row movement;
alter table rhnProductName enable row movement;
alter table rhnProvisionState enable row movement;
alter table rhnProxyInfo enable row movement;
alter table rhnPublicChannelFamily enable row movement;
alter table rhnPushClient enable row movement;
alter table rhnPushClientState enable row movement;
alter table rhnPushDispatcher enable row movement;
alter table rhnRam enable row movement;
alter table rhnRedHatCanonVersion enable row movement;
alter table rhnRegToken enable row movement;
alter table rhnRegTokenChannels enable row movement;
alter table rhnRegTokenConfigChannels enable row movement;
alter table rhnRegTokenEntitlement enable row movement;
alter table rhnRegTokenGroups enable row movement;
alter table rhnRegTokenOrgDefault enable row movement;
alter table rhnRegTokenPackages enable row movement;
alter table rhnRelationshipType enable row movement;
alter table rhnReleaseChannelMap enable row movement;
alter table rhnSGTypeBaseAddonCompat enable row movement;
alter table rhnSGTypeVirtSubLevel enable row movement;
alter table rhnSNPErrataQueue enable row movement;
alter table rhnSNPServerQueue enable row movement;
alter table rhnSatelliteCert enable row movement;
alter table rhnSatelliteChannelFamily enable row movement;
alter table rhnSatelliteInfo enable row movement;
alter table rhnSatelliteServerGroup enable row movement;
alter table rhnSavedSearch enable row movement;
alter table rhnSavedSearchType enable row movement;
alter table rhnServer enable row movement;
alter table rhnServerAction enable row movement;
alter table rhnServerActionPackageResult enable row movement;
alter table rhnServerActionScriptResult enable row movement;
alter table rhnServerActionVerifyMissing enable row movement;
alter table rhnServerActionVerifyResult enable row movement;
alter table rhnServerArch enable row movement;
alter table rhnServerCacheInfo enable row movement;
alter table rhnServerChannel enable row movement;
alter table rhnServerChannelArchCompat enable row movement;
alter table rhnServerConfigChannel enable row movement;
alter table rhnServerCustomDataValue enable row movement;
alter table rhnServerDMI enable row movement;
alter table rhnServerEvent enable row movement;
alter table rhnServerGroup enable row movement;
alter table rhnServerGroupMembers enable row movement;
alter table rhnServerGroupNotes enable row movement;
alter table rhnServerGroupType enable row movement;
alter table rhnServerGroupTypeFeature enable row movement;
alter table rhnServerHistory enable row movement;
alter table rhnServerInfo enable row movement;
alter table rhnServerInstallInfo enable row movement;
alter table rhnServerLocation enable row movement;
alter table rhnServerLock enable row movement;
alter table rhnServerMessage enable row movement;
alter table rhnServerNeededErrataCache enable row movement;
alter table rhnServerNeededPackageCache enable row movement;
alter table rhnServerNetInterface enable row movement;
alter table rhnServerNetwork enable row movement;
alter table rhnServerNotes enable row movement;
alter table rhnServerPackage enable row movement;
alter table rhnServerPackageArchCompat enable row movement;
alter table rhnServerPath enable row movement;
alter table rhnServerPreserveFileList enable row movement;
alter table rhnServerProfile enable row movement;
alter table rhnServerProfilePackage enable row movement;
alter table rhnServerProfileType enable row movement;
alter table rhnServerServerGroupArchCompat enable row movement;
alter table rhnServerTokenRegs enable row movement;
alter table rhnServerUuid enable row movement;
alter table rhnSet enable row movement;
alter table rhnSnapshot enable row movement;
alter table rhnSnapshotChannel enable row movement;
alter table rhnSnapshotConfigChannel enable row movement;
alter table rhnSnapshotConfigRevision enable row movement;
alter table rhnSnapshotInvalidReason enable row movement;
alter table rhnSnapshotPackage enable row movement;
alter table rhnSnapshotServerGroup enable row movement;
alter table rhnSnapshotTag enable row movement;
alter table rhnSolarisPackage enable row movement;
alter table rhnSolarisPatch enable row movement;
alter table rhnSolarisPatchPackages enable row movement;
alter table rhnSolarisPatchSet enable row movement;
alter table rhnSolarisPatchSetMembers enable row movement;
alter table rhnSolarisPatchType enable row movement;
alter table rhnSolarisPatchedPackage enable row movement;
alter table rhnSourceRPM enable row movement;
alter table rhnTag enable row movement;
alter table rhnTagName enable row movement;
alter table rhnTaskQueue enable row movement;
alter table rhnTemplateCategory enable row movement;
alter table rhnTemplateString enable row movement;
alter table rhnTextMessage enable row movement;
alter table rhnTimezone enable row movement;
alter table rhnTinyURL enable row movement;
alter table rhnTransaction enable row movement;
alter table rhnTransactionElement enable row movement;
alter table rhnTransactionOperation enable row movement;
alter table rhnTransactionPackage enable row movement;
alter table rhnUserDefaultSystemGroups enable row movement;
alter table rhnUserGroup enable row movement;
alter table rhnUserGroupMembers enable row movement;
alter table rhnUserGroupType enable row movement;
alter table rhnUserInfo enable row movement;
alter table rhnUserInfoPane enable row movement;
alter table rhnUserMessage enable row movement;
alter table rhnUserMessageStatus enable row movement;
alter table rhnUserMessageType enable row movement;
alter table rhnUserReserved enable row movement;
alter table rhnUserServerGroupPerms enable row movement;
alter table rhnUserServerPerms enable row movement;
alter table rhnUserServerPrefs enable row movement;
alter table rhnVersionInfo enable row movement;
alter table rhnVirtSubLevel enable row movement;
alter table rhnVirtualInstance enable row movement;
alter table rhnVirtualInstanceEventLog enable row movement;
alter table rhnVirtualInstanceEventType enable row movement;
alter table rhnVirtualInstanceInfo enable row movement;
alter table rhnVirtualInstanceInstallLog enable row movement;
alter table rhnVirtualInstanceState enable row movement;
alter table rhnVirtualInstanceType enable row movement;
alter table rhnVisibleObjects enable row movement;
alter table rhnWebContactChangeLog enable row movement;
alter table rhnWebContactChangeState enable row movement;
alter table rhn_check_probe enable row movement;
alter table rhn_check_suite_probe enable row movement;
alter table rhn_check_suites enable row movement;
alter table rhn_command enable row movement;
alter table rhn_command_center_state enable row movement;
alter table rhn_command_class enable row movement;
alter table rhn_command_groups enable row movement;
alter table rhn_command_param_threshold enable row movement;
alter table rhn_command_parameter enable row movement;
alter table rhn_command_queue_commands enable row movement;
alter table rhn_command_queue_execs enable row movement;
alter table rhn_command_queue_execs_bk enable row movement;
alter table rhn_command_queue_instances enable row movement;
alter table rhn_command_queue_instances_bk enable row movement;
alter table rhn_command_queue_params enable row movement;
alter table rhn_command_queue_sessions enable row movement;
alter table rhn_command_requirements enable row movement;
alter table rhn_command_target enable row movement;
alter table rhn_config_group enable row movement;
alter table rhn_config_macro enable row movement;
alter table rhn_config_parameter enable row movement;
alter table rhn_config_security_type enable row movement;
alter table rhn_contact_group_members enable row movement;
alter table rhn_contact_groups enable row movement;
alter table rhn_contact_methods enable row movement;
alter table rhn_current_alerts enable row movement;
alter table rhn_current_state_summaries enable row movement;
alter table rhn_db_environment enable row movement;
alter table rhn_deployed_probe enable row movement;
alter table rhn_environment enable row movement;
alter table rhn_host_check_suites enable row movement;
alter table rhn_host_probe enable row movement;
alter table rhn_interface_monitoring enable row movement;
alter table rhn_ll_netsaint enable row movement;
alter table rhn_method_types enable row movement;
alter table rhn_metrics enable row movement;
alter table rhn_multi_scout_threshold enable row movement;
alter table rhn_notification_formats enable row movement;
alter table rhn_notifservers enable row movement;
alter table rhn_os enable row movement;
alter table rhn_os_commands_xref enable row movement;
alter table rhn_pager_types enable row movement;
alter table rhn_physical_location enable row movement;
alter table rhn_probe enable row movement;
alter table rhn_probe_param_value enable row movement;
alter table rhn_probe_state enable row movement;
alter table rhn_probe_types enable row movement;
alter table rhn_quanta enable row movement;
alter table rhn_redirect_criteria enable row movement;
alter table rhn_redirect_email_targets enable row movement;
alter table rhn_redirect_group_targets enable row movement;
alter table rhn_redirect_match_types enable row movement;
alter table rhn_redirect_method_targets enable row movement;
alter table rhn_redirect_types enable row movement;
alter table rhn_redirects enable row movement;
alter table rhn_sat_cluster enable row movement;
alter table rhn_sat_cluster_probe enable row movement;
alter table rhn_sat_node enable row movement;
alter table rhn_sat_node_probe enable row movement;
alter table rhn_satellite_state enable row movement;
alter table rhn_schedule_days enable row movement;
alter table rhn_schedule_days_norm enable row movement;
alter table rhn_schedule_types enable row movement;
alter table rhn_schedule_weeks enable row movement;
alter table rhn_schedules enable row movement;
alter table rhn_semantic_data_type enable row movement;
alter table rhn_server_monitoring_info enable row movement;
alter table rhn_service_probe_origins enable row movement;
alter table rhn_snmp_alert enable row movement;
alter table rhn_strategies enable row movement;
alter table rhn_threshold_type enable row movement;
alter table rhn_time_zone_names enable row movement;
alter table rhn_units enable row movement;
alter table rhn_url_probe enable row movement;
alter table rhn_url_probe_step enable row movement;
alter table rhn_widget enable row movement;
alter table state_change enable row movement;
alter table time_series enable row movement;
alter table valid_countries enable row movement;
alter table web_contact enable row movement;
alter table web_customer enable row movement;
alter table web_customer_notification enable row movement;
alter table web_user_contact_permission enable row movement;
alter table web_user_personal_info enable row movement;
alter table web_user_prefix enable row movement;
alter table web_user_site_info enable row movement;
alter table web_user_site_type enable row movement;

070701000003E3000081B400000000000000000000000167AE111400000063000000000000000000000000000000000000007400000000susemanager-schema/upgrade/rhn-satellite-schema-5.1-to-spacewalk-schema-0.2/091-rhn_command_parameter_data-user.sql   
update rhn_command_parameter
set last_update_user = 'system'
where last_update_user = 'nhansen';

 070701000003E4000081B400000000000000000000000167AE111400002490000000000000000000000000000000000000007F00000000susemanager-schema/upgrade/rhn-satellite-schema-5.1-to-spacewalk-schema-0.2/092-rhn_command_parameter_data-sshbannerignore.sql    
insert into command_parameter(command_id, param_name, param_type,
data_type_name, description, mandatory, default_value, min_value, max_value,
field_order, field_widget_name, field_visible_length, field_maximum_length,
field_visible, default_value_visible, last_update_user, last_update_date)
    values (25, 'sshbannerignore', 'config', 'integer', 'SSH banner (number of lines)', 0, '',NULL, NULL, 32, 'text', 8, 20, 1, 1, 'system', sysdate);

insert into command_parameter(command_id, param_name, param_type,
data_type_name, description, mandatory, default_value, min_value, max_value,
field_order, field_widget_name, field_visible_length, field_maximum_length,
field_visible, default_value_visible, last_update_user, last_update_date)
    values (26, 'sshbannerignore', 'config', 'integer', 'SSH banner (number of lines)', 0, '',NULL, NULL, 32, 'text', 8, 20, 1, 1, 'system', sysdate);

insert into command_parameter(command_id, param_name, param_type,
data_type_name, description, mandatory, default_value, min_value, max_value,
field_order, field_widget_name, field_visible_length, field_maximum_length,
field_visible, default_value_visible, last_update_user, last_update_date)
    values (27, 'sshbannerignore', 'config', 'integer', 'SSH banner (number of lines)', 0, '',NULL, NULL, 32, 'text', 8, 20, 1, 1, 'system', sysdate);

insert into command_parameter(command_id, param_name, param_type,
data_type_name, description, mandatory, default_value, min_value, max_value,
field_order, field_widget_name, field_visible_length, field_maximum_length,
field_visible, default_value_visible, last_update_user, last_update_date)
    values (28, 'sshbannerignore', 'config', 'integer', 'SSH banner (number of lines)', 0, '',NULL, NULL, 45, 'text', 8, 20, 1, 1, 'system', sysdate);

insert into command_parameter(command_id, param_name, param_type,
data_type_name, description, mandatory, default_value, min_value, max_value,
field_order, field_widget_name, field_visible_length, field_maximum_length,
field_visible, default_value_visible, last_update_user, last_update_date)
    values (29, 'sshbannerignore', 'config', 'integer', 'SSH banner (number of lines)', 0, '',NULL, NULL, 32, 'text', 8, 20, 1, 1, 'system', sysdate);

insert into command_parameter(command_id, param_name, param_type,
data_type_name, description, mandatory, default_value, min_value, max_value,
field_order, field_widget_name, field_visible_length, field_maximum_length,
field_visible, default_value_visible, last_update_user, last_update_date)
    values (30, 'sshbannerignore', 'config', 'integer', 'SSH banner (number of lines)', 0, '',NULL, NULL, 32, 'text', 8, 20, 1, 1, 'system', sysdate);

insert into command_parameter(command_id, param_name, param_type,
data_type_name, description, mandatory, default_value, min_value, max_value,
field_order, field_widget_name, field_visible_length, field_maximum_length,
field_visible, default_value_visible, last_update_user, last_update_date)
    values (31, 'sshbannerignore', 'config', 'integer', 'SSH banner (number of lines)', 0, '',NULL, NULL, 32, 'text', 8, 20, 1, 1, 'system', sysdate);

insert into command_parameter(command_id, param_name, param_type,
data_type_name, description, mandatory, default_value, min_value, max_value,
field_order, field_widget_name, field_visible_length, field_maximum_length,
field_visible, default_value_visible, last_update_user, last_update_date)
    values (99, 'sshbannerignore', 'config', 'integer', 'SSH banner (number of lines)', 0, '',NULL, NULL, 85, 'text', 8, 20, 1, 1, 'system', sysdate);

insert into command_parameter(command_id, param_name, param_type,
data_type_name, description, mandatory, default_value, min_value, max_value,
field_order, field_widget_name, field_visible_length, field_maximum_length,
field_visible, default_value_visible, last_update_user, last_update_date)
    values (105, 'sshbannerignore', 'config', 'integer', 'SSH banner (number of lines)', 0, '',NULL, NULL, 140, 'text', 8, 20, 1, 1, 'system', sysdate);

insert into command_parameter(command_id, param_name, param_type,
data_type_name, description, mandatory, default_value, min_value, max_value,
field_order, field_widget_name, field_visible_length, field_maximum_length,
field_visible, default_value_visible, last_update_user, last_update_date)
    values (106, 'sshbannerignore', 'config', 'integer', 'SSH banner (number of lines)', 0, '',NULL, NULL, 55, 'text', 8, 20, 1, 1, 'system', sysdate);

insert into command_parameter(command_id, param_name, param_type,
data_type_name, description, mandatory, default_value, min_value, max_value,
field_order, field_widget_name, field_visible_length, field_maximum_length,
field_visible, default_value_visible, last_update_user, last_update_date)
    values (107, 'sshbannerignore', 'config', 'integer', 'SSH banner (number of lines)', 0, '',NULL, NULL, 65, 'text', 8, 20, 1, 1, 'system', sysdate);

insert into command_parameter(command_id, param_name, param_type,
data_type_name, description, mandatory, default_value, min_value, max_value,
field_order, field_widget_name, field_visible_length, field_maximum_length,
field_visible, default_value_visible, last_update_user, last_update_date)
    values (109, 'sshbannerignore', 'config', 'integer', 'SSH banner (number of lines)', 0, '',NULL, NULL, 32, 'text', 8, 20, 1, 1, 'system', sysdate);

insert into command_parameter(command_id, param_name, param_type,
data_type_name, description, mandatory, default_value, min_value, max_value,
field_order, field_widget_name, field_visible_length, field_maximum_length,
field_visible, default_value_visible, last_update_user, last_update_date)
    values (117, 'sshbannerignore', 'config', 'integer', 'SSH banner (number of lines)', 0, '',NULL, NULL, 32, 'text', 8, 20, 1, 1, 'system', sysdate);

insert into command_parameter(command_id, param_name, param_type,
data_type_name, description, mandatory, default_value, min_value, max_value,
field_order, field_widget_name, field_visible_length, field_maximum_length,
field_visible, default_value_visible, last_update_user, last_update_date)
    values (118, 'sshbannerignore', 'config', 'integer', 'SSH banner (number of lines)', 0, '',NULL, NULL, 37, 'text', 8, 20, 1, 1, 'system', sysdate);

insert into command_parameter(command_id, param_name, param_type,
data_type_name, description, mandatory, default_value, min_value, max_value,
field_order, field_widget_name, field_visible_length, field_maximum_length,
field_visible, default_value_visible, last_update_user, last_update_date)
    values (123, 'sshbannerignore', 'config', 'integer', 'SSH banner (number of lines)', 0, '',NULL, NULL, 32, 'text', 8, 20, 1, 1, 'system', sysdate);

insert into command_parameter(command_id, param_name, param_type,
data_type_name, description, mandatory, default_value, min_value, max_value,
field_order, field_widget_name, field_visible_length, field_maximum_length,
field_visible, default_value_visible, last_update_user, last_update_date)
    values (226, 'sshbannerignore', 'config', 'integer', 'SSH banner (number of lines)', 0, '',NULL, NULL, 85, 'text', 8, 20, 1, 1, 'system', sysdate);

insert into command_parameter(command_id, param_name, param_type,
data_type_name, description, mandatory, default_value, min_value, max_value,
field_order, field_widget_name, field_visible_length, field_maximum_length,
field_visible, default_value_visible, last_update_user, last_update_date)
    values (228, 'sshbannerignore', 'config', 'integer', 'SSH banner (number of lines)', 0, '',NULL, NULL, 32, 'text', 8, 20, 1, 1, 'system', sysdate);

insert into command_parameter(command_id, param_name, param_type,
data_type_name, description, mandatory, default_value, min_value, max_value,
field_order, field_widget_name, field_visible_length, field_maximum_length,
field_visible, default_value_visible, last_update_user, last_update_date)
    values (230, 'sshbannerignore', 'config', 'integer', 'SSH banner (number of lines)', 0, '',NULL, NULL, 32, 'text', 8, 20, 1, 1, 'system', sysdate);

insert into command_parameter(command_id, param_name, param_type,
data_type_name, description, mandatory, default_value, min_value, max_value,
field_order, field_widget_name, field_visible_length, field_maximum_length,
field_visible, default_value_visible, last_update_user, last_update_date)
    values (249, 'sshbannerignore', 'config', 'integer', 'SSH banner (number of lines)', 0, '',NULL, NULL, 37, 'text', 8, 20, 1, 1, 'system', sysdate);

insert into command_parameter(command_id, param_name, param_type,
data_type_name, description, mandatory, default_value, min_value, max_value,
field_order, field_widget_name, field_visible_length, field_maximum_length,
field_visible, default_value_visible, last_update_user, last_update_date)
    values (274, 'sshbannerignore', 'config', 'integer', 'SSH banner (number of lines)', 0, '',NULL, NULL, 85, 'text', 8, 20, 1, 1, 'system', sysdate);

insert into command_parameter(command_id, param_name, param_type,
data_type_name, description, mandatory, default_value, min_value, max_value,
field_order, field_widget_name, field_visible_length, field_maximum_length,
field_visible, default_value_visible, last_update_user, last_update_date)
    values (304, 'sshbannerignore', 'config', 'integer', 'SSH banner (number of lines)', 0, '',NULL, NULL, 27, 'text', 8, 20, 1, 1, 'system', sysdate);

070701000003E5000081B400000000000000000000000167AE1114000004D0000000000000000000000000000000000000006E00000000susemanager-schema/upgrade/rhn-satellite-schema-5.1-to-spacewalk-schema-0.2/093-rhnChannelCloned_triggers.sql --
-- Copyright (c) 2008 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
-- $Id$
--

create or replace trigger
rhn_channel_cloned_comps_trig
before insert on rhnChannelCloned
for each row
begin
	-- if there are not comps in the cloned channel by now,
	-- we shall clone comps from the original channel
	insert into rhnChannelComps
		( id, channel_id, relative_filename,
			last_modified, created, modified )
	select rhn_channelcomps_id_seq.nextval, :new.id, relative_filename,
			sysdate, sysdate, sysdate
	from rhnChannelComps
	where channel_id = :new.original_id
		and not exists (
			select 1
			from rhnChannelComps x
			where x.channel_id = :new.id
		);
end;
/
show errors

070701000003E6000081B400000000000000000000000167AE1114000000DF000000000000000000000000000000000000008600000000susemanager-schema/upgrade/rhn-satellite-schema-5.1-to-spacewalk-schema-0.2/094-rhnPackageChangelog-rhn_package_changelog_id_trig.sql 
create or replace trigger
rhn_package_changelog_id_trig
before insert on rhnPackageChangelog
for each row
when (new.id is null)
begin
        select rhn_pkg_cl_id_seq.nextval into :new.id from dual;
end;
/ 
show errors 
 
 070701000003E7000081B400000000000000000000000167AE1114000000D0000000000000000000000000000000000000005E00000000susemanager-schema/upgrade/rhn-satellite-schema-5.1-to-spacewalk-schema-0.2/103-rhnKSData.sql 
alter table rhnKSData
add preLog     char(1) default('N')
                constraint rhn_ks_pre_log_nn not null
                constraint rhn_ks_pre_log_ck
                    check (preLog in ('Y','N'));

070701000003E8000081B400000000000000000000000167AE1114000000D1000000000000000000000000000000000000005E00000000susemanager-schema/upgrade/rhn-satellite-schema-5.1-to-spacewalk-schema-0.2/104-rhnKSData.sql 
alter table rhnKSData
add kscfg      char(1) default('N')
                constraint rhn_ks_cfg_save_nn not null
                constraint rhn_ks_cfg_save_ck
                    check (kscfg in ('Y','N'));

   070701000003E9000081B400000000000000000000000167AE1114000001CB000000000000000000000000000000000000005E00000000susemanager-schema/upgrade/rhn-satellite-schema-5.1-to-spacewalk-schema-0.2/105-rhnKSData.sql 
alter table rhnKSData
add verboseup2date char(1) default('N')
                constraint rhn_ks_verbose_up2date_nn not null
                constraint rhn_ks_verbose_up2date_ck
                check (verboseup2date in ('Y','N'));

alter table rhnKSData
add nonchrootpost char(1) default('N')
                constraint rhn_ks_nonchroot_post_nn not null
                constraint rhn_ks_nonchroot_post_ck
                check (nonchrootpost in ('Y','N'));

 070701000003EA000081B400000000000000000000000167AE111400000467000000000000000000000000000000000000006200000000susemanager-schema/upgrade/rhn-satellite-schema-5.1-to-spacewalk-schema-0.2/200-rhn_cache.pks.sql --
-- Copyright (c) 2008 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
-- $Id$
--

create or replace package
rhn_cache
is
	version varchar2(100) := '$Id$';

	-- this searches out all users who get perms...
	procedure update_perms_for_server(
		server_id_in in number
	);

	procedure update_perms_for_user(
		user_id_in in number
	);

	procedure update_perms_for_server_group(
		server_group_id_in in number
	);
end rhn_cache;
/
show errors

--
-- $Log$
-- Revision 1.1  2004/07/02 19:14:32  pjones
-- 125937 -- tools to manipulate rhnUserServerPerms when appropriate.
--

 070701000003EB000081B400000000000000000000000167AE111400000AD4000000000000000000000000000000000000006200000000susemanager-schema/upgrade/rhn-satellite-schema-5.1-to-spacewalk-schema-0.2/201-rhn_cache.pkb.sql --
-- Copyright (c) 2008 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
-- $Id$
--

create or replace package body
rhn_cache
is
	body_version varchar2(100) := '$Id$';

	-- this searches out all users who get perms...
	procedure update_perms_for_server(
		server_id_in in number
	) is
	begin
		delete from rhnUserServerPerms where server_id = server_id_in;
		insert into rhnUserServerPerms(user_id, server_id) (
				select	distinct user_id, server_id_in
				from	rhnUserServerPermsDupes
				where	server_id = server_id_in
			);
	end update_perms_for_server;

	procedure update_perms_for_user(
		user_id_in in number
	) is
	begin
        delete from rhnUserServerPerms
        where user_id = user_id_in
            and server_id in
            (select server_id
             from rhnUserServerPerms
             where user_id = user_id_in
             minus
             select server_id
             from rhnUserServerPermsDupes uspd
             where uspd.user_id = user_id_in);

        insert into rhnUserServerPerms (user_id, server_id)
        select distinct user_id_in, server_id
        from rhnUserServerPermsDupes uspd
        where uspd.user_id = user_id_in
            and not exists
            (select 1
             from rhnUserServerPerms usp
             where usp.user_id = user_id_in
                 and usp.server_id = uspd.server_id);
	end update_perms_for_user;

	-- this means a server got added or removed, so we
	-- can't key off of a server anywhere.
	procedure update_perms_for_server_group(
		server_group_id_in in number
	) is
		cursor users is
			-- org admins aren't affected, so don't test for them
			select	usgp.user_id id
			from	rhnUserServerGroupPerms usgp
			where	usgp.server_group_id = server_group_id_in
				and not exists (
					select	1
					from	rhnUserGroup ug,
							rhnUserGroupMembers ugm,
							rhnServerGroup sg,
							rhnUserGroupType ugt
					where	ugt.label = 'org_admin'
						and sg.id = server_group_id_in
						and ugm.user_id = usgp.user_id
						and ug.org_id = sg.org_id
						and ugm.user_group_id = ug.id
					);
	begin
		for u in users loop
			update_perms_for_user(u.id);
		end loop;
	end update_perms_for_server_group;
end rhn_cache;
/
show errors
070701000003EC000081B400000000000000000000000167AE1114000023B9000000000000000000000000000000000000006400000000susemanager-schema/upgrade/rhn-satellite-schema-5.1-to-spacewalk-schema-0.2/202-rhn_channel.pks.sql   --
-- Copyright (c) 2008 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
-- $Id$
--

CREATE OR REPLACE
PACKAGE rhn_channel
IS
	version varchar2(100) := '$Id$';

    CURSOR server_base_subscriptions(server_id_in NUMBER) IS
    	   SELECT C.id
	     FROM rhnChannel C, rhnServerChannel SC
	    WHERE C.id = SC.channel_id
	      AND SC.server_id = server_id_in
	      AND C.parent_channel IS NULL;
	      
    CURSOR check_server_subscription(server_id_in NUMBER, channel_id_in NUMBER) IS 
           SELECT channel_id 
	     FROM rhnServerChannel 
	    WHERE server_id = server_id_in 
	      AND channel_id = channel_id_in;

    CURSOR check_server_parent_membership(server_id_in NUMBER, channel_id_in NUMBER) IS
    	   SELECT C.id
	     FROM rhnChannel C, rhnServerChannel SC
	    WHERE C.parent_channel = channel_id_in
	      AND C.id = SC.channel_id
	      AND SC.server_id = server_id_in;
	    
    CURSOR channel_family_perm_cursor(channel_family_id_in NUMBER, org_id_in NUMBER) IS
           SELECT *
	     FROM rhnOrgChannelFamilyPermissions
	    WHERE channel_family_id = channel_family_id_in
	      AND org_id = org_id_in;

    PROCEDURE license_consent(channel_id_in IN NUMBER, user_id_in IN NUMBER, server_id_in IN NUMBER);
    FUNCTION get_license_path(channel_id_in IN NUMBER) RETURN VARCHAR2;

    PROCEDURE unsubscribe_server(server_id_in IN NUMBER, channel_id_in NUMBER, immediate_in NUMBER := 1, unsubscribe_children_in number := 0,
                                 deleting_server in number := 0 );
    PROCEDURE subscribe_server(server_id_in IN NUMBER, channel_id_in NUMBER, immediate_in NUMBER := 1, user_id_in number := null);

    function can_server_consume_virt_channl(
        server_id_in IN NUMBER,
        family_id_in in number)
    return number;

    FUNCTION guess_server_base(server_id_in IN NUMBER) RETURN NUMBER;

    FUNCTION base_channel_for_release_arch(release_in in varchar2, 
	server_arch_in in varchar2, org_id_in in number := -1, 
	user_id_in in number := null) RETURN number;

    FUNCTION base_channel_rel_archid(release_in in varchar2, 
	server_arch_id_in in number, org_id_in in number := -1, 
	user_id_in in number := null) RETURN number;

    FUNCTION channel_priority(channel_id_in in number) RETURN number;
    
    PROCEDURE bulk_subscribe_server(channel_id_in IN NUMBER, set_label_in IN VARCHAR2, set_uid_in IN NUMBER);
    PROCEDURE bulk_unsubscribe_server(channel_id_in IN NUMBER, set_label_in IN VARCHAR2, set_uid_in IN NUMBER);
    
    PROCEDURE bulk_server_base_change(channel_id_in IN NUMBER, set_label_in IN VARCHAR2, set_uid_in IN NUMBER);
    procedure bulk_server_basechange_from(
	set_label_in in varchar2,
	set_uid_in in number,
	old_channel_id_in in number,
	new_channel_id_in in number);

    procedure bulk_guess_server_base(
	set_label_in in varchar2,
	set_uid_in in number);

    procedure bulk_guess_server_base_from(
	set_label_in in varchar2,
	set_uid_in in number,
	channel_id_in in number);

    PROCEDURE clear_subscriptions(server_id_in IN NUMBER, deleting_server in number := 0 );
    
    FUNCTION available_family_subscriptions(channel_family_id_in IN NUMBER, org_id_in IN NUMBER) RETURN NUMBER;

    function channel_family_current_members(channel_family_id_in IN NUMBER,
                                            org_id_in IN NUMBER)
    return number;

    PROCEDURE update_family_counts(channel_family_id_in IN NUMBER, org_id_in IN NUMBER);
    FUNCTION family_for_channel(channel_id_in IN NUMBER) RETURN NUMBER;

    FUNCTION available_chan_subscriptions(channel_id_in IN NUMBER, org_id_in IN NUMBER) RETURN NUMBER;

    procedure entitle_customer(customer_id_in in number, channel_family_id_in in number, quantity_in in number);
    procedure set_family_maxmembers(customer_id_in in number, channel_family_id_in in number, quantity_in in number);
    procedure unsubscribe_server_from_family(server_id_in in number, channel_family_id_in in number);

    procedure delete_server_channels(server_id_in in number);
    procedure refresh_newest_package(channel_id_in in number, caller_in in varchar2 := '(unknown)');
    
    function get_org_id(channel_id_in in number) return number;
    PRAGMA RESTRICT_REFERENCES(get_org_id, WNDS, RNPS, WNPS);

    function get_org_access(channel_id_in in number, org_id_in in number) return number;
    PRAGMA RESTRICT_REFERENCES(get_org_access, WNDS, RNPS, WNPS);
    
    function get_cfam_org_access(cfam_id_in in number, org_id_in in number) return number;

    function user_role_check_debug(channel_id_in in number, user_id_in in number, role_in in varchar2, reason_out out varchar2)
    	RETURN NUMBER;
    PRAGMA RESTRICT_REFERENCES(user_role_check_debug, WNDS, RNPS, WNPS);

    function user_role_check(channel_id_in in number, user_id_in in number, role_in in varchar2)
    	RETURN NUMBER;
    PRAGMA RESTRICT_REFERENCES(user_role_check, WNDS, RNPS, WNPS);
    
    function loose_user_role_check(channel_id_in in number, user_id_in in number, role_in in varchar2)
    	RETURN NUMBER;
    PRAGMA RESTRICT_REFERENCES(loose_user_role_check, WNDS, RNPS, WNPS);

    function direct_user_role_check(channel_id_in in number, user_id_in in number, role_in in varchar2)
    	RETURN NUMBER;
    PRAGMA RESTRICT_REFERENCES(direct_user_role_check, WNDS, RNPS, WNPS);

    function org_channel_setting(channel_id_in in number, org_id_in in number, setting_in in varchar2)
    	RETURN NUMBER;

    PROCEDURE update_channel ( channel_id_in in number, invalidate_ss in number := 0, 
                               date_to_use in date := sysdate );

    PROCEDURE  update_channels_by_package ( package_id_in in number, date_to_use in date := sysdate );

     PROCEDURE update_channels_by_errata ( errata_id_in number, date_to_use in date := sysdate );


    PRAGMA RESTRICT_REFERENCES(org_channel_setting, WNDS, RNPS, WNPS);

END rhn_channel;
/
SHOW ERRORS

-- $Log$
-- Revision 1.37  2004/04/14 00:09:24  pjones
-- bugzilla: 120761 -- split rhnChannelPermissions into two tables, eliminating
-- a frequent full table scan
--
-- Revision 1.36  2004/03/26 18:11:32  rbb
-- Bugzilla:  114057
--
-- Add a script to determine channel priority.
--
-- Revision 1.35  2004/02/17 20:16:52  pjones
-- bugzilla: none -- add cvs tags into the package as long as we're touching
-- it anyway
--
-- Revision 1.34  2003/11/13 18:13:09  cturner
-- pragmas can now return now that rhn_user pragmas are fixed
--
-- Revision 1.32  2003/09/22 21:00:40  cturner
-- add method for easy acl check
--
-- Revision 1.31  2003/09/17 22:14:11  misa
-- bugzilla: 103639  Changes to allow me to move the base channel guess into plsql
--
-- Revision 1.30  2003/07/24 16:44:16  misa
-- bugzilla: none  A function more usable on the rhnapp side
--
-- Revision 1.29  2003/07/24 14:00:17  misa
-- bugzilla: none  PRAGMA RESTRICT_REFERENCES good
--
-- Revision 1.28  2003/07/23 21:59:19  cturner
-- rework how rhnUserChannel works; move to plsql for speed and maintenance
--
-- Revision 1.27  2003/07/21 17:49:12  pjones
-- bugzilla: none
--
-- add optional user for subscribe_server
--
-- Revision 1.26  2002/12/19 18:13:42  misa
-- Added caller with a default value
--
-- Revision 1.25  2002/12/11 22:18:46  pjones
-- rhnChannelNewestPackage
--
-- Revision 1.24  2002/11/21 22:08:11  pjones
-- make unsubscribe_channels have a "unsubscribe_children_in number := 0"
-- argument so that you can tell it to unsubscribe children.
--
-- Also, make it raise an exception instead of silent failure in the
-- other case.
--
-- Revision 1.23  2002/11/18 17:20:50  pjones
-- this should have gone back too
--
-- Revision 1.22  2002/11/13 23:16:18  pjones
-- lookup_*_arch()
--
-- Revision 1.21  2002/10/07 20:01:59  rnorwood
-- guess base channel for ssm and single system
--
-- Revision 1.20  2002/10/02 19:21:03  bretm
-- o  3rd party channel schema changes, no more clobs...
--
-- Revision 1.19  2002/09/20 19:21:58  bretm
-- o  more 3rd party channel stuff...
--
-- Revision 1.18  2002/06/12 22:33:03  pjones
-- procedure bulk_guess_server_base_from(
--     set_label_in in varchar2,
--     set_uid_in in number,
--     channel_id_in in number);
--
-- for bretm
--
-- Revision 1.17  2002/06/12 22:12:25  pjones
-- procedure bulk_guess_server_base(
--     set_label_in in varchar2,
--     set_uid_in in number);
--
-- for bretm
--
-- Revision 1.16  2002/06/12 19:37:55  pjones
-- bulk_server_basechange_from(
-- 	set_label_in in varchar2,
-- 	set_uid_in in number,
-- 	old_channel_id_in in number,
-- 	new_channel_id_in in number
-- );
--
-- for bretm
--
-- Revision 1.15  2002/05/10 22:08:22  pjones
-- id/log
--
   070701000003ED000081B400000000000000000000000167AE11140000AF0C000000000000000000000000000000000000006400000000susemanager-schema/upgrade/rhn-satellite-schema-5.1-to-spacewalk-schema-0.2/203-rhn_channel.pkb.sql   --
-- Copyright (c) 2008 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
-- $Id$
--

CREATE OR REPLACE
PACKAGE BODY rhn_channel
IS
	body_version varchar2(100) := '$Id$';

    -- Cursor that fetches all the possible base channels for a
    -- (server_arch_id, release, org_id) combination
	cursor	base_channel_cursor(
		release_in in varchar2,
		server_arch_id_in in number,
		org_id_in in number
	) return rhnChannel%ROWTYPE is
		select distinct c.*
		from	rhnDistChannelMap			dcm,
				rhnServerChannelArchCompat	scac,
				rhnChannel					c,
				rhnChannelPermissions		cp
		where	cp.org_id = org_id_in
			and cp.channel_id = c.id
			and c.parent_channel is null
			and c.id = dcm.channel_id
			and c.channel_arch_id = dcm.channel_arch_id
			and dcm.release = release_in
			and scac.server_arch_id = server_arch_id_in
			and scac.channel_arch_id = c.channel_arch_id;

    FUNCTION get_license_path(channel_id_in IN NUMBER)
    RETURN VARCHAR2
    IS
    	license_val VARCHAR2(1000);
    BEGIN
    	SELECT CFL.license_path INTO license_val
	  FROM rhnChannelFamilyLicense CFL, rhnChannelFamilyMembers CFM
	 WHERE CFM.channel_id = channel_id_in
	   AND CFM.channel_family_id = CFL.channel_family_id;
    
    	RETURN license_val;

    EXCEPTION
    	WHEN NO_DATA_FOUND
	    THEN
	    RETURN NULL;
    END get_license_path;


    PROCEDURE license_consent(channel_id_in IN NUMBER, user_id_in IN NUMBER, server_id_in IN NUMBER)
    IS
    	channel_family_id_val NUMBER;
    BEGIN
    	channel_family_id_val := rhn_channel.family_for_channel(channel_id_in);
	IF channel_family_id_val IS NULL
	THEN
	    rhn_exception.raise_exception('channel_subscribe_no_family');
	END IF;
	
	IF rhn_channel.get_license_path(channel_id_in) IS NULL
	THEN
	    rhn_exception.raise_exception('channel_consent_no_license');
	END IF;
	
	INSERT INTO rhnChannelFamilyLicenseConsent (channel_family_id, user_id, server_id)
	VALUES (channel_family_id_val, user_id_in, server_id_in);
    END license_consent;

    PROCEDURE subscribe_server(server_id_in IN NUMBER, channel_id_in NUMBER, immediate_in NUMBER := 1, user_id_in in number := null)
    IS
        channel_parent_val      rhnChannel.parent_channel%TYPE;
        parent_subscribed       BOOLEAN;
        server_has_base_chan    BOOLEAN;
	server_already_in_chan  BOOLEAN;
	channel_family_id_val   NUMBER;
	server_org_id_val       NUMBER;
	available_subscriptions NUMBER;
	consenting_user         NUMBER;
	allowed			number := 0;
    current_members_val     number;
    BEGIN
    	if user_id_in is not null then
		allowed := rhn_channel.user_role_check(channel_id_in, user_id_in, 'subscribe');
	else
		allowed := 1;
	end if;

	if allowed = 0 then
		rhn_exception.raise_exception('no_subscribe_permissions');
	end if;


        SELECT parent_channel INTO channel_parent_val FROM rhnChannel WHERE id = channel_id_in;

        IF channel_parent_val IS NOT NULL
        THEN    
	    -- child channel; if attempting to cross-subscribe a child to the wrong base, silently ignore
            parent_subscribed := FALSE;    

            FOR check_subscription IN check_server_subscription(server_id_in, channel_parent_val)
            LOOP
                parent_subscribed := TRUE;
            END LOOP check_subscription;
        
            IF NOT parent_subscribed
            THEN
    	    	RETURN;
            END IF;
        ELSE
	    -- base channel
            server_has_base_chan := FALSE;
            FOR base IN server_base_subscriptions(server_id_in)
            LOOP
                server_has_base_chan := TRUE;
            END LOOP base;
            
            IF server_has_base_chan
            THEN
                rhn_exception.raise_exception('channel_server_one_base');
            END IF;
        END IF;
    
        FOR check_subscription IN check_server_subscription(server_id_in, channel_id_in)
        LOOP
            server_already_in_chan := TRUE;
        END LOOP check_subscription;
    
        IF server_already_in_chan
        THEN
    	    RETURN;
        END IF;
	
	channel_family_id_val := rhn_channel.family_for_channel(channel_id_in);
	IF channel_family_id_val IS NULL
	THEN
	    rhn_exception.raise_exception('channel_subscribe_no_family');
	END IF;
	
	SELECT org_id INTO server_org_id_val
	  FROM rhnServer
	 WHERE id = server_id_in;
	 
    select current_members 
    into current_members_val
    from rhnPrivateChannelFamily
    where org_id = server_org_id_val and channel_family_id = channel_family_id_val
    for update of current_members;

	available_subscriptions := rhn_channel.available_family_subscriptions(channel_family_id_val, server_org_id_val);
	
	IF available_subscriptions IS NULL OR 
       available_subscriptions > 0 or
       can_server_consume_virt_channl(server_id_in, channel_family_id_val) = 1
	THEN
	
	    IF rhn_channel.get_license_path(channel_id_in) IS NOT NULL
	    THEN
	    	BEGIN
		
	    	SELECT user_id INTO consenting_user
		  FROM rhnChannelFamilyLicenseConsent
		 WHERE channel_family_id = channel_family_id_val
		   AND server_id = server_id_in;
		
		EXCEPTION
    	    	    WHEN NO_DATA_FOUND
		    	THEN
			    rhn_exception.raise_exception('channel_subscribe_no_consent');
		END;
	    END IF;
	
	    insert into rhnServerHistory (id,server_id,summary,details) (
	    	select	rhn_event_id_seq.nextval,
			server_id_in,
			'subscribed to channel ' || SUBSTR(c.label, 0, 106),
			c.label
		from	rhnChannel c
		where	c.id = channel_id_in
	    );
	    UPDATE rhnServer SET channels_changed = sysdate WHERE id = server_id_in;
            INSERT INTO rhnServerChannel (server_id, channel_id) VALUES (server_id_in, channel_id_in);

    	    rhn_channel.update_family_counts(channel_family_id_val, server_org_id_val);
    	    queue_server(server_id_in, immediate_in);
	ELSE
	    rhn_exception.raise_exception('channel_family_no_subscriptions');
	END IF;
	    
    END subscribe_server;
    
    function can_server_consume_virt_channl(
        server_id_in in number,
        family_id_in in number )
    return number
    is

        cursor server_virt_families is
            select vi.virtual_system_id, cfvsl.channel_family_id
            from
                rhnChannelFamilyVirtSubLevel cfvsl,
                rhnSGTypeVirtSubLevel sgtvsl,
                rhnVirtualInstance vi
            where
                vi.virtual_system_id = server_id_in 
                and sgtvsl.virt_sub_level_id = cfvsl.virt_sub_level_id
                and cfvsl.channel_family_id = family_id_in
                and exists (
                    select 1
                    from rhnServerEntitlementView sev
                    where vi.host_system_id = sev.server_id
                    and sev.server_group_type_id = sgtvsl.server_group_type_id );
    begin

        for server_virt_family in server_virt_families loop
            return 1;
        end loop;

        return 0;

    end;


    PROCEDURE bulk_subscribe_server(channel_id_in IN NUMBER, set_label_in IN VARCHAR2, set_uid_in IN NUMBER)
    IS
    BEGIN
        FOR server IN rhn_set.set_iterator(set_label_in, set_uid_in)
        LOOP
            rhn_channel.subscribe_server(server.element, channel_id_in, 0, set_uid_in);
        END LOOP server;
    END bulk_subscribe_server;

    PROCEDURE bulk_server_base_change(channel_id_in IN NUMBER, set_label_in IN VARCHAR2, set_uid_in IN NUMBER)
    IS
    BEGIN
        FOR server IN rhn_set.set_iterator(set_label_in, set_uid_in)
        LOOP
	    IF rhn_server.can_change_base_channel(server.element) = 1
	    THEN
                rhn_channel.clear_subscriptions(TO_NUMBER(server.element));
                rhn_channel.subscribe_server(server.element, channel_id_in, 0, set_uid_in);
            END IF;
        END LOOP server;
    END bulk_server_base_change;

    procedure bulk_server_basechange_from(
        set_label_in in varchar2,
        set_uid_in in number,
        old_channel_id_in in number,
        new_channel_id_in in number
    ) is
    cursor servers is
        select  sc.server_id id
        from    rhnChannel nc,
                rhnServerChannelArchCompat scac,
                rhnServer s,
                rhnChannel oc,
                rhnServerChannel sc,
                rhnSet st
        where   1=1
            -- first, find the servers we're looking for.
            and st.label = set_label_in
            and st.user_id = set_uid_in
            and st.element = sc.server_id
            -- now, filter out anything that's not in the
            -- old base channel.
            and sc.channel_id = old_channel_id_in
            and sc.channel_id = oc.id
            and oc.parent_channel is null
            -- now, see if it's compatible with the new base channel
            and nc.id = new_channel_id_in
            and nc.parent_channel is null
            and sc.server_id = s.id
            and s.server_arch_id = scac.server_arch_id
            and scac.channel_arch_id = nc.channel_arch_id;
    begin
        for s in servers loop
            insert into rhnSet (
                    user_id, label, element
                ) values (
                    set_uid_in,
                    set_label_in || 'basechange', 
                    s.id
                );
        end loop channel;
        bulk_server_base_change(new_channel_id_in,
                                set_label_in || 'basechange',
                                set_uid_in);
        delete from rhnSet
            where   label = set_label_in||'basechange'
                and user_id = set_uid_in;
    end bulk_server_basechange_from;

    procedure bulk_guess_server_base(
	set_label_in in varchar2,
	set_uid_in in number
    ) is
	channel_id number;
    begin
	for server in rhn_set.set_iterator(set_label_in, set_uid_in)
	loop
	    -- anything that doesn't work, we just ignore
	    begin
	    	if rhn_server.can_change_base_channel(server.element) = 1
		then
    	            channel_id := guess_server_base(TO_NUMBER(server.element));
	    	    rhn_channel.clear_subscriptions(TO_NUMBER(server.element));
	    	    rhn_channel.subscribe_server(TO_NUMBER(server.element), channel_id, 0, set_uid_in);
		end if;
	    exception when others then
	    	null;
	    end;
	end loop server;
    end;

    function guess_server_base(
    	server_id_in in number
    ) RETURN number is
	cursor server_cursor is
	    select s.server_arch_id, s.release, s.org_id
	      from rhnServer s
	     where s.id = server_id_in;
    begin
	for s in server_cursor loop
	    for channel in base_channel_cursor(s.release,
		s.server_arch_id, s.org_id) 
	    loop
		return channel.id;
	    end loop base_channel_cursor;
        end loop server_cursor;
	-- Server not found, or no base channel applies to it
        return null;
    end;

    -- Private function
    function normalize_server_arch(server_arch_in in varchar2)
    return varchar2
    deterministic
    is
	suffix VARCHAR2(128) := '-redhat-linux';
	suffix_len NUMBER := length(suffix);
    begin
	if server_arch_in is NULL then
	    return NULL;
	end if;
        if instr(server_arch_in, '-') > 0
	then
	    -- Suffix already present
	    return server_arch_in;
	end if;
	return server_arch_in || suffix;
    end normalize_server_arch;

    --
    --
    -- Raises: 
    --   server_arch_not_found
    --   no_subscribe_permissions
    function base_channel_for_release_arch(
	release_in in varchar2,
	server_arch_in in varchar2,
	org_id_in in number := -1,
	user_id_in in number := null
    ) return number is
	server_arch varchar2(256) := normalize_server_arch(server_arch_in);
	server_arch_id number;
    begin
	-- Look up the server arch
	begin
	    select id
	      into server_arch_id
	      from rhnServerArch
	     where label = server_arch;
	exception
	    when no_data_found then
		rhn_exception.raise_exception('server_arch_not_found');
	end;
	return base_channel_rel_archid(release_in, server_arch_id,
	    org_id_in, user_id_in);
    end base_channel_for_release_arch;

    function base_channel_rel_archid(
	release_in in varchar2,
	server_arch_id_in in number,
	org_id_in in number := -1,
	user_id_in in number := null
    ) return number is
	denied_channel_id number := null;
	valid_org_id number := org_id_in;
	valid_user_id number := user_id_in;
	channel_subscribable number;
    begin
	if org_id_in = -1 and user_id_in is not null then
	    -- Get the org id from the user id
	    begin
		select org_id
		  into valid_org_id
		  from web_contact
		 where id = user_id_in;
	    exception
		when no_data_found then
		    -- User doesn't exist
		    -- XXX Only list public stuff for now
		    valid_user_id := null;
		    valid_org_id := -1;
	    end;
	end if;

	for c in base_channel_cursor(release_in, server_arch_id_in, valid_org_id)
	loop
	    -- This row is a possible match
	    if valid_user_id is null then
		-- User ID not specified, so no user to channel permissions to
		-- check
		return c.id;
	    end if;

	    -- Check user to channel permissions
	    select loose_user_role_check(c.id, user_id_in, 'subscribe')
	      into channel_subscribable
	      from dual;

	    if channel_subscribable = 1 then
		return c.id;
	    end if;
		
	    -- Base channel exists, but is not subscribable; keep trying
	    denied_channel_id := c.id;
	end loop base_channel_fetch;
	
	if denied_channel_id is not null then
	    rhn_exception.raise_exception('no_subscribe_permissions');
	end if;
	-- No base channel applies
	return NULL;
    end base_channel_rel_archid;

    procedure bulk_guess_server_base_from(
	set_label_in in varchar2,
	set_uid_in in number,
	channel_id_in in number
    ) is
	cursor channels(server_id_in in number) is
	    select	rsc.channel_id
	    from	rhnServerChannel rsc,
			rhnChannel rc
	    where	server_id_in = rsc.server_id
			and rsc.channel_id = rc.id
			and rc.parent_channel is null;
    begin
	for server in rhn_set.set_iterator(set_label_in, set_uid_in)
	loop
	    for channel in channels(server.element)
	    loop
		if channel.channel_id = channel_id_in
		then
		    insert into rhnSet (user_id, label, element) values (set_uid_in, set_label_in || 'baseguess', server.element);
		end if;
	    end loop channel;
	end loop server;
	bulk_guess_server_base(set_label_in||'baseguess',set_uid_in);
	delete from rhnSet where label = set_label_in||'baseguess' and user_id = set_uid_in;
    end;


    PROCEDURE clear_subscriptions(server_id_in IN NUMBER, deleting_server IN NUMBER := 0 )
    IS
    	cursor server_channels(server_id_in in number) is
		select	s.org_id, sc.channel_id, cfm.channel_family_id
		from	rhnServer s,
			rhnServerChannel sc,
			rhnChannelFamilyMembers cfm
		where	s.id = server_id_in
			and s.id = sc.server_id
			and sc.channel_id = cfm.channel_id;
    BEGIN
    	for channel in server_channels(server_id_in)
	loop
		unsubscribe_server(server_id_in, channel.channel_id, 1, 1, deleting_server);
		rhn_channel.update_family_counts(channel.channel_family_id, channel.org_id);
	end loop channel;
    END clear_subscriptions;

    PROCEDURE unsubscribe_server(server_id_in IN NUMBER, channel_id_in NUMBER, immediate_in NUMBER := 1, unsubscribe_children_in number := 0,
                                 deleting_server IN NUMBER := 0 )
    IS
	channel_family_id_val   NUMBER;
	server_org_id_val       NUMBER;
	available_subscriptions NUMBER;	
	server_already_in_chan  BOOLEAN;
	cursor	channel_family_is_proxy(channel_family_id_in in number) is
		select	1
		from	rhnChannelFamily
		where	id = channel_family_id_in
		    and label = 'rhn-proxy';
	cursor	channel_family_is_satellite(channel_family_id_in in number) is
		select	1
		from	rhnChannelFamily
		where	id = channel_family_id_in
		    and label = 'rhn-satellite';
	-- this is *EXACTLY* like check_server_parent_membership, but if we recurse
	-- with the package-level one, we get a "cursor already open", so we need a
	-- copy on our call stack instead.  GROAN.
	cursor local_chk_server_parent_memb (
			server_id_in number,
			channel_id_in number ) is
		select	c.id
		from	rhnChannel			c,
				rhnServerChannel	sc
		where	1=1
			and c.parent_channel = channel_id_in
			and c.id = sc.channel_id
			and sc.server_id = server_id_in;
    BEGIN
        FOR child IN local_chk_server_parent_memb(server_id_in, channel_id_in)
        LOOP
	    if unsubscribe_children_in = 1 then
	    	unsubscribe_server(server_id_in => server_id_in,
								channel_id_in => child.id,
								immediate_in => immediate_in,
								unsubscribe_children_in => unsubscribe_children_in,
                        deleting_server => deleting_server);
	    else
	    	rhn_exception.raise_exception('channel_unsubscribe_child_exists');
	    end if;
        END LOOP child;
	
	server_already_in_chan := FALSE;
    
        FOR check_subscription IN check_server_subscription(server_id_in, channel_id_in)
        LOOP
            server_already_in_chan := TRUE;
        END LOOP check_subscription;
    
        IF NOT server_already_in_chan
        THEN
    	    RETURN;
        END IF;
	
   if deleting_server = 0 then 

      insert into rhnServerHistory (id,server_id,summary,details) (
          select  rhn_event_id_seq.nextval,
                server_id_in,
             'unsubscribed from channel ' || SUBSTR(c.label, 0, 106),
             c.label
          from    rhnChannel c
          where   c.id = channel_id_in
      );

   	UPDATE rhnServer SET channels_changed = sysdate WHERE id = server_id_in;
   end if;
	
   DELETE FROM rhnServerChannel WHERE server_id = server_id_in AND channel_id = channel_id_in;

   if deleting_server = 0 then 
     	queue_server(server_id_in, immediate_in);
   end if;

	channel_family_id_val := rhn_channel.family_for_channel(channel_id_in);
	IF channel_family_id_val IS NULL
	THEN
	    rhn_exception.raise_exception('channel_unsubscribe_no_family');
	END IF;

	for ignore in channel_family_is_satellite(channel_family_id_val) loop
		delete from rhnSatelliteInfo where server_id = server_id_in;
		delete from rhnSatelliteChannelFamily where server_id = server_id_in;
	end loop;

	for ignore in channel_family_is_proxy(channel_family_id_val) loop
		delete from rhnProxyInfo where server_id = server_id_in;
	end loop;

	DELETE FROM rhnChannelFamilyLicenseConsent
	 WHERE channel_family_id = channel_family_id_val
	   AND server_id = server_id_in;
			
	SELECT org_id INTO server_org_id_val
	  FROM rhnServer
	 WHERE id = server_id_in;
	 
	rhn_channel.update_family_counts(channel_family_id_val, server_org_id_val);
    END unsubscribe_server;

    PROCEDURE bulk_unsubscribe_server(channel_id_in IN NUMBER, set_label_in IN VARCHAR2, set_uid_in IN NUMBER)
    IS
    BEGIN
        FOR server IN rhn_set.set_iterator(set_label_in, set_uid_in)
        LOOP
            rhn_channel.unsubscribe_server(server.element, channel_id_in, 0);
        END LOOP server;
    END bulk_unsubscribe_server;

    FUNCTION family_for_channel(channel_id_in IN NUMBER)
    RETURN NUMBER
    IS
    	channel_family_id_val NUMBER;
    BEGIN
    	SELECT channel_family_id INTO channel_family_id_val
	  FROM rhnChannelFamilyMembers
         WHERE channel_id = channel_id_in;
	 
	RETURN channel_family_id_val;
    EXCEPTION
        WHEN NO_DATA_FOUND
	THEN
	    RETURN NULL;
    END family_for_channel;

    FUNCTION available_family_subscriptions(channel_family_id_in IN NUMBER, org_id_in IN NUMBER)
    RETURN NUMBER
    IS
    	cfp channel_family_perm_cursor%ROWTYPE;
    	current_members_val NUMBER;
	max_members_val     NUMBER;
	found               NUMBER;
    BEGIN
	IF NOT channel_family_perm_cursor%ISOPEN
	THEN
	    OPEN channel_family_perm_cursor(channel_family_id_in, org_id_in);
	END IF;

	FETCH channel_family_perm_cursor INTO cfp;
	
	WHILE channel_family_perm_cursor%FOUND
    	LOOP
	    found := 1;
	    
	    current_members_val := cfp.current_members;
	    max_members_val := cfp.max_members;
	    
	    FETCH channel_family_perm_cursor INTO cfp;
	END LOOP;

	IF channel_family_perm_cursor%ISOPEN
	THEN
	    CLOSE channel_family_perm_cursor;
	END IF;

    	-- not found: either the channel fam doesn't have an entry in cfp, or the org doesn't have access to it.
	-- either way, there are no available subscriptions
	
	IF found IS NULL
	THEN
	    RETURN 0;
	END IF;

	-- null max members?  in that case, pass it on; NULL means infinite			
	IF max_members_val IS NULL
	THEN
	    RETURN NULL;
	END IF;

	-- otherwise, return the delta	
	RETURN max_members_val - current_members_val;			
    END available_family_subscriptions;
    
    -- *******************************************************************
    -- FUNCTION: channel_family_current_members
    -- Calculates and returns the actual count of systems consuming
    --   physical channel subscriptions.
    -- Called by: update_family_counts 
    --            rhn_entitlements.repoll_virt_guest_entitlements
    -- *******************************************************************
    function channel_family_current_members(channel_family_id_in IN NUMBER,
                                            org_id_in IN NUMBER)
    return number
    is
        current_members_count number := 0;
    begin
        select	count(sc.server_id)
        into    current_members_count
        from	rhnChannelFamilyMembers cfm,
                rhnServerChannel sc,
                rhnServer s
        where	s.org_id = org_id_in
            and s.id = sc.server_id
            and cfm.channel_family_id = channel_family_id_in
            and cfm.channel_id = sc.channel_id
            and exists ( 
                select 1
                from rhnChannelFamilyServerPhysical cfsp
                where cfsp.CHANNEL_FAMILY_ID = channel_family_id_in
                    and cfsp.server_id = s.id
                );

        return current_members_count;
    end;        

    PROCEDURE update_family_counts(channel_family_id_in IN NUMBER, 
                                   org_id_in IN NUMBER)
    IS
    BEGIN
		update rhnPrivateChannelFamily
		set current_members = (
                channel_family_current_members(channel_family_id_in, org_id_in)
    		)
			where org_id = org_id_in
				and channel_family_id = channel_family_id_in;
    END update_family_counts;
    
    FUNCTION available_chan_subscriptions(channel_id_in IN NUMBER, 
                                          org_id_in IN NUMBER)
    RETURN NUMBER
    IS
	    channel_family_id_val NUMBER;
    BEGIN
    	SELECT channel_family_id INTO channel_family_id_val
	    FROM rhnChannelFamilyMembers
	    WHERE channel_id = channel_id_in;
	 
	    RETURN rhn_channel.available_family_subscriptions(
                           channel_family_id_val, org_id_in);
    END available_chan_subscriptions;

    -- *******************************************************************
    -- PROCEDURE: entitle_customer
    -- Creates a chan fam bucket, or sets max_members for an existing bucket
    -- Called by: rhn_ep.poll_customer_internal
    -- Calls: set_family_maxmembers + update_family_counts if the row
    --        already exists, else it creates it in rhnPrivateChannelFamily.
    -- *******************************************************************
    procedure entitle_customer(customer_id_in in number, 
                               channel_family_id_in in number, 
                               quantity_in in number)
    is
		cursor permissions is
			select	1
			from	rhnPrivateChannelFamily pcf
			where	pcf.org_id = customer_id_in
				and	pcf.channel_family_id = channel_family_id_in; 
    begin
		for perm in permissions loop
			set_family_maxmembers(
				customer_id_in,
				channel_family_id_in,
				quantity_in
			);
			rhn_channel.update_family_counts(
				channel_family_id_in,
				customer_id_in
			);
			return;
		end loop;
        
		insert into rhnPrivateChannelFamily pcf (
				channel_family_id, org_id, max_members, current_members
			) values (
				channel_family_id_in, customer_id_in, quantity_in, 0
			);
    end;

    -- *******************************************************************
    -- PROCEDURE: set_family_maxmembers
    -- Prunes an existing channel family bucket by unsubscribing the
    --   necessary servers and sets max_members.
    -- Called by: rhn_channel.entitle_customer
    -- Calls: unsubscribe_server_from_family
    -- *******************************************************************
    procedure set_family_maxmembers(customer_id_in in number, 
                                    channel_family_id_in in number, 
                                    quantity_in in number)
    is
        cursor servers is
            select  server_id from (
            select	rownum row_number, server_id, modified from (
                select  rcfsp.server_id,
                        rcfsp.modified
                from    rhnChannelFamilyServerPhysical rcfsp
                where   rcfsp.customer_id = customer_id_in
                    and rcfsp.channel_family_id = channel_family_id_in
                order by modified
            )
            where rownum > quantity_in
            );
    begin
	    -- prune subscribed servers
        for server in servers loop
            rhn_channel.unsubscribe_server_from_family(server.server_id, 
                                                       channel_family_id_in);
        end loop;

        update	rhnPrivateChannelFamily pcf
        set	pcf.max_members = quantity_in
        where	pcf.org_id = customer_id_in
            and pcf.channel_family_id = channel_family_id_in;
    end;

    procedure unsubscribe_server_from_family(server_id_in in number, 
                                             channel_family_id_in in number)
    is
    begin
        delete
        from	rhnServerChannel rsc
        where	rsc.server_id = server_id_in
            and channel_id in (
                select	rcfm.channel_id
                from	rhnChannelFamilyMembers rcfm
                where	rcfm.channel_family_id = channel_family_id_in);
    end;

    function get_org_id(channel_id_in in number)
    return number
    is
    	org_id_out number;
    begin
    	select org_id into org_id_out
	    from rhnChannel
	    where id = channel_id_in;
	 
	    return org_id_out;
    end get_org_id;
    
    function get_cfam_org_access(cfam_id_in in number, org_id_in in number)
    return number
    is
    	cursor	families is
			select	1
			from	rhnOrgChannelFamilyPermissions cfp
			where	cfp.org_id = org_id_in;
    begin
		-- the idea: if we get past this query, 
        -- the user has the role, else catch the exception and return 0
		for family in families loop
	    	return 1;
		end loop;
		return 0;
    end;

    function get_org_access(channel_id_in in number, org_id_in in number)
    return number
    is
    	throwaway number;
    begin
    	-- the idea: if we get past this query, 
        -- the org has access to the channel, else catch the exception and return 0
        select distinct 1 into throwaway
          from rhnChannelFamilyMembers CFM,
               rhnOrgChannelFamilyPermissions CFP
         where cfp.org_id = org_id_in
           and CFM.channel_family_id = CFP.channel_family_id
           and CFM.channel_id = channel_id_in
           and (CFP.max_members > 0 or CFP.max_members is null or CFP.org_id = 1);
           
        return 1;
        exception
            when no_data_found
            then
            return 0;
    end;
    
    -- check if a user has a given role, or if such a role is inferrable
    function user_role_check_debug(channel_id_in in number, 
                                   user_id_in in number, 
                                   role_in in varchar2, 
                                   reason_out out varchar2)
    return number
    is
    	org_id number;
    begin
    	org_id := rhn_user.get_org_id(user_id_in);
	
    	if role_in = 'manage' and 
           NVL(rhn_channel.get_org_id(channel_id_in), -1) <> org_id then
	        reason_out := 'channel_not_owned';
	       return 0;
	    end if;
	
    	if role_in = 'subscribe' and 
           rhn_channel.get_org_access(channel_id_in, org_id) = 0 then
	        reason_out := 'channel_not_available';
	        return 0;
	    end if;
	
    	-- channel admins have all roles
    	if rhn_user.check_role_implied(user_id_in, 'channel_admin') = 1 then
            reason_out := 'channel_admin';
            return 1;
	    end if;

	-- the subscribe permission is inferred 
    -- UNLESS the not_globally_subscribable flag is set	
	if role_in = 'subscribe'
	then
	    if rhn_channel.org_channel_setting(channel_id_in, 
                       org_id,
                       'not_globally_subscribable') = 0 then
	    	reason_out := 'globally_subscribable';
		    return 1;
	    end if;
	end if;
	
	-- all other roles (manage right now) are explicitly granted	
	reason_out := 'direct_permission';
	return rhn_channel.direct_user_role_check(channel_id_in, 
                                              user_id_in, role_in);
    end;
    
    -- same as above, but with no OUT param; useful in views, etc
    function user_role_check(channel_id_in in number, user_id_in in number, role_in in varchar2)
    return number
    is
  	throwaway varchar2(256);
    begin
    	return rhn_channel.user_role_check_debug(channel_id_in, user_id_in, role_in, throwaway);
    end;

    -- same as above, but returns 1 if user_id_in is null
    -- This is useful in queries where user_id is not specified
    function loose_user_role_check(channel_id_in in number, user_id_in in number, role_in in varchar2)
    return number
    is
    begin
        if user_id_in is null then
            return 1;
        end if;
        return user_role_check(channel_id_in, user_id_in, role_in);
    end loose_user_role_check;
    
    -- directly checks the table, no inferred permissions
    function direct_user_role_check(channel_id_in in number, user_id_in in number, role_in in varchar2)
    return number
    is
    	throwaway number;
    begin
    	-- the idea: if we get past this query, the user has the role, else catch the exception and return 0
	select 1 into throwaway
	  from rhnChannelPermissionRole CPR,
	       rhnChannelPermission CP
	 where CP.user_id = user_id_in
	   and CP.channel_id = channel_id_in
	   and CPR.label = role_in
	   and CP.role_id = CPR.id;
	   
	return 1;
    exception
    	when no_data_found
	    then
	    return 0;
    end;
    
    -- check if an org has a certain setting
    function org_channel_setting(channel_id_in in number, org_id_in in number, setting_in in varchar2)
    return number
    is
    	throwaway number;
    begin
    	-- the idea: if we get past this query, the org has the setting, else catch the exception and return 0
	select 1 into throwaway
	  from rhnOrgChannelSettingsType OCST,
	       rhnOrgChannelSettings OCS
	 where OCS.org_id = org_id_in
	   and OCS.channel_id = channel_id_in
	   and OCST.label = setting_in
	   and OCS.setting_id = OCST.id;
	   
	return 1;
    exception
    	when no_data_found
	    then
	    return 0;
    end;
    
    FUNCTION channel_priority(channel_id_in IN number) 
    RETURN number
    IS
         channel_name varchar2(64);
         priority number;
         end_of_life_val date;
         org_id_val number;
    BEGIN

        select name, end_of_life, org_id
        into channel_name, end_of_life_val, org_id_val
        from rhnChannel
        where id = channel_id_in;

        if end_of_life_val is not null then
          return -400;
        end if;

        if channel_name like 'Red Hat Enterprise Linux%' or channel_name like 'RHEL%' then
          priority := 1000;
          if channel_name not like '%Beta%' then
            priority := priority + 1000;
          end if;

          priority := priority +
            case
              when channel_name like '%v. 5%' then 600
              when channel_name like '%v. 4%' then 500
              when channel_name like '%v. 3%' then 400
              when channel_name like '%v. 2%' then 300
              when channel_name like '%v. 1%' then 200
              else 0
            end;

          priority := priority +
            case
              when channel_name like 'Red Hat Enterprise Linux (v. 5%' then 60
              when (channel_name like '%AS%' and channel_name not like '%Extras%') then 50
              when (channel_name like '%ES%' and channel_name not like '%Extras%') then 40
              when (channel_name like '%WS%' and channel_name not like '%Extras%') then 30
              when (channel_name like '%Desktop%' and channel_name not like '%Extras%') then 20
              when channel_name like '%Extras%' then 10
              else 0
            end; 

          priority := priority +
            case
              when channel_name like '%)' then 5
              else 0
            end;

          priority := priority +
            case
              when channel_name like '%32-bit x86%' then 4
              when channel_name like '%64-bit Intel Itanium%' then 3
              when channel_name like '%64-bit AMD64/Intel EM64T%' then 2
              else 0
            end;
        elsif channel_name like 'Red Hat Desktop%' then
            priority := 900;

            if channel_name not like '%Beta%' then
               priority := priority + 50;
            end if;
 
          priority := priority +
            case
              when channel_name like '%v. 4%' then 40
              when channel_name like '%v. 3%' then 30
              when channel_name like '%v. 2%' then 20
              when channel_name like '%v. 1%' then 10
              else 0
            end;
            
          priority := priority +
            case
              when channel_name like '%32-bit x86%' then 4
              when channel_name like '%64-bit Intel Itanium%' then 3
              when channel_name like '%64-bit AMD64/Intel EM64T%' then 2
              else 0
            end;
         
        elsif org_id_val is not null then
          priority := 600;
        else
          priority := 500;
        end if;
      
      return -priority;

    end channel_priority;

    -- right now this only does the accounting changes; the cascade
    -- actually does the rhnServerChannel delete.
    procedure delete_server_channels(server_id_in in number)
    is
    begin
	update	rhnPrivateChannelFamily
	set	current_members = current_members -1
	where	org_id in (
			select	org_id
			from	rhnServer
			where	id = server_id_in
		)
		and channel_family_id in (
			select	rcfm.channel_family_id
			from	rhnChannelFamilyMembers rcfm,
				rhnServerChannel rsc
			where	rsc.server_id = server_id_in
				and rsc.channel_id = rcfm.channel_id
                and not exists (
                    select 1
                    from
                        rhnChannelFamilyVirtSubLevel cfvsl,
                        rhnSGTypeVirtSubLevel sgtvsl,
                        rhnServerEntitlementView sev,
                        rhnVirtualInstance vi
                    where
                        -- system is a virtual instance
                        vi.virtual_system_id = server_id_in
                        and vi.host_system_id = sev.server_id
                        -- system's host has a virt ent
                        and sev.label in ('virtualization_host',
                                          'virtualization_host_platform')
                        and sev.server_group_type_id = 
                            sgtvsl.server_group_type_id
                        -- the host's virt ent grants a cf virt sub level
                        and sgtvsl.virt_sub_level_id = cfvsl.virt_sub_level_id
                        -- the cf is in that virt sub level
                        and cfvsl.channel_family_id = rcfm.channel_family_id
                    )
		);
    end;

	-- this could certainly be optimized to do updates if needs be
	procedure refresh_newest_package(channel_id_in in number, caller_in in varchar2 := '(unknown)')
	is
	begin
		delete from rhnChannelNewestPackage where channel_id = channel_id_in;
		insert into rhnChannelNewestPackage
			( channel_id, name_id, evr_id, package_id, package_arch_id ) 
			(	select	channel_id,
						name_id, evr_id,
						package_id, package_arch_id
				from	rhnChannelNewestPackageView
				where	channel_id = channel_id_in
			);
                insert into rhnChannelNewestPackageAudit (channel_id, caller)
                    values (channel_id_in, caller_in);
                update rhnChannel 
                    set last_modified = greatest(sysdate, last_modified + 1/86400)
                    where id = channel_id_in; 
	end;

   procedure update_channel ( channel_id_in in number, invalidate_ss in number := 0, 
                              date_to_use in date := sysdate )
   is

   channel_last_modified date;
   last_modified_value date;

   cursor snapshots is
   select  snapshot_id id
   from    rhnSnapshotChannel
   where   channel_id = channel_id_in;

   begin

      select last_modified
      into channel_last_modified
      from rhnChannel
      where id = channel_id_in;
  
      last_modified_value := date_to_use;

      if last_modified_value <= channel_last_modified then
          last_modified_value := last_modified_value + 1/86400;
      end if;

      update rhnChannel set last_modified = last_modified_value
      where id = channel_id_in;

      if invalidate_ss = 1 then 
        for snapshot in snapshots loop
            update rhnSnapshot
            set invalid = lookup_snapshot_invalid_reason('channel_modified')
            where id = snapshot.id;
        end loop;
      end if;

   end update_channel;

   procedure update_channels_by_package ( package_id_in in number, date_to_use in date := sysdate )
   is

   cursor channels is
   select channel_id
   from rhnChannelPackage
   where package_id = package_id_in
   order by channel_id;

   begin
      for channel in channels loop
         -- we want to invalidate the snapshot assocated with the channel when we
         -- do this b/c we know we've added or removed or packages
         rhn_channel.update_channel ( channel.channel_id, 1, date_to_use );
      end loop;
   end update_channels_by_package;

   
   procedure update_channels_by_errata ( errata_id_in number, date_to_use in date := sysdate )
   is

   cursor channels is
   select channel_id
   from rhnChannelErrata
   where errata_id = errata_id_in
   order by channel_id;

   begin
      for channel in channels loop
         -- we won't invalidate snapshots, b/c just changing the errata associated with
         -- a channel shouldn't invalidate snapshots
         rhn_channel.update_channel ( channel.channel_id, 0, date_to_use );
      end loop;
   end update_channels_by_errata;

END rhn_channel;
/
SHOW ERRORS

-- $Log$
-- Revision 1.75  2005/03/04 00:04:19  jslagle
-- bz #147617
-- Made Red Hat Desktop sort a little better.
--
-- Revision 1.74  2005/02/22 03:24:47  jslagle
-- bz #147617
-- Improve channel_priority function to order channels better.
--
-- Revision 1.73  2004/08/16 20:39:30  pjones
-- bugzilla: 129889 -- make bulk_server_basechange_from() actually work.
--
-- Revision 1.72  2004/04/14 00:09:24  pjones
-- bugzilla: 120761 -- split rhnChannelPermissions into two tables, eliminating
-- a frequent full table scan
--
-- Revision 1.71  2004/04/13 16:28:36  bretm
-- bugzilla:  119871
--
-- keep track of rhnServer.channels_changed through the pl/sql fns
--
-- Revision 1.70  2004/03/26 18:11:32  rbb
-- Bugzilla:  114057
--
-- Add a script to determine channel priority.
--
-- Revision 1.69  2004/02/17 20:16:52  pjones
-- bugzilla: none -- add cvs tags into the package as long as we're touching
-- it anyway
--
-- Revision 1.68  2004/02/17 20:05:38  pjones
-- bugzilla: 115782 -- make bulk_server_basechange_from() filter out servers
-- with arches incompatible with the target channel
--
-- Revision 1.67  2004/02/06 02:36:10  misa
-- Changed normalize_server_arch to allow for solaris arches
--
-- Revision 1.66  2003/11/13 16:58:34  cturner
-- make use of new rhn_user.check_role_implied call; pragmas broke, removed them for now since I have no idea how to fix them
--
-- Revision 1.65  2003/10/23 20:26:24  bretm
-- bugzilla:  none
--
-- note the channel label when we unsubscribe, too
--
-- Revision 1.64  2003/10/15 14:47:17  bretm
-- bugzilla:  none
--
-- add the channel label to the server history summary line when we log a channel change
--
-- Revision 1.63  2003/09/24 19:25:56  pjones
-- this wasn't the right fix, put it back
--
-- Revision 1.62  2003/09/24 17:42:19  pjones
-- bugzilla: none
--
-- limit our server base channel guess to channels with available permissions
--
-- Revision 1.61  2003/09/22 21:00:40  cturner
-- add method for easy acl check
--
-- Revision 1.60  2003/09/17 22:14:11  misa
-- bugzilla: 103639  Changes to allow me to move the base channel guess into plsql
--
-- Revision 1.59  2003/08/21 13:41:17  cturner
-- bugzilla: 99187.  properly test for satellite and proxy in bulk_guess_server_base; reorg code for better reuse
--
-- Revision 1.58  2003/07/24 16:46:22  cturner
-- bugzilla: 100723, the perm check was returning duplicates, so now it just calls the function it should have called anyway
--
-- Revision 1.57  2003/07/24 16:44:16  misa
-- bugzilla: none  A function more usable on the rhnapp side
--
-- Revision 1.56  2003/07/23 22:36:51  cturner
-- argh, max returns null even when now rows; use distinct.  how revolting
--
-- Revision 1.55  2003/07/23 22:01:31  cturner
-- oops, this one can return multiple rows; eliminate that in a lazy way
--
-- Revision 1.54  2003/07/23 21:59:19  cturner
-- rework how rhnUserChannel works; move to plsql for speed and maintenance
--
-- Revision 1.53  2003/07/21 17:49:12  pjones
-- bugzilla: none
--
-- add optional user for subscribe_server
--
-- Revision 1.52  2003/07/14 22:19:29  misa
-- bugzilla: none  Updating guess_base_channel to work more like the rhnapp server code
--
-- Revision 1.51  2003/06/26 22:09:04  pjones
-- bugzilla: none
--
-- log subscribe and unsubscribe
--
-- Revision 1.50  2003/06/05 19:31:15  pjones
-- bugzilla: 88278 -- make the cursor name smaller
--
-- Revision 1.49  2003/06/05 19:18:21  pjones
-- bugzilla: 88278
--
-- unsubscribe_server() opens the package-level cursor when it invokes itself,
-- so we're using a local copy instead.
--
-- Revision 1.48  2003/06/04 16:41:39  pjones
-- bugzilla: none
--
-- make bulk_guess_server_base() silently ignore unguessables
--
-- Revision 1.47  2003/06/04 16:27:03  pjones
-- bugzilla: 88822
--
-- eliminate the last outliers that remove things from channels without using
-- unsubscribe_server, I think.
--
-- Revision 1.46  2003/06/03 20:49:37  pjones
-- bugzilla: 88822
-- unsubscribing from rhn-satellite now clears rhnSatelliteChannelFamily
-- for the server in question
--
-- Revision 1.45  2003/06/02 20:41:45  pjones
-- bugzilla: none - fix rhnProxyInfo/rhnSatelliteInfo channel unsubscribe
-- problem.  Basicly, if you're out of the channel for any reason, you're
-- also out of rhnProxyInfo/rhnProxyInfo
--
-- Revision 1.44  2003/03/24 15:26:28  pjones
-- bugzilla: 85812
--
-- bulk_server_base_change silently ignores servers that are satellites
-- or proxies, as requested.
--
-- Revision 1.43  2003/02/26 20:28:17  pjones
-- rhn_channel.update_family_counts() in rhn_channel.entitle_customer()
-- the old codepath is:
--
-- ep ->
-- rhn_ep.entitlement_run_me() ->
-- rhn_ep.poll_customer() ->
-- rhn_channel.entitle_customer()
--
-- which doesn't change current_members, even though it may remove servers
-- from the family.
--
-- There's another bug here:  currently, we don't try to order forced
-- unsubscribes in any way; we just use
-- rhn_channel.unsubscribe_server_from_family .  If there are any child
-- channel subscriptions, this will leave them subscribed.  We really need
-- to iterate across the channels again, and subscribe any channel for which
-- there are no parent channel subscriptions.
--
-- Ugh.
--
-- Revision 1.42  2003/01/28 00:19:45  pjones
-- fix clear_subscriptions; AFAICT, this is only hit on the
-- bulk_server_base_change / bulk_server_base_guess codepaths, which puts
-- it infrequent enough that it could be our "bad count" culprit.
--
-- Revision 1.41  2003/01/14 19:51:45  pjones
-- make setting current_members on rhnChannelFamilyPermissions work when
-- a server is in more than one channel in a single family.
070701000003EE000081B400000000000000000000000167AE111400001672000000000000000000000000000000000000006900000000susemanager-schema/upgrade/rhn-satellite-schema-5.1-to-spacewalk-schema-0.2/204-rhn_entitlements.pks.sql  --
-- Copyright (c) 2008 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
-- $Id$
--

create or replace
package rhn_entitlements
is
	body_version varchar2(100) := '$Id$';

   type ents_array is varray(10) of rhnServerGroupType.label%TYPE;

    procedure remove_org_entitlements (
        org_id_in number
    );

    function entitlement_grants_service (
	    entitlement_in in varchar2,
		service_level_in in varchar2
	) return number;

	function lookup_entitlement_group (
		org_id_in in number,
		type_label_in in varchar2 := 'sw_mgr_entitled'
	) return number;

	function create_entitlement_group (
		org_id_in in number,
		type_label_in in varchar2 := 'sw_mgr_entitled'
	) return number;

   function can_entitle_server ( 
      server_id_in   in number, 
      type_label_in  in varchar2
   )
   return number;

   function can_switch_base ( 
      server_id_in   in    integer, 
      type_label_in  in    varchar2
   )
   return number;

   function find_compatible_sg (
      server_id_in in number,
      type_label_in in varchar2,
      sgid_out out number
   )
   return boolean;

	procedure entitle_server (
		server_id_in in number,
		type_label_in in varchar2 := 'sw_mgr_entitled'
	);

	procedure remove_server_entitlement (
		server_id_in in number,
		type_label_in in varchar2 := 'sw_mgr_entitled',
        repoll_virt_guests in number := 1
	);

	procedure unentitle_server (
		server_id_in in number
	);

    procedure repoll_virt_guest_entitlements(
        server_id_in in number
    );

	function get_server_entitlement (
		server_id_in in number
	) return ents_array;

	procedure modify_org_service (
		org_id_in in number,
		service_label_in in varchar2,
		enable_in in char
	);

    procedure set_customer_enterprise (
		customer_id_in in number
	);

	procedure set_customer_provisioning (
		customer_id_in in number
	);

	procedure set_customer_nonlinux (
		customer_id_in in number
	);

    procedure unset_customer_enterprise (
		customer_id_in in number
	);

	procedure unset_customer_provisioning (
		customer_id_in in number
	);

	procedure unset_customer_nonlinux (
		customer_id_in in number
	);

    procedure assign_system_entitlement(
        group_label_in in varchar2,
        from_org_id_in in number,
        to_org_id_in in number,
        quantity_in in number
    );

    procedure assign_channel_entitlement(
        channel_family_label_in in varchar2,
        from_org_id_in in number,
        to_org_id_in in number,
        quantity_in in number
    );

    procedure activate_system_entitlement(
        org_id_in in number,
        group_label_in in varchar2,
        quantity_in in number
    );

    procedure activate_channel_entitlement(
        org_id_in in number,
        channel_family_label_in in varchar2,
        quantity_in in number
    );

    procedure set_group_count (
		customer_id_in in number,	-- customer_id
		type_in in char,			-- 'U' or 'S'
		group_type_in in number,	-- rhn[User|Server]GroupType.id
		quantity_in in number		-- quantity
    );

    procedure set_family_count (
		customer_id_in in number,		-- customer_id
		channel_family_id_in in number,	-- 246
		quantity_in in number			-- 3
    );

    -- this makes NO checks that the quantity is within max,
    -- so we should NEVER run this unless we KNOW that we won't be
    -- violating the max
    procedure entitle_last_modified_servers (
		customer_id_in in number,	-- customer_id
		type_label_in in varchar2,	-- 'enterprise_entitled'
		quantity_in in number		-- 3
    );

	procedure prune_everything (
		customer_id_in in number
	);

	procedure subscribe_newest_servers (
		customer_id_in in number
	);
end rhn_entitlements;
/
show errors

-- $Log$
-- Revision 1.19  2004/05/26 19:45:48  pjones
-- bugzilla: 123639
-- 1) reformat "entitlement_grants_service"
-- 2) make the .pks and .pkb be in the same order.
-- 3) add "modify_org_service" (to be used instead of set_customer_SERVICELEVEL)
-- 4) add monitoring specific data.
--
-- Revision 1.18  2004/02/19 20:17:49  pjones
-- bugzilla: 115896 -- add sgt and oet data for nonlinux, add
-- [un]set_customer_nonlinux
--
-- Revision 1.17  2004/01/13 23:37:08  pjones
-- bugzilla: none -- mate provisioning and management slots.
--
-- Revision 1.16  2003/09/23 22:14:41  bretm
-- bugzilla:  103655
--
-- need something in the db that knows provisioning boxes are management boxes too, etc.
--
-- Revision 1.15  2003/09/19 22:35:07  pjones
-- bugzilla: none
--
-- provisioning and config management entitlement support
--
-- Revision 1.14  2003/09/02 22:22:54  pjones
-- bugzilla: none
--
-- attempt to autoentitle upon entitlement changes
--
-- Revision 1.13  2003/06/05 21:43:40  pjones
-- bugzilla: none
--
-- add rhn_entitlements.prune_everything(customer_id_in in number);
--
-- Revision 1.12  2003/05/22 16:01:14  pjones
-- reformat
-- remove update_[server|user]group_counts (unused)
--
-- Revision 1.11  2002/06/03 16:07:29  pjones
-- make prune_group and prune_family update respective max_members
-- correctly.
--
-- Revision 1.10  2002/05/29 19:10:31  pjones
-- code to entitle the last N modified servers to a particular service
-- level
--
-- Revision 1.9  2002/05/10 22:08:23  pjones
-- id/log
--
  070701000003EF000081B400000000000000000000000167AE11140000DC4C000000000000000000000000000000000000006900000000susemanager-schema/upgrade/rhn-satellite-schema-5.1-to-spacewalk-schema-0.2/205-rhn_entitlements.pkb.sql  --
-- Copyright (c) 2008 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
-- $Id$
--

create or replace
package body rhn_entitlements
is
	body_version varchar2(100) := '$Id$';


    -- *******************************************************************
    -- PROCEDURE: remove_org_entitlements
    --
    -- Removes both system entitlements and channel subscriptions
    -- that are currently assigned to an org and re-assigns to the
    -- master org (org_id = 1).
    --
    -- When we call this we expect everything to already be unentitled
    -- which shoul be handled by delete_org.
    --
    -- Called by: delete_org
    -- *******************************************************************
    procedure remove_org_entitlements(
        org_id_in in number
    )
    is

        cursor system_ents is
        select sg.id, sg.max_members, sg.group_type
        from rhnServerGroup sg
        where group_type is not null
          and org_id = org_id_in;

        cursor channel_subs is
        select pcf.channel_family_id, pcf.max_members
        from rhnChannelFamily cf,
             rhnPrivateChannelFamily pcf
        where pcf.org_id = org_id_in
          and pcf.channel_family_id = cf.id
          and cf.org_id is null;

    begin

        for system_ent in system_ents loop
            update rhnServerGroup
            set max_members = max_members + system_ent.max_members
            where org_id = 1
              and group_type = system_ent.group_type;
        end loop;

        update rhnServerGroup
        set max_members = 0
        where org_id = org_id_in;

        for channel_sub in channel_subs loop
            update rhnPrivateChannelFamily
            set max_members = max_members + channel_sub.max_members
            where org_id = 1
              and channel_family_id = channel_sub.channel_family_id;
        end loop;
        
        update rhnPrivateChannelFamily
        set max_members = 0
        where org_id = org_id_in;

    end remove_org_entitlements;
 
	function entitlement_grants_service (
	    entitlement_in in varchar2,
	    service_level_in in varchar2
	) return number	is
	begin
		if service_level_in = 'provisioning' then
			if entitlement_in = 'provisioning_entitled' then
				return 1;
			else
				return 0;
			end if;
		elsif service_level_in = 'management' then
			if entitlement_in = 'enterprise_entitled' then
				return 1;
			else
				return 0;
			end if;
		elsif service_level_in = 'monitoring' then
			if entitlement_in = 'monitoring_entitled' then
				return 1;
			end if;
		elsif service_level_in = 'updates' then
			return 1;			
		else
			return 0;
		end if;
	end entitlement_grants_service;

	function lookup_entitlement_group (
		org_id_in in number,
		type_label_in in varchar2 := 'sw_mgr_entitled'
	) return number is
		cursor server_groups is
			select	sg.id				server_group_id
			from	rhnServerGroup		sg,
					rhnServerGroupType	sgt
			where	sgt.label = type_label_in
				and sgt.id = sg.group_type
				and sg.org_id = org_id_in;
	begin
		for sg in server_groups loop
			return sg.server_group_id;
		end loop;
		return rhn_entitlements.create_entitlement_group(
				org_id_in, 
				type_label_in
			);
	end lookup_entitlement_group;

	function create_entitlement_group (
		org_id_in in number,
		type_label_in in varchar2 := 'sw_mgr_entitled'
	) return number is
		sg_id_val number;
	begin
		select	rhn_server_group_id_seq.nextval
		into	sg_id_val
		from	dual;

		insert into rhnServerGroup (
				id, name, description, max_members, current_members,
				group_type, org_id
			) (
				select	sg_id_val, sgt.label, sgt.label,
						0, 0, sgt.id, org_id_in
				from	rhnServerGroupType sgt
				where	sgt.label = type_label_in
			);

		return sg_id_val;
	end create_entitlement_group;

   function can_entitle_server ( 
        server_id_in in number, 
        type_label_in in varchar2 ) 
   return number is
      cursor addon_servergroups (base_label_in in varchar2, 
                                 addon_label_in in varchar2) is
         select
            addon_id
         from
            rhnSGTypeBaseAddonCompat
         where base_id = lookup_sg_type (base_label_in)
           and addon_id = lookup_sg_type (addon_label_in);

      previous_ent        rhn_entitlements.ents_array;
      is_base_in          char   := 'N';
      is_base_current     char   := 'N';
      i                   number := 0;
      sgid                number := 0;

   begin

      previous_ent := rhn_entitlements.ents_array();
      previous_ent := rhn_entitlements.get_server_entitlement(server_id_in);

      select distinct is_base
      into is_base_in
      from rhnServerGroupType
      where label = type_label_in;

      if previous_ent.count = 0 then
         if (is_base_in = 'Y' and rhn_entitlements.find_compatible_sg (server_id_in, type_label_in, sgid)) then
            -- rhn_server.insert_into_servergroup (server_id_in, sgid);
            return 1;
         else
            -- rhn_exception.raise_exception ('invalid_base_entitlement');
            return 0;
         end if;

      -- there are previous ents, first make sure we're not trying to entitle a base ent
      elsif is_base_in = 'Y' then
         -- rhn_exception.raise_exception ('invalid_addon_entitlement');
         return 0;

      -- it must be an addon, so proceed with the entitlement
      else

         -- find the servers base ent
         is_base_current := 'N';
         i := 0;
         while is_base_current = 'N' and i <= previous_ent.count
         loop
            i := i + 1;
            select is_base
            into is_base_current
            from rhnServerGroupType
            where label = previous_ent(i);
         end loop;

         -- never found a base ent, that would be strange
         if is_base_current  = 'N' then
            -- rhn_exception.raise_exception ('invalid_base_entitlement');
            return 0;
         end if;

         -- this for loop verifies the validity of the addon path
         for addon_servergroup in addon_servergroups  (previous_ent(i), type_label_in) loop
            -- find an appropriate sgid for the addon and entitle the server
            if rhn_entitlements.find_compatible_sg (server_id_in, type_label_in, sgid) then
               -- rhn_server.insert_into_servergroup (server_id_in, sgid);
               return 1;
            else
               -- rhn_exception.raise_exception ('invalid_addon_entitlement');
               return 0;
            end if;
         end loop;

      end if;

      return 0;

   end can_entitle_server;

   function can_switch_base (
      server_id_in   in    integer,
      type_label_in  in    varchar2
   ) return number is

      type_label_in_is_base   char(1);
      sgid                    number;

   begin

      begin
         select is_base into type_label_in_is_base
         from rhnServerGroupType
         where label = type_label_in;
      exception
         when no_data_found then
            rhn_exception.raise_exception ( 'invalid_entitlement' );
      end;

      if type_label_in_is_base = 'N' then
         rhn_exception.raise_exception ( 'invalid_entitlement' );
      elsif rhn_entitlements.find_compatible_sg ( server_id_in, 
                                                  type_label_in, sgid ) then
         return 1;
      else
         return 0;
      end if;

   end can_switch_base;


   function find_compatible_sg (
      server_id_in    in   number,
      type_label_in   in   varchar2,
      sgid_out        out  number
   ) return boolean is

      cursor servergroups is
         select sg.id            id
           from rhnServerGroupType             sgt,
                rhnServerGroup                 sg,
                rhnServer                     s,
                rhnServerServerGroupArchCompat ssgac
          where s.id = server_id_in
            and s.org_id = sg.org_id
            and sgt.label = type_label_in
            and sg.group_type = sgt.id
            and ssgac.server_group_type = sgt.id
            and ssgac.server_arch_id = s.server_arch_id
            and not exists ( 
                     select 1
                      from rhnServerGroupMembers sgm
                     where sgm.server_group_id = sg.id 
                       and sgm.server_id = s.id);

         
   begin
      for servergroup in servergroups loop
         sgid_out := servergroup.id;
         return true;      
      end loop;

      --no servergroup found
      sgid_out := 0;
      return false;
   end find_compatible_sg;

	procedure entitle_server (
		server_id_in in number,
		type_label_in in varchar2 := 'sw_mgr_entitled'
	) is
      sgid  number := 0;
      is_virt number := 0;

	begin

          begin
          select 1 into is_virt
            from rhnServerEntitlementView
           where server_id = server_id_in
             and label in ('virtualization_host', 'virtualization_host_platform');
	  exception
            when no_data_found then
              is_virt := 0;
          end;
      
      if is_virt = 0 and (type_label_in = 'virtualization_host' or
                          type_label_in = 'virtualization_host_platform') then

        is_virt := 1;
      end if;



      if rhn_entitlements.can_entitle_server(server_id_in, 
                                             type_label_in) = 1 then
         if rhn_entitlements.find_compatible_sg (server_id_in, 
                                                 type_label_in, sgid) then
            insert into rhnServerHistory ( id, server_id, summary, details )
            values ( rhn_event_id_seq.nextval, server_id_in,
                     'added system entitlement ',
                      case type_label_in
                       when 'enterprise_entitled' then 'Management'
                       when 'sw_mgr_entitled' then 'Update'
                       when 'provisioning_entitled' then 'Provisioning'
                       when 'monitoring_entitled' then 'Monitoring'  
                       when 'virtualization_host' then 'Virtualization'
                       when 'virtualization_host_platform' then 
                            'Virtualization Platform' end  );

            rhn_server.insert_into_servergroup (server_id_in, sgid);

            if is_virt = 1 then
              rhn_entitlements.repoll_virt_guest_entitlements(server_id_in);
            end if;

         else
            rhn_exception.raise_exception ('no_available_server_group');
         end if;
      else
         rhn_exception.raise_exception ('invalid_entitlement');
      end if;
   end entitle_server;

	procedure remove_server_entitlement (
		server_id_in in number,
		type_label_in in varchar2 := 'sw_mgr_entitled',
        repoll_virt_guests in number := 1
	) is
		group_id number;
      type_is_base char;
      is_virt number := 0;
	begin
      begin


      -- would be nice if there were a virt attribute of entitlement types, not have to specify 2 different ones...
        begin
          select 1 into is_virt
            from rhnServerEntitlementView
           where server_id = server_id_in
             and label in ('virtualization_host', 'virtualization_host_platform');
        exception
          when no_data_found then
            is_virt := 0;
        end;

		select	sg.id, sgt.is_base
  		into	group_id, type_is_base
  		from	rhnServerGroupType sgt,
   			rhnServerGroup sg,
  				rhnServerGroupMembers sgm,
  				rhnServer s
  		where	s.id = server_id_in
  			and s.id = sgm.server_id
  			and sgm.server_group_id = sg.id
  			and sg.org_id = s.org_id
  			and sgt.label = type_label_in
  			and sgt.id = sg.group_type;

      if ( type_is_base = 'Y' ) then
         -- unentitle_server should handle everything, don't really need to do anything else special here
         unentitle_server ( server_id_in );
      else

         insert into rhnServerHistory ( id, server_id, summary, details )
         values ( rhn_event_id_seq.nextval, server_id_in,
                  'removed system entitlement ',
                   case type_label_in
                    when 'enterprise_entitled' then 'Management'
                    when 'sw_mgr_entitled' then 'Update'
                    when 'provisioning_entitled' then 'Provisioning'
                    when 'monitoring_entitled' then 'Monitoring'
                    when 'virtualization_host' then 'Virtualization'
                    when 'virtualization_host_platform' then 
                         'Virtualization Platforrm' end  );

         rhn_server.delete_from_servergroup(server_id_in, group_id);

         -- special case: clean up related monitornig data
         if type_label_in = 'monitoring_entitled' then
           DELETE
             FROM state_change
            WHERE o_id IN (SELECT probe_id
                             FROM rhn_check_probe
                            WHERE host_id = server_id_in);
           DELETE
             FROM time_series
            WHERE SUBSTR(o_id, INSTR(o_id, '-') + 1, 
                        (INSTR(o_id, '-', INSTR(o_id, '-') + 1) - INSTR(o_id, '-')) - 1)
              IN (SELECT probe_id
                    FROM rhn_check_probe
                   WHERE host_id = server_id_in);
           DELETE
             FROM rhn_probe
            WHERE recid IN (SELECT probe_id
                              FROM rhn_check_probe
                             WHERE host_id = server_id_in);
         end if;

         if is_virt = 1 and repoll_virt_guests = 1 then
           rhn_entitlements.repoll_virt_guest_entitlements(server_id_in);
         end if;
      end if;

  		exception
  		when no_data_found then
  				rhn_exception.raise_exception('invalid_server_group_member');	
      end;

 	end remove_server_entitlement;


   procedure unentitle_server (server_id_in in number) is

      cursor servergroups is
         select distinct sgt.label, sg.id server_group_id
         from  rhnServerGroupType sgt,
               rhnServerGroup sg,
               rhnServer s,
               rhnServerGroupMembers sgm
         where s.id = server_id_in
            and s.org_id = sg.org_id
            and sg.group_type = sgt.id
            and sgm.server_group_id = sg.id
            and sgm.server_id = s.id;
            
     is_virt number := 0;

   begin

      begin
        select 1 into is_virt
          from rhnServerEntitlementView
         where server_id = server_id_in
           and label in ('virtualization_host', 'virtualization_host_platform');
      exception
        when no_data_found then
          is_virt := 0;
      end;

      for servergroup in servergroups loop

         insert into rhnServerHistory ( id, server_id, summary, details )
         values ( rhn_event_id_seq.nextval, server_id_in,
                  'removed system entitlement ',
                   case servergroup.label
                    when 'enterprise_entitled' then 'Management'
                    when 'sw_mgr_entitled' then 'Update'
                    when 'provisioning_entitled' then 'Provisioning'
                    when 'monitoring_entitled' then 'Monitoring'
                    when 'virtualization_host' then 'Virtualization'
                    when 'virtualization_host_platform' then 
                         'Virtualization Platform' end  );
  
         rhn_server.delete_from_servergroup(server_id_in, 
                                            servergroup.server_group_id );
      end loop;

      if is_virt = 1 then
        rhn_entitlements.repoll_virt_guest_entitlements(server_id_in);
      end if;

   end unentitle_server;


    -- *******************************************************************
    -- PROCEDURE: repoll_virt_guest_entitlements
    --
    --   Whenever we add/remove a virtualization_host* entitlement from 
    --   a host, we can call this procedure to update what type of slots
    --   the guests are consuming.  
    -- 
    --   If you're removing the entitlement, it's 
    --   possible the guests will become unentitled if you don't have enough
    --   physical slots to cover them.
    --
    --   If you're adding the entitlement, you end up freeing up physical
    --   slots for other systems.
    --
    -- *******************************************************************
    procedure repoll_virt_guest_entitlements(server_id_in in number)
    is

        -- All channel families associated with the guests of server_id_in
        cursor families is 
            select distinct cfs.channel_family_id
            from
                rhnChannelFamilyServers cfs,
                rhnVirtualInstance vi
            where
                vi.host_system_id = server_id_in
                and vi.virtual_system_id = cfs.server_id;
        
        -- All of server group types associated with the guests of
        -- server_id_in
        cursor group_types is
            select distinct sg.group_type, sgt.label
            from
                rhnServerGroupType sgt,
                rhnServerGroup sg,
                rhnServerGroupMembers sgm,
                rhnVirtualInstance vi
            where
                vi.host_system_id = server_id_in
                and vi.virtual_system_id = sgm.server_id
                and sgm.server_group_id = sg.id
                and sg.group_type = sgt.id;

        -- Virtual servers from a certain family belonging to a speicifc
        -- host that are consuming physical channel slots over the limit.
        cursor virt_servers_cfam(family_id_in in number, quantity_in in number)  is
            select virtual_system_id
            from (
                select rownum, vi.virtual_system_id
                from
                    rhnChannelFamilyMembers cfm,
                    rhnServerChannel sc,
                    rhnVirtualInstance vi
                where
                    vi.host_system_id = server_id_in
                    and vi.virtual_system_id = sc.server_id
                    and sc.channel_id = cfm.channel_id
                    and cfm.channel_family_id = family_id_in
                order by sc.modified desc
                )
            where rownum <= quantity_in;                

        -- Virtual servers from a certain family belonging to a speicifc
        -- host that are consuming physical system slots over the limit.
        cursor virt_servers_sgt(group_type_in in number, quantity_in in number)  is
            select virtual_system_id
            from (
                select rownum, vi.virtual_system_id
                from
                    rhnServerGroup sg,
                    rhnServerGroupMembers sgm,
                    rhnVirtualInstance vi
                where
                    vi.host_system_id = server_id_in
                    and vi.virtual_system_id = sgm.server_id
                    and sgm.server_group_id = sg.id
                    and sg.group_type = group_type_in
                order by sgm.modified desc
                )
            where rownum <= quantity_in;                
        
        org_id_val number;
        max_members_val number;
        current_members_calc number;
        sg_id number;

    begin

        select org_id
        into org_id_val
        from rhnServer
        where id = server_id_in;

        -- deal w/ channel entitlements first ...
        for family in families loop
            -- get the current (physical) members of the family
            current_members_calc := 
                rhn_channel.channel_family_current_members(family.channel_family_id,
                                                           org_id_val); -- fixed transposed args

            -- get the max members of the family
            select max_members
            into max_members_val
            from rhnPrivateChannelFamily
            where channel_family_id = family.channel_family_id
            and org_id = org_id_val;

            if current_members_calc > max_members_val then
                -- A virtualization_host* ent must have been removed, so we'll
                -- unsubscribe guests from the host first.

                -- hm, i don't think max_members - current_members_calc yielding a negative number
                -- will work w/ rownum, swaping 'em in the body of this if...
                for virt_server in virt_servers_cfam(family.channel_family_id,
                                current_members_calc - max_members_val) loop 

                    rhn_channel.unsubscribe_server_from_family(
                                virt_server.virtual_system_id,
                                family.channel_family_id);
                end loop;                               

                -- if we're still over the limit, which would be odd,
                -- just prune the group to max_members
                --
                -- er... wouldn't we actually have to refresh the values of
                -- current_members_calc and max_members_val to actually ever
                -- *skip this??
                if current_members_calc > max_members_val then
                    -- argh, transposed again?!
                    set_family_count(org_id_val,
                                     family.channel_family_id,
                                     max_members_val);
                end if; 

           end if;

            -- update current_members for the family.  This will set the value
            -- to reflect adding/removing the entitlement.
            --
            -- what's the difference of doing this vs the unavoidable set_family_count above?
            rhn_channel.update_family_counts(family.channel_family_id,
                                             org_id_val);
        end loop;

        for a_group_type in group_types loop
          -- get the current *physical* members of the system entitlement type for the org...
          -- 
          -- unlike channel families, it appears the standard rhnServerGroup.max_members represents
          -- *physical* slots, vs physical+virt ... boy that's confusing...

          select max_members, id
            into max_members_val, sg_id
            from rhnServerGroup
            where group_type = a_group_type.group_type
            and org_id = org_id_val;


	  select count(sep.server_id) into current_members_calc
            from rhnServerEntitlementPhysical sep
           where sep.server_group_id = sg_id
             and sep.server_group_type_id = a_group_type.group_type;
          
          if current_members_calc > max_members_val then
            -- A virtualization_host* ent must have been removed, and we're over the limit, so unsubscribe guests
            for virt_server in virt_servers_sgt(a_group_type.group_type,
                                                current_members_calc - max_members_val) loop
              rhn_entitlements.remove_server_entitlement(virt_server.virtual_system_id, a_group_type.label);

              -- decrement current_members_calc, we'll use it to reset current_members for the group at the end...
              current_members_calc := current_members_calc - 1;
            end loop;

          end if;

          update rhnServerGroup set current_members = current_members_calc
           where org_id = org_id_val
             and group_type = a_group_type.group_type;

          -- I think that's all the house-keeping we have to do...
        end loop;

    end repoll_virt_guest_entitlements;


	function get_server_entitlement (
		server_id_in in number
	) return ents_array is

		cursor server_groups is
			select	sgt.label
			from	rhnServerGroupType		sgt,
					rhnServerGroup			sg,
					rhnServerGroupMembers	sgm
			where	1=1
				and sgm.server_id = server_id_in
				and sg.id = sgm.server_group_id
				and sgt.id = sg.group_type
				and sgt.label in (
					'sw_mgr_entitled','enterprise_entitled',
					'provisioning_entitled', 'nonlinux_entitled',
					'monitoring_entitled', 'virtualization_host',
                                        'virtualization_host_platform'
					);

         ent_array ents_array;

	begin
      
      ent_array := ents_array();

		for sg in server_groups loop
         ent_array.extend;
         ent_array(ent_array.count) := sg.label;
		end loop;

		return ent_array;

	end get_server_entitlement;


	-- this desperately needs to be table driven.
	procedure modify_org_service (
		org_id_in in number,
		service_label_in in varchar2,
		enable_in in char
	) is
		type roles_v is varray(10) of rhnUserGroupType.label%TYPE;
		roles_to_process roles_v;
		cursor roles(role_label_in in varchar2) is
			select	label, id
			from	rhnUserGroupType
			where	label = role_label_in;
		cursor org_roles(role_label_in in varchar2) is
			select	1
			from	rhnUserGroup ug,
					rhnUserGroupType ugt
			where	ugt.label = role_label_in
				and ug.org_id = org_id_in
				and ugt.id = ug.group_type;
				
		type ents_v is varray(10) of rhnOrgEntitlementType.label%TYPE;
		ents_to_process ents_v;
		cursor ents(ent_label_in in varchar2) is
			select	label, id
			from	rhnOrgEntitlementType
			where	label = ent_label_in;
		cursor org_ents(ent_label_in in varchar2) is
			select	1
			from	rhnOrgEntitlements oe,
					rhnOrgEntitlementType oet
			where	oet.label = ent_label_in
				and oe.org_id = org_id_in
				and oet.id = oe.entitlement_id;
		create_row char(1);
	begin
		ents_to_process := ents_v();
		roles_to_process := roles_v();
		-- a bit kludgy, but only for 3.4 really.  Certainly no
		-- worse than the old code...
		if service_label_in = 'enterprise' or 
           service_label_in = 'management' then
			ents_to_process.extend;
			ents_to_process(ents_to_process.count) := 'sw_mgr_enterprise';

			roles_to_process.extend;
			roles_to_process(roles_to_process.count) := 'org_admin';

			roles_to_process.extend;
			roles_to_process(roles_to_process.count) := 'system_group_admin';

			roles_to_process.extend;
			roles_to_process(roles_to_process.count) := 'activation_key_admin';

			roles_to_process.extend;
			roles_to_process(roles_to_process.count) := 'org_applicant';
		elsif service_label_in = 'provisioning' then
			ents_to_process.extend;
			ents_to_process(ents_to_process.count) := 'rhn_provisioning';

			roles_to_process.extend;
			roles_to_process(roles_to_process.count) := 'system_group_admin';

			roles_to_process.extend;
			roles_to_process(roles_to_process.count) := 'activation_key_admin';

			roles_to_process.extend;
			roles_to_process(roles_to_process.count) := 'config_admin';
			-- another nasty special case...
			if enable_in = 'Y' then
				ents_to_process.extend;
				ents_to_process(ents_to_process.count) := 'sw_mgr_enterprise';
			end if;
		elsif service_label_in = 'monitoring' then
			ents_to_process.extend;
			ents_to_process(ents_to_process.count) := 'rhn_monitor';

			roles_to_process.extend;
			roles_to_process(roles_to_process.count) := 'monitoring_admin';
		elsif service_label_in = 'virtualization' then
			ents_to_process.extend;
			ents_to_process(ents_to_process.count) := 'rhn_virtualization';

			roles_to_process.extend;
			roles_to_process(roles_to_process.count) := 'config_admin';
        elsif service_label_in = 'virtualization_platform' then
			ents_to_process.extend;
			ents_to_process(ents_to_process.count) := 'rhn_virtualization_platform'; 
			roles_to_process.extend;
			roles_to_process(roles_to_process.count) := 'config_admin';
	elsif service_label_in = 'nonlinux' then
			ents_to_process.extend;
			ents_to_process(ents_to_process.count) := 'rhn_nonlinux';
			roles_to_process.extend;
			roles_to_process(roles_to_process.count) := 'config_admin';
		end if;

		if enable_in = 'Y' then
			for i in 1..ents_to_process.count loop
				for ent in ents(ents_to_process(i)) loop
					create_row := 'Y';
					for oe in org_ents(ent.label) loop
						create_row := 'N';
					end loop;
					if create_row = 'Y' then
						insert into rhnOrgEntitlements(org_id, entitlement_id)
							values (org_id_in, ent.id);
					end if;
				end loop;
			end loop;
			for i in 1..roles_to_process.count loop
				for role in roles(roles_to_process(i)) loop
					create_row := 'Y';
					for o_r in org_roles(role.label) loop
						create_row := 'N';
					end loop;
					if create_row = 'Y' then
						insert into rhnUserGroup(
								id, name, description, current_members,
								group_type, org_id
							) (
								select	rhn_user_group_id_seq.nextval,
										ugt.name || 's',
										ugt.name || 's for Org ' ||
											o.name || ' ('|| o.id ||')',
										0, ugt.id, o.id
								from	rhnUserGroupType ugt,
										web_customer o
								where	o.id = org_id_in
									and ugt.id = role.id
							);
					end if;
				end loop;
			end loop;
		else
			for i in 1..ents_to_process.count loop
				for ent in ents(ents_to_process(i)) loop
					delete from rhnOrgEntitlements
					 where org_id = org_id_in
					   and entitlement_id = ent.id;
				end loop;
			end loop;
		end if;
	end modify_org_service;

	procedure set_customer_enterprise (
		customer_id_in in number
	) is
	begin
		modify_org_service(customer_id_in, 'enterprise', 'Y');
	end set_customer_enterprise;

	procedure set_customer_provisioning (
		customer_id_in in number
	) is
	begin
		modify_org_service(customer_id_in, 'provisioning', 'Y');
	end set_customer_provisioning;

	procedure set_customer_monitoring (
		customer_id_in in number
	) is
	begin
		modify_org_service(customer_id_in, 'monitoring', 'Y');
	end set_customer_monitoring;

	procedure set_customer_nonlinux (
		customer_id_in in number
	) is
	begin
		modify_org_service(customer_id_in, 'nonlinux', 'Y');
	end set_customer_nonlinux;

	procedure unset_customer_enterprise (
		customer_id_in in number
	) is
	begin
		modify_org_service(customer_id_in, 'enterprise', 'N');
	end unset_customer_enterprise;

	procedure unset_customer_provisioning (
		customer_id_in in number
	) is
	begin
		modify_org_service(customer_id_in, 'provisioning', 'N');
	end unset_customer_provisioning;

	procedure unset_customer_monitoring (
		customer_id_in in number
	) is
	begin
		modify_org_service(customer_id_in, 'monitoring', 'N');
	end unset_customer_monitoring;

	procedure unset_customer_nonlinux (
		customer_id_in in number
	) is
	begin
		modify_org_service(customer_id_in, 'nonlinux', 'N');
	end unset_customer_nonlinux;

    -- *******************************************************************
    -- PROCEDURE: prune_group
    -- Unsubscribes servers consuming physical slots that over the org's
    --   limit.
    -- Called by: set_group_count, prune_everything, repoll_virt_guest_entitlements
    -- *******************************************************************
	procedure prune_group (
		group_id_in in number,
		type_in in char,
		quantity_in in number
	) is
		cursor usergroups is
			select	user_id, user_group_id, ugt.label
			from	rhnUserGroupType	ugt,
					rhnUserGroup		ug,
					rhnUserGroupMembers	ugm
			where	1=1
				and ugm.user_group_id = group_id_in
				and ugm.user_id in (
					select	user_id
					from	(
						select	rownum row_number,
								user_id,
								time
						from	(
							select	user_id,
									modified time
							from	rhnUserGroupMembers
							where	user_group_id = group_id_in
							order by time asc
						)
					)
					where	row_number > quantity_in
				)
				and ugm.user_group_id = ug.id
				and ug.group_type = ugt.id;
        cursor servergroups is
           select  server_id, server_group_id, sgt.id group_type_id, sgt.label
            from    rhnServerGroupType              sgt,
                            rhnServerGroup                  sg,
                            rhnServerGroupMembers   sgm
            where   1=1
                    and sgm.server_group_id = group_id_in
                    and sgm.server_id in (
                            select  server_id
                            from    (
                                    select  rownum row_number,
                                                    server_id,
                                                    time
                                    from    (
                                            select  sep.server_id,
                                                    sep.modified time
                                            from
                                                rhnServerEntitlementPhysical sep
                                            where
                                                sep.server_group_id = group_id_in
                                            order by time asc
                                    )
                            )
                            where   row_number > quantity_in
                    )
                    and sgm.server_group_id = sg.id
                    and sg.group_type = sgt.id;
      type_is_base char;
	begin
		if type_in = 'U' then
			update		rhnUserGroup
				set		max_members = quantity_in
				where	id = group_id_in;

			for ug in usergroups loop
				rhn_user.remove_from_usergroup(ug.user_id, ug.user_group_id);
			end loop;
		elsif type_in = 'S' then
			update		rhnServerGroup
				set		max_members = quantity_in
				where	id = group_id_in;

			for sg in servergroups loop
				remove_server_entitlement(sg.server_id, sg.label);
            
            select is_base 
            into type_is_base
            from rhnServerGroupType sgt
            where sgt.id = sg.group_type_id;
 
            -- if we're removing a base ent, then be sure to
            -- remove the server's channel subscriptions.
            if ( type_is_base = 'Y' ) then
				   rhn_channel.clear_subscriptions(sg.server_id);
            end if;

			end loop;
		end if;
	end prune_group;

    -- *******************************************************************
    -- PROCEDURE: assign_system_entitlement
    --
    -- Moves system entitlements from from_org_id_in to to_org_id_in.
    -- Can raise not_enough_entitlements_in_base_org if from_org_id_in
    -- does not have enough entitlements to cover the move.
    -- Takes care of unentitling systems if necessary by calling 
    -- set_group_count
    -- *******************************************************************
    procedure assign_system_entitlement(
        group_label_in in varchar2,
        from_org_id_in in number,
        to_org_id_in in number,
        quantity_in in number
    )
    is
        prev_ent_count number;
	to_org_prev_ent_count number;
        new_ent_count number;
	new_quantity number;
        group_type number;
    begin

        begin
            select max_members
            into prev_ent_count
            from rhnServerGroupType sgt,
                 rhnServerGroup sg
            where sg.org_id = from_org_id_in
              and sg.group_type = sgt.id
              and sgt.label = group_label_in;
        exception
            when NO_DATA_FOUND then
                rhn_exception.raise_exception(
                              'not_enough_entitlements_in_base_org');
        end;

        begin
            select max_members
            into to_org_prev_ent_count
            from rhnServerGroupType sgt,
                 rhnServerGroup sg
            where sg.org_id = to_org_id_in
              and sg.group_type = sgt.id
              and sgt.label = group_label_in;
        exception
            when NO_DATA_FOUND then
                to_org_prev_ent_count := 0;
        end;
	
        begin
            select id
            into group_type
            from rhnServerGroupType
            where label = group_label_in;
        exception
            when NO_DATA_FOUND then
                rhn_exception.raise_exception(
                              'invalid_server_group');
        end;

        new_ent_count := prev_ent_count - quantity_in;
	
        if prev_ent_count > new_ent_count then
            new_quantity := to_org_prev_ent_count + quantity_in;
        end if;
	
        if new_ent_count < 0 then
            rhn_exception.raise_exception(
                          'not_enough_entitlements_in_base_org');
        end if;


        rhn_entitlements.set_group_count(from_org_id_in,
                                         'S',
                                         group_type,
                                         new_ent_count);

        rhn_entitlements.set_group_count(to_org_id_in,
                                         'S',
                                         group_type,
                                         new_quantity);
        
        -- Create or delete the entries in rhnOrgEntitlementType
        if group_label_in = 'enterprise_entitled' then 
            if new_quantity > 0 then
                set_customer_enterprise(to_org_id_in);
            else
                unset_customer_enterprise(to_org_id_in);
            end if;
        end if;

        if group_label_in = 'provisioning_entitled' then
            if new_quantity > 0 then
                set_customer_provisioning(to_org_id_in);
            else
                unset_customer_provisioning(to_org_id_in);
            end if;
        end if;

        if group_label_in = 'monitoring_entitled' then
            if new_quantity > 0 then
                set_customer_monitoring(to_org_id_in);
            else
                unset_customer_monitoring(to_org_id_in);
            end if;
        end if;

    end assign_system_entitlement;

    -- *******************************************************************
    -- PROCEDURE: assign_channel_entitlement
    --
    -- Moves channel entitlements from from_org_id_in to to_org_id_in.
    -- Can raise not_enough_entitlements_in_base_org if from_org_id_in
    -- does not have enough entitlements to cover the move.
    -- Takes care of unentitling systems if necessary by calling 
    -- set_family_count
    -- *******************************************************************
    procedure assign_channel_entitlement(
        channel_family_label_in in varchar2,
        from_org_id_in in number,
        to_org_id_in in number,
        quantity_in in number
    )
    is
        prev_ent_count number;
        new_ent_count number;
	to_org_prev_ent_count number;
	new_quantity number;
        cfam_id       number;
    begin

        begin
            select max_members
            into prev_ent_count
            from rhnChannelFamily cf,
                 rhnPrivateChannelFamily pcf
            where pcf.org_id = from_org_id_in
              and pcf.channel_family_id = cf.id
              and cf.label = channel_family_label_in;
        exception
            when NO_DATA_FOUND then
                rhn_exception.raise_exception(
                              'not_enough_entitlements_in_base_org');
        end;
	
        begin
            select max_members
            into to_org_prev_ent_count
            from rhnChannelFamily cf,
                 rhnPrivateChannelFamily pcf
            where pcf.org_id = to_org_id_in
              and pcf.channel_family_id = cf.id
              and cf.label = channel_family_label_in;
        exception
            when NO_DATA_FOUND then
                to_org_prev_ent_count := 0;
        end;
	

        begin
            select id
            into cfam_id
            from rhnChannelFamily
            where label = channel_family_label_in;
        exception
            when NO_DATA_FOUND then
                rhn_exception.raise_exception(
                              'invalid_channel_family');
        end;                              

        new_ent_count := prev_ent_count - quantity_in;
	
	if prev_ent_count > new_ent_count then
            new_quantity := to_org_prev_ent_count + quantity_in;
	end if;
	

        if new_ent_count < 0 then
            rhn_exception.raise_exception(
                          'not_enough_entitlements_in_base_org');
        end if;

        rhn_entitlements.set_family_count(from_org_id_in,
                                          cfam_id,
                                          new_ent_count);

        rhn_entitlements.set_family_count(to_org_id_in,
                                          cfam_id,
                                          new_quantity);

    end assign_channel_entitlement;

    -- *******************************************************************
    -- PROCEDURE: activate_system_entitlement
    --
    -- Sets the values in rhnServerGroup for a given rhnServerGroupType.
    -- 
    -- Calls: set_group_count to update, prune, or create the group.
    -- Called by: the code that activates a satellite cert. 
    --
    -- Raises not_enough_entitlements_in_base_org if all entitlements
    -- in the org are used so the free entitlements would not cover
    -- the difference when descreasing the number of entitlements.
    -- *******************************************************************
    procedure activate_system_entitlement(
        org_id_in in number,
        group_label_in in varchar2,
        quantity_in in number
    )
    is
        prev_ent_count number; 
        prev_ent_count_sum number; 
        group_type number;
    begin

        -- Fetch the current entitlement count for the org
        -- into prev_ent_count
        begin
            select current_members
            into prev_ent_count
            from rhnServerGroupType sgt,
                 rhnServerGroup sg
            where sg.group_type = sgt.id
              and sgt.label = group_label_in
              and sg.org_id = org_id_in;
        exception
            when NO_DATA_FOUND then
                prev_ent_count := 0;
        end;

        begin
            select id
            into group_type
            from rhnServerGroupType
            where label = group_label_in;
        exception
            when NO_DATA_FOUND then
                rhn_exception.raise_exception(
                              'invalid_server_group');
        end;

        -- If we're setting the total entitlemnt count to a lower value,
        -- and that value is less than the allocated count in this org,
        -- we need to raise an exception.
        if quantity_in < prev_ent_count then
            rhn_exception.raise_exception(
                          'not_enough_entitlements_in_base_org');
        else
            rhn_entitlements.set_group_count(org_id_in,
                                             'S',
                                             group_type,
                                             quantity_in);
        end if;


    end activate_system_entitlement;

    -- *******************************************************************
    -- PROCEDURE: activate_channel_entitlement
    --
    -- Calls: set_family_count to update, prune, or create the family
    --        permission bucket.
    -- Called by: the code that activates a satellite cert. 
    --
    -- Raises not_enough_entitlements_in_base_org if there are not enough
    -- entitlements in the org to cover the difference when you are
    -- descreasing the number of entitlements.
    --
    -- The backend code in Python is expected to do whatever arithmetics
    -- is needed.
    -- *******************************************************************
    procedure activate_channel_entitlement(
        org_id_in in number,
        channel_family_label_in in varchar2,
        quantity_in in number
    )
    is
        prev_ent_count number; 
        prev_ent_count_sum number; 
        cfam_id number;
    begin

        -- Fetch the current entitlement count for the org
        -- into prev_ent_count
        begin
            select current_members
            into prev_ent_count
            from rhnChannelFamily cf,
                 rhnPrivateChannelFamily pcf
            where pcf.org_id = org_id_in
              and pcf.channel_family_id = cf.id
              and cf.label = channel_family_label_in;
        exception
            when NO_DATA_FOUND then
                prev_ent_count := 0;
        end;

        begin
            select id
            into cfam_id
            from rhnChannelFamily
            where label = channel_family_label_in;
        exception
            when NO_DATA_FOUND then
                rhn_exception.raise_exception(
                              'invalid_channel_family');
        end;                              

        -- If we're setting the total entitlemnt count to a lower value,
        -- and that value is less than the count in that one org,
        -- we need to raise an exception.
        if quantity_in < prev_ent_count then
            rhn_exception.raise_exception(
                          'not_enough_entitlements_in_base_org');
        else
            rhn_entitlements.set_family_count(org_id_in,
                                              cfam_id,
                                              quantity_in);
        end if;

    end activate_channel_entitlement;


	procedure set_group_count (
		customer_id_in in number,
		type_in in char,
		group_type_in in number,
		quantity_in in number
	) is
		group_id number;
		quantity number;
	begin
		quantity := quantity_in;
		if quantity is not null and quantity < 0 then
			quantity := 0;
		end if;

		if type_in = 'U' then
			select	rug.id
			into	group_id
			from	rhnUserGroup rug
			where	1=1
				and rug.org_id = customer_id_in
				and rug.group_type = group_type_in;
		elsif type_in = 'S' then
			select	rsg.id
			into	group_id
			from	rhnServerGroup rsg
			where	1=1
				and rsg.org_id = customer_id_in
				and rsg.group_type = group_type_in;
		end if;

		rhn_entitlements.prune_group(
			group_id,
			type_in,
			quantity
		);
	exception
		when no_data_found then
			if type_in = 'U' then
				insert into rhnUserGroup (
						id, name, description, max_members, current_members,
						group_type, org_id, created, modified
					) (
						select	rhn_user_group_id_seq.nextval, name, name,
								quantity, 0, id, customer_id_in,
								sysdate, sysdate
						from	rhnUserGroupType
						where	id = group_type_in
				);
			elsif type_in = 'S' then
				insert into rhnServerGroup (
						id, name, description, max_members, current_members,
						group_type, org_id, created, modified
					) (
						select	rhn_server_group_id_seq.nextval, name, name,
								quantity, 0, id, customer_id_in,
								sysdate, sysdate
						from	rhnServerGroupType
						where	id = group_type_in
				);
			end if;
	end set_group_count;

    -- *******************************************************************
    -- PROCEDURE: prune_family
    -- Unsubscribes servers consuming physical slots from the channel family 
    --   that are over the org's limit.
    -- Called by: set_family_count, prune_everything
    -- *******************************************************************
	procedure prune_family (
		customer_id_in in number,
		channel_family_id_in in number,
		quantity_in in number
	) is
		cursor serverchannels is
			select	sc.server_id,
					sc.channel_id
			from	rhnServerChannel sc,
					rhnChannelFamilyMembers cfm
			where	1=1
				and cfm.channel_family_id = channel_family_id_in
				and cfm.channel_id = sc.channel_id
				and server_id in (
					select	server_id
					from	(
						select	server_id,
								time,
								rownum row_number
						from	(
							select	rs.id					server_id,
									rcfm.modified			time
							from	
									rhnServerChannel		rsc,
									rhnChannelFamilyMembers	rcfm,
                                    rhnServer				rs
							where	1=1
								and rs.org_id = customer_id_in
								and rs.id = rsc.server_id
								and rsc.channel_id = rcfm.channel_id
								and rcfm.channel_family_id =
									channel_family_id_in
                                -- we only want to grab servers consuming
                                -- physical slots.
                                and exists (
                                    select 1
                                    from rhnChannelFamilyServerPhysical cfsp
                                    where cfsp.server_id = rs.id
                                    and cfsp.channel_family_id = 
                                        channel_family_id_in
                                    )
							order by time asc
						)
					)
					where row_number > quantity_in
				);
	begin
		-- if we get a null customer_id, this is completely bogus.
		if customer_id_in is null then
			return;
		end if;

		update		rhnPrivateChannelFamily
			set		max_members = quantity_in
			where	1=1
				and org_id = customer_id_in
				and channel_family_id = channel_family_id_in;

		for sc in serverchannels loop
			rhn_channel.unsubscribe_server(sc.server_id, sc.channel_id, 1, 1);
		end loop;
	end prune_family;
		
	procedure set_family_count (
		customer_id_in in number,
		channel_family_id_in in number,
		quantity_in in number
	) is
		cursor privperms is
			select	1
			from	rhnPrivateChannelFamily
			where	org_id = customer_id_in
				and channel_family_id = channel_family_id_in;
		cursor pubperms is
			select	o.id org_id
			from	web_customer o,
					rhnPublicChannelFamily pcf
			where	pcf.channel_family_id = channel_family_id_in;
		quantity number;
		done number := 0;
	begin
		quantity := quantity_in;
		if quantity is not null and quantity < 0 then
			quantity := 0;
		end if;

		if customer_id_in is not null then
			for perm in privperms loop
				rhn_entitlements.prune_family(
					customer_id_in,
					channel_family_id_in,
					quantity
				);
				update rhnPrivateChannelFamily
					set max_members = quantity
					where org_id = customer_id_in
						and channel_family_id = channel_family_id_in;
				return;
			end loop;
			
			insert into rhnPrivateChannelFamily (
					channel_family_id, org_id, max_members, current_members
				) values (
					channel_family_id_in, customer_id_in, quantity, 0
				);
			return;
		end if;

		for perm in pubperms loop
			if quantity = 0 then
				rhn_entitlements.prune_family(
					perm.org_id,
					channel_family_id_in,
					quantity
				);
				if done = 0 then
					delete from rhnPublicChannelFamily
						where channel_family_id = channel_family_id_in;
				end if;
			end if;
			done := 1;
		end loop;
		-- if done's not 1, then we don't have any entitlements
		if done != 1 then
			insert into rhnPublicChannelFamily (
					channel_family_id
				) values (
					channel_family_id_in
				);
		end if;
	end set_family_count;

	-- this expects quantity_in to be the number of available slots, not the
	-- max_members of the server group.  If you give it too many, it'll fail
	-- and raise servergroup_max_members.
	-- We should NEVER run this unless we're SURE that we won't
	-- be violating the max.
	procedure entitle_last_modified_servers (
		customer_id_in in number,
		type_label_in in varchar2,
		quantity_in in number
	) is
		-- find the servers that aren't currently in slots
		cursor servers(cid_in in number, quant_in in number) is
			select	server_id
			from	(
						select	rownum row_number,
								server_id
						from	(
									select	rs.id server_iD
									from	rhnServer rs
									where	1=1
										and rs.org_id = cid_in
										and not exists (
											select	1
											from	rhnServerGroup sg,
													rhnServerGroupMembers rsgm
											where	rsgm.server_id = rs.id
												and rsgm.server_group_id = sg.id
												and sg.group_type is not null
										)
                                        and not exists (
                                            select 1
                                            from rhnVirtualInstance vi
                                            where vi.virtual_system_id =
                                                  rs.id
                                        )                                                                           order by modified desc
								)
					)
			where	row_number <= quant_in;
	begin
		for server in servers(customer_id_in, quantity_in) loop
			rhn_entitlements.entitle_server(server.server_id, type_label_in);
		end loop;
	end entitle_last_modified_servers;

	procedure prune_everything (
		customer_id_in in number
	) is
		cursor everything is
			-- all our server groups
			select	sg.id					id,
					'S'						type,
					sg.max_members			quantity
			from	rhnServerGroup			sg
			where	sg.org_id = customer_id_in
			union
			-- all our user groups
			select	ug.id					id,
					'U'						type,
					ug.max_members 			quantity
			from	rhnUserGroup			ug
			where	ug.org_id = customer_id_in
			union ( 
			-- all the channel families we have perms to
			select	cfp.channel_family_id	id,
					'C'						type,
					cfp.max_members			quantity
			from	rhnOrgChannelFamilyPermissions cfp
			where	cfp.org_id = customer_id_in
			union
			-- plus all the ones we're using that we have no perms for
			select	cfm.channel_family_id	id,
					'C'						type,
					0						quantity
			from	rhnChannelFamily		cf,
					rhnChannelFamilyMembers	cfm,
					rhnServerChannel		sc,
					rhnServer				s
			where	s.org_id = customer_id_in
				and s.id = sc.server_id
				and sc.channel_id = cfm.channel_id
				and cfm.channel_family_id = cf.id
				and cf.org_id is not null
				and cf.org_id != customer_id_in
				and not exists (
					select	1
					from	rhnOrgChannelFamilyPermissions cfp
					where	cfp.org_id = customer_id_in
						and cfp.channel_family_id = cfm.channel_family_id
					)
			);
	begin
		for one in everything loop
			if one.type in ('U','S') then
				prune_group(one.id, one.type, one.quantity);
			else
				prune_family(customer_id_in, one.id, one.quantity);
			end if;
		end loop;
	end prune_everything;

	procedure subscribe_newest_servers (
		customer_id_in in number
	) is
		-- find servers without base channels
		cursor servers(cid_in in number) is
			select	s.id
			from	rhnServer			s
			where	1=1
				and s.org_id = cid_in
				and not exists (
						select 1
						from	rhnChannel			c,
								rhnServerChannel	sc
						where	sc.server_id = s.id
							and sc.channel_id = c.id
							and c.parent_channel is null
					)
                and not exists (
                        select 1
                        from rhnVirtualInstance vi
                        where vi.virtual_system_id = s.id
                    )                        
			order by s.modified desc;
		channel_id number;
	begin
		for server in servers(customer_id_in) loop
			channel_id := rhn_channel.guess_server_base(server.id);
			if channel_id is not null then
				begin
					rhn_channel.subscribe_server(server.id, channel_id);
					commit;
				-- exception is really channel_family_no_subscriptions
				exception
					when others then
						null;
				end;
			end if;
		end loop;
	end subscribe_newest_servers;
end rhn_entitlements;
/
show errors

--
-- $Log$
-- Revision 1.56  2004/07/21 21:27:36  nhansen
-- bug 128196: use rhn_monitor instead of rhn_monitoring as the rhnOrgEntitlementType
--
-- Revision 1.55  2004/07/20 15:38:57  pjones
-- bugzilla: 128196 -- make entitling "monitoring" work.
--
-- Revision 1.54  2004/07/14 19:13:13  pjones
-- bugzilla: 126461 -- entitlement changes for new user roles
--
-- Revision 1.53  2004/07/02 19:18:20  pjones
-- bugzilla: 125937 -- use rhn_user to remove user roles
--
-- Revision 1.52  2004/05/26 19:45:48  pjones
-- bugzilla: 123639
-- 1) reformat "entitlement_grants_service"
-- 2) make the .pks and .pkb be in the same order.
-- 3) add "modify_org_service" (to be used instead of set_customer_SERVICELEVEL)
-- 4) add monitoring specific data.
--
-- Revision 1.51  2004/04/19 18:18:51  pjones
-- bugzilla: none -- misa's using set_family_count() to set null org entitlements
--
-- Revision 1.50  2004/04/14 00:09:24  pjones
-- bugzilla: 120761 -- split rhnChannelPermissions into two tables, eliminating
-- a frequent full table scan
--
-- Revision 1.49  2004/03/26 16:53:42  pjones
-- bugzilla: none -- make rhn_nonlinux give config_admin too on sat.
--
-- Revision 1.48  2004/03/25 22:29:56  pjones
-- bugzilla: none -- only create config_admin in set_customer_prov if we're
-- on a satellite
070701000003F0000081B400000000000000000000000167AE11140000065A000000000000000000000000000000000000006000000000susemanager-schema/upgrade/rhn-satellite-schema-5.1-to-spacewalk-schema-0.2/206-rhn_org.pks.sql   --
-- Copyright (c) 2008 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
-- $Id$
--

CREATE OR REPLACE
PACKAGE rhn_org
IS
	version varchar2(100) := '$Id$';

    CURSOR server_group_by_label(org_id_in NUMBER, group_label_in VARCHAR2) IS
    	   SELECT SG.*
	     FROM rhnServerGroupType SGT,
	     	  rhnServerGroup SG
	    WHERE SG.group_type = SGT.id
	      AND SGT.label = group_label_in
	      AND SG.org_id = org_id_in;
	    
    FUNCTION find_server_group_by_type(org_id_in NUMBER, 
                                       group_label_in VARCHAR2) 
    RETURN NUMBER;

    procedure delete_org(org_id_in in number);
    procedure delete_user(user_id_in in number, deleting_org in number := 0);

END rhn_org;
/
SHOW ERRORS

-- $Log$
-- Revision 1.7  2004/07/13 22:46:04  pjones
-- bugzilla: 125938 -- nothing uses update_errata_cache() any more, remove it
--
-- Revision 1.6  2004/02/10 15:05:01  pjones
-- bugzilla: none -- add version tag here
--
-- Revision 1.5  2003/02/18 16:35:45  pjones
-- delete_user
--
-- Revision 1.4  2002/05/10 22:08:23  pjones
-- id/log
--
  070701000003F1000081B400000000000000000000000167AE111400002317000000000000000000000000000000000000006000000000susemanager-schema/upgrade/rhn-satellite-schema-5.1-to-spacewalk-schema-0.2/207-rhn_org.pkb.sql   --
-- Copyright (c) 2008 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
-- $Id$
--

CREATE OR REPLACE
PACKAGE BODY rhn_org
IS
	body_version varchar2(100) := '$Id$';

    FUNCTION find_server_group_by_type(org_id_in NUMBER, group_label_in VARCHAR2) 
    RETURN NUMBER
    IS
	server_group       server_group_by_label%ROWTYPE;
    BEGIN
    	OPEN server_group_by_label(org_id_in, group_label_in);
	FETCH server_group_by_label INTO server_group;
	CLOSE server_group_by_label;

	RETURN server_group.id;
    END find_server_group_by_type;
    
    procedure delete_org (
        org_id_in in number
    )
    is

        cursor users is
        select id
        from web_contact
        where org_id = org_id_in;

		cursor servers(org_id_in in number) is
        select	id
        from	rhnServer
        where	org_id = org_id_in;

        cursor config_channels is
        select id
        from rhnConfigChannel
        where org_id = org_id_in;

    begin

        if org_id_in = 1 then
            rhn_exception.raise_exception('cannot_delete_base_org');
        end if;

        -- Delete all users.
        for u in users loop
            rhn_org.delete_user(u.id, 1);
        end loop;

        -- Delete all servers.
        for s in servers(org_id_in) loop
            delete_server(s.id);
        end loop;

        -- Delete all config channels.
        for c in config_channels loop
            rhn_config.delete_channel(c.id);
        end loop;

        -- Give the org's entitlements back to the main org.
        rhn_entitlements.remove_org_entitlements(org_id_in);

        -- Clean up tables where we don't have a cascading delete.
        delete from rhnChannel where org_id = org_id_in;
        delete from rhnDailySummaryQueue where org_id = org_id_in;
        delete from rhnOrgQuota where org_id = org_id_in;
        delete from rhnOrgInfo where org_id = org_id_in;
        delete from rhnFileList where org_id = org_id_in;
        delete from rhnServerGroup where org_id = org_id_in;
        delete from rhn_check_suites where customer_id = org_id_in;
        delete from rhn_command_target where customer_id = org_id_in;
        delete from rhn_contact_groups where customer_id = org_id_in;
        delete from rhn_notification_formats where customer_id = org_id_in;
        delete from rhn_probe where customer_id = org_id_in;
        delete from rhn_redirects where customer_id = org_id_in;
        delete from rhn_sat_cluster where customer_id = org_id_in;
        delete from rhn_schedules where customer_id = org_id_in;

        -- Delete the org.
        delete from web_customer where id = org_id_in;

    end delete_org;

	procedure delete_user(user_id_in in number, deleting_org in number := 0) is
		cursor is_admin is
			select	1
			from	rhnUserGroupType	ugt,
					rhnUserGroup		ug,
					rhnUserGroupMembers	ugm
			where	ugm.user_id = user_id_in
				and ugm.user_group_id = ug.id
				and ug.group_type = ugt.id
				and ugt.label = 'org_admin';
		cursor servergroups_needing_admins is
			select	usgp.server_group_id	server_group_id
			from	rhnUserServerGroupPerms	usgp
			where	1=1
				and usgp.user_id = user_id_in
				and not exists (
					select	1
					from	rhnUserServerGroupPerms	sq_usgp
					where	1=1
						and sq_usgp.server_group_id = usgp.server_group_id
						and	sq_usgp.user_id != user_id_in
				);
		cursor messages is
			select	message_id id
			from	rhnUserMessage
			where	user_id = user_id_in;
		users			number;
		our_org_id		number;
		other_users		number;
		other_org_admin	number;
        other_user_id  number;
	begin
		select	wc.org_id
		into	our_org_id
		from	web_contact wc
		where	id = user_id_in;

		-- find any other users
		begin
			select	id, 1
			into	other_user_id, other_users
			from	web_contact
			where	1=1
				and org_id = our_org_id
				and id != user_id_in
				and rownum = 1;
		exception
			when no_data_found then
				other_users := 0;
		end;

		-- now do org admin stuff
		if other_users != 0 then
			for ignore in is_admin loop
				begin 
					select	new_ugm.user_id
					into	other_org_admin
					from	rhnUserGroupMembers	new_ugm,
							rhnUserGroupType	ugt,
							rhnUserGroup		ug,
							rhnUserGroupMembers	ugm
					where	ugm.user_id = user_id_in
						and ugm.user_group_id = ug.id
						and ug.group_type = ugt.id
						and ugt.label = 'org_admin'
						and ug.id = new_ugm.user_group_id
						and new_ugm.user_id != user_id_in
						and rownum = 1;
				exception
					when no_data_found then
                        -- If we're deleting the org, we don't want to raise
                        -- the exception.
                        if deleting_org = 0 then
    						rhn_exception.raise_exception('cannot_delete_user');
                        end if;
				end;

				for sg in servergroups_needing_admins loop
					rhn_user.add_servergroup_perm(other_org_admin,
						sg.server_group_id);
				end loop;
			end loop;
		end if;

		-- and now things for every user
		for message in messages loop
			delete
				from	rhnUserMessage
				where	user_id = user_id_in
					and message_id = message.id;
			begin
				select	1
				into	users
				from	rhnUserMessage
				where	message_id = message.id
					and rownum = 1;
				delete
					from	rhnMessage
					where	id = message.id;
			exception
				when no_data_found then
					null;
			end;
		end loop;
		delete from rhn_command_queue_sessions where contact_id = user_id_in;
		delete from rhn_contact_methods where contact_id = user_id_in;
		delete from rhn_redirects where contact_id = user_id_in;
		delete from rhnUserServerPerms where user_id = user_id_in;
		if other_users != 0 then
			update		rhnRegToken
				set		user_id = nvl(other_org_admin, other_user_id)
				where	org_id = our_org_id
					and user_id = user_id_in;
			begin
				delete from web_contact where id = user_id_in;
			exception
				when others then
					rhn_exception.raise_exception('cannot_delete_user');
			end;
        -- Just Delete the user
		else
            begin
                delete from web_contact where id = user_id_in;
		    exception
				when others then
					rhn_exception.raise_exception('cannot_delete_user');
			end;
		end if;
		return;
	end delete_user;

END rhn_org;
/
SHOW ERRORS

-- $Log$
-- Revision 1.22  2004/10/29 04:50:49  pjones
-- bugzilla: 135179 -- fix org admin swapping during user deletion
--
-- Revision 1.21  2004/07/13 22:46:04  pjones
-- bugzilla: 125938 -- nothing uses update_errata_cache() any more, remove it
--
-- Revision 1.20  2004/07/02 22:24:38  pjones
-- bugzilla: none -- typo fix
--
-- Revision 1.19  2004/07/02 19:19:02  pjones
-- bugzilla: 125937 -- use rhn_user to grant roles to users
--
-- Revision 1.18  2004/05/28 22:21:36  pjones
-- bugzilla: none -- update for monitoring schema
--
-- Revision 1.17  2004/04/05 16:31:07  pjones
-- bugzilla: 120032 -- raise "cannot_delete_user" if web_contact or web_customer
-- has a cascade problem
--
-- Revision 1.16  2004/03/15 17:10:28  pjones
-- bugzilla: 118244 -- delete servers explicitly while deleting lone users
--
-- Revision 1.15  2004/02/09 17:14:54  pjones
-- bugzilla: none -- fix log garbage
--
-- Revision 1.14  2004/01/22 19:44:42  pjones
-- bugzilla: 106562 -- fix exceptions on delete_user()
--
-- Revision 1.13  2004/01/20 17:00:48  pjones
-- bugzilla: none -- try to make delete_user() succeed when there are
-- server groups that have been snapshotted
--
-- Revision 1.12  2004/01/14 20:22:03  pjones
-- bugzilla: 113344 -- no deleting from rhnServerGroup, use the api instead
--
-- Revision 1.11  2003/03/20 17:08:16  pjones
-- avoid the server group members trigger that updates last_modified; it'll
-- cause a mutating table error
--
-- Revision 1.10  2003/03/17 16:31:25  pjones
-- use "on delete set null" where applicable
--
-- Revision 1.9  2003/03/15 00:31:07  pjones
-- bugzilla: none
--
-- tested wrong table for perms on a server group
--
-- Revision 1.8  2003/03/15 00:23:36  pjones
-- bugzilla: 83631
--
-- working delete_user
--
-- Revision 1.7  2003/03/03 23:39:36  pjones
-- different delete_user; this one might actually work.
--
-- Takes about 18 seconds, which seems kindof slow, but isn't
-- intolerable I don't think...
--
-- Revision 1.6  2003/03/02 18:07:00  pjones
-- make it use marty's test instead of is_satellite(); in the sat env,
-- marty's test _is_ is_satellite()
--
-- Revision 1.5  2003/02/18 16:35:45  pjones
-- delete_user
--
-- Revision 1.4  2002/05/10 22:08:23  pjones
-- id/log
--
 070701000003F2000081B400000000000000000000000167AE111400002129000000000000000000000000000000000000006100000000susemanager-schema/upgrade/rhn-satellite-schema-5.1-to-spacewalk-schema-0.2/208-rhn_user.pkb.sql  --
-- Copyright (c) 2008 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
-- $Id$
--

create or replace
package body rhn_user
is
	body_version varchar2(100) := '$Id$';
	
    function check_role(user_id_in in number, role_in in varchar2)
    return number
    is
    	throwaway number;
    begin
    	-- the idea: if we get past this query, the org has the setting, else catch the exception and return 0
	select 1 into throwaway
	  from rhnUserGroupType UGT,
	       rhnUserGroup UG,
	       rhnUserGroupMembers UGM
	 where UGM.user_id = user_id_in
	   and UGM.user_group_id = UG.id
	   and UG.group_type = UGT.id
	   and UGT.label = role_in;
	   
	return 1;
    exception
    	when no_data_found
	    then
	    return 0;
    end check_role;
    
    function check_role_implied(user_id_in in number, role_in in varchar2)
    return number
    is
    	throwaway number;
    begin
    	-- if the user directly has the role, they win
    	if rhn_user.check_role(user_id_in, role_in) = 1
	then
	    return 1;
    	end if;

	-- config_admin and channel_admin are automatically implied for org admins	
	if role_in = 'config_admin' and rhn_user.check_role(user_id_in, 'org_admin') = 1
	then
	    return 1;
	end if;

	if role_in = 'channel_admin' and rhn_user.check_role(user_id_in, 'org_admin') = 1
	then
	    return 1;
	end if;

	return 0;	
    end check_role_implied;
    
    function get_org_id(user_id_in in number)
    return number
    is
    	org_id_out number;
    begin
    	select org_id into org_id_out
	  from web_contact
	 where id = user_id_in;
	 
	return org_id_out;
    end get_org_id;

	-- paid users often don't have verified email addresses, so
	-- try to find an address that is useful to us.
	function find_mailable_address(user_id_in in number)
	return varchar2 is
		PRAGMA AUTONOMOUS_TRANSACTION;
		-- this would be so much prettier if we just had an order built
		-- into rhnEmailAddressState
		cursor addrs is
			select	ea.state_id, ea.address
			from	rhnEmailAddressState eas,
					rhnEmailAddress ea
			where	ea.user_id = user_id_in
				and eas.label = 'verified'
				and ea.state_id = eas.id
			union all
			select	ea.state_id, ea.address
			from	rhnEmailAddressState eas,
					rhnEmailAddress ea
			where	ea.user_id = user_id_in
				and eas.label = 'unverified'
				and ea.state_id = eas.id
			union all
			select	ea.state_id, ea.address
			from	rhnEmailAddressState eas,
					rhnEmailAddress ea
			where	ea.user_id = user_id_in
				and eas.label = 'pending'
				and ea.state_id = eas.id
			union all
			select	ea.state_id, ea.address
			from	rhnEmailAddressState eas,
					rhnEmailAddress ea
			where	ea.user_id = user_id_in
				and eas.label = 'pending_warned'
				and ea.state_id = eas.id
			union all
			select	ea.state_id, ea.address
			from	rhnEmailAddressState eas,
					rhnEmailAddress ea
			where	ea.user_id = user_id_in
				and eas.label = 'needs_verifying'
				and ea.state_id = eas.id
			union all
			select	-1 state_id,
					email address
			from	web_user_personal_info
			where	web_user_id = user_id_in;
		retval rhnEmailAddress.address%TYPE;
	begin
		for addr in addrs loop
			retval := addr.address;
			if addr.address is null then
				update web_user_contact_permission
					set email = 'N'
					where web_user_id = user_id_in;
				commit;
				return null;
			end if;
			if addr.state_id = -1 then
				insert into rhnEmailAddress (
						id, address,
						user_id, state_id
					) (
						select	rhn_eaddress_id_seq.nextval, addr.address,
								user_id_in, eas.id
						from	rhnEmailAddressState eas
						where	eas.label = 'unverified'
					);
			end if;
			commit;
			return retval;
		end loop;
		return null;
	end;

	procedure add_servergroup_perm(
		user_id_in in number,
		server_group_id_in in number
	) is
		cursor	orgs_match is
			select	1
			from	rhnServerGroup sg,
					web_contact u
			where	u.id = user_id_in
				and sg.id = server_group_id_in
				and sg.org_id = u.org_id;
	begin
		for okay in orgs_match loop
			insert into rhnUserServerGroupPerms(user_id, server_group_id)
				values (user_id_in, server_group_id_in);
			rhn_cache.update_perms_for_user(user_id_in);
			return;
		end loop;
		rhn_exception.raise_exception('usgp_different_orgs');
	exception when dup_val_on_index then
		rhn_exception.raise_exception('usgp_already_allowed');
	end add_servergroup_perm;

	procedure remove_servergroup_perm(
		user_id_in in number,
		server_group_id_in in number
	) is
		cursor perms is
			select	1
			from	rhnUserServerGroupPerms
			where	user_id = user_id_in
				and server_group_id = server_group_id_in;
	begin
		for perm in perms loop
			delete from rhnUserServerGroupPerms
				where	user_id = user_id_in
					and server_group_id = server_group_id_in;
			rhn_cache.update_perms_for_user(user_id_in);
			return;
		end loop;
		rhn_exception.raise_exception('usgp_not_allowed');
	end remove_servergroup_perm;

	procedure add_to_usergroup(
		user_id_in in number,
		user_group_id_in in number
	) is
		cursor perm_granting_usergroups is
			select	user_group_id_in
			from	rhnUserGroup		ug,
					rhnUserGroupType	ugt
			where	ugt.label in ('org_admin') -- and server_group_admin ?
				and ug.id = user_group_id_in
				and ug.group_type = ugt.id;
	begin
		insert into rhnUserGroupMembers(user_id, user_group_id)
			values (user_id_in, user_group_id_in);

		for ug in perm_granting_usergroups loop
			rhn_cache.update_perms_for_user(user_id_in);
			return;
		end loop;
	end add_to_usergroup;

	procedure add_users_to_usergroups(
		user_id_in in number
	) is
		cursor ugms is
			select	element user_id,
					element_two user_group_id
			from	rhnSet
			where	user_id = user_id_in
				and label = 'user_group_list';
	begin
		for ugm in ugms loop
			rhn_user.add_to_usergroup(ugm.user_id, ugm.user_group_id);
		end loop;
	end add_users_to_usergroups;

	procedure remove_from_usergroup(
		user_id_in in number,
		user_group_id_in in number
	) is
		cursor perm_granting_usergroups is
			select	label
			from	rhnUserGroupType	ugt,
					rhnUserGroupMembers	ugm,
					rhnUserGroup		ug
			where	1=1
				and ug.id = user_group_id_in
				and ugm.user_group_id = user_group_id_in
				and ug.group_type = ugt.id
				and ugm.user_id = user_id_in;
	begin
		-- we only do anything if you're really in the group, because
		-- testing is significantly cheaper than rebuilding the user's
		-- cache for no reason.
		for ug in perm_granting_usergroups loop
			delete from rhnUserGroupMembers
				where	user_id = user_id_in
					and user_group_id = user_group_id_in;
			if ug.label in ('org_admin') then
				rhn_cache.update_perms_for_user(user_id_in);
			end if;
		end loop;
	end remove_from_usergroup;

	procedure remove_users_from_servergroups(
		user_id_in in number
	) is
		cursor ugms is
			select	element user_id,
					element_two user_group_id
			from	rhnSet
			where	user_id = user_id_in
				and label = 'user_group_list';
	begin
		for ugm in ugms loop
			rhn_user.remove_from_usergroup(ugm.user_id, ugm.user_group_id);
		end loop;
	end remove_users_from_servergroups;
end rhn_user;
/
SHOW ERRORS

-- select rhn_user.get_org_id(502474) from dual;
-- 1271287
-- select rhn_user.check_role(502474, 'org_admin') from dual;
-- 1
-- select rhn_user.check_role(502474, 'org_admin_nope') from dual;
-- 0, but should later raise an exception

--
-- $Log$
-- Revision 1.8  2004/07/12 19:35:51  pjones
-- bugzilla: 125937 -- we _always_ delete, but only rebuild cache on org_admin.
--
-- Revision 1.7  2004/07/02 22:29:36  pjones
-- bugzilla: none -- typos and spelling errors.
--
-- Revision 1.6  2004/07/02 19:16:54  pjones
-- bugzilla: 125937 -- tools to manipulate rhnServerGroupMembers and
-- rhnUserGroupMembers
--
-- Revision 1.5  2004/03/31 21:09:47  pjones
-- bugzilla: none -- if the user truly doesn't have any email address, compensate.
--
-- Revision 1.4  2004/02/12 20:53:30  pjones
-- bugzilla: 108212 -- s/get_email_address/find_mailable_address/ and make it
-- do the same as web's version
--
   070701000003F3000081B400000000000000000000000167AE1114000006D3000000000000000000000000000000000000006100000000susemanager-schema/upgrade/rhn-satellite-schema-5.1-to-spacewalk-schema-0.2/208-rhn_user.pks.sql  --
-- Copyright (c) 2008 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
-- $Id$
--

create or replace
package rhn_user
is
	version varchar2(100) := '$Id$';

    function check_role(user_id_in in number, role_in in varchar2) return number;
    PRAGMA RESTRICT_REFERENCES(check_role, WNDS, RNPS, WNPS);

    function check_role_implied(user_id_in in number, role_in in varchar2) return number;
    PRAGMA RESTRICT_REFERENCES(check_role_implied, WNDS, RNPS, WNPS);

    function get_org_id(user_id_in in number) return number;
    PRAGMA RESTRICT_REFERENCES(get_org_id, WNDS, RNPS, WNPS);
    
	function find_mailable_address(user_id_in in number) return varchar2;

	procedure add_servergroup_perm(
		user_id_in in number,
		server_group_id_in in number
	);

	procedure remove_servergroup_perm(
		user_id_in in number,
		server_group_id_in in number
	);

	procedure add_to_usergroup(
		user_id_in in number,
		user_group_id_in in number
	);

	procedure add_users_to_usergroups(
		user_id_in in number
	);

	procedure remove_from_usergroup(
		user_id_in in number,
		user_group_id_in in number
	);

	procedure remove_users_from_servergroups(
		user_id_in in number
	);
end rhn_user;
/
SHOW ERRORS
 070701000003F4000081B400000000000000000000000167AE1114000012B7000000000000000000000000000000000000006900000000susemanager-schema/upgrade/rhn-satellite-schema-5.1-to-spacewalk-schema-0.2/500-rhnPrivateErrataMail.sql  -- This view is used for extracting data needed by the errata mailer
-- for private errata mails
--
-- $Id$

create or replace view
rhnPrivateErrataMail
as
with rhnSPmaxEVR as (
   select   sq2_sp.server_id, sq2_sp.name_id, max(sq2_pe.evr) max_evr
            from  rhnServerPackage  sq2_sp,
               rhnPackageEVR     sq2_pe
            where sq2_sp.evr_id = sq2_pe.id
	    group by sq2_sp.server_id, sq2_sp.name_id)
select
   w.login, 
   w.login_uc,
   wpi.email,  
   w.id user_id,
   s.id server_id,  
   -- use sg here so we can start with org and work to errata from there
   w.org_id org_id, 
   s.name server_name,  
   sa.name server_arch,  
   s.release server_release,  
   ce.errata_id errata_id,
   e.advisory
from
   rhnServer s,
   web_user_personal_info wpi,
   rhnUserInfo ui,
   rhnErrata e,
   rhnServerArch sa,
   rhnChannelErrata ce,
   web_contact w, 
   rhnServerChannel sc,
   rhnServerGroupMembers sgm,
   rhnServerGroup sg
where 1=1
   -- we plan on starting with org_id, and server group is the 
   -- best place to find that that's near servers
   and sg.id = sgm.server_group_id
   and sgm.server_id = sc.server_id
   -- then find the contacts, because permission checking is next
   and sg.org_id = w.org_id
   -- filter out users who don't want mail about this server
   -- they get an entry if they _don't_ want mail
   and not exists (
      select   usprefs.server_id 
               from  rhnUserServerPrefs usprefs
         where 1=1
         and w.id = usprefs.user_id 
               and sc.server_id = usprefs.server_id 
               and usprefs.name = 'receive_notifications'
   )
   -- filter out users who don't want/can't get email
   and w.id = wpi.web_user_id
   and wpi.email is not null
   and w.id = ui.user_id
      and ui.email_notify = 1
      -- check permissions. For this query being an org admin is the
      -- most common thing, so we test for that first
   and exists (
      select   1
      from  
         rhnUserGroupType  ugt,
         rhnUserGroup      ug,
         rhnUserGroupMembers  ugm
      where 1=1
         and ugt.label = 'org_admin'
         and ugt.id = ug.group_type
         and ug.id = ugm.user_group_id
         and ugm.user_id = w.id
      union all
      select   1
      from
         rhnServerGroupMembers   sq_sgm,
         rhnUserServerGroupPerms usg
      where sc.server_id = sq_sgm.server_id
         and sq_sgm.server_group_id = usg.server_group_id
         and usg.user_id = w.id
   )
   -- filter out servers that aren't in useful channels
   and sc.channel_id = ce.channel_id
   -- find the server, so we can do s.arch comparisons
   and sc.server_id = s.id
      and exists (
         select 1
      from
            rhnPackageEVR        p_evr,
            rhnPackageEVR        sp_evr,
            rhnServerPackage     sp,
            rhnChannelPackage    cp,
            rhnPackage        p,
            rhnErrataPackage     ep,
            rhnServerPackageArchCompat spac
      where 1=1
         -- packages from channels this server is subscribed to
         and sc.channel_id = cp.channel_id
         and cp.package_id = p.id
         -- part of an errata
         and ce.errata_id = ep.errata_id
         and ep.package_id = p.id
         -- and that errata maps back to the server channel
         and sc.channel_id = ce.channel_id
         and ce.errata_id = ep.errata_id
         -- also installed on this server
         and sc.server_id = sp.server_id
         and sp.name_id = p.name_id
         and sp.evr_id = sp_evr.id
         -- different evr
         and p.evr_id = p_evr.id
         and sp.evr_id != p.evr_id
         -- and newer evr
         and sp_evr.evr < p_evr.evr
         and sp_evr.evr = (
            select max_evr from rhnSPmaxEVR rsme
	    where sp.server_id = rsme.server_id
               and sp.name_id = rsme.name_id
         )
         -- compat arch
         and p.package_arch_id = spac.package_arch_id
         and s.server_arch_id = spac.server_arch_id
   )
   -- below here isn't needed except for output
   and s.server_arch_id = sa.id
   and ce.errata_id = e.id
   and not exists ( select 1
                      from rhnWebContactDisabled wcd
                     where wcd.id = w.id )
/


--select count(*) from rhnMailErrataView
--where org_id = 1 and errata_id = 916;

-- $Log$
-- Revision 1.2  2003/02/21 20:56:00  pjones
-- change the comments to match the code ;)
--
-- Revision 1.1  2003/02/21 20:45:00  pjones
-- private errata mail
--
-- Revision 1.4  2003/02/12 18:49:11  pjones
-- note about old errata
--
-- Revision 1.3  2002/11/14 17:20:34  pjones
-- arch -> *_arch_id and archCompat changes
--
-- Revision 1.2  2002/11/11 20:49:46  pjones
-- that line's a typo
--
-- Revision 1.1  2002/09/24 22:42:17  pjones
-- free vs paid
--
 070701000003F5000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000004800000000susemanager-schema/upgrade/satellite-schema-5.3-to-spacewalk-schema-0.6   070701000003F6000081B400000000000000000000000167AE11140000024C000000000000000000000000000000000000006D00000000susemanager-schema/upgrade/satellite-schema-5.3-to-spacewalk-schema-0.6/100-rhnServerNeededCache_indexes.sql  -- rhn_snc_speid_idx index is also created during 0.4 -> 0.5 schema upgrades,
-- but is left out of the base 0.5 schema.

declare
	name_used exception;
	pragma exception_init(name_used, -00955);
begin
	execute immediate 'create index rhn_snc_speid_idx
		on rhnServerNeededCache(server_id, package_id, errata_id)
		noparallel
		tablespace [[128m_tbs]]
		nologging';
exception
	when name_used then
		execute immediate 'alter index rhn_snc_speid_idx noparallel';
end;
/

alter index rhn_snc_pid_idx noparallel;
alter index rhn_snc_sid_idx noparallel;
alter index rhn_snc_eid_idx noparallel;
070701000003F7000081B400000000000000000000000167AE111400002486000000000000000000000000000000000000006000000000susemanager-schema/upgrade/satellite-schema-5.3-to-spacewalk-schema-0.6/104-rhn_channel.pks.sql   --
-- Copyright (c) 2008 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--

CREATE OR REPLACE
PACKAGE rhn_channel
IS
	version varchar2(100) := '';

    CURSOR server_base_subscriptions(server_id_in NUMBER) IS
    	   SELECT C.id
	     FROM rhnChannel C, rhnServerChannel SC
	    WHERE C.id = SC.channel_id
	      AND SC.server_id = server_id_in
	      AND C.parent_channel IS NULL;
	      
    CURSOR check_server_subscription(server_id_in NUMBER, channel_id_in NUMBER) IS 
           SELECT channel_id 
	     FROM rhnServerChannel 
	    WHERE server_id = server_id_in 
	      AND channel_id = channel_id_in;

    CURSOR check_server_parent_membership(server_id_in NUMBER, channel_id_in NUMBER) IS
    	   SELECT C.id
	     FROM rhnChannel C, rhnServerChannel SC
	    WHERE C.parent_channel = channel_id_in
	      AND C.id = SC.channel_id
	      AND SC.server_id = server_id_in;
	    
    CURSOR channel_family_perm_cursor(channel_family_id_in NUMBER, org_id_in NUMBER) IS
           SELECT *
	     FROM rhnOrgChannelFamilyPermissions
	    WHERE channel_family_id = channel_family_id_in
	      AND org_id = org_id_in;

    PROCEDURE license_consent(channel_id_in IN NUMBER, user_id_in IN NUMBER, server_id_in IN NUMBER);
    FUNCTION get_license_path(channel_id_in IN NUMBER) RETURN VARCHAR2;

    PROCEDURE unsubscribe_server(server_id_in IN NUMBER, channel_id_in NUMBER, immediate_in NUMBER := 1, unsubscribe_children_in number := 0,
                                 deleting_server in number := 0 );
    PROCEDURE subscribe_server(server_id_in IN NUMBER, channel_id_in NUMBER, immediate_in NUMBER := 1, user_id_in number := null, recalcfamily_in number := 1);
	
    function can_server_consume_virt_channl(
        server_id_in IN NUMBER,
        family_id_in in number)
    return number;

    FUNCTION guess_server_base(server_id_in IN NUMBER) RETURN NUMBER;

    FUNCTION base_channel_for_release_arch(release_in in varchar2, 
	server_arch_in in varchar2, org_id_in in number := -1, 
	user_id_in in number := null) RETURN number;

    FUNCTION base_channel_rel_archid(release_in in varchar2, 
	server_arch_id_in in number, org_id_in in number := -1, 
	user_id_in in number := null) RETURN number;

    FUNCTION channel_priority(channel_id_in in number) RETURN number;
    
    PROCEDURE bulk_subscribe_server(channel_id_in IN NUMBER, set_label_in IN VARCHAR2, set_uid_in IN NUMBER);
    PROCEDURE bulk_unsubscribe_server(channel_id_in IN NUMBER, set_label_in IN VARCHAR2, set_uid_in IN NUMBER);
    
    PROCEDURE bulk_server_base_change(channel_id_in IN NUMBER, set_label_in IN VARCHAR2, set_uid_in IN NUMBER);
    procedure bulk_server_basechange_from(
	set_label_in in varchar2,
	set_uid_in in number,
	old_channel_id_in in number,
	new_channel_id_in in number);

    procedure bulk_guess_server_base(
	set_label_in in varchar2,
	set_uid_in in number);

    procedure bulk_guess_server_base_from(
	set_label_in in varchar2,
	set_uid_in in number,
	channel_id_in in number);

    PROCEDURE clear_subscriptions(server_id_in IN NUMBER, deleting_server in number := 0 );
    
    FUNCTION available_family_subscriptions(channel_family_id_in IN NUMBER, org_id_in IN NUMBER) RETURN NUMBER;

    function channel_family_current_members(channel_family_id_in IN NUMBER,
                                            org_id_in IN NUMBER)
    return number;

    PROCEDURE update_family_counts(channel_family_id_in IN NUMBER, org_id_in IN NUMBER);
    FUNCTION family_for_channel(channel_id_in IN NUMBER) RETURN NUMBER;

    FUNCTION available_chan_subscriptions(channel_id_in IN NUMBER, org_id_in IN NUMBER) RETURN NUMBER;

    procedure entitle_customer(customer_id_in in number, channel_family_id_in in number, quantity_in in number);
    procedure set_family_maxmembers(customer_id_in in number, channel_family_id_in in number, quantity_in in number);
    procedure unsubscribe_server_from_family(server_id_in in number, channel_family_id_in in number);

    procedure delete_server_channels(server_id_in in number);
    procedure refresh_newest_package(channel_id_in in number, caller_in in varchar2 := '(unknown)');
    
    function get_org_id(channel_id_in in number) return number;
    PRAGMA RESTRICT_REFERENCES(get_org_id, WNDS, RNPS, WNPS);

    function get_org_access(channel_id_in in number, org_id_in in number) return number;
    PRAGMA RESTRICT_REFERENCES(get_org_access, WNDS, RNPS, WNPS);
    
    function get_cfam_org_access(cfam_id_in in number, org_id_in in number) return number;

    function user_role_check_debug(channel_id_in in number, user_id_in in number, role_in in varchar2, reason_out out varchar2)
    	RETURN NUMBER;
    PRAGMA RESTRICT_REFERENCES(user_role_check_debug, WNDS, RNPS, WNPS);

    function user_role_check(channel_id_in in number, user_id_in in number, role_in in varchar2)
    	RETURN NUMBER;
    PRAGMA RESTRICT_REFERENCES(user_role_check, WNDS, RNPS, WNPS);
    
    function loose_user_role_check(channel_id_in in number, user_id_in in number, role_in in varchar2)
    	RETURN NUMBER;
    PRAGMA RESTRICT_REFERENCES(loose_user_role_check, WNDS, RNPS, WNPS);

    function direct_user_role_check(channel_id_in in number, user_id_in in number, role_in in varchar2)
    	RETURN NUMBER;
    PRAGMA RESTRICT_REFERENCES(direct_user_role_check, WNDS, RNPS, WNPS);

    function shared_user_role_check(channel_id in number, user_id in number, role in varchar2)
    	RETURN NUMBER;
    PRAGMA RESTRICT_REFERENCES(shared_user_role_check, WNDS, RNPS, WNPS);

    function org_channel_setting(channel_id_in in number, org_id_in in number, setting_in in varchar2)
    	RETURN NUMBER;

    PROCEDURE update_channel ( channel_id_in in number, invalidate_ss in number := 0, 
                               date_to_use in date := sysdate );

    PROCEDURE  update_channels_by_package ( package_id_in in number, date_to_use in date := sysdate );

     PROCEDURE update_channels_by_errata ( errata_id_in number, date_to_use in date := sysdate );


    PRAGMA RESTRICT_REFERENCES(org_channel_setting, WNDS, RNPS, WNPS);

END rhn_channel;
/
SHOW ERRORS

--
-- Revision 1.37  2004/04/14 00:09:24  pjones
-- bugzilla: 120761 -- split rhnChannelPermissions into two tables, eliminating
-- a frequent full table scan
--
-- Revision 1.36  2004/03/26 18:11:32  rbb
-- Bugzilla:  114057
--
-- Add a script to determine channel priority.
--
-- Revision 1.35  2004/02/17 20:16:52  pjones
-- bugzilla: none -- add cvs tags into the package as long as we're touching
-- it anyway
--
-- Revision 1.34  2003/11/13 18:13:09  cturner
-- pragmas can now return now that rhn_user pragmas are fixed
--
-- Revision 1.32  2003/09/22 21:00:40  cturner
-- add method for easy acl check
--
-- Revision 1.31  2003/09/17 22:14:11  misa
-- bugzilla: 103639  Changes to allow me to move the base channel guess into plsql
--
-- Revision 1.30  2003/07/24 16:44:16  misa
-- bugzilla: none  A function more usable on the rhnapp side
--
-- Revision 1.29  2003/07/24 14:00:17  misa
-- bugzilla: none  PRAGMA RESTRICT_REFERENCES good
--
-- Revision 1.28  2003/07/23 21:59:19  cturner
-- rework how rhnUserChannel works; move to plsql for speed and maintenance
--
-- Revision 1.27  2003/07/21 17:49:12  pjones
-- bugzilla: none
--
-- add optional user for subscribe_server
--
-- Revision 1.26  2002/12/19 18:13:42  misa
-- Added caller with a default value
--
-- Revision 1.25  2002/12/11 22:18:46  pjones
-- rhnChannelNewestPackage
--
-- Revision 1.24  2002/11/21 22:08:11  pjones
-- make unsubscribe_channels have a "unsubscribe_children_in number := 0"
-- argument so that you can tell it to unsubscribe children.
--
-- Also, make it raise an exception instead of silent failure in the
-- other case.
--
-- Revision 1.23  2002/11/18 17:20:50  pjones
-- this should have gone back too
--
-- Revision 1.22  2002/11/13 23:16:18  pjones
-- lookup_*_arch()
--
-- Revision 1.21  2002/10/07 20:01:59  rnorwood
-- guess base channel for ssm and single system
--
-- Revision 1.20  2002/10/02 19:21:03  bretm
-- o  3rd party channel schema changes, no more clobs...
--
-- Revision 1.19  2002/09/20 19:21:58  bretm
-- o  more 3rd party channel stuff...
--
-- Revision 1.18  2002/06/12 22:33:03  pjones
-- procedure bulk_guess_server_base_from(
--     set_label_in in varchar2,
--     set_uid_in in number,
--     channel_id_in in number);
--
-- for bretm
--
-- Revision 1.17  2002/06/12 22:12:25  pjones
-- procedure bulk_guess_server_base(
--     set_label_in in varchar2,
--     set_uid_in in number);
--
-- for bretm
--
-- Revision 1.16  2002/06/12 19:37:55  pjones
-- bulk_server_basechange_from(
-- 	set_label_in in varchar2,
-- 	set_uid_in in number,
-- 	old_channel_id_in in number,
-- 	new_channel_id_in in number
-- );
--
-- for bretm
--
-- Revision 1.15  2002/05/10 22:08:22  pjones
-- id/log
--
  070701000003F8000081B400000000000000000000000167AE11140000C832000000000000000000000000000000000000006000000000susemanager-schema/upgrade/satellite-schema-5.3-to-spacewalk-schema-0.6/105-rhn_channel.pkb.sql   --
-- Copyright (c) 2008 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--

CREATE OR REPLACE
PACKAGE BODY rhn_channel
IS
        body_version varchar2(100) := '';

    -- Cursor that fetches all the possible base channels for a
    -- (server_arch_id, release, org_id) combination
        cursor  base_channel_cursor(
                release_in in varchar2,
                server_arch_id_in in number,
                org_id_in in number
        ) return rhnChannel%ROWTYPE is
                select distinct c.*
                from    rhnDistChannelMap                       dcm,
                                rhnServerChannelArchCompat      scac,
                                rhnChannel                                      c,
                                rhnChannelPermissions           cp
                where   cp.org_id = org_id_in
                        and cp.channel_id = c.id
                        and c.parent_channel is null
                        and c.id = dcm.channel_id
                        and c.channel_arch_id = dcm.channel_arch_id
                        and dcm.release = release_in
                        and scac.server_arch_id = server_arch_id_in
                        and scac.channel_arch_id = c.channel_arch_id;

    FUNCTION get_license_path(channel_id_in IN NUMBER)
    RETURN VARCHAR2
    IS
        license_val VARCHAR2(1000);
    BEGIN
        SELECT CFL.license_path INTO license_val
          FROM rhnChannelFamilyLicense CFL, rhnChannelFamilyMembers CFM
         WHERE CFM.channel_id = channel_id_in
           AND CFM.channel_family_id = CFL.channel_family_id;
    
        RETURN license_val;

    EXCEPTION
        WHEN NO_DATA_FOUND
            THEN
            RETURN NULL;
    END get_license_path;


    PROCEDURE license_consent(channel_id_in IN NUMBER, user_id_in IN NUMBER, server_id_in IN NUMBER)
    IS
        channel_family_id_val NUMBER;
    BEGIN
        channel_family_id_val := rhn_channel.family_for_channel(channel_id_in);
        IF channel_family_id_val IS NULL
        THEN
            rhn_exception.raise_exception('channel_subscribe_no_family');
        END IF;
        
        IF rhn_channel.get_license_path(channel_id_in) IS NULL
        THEN
            rhn_exception.raise_exception('channel_consent_no_license');
        END IF;
        
        INSERT INTO rhnChannelFamilyLicenseConsent (channel_family_id, user_id, server_id)
        VALUES (channel_family_id_val, user_id_in, server_id_in);
    END license_consent;

    PROCEDURE subscribe_server(server_id_in IN NUMBER, channel_id_in NUMBER, immediate_in NUMBER := 1, user_id_in in number := null, recalcfamily_in NUMBER := 1)
    IS
        channel_parent_val      rhnChannel.parent_channel%TYPE;
        parent_subscribed       BOOLEAN;
        server_has_base_chan    BOOLEAN;
        server_already_in_chan  BOOLEAN;
        channel_family_id_val   NUMBER;
        server_org_id_val       NUMBER;
        available_subscriptions NUMBER;
        consenting_user         NUMBER;
        allowed                 number := 0;
        current_members_val     number;
    BEGIN
        if user_id_in is not null then
            allowed := rhn_channel.user_role_check(channel_id_in, user_id_in, 'subscribe');
        else
            allowed := 1;
        end if;

        if allowed = 0 then
            rhn_exception.raise_exception('no_subscribe_permissions');
        end if;


        SELECT parent_channel INTO channel_parent_val FROM rhnChannel WHERE id = channel_id_in;

        IF channel_parent_val IS NOT NULL
        THEN    
            -- child channel; if attempting to cross-subscribe a child to the wrong base, silently ignore
            parent_subscribed := FALSE;    

            FOR check_subscription IN check_server_subscription(server_id_in, channel_parent_val)
            LOOP
                parent_subscribed := TRUE;
            END LOOP check_subscription;
        
            IF NOT parent_subscribed
            THEN
                RETURN;
            END IF;
        ELSE
            -- base channel
            server_has_base_chan := FALSE;
            FOR base IN server_base_subscriptions(server_id_in)
            LOOP
                server_has_base_chan := TRUE;
            END LOOP base;
            
            IF server_has_base_chan
            THEN
                rhn_exception.raise_exception('channel_server_one_base');
            END IF;
        END IF;
    
        FOR check_subscription IN check_server_subscription(server_id_in, channel_id_in)
        LOOP
            server_already_in_chan := TRUE;
        END LOOP check_subscription;
    
        IF server_already_in_chan
        THEN
            RETURN;
        END IF;
        
        channel_family_id_val := rhn_channel.family_for_channel(channel_id_in);
        IF channel_family_id_val IS NULL
        THEN
            rhn_exception.raise_exception('channel_subscribe_no_family');
        END IF;

        --
        -- Use the org_id of the server only if the org_id of the channel = NULL.
        -- This is required for subscribing to shared channels.
        --
        SELECT NVL(org_id, (SELECT org_id FROM rhnServer WHERE id = server_id_in))
          INTO server_org_id_val
          FROM rhnChannel
         WHERE id = channel_id_in;
         
        select current_members 
        into current_members_val
        from rhnPrivateChannelFamily
        where org_id = server_org_id_val and channel_family_id = channel_family_id_val
        for update of current_members;

        available_subscriptions := rhn_channel.available_family_subscriptions(channel_family_id_val, server_org_id_val);
        
        IF available_subscriptions IS NULL OR 
           available_subscriptions > 0 or
           can_server_consume_virt_channl(server_id_in, channel_family_id_val) = 1
        THEN
        
            IF rhn_channel.get_license_path(channel_id_in) IS NOT NULL
            THEN
                BEGIN
                
                SELECT user_id INTO consenting_user
                  FROM rhnChannelFamilyLicenseConsent
                 WHERE channel_family_id = channel_family_id_val
                   AND server_id = server_id_in;
                
                EXCEPTION
                    WHEN NO_DATA_FOUND THEN
                        rhn_exception.raise_exception('channel_subscribe_no_consent');
                END;
            END IF;
        
            insert into rhnServerHistory (id,server_id,summary,details) (
                select  rhn_event_id_seq.nextval,
                        server_id_in,
                        'subscribed to channel ' || SUBSTR(c.label, 0, 106),
                        c.label
                from    rhnChannel c
                where   c.id = channel_id_in
            );
            UPDATE rhnServer SET channels_changed = sysdate WHERE id = server_id_in;
            INSERT INTO rhnServerChannel (server_id, channel_id) VALUES (server_id_in, channel_id_in);
			IF recalcfamily_in > 0
			THEN
                rhn_channel.update_family_counts(channel_family_id_val, server_org_id_val);
			END IF;
            queue_server(server_id_in, immediate_in);
        ELSE
            rhn_exception.raise_exception('channel_family_no_subscriptions');
        END IF;
            
    END subscribe_server;
    
    function can_server_consume_virt_channl(
        server_id_in in number,
        family_id_in in number )
    return number
    is

        cursor server_virt_families is
            select vi.virtual_system_id, cfvsl.channel_family_id
            from
                rhnChannelFamilyVirtSubLevel cfvsl,
                rhnSGTypeVirtSubLevel sgtvsl,
                rhnVirtualInstance vi
            where
                vi.virtual_system_id = server_id_in 
                and sgtvsl.virt_sub_level_id = cfvsl.virt_sub_level_id
                and cfvsl.channel_family_id = family_id_in
                and exists (
                    select 1
                    from rhnServerEntitlementView sev
                    where vi.host_system_id = sev.server_id
                    and sev.server_group_type_id = sgtvsl.server_group_type_id );
    begin

        for server_virt_family in server_virt_families loop
            return 1;
        end loop;

        return 0;

    end;


    PROCEDURE bulk_subscribe_server(channel_id_in IN NUMBER, set_label_in IN VARCHAR2, set_uid_in IN NUMBER)
    IS
    BEGIN
        FOR server IN rhn_set.set_iterator(set_label_in, set_uid_in)
        LOOP
            rhn_channel.subscribe_server(server.element, channel_id_in, 0, set_uid_in);
        END LOOP server;
    END bulk_subscribe_server;

    PROCEDURE bulk_server_base_change(channel_id_in IN NUMBER, set_label_in IN VARCHAR2, set_uid_in IN NUMBER)
    IS
    BEGIN
        FOR server IN rhn_set.set_iterator(set_label_in, set_uid_in)
        LOOP
            IF rhn_server.can_change_base_channel(server.element) = 1
            THEN
                rhn_channel.clear_subscriptions(TO_NUMBER(server.element));
                rhn_channel.subscribe_server(server.element, channel_id_in, 0, set_uid_in);
            END IF;
        END LOOP server;
    END bulk_server_base_change;

    procedure bulk_server_basechange_from(
        set_label_in in varchar2,
        set_uid_in in number,
        old_channel_id_in in number,
        new_channel_id_in in number
    ) is
    cursor servers is
        select  sc.server_id id
        from    rhnChannel nc,
                rhnServerChannelArchCompat scac,
                rhnServer s,
                rhnChannel oc,
                rhnServerChannel sc,
                rhnSet st
        where   1=1
            -- first, find the servers we're looking for.
            and st.label = set_label_in
            and st.user_id = set_uid_in
            and st.element = sc.server_id
            -- now, filter out anything that's not in the
            -- old base channel.
            and sc.channel_id = old_channel_id_in
            and sc.channel_id = oc.id
            and oc.parent_channel is null
            -- now, see if it's compatible with the new base channel
            and nc.id = new_channel_id_in
            and nc.parent_channel is null
            and sc.server_id = s.id
            and s.server_arch_id = scac.server_arch_id
            and scac.channel_arch_id = nc.channel_arch_id;
    begin
        for s in servers loop
            insert into rhnSet (
                    user_id, label, element
                ) values (
                    set_uid_in,
                    set_label_in || 'basechange', 
                    s.id
                );
        end loop channel;
        bulk_server_base_change(new_channel_id_in,
                                set_label_in || 'basechange',
                                set_uid_in);
        delete from rhnSet
            where   label = set_label_in||'basechange'
                and user_id = set_uid_in;
    end bulk_server_basechange_from;

    procedure bulk_guess_server_base(
        set_label_in in varchar2,
        set_uid_in in number
    ) is
        channel_id number;
    begin
        for server in rhn_set.set_iterator(set_label_in, set_uid_in)
        loop
            -- anything that doesn't work, we just ignore
            begin
                if rhn_server.can_change_base_channel(server.element) = 1
                then
                    channel_id := guess_server_base(TO_NUMBER(server.element));
                    rhn_channel.clear_subscriptions(TO_NUMBER(server.element));
                    rhn_channel.subscribe_server(TO_NUMBER(server.element), channel_id, 0, set_uid_in);
                end if;
            exception when others then
                null;
            end;
        end loop server;
    end;

    function guess_server_base(
        server_id_in in number
    ) RETURN number is
        cursor server_cursor is
            select s.server_arch_id, s.release, s.org_id
              from rhnServer s
             where s.id = server_id_in;
    begin
        for s in server_cursor loop
            for channel in base_channel_cursor(s.release,
                s.server_arch_id, s.org_id) 
            loop
                return channel.id;
            end loop base_channel_cursor;
        end loop server_cursor;
        -- Server not found, or no base channel applies to it
        return null;
    end;

    -- Private function
    function normalize_server_arch(server_arch_in in varchar2)
    return varchar2
    deterministic
    is
        suffix VARCHAR2(128) := '-redhat-linux';
        suffix_len NUMBER := length(suffix);
    begin
        if server_arch_in is NULL then
            return NULL;
        end if;
        if instr(server_arch_in, '-') > 0
        then
            -- Suffix already present
            return server_arch_in;
        end if;
        return server_arch_in || suffix;
    end normalize_server_arch;

    --
    --
    -- Raises: 
    --   server_arch_not_found
    --   no_subscribe_permissions
    function base_channel_for_release_arch(
        release_in in varchar2,
        server_arch_in in varchar2,
        org_id_in in number := -1,
        user_id_in in number := null
    ) return number is
        server_arch varchar2(256) := normalize_server_arch(server_arch_in);
        server_arch_id number;
    begin
        -- Look up the server arch
        begin
            select id
              into server_arch_id
              from rhnServerArch
             where label = server_arch;
        exception
            when no_data_found then
                rhn_exception.raise_exception('server_arch_not_found');
        end;
        return base_channel_rel_archid(release_in, server_arch_id,
            org_id_in, user_id_in);
    end base_channel_for_release_arch;

    function base_channel_rel_archid(
        release_in in varchar2,
        server_arch_id_in in number,
        org_id_in in number := -1,
        user_id_in in number := null
    ) return number is
        denied_channel_id number := null;
        valid_org_id number := org_id_in;
        valid_user_id number := user_id_in;
        channel_subscribable number;
    begin
        if org_id_in = -1 and user_id_in is not null then
            -- Get the org id from the user id
            begin
                select org_id
                  into valid_org_id
                  from web_contact
                 where id = user_id_in;
            exception
                when no_data_found then
                    -- User doesn't exist
                    -- XXX Only list public stuff for now
                    valid_user_id := null;
                    valid_org_id := -1;
            end;
        end if;

        for c in base_channel_cursor(release_in, server_arch_id_in, valid_org_id)
        loop
            -- This row is a possible match
            if valid_user_id is null then
                -- User ID not specified, so no user to channel permissions to
                -- check
                return c.id;
            end if;

            -- Check user to channel permissions
            select loose_user_role_check(c.id, user_id_in, 'subscribe')
              into channel_subscribable
              from dual;

            if channel_subscribable = 1 then
                return c.id;
            end if;
                
            -- Base channel exists, but is not subscribable; keep trying
            denied_channel_id := c.id;
        end loop base_channel_fetch;
        
        if denied_channel_id is not null then
            rhn_exception.raise_exception('no_subscribe_permissions');
        end if;
        -- No base channel applies
        return NULL;
    end base_channel_rel_archid;

    procedure bulk_guess_server_base_from(
        set_label_in in varchar2,
        set_uid_in in number,
        channel_id_in in number
    ) is
        cursor channels(server_id_in in number) is
            select      rsc.channel_id
            from        rhnServerChannel rsc,
                        rhnChannel rc
            where       server_id_in = rsc.server_id
                        and rsc.channel_id = rc.id
                        and rc.parent_channel is null;
    begin
        for server in rhn_set.set_iterator(set_label_in, set_uid_in)
        loop
            for channel in channels(server.element)
            loop
                if channel.channel_id = channel_id_in
                then
                    insert into rhnSet (user_id, label, element) values (set_uid_in, set_label_in || 'baseguess', server.element);
                end if;
            end loop channel;
        end loop server;
        bulk_guess_server_base(set_label_in||'baseguess',set_uid_in);
        delete from rhnSet where label = set_label_in||'baseguess' and user_id = set_uid_in;
    end;


    PROCEDURE clear_subscriptions(server_id_in IN NUMBER, deleting_server IN NUMBER := 0 )
    IS
        cursor server_channels(server_id_in in number) is
                select  s.org_id, sc.channel_id, cfm.channel_family_id
                from    rhnServer s,
                        rhnServerChannel sc,
                        rhnChannelFamilyMembers cfm
                where   s.id = server_id_in
                        and s.id = sc.server_id
                        and sc.channel_id = cfm.channel_id;
    BEGIN
        for channel in server_channels(server_id_in)
        loop
                unsubscribe_server(server_id_in, channel.channel_id, 1, 1, deleting_server);
                rhn_channel.update_family_counts(channel.channel_family_id, channel.org_id);
        end loop channel;
    END clear_subscriptions;

    PROCEDURE unsubscribe_server(server_id_in IN NUMBER, channel_id_in NUMBER, immediate_in NUMBER := 1, unsubscribe_children_in number := 0,
                                 deleting_server IN NUMBER := 0 )
    IS
        channel_family_id_val   NUMBER;
        server_org_id_val       NUMBER;
        available_subscriptions NUMBER; 
        server_already_in_chan  BOOLEAN;
        cursor  channel_family_is_proxy(channel_family_id_in in number) is
                select  1
                from    rhnChannelFamily
                where   id = channel_family_id_in
                    and label = 'rhn-proxy';
        cursor  channel_family_is_satellite(channel_family_id_in in number) is
                select  1
                from    rhnChannelFamily
                where   id = channel_family_id_in
                    and label = 'rhn-satellite';
        -- this is *EXACTLY* like check_server_parent_membership, but if we recurse
        -- with the package-level one, we get a "cursor already open", so we need a
        -- copy on our call stack instead.  GROAN.
        cursor local_chk_server_parent_memb (
                        server_id_in number,
                        channel_id_in number ) is
                select  c.id
                from    rhnChannel                      c,
                                rhnServerChannel        sc
                where   1=1
                        and c.parent_channel = channel_id_in
                        and c.id = sc.channel_id
                        and sc.server_id = server_id_in;
    BEGIN
        FOR child IN local_chk_server_parent_memb(server_id_in, channel_id_in)
        LOOP
            if unsubscribe_children_in = 1 then
                unsubscribe_server(server_id_in => server_id_in,
                                                                channel_id_in => child.id,
                                                                immediate_in => immediate_in,
                                                                unsubscribe_children_in => unsubscribe_children_in,
                        deleting_server => deleting_server);
            else
                rhn_exception.raise_exception('channel_unsubscribe_child_exists');
            end if;
        END LOOP child;
        
        server_already_in_chan := FALSE;
    
        FOR check_subscription IN check_server_subscription(server_id_in, channel_id_in)
        LOOP
            server_already_in_chan := TRUE;
        END LOOP check_subscription;
    
        IF NOT server_already_in_chan
        THEN
            RETURN;
        END IF;
        
   if deleting_server = 0 then 

      insert into rhnServerHistory (id,server_id,summary,details) (
          select  rhn_event_id_seq.nextval,
                server_id_in,
             'unsubscribed from channel ' || SUBSTR(c.label, 0, 106),
             c.label
          from    rhnChannel c
          where   c.id = channel_id_in
      );

        UPDATE rhnServer SET channels_changed = sysdate WHERE id = server_id_in;
   end if;
        
   DELETE FROM rhnServerChannel WHERE server_id = server_id_in AND channel_id = channel_id_in;

   if deleting_server = 0 then 
        queue_server(server_id_in, immediate_in);
   end if;

        channel_family_id_val := rhn_channel.family_for_channel(channel_id_in);
        IF channel_family_id_val IS NULL
        THEN
            rhn_exception.raise_exception('channel_unsubscribe_no_family');
        END IF;

        for ignore in channel_family_is_satellite(channel_family_id_val) loop
                delete from rhnSatelliteInfo where server_id = server_id_in;
                delete from rhnSatelliteChannelFamily where server_id = server_id_in;
        end loop;

        for ignore in channel_family_is_proxy(channel_family_id_val) loop
                delete from rhnProxyInfo where server_id = server_id_in;
        end loop;

        DELETE FROM rhnChannelFamilyLicenseConsent
         WHERE channel_family_id = channel_family_id_val
           AND server_id = server_id_in;
                        
        SELECT org_id INTO server_org_id_val
          FROM rhnServer
         WHERE id = server_id_in;
         
        rhn_channel.update_family_counts(channel_family_id_val, server_org_id_val);
    END unsubscribe_server;

    PROCEDURE bulk_unsubscribe_server(channel_id_in IN NUMBER, set_label_in IN VARCHAR2, set_uid_in IN NUMBER)
    IS
    BEGIN
        FOR server IN rhn_set.set_iterator(set_label_in, set_uid_in)
        LOOP
            rhn_channel.unsubscribe_server(server.element, channel_id_in, 0);
        END LOOP server;
    END bulk_unsubscribe_server;

    FUNCTION family_for_channel(channel_id_in IN NUMBER)
    RETURN NUMBER
    IS
        channel_family_id_val NUMBER;
    BEGIN
        SELECT channel_family_id INTO channel_family_id_val
          FROM rhnChannelFamilyMembers
         WHERE channel_id = channel_id_in;
         
        RETURN channel_family_id_val;
    EXCEPTION
        WHEN NO_DATA_FOUND
        THEN
            RETURN NULL;
    END family_for_channel;

    FUNCTION available_family_subscriptions(channel_family_id_in IN NUMBER, org_id_in IN NUMBER)
    RETURN NUMBER
    IS
        cfp channel_family_perm_cursor%ROWTYPE;
        current_members_val NUMBER;
        max_members_val     NUMBER;
        found               NUMBER;
    BEGIN
        IF NOT channel_family_perm_cursor%ISOPEN
        THEN
            OPEN channel_family_perm_cursor(channel_family_id_in, org_id_in);
        END IF;

        FETCH channel_family_perm_cursor INTO cfp;
        
        WHILE channel_family_perm_cursor%FOUND
        LOOP
            found := 1;
            
            current_members_val := cfp.current_members;
            max_members_val := cfp.max_members;
            
            FETCH channel_family_perm_cursor INTO cfp;
        END LOOP;

        IF channel_family_perm_cursor%ISOPEN
        THEN
            CLOSE channel_family_perm_cursor;
        END IF;

        -- not found: either the channel fam doesn't have an entry in cfp, or the org doesn't have access to it.
        -- either way, there are no available subscriptions
        
        IF found IS NULL
        THEN
            RETURN 0;
        END IF;

        -- null max members?  in that case, pass it on; NULL means infinite                     
        IF max_members_val IS NULL
        THEN
            RETURN NULL;
        END IF;

        -- otherwise, return the delta  
        RETURN max_members_val - current_members_val;                   
    END available_family_subscriptions;
    
    -- *******************************************************************
    -- FUNCTION: channel_family_current_members
    -- Calculates and returns the actual count of systems consuming
    --   physical channel subscriptions.
    -- Called by: update_family_counts 
    --            rhn_entitlements.repoll_virt_guest_entitlements
    -- *******************************************************************
    function channel_family_current_members(channel_family_id_in IN NUMBER,
                                            org_id_in IN NUMBER)
    return number
    is
        current_members_count number := 0;
    begin
        select  count(distinct sc.server_id)
        into    current_members_count
        from    rhnChannelFamilyMembers cfm,
                rhnServerChannel sc,
                rhnServer s
        where   s.org_id = org_id_in
            and s.id = sc.server_id
            and cfm.channel_family_id = channel_family_id_in
            and cfm.channel_id = sc.channel_id
            and exists ( 
                select 1
                from rhnChannelFamilyServerPhysical cfsp
                where cfsp.CHANNEL_FAMILY_ID = channel_family_id_in
                    and cfsp.server_id = s.id
                );

        return current_members_count;
    end;        

    PROCEDURE update_family_counts(channel_family_id_in IN NUMBER, 
                                   org_id_in IN NUMBER)
    IS
    BEGIN
                update rhnPrivateChannelFamily
                set current_members = (
                channel_family_current_members(channel_family_id_in, org_id_in)
                )
                        where org_id = org_id_in
                                and channel_family_id = channel_family_id_in;

    END update_family_counts;
    
    FUNCTION available_chan_subscriptions(channel_id_in IN NUMBER, 
                                          org_id_in IN NUMBER)
    RETURN NUMBER
    IS
            channel_family_id_val NUMBER;
    BEGIN
        SELECT channel_family_id INTO channel_family_id_val
            FROM rhnChannelFamilyMembers
            WHERE channel_id = channel_id_in;
         
            RETURN rhn_channel.available_family_subscriptions(
                           channel_family_id_val, org_id_in);
    END available_chan_subscriptions;

    -- *******************************************************************
    -- PROCEDURE: entitle_customer
    -- Creates a chan fam bucket, or sets max_members for an existing bucket
    -- Called by: rhn_ep.poll_customer_internal
    -- Calls: set_family_maxmembers + update_family_counts if the row
    --        already exists, else it creates it in rhnPrivateChannelFamily.
    -- *******************************************************************
    procedure entitle_customer(customer_id_in in number, 
                               channel_family_id_in in number, 
                               quantity_in in number)
    is
                cursor permissions is
                        select  1
                        from    rhnPrivateChannelFamily pcf
                        where   pcf.org_id = customer_id_in
                                and     pcf.channel_family_id = channel_family_id_in; 
    begin
                for perm in permissions loop
                        set_family_maxmembers(
                                customer_id_in,
                                channel_family_id_in,
                                quantity_in
                        );
                        rhn_channel.update_family_counts(
                                channel_family_id_in,
                                customer_id_in
                        );
                        return;
                end loop;
        
                insert into rhnPrivateChannelFamily pcf (
                                channel_family_id, org_id, max_members, current_members
                        ) values (
                                channel_family_id_in, customer_id_in, quantity_in, 0
                        );
    end;

    -- *******************************************************************
    -- PROCEDURE: set_family_maxmembers
    -- Prunes an existing channel family bucket by unsubscribing the
    --   necessary servers and sets max_members.
    -- Called by: rhn_channel.entitle_customer
    -- Calls: unsubscribe_server_from_family
    -- *******************************************************************
    procedure set_family_maxmembers(customer_id_in in number, 
                                    channel_family_id_in in number, 
                                    quantity_in in number)
    is
        cursor servers is
            select  server_id from (
            select      rownum row_number, server_id, modified from (
                select  rcfsp.server_id,
                        rcfsp.modified
                from    rhnChannelFamilyServerPhysical rcfsp
                where   rcfsp.customer_id = customer_id_in
                    and rcfsp.channel_family_id = channel_family_id_in
                order by modified
            )
            where rownum > quantity_in
            );
    begin
            -- prune subscribed servers
        for server in servers loop
            rhn_channel.unsubscribe_server_from_family(server.server_id, 
                                                       channel_family_id_in);
        end loop;

        update  rhnPrivateChannelFamily pcf
        set     pcf.max_members = quantity_in
        where   pcf.org_id = customer_id_in
            and pcf.channel_family_id = channel_family_id_in;
    end;

    procedure unsubscribe_server_from_family(server_id_in in number, 
                                             channel_family_id_in in number)
    is
    begin
        delete
        from    rhnServerChannel rsc
        where   rsc.server_id = server_id_in
            and channel_id in (
                select  rcfm.channel_id
                from    rhnChannelFamilyMembers rcfm
                where   rcfm.channel_family_id = channel_family_id_in);
    end;

    function get_org_id(channel_id_in in number)
    return number
    is
        org_id_out number;
    begin
        select org_id into org_id_out
            from rhnChannel
            where id = channel_id_in;
         
            return org_id_out;
    end get_org_id;
    
    function get_cfam_org_access(cfam_id_in in number, org_id_in in number)
    return number
    is
        cursor  families is
                        select  1
                        from    rhnOrgChannelFamilyPermissions cfp
                        where   cfp.org_id = org_id_in;
    begin
                -- the idea: if we get past this query, 
        -- the user has the role, else catch the exception and return 0
                for family in families loop
                return 1;
                end loop;
                return 0;
    end;

    function get_org_access(channel_id_in in number, org_id_in in number)
    return number
    is
        throwaway number;
    begin
        -- the idea: if we get past this query, 
        -- the org has access to the channel, else catch the exception and return 0
        select distinct 1 into throwaway
          from rhnChannelFamilyMembers CFM,
               rhnOrgChannelFamilyPermissions CFP
         where cfp.org_id = org_id_in
           and CFM.channel_family_id = CFP.channel_family_id
           and CFM.channel_id = channel_id_in
           and (CFP.max_members > 0 or CFP.max_members is null or CFP.org_id = 1);
           
        return 1;
        exception
            when no_data_found
            then
            return 0;
    end;
    
    -- check if a user has a given role, or if such a role is inferrable
    function user_role_check_debug(channel_id_in in number, 
                                   user_id_in in number, 
                                   role_in in varchar2, 
                                   reason_out out varchar2)
    return number
    is
        org_id number;
    begin
        org_id := rhn_user.get_org_id(user_id_in);

        -- channel might be shared
        if role_in = 'subscribe' and
           rhn_channel.shared_user_role_check(channel_id_in, user_id_in, role_in) = 1 then
            return 1;
        end if;
        
        if role_in = 'manage' and 
           NVL(rhn_channel.get_org_id(channel_id_in), -1) <> org_id then
                reason_out := 'channel_not_owned';
               return 0;
            end if;
        
        if role_in = 'subscribe' and 
           rhn_channel.get_org_access(channel_id_in, org_id) = 0 then
                reason_out := 'channel_not_available';
                return 0;
            end if;
        
        -- channel admins have all roles
        if rhn_user.check_role_implied(user_id_in, 'channel_admin') = 1 then
            reason_out := 'channel_admin';
            return 1;
            end if;

        -- the subscribe permission is inferred 
    -- UNLESS the not_globally_subscribable flag is set 
        if role_in = 'subscribe'
        then
            if rhn_channel.org_channel_setting(channel_id_in, 
                       org_id,
                       'not_globally_subscribable') = 0 then
                reason_out := 'globally_subscribable';
                    return 1;
            end if;
        end if;
        
        -- all other roles (manage right now) are explicitly granted    
        reason_out := 'direct_permission';
        return rhn_channel.direct_user_role_check(channel_id_in, 
                                              user_id_in, role_in);
    end;
    
    -- same as above, but with no OUT param; useful in views, etc
    function user_role_check(channel_id_in in number, user_id_in in number, role_in in varchar2)
    return number
    is
        throwaway varchar2(256);
    begin
        return rhn_channel.user_role_check_debug(channel_id_in, user_id_in, role_in, throwaway);
    end;

    --
    -- For multiorg phase II, this function simply checks to see if the user's
    -- has a trust relationship that includes this channel by id.
    --
    function shared_user_role_check(channel_id in number, user_id in number, role in varchar2)
    return number
    is
      n number;
      oid number;
    begin
      oid := rhn_user.get_org_id(user_id);
      select 1 into n
      from rhnSharedChannelView s
      where s.id = channel_id and s.org_trust_id = oid;
      return 1;
      exception
        when no_data_found then
          return 0;
    end;

    -- same as above, but returns 1 if user_id_in is null
    -- This is useful in queries where user_id is not specified
    function loose_user_role_check(channel_id_in in number, user_id_in in number, role_in in varchar2)
    return number
    is
    begin
        if user_id_in is null then
            return 1;
        end if;
        return user_role_check(channel_id_in, user_id_in, role_in);
    end loose_user_role_check;
    
    -- directly checks the table, no inferred permissions
    function direct_user_role_check(channel_id_in in number, user_id_in in number, role_in in varchar2)
    return number
    is
        throwaway number;
    begin
        -- the idea: if we get past this query, the user has the role, else catch the exception and return 0
        select 1 into throwaway
          from rhnChannelPermissionRole CPR,
               rhnChannelPermission CP
         where CP.user_id = user_id_in
           and CP.channel_id = channel_id_in
           and CPR.label = role_in
           and CP.role_id = CPR.id;
           
        return 1;
    exception
        when no_data_found
            then
            return 0;
    end;
    
    -- check if an org has a certain setting
    function org_channel_setting(channel_id_in in number, org_id_in in number, setting_in in varchar2)
    return number
    is
        throwaway number;
    begin
        -- the idea: if we get past this query, the org has the setting, else catch the exception and return 0
        select 1 into throwaway
          from rhnOrgChannelSettingsType OCST,
               rhnOrgChannelSettings OCS
         where OCS.org_id = org_id_in
           and OCS.channel_id = channel_id_in
           and OCST.label = setting_in
           and OCS.setting_id = OCST.id;
           
        return 1;
    exception
        when no_data_found
            then
            return 0;
    end;
    
    FUNCTION channel_priority(channel_id_in IN number) 
    RETURN number
    IS
         channel_name varchar2(64);
         priority number;
         end_of_life_val date;
         org_id_val number;
    BEGIN

        select name, end_of_life, org_id
        into channel_name, end_of_life_val, org_id_val
        from rhnChannel
        where id = channel_id_in;

        if end_of_life_val is not null then
          return -400;
        end if;

        if channel_name like 'Red Hat Enterprise Linux%' or channel_name like 'RHEL%' then
          priority := 1000;
          if channel_name not like '%Beta%' then
            priority := priority + 1000;
          end if;

          priority := priority +
            case
              when channel_name like '%v. 5%' then 600
              when channel_name like '%v. 4%' then 500
              when channel_name like '%v. 3%' then 400
              when channel_name like '%v. 2%' then 300
              when channel_name like '%v. 1%' then 200
              else 0
            end;

          priority := priority +
            case
              when channel_name like 'Red Hat Enterprise Linux (v. 5%' then 60
              when (channel_name like '%AS%' and channel_name not like '%Extras%') then 50
              when (channel_name like '%ES%' and channel_name not like '%Extras%') then 40
              when (channel_name like '%WS%' and channel_name not like '%Extras%') then 30
              when (channel_name like '%Desktop%' and channel_name not like '%Extras%') then 20
              when channel_name like '%Extras%' then 10
              else 0
            end; 

          priority := priority +
            case
              when channel_name like '%)' then 5
              else 0
            end;

          priority := priority +
            case
              when channel_name like '%32-bit x86%' then 4
              when channel_name like '%64-bit Intel Itanium%' then 3
              when channel_name like '%64-bit AMD64/Intel EM64T%' then 2
              else 0
            end;
        elsif channel_name like 'Red Hat Desktop%' then
            priority := 900;

            if channel_name not like '%Beta%' then
               priority := priority + 50;
            end if;
 
          priority := priority +
            case
              when channel_name like '%v. 4%' then 40
              when channel_name like '%v. 3%' then 30
              when channel_name like '%v. 2%' then 20
              when channel_name like '%v. 1%' then 10
              else 0
            end;
            
          priority := priority +
            case
              when channel_name like '%32-bit x86%' then 4
              when channel_name like '%64-bit Intel Itanium%' then 3
              when channel_name like '%64-bit AMD64/Intel EM64T%' then 2
              else 0
            end;
         
        elsif org_id_val is not null then
          priority := 600;
        else
          priority := 500;
        end if;
      
      return -priority;

    end channel_priority;

    -- right now this only does the accounting changes; the cascade
    -- actually does the rhnServerChannel delete.
    procedure delete_server_channels(server_id_in in number)
    is
    begin
        update  rhnPrivateChannelFamily
        set     current_members = current_members -1
        where   org_id in (
                        select  org_id
                        from    rhnServer
                        where   id = server_id_in
                )
                and channel_family_id in (
                        select  rcfm.channel_family_id
                        from    rhnChannelFamilyMembers rcfm,
                                rhnServerChannel rsc
                        where   rsc.server_id = server_id_in
                                and rsc.channel_id = rcfm.channel_id
                and not exists (
                    select 1
                    from
                        rhnChannelFamilyVirtSubLevel cfvsl,
                        rhnSGTypeVirtSubLevel sgtvsl,
                        rhnServerEntitlementView sev,
                        rhnVirtualInstance vi
                    where
                        -- system is a virtual instance
                        vi.virtual_system_id = server_id_in
                        and vi.host_system_id = sev.server_id
                        -- system's host has a virt ent
                        and sev.label in ('virtualization_host',
                                          'virtualization_host_platform')
                        and sev.server_group_type_id = 
                            sgtvsl.server_group_type_id
                        -- the host's virt ent grants a cf virt sub level
                        and sgtvsl.virt_sub_level_id = cfvsl.virt_sub_level_id
                        -- the cf is in that virt sub level
                        and cfvsl.channel_family_id = rcfm.channel_family_id
                    )
                );
    end;

        -- this could certainly be optimized to do updates if needs be
        procedure refresh_newest_package(channel_id_in in number, caller_in in varchar2 := '(unknown)')
        is
        begin
                delete from rhnChannelNewestPackage where channel_id = channel_id_in;
                insert into rhnChannelNewestPackage
                        ( channel_id, name_id, evr_id, package_id, package_arch_id ) 
                        (       select  channel_id,
                                                name_id, evr_id,
                                                package_id, package_arch_id
                                from    rhnChannelNewestPackageView
                                where   channel_id = channel_id_in
                        );
                insert into rhnChannelNewestPackageAudit (channel_id, caller)
                    values (channel_id_in, caller_in);
                update rhnChannel 
                    set last_modified = greatest(sysdate, last_modified + 1/86400)
                    where id = channel_id_in; 
        end;

   procedure update_channel ( channel_id_in in number, invalidate_ss in number := 0, 
                              date_to_use in date := sysdate )
   is

   channel_last_modified date;
   last_modified_value date;

   cursor snapshots is
   select  snapshot_id id
   from    rhnSnapshotChannel
   where   channel_id = channel_id_in;

   begin

      select last_modified
      into channel_last_modified
      from rhnChannel
      where id = channel_id_in;
  
      last_modified_value := date_to_use;

      if last_modified_value <= channel_last_modified then
          last_modified_value := last_modified_value + 1/86400;
      end if;

      update rhnChannel set last_modified = last_modified_value
      where id = channel_id_in;

      if invalidate_ss = 1 then 
        for snapshot in snapshots loop
            update rhnSnapshot
            set invalid = lookup_snapshot_invalid_reason('channel_modified')
            where id = snapshot.id;
        end loop;
      end if;

   end update_channel;

   procedure update_channels_by_package ( package_id_in in number, date_to_use in date := sysdate )
   is

   cursor channels is
   select channel_id
   from rhnChannelPackage
   where package_id = package_id_in
   order by channel_id;

   begin
      for channel in channels loop
         -- we want to invalidate the snapshot assocated with the channel when we
         -- do this b/c we know we've added or removed or packages
         rhn_channel.update_channel ( channel.channel_id, 1, date_to_use );
      end loop;
   end update_channels_by_package;

   
   procedure update_channels_by_errata ( errata_id_in number, date_to_use in date := sysdate )
   is

   cursor channels is
   select channel_id
   from rhnChannelErrata
   where errata_id = errata_id_in
   order by channel_id;

   begin
      for channel in channels loop
         -- we won't invalidate snapshots, b/c just changing the errata associated with
         -- a channel shouldn't invalidate snapshots
         rhn_channel.update_channel ( channel.channel_id, 0, date_to_use );
      end loop;
   end update_channels_by_errata;

END rhn_channel;
/
SHOW ERRORS

--
-- Revision 1.75  2005/03/04 00:04:19  jslagle
-- bz #147617
-- Made Red Hat Desktop sort a little better.
--
-- Revision 1.74  2005/02/22 03:24:47  jslagle
-- bz #147617
-- Improve channel_priority function to order channels better.
--
-- Revision 1.73  2004/08/16 20:39:30  pjones
-- bugzilla: 129889 -- make bulk_server_basechange_from() actually work.
--
-- Revision 1.72  2004/04/14 00:09:24  pjones
-- bugzilla: 120761 -- split rhnChannelPermissions into two tables, eliminating
-- a frequent full table scan
--
-- Revision 1.71  2004/04/13 16:28:36  bretm
-- bugzilla:  119871
--
-- keep track of rhnServer.channels_changed through the pl/sql fns
--
-- Revision 1.70  2004/03/26 18:11:32  rbb
-- Bugzilla:  114057
--
-- Add a script to determine channel priority.
--
-- Revision 1.69  2004/02/17 20:16:52  pjones
-- bugzilla: none -- add cvs tags into the package as long as we're touching
-- it anyway
--
-- Revision 1.68  2004/02/17 20:05:38  pjones
-- bugzilla: 115782 -- make bulk_server_basechange_from() filter out servers
-- with arches incompatible with the target channel
--
-- Revision 1.67  2004/02/06 02:36:10  misa
-- Changed normalize_server_arch to allow for solaris arches
--
-- Revision 1.66  2003/11/13 16:58:34  cturner
-- make use of new rhn_user.check_role_implied call; pragmas broke, removed them for now since I have no idea how to fix them
--
-- Revision 1.65  2003/10/23 20:26:24  bretm
-- bugzilla:  none
--
-- note the channel label when we unsubscribe, too
--
-- Revision 1.64  2003/10/15 14:47:17  bretm
-- bugzilla:  none
--
-- add the channel label to the server history summary line when we log a channel change
--
-- Revision 1.63  2003/09/24 19:25:56  pjones
-- this wasn't the right fix, put it back
--
-- Revision 1.62  2003/09/24 17:42:19  pjones
-- bugzilla: none
--
-- limit our server base channel guess to channels with available permissions
--
-- Revision 1.61  2003/09/22 21:00:40  cturner
-- add method for easy acl check
--
-- Revision 1.60  2003/09/17 22:14:11  misa
-- bugzilla: 103639  Changes to allow me to move the base channel guess into plsql
--
-- Revision 1.59  2003/08/21 13:41:17  cturner
-- bugzilla: 99187.  properly test for satellite and proxy in bulk_guess_server_base; reorg code for better reuse
--
-- Revision 1.58  2003/07/24 16:46:22  cturner
-- bugzilla: 100723, the perm check was returning duplicates, so now it just calls the function it should have called anyway
--
-- Revision 1.57  2003/07/24 16:44:16  misa
-- bugzilla: none  A function more usable on the rhnapp side
--
-- Revision 1.56  2003/07/23 22:36:51  cturner
-- argh, max returns null even when now rows; use distinct.  how revolting
--
-- Revision 1.55  2003/07/23 22:01:31  cturner
-- oops, this one can return multiple rows; eliminate that in a lazy way
--
-- Revision 1.54  2003/07/23 21:59:19  cturner
-- rework how rhnUserChannel works; move to plsql for speed and maintenance
--
-- Revision 1.53  2003/07/21 17:49:12  pjones
-- bugzilla: none
--
-- add optional user for subscribe_server
--
-- Revision 1.52  2003/07/14 22:19:29  misa
-- bugzilla: none  Updating guess_base_channel to work more like the rhnapp server code
--
-- Revision 1.51  2003/06/26 22:09:04  pjones
-- bugzilla: none
--
-- log subscribe and unsubscribe
--
-- Revision 1.50  2003/06/05 19:31:15  pjones
-- bugzilla: 88278 -- make the cursor name smaller
--
-- Revision 1.49  2003/06/05 19:18:21  pjones
-- bugzilla: 88278
--
-- unsubscribe_server() opens the package-level cursor when it invokes itself,
-- so we're using a local copy instead.
--
-- Revision 1.48  2003/06/04 16:41:39  pjones
-- bugzilla: none
--
-- make bulk_guess_server_base() silently ignore unguessables
--
-- Revision 1.47  2003/06/04 16:27:03  pjones
-- bugzilla: 88822
--
-- eliminate the last outliers that remove things from channels without using
-- unsubscribe_server, I think.
--
-- Revision 1.46  2003/06/03 20:49:37  pjones
-- bugzilla: 88822
-- unsubscribing from rhn-satellite now clears rhnSatelliteChannelFamily
-- for the server in question
--
-- Revision 1.45  2003/06/02 20:41:45  pjones
-- bugzilla: none - fix rhnProxyInfo/rhnSatelliteInfo channel unsubscribe
-- problem.  Basicly, if you're out of the channel for any reason, you're
-- also out of rhnProxyInfo/rhnProxyInfo
--
-- Revision 1.44  2003/03/24 15:26:28  pjones
-- bugzilla: 85812
--
-- bulk_server_base_change silently ignores servers that are satellites
-- or proxies, as requested.
--
-- Revision 1.43  2003/02/26 20:28:17  pjones
-- rhn_channel.update_family_counts() in rhn_channel.entitle_customer()
-- the old codepath is:
--
-- ep ->
-- rhn_ep.entitlement_run_me() ->
-- rhn_ep.poll_customer() ->
-- rhn_channel.entitle_customer()
--
-- which doesn't change current_members, even though it may remove servers
-- from the family.
--
-- There's another bug here:  currently, we don't try to order forced
-- unsubscribes in any way; we just use
-- rhn_channel.unsubscribe_server_from_family .  If there are any child
-- channel subscriptions, this will leave them subscribed.  We really need
-- to iterate across the channels again, and subscribe any channel for which
-- there are no parent channel subscriptions.
--
-- Ugh.
--
-- Revision 1.42  2003/01/28 00:19:45  pjones
-- fix clear_subscriptions; AFAICT, this is only hit on the
-- bulk_server_base_change / bulk_server_base_guess codepaths, which puts
-- it infrequent enough that it could be our "bad count" culprit.
--
-- Revision 1.41  2003/01/14 19:51:45  pjones
-- make setting current_members on rhnChannelFamilyPermissions work when
-- a server is in more than one channel in a single family.
  070701000003F9000081B400000000000000000000000167AE11140000018E000000000000000000000000000000000000006600000000susemanager-schema/upgrade/satellite-schema-5.3-to-spacewalk-schema-0.6/108-rhn_command_parameter.sql -- In Satellite 5.1.0 (svn rev. 136500, bug #429529) input field for
-- "SNMP Community String" was mistakenly changed from 'text' to
-- 'password'. This caused web forms for creating "General: SNMP Check"
-- and "General: Uptime (SNMP)" to be rendered incorrectly.

update rhn_command_parameter
	set field_widget_name = 'text' where
	command_id in (16, 113) and param_name = 'community';

commit;
  070701000003FA000081B400000000000000000000000167AE11140000DC77000000000000000000000000000000000000006500000000susemanager-schema/upgrade/satellite-schema-5.3-to-spacewalk-schema-0.6/111-rhn_entitlements.pkb.sql  --
-- Copyright (c) 2008 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--

create or replace
package body rhn_entitlements
is
	body_version varchar2(100) := '';


    -- *******************************************************************
    -- PROCEDURE: remove_org_entitlements
    --
    -- Removes both system entitlements and channel subscriptions
    -- that are currently assigned to an org and re-assigns to the
    -- master org (org_id = 1).
    --
    -- When we call this we expect everything to already be unentitled
    -- which shoul be handled by delete_org.
    --
    -- Called by: delete_org
    -- *******************************************************************
    procedure remove_org_entitlements(
        org_id_in in number
    )
    is

        cursor system_ents is
        select sg.id, sg.max_members, sg.group_type
        from rhnServerGroup sg
        where group_type is not null
          and org_id = org_id_in;

        cursor channel_subs is
        select pcf.channel_family_id, pcf.max_members
        from rhnChannelFamily cf,
             rhnPrivateChannelFamily pcf
        where pcf.org_id = org_id_in
          and pcf.channel_family_id = cf.id
          and cf.org_id is null;

    begin

        for system_ent in system_ents loop
            update rhnServerGroup
            set max_members = max_members + system_ent.max_members
            where org_id = 1
              and group_type = system_ent.group_type;
        end loop;

        update rhnServerGroup
        set max_members = 0
        where org_id = org_id_in;

        for channel_sub in channel_subs loop
            update rhnPrivateChannelFamily
            set max_members = max_members + channel_sub.max_members
            where org_id = 1
              and channel_family_id = channel_sub.channel_family_id;
        end loop;
        
        update rhnPrivateChannelFamily
        set max_members = 0
        where org_id = org_id_in;

    end remove_org_entitlements;
 
	function entitlement_grants_service (
	    entitlement_in in varchar2,
	    service_level_in in varchar2
	) return number	is
	begin
		if service_level_in = 'provisioning' then
			if entitlement_in = 'provisioning_entitled' then
				return 1;
			else
				return 0;
			end if;
		elsif service_level_in = 'management' then
			if entitlement_in = 'enterprise_entitled' then
				return 1;
			else
				return 0;
			end if;
		elsif service_level_in = 'monitoring' then
			if entitlement_in = 'monitoring_entitled' then
				return 1;
			end if;
		elsif service_level_in = 'updates' then
			return 1;			
		else
			return 0;
		end if;
	end entitlement_grants_service;

	function lookup_entitlement_group (
		org_id_in in number,
		type_label_in in varchar2 := 'sw_mgr_entitled'
	) return number is
		cursor server_groups is
			select	sg.id				server_group_id
			from	rhnServerGroup		sg,
					rhnServerGroupType	sgt
			where	sgt.label = type_label_in
				and sgt.id = sg.group_type
				and sg.org_id = org_id_in;
	begin
		for sg in server_groups loop
			return sg.server_group_id;
		end loop;
		return rhn_entitlements.create_entitlement_group(
				org_id_in, 
				type_label_in
			);
	end lookup_entitlement_group;

	function create_entitlement_group (
		org_id_in in number,
		type_label_in in varchar2 := 'sw_mgr_entitled'
	) return number is
		sg_id_val number;
	begin
		select	rhn_server_group_id_seq.nextval
		into	sg_id_val
		from	dual;

		insert into rhnServerGroup (
				id, name, description, max_members, current_members,
				group_type, org_id
			) (
				select	sg_id_val, sgt.label, sgt.label,
						0, 0, sgt.id, org_id_in
				from	rhnServerGroupType sgt
				where	sgt.label = type_label_in
			);

		return sg_id_val;
	end create_entitlement_group;

   function can_entitle_server ( 
        server_id_in in number, 
        type_label_in in varchar2 ) 
   return number is
      cursor addon_servergroups (base_label_in in varchar2, 
                                 addon_label_in in varchar2) is
         select
            addon_id
         from
            rhnSGTypeBaseAddonCompat
         where base_id = lookup_sg_type (base_label_in)
           and addon_id = lookup_sg_type (addon_label_in);

      previous_ent        rhn_entitlements.ents_array;
      is_base_in          char   := 'N';
      is_base_current     char   := 'N';
      i                   number := 0;
      sgid                number := 0;

   begin

      previous_ent := rhn_entitlements.ents_array();
      previous_ent := rhn_entitlements.get_server_entitlement(server_id_in);

      select distinct is_base
      into is_base_in
      from rhnServerGroupType
      where label = type_label_in;

      if previous_ent.count = 0 then
         if (is_base_in = 'Y' and rhn_entitlements.find_compatible_sg (server_id_in, type_label_in, sgid)) then
            -- rhn_server.insert_into_servergroup (server_id_in, sgid);
            return 1;
         else
            -- rhn_exception.raise_exception ('invalid_base_entitlement');
            return 0;
         end if;

      -- there are previous ents, first make sure we're not trying to entitle a base ent
      elsif is_base_in = 'Y' then
         -- rhn_exception.raise_exception ('invalid_addon_entitlement');
         return 0;

      -- it must be an addon, so proceed with the entitlement
      else

         -- find the servers base ent
         is_base_current := 'N';
         i := 0;
         while is_base_current = 'N' and i <= previous_ent.count
         loop
            i := i + 1;
            select is_base
            into is_base_current
            from rhnServerGroupType
            where label = previous_ent(i);
         end loop;

         -- never found a base ent, that would be strange
         if is_base_current  = 'N' then
            -- rhn_exception.raise_exception ('invalid_base_entitlement');
            return 0;
         end if;

         -- this for loop verifies the validity of the addon path
         for addon_servergroup in addon_servergroups  (previous_ent(i), type_label_in) loop
            -- find an appropriate sgid for the addon and entitle the server
            if rhn_entitlements.find_compatible_sg (server_id_in, type_label_in, sgid) then
               -- rhn_server.insert_into_servergroup (server_id_in, sgid);
               return 1;
            else
               -- rhn_exception.raise_exception ('invalid_addon_entitlement');
               return 0;
            end if;
         end loop;

      end if;

      return 0;

   end can_entitle_server;

   function can_switch_base (
      server_id_in   in    integer,
      type_label_in  in    varchar2
   ) return number is

      type_label_in_is_base   char(1);
      sgid                    number;

   begin

      begin
         select is_base into type_label_in_is_base
         from rhnServerGroupType
         where label = type_label_in;
      exception
         when no_data_found then
            rhn_exception.raise_exception ( 'invalid_entitlement' );
      end;

      if type_label_in_is_base = 'N' then
         rhn_exception.raise_exception ( 'invalid_entitlement' );
      elsif rhn_entitlements.find_compatible_sg ( server_id_in, 
                                                  type_label_in, sgid ) then
         return 1;
      else
         return 0;
      end if;

   end can_switch_base;


   function find_compatible_sg (
      server_id_in    in   number,
      type_label_in   in   varchar2,
      sgid_out        out  number
   ) return boolean is

      cursor servergroups is
         select sg.id            id
           from rhnServerGroupType             sgt,
                rhnServerGroup                 sg,
                rhnServer                     s,
                rhnServerServerGroupArchCompat ssgac
          where s.id = server_id_in
            and s.org_id = sg.org_id
            and sgt.label = type_label_in
            and sg.group_type = sgt.id
            and ssgac.server_group_type = sgt.id
            and ssgac.server_arch_id = s.server_arch_id
            and not exists ( 
                     select 1
                      from rhnServerGroupMembers sgm
                     where sgm.server_group_id = sg.id 
                       and sgm.server_id = s.id);

         
   begin
      for servergroup in servergroups loop
         sgid_out := servergroup.id;
         return true;      
      end loop;

      --no servergroup found
      sgid_out := 0;
      return false;
   end find_compatible_sg;

	procedure entitle_server (
		server_id_in in number,
		type_label_in in varchar2 := 'sw_mgr_entitled'
	) is
      sgid  number := 0;
      is_virt number := 0;

	begin

          begin
          select 1 into is_virt
            from rhnServerEntitlementView
           where server_id = server_id_in
             and label in ('virtualization_host', 'virtualization_host_platform');
	  exception
            when no_data_found then
              is_virt := 0;
          end;
      
      if is_virt = 0 and (type_label_in = 'virtualization_host' or
                          type_label_in = 'virtualization_host_platform') then

        is_virt := 1;
      end if;



      if rhn_entitlements.can_entitle_server(server_id_in, 
                                             type_label_in) = 1 then
         if rhn_entitlements.find_compatible_sg (server_id_in, 
                                                 type_label_in, sgid) then
            insert into rhnServerHistory ( id, server_id, summary, details )
            values ( rhn_event_id_seq.nextval, server_id_in,
                     'added system entitlement ',
                      case type_label_in
                       when 'enterprise_entitled' then 'Management'
                       when 'sw_mgr_entitled' then 'Update'
                       when 'provisioning_entitled' then 'Provisioning'
                       when 'monitoring_entitled' then 'Monitoring'  
                       when 'virtualization_host' then 'Virtualization'
                       when 'virtualization_host_platform' then 
                            'Virtualization Platform' end  );

            rhn_server.insert_into_servergroup (server_id_in, sgid);

            if is_virt = 1 then
              rhn_entitlements.repoll_virt_guest_entitlements(server_id_in);
            end if;

         else
            rhn_exception.raise_exception ('no_available_server_group');
         end if;
      else
         rhn_exception.raise_exception ('invalid_entitlement');
      end if;
   end entitle_server;

	procedure remove_server_entitlement (
		server_id_in in number,
		type_label_in in varchar2 := 'sw_mgr_entitled',
        repoll_virt_guests in number := 1
	) is
		group_id number;
      type_is_base char;
      is_virt number := 0;
	begin
      begin


      -- would be nice if there were a virt attribute of entitlement types, not have to specify 2 different ones...
        begin
          select 1 into is_virt
            from rhnServerEntitlementView
           where server_id = server_id_in
             and label in ('virtualization_host', 'virtualization_host_platform');
        exception
          when no_data_found then
            is_virt := 0;
        end;

		select	sg.id, sgt.is_base
  		into	group_id, type_is_base
  		from	rhnServerGroupType sgt,
   			rhnServerGroup sg,
  				rhnServerGroupMembers sgm,
  				rhnServer s
  		where	s.id = server_id_in
  			and s.id = sgm.server_id
  			and sgm.server_group_id = sg.id
  			and sg.org_id = s.org_id
  			and sgt.label = type_label_in
  			and sgt.id = sg.group_type;

      if ( type_is_base = 'Y' ) then
         -- unentitle_server should handle everything, don't really need to do anything else special here
         unentitle_server ( server_id_in );
      else

         insert into rhnServerHistory ( id, server_id, summary, details )
         values ( rhn_event_id_seq.nextval, server_id_in,
                  'removed system entitlement ',
                   case type_label_in
                    when 'enterprise_entitled' then 'Management'
                    when 'sw_mgr_entitled' then 'Update'
                    when 'provisioning_entitled' then 'Provisioning'
                    when 'monitoring_entitled' then 'Monitoring'
                    when 'virtualization_host' then 'Virtualization'
                    when 'virtualization_host_platform' then 
                         'Virtualization Platforrm' end  );

         rhn_server.delete_from_servergroup(server_id_in, group_id);

         -- special case: clean up related monitornig data
         if type_label_in = 'monitoring_entitled' then
           DELETE
             FROM state_change
            WHERE o_id IN (SELECT probe_id
                             FROM rhn_check_probe
                            WHERE host_id = server_id_in);
           DELETE /*+index(time_series time_series_probe_id_idx)*/
             FROM time_series
            WHERE SUBSTR(o_id, INSTR(o_id, '-') + 1, 
                        (INSTR(o_id, '-', INSTR(o_id, '-') + 1) - INSTR(o_id, '-')) - 1)
              IN (SELECT to_char(probe_id)
                    FROM rhn_check_probe
                   WHERE host_id = server_id_in);
           DELETE
             FROM rhn_probe
            WHERE recid IN (SELECT probe_id
                              FROM rhn_check_probe
                             WHERE host_id = server_id_in);
         end if;

         if is_virt = 1 and repoll_virt_guests = 1 then
           rhn_entitlements.repoll_virt_guest_entitlements(server_id_in);
         end if;
      end if;

  		exception
  		when no_data_found then
  				rhn_exception.raise_exception('invalid_server_group_member');	
      end;

 	end remove_server_entitlement;


   procedure unentitle_server (server_id_in in number) is

      cursor servergroups is
         select distinct sgt.label, sg.id server_group_id
         from  rhnServerGroupType sgt,
               rhnServerGroup sg,
               rhnServer s,
               rhnServerGroupMembers sgm
         where s.id = server_id_in
            and s.org_id = sg.org_id
            and sg.group_type = sgt.id
            and sgm.server_group_id = sg.id
            and sgm.server_id = s.id;
            
     is_virt number := 0;

   begin

      begin
        select 1 into is_virt
          from rhnServerEntitlementView
         where server_id = server_id_in
           and label in ('virtualization_host', 'virtualization_host_platform');
      exception
        when no_data_found then
          is_virt := 0;
      end;

      for servergroup in servergroups loop

         insert into rhnServerHistory ( id, server_id, summary, details )
         values ( rhn_event_id_seq.nextval, server_id_in,
                  'removed system entitlement ',
                   case servergroup.label
                    when 'enterprise_entitled' then 'Management'
                    when 'sw_mgr_entitled' then 'Update'
                    when 'provisioning_entitled' then 'Provisioning'
                    when 'monitoring_entitled' then 'Monitoring'
                    when 'virtualization_host' then 'Virtualization'
                    when 'virtualization_host_platform' then 
                         'Virtualization Platform' end  );
  
         rhn_server.delete_from_servergroup(server_id_in, 
                                            servergroup.server_group_id );
      end loop;

      if is_virt = 1 then
        rhn_entitlements.repoll_virt_guest_entitlements(server_id_in);
      end if;

   end unentitle_server;


    -- *******************************************************************
    -- PROCEDURE: repoll_virt_guest_entitlements
    --
    --   Whenever we add/remove a virtualization_host* entitlement from 
    --   a host, we can call this procedure to update what type of slots
    --   the guests are consuming.  
    -- 
    --   If you're removing the entitlement, it's 
    --   possible the guests will become unentitled if you don't have enough
    --   physical slots to cover them.
    --
    --   If you're adding the entitlement, you end up freeing up physical
    --   slots for other systems.
    --
    -- *******************************************************************
    procedure repoll_virt_guest_entitlements(server_id_in in number)
    is

        -- All channel families associated with the guests of server_id_in
        cursor families is 
            select distinct cfs.channel_family_id
            from
                rhnChannelFamilyServers cfs,
                rhnVirtualInstance vi
            where
                vi.host_system_id = server_id_in
                and vi.virtual_system_id = cfs.server_id;
        
        -- All of server group types associated with the guests of
        -- server_id_in
        cursor group_types is
            select distinct sg.group_type, sgt.label
            from
                rhnServerGroupType sgt,
                rhnServerGroup sg,
                rhnServerGroupMembers sgm,
                rhnVirtualInstance vi
            where
                vi.host_system_id = server_id_in
                and vi.virtual_system_id = sgm.server_id
                and sgm.server_group_id = sg.id
                and sg.group_type = sgt.id;

        -- Virtual servers from a certain family belonging to a speicifc
        -- host that are consuming physical channel slots over the limit.
        cursor virt_servers_cfam(family_id_in in number, quantity_in in number)  is
            select virtual_system_id
            from (
                select rownum, vi.virtual_system_id
                from
                    rhnChannelFamilyMembers cfm,
                    rhnServerChannel sc,
                    rhnVirtualInstance vi
                where
                    vi.host_system_id = server_id_in
                    and vi.virtual_system_id = sc.server_id
                    and sc.channel_id = cfm.channel_id
                    and cfm.channel_family_id = family_id_in
                order by sc.modified desc
                )
            where rownum <= quantity_in;                

        -- Virtual servers from a certain family belonging to a speicifc
        -- host that are consuming physical system slots over the limit.
        cursor virt_servers_sgt(group_type_in in number, quantity_in in number)  is
            select virtual_system_id
            from (
                select rownum, vi.virtual_system_id
                from
                    rhnServerGroup sg,
                    rhnServerGroupMembers sgm,
                    rhnVirtualInstance vi
                where
                    vi.host_system_id = server_id_in
                    and vi.virtual_system_id = sgm.server_id
                    and sgm.server_group_id = sg.id
                    and sg.group_type = group_type_in
                order by sgm.modified desc
                )
            where rownum <= quantity_in;                
        
        org_id_val number;
        max_members_val number;
        current_members_calc number;
        sg_id number;

    begin

        select org_id
        into org_id_val
        from rhnServer
        where id = server_id_in;

        -- deal w/ channel entitlements first ...
        for family in families loop
            -- get the current (physical) members of the family
            current_members_calc := 
                rhn_channel.channel_family_current_members(family.channel_family_id,
                                                           org_id_val); -- fixed transposed args

            -- get the max members of the family
            select max_members
            into max_members_val
            from rhnPrivateChannelFamily
            where channel_family_id = family.channel_family_id
            and org_id = org_id_val;

            if current_members_calc > max_members_val then
                -- A virtualization_host* ent must have been removed, so we'll
                -- unsubscribe guests from the host first.

                -- hm, i don't think max_members - current_members_calc yielding a negative number
                -- will work w/ rownum, swaping 'em in the body of this if...
                for virt_server in virt_servers_cfam(family.channel_family_id,
                                current_members_calc - max_members_val) loop 

                    rhn_channel.unsubscribe_server_from_family(
                                virt_server.virtual_system_id,
                                family.channel_family_id);
                end loop;                               

                -- if we're still over the limit, which would be odd,
                -- just prune the group to max_members
                --
                -- er... wouldn't we actually have to refresh the values of
                -- current_members_calc and max_members_val to actually ever
                -- *skip this??
                if current_members_calc > max_members_val then
                    -- argh, transposed again?!
                    set_family_count(org_id_val,
                                     family.channel_family_id,
                                     max_members_val);
                end if; 

           end if;

            -- update current_members for the family.  This will set the value
            -- to reflect adding/removing the entitlement.
            --
            -- what's the difference of doing this vs the unavoidable set_family_count above?
            rhn_channel.update_family_counts(family.channel_family_id,
                                             org_id_val);
        end loop;

        for a_group_type in group_types loop
          -- get the current *physical* members of the system entitlement type for the org...
          -- 
          -- unlike channel families, it appears the standard rhnServerGroup.max_members represents
          -- *physical* slots, vs physical+virt ... boy that's confusing...

          select max_members, id
            into max_members_val, sg_id
            from rhnServerGroup
            where group_type = a_group_type.group_type
            and org_id = org_id_val;


	  select count(sep.server_id) into current_members_calc
            from rhnServerEntitlementPhysical sep
           where sep.server_group_id = sg_id
             and sep.server_group_type_id = a_group_type.group_type;
          
          if current_members_calc > max_members_val then
            -- A virtualization_host* ent must have been removed, and we're over the limit, so unsubscribe guests
            for virt_server in virt_servers_sgt(a_group_type.group_type,
                                                current_members_calc - max_members_val) loop
              rhn_entitlements.remove_server_entitlement(virt_server.virtual_system_id, a_group_type.label);

              -- decrement current_members_calc, we'll use it to reset current_members for the group at the end...
              current_members_calc := current_members_calc - 1;
            end loop;

          end if;

          update rhnServerGroup set current_members = current_members_calc
           where org_id = org_id_val
             and group_type = a_group_type.group_type;

          -- I think that's all the house-keeping we have to do...
        end loop;

    end repoll_virt_guest_entitlements;


	function get_server_entitlement (
		server_id_in in number
	) return ents_array is

		cursor server_groups is
			select	sgt.label
			from	rhnServerGroupType		sgt,
					rhnServerGroup			sg,
					rhnServerGroupMembers	sgm
			where	1=1
				and sgm.server_id = server_id_in
				and sg.id = sgm.server_group_id
				and sgt.id = sg.group_type
				and sgt.label in (
					'sw_mgr_entitled','enterprise_entitled',
					'provisioning_entitled', 'nonlinux_entitled',
					'monitoring_entitled', 'virtualization_host',
                                        'virtualization_host_platform'
					);

         ent_array ents_array;

	begin
      
      ent_array := ents_array();

		for sg in server_groups loop
         ent_array.extend;
         ent_array(ent_array.count) := sg.label;
		end loop;

		return ent_array;

	end get_server_entitlement;


	-- this desperately needs to be table driven.
	procedure modify_org_service (
		org_id_in in number,
		service_label_in in varchar2,
		enable_in in char
	) is
		type roles_v is varray(10) of rhnUserGroupType.label%TYPE;
		roles_to_process roles_v;
		cursor roles(role_label_in in varchar2) is
			select	label, id
			from	rhnUserGroupType
			where	label = role_label_in;
		cursor org_roles(role_label_in in varchar2) is
			select	1
			from	rhnUserGroup ug,
					rhnUserGroupType ugt
			where	ugt.label = role_label_in
				and ug.org_id = org_id_in
				and ugt.id = ug.group_type;
				
		type ents_v is varray(10) of rhnOrgEntitlementType.label%TYPE;
		ents_to_process ents_v;
		cursor ents(ent_label_in in varchar2) is
			select	label, id
			from	rhnOrgEntitlementType
			where	label = ent_label_in;
		cursor org_ents(ent_label_in in varchar2) is
			select	1
			from	rhnOrgEntitlements oe,
					rhnOrgEntitlementType oet
			where	oet.label = ent_label_in
				and oe.org_id = org_id_in
				and oet.id = oe.entitlement_id;
		create_row char(1);
	begin
		ents_to_process := ents_v();
		roles_to_process := roles_v();
		-- a bit kludgy, but only for 3.4 really.  Certainly no
		-- worse than the old code...
		if service_label_in = 'enterprise' or 
           service_label_in = 'management' then
			ents_to_process.extend;
			ents_to_process(ents_to_process.count) := 'sw_mgr_enterprise';

			roles_to_process.extend;
			roles_to_process(roles_to_process.count) := 'org_admin';

			roles_to_process.extend;
			roles_to_process(roles_to_process.count) := 'system_group_admin';

			roles_to_process.extend;
			roles_to_process(roles_to_process.count) := 'activation_key_admin';

			roles_to_process.extend;
			roles_to_process(roles_to_process.count) := 'org_applicant';
		elsif service_label_in = 'provisioning' then
			ents_to_process.extend;
			ents_to_process(ents_to_process.count) := 'rhn_provisioning';

			roles_to_process.extend;
			roles_to_process(roles_to_process.count) := 'system_group_admin';

			roles_to_process.extend;
			roles_to_process(roles_to_process.count) := 'activation_key_admin';

			roles_to_process.extend;
			roles_to_process(roles_to_process.count) := 'config_admin';
			-- another nasty special case...
			if enable_in = 'Y' then
				ents_to_process.extend;
				ents_to_process(ents_to_process.count) := 'sw_mgr_enterprise';
			end if;
		elsif service_label_in = 'monitoring' then
			ents_to_process.extend;
			ents_to_process(ents_to_process.count) := 'rhn_monitor';

			roles_to_process.extend;
			roles_to_process(roles_to_process.count) := 'monitoring_admin';
		elsif service_label_in = 'virtualization' then
			ents_to_process.extend;
			ents_to_process(ents_to_process.count) := 'rhn_virtualization';

			roles_to_process.extend;
			roles_to_process(roles_to_process.count) := 'config_admin';
        elsif service_label_in = 'virtualization_platform' then
			ents_to_process.extend;
			ents_to_process(ents_to_process.count) := 'rhn_virtualization_platform'; 
			roles_to_process.extend;
			roles_to_process(roles_to_process.count) := 'config_admin';
	elsif service_label_in = 'nonlinux' then
			ents_to_process.extend;
			ents_to_process(ents_to_process.count) := 'rhn_nonlinux';
			roles_to_process.extend;
			roles_to_process(roles_to_process.count) := 'config_admin';
		end if;

		if enable_in = 'Y' then
			for i in 1..ents_to_process.count loop
				for ent in ents(ents_to_process(i)) loop
					create_row := 'Y';
					for oe in org_ents(ent.label) loop
						create_row := 'N';
					end loop;
					if create_row = 'Y' then
						insert into rhnOrgEntitlements(org_id, entitlement_id)
							values (org_id_in, ent.id);
					end if;
				end loop;
			end loop;
			for i in 1..roles_to_process.count loop
				for role in roles(roles_to_process(i)) loop
					create_row := 'Y';
					for o_r in org_roles(role.label) loop
						create_row := 'N';
					end loop;
					if create_row = 'Y' then
						insert into rhnUserGroup(
								id, name, description, current_members,
								group_type, org_id
							) (
								select	rhn_user_group_id_seq.nextval,
										ugt.name || 's',
										ugt.name || 's for Org ' ||
											o.name || ' ('|| o.id ||')',
										0, ugt.id, o.id
								from	rhnUserGroupType ugt,
										web_customer o
								where	o.id = org_id_in
									and ugt.id = role.id
							);
					end if;
				end loop;
			end loop;
		else
			for i in 1..ents_to_process.count loop
				for ent in ents(ents_to_process(i)) loop
					delete from rhnOrgEntitlements
					 where org_id = org_id_in
					   and entitlement_id = ent.id;
				end loop;
			end loop;
		end if;
	end modify_org_service;

	procedure set_customer_enterprise (
		customer_id_in in number
	) is
	begin
		modify_org_service(customer_id_in, 'enterprise', 'Y');
	end set_customer_enterprise;

	procedure set_customer_provisioning (
		customer_id_in in number
	) is
	begin
		modify_org_service(customer_id_in, 'provisioning', 'Y');
	end set_customer_provisioning;

	procedure set_customer_monitoring (
		customer_id_in in number
	) is
	begin
		modify_org_service(customer_id_in, 'monitoring', 'Y');
	end set_customer_monitoring;

	procedure set_customer_nonlinux (
		customer_id_in in number
	) is
	begin
		modify_org_service(customer_id_in, 'nonlinux', 'Y');
	end set_customer_nonlinux;

	procedure unset_customer_enterprise (
		customer_id_in in number
	) is
	begin
		modify_org_service(customer_id_in, 'enterprise', 'N');
	end unset_customer_enterprise;

	procedure unset_customer_provisioning (
		customer_id_in in number
	) is
	begin
		modify_org_service(customer_id_in, 'provisioning', 'N');
	end unset_customer_provisioning;

	procedure unset_customer_monitoring (
		customer_id_in in number
	) is
	begin
		modify_org_service(customer_id_in, 'monitoring', 'N');
	end unset_customer_monitoring;

	procedure unset_customer_nonlinux (
		customer_id_in in number
	) is
	begin
		modify_org_service(customer_id_in, 'nonlinux', 'N');
	end unset_customer_nonlinux;

    -- *******************************************************************
    -- PROCEDURE: prune_group
    -- Unsubscribes servers consuming physical slots that over the org's
    --   limit.
    -- Called by: set_group_count, prune_everything, repoll_virt_guest_entitlements
    -- *******************************************************************
	procedure prune_group (
		group_id_in in number,
		type_in in char,
		quantity_in in number
	) is
		cursor usergroups is
			select	user_id, user_group_id, ugt.label
			from	rhnUserGroupType	ugt,
					rhnUserGroup		ug,
					rhnUserGroupMembers	ugm
			where	1=1
				and ugm.user_group_id = group_id_in
				and ugm.user_id in (
					select	user_id
					from	(
						select	rownum row_number,
								user_id,
								time
						from	(
							select	user_id,
									modified time
							from	rhnUserGroupMembers
							where	user_group_id = group_id_in
							order by time asc
						)
					)
					where	row_number > quantity_in
				)
				and ugm.user_group_id = ug.id
				and ug.group_type = ugt.id;
        cursor servergroups is
           select  server_id, server_group_id, sgt.id group_type_id, sgt.label
            from    rhnServerGroupType              sgt,
                            rhnServerGroup                  sg,
                            rhnServerGroupMembers   sgm
            where   1=1
                    and sgm.server_group_id = group_id_in
                    and sgm.server_id in (
                            select  server_id
                            from    (
                                    select  rownum row_number,
                                                    server_id,
                                                    time
                                    from    (
                                            select  sep.server_id,
                                                    sep.modified time
                                            from
                                                rhnServerEntitlementPhysical sep
                                            where
                                                sep.server_group_id = group_id_in
                                            order by time asc
                                    )
                            )
                            where   row_number > quantity_in
                    )
                    and sgm.server_group_id = sg.id
                    and sg.group_type = sgt.id;
      type_is_base char;
	begin
		if type_in = 'U' then
			update		rhnUserGroup
				set		max_members = quantity_in
				where	id = group_id_in;

			for ug in usergroups loop
				rhn_user.remove_from_usergroup(ug.user_id, ug.user_group_id);
			end loop;
		elsif type_in = 'S' then
			update		rhnServerGroup
				set		max_members = quantity_in
				where	id = group_id_in;

			for sg in servergroups loop
				remove_server_entitlement(sg.server_id, sg.label);
            
            select is_base 
            into type_is_base
            from rhnServerGroupType sgt
            where sgt.id = sg.group_type_id;
 
            -- if we're removing a base ent, then be sure to
            -- remove the server's channel subscriptions.
            if ( type_is_base = 'Y' ) then
				   rhn_channel.clear_subscriptions(sg.server_id);
            end if;

			end loop;
		end if;
	end prune_group;

    -- *******************************************************************
    -- PROCEDURE: assign_system_entitlement
    --
    -- Moves system entitlements from from_org_id_in to to_org_id_in.
    -- Can raise not_enough_entitlements_in_base_org if from_org_id_in
    -- does not have enough entitlements to cover the move.
    -- Takes care of unentitling systems if necessary by calling 
    -- set_group_count
    -- *******************************************************************
    procedure assign_system_entitlement(
        group_label_in in varchar2,
        from_org_id_in in number,
        to_org_id_in in number,
        quantity_in in number
    )
    is
        prev_ent_count number;
	to_org_prev_ent_count number;
        new_ent_count number;
	new_quantity number;
        group_type number;
    begin

        begin
            select max_members
            into prev_ent_count
            from rhnServerGroupType sgt,
                 rhnServerGroup sg
            where sg.org_id = from_org_id_in
              and sg.group_type = sgt.id
              and sgt.label = group_label_in;
        exception
            when NO_DATA_FOUND then
                rhn_exception.raise_exception(
                              'not_enough_entitlements_in_base_org');
        end;

        begin
            select max_members
            into to_org_prev_ent_count
            from rhnServerGroupType sgt,
                 rhnServerGroup sg
            where sg.org_id = to_org_id_in
              and sg.group_type = sgt.id
              and sgt.label = group_label_in;
        exception
            when NO_DATA_FOUND then
                to_org_prev_ent_count := 0;
        end;
	
        begin
            select id
            into group_type
            from rhnServerGroupType
            where label = group_label_in;
        exception
            when NO_DATA_FOUND then
                rhn_exception.raise_exception(
                              'invalid_server_group');
        end;

        new_ent_count := prev_ent_count - quantity_in;
	
        if prev_ent_count > new_ent_count then
            new_quantity := to_org_prev_ent_count + quantity_in;
        end if;
	
        if new_ent_count < 0 then
            rhn_exception.raise_exception(
                          'not_enough_entitlements_in_base_org');
        end if;


        rhn_entitlements.set_group_count(from_org_id_in,
                                         'S',
                                         group_type,
                                         new_ent_count);

        rhn_entitlements.set_group_count(to_org_id_in,
                                         'S',
                                         group_type,
                                         new_quantity);
        
        -- Create or delete the entries in rhnOrgEntitlementType
        if group_label_in = 'enterprise_entitled' then 
            if new_quantity > 0 then
                set_customer_enterprise(to_org_id_in);
            else
                unset_customer_enterprise(to_org_id_in);
            end if;
        end if;

        if group_label_in = 'provisioning_entitled' then
            if new_quantity > 0 then
                set_customer_provisioning(to_org_id_in);
            else
                unset_customer_provisioning(to_org_id_in);
            end if;
        end if;

        if group_label_in = 'monitoring_entitled' then
            if new_quantity > 0 then
                set_customer_monitoring(to_org_id_in);
            else
                unset_customer_monitoring(to_org_id_in);
            end if;
        end if;

    end assign_system_entitlement;

    -- *******************************************************************
    -- PROCEDURE: assign_channel_entitlement
    --
    -- Moves channel entitlements from from_org_id_in to to_org_id_in.
    -- Can raise not_enough_entitlements_in_base_org if from_org_id_in
    -- does not have enough entitlements to cover the move.
    -- Takes care of unentitling systems if necessary by calling 
    -- set_family_count
    -- *******************************************************************
    procedure assign_channel_entitlement(
        channel_family_label_in in varchar2,
        from_org_id_in in number,
        to_org_id_in in number,
        quantity_in in number
    )
    is
        prev_ent_count number;
        new_ent_count number;
	to_org_prev_ent_count number;
	new_quantity number;
        cfam_id       number;
    begin

        begin
            select max_members
            into prev_ent_count
            from rhnChannelFamily cf,
                 rhnPrivateChannelFamily pcf
            where pcf.org_id = from_org_id_in
              and pcf.channel_family_id = cf.id
              and cf.label = channel_family_label_in;
        exception
            when NO_DATA_FOUND then
                rhn_exception.raise_exception(
                              'not_enough_entitlements_in_base_org');
        end;
	
        begin
            select max_members
            into to_org_prev_ent_count
            from rhnChannelFamily cf,
                 rhnPrivateChannelFamily pcf
            where pcf.org_id = to_org_id_in
              and pcf.channel_family_id = cf.id
              and cf.label = channel_family_label_in;
        exception
            when NO_DATA_FOUND then
                to_org_prev_ent_count := 0;
        end;
	

        begin
            select id
            into cfam_id
            from rhnChannelFamily
            where label = channel_family_label_in;
        exception
            when NO_DATA_FOUND then
                rhn_exception.raise_exception(
                              'invalid_channel_family');
        end;                              

        new_ent_count := prev_ent_count - quantity_in;
	
	if prev_ent_count > new_ent_count then
            new_quantity := to_org_prev_ent_count + quantity_in;
	end if;
	

        if new_ent_count < 0 then
            rhn_exception.raise_exception(
                          'not_enough_entitlements_in_base_org');
        end if;

        rhn_entitlements.set_family_count(from_org_id_in,
                                          cfam_id,
                                          new_ent_count);

        rhn_entitlements.set_family_count(to_org_id_in,
                                          cfam_id,
                                          new_quantity);

    end assign_channel_entitlement;

    -- *******************************************************************
    -- PROCEDURE: activate_system_entitlement
    --
    -- Sets the values in rhnServerGroup for a given rhnServerGroupType.
    -- 
    -- Calls: set_group_count to update, prune, or create the group.
    -- Called by: the code that activates a satellite cert. 
    --
    -- Raises not_enough_entitlements_in_base_org if all entitlements
    -- in the org are used so the free entitlements would not cover
    -- the difference when descreasing the number of entitlements.
    -- *******************************************************************
    procedure activate_system_entitlement(
        org_id_in in number,
        group_label_in in varchar2,
        quantity_in in number
    )
    is
        prev_ent_count number; 
        prev_ent_count_sum number; 
        group_type number;
    begin

        -- Fetch the current entitlement count for the org
        -- into prev_ent_count
        begin
            select current_members
            into prev_ent_count
            from rhnServerGroupType sgt,
                 rhnServerGroup sg
            where sg.group_type = sgt.id
              and sgt.label = group_label_in
              and sg.org_id = org_id_in;
        exception
            when NO_DATA_FOUND then
                prev_ent_count := 0;
        end;

        begin
            select id
            into group_type
            from rhnServerGroupType
            where label = group_label_in;
        exception
            when NO_DATA_FOUND then
                rhn_exception.raise_exception(
                              'invalid_server_group');
        end;

        -- If we're setting the total entitlemnt count to a lower value,
        -- and that value is less than the allocated count in this org,
        -- we need to raise an exception.
        if quantity_in < prev_ent_count then
            rhn_exception.raise_exception(
                          'not_enough_entitlements_in_base_org');
        else
            rhn_entitlements.set_group_count(org_id_in,
                                             'S',
                                             group_type,
                                             quantity_in);
        end if;


    end activate_system_entitlement;

    -- *******************************************************************
    -- PROCEDURE: activate_channel_entitlement
    --
    -- Calls: set_family_count to update, prune, or create the family
    --        permission bucket.
    -- Called by: the code that activates a satellite cert. 
    --
    -- Raises not_enough_entitlements_in_base_org if there are not enough
    -- entitlements in the org to cover the difference when you are
    -- descreasing the number of entitlements.
    --
    -- The backend code in Python is expected to do whatever arithmetics
    -- is needed.
    -- *******************************************************************
    procedure activate_channel_entitlement(
        org_id_in in number,
        channel_family_label_in in varchar2,
        quantity_in in number
    )
    is
        prev_ent_count number; 
        prev_ent_count_sum number; 
        cfam_id number;
    begin

        -- Fetch the current entitlement count for the org
        -- into prev_ent_count
        begin
            select current_members
            into prev_ent_count
            from rhnChannelFamily cf,
                 rhnPrivateChannelFamily pcf
            where pcf.org_id = org_id_in
              and pcf.channel_family_id = cf.id
              and cf.label = channel_family_label_in;
        exception
            when NO_DATA_FOUND then
                prev_ent_count := 0;
        end;

        begin
            select id
            into cfam_id
            from rhnChannelFamily
            where label = channel_family_label_in;
        exception
            when NO_DATA_FOUND then
                rhn_exception.raise_exception(
                              'invalid_channel_family');
        end;                              

        -- If we're setting the total entitlemnt count to a lower value,
        -- and that value is less than the count in that one org,
        -- we need to raise an exception.
        if quantity_in < prev_ent_count then
            rhn_exception.raise_exception(
                          'not_enough_entitlements_in_base_org');
        else
            rhn_entitlements.set_family_count(org_id_in,
                                              cfam_id,
                                              quantity_in);
        end if;

    end activate_channel_entitlement;


	procedure set_group_count (
		customer_id_in in number,
		type_in in char,
		group_type_in in number,
		quantity_in in number
	) is
		group_id number;
		quantity number;
	begin
		quantity := quantity_in;
		if quantity is not null and quantity < 0 then
			quantity := 0;
		end if;

		if type_in = 'U' then
			select	rug.id
			into	group_id
			from	rhnUserGroup rug
			where	1=1
				and rug.org_id = customer_id_in
				and rug.group_type = group_type_in;
		elsif type_in = 'S' then
			select	rsg.id
			into	group_id
			from	rhnServerGroup rsg
			where	1=1
				and rsg.org_id = customer_id_in
				and rsg.group_type = group_type_in;
		end if;

		rhn_entitlements.prune_group(
			group_id,
			type_in,
			quantity
		);
	exception
		when no_data_found then
			if type_in = 'U' then
				insert into rhnUserGroup (
						id, name, description, max_members, current_members,
						group_type, org_id, created, modified
					) (
						select	rhn_user_group_id_seq.nextval, name, name,
								quantity, 0, id, customer_id_in,
								sysdate, sysdate
						from	rhnUserGroupType
						where	id = group_type_in
				);
			elsif type_in = 'S' then
				insert into rhnServerGroup (
						id, name, description, max_members, current_members,
						group_type, org_id, created, modified
					) (
						select	rhn_server_group_id_seq.nextval, name, name,
								quantity, 0, id, customer_id_in,
								sysdate, sysdate
						from	rhnServerGroupType
						where	id = group_type_in
				);
			end if;
	end set_group_count;

    -- *******************************************************************
    -- PROCEDURE: prune_family
    -- Unsubscribes servers consuming physical slots from the channel family 
    --   that are over the org's limit.
    -- Called by: set_family_count, prune_everything
    -- *******************************************************************
	procedure prune_family (
		customer_id_in in number,
		channel_family_id_in in number,
		quantity_in in number
	) is
		cursor serverchannels is
			select	sc.server_id,
					sc.channel_id
			from	rhnServerChannel sc,
					rhnChannelFamilyMembers cfm
			where	1=1
				and cfm.channel_family_id = channel_family_id_in
				and cfm.channel_id = sc.channel_id
				and server_id in (
					select	server_id
					from	(
						select	server_id,
								time,
								rownum row_number
						from	(
							select	rs.id					server_id,
									rcfm.modified			time
							from	
									rhnServerChannel		rsc,
									rhnChannelFamilyMembers	rcfm,
                                    rhnServer				rs
							where	1=1
								and rs.org_id = customer_id_in
								and rs.id = rsc.server_id
								and rsc.channel_id = rcfm.channel_id
								and rcfm.channel_family_id =
									channel_family_id_in
                                -- we only want to grab servers consuming
                                -- physical slots.
                                and exists (
                                    select 1
                                    from rhnChannelFamilyServerPhysical cfsp
                                    where cfsp.server_id = rs.id
                                    and cfsp.channel_family_id = 
                                        channel_family_id_in
                                    )
							order by time asc
						)
					)
					where row_number > quantity_in
				);
	begin
		-- if we get a null customer_id, this is completely bogus.
		if customer_id_in is null then
			return;
		end if;

		update		rhnPrivateChannelFamily
			set		max_members = quantity_in
			where	1=1
				and org_id = customer_id_in
				and channel_family_id = channel_family_id_in;

		for sc in serverchannels loop
			rhn_channel.unsubscribe_server(sc.server_id, sc.channel_id, 1, 1);
		end loop;
	end prune_family;
		
	procedure set_family_count (
		customer_id_in in number,
		channel_family_id_in in number,
		quantity_in in number
	) is
		cursor privperms is
			select	1
			from	rhnPrivateChannelFamily
			where	org_id = customer_id_in
				and channel_family_id = channel_family_id_in;
		cursor pubperms is
			select	o.id org_id
			from	web_customer o,
					rhnPublicChannelFamily pcf
			where	pcf.channel_family_id = channel_family_id_in;
		quantity number;
		done number := 0;
	begin
		quantity := quantity_in;
		if quantity is not null and quantity < 0 then
			quantity := 0;
		end if;

		if customer_id_in is not null then
			for perm in privperms loop
				rhn_entitlements.prune_family(
					customer_id_in,
					channel_family_id_in,
					quantity
				);
				update rhnPrivateChannelFamily
					set max_members = quantity
					where org_id = customer_id_in
						and channel_family_id = channel_family_id_in;
				return;
			end loop;
			
			insert into rhnPrivateChannelFamily (
					channel_family_id, org_id, max_members, current_members
				) values (
					channel_family_id_in, customer_id_in, quantity, 0
				);
			return;
		end if;

		for perm in pubperms loop
			if quantity = 0 then
				rhn_entitlements.prune_family(
					perm.org_id,
					channel_family_id_in,
					quantity
				);
				if done = 0 then
					delete from rhnPublicChannelFamily
						where channel_family_id = channel_family_id_in;
				end if;
			end if;
			done := 1;
		end loop;
		-- if done's not 1, then we don't have any entitlements
		if done != 1 then
			insert into rhnPublicChannelFamily (
					channel_family_id
				) values (
					channel_family_id_in
				);
		end if;
	end set_family_count;

	-- this expects quantity_in to be the number of available slots, not the
	-- max_members of the server group.  If you give it too many, it'll fail
	-- and raise servergroup_max_members.
	-- We should NEVER run this unless we're SURE that we won't
	-- be violating the max.
	procedure entitle_last_modified_servers (
		customer_id_in in number,
		type_label_in in varchar2,
		quantity_in in number
	) is
		-- find the servers that aren't currently in slots
		cursor servers(cid_in in number, quant_in in number) is
			select	server_id
			from	(
						select	rownum row_number,
								server_id
						from	(
									select	rs.id server_iD
									from	rhnServer rs
									where	1=1
										and rs.org_id = cid_in
										and not exists (
											select	1
											from	rhnServerGroup sg,
													rhnServerGroupMembers rsgm
											where	rsgm.server_id = rs.id
												and rsgm.server_group_id = sg.id
												and sg.group_type is not null
										)
                                        and not exists (
                                            select 1
                                            from rhnVirtualInstance vi
                                            where vi.virtual_system_id =
                                                  rs.id
                                        )                                                                           order by modified desc
								)
					)
			where	row_number <= quant_in;
	begin
		for server in servers(customer_id_in, quantity_in) loop
			rhn_entitlements.entitle_server(server.server_id, type_label_in);
		end loop;
	end entitle_last_modified_servers;

	procedure prune_everything (
		customer_id_in in number
	) is
		cursor everything is
			-- all our server groups
			select	sg.id					id,
					'S'						type,
					sg.max_members			quantity
			from	rhnServerGroup			sg
			where	sg.org_id = customer_id_in
			union
			-- all our user groups
			select	ug.id					id,
					'U'						type,
					ug.max_members 			quantity
			from	rhnUserGroup			ug
			where	ug.org_id = customer_id_in
			union ( 
			-- all the channel families we have perms to
			select	cfp.channel_family_id	id,
					'C'						type,
					cfp.max_members			quantity
			from	rhnOrgChannelFamilyPermissions cfp
			where	cfp.org_id = customer_id_in
			union
			-- plus all the ones we're using that we have no perms for
			select	cfm.channel_family_id	id,
					'C'						type,
					0						quantity
			from	rhnChannelFamily		cf,
					rhnChannelFamilyMembers	cfm,
					rhnServerChannel		sc,
					rhnServer				s
			where	s.org_id = customer_id_in
				and s.id = sc.server_id
				and sc.channel_id = cfm.channel_id
				and cfm.channel_family_id = cf.id
				and cf.org_id is not null
				and cf.org_id != customer_id_in
				and not exists (
					select	1
					from	rhnOrgChannelFamilyPermissions cfp
					where	cfp.org_id = customer_id_in
						and cfp.channel_family_id = cfm.channel_family_id
					)
			);
	begin
		for one in everything loop
			if one.type in ('U','S') then
				prune_group(one.id, one.type, one.quantity);
			else
				prune_family(customer_id_in, one.id, one.quantity);
			end if;
		end loop;
	end prune_everything;

	procedure subscribe_newest_servers (
		customer_id_in in number
	) is
		-- find servers without base channels
		cursor servers(cid_in in number) is
			select	s.id
			from	rhnServer			s
			where	1=1
				and s.org_id = cid_in
				and not exists (
						select 1
						from	rhnChannel			c,
								rhnServerChannel	sc
						where	sc.server_id = s.id
							and sc.channel_id = c.id
							and c.parent_channel is null
					)
                and not exists (
                        select 1
                        from rhnVirtualInstance vi
                        where vi.virtual_system_id = s.id
                    )                        
			order by s.modified desc;
		channel_id number;
	begin
		for server in servers(customer_id_in) loop
			channel_id := rhn_channel.guess_server_base(server.id);
			if channel_id is not null then
				begin
					rhn_channel.subscribe_server(server.id, channel_id);
					commit;
				-- exception is really channel_family_no_subscriptions
				exception
					when others then
						null;
				end;
			end if;
		end loop;
	end subscribe_newest_servers;
end rhn_entitlements;
/
show errors

--
--
-- Revision 1.56  2004/07/21 21:27:36  nhansen
-- bug 128196: use rhn_monitor instead of rhn_monitoring as the rhnOrgEntitlementType
--
-- Revision 1.55  2004/07/20 15:38:57  pjones
-- bugzilla: 128196 -- make entitling "monitoring" work.
--
-- Revision 1.54  2004/07/14 19:13:13  pjones
-- bugzilla: 126461 -- entitlement changes for new user roles
--
-- Revision 1.53  2004/07/02 19:18:20  pjones
-- bugzilla: 125937 -- use rhn_user to remove user roles
--
-- Revision 1.52  2004/05/26 19:45:48  pjones
-- bugzilla: 123639
-- 1) reformat "entitlement_grants_service"
-- 2) make the .pks and .pkb be in the same order.
-- 3) add "modify_org_service" (to be used instead of set_customer_SERVICELEVEL)
-- 4) add monitoring specific data.
--
-- Revision 1.51  2004/04/19 18:18:51  pjones
-- bugzilla: none -- misa's using set_family_count() to set null org entitlements
--
-- Revision 1.50  2004/04/14 00:09:24  pjones
-- bugzilla: 120761 -- split rhnChannelPermissions into two tables, eliminating
-- a frequent full table scan
--
-- Revision 1.49  2004/03/26 16:53:42  pjones
-- bugzilla: none -- make rhn_nonlinux give config_admin too on sat.
--
-- Revision 1.48  2004/03/25 22:29:56  pjones
-- bugzilla: none -- only create config_admin in set_customer_prov if we're
-- on a satellite
 070701000003FB000081B400000000000000000000000167AE1114000010B4000000000000000000000000000000000000006500000000susemanager-schema/upgrade/satellite-schema-5.3-to-spacewalk-schema-0.6/112-rhnPrivateErrataMail.sql  --
-- Copyright (c) 2008 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
-- This view is used for extracting data needed by the errata mailer
-- for private errata mails
--
--

create or replace view
rhnPrivateErrataMail
as
select
   w.id user_id,
   s.id server_id,
   w.org_id org_id,
   sc.channel_id channel_id,
   ce.errata_id errata_id
from
   rhnServer s,
   web_user_personal_info wpi,
   rhnUserInfo ui,
   rhnChannelErrata ce,
   web_contact w, 
   rhnServerChannel sc,
   rhnUserServerPerms usp
where
   -- we plan on starting with org_id, and server group is the 
   -- best place to find that that's near servers
   -- filter out servers that aren't in useful channels
   sc.channel_id = ce.channel_id
   -- find the server, so we can do s.arch comparisons
   and sc.server_id = s.id
   -- filter out users who don't want/can't get email
   and w.id = wpi.web_user_id
   and wpi.email is not null
   and w.id = ui.user_id
   and s.id = usp.server_id
   and usp.user_id = w.id
   -- filter out users who don't want mail about this server
   -- they get an entry if they _don't_ want mail
   and not exists (
      select   usprefs.server_id 
               from  rhnUserServerPrefs usprefs
         where w.id = usprefs.user_id 
               and sc.server_id = usprefs.server_id 
               and usprefs.name = 'receive_notifications'
   )
   and ui.email_notify = 1
      -- check permissions. For this query being an org admin is the
      -- most common thing, so we test for that first
   and exists (
         select 1
      from
            rhnPackageEVR        p_evr,
            rhnPackageEVR        sp_evr,
            rhnServerPackage     sp,
            rhnChannelPackage    cp,
            rhnPackage        p,
            rhnErrataPackage     ep,
            rhnServerPackageArchCompat spac
      where 1=1
         -- packages from channels this server is subscribed to
         and sc.channel_id = cp.channel_id
         and cp.package_id = p.id
         -- part of an errata
         and ce.errata_id = ep.errata_id
         and ep.package_id = p.id
         -- and that errata maps back to the server channel
         and sc.channel_id = ce.channel_id
         and ce.errata_id = ep.errata_id
         -- also installed on this server
         and sc.server_id = sp.server_id
         and sp.name_id = p.name_id
         and sp.evr_id = sp_evr.id
         -- different evr
         and p.evr_id = p_evr.id
         and sp.evr_id != p.evr_id
         -- and newer evr
         and sp_evr.evr < p_evr.evr
         and sp_evr.evr = (
            select max(sq2_pe.evr) max_evr
                from  rhnServerPackage  sq2_sp,
                rhnPackageEVR     sq2_pe
                where sq2_sp.evr_id = sq2_pe.id and
                  sq2_sp.server_id = sp.server_id and
                  sp.name_id = sq2_sp.name_id
	            group by sq2_sp.server_id, sq2_sp.name_id
         )
         -- compat arch
         and p.package_arch_id = spac.package_arch_id
         and s.server_arch_id = spac.server_arch_id
   )
   and not exists ( select 1
                      from rhnWebContactDisabled wcd
                     where wcd.id = w.id )
/


--select count(*) from rhnMailErrataView
--where org_id = 1 and errata_id = 916;

--
-- Revision 1.2  2003/02/21 20:56:00  pjones
-- change the comments to match the code ;)
--
-- Revision 1.1  2003/02/21 20:45:00  pjones
-- private errata mail
--
-- Revision 1.4  2003/02/12 18:49:11  pjones
-- note about old errata
--
-- Revision 1.3  2002/11/14 17:20:34  pjones
-- arch -> *_arch_id and archCompat changes
--
-- Revision 1.2  2002/11/11 20:49:46  pjones
-- that line's a typo
--
-- Revision 1.1  2002/09/24 22:42:17  pjones
-- free vs paid
--
070701000003FC000081B400000000000000000000000167AE111400002A76000000000000000000000000000000000000005E00000000susemanager-schema/upgrade/satellite-schema-5.3-to-spacewalk-schema-0.6/113-delete_server.sql -- 461704 - we need to wipe out all relevant entries for a probe from time_series
-- table whenever we're deleting server

create or replace
procedure delete_server (
	server_id_in in number
) is
	cursor servergroups is
		select	server_id, server_group_id
		from	rhnServerGroupMembers sgm
		where	sgm.server_id = server_id_in;
	cursor configchannels is
		select	cc.id
		from	rhnConfigChannel cc,
			rhnConfigChannelType cct,
			rhnServerConfigChannel scc
		where	1=1
			and scc.server_id = server_id_in
			and scc.config_channel_id = cc.id
			-- these config channel types are reserved
			-- for use by a single server, so we don't
			-- need to check for other servers subscribed
			and cct.label in
				('local_override','server_import')
			and cct.id = cc.confchan_type_id;
        type filelistsid_t is table of rhnServerPreserveFileList.file_list_id%type;
        filelistsid_c filelistsid_t;

        type probesid_t is table of rhn_check_probe.probe_id%type;
        probesid_c probesid_t;

    is_virt number := 0;
begin
	rhn_channel.delete_server_channels(server_id_in);
	-- rhn_channel.clear_subscriptions(server_id_in);

        -- filelists
	select	spfl.file_list_id id bulk collect into filelistsid_c
	  from	rhnServerPreserveFileList spfl
	 where	spfl.server_id = server_id_in
			and not exists (
				select	1
				from	rhnServerPreserveFileList
				where	file_list_id = spfl.file_list_id
					and server_id != server_id_in
				union
				select	1
				from	rhnKickstartPreserveFileList
				where	file_list_id = spfl.file_list_id
			);
        if filelistsid_c.first is not null then
            forall i in filelistsid_c.first..filelistsid_c.last
                delete from rhnFileList where id = filelistsid_c(i);
        end if;

	for configchannel in configchannels loop
		rhn_config.delete_channel(configchannel.id);
	end loop;

      select count(1) into is_virt
        from rhnServerEntitlementView
       where server_id = server_id_in
         and label in ('virtualization_host', 'virtualization_host_platform')
         and rownum <= 1;

	for sgm in servergroups loop
		rhn_server.delete_from_servergroup(
			sgm.server_id, sgm.server_group_id);
	end loop;

    if is_virt = 1 then
        rhn_entitlements.repoll_virt_guest_entitlements(server_id_in);
    end if;

	-- we're handling this instead of letting an "on delete
	-- set null" do it so that we don't run the risk
	-- of setting off the triggers and killing us with a
	-- mutating table

	-- this is merge of two single updates:
        --  update ... set old_server_id = null where old_server_id = server_id_in;
        --  update ... set new_server_id = null where new_server_id = server_id_in;
        -- so we scan rhnKickstartSession table only once
	update rhnKickstartSession
		set old_server_id = case when old_server_id = server_id_in then null else old_server_id end,
		    new_server_id = case when new_server_id = server_id_in then null else new_server_id end
		where old_server_id = server_id_in
		   or new_server_id = server_id_in;

	rhn_channel.clear_subscriptions(server_id_in,1);

	-- A little complicated here, but the goal is to
	-- delete records from rhnVirtualInstace only if we don't
	-- care about them anymore.  We don't care about records
	-- in rhnVirtualInstance if we are deleting the host
	-- system and the virtual system is already null, or
	-- vice-versa.  We *do* care about them if either the
	-- host or virtual system is still registered because we
	-- still want them to show up in the UI.
    -- If there's a newer row in rhnVirtualInstance with the same
    -- uuid, this guest must have been re-registered, so we can clean
    -- this data up.

        delete from rhnVirtualInstance vi
	      where (host_system_id = server_id_in and virtual_system_id is null)
                 or (virtual_system_id = server_id_in and host_system_id is null)
                 or (vi.virtual_system_id = server_id_in and vi.modified < (select max(vi2.modified)
                    from rhnVirtualInstance vi2 where vi2.uuid = vi.uuid));

        -- this is merge of two single updates:
        --  update ... set host_system_id = null where host_system_id = server_id_in;
        --  update ... set virtual_system_id = null where virtual_system_id = server_id_in;
        -- so we scan rhnVirtualInstance table only once
        update rhnVirtualInstance
	   set host_system_id = case when host_system_id = server_id_in then null else host_system_id end,
	       virtual_system_id = case when virtual_system_id = server_id_in then null else virtual_system_id end
	 where host_system_id = server_id_in
	    or virtual_system_id = server_id_in;

        -- this is merge of two single updates:
        --  update ... set old_host_system_id = null when old_host_system_id = server_id_in;
        --  update ... set new_host_system_id = null when new_host_system_id = server_id_in;
        -- so we scan rhnVirtualInstanceEventLog table only once
	update rhnVirtualInstanceEventLog
	   set old_host_system_id = case when old_host_system_id = server_id_in then null else old_host_system_id end,
               new_host_system_id = case when new_host_system_id = server_id_in then null else new_host_system_id end
         where old_host_system_id = server_id_in
            or new_host_system_id = server_id_in;

	-- We're deleting everything with a foreign key to rhnServer
	-- here, now.  I'm hoping this will help aleviate our deadlock
	-- problem.

	delete from rhnActionConfigChannel where server_id = server_id_in;
	delete from rhnActionConfigRevision where server_id = server_id_in;
	delete from rhnActionPackageRemovalFailure where server_id = server_id_in;
	delete from rhnChannelFamilyLicenseConsent where server_id = server_id_in;
	delete from rhnClientCapability where server_id = server_id_in;
	delete from rhnCpu where server_id = server_id_in;
	-- there's still a cascade here, because the constraint keeps the
	-- table locked for too long to rebuild it.  Ugh...
	delete from rhnDevice where server_id = server_id_in;
	delete from rhnProxyInfo where server_id = server_id_in;
	delete from rhnRam where server_id = server_id_in;
	delete from rhnRegToken where server_id = server_id_in;
	delete from rhnSNPServerQueue where server_id = server_id_in;
	delete from rhnSatelliteChannelFamily where server_id = server_id_in;
	delete from rhnSatelliteInfo where server_id = server_id_in;
	-- this cascades to rhnActionConfigChannel and rhnActionConfigFileName
	delete from rhnServerAction where server_id = server_id_in;
	delete from rhnServerActionPackageResult where server_id = server_id_in;
	delete from rhnServerActionScriptResult where server_id = server_id_in;
	delete from rhnServerActionVerifyResult where server_id = server_id_in;
	delete from rhnServerActionVerifyMissing where server_id = server_id_in;
	-- counts are handled above.  this should be a delete_ function.
	delete from rhnServerChannel where server_id = server_id_in;
	delete from rhnServerConfigChannel where server_id = server_id_in;
	delete from rhnServerCustomDataValue where server_id = server_id_in;
	delete from rhnServerDMI where server_id = server_id_in;
	delete from rhnServerMessage where server_id = server_id_in;
	-- this gets rhnServerMessage (only) on cascade; it's handled just above
	delete from rhnServerEvent where server_id = server_id_in;
	delete from rhnServerHistory where server_id = server_id_in;
	delete from rhnServerInfo where server_id = server_id_in;
	delete from rhnServerInstallInfo where server_id = server_id_in;
	delete from rhnServerLocation where server_id = server_id_in;
	delete from rhnServerLock where server_id = server_id_in;
	delete from rhnServerNeededCache where server_id = server_id_in;
	delete from rhnServerNetwork where server_id = server_id_in;
	delete from rhnServerNotes where server_id = server_id_in;
	-- I'm not removing the foreign key from rhnServerPackage; that'll
	-- take forever.  Do the delete anyway.
	delete from rhnServerPackage where server_id = server_id_in;
	delete from rhnServerTokenRegs where server_id = server_id_in;
	delete from rhnSnapshotTag where server_id = server_id_in;
	-- this cascades to:
	--   rhnSnapshotChannel, rhnSnapshotConfigChannel, rhnSnapshotPackage,
	--   rhnSnapshotConfigRevision, rhnSnapshotServerGroup,
	--   rhnSnapshotTag.
	-- We may want to consider delete_snapshot() at some point, but
	--   I don't think we need to yet.
	delete from rhnSnapshot where server_id = server_id_in;
	delete from rhnTransaction where server_id = server_id_in;
	delete from rhnUserServerPrefs where server_id = server_id_in;
	-- hrm, this one's interesting... we _probably_ should delete
	-- everything for the parent server_id when we delete the proxy,
	-- but we don't currently.
	delete from rhnServerPath where server_id_in in (server_id, proxy_server_id);
	delete from rhnUserServerPerms where server_id = server_id_in;

	delete from rhn_interface_monitoring where server_id = server_id_in;
	delete from rhnServerNetInterface where server_id = server_id_in;
	delete from rhn_server_monitoring_info where recid = server_id_in;

	delete from rhnAppInstallSession where server_id = server_id_in;
	delete from rhnServerUuid where server_id = server_id_in;
    -- We delete all the probes running directly against this system
    -- and any probes that were using this Server as a Proxy Scout.
     SELECT CP.probe_id bulk collect into probesid_c
       FROM rhn_check_probe CP
      WHERE CP.host_id = server_id_in
         OR CP.sat_cluster_id in
    (SELECT SN.sat_cluster_id
       FROM rhn_sat_node SN
      WHERE SN.server_id = server_id_in);

    if probesid_c.first is not null then
        FORALL i IN probesid_c.first..probesid_c.last
            DELETE FROM rhn_probe_state PS WHERE PS.probe_id = probesid_c(i);
        FORALL i IN probesid_c.first..probesid_c.last
            DELETE FROM rhn_probe P  WHERE P.recid = probesid_c(i);
        FORALL i IN probesid_c.first..probesid_c.last
            DELETE /*+index(time_series time_series_probe_id_idx)*/
            FROM time_series
            WHERE substr(o_id, instr(o_id, '-') + 1,
                (instr(o_id, '-', instr(o_id, '-') + 1) - instr(o_id, '-'))	- 1) = probesid_c(i);
    end if;

	delete from rhn_check_probe where host_id = server_id_in;
	delete from rhn_host_probe where host_id = server_id_in;

    delete from rhn_sat_cluster where recid in
      ( select sat_cluster_id from rhn_sat_node where server_id = server_id_in );

	delete from rhn_sat_node where server_id = server_id_in;

	-- now get rhnServer itself.
	delete
	from	rhnServer
		where id = server_id_in;

	delete
	from	rhnSet
	where	1=1
		and user_id in (
			select	wc.id
			from	rhnServer rs,
				web_contact wc
			where	rs.id = server_id_in
				and rs.org_id = wc.org_id
		)
		and label = 'system_list'
		and element = server_id_in;
end delete_server;
/
  070701000003FD000081B400000000000000000000000167AE111400000033000000000000000000000000000000000000005B00000000susemanager-schema/upgrade/satellite-schema-5.3-to-spacewalk-schema-0.6/115-rhnChannel.sql    alter table rhnChannel
modify name varchar2(256);

 070701000003FE000081B400000000000000000000000167AE111400000094000000000000000000000000000000000000005D00000000susemanager-schema/upgrade/satellite-schema-5.3-to-spacewalk-schema-0.6/116-rhn_sat_node.sql  drop index rhn_sat_node_sid_idx;
create unique index rhn_sat_node_sid_idx
on rhn_sat_node ( server_id )
   tablespace [[64k_tbs]]
   nologging
  ;

070701000003FF000081B400000000000000000000000167AE11140000C833000000000000000000000000000000000000006000000000susemanager-schema/upgrade/satellite-schema-5.3-to-spacewalk-schema-0.6/118-rhn_channel.pkb.sql   --
-- Copyright (c) 2008 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--

CREATE OR REPLACE
PACKAGE BODY rhn_channel
IS
        body_version varchar2(100) := '';

    -- Cursor that fetches all the possible base channels for a
    -- (server_arch_id, release, org_id) combination
        cursor  base_channel_cursor(
                release_in in varchar2,
                server_arch_id_in in number,
                org_id_in in number
        ) return rhnChannel%ROWTYPE is
                select distinct c.*
                from    rhnDistChannelMap                       dcm,
                                rhnServerChannelArchCompat      scac,
                                rhnChannel                                      c,
                                rhnChannelPermissions           cp
                where   cp.org_id = org_id_in
                        and cp.channel_id = c.id
                        and c.parent_channel is null
                        and c.id = dcm.channel_id
                        and c.channel_arch_id = dcm.channel_arch_id
                        and dcm.release = release_in
                        and scac.server_arch_id = server_arch_id_in
                        and scac.channel_arch_id = c.channel_arch_id;

    FUNCTION get_license_path(channel_id_in IN NUMBER)
    RETURN VARCHAR2
    IS
        license_val VARCHAR2(1000);
    BEGIN
        SELECT CFL.license_path INTO license_val
          FROM rhnChannelFamilyLicense CFL, rhnChannelFamilyMembers CFM
         WHERE CFM.channel_id = channel_id_in
           AND CFM.channel_family_id = CFL.channel_family_id;
    
        RETURN license_val;

    EXCEPTION
        WHEN NO_DATA_FOUND
            THEN
            RETURN NULL;
    END get_license_path;


    PROCEDURE license_consent(channel_id_in IN NUMBER, user_id_in IN NUMBER, server_id_in IN NUMBER)
    IS
        channel_family_id_val NUMBER;
    BEGIN
        channel_family_id_val := rhn_channel.family_for_channel(channel_id_in);
        IF channel_family_id_val IS NULL
        THEN
            rhn_exception.raise_exception('channel_subscribe_no_family');
        END IF;
        
        IF rhn_channel.get_license_path(channel_id_in) IS NULL
        THEN
            rhn_exception.raise_exception('channel_consent_no_license');
        END IF;
        
        INSERT INTO rhnChannelFamilyLicenseConsent (channel_family_id, user_id, server_id)
        VALUES (channel_family_id_val, user_id_in, server_id_in);
    END license_consent;

    PROCEDURE subscribe_server(server_id_in IN NUMBER, channel_id_in NUMBER, immediate_in NUMBER := 1, user_id_in in number := null, recalcfamily_in NUMBER := 1)
    IS
        channel_parent_val      rhnChannel.parent_channel%TYPE;
        parent_subscribed       BOOLEAN;
        server_has_base_chan    BOOLEAN;
        server_already_in_chan  BOOLEAN;
        channel_family_id_val   NUMBER;
        server_org_id_val       NUMBER;
        available_subscriptions NUMBER;
        consenting_user         NUMBER;
        allowed                 number := 0;
        current_members_val     number;
    BEGIN
        if user_id_in is not null then
            allowed := rhn_channel.user_role_check(channel_id_in, user_id_in, 'subscribe');
        else
            allowed := 1;
        end if;

        if allowed = 0 then
            rhn_exception.raise_exception('no_subscribe_permissions');
        end if;


        SELECT parent_channel INTO channel_parent_val FROM rhnChannel WHERE id = channel_id_in;

        IF channel_parent_val IS NOT NULL
        THEN    
            -- child channel; if attempting to cross-subscribe a child to the wrong base, silently ignore
            parent_subscribed := FALSE;    

            FOR check_subscription IN check_server_subscription(server_id_in, channel_parent_val)
            LOOP
                parent_subscribed := TRUE;
            END LOOP check_subscription;
        
            IF NOT parent_subscribed
            THEN
                RETURN;
            END IF;
        ELSE
            -- base channel
            server_has_base_chan := FALSE;
            FOR base IN server_base_subscriptions(server_id_in)
            LOOP
                server_has_base_chan := TRUE;
            END LOOP base;
            
            IF server_has_base_chan
            THEN
                rhn_exception.raise_exception('channel_server_one_base');
            END IF;
        END IF;
    
        FOR check_subscription IN check_server_subscription(server_id_in, channel_id_in)
        LOOP
            server_already_in_chan := TRUE;
        END LOOP check_subscription;
    
        IF server_already_in_chan
        THEN
            RETURN;
        END IF;
        
        channel_family_id_val := rhn_channel.family_for_channel(channel_id_in);
        IF channel_family_id_val IS NULL
        THEN
            rhn_exception.raise_exception('channel_subscribe_no_family');
        END IF;

        --
        -- Use the org_id of the server only if the org_id of the channel = NULL.
        -- This is required for subscribing to shared channels.
        --
        SELECT NVL(org_id, (SELECT org_id FROM rhnServer WHERE id = server_id_in))
          INTO server_org_id_val
          FROM rhnChannel
         WHERE id = channel_id_in;
         
        select current_members 
        into current_members_val
        from rhnPrivateChannelFamily
        where org_id = server_org_id_val and channel_family_id = channel_family_id_val
        for update of current_members;

        available_subscriptions := rhn_channel.available_family_subscriptions(channel_family_id_val, server_org_id_val);
        
        IF available_subscriptions IS NULL OR 
           available_subscriptions > 0 or
           can_server_consume_virt_channl(server_id_in, channel_family_id_val) = 1
        THEN
        
            IF rhn_channel.get_license_path(channel_id_in) IS NOT NULL
            THEN
                BEGIN
                
                SELECT user_id INTO consenting_user
                  FROM rhnChannelFamilyLicenseConsent
                 WHERE channel_family_id = channel_family_id_val
                   AND server_id = server_id_in;
                
                EXCEPTION
                    WHEN NO_DATA_FOUND THEN
                        rhn_exception.raise_exception('channel_subscribe_no_consent');
                END;
            END IF;
        
            insert into rhnServerHistory (id,server_id,summary,details) (
                select  rhn_event_id_seq.nextval,
                        server_id_in,
                        'subscribed to channel ' || SUBSTR(c.label, 0, 106),
                        c.label
                from    rhnChannel c
                where   c.id = channel_id_in
            );
            UPDATE rhnServer SET channels_changed = sysdate WHERE id = server_id_in;
            INSERT INTO rhnServerChannel (server_id, channel_id) VALUES (server_id_in, channel_id_in);
			IF recalcfamily_in > 0
			THEN
                rhn_channel.update_family_counts(channel_family_id_val, server_org_id_val);
			END IF;
            queue_server(server_id_in, immediate_in);
        ELSE
            rhn_exception.raise_exception('channel_family_no_subscriptions');
        END IF;
            
    END subscribe_server;
    
    function can_server_consume_virt_channl(
        server_id_in in number,
        family_id_in in number )
    return number
    is

        cursor server_virt_families is
            select vi.virtual_system_id, cfvsl.channel_family_id
            from
                rhnChannelFamilyVirtSubLevel cfvsl,
                rhnSGTypeVirtSubLevel sgtvsl,
                rhnVirtualInstance vi
            where
                vi.virtual_system_id = server_id_in 
                and sgtvsl.virt_sub_level_id = cfvsl.virt_sub_level_id
                and cfvsl.channel_family_id = family_id_in
                and exists (
                    select 1
                    from rhnServerEntitlementView sev
                    where vi.host_system_id = sev.server_id
                    and sev.server_group_type_id = sgtvsl.server_group_type_id );
    begin

        for server_virt_family in server_virt_families loop
            return 1;
        end loop;

        return 0;

    end;


    PROCEDURE bulk_subscribe_server(channel_id_in IN NUMBER, set_label_in IN VARCHAR2, set_uid_in IN NUMBER)
    IS
    BEGIN
        FOR server IN rhn_set.set_iterator(set_label_in, set_uid_in)
        LOOP
            rhn_channel.subscribe_server(server.element, channel_id_in, 0, set_uid_in);
        END LOOP server;
    END bulk_subscribe_server;

    PROCEDURE bulk_server_base_change(channel_id_in IN NUMBER, set_label_in IN VARCHAR2, set_uid_in IN NUMBER)
    IS
    BEGIN
        FOR server IN rhn_set.set_iterator(set_label_in, set_uid_in)
        LOOP
            IF rhn_server.can_change_base_channel(server.element) = 1
            THEN
                rhn_channel.clear_subscriptions(TO_NUMBER(server.element));
                rhn_channel.subscribe_server(server.element, channel_id_in, 0, set_uid_in);
            END IF;
        END LOOP server;
    END bulk_server_base_change;

    procedure bulk_server_basechange_from(
        set_label_in in varchar2,
        set_uid_in in number,
        old_channel_id_in in number,
        new_channel_id_in in number
    ) is
    cursor servers is
        select  sc.server_id id
        from    rhnChannel nc,
                rhnServerChannelArchCompat scac,
                rhnServer s,
                rhnChannel oc,
                rhnServerChannel sc,
                rhnSet st
        where   1=1
            -- first, find the servers we're looking for.
            and st.label = set_label_in
            and st.user_id = set_uid_in
            and st.element = sc.server_id
            -- now, filter out anything that's not in the
            -- old base channel.
            and sc.channel_id = old_channel_id_in
            and sc.channel_id = oc.id
            and oc.parent_channel is null
            -- now, see if it's compatible with the new base channel
            and nc.id = new_channel_id_in
            and nc.parent_channel is null
            and sc.server_id = s.id
            and s.server_arch_id = scac.server_arch_id
            and scac.channel_arch_id = nc.channel_arch_id;
    begin
        for s in servers loop
            insert into rhnSet (
                    user_id, label, element
                ) values (
                    set_uid_in,
                    set_label_in || 'basechange', 
                    s.id
                );
        end loop channel;
        bulk_server_base_change(new_channel_id_in,
                                set_label_in || 'basechange',
                                set_uid_in);
        delete from rhnSet
            where   label = set_label_in||'basechange'
                and user_id = set_uid_in;
    end bulk_server_basechange_from;

    procedure bulk_guess_server_base(
        set_label_in in varchar2,
        set_uid_in in number
    ) is
        channel_id number;
    begin
        for server in rhn_set.set_iterator(set_label_in, set_uid_in)
        loop
            -- anything that doesn't work, we just ignore
            begin
                if rhn_server.can_change_base_channel(server.element) = 1
                then
                    channel_id := guess_server_base(TO_NUMBER(server.element));
                    rhn_channel.clear_subscriptions(TO_NUMBER(server.element));
                    rhn_channel.subscribe_server(TO_NUMBER(server.element), channel_id, 0, set_uid_in);
                end if;
            exception when others then
                null;
            end;
        end loop server;
    end;

    function guess_server_base(
        server_id_in in number
    ) RETURN number is
        cursor server_cursor is
            select s.server_arch_id, s.release, s.org_id
              from rhnServer s
             where s.id = server_id_in;
    begin
        for s in server_cursor loop
            for channel in base_channel_cursor(s.release,
                s.server_arch_id, s.org_id) 
            loop
                return channel.id;
            end loop base_channel_cursor;
        end loop server_cursor;
        -- Server not found, or no base channel applies to it
        return null;
    end;

    -- Private function
    function normalize_server_arch(server_arch_in in varchar2)
    return varchar2
    deterministic
    is
        suffix VARCHAR2(128) := '-redhat-linux';
        suffix_len NUMBER := length(suffix);
    begin
        if server_arch_in is NULL then
            return NULL;
        end if;
        if instr(server_arch_in, '-') > 0
        then
            -- Suffix already present
            return server_arch_in;
        end if;
        return server_arch_in || suffix;
    end normalize_server_arch;

    --
    --
    -- Raises: 
    --   server_arch_not_found
    --   no_subscribe_permissions
    function base_channel_for_release_arch(
        release_in in varchar2,
        server_arch_in in varchar2,
        org_id_in in number := -1,
        user_id_in in number := null
    ) return number is
        server_arch varchar2(256) := normalize_server_arch(server_arch_in);
        server_arch_id number;
    begin
        -- Look up the server arch
        begin
            select id
              into server_arch_id
              from rhnServerArch
             where label = server_arch;
        exception
            when no_data_found then
                rhn_exception.raise_exception('server_arch_not_found');
        end;
        return base_channel_rel_archid(release_in, server_arch_id,
            org_id_in, user_id_in);
    end base_channel_for_release_arch;

    function base_channel_rel_archid(
        release_in in varchar2,
        server_arch_id_in in number,
        org_id_in in number := -1,
        user_id_in in number := null
    ) return number is
        denied_channel_id number := null;
        valid_org_id number := org_id_in;
        valid_user_id number := user_id_in;
        channel_subscribable number;
    begin
        if org_id_in = -1 and user_id_in is not null then
            -- Get the org id from the user id
            begin
                select org_id
                  into valid_org_id
                  from web_contact
                 where id = user_id_in;
            exception
                when no_data_found then
                    -- User doesn't exist
                    -- XXX Only list public stuff for now
                    valid_user_id := null;
                    valid_org_id := -1;
            end;
        end if;

        for c in base_channel_cursor(release_in, server_arch_id_in, valid_org_id)
        loop
            -- This row is a possible match
            if valid_user_id is null then
                -- User ID not specified, so no user to channel permissions to
                -- check
                return c.id;
            end if;

            -- Check user to channel permissions
            select loose_user_role_check(c.id, user_id_in, 'subscribe')
              into channel_subscribable
              from dual;

            if channel_subscribable = 1 then
                return c.id;
            end if;
                
            -- Base channel exists, but is not subscribable; keep trying
            denied_channel_id := c.id;
        end loop base_channel_fetch;
        
        if denied_channel_id is not null then
            rhn_exception.raise_exception('no_subscribe_permissions');
        end if;
        -- No base channel applies
        return NULL;
    end base_channel_rel_archid;

    procedure bulk_guess_server_base_from(
        set_label_in in varchar2,
        set_uid_in in number,
        channel_id_in in number
    ) is
        cursor channels(server_id_in in number) is
            select      rsc.channel_id
            from        rhnServerChannel rsc,
                        rhnChannel rc
            where       server_id_in = rsc.server_id
                        and rsc.channel_id = rc.id
                        and rc.parent_channel is null;
    begin
        for server in rhn_set.set_iterator(set_label_in, set_uid_in)
        loop
            for channel in channels(server.element)
            loop
                if channel.channel_id = channel_id_in
                then
                    insert into rhnSet (user_id, label, element) values (set_uid_in, set_label_in || 'baseguess', server.element);
                end if;
            end loop channel;
        end loop server;
        bulk_guess_server_base(set_label_in||'baseguess',set_uid_in);
        delete from rhnSet where label = set_label_in||'baseguess' and user_id = set_uid_in;
    end;


    PROCEDURE clear_subscriptions(server_id_in IN NUMBER, deleting_server IN NUMBER := 0 )
    IS
        cursor server_channels(server_id_in in number) is
                select  s.org_id, sc.channel_id, cfm.channel_family_id
                from    rhnServer s,
                        rhnServerChannel sc,
                        rhnChannelFamilyMembers cfm
                where   s.id = server_id_in
                        and s.id = sc.server_id
                        and sc.channel_id = cfm.channel_id;
    BEGIN
        for channel in server_channels(server_id_in)
        loop
                unsubscribe_server(server_id_in, channel.channel_id, 1, 1, deleting_server);
                rhn_channel.update_family_counts(channel.channel_family_id, channel.org_id);
        end loop channel;
    END clear_subscriptions;

    PROCEDURE unsubscribe_server(server_id_in IN NUMBER, channel_id_in NUMBER, immediate_in NUMBER := 1, unsubscribe_children_in number := 0,
                                 deleting_server IN NUMBER := 0 )
    IS
        channel_family_id_val   NUMBER;
        server_org_id_val       NUMBER;
        available_subscriptions NUMBER; 
        server_already_in_chan  BOOLEAN;
        cursor  channel_family_is_proxy(channel_family_id_in in number) is
                select  1
                from    rhnChannelFamily
                where   id = channel_family_id_in
                    and label = 'rhn-proxy';
        cursor  channel_family_is_satellite(channel_family_id_in in number) is
                select  1
                from    rhnChannelFamily
                where   id = channel_family_id_in
                    and label = 'rhn-satellite';
        -- this is *EXACTLY* like check_server_parent_membership, but if we recurse
        -- with the package-level one, we get a "cursor already open", so we need a
        -- copy on our call stack instead.  GROAN.
        cursor local_chk_server_parent_memb (
                        server_id_in number,
                        channel_id_in number ) is
                select  c.id
                from    rhnChannel                      c,
                                rhnServerChannel        sc
                where   1=1
                        and c.parent_channel = channel_id_in
                        and c.id = sc.channel_id
                        and sc.server_id = server_id_in;
    BEGIN
        FOR child IN local_chk_server_parent_memb(server_id_in, channel_id_in)
        LOOP
            if unsubscribe_children_in = 1 then
                unsubscribe_server(server_id_in => server_id_in,
                                                                channel_id_in => child.id,
                                                                immediate_in => immediate_in,
                                                                unsubscribe_children_in => unsubscribe_children_in,
                        deleting_server => deleting_server);
            else
                rhn_exception.raise_exception('channel_unsubscribe_child_exists');
            end if;
        END LOOP child;
        
        server_already_in_chan := FALSE;
    
        FOR check_subscription IN check_server_subscription(server_id_in, channel_id_in)
        LOOP
            server_already_in_chan := TRUE;
        END LOOP check_subscription;
    
        IF NOT server_already_in_chan
        THEN
            RETURN;
        END IF;
        
   if deleting_server = 0 then 

      insert into rhnServerHistory (id,server_id,summary,details) (
          select  rhn_event_id_seq.nextval,
                server_id_in,
             'unsubscribed from channel ' || SUBSTR(c.label, 0, 106),
             c.label
          from    rhnChannel c
          where   c.id = channel_id_in
      );

        UPDATE rhnServer SET channels_changed = sysdate WHERE id = server_id_in;
   end if;
        
   DELETE FROM rhnServerChannel WHERE server_id = server_id_in AND channel_id = channel_id_in;

   if deleting_server = 0 then 
        queue_server(server_id_in, immediate_in);
   end if;

        channel_family_id_val := rhn_channel.family_for_channel(channel_id_in);
        IF channel_family_id_val IS NULL
        THEN
            rhn_exception.raise_exception('channel_unsubscribe_no_family');
        END IF;

        for ignore in channel_family_is_satellite(channel_family_id_val) loop
                delete from rhnSatelliteInfo where server_id = server_id_in;
                delete from rhnSatelliteChannelFamily where server_id = server_id_in;
        end loop;

        for ignore in channel_family_is_proxy(channel_family_id_val) loop
                delete from rhnProxyInfo where server_id = server_id_in;
        end loop;

        DELETE FROM rhnChannelFamilyLicenseConsent
         WHERE channel_family_id = channel_family_id_val
           AND server_id = server_id_in;
                        
        SELECT org_id INTO server_org_id_val
          FROM rhnServer
         WHERE id = server_id_in;
         
        rhn_channel.update_family_counts(channel_family_id_val, server_org_id_val);
    END unsubscribe_server;

    PROCEDURE bulk_unsubscribe_server(channel_id_in IN NUMBER, set_label_in IN VARCHAR2, set_uid_in IN NUMBER)
    IS
    BEGIN
        FOR server IN rhn_set.set_iterator(set_label_in, set_uid_in)
        LOOP
            rhn_channel.unsubscribe_server(server.element, channel_id_in, 0);
        END LOOP server;
    END bulk_unsubscribe_server;

    FUNCTION family_for_channel(channel_id_in IN NUMBER)
    RETURN NUMBER
    IS
        channel_family_id_val NUMBER;
    BEGIN
        SELECT channel_family_id INTO channel_family_id_val
          FROM rhnChannelFamilyMembers
         WHERE channel_id = channel_id_in;
         
        RETURN channel_family_id_val;
    EXCEPTION
        WHEN NO_DATA_FOUND
        THEN
            RETURN NULL;
    END family_for_channel;

    FUNCTION available_family_subscriptions(channel_family_id_in IN NUMBER, org_id_in IN NUMBER)
    RETURN NUMBER
    IS
        cfp channel_family_perm_cursor%ROWTYPE;
        current_members_val NUMBER;
        max_members_val     NUMBER;
        found               NUMBER;
    BEGIN
        IF NOT channel_family_perm_cursor%ISOPEN
        THEN
            OPEN channel_family_perm_cursor(channel_family_id_in, org_id_in);
        END IF;

        FETCH channel_family_perm_cursor INTO cfp;
        
        WHILE channel_family_perm_cursor%FOUND
        LOOP
            found := 1;
            
            current_members_val := cfp.current_members;
            max_members_val := cfp.max_members;
            
            FETCH channel_family_perm_cursor INTO cfp;
        END LOOP;

        IF channel_family_perm_cursor%ISOPEN
        THEN
            CLOSE channel_family_perm_cursor;
        END IF;

        -- not found: either the channel fam doesn't have an entry in cfp, or the org doesn't have access to it.
        -- either way, there are no available subscriptions
        
        IF found IS NULL
        THEN
            RETURN 0;
        END IF;

        -- null max members?  in that case, pass it on; NULL means infinite                     
        IF max_members_val IS NULL
        THEN
            RETURN NULL;
        END IF;

        -- otherwise, return the delta  
        RETURN max_members_val - current_members_val;                   
    END available_family_subscriptions;
    
    -- *******************************************************************
    -- FUNCTION: channel_family_current_members
    -- Calculates and returns the actual count of systems consuming
    --   physical channel subscriptions.
    -- Called by: update_family_counts 
    --            rhn_entitlements.repoll_virt_guest_entitlements
    -- *******************************************************************
    function channel_family_current_members(channel_family_id_in IN NUMBER,
                                            org_id_in IN NUMBER)
    return number
    is
        current_members_count number := 0;
    begin
        select  count(distinct sc.server_id)
        into    current_members_count
        from    rhnChannelFamilyMembers cfm,
                rhnServerChannel sc,
                rhnServer s
        where   s.org_id = org_id_in
            and s.id = sc.server_id
            and cfm.channel_family_id = channel_family_id_in
            and cfm.channel_id = sc.channel_id
            and exists ( 
                select 1
                from rhnChannelFamilyServerPhysical cfsp
                where cfsp.CHANNEL_FAMILY_ID = channel_family_id_in
                    and cfsp.server_id = s.id
                );

        return current_members_count;
    end;        

    PROCEDURE update_family_counts(channel_family_id_in IN NUMBER, 
                                   org_id_in IN NUMBER)
    IS
    BEGIN
                update rhnPrivateChannelFamily
                set current_members = (
                channel_family_current_members(channel_family_id_in, org_id_in)
                )
                        where org_id = org_id_in
                                and channel_family_id = channel_family_id_in;

    END update_family_counts;
    
    FUNCTION available_chan_subscriptions(channel_id_in IN NUMBER, 
                                          org_id_in IN NUMBER)
    RETURN NUMBER
    IS
            channel_family_id_val NUMBER;
    BEGIN
        SELECT channel_family_id INTO channel_family_id_val
            FROM rhnChannelFamilyMembers
            WHERE channel_id = channel_id_in;
         
            RETURN rhn_channel.available_family_subscriptions(
                           channel_family_id_val, org_id_in);
    END available_chan_subscriptions;

    -- *******************************************************************
    -- PROCEDURE: entitle_customer
    -- Creates a chan fam bucket, or sets max_members for an existing bucket
    -- Called by: rhn_ep.poll_customer_internal
    -- Calls: set_family_maxmembers + update_family_counts if the row
    --        already exists, else it creates it in rhnPrivateChannelFamily.
    -- *******************************************************************
    procedure entitle_customer(customer_id_in in number, 
                               channel_family_id_in in number, 
                               quantity_in in number)
    is
                cursor permissions is
                        select  1
                        from    rhnPrivateChannelFamily pcf
                        where   pcf.org_id = customer_id_in
                                and     pcf.channel_family_id = channel_family_id_in; 
    begin
                for perm in permissions loop
                        set_family_maxmembers(
                                customer_id_in,
                                channel_family_id_in,
                                quantity_in
                        );
                        rhn_channel.update_family_counts(
                                channel_family_id_in,
                                customer_id_in
                        );
                        return;
                end loop;
        
                insert into rhnPrivateChannelFamily pcf (
                                channel_family_id, org_id, max_members, current_members
                        ) values (
                                channel_family_id_in, customer_id_in, quantity_in, 0
                        );
    end;

    -- *******************************************************************
    -- PROCEDURE: set_family_maxmembers
    -- Prunes an existing channel family bucket by unsubscribing the
    --   necessary servers and sets max_members.
    -- Called by: rhn_channel.entitle_customer
    -- Calls: unsubscribe_server_from_family
    -- *******************************************************************
    procedure set_family_maxmembers(customer_id_in in number, 
                                    channel_family_id_in in number, 
                                    quantity_in in number)
    is
        cursor servers is
            select  server_id from (
            select      rownum row_number, server_id, modified from (
                select  rcfsp.server_id,
                        rcfsp.modified
                from    rhnChannelFamilyServerPhysical rcfsp
                where   rcfsp.customer_id = customer_id_in
                    and rcfsp.channel_family_id = channel_family_id_in
                order by modified
            )
            where rownum > quantity_in
            );
    begin
            -- prune subscribed servers
        for server in servers loop
            rhn_channel.unsubscribe_server_from_family(server.server_id, 
                                                       channel_family_id_in);
        end loop;

        update  rhnPrivateChannelFamily pcf
        set     pcf.max_members = quantity_in
        where   pcf.org_id = customer_id_in
            and pcf.channel_family_id = channel_family_id_in;
    end;

    procedure unsubscribe_server_from_family(server_id_in in number, 
                                             channel_family_id_in in number)
    is
    begin
        delete
        from    rhnServerChannel rsc
        where   rsc.server_id = server_id_in
            and channel_id in (
                select  rcfm.channel_id
                from    rhnChannelFamilyMembers rcfm
                where   rcfm.channel_family_id = channel_family_id_in);
    end;

    function get_org_id(channel_id_in in number)
    return number
    is
        org_id_out number;
    begin
        select org_id into org_id_out
            from rhnChannel
            where id = channel_id_in;
         
            return org_id_out;
    end get_org_id;
    
    function get_cfam_org_access(cfam_id_in in number, org_id_in in number)
    return number
    is
        cursor  families is
                        select  1
                        from    rhnOrgChannelFamilyPermissions cfp
                        where   cfp.org_id = org_id_in;
    begin
                -- the idea: if we get past this query, 
        -- the user has the role, else catch the exception and return 0
                for family in families loop
                return 1;
                end loop;
                return 0;
    end;

    function get_org_access(channel_id_in in number, org_id_in in number)
    return number
    is
        throwaway number;
    begin
        -- the idea: if we get past this query, 
        -- the org has access to the channel, else catch the exception and return 0
        select distinct 1 into throwaway
          from rhnChannelFamilyMembers CFM,
               rhnOrgChannelFamilyPermissions CFP
         where cfp.org_id = org_id_in
           and CFM.channel_family_id = CFP.channel_family_id
           and CFM.channel_id = channel_id_in
           and (CFP.max_members > 0 or CFP.max_members is null or CFP.org_id = 1);
           
        return 1;
        exception
            when no_data_found
            then
            return 0;
    end;
    
    -- check if a user has a given role, or if such a role is inferrable
    function user_role_check_debug(channel_id_in in number, 
                                   user_id_in in number, 
                                   role_in in varchar2, 
                                   reason_out out varchar2)
    return number
    is
        org_id number;
    begin
        org_id := rhn_user.get_org_id(user_id_in);

        -- channel might be shared
        if role_in = 'subscribe' and
           rhn_channel.shared_user_role_check(channel_id_in, user_id_in, role_in) = 1 then
            return 1;
        end if;
        
        if role_in = 'manage' and 
           NVL(rhn_channel.get_org_id(channel_id_in), -1) <> org_id then
                reason_out := 'channel_not_owned';
               return 0;
            end if;
        
        if role_in = 'subscribe' and 
           rhn_channel.get_org_access(channel_id_in, org_id) = 0 then
                reason_out := 'channel_not_available';
                return 0;
            end if;
        
        -- channel admins have all roles
        if rhn_user.check_role_implied(user_id_in, 'channel_admin') = 1 then
            reason_out := 'channel_admin';
            return 1;
            end if;

        -- the subscribe permission is inferred 
    -- UNLESS the not_globally_subscribable flag is set 
        if role_in = 'subscribe'
        then
            if rhn_channel.org_channel_setting(channel_id_in, 
                       org_id,
                       'not_globally_subscribable') = 0 then
                reason_out := 'globally_subscribable';
                    return 1;
            end if;
        end if;
        
        -- all other roles (manage right now) are explicitly granted    
        reason_out := 'direct_permission';
        return rhn_channel.direct_user_role_check(channel_id_in, 
                                              user_id_in, role_in);
    end;
    
    -- same as above, but with no OUT param; useful in views, etc
    function user_role_check(channel_id_in in number, user_id_in in number, role_in in varchar2)
    return number
    is
        throwaway varchar2(256);
    begin
        return rhn_channel.user_role_check_debug(channel_id_in, user_id_in, role_in, throwaway);
    end;

    --
    -- For multiorg phase II, this function simply checks to see if the user's
    -- has a trust relationship that includes this channel by id.
    --
    function shared_user_role_check(channel_id in number, user_id in number, role in varchar2)
    return number
    is
      n number;
      oid number;
    begin
      oid := rhn_user.get_org_id(user_id);
      select 1 into n
      from rhnSharedChannelView s
      where s.id = channel_id and s.org_trust_id = oid;
      return 1;
      exception
        when no_data_found then
          return 0;
    end;

    -- same as above, but returns 1 if user_id_in is null
    -- This is useful in queries where user_id is not specified
    function loose_user_role_check(channel_id_in in number, user_id_in in number, role_in in varchar2)
    return number
    is
    begin
        if user_id_in is null then
            return 1;
        end if;
        return user_role_check(channel_id_in, user_id_in, role_in);
    end loose_user_role_check;
    
    -- directly checks the table, no inferred permissions
    function direct_user_role_check(channel_id_in in number, user_id_in in number, role_in in varchar2)
    return number
    is
        throwaway number;
    begin
        -- the idea: if we get past this query, the user has the role, else catch the exception and return 0
        select 1 into throwaway
          from rhnChannelPermissionRole CPR,
               rhnChannelPermission CP
         where CP.user_id = user_id_in
           and CP.channel_id = channel_id_in
           and CPR.label = role_in
           and CP.role_id = CPR.id;
           
        return 1;
    exception
        when no_data_found
            then
            return 0;
    end;
    
    -- check if an org has a certain setting
    function org_channel_setting(channel_id_in in number, org_id_in in number, setting_in in varchar2)
    return number
    is
        throwaway number;
    begin
        -- the idea: if we get past this query, the org has the setting, else catch the exception and return 0
        select 1 into throwaway
          from rhnOrgChannelSettingsType OCST,
               rhnOrgChannelSettings OCS
         where OCS.org_id = org_id_in
           and OCS.channel_id = channel_id_in
           and OCST.label = setting_in
           and OCS.setting_id = OCST.id;
           
        return 1;
    exception
        when no_data_found
            then
            return 0;
    end;
    
    FUNCTION channel_priority(channel_id_in IN number) 
    RETURN number
    IS
         channel_name varchar2(256);
         priority number;
         end_of_life_val date;
         org_id_val number;
    BEGIN

        select name, end_of_life, org_id
        into channel_name, end_of_life_val, org_id_val
        from rhnChannel
        where id = channel_id_in;

        if end_of_life_val is not null then
          return -400;
        end if;

        if channel_name like 'Red Hat Enterprise Linux%' or channel_name like 'RHEL%' then
          priority := 1000;
          if channel_name not like '%Beta%' then
            priority := priority + 1000;
          end if;

          priority := priority +
            case
              when channel_name like '%v. 5%' then 600
              when channel_name like '%v. 4%' then 500
              when channel_name like '%v. 3%' then 400
              when channel_name like '%v. 2%' then 300
              when channel_name like '%v. 1%' then 200
              else 0
            end;

          priority := priority +
            case
              when channel_name like 'Red Hat Enterprise Linux (v. 5%' then 60
              when (channel_name like '%AS%' and channel_name not like '%Extras%') then 50
              when (channel_name like '%ES%' and channel_name not like '%Extras%') then 40
              when (channel_name like '%WS%' and channel_name not like '%Extras%') then 30
              when (channel_name like '%Desktop%' and channel_name not like '%Extras%') then 20
              when channel_name like '%Extras%' then 10
              else 0
            end; 

          priority := priority +
            case
              when channel_name like '%)' then 5
              else 0
            end;

          priority := priority +
            case
              when channel_name like '%32-bit x86%' then 4
              when channel_name like '%64-bit Intel Itanium%' then 3
              when channel_name like '%64-bit AMD64/Intel EM64T%' then 2
              else 0
            end;
        elsif channel_name like 'Red Hat Desktop%' then
            priority := 900;

            if channel_name not like '%Beta%' then
               priority := priority + 50;
            end if;
 
          priority := priority +
            case
              when channel_name like '%v. 4%' then 40
              when channel_name like '%v. 3%' then 30
              when channel_name like '%v. 2%' then 20
              when channel_name like '%v. 1%' then 10
              else 0
            end;
            
          priority := priority +
            case
              when channel_name like '%32-bit x86%' then 4
              when channel_name like '%64-bit Intel Itanium%' then 3
              when channel_name like '%64-bit AMD64/Intel EM64T%' then 2
              else 0
            end;
         
        elsif org_id_val is not null then
          priority := 600;
        else
          priority := 500;
        end if;
      
      return -priority;

    end channel_priority;

    -- right now this only does the accounting changes; the cascade
    -- actually does the rhnServerChannel delete.
    procedure delete_server_channels(server_id_in in number)
    is
    begin
        update  rhnPrivateChannelFamily
        set     current_members = current_members -1
        where   org_id in (
                        select  org_id
                        from    rhnServer
                        where   id = server_id_in
                )
                and channel_family_id in (
                        select  rcfm.channel_family_id
                        from    rhnChannelFamilyMembers rcfm,
                                rhnServerChannel rsc
                        where   rsc.server_id = server_id_in
                                and rsc.channel_id = rcfm.channel_id
                and not exists (
                    select 1
                    from
                        rhnChannelFamilyVirtSubLevel cfvsl,
                        rhnSGTypeVirtSubLevel sgtvsl,
                        rhnServerEntitlementView sev,
                        rhnVirtualInstance vi
                    where
                        -- system is a virtual instance
                        vi.virtual_system_id = server_id_in
                        and vi.host_system_id = sev.server_id
                        -- system's host has a virt ent
                        and sev.label in ('virtualization_host',
                                          'virtualization_host_platform')
                        and sev.server_group_type_id = 
                            sgtvsl.server_group_type_id
                        -- the host's virt ent grants a cf virt sub level
                        and sgtvsl.virt_sub_level_id = cfvsl.virt_sub_level_id
                        -- the cf is in that virt sub level
                        and cfvsl.channel_family_id = rcfm.channel_family_id
                    )
                );
    end;

        -- this could certainly be optimized to do updates if needs be
        procedure refresh_newest_package(channel_id_in in number, caller_in in varchar2 := '(unknown)')
        is
        begin
                delete from rhnChannelNewestPackage where channel_id = channel_id_in;
                insert into rhnChannelNewestPackage
                        ( channel_id, name_id, evr_id, package_id, package_arch_id ) 
                        (       select  channel_id,
                                                name_id, evr_id,
                                                package_id, package_arch_id
                                from    rhnChannelNewestPackageView
                                where   channel_id = channel_id_in
                        );
                insert into rhnChannelNewestPackageAudit (channel_id, caller)
                    values (channel_id_in, caller_in);
                update rhnChannel 
                    set last_modified = greatest(sysdate, last_modified + 1/86400)
                    where id = channel_id_in; 
        end;

   procedure update_channel ( channel_id_in in number, invalidate_ss in number := 0, 
                              date_to_use in date := sysdate )
   is

   channel_last_modified date;
   last_modified_value date;

   cursor snapshots is
   select  snapshot_id id
   from    rhnSnapshotChannel
   where   channel_id = channel_id_in;

   begin

      select last_modified
      into channel_last_modified
      from rhnChannel
      where id = channel_id_in;
  
      last_modified_value := date_to_use;

      if last_modified_value <= channel_last_modified then
          last_modified_value := last_modified_value + 1/86400;
      end if;

      update rhnChannel set last_modified = last_modified_value
      where id = channel_id_in;

      if invalidate_ss = 1 then 
        for snapshot in snapshots loop
            update rhnSnapshot
            set invalid = lookup_snapshot_invalid_reason('channel_modified')
            where id = snapshot.id;
        end loop;
      end if;

   end update_channel;

   procedure update_channels_by_package ( package_id_in in number, date_to_use in date := sysdate )
   is

   cursor channels is
   select channel_id
   from rhnChannelPackage
   where package_id = package_id_in
   order by channel_id;

   begin
      for channel in channels loop
         -- we want to invalidate the snapshot assocated with the channel when we
         -- do this b/c we know we've added or removed or packages
         rhn_channel.update_channel ( channel.channel_id, 1, date_to_use );
      end loop;
   end update_channels_by_package;

   
   procedure update_channels_by_errata ( errata_id_in number, date_to_use in date := sysdate )
   is

   cursor channels is
   select channel_id
   from rhnChannelErrata
   where errata_id = errata_id_in
   order by channel_id;

   begin
      for channel in channels loop
         -- we won't invalidate snapshots, b/c just changing the errata associated with
         -- a channel shouldn't invalidate snapshots
         rhn_channel.update_channel ( channel.channel_id, 0, date_to_use );
      end loop;
   end update_channels_by_errata;

END rhn_channel;
/
SHOW ERRORS

--
-- Revision 1.75  2005/03/04 00:04:19  jslagle
-- bz #147617
-- Made Red Hat Desktop sort a little better.
--
-- Revision 1.74  2005/02/22 03:24:47  jslagle
-- bz #147617
-- Improve channel_priority function to order channels better.
--
-- Revision 1.73  2004/08/16 20:39:30  pjones
-- bugzilla: 129889 -- make bulk_server_basechange_from() actually work.
--
-- Revision 1.72  2004/04/14 00:09:24  pjones
-- bugzilla: 120761 -- split rhnChannelPermissions into two tables, eliminating
-- a frequent full table scan
--
-- Revision 1.71  2004/04/13 16:28:36  bretm
-- bugzilla:  119871
--
-- keep track of rhnServer.channels_changed through the pl/sql fns
--
-- Revision 1.70  2004/03/26 18:11:32  rbb
-- Bugzilla:  114057
--
-- Add a script to determine channel priority.
--
-- Revision 1.69  2004/02/17 20:16:52  pjones
-- bugzilla: none -- add cvs tags into the package as long as we're touching
-- it anyway
--
-- Revision 1.68  2004/02/17 20:05:38  pjones
-- bugzilla: 115782 -- make bulk_server_basechange_from() filter out servers
-- with arches incompatible with the target channel
--
-- Revision 1.67  2004/02/06 02:36:10  misa
-- Changed normalize_server_arch to allow for solaris arches
--
-- Revision 1.66  2003/11/13 16:58:34  cturner
-- make use of new rhn_user.check_role_implied call; pragmas broke, removed them for now since I have no idea how to fix them
--
-- Revision 1.65  2003/10/23 20:26:24  bretm
-- bugzilla:  none
--
-- note the channel label when we unsubscribe, too
--
-- Revision 1.64  2003/10/15 14:47:17  bretm
-- bugzilla:  none
--
-- add the channel label to the server history summary line when we log a channel change
--
-- Revision 1.63  2003/09/24 19:25:56  pjones
-- this wasn't the right fix, put it back
--
-- Revision 1.62  2003/09/24 17:42:19  pjones
-- bugzilla: none
--
-- limit our server base channel guess to channels with available permissions
--
-- Revision 1.61  2003/09/22 21:00:40  cturner
-- add method for easy acl check
--
-- Revision 1.60  2003/09/17 22:14:11  misa
-- bugzilla: 103639  Changes to allow me to move the base channel guess into plsql
--
-- Revision 1.59  2003/08/21 13:41:17  cturner
-- bugzilla: 99187.  properly test for satellite and proxy in bulk_guess_server_base; reorg code for better reuse
--
-- Revision 1.58  2003/07/24 16:46:22  cturner
-- bugzilla: 100723, the perm check was returning duplicates, so now it just calls the function it should have called anyway
--
-- Revision 1.57  2003/07/24 16:44:16  misa
-- bugzilla: none  A function more usable on the rhnapp side
--
-- Revision 1.56  2003/07/23 22:36:51  cturner
-- argh, max returns null even when now rows; use distinct.  how revolting
--
-- Revision 1.55  2003/07/23 22:01:31  cturner
-- oops, this one can return multiple rows; eliminate that in a lazy way
--
-- Revision 1.54  2003/07/23 21:59:19  cturner
-- rework how rhnUserChannel works; move to plsql for speed and maintenance
--
-- Revision 1.53  2003/07/21 17:49:12  pjones
-- bugzilla: none
--
-- add optional user for subscribe_server
--
-- Revision 1.52  2003/07/14 22:19:29  misa
-- bugzilla: none  Updating guess_base_channel to work more like the rhnapp server code
--
-- Revision 1.51  2003/06/26 22:09:04  pjones
-- bugzilla: none
--
-- log subscribe and unsubscribe
--
-- Revision 1.50  2003/06/05 19:31:15  pjones
-- bugzilla: 88278 -- make the cursor name smaller
--
-- Revision 1.49  2003/06/05 19:18:21  pjones
-- bugzilla: 88278
--
-- unsubscribe_server() opens the package-level cursor when it invokes itself,
-- so we're using a local copy instead.
--
-- Revision 1.48  2003/06/04 16:41:39  pjones
-- bugzilla: none
--
-- make bulk_guess_server_base() silently ignore unguessables
--
-- Revision 1.47  2003/06/04 16:27:03  pjones
-- bugzilla: 88822
--
-- eliminate the last outliers that remove things from channels without using
-- unsubscribe_server, I think.
--
-- Revision 1.46  2003/06/03 20:49:37  pjones
-- bugzilla: 88822
-- unsubscribing from rhn-satellite now clears rhnSatelliteChannelFamily
-- for the server in question
--
-- Revision 1.45  2003/06/02 20:41:45  pjones
-- bugzilla: none - fix rhnProxyInfo/rhnSatelliteInfo channel unsubscribe
-- problem.  Basicly, if you're out of the channel for any reason, you're
-- also out of rhnProxyInfo/rhnProxyInfo
--
-- Revision 1.44  2003/03/24 15:26:28  pjones
-- bugzilla: 85812
--
-- bulk_server_base_change silently ignores servers that are satellites
-- or proxies, as requested.
--
-- Revision 1.43  2003/02/26 20:28:17  pjones
-- rhn_channel.update_family_counts() in rhn_channel.entitle_customer()
-- the old codepath is:
--
-- ep ->
-- rhn_ep.entitlement_run_me() ->
-- rhn_ep.poll_customer() ->
-- rhn_channel.entitle_customer()
--
-- which doesn't change current_members, even though it may remove servers
-- from the family.
--
-- There's another bug here:  currently, we don't try to order forced
-- unsubscribes in any way; we just use
-- rhn_channel.unsubscribe_server_from_family .  If there are any child
-- channel subscriptions, this will leave them subscribed.  We really need
-- to iterate across the channels again, and subscribe any channel for which
-- there are no parent channel subscriptions.
--
-- Ugh.
--
-- Revision 1.42  2003/01/28 00:19:45  pjones
-- fix clear_subscriptions; AFAICT, this is only hit on the
-- bulk_server_base_change / bulk_server_base_guess codepaths, which puts
-- it infrequent enough that it could be our "bad count" culprit.
--
-- Revision 1.41  2003/01/14 19:51:45  pjones
-- make setting current_members on rhnChannelFamilyPermissions work when
-- a server is in more than one channel in a single family.
 07070100000400000081B400000000000000000000000167AE111400000081000000000000000000000000000000000000006500000000susemanager-schema/upgrade/satellite-schema-5.3-to-spacewalk-schema-0.6/120-rhn_config_parameter.sql  update rhn_config_parameter
	set value = '%{NPVAR}/execute_commands.log'
	where group_name = 'CommandQueue' and name = 'exelog';
   07070100000401000081B400000000000000000000000167AE111400000858000000000000000000000000000000000000006400000000susemanager-schema/upgrade/satellite-schema-5.3-to-spacewalk-schema-0.6/122-rhnServerNeededView.sql   --
-- Copyright (c) 2008 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--


-- A view that displays an uncached version of rhnServerNeededCache


CREATE OR REPLACE VIEW
rhnServerNeededView
(
    org_id,
    server_id,
    errata_id,
    package_id,
    package_name_id,
    channel_id
)
AS
SELECT DISTINCT S.org_id,
     S.id as server_id,
     ep.errata_id as errata_id,
     P.id as package_id,
     P.name_id as package_name_id,
     CP.channel_id as channel_id
FROM
    rhnPackage P
    inner join rhnPackageEVR P_EVR on P_EVR.id = P.evr_id
    inner join rhnPackageEVR SP_EVR on SP_EVR.evr < P_EVR.evr  
    inner join rhnServerPackage SP on SP.name_id = P.name_id 
               and SP.evr_id = SP_EVR.id
               AND SP.evr_id != P.evr_id
    inner join rhnServer S on SP.server_id = S.id
    inner join rhnServerPackageArchCompat SPAC on spac.server_arch_id = s.server_arch_id 
               AND p.package_arch_id = spac.package_arch_id
    inner join rhnServerChannel SC on SC.server_id = S.id 
    inner join rhnChannelPackage CP on CP.package_id = P.id 
               and SC.channel_id = CP.channel_id
    left outer join rhnErrataPackage EP on EP.package_id = P.id
                   AND EXISTS 
                   (SELECT 1 from rhnChannelErrata CE where ce.channel_id = SC.channel_id
                    AND CE.errata_id = EP.errata_id) 
    where SP_EVR.evr = (SELECT MAX(PE.evr) FROM rhnServerPackage SP2, rhnPackageEvr PE 
                       WHERE PE.id = SP2.evr_id AND SP2.server_id = SP.server_id AND 
                        SP2.name_id = SP.name_id)
/
07070100000402000081B400000000000000000000000167AE1114000005F6000000000000000000000000000000000000006300000000susemanager-schema/upgrade/satellite-schema-5.3-to-spacewalk-schema-0.6/123-rhnActionType_data.sql    --
-- Copyright (c) 2008 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--
--
--
--

update rhnActionType
set name = 'Initiate a kickstart for a virtual guest.'
where label = 'kickstart_guest.initiate';

update rhnActionType
set name = 'Shuts down a virtual domain.'
where label = 'virt.shutdown';

update rhnActionType
set name = 'Starts up a virtual domain.'
where label = 'virt.start';

update rhnActionType
set name = 'Suspends a virtual domain.'
where label = 'virt.suspend';

update rhnActionType
set name = 'Resumes a virtual domain.'
where label = 'virt.resume';

update rhnActionType
set name = 'Reboots a virtual domain.'
where label = 'virt.reboot';

update rhnActionType
set name = 'Destroys a virtual domain.'
where label = 'virt.destroy';

update rhnActionType
set name = 'Sets the maximum memory usage for a virtual domain.'
where label = 'virt.setMemory';

update rhnActionType
set name = 'Sets the Vcpu usage for a virtual domain.'
where label = 'virt.setVCPUs';
  07070100000403000081B400000000000000000000000167AE111400000449000000000000000000000000000000000000006600000000susemanager-schema/upgrade/satellite-schema-5.3-to-spacewalk-schema-0.6/124-rhn_probe_param_value.sql DECLARE
        type result_type is record (
                probe_id NUMBER,
                command_id NUMBER
        );
        one_row result_type;
BEGIN
FOR one_row IN (
        select probe_id, command_id from rhn_probe_param_value
                where
                        command_id in (25, 26, 27, 28, 29, 30, 31, 99, 105, 106, 107, 109, 117, 118, 123, 226, 228, 230, 249, 274, 304)
                group by probe_id, command_id
                having (probe_id, command_id) not in (
                        select probe_id, command_id from rhn_probe_param_value  where
                                command_id in (25, 26, 27, 28, 29, 30, 31, 99, 105, 106, 107, 109, 117, 118, 123, 226, 228, 230, 249, 274, 304)
                                AND param_name = 'sshbannerignore'
               )
        )
LOOP
        insert into rhn_probe_param_value
                (probe_id, command_id, param_name, value, last_update_user, last_update_date) values
                (one_row.probe_id, one_row.command_id, 'sshbannerignore', '0', 'upgrade', SYSDATE());
END LOOP;
END;
/

commit;
   07070100000404000081B400000000000000000000000167AE1114000003F9000000000000000000000000000000000000006000000000susemanager-schema/upgrade/satellite-schema-5.3-to-spacewalk-schema-0.6/125-rhnChecksumType.sql   create sequence rhn_checksum_id_seq;

create table
rhnChecksumType
(
	id			number
				constraint rhn_checksumtype_id_nn not null,
	label			varchar2(32)
				constraint rhn_checksumtype_label_nn not null,
	description		varchar2(64)
				constraint rhn_checksumtype_desc_nn not null,
	created			date default(sysdate)
				constraint rhn_checksumtype_creat_nn not null,
	modified		date default(sysdate)
				constraint rhn_checksumtype_mod_nn not null
)
	enable row movement
  ;

create index rhn_checksumtype_label_id_idx
	on rhnChecksumType( label, id )
	tablespace [[64k_tbs]]
  ;
alter table rhnChecksumType add constraint rhn_checksumtype_id_pk 
        primary key ( id );
alter table rhnChecksumType add constraint rhn_checksumtype_label_uq
	unique ( label );

create or replace trigger
rhn_checksumtype_mod_trig
before insert or update on rhnChecksumType
for each row
begin
	:new.modified := sysdate;
end;
/
show errors

--
--
-- Revision 1.1  2009/06/26 10:39:17  pkilambi
--  add schema to hold checksum types
--

   07070100000405000081B400000000000000000000000167AE111400000521000000000000000000000000000000000000006500000000susemanager-schema/upgrade/satellite-schema-5.3-to-spacewalk-schema-0.6/126-rhnChecksumType_data.sql  --
-- Copyright (c) 2008 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--


insert into rhnChecksumType (id, label, description) values
            (rhn_checksum_id_seq.nextval, 'md5', 'md5' );
insert into rhnChecksumType (id, label, description) values
            (rhn_checksum_id_seq.nextval, 'sha1', 'sha' );
insert into rhnChecksumType (id, label, description) values
            (rhn_checksum_id_seq.nextval, 'sha-256', 'sha256' );
insert into rhnChecksumType (id, label, description) values
            (rhn_checksum_id_seq.nextval, 'sha-384', 'sha384' );
insert into rhnChecksumType (id, label, description) values
            (rhn_checksum_id_seq.nextval, 'sha-512', 'sha512' );

commit;

--
--
-- Revision 1.1  2009/06/26 11:00:17  pkilambi
--

   07070100000406000081B400000000000000000000000167AE1114000004CB000000000000000000000000000000000000006600000000susemanager-schema/upgrade/satellite-schema-5.3-to-spacewalk-schema-0.6/150-rhnConfigInfo_selinux.sql --
-- Add in a column for selinux context
--

ALTER TABLE rhnConfigInfo
  ADD selinux_ctx VARCHAR(64);

DROP INDEX RHN_CONFINFO_UGF_UQ;

CREATE UNIQUE INDEX rhn_confinfo_ugf_uq
    ON rhnConfigInfo( username, groupname, filemode, selinux_ctx )
    tablespace [[4m_tbs]]
  ;

CREATE OR REPLACE FUNCTION
lookup_config_info (
    username_in     IN VARCHAR2,
    groupname_in    IN VARCHAR2,
    filemode_in     IN VARCHAR2,
    selinux_ctx_in  IN VARCHAR2
) RETURN NUMBER
DETERMINISTIC
IS
    PRAGMA AUTONOMOUS_TRANSACTION;
    v_id    NUMBER;
    CURSOR lookup_cursor IS
        SELECT id
          FROM rhnConfigInfo
         WHERE 1=1
           AND username = username_in
           AND groupname = groupname_in
           AND filemode = filemode_in
           AND nvl(selinux_ctx, ' ') = nvl(selinux_ctx_in, ' ');
BEGIN
    FOR r IN lookup_cursor LOOP
        RETURN r.id;
    END LOOP;
    -- If we got here, we don't have the id
    SELECT rhn_confinfo_id_seq.nextval
      INTO v_id
      FROM dual;
    INSERT INTO rhnConfigInfo (id, username, groupname, filemode, selinux_ctx)
    VALUES (v_id, username_in, groupname_in, filemode_in, selinux_ctx_in);
    COMMIT;
    RETURN v_id;
END lookup_config_info;
/
show errors
 07070100000407000081B400000000000000000000000167AE111400000623000000000000000000000000000000000000006900000000susemanager-schema/upgrade/satellite-schema-5.3-to-spacewalk-schema-0.6/190-rhnSharedChannelTreeView.sql  --
-- Copyright (c) 2008 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--

CREATE OR REPLACE VIEW RHNSHAREDCHANNELTREEVIEW
(
  ORG_ID,
  ID,
  DEPTH,
  NAME,
  PADDED_NAME,
  CHANNEL_ARCH_ID,
  LAST_MODIFIED,
  LABEL,
  PARENT_OR_SELF_LABEL,
  PARENT_OR_SELF_ID,
  END_OF_LIFE
)
AS
SELECT * FROM (
  SELECT
    C.ORG_TRUST_ID AS ORG_ID,
    C.ID,
    1 AS DEPTH,
    C.NAME,
    '  '||C.NAME AS PADDED_NAME,
    C.CHANNEL_ARCH_ID,
    C.LAST_MODIFIED,
    C.LABEL,
    C.LABEL AS PARENT_OR_SELF_LABEL,
    C.ID AS PARENT_OR_SELF_ID,
    C.END_OF_LIFE
  FROM RHNSHAREDCHANNELVIEW C
  WHERE C.PARENT_CHANNEL IS NULL
  UNION
  SELECT
    C.ORG_TRUST_ID AS ORG_ID,
    C.ID,
    2 AS DEPTH,
    c.name,
    ''||C.NAME AS PADDED_NAME,
    C.CHANNEL_ARCH_ID,
    C.LAST_MODIFIED,
    C.LABEL,
    PC.LABEL AS PARENT_OR_SELF_LABEL,
    PC.ID AS PARENT_OR_SELF_ID,
    C.END_OF_LIFE
  FROM RHNCHANNEL PC,
       RHNSHAREDCHANNELVIEW C
  WHERE C.PARENT_CHANNEL = PC.ID
) ORDER BY PARENT_OR_SELF_LABEL, PARENT_OR_SELF_ID;

 07070100000408000081B400000000000000000000000167AE1114000001AA000000000000000000000000000000000000005B00000000susemanager-schema/upgrade/satellite-schema-5.3-to-spacewalk-schema-0.6/191-rhnChannel.sql    -- Add a checksum_type_id column, and fk to rhnChecksumType
ALTER TABLE rhnChannel
  ADD checksum_type_id number
CONSTRAINT rhn_channel_checksum_fk
    REFERENCES rhnChecksumType(id);

-- Update any existing channels that are not set
UPDATE rhnChannel SET 
  checksum_type_id = (select id 
                        from rhnChecksumType 
                       where LABEL = 'sha1')
WHERE checksum_type_id is null;

show errors
  07070100000409000081B400000000000000000000000167AE111400000507000000000000000000000000000000000000006500000000susemanager-schema/upgrade/satellite-schema-5.3-to-spacewalk-schema-0.6/191-rhnContentSourceType.sql  --
-- Copyright (c) 2008 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--

create table
rhnContentSourceType
(
        id              number NOT NULL
                        constraint rhn_cst_id_pk primary key,
        label           varchar2(32) NOT NULL
                        constraint rhn_cst_label_uq unique,
        created         date default(sysdate) NOT NULL,
        modified        date default(sysdate) NOT NULL
)
        enable row movement
  ;



create sequence rhn_content_source_type_id_seq start with 500;

create index rhn_ccst_id_l_idx
	on rhnContentSourceType(id,label)
	tablespace [[64k_tbs]]
  ;


insert into rhnContentSourceType (id, label) values
(rhn_content_source_type_id_seq.nextval, 'yum');

 0707010000040A000081B400000000000000000000000167AE1114000002E8000000000000000000000000000000000000006B00000000susemanager-schema/upgrade/satellite-schema-5.3-to-spacewalk-schema-0.6/191-upgrade_kickstart_profiles.sql    --
-- Copyright (c) 2008 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--

INSERT INTO rhnTaskQueue (org_id, task_name, task_data)
VALUES (1, 'upgrade_satellite_kickstart_profiles', 0);
0707010000040B000081B400000000000000000000000167AE111400000621000000000000000000000000000000000000006800000000susemanager-schema/upgrade/satellite-schema-5.3-to-spacewalk-schema-0.6/192-rhnChannelContentSource.sql   --
-- Copyright (c) 2008 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--


create table
rhnChannelContentSource
(
        id              number NOT NULL
                        constraint rhn_ccs_id_pk primary key,
        channel_id      number NOT NULL
                        constraint rhn_ccs_c_fk
                                references rhnChannel(id) on delete cascade,
        type_id         number NOT NULL
                        constraint rhn_ccs_type_fk
                                references rhnContentSourceType(id),
        source_url      varchar2(512) NOT NULL,
        label           varchar2(64) NOT NULL,
        last_synced     date,
        created         date default(sysdate) NOT NULL,
        modified        date default(sysdate) NOT NULL
)
        enable row movement
  ;



create sequence rhn_chan_content_src_id_seq start with 500;


create unique index rhn_ccs_uq
	on rhnChannelContentSource(channel_id, type_id, source_url)
	tablespace [[64k_tbs]]
  ;

show errors

   0707010000040C000081B400000000000000000000000167AE1114000000BE000000000000000000000000000000000000005F00000000susemanager-schema/upgrade/satellite-schema-5.3-to-spacewalk-schema-0.6/193-rhn-PackageKey.sql    insert into rhnPackageKey (id, key_id, key_type_id, provider_id) values 
   (rhn_pkey_id_seq.nextval, '1dc5c758d22e77f2', lookup_package_key_type('gpg'), lookup_package_provider('Fedora'));
  0707010000040D000081B400000000000000000000000167AE11140000057C000000000000000000000000000000000000006F00000000susemanager-schema/upgrade/satellite-schema-5.3-to-spacewalk-schema-0.6/998-postgresql-compatability-procs.sql    ---
--- Add stored procedures for PostgreSQL compatability.
---

create or replace function evr_t_as_vre( a evr_t )
  return varchar2
is
begin
        return a.as_vre;
end;
/
show errors

create or replace function evr_t_as_vre_simple( a evr_t )
  return VARCHAR2
is
begin
    return a.as_vre_simple;
end;
/
show errors

create or replace function sequence_currval( seq_name varchar2 ) return number as
       ret number;
begin
       execute immediate 'select '|| seq_name || '.currval from dual'
               into ret;
       return ret;
end;
/
show errors

create or replace function sequence_nextval( seq_name varchar2 ) return number as
       ret number;
begin
       execute immediate 'select '|| seq_name || '.nextval from dual'
               into ret;
       return ret;
end;
/
show errors


CREATE OR REPLACE VIEW
rhnServerOutdatedPackages
(
    server_id,
    package_name_id,
    package_evr_id,    
    package_nvre,
    errata_id,
    errata_advisory
)
AS
SELECT DISTINCT SNPC.server_id,
       P.name_id, 
       P.evr_id, 
       PN.name || '-' || evr_t_as_vre_simple( PE.evr ),
       E.id,
       E.advisory
  FROM rhnPackageName PN,
       rhnPackageEVR PE,
       rhnPackage P,
       rhnServerNeededPackageCache SNPC
         left outer join
        rhnErrata E
          on SNPC.errata_id = E.id
 WHERE SNPC.package_id = P.id
   AND P.name_id = PN.id
   AND P.evr_id = PE.id;



0707010000040E000081B400000000000000000000000167AE11140003F81E000000000000000000000000000000000000005700000000susemanager-schema/upgrade/satellite-schema-5.3-to-spacewalk-schema-0.6/999-pgport.sql    --
-- Postgres compatability script.
-- Replaces named NOT NULL constraints with anonymous constraits via keyword.
-- Required so that upgraded schema matches fresh install.
--

--
-- RHNPRODUCTNAME
--
ALTER TABLE RHNPRODUCTNAME DROP CONSTRAINT PRODUCT_NAME_CREATED_NN;
ALTER TABLE RHNPRODUCTNAME MODIFY CREATED NOT NULL;

--
-- RHNPRODUCTNAME
--
ALTER TABLE RHNPRODUCTNAME DROP CONSTRAINT PRODUCT_NAME_MODIFIED_NN;
ALTER TABLE RHNPRODUCTNAME MODIFY MODIFIED NOT NULL;

--
-- PXTSESSIONS
--
ALTER TABLE PXTSESSIONS DROP CONSTRAINT PXTSESSIONS_EXPIRES_NN;
ALTER TABLE PXTSESSIONS MODIFY EXPIRES NOT NULL;

--
-- PXTSESSIONS
--
ALTER TABLE PXTSESSIONS DROP CONSTRAINT PXTSESSIONS_VALUE_NN;
ALTER TABLE PXTSESSIONS MODIFY VALUE NOT NULL;

--
-- RHNACTIONCONFIGCHANNEL
--
ALTER TABLE RHNACTIONCONFIGCHANNEL DROP CONSTRAINT RHN_ACTIONCC_AID_NN;
ALTER TABLE RHNACTIONCONFIGCHANNEL MODIFY ACTION_ID NOT NULL;

--
-- RHNACTIONCONFIGCHANNEL
--
ALTER TABLE RHNACTIONCONFIGCHANNEL DROP CONSTRAINT RHN_ACTIONCC_CCID_NN;
ALTER TABLE RHNACTIONCONFIGCHANNEL MODIFY CONFIG_CHANNEL_ID NOT NULL;

--
-- RHNACTIONCONFIGCHANNEL
--
ALTER TABLE RHNACTIONCONFIGCHANNEL DROP CONSTRAINT RHN_ACTIONCC_CREAT_NN;
ALTER TABLE RHNACTIONCONFIGCHANNEL MODIFY CREATED NOT NULL;

--
-- RHNACTIONCONFIGCHANNEL
--
ALTER TABLE RHNACTIONCONFIGCHANNEL DROP CONSTRAINT RHN_ACTIONCC_MOD_NN;
ALTER TABLE RHNACTIONCONFIGCHANNEL MODIFY MODIFIED NOT NULL;

--
-- RHNACTIONCONFIGCHANNEL
--
ALTER TABLE RHNACTIONCONFIGCHANNEL DROP CONSTRAINT RHN_ACTIONCC_SID_NN;
ALTER TABLE RHNACTIONCONFIGCHANNEL MODIFY SERVER_ID NOT NULL;

--
-- RHNACTIONCONFIGDATE
--
ALTER TABLE RHNACTIONCONFIGDATE DROP CONSTRAINT RHN_ACTIONCD_AID_NN;
ALTER TABLE RHNACTIONCONFIGDATE MODIFY ACTION_ID NOT NULL;

--
-- RHNACTIONCONFIGDATE
--
ALTER TABLE RHNACTIONCONFIGDATE DROP CONSTRAINT RHN_ACTIONCD_CREAT_NN;
ALTER TABLE RHNACTIONCONFIGDATE MODIFY CREATED NOT NULL;

--
-- RHNACTIONCONFIGDATEFILE
--
ALTER TABLE RHNACTIONCONFIGDATEFILE DROP CONSTRAINT RHN_ACTIONCD_FILE_AID_NN;
ALTER TABLE RHNACTIONCONFIGDATEFILE MODIFY ACTION_ID NOT NULL;

--
-- RHNACTIONCONFIGDATEFILE
--
ALTER TABLE RHNACTIONCONFIGDATEFILE DROP CONSTRAINT RHN_ACTIONCD_FILE_CREAT_NN;
ALTER TABLE RHNACTIONCONFIGDATEFILE MODIFY CREATED NOT NULL;

--
-- RHNACTIONCONFIGDATEFILE
--
ALTER TABLE RHNACTIONCONFIGDATEFILE DROP CONSTRAINT RHN_ACTIONCD_FILE_FN_NN;
ALTER TABLE RHNACTIONCONFIGDATEFILE MODIFY FILE_NAME NOT NULL;

--
-- RHNACTIONCONFIGDATEFILE
--
ALTER TABLE RHNACTIONCONFIGDATEFILE DROP CONSTRAINT RHN_ACTIONCD_FILE_FT_NN;
ALTER TABLE RHNACTIONCONFIGDATEFILE MODIFY FILE_TYPE NOT NULL;

--
-- RHNACTIONCONFIGDATE
--
ALTER TABLE RHNACTIONCONFIGDATE DROP CONSTRAINT RHN_ACTIONCD_FILE_IC_NN;
ALTER TABLE RHNACTIONCONFIGDATE MODIFY IMPORT_CONTENTS NOT NULL;

--
-- RHNACTIONCONFIGDATEFILE
--
ALTER TABLE RHNACTIONCONFIGDATEFILE DROP CONSTRAINT RHN_ACTIONCD_FILE_MOD_NN;
ALTER TABLE RHNACTIONCONFIGDATEFILE MODIFY MODIFIED NOT NULL;

--
-- RHNACTIONCONFIGDATE
--
ALTER TABLE RHNACTIONCONFIGDATE DROP CONSTRAINT RHN_ACTIONCD_MOD_NN;
ALTER TABLE RHNACTIONCONFIGDATE MODIFY MODIFIED NOT NULL;

--
-- RHNACTIONCONFIGDATE
--
ALTER TABLE RHNACTIONCONFIGDATE DROP CONSTRAINT RHN_ACTIONCD_START_NN;
ALTER TABLE RHNACTIONCONFIGDATE MODIFY START_DATE NOT NULL;

--
-- RHNACTIONCONFIGREVISIONRESULT
--
ALTER TABLE RHNACTIONCONFIGREVISIONRESULT DROP CONSTRAINT RHN_ACTIONCFR_ACRID_NN;
ALTER TABLE RHNACTIONCONFIGREVISIONRESULT MODIFY ACTION_CONFIG_REVISION_ID NOT NULL;

--
-- RHNACTIONCONFIGREVISIONRESULT
--
ALTER TABLE RHNACTIONCONFIGREVISIONRESULT DROP CONSTRAINT RHN_ACTIONCFR_CREAT_NN;
ALTER TABLE RHNACTIONCONFIGREVISIONRESULT MODIFY CREATED NOT NULL;

--
-- RHNACTIONCONFIGREVISIONRESULT
--
ALTER TABLE RHNACTIONCONFIGREVISIONRESULT DROP CONSTRAINT RHN_ACTIONCFR_MOD_NN;
ALTER TABLE RHNACTIONCONFIGREVISIONRESULT MODIFY MODIFIED NOT NULL;

--
-- RHNACTIONCONFIGFILENAME
--
ALTER TABLE RHNACTIONCONFIGFILENAME DROP CONSTRAINT RHN_ACTIONCF_CREAT_NN;
ALTER TABLE RHNACTIONCONFIGFILENAME MODIFY CREATED NOT NULL;

--
-- RHNACTIONCONFIGFILENAME
--
ALTER TABLE RHNACTIONCONFIGFILENAME DROP CONSTRAINT RHN_ACTIONCF_MOD_NN;
ALTER TABLE RHNACTIONCONFIGFILENAME MODIFY MODIFIED NOT NULL;

--
-- RHNACTIONCONFIGFILENAME
--
ALTER TABLE RHNACTIONCONFIGFILENAME DROP CONSTRAINT RHN_ACTIONCF_NAME_AID_NN;
ALTER TABLE RHNACTIONCONFIGFILENAME MODIFY ACTION_ID NOT NULL;

--
-- RHNACTIONCONFIGFILENAME
--
ALTER TABLE RHNACTIONCONFIGFILENAME DROP CONSTRAINT RHN_ACTIONCF_NAME_CFNID_NN;
ALTER TABLE RHNACTIONCONFIGFILENAME MODIFY CONFIG_FILE_NAME_ID NOT NULL;

--
-- RHNACTIONCONFIGFILENAME
--
ALTER TABLE RHNACTIONCONFIGFILENAME DROP CONSTRAINT RHN_ACTIONCF_NAME_SID_NN;
ALTER TABLE RHNACTIONCONFIGFILENAME MODIFY SERVER_ID NOT NULL;

--
-- RHNACTIONCONFIGREVISION
--
ALTER TABLE RHNACTIONCONFIGREVISION DROP CONSTRAINT RHN_ACTIONCR_AID_NN;
ALTER TABLE RHNACTIONCONFIGREVISION MODIFY ACTION_ID NOT NULL;

--
-- RHNACTIONCONFIGREVISION
--
ALTER TABLE RHNACTIONCONFIGREVISION DROP CONSTRAINT RHN_ACTIONCR_CREAT_NN;
ALTER TABLE RHNACTIONCONFIGREVISION MODIFY CREATED NOT NULL;

--
-- RHNACTIONCONFIGREVISION
--
ALTER TABLE RHNACTIONCONFIGREVISION DROP CONSTRAINT RHN_ACTIONCR_CRID_NN;
ALTER TABLE RHNACTIONCONFIGREVISION MODIFY CONFIG_REVISION_ID NOT NULL;

--
-- RHNACTIONCONFIGREVISION
--
ALTER TABLE RHNACTIONCONFIGREVISION DROP CONSTRAINT RHN_ACTIONCR_ID_NN;
ALTER TABLE RHNACTIONCONFIGREVISION MODIFY ID NOT NULL;

--
-- RHNACTIONCONFIGREVISION
--
ALTER TABLE RHNACTIONCONFIGREVISION DROP CONSTRAINT RHN_ACTIONCR_MOD_NN;
ALTER TABLE RHNACTIONCONFIGREVISION MODIFY MODIFIED NOT NULL;

--
-- RHNACTIONCONFIGREVISION
--
ALTER TABLE RHNACTIONCONFIGREVISION DROP CONSTRAINT RHN_ACTIONCR_SID_NN;
ALTER TABLE RHNACTIONCONFIGREVISION MODIFY SERVER_ID NOT NULL;

--
-- RHNACTIONDAEMONCONFIG
--
ALTER TABLE RHNACTIONDAEMONCONFIG DROP CONSTRAINT RHN_ACTIONDC_AID_NN;
ALTER TABLE RHNACTIONDAEMONCONFIG MODIFY ACTION_ID NOT NULL;

--
-- RHNACTIONDAEMONCONFIG
--
ALTER TABLE RHNACTIONDAEMONCONFIG DROP CONSTRAINT RHN_ACTIONDC_CREAT_NN;
ALTER TABLE RHNACTIONDAEMONCONFIG MODIFY CREATED NOT NULL;

--
-- RHNACTIONDAEMONCONFIG
--
ALTER TABLE RHNACTIONDAEMONCONFIG DROP CONSTRAINT RHN_ACTIONDC_INT_NN;
ALTER TABLE RHNACTIONDAEMONCONFIG MODIFY INTERVAL NOT NULL;

--
-- RHNACTIONDAEMONCONFIG
--
ALTER TABLE RHNACTIONDAEMONCONFIG DROP CONSTRAINT RHN_ACTIONDC_MOD_NN;
ALTER TABLE RHNACTIONDAEMONCONFIG MODIFY MODIFIED NOT NULL;

--
-- RHNACTIONDAEMONCONFIG
--
ALTER TABLE RHNACTIONDAEMONCONFIG DROP CONSTRAINT RHN_ACTIONDC_REST_NN;
ALTER TABLE RHNACTIONDAEMONCONFIG MODIFY RESTART NOT NULL;

--
-- RHNACTIONKICKSTARTFILELIST
--
ALTER TABLE RHNACTIONKICKSTARTFILELIST DROP CONSTRAINT RHN_ACTIONKSFL_AKSID_NN;
ALTER TABLE RHNACTIONKICKSTARTFILELIST MODIFY ACTION_KS_ID NOT NULL;

--
-- RHNACTIONKICKSTARTFILELIST
--
ALTER TABLE RHNACTIONKICKSTARTFILELIST DROP CONSTRAINT RHN_ACTIONKSFL_CREAT_NN;
ALTER TABLE RHNACTIONKICKSTARTFILELIST MODIFY CREATED NOT NULL;

--
-- RHNACTIONKICKSTARTFILELIST
--
ALTER TABLE RHNACTIONKICKSTARTFILELIST DROP CONSTRAINT RHN_ACTIONKSFL_FLID_NN;
ALTER TABLE RHNACTIONKICKSTARTFILELIST MODIFY FILE_LIST_ID NOT NULL;

--
-- RHNACTIONKICKSTARTFILELIST
--
ALTER TABLE RHNACTIONKICKSTARTFILELIST DROP CONSTRAINT RHN_ACTIONKSFL_MOD_NN;
ALTER TABLE RHNACTIONKICKSTARTFILELIST MODIFY MODIFIED NOT NULL;

--
-- RHNACTIONKICKSTART
--
ALTER TABLE RHNACTIONKICKSTART DROP CONSTRAINT RHN_ACTIONKS_AID_NN;
ALTER TABLE RHNACTIONKICKSTART MODIFY ACTION_ID NOT NULL;

--
-- RHNACTIONKICKSTART
--
ALTER TABLE RHNACTIONKICKSTART DROP CONSTRAINT RHN_ACTIONKS_CREAT_NN;
ALTER TABLE RHNACTIONKICKSTART MODIFY CREATED NOT NULL;

--
-- RHNACTIONKICKSTART
--
ALTER TABLE RHNACTIONKICKSTART DROP CONSTRAINT RHN_ACTIONKS_ID_NN;
ALTER TABLE RHNACTIONKICKSTART MODIFY ID NOT NULL;

--
-- RHNACTIONKICKSTART
--
ALTER TABLE RHNACTIONKICKSTART DROP CONSTRAINT RHN_ACTIONKS_MOD_NN;
ALTER TABLE RHNACTIONKICKSTART MODIFY MODIFIED NOT NULL;

--
-- RHNACTIONKICKSTARTGUEST
--
ALTER TABLE RHNACTIONKICKSTARTGUEST DROP CONSTRAINT RHN_ACTIONKS_XENGUEST_AID_NN;
ALTER TABLE RHNACTIONKICKSTARTGUEST MODIFY ACTION_ID NOT NULL;

--
-- RHNACTIONKICKSTARTGUEST
--
ALTER TABLE RHNACTIONKICKSTARTGUEST DROP CONSTRAINT RHN_ACTIONKS_XENGUEST_CREAT_NN;
ALTER TABLE RHNACTIONKICKSTARTGUEST MODIFY CREATED NOT NULL;

--
-- RHNACTIONKICKSTARTGUEST
--
ALTER TABLE RHNACTIONKICKSTARTGUEST DROP CONSTRAINT RHN_ACTIONKS_XENGUEST_ID_NN;
ALTER TABLE RHNACTIONKICKSTARTGUEST MODIFY ID NOT NULL;

--
-- RHNACTIONKICKSTARTGUEST
--
ALTER TABLE RHNACTIONKICKSTARTGUEST DROP CONSTRAINT RHN_ACTIONKS_XENGUEST_MOD_NN;
ALTER TABLE RHNACTIONKICKSTARTGUEST MODIFY MODIFIED NOT NULL;

--
-- RHNACTION
--
ALTER TABLE RHNACTION DROP CONSTRAINT RHN_ACTION_ARCHIVED_NN;
ALTER TABLE RHNACTION MODIFY ARCHIVED NOT NULL;

--
-- RHNACTION
--
ALTER TABLE RHNACTION DROP CONSTRAINT RHN_ACTION_AT_NN;
ALTER TABLE RHNACTION MODIFY ACTION_TYPE NOT NULL;

--
-- RHNACTION
--
ALTER TABLE RHNACTION DROP CONSTRAINT RHN_ACTION_CREATED_NN;
ALTER TABLE RHNACTION MODIFY CREATED NOT NULL;

--
-- RHNACTION
--
ALTER TABLE RHNACTION DROP CONSTRAINT RHN_ACTION_EA_NN;
ALTER TABLE RHNACTION MODIFY EARLIEST_ACTION NOT NULL;

--
-- RHNACTION
--
ALTER TABLE RHNACTION DROP CONSTRAINT RHN_ACTION_ID_NN;
ALTER TABLE RHNACTION MODIFY ID NOT NULL;

--
-- RHNACTION
--
ALTER TABLE RHNACTION DROP CONSTRAINT RHN_ACTION_MODIFIED_NN;
ALTER TABLE RHNACTION MODIFY MODIFIED NOT NULL;

--
-- RHNACTION
--
ALTER TABLE RHNACTION DROP CONSTRAINT RHN_ACTION_OID_NN;
ALTER TABLE RHNACTION MODIFY ORG_ID NOT NULL;

--
-- RHNACTIONSTATUS
--
ALTER TABLE RHNACTIONSTATUS DROP CONSTRAINT RHN_ACTION_STATUS_CREATED_NN;
ALTER TABLE RHNACTIONSTATUS MODIFY CREATED NOT NULL;

--
-- RHNACTIONSTATUS
--
ALTER TABLE RHNACTIONSTATUS DROP CONSTRAINT RHN_ACTION_STATUS_ID_NN;
ALTER TABLE RHNACTIONSTATUS MODIFY ID NOT NULL;

--
-- RHNACTIONSTATUS
--
ALTER TABLE RHNACTIONSTATUS DROP CONSTRAINT RHN_ACTION_STATUS_MODIFIED_NN;
ALTER TABLE RHNACTIONSTATUS MODIFY MODIFIED NOT NULL;

--
-- RHNACTIONTYPE
--
ALTER TABLE RHNACTIONTYPE DROP CONSTRAINT RHN_ACTION_TYPE_ID_NN;
ALTER TABLE RHNACTIONTYPE MODIFY ID NOT NULL;

--
-- RHNACTIONTYPE
--
ALTER TABLE RHNACTIONTYPE DROP CONSTRAINT RHN_ACTION_TYPE_LABEL_NN;
ALTER TABLE RHNACTIONTYPE MODIFY LABEL NOT NULL;

--
-- RHNACTIONTYPE
--
ALTER TABLE RHNACTIONTYPE DROP CONSTRAINT RHN_ACTION_TYPE_NAME_NN;
ALTER TABLE RHNACTIONTYPE MODIFY NAME NOT NULL;

--
-- RHNACTIONTYPE
--
ALTER TABLE RHNACTIONTYPE DROP CONSTRAINT RHN_ACTION_TYPE_TRIGSNAP_NN;
ALTER TABLE RHNACTIONTYPE MODIFY TRIGGER_SNAPSHOT NOT NULL;

--
-- RHNACTIONTYPE
--
ALTER TABLE RHNACTIONTYPE DROP CONSTRAINT RHN_ACTION_TYPE_UNLCK_NN;
ALTER TABLE RHNACTIONTYPE MODIFY UNLOCKED_ONLY NOT NULL;

--
-- RHNACTION
--
ALTER TABLE RHNACTION DROP CONSTRAINT RHN_ACTION_VERSION_NN;
ALTER TABLE RHNACTION MODIFY VERSION NOT NULL;

--
-- RHNACTIONSCRIPT
--
ALTER TABLE RHNACTIONSCRIPT DROP CONSTRAINT RHN_ACTSCRIPT_AID_NN;
ALTER TABLE RHNACTIONSCRIPT MODIFY ACTION_ID NOT NULL;

--
-- RHNACTIONSCRIPT
--
ALTER TABLE RHNACTIONSCRIPT DROP CONSTRAINT RHN_ACTSCRIPT_CREAT_NN;
ALTER TABLE RHNACTIONSCRIPT MODIFY CREATED NOT NULL;

--
-- RHNACTIONSCRIPT
--
ALTER TABLE RHNACTIONSCRIPT DROP CONSTRAINT RHN_ACTSCRIPT_GROUP_NN;
ALTER TABLE RHNACTIONSCRIPT MODIFY GROUPNAME NOT NULL;

--
-- RHNACTIONSCRIPT
--
ALTER TABLE RHNACTIONSCRIPT DROP CONSTRAINT RHN_ACTSCRIPT_ID_NN;
ALTER TABLE RHNACTIONSCRIPT MODIFY ID NOT NULL;

--
-- RHNACTIONSCRIPT
--
ALTER TABLE RHNACTIONSCRIPT DROP CONSTRAINT RHN_ACTSCRIPT_MOD_NN;
ALTER TABLE RHNACTIONSCRIPT MODIFY MODIFIED NOT NULL;

--
-- RHNACTIONSCRIPT
--
ALTER TABLE RHNACTIONSCRIPT DROP CONSTRAINT RHN_ACTSCRIPT_USER_NN;
ALTER TABLE RHNACTIONSCRIPT MODIFY USERNAME NOT NULL;

--
-- RHNACTIONERRATAUPDATE
--
ALTER TABLE RHNACTIONERRATAUPDATE DROP CONSTRAINT RHN_ACT_EU_ACT_NN;
ALTER TABLE RHNACTIONERRATAUPDATE MODIFY ACTION_ID NOT NULL;

--
-- RHNACTIONERRATAUPDATE
--
ALTER TABLE RHNACTIONERRATAUPDATE DROP CONSTRAINT RHN_ACT_EU_ERR_NN;
ALTER TABLE RHNACTIONERRATAUPDATE MODIFY ERRATA_ID NOT NULL;

--
-- RHNACTIVATIONKEY
--
ALTER TABLE RHNACTIVATIONKEY DROP CONSTRAINT RHN_ACT_KEY_CREATED_NN;
ALTER TABLE RHNACTIVATIONKEY MODIFY CREATED NOT NULL;

--
-- RHNACTIVATIONKEY
--
ALTER TABLE RHNACTIVATIONKEY DROP CONSTRAINT RHN_ACT_KEY_MODIFIED_NN;
ALTER TABLE RHNACTIVATIONKEY MODIFY MODIFIED NOT NULL;

--
-- RHNACTIVATIONKEY
--
ALTER TABLE RHNACTIVATIONKEY DROP CONSTRAINT RHN_ACT_KEY_REG_TID_NN;
ALTER TABLE RHNACTIVATIONKEY MODIFY REG_TOKEN_ID NOT NULL;

--
-- RHNACTIVATIONKEY
--
ALTER TABLE RHNACTIVATIONKEY DROP CONSTRAINT RHN_ACT_KEY_TOKEN_NN;
ALTER TABLE RHNACTIVATIONKEY MODIFY TOKEN NOT NULL;

--
-- RHNACTIONPACKAGEDELTA
--
ALTER TABLE RHNACTIONPACKAGEDELTA DROP CONSTRAINT RHN_ACT_PD_AID_NN;
ALTER TABLE RHNACTIONPACKAGEDELTA MODIFY ACTION_ID NOT NULL;

--
-- RHNACTIONPACKAGEDELTA
--
ALTER TABLE RHNACTIONPACKAGEDELTA DROP CONSTRAINT RHN_ACT_PD_PDID_NN;
ALTER TABLE RHNACTIONPACKAGEDELTA MODIFY PACKAGE_DELTA_ID NOT NULL;

--
-- RHNACTIONPACKAGEORDER
--
ALTER TABLE RHNACTIONPACKAGEORDER DROP CONSTRAINT RHN_ACT_PKG_APID_NN;
ALTER TABLE RHNACTIONPACKAGEORDER MODIFY ACTION_PACKAGE_ID NOT NULL;

--
-- RHNACTIONPACKAGEORDER
--
ALTER TABLE RHNACTIONPACKAGEORDER DROP CONSTRAINT RHN_ACT_PKG_ORDER_NN;
ALTER TABLE RHNACTIONPACKAGEORDER MODIFY PACKAGE_ORDER NOT NULL;

--
-- RHNACTIONPACKAGE
--
ALTER TABLE RHNACTIONPACKAGE DROP CONSTRAINT RHN_ACT_P_ACT_NN;
ALTER TABLE RHNACTIONPACKAGE MODIFY ACTION_ID NOT NULL;

--
-- RHNACTIONPACKAGEANSWERFILE
--
ALTER TABLE RHNACTIONPACKAGEANSWERFILE DROP CONSTRAINT RHN_ACT_P_AF_APID_NN;
ALTER TABLE RHNACTIONPACKAGEANSWERFILE MODIFY ACTION_PACKAGE_ID NOT NULL;

--
-- RHNACTIONPACKAGEANSWERFILE
--
ALTER TABLE RHNACTIONPACKAGEANSWERFILE DROP CONSTRAINT RHN_ACT_P_AF_CREAT_NN;
ALTER TABLE RHNACTIONPACKAGEANSWERFILE MODIFY CREATED NOT NULL;

--
-- RHNACTIONPACKAGEANSWERFILE
--
ALTER TABLE RHNACTIONPACKAGEANSWERFILE DROP CONSTRAINT RHN_ACT_P_AF_MOD_NN;
ALTER TABLE RHNACTIONPACKAGEANSWERFILE MODIFY MODIFIED NOT NULL;

--
-- RHNACTIONPACKAGE
--
ALTER TABLE RHNACTIONPACKAGE DROP CONSTRAINT RHN_ACT_P_ID_NN;
ALTER TABLE RHNACTIONPACKAGE MODIFY ID NOT NULL;

--
-- RHNACTIONPACKAGE
--
ALTER TABLE RHNACTIONPACKAGE DROP CONSTRAINT RHN_ACT_P_NAME_NN;
ALTER TABLE RHNACTIONPACKAGE MODIFY NAME_ID NOT NULL;

--
-- RHNACTIONPACKAGE
--
ALTER TABLE RHNACTIONPACKAGE DROP CONSTRAINT RHN_ACT_P_PARAM_NN;
ALTER TABLE RHNACTIONPACKAGE MODIFY PARAMETER NOT NULL;

--
-- RHNALLOWTRUST
--
ALTER TABLE RHNALLOWTRUST DROP CONSTRAINT RHN_ALLOW_TRUST_CHANNELFLG_NN;
ALTER TABLE RHNALLOWTRUST MODIFY CHANNEL_FLAG NOT NULL;

--
-- RHNALLOWTRUST
--
ALTER TABLE RHNALLOWTRUST DROP CONSTRAINT RHN_ALLOW_TRUST_CREATED_NN;
ALTER TABLE RHNALLOWTRUST MODIFY CREATED NOT NULL;

--
-- RHNALLOWTRUST
--
ALTER TABLE RHNALLOWTRUST DROP CONSTRAINT RHN_ALLOW_TRUST_MIGRFLG_NN;
ALTER TABLE RHNALLOWTRUST MODIFY MIGRATION_FLAG NOT NULL;

--
-- RHNALLOWTRUST
--
ALTER TABLE RHNALLOWTRUST DROP CONSTRAINT RHN_ALLOW_TRUST_MODIFIED_NN;
ALTER TABLE RHNALLOWTRUST MODIFY MODIFIED NOT NULL;

--
-- RHNALLOWTRUST
--
ALTER TABLE RHNALLOWTRUST DROP CONSTRAINT RHN_ALLOW_TRUST_OID_NN;
ALTER TABLE RHNALLOWTRUST MODIFY ORG_ID NOT NULL;

--
-- RHN_CURRENT_ALERTS
--
ALTER TABLE RHN_CURRENT_ALERTS DROP CONSTRAINT RHN_ALRTS_CUST_ID_NN;
ALTER TABLE RHN_CURRENT_ALERTS MODIFY CUSTOMER_ID NOT NULL;

--
-- RHN_CURRENT_ALERTS
--
ALTER TABLE RHN_CURRENT_ALERTS DROP CONSTRAINT RHN_ALRTS_IN_PROG_NN;
ALTER TABLE RHN_CURRENT_ALERTS MODIFY IN_PROGRESS NOT NULL;

--
-- RHN_CURRENT_ALERTS
--
ALTER TABLE RHN_CURRENT_ALERTS DROP CONSTRAINT RHN_ALRTS_RECID_NN;
ALTER TABLE RHN_CURRENT_ALERTS MODIFY RECID NOT NULL;

--
-- RHNAPPINSTALLINSTANCE
--
ALTER TABLE RHNAPPINSTALLINSTANCE DROP CONSTRAINT RHN_APPINST_INSTANCE_CREAT_NN;
ALTER TABLE RHNAPPINSTALLINSTANCE MODIFY CREATED NOT NULL;

--
-- RHNAPPINSTALLINSTANCE
--
ALTER TABLE RHNAPPINSTALLINSTANCE DROP CONSTRAINT RHN_APPINST_INSTANCE_ID_NN;
ALTER TABLE RHNAPPINSTALLINSTANCE MODIFY ID NOT NULL;

--
-- RHNAPPINSTALLINSTANCE
--
ALTER TABLE RHNAPPINSTALLINSTANCE DROP CONSTRAINT RHN_APPINST_INSTANCE_LABEL_NN;
ALTER TABLE RHNAPPINSTALLINSTANCE MODIFY LABEL NOT NULL;

--
-- RHNAPPINSTALLINSTANCE
--
ALTER TABLE RHNAPPINSTALLINSTANCE DROP CONSTRAINT RHN_APPINST_INSTANCE_MOD_NN;
ALTER TABLE RHNAPPINSTALLINSTANCE MODIFY MODIFIED NOT NULL;

--
-- RHNAPPINSTALLINSTANCE
--
ALTER TABLE RHNAPPINSTALLINSTANCE DROP CONSTRAINT RHN_APPINST_INSTANCE_NAME_NN;
ALTER TABLE RHNAPPINSTALLINSTANCE MODIFY NAME NOT NULL;

--
-- RHNAPPINSTALLINSTANCE
--
ALTER TABLE RHNAPPINSTALLINSTANCE DROP CONSTRAINT RHN_APPINST_INSTANCE_VERS_NN;
ALTER TABLE RHNAPPINSTALLINSTANCE MODIFY VERSION NOT NULL;

--
-- RHNAPPINSTALLSESSIONDATA
--
ALTER TABLE RHNAPPINSTALLSESSIONDATA DROP CONSTRAINT RHN_APPINST_SDATA_CREAT_NN;
ALTER TABLE RHNAPPINSTALLSESSIONDATA MODIFY CREATED NOT NULL;

--
-- RHNAPPINSTALLSESSIONDATA
--
ALTER TABLE RHNAPPINSTALLSESSIONDATA DROP CONSTRAINT RHN_APPINST_SDATA_ID_NN;
ALTER TABLE RHNAPPINSTALLSESSIONDATA MODIFY ID NOT NULL;

--
-- RHNAPPINSTALLSESSIONDATA
--
ALTER TABLE RHNAPPINSTALLSESSIONDATA DROP CONSTRAINT RHN_APPINST_SDATA_K_NN;
ALTER TABLE RHNAPPINSTALLSESSIONDATA MODIFY KEY NOT NULL;

--
-- RHNAPPINSTALLSESSIONDATA
--
ALTER TABLE RHNAPPINSTALLSESSIONDATA DROP CONSTRAINT RHN_APPINST_SDATA_MOD_NN;
ALTER TABLE RHNAPPINSTALLSESSIONDATA MODIFY MODIFIED NOT NULL;

--
-- RHNAPPINSTALLSESSIONDATA
--
ALTER TABLE RHNAPPINSTALLSESSIONDATA DROP CONSTRAINT RHN_APPINST_SDATA_SID_NN;
ALTER TABLE RHNAPPINSTALLSESSIONDATA MODIFY SESSION_ID NOT NULL;

--
-- RHNAPPINSTALLSESSION
--
ALTER TABLE RHNAPPINSTALLSESSION DROP CONSTRAINT RHN_APPINST_SESSION_CREAT_NN;
ALTER TABLE RHNAPPINSTALLSESSION MODIFY CREATED NOT NULL;

--
-- RHNAPPINSTALLSESSION
--
ALTER TABLE RHNAPPINSTALLSESSION DROP CONSTRAINT RHN_APPINST_SESSION_ID_NN;
ALTER TABLE RHNAPPINSTALLSESSION MODIFY ID NOT NULL;

--
-- RHNAPPINSTALLSESSION
--
ALTER TABLE RHNAPPINSTALLSESSION DROP CONSTRAINT RHN_APPINST_SESSION_IID_NN;
ALTER TABLE RHNAPPINSTALLSESSION MODIFY INSTANCE_ID NOT NULL;

--
-- RHNAPPINSTALLSESSION
--
ALTER TABLE RHNAPPINSTALLSESSION DROP CONSTRAINT RHN_APPINST_SESSION_MOD_NN;
ALTER TABLE RHNAPPINSTALLSESSION MODIFY MODIFIED NOT NULL;

--
-- RHNAPPINSTALLSESSION
--
ALTER TABLE RHNAPPINSTALLSESSION DROP CONSTRAINT RHN_APPINST_SESSION_SID_NN;
ALTER TABLE RHNAPPINSTALLSESSION MODIFY SERVER_ID NOT NULL;

--
-- RHNAPPINSTALLSESSION
--
ALTER TABLE RHNAPPINSTALLSESSION DROP CONSTRAINT RHN_APPINST_SESSION_UID_NN;
ALTER TABLE RHNAPPINSTALLSESSION MODIFY USER_ID NOT NULL;

--
-- RHNACTIONPACKAGEREMOVALFAILURE
--
ALTER TABLE RHNACTIONPACKAGEREMOVALFAILURE DROP CONSTRAINT RHN_APR_FAILURE_AID_NN;
ALTER TABLE RHNACTIONPACKAGEREMOVALFAILURE MODIFY ACTION_ID NOT NULL;

--
-- RHNACTIONPACKAGEREMOVALFAILURE
--
ALTER TABLE RHNACTIONPACKAGEREMOVALFAILURE DROP CONSTRAINT RHN_APR_FAILURE_CAPID_NN;
ALTER TABLE RHNACTIONPACKAGEREMOVALFAILURE MODIFY CAPABILITY_ID NOT NULL;

--
-- RHNACTIONPACKAGEREMOVALFAILURE
--
ALTER TABLE RHNACTIONPACKAGEREMOVALFAILURE DROP CONSTRAINT RHN_APR_FAILURE_EID_NN;
ALTER TABLE RHNACTIONPACKAGEREMOVALFAILURE MODIFY EVR_ID NOT NULL;

--
-- RHNACTIONPACKAGEREMOVALFAILURE
--
ALTER TABLE RHNACTIONPACKAGEREMOVALFAILURE DROP CONSTRAINT RHN_APR_FAILURE_FLAGS_NN;
ALTER TABLE RHNACTIONPACKAGEREMOVALFAILURE MODIFY FLAGS NOT NULL;

--
-- RHNACTIONPACKAGEREMOVALFAILURE
--
ALTER TABLE RHNACTIONPACKAGEREMOVALFAILURE DROP CONSTRAINT RHN_APR_FAILURE_NID_NN;
ALTER TABLE RHNACTIONPACKAGEREMOVALFAILURE MODIFY NAME_ID NOT NULL;

--
-- RHNACTIONPACKAGEREMOVALFAILURE
--
ALTER TABLE RHNACTIONPACKAGEREMOVALFAILURE DROP CONSTRAINT RHN_APR_FAILURE_SENSE_NN;
ALTER TABLE RHNACTIONPACKAGEREMOVALFAILURE MODIFY SENSE NOT NULL;

--
-- RHNACTIONPACKAGEREMOVALFAILURE
--
ALTER TABLE RHNACTIONPACKAGEREMOVALFAILURE DROP CONSTRAINT RHN_APR_FAILURE_SID_NN;
ALTER TABLE RHNACTIONPACKAGEREMOVALFAILURE MODIFY SERVER_ID NOT NULL;

--
-- RHNARCHTYPEACTIONS
--
ALTER TABLE RHNARCHTYPEACTIONS DROP CONSTRAINT RHN_ARCHTYPEACTS_ACTID_NN;
ALTER TABLE RHNARCHTYPEACTIONS MODIFY ACTION_TYPE_ID NOT NULL;

--
-- RHNARCHTYPEACTIONS
--
ALTER TABLE RHNARCHTYPEACTIONS DROP CONSTRAINT RHN_ARCHTYPEACTS_AS_NN;
ALTER TABLE RHNARCHTYPEACTIONS MODIFY ACTION_STYLE NOT NULL;

--
-- RHNARCHTYPEACTIONS
--
ALTER TABLE RHNARCHTYPEACTIONS DROP CONSTRAINT RHN_ARCHTYPEACTS_ATID_NN;
ALTER TABLE RHNARCHTYPEACTIONS MODIFY ARCH_TYPE_ID NOT NULL;

--
-- RHNARCHTYPEACTIONS
--
ALTER TABLE RHNARCHTYPEACTIONS DROP CONSTRAINT RHN_ARCHTYPEACTS_CREAT_NN;
ALTER TABLE RHNARCHTYPEACTIONS MODIFY CREATED NOT NULL;

--
-- RHNARCHTYPEACTIONS
--
ALTER TABLE RHNARCHTYPEACTIONS DROP CONSTRAINT RHN_ARCHTYPEACTS_MOD_NN;
ALTER TABLE RHNARCHTYPEACTIONS MODIFY MODIFIED NOT NULL;

--
-- RHNARCHTYPE
--
ALTER TABLE RHNARCHTYPE DROP CONSTRAINT RHN_ARCHTYPE_CREAT_NN;
ALTER TABLE RHNARCHTYPE MODIFY CREATED NOT NULL;

--
-- RHNARCHTYPE
--
ALTER TABLE RHNARCHTYPE DROP CONSTRAINT RHN_ARCHTYPE_ID_NN;
ALTER TABLE RHNARCHTYPE MODIFY ID NOT NULL;

--
-- RHNARCHTYPE
--
ALTER TABLE RHNARCHTYPE DROP CONSTRAINT RHN_ARCHTYPE_LABEL_NN;
ALTER TABLE RHNARCHTYPE MODIFY LABEL NOT NULL;

--
-- RHNARCHTYPE
--
ALTER TABLE RHNARCHTYPE DROP CONSTRAINT RHN_ARCHTYPE_MOD_NN;
ALTER TABLE RHNARCHTYPE MODIFY MODIFIED NOT NULL;

--
-- RHNARCHTYPE
--
ALTER TABLE RHNARCHTYPE DROP CONSTRAINT RHN_ARCHTYPE_NAME_NN;
ALTER TABLE RHNARCHTYPE MODIFY NAME NOT NULL;

--
-- RHNACTIONTRANSACTIONS
--
ALTER TABLE RHNACTIONTRANSACTIONS DROP CONSTRAINT RHN_AT_AID_NN;
ALTER TABLE RHNACTIONTRANSACTIONS MODIFY ACTION_ID NOT NULL;

--
-- RHNACTIONTRANSACTIONS
--
ALTER TABLE RHNACTIONTRANSACTIONS DROP CONSTRAINT RHN_AT_FTID_NN;
ALTER TABLE RHNACTIONTRANSACTIONS MODIFY FROM_TRANS_ID NOT NULL;

--
-- RHNACTIONTRANSACTIONS
--
ALTER TABLE RHNACTIONTRANSACTIONS DROP CONSTRAINT RHN_AT_TTID_NN;
ALTER TABLE RHNACTIONTRANSACTIONS MODIFY TO_TRANS_ID NOT NULL;

--
-- RHNACTIONVIRTVCPU
--
ALTER TABLE RHNACTIONVIRTVCPU DROP CONSTRAINT RHN_AVCPU_AID_NN;
ALTER TABLE RHNACTIONVIRTVCPU MODIFY ACTION_ID NOT NULL;

--
-- RHNACTIONVIRTVCPU
--
ALTER TABLE RHNACTIONVIRTVCPU DROP CONSTRAINT RHN_AVCPU_CREAT_NN;
ALTER TABLE RHNACTIONVIRTVCPU MODIFY CREATED NOT NULL;

--
-- RHNACTIONVIRTVCPU
--
ALTER TABLE RHNACTIONVIRTVCPU DROP CONSTRAINT RHN_AVCPU_MOD_NN;
ALTER TABLE RHNACTIONVIRTVCPU MODIFY MODIFIED NOT NULL;

--
-- RHNACTIONVIRTVCPU
--
ALTER TABLE RHNACTIONVIRTVCPU DROP CONSTRAINT RHN_AVCPU_UUID_NN;
ALTER TABLE RHNACTIONVIRTVCPU MODIFY UUID NOT NULL;

--
-- RHNACTIONVIRTVCPU
--
ALTER TABLE RHNACTIONVIRTVCPU DROP CONSTRAINT RHN_AVCPU_VCPUS_NN;
ALTER TABLE RHNACTIONVIRTVCPU MODIFY VCPU NOT NULL;

--
-- RHNACTIONVIRTDESTROY
--
ALTER TABLE RHNACTIONVIRTDESTROY DROP CONSTRAINT RHN_AVD_AID_NN;
ALTER TABLE RHNACTIONVIRTDESTROY MODIFY ACTION_ID NOT NULL;

--
-- RHNACTIONVIRTDESTROY
--
ALTER TABLE RHNACTIONVIRTDESTROY DROP CONSTRAINT RHN_AVD_CREAT_NN;
ALTER TABLE RHNACTIONVIRTDESTROY MODIFY CREATED NOT NULL;

--
-- RHNACTIONVIRTDESTROY
--
ALTER TABLE RHNACTIONVIRTDESTROY DROP CONSTRAINT RHN_AVD_MOD_NN;
ALTER TABLE RHNACTIONVIRTDESTROY MODIFY MODIFIED NOT NULL;

--
-- RHNACTIONVIRTDESTROY
--
ALTER TABLE RHNACTIONVIRTDESTROY DROP CONSTRAINT RHN_AVD_UUID_NN;
ALTER TABLE RHNACTIONVIRTDESTROY MODIFY UUID NOT NULL;

--
-- RHNACTIONVIRTREBOOT
--
ALTER TABLE RHNACTIONVIRTREBOOT DROP CONSTRAINT RHN_AVREBOOT_AID_NN;
ALTER TABLE RHNACTIONVIRTREBOOT MODIFY ACTION_ID NOT NULL;

--
-- RHNACTIONVIRTREBOOT
--
ALTER TABLE RHNACTIONVIRTREBOOT DROP CONSTRAINT RHN_AVREBOOT_CREAT_NN;
ALTER TABLE RHNACTIONVIRTREBOOT MODIFY CREATED NOT NULL;

--
-- RHNACTIONVIRTREBOOT
--
ALTER TABLE RHNACTIONVIRTREBOOT DROP CONSTRAINT RHN_AVREBOOT_MOD_NN;
ALTER TABLE RHNACTIONVIRTREBOOT MODIFY MODIFIED NOT NULL;

--
-- RHNACTIONVIRTREBOOT
--
ALTER TABLE RHNACTIONVIRTREBOOT DROP CONSTRAINT RHN_AVREBOOT_UUID_NN;
ALTER TABLE RHNACTIONVIRTREBOOT MODIFY UUID NOT NULL;

--
-- RHNACTIONVIRTREFRESH
--
ALTER TABLE RHNACTIONVIRTREFRESH DROP CONSTRAINT RHN_AVREFRESH_AID_NN;
ALTER TABLE RHNACTIONVIRTREFRESH MODIFY ACTION_ID NOT NULL;

--
-- RHNACTIONVIRTREFRESH
--
ALTER TABLE RHNACTIONVIRTREFRESH DROP CONSTRAINT RHN_AVREFRESH_CREAT_NN;
ALTER TABLE RHNACTIONVIRTREFRESH MODIFY CREATED NOT NULL;

--
-- RHNACTIONVIRTREFRESH
--
ALTER TABLE RHNACTIONVIRTREFRESH DROP CONSTRAINT RHN_AVREFRESH_MOD_NN;
ALTER TABLE RHNACTIONVIRTREFRESH MODIFY MODIFIED NOT NULL;

--
-- RHNACTIONVIRTRESUME
--
ALTER TABLE RHNACTIONVIRTRESUME DROP CONSTRAINT RHN_AVRESUME_AID_NN;
ALTER TABLE RHNACTIONVIRTRESUME MODIFY ACTION_ID NOT NULL;

--
-- RHNACTIONVIRTRESUME
--
ALTER TABLE RHNACTIONVIRTRESUME DROP CONSTRAINT RHN_AVRESUME_CREAT_NN;
ALTER TABLE RHNACTIONVIRTRESUME MODIFY CREATED NOT NULL;

--
-- RHNACTIONVIRTRESUME
--
ALTER TABLE RHNACTIONVIRTRESUME DROP CONSTRAINT RHN_AVRESUME_MOD_NN;
ALTER TABLE RHNACTIONVIRTRESUME MODIFY MODIFIED NOT NULL;

--
-- RHNACTIONVIRTRESUME
--
ALTER TABLE RHNACTIONVIRTRESUME DROP CONSTRAINT RHN_AVRESUME_UUID_NN;
ALTER TABLE RHNACTIONVIRTRESUME MODIFY UUID NOT NULL;

--
-- RHNACTIONVIRTSHUTDOWN
--
ALTER TABLE RHNACTIONVIRTSHUTDOWN DROP CONSTRAINT RHN_AVSHUTDOWN_AID_NN;
ALTER TABLE RHNACTIONVIRTSHUTDOWN MODIFY ACTION_ID NOT NULL;

--
-- RHNACTIONVIRTSHUTDOWN
--
ALTER TABLE RHNACTIONVIRTSHUTDOWN DROP CONSTRAINT RHN_AVSHUTDOWN_CREAT_NN;
ALTER TABLE RHNACTIONVIRTSHUTDOWN MODIFY CREATED NOT NULL;

--
-- RHNACTIONVIRTSHUTDOWN
--
ALTER TABLE RHNACTIONVIRTSHUTDOWN DROP CONSTRAINT RHN_AVSHUTDOWN_MOD_NN;
ALTER TABLE RHNACTIONVIRTSHUTDOWN MODIFY MODIFIED NOT NULL;

--
-- RHNACTIONVIRTSHUTDOWN
--
ALTER TABLE RHNACTIONVIRTSHUTDOWN DROP CONSTRAINT RHN_AVSHUTDOWN_UUID_NN;
ALTER TABLE RHNACTIONVIRTSHUTDOWN MODIFY UUID NOT NULL;

--
-- RHNACTIONVIRTSETMEMORY
--
ALTER TABLE RHNACTIONVIRTSETMEMORY DROP CONSTRAINT RHN_AVSM_AID_NN;
ALTER TABLE RHNACTIONVIRTSETMEMORY MODIFY ACTION_ID NOT NULL;

--
-- RHNACTIONVIRTSETMEMORY
--
ALTER TABLE RHNACTIONVIRTSETMEMORY DROP CONSTRAINT RHN_AVSM_CREAT_NN;
ALTER TABLE RHNACTIONVIRTSETMEMORY MODIFY CREATED NOT NULL;

--
-- RHNACTIONVIRTSETMEMORY
--
ALTER TABLE RHNACTIONVIRTSETMEMORY DROP CONSTRAINT RHN_AVSM_MEM_NN;
ALTER TABLE RHNACTIONVIRTSETMEMORY MODIFY MEMORY NOT NULL;

--
-- RHNACTIONVIRTSETMEMORY
--
ALTER TABLE RHNACTIONVIRTSETMEMORY DROP CONSTRAINT RHN_AVSM_MOD_NN;
ALTER TABLE RHNACTIONVIRTSETMEMORY MODIFY MODIFIED NOT NULL;

--
-- RHNACTIONVIRTSETMEMORY
--
ALTER TABLE RHNACTIONVIRTSETMEMORY DROP CONSTRAINT RHN_AVSM_UUID_NN;
ALTER TABLE RHNACTIONVIRTSETMEMORY MODIFY UUID NOT NULL;

--
-- RHNACTIONVIRTSCHEDULEPOLLER
--
ALTER TABLE RHNACTIONVIRTSCHEDULEPOLLER DROP CONSTRAINT RHN_AVSP_AID_NN;
ALTER TABLE RHNACTIONVIRTSCHEDULEPOLLER MODIFY ACTION_ID NOT NULL;

--
-- RHNACTIONVIRTSCHEDULEPOLLER
--
ALTER TABLE RHNACTIONVIRTSCHEDULEPOLLER DROP CONSTRAINT RHN_AVSP_CREAT_NN;
ALTER TABLE RHNACTIONVIRTSCHEDULEPOLLER MODIFY CREATED NOT NULL;

--
-- RHNACTIONVIRTSCHEDULEPOLLER
--
ALTER TABLE RHNACTIONVIRTSCHEDULEPOLLER DROP CONSTRAINT RHN_AVSP_MOD_NN;
ALTER TABLE RHNACTIONVIRTSCHEDULEPOLLER MODIFY MODIFIED NOT NULL;

--
-- RHNACTIONVIRTSTART
--
ALTER TABLE RHNACTIONVIRTSTART DROP CONSTRAINT RHN_AVSTART_AID_NN;
ALTER TABLE RHNACTIONVIRTSTART MODIFY ACTION_ID NOT NULL;

--
-- RHNACTIONVIRTSTART
--
ALTER TABLE RHNACTIONVIRTSTART DROP CONSTRAINT RHN_AVSTART_CREAT_NN;
ALTER TABLE RHNACTIONVIRTSTART MODIFY CREATED NOT NULL;

--
-- RHNACTIONVIRTSTART
--
ALTER TABLE RHNACTIONVIRTSTART DROP CONSTRAINT RHN_AVSTART_MOD_NN;
ALTER TABLE RHNACTIONVIRTSTART MODIFY MODIFIED NOT NULL;

--
-- RHNACTIONVIRTSTART
--
ALTER TABLE RHNACTIONVIRTSTART DROP CONSTRAINT RHN_AVSTART_UUID_NN;
ALTER TABLE RHNACTIONVIRTSTART MODIFY UUID NOT NULL;

--
-- RHNACTIONVIRTSUSPEND
--
ALTER TABLE RHNACTIONVIRTSUSPEND DROP CONSTRAINT RHN_AVSUSPEND_AID_NN;
ALTER TABLE RHNACTIONVIRTSUSPEND MODIFY ACTION_ID NOT NULL;

--
-- RHNACTIONVIRTSUSPEND
--
ALTER TABLE RHNACTIONVIRTSUSPEND DROP CONSTRAINT RHN_AVSUSPEND_CREAT_NN;
ALTER TABLE RHNACTIONVIRTSUSPEND MODIFY CREATED NOT NULL;

--
-- RHNACTIONVIRTSUSPEND
--
ALTER TABLE RHNACTIONVIRTSUSPEND DROP CONSTRAINT RHN_AVSUSPEND_MOD_NN;
ALTER TABLE RHNACTIONVIRTSUSPEND MODIFY MODIFIED NOT NULL;

--
-- RHNACTIONVIRTSUSPEND
--
ALTER TABLE RHNACTIONVIRTSUSPEND DROP CONSTRAINT RHN_AVSUSPEND_UUID_NN;
ALTER TABLE RHNACTIONVIRTSUSPEND MODIFY UUID NOT NULL;

--
-- RHNBEEHIVEPATHMAP
--
ALTER TABLE RHNBEEHIVEPATHMAP DROP CONSTRAINT RHN_BEEHIVE_PATH_MAP_BP_NN;
ALTER TABLE RHNBEEHIVEPATHMAP MODIFY BEEHIVE_PATH NOT NULL;

--
-- RHNBEEHIVEPATHMAP
--
ALTER TABLE RHNBEEHIVEPATHMAP DROP CONSTRAINT RHN_BEEHIVE_PATH_MAP_FP_NN;
ALTER TABLE RHNBEEHIVEPATHMAP MODIFY FTP_PATH NOT NULL;

--
-- RHNBEEHIVEPATHMAP
--
ALTER TABLE RHNBEEHIVEPATHMAP DROP CONSTRAINT RHN_BEEHIVE_PATH_MAP_P_NN;
ALTER TABLE RHNBEEHIVEPATHMAP MODIFY PATH NOT NULL;

--
-- RHNBLACKLISTOBSOLETES
--
ALTER TABLE RHNBLACKLISTOBSOLETES DROP CONSTRAINT RHN_BL_OBS_CREATED_NN;
ALTER TABLE RHNBLACKLISTOBSOLETES MODIFY CREATED NOT NULL;

--
-- RHNBLACKLISTOBSOLETES
--
ALTER TABLE RHNBLACKLISTOBSOLETES DROP CONSTRAINT RHN_BL_OBS_EID_NN;
ALTER TABLE RHNBLACKLISTOBSOLETES MODIFY EVR_ID NOT NULL;

--
-- RHNBLACKLISTOBSOLETES
--
ALTER TABLE RHNBLACKLISTOBSOLETES DROP CONSTRAINT RHN_BL_OBS_INID_NN;
ALTER TABLE RHNBLACKLISTOBSOLETES MODIFY IGNORE_NAME_ID NOT NULL;

--
-- RHNBLACKLISTOBSOLETES
--
ALTER TABLE RHNBLACKLISTOBSOLETES DROP CONSTRAINT RHN_BL_OBS_MODIFIED_NN;
ALTER TABLE RHNBLACKLISTOBSOLETES MODIFY MODIFIED NOT NULL;

--
-- RHNBLACKLISTOBSOLETES
--
ALTER TABLE RHNBLACKLISTOBSOLETES DROP CONSTRAINT RHN_BL_OBS_NID_NN;
ALTER TABLE RHNBLACKLISTOBSOLETES MODIFY NAME_ID NOT NULL;

--
-- RHNBLACKLISTOBSOLETES
--
ALTER TABLE RHNBLACKLISTOBSOLETES DROP CONSTRAINT RHN_BL_OBS_PAID_NN;
ALTER TABLE RHNBLACKLISTOBSOLETES MODIFY PACKAGE_ARCH_ID NOT NULL;

--
-- RHNCHANNELARCH
--
ALTER TABLE RHNCHANNELARCH DROP CONSTRAINT RHN_CARCH_ATID_NN;
ALTER TABLE RHNCHANNELARCH MODIFY ARCH_TYPE_ID NOT NULL;

--
-- RHNCHANNELARCH
--
ALTER TABLE RHNCHANNELARCH DROP CONSTRAINT RHN_CARCH_CREATED_NN;
ALTER TABLE RHNCHANNELARCH MODIFY CREATED NOT NULL;

--
-- RHNCHANNELARCH
--
ALTER TABLE RHNCHANNELARCH DROP CONSTRAINT RHN_CARCH_ID_NN;
ALTER TABLE RHNCHANNELARCH MODIFY ID NOT NULL;

--
-- RHNCHANNELARCH
--
ALTER TABLE RHNCHANNELARCH DROP CONSTRAINT RHN_CARCH_LABEL_NN;
ALTER TABLE RHNCHANNELARCH MODIFY LABEL NOT NULL;

--
-- RHNCHANNELARCH
--
ALTER TABLE RHNCHANNELARCH DROP CONSTRAINT RHN_CARCH_MODIFIED_NN;
ALTER TABLE RHNCHANNELARCH MODIFY MODIFIED NOT NULL;

--
-- RHNCHANNELARCH
--
ALTER TABLE RHNCHANNELARCH DROP CONSTRAINT RHN_CARCH_NAME_NN;
ALTER TABLE RHNCHANNELARCH MODIFY NAME NOT NULL;

--
-- RHNCUSTOMDATAKEY
--
ALTER TABLE RHNCUSTOMDATAKEY DROP CONSTRAINT RHN_CDATAKEY_CREATED_NN;
ALTER TABLE RHNCUSTOMDATAKEY MODIFY CREATED NOT NULL;

--
-- RHNCUSTOMDATAKEY
--
ALTER TABLE RHNCUSTOMDATAKEY DROP CONSTRAINT RHN_CDATAKEY_DESC_NN;
ALTER TABLE RHNCUSTOMDATAKEY MODIFY DESCRIPTION NOT NULL;

--
-- RHNCUSTOMDATAKEY
--
ALTER TABLE RHNCUSTOMDATAKEY DROP CONSTRAINT RHN_CDATAKEY_ID_NN;
ALTER TABLE RHNCUSTOMDATAKEY MODIFY ID NOT NULL;

--
-- RHNCUSTOMDATAKEY
--
ALTER TABLE RHNCUSTOMDATAKEY DROP CONSTRAINT RHN_CDATAKEY_LABEL_NN;
ALTER TABLE RHNCUSTOMDATAKEY MODIFY LABEL NOT NULL;

--
-- RHNCUSTOMDATAKEY
--
ALTER TABLE RHNCUSTOMDATAKEY DROP CONSTRAINT RHN_CDATAKEY_MODIFIED_NN;
ALTER TABLE RHNCUSTOMDATAKEY MODIFY MODIFIED NOT NULL;

--
-- RHNCUSTOMDATAKEY
--
ALTER TABLE RHNCUSTOMDATAKEY DROP CONSTRAINT RHN_CDATAKEY_OID_NN;
ALTER TABLE RHNCUSTOMDATAKEY MODIFY ORG_ID NOT NULL;

--
-- RHNCHANNELDOWNLOADS
--
ALTER TABLE RHNCHANNELDOWNLOADS DROP CONSTRAINT RHN_CD_CID_NN;
ALTER TABLE RHNCHANNELDOWNLOADS MODIFY CHANNEL_ID NOT NULL;

--
-- RHNCHANNELDOWNLOADS
--
ALTER TABLE RHNCHANNELDOWNLOADS DROP CONSTRAINT RHN_CD_CREATED_NN;
ALTER TABLE RHNCHANNELDOWNLOADS MODIFY CREATED NOT NULL;

--
-- RHNCHANNELDOWNLOADS
--
ALTER TABLE RHNCHANNELDOWNLOADS DROP CONSTRAINT RHN_CD_DID_NN;
ALTER TABLE RHNCHANNELDOWNLOADS MODIFY DOWNLOADS_ID NOT NULL;

--
-- RHNCHANNELDOWNLOADS
--
ALTER TABLE RHNCHANNELDOWNLOADS DROP CONSTRAINT RHN_CD_MODIFIED_NN;
ALTER TABLE RHNCHANNELDOWNLOADS MODIFY MODIFIED NOT NULL;

--
-- RHNCHANNELERRATA
--
ALTER TABLE RHNCHANNELERRATA DROP CONSTRAINT RHN_CE_CID_NN;
ALTER TABLE RHNCHANNELERRATA MODIFY CHANNEL_ID NOT NULL;

--
-- RHNCHANNELERRATA
--
ALTER TABLE RHNCHANNELERRATA DROP CONSTRAINT RHN_CE_CREATED_NN;
ALTER TABLE RHNCHANNELERRATA MODIFY CREATED NOT NULL;

--
-- RHNCHANNELERRATA
--
ALTER TABLE RHNCHANNELERRATA DROP CONSTRAINT RHN_CE_EID_NN;
ALTER TABLE RHNCHANNELERRATA MODIFY ERRATA_ID NOT NULL;

--
-- RHNCHANNELERRATA
--
ALTER TABLE RHNCHANNELERRATA DROP CONSTRAINT RHN_CE_MODIFIED_NN;
ALTER TABLE RHNCHANNELERRATA MODIFY MODIFIED NOT NULL;

--
-- RHNCHANNELFAMILYLICENSE
--
ALTER TABLE RHNCHANNELFAMILYLICENSE DROP CONSTRAINT RHN_CFL_CFID_NN;
ALTER TABLE RHNCHANNELFAMILYLICENSE MODIFY CHANNEL_FAMILY_ID NOT NULL;

--
-- RHNCHANNELFAMILYLICENSECONSENT
--
ALTER TABLE RHNCHANNELFAMILYLICENSECONSENT DROP CONSTRAINT RHN_CFL_CONSENT_CFID_NN;
ALTER TABLE RHNCHANNELFAMILYLICENSECONSENT MODIFY CHANNEL_FAMILY_ID NOT NULL;

--
-- RHNCHANNELFAMILYLICENSECONSENT
--
ALTER TABLE RHNCHANNELFAMILYLICENSECONSENT DROP CONSTRAINT RHN_CFL_CONSENT_CREATED_NN;
ALTER TABLE RHNCHANNELFAMILYLICENSECONSENT MODIFY CREATED NOT NULL;

--
-- RHNCHANNELFAMILYLICENSECONSENT
--
ALTER TABLE RHNCHANNELFAMILYLICENSECONSENT DROP CONSTRAINT RHN_CFL_CONSENT_MODIFIED_NN;
ALTER TABLE RHNCHANNELFAMILYLICENSECONSENT MODIFY MODIFIED NOT NULL;

--
-- RHNCHANNELFAMILYLICENSECONSENT
--
ALTER TABLE RHNCHANNELFAMILYLICENSECONSENT DROP CONSTRAINT RHN_CFL_CONSENT_SID_NN;
ALTER TABLE RHNCHANNELFAMILYLICENSECONSENT MODIFY SERVER_ID NOT NULL;

--
-- RHNCHANNELFAMILYLICENSECONSENT
--
ALTER TABLE RHNCHANNELFAMILYLICENSECONSENT DROP CONSTRAINT RHN_CFL_CONSENT_UID_NN;
ALTER TABLE RHNCHANNELFAMILYLICENSECONSENT MODIFY USER_ID NOT NULL;

--
-- RHNCHANNELFAMILYLICENSE
--
ALTER TABLE RHNCHANNELFAMILYLICENSE DROP CONSTRAINT RHN_CFL_CREATED_NN;
ALTER TABLE RHNCHANNELFAMILYLICENSE MODIFY CREATED NOT NULL;

--
-- RHNCHANNELFAMILYLICENSE
--
ALTER TABLE RHNCHANNELFAMILYLICENSE DROP CONSTRAINT RHN_CFL_LICENSE_NN;
ALTER TABLE RHNCHANNELFAMILYLICENSE MODIFY LICENSE_PATH NOT NULL;

--
-- RHNCHANNELFAMILYLICENSE
--
ALTER TABLE RHNCHANNELFAMILYLICENSE DROP CONSTRAINT RHN_CFL_MODIFIED_NN;
ALTER TABLE RHNCHANNELFAMILYLICENSE MODIFY MODIFIED NOT NULL;

--
-- RHNCONFIGFILENAME
--
ALTER TABLE RHNCONFIGFILENAME DROP CONSTRAINT RHN_CFNAME_CREATED_NN;
ALTER TABLE RHNCONFIGFILENAME MODIFY CREATED NOT NULL;

--
-- RHNCONFIGFILENAME
--
ALTER TABLE RHNCONFIGFILENAME DROP CONSTRAINT RHN_CFNAME_ID_NN;
ALTER TABLE RHNCONFIGFILENAME MODIFY ID NOT NULL;

--
-- RHNCONFIGFILENAME
--
ALTER TABLE RHNCONFIGFILENAME DROP CONSTRAINT RHN_CFNAME_MODIFIED_NN;
ALTER TABLE RHNCONFIGFILENAME MODIFY MODIFIED NOT NULL;

--
-- RHNCONFIGFILENAME
--
ALTER TABLE RHNCONFIGFILENAME DROP CONSTRAINT RHN_CFNAME_PATH_NN;
ALTER TABLE RHNCONFIGFILENAME MODIFY PATH NOT NULL;

--
-- RHNCONFIGFILESTATE
--
ALTER TABLE RHNCONFIGFILESTATE DROP CONSTRAINT RHN_CFSTATE_CREAT_NN;
ALTER TABLE RHNCONFIGFILESTATE MODIFY CREATED NOT NULL;

--
-- RHNCONFIGFILESTATE
--
ALTER TABLE RHNCONFIGFILESTATE DROP CONSTRAINT RHN_CFSTATE_ID_NN;
ALTER TABLE RHNCONFIGFILESTATE MODIFY ID NOT NULL;

--
-- RHNCONFIGFILESTATE
--
ALTER TABLE RHNCONFIGFILESTATE DROP CONSTRAINT RHN_CFSTATE_LABEL_NN;
ALTER TABLE RHNCONFIGFILESTATE MODIFY LABEL NOT NULL;

--
-- RHNCONFIGFILESTATE
--
ALTER TABLE RHNCONFIGFILESTATE DROP CONSTRAINT RHN_CFSTATE_MOD_NN;
ALTER TABLE RHNCONFIGFILESTATE MODIFY MODIFIED NOT NULL;

--
-- RHNCONFIGFILESTATE
--
ALTER TABLE RHNCONFIGFILESTATE DROP CONSTRAINT RHN_CFSTATE_NAME_NN;
ALTER TABLE RHNCONFIGFILESTATE MODIFY NAME NOT NULL;

--
-- RHNCHANNELFAMILYVIRTSUBLEVEL
--
ALTER TABLE RHNCHANNELFAMILYVIRTSUBLEVEL DROP CONSTRAINT RHN_CFVSL_CFID_NN;
ALTER TABLE RHNCHANNELFAMILYVIRTSUBLEVEL MODIFY CHANNEL_FAMILY_ID NOT NULL;

--
-- RHNCHANNELFAMILYVIRTSUBLEVEL
--
ALTER TABLE RHNCHANNELFAMILYVIRTSUBLEVEL DROP CONSTRAINT RHN_CFVSL_CREATED_NN;
ALTER TABLE RHNCHANNELFAMILYVIRTSUBLEVEL MODIFY CREATED NOT NULL;

--
-- RHNCHANNELFAMILYVIRTSUBLEVEL
--
ALTER TABLE RHNCHANNELFAMILYVIRTSUBLEVEL DROP CONSTRAINT RHN_CFVSL_MODIFIED_NN;
ALTER TABLE RHNCHANNELFAMILYVIRTSUBLEVEL MODIFY MODIFIED NOT NULL;

--
-- RHNCHANNELFAMILYVIRTSUBLEVEL
--
ALTER TABLE RHNCHANNELFAMILYVIRTSUBLEVEL DROP CONSTRAINT RHN_CFVSL_VSLID_NN;
ALTER TABLE RHNCHANNELFAMILYVIRTSUBLEVEL MODIFY VIRT_SUB_LEVEL_ID NOT NULL;

--
-- RHNCHANNELFAMILYMEMBERS
--
ALTER TABLE RHNCHANNELFAMILYMEMBERS DROP CONSTRAINT RHN_CF_FAMILY_NN;
ALTER TABLE RHNCHANNELFAMILYMEMBERS MODIFY CHANNEL_FAMILY_ID NOT NULL;

--
-- RHNCHANNELFAMILYMEMBERS
--
ALTER TABLE RHNCHANNELFAMILYMEMBERS DROP CONSTRAINT RHN_CF_MEMBERS_C_NN;
ALTER TABLE RHNCHANNELFAMILYMEMBERS MODIFY CHANNEL_ID NOT NULL;

--
-- RHNCHANNELFAMILYMEMBERS
--
ALTER TABLE RHNCHANNELFAMILYMEMBERS DROP CONSTRAINT RHN_CF_MEMBER_CRE_NN;
ALTER TABLE RHNCHANNELFAMILYMEMBERS MODIFY CREATED NOT NULL;

--
-- RHNCHANNELFAMILYMEMBERS
--
ALTER TABLE RHNCHANNELFAMILYMEMBERS DROP CONSTRAINT RHN_CF_MEMBER_MOD_NN;
ALTER TABLE RHNCHANNELFAMILYMEMBERS MODIFY MODIFIED NOT NULL;

--
-- RHNCHANNELCLONED
--
ALTER TABLE RHNCHANNELCLONED DROP CONSTRAINT RHN_CHANNELCLONE_CREATED_NN;
ALTER TABLE RHNCHANNELCLONED MODIFY CREATED NOT NULL;

--
-- RHNCHANNELCLONED
--
ALTER TABLE RHNCHANNELCLONED DROP CONSTRAINT RHN_CHANNELCLONE_FCID_NN;
ALTER TABLE RHNCHANNELCLONED MODIFY ORIGINAL_ID NOT NULL;

--
-- RHNCHANNELCLONED
--
ALTER TABLE RHNCHANNELCLONED DROP CONSTRAINT RHN_CHANNELCLONE_MODIFIED_NN;
ALTER TABLE RHNCHANNELCLONED MODIFY MODIFIED NOT NULL;

--
-- RHNCHANNELCLONED
--
ALTER TABLE RHNCHANNELCLONED DROP CONSTRAINT RHN_CHANNELCLONE_TCID_NN;
ALTER TABLE RHNCHANNELCLONED MODIFY ID NOT NULL;

--
-- RHNCHANNELCOMPS
--
ALTER TABLE RHNCHANNELCOMPS DROP CONSTRAINT RHN_CHANNELCOMPS_CID_NN;
ALTER TABLE RHNCHANNELCOMPS MODIFY CHANNEL_ID NOT NULL;

--
-- RHNCHANNELCOMPS
--
ALTER TABLE RHNCHANNELCOMPS DROP CONSTRAINT RHN_CHANNELCOMPS_CREATED_NN;
ALTER TABLE RHNCHANNELCOMPS MODIFY CREATED NOT NULL;

--
-- RHNCHANNELCOMPS
--
ALTER TABLE RHNCHANNELCOMPS DROP CONSTRAINT RHN_CHANNELCOMPS_ID_NN;
ALTER TABLE RHNCHANNELCOMPS MODIFY ID NOT NULL;

--
-- RHNCHANNELCOMPS
--
ALTER TABLE RHNCHANNELCOMPS DROP CONSTRAINT RHN_CHANNELCOMPS_LASTMOD_NN;
ALTER TABLE RHNCHANNELCOMPS MODIFY LAST_MODIFIED NOT NULL;

--
-- RHNCHANNELCOMPS
--
ALTER TABLE RHNCHANNELCOMPS DROP CONSTRAINT RHN_CHANNELCOMPS_MODIFIED_NN;
ALTER TABLE RHNCHANNELCOMPS MODIFY MODIFIED NOT NULL;

--
-- RHNCHANNELCOMPS
--
ALTER TABLE RHNCHANNELCOMPS DROP CONSTRAINT RHN_CHANNELCOMPS_RFN_NN;
ALTER TABLE RHNCHANNELCOMPS MODIFY RELATIVE_FILENAME NOT NULL;

--
-- RHNCHANNELPRODUCT
--
ALTER TABLE RHNCHANNELPRODUCT DROP CONSTRAINT RHN_CHANNELPROD_BETA_NN;
ALTER TABLE RHNCHANNELPRODUCT MODIFY BETA NOT NULL;

--
-- RHNCHANNELPRODUCT
--
ALTER TABLE RHNCHANNELPRODUCT DROP CONSTRAINT RHN_CHANNELPROD_CREATED_NN;
ALTER TABLE RHNCHANNELPRODUCT MODIFY CREATED NOT NULL;

--
-- RHNCHANNELPRODUCT
--
ALTER TABLE RHNCHANNELPRODUCT DROP CONSTRAINT RHN_CHANNELPROD_ID_NN;
ALTER TABLE RHNCHANNELPRODUCT MODIFY ID NOT NULL;

--
-- RHNCHANNELPRODUCT
--
ALTER TABLE RHNCHANNELPRODUCT DROP CONSTRAINT RHN_CHANNELPROD_MODIFIED_NN;
ALTER TABLE RHNCHANNELPRODUCT MODIFY MODIFIED NOT NULL;

--
-- RHNCHANNELPRODUCT
--
ALTER TABLE RHNCHANNELPRODUCT DROP CONSTRAINT RHN_CHANNELPROD_PRODUCT_NN;
ALTER TABLE RHNCHANNELPRODUCT MODIFY PRODUCT NOT NULL;

--
-- RHNCHANNELPRODUCT
--
ALTER TABLE RHNCHANNELPRODUCT DROP CONSTRAINT RHN_CHANNELPROD_VERSION_NN;
ALTER TABLE RHNCHANNELPRODUCT MODIFY VERSION NOT NULL;

--
-- RHNCHANNEL
--
ALTER TABLE RHNCHANNEL DROP CONSTRAINT RHN_CHANNEL_BASEDIR_NN;
ALTER TABLE RHNCHANNEL MODIFY BASEDIR NOT NULL;

--
-- RHNCHANNEL
--
ALTER TABLE RHNCHANNEL DROP CONSTRAINT RHN_CHANNEL_CAID_NN;
ALTER TABLE RHNCHANNEL MODIFY CHANNEL_ARCH_ID NOT NULL;

--
-- RHNCHANNEL
--
ALTER TABLE RHNCHANNEL DROP CONSTRAINT RHN_CHANNEL_CREATED_NN;
ALTER TABLE RHNCHANNEL MODIFY CREATED NOT NULL;

--
-- RHNCHANNELFAMILY
--
ALTER TABLE RHNCHANNELFAMILY DROP CONSTRAINT RHN_CHANNEL_FAMILY_CREATED_NN;
ALTER TABLE RHNCHANNELFAMILY MODIFY CREATED NOT NULL;

--
-- RHNCHANNELFAMILY
--
ALTER TABLE RHNCHANNELFAMILY DROP CONSTRAINT RHN_CHANNEL_FAMILY_ID_NN;
ALTER TABLE RHNCHANNELFAMILY MODIFY ID NOT NULL;

--
-- RHNCHANNELFAMILY
--
ALTER TABLE RHNCHANNELFAMILY DROP CONSTRAINT RHN_CHANNEL_FAMILY_LABEL_NN;
ALTER TABLE RHNCHANNELFAMILY MODIFY LABEL NOT NULL;

--
-- RHNCHANNELFAMILY
--
ALTER TABLE RHNCHANNELFAMILY DROP CONSTRAINT RHN_CHANNEL_FAMILY_MODIFIED_NN;
ALTER TABLE RHNCHANNELFAMILY MODIFY MODIFIED NOT NULL;

--
-- RHNCHANNELFAMILY
--
ALTER TABLE RHNCHANNELFAMILY DROP CONSTRAINT RHN_CHANNEL_FAMILY_NAME_NN;
ALTER TABLE RHNCHANNELFAMILY MODIFY NAME NOT NULL;

--
-- RHNCHANNELFAMILY
--
ALTER TABLE RHNCHANNELFAMILY DROP CONSTRAINT RHN_CHANNEL_FAMILY_URL_NN;
ALTER TABLE RHNCHANNELFAMILY MODIFY PRODUCT_URL NOT NULL;

--
-- RHNCHANNEL
--
ALTER TABLE RHNCHANNEL DROP CONSTRAINT RHN_CHANNEL_ID_NN;
ALTER TABLE RHNCHANNEL MODIFY ID NOT NULL;

--
-- RHNCHANNEL
--
ALTER TABLE RHNCHANNEL DROP CONSTRAINT RHN_CHANNEL_LABEL_NN;
ALTER TABLE RHNCHANNEL MODIFY LABEL NOT NULL;

--
-- RHNCHANNEL
--
ALTER TABLE RHNCHANNEL DROP CONSTRAINT RHN_CHANNEL_LM_NN;
ALTER TABLE RHNCHANNEL MODIFY LAST_MODIFIED NOT NULL;

--
-- RHNCHANNEL
--
ALTER TABLE RHNCHANNEL DROP CONSTRAINT RHN_CHANNEL_MODIFIED_NN;
ALTER TABLE RHNCHANNEL MODIFY MODIFIED NOT NULL;

--
-- RHNCHANNEL
--
ALTER TABLE RHNCHANNEL DROP CONSTRAINT RHN_CHANNEL_NAME_NN;
ALTER TABLE RHNCHANNEL MODIFY NAME NOT NULL;

--
-- RHNCHANNEL
--
ALTER TABLE RHNCHANNEL DROP CONSTRAINT RHN_CHANNEL_RU_NN;
ALTER TABLE RHNCHANNEL MODIFY RECEIVING_UPDATES NOT NULL;

--
-- RHNCHANNEL
--
ALTER TABLE RHNCHANNEL DROP CONSTRAINT RHN_CHANNEL_SUMMARY_NN;
ALTER TABLE RHNCHANNEL MODIFY SUMMARY NOT NULL;

--
-- RHNCHANNELTRUST
--
ALTER TABLE RHNCHANNELTRUST DROP CONSTRAINT RHN_CHANNEL_TRUST_CID_NN;
ALTER TABLE RHNCHANNELTRUST MODIFY CHANNEL_ID NOT NULL;

--
-- RHNCHANNELTRUST
--
ALTER TABLE RHNCHANNELTRUST DROP CONSTRAINT RHN_CHANNEL_TRUST_CREATED_NN;
ALTER TABLE RHNCHANNELTRUST MODIFY CREATED NOT NULL;

--
-- RHNCHANNELTRUST
--
ALTER TABLE RHNCHANNELTRUST DROP CONSTRAINT RHN_CHANNEL_TRUST_MODIFIED_NN;
ALTER TABLE RHNCHANNELTRUST MODIFY MODIFIED NOT NULL;

--
-- RHNCHANNELTRUST
--
ALTER TABLE RHNCHANNELTRUST DROP CONSTRAINT RHN_CHANNEL_TRUST_OTID_NN;
ALTER TABLE RHNCHANNELTRUST MODIFY ORG_TRUST_ID NOT NULL;

--
-- RHN_CHECK_PROBE
--
ALTER TABLE RHN_CHECK_PROBE DROP CONSTRAINT RHN_CHKPB_PROBE_ID_NN;
ALTER TABLE RHN_CHECK_PROBE MODIFY PROBE_ID NOT NULL;

--
-- RHN_CHECK_PROBE
--
ALTER TABLE RHN_CHECK_PROBE DROP CONSTRAINT RHN_CHK_HOST_ID_NN;
ALTER TABLE RHN_CHECK_PROBE MODIFY HOST_ID NOT NULL;

--
-- RHN_CHECK_PROBE
--
ALTER TABLE RHN_CHECK_PROBE DROP CONSTRAINT RHN_CHK_PROBE_TYPE_NN;
ALTER TABLE RHN_CHECK_PROBE MODIFY PROBE_TYPE NOT NULL;

--
-- RHN_CHECK_PROBE
--
ALTER TABLE RHN_CHECK_PROBE DROP CONSTRAINT RHN_CHK_SAT_CLUSTER_ID_NN;
ALTER TABLE RHN_CHECK_PROBE MODIFY SAT_CLUSTER_ID NOT NULL;

--
-- RHNCHANNELPARENT
--
ALTER TABLE RHNCHANNELPARENT DROP CONSTRAINT RHN_CHP_CREATED_NN;
ALTER TABLE RHNCHANNELPARENT MODIFY CREATED NOT NULL;

--
-- RHNCHANNELPARENT
--
ALTER TABLE RHNCHANNELPARENT DROP CONSTRAINT RHN_CHP_MODIFIED_NN;
ALTER TABLE RHNCHANNELPARENT MODIFY MODIFIED NOT NULL;

--
-- RHNCRYPTOKEYKICKSTART
--
ALTER TABLE RHNCRYPTOKEYKICKSTART DROP CONSTRAINT RHN_CKEY_KS_CKID_NN;
ALTER TABLE RHNCRYPTOKEYKICKSTART MODIFY CRYPTO_KEY_ID NOT NULL;

--
-- RHNCRYPTOKEYKICKSTART
--
ALTER TABLE RHNCRYPTOKEYKICKSTART DROP CONSTRAINT RHN_CKEY_KS_KSD_NN;
ALTER TABLE RHNCRYPTOKEYKICKSTART MODIFY KSDATA_ID NOT NULL;

--
-- RHN_CHECK_SUITE_PROBE
--
ALTER TABLE RHN_CHECK_SUITE_PROBE DROP CONSTRAINT RHN_CKSPB_CHECK_SUITE_ID_NN;
ALTER TABLE RHN_CHECK_SUITE_PROBE MODIFY CHECK_SUITE_ID NOT NULL;

--
-- RHN_CHECK_SUITE_PROBE
--
ALTER TABLE RHN_CHECK_SUITE_PROBE DROP CONSTRAINT RHN_CKSPB_PROBE_ID_NN;
ALTER TABLE RHN_CHECK_SUITE_PROBE MODIFY PROBE_ID NOT NULL;

--
-- RHN_CHECK_SUITE_PROBE
--
ALTER TABLE RHN_CHECK_SUITE_PROBE DROP CONSTRAINT RHN_CKSPB_PROBE_TYPE_NN;
ALTER TABLE RHN_CHECK_SUITE_PROBE MODIFY PROBE_TYPE NOT NULL;

--
-- RHN_CHECK_SUITES
--
ALTER TABLE RHN_CHECK_SUITES DROP CONSTRAINT RHN_CKSUT_CUSTID_NN;
ALTER TABLE RHN_CHECK_SUITES MODIFY CUSTOMER_ID NOT NULL;

--
-- RHN_CHECK_SUITES
--
ALTER TABLE RHN_CHECK_SUITES DROP CONSTRAINT RHN_CKSUT_LAST_DATE_NN;
ALTER TABLE RHN_CHECK_SUITES MODIFY LAST_UPDATE_DATE NOT NULL;

--
-- RHN_CHECK_SUITES
--
ALTER TABLE RHN_CHECK_SUITES DROP CONSTRAINT RHN_CKSUT_LAST_USER_NN;
ALTER TABLE RHN_CHECK_SUITES MODIFY LAST_UPDATE_USER NOT NULL;

--
-- RHN_CHECK_SUITES
--
ALTER TABLE RHN_CHECK_SUITES DROP CONSTRAINT RHN_CKSUT_RECID_NN;
ALTER TABLE RHN_CHECK_SUITES MODIFY RECID NOT NULL;

--
-- RHN_CHECK_SUITES
--
ALTER TABLE RHN_CHECK_SUITES DROP CONSTRAINT RHN_CKSUT_SUITE_NAME_NN;
ALTER TABLE RHN_CHECK_SUITES MODIFY SUITE_NAME NOT NULL;

--
-- RHNCLIENTCAPABILITYNAME
--
ALTER TABLE RHNCLIENTCAPABILITYNAME DROP CONSTRAINT RHN_CLIENTCAPNAM_ID_NN;
ALTER TABLE RHNCLIENTCAPABILITYNAME MODIFY ID NOT NULL;

--
-- RHNCLIENTCAPABILITYNAME
--
ALTER TABLE RHNCLIENTCAPABILITYNAME DROP CONSTRAINT RHN_CLIENTCAPNAM_NAME_NN;
ALTER TABLE RHNCLIENTCAPABILITYNAME MODIFY NAME NOT NULL;

--
-- RHNCLIENTCAPABILITY
--
ALTER TABLE RHNCLIENTCAPABILITY DROP CONSTRAINT RHN_CLIENTCAP_CAP_NID_NN;
ALTER TABLE RHNCLIENTCAPABILITY MODIFY CAPABILITY_NAME_ID NOT NULL;

--
-- RHNCLIENTCAPABILITY
--
ALTER TABLE RHNCLIENTCAPABILITY DROP CONSTRAINT RHN_CLIENTCAP_CREATED_NN;
ALTER TABLE RHNCLIENTCAPABILITY MODIFY CREATED NOT NULL;

--
-- RHNCLIENTCAPABILITY
--
ALTER TABLE RHNCLIENTCAPABILITY DROP CONSTRAINT RHN_CLIENTCAP_MODIFIED_NN;
ALTER TABLE RHNCLIENTCAPABILITY MODIFY MODIFIED NOT NULL;

--
-- RHNCLIENTCAPABILITY
--
ALTER TABLE RHNCLIENTCAPABILITY DROP CONSTRAINT RHN_CLIENTCAP_SID_NN;
ALTER TABLE RHNCLIENTCAPABILITY MODIFY SERVER_ID NOT NULL;

--
-- RHNCLIENTCAPABILITY
--
ALTER TABLE RHNCLIENTCAPABILITY DROP CONSTRAINT RHN_CLIENTCAP_VER_NN;
ALTER TABLE RHNCLIENTCAPABILITY MODIFY VERSION NOT NULL;

--
-- RHN_COMMAND_CENTER_STATE
--
ALTER TABLE RHN_COMMAND_CENTER_STATE DROP CONSTRAINT RHN_CMDCS_ALLOWED_NN;
ALTER TABLE RHN_COMMAND_CENTER_STATE MODIFY CUST_ADMIN_ACCESS_ALLOWED NOT NULL;

--
-- RHN_COMMAND_CENTER_STATE
--
ALTER TABLE RHN_COMMAND_CENTER_STATE DROP CONSTRAINT RHN_CMDCS_LAST_DATE_NN;
ALTER TABLE RHN_COMMAND_CENTER_STATE MODIFY LAST_UPDATE_DATE NOT NULL;

--
-- RHN_COMMAND_CENTER_STATE
--
ALTER TABLE RHN_COMMAND_CENTER_STATE DROP CONSTRAINT RHN_CMDCS_LAST_USER_NN;
ALTER TABLE RHN_COMMAND_CENTER_STATE MODIFY LAST_UPDATE_USER NOT NULL;

--
-- RHN_COMMAND_CENTER_STATE
--
ALTER TABLE RHN_COMMAND_CENTER_STATE DROP CONSTRAINT RHN_CMDCS_REASON_NN;
ALTER TABLE RHN_COMMAND_CENTER_STATE MODIFY REASON NOT NULL;

--
-- RHN_COMMAND_GROUPS
--
ALTER TABLE RHN_COMMAND_GROUPS DROP CONSTRAINT RHN_CMDGR_GROUP_NAME_NN;
ALTER TABLE RHN_COMMAND_GROUPS MODIFY GROUP_NAME NOT NULL;

--
-- RHN_COMMAND_TARGET
--
ALTER TABLE RHN_COMMAND_TARGET DROP CONSTRAINT RHN_CMDTG_CUST_ID_NN;
ALTER TABLE RHN_COMMAND_TARGET MODIFY CUSTOMER_ID NOT NULL;

--
-- RHN_COMMAND_TARGET
--
ALTER TABLE RHN_COMMAND_TARGET DROP CONSTRAINT RHN_CMDTG_RECID_NN;
ALTER TABLE RHN_COMMAND_TARGET MODIFY RECID NOT NULL;

--
-- RHN_COMMAND_TARGET
--
ALTER TABLE RHN_COMMAND_TARGET DROP CONSTRAINT RHN_CMDTG_TARGET_TY_NN;
ALTER TABLE RHN_COMMAND_TARGET MODIFY TARGET_TYPE NOT NULL;

--
-- RHN_CONTACT_METHODS
--
ALTER TABLE RHN_CONTACT_METHODS DROP CONSTRAINT RHN_CMETH_CONTACT_ID_NN;
ALTER TABLE RHN_CONTACT_METHODS MODIFY CONTACT_ID NOT NULL;

--
-- RHN_CONTACT_METHODS
--
ALTER TABLE RHN_CONTACT_METHODS DROP CONSTRAINT RHN_CMETH_METH_TYPE_NN;
ALTER TABLE RHN_CONTACT_METHODS MODIFY METHOD_TYPE_ID NOT NULL;

--
-- RHN_CONTACT_METHODS
--
ALTER TABLE RHN_CONTACT_METHODS DROP CONSTRAINT RHN_CMETH_NOTIF_FMT_NN;
ALTER TABLE RHN_CONTACT_METHODS MODIFY NOTIFICATION_FORMAT_ID NOT NULL;

--
-- RHN_CONTACT_METHODS
--
ALTER TABLE RHN_CONTACT_METHODS DROP CONSTRAINT RHN_CMETH_RECID_NN;
ALTER TABLE RHN_CONTACT_METHODS MODIFY RECID NOT NULL;

--
-- RHN_COMMAND
--
ALTER TABLE RHN_COMMAND DROP CONSTRAINT RHN_CMMND_ALLOWED_NN;
ALTER TABLE RHN_COMMAND MODIFY ALLOWED_IN_SUITE NOT NULL;

--
-- RHN_COMMAND
--
ALTER TABLE RHN_COMMAND DROP CONSTRAINT RHN_CMMND_CLASS_NN;
ALTER TABLE RHN_COMMAND MODIFY COMMAND_CLASS NOT NULL;

--
-- RHN_COMMAND
--
ALTER TABLE RHN_COMMAND DROP CONSTRAINT RHN_CMMND_DESC_NN;
ALTER TABLE RHN_COMMAND MODIFY DESCRIPTION NOT NULL;

--
-- RHN_COMMAND
--
ALTER TABLE RHN_COMMAND DROP CONSTRAINT RHN_CMMND_ENABLED_NN;
ALTER TABLE RHN_COMMAND MODIFY ENABLED NOT NULL;

--
-- RHN_COMMAND
--
ALTER TABLE RHN_COMMAND DROP CONSTRAINT RHN_CMMND_HOST_PROBE_NN;
ALTER TABLE RHN_COMMAND MODIFY FOR_HOST_PROBE NOT NULL;

--
-- RHN_COMMAND
--
ALTER TABLE RHN_COMMAND DROP CONSTRAINT RHN_CMMND_NAME_NN;
ALTER TABLE RHN_COMMAND MODIFY NAME NOT NULL;

--
-- RHN_COMMAND
--
ALTER TABLE RHN_COMMAND DROP CONSTRAINT RHN_CMMND_RECID_NN;
ALTER TABLE RHN_COMMAND MODIFY RECID NOT NULL;

--
-- RHNCHANNELNEWESTPACKAGEAUDIT
--
ALTER TABLE RHNCHANNELNEWESTPACKAGEAUDIT DROP CONSTRAINT RHN_CNP_AT_CALLER_NN;
ALTER TABLE RHNCHANNELNEWESTPACKAGEAUDIT MODIFY CALLER NOT NULL;

--
-- RHNCHANNELNEWESTPACKAGEAUDIT
--
ALTER TABLE RHNCHANNELNEWESTPACKAGEAUDIT DROP CONSTRAINT RHN_CNP_AT_CID_NN;
ALTER TABLE RHNCHANNELNEWESTPACKAGEAUDIT MODIFY CHANNEL_ID NOT NULL;

--
-- RHNCHANNELNEWESTPACKAGEAUDIT
--
ALTER TABLE RHNCHANNELNEWESTPACKAGEAUDIT DROP CONSTRAINT RHN_CNP_AT_RT_NN;
ALTER TABLE RHNCHANNELNEWESTPACKAGEAUDIT MODIFY REFRESH_TIME NOT NULL;

--
-- RHNCHANNELNEWESTPACKAGE
--
ALTER TABLE RHNCHANNELNEWESTPACKAGE DROP CONSTRAINT RHN_CNP_CID_NN;
ALTER TABLE RHNCHANNELNEWESTPACKAGE MODIFY CHANNEL_ID NOT NULL;

--
-- RHNCHANNELNEWESTPACKAGE
--
ALTER TABLE RHNCHANNELNEWESTPACKAGE DROP CONSTRAINT RHN_CNP_EID_NN;
ALTER TABLE RHNCHANNELNEWESTPACKAGE MODIFY EVR_ID NOT NULL;

--
-- RHNCHANNELNEWESTPACKAGE
--
ALTER TABLE RHNCHANNELNEWESTPACKAGE DROP CONSTRAINT RHN_CNP_NID_NN;
ALTER TABLE RHNCHANNELNEWESTPACKAGE MODIFY NAME_ID NOT NULL;

--
-- RHNCHANNELNEWESTPACKAGE
--
ALTER TABLE RHNCHANNELNEWESTPACKAGE DROP CONSTRAINT RHN_CNP_PAID_NN;
ALTER TABLE RHNCHANNELNEWESTPACKAGE MODIFY PACKAGE_ARCH_ID NOT NULL;

--
-- RHNCHANNELNEWESTPACKAGE
--
ALTER TABLE RHNCHANNELNEWESTPACKAGE DROP CONSTRAINT RHN_CNP_PID_NN;
ALTER TABLE RHNCHANNELNEWESTPACKAGE MODIFY PACKAGE_ID NOT NULL;

--
-- RHN_CONTACT_GROUP_MEMBERS
--
ALTER TABLE RHN_CONTACT_GROUP_MEMBERS DROP CONSTRAINT RHN_CNTGM_CGID_NN;
ALTER TABLE RHN_CONTACT_GROUP_MEMBERS MODIFY CONTACT_GROUP_ID NOT NULL;

--
-- RHN_CONTACT_GROUP_MEMBERS
--
ALTER TABLE RHN_CONTACT_GROUP_MEMBERS DROP CONSTRAINT RHN_CNTGM_LAST_DATE_NN;
ALTER TABLE RHN_CONTACT_GROUP_MEMBERS MODIFY LAST_UPDATE_DATE NOT NULL;

--
-- RHN_CONTACT_GROUP_MEMBERS
--
ALTER TABLE RHN_CONTACT_GROUP_MEMBERS DROP CONSTRAINT RHN_CNTGM_LAST_USER_NN;
ALTER TABLE RHN_CONTACT_GROUP_MEMBERS MODIFY LAST_UPDATE_USER NOT NULL;

--
-- RHN_CONTACT_GROUP_MEMBERS
--
ALTER TABLE RHN_CONTACT_GROUP_MEMBERS DROP CONSTRAINT RHN_CNTGM_ON_NN;
ALTER TABLE RHN_CONTACT_GROUP_MEMBERS MODIFY ORDER_NUMBER NOT NULL;

--
-- RHN_CONTACT_GROUPS
--
ALTER TABLE RHN_CONTACT_GROUPS DROP CONSTRAINT RHN_CNTGP_ACK_WAIT_NN;
ALTER TABLE RHN_CONTACT_GROUPS MODIFY ACK_WAIT NOT NULL;

--
-- RHN_CONTACT_GROUPS
--
ALTER TABLE RHN_CONTACT_GROUPS DROP CONSTRAINT RHN_CNTGP_CUST_ID_NN;
ALTER TABLE RHN_CONTACT_GROUPS MODIFY CUSTOMER_ID NOT NULL;

--
-- RHN_CONTACT_GROUPS
--
ALTER TABLE RHN_CONTACT_GROUPS DROP CONSTRAINT RHN_CNTGP_GROUP_NAME_NN;
ALTER TABLE RHN_CONTACT_GROUPS MODIFY CONTACT_GROUP_NAME NOT NULL;

--
-- RHN_CONTACT_GROUPS
--
ALTER TABLE RHN_CONTACT_GROUPS DROP CONSTRAINT RHN_CNTGP_LAST_DATE_NN;
ALTER TABLE RHN_CONTACT_GROUPS MODIFY LAST_UPDATE_DATE NOT NULL;

--
-- RHN_CONTACT_GROUPS
--
ALTER TABLE RHN_CONTACT_GROUPS DROP CONSTRAINT RHN_CNTGP_LAST_USER_NN;
ALTER TABLE RHN_CONTACT_GROUPS MODIFY LAST_UPDATE_USER NOT NULL;

--
-- RHN_CONTACT_GROUPS
--
ALTER TABLE RHN_CONTACT_GROUPS DROP CONSTRAINT RHN_CNTGP_NOTIF_FMT_NN;
ALTER TABLE RHN_CONTACT_GROUPS MODIFY NOTIFICATION_FORMAT_ID NOT NULL;

--
-- RHN_CONTACT_GROUPS
--
ALTER TABLE RHN_CONTACT_GROUPS DROP CONSTRAINT RHN_CNTGP_RECID_NN;
ALTER TABLE RHN_CONTACT_GROUPS MODIFY RECID NOT NULL;

--
-- RHN_CONTACT_GROUPS
--
ALTER TABLE RHN_CONTACT_GROUPS DROP CONSTRAINT RHN_CNTGP_ROTATE_F_NN;
ALTER TABLE RHN_CONTACT_GROUPS MODIFY ROTATE_FIRST NOT NULL;

--
-- RHN_CONTACT_GROUPS
--
ALTER TABLE RHN_CONTACT_GROUPS DROP CONSTRAINT RHN_CNTGP_STRAT_ID_NN;
ALTER TABLE RHN_CONTACT_GROUPS MODIFY STRATEGY_ID NOT NULL;

--
-- RHN_COMMAND_CLASS
--
ALTER TABLE RHN_COMMAND_CLASS DROP CONSTRAINT RHN_COMCL_CLASS_NAME_NN;
ALTER TABLE RHN_COMMAND_CLASS MODIFY CLASS_NAME NOT NULL;

--
-- RHN_CONFIG_SECURITY_TYPE
--
ALTER TABLE RHN_CONFIG_SECURITY_TYPE DROP CONSTRAINT RHN_CONCT_NAME_NN;
ALTER TABLE RHN_CONFIG_SECURITY_TYPE MODIFY NAME NOT NULL;

--
-- RHNCONFIGCHANNELTYPE
--
ALTER TABLE RHNCONFIGCHANNELTYPE DROP CONSTRAINT RHN_CONFCHANTYPE_CREAT_NN;
ALTER TABLE RHNCONFIGCHANNELTYPE MODIFY CREATED NOT NULL;

--
-- RHNCONFIGCHANNELTYPE
--
ALTER TABLE RHNCONFIGCHANNELTYPE DROP CONSTRAINT RHN_CONFCHANTYPE_ID_NN;
ALTER TABLE RHNCONFIGCHANNELTYPE MODIFY ID NOT NULL;

--
-- RHNCONFIGCHANNELTYPE
--
ALTER TABLE RHNCONFIGCHANNELTYPE DROP CONSTRAINT RHN_CONFCHANTYPE_LABEL_NN;
ALTER TABLE RHNCONFIGCHANNELTYPE MODIFY LABEL NOT NULL;

--
-- RHNCONFIGCHANNELTYPE
--
ALTER TABLE RHNCONFIGCHANNELTYPE DROP CONSTRAINT RHN_CONFCHANTYPE_MOD_NN;
ALTER TABLE RHNCONFIGCHANNELTYPE MODIFY MODIFIED NOT NULL;

--
-- RHNCONFIGCHANNELTYPE
--
ALTER TABLE RHNCONFIGCHANNELTYPE DROP CONSTRAINT RHN_CONFCHANTYPE_NAME_NN;
ALTER TABLE RHNCONFIGCHANNELTYPE MODIFY NAME NOT NULL;

--
-- RHNCONFIGCHANNELTYPE
--
ALTER TABLE RHNCONFIGCHANNELTYPE DROP CONSTRAINT RHN_CONFCHANTYPE_PRI_NN;
ALTER TABLE RHNCONFIGCHANNELTYPE MODIFY PRIORITY NOT NULL;

--
-- RHNCONFIGCHANNEL
--
ALTER TABLE RHNCONFIGCHANNEL DROP CONSTRAINT RHN_CONFCHAN_CREAT_NN;
ALTER TABLE RHNCONFIGCHANNEL MODIFY CREATED NOT NULL;

--
-- RHNCONFIGCHANNEL
--
ALTER TABLE RHNCONFIGCHANNEL DROP CONSTRAINT RHN_CONFCHAN_CTID_NN;
ALTER TABLE RHNCONFIGCHANNEL MODIFY CONFCHAN_TYPE_ID NOT NULL;

--
-- RHNCONFIGCHANNEL
--
ALTER TABLE RHNCONFIGCHANNEL DROP CONSTRAINT RHN_CONFCHAN_DESC_NN;
ALTER TABLE RHNCONFIGCHANNEL MODIFY DESCRIPTION NOT NULL;

--
-- RHNCONFIGCHANNEL
--
ALTER TABLE RHNCONFIGCHANNEL DROP CONSTRAINT RHN_CONFCHAN_ID_NN;
ALTER TABLE RHNCONFIGCHANNEL MODIFY ID NOT NULL;

--
-- RHNCONFIGCHANNEL
--
ALTER TABLE RHNCONFIGCHANNEL DROP CONSTRAINT RHN_CONFCHAN_LABEL_NN;
ALTER TABLE RHNCONFIGCHANNEL MODIFY LABEL NOT NULL;

--
-- RHNCONFIGCHANNEL
--
ALTER TABLE RHNCONFIGCHANNEL DROP CONSTRAINT RHN_CONFCHAN_MOD_NN;
ALTER TABLE RHNCONFIGCHANNEL MODIFY MODIFIED NOT NULL;

--
-- RHNCONFIGCHANNEL
--
ALTER TABLE RHNCONFIGCHANNEL DROP CONSTRAINT RHN_CONFCHAN_NAME_NN;
ALTER TABLE RHNCONFIGCHANNEL MODIFY NAME NOT NULL;

--
-- RHNCONFIGCHANNEL
--
ALTER TABLE RHNCONFIGCHANNEL DROP CONSTRAINT RHN_CONFCHAN_OID_NN;
ALTER TABLE RHNCONFIGCHANNEL MODIFY ORG_ID NOT NULL;

--
-- RHNCONFIGCONTENT
--
ALTER TABLE RHNCONFIGCONTENT DROP CONSTRAINT RHN_CONFCONTENT_CREAT_NN;
ALTER TABLE RHNCONFIGCONTENT MODIFY CREATED NOT NULL;

--
-- RHNCONFIGCONTENT
--
ALTER TABLE RHNCONFIGCONTENT DROP CONSTRAINT RHN_CONFCONTENT_ID_NN;
ALTER TABLE RHNCONFIGCONTENT MODIFY ID NOT NULL;

--
-- RHNCONFIGCONTENT
--
ALTER TABLE RHNCONFIGCONTENT DROP CONSTRAINT RHN_CONFCONTENT_ISBIN_NN;
ALTER TABLE RHNCONFIGCONTENT MODIFY IS_BINARY NOT NULL;

--
-- RHNCONFIGCONTENT
--
ALTER TABLE RHNCONFIGCONTENT DROP CONSTRAINT RHN_CONFCONTENT_MD5_NN;
ALTER TABLE RHNCONFIGCONTENT MODIFY MD5SUM NOT NULL;

--
-- RHNCONFIGCONTENT
--
ALTER TABLE RHNCONFIGCONTENT DROP CONSTRAINT RHN_CONFCONTENT_MOD_NN;
ALTER TABLE RHNCONFIGCONTENT MODIFY MODIFIED NOT NULL;

--
-- RHNCONFIGFILETYPE
--
ALTER TABLE RHNCONFIGFILETYPE DROP CONSTRAINT RHN_CONFFILETYPE_CREAT_NN;
ALTER TABLE RHNCONFIGFILETYPE MODIFY CREATED NOT NULL;

--
-- RHNCONFIGFILETYPE
--
ALTER TABLE RHNCONFIGFILETYPE DROP CONSTRAINT RHN_CONFFILETYPE_ID_NN;
ALTER TABLE RHNCONFIGFILETYPE MODIFY ID NOT NULL;

--
-- RHNCONFIGFILETYPE
--
ALTER TABLE RHNCONFIGFILETYPE DROP CONSTRAINT RHN_CONFFILETYPE_LABEL_NN;
ALTER TABLE RHNCONFIGFILETYPE MODIFY LABEL NOT NULL;

--
-- RHNCONFIGFILETYPE
--
ALTER TABLE RHNCONFIGFILETYPE DROP CONSTRAINT RHN_CONFFILETYPE_MOD_NN;
ALTER TABLE RHNCONFIGFILETYPE MODIFY MODIFIED NOT NULL;

--
-- RHNCONFIGFILETYPE
--
ALTER TABLE RHNCONFIGFILETYPE DROP CONSTRAINT RHN_CONFFILETYPE_NAME_NN;
ALTER TABLE RHNCONFIGFILETYPE MODIFY NAME NOT NULL;

--
-- RHNCONFIGFILE
--
ALTER TABLE RHNCONFIGFILE DROP CONSTRAINT RHN_CONFFILE_CCID_NN;
ALTER TABLE RHNCONFIGFILE MODIFY CONFIG_CHANNEL_ID NOT NULL;

--
-- RHNCONFIGFILE
--
ALTER TABLE RHNCONFIGFILE DROP CONSTRAINT RHN_CONFFILE_CFNID_NN;
ALTER TABLE RHNCONFIGFILE MODIFY CONFIG_FILE_NAME_ID NOT NULL;

--
-- RHNCONFIGFILE
--
ALTER TABLE RHNCONFIGFILE DROP CONSTRAINT RHN_CONFFILE_CREAT_NN;
ALTER TABLE RHNCONFIGFILE MODIFY CREATED NOT NULL;

--
-- RHNCONFIGFILEFAILURE
--
ALTER TABLE RHNCONFIGFILEFAILURE DROP CONSTRAINT RHN_CONFFILE_FAIL_CREAT_NN;
ALTER TABLE RHNCONFIGFILEFAILURE MODIFY CREATED NOT NULL;

--
-- RHNCONFIGFILEFAILURE
--
ALTER TABLE RHNCONFIGFILEFAILURE DROP CONSTRAINT RHN_CONFFILE_FAIL_ID_NN;
ALTER TABLE RHNCONFIGFILEFAILURE MODIFY ID NOT NULL;

--
-- RHNCONFIGFILEFAILURE
--
ALTER TABLE RHNCONFIGFILEFAILURE DROP CONSTRAINT RHN_CONFFILE_FAIL_LABEL_NN;
ALTER TABLE RHNCONFIGFILEFAILURE MODIFY LABEL NOT NULL;

--
-- RHNCONFIGFILEFAILURE
--
ALTER TABLE RHNCONFIGFILEFAILURE DROP CONSTRAINT RHN_CONFFILE_FAIL_MOD_NN;
ALTER TABLE RHNCONFIGFILEFAILURE MODIFY MODIFIED NOT NULL;

--
-- RHNCONFIGFILEFAILURE
--
ALTER TABLE RHNCONFIGFILEFAILURE DROP CONSTRAINT RHN_CONFFILE_FAIL_NAME_NN;
ALTER TABLE RHNCONFIGFILEFAILURE MODIFY NAME NOT NULL;

--
-- RHNCONFIGFILE
--
ALTER TABLE RHNCONFIGFILE DROP CONSTRAINT RHN_CONFFILE_ID_NN;
ALTER TABLE RHNCONFIGFILE MODIFY ID NOT NULL;

--
-- RHNCONFIGFILE
--
ALTER TABLE RHNCONFIGFILE DROP CONSTRAINT RHN_CONFFILE_MOD_NN;
ALTER TABLE RHNCONFIGFILE MODIFY MODIFIED NOT NULL;

--
-- RHNCONFIGFILE
--
ALTER TABLE RHNCONFIGFILE DROP CONSTRAINT RHN_CONFFILE_SID_NN;
ALTER TABLE RHNCONFIGFILE MODIFY STATE_ID NOT NULL;

--
-- RHN_CONFIG_GROUP
--
ALTER TABLE RHN_CONFIG_GROUP DROP CONSTRAINT RHN_CONFG_NAME_NN;
ALTER TABLE RHN_CONFIG_GROUP MODIFY NAME NOT NULL;

--
-- RHNCONFIGINFO
--
ALTER TABLE RHNCONFIGINFO DROP CONSTRAINT RHN_CONFINFO_CREAT_NN;
ALTER TABLE RHNCONFIGINFO MODIFY CREATED NOT NULL;

--
-- RHNCONFIGINFO
--
ALTER TABLE RHNCONFIGINFO DROP CONSTRAINT RHN_CONFINFO_FILEMODE_NN;
ALTER TABLE RHNCONFIGINFO MODIFY FILEMODE NOT NULL;

--
-- RHNCONFIGINFO
--
ALTER TABLE RHNCONFIGINFO DROP CONSTRAINT RHN_CONFINFO_GROUPNAME_NN;
ALTER TABLE RHNCONFIGINFO MODIFY GROUPNAME NOT NULL;

--
-- RHNCONFIGINFO
--
ALTER TABLE RHNCONFIGINFO DROP CONSTRAINT RHN_CONFINFO_ID_NN;
ALTER TABLE RHNCONFIGINFO MODIFY ID NOT NULL;

--
-- RHNCONFIGINFO
--
ALTER TABLE RHNCONFIGINFO DROP CONSTRAINT RHN_CONFINFO_MOD_NN;
ALTER TABLE RHNCONFIGINFO MODIFY MODIFIED NOT NULL;

--
-- RHNCONFIGINFO
--
ALTER TABLE RHNCONFIGINFO DROP CONSTRAINT RHN_CONFINFO_USERNAME_NN;
ALTER TABLE RHNCONFIGINFO MODIFY USERNAME NOT NULL;

--
-- RHN_CONFIG_MACRO
--
ALTER TABLE RHN_CONFIG_MACRO DROP CONSTRAINT RHN_CONFM_EDITABLE_NN;
ALTER TABLE RHN_CONFIG_MACRO MODIFY EDITABLE NOT NULL;

--
-- RHN_CONFIG_MACRO
--
ALTER TABLE RHN_CONFIG_MACRO DROP CONSTRAINT RHN_CONFM_ENV_NN;
ALTER TABLE RHN_CONFIG_MACRO MODIFY ENVIRONMENT NOT NULL;

--
-- RHN_CONFIG_MACRO
--
ALTER TABLE RHN_CONFIG_MACRO DROP CONSTRAINT RHN_CONFM_NAME_NN;
ALTER TABLE RHN_CONFIG_MACRO MODIFY NAME NOT NULL;

--
-- RHN_CONFIG_PARAMETER
--
ALTER TABLE RHN_CONFIG_PARAMETER DROP CONSTRAINT RHN_CONFP_GROUP_NAME_NN;
ALTER TABLE RHN_CONFIG_PARAMETER MODIFY GROUP_NAME NOT NULL;

--
-- RHN_CONFIG_PARAMETER
--
ALTER TABLE RHN_CONFIG_PARAMETER DROP CONSTRAINT RHN_CONFP_NAME_NN;
ALTER TABLE RHN_CONFIG_PARAMETER MODIFY NAME NOT NULL;

--
-- RHN_CONFIG_PARAMETER
--
ALTER TABLE RHN_CONFIG_PARAMETER DROP CONSTRAINT RHN_CONFP_SECURITY_TYPE_NN;
ALTER TABLE RHN_CONFIG_PARAMETER MODIFY SECURITY_TYPE NOT NULL;

--
-- RHNCONFIGREVISION
--
ALTER TABLE RHNCONFIGREVISION DROP CONSTRAINT RHN_CONFREVISION_CCID_NN;
ALTER TABLE RHNCONFIGREVISION MODIFY CONFIG_CONTENT_ID NOT NULL;

--
-- RHNCONFIGREVISION
--
ALTER TABLE RHNCONFIGREVISION DROP CONSTRAINT RHN_CONFREVISION_CFID_NN;
ALTER TABLE RHNCONFIGREVISION MODIFY CONFIG_FILE_ID NOT NULL;

--
-- RHNCONFIGREVISION
--
ALTER TABLE RHNCONFIGREVISION DROP CONSTRAINT RHN_CONFREVISION_CIID_NN;
ALTER TABLE RHNCONFIGREVISION MODIFY CONFIG_INFO_ID NOT NULL;

--
-- RHNCONFIGREVISION
--
ALTER TABLE RHNCONFIGREVISION DROP CONSTRAINT RHN_CONFREVISION_CREAT_NN;
ALTER TABLE RHNCONFIGREVISION MODIFY CREATED NOT NULL;

--
-- RHNCONFIGREVISION
--
ALTER TABLE RHNCONFIGREVISION DROP CONSTRAINT RHN_CONFREVISION_DEND_NN;
ALTER TABLE RHNCONFIGREVISION MODIFY DELIM_END NOT NULL;

--
-- RHNCONFIGREVISION
--
ALTER TABLE RHNCONFIGREVISION DROP CONSTRAINT RHN_CONFREVISION_DSTART_NN;
ALTER TABLE RHNCONFIGREVISION MODIFY DELIM_START NOT NULL;

--
-- RHNCONFIGREVISION
--
ALTER TABLE RHNCONFIGREVISION DROP CONSTRAINT RHN_CONFREVISION_ID_NN;
ALTER TABLE RHNCONFIGREVISION MODIFY ID NOT NULL;

--
-- RHNCONFIGREVISION
--
ALTER TABLE RHNCONFIGREVISION DROP CONSTRAINT RHN_CONFREVISION_MOD_NN;
ALTER TABLE RHNCONFIGREVISION MODIFY MODIFIED NOT NULL;

--
-- RHNCONFIGREVISION
--
ALTER TABLE RHNCONFIGREVISION DROP CONSTRAINT RHN_CONFREVISION_REV_NN;
ALTER TABLE RHNCONFIGREVISION MODIFY REVISION NOT NULL;

--
-- RHNCONFIGREVISION
--
ALTER TABLE RHNCONFIGREVISION DROP CONSTRAINT RHN_CONF_REV_CFTI_NN;
ALTER TABLE RHNCONFIGREVISION MODIFY CONFIG_FILE_TYPE_ID NOT NULL;

--
-- RHNWEBCONTACTCHANGESTATE
--
ALTER TABLE RHNWEBCONTACTCHANGESTATE DROP CONSTRAINT RHN_CONT_CHANGE_STATE_NN;
ALTER TABLE RHNWEBCONTACTCHANGESTATE MODIFY LABEL NOT NULL;

--
-- RHN_COMMAND_PARAM_THRESHOLD
--
ALTER TABLE RHN_COMMAND_PARAM_THRESHOLD DROP CONSTRAINT RHN_COPTR_COMMAND_CLASS_NN;
ALTER TABLE RHN_COMMAND_PARAM_THRESHOLD MODIFY COMMAND_CLASS NOT NULL;

--
-- RHN_COMMAND_PARAM_THRESHOLD
--
ALTER TABLE RHN_COMMAND_PARAM_THRESHOLD DROP CONSTRAINT RHN_COPTR_COMMAND_ID_NN;
ALTER TABLE RHN_COMMAND_PARAM_THRESHOLD MODIFY COMMAND_ID NOT NULL;

--
-- RHN_COMMAND_PARAM_THRESHOLD
--
ALTER TABLE RHN_COMMAND_PARAM_THRESHOLD DROP CONSTRAINT RHN_COPTR_PARAM_NAME_NN;
ALTER TABLE RHN_COMMAND_PARAM_THRESHOLD MODIFY PARAM_NAME NOT NULL;

--
-- RHN_COMMAND_PARAM_THRESHOLD
--
ALTER TABLE RHN_COMMAND_PARAM_THRESHOLD DROP CONSTRAINT RHN_COPTR_PARAM_TYPE_NN;
ALTER TABLE RHN_COMMAND_PARAM_THRESHOLD MODIFY PARAM_TYPE NOT NULL;

--
-- RHN_COMMAND_PARAM_THRESHOLD
--
ALTER TABLE RHN_COMMAND_PARAM_THRESHOLD DROP CONSTRAINT RHN_COPTR_THRES_MET_ID_NN;
ALTER TABLE RHN_COMMAND_PARAM_THRESHOLD MODIFY THRESHOLD_METRIC_ID NOT NULL;

--
-- RHN_COMMAND_PARAM_THRESHOLD
--
ALTER TABLE RHN_COMMAND_PARAM_THRESHOLD DROP CONSTRAINT RHN_COPTR_THRES_NAME_NN;
ALTER TABLE RHN_COMMAND_PARAM_THRESHOLD MODIFY THRESHOLD_TYPE_NAME NOT NULL;

--
-- RHN_COMMAND_PARAMETER
--
ALTER TABLE RHN_COMMAND_PARAMETER DROP CONSTRAINT RHN_CPARM_COMMAND_ID_NN;
ALTER TABLE RHN_COMMAND_PARAMETER MODIFY COMMAND_ID NOT NULL;

--
-- RHN_COMMAND_PARAMETER
--
ALTER TABLE RHN_COMMAND_PARAMETER DROP CONSTRAINT RHN_CPARM_DATA_TYPE_NAME_NN;
ALTER TABLE RHN_COMMAND_PARAMETER MODIFY DATA_TYPE_NAME NOT NULL;

--
-- RHN_COMMAND_PARAMETER
--
ALTER TABLE RHN_COMMAND_PARAMETER DROP CONSTRAINT RHN_CPARM_DEF_VALUE_VIS_NN;
ALTER TABLE RHN_COMMAND_PARAMETER MODIFY DEFAULT_VALUE_VISIBLE NOT NULL;

--
-- RHN_COMMAND_PARAMETER
--
ALTER TABLE RHN_COMMAND_PARAMETER DROP CONSTRAINT RHN_CPARM_DESCRIPTION_NN;
ALTER TABLE RHN_COMMAND_PARAMETER MODIFY DESCRIPTION NOT NULL;

--
-- RHN_COMMAND_PARAMETER
--
ALTER TABLE RHN_COMMAND_PARAMETER DROP CONSTRAINT RHN_CPARM_FIELD_ORDER_NN;
ALTER TABLE RHN_COMMAND_PARAMETER MODIFY FIELD_ORDER NOT NULL;

--
-- RHN_COMMAND_PARAMETER
--
ALTER TABLE RHN_COMMAND_PARAMETER DROP CONSTRAINT RHN_CPARM_FIELD_VISIBLE_NN;
ALTER TABLE RHN_COMMAND_PARAMETER MODIFY FIELD_VISIBLE NOT NULL;

--
-- RHN_COMMAND_PARAMETER
--
ALTER TABLE RHN_COMMAND_PARAMETER DROP CONSTRAINT RHN_CPARM_FIELD_WIDGET_NAME_NN;
ALTER TABLE RHN_COMMAND_PARAMETER MODIFY FIELD_WIDGET_NAME NOT NULL;

--
-- RHN_COMMAND_PARAMETER
--
ALTER TABLE RHN_COMMAND_PARAMETER DROP CONSTRAINT RHN_CPARM_MANDATORY_NN;
ALTER TABLE RHN_COMMAND_PARAMETER MODIFY MANDATORY NOT NULL;

--
-- RHN_COMMAND_PARAMETER
--
ALTER TABLE RHN_COMMAND_PARAMETER DROP CONSTRAINT RHN_CPARM_PARAM_NAME_NN;
ALTER TABLE RHN_COMMAND_PARAMETER MODIFY PARAM_NAME NOT NULL;

--
-- RHN_COMMAND_PARAMETER
--
ALTER TABLE RHN_COMMAND_PARAMETER DROP CONSTRAINT RHN_CPARM_PARAM_TYPE_NN;
ALTER TABLE RHN_COMMAND_PARAMETER MODIFY PARAM_TYPE NOT NULL;

--
-- RHNCHANNELPERMISSION
--
ALTER TABLE RHNCHANNELPERMISSION DROP CONSTRAINT RHN_CPERM_CID_NN;
ALTER TABLE RHNCHANNELPERMISSION MODIFY CHANNEL_ID NOT NULL;

--
-- RHNCHANNELPERMISSION
--
ALTER TABLE RHNCHANNELPERMISSION DROP CONSTRAINT RHN_CPERM_CREATED_NN;
ALTER TABLE RHNCHANNELPERMISSION MODIFY CREATED NOT NULL;

--
-- RHNCHANNELPERMISSION
--
ALTER TABLE RHNCHANNELPERMISSION DROP CONSTRAINT RHN_CPERM_MODIFIED_NN;
ALTER TABLE RHNCHANNELPERMISSION MODIFY MODIFIED NOT NULL;

--
-- RHNCHANNELPERMISSION
--
ALTER TABLE RHNCHANNELPERMISSION DROP CONSTRAINT RHN_CPERM_RID_NN;
ALTER TABLE RHNCHANNELPERMISSION MODIFY ROLE_ID NOT NULL;

--
-- RHNCHANNELPERMISSIONROLE
--
ALTER TABLE RHNCHANNELPERMISSIONROLE DROP CONSTRAINT RHN_CPERM_ROLE_CREATED_NN;
ALTER TABLE RHNCHANNELPERMISSIONROLE MODIFY CREATED NOT NULL;

--
-- RHNCHANNELPERMISSIONROLE
--
ALTER TABLE RHNCHANNELPERMISSIONROLE DROP CONSTRAINT RHN_CPERM_ROLE_DESC_NN;
ALTER TABLE RHNCHANNELPERMISSIONROLE MODIFY DESCRIPTION NOT NULL;

--
-- RHNCHANNELPERMISSIONROLE
--
ALTER TABLE RHNCHANNELPERMISSIONROLE DROP CONSTRAINT RHN_CPERM_ROLE_ID_NN;
ALTER TABLE RHNCHANNELPERMISSIONROLE MODIFY ID NOT NULL;

--
-- RHNCHANNELPERMISSIONROLE
--
ALTER TABLE RHNCHANNELPERMISSIONROLE DROP CONSTRAINT RHN_CPERM_ROLE_LABEL_NN;
ALTER TABLE RHNCHANNELPERMISSIONROLE MODIFY LABEL NOT NULL;

--
-- RHNCHANNELPERMISSIONROLE
--
ALTER TABLE RHNCHANNELPERMISSIONROLE DROP CONSTRAINT RHN_CPERM_ROLE_MODIFIED_NN;
ALTER TABLE RHNCHANNELPERMISSIONROLE MODIFY MODIFIED NOT NULL;

--
-- RHNCHANNELPERMISSION
--
ALTER TABLE RHNCHANNELPERMISSION DROP CONSTRAINT RHN_CPERM_UID_NN;
ALTER TABLE RHNCHANNELPERMISSION MODIFY USER_ID NOT NULL;

--
-- RHNCPUARCH
--
ALTER TABLE RHNCPUARCH DROP CONSTRAINT RHN_CPUARCH_CREATED_NN;
ALTER TABLE RHNCPUARCH MODIFY CREATED NOT NULL;

--
-- RHNCPUARCH
--
ALTER TABLE RHNCPUARCH DROP CONSTRAINT RHN_CPUARCH_ID_NN;
ALTER TABLE RHNCPUARCH MODIFY ID NOT NULL;

--
-- RHNCPUARCH
--
ALTER TABLE RHNCPUARCH DROP CONSTRAINT RHN_CPUARCH_LABEL_NN;
ALTER TABLE RHNCPUARCH MODIFY LABEL NOT NULL;

--
-- RHNCPUARCH
--
ALTER TABLE RHNCPUARCH DROP CONSTRAINT RHN_CPUARCH_MODIFIED_NN;
ALTER TABLE RHNCPUARCH MODIFY MODIFIED NOT NULL;

--
-- RHNCPUARCH
--
ALTER TABLE RHNCPUARCH DROP CONSTRAINT RHN_CPUARCH_NAME_NN;
ALTER TABLE RHNCPUARCH MODIFY NAME NOT NULL;

--
-- RHNCPU
--
ALTER TABLE RHNCPU DROP CONSTRAINT RHN_CPU_CAID_NN;
ALTER TABLE RHNCPU MODIFY CPU_ARCH_ID NOT NULL;

--
-- RHNCPU
--
ALTER TABLE RHNCPU DROP CONSTRAINT RHN_CPU_CREATED_NN;
ALTER TABLE RHNCPU MODIFY CREATED NOT NULL;

--
-- RHNCPU
--
ALTER TABLE RHNCPU DROP CONSTRAINT RHN_CPU_ID_NN;
ALTER TABLE RHNCPU MODIFY ID NOT NULL;

--
-- RHNCPU
--
ALTER TABLE RHNCPU DROP CONSTRAINT RHN_CPU_MODIFIED_NN;
ALTER TABLE RHNCPU MODIFY MODIFIED NOT NULL;

--
-- RHNCPU
--
ALTER TABLE RHNCPU DROP CONSTRAINT RHN_CPU_SERVER_NN;
ALTER TABLE RHNCPU MODIFY SERVER_ID NOT NULL;

--
-- RHNCHANNELPACKAGEARCHCOMPAT
--
ALTER TABLE RHNCHANNELPACKAGEARCHCOMPAT DROP CONSTRAINT RHN_CP_AC_CAID_NN;
ALTER TABLE RHNCHANNELPACKAGEARCHCOMPAT MODIFY CHANNEL_ARCH_ID NOT NULL;

--
-- RHNCHANNELPACKAGEARCHCOMPAT
--
ALTER TABLE RHNCHANNELPACKAGEARCHCOMPAT DROP CONSTRAINT RHN_CP_AC_CREATED_NN;
ALTER TABLE RHNCHANNELPACKAGEARCHCOMPAT MODIFY CREATED NOT NULL;

--
-- RHNCHANNELPACKAGEARCHCOMPAT
--
ALTER TABLE RHNCHANNELPACKAGEARCHCOMPAT DROP CONSTRAINT RHN_CP_AC_MODIFIED_NN;
ALTER TABLE RHNCHANNELPACKAGEARCHCOMPAT MODIFY MODIFIED NOT NULL;

--
-- RHNCHANNELPACKAGEARCHCOMPAT
--
ALTER TABLE RHNCHANNELPACKAGEARCHCOMPAT DROP CONSTRAINT RHN_CP_AC_PAID_NN;
ALTER TABLE RHNCHANNELPACKAGEARCHCOMPAT MODIFY PACKAGE_ARCH_ID NOT NULL;

--
-- RHNCHANNELPARENT
--
ALTER TABLE RHNCHANNELPARENT DROP CONSTRAINT RHN_CP_CH_NN;
ALTER TABLE RHNCHANNELPARENT MODIFY CHANNEL NOT NULL;

--
-- RHNCHANNELPACKAGE
--
ALTER TABLE RHNCHANNELPACKAGE DROP CONSTRAINT RHN_CP_CID_NN;
ALTER TABLE RHNCHANNELPACKAGE MODIFY CHANNEL_ID NOT NULL;

--
-- RHNCHANNELPACKAGE
--
ALTER TABLE RHNCHANNELPACKAGE DROP CONSTRAINT RHN_CP_CREATED_NN;
ALTER TABLE RHNCHANNELPACKAGE MODIFY CREATED NOT NULL;

--
-- RHNCHANNELPACKAGE
--
ALTER TABLE RHNCHANNELPACKAGE DROP CONSTRAINT RHN_CP_MODIFIED_NN;
ALTER TABLE RHNCHANNELPACKAGE MODIFY MODIFIED NOT NULL;

--
-- RHNCHANNELPARENT
--
ALTER TABLE RHNCHANNELPARENT DROP CONSTRAINT RHN_CP_PARENT_CH_NN;
ALTER TABLE RHNCHANNELPARENT MODIFY PARENT_CHANNEL NOT NULL;

--
-- RHNCHANNELPACKAGE
--
ALTER TABLE RHNCHANNELPACKAGE DROP CONSTRAINT RHN_CP_PID_NN;
ALTER TABLE RHNCHANNELPACKAGE MODIFY PACKAGE_ID NOT NULL;

--
-- RHN_COMMAND_QUEUE_EXECS_BK
--
ALTER TABLE RHN_COMMAND_QUEUE_EXECS_BK DROP CONSTRAINT RHN_CQCMDBK_INSTANCE_ID_NN;
ALTER TABLE RHN_COMMAND_QUEUE_EXECS_BK MODIFY INSTANCE_ID NOT NULL;

--
-- RHN_COMMAND_QUEUE_EXECS_BK
--
ALTER TABLE RHN_COMMAND_QUEUE_EXECS_BK DROP CONSTRAINT RHN_CQCMDBK_NETSAINT_ID_NN;
ALTER TABLE RHN_COMMAND_QUEUE_EXECS_BK MODIFY NETSAINT_ID NOT NULL;

--
-- RHN_COMMAND_QUEUE_EXECS_BK
--
ALTER TABLE RHN_COMMAND_QUEUE_EXECS_BK DROP CONSTRAINT RHN_CQCMDBK_TARGET_TYPE_NN;
ALTER TABLE RHN_COMMAND_QUEUE_EXECS_BK MODIFY TARGET_TYPE NOT NULL;

--
-- RHN_COMMAND_QUEUE_COMMANDS
--
ALTER TABLE RHN_COMMAND_QUEUE_COMMANDS DROP CONSTRAINT RHN_CQCMD_COMMAND_LINE_NN;
ALTER TABLE RHN_COMMAND_QUEUE_COMMANDS MODIFY COMMAND_LINE NOT NULL;

--
-- RHN_COMMAND_QUEUE_COMMANDS
--
ALTER TABLE RHN_COMMAND_QUEUE_COMMANDS DROP CONSTRAINT RHN_CQCMD_DESCRIPTION_NN;
ALTER TABLE RHN_COMMAND_QUEUE_COMMANDS MODIFY DESCRIPTION NOT NULL;

--
-- RHN_COMMAND_QUEUE_COMMANDS
--
ALTER TABLE RHN_COMMAND_QUEUE_COMMANDS DROP CONSTRAINT RHN_CQCMD_EFFECTIVE_GRP_NN;
ALTER TABLE RHN_COMMAND_QUEUE_COMMANDS MODIFY EFFECTIVE_GROUP NOT NULL;

--
-- RHN_COMMAND_QUEUE_COMMANDS
--
ALTER TABLE RHN_COMMAND_QUEUE_COMMANDS DROP CONSTRAINT RHN_CQCMD_EFFECTIVE_USR_NN;
ALTER TABLE RHN_COMMAND_QUEUE_COMMANDS MODIFY EFFECTIVE_USER NOT NULL;

--
-- RHN_COMMAND_QUEUE_COMMANDS
--
ALTER TABLE RHN_COMMAND_QUEUE_COMMANDS DROP CONSTRAINT RHN_CQCMD_PERMANENT_NN;
ALTER TABLE RHN_COMMAND_QUEUE_COMMANDS MODIFY PERMANENT NOT NULL;

--
-- RHN_COMMAND_QUEUE_COMMANDS
--
ALTER TABLE RHN_COMMAND_QUEUE_COMMANDS DROP CONSTRAINT RHN_CQCMD_RECID_NN;
ALTER TABLE RHN_COMMAND_QUEUE_COMMANDS MODIFY RECID NOT NULL;

--
-- RHN_COMMAND_QUEUE_COMMANDS
--
ALTER TABLE RHN_COMMAND_QUEUE_COMMANDS DROP CONSTRAINT RHN_CQCMD_RESTARTABLE_NN;
ALTER TABLE RHN_COMMAND_QUEUE_COMMANDS MODIFY RESTARTABLE NOT NULL;

--
-- RHN_COMMAND_QUEUE_EXECS
--
ALTER TABLE RHN_COMMAND_QUEUE_EXECS DROP CONSTRAINT RHN_CQEXE_INSTANCE_ID_NN;
ALTER TABLE RHN_COMMAND_QUEUE_EXECS MODIFY INSTANCE_ID NOT NULL;

--
-- RHN_COMMAND_QUEUE_EXECS
--
ALTER TABLE RHN_COMMAND_QUEUE_EXECS DROP CONSTRAINT RHN_CQEXE_NETSAINT_ID_NN;
ALTER TABLE RHN_COMMAND_QUEUE_EXECS MODIFY NETSAINT_ID NOT NULL;

--
-- RHN_COMMAND_QUEUE_EXECS
--
ALTER TABLE RHN_COMMAND_QUEUE_EXECS DROP CONSTRAINT RHN_CQEXE_TARGET_TYPE_NN;
ALTER TABLE RHN_COMMAND_QUEUE_EXECS MODIFY TARGET_TYPE NOT NULL;

--
-- RHN_COMMAND_QUEUE_INSTANCES_BK
--
ALTER TABLE RHN_COMMAND_QUEUE_INSTANCES_BK DROP CONSTRAINT RHN_CQINSBK_COMMAND_ID_NN;
ALTER TABLE RHN_COMMAND_QUEUE_INSTANCES_BK MODIFY COMMAND_ID NOT NULL;

--
-- RHN_COMMAND_QUEUE_INSTANCES_BK
--
ALTER TABLE RHN_COMMAND_QUEUE_INSTANCES_BK DROP CONSTRAINT RHN_CQINSBK_DATE_SUB_NN;
ALTER TABLE RHN_COMMAND_QUEUE_INSTANCES_BK MODIFY DATE_SUBMITTED NOT NULL;

--
-- RHN_COMMAND_QUEUE_INSTANCES_BK
--
ALTER TABLE RHN_COMMAND_QUEUE_INSTANCES_BK DROP CONSTRAINT RHN_CQINSBK_EXP_DATE_NN;
ALTER TABLE RHN_COMMAND_QUEUE_INSTANCES_BK MODIFY EXPIRATION_DATE NOT NULL;

--
-- RHN_COMMAND_QUEUE_INSTANCES_BK
--
ALTER TABLE RHN_COMMAND_QUEUE_INSTANCES_BK DROP CONSTRAINT RHN_CQINSBK_RECID_NN;
ALTER TABLE RHN_COMMAND_QUEUE_INSTANCES_BK MODIFY RECID NOT NULL;

--
-- RHN_COMMAND_QUEUE_INSTANCES
--
ALTER TABLE RHN_COMMAND_QUEUE_INSTANCES DROP CONSTRAINT RHN_CQINS_COMMAND_ID_NN;
ALTER TABLE RHN_COMMAND_QUEUE_INSTANCES MODIFY COMMAND_ID NOT NULL;

--
-- RHN_COMMAND_QUEUE_INSTANCES
--
ALTER TABLE RHN_COMMAND_QUEUE_INSTANCES DROP CONSTRAINT RHN_CQINS_DATE_SUBMITTED_NN;
ALTER TABLE RHN_COMMAND_QUEUE_INSTANCES MODIFY DATE_SUBMITTED NOT NULL;

--
-- RHN_COMMAND_QUEUE_INSTANCES
--
ALTER TABLE RHN_COMMAND_QUEUE_INSTANCES DROP CONSTRAINT RHN_CQINS_EXPIRATION_DATE_NN;
ALTER TABLE RHN_COMMAND_QUEUE_INSTANCES MODIFY EXPIRATION_DATE NOT NULL;

--
-- RHN_COMMAND_QUEUE_INSTANCES
--
ALTER TABLE RHN_COMMAND_QUEUE_INSTANCES DROP CONSTRAINT RHN_CQINS_RECID_NN;
ALTER TABLE RHN_COMMAND_QUEUE_INSTANCES MODIFY RECID NOT NULL;

--
-- RHN_COMMAND_QUEUE_PARAMS
--
ALTER TABLE RHN_COMMAND_QUEUE_PARAMS DROP CONSTRAINT RHN_CQPRM_INSTANCE_ID_NN;
ALTER TABLE RHN_COMMAND_QUEUE_PARAMS MODIFY INSTANCE_ID NOT NULL;

--
-- RHN_COMMAND_QUEUE_PARAMS
--
ALTER TABLE RHN_COMMAND_QUEUE_PARAMS DROP CONSTRAINT RHN_CQPRM_ORD_NN;
ALTER TABLE RHN_COMMAND_QUEUE_PARAMS MODIFY ORD NOT NULL;

--
-- RHN_COMMAND_QUEUE_SESSIONS
--
ALTER TABLE RHN_COMMAND_QUEUE_SESSIONS DROP CONSTRAINT RHN_CQSES_CONTACT_ID_NN;
ALTER TABLE RHN_COMMAND_QUEUE_SESSIONS MODIFY CONTACT_ID NOT NULL;

--
-- RHN_COMMAND_REQUIREMENTS
--
ALTER TABLE RHN_COMMAND_REQUIREMENTS DROP CONSTRAINT RHN_CREQS_DESCRIPTION_NN;
ALTER TABLE RHN_COMMAND_REQUIREMENTS MODIFY DESCRIPTION NOT NULL;

--
-- RHN_COMMAND_REQUIREMENTS
--
ALTER TABLE RHN_COMMAND_REQUIREMENTS DROP CONSTRAINT RHN_CREQS_NAME_NN;
ALTER TABLE RHN_COMMAND_REQUIREMENTS MODIFY NAME NOT NULL;

--
-- RHNCRYPTOKEYTYPE
--
ALTER TABLE RHNCRYPTOKEYTYPE DROP CONSTRAINT RHN_CRYPTOKEYTYPE_CREAT_NN;
ALTER TABLE RHNCRYPTOKEYTYPE MODIFY CREATED NOT NULL;

--
-- RHNCRYPTOKEYTYPE
--
ALTER TABLE RHNCRYPTOKEYTYPE DROP CONSTRAINT RHN_CRYPTOKEYTYPE_DESC_NN;
ALTER TABLE RHNCRYPTOKEYTYPE MODIFY DESCRIPTION NOT NULL;

--
-- RHNCRYPTOKEYTYPE
--
ALTER TABLE RHNCRYPTOKEYTYPE DROP CONSTRAINT RHN_CRYPTOKEYTYPE_ID_NN;
ALTER TABLE RHNCRYPTOKEYTYPE MODIFY ID NOT NULL;

--
-- RHNCRYPTOKEYTYPE
--
ALTER TABLE RHNCRYPTOKEYTYPE DROP CONSTRAINT RHN_CRYPTOKEYTYPE_LABEL_NN;
ALTER TABLE RHNCRYPTOKEYTYPE MODIFY LABEL NOT NULL;

--
-- RHNCRYPTOKEYTYPE
--
ALTER TABLE RHNCRYPTOKEYTYPE DROP CONSTRAINT RHN_CRYPTOKEYTYPE_MOD_NN;
ALTER TABLE RHNCRYPTOKEYTYPE MODIFY MODIFIED NOT NULL;

--
-- RHNCRYPTOKEY
--
ALTER TABLE RHNCRYPTOKEY DROP CONSTRAINT RHN_CRYPTOKEY_CKTID_NN;
ALTER TABLE RHNCRYPTOKEY MODIFY CRYPTO_KEY_TYPE_ID NOT NULL;

--
-- RHNCRYPTOKEY
--
ALTER TABLE RHNCRYPTOKEY DROP CONSTRAINT RHN_CRYPTOKEY_DESC_NN;
ALTER TABLE RHNCRYPTOKEY MODIFY DESCRIPTION NOT NULL;

--
-- RHNCRYPTOKEY
--
ALTER TABLE RHNCRYPTOKEY DROP CONSTRAINT RHN_CRYPTOKEY_ID_NN;
ALTER TABLE RHNCRYPTOKEY MODIFY ID NOT NULL;

--
-- RHNCRYPTOKEY
--
ALTER TABLE RHNCRYPTOKEY DROP CONSTRAINT RHN_CRYPTOKEY_OID_NN;
ALTER TABLE RHNCRYPTOKEY MODIFY ORG_ID NOT NULL;

--
-- RHN_CURRENT_STATE_SUMMARIES
--
ALTER TABLE RHN_CURRENT_STATE_SUMMARIES DROP CONSTRAINT RHN_CURSU_CUST_ID_NN;
ALTER TABLE RHN_CURRENT_STATE_SUMMARIES MODIFY CUSTOMER_ID NOT NULL;

--
-- RHN_CURRENT_STATE_SUMMARIES
--
ALTER TABLE RHN_CURRENT_STATE_SUMMARIES DROP CONSTRAINT RHN_CURSU_STATE_NN;
ALTER TABLE RHN_CURRENT_STATE_SUMMARIES MODIFY STATE NOT NULL;

--
-- RHN_CURRENT_STATE_SUMMARIES
--
ALTER TABLE RHN_CURRENT_STATE_SUMMARIES DROP CONSTRAINT RHN_CURSU_TEMPLATE_ID_NN;
ALTER TABLE RHN_CURRENT_STATE_SUMMARIES MODIFY TEMPLATE_ID NOT NULL;

--
-- RHNCVE
--
ALTER TABLE RHNCVE DROP CONSTRAINT RHN_CVE_ID_NN;
ALTER TABLE RHNCVE MODIFY ID NOT NULL;

--
-- RHNCVE
--
ALTER TABLE RHNCVE DROP CONSTRAINT RHN_CVE_NAME_NN;
ALTER TABLE RHNCVE MODIFY NAME NOT NULL;

--
-- RHNDAEMONSTATE
--
ALTER TABLE RHNDAEMONSTATE DROP CONSTRAINT RHN_DAEMONSTATE_LABEL_NN;
ALTER TABLE RHNDAEMONSTATE MODIFY LABEL NOT NULL;

--
-- RHNDAEMONSTATE
--
ALTER TABLE RHNDAEMONSTATE DROP CONSTRAINT RHN_DAEMONSTATE_LP_NN;
ALTER TABLE RHNDAEMONSTATE MODIFY LAST_POLL NOT NULL;

--
-- RHN_DB_ENVIRONMENT
--
ALTER TABLE RHN_DB_ENVIRONMENT DROP CONSTRAINT RHN_DBENV_DB_NAME_NN;
ALTER TABLE RHN_DB_ENVIRONMENT MODIFY DB_NAME NOT NULL;

--
-- RHNDISTCHANNELMAP
--
ALTER TABLE RHNDISTCHANNELMAP DROP CONSTRAINT RHN_DCM_CAID_NN;
ALTER TABLE RHNDISTCHANNELMAP MODIFY CHANNEL_ARCH_ID NOT NULL;

--
-- RHNDISTCHANNELMAP
--
ALTER TABLE RHNDISTCHANNELMAP DROP CONSTRAINT RHN_DCM_CID_NN;
ALTER TABLE RHNDISTCHANNELMAP MODIFY CHANNEL_ID NOT NULL;

--
-- RHNDISTCHANNELMAP
--
ALTER TABLE RHNDISTCHANNELMAP DROP CONSTRAINT RHN_DCM_OS_NN;
ALTER TABLE RHNDISTCHANNELMAP MODIFY OS NOT NULL;

--
-- RHNDISTCHANNELMAP
--
ALTER TABLE RHNDISTCHANNELMAP DROP CONSTRAINT RHN_DCM_RELEASE_NN;
ALTER TABLE RHNDISTCHANNELMAP MODIFY RELEASE NOT NULL;

--
-- RHNDEVICE
--
ALTER TABLE RHNDEVICE DROP CONSTRAINT RHN_DEVICE_CREATED_NN;
ALTER TABLE RHNDEVICE MODIFY CREATED NOT NULL;

--
-- RHNDEVICE
--
ALTER TABLE RHNDEVICE DROP CONSTRAINT RHN_DEVICE_ID_NN;
ALTER TABLE RHNDEVICE MODIFY ID NOT NULL;

--
-- RHNDEVICE
--
ALTER TABLE RHNDEVICE DROP CONSTRAINT RHN_DEVICE_MODIFIED_NN;
ALTER TABLE RHNDEVICE MODIFY MODIFIED NOT NULL;

--
-- RHNDEVICE
--
ALTER TABLE RHNDEVICE DROP CONSTRAINT RHN_DEVICE_SID_NN;
ALTER TABLE RHNDEVICE MODIFY SERVER_ID NOT NULL;

--
-- RHNDOWNLOADS
--
ALTER TABLE RHNDOWNLOADS DROP CONSTRAINT RHN_DL_CAT_NN;
ALTER TABLE RHNDOWNLOADS MODIFY CATEGORY NOT NULL;

--
-- RHNDOWNLOADS
--
ALTER TABLE RHNDOWNLOADS DROP CONSTRAINT RHN_DL_CFID_NN;
ALTER TABLE RHNDOWNLOADS MODIFY CHANNEL_FAMILY_ID NOT NULL;

--
-- RHNDOWNLOADS
--
ALTER TABLE RHNDOWNLOADS DROP CONSTRAINT RHN_DL_CREATED_NN;
ALTER TABLE RHNDOWNLOADS MODIFY CREATED NOT NULL;

--
-- RHNDOWNLOADS
--
ALTER TABLE RHNDOWNLOADS DROP CONSTRAINT RHN_DL_FID_NN;
ALTER TABLE RHNDOWNLOADS MODIFY FILE_ID NOT NULL;

--
-- RHNDOWNLOADS
--
ALTER TABLE RHNDOWNLOADS DROP CONSTRAINT RHN_DL_ID_NN;
ALTER TABLE RHNDOWNLOADS MODIFY ID NOT NULL;

--
-- RHNDOWNLOADS
--
ALTER TABLE RHNDOWNLOADS DROP CONSTRAINT RHN_DL_MODIFIED_NN;
ALTER TABLE RHNDOWNLOADS MODIFY MODIFIED NOT NULL;

--
-- RHNDOWNLOADS
--
ALTER TABLE RHNDOWNLOADS DROP CONSTRAINT RHN_DL_NAME_NN;
ALTER TABLE RHNDOWNLOADS MODIFY NAME NOT NULL;

--
-- RHNDOWNLOADS
--
ALTER TABLE RHNDOWNLOADS DROP CONSTRAINT RHN_DL_ORD_NN;
ALTER TABLE RHNDOWNLOADS MODIFY ORDERING NOT NULL;

--
-- RHNDOWNLOADTYPE
--
ALTER TABLE RHNDOWNLOADTYPE DROP CONSTRAINT RHN_DOWNLOAD_TYPE_ID_NN;
ALTER TABLE RHNDOWNLOADTYPE MODIFY ID NOT NULL;

--
-- RHNDOWNLOADTYPE
--
ALTER TABLE RHNDOWNLOADTYPE DROP CONSTRAINT RHN_DOWNLOAD_TYPE_LABEL_NN;
ALTER TABLE RHNDOWNLOADTYPE MODIFY LABEL NOT NULL;

--
-- RHNDOWNLOADTYPE
--
ALTER TABLE RHNDOWNLOADTYPE DROP CONSTRAINT RHN_DOWNLOAD_TYPE_NAME_NN;
ALTER TABLE RHNDOWNLOADTYPE MODIFY NAME NOT NULL;

--
-- RHN_DEPLOYED_PROBE
--
ALTER TABLE RHN_DEPLOYED_PROBE DROP CONSTRAINT RHN_DPROB_CHECK_INT_NN;
ALTER TABLE RHN_DEPLOYED_PROBE MODIFY CHECK_INTERVAL_MINUTES NOT NULL;

--
-- RHN_DEPLOYED_PROBE
--
ALTER TABLE RHN_DEPLOYED_PROBE DROP CONSTRAINT RHN_DPROB_COMMAND_ID_NN;
ALTER TABLE RHN_DEPLOYED_PROBE MODIFY COMMAND_ID NOT NULL;

--
-- RHN_DEPLOYED_PROBE
--
ALTER TABLE RHN_DEPLOYED_PROBE DROP CONSTRAINT RHN_DPROB_CUST_ID_NN;
ALTER TABLE RHN_DEPLOYED_PROBE MODIFY CUSTOMER_ID NOT NULL;

--
-- RHN_DEPLOYED_PROBE
--
ALTER TABLE RHN_DEPLOYED_PROBE DROP CONSTRAINT RHN_DPROB_PROBE_TYPE_NN;
ALTER TABLE RHN_DEPLOYED_PROBE MODIFY PROBE_TYPE NOT NULL;

--
-- RHN_DEPLOYED_PROBE
--
ALTER TABLE RHN_DEPLOYED_PROBE DROP CONSTRAINT RHN_DPROB_RECID_NN;
ALTER TABLE RHN_DEPLOYED_PROBE MODIFY RECID NOT NULL;

--
-- RHN_DEPLOYED_PROBE
--
ALTER TABLE RHN_DEPLOYED_PROBE DROP CONSTRAINT RHN_DPROB_RETRY_INT_NN;
ALTER TABLE RHN_DEPLOYED_PROBE MODIFY RETRY_INTERVAL_MINUTES NOT NULL;

--
-- RHNDAILYSUMMARYQUEUE
--
ALTER TABLE RHNDAILYSUMMARYQUEUE DROP CONSTRAINT RHN_DSQUEUE_CREATED_NN;
ALTER TABLE RHNDAILYSUMMARYQUEUE MODIFY CREATED NOT NULL;

--
-- RHNDAILYSUMMARYQUEUE
--
ALTER TABLE RHNDAILYSUMMARYQUEUE DROP CONSTRAINT RHN_DSQUEUE_MODIFIED_NN;
ALTER TABLE RHNDAILYSUMMARYQUEUE MODIFY MODIFIED NOT NULL;

--
-- RHNDAILYSUMMARYQUEUE
--
ALTER TABLE RHNDAILYSUMMARYQUEUE DROP CONSTRAINT RHN_DSQUEUE_OID_NN;
ALTER TABLE RHNDAILYSUMMARYQUEUE MODIFY ORG_ID NOT NULL;

--
-- RHNEMAILADDRESSLOG
--
ALTER TABLE RHNEMAILADDRESSLOG DROP CONSTRAINT RHN_EADDRESSLOG_A_NN;
ALTER TABLE RHNEMAILADDRESSLOG MODIFY ADDRESS NOT NULL;

--
-- RHNEMAILADDRESSLOG
--
ALTER TABLE RHNEMAILADDRESSLOG DROP CONSTRAINT RHN_EADDRESSLOG_CREATED_NN;
ALTER TABLE RHNEMAILADDRESSLOG MODIFY CREATED NOT NULL;

--
-- RHNEMAILADDRESSLOG
--
ALTER TABLE RHNEMAILADDRESSLOG DROP CONSTRAINT RHN_EADDRESSLOG_UID_NN;
ALTER TABLE RHNEMAILADDRESSLOG MODIFY USER_ID NOT NULL;

--
-- RHNEMAILADDRESS
--
ALTER TABLE RHNEMAILADDRESS DROP CONSTRAINT RHN_EADDRESS_A_NN;
ALTER TABLE RHNEMAILADDRESS MODIFY ADDRESS NOT NULL;

--
-- RHNEMAILADDRESS
--
ALTER TABLE RHNEMAILADDRESS DROP CONSTRAINT RHN_EADDRESS_CREATED_NN;
ALTER TABLE RHNEMAILADDRESS MODIFY CREATED NOT NULL;

--
-- RHNEMAILADDRESS
--
ALTER TABLE RHNEMAILADDRESS DROP CONSTRAINT RHN_EADDRESS_ID_NN;
ALTER TABLE RHNEMAILADDRESS MODIFY ID NOT NULL;

--
-- RHNEMAILADDRESS
--
ALTER TABLE RHNEMAILADDRESS DROP CONSTRAINT RHN_EADDRESS_MODIFIED_NN;
ALTER TABLE RHNEMAILADDRESS MODIFY MODIFIED NOT NULL;

--
-- RHNEMAILADDRESS
--
ALTER TABLE RHNEMAILADDRESS DROP CONSTRAINT RHN_EADDRESS_SID_NN;
ALTER TABLE RHNEMAILADDRESS MODIFY STATE_ID NOT NULL;

--
-- RHNEMAILADDRESS
--
ALTER TABLE RHNEMAILADDRESS DROP CONSTRAINT RHN_EADDRESS_UID_NN;
ALTER TABLE RHNEMAILADDRESS MODIFY USER_ID NOT NULL;

--
-- RHNEMAILADDRESSSTATE
--
ALTER TABLE RHNEMAILADDRESSSTATE DROP CONSTRAINT RHN_EASTATE_CREATED_NN;
ALTER TABLE RHNEMAILADDRESSSTATE MODIFY CREATED NOT NULL;

--
-- RHNEMAILADDRESSSTATE
--
ALTER TABLE RHNEMAILADDRESSSTATE DROP CONSTRAINT RHN_EASTATE_ID_NN;
ALTER TABLE RHNEMAILADDRESSSTATE MODIFY ID NOT NULL;

--
-- RHNEMAILADDRESSSTATE
--
ALTER TABLE RHNEMAILADDRESSSTATE DROP CONSTRAINT RHN_EASTATE_LABEL_NN;
ALTER TABLE RHNEMAILADDRESSSTATE MODIFY LABEL NOT NULL;

--
-- RHNEMAILADDRESSSTATE
--
ALTER TABLE RHNEMAILADDRESSSTATE DROP CONSTRAINT RHN_EASTATE_MODIFIED_NN;
ALTER TABLE RHNEMAILADDRESSSTATE MODIFY MODIFIED NOT NULL;

--
-- RHNERRATACLONEDTMP
--
ALTER TABLE RHNERRATACLONEDTMP DROP CONSTRAINT RHN_ECLONEDTMP_CREATED_NN;
ALTER TABLE RHNERRATACLONEDTMP MODIFY CREATED NOT NULL;

--
-- RHNERRATACLONEDTMP
--
ALTER TABLE RHNERRATACLONEDTMP DROP CONSTRAINT RHN_ECLONEDTMP_FEID_NN;
ALTER TABLE RHNERRATACLONEDTMP MODIFY ORIGINAL_ID NOT NULL;

--
-- RHNERRATACLONEDTMP
--
ALTER TABLE RHNERRATACLONEDTMP DROP CONSTRAINT RHN_ECLONEDTMP_MODIFIED_NN;
ALTER TABLE RHNERRATACLONEDTMP MODIFY MODIFIED NOT NULL;

--
-- RHNERRATACLONEDTMP
--
ALTER TABLE RHNERRATACLONEDTMP DROP CONSTRAINT RHN_ECLONEDTMP_TEID_NN;
ALTER TABLE RHNERRATACLONEDTMP MODIFY ID NOT NULL;

--
-- RHNERRATAFILECHANNELTMP
--
ALTER TABLE RHNERRATAFILECHANNELTMP DROP CONSTRAINT RHN_EFILECTMP_CID_NN;
ALTER TABLE RHNERRATAFILECHANNELTMP MODIFY CHANNEL_ID NOT NULL;

--
-- RHNERRATAFILECHANNELTMP
--
ALTER TABLE RHNERRATAFILECHANNELTMP DROP CONSTRAINT RHN_EFILECTMP_CREATED_NN;
ALTER TABLE RHNERRATAFILECHANNELTMP MODIFY CREATED NOT NULL;

--
-- RHNERRATAFILECHANNELTMP
--
ALTER TABLE RHNERRATAFILECHANNELTMP DROP CONSTRAINT RHN_EFILECTMP_EID_NN;
ALTER TABLE RHNERRATAFILECHANNELTMP MODIFY ERRATA_FILE_ID NOT NULL;

--
-- RHNERRATAFILECHANNELTMP
--
ALTER TABLE RHNERRATAFILECHANNELTMP DROP CONSTRAINT RHN_EFILECTMP_MODIFIED_NN;
ALTER TABLE RHNERRATAFILECHANNELTMP MODIFY MODIFIED NOT NULL;

--
-- RHNERRATAFILECHANNEL
--
ALTER TABLE RHNERRATAFILECHANNEL DROP CONSTRAINT RHN_EFILEC_CID_NN;
ALTER TABLE RHNERRATAFILECHANNEL MODIFY CHANNEL_ID NOT NULL;

--
-- RHNERRATAFILECHANNEL
--
ALTER TABLE RHNERRATAFILECHANNEL DROP CONSTRAINT RHN_EFILEC_CREATED_NN;
ALTER TABLE RHNERRATAFILECHANNEL MODIFY CREATED NOT NULL;

--
-- RHNERRATAFILECHANNEL
--
ALTER TABLE RHNERRATAFILECHANNEL DROP CONSTRAINT RHN_EFILEC_EID_NN;
ALTER TABLE RHNERRATAFILECHANNEL MODIFY ERRATA_FILE_ID NOT NULL;

--
-- RHNERRATAFILECHANNEL
--
ALTER TABLE RHNERRATAFILECHANNEL DROP CONSTRAINT RHN_EFILEC_MODIFIED_NN;
ALTER TABLE RHNERRATAFILECHANNEL MODIFY MODIFIED NOT NULL;

--
-- RHNERRATAFILEPACKAGESOURCE
--
ALTER TABLE RHNERRATAFILEPACKAGESOURCE DROP CONSTRAINT RHN_EFILEPS_CREATED_NN;
ALTER TABLE RHNERRATAFILEPACKAGESOURCE MODIFY CREATED NOT NULL;

--
-- RHNERRATAFILEPACKAGESOURCE
--
ALTER TABLE RHNERRATAFILEPACKAGESOURCE DROP CONSTRAINT RHN_EFILEPS_FILEID_NN;
ALTER TABLE RHNERRATAFILEPACKAGESOURCE MODIFY ERRATA_FILE_ID NOT NULL;

--
-- RHNERRATAFILEPACKAGESOURCE
--
ALTER TABLE RHNERRATAFILEPACKAGESOURCE DROP CONSTRAINT RHN_EFILEPS_MODIFIED_NN;
ALTER TABLE RHNERRATAFILEPACKAGESOURCE MODIFY MODIFIED NOT NULL;

--
-- RHNERRATAFILEPACKAGESOURCE
--
ALTER TABLE RHNERRATAFILEPACKAGESOURCE DROP CONSTRAINT RHN_EFILEPS_PID_NN;
ALTER TABLE RHNERRATAFILEPACKAGESOURCE MODIFY PACKAGE_ID NOT NULL;

--
-- RHNERRATAFILEPACKAGETMP
--
ALTER TABLE RHNERRATAFILEPACKAGETMP DROP CONSTRAINT RHN_EFILEPTMP_CREATED_NN;
ALTER TABLE RHNERRATAFILEPACKAGETMP MODIFY CREATED NOT NULL;

--
-- RHNERRATAFILEPACKAGETMP
--
ALTER TABLE RHNERRATAFILEPACKAGETMP DROP CONSTRAINT RHN_EFILEPTMP_FILEID_NN;
ALTER TABLE RHNERRATAFILEPACKAGETMP MODIFY ERRATA_FILE_ID NOT NULL;

--
-- RHNERRATAFILEPACKAGETMP
--
ALTER TABLE RHNERRATAFILEPACKAGETMP DROP CONSTRAINT RHN_EFILEPTMP_MODIFIED_NN;
ALTER TABLE RHNERRATAFILEPACKAGETMP MODIFY MODIFIED NOT NULL;

--
-- RHNERRATAFILEPACKAGETMP
--
ALTER TABLE RHNERRATAFILEPACKAGETMP DROP CONSTRAINT RHN_EFILEPTMP_PID_NN;
ALTER TABLE RHNERRATAFILEPACKAGETMP MODIFY PACKAGE_ID NOT NULL;

--
-- RHNERRATAFILEPACKAGE
--
ALTER TABLE RHNERRATAFILEPACKAGE DROP CONSTRAINT RHN_EFILEP_CREATED_NN;
ALTER TABLE RHNERRATAFILEPACKAGE MODIFY CREATED NOT NULL;

--
-- RHNERRATAFILEPACKAGE
--
ALTER TABLE RHNERRATAFILEPACKAGE DROP CONSTRAINT RHN_EFILEP_FILEID_NN;
ALTER TABLE RHNERRATAFILEPACKAGE MODIFY ERRATA_FILE_ID NOT NULL;

--
-- RHNERRATAFILEPACKAGE
--
ALTER TABLE RHNERRATAFILEPACKAGE DROP CONSTRAINT RHN_EFILEP_MODIFIED_NN;
ALTER TABLE RHNERRATAFILEPACKAGE MODIFY MODIFIED NOT NULL;

--
-- RHNERRATAFILEPACKAGE
--
ALTER TABLE RHNERRATAFILEPACKAGE DROP CONSTRAINT RHN_EFILEP_PID_NN;
ALTER TABLE RHNERRATAFILEPACKAGE MODIFY PACKAGE_ID NOT NULL;

--
-- RHNERRATANOTIFICATIONQUEUE
--
ALTER TABLE RHNERRATANOTIFICATIONQUEUE DROP CONSTRAINT RHN_ENQUEUE_CREATED_NN;
ALTER TABLE RHNERRATANOTIFICATIONQUEUE MODIFY CREATED NOT NULL;

--
-- RHNERRATANOTIFICATIONQUEUE
--
ALTER TABLE RHNERRATANOTIFICATIONQUEUE DROP CONSTRAINT RHN_ENQUEUE_EID_NN;
ALTER TABLE RHNERRATANOTIFICATIONQUEUE MODIFY ERRATA_ID NOT NULL;

--
-- RHNERRATANOTIFICATIONQUEUE
--
ALTER TABLE RHNERRATANOTIFICATIONQUEUE DROP CONSTRAINT RHN_ENQUEUE_MODIFIED_NN;
ALTER TABLE RHNERRATANOTIFICATIONQUEUE MODIFY MODIFIED NOT NULL;

--
-- RHNERRATANOTIFICATIONQUEUE
--
ALTER TABLE RHNERRATANOTIFICATIONQUEUE DROP CONSTRAINT RHN_ENQUEUE_NN;
ALTER TABLE RHNERRATANOTIFICATIONQUEUE MODIFY CHANNEL_ID NOT NULL;

--
-- RHNERRATANOTIFICATIONQUEUE
--
ALTER TABLE RHNERRATANOTIFICATIONQUEUE DROP CONSTRAINT RHN_ENQUEUE_OID_NN;
ALTER TABLE RHNERRATANOTIFICATIONQUEUE MODIFY ORG_ID NOT NULL;

--
-- RHNENTITLEMENTLOG
--
ALTER TABLE RHNENTITLEMENTLOG DROP CONSTRAINT RHN_ENTITLEMENT_LOG_BDATE_NN;
ALTER TABLE RHNENTITLEMENTLOG MODIFY BDATE NOT NULL;

--
-- RHNENTITLEMENTLOG
--
ALTER TABLE RHNENTITLEMENTLOG DROP CONSTRAINT RHN_ENTITLEMENT_LOG_EDATE_NN;
ALTER TABLE RHNENTITLEMENTLOG MODIFY EDATE NOT NULL;

--
-- RHNENTITLEMENTLOG
--
ALTER TABLE RHNENTITLEMENTLOG DROP CONSTRAINT RHN_ENTITLEMENT_LOG_RT_NN;
ALTER TABLE RHNENTITLEMENTLOG MODIFY RUN_TIME NOT NULL;

--
-- RHN_ENVIRONMENT
--
ALTER TABLE RHN_ENVIRONMENT DROP CONSTRAINT RHN_ENVIR_NAME_NN;
ALTER TABLE RHN_ENVIRONMENT MODIFY NAME NOT NULL;

--
-- RHNERRATAQUEUE
--
ALTER TABLE RHNERRATAQUEUE DROP CONSTRAINT RHN_EQUEUE_CID_NN;
ALTER TABLE RHNERRATAQUEUE MODIFY CHANNEL_ID NOT NULL;

--
-- RHNERRATAQUEUE
--
ALTER TABLE RHNERRATAQUEUE DROP CONSTRAINT RHN_EQUEUE_CREATED_NN;
ALTER TABLE RHNERRATAQUEUE MODIFY CREATED NOT NULL;

--
-- RHNERRATAQUEUE
--
ALTER TABLE RHNERRATAQUEUE DROP CONSTRAINT RHN_EQUEUE_EID_NN;
ALTER TABLE RHNERRATAQUEUE MODIFY ERRATA_ID NOT NULL;

--
-- RHNERRATAQUEUE
--
ALTER TABLE RHNERRATAQUEUE DROP CONSTRAINT RHN_EQUEUE_MODIFIED_NN;
ALTER TABLE RHNERRATAQUEUE MODIFY MODIFIED NOT NULL;

--
-- RHNERRATACLONED
--
ALTER TABLE RHNERRATACLONED DROP CONSTRAINT RHN_ERRATACLONE_CREATED_NN;
ALTER TABLE RHNERRATACLONED MODIFY CREATED NOT NULL;

--
-- RHNERRATACLONED
--
ALTER TABLE RHNERRATACLONED DROP CONSTRAINT RHN_ERRATACLONE_FEID_NN;
ALTER TABLE RHNERRATACLONED MODIFY ORIGINAL_ID NOT NULL;

--
-- RHNERRATACLONED
--
ALTER TABLE RHNERRATACLONED DROP CONSTRAINT RHN_ERRATACLONE_MODIFIED_NN;
ALTER TABLE RHNERRATACLONED MODIFY MODIFIED NOT NULL;

--
-- RHNERRATACLONED
--
ALTER TABLE RHNERRATACLONED DROP CONSTRAINT RHN_ERRATACLONE_TEID_NN;
ALTER TABLE RHNERRATACLONED MODIFY ID NOT NULL;

--
-- RHNERRATAFILETMP
--
ALTER TABLE RHNERRATAFILETMP DROP CONSTRAINT RHN_ERRATAFILETMP_CREATED_NN;
ALTER TABLE RHNERRATAFILETMP MODIFY CREATED NOT NULL;

--
-- RHNERRATAFILETMP
--
ALTER TABLE RHNERRATAFILETMP DROP CONSTRAINT RHN_ERRATAFILETMP_ERRATA_NN;
ALTER TABLE RHNERRATAFILETMP MODIFY ERRATA_ID NOT NULL;

--
-- RHNERRATAFILETMP
--
ALTER TABLE RHNERRATAFILETMP DROP CONSTRAINT RHN_ERRATAFILETMP_ID_NN;
ALTER TABLE RHNERRATAFILETMP MODIFY ID NOT NULL;

--
-- RHNERRATAFILETMP
--
ALTER TABLE RHNERRATAFILETMP DROP CONSTRAINT RHN_ERRATAFILETMP_MD5_NN;
ALTER TABLE RHNERRATAFILETMP MODIFY MD5SUM NOT NULL;

--
-- RHNERRATAFILETMP
--
ALTER TABLE RHNERRATAFILETMP DROP CONSTRAINT RHN_ERRATAFILETMP_MODIFIED_NN;
ALTER TABLE RHNERRATAFILETMP MODIFY MODIFIED NOT NULL;

--
-- RHNERRATAFILETMP
--
ALTER TABLE RHNERRATAFILETMP DROP CONSTRAINT RHN_ERRATAFILETMP_NAME_NN;
ALTER TABLE RHNERRATAFILETMP MODIFY FILENAME NOT NULL;

--
-- RHNERRATAFILETMP
--
ALTER TABLE RHNERRATAFILETMP DROP CONSTRAINT RHN_ERRATAFILETMP_TYPE_NN;
ALTER TABLE RHNERRATAFILETMP MODIFY TYPE NOT NULL;

--
-- RHNERRATAFILE
--
ALTER TABLE RHNERRATAFILE DROP CONSTRAINT RHN_ERRATAFILE_CREATED_NN;
ALTER TABLE RHNERRATAFILE MODIFY CREATED NOT NULL;

--
-- RHNERRATAFILE
--
ALTER TABLE RHNERRATAFILE DROP CONSTRAINT RHN_ERRATAFILE_ERRATA_NN;
ALTER TABLE RHNERRATAFILE MODIFY ERRATA_ID NOT NULL;

--
-- RHNERRATAFILE
--
ALTER TABLE RHNERRATAFILE DROP CONSTRAINT RHN_ERRATAFILE_ID_NN;
ALTER TABLE RHNERRATAFILE MODIFY ID NOT NULL;

--
-- RHNERRATAFILE
--
ALTER TABLE RHNERRATAFILE DROP CONSTRAINT RHN_ERRATAFILE_MD5_NN;
ALTER TABLE RHNERRATAFILE MODIFY MD5SUM NOT NULL;

--
-- RHNERRATAFILE
--
ALTER TABLE RHNERRATAFILE DROP CONSTRAINT RHN_ERRATAFILE_MODIFIED_NN;
ALTER TABLE RHNERRATAFILE MODIFY MODIFIED NOT NULL;

--
-- RHNERRATAFILE
--
ALTER TABLE RHNERRATAFILE DROP CONSTRAINT RHN_ERRATAFILE_NAME_NN;
ALTER TABLE RHNERRATAFILE MODIFY FILENAME NOT NULL;

--
-- RHNERRATAFILETYPE
--
ALTER TABLE RHNERRATAFILETYPE DROP CONSTRAINT RHN_ERRATAFILE_TYPE_ID_NN;
ALTER TABLE RHNERRATAFILETYPE MODIFY ID NOT NULL;

--
-- RHNERRATAFILETYPE
--
ALTER TABLE RHNERRATAFILETYPE DROP CONSTRAINT RHN_ERRATAFILE_TYPE_LABEL_NN;
ALTER TABLE RHNERRATAFILETYPE MODIFY LABEL NOT NULL;

--
-- RHNERRATAFILE
--
ALTER TABLE RHNERRATAFILE DROP CONSTRAINT RHN_ERRATAFILE_TYPE_NN;
ALTER TABLE RHNERRATAFILE MODIFY TYPE NOT NULL;

--
-- RHNERRATATMP
--
ALTER TABLE RHNERRATATMP DROP CONSTRAINT RHN_ERRATATMP_ADVISORY_NAME_NN;
ALTER TABLE RHNERRATATMP MODIFY ADVISORY_NAME NOT NULL;

--
-- RHNERRATATMP
--
ALTER TABLE RHNERRATATMP DROP CONSTRAINT RHN_ERRATATMP_ADVISORY_NN;
ALTER TABLE RHNERRATATMP MODIFY ADVISORY NOT NULL;

--
-- RHNERRATATMP
--
ALTER TABLE RHNERRATATMP DROP CONSTRAINT RHN_ERRATATMP_ADVISORY_REL_NN;
ALTER TABLE RHNERRATATMP MODIFY ADVISORY_REL NOT NULL;

--
-- RHNERRATATMP
--
ALTER TABLE RHNERRATATMP DROP CONSTRAINT RHN_ERRATATMP_ADV_TYPE_NN;
ALTER TABLE RHNERRATATMP MODIFY ADVISORY_TYPE NOT NULL;

--
-- RHNERRATATMP
--
ALTER TABLE RHNERRATATMP DROP CONSTRAINT RHN_ERRATATMP_CREATED_NN;
ALTER TABLE RHNERRATATMP MODIFY CREATED NOT NULL;

--
-- RHNERRATATMP
--
ALTER TABLE RHNERRATATMP DROP CONSTRAINT RHN_ERRATATMP_ID_NN;
ALTER TABLE RHNERRATATMP MODIFY ID NOT NULL;

--
-- RHNERRATATMP
--
ALTER TABLE RHNERRATATMP DROP CONSTRAINT RHN_ERRATATMP_ISSUE_NN;
ALTER TABLE RHNERRATATMP MODIFY ISSUE_DATE NOT NULL;

--
-- RHNERRATATMP
--
ALTER TABLE RHNERRATATMP DROP CONSTRAINT RHN_ERRATATMP_LAST_MOD_NN;
ALTER TABLE RHNERRATATMP MODIFY LAST_MODIFIED NOT NULL;

--
-- RHNERRATATMP
--
ALTER TABLE RHNERRATATMP DROP CONSTRAINT RHN_ERRATATMP_MODIFIED_NN;
ALTER TABLE RHNERRATATMP MODIFY MODIFIED NOT NULL;

--
-- RHNERRATATMP
--
ALTER TABLE RHNERRATATMP DROP CONSTRAINT RHN_ERRATATMP_UPDATE_NN;
ALTER TABLE RHNERRATATMP MODIFY UPDATE_DATE NOT NULL;

--
-- RHNERRATA
--
ALTER TABLE RHNERRATA DROP CONSTRAINT RHN_ERRATA_ADVISORY_NAME_NN;
ALTER TABLE RHNERRATA MODIFY ADVISORY_NAME NOT NULL;

--
-- RHNERRATA
--
ALTER TABLE RHNERRATA DROP CONSTRAINT RHN_ERRATA_ADVISORY_NN;
ALTER TABLE RHNERRATA MODIFY ADVISORY NOT NULL;

--
-- RHNERRATA
--
ALTER TABLE RHNERRATA DROP CONSTRAINT RHN_ERRATA_ADVISORY_REL_NN;
ALTER TABLE RHNERRATA MODIFY ADVISORY_REL NOT NULL;

--
-- RHNERRATA
--
ALTER TABLE RHNERRATA DROP CONSTRAINT RHN_ERRATA_ADV_TYPE_NN;
ALTER TABLE RHNERRATA MODIFY ADVISORY_TYPE NOT NULL;

--
-- RHNERRATABUGLISTTMP
--
ALTER TABLE RHNERRATABUGLISTTMP DROP CONSTRAINT RHN_ERRATA_BUGLISTTMP_BID_NN;
ALTER TABLE RHNERRATABUGLISTTMP MODIFY BUG_ID NOT NULL;

--
-- RHNERRATABUGLISTTMP
--
ALTER TABLE RHNERRATABUGLISTTMP DROP CONSTRAINT RHN_ERRATA_BUGLISTTMP_C_NN;
ALTER TABLE RHNERRATABUGLISTTMP MODIFY CREATED NOT NULL;

--
-- RHNERRATABUGLISTTMP
--
ALTER TABLE RHNERRATABUGLISTTMP DROP CONSTRAINT RHN_ERRATA_BUGLISTTMP_EID_NN;
ALTER TABLE RHNERRATABUGLISTTMP MODIFY ERRATA_ID NOT NULL;

--
-- RHNERRATABUGLISTTMP
--
ALTER TABLE RHNERRATABUGLISTTMP DROP CONSTRAINT RHN_ERRATA_BUGLISTTMP_M_NN;
ALTER TABLE RHNERRATABUGLISTTMP MODIFY MODIFIED NOT NULL;

--
-- RHNERRATABUGLIST
--
ALTER TABLE RHNERRATABUGLIST DROP CONSTRAINT RHN_ERRATA_BUGLIST_BUG_NN;
ALTER TABLE RHNERRATABUGLIST MODIFY BUG_ID NOT NULL;

--
-- RHNERRATABUGLIST
--
ALTER TABLE RHNERRATABUGLIST DROP CONSTRAINT RHN_ERRATA_BUGLIST_CREATED_NN;
ALTER TABLE RHNERRATABUGLIST MODIFY CREATED NOT NULL;

--
-- RHNERRATABUGLIST
--
ALTER TABLE RHNERRATABUGLIST DROP CONSTRAINT RHN_ERRATA_BUGLIST_ERRATA_NN;
ALTER TABLE RHNERRATABUGLIST MODIFY ERRATA_ID NOT NULL;

--
-- RHNERRATABUGLIST
--
ALTER TABLE RHNERRATABUGLIST DROP CONSTRAINT RHN_ERRATA_BUGLIST_MODIFIED_NN;
ALTER TABLE RHNERRATABUGLIST MODIFY MODIFIED NOT NULL;

--
-- RHNERRATA
--
ALTER TABLE RHNERRATA DROP CONSTRAINT RHN_ERRATA_CREATED_NN;
ALTER TABLE RHNERRATA MODIFY CREATED NOT NULL;

--
-- RHNERRATA
--
ALTER TABLE RHNERRATA DROP CONSTRAINT RHN_ERRATA_ID_NN;
ALTER TABLE RHNERRATA MODIFY ID NOT NULL;

--
-- RHNERRATA
--
ALTER TABLE RHNERRATA DROP CONSTRAINT RHN_ERRATA_ISSUE_NN;
ALTER TABLE RHNERRATA MODIFY ISSUE_DATE NOT NULL;

--
-- RHNERRATA
--
ALTER TABLE RHNERRATA DROP CONSTRAINT RHN_ERRATA_LAST_MOD_NN;
ALTER TABLE RHNERRATA MODIFY LAST_MODIFIED NOT NULL;

--
-- RHNERRATA
--
ALTER TABLE RHNERRATA DROP CONSTRAINT RHN_ERRATA_MODIFIED_NN;
ALTER TABLE RHNERRATA MODIFY MODIFIED NOT NULL;

--
-- RHNERRATA
--
ALTER TABLE RHNERRATA DROP CONSTRAINT RHN_ERRATA_PRODUCT_NN;
ALTER TABLE RHNERRATA MODIFY PRODUCT NOT NULL;

--
-- RHNERRATASEVERITY
--
ALTER TABLE RHNERRATASEVERITY DROP CONSTRAINT RHN_ERRATA_SEV_ID_NN;
ALTER TABLE RHNERRATASEVERITY MODIFY ID NOT NULL;

--
-- RHNERRATASEVERITY
--
ALTER TABLE RHNERRATASEVERITY DROP CONSTRAINT RHN_ERRATA_SEV_LABEL_NN;
ALTER TABLE RHNERRATASEVERITY MODIFY LABEL NOT NULL;

--
-- RHNERRATASEVERITY
--
ALTER TABLE RHNERRATASEVERITY DROP CONSTRAINT RHN_ERRATA_SEV_RANK_NN;
ALTER TABLE RHNERRATASEVERITY MODIFY RANK NOT NULL;

--
-- RHNERRATA
--
ALTER TABLE RHNERRATA DROP CONSTRAINT RHN_ERRATA_SOLUTION_NN;
ALTER TABLE RHNERRATA MODIFY SOLUTION NOT NULL;

--
-- RHNERRATA
--
ALTER TABLE RHNERRATA DROP CONSTRAINT RHN_ERRATA_SYNOPSIS_NN;
ALTER TABLE RHNERRATA MODIFY SYNOPSIS NOT NULL;

--
-- RHNERRATA
--
ALTER TABLE RHNERRATA DROP CONSTRAINT RHN_ERRATA_UPDATE_NN;
ALTER TABLE RHNERRATA MODIFY UPDATE_DATE NOT NULL;

--
-- RHNERRATACVE
--
ALTER TABLE RHNERRATACVE DROP CONSTRAINT RHN_ERR_CVE_CID_NN;
ALTER TABLE RHNERRATACVE MODIFY CVE_ID NOT NULL;

--
-- RHNERRATACVE
--
ALTER TABLE RHNERRATACVE DROP CONSTRAINT RHN_ERR_CVE_CREATED_NN;
ALTER TABLE RHNERRATACVE MODIFY CREATED NOT NULL;

--
-- RHNERRATACVE
--
ALTER TABLE RHNERRATACVE DROP CONSTRAINT RHN_ERR_CVE_EID_NN;
ALTER TABLE RHNERRATACVE MODIFY ERRATA_ID NOT NULL;

--
-- RHNERRATACVE
--
ALTER TABLE RHNERRATACVE DROP CONSTRAINT RHN_ERR_CVE_MODIFIED_NN;
ALTER TABLE RHNERRATACVE MODIFY MODIFIED NOT NULL;

--
-- RHNERRATAKEYWORDTMP
--
ALTER TABLE RHNERRATAKEYWORDTMP DROP CONSTRAINT RHN_ERR_KEYWORDTMP_CREATED_NN;
ALTER TABLE RHNERRATAKEYWORDTMP MODIFY CREATED NOT NULL;

--
-- RHNERRATAKEYWORDTMP
--
ALTER TABLE RHNERRATAKEYWORDTMP DROP CONSTRAINT RHN_ERR_KEYWORDTMP_EID_NN;
ALTER TABLE RHNERRATAKEYWORDTMP MODIFY ERRATA_ID NOT NULL;

--
-- RHNERRATAKEYWORDTMP
--
ALTER TABLE RHNERRATAKEYWORDTMP DROP CONSTRAINT RHN_ERR_KEYWORDTMP_MODIFIED_NN;
ALTER TABLE RHNERRATAKEYWORDTMP MODIFY MODIFIED NOT NULL;

--
-- RHNERRATAKEYWORD
--
ALTER TABLE RHNERRATAKEYWORD DROP CONSTRAINT RHN_ERR_KEYWORD_CREATED_NN;
ALTER TABLE RHNERRATAKEYWORD MODIFY CREATED NOT NULL;

--
-- RHNERRATAKEYWORD
--
ALTER TABLE RHNERRATAKEYWORD DROP CONSTRAINT RHN_ERR_KEYWORD_EID_NN;
ALTER TABLE RHNERRATAKEYWORD MODIFY ERRATA_ID NOT NULL;

--
-- RHNERRATAKEYWORD
--
ALTER TABLE RHNERRATAKEYWORD DROP CONSTRAINT RHN_ERR_KEYWORD_MODIFIED_NN;
ALTER TABLE RHNERRATAKEYWORD MODIFY MODIFIED NOT NULL;

--
-- RHNERRATAPACKAGETMP
--
ALTER TABLE RHNERRATAPACKAGETMP DROP CONSTRAINT RHN_ERR_PKGTMP_CREATED_NN;
ALTER TABLE RHNERRATAPACKAGETMP MODIFY CREATED NOT NULL;

--
-- RHNERRATAPACKAGETMP
--
ALTER TABLE RHNERRATAPACKAGETMP DROP CONSTRAINT RHN_ERR_PKGTMP_EID_NN;
ALTER TABLE RHNERRATAPACKAGETMP MODIFY ERRATA_ID NOT NULL;

--
-- RHNERRATAPACKAGETMP
--
ALTER TABLE RHNERRATAPACKAGETMP DROP CONSTRAINT RHN_ERR_PKGTMP_MODIFIED_NN;
ALTER TABLE RHNERRATAPACKAGETMP MODIFY MODIFIED NOT NULL;

--
-- RHNERRATAPACKAGETMP
--
ALTER TABLE RHNERRATAPACKAGETMP DROP CONSTRAINT RHN_ERR_PKGTMP_PID_NN;
ALTER TABLE RHNERRATAPACKAGETMP MODIFY PACKAGE_ID NOT NULL;

--
-- RHNERRATAPACKAGE
--
ALTER TABLE RHNERRATAPACKAGE DROP CONSTRAINT RHN_ERR_PKG_CREATED_NN;
ALTER TABLE RHNERRATAPACKAGE MODIFY CREATED NOT NULL;

--
-- RHNERRATAPACKAGE
--
ALTER TABLE RHNERRATAPACKAGE DROP CONSTRAINT RHN_ERR_PKG_EID_NN;
ALTER TABLE RHNERRATAPACKAGE MODIFY ERRATA_ID NOT NULL;

--
-- RHNERRATAPACKAGE
--
ALTER TABLE RHNERRATAPACKAGE DROP CONSTRAINT RHN_ERR_PKG_MODIFIED_NN;
ALTER TABLE RHNERRATAPACKAGE MODIFY MODIFIED NOT NULL;

--
-- RHNERRATAPACKAGE
--
ALTER TABLE RHNERRATAPACKAGE DROP CONSTRAINT RHN_ERR_PKG_PID_NN;
ALTER TABLE RHNERRATAPACKAGE MODIFY PACKAGE_ID NOT NULL;

--
-- RHNEXCEPTION
--
ALTER TABLE RHNEXCEPTION DROP CONSTRAINT RHN_EXC_ID_NN;
ALTER TABLE RHNEXCEPTION MODIFY ID NOT NULL;

--
-- RHNEXCEPTION
--
ALTER TABLE RHNEXCEPTION DROP CONSTRAINT RHN_EXC_LABEL_NN;
ALTER TABLE RHNEXCEPTION MODIFY LABEL NOT NULL;

--
-- RHNEXCEPTION
--
ALTER TABLE RHNEXCEPTION DROP CONSTRAINT RHN_EXC_MSG_NN;
ALTER TABLE RHNEXCEPTION MODIFY MESSAGE NOT NULL;

--
-- RHNFEATURE
--
ALTER TABLE RHNFEATURE DROP CONSTRAINT RHN_FEATURE_CREATED_NN;
ALTER TABLE RHNFEATURE MODIFY CREATED NOT NULL;

--
-- RHNFEATURE
--
ALTER TABLE RHNFEATURE DROP CONSTRAINT RHN_FEATURE_LABEL_NN;
ALTER TABLE RHNFEATURE MODIFY LABEL NOT NULL;

--
-- RHNFEATURE
--
ALTER TABLE RHNFEATURE DROP CONSTRAINT RHN_FEATURE_MODIFIED_NN;
ALTER TABLE RHNFEATURE MODIFY MODIFIED NOT NULL;

--
-- RHNFEATURE
--
ALTER TABLE RHNFEATURE DROP CONSTRAINT RHN_FEATURE_NAME_NN;
ALTER TABLE RHNFEATURE MODIFY NAME NOT NULL;

--
-- RHNFILEDOWNLOAD
--
ALTER TABLE RHNFILEDOWNLOAD DROP CONSTRAINT RHN_FILEDL_FID_NN;
ALTER TABLE RHNFILEDOWNLOAD MODIFY FILE_ID NOT NULL;

--
-- RHNFILEDOWNLOAD
--
ALTER TABLE RHNFILEDOWNLOAD DROP CONSTRAINT RHN_FILEDL_LOCATION_NN;
ALTER TABLE RHNFILEDOWNLOAD MODIFY LOCATION NOT NULL;

--
-- RHNFILEDOWNLOAD
--
ALTER TABLE RHNFILEDOWNLOAD DROP CONSTRAINT RHN_FILEDL_RIP_NN;
ALTER TABLE RHNFILEDOWNLOAD MODIFY REQUESTOR_IP NOT NULL;

--
-- RHNFILEDOWNLOAD
--
ALTER TABLE RHNFILEDOWNLOAD DROP CONSTRAINT RHN_FILEDL_START_NN;
ALTER TABLE RHNFILEDOWNLOAD MODIFY START_TIME NOT NULL;

--
-- RHNFILELIST
--
ALTER TABLE RHNFILELIST DROP CONSTRAINT RHN_FILELIST_CREAT_NN;
ALTER TABLE RHNFILELIST MODIFY CREATED NOT NULL;

--
-- RHNFILELIST
--
ALTER TABLE RHNFILELIST DROP CONSTRAINT RHN_FILELIST_ID_NN;
ALTER TABLE RHNFILELIST MODIFY ID NOT NULL;

--
-- RHNFILELIST
--
ALTER TABLE RHNFILELIST DROP CONSTRAINT RHN_FILELIST_L_NN;
ALTER TABLE RHNFILELIST MODIFY LABEL NOT NULL;

--
-- RHNFILELIST
--
ALTER TABLE RHNFILELIST DROP CONSTRAINT RHN_FILELIST_MOD_NN;
ALTER TABLE RHNFILELIST MODIFY MODIFIED NOT NULL;

--
-- RHNFILELIST
--
ALTER TABLE RHNFILELIST DROP CONSTRAINT RHN_FILELIST_OID_NN;
ALTER TABLE RHNFILELIST MODIFY ORG_ID NOT NULL;

--
-- RHNFILELOCATION
--
ALTER TABLE RHNFILELOCATION DROP CONSTRAINT RHN_FILELOC_FID_NN;
ALTER TABLE RHNFILELOCATION MODIFY FILE_ID NOT NULL;

--
-- RHNFILELOCATION
--
ALTER TABLE RHNFILELOCATION DROP CONSTRAINT RHN_FILELOC_LOC_NN;
ALTER TABLE RHNFILELOCATION MODIFY LOCATION NOT NULL;

--
-- RHNFILE
--
ALTER TABLE RHNFILE DROP CONSTRAINT RHN_FILE_CREATED_NN;
ALTER TABLE RHNFILE MODIFY CREATED NOT NULL;

--
-- RHNFILE
--
ALTER TABLE RHNFILE DROP CONSTRAINT RHN_FILE_FS_NN;
ALTER TABLE RHNFILE MODIFY FILE_SIZE NOT NULL;

--
-- RHNFILE
--
ALTER TABLE RHNFILE DROP CONSTRAINT RHN_FILE_ID_NN;
ALTER TABLE RHNFILE MODIFY ID NOT NULL;

--
-- RHNFILE
--
ALTER TABLE RHNFILE DROP CONSTRAINT RHN_FILE_MD5SUM_NN;
ALTER TABLE RHNFILE MODIFY MD5SUM NOT NULL;

--
-- RHNFILE
--
ALTER TABLE RHNFILE DROP CONSTRAINT RHN_FILE_MODIFIED_NN;
ALTER TABLE RHNFILE MODIFY MODIFIED NOT NULL;

--
-- RHNFILE
--
ALTER TABLE RHNFILE DROP CONSTRAINT RHN_FILE_PATH_NN;
ALTER TABLE RHNFILE MODIFY PATH NOT NULL;

--
-- RHNFILELISTMEMBERS
--
ALTER TABLE RHNFILELISTMEMBERS DROP CONSTRAINT RHN_FLMEMBERS_CFNID_NN;
ALTER TABLE RHNFILELISTMEMBERS MODIFY CONFIG_FILE_NAME_ID NOT NULL;

--
-- RHNFILELISTMEMBERS
--
ALTER TABLE RHNFILELISTMEMBERS DROP CONSTRAINT RHN_FLMEMBERS_CREAT_NN;
ALTER TABLE RHNFILELISTMEMBERS MODIFY CREATED NOT NULL;

--
-- RHNFILELISTMEMBERS
--
ALTER TABLE RHNFILELISTMEMBERS DROP CONSTRAINT RHN_FLMEMBERS_FLID_NN;
ALTER TABLE RHNFILELISTMEMBERS MODIFY FILE_LIST_ID NOT NULL;

--
-- RHNFILELISTMEMBERS
--
ALTER TABLE RHNFILELISTMEMBERS DROP CONSTRAINT RHN_FLMEMBERS_MOD_NN;
ALTER TABLE RHNFILELISTMEMBERS MODIFY MODIFIED NOT NULL;

--
-- RHNGRAILCOMPONENTCHOICES
--
ALTER TABLE RHNGRAILCOMPONENTCHOICES DROP CONSTRAINT RHN_GRAIL_COMP_CH_MODE_NN;
ALTER TABLE RHNGRAILCOMPONENTCHOICES MODIFY COMPONENT_MODE NOT NULL;

--
-- RHNGRAILCOMPONENTCHOICES
--
ALTER TABLE RHNGRAILCOMPONENTCHOICES DROP CONSTRAINT RHN_GRAIL_COMP_CH_NN;
ALTER TABLE RHNGRAILCOMPONENTCHOICES MODIFY USER_ID NOT NULL;

--
-- RHNGRAILCOMPONENTCHOICES
--
ALTER TABLE RHNGRAILCOMPONENTCHOICES DROP CONSTRAINT RHN_GRAIL_COMP_CH_ORDER_NN;
ALTER TABLE RHNGRAILCOMPONENTCHOICES MODIFY ORDERING NOT NULL;

--
-- RHNGRAILCOMPONENTCHOICES
--
ALTER TABLE RHNGRAILCOMPONENTCHOICES DROP CONSTRAINT RHN_GRAIL_COMP_CH_PKG_NN;
ALTER TABLE RHNGRAILCOMPONENTCHOICES MODIFY COMPONENT_PKG NOT NULL;

--
-- RHNGRAILCOMPONENTS
--
ALTER TABLE RHNGRAILCOMPONENTS DROP CONSTRAINT RHN_GRAIL_COMP_MODE_NN;
ALTER TABLE RHNGRAILCOMPONENTS MODIFY COMPONENT_MODE NOT NULL;

--
-- RHNGRAILCOMPONENTS
--
ALTER TABLE RHNGRAILCOMPONENTS DROP CONSTRAINT RHN_GRAIL_COMP_PKG_NN;
ALTER TABLE RHNGRAILCOMPONENTS MODIFY COMPONENT_PKG NOT NULL;

--
-- RHN_SERVER_MONITORING_INFO
--
ALTER TABLE RHN_SERVER_MONITORING_INFO DROP CONSTRAINT RHN_HOST_RECID_NN;
ALTER TABLE RHN_SERVER_MONITORING_INFO MODIFY RECID NOT NULL;

--
-- RHN_HOST_CHECK_SUITES
--
ALTER TABLE RHN_HOST_CHECK_SUITES DROP CONSTRAINT RHN_HSTCK_HOST_PROBE_NN;
ALTER TABLE RHN_HOST_CHECK_SUITES MODIFY HOST_PROBE_ID NOT NULL;

--
-- RHN_HOST_CHECK_SUITES
--
ALTER TABLE RHN_HOST_CHECK_SUITES DROP CONSTRAINT RHN_HSTCK_SUITE_ID_NN;
ALTER TABLE RHN_HOST_CHECK_SUITES MODIFY SUITE_ID NOT NULL;

--
-- RHN_HOST_PROBE
--
ALTER TABLE RHN_HOST_PROBE DROP CONSTRAINT RHN_HSTPB_HOST_ID_NN;
ALTER TABLE RHN_HOST_PROBE MODIFY HOST_ID NOT NULL;

--
-- RHN_HOST_PROBE
--
ALTER TABLE RHN_HOST_PROBE DROP CONSTRAINT RHN_HSTPB_PROBE_ID_NN;
ALTER TABLE RHN_HOST_PROBE MODIFY PROBE_ID NOT NULL;

--
-- RHN_HOST_PROBE
--
ALTER TABLE RHN_HOST_PROBE DROP CONSTRAINT RHN_HSTPB_PROBE_TYPE_NN;
ALTER TABLE RHN_HOST_PROBE MODIFY PROBE_TYPE NOT NULL;

--
-- RHN_HOST_PROBE
--
ALTER TABLE RHN_HOST_PROBE DROP CONSTRAINT RHN_HSTPB_SAT_CL_ID_NN;
ALTER TABLE RHN_HOST_PROBE MODIFY SAT_CLUSTER_ID NOT NULL;

--
-- RHNINFOPANE
--
ALTER TABLE RHNINFOPANE DROP CONSTRAINT RHN_INFO_PANE_LABL_NN;
ALTER TABLE RHNINFOPANE MODIFY LABEL NOT NULL;

--
-- RHNKICKSTARTCOMMANDNAME
--
ALTER TABLE RHNKICKSTARTCOMMANDNAME DROP CONSTRAINT RHN_KSCOMMANDNAME_ID_NN;
ALTER TABLE RHNKICKSTARTCOMMANDNAME MODIFY ID NOT NULL;

--
-- RHNKICKSTARTCOMMANDNAME
--
ALTER TABLE RHNKICKSTARTCOMMANDNAME DROP CONSTRAINT RHN_KSCOMMANDNAME_REQRD_NN;
ALTER TABLE RHNKICKSTARTCOMMANDNAME MODIFY REQUIRED NOT NULL;

--
-- RHNKICKSTARTCOMMANDNAME
--
ALTER TABLE RHNKICKSTARTCOMMANDNAME DROP CONSTRAINT RHN_KSCOMMANDNAME_SORTORDR_NN;
ALTER TABLE RHNKICKSTARTCOMMANDNAME MODIFY SORT_ORDER NOT NULL;

--
-- RHNKICKSTARTCOMMANDNAME
--
ALTER TABLE RHNKICKSTARTCOMMANDNAME DROP CONSTRAINT RHN_KSCOMMANDNAME_USES_ARGS_NN;
ALTER TABLE RHNKICKSTARTCOMMANDNAME MODIFY USES_ARGUMENTS NOT NULL;

--
-- RHNKICKSTARTCOMMAND
--
ALTER TABLE RHNKICKSTARTCOMMAND DROP CONSTRAINT RHN_KSCOMMAND_CREATED_NN;
ALTER TABLE RHNKICKSTARTCOMMAND MODIFY CREATED NOT NULL;

--
-- RHNKICKSTARTCOMMAND
--
ALTER TABLE RHNKICKSTARTCOMMAND DROP CONSTRAINT RHN_KSCOMMAND_KCNID_NN;
ALTER TABLE RHNKICKSTARTCOMMAND MODIFY KS_COMMAND_NAME_ID NOT NULL;

--
-- RHNKICKSTARTCOMMAND
--
ALTER TABLE RHNKICKSTARTCOMMAND DROP CONSTRAINT RHN_KSCOMMAND_KSID_NN;
ALTER TABLE RHNKICKSTARTCOMMAND MODIFY KICKSTART_ID NOT NULL;

--
-- RHNKICKSTARTCOMMAND
--
ALTER TABLE RHNKICKSTARTCOMMAND DROP CONSTRAINT RHN_KSCOMMAND_MODIFIED_NN;
ALTER TABLE RHNKICKSTARTCOMMAND MODIFY MODIFIED NOT NULL;

--
-- RHNKICKSTARTCOMMANDNAME
--
ALTER TABLE RHNKICKSTARTCOMMANDNAME DROP CONSTRAINT RHN_KSCOMMAND_NAME_NN;
ALTER TABLE RHNKICKSTARTCOMMANDNAME MODIFY NAME NOT NULL;

--
-- RHNKICKSTARTDEFAULTREGTOKEN
--
ALTER TABLE RHNKICKSTARTDEFAULTREGTOKEN DROP CONSTRAINT RHN_KSDRT_CREAT_NN;
ALTER TABLE RHNKICKSTARTDEFAULTREGTOKEN MODIFY CREATED NOT NULL;

--
-- RHNKICKSTARTDEFAULTREGTOKEN
--
ALTER TABLE RHNKICKSTARTDEFAULTREGTOKEN DROP CONSTRAINT RHN_KSDRT_KSID_NN;
ALTER TABLE RHNKICKSTARTDEFAULTREGTOKEN MODIFY KICKSTART_ID NOT NULL;

--
-- RHNKICKSTARTDEFAULTREGTOKEN
--
ALTER TABLE RHNKICKSTARTDEFAULTREGTOKEN DROP CONSTRAINT RHN_KSDRT_MOD_NN;
ALTER TABLE RHNKICKSTARTDEFAULTREGTOKEN MODIFY MODIFIED NOT NULL;

--
-- RHNKICKSTARTDEFAULTREGTOKEN
--
ALTER TABLE RHNKICKSTARTDEFAULTREGTOKEN DROP CONSTRAINT RHN_KSDRT_RTID_NN;
ALTER TABLE RHNKICKSTARTDEFAULTREGTOKEN MODIFY REGTOKEN_ID NOT NULL;

--
-- RHNKICKSTARTDEFAULTS
--
ALTER TABLE RHNKICKSTARTDEFAULTS DROP CONSTRAINT RHN_KSD_CMF_NN;
ALTER TABLE RHNKICKSTARTDEFAULTS MODIFY CFG_MANAGEMENT_FLAG NOT NULL;

--
-- RHNKICKSTARTDEFAULTS
--
ALTER TABLE RHNKICKSTARTDEFAULTS DROP CONSTRAINT RHN_KSD_CREATED_NN;
ALTER TABLE RHNKICKSTARTDEFAULTS MODIFY CREATED NOT NULL;

--
-- RHNKICKSTARTDEFAULTS
--
ALTER TABLE RHNKICKSTARTDEFAULTS DROP CONSTRAINT RHN_KSD_KSID_NN;
ALTER TABLE RHNKICKSTARTDEFAULTS MODIFY KICKSTART_ID NOT NULL;

--
-- RHNKICKSTARTDEFAULTS
--
ALTER TABLE RHNKICKSTARTDEFAULTS DROP CONSTRAINT RHN_KSD_KSTID_NN;
ALTER TABLE RHNKICKSTARTDEFAULTS MODIFY KSTREE_ID NOT NULL;

--
-- RHNKICKSTARTDEFAULTS
--
ALTER TABLE RHNKICKSTARTDEFAULTS DROP CONSTRAINT RHN_KSD_KVT_NN;
ALTER TABLE RHNKICKSTARTDEFAULTS MODIFY VIRTUALIZATION_TYPE NOT NULL;

--
-- RHNKICKSTARTDEFAULTS
--
ALTER TABLE RHNKICKSTARTDEFAULTS DROP CONSTRAINT RHN_KSD_MODIFIED_NN;
ALTER TABLE RHNKICKSTARTDEFAULTS MODIFY MODIFIED NOT NULL;

--
-- RHNKICKSTARTDEFAULTS
--
ALTER TABLE RHNKICKSTARTDEFAULTS DROP CONSTRAINT RHN_KSD_RMF_NN;
ALTER TABLE RHNKICKSTARTDEFAULTS MODIFY REMOTE_COMMAND_FLAG NOT NULL;

--
-- RHNKSINSTALLTYPE
--
ALTER TABLE RHNKSINSTALLTYPE DROP CONSTRAINT RHN_KSINSTALLTYPE_CREATED_NN;
ALTER TABLE RHNKSINSTALLTYPE MODIFY CREATED NOT NULL;

--
-- RHNKSINSTALLTYPE
--
ALTER TABLE RHNKSINSTALLTYPE DROP CONSTRAINT RHN_KSINSTALLTYPE_ID_NN;
ALTER TABLE RHNKSINSTALLTYPE MODIFY ID NOT NULL;

--
-- RHNKSINSTALLTYPE
--
ALTER TABLE RHNKSINSTALLTYPE DROP CONSTRAINT RHN_KSINSTALLTYPE_LABEL_NN;
ALTER TABLE RHNKSINSTALLTYPE MODIFY LABEL NOT NULL;

--
-- RHNKSINSTALLTYPE
--
ALTER TABLE RHNKSINSTALLTYPE DROP CONSTRAINT RHN_KSINSTALLTYPE_MOD_NN;
ALTER TABLE RHNKSINSTALLTYPE MODIFY MODIFIED NOT NULL;

--
-- RHNKSINSTALLTYPE
--
ALTER TABLE RHNKSINSTALLTYPE DROP CONSTRAINT RHN_KSINSTALLTYPE_NAME_NN;
ALTER TABLE RHNKSINSTALLTYPE MODIFY NAME NOT NULL;

--
-- RHNKICKSTARTIPRANGE
--
ALTER TABLE RHNKICKSTARTIPRANGE DROP CONSTRAINT RHN_KSIP_CREATED_NN;
ALTER TABLE RHNKICKSTARTIPRANGE MODIFY CREATED NOT NULL;

--
-- RHNKICKSTARTIPRANGE
--
ALTER TABLE RHNKICKSTARTIPRANGE DROP CONSTRAINT RHN_KSIP_KSID_NN;
ALTER TABLE RHNKICKSTARTIPRANGE MODIFY KICKSTART_ID NOT NULL;

--
-- RHNKICKSTARTIPRANGE
--
ALTER TABLE RHNKICKSTARTIPRANGE DROP CONSTRAINT RHN_KSIP_MAX_NN;
ALTER TABLE RHNKICKSTARTIPRANGE MODIFY MAX NOT NULL;

--
-- RHNKICKSTARTIPRANGE
--
ALTER TABLE RHNKICKSTARTIPRANGE DROP CONSTRAINT RHN_KSIP_MIN_NN;
ALTER TABLE RHNKICKSTARTIPRANGE MODIFY MIN NOT NULL;

--
-- RHNKICKSTARTIPRANGE
--
ALTER TABLE RHNKICKSTARTIPRANGE DROP CONSTRAINT RHN_KSIP_MODIFIED_NN;
ALTER TABLE RHNKICKSTARTIPRANGE MODIFY MODIFIED NOT NULL;

--
-- RHNKICKSTARTIPRANGE
--
ALTER TABLE RHNKICKSTARTIPRANGE DROP CONSTRAINT RHN_KSIP_OID_NN;
ALTER TABLE RHNKICKSTARTIPRANGE MODIFY ORG_ID NOT NULL;

--
-- RHNKICKSTARTPACKAGE
--
ALTER TABLE RHNKICKSTARTPACKAGE DROP CONSTRAINT RHN_KSPACKAGE_CREATED_NN;
ALTER TABLE RHNKICKSTARTPACKAGE MODIFY CREATED NOT NULL;

--
-- RHNKICKSTARTPACKAGE
--
ALTER TABLE RHNKICKSTARTPACKAGE DROP CONSTRAINT RHN_KSPACKAGE_KSID_NN;
ALTER TABLE RHNKICKSTARTPACKAGE MODIFY KICKSTART_ID NOT NULL;

--
-- RHNKICKSTARTPACKAGE
--
ALTER TABLE RHNKICKSTARTPACKAGE DROP CONSTRAINT RHN_KSPACKAGE_MODIFIED_NN;
ALTER TABLE RHNKICKSTARTPACKAGE MODIFY MODIFIED NOT NULL;

--
-- RHNKICKSTARTPACKAGE
--
ALTER TABLE RHNKICKSTARTPACKAGE DROP CONSTRAINT RHN_KSPACKAGE_PNID_NN;
ALTER TABLE RHNKICKSTARTPACKAGE MODIFY PACKAGE_NAME_ID NOT NULL;

--
-- RHNKICKSTARTPRESERVEFILELIST
--
ALTER TABLE RHNKICKSTARTPRESERVEFILELIST DROP CONSTRAINT RHN_KSPRESERVEFL_CREAT_NN;
ALTER TABLE RHNKICKSTARTPRESERVEFILELIST MODIFY CREATED NOT NULL;

--
-- RHNKICKSTARTPRESERVEFILELIST
--
ALTER TABLE RHNKICKSTARTPRESERVEFILELIST DROP CONSTRAINT RHN_KSPRESERVEFL_FLID_NN;
ALTER TABLE RHNKICKSTARTPRESERVEFILELIST MODIFY FILE_LIST_ID NOT NULL;

--
-- RHNKICKSTARTPRESERVEFILELIST
--
ALTER TABLE RHNKICKSTARTPRESERVEFILELIST DROP CONSTRAINT RHN_KSPRESERVEFL_KSID_NN;
ALTER TABLE RHNKICKSTARTPRESERVEFILELIST MODIFY KICKSTART_ID NOT NULL;

--
-- RHNKICKSTARTPRESERVEFILELIST
--
ALTER TABLE RHNKICKSTARTPRESERVEFILELIST DROP CONSTRAINT RHN_KSPRESERVEFL_MOD_NN;
ALTER TABLE RHNKICKSTARTPRESERVEFILELIST MODIFY MODIFIED NOT NULL;

--
-- RHNKICKSTARTSCRIPT
--
ALTER TABLE RHNKICKSTARTSCRIPT DROP CONSTRAINT RHN_KSSCRIPT_CHROOT_NN;
ALTER TABLE RHNKICKSTARTSCRIPT MODIFY CHROOT NOT NULL;

--
-- RHNKICKSTARTSCRIPT
--
ALTER TABLE RHNKICKSTARTSCRIPT DROP CONSTRAINT RHN_KSSCRIPT_CREAT_NN;
ALTER TABLE RHNKICKSTARTSCRIPT MODIFY CREATED NOT NULL;

--
-- RHNKICKSTARTSCRIPT
--
ALTER TABLE RHNKICKSTARTSCRIPT DROP CONSTRAINT RHN_KSSCRIPT_ID_NN;
ALTER TABLE RHNKICKSTARTSCRIPT MODIFY ID NOT NULL;

--
-- RHNKICKSTARTSCRIPT
--
ALTER TABLE RHNKICKSTARTSCRIPT DROP CONSTRAINT RHN_KSSCRIPT_KSID_NN;
ALTER TABLE RHNKICKSTARTSCRIPT MODIFY KICKSTART_ID NOT NULL;

--
-- RHNKICKSTARTSCRIPT
--
ALTER TABLE RHNKICKSTARTSCRIPT DROP CONSTRAINT RHN_KSSCRIPT_MOD_NN;
ALTER TABLE RHNKICKSTARTSCRIPT MODIFY MODIFIED NOT NULL;

--
-- RHNKICKSTARTSCRIPT
--
ALTER TABLE RHNKICKSTARTSCRIPT DROP CONSTRAINT RHN_KSSCRIPT_POS_NN;
ALTER TABLE RHNKICKSTARTSCRIPT MODIFY POSITION NOT NULL;

--
-- RHNKICKSTARTSCRIPT
--
ALTER TABLE RHNKICKSTARTSCRIPT DROP CONSTRAINT RHN_KSSCRIPT_RAW_NN;
ALTER TABLE RHNKICKSTARTSCRIPT MODIFY RAW_SCRIPT NOT NULL;

--
-- RHNKICKSTARTSCRIPT
--
ALTER TABLE RHNKICKSTARTSCRIPT DROP CONSTRAINT RHN_KSSCRIPT_ST_NN;
ALTER TABLE RHNKICKSTARTSCRIPT MODIFY SCRIPT_TYPE NOT NULL;

--
-- RHNKICKSTARTSESSION
--
ALTER TABLE RHNKICKSTARTSESSION DROP CONSTRAINT RHN_KSS_KVT_NN;
ALTER TABLE RHNKICKSTARTSESSION MODIFY VIRTUALIZATION_TYPE NOT NULL;

--
-- RHNKSTREEFILE
--
ALTER TABLE RHNKSTREEFILE DROP CONSTRAINT RHN_KSTREEFILE_CREATED_NN;
ALTER TABLE RHNKSTREEFILE MODIFY CREATED NOT NULL;

--
-- RHNKSTREEFILE
--
ALTER TABLE RHNKSTREEFILE DROP CONSTRAINT RHN_KSTREEFILE_FILE_SIZE_NN;
ALTER TABLE RHNKSTREEFILE MODIFY FILE_SIZE NOT NULL;

--
-- RHNKSTREEFILE
--
ALTER TABLE RHNKSTREEFILE DROP CONSTRAINT RHN_KSTREEFILE_KID_NN;
ALTER TABLE RHNKSTREEFILE MODIFY KSTREE_ID NOT NULL;

--
-- RHNKSTREEFILE
--
ALTER TABLE RHNKSTREEFILE DROP CONSTRAINT RHN_KSTREEFILE_LASTMOD_NN;
ALTER TABLE RHNKSTREEFILE MODIFY LAST_MODIFIED NOT NULL;

--
-- RHNKSTREEFILE
--
ALTER TABLE RHNKSTREEFILE DROP CONSTRAINT RHN_KSTREEFILE_MD5SUM_NN;
ALTER TABLE RHNKSTREEFILE MODIFY MD5SUM NOT NULL;

--
-- RHNKSTREEFILE
--
ALTER TABLE RHNKSTREEFILE DROP CONSTRAINT RHN_KSTREEFILE_MODIFIED_NN;
ALTER TABLE RHNKSTREEFILE MODIFY MODIFIED NOT NULL;

--
-- RHNKSTREEFILE
--
ALTER TABLE RHNKSTREEFILE DROP CONSTRAINT RHN_KSTREEFILE_RFN_NN;
ALTER TABLE RHNKSTREEFILE MODIFY RELATIVE_FILENAME NOT NULL;

--
-- RHNKSTREETYPE
--
ALTER TABLE RHNKSTREETYPE DROP CONSTRAINT RHN_KSTREETYPE_CREATED_NN;
ALTER TABLE RHNKSTREETYPE MODIFY CREATED NOT NULL;

--
-- RHNKSTREETYPE
--
ALTER TABLE RHNKSTREETYPE DROP CONSTRAINT RHN_KSTREETYPE_ID_NN;
ALTER TABLE RHNKSTREETYPE MODIFY ID NOT NULL;

--
-- RHNKSTREETYPE
--
ALTER TABLE RHNKSTREETYPE DROP CONSTRAINT RHN_KSTREETYPE_LABEL_NN;
ALTER TABLE RHNKSTREETYPE MODIFY LABEL NOT NULL;

--
-- RHNKSTREETYPE
--
ALTER TABLE RHNKSTREETYPE DROP CONSTRAINT RHN_KSTREETYPE_MOD_NN;
ALTER TABLE RHNKSTREETYPE MODIFY MODIFIED NOT NULL;

--
-- RHNKSTREETYPE
--
ALTER TABLE RHNKSTREETYPE DROP CONSTRAINT RHN_KSTREETYPE_NAME_NN;
ALTER TABLE RHNKSTREETYPE MODIFY NAME NOT NULL;

--
-- RHNKICKSTARTABLETREE
--
ALTER TABLE RHNKICKSTARTABLETREE DROP CONSTRAINT RHN_KSTREE_BP_NN;
ALTER TABLE RHNKICKSTARTABLETREE MODIFY BASE_PATH NOT NULL;

--
-- RHNKICKSTARTABLETREE
--
ALTER TABLE RHNKICKSTARTABLETREE DROP CONSTRAINT RHN_KSTREE_CID_NN;
ALTER TABLE RHNKICKSTARTABLETREE MODIFY CHANNEL_ID NOT NULL;

--
-- RHNKICKSTARTABLETREE
--
ALTER TABLE RHNKICKSTARTABLETREE DROP CONSTRAINT RHN_KSTREE_CREATED_NN;
ALTER TABLE RHNKICKSTARTABLETREE MODIFY CREATED NOT NULL;

--
-- RHNKICKSTARTABLETREE
--
ALTER TABLE RHNKICKSTARTABLETREE DROP CONSTRAINT RHN_KSTREE_ID_NN;
ALTER TABLE RHNKICKSTARTABLETREE MODIFY ID NOT NULL;

--
-- RHNKICKSTARTABLETREE
--
ALTER TABLE RHNKICKSTARTABLETREE DROP CONSTRAINT RHN_KSTREE_IT_NN;
ALTER TABLE RHNKICKSTARTABLETREE MODIFY INSTALL_TYPE NOT NULL;

--
-- RHNKICKSTARTABLETREE
--
ALTER TABLE RHNKICKSTARTABLETREE DROP CONSTRAINT RHN_KSTREE_KSTREETYPE_NN;
ALTER TABLE RHNKICKSTARTABLETREE MODIFY KSTREE_TYPE NOT NULL;

--
-- RHNKICKSTARTABLETREE
--
ALTER TABLE RHNKICKSTARTABLETREE DROP CONSTRAINT RHN_KSTREE_LABEL_NN;
ALTER TABLE RHNKICKSTARTABLETREE MODIFY LABEL NOT NULL;

--
-- RHNKICKSTARTABLETREE
--
ALTER TABLE RHNKICKSTARTABLETREE DROP CONSTRAINT RHN_KSTREE_LASTMOD_NN;
ALTER TABLE RHNKICKSTARTABLETREE MODIFY LAST_MODIFIED NOT NULL;

--
-- RHNKICKSTARTABLETREE
--
ALTER TABLE RHNKICKSTARTABLETREE DROP CONSTRAINT RHN_KSTREE_MODIFIED_NN;
ALTER TABLE RHNKICKSTARTABLETREE MODIFY MODIFIED NOT NULL;

--
-- RHNKSDATA
--
ALTER TABLE RHNKSDATA DROP CONSTRAINT RHN_KS_ACTIVE_NN;
ALTER TABLE RHNKSDATA MODIFY ACTIVE NOT NULL;

--
-- RHNKICKSTARTCHILDCHANNEL
--
ALTER TABLE RHNKICKSTARTCHILDCHANNEL DROP CONSTRAINT RHN_KS_CC_CID_NN;
ALTER TABLE RHNKICKSTARTCHILDCHANNEL MODIFY CHANNEL_ID NOT NULL;

--
-- RHNKICKSTARTCHILDCHANNEL
--
ALTER TABLE RHNKICKSTARTCHILDCHANNEL DROP CONSTRAINT RHN_KS_CC_CRE_NN;
ALTER TABLE RHNKICKSTARTCHILDCHANNEL MODIFY CREATED NOT NULL;

--
-- RHNKICKSTARTCHILDCHANNEL
--
ALTER TABLE RHNKICKSTARTCHILDCHANNEL DROP CONSTRAINT RHN_KS_CC_KSD_NN;
ALTER TABLE RHNKICKSTARTCHILDCHANNEL MODIFY KSDATA_ID NOT NULL;

--
-- RHNKICKSTARTCHILDCHANNEL
--
ALTER TABLE RHNKICKSTARTCHILDCHANNEL DROP CONSTRAINT RHN_KS_CC_MOD_NN;
ALTER TABLE RHNKICKSTARTCHILDCHANNEL MODIFY MODIFIED NOT NULL;

--
-- RHNKSDATA
--
ALTER TABLE RHNKSDATA DROP CONSTRAINT RHN_KS_CFG_SAVE_NN;
ALTER TABLE RHNKSDATA MODIFY KSCFG NOT NULL;

--
-- RHNKSDATA
--
ALTER TABLE RHNKSDATA DROP CONSTRAINT RHN_KS_CREATED_NN;
ALTER TABLE RHNKSDATA MODIFY CREATED NOT NULL;

--
-- RHNKSDATA
--
ALTER TABLE RHNKSDATA DROP CONSTRAINT RHN_KS_DEFAULT_NN;
ALTER TABLE RHNKSDATA MODIFY IS_ORG_DEFAULT NOT NULL;

--
-- RHNKSDATA
--
ALTER TABLE RHNKSDATA DROP CONSTRAINT RHN_KS_ID_NN;
ALTER TABLE RHNKSDATA MODIFY ID NOT NULL;

--
-- RHNKSDATA
--
ALTER TABLE RHNKSDATA DROP CONSTRAINT RHN_KS_LABEL_NN;
ALTER TABLE RHNKSDATA MODIFY LABEL NOT NULL;

--
-- RHNKSDATA
--
ALTER TABLE RHNKSDATA DROP CONSTRAINT RHN_KS_MODIFIED_NN;
ALTER TABLE RHNKSDATA MODIFY MODIFIED NOT NULL;

--
-- RHNKSDATA
--
ALTER TABLE RHNKSDATA DROP CONSTRAINT RHN_KS_NONCHROOT_POST_NN;
ALTER TABLE RHNKSDATA MODIFY NONCHROOTPOST NOT NULL;

--
-- RHNKSDATA
--
ALTER TABLE RHNKSDATA DROP CONSTRAINT RHN_KS_OID_NN;
ALTER TABLE RHNKSDATA MODIFY ORG_ID NOT NULL;

--
-- RHNKSDATA
--
ALTER TABLE RHNKSDATA DROP CONSTRAINT RHN_KS_POST_LOG_NN;
ALTER TABLE RHNKSDATA MODIFY POSTLOG NOT NULL;

--
-- RHNKSDATA
--
ALTER TABLE RHNKSDATA DROP CONSTRAINT RHN_KS_PRE_LOG_NN;
ALTER TABLE RHNKSDATA MODIFY PRELOG NOT NULL;

--
-- RHNKICKSTARTSESSIONHISTORY
--
ALTER TABLE RHNKICKSTARTSESSIONHISTORY DROP CONSTRAINT RHN_KS_SESSIONHIST_CREAT_NN;
ALTER TABLE RHNKICKSTARTSESSIONHISTORY MODIFY CREATED NOT NULL;

--
-- RHNKICKSTARTSESSIONHISTORY
--
ALTER TABLE RHNKICKSTARTSESSIONHISTORY DROP CONSTRAINT RHN_KS_SESSIONHIST_ID_NN;
ALTER TABLE RHNKICKSTARTSESSIONHISTORY MODIFY ID NOT NULL;

--
-- RHNKICKSTARTSESSIONHISTORY
--
ALTER TABLE RHNKICKSTARTSESSIONHISTORY DROP CONSTRAINT RHN_KS_SESSIONHIST_KSID_NN;
ALTER TABLE RHNKICKSTARTSESSIONHISTORY MODIFY KICKSTART_SESSION_ID NOT NULL;

--
-- RHNKICKSTARTSESSIONHISTORY
--
ALTER TABLE RHNKICKSTARTSESSIONHISTORY DROP CONSTRAINT RHN_KS_SESSIONHIST_MOD_NN;
ALTER TABLE RHNKICKSTARTSESSIONHISTORY MODIFY MODIFIED NOT NULL;

--
-- RHNKICKSTARTSESSIONHISTORY
--
ALTER TABLE RHNKICKSTARTSESSIONHISTORY DROP CONSTRAINT RHN_KS_SESSIONHIST_STAT_NN;
ALTER TABLE RHNKICKSTARTSESSIONHISTORY MODIFY STATE_ID NOT NULL;

--
-- RHNKICKSTARTSESSIONHISTORY
--
ALTER TABLE RHNKICKSTARTSESSIONHISTORY DROP CONSTRAINT RHN_KS_SESSIONHIST_TIME_NN;
ALTER TABLE RHNKICKSTARTSESSIONHISTORY MODIFY TIME NOT NULL;

--
-- RHNKICKSTARTSESSION
--
ALTER TABLE RHNKICKSTARTSESSION DROP CONSTRAINT RHN_KS_SESSION_CREATED_NN;
ALTER TABLE RHNKICKSTARTSESSION MODIFY CREATED NOT NULL;

--
-- RHNKICKSTARTSESSION
--
ALTER TABLE RHNKICKSTARTSESSION DROP CONSTRAINT RHN_KS_SESSION_DC_NN;
ALTER TABLE RHNKICKSTARTSESSION MODIFY DEPLOY_CONFIGS NOT NULL;

--
-- RHNKICKSTARTSESSION
--
ALTER TABLE RHNKICKSTARTSESSION DROP CONSTRAINT RHN_KS_SESSION_ID_NN;
ALTER TABLE RHNKICKSTARTSESSION MODIFY ID NOT NULL;

--
-- RHNKICKSTARTSESSION
--
ALTER TABLE RHNKICKSTARTSESSION DROP CONSTRAINT RHN_KS_SESSION_KSSSID_NN;
ALTER TABLE RHNKICKSTARTSESSION MODIFY STATE_ID NOT NULL;

--
-- RHNKICKSTARTSESSION
--
ALTER TABLE RHNKICKSTARTSESSION DROP CONSTRAINT RHN_KS_SESSION_LAST_ACTION_NN;
ALTER TABLE RHNKICKSTARTSESSION MODIFY LAST_ACTION NOT NULL;

--
-- RHNKICKSTARTSESSION
--
ALTER TABLE RHNKICKSTARTSESSION DROP CONSTRAINT RHN_KS_SESSION_MODIFIED_NN;
ALTER TABLE RHNKICKSTARTSESSION MODIFY MODIFIED NOT NULL;

--
-- RHNKICKSTARTSESSION
--
ALTER TABLE RHNKICKSTARTSESSION DROP CONSTRAINT RHN_KS_SESSION_OID_NN;
ALTER TABLE RHNKICKSTARTSESSION MODIFY ORG_ID NOT NULL;

--
-- RHNKICKSTARTSESSION
--
ALTER TABLE RHNKICKSTARTSESSION DROP CONSTRAINT RHN_KS_SESSION_PFC_NN;
ALTER TABLE RHNKICKSTARTSESSION MODIFY PACKAGE_FETCH_COUNT NOT NULL;

--
-- RHNKICKSTARTSESSIONSTATE
--
ALTER TABLE RHNKICKSTARTSESSIONSTATE DROP CONSTRAINT RHN_KS_SESSION_STATE_CREAT_NN;
ALTER TABLE RHNKICKSTARTSESSIONSTATE MODIFY CREATED NOT NULL;

--
-- RHNKICKSTARTSESSIONSTATE
--
ALTER TABLE RHNKICKSTARTSESSIONSTATE DROP CONSTRAINT RHN_KS_SESSION_STATE_DESC_NN;
ALTER TABLE RHNKICKSTARTSESSIONSTATE MODIFY DESCRIPTION NOT NULL;

--
-- RHNKICKSTARTSESSIONSTATE
--
ALTER TABLE RHNKICKSTARTSESSIONSTATE DROP CONSTRAINT RHN_KS_SESSION_STATE_ID_NN;
ALTER TABLE RHNKICKSTARTSESSIONSTATE MODIFY ID NOT NULL;

--
-- RHNKICKSTARTSESSIONSTATE
--
ALTER TABLE RHNKICKSTARTSESSIONSTATE DROP CONSTRAINT RHN_KS_SESSION_STATE_LABEL_NN;
ALTER TABLE RHNKICKSTARTSESSIONSTATE MODIFY LABEL NOT NULL;

--
-- RHNKICKSTARTSESSIONSTATE
--
ALTER TABLE RHNKICKSTARTSESSIONSTATE DROP CONSTRAINT RHN_KS_SESSION_STATE_MOD_NN;
ALTER TABLE RHNKICKSTARTSESSIONSTATE MODIFY MODIFIED NOT NULL;

--
-- RHNKICKSTARTSESSIONSTATE
--
ALTER TABLE RHNKICKSTARTSESSIONSTATE DROP CONSTRAINT RHN_KS_SESSION_STATE_NAME_NN;
ALTER TABLE RHNKICKSTARTSESSIONSTATE MODIFY NAME NOT NULL;

--
-- RHNKICKSTARTTIMEZONE
--
ALTER TABLE RHNKICKSTARTTIMEZONE DROP CONSTRAINT RHN_KS_TIMEZONE_ID_NN;
ALTER TABLE RHNKICKSTARTTIMEZONE MODIFY ID NOT NULL;

--
-- RHNKICKSTARTTIMEZONE
--
ALTER TABLE RHNKICKSTARTTIMEZONE DROP CONSTRAINT RHN_KS_TIMEZONE_IT_NN;
ALTER TABLE RHNKICKSTARTTIMEZONE MODIFY INSTALL_TYPE NOT NULL;

--
-- RHNKICKSTARTTIMEZONE
--
ALTER TABLE RHNKICKSTARTTIMEZONE DROP CONSTRAINT RHN_KS_TIMEZONE_LABEL_NN;
ALTER TABLE RHNKICKSTARTTIMEZONE MODIFY LABEL NOT NULL;

--
-- RHNKICKSTARTTIMEZONE
--
ALTER TABLE RHNKICKSTARTTIMEZONE DROP CONSTRAINT RHN_KS_TIMEZONE_NAME_NN;
ALTER TABLE RHNKICKSTARTTIMEZONE MODIFY NAME NOT NULL;

--
-- RHNKSDATA
--
ALTER TABLE RHNKSDATA DROP CONSTRAINT RHN_KS_TYPE_NN;
ALTER TABLE RHNKSDATA MODIFY KS_TYPE NOT NULL;

--
-- RHNKSDATA
--
ALTER TABLE RHNKSDATA DROP CONSTRAINT RHN_KS_VERBOSE_UP2DATE_NN;
ALTER TABLE RHNKSDATA MODIFY VERBOSEUP2DATE NOT NULL;

--
-- RHNKICKSTARTVIRTUALIZATIONTYPE
--
ALTER TABLE RHNKICKSTARTVIRTUALIZATIONTYPE DROP CONSTRAINT RHN_KVT_CREATED_NN;
ALTER TABLE RHNKICKSTARTVIRTUALIZATIONTYPE MODIFY CREATED NOT NULL;

--
-- RHNKICKSTARTVIRTUALIZATIONTYPE
--
ALTER TABLE RHNKICKSTARTVIRTUALIZATIONTYPE DROP CONSTRAINT RHN_KVT_ID_NN;
ALTER TABLE RHNKICKSTARTVIRTUALIZATIONTYPE MODIFY ID NOT NULL;

--
-- RHNKICKSTARTVIRTUALIZATIONTYPE
--
ALTER TABLE RHNKICKSTARTVIRTUALIZATIONTYPE DROP CONSTRAINT RHN_KVT_LABEL_NN;
ALTER TABLE RHNKICKSTARTVIRTUALIZATIONTYPE MODIFY LABEL NOT NULL;

--
-- RHNKICKSTARTVIRTUALIZATIONTYPE
--
ALTER TABLE RHNKICKSTARTVIRTUALIZATIONTYPE DROP CONSTRAINT RHN_KVT_MODIFIED_NN;
ALTER TABLE RHNKICKSTARTVIRTUALIZATIONTYPE MODIFY MODIFIED NOT NULL;

--
-- RHNKICKSTARTVIRTUALIZATIONTYPE
--
ALTER TABLE RHNKICKSTARTVIRTUALIZATIONTYPE DROP CONSTRAINT RHN_KVT_NAME_NN;
ALTER TABLE RHNKICKSTARTVIRTUALIZATIONTYPE MODIFY NAME NOT NULL;

--
-- RHN_LL_NETSAINT
--
ALTER TABLE RHN_LL_NETSAINT DROP CONSTRAINT RHN_LLNET_NETSAINT_ID_NN;
ALTER TABLE RHN_LL_NETSAINT MODIFY NETSAINT_ID NOT NULL;

--
-- RHN_METRICS
--
ALTER TABLE RHN_METRICS DROP CONSTRAINT RHN_METRIC_CMD_CLASS_NN;
ALTER TABLE RHN_METRICS MODIFY COMMAND_CLASS NOT NULL;

--
-- RHN_METRICS
--
ALTER TABLE RHN_METRICS DROP CONSTRAINT RHN_METRIC_METRIC_ID_NN;
ALTER TABLE RHN_METRICS MODIFY METRIC_ID NOT NULL;

--
-- RHN_METRICS
--
ALTER TABLE RHN_METRICS DROP CONSTRAINT RHN_METRIC_STORAGE_ID_NN;
ALTER TABLE RHN_METRICS MODIFY STORAGE_UNIT_ID NOT NULL;

--
-- RHN_INTERFACE_MONITORING
--
ALTER TABLE RHN_INTERFACE_MONITORING DROP CONSTRAINT RHN_MONIF_SERVER_ID_NN;
ALTER TABLE RHN_INTERFACE_MONITORING MODIFY SERVER_ID NOT NULL;

--
-- RHN_INTERFACE_MONITORING
--
ALTER TABLE RHN_INTERFACE_MONITORING DROP CONSTRAINT RHN_MONIF_SERVER_NAME_NN;
ALTER TABLE RHN_INTERFACE_MONITORING MODIFY SERVER_NAME NOT NULL;

--
-- RHNMONITORGRANULARITY
--
ALTER TABLE RHNMONITORGRANULARITY DROP CONSTRAINT RHN_MONITORGRAN_ID_NN;
ALTER TABLE RHNMONITORGRANULARITY MODIFY ID NOT NULL;

--
-- RHNMONITORGRANULARITY
--
ALTER TABLE RHNMONITORGRANULARITY DROP CONSTRAINT RHN_MONITORGRAN_LABEL_NN;
ALTER TABLE RHNMONITORGRANULARITY MODIFY LABEL NOT NULL;

--
-- RHNMONITOR
--
ALTER TABLE RHNMONITOR DROP CONSTRAINT RHN_MONITOR_BID_NN;
ALTER TABLE RHNMONITOR MODIFY BATCH_ID NOT NULL;

--
-- RHNMONITOR
--
ALTER TABLE RHNMONITOR DROP CONSTRAINT RHN_MONITOR_GRANULARITY_NN;
ALTER TABLE RHNMONITOR MODIFY GRANULARITY NOT NULL;

--
-- RHNMONITOR
--
ALTER TABLE RHNMONITOR DROP CONSTRAINT RHN_MONITOR_PROBE_NN;
ALTER TABLE RHNMONITOR MODIFY PROBE_ID NOT NULL;

--
-- RHNMONITOR
--
ALTER TABLE RHNMONITOR DROP CONSTRAINT RHN_MONITOR_SID_NN;
ALTER TABLE RHNMONITOR MODIFY SERVER_ID NOT NULL;

--
-- RHNMONITOR
--
ALTER TABLE RHNMONITOR DROP CONSTRAINT RHN_MONITOR_TS_NN;
ALTER TABLE RHNMONITOR MODIFY TIMESTAMP NOT NULL;

--
-- RHN_MULTI_SCOUT_THRESHOLD
--
ALTER TABLE RHN_MULTI_SCOUT_THRESHOLD DROP CONSTRAINT RHN_MSTHR_PROBE_ID_NN;
ALTER TABLE RHN_MULTI_SCOUT_THRESHOLD MODIFY PROBE_ID NOT NULL;

--
-- RHN_METHOD_TYPES
--
ALTER TABLE RHN_METHOD_TYPES DROP CONSTRAINT RHN_MTHTP_NOTIF_FMT_NN;
ALTER TABLE RHN_METHOD_TYPES MODIFY NOTIFICATION_FORMAT_ID NOT NULL;

--
-- RHN_METHOD_TYPES
--
ALTER TABLE RHN_METHOD_TYPES DROP CONSTRAINT RHN_MTHTP_RECID_NN;
ALTER TABLE RHN_METHOD_TYPES MODIFY RECID NOT NULL;

--
-- RHNMESSAGE
--
ALTER TABLE RHNMESSAGE DROP CONSTRAINT RHN_M_CREATED_NN;
ALTER TABLE RHNMESSAGE MODIFY CREATED NOT NULL;

--
-- RHNMESSAGE
--
ALTER TABLE RHNMESSAGE DROP CONSTRAINT RHN_M_ID_NN;
ALTER TABLE RHNMESSAGE MODIFY ID NOT NULL;

--
-- RHNMESSAGE
--
ALTER TABLE RHNMESSAGE DROP CONSTRAINT RHN_M_MODIFIED_NN;
ALTER TABLE RHNMESSAGE MODIFY MODIFIED NOT NULL;

--
-- RHNMESSAGE
--
ALTER TABLE RHNMESSAGE DROP CONSTRAINT RHN_M_MT_NN;
ALTER TABLE RHNMESSAGE MODIFY MESSAGE_TYPE NOT NULL;

--
-- RHNMESSAGEPRIORITY
--
ALTER TABLE RHNMESSAGEPRIORITY DROP CONSTRAINT RHN_M_PRIORITY_ID_NN;
ALTER TABLE RHNMESSAGEPRIORITY MODIFY ID NOT NULL;

--
-- RHNMESSAGEPRIORITY
--
ALTER TABLE RHNMESSAGEPRIORITY DROP CONSTRAINT RHN_M_PRIORITY_LABEL_NN;
ALTER TABLE RHNMESSAGEPRIORITY MODIFY LABEL NOT NULL;

--
-- RHNMESSAGE
--
ALTER TABLE RHNMESSAGE DROP CONSTRAINT RHN_M_PRIORITY_NN;
ALTER TABLE RHNMESSAGE MODIFY PRIORITY NOT NULL;

--
-- RHNMESSAGETYPE
--
ALTER TABLE RHNMESSAGETYPE DROP CONSTRAINT RHN_M_TYPE_ID_NN;
ALTER TABLE RHNMESSAGETYPE MODIFY ID NOT NULL;

--
-- RHNMESSAGETYPE
--
ALTER TABLE RHNMESSAGETYPE DROP CONSTRAINT RHN_M_TYPE_LABEL_NN;
ALTER TABLE RHNMESSAGETYPE MODIFY LABEL NOT NULL;

--
-- RHNMESSAGETYPE
--
ALTER TABLE RHNMESSAGETYPE DROP CONSTRAINT RHN_M_TYPE_NAME_NN;
ALTER TABLE RHNMESSAGETYPE MODIFY NAME NOT NULL;

--
-- RHN_NOTIFSERVERS
--
ALTER TABLE RHN_NOTIFSERVERS DROP CONSTRAINT RHN_NOTSV_RECID_NN;
ALTER TABLE RHN_NOTIFSERVERS MODIFY RECID NOT NULL;

--
-- RHN_NOTIFICATION_FORMATS
--
ALTER TABLE RHN_NOTIFICATION_FORMATS DROP CONSTRAINT RHN_NTFMT_BODY_FMT_NN;
ALTER TABLE RHN_NOTIFICATION_FORMATS MODIFY BODY_FORMAT NOT NULL;

--
-- RHN_NOTIFICATION_FORMATS
--
ALTER TABLE RHN_NOTIFICATION_FORMATS DROP CONSTRAINT RHN_NTFMT_DESC_NN;
ALTER TABLE RHN_NOTIFICATION_FORMATS MODIFY DESCRIPTION NOT NULL;

--
-- RHN_NOTIFICATION_FORMATS
--
ALTER TABLE RHN_NOTIFICATION_FORMATS DROP CONSTRAINT RHN_NTFMT_MAX_BODY_NN;
ALTER TABLE RHN_NOTIFICATION_FORMATS MODIFY MAX_BODY_LENGTH NOT NULL;

--
-- RHN_NOTIFICATION_FORMATS
--
ALTER TABLE RHN_NOTIFICATION_FORMATS DROP CONSTRAINT RHN_NTFMT_RECID_NN;
ALTER TABLE RHN_NOTIFICATION_FORMATS MODIFY RECID NOT NULL;

--
-- RHNORGCHANNELSETTINGSTYPE
--
ALTER TABLE RHNORGCHANNELSETTINGSTYPE DROP CONSTRAINT RHN_OCSTNGS_TYPE_CREATED_NN;
ALTER TABLE RHNORGCHANNELSETTINGSTYPE MODIFY CREATED NOT NULL;

--
-- RHNORGCHANNELSETTINGSTYPE
--
ALTER TABLE RHNORGCHANNELSETTINGSTYPE DROP CONSTRAINT RHN_OCSTNGS_TYPE_ID_NN;
ALTER TABLE RHNORGCHANNELSETTINGSTYPE MODIFY ID NOT NULL;

--
-- RHNORGCHANNELSETTINGSTYPE
--
ALTER TABLE RHNORGCHANNELSETTINGSTYPE DROP CONSTRAINT RHN_OCSTNGS_TYPE_LABEL_NN;
ALTER TABLE RHNORGCHANNELSETTINGSTYPE MODIFY LABEL NOT NULL;

--
-- RHNORGCHANNELSETTINGSTYPE
--
ALTER TABLE RHNORGCHANNELSETTINGSTYPE DROP CONSTRAINT RHN_OCSTNGS_TYPE_MODIFIED_NN;
ALTER TABLE RHNORGCHANNELSETTINGSTYPE MODIFY MODIFIED NOT NULL;

--
-- RHNORGERRATACACHEQUEUE
--
ALTER TABLE RHNORGERRATACACHEQUEUE DROP CONSTRAINT RHN_OECQ_OID_NN;
ALTER TABLE RHNORGERRATACACHEQUEUE MODIFY ORG_ID NOT NULL;

--
-- RHNORGERRATACACHEQUEUE
--
ALTER TABLE RHNORGERRATACACHEQUEUE DROP CONSTRAINT RHN_OECQ_OID_PROCESSED_NN;
ALTER TABLE RHNORGERRATACACHEQUEUE MODIFY PROCESSED NOT NULL;

--
-- RHNORGERRATACACHEQUEUE
--
ALTER TABLE RHNORGERRATACACHEQUEUE DROP CONSTRAINT RHN_OECQ_SC_NN;
ALTER TABLE RHNORGERRATACACHEQUEUE MODIFY SERVER_COUNT NOT NULL;

--
-- RHNORGCHANNELSETTINGS
--
ALTER TABLE RHNORGCHANNELSETTINGS DROP CONSTRAINT RHN_ORGCSETTINGS_CID_NN;
ALTER TABLE RHNORGCHANNELSETTINGS MODIFY CHANNEL_ID NOT NULL;

--
-- RHNORGCHANNELSETTINGS
--
ALTER TABLE RHNORGCHANNELSETTINGS DROP CONSTRAINT RHN_ORGCSETTINGS_CREATED_NN;
ALTER TABLE RHNORGCHANNELSETTINGS MODIFY CREATED NOT NULL;

--
-- RHNORGCHANNELSETTINGS
--
ALTER TABLE RHNORGCHANNELSETTINGS DROP CONSTRAINT RHN_ORGCSETTINGS_MODIFIED_NN;
ALTER TABLE RHNORGCHANNELSETTINGS MODIFY MODIFIED NOT NULL;

--
-- RHNORGCHANNELSETTINGS
--
ALTER TABLE RHNORGCHANNELSETTINGS DROP CONSTRAINT RHN_ORGCSETTINGS_OID_NN;
ALTER TABLE RHNORGCHANNELSETTINGS MODIFY ORG_ID NOT NULL;

--
-- RHNORGCHANNELSETTINGS
--
ALTER TABLE RHNORGCHANNELSETTINGS DROP CONSTRAINT RHN_ORGCSETTINGS_SID_NN;
ALTER TABLE RHNORGCHANNELSETTINGS MODIFY SETTING_ID NOT NULL;

--
-- RHNORGINFO
--
ALTER TABLE RHNORGINFO DROP CONSTRAINT RHN_ORGINFO_CREATED_NN;
ALTER TABLE RHNORGINFO MODIFY CREATED NOT NULL;

--
-- RHNORGINFO
--
ALTER TABLE RHNORGINFO DROP CONSTRAINT RHN_ORGINFO_DGT_NN;
ALTER TABLE RHNORGINFO MODIFY DEFAULT_GROUP_TYPE NOT NULL;

--
-- RHNORGINFO
--
ALTER TABLE RHNORGINFO DROP CONSTRAINT RHN_ORGINFO_MODIFIED_NN;
ALTER TABLE RHNORGINFO MODIFY MODIFIED NOT NULL;

--
-- RHNORGINFO
--
ALTER TABLE RHNORGINFO DROP CONSTRAINT RHN_ORGINFO_OID_NN;
ALTER TABLE RHNORGINFO MODIFY ORG_ID NOT NULL;

--
-- RHNORGQUOTA
--
ALTER TABLE RHNORGQUOTA DROP CONSTRAINT RHN_ORGQUOTA_BONUS_NN;
ALTER TABLE RHNORGQUOTA MODIFY BONUS NOT NULL;

--
-- RHNORGQUOTA
--
ALTER TABLE RHNORGQUOTA DROP CONSTRAINT RHN_ORGQUOTA_CREAT_NN;
ALTER TABLE RHNORGQUOTA MODIFY CREATED NOT NULL;

--
-- RHNORGQUOTA
--
ALTER TABLE RHNORGQUOTA DROP CONSTRAINT RHN_ORGQUOTA_MOD_NN;
ALTER TABLE RHNORGQUOTA MODIFY MODIFIED NOT NULL;

--
-- RHNORGQUOTA
--
ALTER TABLE RHNORGQUOTA DROP CONSTRAINT RHN_ORGQUOTA_OID_NN;
ALTER TABLE RHNORGQUOTA MODIFY ORG_ID NOT NULL;

--
-- RHNORGQUOTA
--
ALTER TABLE RHNORGQUOTA DROP CONSTRAINT RHN_ORGQUOTA_TOTAL_NN;
ALTER TABLE RHNORGQUOTA MODIFY TOTAL NOT NULL;

--
-- RHNORGQUOTA
--
ALTER TABLE RHNORGQUOTA DROP CONSTRAINT RHN_ORGQUOTA_USED_NN;
ALTER TABLE RHNORGQUOTA MODIFY USED NOT NULL;

--
-- RHNORGENTITLEMENTS
--
ALTER TABLE RHNORGENTITLEMENTS DROP CONSTRAINT RHN_ORG_ENT_CRE_NN;
ALTER TABLE RHNORGENTITLEMENTS MODIFY CREATED NOT NULL;

--
-- RHNORGENTITLEMENTS
--
ALTER TABLE RHNORGENTITLEMENTS DROP CONSTRAINT RHN_ORG_ENT_EID_NN;
ALTER TABLE RHNORGENTITLEMENTS MODIFY ENTITLEMENT_ID NOT NULL;

--
-- RHNORGENTITLEMENTS
--
ALTER TABLE RHNORGENTITLEMENTS DROP CONSTRAINT RHN_ORG_ENT_MOD_NN;
ALTER TABLE RHNORGENTITLEMENTS MODIFY MODIFIED NOT NULL;

--
-- RHNORGENTITLEMENTS
--
ALTER TABLE RHNORGENTITLEMENTS DROP CONSTRAINT RHN_ORG_ENT_NN;
ALTER TABLE RHNORGENTITLEMENTS MODIFY ORG_ID NOT NULL;

--
-- RHNORGENTITLEMENTTYPE
--
ALTER TABLE RHNORGENTITLEMENTTYPE DROP CONSTRAINT RHN_ORG_ENT_TYPE_CREATED_NN;
ALTER TABLE RHNORGENTITLEMENTTYPE MODIFY CREATED NOT NULL;

--
-- RHNORGENTITLEMENTTYPE
--
ALTER TABLE RHNORGENTITLEMENTTYPE DROP CONSTRAINT RHN_ORG_ENT_TYPE_ID_NN;
ALTER TABLE RHNORGENTITLEMENTTYPE MODIFY ID NOT NULL;

--
-- RHNORGENTITLEMENTTYPE
--
ALTER TABLE RHNORGENTITLEMENTTYPE DROP CONSTRAINT RHN_ORG_ENT_TYPE_LABEL_NN;
ALTER TABLE RHNORGENTITLEMENTTYPE MODIFY LABEL NOT NULL;

--
-- RHNORGENTITLEMENTTYPE
--
ALTER TABLE RHNORGENTITLEMENTTYPE DROP CONSTRAINT RHN_ORG_ENT_TYPE_MOD_NN;
ALTER TABLE RHNORGENTITLEMENTTYPE MODIFY MODIFIED NOT NULL;

--
-- RHNORGENTITLEMENTTYPE
--
ALTER TABLE RHNORGENTITLEMENTTYPE DROP CONSTRAINT RHN_ORG_ENT_TYPE_NAME_NN;
ALTER TABLE RHNORGENTITLEMENTTYPE MODIFY NAME NOT NULL;

--
-- RHN_OS
--
ALTER TABLE RHN_OS DROP CONSTRAINT RHN_OS000_RECID_NN;
ALTER TABLE RHN_OS MODIFY RECID NOT NULL;

--
-- RHN_OS_COMMANDS_XREF
--
ALTER TABLE RHN_OS_COMMANDS_XREF DROP CONSTRAINT RHN_OSCXR_COMMANDS_ID_NN;
ALTER TABLE RHN_OS_COMMANDS_XREF MODIFY COMMANDS_ID NOT NULL;

--
-- RHN_OS_COMMANDS_XREF
--
ALTER TABLE RHN_OS_COMMANDS_XREF DROP CONSTRAINT RHN_OSCXR_OS_ID_NN;
ALTER TABLE RHN_OS_COMMANDS_XREF MODIFY OS_ID NOT NULL;

--
-- RHNPACKAGEDELTA
--
ALTER TABLE RHNPACKAGEDELTA DROP CONSTRAINT RHN_PACKAGEDELTA_CREATED_NN;
ALTER TABLE RHNPACKAGEDELTA MODIFY CREATED NOT NULL;

--
-- RHNPACKAGEDELTA
--
ALTER TABLE RHNPACKAGEDELTA DROP CONSTRAINT RHN_PACKAGEDELTA_ID_NN;
ALTER TABLE RHNPACKAGEDELTA MODIFY ID NOT NULL;

--
-- RHNPACKAGEDELTA
--
ALTER TABLE RHNPACKAGEDELTA DROP CONSTRAINT RHN_PACKAGEDELTA_LABEL_NN;
ALTER TABLE RHNPACKAGEDELTA MODIFY LABEL NOT NULL;

--
-- RHNPACKAGEDELTA
--
ALTER TABLE RHNPACKAGEDELTA DROP CONSTRAINT RHN_PACKAGEDELTA_MODIFIED_NN;
ALTER TABLE RHNPACKAGEDELTA MODIFY MODIFIED NOT NULL;

--
-- RHNPACKAGESYNCBLACKLIST
--
ALTER TABLE RHNPACKAGESYNCBLACKLIST DROP CONSTRAINT RHN_PACKAGESYNCBL_CREAT_NN;
ALTER TABLE RHNPACKAGESYNCBLACKLIST MODIFY CREATED NOT NULL;

--
-- RHNPACKAGESYNCBLACKLIST
--
ALTER TABLE RHNPACKAGESYNCBLACKLIST DROP CONSTRAINT RHN_PACKAGESYNCBL_MOD_NN;
ALTER TABLE RHNPACKAGESYNCBLACKLIST MODIFY MODIFIED NOT NULL;

--
-- RHNPACKAGESYNCBLACKLIST
--
ALTER TABLE RHNPACKAGESYNCBLACKLIST DROP CONSTRAINT RHN_PACKAGESYNCBL_PNID_NN;
ALTER TABLE RHNPACKAGESYNCBLACKLIST MODIFY PACKAGE_NAME_ID NOT NULL;

--
-- RHNPACKAGE
--
ALTER TABLE RHNPACKAGE DROP CONSTRAINT RHN_PACKAGE_CREATED_NN;
ALTER TABLE RHNPACKAGE MODIFY CREATED NOT NULL;

--
-- RHNPACKAGE
--
ALTER TABLE RHNPACKAGE DROP CONSTRAINT RHN_PACKAGE_EID_NN;
ALTER TABLE RHNPACKAGE MODIFY EVR_ID NOT NULL;

--
-- RHNPACKAGEFILE
--
ALTER TABLE RHNPACKAGEFILE DROP CONSTRAINT RHN_PACKAGE_FILE_CID_NN;
ALTER TABLE RHNPACKAGEFILE MODIFY CAPABILITY_ID NOT NULL;

--
-- RHNPACKAGEFILE
--
ALTER TABLE RHNPACKAGEFILE DROP CONSTRAINT RHN_PACKAGE_FILE_CREATED_NN;
ALTER TABLE RHNPACKAGEFILE MODIFY CREATED NOT NULL;

--
-- RHNPACKAGEFILE
--
ALTER TABLE RHNPACKAGEFILE DROP CONSTRAINT RHN_PACKAGE_FILE_DEVICES_NN;
ALTER TABLE RHNPACKAGEFILE MODIFY DEVICE NOT NULL;

--
-- RHNPACKAGEFILE
--
ALTER TABLE RHNPACKAGEFILE DROP CONSTRAINT RHN_PACKAGE_FILE_DEV_NN;
ALTER TABLE RHNPACKAGEFILE MODIFY RDEV NOT NULL;

--
-- RHNPACKAGEFILE
--
ALTER TABLE RHNPACKAGEFILE DROP CONSTRAINT RHN_PACKAGE_FILE_FLAGS_NN;
ALTER TABLE RHNPACKAGEFILE MODIFY FLAGS NOT NULL;

--
-- RHNPACKAGEFILE
--
ALTER TABLE RHNPACKAGEFILE DROP CONSTRAINT RHN_PACKAGE_FILE_GROUPNAME_NN;
ALTER TABLE RHNPACKAGEFILE MODIFY GROUPNAME NOT NULL;

--
-- RHNPACKAGEFILE
--
ALTER TABLE RHNPACKAGEFILE DROP CONSTRAINT RHN_PACKAGE_FILE_INODE_NN;
ALTER TABLE RHNPACKAGEFILE MODIFY INODE NOT NULL;

--
-- RHNPACKAGEFILE
--
ALTER TABLE RHNPACKAGEFILE DROP CONSTRAINT RHN_PACKAGE_FILE_MODE_NN;
ALTER TABLE RHNPACKAGEFILE MODIFY FILE_MODE NOT NULL;

--
-- RHNPACKAGEFILE
--
ALTER TABLE RHNPACKAGEFILE DROP CONSTRAINT RHN_PACKAGE_FILE_MODIFIED_NN;
ALTER TABLE RHNPACKAGEFILE MODIFY MODIFIED NOT NULL;

--
-- RHNPACKAGEFILE
--
ALTER TABLE RHNPACKAGEFILE DROP CONSTRAINT RHN_PACKAGE_FILE_MTIME_NN;
ALTER TABLE RHNPACKAGEFILE MODIFY MTIME NOT NULL;

--
-- RHNPACKAGEFILE
--
ALTER TABLE RHNPACKAGEFILE DROP CONSTRAINT RHN_PACKAGE_FILE_PID_NN;
ALTER TABLE RHNPACKAGEFILE MODIFY PACKAGE_ID NOT NULL;

--
-- RHNPACKAGEFILE
--
ALTER TABLE RHNPACKAGEFILE DROP CONSTRAINT RHN_PACKAGE_FILE_SIZE_NN;
ALTER TABLE RHNPACKAGEFILE MODIFY FILE_SIZE NOT NULL;

--
-- RHNPACKAGEFILE
--
ALTER TABLE RHNPACKAGEFILE DROP CONSTRAINT RHN_PACKAGE_FILE_USERNAME_NN;
ALTER TABLE RHNPACKAGEFILE MODIFY USERNAME NOT NULL;

--
-- RHNPACKAGEFILE
--
ALTER TABLE RHNPACKAGEFILE DROP CONSTRAINT RHN_PACKAGE_FILE_VERIFY_NN;
ALTER TABLE RHNPACKAGEFILE MODIFY VERIFYFLAGS NOT NULL;

--
-- RHNPACKAGEGROUP
--
ALTER TABLE RHNPACKAGEGROUP DROP CONSTRAINT RHN_PACKAGE_GROUP_CREATED_NN;
ALTER TABLE RHNPACKAGEGROUP MODIFY CREATED NOT NULL;

--
-- RHNPACKAGEGROUP
--
ALTER TABLE RHNPACKAGEGROUP DROP CONSTRAINT RHN_PACKAGE_GROUP_ID_NN;
ALTER TABLE RHNPACKAGEGROUP MODIFY ID NOT NULL;

--
-- RHNPACKAGEGROUP
--
ALTER TABLE RHNPACKAGEGROUP DROP CONSTRAINT RHN_PACKAGE_GROUP_MODIFIED_NN;
ALTER TABLE RHNPACKAGEGROUP MODIFY MODIFIED NOT NULL;

--
-- RHNPACKAGEGROUP
--
ALTER TABLE RHNPACKAGEGROUP DROP CONSTRAINT RHN_PACKAGE_GROUP_NAME_NN;
ALTER TABLE RHNPACKAGEGROUP MODIFY NAME NOT NULL;

--
-- RHNPACKAGE
--
ALTER TABLE RHNPACKAGE DROP CONSTRAINT RHN_PACKAGE_HE_NN;
ALTER TABLE RHNPACKAGE MODIFY HEADER_END NOT NULL;

--
-- RHNPACKAGE
--
ALTER TABLE RHNPACKAGE DROP CONSTRAINT RHN_PACKAGE_HS_NN;
ALTER TABLE RHNPACKAGE MODIFY HEADER_START NOT NULL;

--
-- RHNPACKAGE
--
ALTER TABLE RHNPACKAGE DROP CONSTRAINT RHN_PACKAGE_ID_NN;
ALTER TABLE RHNPACKAGE MODIFY ID NOT NULL;

--
-- RHNPACKAGE
--
ALTER TABLE RHNPACKAGE DROP CONSTRAINT RHN_PACKAGE_LM_NN;
ALTER TABLE RHNPACKAGE MODIFY LAST_MODIFIED NOT NULL;

--
-- RHNPACKAGE
--
ALTER TABLE RHNPACKAGE DROP CONSTRAINT RHN_PACKAGE_MD5_NN;
ALTER TABLE RHNPACKAGE MODIFY MD5SUM NOT NULL;

--
-- RHNPACKAGE
--
ALTER TABLE RHNPACKAGE DROP CONSTRAINT RHN_PACKAGE_MODIFIED_NN;
ALTER TABLE RHNPACKAGE MODIFY MODIFIED NOT NULL;

--
-- RHNPACKAGE
--
ALTER TABLE RHNPACKAGE DROP CONSTRAINT RHN_PACKAGE_NID_NN;
ALTER TABLE RHNPACKAGE MODIFY NAME_ID NOT NULL;

--
-- RHNPACKAGE
--
ALTER TABLE RHNPACKAGE DROP CONSTRAINT RHN_PACKAGE_PAID_NN;
ALTER TABLE RHNPACKAGE MODIFY PACKAGE_ARCH_ID NOT NULL;

--
-- RHNPACKAGE
--
ALTER TABLE RHNPACKAGE DROP CONSTRAINT RHN_PACKAGE_PKG_SIZE_NN;
ALTER TABLE RHNPACKAGE MODIFY PACKAGE_SIZE NOT NULL;

--
-- RHNPACKAGESOURCE
--
ALTER TABLE RHNPACKAGESOURCE DROP CONSTRAINT RHN_PACKAGE_SIGMD5_NN;
ALTER TABLE RHNPACKAGESOURCE MODIFY SIGMD5 NOT NULL;

--
-- RHNPACKAGE
--
ALTER TABLE RHNPACKAGE DROP CONSTRAINT RHN_PACKAGE_VENDOR_NN;
ALTER TABLE RHNPACKAGE MODIFY VENDOR NOT NULL;

--
-- RHNPACKAGEARCH
--
ALTER TABLE RHNPACKAGEARCH DROP CONSTRAINT RHN_PARCH_ATID_NN;
ALTER TABLE RHNPACKAGEARCH MODIFY ARCH_TYPE_ID NOT NULL;

--
-- RHNPACKAGEARCH
--
ALTER TABLE RHNPACKAGEARCH DROP CONSTRAINT RHN_PARCH_CREATED_NN;
ALTER TABLE RHNPACKAGEARCH MODIFY CREATED NOT NULL;

--
-- RHNPACKAGEARCH
--
ALTER TABLE RHNPACKAGEARCH DROP CONSTRAINT RHN_PARCH_ID_NN;
ALTER TABLE RHNPACKAGEARCH MODIFY ID NOT NULL;

--
-- RHNPACKAGEARCH
--
ALTER TABLE RHNPACKAGEARCH DROP CONSTRAINT RHN_PARCH_LABEL_NN;
ALTER TABLE RHNPACKAGEARCH MODIFY LABEL NOT NULL;

--
-- RHNPACKAGEARCH
--
ALTER TABLE RHNPACKAGEARCH DROP CONSTRAINT RHN_PARCH_MODIFIED_NN;
ALTER TABLE RHNPACKAGEARCH MODIFY MODIFIED NOT NULL;

--
-- RHNPACKAGEARCH
--
ALTER TABLE RHNPACKAGEARCH DROP CONSTRAINT RHN_PARCH_NAME_NN;
ALTER TABLE RHNPACKAGEARCH MODIFY NAME NOT NULL;

--
-- RHNPATHCHANNELMAP
--
ALTER TABLE RHNPATHCHANNELMAP DROP CONSTRAINT RHN_PATH_CHANNEL_MAP_CID_NN;
ALTER TABLE RHNPATHCHANNELMAP MODIFY CHANNEL_ID NOT NULL;

--
-- RHNPATHCHANNELMAP
--
ALTER TABLE RHNPATHCHANNELMAP DROP CONSTRAINT RHN_PATH_CHANNEL_MAP_P_NN;
ALTER TABLE RHNPATHCHANNELMAP MODIFY PATH NOT NULL;

--
-- RHNPUSHCLIENT
--
ALTER TABLE RHNPUSHCLIENT DROP CONSTRAINT RHN_PCLIENT_CREATED_NN;
ALTER TABLE RHNPUSHCLIENT MODIFY CREATED NOT NULL;

--
-- RHNPUSHCLIENT
--
ALTER TABLE RHNPUSHCLIENT DROP CONSTRAINT RHN_PCLIENT_ID_NN;
ALTER TABLE RHNPUSHCLIENT MODIFY ID NOT NULL;

--
-- RHNPUSHCLIENT
--
ALTER TABLE RHNPUSHCLIENT DROP CONSTRAINT RHN_PCLIENT_MODIFIED_NN;
ALTER TABLE RHNPUSHCLIENT MODIFY MODIFIED NOT NULL;

--
-- RHNPUSHCLIENT
--
ALTER TABLE RHNPUSHCLIENT DROP CONSTRAINT RHN_PCLIENT_NAME_NN;
ALTER TABLE RHNPUSHCLIENT MODIFY NAME NOT NULL;

--
-- RHNPUSHCLIENT
--
ALTER TABLE RHNPUSHCLIENT DROP CONSTRAINT RHN_PCLIENT_SID_NN;
ALTER TABLE RHNPUSHCLIENT MODIFY SERVER_ID NOT NULL;

--
-- RHNPUSHCLIENT
--
ALTER TABLE RHNPUSHCLIENT DROP CONSTRAINT RHN_PCLIENT_SKEY_NN;
ALTER TABLE RHNPUSHCLIENT MODIFY SHARED_KEY NOT NULL;

--
-- RHNPUSHCLIENTSTATE
--
ALTER TABLE RHNPUSHCLIENTSTATE DROP CONSTRAINT RHN_PCLIENT_STATE_CREATED_NN;
ALTER TABLE RHNPUSHCLIENTSTATE MODIFY CREATED NOT NULL;

--
-- RHNPUSHCLIENTSTATE
--
ALTER TABLE RHNPUSHCLIENTSTATE DROP CONSTRAINT RHN_PCLIENT_STATE_ID_NN;
ALTER TABLE RHNPUSHCLIENTSTATE MODIFY ID NOT NULL;

--
-- RHNPUSHCLIENTSTATE
--
ALTER TABLE RHNPUSHCLIENTSTATE DROP CONSTRAINT RHN_PCLIENT_STATE_LABEL_NN;
ALTER TABLE RHNPUSHCLIENTSTATE MODIFY LABEL NOT NULL;

--
-- RHNPUSHCLIENTSTATE
--
ALTER TABLE RHNPUSHCLIENTSTATE DROP CONSTRAINT RHN_PCLIENT_STATE_MODIFIED_NN;
ALTER TABLE RHNPUSHCLIENTSTATE MODIFY MODIFIED NOT NULL;

--
-- RHNPUSHCLIENTSTATE
--
ALTER TABLE RHNPUSHCLIENTSTATE DROP CONSTRAINT RHN_PCLIENT_STATE_NAME_NN;
ALTER TABLE RHNPUSHCLIENTSTATE MODIFY NAME NOT NULL;

--
-- RHNPUSHCLIENT
--
ALTER TABLE RHNPUSHCLIENT DROP CONSTRAINT RHN_PCLIENT_STID_NN;
ALTER TABLE RHNPUSHCLIENT MODIFY STATE_ID NOT NULL;

--
-- RHNPRODUCTCHANNEL
--
ALTER TABLE RHNPRODUCTCHANNEL DROP CONSTRAINT RHN_PC_CID_NN;
ALTER TABLE RHNPRODUCTCHANNEL MODIFY CHANNEL_ID NOT NULL;

--
-- RHNPRODUCTCHANNEL
--
ALTER TABLE RHNPRODUCTCHANNEL DROP CONSTRAINT RHN_PC_CREATED_NN;
ALTER TABLE RHNPRODUCTCHANNEL MODIFY CREATED NOT NULL;

--
-- RHNPRODUCTCHANNEL
--
ALTER TABLE RHNPRODUCTCHANNEL DROP CONSTRAINT RHN_PC_MODIFIED_NN;
ALTER TABLE RHNPRODUCTCHANNEL MODIFY MODIFIED NOT NULL;

--
-- RHNPRODUCTCHANNEL
--
ALTER TABLE RHNPRODUCTCHANNEL DROP CONSTRAINT RHN_PC_PID_NN;
ALTER TABLE RHNPRODUCTCHANNEL MODIFY PRODUCT_ID NOT NULL;

--
-- RHNPACKAGEDELTAELEMENT
--
ALTER TABLE RHNPACKAGEDELTAELEMENT DROP CONSTRAINT RHN_PDELEMENT_PDID_NN;
ALTER TABLE RHNPACKAGEDELTAELEMENT MODIFY PACKAGE_DELTA_ID NOT NULL;

--
-- RHNPACKAGEDELTAELEMENT
--
ALTER TABLE RHNPACKAGEDELTAELEMENT DROP CONSTRAINT RHN_PDELEMENT_TPID_NN;
ALTER TABLE RHNPACKAGEDELTAELEMENT MODIFY TRANSACTION_PACKAGE_ID NOT NULL;

--
-- RHNPACKAGEEVR
--
ALTER TABLE RHNPACKAGEEVR DROP CONSTRAINT RHN_PE_ID_NN;
ALTER TABLE RHNPACKAGEEVR MODIFY ID NOT NULL;

--
-- RHNPACKAGEEVR
--
ALTER TABLE RHNPACKAGEEVR DROP CONSTRAINT RHN_PE_RELEASE_NN;
ALTER TABLE RHNPACKAGEEVR MODIFY RELEASE NOT NULL;

--
-- RHNPACKAGEEVR
--
ALTER TABLE RHNPACKAGEEVR DROP CONSTRAINT RHN_PE_VERSION_NN;
ALTER TABLE RHNPACKAGEEVR MODIFY VERSION NOT NULL;

--
-- RHNPACKAGEFILEDELETEQUEUE
--
ALTER TABLE RHNPACKAGEFILEDELETEQUEUE DROP CONSTRAINT RHN_PFDQUEUE_CREATED_NN;
ALTER TABLE RHNPACKAGEFILEDELETEQUEUE MODIFY CREATED NOT NULL;

--
-- RHN_PAGER_TYPES
--
ALTER TABLE RHN_PAGER_TYPES DROP CONSTRAINT RHN_PGRTP_RECID_NN;
ALTER TABLE RHN_PAGER_TYPES MODIFY RECID NOT NULL;

--
-- RHN_PHYSICAL_LOCATION
--
ALTER TABLE RHN_PHYSICAL_LOCATION DROP CONSTRAINT RHN_PHSLC_CUST_ID_NN;
ALTER TABLE RHN_PHYSICAL_LOCATION MODIFY CUSTOMER_ID NOT NULL;

--
-- RHN_PHYSICAL_LOCATION
--
ALTER TABLE RHN_PHYSICAL_LOCATION DROP CONSTRAINT RHN_PHSLC_RECID_NN;
ALTER TABLE RHN_PHYSICAL_LOCATION MODIFY RECID NOT NULL;

--
-- RHNPACKAGEKEYASSOCIATION
--
ALTER TABLE RHNPACKAGEKEYASSOCIATION DROP CONSTRAINT RHN_PKEYA_CREATED_NN;
ALTER TABLE RHNPACKAGEKEYASSOCIATION MODIFY CREATED NOT NULL;

--
-- RHNPACKAGEKEYASSOCIATION
--
ALTER TABLE RHNPACKAGEKEYASSOCIATION DROP CONSTRAINT RHN_PKEYA_KID_NN;
ALTER TABLE RHNPACKAGEKEYASSOCIATION MODIFY KEY_ID NOT NULL;

--
-- RHNPACKAGEKEYASSOCIATION
--
ALTER TABLE RHNPACKAGEKEYASSOCIATION DROP CONSTRAINT RHN_PKEYA_MODIFIED_NN;
ALTER TABLE RHNPACKAGEKEYASSOCIATION MODIFY MODIFIED NOT NULL;

--
-- RHNPACKAGEKEYASSOCIATION
--
ALTER TABLE RHNPACKAGEKEYASSOCIATION DROP CONSTRAINT RHN_PKEYA_PID_NN;
ALTER TABLE RHNPACKAGEKEYASSOCIATION MODIFY PACKAGE_ID NOT NULL;

--
-- RHNPACKAGEKEY
--
ALTER TABLE RHNPACKAGEKEY DROP CONSTRAINT RHN_PKEY_CREATED_NN;
ALTER TABLE RHNPACKAGEKEY MODIFY CREATED NOT NULL;

--
-- RHNPACKAGEKEY
--
ALTER TABLE RHNPACKAGEKEY DROP CONSTRAINT RHN_PKEY_ID_NN;
ALTER TABLE RHNPACKAGEKEY MODIFY ID NOT NULL;

--
-- RHNPACKAGEKEY
--
ALTER TABLE RHNPACKAGEKEY DROP CONSTRAINT RHN_PKEY_KEY_NN;
ALTER TABLE RHNPACKAGEKEY MODIFY KEY_ID NOT NULL;

--
-- RHNPACKAGEKEY
--
ALTER TABLE RHNPACKAGEKEY DROP CONSTRAINT RHN_PKEY_MODIFIED_NN;
ALTER TABLE RHNPACKAGEKEY MODIFY MODIFIED NOT NULL;

--
-- RHNPACKAGEKEY
--
ALTER TABLE RHNPACKAGEKEY DROP CONSTRAINT RHN_PKEY_TYPE_ID_NN;
ALTER TABLE RHNPACKAGEKEY MODIFY KEY_TYPE_ID NOT NULL;

--
-- RHNPACKAGENEVRA
--
ALTER TABLE RHNPACKAGENEVRA DROP CONSTRAINT RHN_PKGNEVRA_EID_NN;
ALTER TABLE RHNPACKAGENEVRA MODIFY EVR_ID NOT NULL;

--
-- RHNPACKAGENEVRA
--
ALTER TABLE RHNPACKAGENEVRA DROP CONSTRAINT RHN_PKGNEVRA_ID_NN;
ALTER TABLE RHNPACKAGENEVRA MODIFY ID NOT NULL;

--
-- RHNPACKAGENEVRA
--
ALTER TABLE RHNPACKAGENEVRA DROP CONSTRAINT RHN_PKGNEVRA_NID_NN;
ALTER TABLE RHNPACKAGENEVRA MODIFY NAME_ID NOT NULL;

--
-- RHNPACKAGESOURCE
--
ALTER TABLE RHNPACKAGESOURCE DROP CONSTRAINT RHN_PKGSRC_BH_NN;
ALTER TABLE RHNPACKAGESOURCE MODIFY BUILD_HOST NOT NULL;

--
-- RHNPACKAGESOURCE
--
ALTER TABLE RHNPACKAGESOURCE DROP CONSTRAINT RHN_PKGSRC_BT_NN;
ALTER TABLE RHNPACKAGESOURCE MODIFY BUILD_TIME NOT NULL;

--
-- RHNPACKAGESOURCE
--
ALTER TABLE RHNPACKAGESOURCE DROP CONSTRAINT RHN_PKGSRC_COOKIE_NN;
ALTER TABLE RHNPACKAGESOURCE MODIFY COOKIE NOT NULL;

--
-- RHNPACKAGESOURCE
--
ALTER TABLE RHNPACKAGESOURCE DROP CONSTRAINT RHN_PKGSRC_CREATED_NN;
ALTER TABLE RHNPACKAGESOURCE MODIFY CREATED NOT NULL;

--
-- RHNPACKAGESOURCE
--
ALTER TABLE RHNPACKAGESOURCE DROP CONSTRAINT RHN_PKGSRC_GROUP_NN;
ALTER TABLE RHNPACKAGESOURCE MODIFY PACKAGE_GROUP NOT NULL;

--
-- RHNPACKAGESOURCE
--
ALTER TABLE RHNPACKAGESOURCE DROP CONSTRAINT RHN_PKGSRC_ID_NN;
ALTER TABLE RHNPACKAGESOURCE MODIFY ID NOT NULL;

--
-- RHNPACKAGESOURCE
--
ALTER TABLE RHNPACKAGESOURCE DROP CONSTRAINT RHN_PKGSRC_LM_NN;
ALTER TABLE RHNPACKAGESOURCE MODIFY LAST_MODIFIED NOT NULL;

--
-- RHNPACKAGESOURCE
--
ALTER TABLE RHNPACKAGESOURCE DROP CONSTRAINT RHN_PKGSRC_MD5SUM_NN;
ALTER TABLE RHNPACKAGESOURCE MODIFY MD5SUM NOT NULL;

--
-- RHNPACKAGESOURCE
--
ALTER TABLE RHNPACKAGESOURCE DROP CONSTRAINT RHN_PKGSRC_MODIFIED_NN;
ALTER TABLE RHNPACKAGESOURCE MODIFY MODIFIED NOT NULL;

--
-- RHNPACKAGESOURCE
--
ALTER TABLE RHNPACKAGESOURCE DROP CONSTRAINT RHN_PKGSRC_PAYSIZE_NN;
ALTER TABLE RHNPACKAGESOURCE MODIFY PAYLOAD_SIZE NOT NULL;

--
-- RHNPACKAGESOURCE
--
ALTER TABLE RHNPACKAGESOURCE DROP CONSTRAINT RHN_PKGSRC_PS_NN;
ALTER TABLE RHNPACKAGESOURCE MODIFY PACKAGE_SIZE NOT NULL;

--
-- RHNPACKAGESOURCE
--
ALTER TABLE RHNPACKAGESOURCE DROP CONSTRAINT RHN_PKGSRC_RPM_VER_NN;
ALTER TABLE RHNPACKAGESOURCE MODIFY RPM_VERSION NOT NULL;

--
-- RHNPACKAGESOURCE
--
ALTER TABLE RHNPACKAGESOURCE DROP CONSTRAINT RHN_PKGSRC_SRID_NN;
ALTER TABLE RHNPACKAGESOURCE MODIFY SOURCE_RPM_ID NOT NULL;

--
-- RHNPACKAGESOURCE
--
ALTER TABLE RHNPACKAGESOURCE DROP CONSTRAINT RHN_PKGSRC_VENDOR_NN;
ALTER TABLE RHNPACKAGESOURCE MODIFY VENDOR NOT NULL;

--
-- RHNPACKAGECAPABILITY
--
ALTER TABLE RHNPACKAGECAPABILITY DROP CONSTRAINT RHN_PKG_CAPABILITY_CREATED_NN;
ALTER TABLE RHNPACKAGECAPABILITY MODIFY CREATED NOT NULL;

--
-- RHNPACKAGECAPABILITY
--
ALTER TABLE RHNPACKAGECAPABILITY DROP CONSTRAINT RHN_PKG_CAPABILITY_ID_NN;
ALTER TABLE RHNPACKAGECAPABILITY MODIFY ID NOT NULL;

--
-- RHNPACKAGECAPABILITY
--
ALTER TABLE RHNPACKAGECAPABILITY DROP CONSTRAINT RHN_PKG_CAPABILITY_MODIFIED_NN;
ALTER TABLE RHNPACKAGECAPABILITY MODIFY MODIFIED NOT NULL;

--
-- RHNPACKAGECAPABILITY
--
ALTER TABLE RHNPACKAGECAPABILITY DROP CONSTRAINT RHN_PKG_CAPABILITY_NAME_NN;
ALTER TABLE RHNPACKAGECAPABILITY MODIFY NAME NOT NULL;

--
-- RHNPACKAGECHANGELOG
--
ALTER TABLE RHNPACKAGECHANGELOG DROP CONSTRAINT RHN_PKG_CHANGELOG_CREATED_NN;
ALTER TABLE RHNPACKAGECHANGELOG MODIFY CREATED NOT NULL;

--
-- RHNPACKAGECHANGELOG
--
ALTER TABLE RHNPACKAGECHANGELOG DROP CONSTRAINT RHN_PKG_CHANGELOG_MODIFIED_NN;
ALTER TABLE RHNPACKAGECHANGELOG MODIFY MODIFIED NOT NULL;

--
-- RHNPACKAGECHANGELOG
--
ALTER TABLE RHNPACKAGECHANGELOG DROP CONSTRAINT RHN_PKG_CHANGELOG_NAME;
ALTER TABLE RHNPACKAGECHANGELOG MODIFY NAME NOT NULL;

--
-- RHNPACKAGECHANGELOG
--
ALTER TABLE RHNPACKAGECHANGELOG DROP CONSTRAINT RHN_PKG_CHANGELOG_PID_NN;
ALTER TABLE RHNPACKAGECHANGELOG MODIFY PACKAGE_ID NOT NULL;

--
-- RHNPACKAGECHANGELOG
--
ALTER TABLE RHNPACKAGECHANGELOG DROP CONSTRAINT RHN_PKG_CHANGELOG_TEXT;
ALTER TABLE RHNPACKAGECHANGELOG MODIFY TEXT NOT NULL;

--
-- RHNPACKAGECHANGELOG
--
ALTER TABLE RHNPACKAGECHANGELOG DROP CONSTRAINT RHN_PKG_CHANGELOG_TIME;
ALTER TABLE RHNPACKAGECHANGELOG MODIFY TIME NOT NULL;

--
-- RHNPACKAGECHANGELOG
--
ALTER TABLE RHNPACKAGECHANGELOG DROP CONSTRAINT RHN_PKG_CL_ID_NN;
ALTER TABLE RHNPACKAGECHANGELOG MODIFY ID NOT NULL;

--
-- RHNPACKAGECONFLICTS
--
ALTER TABLE RHNPACKAGECONFLICTS DROP CONSTRAINT RHN_PKG_CONFLICTS_CID_NN;
ALTER TABLE RHNPACKAGECONFLICTS MODIFY CAPABILITY_ID NOT NULL;

--
-- RHNPACKAGECONFLICTS
--
ALTER TABLE RHNPACKAGECONFLICTS DROP CONSTRAINT RHN_PKG_CONFLICTS_CTIME_NN;
ALTER TABLE RHNPACKAGECONFLICTS MODIFY CREATED NOT NULL;

--
-- RHNPACKAGECONFLICTS
--
ALTER TABLE RHNPACKAGECONFLICTS DROP CONSTRAINT RHN_PKG_CONFLICTS_MTIME_NN;
ALTER TABLE RHNPACKAGECONFLICTS MODIFY MODIFIED NOT NULL;

--
-- RHNPACKAGECONFLICTS
--
ALTER TABLE RHNPACKAGECONFLICTS DROP CONSTRAINT RHN_PKG_CONFLICTS_PID_NN;
ALTER TABLE RHNPACKAGECONFLICTS MODIFY PACKAGE_ID NOT NULL;

--
-- RHNPACKAGECONFLICTS
--
ALTER TABLE RHNPACKAGECONFLICTS DROP CONSTRAINT RHN_PKG_CONFLICTS_SENSE_NN;
ALTER TABLE RHNPACKAGECONFLICTS MODIFY SENSE NOT NULL;

--
-- RHNPACKAGEKEYTYPE
--
ALTER TABLE RHNPACKAGEKEYTYPE DROP CONSTRAINT RHN_PKG_KEY_TYPE_CREATED_NN;
ALTER TABLE RHNPACKAGEKEYTYPE MODIFY CREATED NOT NULL;

--
-- RHNPACKAGEKEYTYPE
--
ALTER TABLE RHNPACKAGEKEYTYPE DROP CONSTRAINT RHN_PKG_KEY_TYPE_ID_NN;
ALTER TABLE RHNPACKAGEKEYTYPE MODIFY ID NOT NULL;

--
-- RHNPACKAGEKEYTYPE
--
ALTER TABLE RHNPACKAGEKEYTYPE DROP CONSTRAINT RHN_PKG_KEY_TYPE_LABEL_NN;
ALTER TABLE RHNPACKAGEKEYTYPE MODIFY LABEL NOT NULL;

--
-- RHNPACKAGEKEYTYPE
--
ALTER TABLE RHNPACKAGEKEYTYPE DROP CONSTRAINT RHN_PKG_KEY_TYPE_MODIFIED_NN;
ALTER TABLE RHNPACKAGEKEYTYPE MODIFY MODIFIED NOT NULL;

--
-- RHNPACKAGEOBSOLETES
--
ALTER TABLE RHNPACKAGEOBSOLETES DROP CONSTRAINT RHN_PKG_OBSOLETES_CID_NN;
ALTER TABLE RHNPACKAGEOBSOLETES MODIFY CAPABILITY_ID NOT NULL;

--
-- RHNPACKAGEOBSOLETES
--
ALTER TABLE RHNPACKAGEOBSOLETES DROP CONSTRAINT RHN_PKG_OBSOLETES_CTIME_NN;
ALTER TABLE RHNPACKAGEOBSOLETES MODIFY CREATED NOT NULL;

--
-- RHNPACKAGEOBSOLETES
--
ALTER TABLE RHNPACKAGEOBSOLETES DROP CONSTRAINT RHN_PKG_OBSOLETES_MTIME_NN;
ALTER TABLE RHNPACKAGEOBSOLETES MODIFY MODIFIED NOT NULL;

--
-- RHNPACKAGEOBSOLETES
--
ALTER TABLE RHNPACKAGEOBSOLETES DROP CONSTRAINT RHN_PKG_OBSOLETES_PID_NN;
ALTER TABLE RHNPACKAGEOBSOLETES MODIFY PACKAGE_ID NOT NULL;

--
-- RHNPACKAGEOBSOLETES
--
ALTER TABLE RHNPACKAGEOBSOLETES DROP CONSTRAINT RHN_PKG_OBSOLETES_SENSE_NN;
ALTER TABLE RHNPACKAGEOBSOLETES MODIFY SENSE NOT NULL;

--
-- RHNPACKAGEPROVIDER
--
ALTER TABLE RHNPACKAGEPROVIDER DROP CONSTRAINT RHN_PKG_PROVIDER_CREATED_NN;
ALTER TABLE RHNPACKAGEPROVIDER MODIFY CREATED NOT NULL;

--
-- RHNPACKAGEPROVIDER
--
ALTER TABLE RHNPACKAGEPROVIDER DROP CONSTRAINT RHN_PKG_PROVIDER_ID_NN;
ALTER TABLE RHNPACKAGEPROVIDER MODIFY ID NOT NULL;

--
-- RHNPACKAGEPROVIDER
--
ALTER TABLE RHNPACKAGEPROVIDER DROP CONSTRAINT RHN_PKG_PROVIDER_KEY_NN;
ALTER TABLE RHNPACKAGEPROVIDER MODIFY NAME NOT NULL;

--
-- RHNPACKAGEPROVIDER
--
ALTER TABLE RHNPACKAGEPROVIDER DROP CONSTRAINT RHN_PKG_PROVIDER_MODIFIED_NN;
ALTER TABLE RHNPACKAGEPROVIDER MODIFY MODIFIED NOT NULL;

--
-- RHNPACKAGEPROVIDES
--
ALTER TABLE RHNPACKAGEPROVIDES DROP CONSTRAINT RHN_PKG_PROVIDES_CID_NN;
ALTER TABLE RHNPACKAGEPROVIDES MODIFY CAPABILITY_ID NOT NULL;

--
-- RHNPACKAGEPROVIDES
--
ALTER TABLE RHNPACKAGEPROVIDES DROP CONSTRAINT RHN_PKG_PROVIDES_CTIME_NN;
ALTER TABLE RHNPACKAGEPROVIDES MODIFY CREATED NOT NULL;

--
-- RHNPACKAGEPROVIDES
--
ALTER TABLE RHNPACKAGEPROVIDES DROP CONSTRAINT RHN_PKG_PROVIDES_MTIME_NN;
ALTER TABLE RHNPACKAGEPROVIDES MODIFY MODIFIED NOT NULL;

--
-- RHNPACKAGEPROVIDES
--
ALTER TABLE RHNPACKAGEPROVIDES DROP CONSTRAINT RHN_PKG_PROVIDES_PID_NN;
ALTER TABLE RHNPACKAGEPROVIDES MODIFY PACKAGE_ID NOT NULL;

--
-- RHNPACKAGEPROVIDES
--
ALTER TABLE RHNPACKAGEPROVIDES DROP CONSTRAINT RHN_PKG_PROVIDES_SENSE_NN;
ALTER TABLE RHNPACKAGEPROVIDES MODIFY SENSE NOT NULL;

--
-- RHNPACKAGEREQUIRES
--
ALTER TABLE RHNPACKAGEREQUIRES DROP CONSTRAINT RHN_PKG_REQUIRES_CID_NN;
ALTER TABLE RHNPACKAGEREQUIRES MODIFY CAPABILITY_ID NOT NULL;

--
-- RHNPACKAGEREQUIRES
--
ALTER TABLE RHNPACKAGEREQUIRES DROP CONSTRAINT RHN_PKG_REQUIRES_CTIME_NN;
ALTER TABLE RHNPACKAGEREQUIRES MODIFY CREATED NOT NULL;

--
-- RHNPACKAGEREQUIRES
--
ALTER TABLE RHNPACKAGEREQUIRES DROP CONSTRAINT RHN_PKG_REQUIRES_MTIME_NN;
ALTER TABLE RHNPACKAGEREQUIRES MODIFY MODIFIED NOT NULL;

--
-- RHNPACKAGEREQUIRES
--
ALTER TABLE RHNPACKAGEREQUIRES DROP CONSTRAINT RHN_PKG_REQUIRES_PID_NN;
ALTER TABLE RHNPACKAGEREQUIRES MODIFY PACKAGE_ID NOT NULL;

--
-- RHNPACKAGEREQUIRES
--
ALTER TABLE RHNPACKAGEREQUIRES DROP CONSTRAINT RHN_PKG_REQUIRES_SENSE_NN;
ALTER TABLE RHNPACKAGEREQUIRES MODIFY SENSE NOT NULL;

--
-- RHNPACKAGESENSEMAP
--
ALTER TABLE RHNPACKAGESENSEMAP DROP CONSTRAINT RHN_PKG_SENSEMAP_SENSE_NN;
ALTER TABLE RHNPACKAGESENSEMAP MODIFY SENSE NOT NULL;

--
-- RHNPACKAGESENSEMAP
--
ALTER TABLE RHNPACKAGESENSEMAP DROP CONSTRAINT RHN_PKG_SENSEMAP_SID_NN;
ALTER TABLE RHNPACKAGESENSEMAP MODIFY SENSE_ID NOT NULL;

--
-- RHNPACKAGESENSE
--
ALTER TABLE RHNPACKAGESENSE DROP CONSTRAINT RHN_PKG_SENSE_ID_NN;
ALTER TABLE RHNPACKAGESENSE MODIFY ID NOT NULL;

--
-- RHNPACKAGESENSE
--
ALTER TABLE RHNPACKAGESENSE DROP CONSTRAINT RHN_PKG_SENSE_LABEL_NN;
ALTER TABLE RHNPACKAGESENSE MODIFY LABEL NOT NULL;

--
-- RHNPACKAGENAME
--
ALTER TABLE RHNPACKAGENAME DROP CONSTRAINT RHN_PN_ID_NN;
ALTER TABLE RHNPACKAGENAME MODIFY ID NOT NULL;

--
-- RHNPACKAGENAME
--
ALTER TABLE RHNPACKAGENAME DROP CONSTRAINT RHN_PN_NAME_NN;
ALTER TABLE RHNPACKAGENAME MODIFY NAME NOT NULL;

--
-- RHN_PROBE_PARAM_VALUE
--
ALTER TABLE RHN_PROBE_PARAM_VALUE DROP CONSTRAINT RHN_PPVAL_COMMAND_ID_NN;
ALTER TABLE RHN_PROBE_PARAM_VALUE MODIFY COMMAND_ID NOT NULL;

--
-- RHN_PROBE_PARAM_VALUE
--
ALTER TABLE RHN_PROBE_PARAM_VALUE DROP CONSTRAINT RHN_PPVAL_PARAM_NAME_NN;
ALTER TABLE RHN_PROBE_PARAM_VALUE MODIFY PARAM_NAME NOT NULL;

--
-- RHN_PROBE_PARAM_VALUE
--
ALTER TABLE RHN_PROBE_PARAM_VALUE DROP CONSTRAINT RHN_PPVAL_PROBE_ID_NN;
ALTER TABLE RHN_PROBE_PARAM_VALUE MODIFY PROBE_ID NOT NULL;

--
-- RHN_PROBE_STATE
--
ALTER TABLE RHN_PROBE_STATE DROP CONSTRAINT RHN_PRBST_PROBE_ID_NN;
ALTER TABLE RHN_PROBE_STATE MODIFY PROBE_ID NOT NULL;

--
-- RHN_PROBE_STATE
--
ALTER TABLE RHN_PROBE_STATE DROP CONSTRAINT RHN_PRBST_SCOUT_ID_NN;
ALTER TABLE RHN_PROBE_STATE MODIFY SCOUT_ID NOT NULL;

--
-- RHN_PROBE_TYPES
--
ALTER TABLE RHN_PROBE_TYPES DROP CONSTRAINT RHN_PRBTP_PROBE_TYPE_NN;
ALTER TABLE RHN_PROBE_TYPES MODIFY PROBE_TYPE NOT NULL;

--
-- RHN_PROBE_TYPES
--
ALTER TABLE RHN_PROBE_TYPES DROP CONSTRAINT RHN_PRBTP_TYPE_DESC_NN;
ALTER TABLE RHN_PROBE_TYPES MODIFY TYPE_DESCRIPTION NOT NULL;

--
-- RHNPRIVATECHANNELFAMILY
--
ALTER TABLE RHNPRIVATECHANNELFAMILY DROP CONSTRAINT RHN_PRIVCF_CFID_NN;
ALTER TABLE RHNPRIVATECHANNELFAMILY MODIFY CHANNEL_FAMILY_ID NOT NULL;

--
-- RHNPRIVATECHANNELFAMILY
--
ALTER TABLE RHNPRIVATECHANNELFAMILY DROP CONSTRAINT RHN_PRIVCF_CREATED_NN;
ALTER TABLE RHNPRIVATECHANNELFAMILY MODIFY CREATED NOT NULL;

--
-- RHNPRIVATECHANNELFAMILY
--
ALTER TABLE RHNPRIVATECHANNELFAMILY DROP CONSTRAINT RHN_PRIVCF_CURMEMBERS_NN;
ALTER TABLE RHNPRIVATECHANNELFAMILY MODIFY CURRENT_MEMBERS NOT NULL;

--
-- RHNPRIVATECHANNELFAMILY
--
ALTER TABLE RHNPRIVATECHANNELFAMILY DROP CONSTRAINT RHN_PRIVCF_MODIFIED_NN;
ALTER TABLE RHNPRIVATECHANNELFAMILY MODIFY MODIFIED NOT NULL;

--
-- RHNPRIVATECHANNELFAMILY
--
ALTER TABLE RHNPRIVATECHANNELFAMILY DROP CONSTRAINT RHN_PRIVCF_OID_NN;
ALTER TABLE RHNPRIVATECHANNELFAMILY MODIFY ORG_ID NOT NULL;

--
-- RHN_PROBE
--
ALTER TABLE RHN_PROBE DROP CONSTRAINT RHN_PROBE_CHK_INT_NN;
ALTER TABLE RHN_PROBE MODIFY CHECK_INTERVAL_MINUTES NOT NULL;

--
-- RHN_PROBE
--
ALTER TABLE RHN_PROBE DROP CONSTRAINT RHN_PROBE_COMMAND_ID_NN;
ALTER TABLE RHN_PROBE MODIFY COMMAND_ID NOT NULL;

--
-- RHN_PROBE
--
ALTER TABLE RHN_PROBE DROP CONSTRAINT RHN_PROBE_CUST_ID_NN;
ALTER TABLE RHN_PROBE MODIFY CUSTOMER_ID NOT NULL;

--
-- RHN_PROBE
--
ALTER TABLE RHN_PROBE DROP CONSTRAINT RHN_PROBE_DESCRIPTION_NN;
ALTER TABLE RHN_PROBE MODIFY DESCRIPTION NOT NULL;

--
-- RHN_PROBE
--
ALTER TABLE RHN_PROBE DROP CONSTRAINT RHN_PROBE_PROBE_TYPE_NN;
ALTER TABLE RHN_PROBE MODIFY PROBE_TYPE NOT NULL;

--
-- RHN_PROBE
--
ALTER TABLE RHN_PROBE DROP CONSTRAINT RHN_PROBE_RECID_NN;
ALTER TABLE RHN_PROBE MODIFY RECID NOT NULL;

--
-- RHN_PROBE
--
ALTER TABLE RHN_PROBE DROP CONSTRAINT RHN_PROBE_RETRY_INT_NN;
ALTER TABLE RHN_PROBE MODIFY RETRY_INTERVAL_MINUTES NOT NULL;

--
-- RHNPRODUCTNAME
--
ALTER TABLE RHNPRODUCTNAME DROP CONSTRAINT RHN_PRODUCTNAME_ID_NN;
ALTER TABLE RHNPRODUCTNAME MODIFY ID NOT NULL;

--
-- RHNPRODUCTNAME
--
ALTER TABLE RHNPRODUCTNAME DROP CONSTRAINT RHN_PRODUCTNAME_LBL_NN;
ALTER TABLE RHNPRODUCTNAME MODIFY LABEL NOT NULL;

--
-- RHNPRODUCTNAME
--
ALTER TABLE RHNPRODUCTNAME DROP CONSTRAINT RHN_PRODUCTNAME_NAME_NN;
ALTER TABLE RHNPRODUCTNAME MODIFY NAME NOT NULL;

--
-- RHNPRODUCT
--
ALTER TABLE RHNPRODUCT DROP CONSTRAINT RHN_PRODUCT_CAT_NN;
ALTER TABLE RHNPRODUCT MODIFY PRODUCT_LINE_ID NOT NULL;

--
-- RHNPRODUCT
--
ALTER TABLE RHNPRODUCT DROP CONSTRAINT RHN_PRODUCT_CREATED_NN;
ALTER TABLE RHNPRODUCT MODIFY CREATED NOT NULL;

--
-- RHNPRODUCT
--
ALTER TABLE RHNPRODUCT DROP CONSTRAINT RHN_PRODUCT_ID_NN;
ALTER TABLE RHNPRODUCT MODIFY ID NOT NULL;

--
-- RHNPRODUCT
--
ALTER TABLE RHNPRODUCT DROP CONSTRAINT RHN_PRODUCT_LABEL_NN;
ALTER TABLE RHNPRODUCT MODIFY LABEL NOT NULL;

--
-- RHNPRODUCT
--
ALTER TABLE RHNPRODUCT DROP CONSTRAINT RHN_PRODUCT_LM_NN;
ALTER TABLE RHNPRODUCT MODIFY LAST_MODIFIED NOT NULL;

--
-- RHNPRODUCT
--
ALTER TABLE RHNPRODUCT DROP CONSTRAINT RHN_PRODUCT_MODIFIED_NN;
ALTER TABLE RHNPRODUCT MODIFY MODIFIED NOT NULL;

--
-- RHNPRODUCT
--
ALTER TABLE RHNPRODUCT DROP CONSTRAINT RHN_PRODUCT_NAME_NN;
ALTER TABLE RHNPRODUCT MODIFY NAME NOT NULL;

--
-- RHNPRODUCTLINE
--
ALTER TABLE RHNPRODUCTLINE DROP CONSTRAINT RHN_PROD_LINE_CREATED_NN;
ALTER TABLE RHNPRODUCTLINE MODIFY CREATED NOT NULL;

--
-- RHNPRODUCTLINE
--
ALTER TABLE RHNPRODUCTLINE DROP CONSTRAINT RHN_PROD_LINE_ID_NN;
ALTER TABLE RHNPRODUCTLINE MODIFY ID NOT NULL;

--
-- RHNPRODUCTLINE
--
ALTER TABLE RHNPRODUCTLINE DROP CONSTRAINT RHN_PROD_LINE_LABEL_NN;
ALTER TABLE RHNPRODUCTLINE MODIFY LABEL NOT NULL;

--
-- RHNPRODUCTLINE
--
ALTER TABLE RHNPRODUCTLINE DROP CONSTRAINT RHN_PROD_LINE_LM_NN;
ALTER TABLE RHNPRODUCTLINE MODIFY LAST_MODIFIED NOT NULL;

--
-- RHNPRODUCTLINE
--
ALTER TABLE RHNPRODUCTLINE DROP CONSTRAINT RHN_PROD_LINE_MODIFIED_NN;
ALTER TABLE RHNPRODUCTLINE MODIFY MODIFIED NOT NULL;

--
-- RHNPRODUCTLINE
--
ALTER TABLE RHNPRODUCTLINE DROP CONSTRAINT RHN_PROD_LINE_NAME_NN;
ALTER TABLE RHNPRODUCTLINE MODIFY NAME NOT NULL;

--
-- RHNPROVISIONSTATE
--
ALTER TABLE RHNPROVISIONSTATE DROP CONSTRAINT RHN_PROVSTATE_CREAT_NN;
ALTER TABLE RHNPROVISIONSTATE MODIFY CREATED NOT NULL;

--
-- RHNPROVISIONSTATE
--
ALTER TABLE RHNPROVISIONSTATE DROP CONSTRAINT RHN_PROVSTATE_DESC_NN;
ALTER TABLE RHNPROVISIONSTATE MODIFY DESCRIPTION NOT NULL;

--
-- RHNPROVISIONSTATE
--
ALTER TABLE RHNPROVISIONSTATE DROP CONSTRAINT RHN_PROVSTATE_ID_NN;
ALTER TABLE RHNPROVISIONSTATE MODIFY ID NOT NULL;

--
-- RHNPROVISIONSTATE
--
ALTER TABLE RHNPROVISIONSTATE DROP CONSTRAINT RHN_PROVSTATE_LABEL_NN;
ALTER TABLE RHNPROVISIONSTATE MODIFY LABEL NOT NULL;

--
-- RHNPROVISIONSTATE
--
ALTER TABLE RHNPROVISIONSTATE DROP CONSTRAINT RHN_PROVSTATE_MOD_NN;
ALTER TABLE RHNPROVISIONSTATE MODIFY MODIFIED NOT NULL;

--
-- RHNPROXYINFO
--
ALTER TABLE RHNPROXYINFO DROP CONSTRAINT RHN_PROXY_INFO_SID_NN;
ALTER TABLE RHNPROXYINFO MODIFY SERVER_ID NOT NULL;

--
-- RHNPUBLICCHANNELFAMILY
--
ALTER TABLE RHNPUBLICCHANNELFAMILY DROP CONSTRAINT RHN_PUBCF_CFID_NN;
ALTER TABLE RHNPUBLICCHANNELFAMILY MODIFY CHANNEL_FAMILY_ID NOT NULL;

--
-- RHNPUBLICCHANNELFAMILY
--
ALTER TABLE RHNPUBLICCHANNELFAMILY DROP CONSTRAINT RHN_PUBCF_CREAT_NN;
ALTER TABLE RHNPUBLICCHANNELFAMILY MODIFY CREATED NOT NULL;

--
-- RHNPUBLICCHANNELFAMILY
--
ALTER TABLE RHNPUBLICCHANNELFAMILY DROP CONSTRAINT RHN_PUBCF_MOD_NN;
ALTER TABLE RHNPUBLICCHANNELFAMILY MODIFY MODIFIED NOT NULL;

--
-- RHNPUSHDISPATCHER
--
ALTER TABLE RHNPUSHDISPATCHER DROP CONSTRAINT RHN_PUSHDISPATCH_CREAT_NN;
ALTER TABLE RHNPUSHDISPATCHER MODIFY CREATED NOT NULL;

--
-- RHNPUSHDISPATCHER
--
ALTER TABLE RHNPUSHDISPATCHER DROP CONSTRAINT RHN_PUSHDISPATCH_HN_NN;
ALTER TABLE RHNPUSHDISPATCHER MODIFY HOSTNAME NOT NULL;

--
-- RHNPUSHDISPATCHER
--
ALTER TABLE RHNPUSHDISPATCHER DROP CONSTRAINT RHN_PUSHDISPATCH_ID_NN;
ALTER TABLE RHNPUSHDISPATCHER MODIFY ID NOT NULL;

--
-- RHNPUSHDISPATCHER
--
ALTER TABLE RHNPUSHDISPATCHER DROP CONSTRAINT RHN_PUSHDISPATCH_JID_NN;
ALTER TABLE RHNPUSHDISPATCHER MODIFY JABBER_ID NOT NULL;

--
-- RHNPUSHDISPATCHER
--
ALTER TABLE RHNPUSHDISPATCHER DROP CONSTRAINT RHN_PUSHDISPATCH_LC_NN;
ALTER TABLE RHNPUSHDISPATCHER MODIFY LAST_CHECKIN NOT NULL;

--
-- RHNPUSHDISPATCHER
--
ALTER TABLE RHNPUSHDISPATCHER DROP CONSTRAINT RHN_PUSHDISPATCH_MOD_NN;
ALTER TABLE RHNPUSHDISPATCHER MODIFY MODIFIED NOT NULL;

--
-- RHNPUSHDISPATCHER
--
ALTER TABLE RHNPUSHDISPATCHER DROP CONSTRAINT RHN_PUSHDISPATCH_PORT_NN;
ALTER TABLE RHNPUSHDISPATCHER MODIFY PORT NOT NULL;

--
-- RHN_QUANTA
--
ALTER TABLE RHN_QUANTA DROP CONSTRAINT RHN_QNTA0_QUANTUM_ID_NN;
ALTER TABLE RHN_QUANTA MODIFY QUANTUM_ID NOT NULL;

--
-- RHNRAM
--
ALTER TABLE RHNRAM DROP CONSTRAINT RHN_RAM_CREATED_NN;
ALTER TABLE RHNRAM MODIFY CREATED NOT NULL;

--
-- RHNRAM
--
ALTER TABLE RHNRAM DROP CONSTRAINT RHN_RAM_ID_NN;
ALTER TABLE RHNRAM MODIFY ID NOT NULL;

--
-- RHNRAM
--
ALTER TABLE RHNRAM DROP CONSTRAINT RHN_RAM_MODIFIED_NN;
ALTER TABLE RHNRAM MODIFY MODIFIED NOT NULL;

--
-- RHNRAM
--
ALTER TABLE RHNRAM DROP CONSTRAINT RHN_RAM_RAM_NN;
ALTER TABLE RHNRAM MODIFY RAM NOT NULL;

--
-- RHNRAM
--
ALTER TABLE RHNRAM DROP CONSTRAINT RHN_RAM_SERVER_NN;
ALTER TABLE RHNRAM MODIFY SERVER_ID NOT NULL;

--
-- RHNRAM
--
ALTER TABLE RHNRAM DROP CONSTRAINT RHN_RAM_SWAP_NN;
ALTER TABLE RHNRAM MODIFY SWAP NOT NULL;

--
-- RHNRELEASECHANNELMAP
--
ALTER TABLE RHNRELEASECHANNELMAP DROP CONSTRAINT RHN_RCM_CAID_NN;
ALTER TABLE RHNRELEASECHANNELMAP MODIFY CHANNEL_ARCH_ID NOT NULL;

--
-- RHNRELEASECHANNELMAP
--
ALTER TABLE RHNRELEASECHANNELMAP DROP CONSTRAINT RHN_RCM_CID_NN;
ALTER TABLE RHNRELEASECHANNELMAP MODIFY CHANNEL_ID NOT NULL;

--
-- RHNRELEASECHANNELMAP
--
ALTER TABLE RHNRELEASECHANNELMAP DROP CONSTRAINT RHN_RCM_PRODCT_NN;
ALTER TABLE RHNRELEASECHANNELMAP MODIFY PRODUCT NOT NULL;

--
-- RHNRELEASECHANNELMAP
--
ALTER TABLE RHNRELEASECHANNELMAP DROP CONSTRAINT RHN_RCM_RELSE_NN;
ALTER TABLE RHNRELEASECHANNELMAP MODIFY RELEASE NOT NULL;

--
-- RHNRELEASECHANNELMAP
--
ALTER TABLE RHNRELEASECHANNELMAP DROP CONSTRAINT RHN_RCM_VERSN_NN;
ALTER TABLE RHNRELEASECHANNELMAP MODIFY VERSION NOT NULL;

--
-- RHN_REDIRECT_CRITERIA
--
ALTER TABLE RHN_REDIRECT_CRITERIA DROP CONSTRAINT RHN_RDRCR_INVERTED_NN;
ALTER TABLE RHN_REDIRECT_CRITERIA MODIFY INVERTED NOT NULL;

--
-- RHN_REDIRECT_CRITERIA
--
ALTER TABLE RHN_REDIRECT_CRITERIA DROP CONSTRAINT RHN_RDRCR_MATCH_PARAM_NN;
ALTER TABLE RHN_REDIRECT_CRITERIA MODIFY MATCH_PARAM NOT NULL;

--
-- RHN_REDIRECT_CRITERIA
--
ALTER TABLE RHN_REDIRECT_CRITERIA DROP CONSTRAINT RHN_RDRCR_RECID_NN;
ALTER TABLE RHN_REDIRECT_CRITERIA MODIFY RECID NOT NULL;

--
-- RHN_REDIRECT_CRITERIA
--
ALTER TABLE RHN_REDIRECT_CRITERIA DROP CONSTRAINT RHN_RDRCR_REDIRECT_ID_NN;
ALTER TABLE RHN_REDIRECT_CRITERIA MODIFY REDIRECT_ID NOT NULL;

--
-- RHN_REDIRECTS
--
ALTER TABLE RHN_REDIRECTS DROP CONSTRAINT RHN_RDRCT_EXPIRATION_NN;
ALTER TABLE RHN_REDIRECTS MODIFY EXPIRATION NOT NULL;

--
-- RHN_REDIRECTS
--
ALTER TABLE RHN_REDIRECTS DROP CONSTRAINT RHN_RDRCT_RECID_NN;
ALTER TABLE RHN_REDIRECTS MODIFY RECID NOT NULL;

--
-- RHN_REDIRECTS
--
ALTER TABLE RHN_REDIRECTS DROP CONSTRAINT RHN_RDRCT_RECURRING_NN;
ALTER TABLE RHN_REDIRECTS MODIFY RECURRING NOT NULL;

--
-- RHN_REDIRECTS
--
ALTER TABLE RHN_REDIRECTS DROP CONSTRAINT RHN_RDRCT_REDIRECT_TYPE_NN;
ALTER TABLE RHN_REDIRECTS MODIFY REDIRECT_TYPE NOT NULL;

--
-- RHN_REDIRECTS
--
ALTER TABLE RHN_REDIRECTS DROP CONSTRAINT RHN_RDRCT_START_DATE_NN;
ALTER TABLE RHN_REDIRECTS MODIFY START_DATE NOT NULL;

--
-- RHN_REDIRECT_EMAIL_TARGETS
--
ALTER TABLE RHN_REDIRECT_EMAIL_TARGETS DROP CONSTRAINT RHN_RDRET_EMAIL_ADDR_NN;
ALTER TABLE RHN_REDIRECT_EMAIL_TARGETS MODIFY EMAIL_ADDRESS NOT NULL;

--
-- RHN_REDIRECT_EMAIL_TARGETS
--
ALTER TABLE RHN_REDIRECT_EMAIL_TARGETS DROP CONSTRAINT RHN_RDRET_REDIRECT_ID_NN;
ALTER TABLE RHN_REDIRECT_EMAIL_TARGETS MODIFY REDIRECT_ID NOT NULL;

--
-- RHN_REDIRECT_GROUP_TARGETS
--
ALTER TABLE RHN_REDIRECT_GROUP_TARGETS DROP CONSTRAINT RHN_RDRGT_GROUP_ID_NN;
ALTER TABLE RHN_REDIRECT_GROUP_TARGETS MODIFY CONTACT_GROUP_ID NOT NULL;

--
-- RHN_REDIRECT_GROUP_TARGETS
--
ALTER TABLE RHN_REDIRECT_GROUP_TARGETS DROP CONSTRAINT RHN_RDRGT_REDIRECT_ID_NN;
ALTER TABLE RHN_REDIRECT_GROUP_TARGETS MODIFY REDIRECT_ID NOT NULL;

--
-- RHN_REDIRECT_METHOD_TARGETS
--
ALTER TABLE RHN_REDIRECT_METHOD_TARGETS DROP CONSTRAINT RHN_RDRME_METHOD_ID;
ALTER TABLE RHN_REDIRECT_METHOD_TARGETS MODIFY CONTACT_METHOD_ID NOT NULL;

--
-- RHN_REDIRECT_METHOD_TARGETS
--
ALTER TABLE RHN_REDIRECT_METHOD_TARGETS DROP CONSTRAINT RHN_RDRME_REDIRECT_ID;
ALTER TABLE RHN_REDIRECT_METHOD_TARGETS MODIFY REDIRECT_ID NOT NULL;

--
-- RHN_REDIRECT_MATCH_TYPES
--
ALTER TABLE RHN_REDIRECT_MATCH_TYPES DROP CONSTRAINT RHN_RDRMT_NAME_NN;
ALTER TABLE RHN_REDIRECT_MATCH_TYPES MODIFY NAME NOT NULL;

--
-- RHN_REDIRECT_TYPES
--
ALTER TABLE RHN_REDIRECT_TYPES DROP CONSTRAINT RHN_RDRTP_NAME_NN;
ALTER TABLE RHN_REDIRECT_TYPES MODIFY NAME NOT NULL;

--
-- RHNREGTOKENCONFIGCHANNELS
--
ALTER TABLE RHNREGTOKENCONFIGCHANNELS DROP CONSTRAINT RHN_REGTOK_CONFCHAN_CCID_NN;
ALTER TABLE RHNREGTOKENCONFIGCHANNELS MODIFY CONFIG_CHANNEL_ID NOT NULL;

--
-- RHNREGTOKENCONFIGCHANNELS
--
ALTER TABLE RHNREGTOKENCONFIGCHANNELS DROP CONSTRAINT RHN_REGTOK_CONFCHAN_POS_NN;
ALTER TABLE RHNREGTOKENCONFIGCHANNELS MODIFY POSITION NOT NULL;

--
-- RHNREGTOKENCONFIGCHANNELS
--
ALTER TABLE RHNREGTOKENCONFIGCHANNELS DROP CONSTRAINT RHN_REGTOK_CONFCHAN_TID_NN;
ALTER TABLE RHNREGTOKENCONFIGCHANNELS MODIFY TOKEN_ID NOT NULL;

--
-- RHNREGTOKEN
--
ALTER TABLE RHNREGTOKEN DROP CONSTRAINT RHN_REG_TOKEN_DEF_NN;
ALTER TABLE RHNREGTOKEN MODIFY DISABLED NOT NULL;

--
-- RHNREGTOKENORGDEFAULT
--
ALTER TABLE RHNREGTOKENORGDEFAULT DROP CONSTRAINT RHN_REG_TOKEN_DEF_OID_NN;
ALTER TABLE RHNREGTOKENORGDEFAULT MODIFY ORG_ID NOT NULL;

--
-- RHNREGTOKEN
--
ALTER TABLE RHNREGTOKEN DROP CONSTRAINT RHN_REG_TOKEN_DEPLOYCONFS_NN;
ALTER TABLE RHNREGTOKEN MODIFY DEPLOY_CONFIGS NOT NULL;

--
-- RHNREGTOKEN
--
ALTER TABLE RHNREGTOKEN DROP CONSTRAINT RHN_REG_TOKEN_ID_NN;
ALTER TABLE RHNREGTOKEN MODIFY ID NOT NULL;

--
-- RHNREGTOKEN
--
ALTER TABLE RHNREGTOKEN DROP CONSTRAINT RHN_REG_TOKEN_NOTE_NN;
ALTER TABLE RHNREGTOKEN MODIFY NOTE NOT NULL;

--
-- RHNREGTOKEN
--
ALTER TABLE RHNREGTOKEN DROP CONSTRAINT RHN_REG_TOKEN_OID_NN;
ALTER TABLE RHNREGTOKEN MODIFY ORG_ID NOT NULL;

--
-- RHNREGTOKENCHANNELS
--
ALTER TABLE RHNREGTOKENCHANNELS DROP CONSTRAINT RHN_REG_TOK_CHN_SG_NN;
ALTER TABLE RHNREGTOKENCHANNELS MODIFY CHANNEL_ID NOT NULL;

--
-- RHNREGTOKENCHANNELS
--
ALTER TABLE RHNREGTOKENCHANNELS DROP CONSTRAINT RHN_REG_TOK_CHN_TID_NN;
ALTER TABLE RHNREGTOKENCHANNELS MODIFY TOKEN_ID NOT NULL;

--
-- RHNREGTOKENENTITLEMENT
--
ALTER TABLE RHNREGTOKENENTITLEMENT DROP CONSTRAINT RHN_REG_TOK_ENT_RTID_NN;
ALTER TABLE RHNREGTOKENENTITLEMENT MODIFY REG_TOKEN_ID NOT NULL;

--
-- RHNREGTOKENENTITLEMENT
--
ALTER TABLE RHNREGTOKENENTITLEMENT DROP CONSTRAINT RHN_REG_TOK_ENT_SGTID_NN;
ALTER TABLE RHNREGTOKENENTITLEMENT MODIFY SERVER_GROUP_TYPE_ID NOT NULL;

--
-- RHNREGTOKENGROUPS
--
ALTER TABLE RHNREGTOKENGROUPS DROP CONSTRAINT RHN_REG_TOK_GRP_SG_NN;
ALTER TABLE RHNREGTOKENGROUPS MODIFY SERVER_GROUP_ID NOT NULL;

--
-- RHNREGTOKENGROUPS
--
ALTER TABLE RHNREGTOKENGROUPS DROP CONSTRAINT RHN_REG_TOK_GRP_TID_NN;
ALTER TABLE RHNREGTOKENGROUPS MODIFY TOKEN_ID NOT NULL;

--
-- RHNREGTOKENPACKAGES
--
ALTER TABLE RHNREGTOKENPACKAGES DROP CONSTRAINT RHN_REG_TOK_PKG_ID_NN;
ALTER TABLE RHNREGTOKENPACKAGES MODIFY ID NOT NULL;

--
-- RHNREGTOKENPACKAGES
--
ALTER TABLE RHNREGTOKENPACKAGES DROP CONSTRAINT RHN_REG_TOK_PKG_SG_NN;
ALTER TABLE RHNREGTOKENPACKAGES MODIFY NAME_ID NOT NULL;

--
-- RHNREGTOKENPACKAGES
--
ALTER TABLE RHNREGTOKENPACKAGES DROP CONSTRAINT RHN_REG_TOK_PKG_TID_NN;
ALTER TABLE RHNREGTOKENPACKAGES MODIFY TOKEN_ID NOT NULL;

--
-- RHNRELATIONSHIPTYPE
--
ALTER TABLE RHNRELATIONSHIPTYPE DROP CONSTRAINT RHN_RELTYPE_CREATED_NN;
ALTER TABLE RHNRELATIONSHIPTYPE MODIFY CREATED NOT NULL;

--
-- RHNRELATIONSHIPTYPE
--
ALTER TABLE RHNRELATIONSHIPTYPE DROP CONSTRAINT RHN_RELTYPE_ID_NN;
ALTER TABLE RHNRELATIONSHIPTYPE MODIFY ID NOT NULL;

--
-- RHNRELATIONSHIPTYPE
--
ALTER TABLE RHNRELATIONSHIPTYPE DROP CONSTRAINT RHN_RELTYPE_LABEL_NN;
ALTER TABLE RHNRELATIONSHIPTYPE MODIFY LABEL NOT NULL;

--
-- RHNRELATIONSHIPTYPE
--
ALTER TABLE RHNRELATIONSHIPTYPE DROP CONSTRAINT RHN_RELTYPE_MODIFIED_NN;
ALTER TABLE RHNRELATIONSHIPTYPE MODIFY MODIFIED NOT NULL;

--
-- RHNREPOREGENQUEUE
--
ALTER TABLE RHNREPOREGENQUEUE DROP CONSTRAINT RHN_REPOREGENQ_CHAN_LABEL_NN;
ALTER TABLE RHNREPOREGENQUEUE MODIFY CHANNEL_LABEL NOT NULL;

--
-- RHNREPOREGENQUEUE
--
ALTER TABLE RHNREPOREGENQUEUE DROP CONSTRAINT RHN_REPOREGENQ_CREATED_NN;
ALTER TABLE RHNREPOREGENQUEUE MODIFY CREATED NOT NULL;

--
-- RHNREPOREGENQUEUE
--
ALTER TABLE RHNREPOREGENQUEUE DROP CONSTRAINT RHN_REPOREGENQ_ID_NN;
-- ALTER TABLE RHNREPOREGENQUEUE MODIFY ID NOT NULL;

--
-- RHNREPOREGENQUEUE
--
ALTER TABLE RHNREPOREGENQUEUE DROP CONSTRAINT RHN_REPOREGENQ_MODIFIED_NN;
ALTER TABLE RHNREPOREGENQUEUE MODIFY MODIFIED NOT NULL;

--
-- RHNREDHATCANONVERSION
--
ALTER TABLE RHNREDHATCANONVERSION DROP CONSTRAINT RHN_RH_CANON_VER_CREATED_NN;
ALTER TABLE RHNREDHATCANONVERSION MODIFY CREATED NOT NULL;

--
-- RHNREDHATCANONVERSION
--
ALTER TABLE RHNREDHATCANONVERSION DROP CONSTRAINT RHN_RH_CANON_VER_CV_NN;
ALTER TABLE RHNREDHATCANONVERSION MODIFY CANON_VERSION NOT NULL;

--
-- RHNREDHATCANONVERSION
--
ALTER TABLE RHNREDHATCANONVERSION DROP CONSTRAINT RHN_RH_CANON_VER_MODIFIED_NN;
ALTER TABLE RHNREDHATCANONVERSION MODIFY MODIFIED NOT NULL;

--
-- RHNREDHATCANONVERSION
--
ALTER TABLE RHNREDHATCANONVERSION DROP CONSTRAINT RHN_RH_CANON_VER_V_NN;
ALTER TABLE RHNREDHATCANONVERSION MODIFY VERSION NOT NULL;

--
-- RHNSERVERACTIONVERIFYMISSING
--
ALTER TABLE RHNSERVERACTIONVERIFYMISSING DROP CONSTRAINT RHN_SACTIONVM_AID_NN;
ALTER TABLE RHNSERVERACTIONVERIFYMISSING MODIFY ACTION_ID NOT NULL;

--
-- RHNSERVERACTIONVERIFYMISSING
--
ALTER TABLE RHNSERVERACTIONVERIFYMISSING DROP CONSTRAINT RHN_SACTIONVM_CREAT_NN;
ALTER TABLE RHNSERVERACTIONVERIFYMISSING MODIFY CREATED NOT NULL;

--
-- RHNSERVERACTIONVERIFYMISSING
--
ALTER TABLE RHNSERVERACTIONVERIFYMISSING DROP CONSTRAINT RHN_SACTIONVM_MOD_NN;
ALTER TABLE RHNSERVERACTIONVERIFYMISSING MODIFY MODIFIED NOT NULL;

--
-- RHNSERVERACTIONVERIFYMISSING
--
ALTER TABLE RHNSERVERACTIONVERIFYMISSING DROP CONSTRAINT RHN_SACTIONVM_PAID_NN;
ALTER TABLE RHNSERVERACTIONVERIFYMISSING MODIFY PACKAGE_ARCH_ID NOT NULL;

--
-- RHNSERVERACTIONVERIFYMISSING
--
ALTER TABLE RHNSERVERACTIONVERIFYMISSING DROP CONSTRAINT RHN_SACTIONVM_PCID_NN;
ALTER TABLE RHNSERVERACTIONVERIFYMISSING MODIFY PACKAGE_CAPABILITY_ID NOT NULL;

--
-- RHNSERVERACTIONVERIFYMISSING
--
ALTER TABLE RHNSERVERACTIONVERIFYMISSING DROP CONSTRAINT RHN_SACTIONVM_PEID_NN;
ALTER TABLE RHNSERVERACTIONVERIFYMISSING MODIFY PACKAGE_EVR_ID NOT NULL;

--
-- RHNSERVERACTIONVERIFYMISSING
--
ALTER TABLE RHNSERVERACTIONVERIFYMISSING DROP CONSTRAINT RHN_SACTIONVM_PNID_NN;
ALTER TABLE RHNSERVERACTIONVERIFYMISSING MODIFY PACKAGE_NAME_ID NOT NULL;

--
-- RHNSERVERACTIONVERIFYMISSING
--
ALTER TABLE RHNSERVERACTIONVERIFYMISSING DROP CONSTRAINT RHN_SACTIONVM_SID_NN;
ALTER TABLE RHNSERVERACTIONVERIFYMISSING MODIFY SERVER_ID NOT NULL;

--
-- RHNSERVERACTIONVERIFYRESULT
--
ALTER TABLE RHNSERVERACTIONVERIFYRESULT DROP CONSTRAINT RHN_SACTIONVR_AID_NN;
ALTER TABLE RHNSERVERACTIONVERIFYRESULT MODIFY ACTION_ID NOT NULL;

--
-- RHNSERVERACTIONVERIFYRESULT
--
ALTER TABLE RHNSERVERACTIONVERIFYRESULT DROP CONSTRAINT RHN_SACTIONVR_CREAT_NN;
ALTER TABLE RHNSERVERACTIONVERIFYRESULT MODIFY CREATED NOT NULL;

--
-- RHNSERVERACTIONVERIFYRESULT
--
ALTER TABLE RHNSERVERACTIONVERIFYRESULT DROP CONSTRAINT RHN_SACTIONVR_DEVNUM_NN;
ALTER TABLE RHNSERVERACTIONVERIFYRESULT MODIFY DEVNUM_DIFFERS NOT NULL;

--
-- RHNSERVERACTIONVERIFYRESULT
--
ALTER TABLE RHNSERVERACTIONVERIFYRESULT DROP CONSTRAINT RHN_SACTIONVR_GID_NN;
ALTER TABLE RHNSERVERACTIONVERIFYRESULT MODIFY GID_DIFFERS NOT NULL;

--
-- RHNSERVERACTIONVERIFYRESULT
--
ALTER TABLE RHNSERVERACTIONVERIFYRESULT DROP CONSTRAINT RHN_SACTIONVR_MD5_NN;
ALTER TABLE RHNSERVERACTIONVERIFYRESULT MODIFY MD5_DIFFERS NOT NULL;

--
-- RHNSERVERACTIONVERIFYRESULT
--
ALTER TABLE RHNSERVERACTIONVERIFYRESULT DROP CONSTRAINT RHN_SACTIONVR_MODE_NN;
ALTER TABLE RHNSERVERACTIONVERIFYRESULT MODIFY MODE_DIFFERS NOT NULL;

--
-- RHNSERVERACTIONVERIFYRESULT
--
ALTER TABLE RHNSERVERACTIONVERIFYRESULT DROP CONSTRAINT RHN_SACTIONVR_MOD_NN;
ALTER TABLE RHNSERVERACTIONVERIFYRESULT MODIFY MODIFIED NOT NULL;

--
-- RHNSERVERACTIONVERIFYRESULT
--
ALTER TABLE RHNSERVERACTIONVERIFYRESULT DROP CONSTRAINT RHN_SACTIONVR_MTIME_NN;
ALTER TABLE RHNSERVERACTIONVERIFYRESULT MODIFY MTIME_DIFFERS NOT NULL;

--
-- RHNSERVERACTIONVERIFYRESULT
--
ALTER TABLE RHNSERVERACTIONVERIFYRESULT DROP CONSTRAINT RHN_SACTIONVR_PAID_NN;
ALTER TABLE RHNSERVERACTIONVERIFYRESULT MODIFY PACKAGE_ARCH_ID NOT NULL;

--
-- RHNSERVERACTIONVERIFYRESULT
--
ALTER TABLE RHNSERVERACTIONVERIFYRESULT DROP CONSTRAINT RHN_SACTIONVR_PCID_NN;
ALTER TABLE RHNSERVERACTIONVERIFYRESULT MODIFY PACKAGE_CAPABILITY_ID NOT NULL;

--
-- RHNSERVERACTIONVERIFYRESULT
--
ALTER TABLE RHNSERVERACTIONVERIFYRESULT DROP CONSTRAINT RHN_SACTIONVR_PEID_NN;
ALTER TABLE RHNSERVERACTIONVERIFYRESULT MODIFY PACKAGE_EVR_ID NOT NULL;

--
-- RHNSERVERACTIONVERIFYRESULT
--
ALTER TABLE RHNSERVERACTIONVERIFYRESULT DROP CONSTRAINT RHN_SACTIONVR_PNID_NN;
ALTER TABLE RHNSERVERACTIONVERIFYRESULT MODIFY PACKAGE_NAME_ID NOT NULL;

--
-- RHNSERVERACTIONVERIFYRESULT
--
ALTER TABLE RHNSERVERACTIONVERIFYRESULT DROP CONSTRAINT RHN_SACTIONVR_READLINK_NN;
ALTER TABLE RHNSERVERACTIONVERIFYRESULT MODIFY READLINK_DIFFERS NOT NULL;

--
-- RHNSERVERACTIONVERIFYRESULT
--
ALTER TABLE RHNSERVERACTIONVERIFYRESULT DROP CONSTRAINT RHN_SACTIONVR_SID_NN;
ALTER TABLE RHNSERVERACTIONVERIFYRESULT MODIFY SERVER_ID NOT NULL;

--
-- RHNSERVERACTIONVERIFYRESULT
--
ALTER TABLE RHNSERVERACTIONVERIFYRESULT DROP CONSTRAINT RHN_SACTIONVR_SIZE_NN;
ALTER TABLE RHNSERVERACTIONVERIFYRESULT MODIFY SIZE_DIFFERS NOT NULL;

--
-- RHNSERVERACTIONVERIFYRESULT
--
ALTER TABLE RHNSERVERACTIONVERIFYRESULT DROP CONSTRAINT RHN_SACTIONVR_UID_NN;
ALTER TABLE RHNSERVERACTIONVERIFYRESULT MODIFY UID_DIFFERS NOT NULL;

--
-- RHNSERVERACTIONPACKAGERESULT
--
ALTER TABLE RHNSERVERACTIONPACKAGERESULT DROP CONSTRAINT RHN_SAP_RESULT_APID_NN;
ALTER TABLE RHNSERVERACTIONPACKAGERESULT MODIFY ACTION_PACKAGE_ID NOT NULL;

--
-- RHNSERVERACTIONPACKAGERESULT
--
ALTER TABLE RHNSERVERACTIONPACKAGERESULT DROP CONSTRAINT RHN_SAP_RESULT_CREAT_NN;
ALTER TABLE RHNSERVERACTIONPACKAGERESULT MODIFY CREATED NOT NULL;

--
-- RHNSERVERACTIONPACKAGERESULT
--
ALTER TABLE RHNSERVERACTIONPACKAGERESULT DROP CONSTRAINT RHN_SAP_RESULT_MOD_NN;
ALTER TABLE RHNSERVERACTIONPACKAGERESULT MODIFY MODIFIED NOT NULL;

--
-- RHNSERVERACTIONPACKAGERESULT
--
ALTER TABLE RHNSERVERACTIONPACKAGERESULT DROP CONSTRAINT RHN_SAP_RESULT_RC_NN;
ALTER TABLE RHNSERVERACTIONPACKAGERESULT MODIFY RESULT_CODE NOT NULL;

--
-- RHNSERVERACTIONPACKAGERESULT
--
ALTER TABLE RHNSERVERACTIONPACKAGERESULT DROP CONSTRAINT RHN_SAP_RESULT_SID_NN;
ALTER TABLE RHNSERVERACTIONPACKAGERESULT MODIFY SERVER_ID NOT NULL;

--
-- RHNSERVERARCH
--
ALTER TABLE RHNSERVERARCH DROP CONSTRAINT RHN_SARCH_ATID_NN;
ALTER TABLE RHNSERVERARCH MODIFY ARCH_TYPE_ID NOT NULL;

--
-- RHNSERVERARCH
--
ALTER TABLE RHNSERVERARCH DROP CONSTRAINT RHN_SARCH_CREATED_NN;
ALTER TABLE RHNSERVERARCH MODIFY CREATED NOT NULL;

--
-- RHNSERVERARCH
--
ALTER TABLE RHNSERVERARCH DROP CONSTRAINT RHN_SARCH_ID_NN;
ALTER TABLE RHNSERVERARCH MODIFY ID NOT NULL;

--
-- RHNSERVERARCH
--
ALTER TABLE RHNSERVERARCH DROP CONSTRAINT RHN_SARCH_LABEL_NN;
ALTER TABLE RHNSERVERARCH MODIFY LABEL NOT NULL;

--
-- RHNSERVERARCH
--
ALTER TABLE RHNSERVERARCH DROP CONSTRAINT RHN_SARCH_MODIFIED_NN;
ALTER TABLE RHNSERVERARCH MODIFY MODIFIED NOT NULL;

--
-- RHNSERVERARCH
--
ALTER TABLE RHNSERVERARCH DROP CONSTRAINT RHN_SARCH_NAME_NN;
ALTER TABLE RHNSERVERARCH MODIFY NAME NOT NULL;

--
-- RHNSATELLITECERT
--
ALTER TABLE RHNSATELLITECERT DROP CONSTRAINT RHN_SATCERT_CERT_NN;
ALTER TABLE RHNSATELLITECERT MODIFY CERT NOT NULL;

--
-- RHNSATELLITECERT
--
ALTER TABLE RHNSATELLITECERT DROP CONSTRAINT RHN_SATCERT_CREATED_NN;
ALTER TABLE RHNSATELLITECERT MODIFY CREATED NOT NULL;

--
-- RHNSATELLITECERT
--
ALTER TABLE RHNSATELLITECERT DROP CONSTRAINT RHN_SATCERT_LABEL_NN;
ALTER TABLE RHNSATELLITECERT MODIFY LABEL NOT NULL;

--
-- RHNSATELLITECERT
--
ALTER TABLE RHNSATELLITECERT DROP CONSTRAINT RHN_SATCERT_MODIFIED_NN;
ALTER TABLE RHNSATELLITECERT MODIFY MODIFIED NOT NULL;

--
-- RHN_SAT_CLUSTER
--
ALTER TABLE RHN_SAT_CLUSTER DROP CONSTRAINT RHN_SATCL_CUST_ID_NN;
ALTER TABLE RHN_SAT_CLUSTER MODIFY CUSTOMER_ID NOT NULL;

--
-- RHN_SAT_CLUSTER
--
ALTER TABLE RHN_SAT_CLUSTER DROP CONSTRAINT RHN_SATCL_DEPLOYED_NN;
ALTER TABLE RHN_SAT_CLUSTER MODIFY DEPLOYED NOT NULL;

--
-- RHN_SAT_CLUSTER
--
ALTER TABLE RHN_SAT_CLUSTER DROP CONSTRAINT RHN_SATCL_DESC_NN;
ALTER TABLE RHN_SAT_CLUSTER MODIFY DESCRIPTION NOT NULL;

--
-- RHN_SAT_CLUSTER
--
ALTER TABLE RHN_SAT_CLUSTER DROP CONSTRAINT RHN_SATCL_LOCATION_ID_NN;
ALTER TABLE RHN_SAT_CLUSTER MODIFY PHYSICAL_LOCATION_ID NOT NULL;

--
-- RHN_SAT_CLUSTER
--
ALTER TABLE RHN_SAT_CLUSTER DROP CONSTRAINT RHN_SATCL_RECID_NN;
ALTER TABLE RHN_SAT_CLUSTER MODIFY RECID NOT NULL;

--
-- RHN_SAT_CLUSTER
--
ALTER TABLE RHN_SAT_CLUSTER DROP CONSTRAINT RHN_SATCL_TARGET_TYPE_NN;
ALTER TABLE RHN_SAT_CLUSTER MODIFY TARGET_TYPE NOT NULL;

--
-- RHNSATELLITEINFO
--
ALTER TABLE RHNSATELLITEINFO DROP CONSTRAINT RHN_SATELLITE_INFO_CERT_NN;
ALTER TABLE RHNSATELLITEINFO MODIFY CERT NOT NULL;

--
-- RHNSATELLITEINFO
--
ALTER TABLE RHNSATELLITEINFO DROP CONSTRAINT RHN_SATELLITE_INFO_CREATED_NN;
ALTER TABLE RHNSATELLITEINFO MODIFY CREATED NOT NULL;

--
-- RHNSATELLITEINFO
--
ALTER TABLE RHNSATELLITEINFO DROP CONSTRAINT RHN_SATELLITE_INFO_MODIFIED_NN;
ALTER TABLE RHNSATELLITEINFO MODIFY MODIFIED NOT NULL;

--
-- RHNSATELLITEINFO
--
ALTER TABLE RHNSATELLITEINFO DROP CONSTRAINT RHN_SATELLITE_INFO_OWNER_NN;
ALTER TABLE RHNSATELLITEINFO MODIFY OWNER NOT NULL;

--
-- RHNSATELLITEINFO
--
ALTER TABLE RHNSATELLITEINFO DROP CONSTRAINT RHN_SATELLITE_INFO_PRODUCT_NN;
ALTER TABLE RHNSATELLITEINFO MODIFY PRODUCT NOT NULL;

--
-- RHNSATELLITEINFO
--
ALTER TABLE RHNSATELLITEINFO DROP CONSTRAINT RHN_SATELLITE_INFO_SID_NN;
ALTER TABLE RHNSATELLITEINFO MODIFY SERVER_ID NOT NULL;

--
-- RHN_SAT_NODE
--
ALTER TABLE RHN_SAT_NODE DROP CONSTRAINT RHN_SATND_DQ_LOG_LEVEL_NN;
ALTER TABLE RHN_SAT_NODE MODIFY DQ_LOG_LEVEL NOT NULL;

--
-- RHN_SAT_NODE
--
ALTER TABLE RHN_SAT_NODE DROP CONSTRAINT RHN_SATND_MAC_ADDRESS_NN;
ALTER TABLE RHN_SAT_NODE MODIFY MAC_ADDRESS NOT NULL;

--
-- RHN_SAT_NODE
--
ALTER TABLE RHN_SAT_NODE DROP CONSTRAINT RHN_SATND_RECID_NN;
ALTER TABLE RHN_SAT_NODE MODIFY RECID NOT NULL;

--
-- RHN_SAT_NODE
--
ALTER TABLE RHN_SAT_NODE DROP CONSTRAINT RHN_SATND_SAT_CLUSTER_ID_NN;
ALTER TABLE RHN_SAT_NODE MODIFY SAT_CLUSTER_ID NOT NULL;

--
-- RHN_SAT_NODE
--
ALTER TABLE RHN_SAT_NODE DROP CONSTRAINT RHN_SATND_SCHED_LOG_LEVEL_NN;
ALTER TABLE RHN_SAT_NODE MODIFY SCHED_LOG_LEVEL NOT NULL;

--
-- RHN_SAT_NODE
--
ALTER TABLE RHN_SAT_NODE DROP CONSTRAINT RHN_SATND_SPUT_LOG_LEVEL_NN;
ALTER TABLE RHN_SAT_NODE MODIFY SPUT_LOG_LEVEL NOT NULL;

--
-- RHN_SAT_NODE
--
ALTER TABLE RHN_SAT_NODE DROP CONSTRAINT RHN_SATND_SSK_NN;
ALTER TABLE RHN_SAT_NODE MODIFY SCOUT_SHARED_KEY NOT NULL;

--
-- RHN_SAT_NODE
--
ALTER TABLE RHN_SAT_NODE DROP CONSTRAINT RHN_SATND_TARGET_TYPE_NN;
ALTER TABLE RHN_SAT_NODE MODIFY TARGET_TYPE NOT NULL;

--
-- RHNSATELLITESERVERGROUP
--
ALTER TABLE RHNSATELLITESERVERGROUP DROP CONSTRAINT RHN_SATSG_CREAT_NN;
ALTER TABLE RHNSATELLITESERVERGROUP MODIFY CREATED NOT NULL;

--
-- RHNSATELLITESERVERGROUP
--
ALTER TABLE RHNSATELLITESERVERGROUP DROP CONSTRAINT RHN_SATSG_MOD_NN;
ALTER TABLE RHNSATELLITESERVERGROUP MODIFY MODIFIED NOT NULL;

--
-- RHNSATELLITESERVERGROUP
--
ALTER TABLE RHNSATELLITESERVERGROUP DROP CONSTRAINT RHN_SATSG_SGTYPE_NN;
ALTER TABLE RHNSATELLITESERVERGROUP MODIFY SERVER_GROUP_TYPE NOT NULL;

--
-- RHNSATELLITESERVERGROUP
--
ALTER TABLE RHNSATELLITESERVERGROUP DROP CONSTRAINT RHN_SATSG_SID_NN;
ALTER TABLE RHNSATELLITESERVERGROUP MODIFY SERVER_ID NOT NULL;

--
-- RHN_SATELLITE_STATE
--
ALTER TABLE RHN_SATELLITE_STATE DROP CONSTRAINT RHN_SATST_SAT_ID_NN;
ALTER TABLE RHN_SATELLITE_STATE MODIFY SATELLITE_ID NOT NULL;

--
-- RHNSATELLITECHANNELFAMILY
--
ALTER TABLE RHNSATELLITECHANNELFAMILY DROP CONSTRAINT RHN_SAT_CF_CFID_NN;
ALTER TABLE RHNSATELLITECHANNELFAMILY MODIFY CHANNEL_FAMILY_ID NOT NULL;

--
-- RHNSATELLITECHANNELFAMILY
--
ALTER TABLE RHNSATELLITECHANNELFAMILY DROP CONSTRAINT RHN_SAT_CF_CREATED_NN;
ALTER TABLE RHNSATELLITECHANNELFAMILY MODIFY CREATED NOT NULL;

--
-- RHNSATELLITECHANNELFAMILY
--
ALTER TABLE RHNSATELLITECHANNELFAMILY DROP CONSTRAINT RHN_SAT_CF_MODIFIED_NN;
ALTER TABLE RHNSATELLITECHANNELFAMILY MODIFY MODIFIED NOT NULL;

--
-- RHNSATELLITECHANNELFAMILY
--
ALTER TABLE RHNSATELLITECHANNELFAMILY DROP CONSTRAINT RHN_SAT_CF_SID_NN;
ALTER TABLE RHNSATELLITECHANNELFAMILY MODIFY SERVER_ID NOT NULL;

--
-- RHNSAVEDSEARCH
--
ALTER TABLE RHNSAVEDSEARCH DROP CONSTRAINT RHN_SAVEDSEARCH_ID_NN;
ALTER TABLE RHNSAVEDSEARCH MODIFY ID NOT NULL;

--
-- RHNSAVEDSEARCH
--
ALTER TABLE RHNSAVEDSEARCH DROP CONSTRAINT RHN_SAVEDSEARCH_INVERT_NN;
ALTER TABLE RHNSAVEDSEARCH MODIFY INVERT NOT NULL;

--
-- RHNSAVEDSEARCH
--
ALTER TABLE RHNSAVEDSEARCH DROP CONSTRAINT RHN_SAVEDSEARCH_NAME_NN;
ALTER TABLE RHNSAVEDSEARCH MODIFY NAME NOT NULL;

--
-- RHNSAVEDSEARCH
--
ALTER TABLE RHNSAVEDSEARCH DROP CONSTRAINT RHN_SAVEDSEARCH_SFIELD_NN;
ALTER TABLE RHNSAVEDSEARCH MODIFY SEARCH_FIELD NOT NULL;

--
-- RHNSAVEDSEARCH
--
ALTER TABLE RHNSAVEDSEARCH DROP CONSTRAINT RHN_SAVEDSEARCH_SSET_NN;
ALTER TABLE RHNSAVEDSEARCH MODIFY SEARCH_SET NOT NULL;

--
-- RHNSAVEDSEARCH
--
ALTER TABLE RHNSAVEDSEARCH DROP CONSTRAINT RHN_SAVEDSEARCH_SSTRING_NN;
ALTER TABLE RHNSAVEDSEARCH MODIFY SEARCH_STRING NOT NULL;

--
-- RHNSAVEDSEARCH
--
ALTER TABLE RHNSAVEDSEARCH DROP CONSTRAINT RHN_SAVEDSEARCH_TYPE_NN;
ALTER TABLE RHNSAVEDSEARCH MODIFY TYPE NOT NULL;

--
-- RHNSAVEDSEARCH
--
ALTER TABLE RHNSAVEDSEARCH DROP CONSTRAINT RHN_SAVEDSEARCH_WCID_NN;
ALTER TABLE RHNSAVEDSEARCH MODIFY WEB_CONTACT_ID NOT NULL;

--
-- RHNSERVERCUSTOMDATAVALUE
--
ALTER TABLE RHNSERVERCUSTOMDATAVALUE DROP CONSTRAINT RHN_SCDV_CREATED_NN;
ALTER TABLE RHNSERVERCUSTOMDATAVALUE MODIFY CREATED NOT NULL;

--
-- RHNSERVERCUSTOMDATAVALUE
--
ALTER TABLE RHNSERVERCUSTOMDATAVALUE DROP CONSTRAINT RHN_SCDV_KID_NN;
ALTER TABLE RHNSERVERCUSTOMDATAVALUE MODIFY KEY_ID NOT NULL;

--
-- RHNSERVERCUSTOMDATAVALUE
--
ALTER TABLE RHNSERVERCUSTOMDATAVALUE DROP CONSTRAINT RHN_SCDV_MODIFIED_NN;
ALTER TABLE RHNSERVERCUSTOMDATAVALUE MODIFY MODIFIED NOT NULL;

--
-- RHNSERVERCUSTOMDATAVALUE
--
ALTER TABLE RHNSERVERCUSTOMDATAVALUE DROP CONSTRAINT RHN_SCDV_SID_NN;
ALTER TABLE RHNSERVERCUSTOMDATAVALUE MODIFY SERVER_ID NOT NULL;

--
-- RHN_SCHEDULE_DAYS
--
ALTER TABLE RHN_SCHEDULE_DAYS DROP CONSTRAINT RHN_SCHDY_RECID_NN;
ALTER TABLE RHN_SCHEDULE_DAYS MODIFY RECID NOT NULL;

--
-- RHN_SCHEDULES
--
ALTER TABLE RHN_SCHEDULES DROP CONSTRAINT RHN_SCHED_DESC_NN;
ALTER TABLE RHN_SCHEDULES MODIFY DESCRIPTION NOT NULL;

--
-- RHN_SCHEDULES
--
ALTER TABLE RHN_SCHEDULES DROP CONSTRAINT RHN_SCHED_RECID_NN;
ALTER TABLE RHN_SCHEDULES MODIFY RECID NOT NULL;

--
-- RHN_SCHEDULES
--
ALTER TABLE RHN_SCHEDULES DROP CONSTRAINT RHN_SCHED_TYPE_ID_NN;
ALTER TABLE RHN_SCHEDULES MODIFY SCHEDULE_TYPE_ID NOT NULL;

--
-- RHN_SCHEDULE_TYPES
--
ALTER TABLE RHN_SCHEDULE_TYPES DROP CONSTRAINT RHN_SCHTP_RECID_NN;
ALTER TABLE RHN_SCHEDULE_TYPES MODIFY RECID NOT NULL;

--
-- RHN_SCHEDULE_WEEKS
--
ALTER TABLE RHN_SCHEDULE_WEEKS DROP CONSTRAINT RHN_SCHWK_RECID_NN;
ALTER TABLE RHN_SCHEDULE_WEEKS MODIFY RECID NOT NULL;

--
-- RHN_SCHEDULE_WEEKS
--
ALTER TABLE RHN_SCHEDULE_WEEKS DROP CONSTRAINT RHN_SCHWK_SCHED_ID_NN;
ALTER TABLE RHN_SCHEDULE_WEEKS MODIFY SCHEDULE_ID NOT NULL;

--
-- RHN_SAT_CLUSTER_PROBE
--
ALTER TABLE RHN_SAT_CLUSTER_PROBE DROP CONSTRAINT RHN_SCLPB_PROBE_ID_NN;
ALTER TABLE RHN_SAT_CLUSTER_PROBE MODIFY PROBE_ID NOT NULL;

--
-- RHN_SAT_CLUSTER_PROBE
--
ALTER TABLE RHN_SAT_CLUSTER_PROBE DROP CONSTRAINT RHN_SCLPB_PROBE_TYPE_NN;
ALTER TABLE RHN_SAT_CLUSTER_PROBE MODIFY PROBE_TYPE NOT NULL;

--
-- RHN_SAT_CLUSTER_PROBE
--
ALTER TABLE RHN_SAT_CLUSTER_PROBE DROP CONSTRAINT RHN_SCLPB_SAT_CLUSTER_ID_NN;
ALTER TABLE RHN_SAT_CLUSTER_PROBE MODIFY SAT_CLUSTER_ID NOT NULL;

--
-- RHNSERVERCHANNELARCHCOMPAT
--
ALTER TABLE RHNSERVERCHANNELARCHCOMPAT DROP CONSTRAINT RHN_SC_AC_CAID_NN;
ALTER TABLE RHNSERVERCHANNELARCHCOMPAT MODIFY CHANNEL_ARCH_ID NOT NULL;

--
-- RHNSERVERCHANNELARCHCOMPAT
--
ALTER TABLE RHNSERVERCHANNELARCHCOMPAT DROP CONSTRAINT RHN_SC_AC_CREATED_NN;
ALTER TABLE RHNSERVERCHANNELARCHCOMPAT MODIFY CREATED NOT NULL;

--
-- RHNSERVERCHANNELARCHCOMPAT
--
ALTER TABLE RHNSERVERCHANNELARCHCOMPAT DROP CONSTRAINT RHN_SC_AC_MODIFIED_NN;
ALTER TABLE RHNSERVERCHANNELARCHCOMPAT MODIFY MODIFIED NOT NULL;

--
-- RHNSERVERCHANNELARCHCOMPAT
--
ALTER TABLE RHNSERVERCHANNELARCHCOMPAT DROP CONSTRAINT RHN_SC_AC_SAID_NN;
ALTER TABLE RHNSERVERCHANNELARCHCOMPAT MODIFY SERVER_ARCH_ID NOT NULL;

--
-- RHNSERVERCHANNEL
--
ALTER TABLE RHNSERVERCHANNEL DROP CONSTRAINT RHN_SC_CID_NN;
ALTER TABLE RHNSERVERCHANNEL MODIFY CHANNEL_ID NOT NULL;

--
-- RHNSERVERCHANNEL
--
ALTER TABLE RHNSERVERCHANNEL DROP CONSTRAINT RHN_SC_CREATED_NN;
ALTER TABLE RHNSERVERCHANNEL MODIFY CREATED NOT NULL;

--
-- RHNSERVERCHANNEL
--
ALTER TABLE RHNSERVERCHANNEL DROP CONSTRAINT RHN_SC_MODIFIED_NN;
ALTER TABLE RHNSERVERCHANNEL MODIFY MODIFIED NOT NULL;

--
-- RHNSERVERCHANNEL
--
ALTER TABLE RHNSERVERCHANNEL DROP CONSTRAINT RHN_SC_SID_NN;
ALTER TABLE RHNSERVERCHANNEL MODIFY SERVER_ID NOT NULL;

--
-- RHN_SEMANTIC_DATA_TYPE
--
ALTER TABLE RHN_SEMANTIC_DATA_TYPE DROP CONSTRAINT RHN_SDTYP_DESC_NN;
ALTER TABLE RHN_SEMANTIC_DATA_TYPE MODIFY DESCRIPTION NOT NULL;

--
-- RHN_SEMANTIC_DATA_TYPE
--
ALTER TABLE RHN_SEMANTIC_DATA_TYPE DROP CONSTRAINT RHN_SDTYP_NAME_NN;
ALTER TABLE RHN_SEMANTIC_DATA_TYPE MODIFY NAME NOT NULL;

--
-- RHNSNPSERVERQUEUE
--
ALTER TABLE RHNSNPSERVERQUEUE DROP CONSTRAINT RHN_SEC_NP_PROCESSED_NN;
ALTER TABLE RHNSNPSERVERQUEUE MODIFY PROCESSED NOT NULL;

--
-- RHNSNPSERVERQUEUE
--
ALTER TABLE RHNSNPSERVERQUEUE DROP CONSTRAINT RHN_SEC_NP_SID_NN;
ALTER TABLE RHNSNPSERVERQUEUE MODIFY SERVER_ID NOT NULL;

--
-- RHNSERVERACTIONSCRIPTRESULT
--
ALTER TABLE RHNSERVERACTIONSCRIPTRESULT DROP CONSTRAINT RHN_SERVERAS_RESULT_ASID_NN;
ALTER TABLE RHNSERVERACTIONSCRIPTRESULT MODIFY ACTION_SCRIPT_ID NOT NULL;

--
-- RHNSERVERACTIONSCRIPTRESULT
--
ALTER TABLE RHNSERVERACTIONSCRIPTRESULT DROP CONSTRAINT RHN_SERVERAS_RESULT_CREAT_NN;
ALTER TABLE RHNSERVERACTIONSCRIPTRESULT MODIFY CREATED NOT NULL;

--
-- RHNSERVERACTIONSCRIPTRESULT
--
ALTER TABLE RHNSERVERACTIONSCRIPTRESULT DROP CONSTRAINT RHN_SERVERAS_RESULT_MOD_NN;
ALTER TABLE RHNSERVERACTIONSCRIPTRESULT MODIFY MODIFIED NOT NULL;

--
-- RHNSERVERACTIONSCRIPTRESULT
--
ALTER TABLE RHNSERVERACTIONSCRIPTRESULT DROP CONSTRAINT RHN_SERVERAS_RESULT_RETURN_NN;
ALTER TABLE RHNSERVERACTIONSCRIPTRESULT MODIFY RETURN_CODE NOT NULL;

--
-- RHNSERVERACTIONSCRIPTRESULT
--
ALTER TABLE RHNSERVERACTIONSCRIPTRESULT DROP CONSTRAINT RHN_SERVERAS_RESULT_SID_NN;
ALTER TABLE RHNSERVERACTIONSCRIPTRESULT MODIFY SERVER_ID NOT NULL;

--
-- RHNSERVERACTIONSCRIPTRESULT
--
ALTER TABLE RHNSERVERACTIONSCRIPTRESULT DROP CONSTRAINT RHN_SERVERAS_RESULT_START_NN;
ALTER TABLE RHNSERVERACTIONSCRIPTRESULT MODIFY START_DATE NOT NULL;

--
-- RHNSERVERACTIONSCRIPTRESULT
--
ALTER TABLE RHNSERVERACTIONSCRIPTRESULT DROP CONSTRAINT RHN_SERVERAS_RESULT_STOP_NN;
ALTER TABLE RHNSERVERACTIONSCRIPTRESULT MODIFY STOP_DATE NOT NULL;

--
-- RHNSERVERCONFIGCHANNEL
--
ALTER TABLE RHNSERVERCONFIGCHANNEL DROP CONSTRAINT RHN_SERVERCC_CCID_NN;
ALTER TABLE RHNSERVERCONFIGCHANNEL MODIFY CONFIG_CHANNEL_ID NOT NULL;

--
-- RHNSERVERCONFIGCHANNEL
--
ALTER TABLE RHNSERVERCONFIGCHANNEL DROP CONSTRAINT RHN_SERVERCC_CREAT_NN;
ALTER TABLE RHNSERVERCONFIGCHANNEL MODIFY CREATED NOT NULL;

--
-- RHNSERVERCONFIGCHANNEL
--
ALTER TABLE RHNSERVERCONFIGCHANNEL DROP CONSTRAINT RHN_SERVERCC_MOD_NN;
ALTER TABLE RHNSERVERCONFIGCHANNEL MODIFY MODIFIED NOT NULL;

--
-- RHNSERVERCONFIGCHANNEL
--
ALTER TABLE RHNSERVERCONFIGCHANNEL DROP CONSTRAINT RHN_SERVERCC_SID_NN;
ALTER TABLE RHNSERVERCONFIGCHANNEL MODIFY SERVER_ID NOT NULL;

--
-- RHNSERVERGROUPTYPE
--
ALTER TABLE RHNSERVERGROUPTYPE DROP CONSTRAINT RHN_SERVERGROUPTYPE_CREATED_NN;
ALTER TABLE RHNSERVERGROUPTYPE MODIFY CREATED NOT NULL;

--
-- RHNSERVERGROUPTYPE
--
ALTER TABLE RHNSERVERGROUPTYPE DROP CONSTRAINT RHN_SERVERGROUPTYPE_ID_NN;
ALTER TABLE RHNSERVERGROUPTYPE MODIFY ID NOT NULL;

--
-- RHNSERVERGROUPTYPE
--
ALTER TABLE RHNSERVERGROUPTYPE DROP CONSTRAINT RHN_SERVERGROUPTYPE_ISBASE_NN;
ALTER TABLE RHNSERVERGROUPTYPE MODIFY IS_BASE NOT NULL;

--
-- RHNSERVERGROUPTYPE
--
ALTER TABLE RHNSERVERGROUPTYPE DROP CONSTRAINT RHN_SERVERGROUPTYPE_LABEL_NN;
ALTER TABLE RHNSERVERGROUPTYPE MODIFY LABEL NOT NULL;

--
-- RHNSERVERGROUPTYPE
--
ALTER TABLE RHNSERVERGROUPTYPE DROP CONSTRAINT RHN_SERVERGROUPTYPE_MOD_NN;
ALTER TABLE RHNSERVERGROUPTYPE MODIFY MODIFIED NOT NULL;

--
-- RHNSERVERGROUPTYPE
--
ALTER TABLE RHNSERVERGROUPTYPE DROP CONSTRAINT RHN_SERVERGROUPTYPE_NAME_NN;
ALTER TABLE RHNSERVERGROUPTYPE MODIFY NAME NOT NULL;

--
-- RHNSERVERGROUPTYPE
--
ALTER TABLE RHNSERVERGROUPTYPE DROP CONSTRAINT RHN_SERVERGROUPTYPE_PERM_NN;
ALTER TABLE RHNSERVERGROUPTYPE MODIFY PERMANENT NOT NULL;

--
-- RHNSERVERGROUP
--
ALTER TABLE RHNSERVERGROUP DROP CONSTRAINT RHN_SERVERGROUP_CREATED_NN;
ALTER TABLE RHNSERVERGROUP MODIFY CREATED NOT NULL;

--
-- RHNSERVERGROUP
--
ALTER TABLE RHNSERVERGROUP DROP CONSTRAINT RHN_SERVERGROUP_CURMEMBERS_NN;
ALTER TABLE RHNSERVERGROUP MODIFY CURRENT_MEMBERS NOT NULL;

--
-- RHNSERVERGROUP
--
ALTER TABLE RHNSERVERGROUP DROP CONSTRAINT RHN_SERVERGROUP_DESC_NN;
ALTER TABLE RHNSERVERGROUP MODIFY DESCRIPTION NOT NULL;

--
-- RHNSERVERGROUP
--
ALTER TABLE RHNSERVERGROUP DROP CONSTRAINT RHN_SERVERGROUP_ID_NN;
ALTER TABLE RHNSERVERGROUP MODIFY ID NOT NULL;

--
-- RHNSERVERGROUP
--
ALTER TABLE RHNSERVERGROUP DROP CONSTRAINT RHN_SERVERGROUP_MODIFIED_NN;
ALTER TABLE RHNSERVERGROUP MODIFY MODIFIED NOT NULL;

--
-- RHNSERVERGROUP
--
ALTER TABLE RHNSERVERGROUP DROP CONSTRAINT RHN_SERVERGROUP_NAME_NN;
ALTER TABLE RHNSERVERGROUP MODIFY NAME NOT NULL;

--
-- RHNSERVERGROUP
--
ALTER TABLE RHNSERVERGROUP DROP CONSTRAINT RHN_SERVERGROUP_OID_NN;
ALTER TABLE RHNSERVERGROUP MODIFY ORG_ID NOT NULL;

--
-- RHNSERVERGROUPNOTES
--
ALTER TABLE RHNSERVERGROUPNOTES DROP CONSTRAINT RHN_SERVERGRP_NOTE_CREATED_NN;
ALTER TABLE RHNSERVERGROUPNOTES MODIFY CREATED NOT NULL;

--
-- RHNSERVERGROUPNOTES
--
ALTER TABLE RHNSERVERGROUPNOTES DROP CONSTRAINT RHN_SERVERGRP_NOTE_ID_NN;
ALTER TABLE RHNSERVERGROUPNOTES MODIFY ID NOT NULL;

--
-- RHNSERVERGROUPNOTES
--
ALTER TABLE RHNSERVERGROUPNOTES DROP CONSTRAINT RHN_SERVERGRP_NOTE_MODIFIED_NN;
ALTER TABLE RHNSERVERGROUPNOTES MODIFY MODIFIED NOT NULL;

--
-- RHNSERVERGROUPNOTES
--
ALTER TABLE RHNSERVERGROUPNOTES DROP CONSTRAINT RHN_SERVERGRP_NOTE_NN;
ALTER TABLE RHNSERVERGROUPNOTES MODIFY SERVER_GROUP_ID NOT NULL;

--
-- RHNSERVERGROUPNOTES
--
ALTER TABLE RHNSERVERGROUPNOTES DROP CONSTRAINT RHN_SERVERGRP_NOTE_NOTE_NN;
ALTER TABLE RHNSERVERGROUPNOTES MODIFY NOTE NOT NULL;

--
-- RHNSERVERGROUPNOTES
--
ALTER TABLE RHNSERVERGROUPNOTES DROP CONSTRAINT RHN_SERVERGRP_NOTE_SUBJECT_NN;
ALTER TABLE RHNSERVERGROUPNOTES MODIFY SUBJECT NOT NULL;

--
-- RHNSERVERHISTORY
--
ALTER TABLE RHNSERVERHISTORY DROP CONSTRAINT RHN_SERVERHISTORY_CREATED_NN;
ALTER TABLE RHNSERVERHISTORY MODIFY CREATED NOT NULL;

--
-- RHNSERVERHISTORY
--
ALTER TABLE RHNSERVERHISTORY DROP CONSTRAINT RHN_SERVERHISTORY_ID_NN;
ALTER TABLE RHNSERVERHISTORY MODIFY ID NOT NULL;

--
-- RHNSERVERHISTORY
--
ALTER TABLE RHNSERVERHISTORY DROP CONSTRAINT RHN_SERVERHISTORY_MODIFIED_NN;
ALTER TABLE RHNSERVERHISTORY MODIFY MODIFIED NOT NULL;

--
-- RHNSERVERHISTORY
--
ALTER TABLE RHNSERVERHISTORY DROP CONSTRAINT RHN_SERVERHISTORY_SID_NN;
ALTER TABLE RHNSERVERHISTORY MODIFY SERVER_ID NOT NULL;

--
-- RHNSERVERHISTORY
--
ALTER TABLE RHNSERVERHISTORY DROP CONSTRAINT RHN_SERVERHISTORY_SUMMARY_NN;
ALTER TABLE RHNSERVERHISTORY MODIFY SUMMARY NOT NULL;

--
-- RHNSERVERLOCATION
--
ALTER TABLE RHNSERVERLOCATION DROP CONSTRAINT RHN_SERVERLOCATION_CREATED_NN;
ALTER TABLE RHNSERVERLOCATION MODIFY CREATED NOT NULL;

--
-- RHNSERVERLOCATION
--
ALTER TABLE RHNSERVERLOCATION DROP CONSTRAINT RHN_SERVERLOCATION_ID_NN;
ALTER TABLE RHNSERVERLOCATION MODIFY ID NOT NULL;

--
-- RHNSERVERLOCATION
--
ALTER TABLE RHNSERVERLOCATION DROP CONSTRAINT RHN_SERVERLOCATION_MODIFIED_NN;
ALTER TABLE RHNSERVERLOCATION MODIFY MODIFIED NOT NULL;

--
-- RHNSERVERLOCATION
--
ALTER TABLE RHNSERVERLOCATION DROP CONSTRAINT RHN_SERVERLOCATION_SID_NN;
ALTER TABLE RHNSERVERLOCATION MODIFY SERVER_ID NOT NULL;

--
-- RHNSERVERNETWORK
--
ALTER TABLE RHNSERVERNETWORK DROP CONSTRAINT RHN_SERVERNETWORK_CREATED_NN;
ALTER TABLE RHNSERVERNETWORK MODIFY CREATED NOT NULL;

--
-- RHNSERVERNETWORK
--
ALTER TABLE RHNSERVERNETWORK DROP CONSTRAINT RHN_SERVERNETWORK_ID_NN;
ALTER TABLE RHNSERVERNETWORK MODIFY ID NOT NULL;

--
-- RHNSERVERNETWORK
--
ALTER TABLE RHNSERVERNETWORK DROP CONSTRAINT RHN_SERVERNETWORK_MODIFIED_NN;
ALTER TABLE RHNSERVERNETWORK MODIFY MODIFIED NOT NULL;

--
-- RHNSERVERNETWORK
--
ALTER TABLE RHNSERVERNETWORK DROP CONSTRAINT RHN_SERVERNETWORK_SID_NN;
ALTER TABLE RHNSERVERNETWORK MODIFY SERVER_ID NOT NULL;

--
-- RHNSERVERNOTES
--
ALTER TABLE RHNSERVERNOTES DROP CONSTRAINT RHN_SERVERNOTES_CREATED_NN;
ALTER TABLE RHNSERVERNOTES MODIFY CREATED NOT NULL;

--
-- RHNSERVERNOTES
--
ALTER TABLE RHNSERVERNOTES DROP CONSTRAINT RHN_SERVERNOTES_ID_NN;
ALTER TABLE RHNSERVERNOTES MODIFY ID NOT NULL;

--
-- RHNSERVERNOTES
--
ALTER TABLE RHNSERVERNOTES DROP CONSTRAINT RHN_SERVERNOTES_MODIFIED_NN;
ALTER TABLE RHNSERVERNOTES MODIFY MODIFIED NOT NULL;

--
-- RHNSERVERNOTES
--
ALTER TABLE RHNSERVERNOTES DROP CONSTRAINT RHN_SERVERNOTES_SID_NN;
ALTER TABLE RHNSERVERNOTES MODIFY SERVER_ID NOT NULL;

--
-- RHNSERVERNOTES
--
ALTER TABLE RHNSERVERNOTES DROP CONSTRAINT RHN_SERVERNOTES_SUBJECT_NN;
ALTER TABLE RHNSERVERNOTES MODIFY SUBJECT NOT NULL;

--
-- RHNSERVERPACKAGE
--
ALTER TABLE RHNSERVERPACKAGE DROP CONSTRAINT RHN_SERVERPACKAGE_EID_NN;
ALTER TABLE RHNSERVERPACKAGE MODIFY EVR_ID NOT NULL;

--
-- RHNSERVERPACKAGE
--
ALTER TABLE RHNSERVERPACKAGE DROP CONSTRAINT RHN_SERVERPACKAGE_NID_NN;
ALTER TABLE RHNSERVERPACKAGE MODIFY NAME_ID NOT NULL;

--
-- RHNSERVERPACKAGE
--
ALTER TABLE RHNSERVERPACKAGE DROP CONSTRAINT RHN_SERVERPACKAGE_SID_NN;
ALTER TABLE RHNSERVERPACKAGE MODIFY SERVER_ID NOT NULL;

--
-- RHNSERVERPATH
--
ALTER TABLE RHNSERVERPATH DROP CONSTRAINT RHN_SERVERPATH_CREAT_NN;
ALTER TABLE RHNSERVERPATH MODIFY CREATED NOT NULL;

--
-- RHNSERVERPATH
--
ALTER TABLE RHNSERVERPATH DROP CONSTRAINT RHN_SERVERPATH_HOSTNAME_NN;
ALTER TABLE RHNSERVERPATH MODIFY HOSTNAME NOT NULL;

--
-- RHNSERVERPATH
--
ALTER TABLE RHNSERVERPATH DROP CONSTRAINT RHN_SERVERPATH_MOD_NN;
ALTER TABLE RHNSERVERPATH MODIFY MODIFIED NOT NULL;

--
-- RHNSERVERPATH
--
ALTER TABLE RHNSERVERPATH DROP CONSTRAINT RHN_SERVERPATH_POS_NN;
ALTER TABLE RHNSERVERPATH MODIFY POSITION NOT NULL;

--
-- RHNSERVERPATH
--
ALTER TABLE RHNSERVERPATH DROP CONSTRAINT RHN_SERVERPATH_PSID_NN;
ALTER TABLE RHNSERVERPATH MODIFY PROXY_SERVER_ID NOT NULL;

--
-- RHNSERVERPATH
--
ALTER TABLE RHNSERVERPATH DROP CONSTRAINT RHN_SERVERPATH_SID_NN;
ALTER TABLE RHNSERVERPATH MODIFY SERVER_ID NOT NULL;

--
-- RHNSERVERPRESERVEFILELIST
--
ALTER TABLE RHNSERVERPRESERVEFILELIST DROP CONSTRAINT RHN_SERVERPFL_CREAT_NN;
ALTER TABLE RHNSERVERPRESERVEFILELIST MODIFY CREATED NOT NULL;

--
-- RHNSERVERPRESERVEFILELIST
--
ALTER TABLE RHNSERVERPRESERVEFILELIST DROP CONSTRAINT RHN_SERVERPFL_FLID_NN;
ALTER TABLE RHNSERVERPRESERVEFILELIST MODIFY FILE_LIST_ID NOT NULL;

--
-- RHNSERVERPRESERVEFILELIST
--
ALTER TABLE RHNSERVERPRESERVEFILELIST DROP CONSTRAINT RHN_SERVERPFL_KSID_NN;
ALTER TABLE RHNSERVERPRESERVEFILELIST MODIFY SERVER_ID NOT NULL;

--
-- RHNSERVERPRESERVEFILELIST
--
ALTER TABLE RHNSERVERPRESERVEFILELIST DROP CONSTRAINT RHN_SERVERPFL_MOD_NN;
ALTER TABLE RHNSERVERPRESERVEFILELIST MODIFY MODIFIED NOT NULL;

--
-- RHNSERVERACTION
--
ALTER TABLE RHNSERVERACTION DROP CONSTRAINT RHN_SERVER_ACTION_AID_NN;
ALTER TABLE RHNSERVERACTION MODIFY ACTION_ID NOT NULL;

--
-- RHNSERVERACTION
--
ALTER TABLE RHNSERVERACTION DROP CONSTRAINT RHN_SERVER_ACTION_CREATED_NN;
ALTER TABLE RHNSERVERACTION MODIFY CREATED NOT NULL;

--
-- RHNSERVERACTION
--
ALTER TABLE RHNSERVERACTION DROP CONSTRAINT RHN_SERVER_ACTION_MODIFIED_NN;
ALTER TABLE RHNSERVERACTION MODIFY MODIFIED NOT NULL;

--
-- RHNSERVERACTION
--
ALTER TABLE RHNSERVERACTION DROP CONSTRAINT RHN_SERVER_ACTION_REMAINING_NN;
ALTER TABLE RHNSERVERACTION MODIFY REMAINING_TRIES NOT NULL;

--
-- RHNSERVERACTION
--
ALTER TABLE RHNSERVERACTION DROP CONSTRAINT RHN_SERVER_ACTION_SID_NN;
ALTER TABLE RHNSERVERACTION MODIFY SERVER_ID NOT NULL;

--
-- RHNSERVERACTION
--
ALTER TABLE RHNSERVERACTION DROP CONSTRAINT RHN_SERVER_ACTION_STATUS_NN;
ALTER TABLE RHNSERVERACTION MODIFY STATUS NOT NULL;

--
-- RHNSERVER
--
ALTER TABLE RHNSERVER DROP CONSTRAINT RHN_SERVER_AUTO_DELIVER_NN;
ALTER TABLE RHNSERVER MODIFY AUTO_DELIVER NOT NULL;

--
-- RHNSERVER
--
ALTER TABLE RHNSERVER DROP CONSTRAINT RHN_SERVER_AUTO_UPDATE_NN;
ALTER TABLE RHNSERVER MODIFY AUTO_UPDATE NOT NULL;

--
-- RHNSERVERCACHEINFO
--
ALTER TABLE RHNSERVERCACHEINFO DROP CONSTRAINT RHN_SERVER_CACHE_INFO_SID_NN;
ALTER TABLE RHNSERVERCACHEINFO MODIFY SERVER_ID NOT NULL;

--
-- RHNSERVER
--
ALTER TABLE RHNSERVER DROP CONSTRAINT RHN_SERVER_CREATED_NN;
ALTER TABLE RHNSERVER MODIFY CREATED NOT NULL;

--
-- RHNSERVERDMI
--
ALTER TABLE RHNSERVERDMI DROP CONSTRAINT RHN_SERVER_DMI_CREATED_NN;
ALTER TABLE RHNSERVERDMI MODIFY CREATED NOT NULL;

--
-- RHNSERVERDMI
--
ALTER TABLE RHNSERVERDMI DROP CONSTRAINT RHN_SERVER_DMI_ID_NN;
ALTER TABLE RHNSERVERDMI MODIFY ID NOT NULL;

--
-- RHNSERVERDMI
--
ALTER TABLE RHNSERVERDMI DROP CONSTRAINT RHN_SERVER_DMI_MODIFIED_NN;
ALTER TABLE RHNSERVERDMI MODIFY MODIFIED NOT NULL;

--
-- RHNSERVERDMI
--
ALTER TABLE RHNSERVERDMI DROP CONSTRAINT RHN_SERVER_DMI_SID_NN;
ALTER TABLE RHNSERVERDMI MODIFY SERVER_ID NOT NULL;

--
-- RHNSERVER
--
ALTER TABLE RHNSERVER DROP CONSTRAINT RHN_SERVER_DSI_NN;
ALTER TABLE RHNSERVER MODIFY DIGITAL_SERVER_ID NOT NULL;

--
-- RHNSERVER
--
ALTER TABLE RHNSERVER DROP CONSTRAINT RHN_SERVER_ID_NN;
ALTER TABLE RHNSERVER MODIFY ID NOT NULL;

--
-- RHNSERVERINFO
--
ALTER TABLE RHNSERVERINFO DROP CONSTRAINT RHN_SERVER_INFO_SID_NN;
ALTER TABLE RHNSERVERINFO MODIFY SERVER_ID NOT NULL;

--
-- RHNSERVERINSTALLINFO
--
ALTER TABLE RHNSERVERINSTALLINFO DROP CONSTRAINT RHN_SERVER_INSTALL_INFO_CR_NN;
ALTER TABLE RHNSERVERINSTALLINFO MODIFY CREATED NOT NULL;

--
-- RHNSERVERINSTALLINFO
--
ALTER TABLE RHNSERVERINSTALLINFO DROP CONSTRAINT RHN_SERVER_INSTALL_INFO_ID_NN;
ALTER TABLE RHNSERVERINSTALLINFO MODIFY ID NOT NULL;

--
-- RHNSERVERINSTALLINFO
--
ALTER TABLE RHNSERVERINSTALLINFO DROP CONSTRAINT RHN_SERVER_INSTALL_INFO_IM_NN;
ALTER TABLE RHNSERVERINSTALLINFO MODIFY INSTALL_METHOD NOT NULL;

--
-- RHNSERVERINSTALLINFO
--
ALTER TABLE RHNSERVERINSTALLINFO DROP CONSTRAINT RHN_SERVER_INSTALL_INFO_MD_NN;
ALTER TABLE RHNSERVERINSTALLINFO MODIFY MODIFIED NOT NULL;

--
-- RHNSERVERINSTALLINFO
--
ALTER TABLE RHNSERVERINSTALLINFO DROP CONSTRAINT RHN_SERVER_INSTALL_INFO_SID_NN;
ALTER TABLE RHNSERVERINSTALLINFO MODIFY SERVER_ID NOT NULL;

--
-- RHNSERVER
--
ALTER TABLE RHNSERVER DROP CONSTRAINT RHN_SERVER_LB_NN;
ALTER TABLE RHNSERVER MODIFY LAST_BOOT NOT NULL;

--
-- RHNSERVERLOCK
--
ALTER TABLE RHNSERVERLOCK DROP CONSTRAINT RHN_SERVER_LOCK_CREATED_NN;
ALTER TABLE RHNSERVERLOCK MODIFY CREATED NOT NULL;

--
-- RHNSERVERLOCK
--
ALTER TABLE RHNSERVERLOCK DROP CONSTRAINT RHN_SERVER_LOCK_SID_NN;
ALTER TABLE RHNSERVERLOCK MODIFY SERVER_ID NOT NULL;

--
-- RHNSERVER
--
ALTER TABLE RHNSERVER DROP CONSTRAINT RHN_SERVER_MODIFIED_NN;
ALTER TABLE RHNSERVER MODIFY MODIFIED NOT NULL;

--
-- RHNSERVER
--
ALTER TABLE RHNSERVER DROP CONSTRAINT RHN_SERVER_OID_NN;
ALTER TABLE RHNSERVER MODIFY ORG_ID NOT NULL;

--
-- RHNSERVER
--
ALTER TABLE RHNSERVER DROP CONSTRAINT RHN_SERVER_OS_NN;
ALTER TABLE RHNSERVER MODIFY OS NOT NULL;

--
-- RHNSERVERPROFILE
--
ALTER TABLE RHNSERVERPROFILE DROP CONSTRAINT RHN_SERVER_PROFILE_BCID_NN;
ALTER TABLE RHNSERVERPROFILE MODIFY BASE_CHANNEL NOT NULL;

--
-- RHNSERVERPROFILE
--
ALTER TABLE RHNSERVERPROFILE DROP CONSTRAINT RHN_SERVER_PROFILE_CREATED_NN;
ALTER TABLE RHNSERVERPROFILE MODIFY CREATED NOT NULL;

--
-- RHNSERVERPROFILE
--
ALTER TABLE RHNSERVERPROFILE DROP CONSTRAINT RHN_SERVER_PROFILE_ID_NN;
ALTER TABLE RHNSERVERPROFILE MODIFY ID NOT NULL;

--
-- RHNSERVERPROFILE
--
ALTER TABLE RHNSERVERPROFILE DROP CONSTRAINT RHN_SERVER_PROFILE_MODIFIED_NN;
ALTER TABLE RHNSERVERPROFILE MODIFY MODIFIED NOT NULL;

--
-- RHNSERVERPROFILE
--
ALTER TABLE RHNSERVERPROFILE DROP CONSTRAINT RHN_SERVER_PROFILE_OID_NN;
ALTER TABLE RHNSERVERPROFILE MODIFY ORG_ID NOT NULL;

--
-- RHNSERVERPROFILE
--
ALTER TABLE RHNSERVERPROFILE DROP CONSTRAINT RHN_SERVER_PROFILE_PTYPE_NN;
ALTER TABLE RHNSERVERPROFILE MODIFY PROFILE_TYPE_ID NOT NULL;

--
-- RHNSERVER
--
ALTER TABLE RHNSERVER DROP CONSTRAINT RHN_SERVER_RELEASE_NN;
ALTER TABLE RHNSERVER MODIFY RELEASE NOT NULL;

--
-- RHNSERVER
--
ALTER TABLE RHNSERVER DROP CONSTRAINT RHN_SERVER_SAID_NN;
ALTER TABLE RHNSERVER MODIFY SERVER_ARCH_ID NOT NULL;

--
-- RHNSERVER
--
ALTER TABLE RHNSERVER DROP CONSTRAINT RHN_SERVER_SECRET_NN;
ALTER TABLE RHNSERVER MODIFY SECRET NOT NULL;

--
-- RHNSERVERUUID
--
ALTER TABLE RHNSERVERUUID DROP CONSTRAINT RHN_SERVER_UUID_SID_NN;
ALTER TABLE RHNSERVERUUID MODIFY SERVER_ID NOT NULL;

--
-- RHNSERVERUUID
--
ALTER TABLE RHNSERVERUUID DROP CONSTRAINT RHN_SERVER_UUID_UUID_NN;
ALTER TABLE RHNSERVERUUID MODIFY UUID NOT NULL;

--
-- RHNSET
--
ALTER TABLE RHNSET DROP CONSTRAINT RHN_SET_ELEM_NN;
ALTER TABLE RHNSET MODIFY "ELEMENT" NOT NULL;

--
-- RHNSET
--
ALTER TABLE RHNSET DROP CONSTRAINT RHN_SET_LABEL_NN;
ALTER TABLE RHNSET MODIFY LABEL NOT NULL;

--
-- RHNSET
--
ALTER TABLE RHNSET DROP CONSTRAINT RHN_SET_USER_NN;
ALTER TABLE RHNSET MODIFY USER_ID NOT NULL;

--
-- RHNSERVEREVENT
--
ALTER TABLE RHNSERVEREVENT DROP CONSTRAINT RHN_SE_CREATED_NN;
ALTER TABLE RHNSERVEREVENT MODIFY CREATED NOT NULL;

--
-- RHNSERVEREVENT
--
ALTER TABLE RHNSERVEREVENT DROP CONSTRAINT RHN_SE_DETAILS_NN;
ALTER TABLE RHNSERVEREVENT MODIFY DETAILS NOT NULL;

--
-- RHNSERVEREVENT
--
ALTER TABLE RHNSERVEREVENT DROP CONSTRAINT RHN_SE_ID_NN;
ALTER TABLE RHNSERVEREVENT MODIFY ID NOT NULL;

--
-- RHNSERVEREVENT
--
ALTER TABLE RHNSERVEREVENT DROP CONSTRAINT RHN_SE_MODIFIED_NN;
ALTER TABLE RHNSERVEREVENT MODIFY MODIFIED NOT NULL;

--
-- RHNSERVEREVENT
--
ALTER TABLE RHNSERVEREVENT DROP CONSTRAINT RHN_SE_SERVER_ID_NN;
ALTER TABLE RHNSERVEREVENT MODIFY SERVER_ID NOT NULL;

--
-- RHNSGTYPEVIRTSUBLEVEL
--
ALTER TABLE RHNSGTYPEVIRTSUBLEVEL DROP CONSTRAINT RHN_SGTVSL_CREATED_NN;
ALTER TABLE RHNSGTYPEVIRTSUBLEVEL MODIFY CREATED NOT NULL;

--
-- RHNSGTYPEVIRTSUBLEVEL
--
ALTER TABLE RHNSGTYPEVIRTSUBLEVEL DROP CONSTRAINT RHN_SGTVSL_MODIFIED_NN;
ALTER TABLE RHNSGTYPEVIRTSUBLEVEL MODIFY MODIFIED NOT NULL;

--
-- RHNSGTYPEVIRTSUBLEVEL
--
ALTER TABLE RHNSGTYPEVIRTSUBLEVEL DROP CONSTRAINT RHN_SGTVSL_SGTID_NN;
ALTER TABLE RHNSGTYPEVIRTSUBLEVEL MODIFY SERVER_GROUP_TYPE_ID NOT NULL;

--
-- RHNSGTYPEVIRTSUBLEVEL
--
ALTER TABLE RHNSGTYPEVIRTSUBLEVEL DROP CONSTRAINT RHN_SGTVSL_VSLID_NN;
ALTER TABLE RHNSGTYPEVIRTSUBLEVEL MODIFY VIRT_SUB_LEVEL_ID NOT NULL;

--
-- RHNSGTYPEBASEADDONCOMPAT
--
ALTER TABLE RHNSGTYPEBASEADDONCOMPAT DROP CONSTRAINT RHN_SGT_BAC_AID_NN;
ALTER TABLE RHNSGTYPEBASEADDONCOMPAT MODIFY ADDON_ID NOT NULL;

--
-- RHNSGTYPEBASEADDONCOMPAT
--
ALTER TABLE RHNSGTYPEBASEADDONCOMPAT DROP CONSTRAINT RHN_SGT_BAC_BID_NN;
ALTER TABLE RHNSGTYPEBASEADDONCOMPAT MODIFY BASE_ID NOT NULL;

--
-- RHNSERVERGROUPTYPEFEATURE
--
ALTER TABLE RHNSERVERGROUPTYPEFEATURE DROP CONSTRAINT RHN_SGT_FEAT_CREATED_NN;
ALTER TABLE RHNSERVERGROUPTYPEFEATURE MODIFY CREATED NOT NULL;

--
-- RHNSERVERGROUPTYPEFEATURE
--
ALTER TABLE RHNSERVERGROUPTYPEFEATURE DROP CONSTRAINT RHN_SGT_FEAT_MOD_NN;
ALTER TABLE RHNSERVERGROUPTYPEFEATURE MODIFY MODIFIED NOT NULL;

--
-- RHNSERVERGROUPTYPEFEATURE
--
ALTER TABLE RHNSERVERGROUPTYPEFEATURE DROP CONSTRAINT RHN_SGT_FID_NN;
ALTER TABLE RHNSERVERGROUPTYPEFEATURE MODIFY FEATURE_ID NOT NULL;

--
-- RHNSERVERGROUPTYPEFEATURE
--
ALTER TABLE RHNSERVERGROUPTYPEFEATURE DROP CONSTRAINT RHN_SGT_SGTID_NN;
ALTER TABLE RHNSERVERGROUPTYPEFEATURE MODIFY SERVER_GROUP_TYPE_ID NOT NULL;

--
-- RHNSERVERGROUPMEMBERS
--
ALTER TABLE RHNSERVERGROUPMEMBERS DROP CONSTRAINT RHN_SG_GROUP_NN;
ALTER TABLE RHNSERVERGROUPMEMBERS MODIFY SERVER_GROUP_ID NOT NULL;

--
-- RHNSERVERGROUPMEMBERS
--
ALTER TABLE RHNSERVERGROUPMEMBERS DROP CONSTRAINT RHN_SG_MEMBERS_NN;
ALTER TABLE RHNSERVERGROUPMEMBERS MODIFY SERVER_ID NOT NULL;

--
-- RHNSERVERGROUPMEMBERS
--
ALTER TABLE RHNSERVERGROUPMEMBERS DROP CONSTRAINT RHN_SG_MEMBER_CRE_NN;
ALTER TABLE RHNSERVERGROUPMEMBERS MODIFY CREATED NOT NULL;

--
-- RHNSERVERGROUPMEMBERS
--
ALTER TABLE RHNSERVERGROUPMEMBERS DROP CONSTRAINT RHN_SG_MEMBER_MOD_NN;
ALTER TABLE RHNSERVERGROUPMEMBERS MODIFY MODIFIED NOT NULL;

--
-- RHNSERVERMESSAGE
--
ALTER TABLE RHNSERVERMESSAGE DROP CONSTRAINT RHN_SM_CREATED_NN;
ALTER TABLE RHNSERVERMESSAGE MODIFY CREATED NOT NULL;

--
-- RHNSERVERMESSAGE
--
ALTER TABLE RHNSERVERMESSAGE DROP CONSTRAINT RHN_SM_MESSAGE_ID_NN;
ALTER TABLE RHNSERVERMESSAGE MODIFY MESSAGE_ID NOT NULL;

--
-- RHNSERVERMESSAGE
--
ALTER TABLE RHNSERVERMESSAGE DROP CONSTRAINT RHN_SM_MODIFIED_NN;
ALTER TABLE RHNSERVERMESSAGE MODIFY MODIFIED NOT NULL;

--
-- RHNSERVERMESSAGE
--
ALTER TABLE RHNSERVERMESSAGE DROP CONSTRAINT RHN_SM_SERVER_ID_NN;
ALTER TABLE RHNSERVERMESSAGE MODIFY SERVER_ID NOT NULL;

--
-- RHNSNAPSHOTCHANNEL
--
ALTER TABLE RHNSNAPSHOTCHANNEL DROP CONSTRAINT RHN_SNAPCHAN_CID_NN;
ALTER TABLE RHNSNAPSHOTCHANNEL MODIFY CHANNEL_ID NOT NULL;

--
-- RHNSNAPSHOTCHANNEL
--
ALTER TABLE RHNSNAPSHOTCHANNEL DROP CONSTRAINT RHN_SNAPCHAN_SID_NN;
ALTER TABLE RHNSNAPSHOTCHANNEL MODIFY SNAPSHOT_ID NOT NULL;

--
-- RHNSNAPSHOTCONFIGCHANNEL
--
ALTER TABLE RHNSNAPSHOTCONFIGCHANNEL DROP CONSTRAINT RHN_SNAPSHOTCC_CCID_NN;
ALTER TABLE RHNSNAPSHOTCONFIGCHANNEL MODIFY CONFIG_CHANNEL_ID NOT NULL;

--
-- RHNSNAPSHOTCONFIGCHANNEL
--
ALTER TABLE RHNSNAPSHOTCONFIGCHANNEL DROP CONSTRAINT RHN_SNAPSHOTCC_CREAT_NN;
ALTER TABLE RHNSNAPSHOTCONFIGCHANNEL MODIFY CREATED NOT NULL;

--
-- RHNSNAPSHOTCONFIGCHANNEL
--
ALTER TABLE RHNSNAPSHOTCONFIGCHANNEL DROP CONSTRAINT RHN_SNAPSHOTCC_MOD_NN;
ALTER TABLE RHNSNAPSHOTCONFIGCHANNEL MODIFY MODIFIED NOT NULL;

--
-- RHNSNAPSHOTCONFIGCHANNEL
--
ALTER TABLE RHNSNAPSHOTCONFIGCHANNEL DROP CONSTRAINT RHN_SNAPSHOTCC_SID_NN;
ALTER TABLE RHNSNAPSHOTCONFIGCHANNEL MODIFY SNAPSHOT_ID NOT NULL;

--
-- RHNSNAPSHOTCONFIGREVISION
--
ALTER TABLE RHNSNAPSHOTCONFIGREVISION DROP CONSTRAINT RHN_SNAPSHOTCR_CREAT_NN;
ALTER TABLE RHNSNAPSHOTCONFIGREVISION MODIFY CREATED NOT NULL;

--
-- RHNSNAPSHOTCONFIGREVISION
--
ALTER TABLE RHNSNAPSHOTCONFIGREVISION DROP CONSTRAINT RHN_SNAPSHOTCR_CRID_NN;
ALTER TABLE RHNSNAPSHOTCONFIGREVISION MODIFY CONFIG_REVISION_ID NOT NULL;

--
-- RHNSNAPSHOTCONFIGREVISION
--
ALTER TABLE RHNSNAPSHOTCONFIGREVISION DROP CONSTRAINT RHN_SNAPSHOTCR_MOD_NN;
ALTER TABLE RHNSNAPSHOTCONFIGREVISION MODIFY MODIFIED NOT NULL;

--
-- RHNSNAPSHOTCONFIGREVISION
--
ALTER TABLE RHNSNAPSHOTCONFIGREVISION DROP CONSTRAINT RHN_SNAPSHOTCR_SID_NN;
ALTER TABLE RHNSNAPSHOTCONFIGREVISION MODIFY SNAPSHOT_ID NOT NULL;

--
-- RHNSNAPSHOTPACKAGE
--
ALTER TABLE RHNSNAPSHOTPACKAGE DROP CONSTRAINT RHN_SNAPSHOTPKG_NID_NN;
ALTER TABLE RHNSNAPSHOTPACKAGE MODIFY NEVRA_ID NOT NULL;

--
-- RHNSNAPSHOTPACKAGE
--
ALTER TABLE RHNSNAPSHOTPACKAGE DROP CONSTRAINT RHN_SNAPSHOTPKG_SID_NN;
ALTER TABLE RHNSNAPSHOTPACKAGE MODIFY SNAPSHOT_ID NOT NULL;

--
-- RHNSNAPSHOTSERVERGROUP
--
ALTER TABLE RHNSNAPSHOTSERVERGROUP DROP CONSTRAINT RHN_SNAPSHOTSG_SGID_NN;
ALTER TABLE RHNSNAPSHOTSERVERGROUP MODIFY SERVER_GROUP_ID NOT NULL;

--
-- RHNSNAPSHOTSERVERGROUP
--
ALTER TABLE RHNSNAPSHOTSERVERGROUP DROP CONSTRAINT RHN_SNAPSHOTSG_SID_NN;
ALTER TABLE RHNSNAPSHOTSERVERGROUP MODIFY SNAPSHOT_ID NOT NULL;

--
-- RHNSNAPSHOT
--
ALTER TABLE RHNSNAPSHOT DROP CONSTRAINT RHN_SNAPSHOT_CREATED_NN;
ALTER TABLE RHNSNAPSHOT MODIFY CREATED NOT NULL;

--
-- RHNSNAPSHOT
--
ALTER TABLE RHNSNAPSHOT DROP CONSTRAINT RHN_SNAPSHOT_ID_NN;
ALTER TABLE RHNSNAPSHOT MODIFY ID NOT NULL;

--
-- RHNSNAPSHOT
--
ALTER TABLE RHNSNAPSHOT DROP CONSTRAINT RHN_SNAPSHOT_MODIFIED_NN;
ALTER TABLE RHNSNAPSHOT MODIFY MODIFIED NOT NULL;

--
-- RHNSNAPSHOT
--
ALTER TABLE RHNSNAPSHOT DROP CONSTRAINT RHN_SNAPSHOT_OID_NN;
ALTER TABLE RHNSNAPSHOT MODIFY ORG_ID NOT NULL;

--
-- RHNSNAPSHOT
--
ALTER TABLE RHNSNAPSHOT DROP CONSTRAINT RHN_SNAPSHOT_REASON_NN;
ALTER TABLE RHNSNAPSHOT MODIFY REASON NOT NULL;

--
-- RHNSNAPSHOT
--
ALTER TABLE RHNSNAPSHOT DROP CONSTRAINT RHN_SNAPSHOT_SID_NN;
ALTER TABLE RHNSNAPSHOT MODIFY SERVER_ID NOT NULL;

--
-- RHNSERVERNEEDEDCACHE
--
ALTER TABLE RHNSERVERNEEDEDCACHE DROP CONSTRAINT RHN_SNCP_PID_NN;
ALTER TABLE RHNSERVERNEEDEDCACHE MODIFY PACKAGE_ID NOT NULL;

--
-- RHNSERVERNEEDEDCACHE
--
ALTER TABLE RHNSERVERNEEDEDCACHE DROP CONSTRAINT RHN_SNCP_SID_NN;
ALTER TABLE RHNSERVERNEEDEDCACHE MODIFY SERVER_ID NOT NULL;

--
-- RHN_SAT_NODE_PROBE
--
ALTER TABLE RHN_SAT_NODE_PROBE DROP CONSTRAINT RHN_SNDPB_PROBE_ID_NN;
ALTER TABLE RHN_SAT_NODE_PROBE MODIFY PROBE_ID NOT NULL;

--
-- RHN_SAT_NODE_PROBE
--
ALTER TABLE RHN_SAT_NODE_PROBE DROP CONSTRAINT RHN_SNDPB_PROBE_TYPE_NN;
ALTER TABLE RHN_SAT_NODE_PROBE MODIFY PROBE_TYPE NOT NULL;

--
-- RHN_SAT_NODE_PROBE
--
ALTER TABLE RHN_SAT_NODE_PROBE DROP CONSTRAINT RHN_SNDPB_SAT_NODE_ID_NN;
ALTER TABLE RHN_SAT_NODE_PROBE MODIFY SAT_NODE_ID NOT NULL;

--
-- RHN_SNMP_ALERT
--
ALTER TABLE RHN_SNMP_ALERT DROP CONSTRAINT RHN_SNMPA_DEST_IP_NN;
ALTER TABLE RHN_SNMP_ALERT MODIFY DEST_IP NOT NULL;

--
-- RHN_SNMP_ALERT
--
ALTER TABLE RHN_SNMP_ALERT DROP CONSTRAINT RHN_SNMPA_DEST_PORT_NN;
ALTER TABLE RHN_SNMP_ALERT MODIFY DEST_PORT NOT NULL;

--
-- RHN_SNMP_ALERT
--
ALTER TABLE RHN_SNMP_ALERT DROP CONSTRAINT RHN_SNMPA_RECID_NN;
ALTER TABLE RHN_SNMP_ALERT MODIFY RECID NOT NULL;

--
-- RHN_SNMP_ALERT
--
ALTER TABLE RHN_SNMP_ALERT DROP CONSTRAINT RHN_SNMPA_SEND_CLUST_ID_NN;
ALTER TABLE RHN_SNMP_ALERT MODIFY SENDER_CLUSTER_ID NOT NULL;

--
-- RHNSNPERRATAQUEUE
--
ALTER TABLE RHNSNPERRATAQUEUE DROP CONSTRAINT RHN_SNPERRQUEUE_EID_NN;
ALTER TABLE RHNSNPERRATAQUEUE MODIFY ERRATA_ID NOT NULL;

--
-- RHNSNPERRATAQUEUE
--
ALTER TABLE RHNSNPERRATAQUEUE DROP CONSTRAINT RHN_SNPERRQUEUE_PROCESSED_NN;
ALTER TABLE RHNSNPERRATAQUEUE MODIFY PROCESSED NOT NULL;

--
-- RHNSOLARISPATCHEDPACKAGE
--
ALTER TABLE RHNSOLARISPATCHEDPACKAGE DROP CONSTRAINT RHN_SOLARIS_PATCHEDP_PID_NN;
ALTER TABLE RHNSOLARISPATCHEDPACKAGE MODIFY PATCH_ID NOT NULL;

--
-- RHNSOLARISPATCHEDPACKAGE
--
ALTER TABLE RHNSOLARISPATCHEDPACKAGE DROP CONSTRAINT RHN_SOLARIS_PATCHEDP_PNID_NN;
ALTER TABLE RHNSOLARISPATCHEDPACKAGE MODIFY PACKAGE_NEVRA_ID NOT NULL;

--
-- RHNSOLARISPATCHEDPACKAGE
--
ALTER TABLE RHNSOLARISPATCHEDPACKAGE DROP CONSTRAINT RHN_SOLARIS_PATCHEDP_SID_NN;
ALTER TABLE RHNSOLARISPATCHEDPACKAGE MODIFY SERVER_ID NOT NULL;

--
-- RHNSOLARISPACKAGE
--
ALTER TABLE RHNSOLARISPACKAGE DROP CONSTRAINT RHN_SOLARIS_PKG_CAT_NN;
ALTER TABLE RHNSOLARISPACKAGE MODIFY CATEGORY NOT NULL;

--
-- RHNSOLARISPATCHPACKAGES
--
ALTER TABLE RHNSOLARISPATCHPACKAGES DROP CONSTRAINT RHN_SOLARIS_PNID_NN;
ALTER TABLE RHNSOLARISPATCHPACKAGES MODIFY PACKAGE_NEVRA_ID NOT NULL;

--
-- RHNSOLARISPATCHPACKAGES
--
ALTER TABLE RHNSOLARISPATCHPACKAGES DROP CONSTRAINT RHN_SOLARIS_PP_NN;
ALTER TABLE RHNSOLARISPATCHPACKAGES MODIFY PATCH_ID NOT NULL;

--
-- RHNSOLARISPATCHSETMEMBERS
--
ALTER TABLE RHNSOLARISPATCHSETMEMBERS DROP CONSTRAINT RHN_SOLARIS_PSM_CREATED_NN;
ALTER TABLE RHNSOLARISPATCHSETMEMBERS MODIFY CREATED NOT NULL;

--
-- RHNSOLARISPATCHSETMEMBERS
--
ALTER TABLE RHNSOLARISPATCHSETMEMBERS DROP CONSTRAINT RHN_SOLARIS_PSM_MODIFIED_NN;
ALTER TABLE RHNSOLARISPATCHSETMEMBERS MODIFY MODIFIED NOT NULL;

--
-- RHNSOLARISPATCHSETMEMBERS
--
ALTER TABLE RHNSOLARISPATCHSETMEMBERS DROP CONSTRAINT RHN_SOLARIS_PSM_PID_NN;
ALTER TABLE RHNSOLARISPATCHSETMEMBERS MODIFY PATCH_ID NOT NULL;

--
-- RHNSOLARISPATCHSETMEMBERS
--
ALTER TABLE RHNSOLARISPATCHSETMEMBERS DROP CONSTRAINT RHN_SOLARIS_PSM_PSID_NN;
ALTER TABLE RHNSOLARISPATCHSETMEMBERS MODIFY PATCH_SET_ID NOT NULL;

--
-- RHNSOLARISPATCHSET
--
ALTER TABLE RHNSOLARISPATCHSET DROP CONSTRAINT RHN_SOLARIS_PS_CREATED_NN;
ALTER TABLE RHNSOLARISPATCHSET MODIFY CREATED NOT NULL;

--
-- RHNSOLARISPATCHSET
--
ALTER TABLE RHNSOLARISPATCHSET DROP CONSTRAINT RHN_SOLARIS_PS_MODIFIED_NN;
ALTER TABLE RHNSOLARISPATCHSET MODIFY MODIFIED NOT NULL;

--
-- RHNSOLARISPATCHSET
--
ALTER TABLE RHNSOLARISPATCHSET DROP CONSTRAINT RHN_SOLARIS_PS_SD_NN;
ALTER TABLE RHNSOLARISPATCHSET MODIFY SET_DATE NOT NULL;

--
-- RHNSOLARISPATCHTYPE
--
ALTER TABLE RHNSOLARISPATCHTYPE DROP CONSTRAINT RHN_SOLARIS_PT_LABEL_NN;
ALTER TABLE RHNSOLARISPATCHTYPE MODIFY LABEL NOT NULL;

--
-- RHNSOLARISPATCHTYPE
--
ALTER TABLE RHNSOLARISPATCHTYPE DROP CONSTRAINT RHN_SOLARIS_PT_NAME_NN;
ALTER TABLE RHNSOLARISPATCHTYPE MODIFY NAME NOT NULL;

--
-- RHNSOLARISPATCH
--
ALTER TABLE RHNSOLARISPATCH DROP CONSTRAINT RHN_SOLARIS_P_CREATED_NN;
ALTER TABLE RHNSOLARISPATCH MODIFY CREATED NOT NULL;

--
-- RHNSOLARISPATCH
--
ALTER TABLE RHNSOLARISPATCH DROP CONSTRAINT RHN_SOLARIS_P_MODIFIED_NN;
ALTER TABLE RHNSOLARISPATCH MODIFY MODIFIED NOT NULL;

--
-- RHNSOLARISPATCH
--
ALTER TABLE RHNSOLARISPATCH DROP CONSTRAINT RHN_SOLARIS_P_PT_NN;
ALTER TABLE RHNSOLARISPATCH MODIFY PATCH_TYPE NOT NULL;

--
-- RHNSOLARISPATCH
--
ALTER TABLE RHNSOLARISPATCH DROP CONSTRAINT RHN_SOLARIS_P_RDME_NN;
ALTER TABLE RHNSOLARISPATCH MODIFY README NOT NULL;

--
-- RHNSOURCERPM
--
ALTER TABLE RHNSOURCERPM DROP CONSTRAINT RHN_SOURCERPM_ID_NN;
ALTER TABLE RHNSOURCERPM MODIFY ID NOT NULL;

--
-- RHNSOURCERPM
--
ALTER TABLE RHNSOURCERPM DROP CONSTRAINT RHN_SOURCERPM_NAME_NN;
ALTER TABLE RHNSOURCERPM MODIFY NAME NOT NULL;

--
-- RHNSERVERPROFILEPACKAGE
--
ALTER TABLE RHNSERVERPROFILEPACKAGE DROP CONSTRAINT RHN_SPROFILE_EVRID_NN;
ALTER TABLE RHNSERVERPROFILEPACKAGE MODIFY EVR_ID NOT NULL;

--
-- RHNSERVERPROFILEPACKAGE
--
ALTER TABLE RHNSERVERPROFILEPACKAGE DROP CONSTRAINT RHN_SPROFILE_NID_NN;
ALTER TABLE RHNSERVERPROFILEPACKAGE MODIFY NAME_ID NOT NULL;

--
-- RHNSERVERPROFILEPACKAGE
--
ALTER TABLE RHNSERVERPROFILEPACKAGE DROP CONSTRAINT RHN_SPROFILE_SPID_NN;
ALTER TABLE RHNSERVERPROFILEPACKAGE MODIFY SERVER_PROFILE_ID NOT NULL;

--
-- RHNSERVERPROFILETYPE
--
ALTER TABLE RHNSERVERPROFILETYPE DROP CONSTRAINT RHN_SPROFTYPE_CREAT_NN;
ALTER TABLE RHNSERVERPROFILETYPE MODIFY CREATED NOT NULL;

--
-- RHNSERVERPROFILETYPE
--
ALTER TABLE RHNSERVERPROFILETYPE DROP CONSTRAINT RHN_SPROFTYPE_ID_NN;
ALTER TABLE RHNSERVERPROFILETYPE MODIFY ID NOT NULL;

--
-- RHNSERVERPROFILETYPE
--
ALTER TABLE RHNSERVERPROFILETYPE DROP CONSTRAINT RHN_SPROFTYPE_LABEL_NN;
ALTER TABLE RHNSERVERPROFILETYPE MODIFY LABEL NOT NULL;

--
-- RHNSERVERPROFILETYPE
--
ALTER TABLE RHNSERVERPROFILETYPE DROP CONSTRAINT RHN_SPROFTYPE_MOD_NN;
ALTER TABLE RHNSERVERPROFILETYPE MODIFY MODIFIED NOT NULL;

--
-- RHNSERVERPROFILETYPE
--
ALTER TABLE RHNSERVERPROFILETYPE DROP CONSTRAINT RHN_SPROFTYPE_NAME_NN;
ALTER TABLE RHNSERVERPROFILETYPE MODIFY NAME NOT NULL;

--
-- RHNSERVERPACKAGEARCHCOMPAT
--
ALTER TABLE RHNSERVERPACKAGEARCHCOMPAT DROP CONSTRAINT RHN_SP_AC_CREATED_NN;
ALTER TABLE RHNSERVERPACKAGEARCHCOMPAT MODIFY CREATED NOT NULL;

--
-- RHNSERVERPACKAGEARCHCOMPAT
--
ALTER TABLE RHNSERVERPACKAGEARCHCOMPAT DROP CONSTRAINT RHN_SP_AC_MODIFIED_NN;
ALTER TABLE RHNSERVERPACKAGEARCHCOMPAT MODIFY MODIFIED NOT NULL;

--
-- RHNSERVERPACKAGEARCHCOMPAT
--
ALTER TABLE RHNSERVERPACKAGEARCHCOMPAT DROP CONSTRAINT RHN_SP_AC_PAID_NN;
ALTER TABLE RHNSERVERPACKAGEARCHCOMPAT MODIFY PACKAGE_ARCH_ID NOT NULL;

--
-- RHNSERVERPACKAGEARCHCOMPAT
--
ALTER TABLE RHNSERVERPACKAGEARCHCOMPAT DROP CONSTRAINT RHN_SP_AC_PREF_NN;
ALTER TABLE RHNSERVERPACKAGEARCHCOMPAT MODIFY PREFERENCE NOT NULL;

--
-- RHNSERVERPACKAGEARCHCOMPAT
--
ALTER TABLE RHNSERVERPACKAGEARCHCOMPAT DROP CONSTRAINT RHN_SP_AC_SAID_NN;
ALTER TABLE RHNSERVERPACKAGEARCHCOMPAT MODIFY SERVER_ARCH_ID NOT NULL;

--
-- RHN_SERVICE_PROBE_ORIGINS
--
ALTER TABLE RHN_SERVICE_PROBE_ORIGINS DROP CONSTRAINT RHN_SRVPO_DECOUPLED_NN;
ALTER TABLE RHN_SERVICE_PROBE_ORIGINS MODIFY DECOUPLED NOT NULL;

--
-- RHN_SERVICE_PROBE_ORIGINS
--
ALTER TABLE RHN_SERVICE_PROBE_ORIGINS DROP CONSTRAINT RHN_SRVPO_SERV_P_ID_NN;
ALTER TABLE RHN_SERVICE_PROBE_ORIGINS MODIFY SERVICE_PROBE_ID NOT NULL;

--
-- RHNSERVERNETINTERFACE
--
ALTER TABLE RHNSERVERNETINTERFACE DROP CONSTRAINT RHN_SRV_NET_IFACE_CREATED_NN;
ALTER TABLE RHNSERVERNETINTERFACE MODIFY CREATED NOT NULL;

--
-- RHNSERVERNETINTERFACE
--
ALTER TABLE RHNSERVERNETINTERFACE DROP CONSTRAINT RHN_SRV_NET_IFACE_MODIFIED_NN;
ALTER TABLE RHNSERVERNETINTERFACE MODIFY MODIFIED NOT NULL;

--
-- RHNSERVERNETINTERFACE
--
ALTER TABLE RHNSERVERNETINTERFACE DROP CONSTRAINT RHN_SRV_NET_IFACE_NAME_NN;
ALTER TABLE RHNSERVERNETINTERFACE MODIFY NAME NOT NULL;

--
-- RHNSERVERNETINTERFACE
--
ALTER TABLE RHNSERVERNETINTERFACE DROP CONSTRAINT RHN_SRV_NET_IFACE_SID_NN;
ALTER TABLE RHNSERVERNETINTERFACE MODIFY SERVER_ID NOT NULL;

--
-- RHNSERVERTOKENREGS
--
ALTER TABLE RHNSERVERTOKENREGS DROP CONSTRAINT RHN_SRV_REG_TOK_SID_NN;
ALTER TABLE RHNSERVERTOKENREGS MODIFY SERVER_ID NOT NULL;

--
-- RHNSERVERTOKENREGS
--
ALTER TABLE RHNSERVERTOKENREGS DROP CONSTRAINT RHN_SRV_REG_TOK_TID_NN;
ALTER TABLE RHNSERVERTOKENREGS MODIFY TOKEN_ID NOT NULL;

--
-- RHNSERVERSERVERGROUPARCHCOMPAT
--
ALTER TABLE RHNSERVERSERVERGROUPARCHCOMPAT DROP CONSTRAINT RHN_SSG_AC_CREATED_NN;
ALTER TABLE RHNSERVERSERVERGROUPARCHCOMPAT MODIFY CREATED NOT NULL;

--
-- RHNSERVERSERVERGROUPARCHCOMPAT
--
ALTER TABLE RHNSERVERSERVERGROUPARCHCOMPAT DROP CONSTRAINT RHN_SSG_AC_MODIFIED_NN;
ALTER TABLE RHNSERVERSERVERGROUPARCHCOMPAT MODIFY MODIFIED NOT NULL;

--
-- RHNSERVERSERVERGROUPARCHCOMPAT
--
ALTER TABLE RHNSERVERSERVERGROUPARCHCOMPAT DROP CONSTRAINT RHN_SSG_AC_SAID_NN;
ALTER TABLE RHNSERVERSERVERGROUPARCHCOMPAT MODIFY SERVER_ARCH_ID NOT NULL;

--
-- RHNSERVERSERVERGROUPARCHCOMPAT
--
ALTER TABLE RHNSERVERSERVERGROUPARCHCOMPAT DROP CONSTRAINT RHN_SSG_AC_SGT_NN;
ALTER TABLE RHNSERVERSERVERGROUPARCHCOMPAT MODIFY SERVER_GROUP_TYPE NOT NULL;

--
-- RHNSNAPSHOTINVALIDREASON
--
ALTER TABLE RHNSNAPSHOTINVALIDREASON DROP CONSTRAINT RHN_SSINVALID_CREATED_NN;
ALTER TABLE RHNSNAPSHOTINVALIDREASON MODIFY CREATED NOT NULL;

--
-- RHNSNAPSHOTINVALIDREASON
--
ALTER TABLE RHNSNAPSHOTINVALIDREASON DROP CONSTRAINT RHN_SSINVALID_ID_NN;
ALTER TABLE RHNSNAPSHOTINVALIDREASON MODIFY ID NOT NULL;

--
-- RHNSNAPSHOTINVALIDREASON
--
ALTER TABLE RHNSNAPSHOTINVALIDREASON DROP CONSTRAINT RHN_SSINVALID_LABEL_NN;
ALTER TABLE RHNSNAPSHOTINVALIDREASON MODIFY LABEL NOT NULL;

--
-- RHNSNAPSHOTINVALIDREASON
--
ALTER TABLE RHNSNAPSHOTINVALIDREASON DROP CONSTRAINT RHN_SSINVALID_MODIFIED_NN;
ALTER TABLE RHNSNAPSHOTINVALIDREASON MODIFY MODIFIED NOT NULL;

--
-- RHNSNAPSHOTINVALIDREASON
--
ALTER TABLE RHNSNAPSHOTINVALIDREASON DROP CONSTRAINT RHN_SSINVALID_NAME_NN;
ALTER TABLE RHNSNAPSHOTINVALIDREASON MODIFY NAME NOT NULL;

--
-- RHNSSMOPERATION
--
ALTER TABLE RHNSSMOPERATION DROP CONSTRAINT RHN_SSMOP_DESC_NN;
ALTER TABLE RHNSSMOPERATION MODIFY DESCRIPTION NOT NULL;

--
-- RHNSSMOPERATION
--
ALTER TABLE RHNSSMOPERATION DROP CONSTRAINT RHN_SSMOP_ID_NN;
ALTER TABLE RHNSSMOPERATION MODIFY ID NOT NULL;

--
-- RHNSSMOPERATION
--
ALTER TABLE RHNSSMOPERATION DROP CONSTRAINT RHN_SSMOP_MOD_NN;
ALTER TABLE RHNSSMOPERATION MODIFY MODIFIED NOT NULL;

--
-- RHNSSMOPERATION
--
ALTER TABLE RHNSSMOPERATION DROP CONSTRAINT RHN_SSMOP_STRT_NN;
ALTER TABLE RHNSSMOPERATION MODIFY STARTED NOT NULL;

--
-- RHNSSMOPERATION
--
ALTER TABLE RHNSSMOPERATION DROP CONSTRAINT RHN_SSMOP_ST_NN;
ALTER TABLE RHNSSMOPERATION MODIFY STATUS NOT NULL;

--
-- RHNSSMOPERATION
--
ALTER TABLE RHNSSMOPERATION DROP CONSTRAINT RHN_SSMOP_USER_NN;
ALTER TABLE RHNSSMOPERATION MODIFY USER_ID NOT NULL;

--
-- RHNSAVEDSEARCHTYPE
--
ALTER TABLE RHNSAVEDSEARCHTYPE DROP CONSTRAINT RHN_SSTYPE_CREATED_NN;
ALTER TABLE RHNSAVEDSEARCHTYPE MODIFY CREATED NOT NULL;

--
-- RHNSAVEDSEARCHTYPE
--
ALTER TABLE RHNSAVEDSEARCHTYPE DROP CONSTRAINT RHN_SSTYPE_ID_NN;
ALTER TABLE RHNSAVEDSEARCHTYPE MODIFY ID NOT NULL;

--
-- RHNSAVEDSEARCHTYPE
--
ALTER TABLE RHNSAVEDSEARCHTYPE DROP CONSTRAINT RHN_SSTYPE_LABEL_NN;
ALTER TABLE RHNSAVEDSEARCHTYPE MODIFY LABEL NOT NULL;

--
-- RHNSAVEDSEARCHTYPE
--
ALTER TABLE RHNSAVEDSEARCHTYPE DROP CONSTRAINT RHN_SSTYPE_MODIFIED_NN;
ALTER TABLE RHNSAVEDSEARCHTYPE MODIFY MODIFIED NOT NULL;

--
-- RHN_STRATEGIES
--
ALTER TABLE RHN_STRATEGIES DROP CONSTRAINT RHN_STRAT_RECID_NN;
ALTER TABLE RHN_STRATEGIES MODIFY RECID NOT NULL;

--
-- RHNSNAPSHOTTAG
--
ALTER TABLE RHNSNAPSHOTTAG DROP CONSTRAINT RHN_ST_CREATED_NN;
ALTER TABLE RHNSNAPSHOTTAG MODIFY CREATED NOT NULL;

--
-- RHNSNAPSHOTTAG
--
ALTER TABLE RHNSNAPSHOTTAG DROP CONSTRAINT RHN_ST_MODIFIED_NN;
ALTER TABLE RHNSNAPSHOTTAG MODIFY MODIFIED NOT NULL;

--
-- RHNSNAPSHOTTAG
--
ALTER TABLE RHNSNAPSHOTTAG DROP CONSTRAINT RHN_ST_SSID_NN;
ALTER TABLE RHNSNAPSHOTTAG MODIFY SNAPSHOT_ID NOT NULL;

--
-- RHNSNAPSHOTTAG
--
ALTER TABLE RHNSNAPSHOTTAG DROP CONSTRAINT RHN_ST_TID_NN;
ALTER TABLE RHNSNAPSHOTTAG MODIFY TAG_ID NOT NULL;

--
-- RHNSYSTEMMIGRATIONS
--
ALTER TABLE RHNSYSTEMMIGRATIONS DROP CONSTRAINT RHN_SYS_MIG_MIGRATED_NN;
ALTER TABLE RHNSYSTEMMIGRATIONS MODIFY MIGRATED NOT NULL;

--
-- RHNSYSTEMMIGRATIONS
--
ALTER TABLE RHNSYSTEMMIGRATIONS DROP CONSTRAINT RHN_SYS_MIG_SID_NN;
ALTER TABLE RHNSYSTEMMIGRATIONS MODIFY SERVER_ID NOT NULL;

--
-- RHNTAG
--
ALTER TABLE RHNTAG DROP CONSTRAINT RHN_TAG_CREATED_NN;
ALTER TABLE RHNTAG MODIFY CREATED NOT NULL;

--
-- RHNTAG
--
ALTER TABLE RHNTAG DROP CONSTRAINT RHN_TAG_ID_NN;
ALTER TABLE RHNTAG MODIFY ID NOT NULL;

--
-- RHNTAG
--
ALTER TABLE RHNTAG DROP CONSTRAINT RHN_TAG_MODIFIED_NN;
ALTER TABLE RHNTAG MODIFY MODIFIED NOT NULL;

--
-- RHNTAG
--
ALTER TABLE RHNTAG DROP CONSTRAINT RHN_TAG_NID_NN;
ALTER TABLE RHNTAG MODIFY NAME_ID NOT NULL;

--
-- RHNTAG
--
ALTER TABLE RHNTAG DROP CONSTRAINT RHN_TAG_OID_NN;
ALTER TABLE RHNTAG MODIFY ORG_ID NOT NULL;

--
-- RHNTASKQUEUE
--
ALTER TABLE RHNTASKQUEUE DROP CONSTRAINT RHN_TASK_QUEUE_EARLIEST_NN;
ALTER TABLE RHNTASKQUEUE MODIFY EARLIEST NOT NULL;

--
-- RHNTASKQUEUE
--
ALTER TABLE RHNTASKQUEUE DROP CONSTRAINT RHN_TASK_QUEUE_ORG_ID_NN;
ALTER TABLE RHNTASKQUEUE MODIFY ORG_ID NOT NULL;

--
-- RHNTASKQUEUE
--
ALTER TABLE RHNTASKQUEUE DROP CONSTRAINT RHN_TASK_QUEUE_TASK_NAME_NN;
ALTER TABLE RHNTASKQUEUE MODIFY TASK_NAME NOT NULL;

--
-- RHNTEMPLATECATEGORY
--
ALTER TABLE RHNTEMPLATECATEGORY DROP CONSTRAINT RHN_TEMPLATE_CAT_CREATED_NN;
ALTER TABLE RHNTEMPLATECATEGORY MODIFY CREATED NOT NULL;

--
-- RHNTEMPLATECATEGORY
--
ALTER TABLE RHNTEMPLATECATEGORY DROP CONSTRAINT RHN_TEMPLATE_CAT_DESC_NN;
ALTER TABLE RHNTEMPLATECATEGORY MODIFY DESCRIPTION NOT NULL;

--
-- RHNTEMPLATECATEGORY
--
ALTER TABLE RHNTEMPLATECATEGORY DROP CONSTRAINT RHN_TEMPLATE_CAT_ID_NN;
ALTER TABLE RHNTEMPLATECATEGORY MODIFY ID NOT NULL;

--
-- RHNTEMPLATECATEGORY
--
ALTER TABLE RHNTEMPLATECATEGORY DROP CONSTRAINT RHN_TEMPLATE_CAT_LABEL_NN;
ALTER TABLE RHNTEMPLATECATEGORY MODIFY LABEL NOT NULL;

--
-- RHNTEMPLATECATEGORY
--
ALTER TABLE RHNTEMPLATECATEGORY DROP CONSTRAINT RHN_TEMPLATE_CAT_MODIFIED_NN;
ALTER TABLE RHNTEMPLATECATEGORY MODIFY MODIFIED NOT NULL;

--
-- RHNTEMPLATESTRING
--
ALTER TABLE RHNTEMPLATESTRING DROP CONSTRAINT RHN_TEMPLATE_STR_CID_NN;
ALTER TABLE RHNTEMPLATESTRING MODIFY CATEGORY_ID NOT NULL;

--
-- RHNTEMPLATESTRING
--
ALTER TABLE RHNTEMPLATESTRING DROP CONSTRAINT RHN_TEMPLATE_STR_CREATED_NN;
ALTER TABLE RHNTEMPLATESTRING MODIFY CREATED NOT NULL;

--
-- RHNTEMPLATESTRING
--
ALTER TABLE RHNTEMPLATESTRING DROP CONSTRAINT RHN_TEMPLATE_STR_DESC_NN;
ALTER TABLE RHNTEMPLATESTRING MODIFY DESCRIPTION NOT NULL;

--
-- RHNTEMPLATESTRING
--
ALTER TABLE RHNTEMPLATESTRING DROP CONSTRAINT RHN_TEMPLATE_STR_ID_NN;
ALTER TABLE RHNTEMPLATESTRING MODIFY ID NOT NULL;

--
-- RHNTEMPLATESTRING
--
ALTER TABLE RHNTEMPLATESTRING DROP CONSTRAINT RHN_TEMPLATE_STR_KEY_NN;
ALTER TABLE RHNTEMPLATESTRING MODIFY LABEL NOT NULL;

--
-- RHNTEMPLATESTRING
--
ALTER TABLE RHNTEMPLATESTRING DROP CONSTRAINT RHN_TEMPLATE_STR_MODIFIED_NN;
ALTER TABLE RHNTEMPLATESTRING MODIFY MODIFIED NOT NULL;

--
-- RHNTIMEZONE
--
ALTER TABLE RHNTIMEZONE DROP CONSTRAINT RHN_TIMEZONE_DISPLAY_NN;
ALTER TABLE RHNTIMEZONE MODIFY DISPLAY_NAME NOT NULL;

--
-- RHNTIMEZONE
--
ALTER TABLE RHNTIMEZONE DROP CONSTRAINT RHN_TIMEZONE_ID_NN;
ALTER TABLE RHNTIMEZONE MODIFY ID NOT NULL;

--
-- RHNTIMEZONE
--
ALTER TABLE RHNTIMEZONE DROP CONSTRAINT RHN_TIMEZONE_OLSON_NN;
ALTER TABLE RHNTIMEZONE MODIFY OLSON_NAME NOT NULL;

--
-- RHNTEXTMESSAGE
--
ALTER TABLE RHNTEXTMESSAGE DROP CONSTRAINT RHN_TM_CREATED_NN;
ALTER TABLE RHNTEXTMESSAGE MODIFY CREATED NOT NULL;

--
-- RHNTEXTMESSAGE
--
ALTER TABLE RHNTEXTMESSAGE DROP CONSTRAINT RHN_TM_MESSAGE_BODY_NN;
ALTER TABLE RHNTEXTMESSAGE MODIFY MESSAGE_BODY NOT NULL;

--
-- RHNTEXTMESSAGE
--
ALTER TABLE RHNTEXTMESSAGE DROP CONSTRAINT RHN_TM_MESSAGE_ID_NN;
ALTER TABLE RHNTEXTMESSAGE MODIFY MESSAGE_ID NOT NULL;

--
-- RHNTEXTMESSAGE
--
ALTER TABLE RHNTEXTMESSAGE DROP CONSTRAINT RHN_TM_MODIFIED_NN;
ALTER TABLE RHNTEXTMESSAGE MODIFY MODIFIED NOT NULL;

--
-- RHNTAGNAME
--
ALTER TABLE RHNTAGNAME DROP CONSTRAINT RHN_TN_CREATED_NN;
ALTER TABLE RHNTAGNAME MODIFY CREATED NOT NULL;

--
-- RHNTAGNAME
--
ALTER TABLE RHNTAGNAME DROP CONSTRAINT RHN_TN_ID_NN;
ALTER TABLE RHNTAGNAME MODIFY ID NOT NULL;

--
-- RHNTAGNAME
--
ALTER TABLE RHNTAGNAME DROP CONSTRAINT RHN_TN_MODIFIED_NN;
ALTER TABLE RHNTAGNAME MODIFY MODIFIED NOT NULL;

--
-- RHNTAGNAME
--
ALTER TABLE RHNTAGNAME DROP CONSTRAINT RHN_TN_NAME_NN;
ALTER TABLE RHNTAGNAME MODIFY NAME NOT NULL;

--
-- RHNTRANSACTIONELEMENT
--
ALTER TABLE RHNTRANSACTIONELEMENT DROP CONSTRAINT RHN_TRANSELEM_TID_NN;
ALTER TABLE RHNTRANSACTIONELEMENT MODIFY TRANSACTION_ID NOT NULL;

--
-- RHNTRANSACTIONELEMENT
--
ALTER TABLE RHNTRANSACTIONELEMENT DROP CONSTRAINT RHN_TRANSELEM_TPID_NN;
ALTER TABLE RHNTRANSACTIONELEMENT MODIFY TRANSACTION_PACKAGE_ID NOT NULL;

--
-- RHNTRANSACTIONOPERATION
--
ALTER TABLE RHNTRANSACTIONOPERATION DROP CONSTRAINT RHN_TRANSOP_CREATED_NN;
ALTER TABLE RHNTRANSACTIONOPERATION MODIFY CREATED NOT NULL;

--
-- RHNTRANSACTIONOPERATION
--
ALTER TABLE RHNTRANSACTIONOPERATION DROP CONSTRAINT RHN_TRANSOP_ID_NN;
ALTER TABLE RHNTRANSACTIONOPERATION MODIFY ID NOT NULL;

--
-- RHNTRANSACTIONOPERATION
--
ALTER TABLE RHNTRANSACTIONOPERATION DROP CONSTRAINT RHN_TRANSOP_LABEL_NN;
ALTER TABLE RHNTRANSACTIONOPERATION MODIFY LABEL NOT NULL;

--
-- RHNTRANSACTIONOPERATION
--
ALTER TABLE RHNTRANSACTIONOPERATION DROP CONSTRAINT RHN_TRANSOP_MODIFIED_NN;
ALTER TABLE RHNTRANSACTIONOPERATION MODIFY MODIFIED NOT NULL;

--
-- RHNTRANSACTIONPACKAGE
--
ALTER TABLE RHNTRANSACTIONPACKAGE DROP CONSTRAINT RHN_TRANSPACK_EID_NN;
ALTER TABLE RHNTRANSACTIONPACKAGE MODIFY EVR_ID NOT NULL;

--
-- RHNTRANSACTIONPACKAGE
--
ALTER TABLE RHNTRANSACTIONPACKAGE DROP CONSTRAINT RHN_TRANSPACK_ID_NN;
ALTER TABLE RHNTRANSACTIONPACKAGE MODIFY ID NOT NULL;

--
-- RHNTRANSACTIONPACKAGE
--
ALTER TABLE RHNTRANSACTIONPACKAGE DROP CONSTRAINT RHN_TRANSPACK_NID_NN;
ALTER TABLE RHNTRANSACTIONPACKAGE MODIFY NAME_ID NOT NULL;

--
-- RHNTRANSACTIONPACKAGE
--
ALTER TABLE RHNTRANSACTIONPACKAGE DROP CONSTRAINT RHN_TRANSPACK_OP_NN;
ALTER TABLE RHNTRANSACTIONPACKAGE MODIFY OPERATION NOT NULL;

--
-- RHNTRANSACTION
--
ALTER TABLE RHNTRANSACTION DROP CONSTRAINT RHN_TRANS_CREATED_NN;
ALTER TABLE RHNTRANSACTION MODIFY CREATED NOT NULL;

--
-- RHNTRANSACTION
--
ALTER TABLE RHNTRANSACTION DROP CONSTRAINT RHN_TRANS_ID_NN;
ALTER TABLE RHNTRANSACTION MODIFY ID NOT NULL;

--
-- RHNTRANSACTION
--
ALTER TABLE RHNTRANSACTION DROP CONSTRAINT RHN_TRANS_MODIFIED_NN;
ALTER TABLE RHNTRANSACTION MODIFY MODIFIED NOT NULL;

--
-- RHNTRANSACTION
--
ALTER TABLE RHNTRANSACTION DROP CONSTRAINT RHN_TRANS_RTI_NN;
ALTER TABLE RHNTRANSACTION MODIFY RPM_TRANS_ID NOT NULL;

--
-- RHNTRANSACTION
--
ALTER TABLE RHNTRANSACTION DROP CONSTRAINT RHN_TRANS_SID_NN;
ALTER TABLE RHNTRANSACTION MODIFY SERVER_ID NOT NULL;

--
-- RHNTRANSACTION
--
ALTER TABLE RHNTRANSACTION DROP CONSTRAINT RHN_TRANS_TS_NN;
ALTER TABLE RHNTRANSACTION MODIFY TIMESTAMP NOT NULL;

--
-- RHN_THRESHOLD_TYPE
--
ALTER TABLE RHN_THRESHOLD_TYPE DROP CONSTRAINT RHN_TRTYP_DESC_NN;
ALTER TABLE RHN_THRESHOLD_TYPE MODIFY DESCRIPTION NOT NULL;

--
-- RHN_THRESHOLD_TYPE
--
ALTER TABLE RHN_THRESHOLD_TYPE DROP CONSTRAINT RHN_TRTYP_NAME_NN;
ALTER TABLE RHN_THRESHOLD_TYPE MODIFY NAME NOT NULL;

--
-- RHN_THRESHOLD_TYPE
--
ALTER TABLE RHN_THRESHOLD_TYPE DROP CONSTRAINT RHN_TRTYP_ORD_NN;
ALTER TABLE RHN_THRESHOLD_TYPE MODIFY ORDINAL NOT NULL;

--
-- RHNTRUSTEDORGS
--
ALTER TABLE RHNTRUSTEDORGS DROP CONSTRAINT RHN_TRUSTED_ORGS_CREATED_NN;
ALTER TABLE RHNTRUSTEDORGS MODIFY CREATED NOT NULL;

--
-- RHNTRUSTEDORGS
--
ALTER TABLE RHNTRUSTEDORGS DROP CONSTRAINT RHN_TRUSTED_ORGS_MODIFIED_NN;
ALTER TABLE RHNTRUSTEDORGS MODIFY MODIFIED NOT NULL;

--
-- RHNTRUSTEDORGS
--
ALTER TABLE RHNTRUSTEDORGS DROP CONSTRAINT RHN_TRUSTED_ORGS_OID_NN;
ALTER TABLE RHNTRUSTEDORGS MODIFY ORG_ID NOT NULL;

--
-- RHNTRUSTEDORGS
--
ALTER TABLE RHNTRUSTEDORGS DROP CONSTRAINT RHN_TRUSTED_ORGS_OTID_NN;
ALTER TABLE RHNTRUSTEDORGS MODIFY ORG_TRUST_ID NOT NULL;

--
-- RHNTINYURL
--
ALTER TABLE RHNTINYURL DROP CONSTRAINT RHN_TU_CREATED_NN;
ALTER TABLE RHNTINYURL MODIFY CREATED NOT NULL;

--
-- RHNTINYURL
--
ALTER TABLE RHNTINYURL DROP CONSTRAINT RHN_TU_ENABLED_NN;
ALTER TABLE RHNTINYURL MODIFY ENABLED NOT NULL;

--
-- RHNTINYURL
--
ALTER TABLE RHNTINYURL DROP CONSTRAINT RHN_TU_EXPIRES_NN;
ALTER TABLE RHNTINYURL MODIFY EXPIRES NOT NULL;

--
-- RHNTINYURL
--
ALTER TABLE RHNTINYURL DROP CONSTRAINT RHN_TU_TOKEN_NN;
ALTER TABLE RHNTINYURL MODIFY TOKEN NOT NULL;

--
-- RHNTINYURL
--
ALTER TABLE RHNTINYURL DROP CONSTRAINT RHN_TU_URL_NN;
ALTER TABLE RHNTINYURL MODIFY URL NOT NULL;

--
-- RHN_TIME_ZONE_NAMES
--
ALTER TABLE RHN_TIME_ZONE_NAMES DROP CONSTRAINT RHN_TZNMS_DISPLAY_NAME_NN;
ALTER TABLE RHN_TIME_ZONE_NAMES MODIFY DISPLAY_NAME NOT NULL;

--
-- RHN_TIME_ZONE_NAMES
--
ALTER TABLE RHN_TIME_ZONE_NAMES DROP CONSTRAINT RHN_TZNMS_GMT_OFFSET_NN;
ALTER TABLE RHN_TIME_ZONE_NAMES MODIFY GMT_OFFSET_MINUTES NOT NULL;

--
-- RHN_TIME_ZONE_NAMES
--
ALTER TABLE RHN_TIME_ZONE_NAMES DROP CONSTRAINT RHN_TZNMS_JAVA_ID_NN;
ALTER TABLE RHN_TIME_ZONE_NAMES MODIFY JAVA_ID NOT NULL;

--
-- RHN_TIME_ZONE_NAMES
--
ALTER TABLE RHN_TIME_ZONE_NAMES DROP CONSTRAINT RHN_TZNMS_RECID_NN;
ALTER TABLE RHN_TIME_ZONE_NAMES MODIFY RECID NOT NULL;

--
-- RHN_TIME_ZONE_NAMES
--
ALTER TABLE RHN_TIME_ZONE_NAMES DROP CONSTRAINT RHN_TZNMS_USE_DST_NN;
ALTER TABLE RHN_TIME_ZONE_NAMES MODIFY USE_DAYLIGHT_TIME NOT NULL;

--
-- RHNUSERDEFAULTSYSTEMGROUPS
--
ALTER TABLE RHNUSERDEFAULTSYSTEMGROUPS DROP CONSTRAINT RHN_UDSG_CID_NN;
ALTER TABLE RHNUSERDEFAULTSYSTEMGROUPS MODIFY SYSTEM_GROUP_ID NOT NULL;

--
-- RHNUSERDEFAULTSYSTEMGROUPS
--
ALTER TABLE RHNUSERDEFAULTSYSTEMGROUPS DROP CONSTRAINT RHN_UDSG_UID_NN;
ALTER TABLE RHNUSERDEFAULTSYSTEMGROUPS MODIFY USER_ID NOT NULL;

--
-- RHNUSERGROUPMEMBERS
--
ALTER TABLE RHNUSERGROUPMEMBERS DROP CONSTRAINT RHN_UGMEMBERS_CREATED_NN;
ALTER TABLE RHNUSERGROUPMEMBERS MODIFY CREATED NOT NULL;

--
-- RHNUSERGROUPMEMBERS
--
ALTER TABLE RHNUSERGROUPMEMBERS DROP CONSTRAINT RHN_UGMEMBERS_MODIFIED_NN;
ALTER TABLE RHNUSERGROUPMEMBERS MODIFY MODIFIED NOT NULL;

--
-- RHNUSERGROUPMEMBERS
--
ALTER TABLE RHNUSERGROUPMEMBERS DROP CONSTRAINT RHN_UGMEMBERS_UGID_NN;
ALTER TABLE RHNUSERGROUPMEMBERS MODIFY USER_GROUP_ID NOT NULL;

--
-- RHNUSERGROUPMEMBERS
--
ALTER TABLE RHNUSERGROUPMEMBERS DROP CONSTRAINT RHN_UGMEMBERS_UID_NN;
ALTER TABLE RHNUSERGROUPMEMBERS MODIFY USER_ID NOT NULL;

--
-- RHNUSERMESSAGE
--
ALTER TABLE RHNUSERMESSAGE DROP CONSTRAINT RHN_UM_MESSAGE_ID_NN;
ALTER TABLE RHNUSERMESSAGE MODIFY MESSAGE_ID NOT NULL;

--
-- RHNUSERMESSAGESTATUS
--
ALTER TABLE RHNUSERMESSAGESTATUS DROP CONSTRAINT RHN_UM_STATUS_ID_NN;
ALTER TABLE RHNUSERMESSAGESTATUS MODIFY ID NOT NULL;

--
-- RHNUSERMESSAGESTATUS
--
ALTER TABLE RHNUSERMESSAGESTATUS DROP CONSTRAINT RHN_UM_STATUS_LABEL_NN;
ALTER TABLE RHNUSERMESSAGESTATUS MODIFY LABEL NOT NULL;

--
-- RHNUSERMESSAGE
--
ALTER TABLE RHNUSERMESSAGE DROP CONSTRAINT RHN_UM_STATUS_NN;
ALTER TABLE RHNUSERMESSAGE MODIFY STATUS NOT NULL;

--
-- RHNUSERMESSAGETYPE
--
ALTER TABLE RHNUSERMESSAGETYPE DROP CONSTRAINT RHN_UM_TYPE_ID_NN;
ALTER TABLE RHNUSERMESSAGETYPE MODIFY ID NOT NULL;

--
-- RHNUSERMESSAGETYPE
--
ALTER TABLE RHNUSERMESSAGETYPE DROP CONSTRAINT RHN_UM_TYPE_LABEL_NN;
ALTER TABLE RHNUSERMESSAGETYPE MODIFY LABEL NOT NULL;

--
-- RHNUSERMESSAGETYPE
--
ALTER TABLE RHNUSERMESSAGETYPE DROP CONSTRAINT RHN_UM_TYPE_NAME_NN;
ALTER TABLE RHNUSERMESSAGETYPE MODIFY NAME NOT NULL;

--
-- RHNUSERMESSAGE
--
ALTER TABLE RHNUSERMESSAGE DROP CONSTRAINT RHN_UM_USER_ID_NN;
ALTER TABLE RHNUSERMESSAGE MODIFY USER_ID NOT NULL;

--
-- RHN_UNITS
--
ALTER TABLE RHN_UNITS DROP CONSTRAINT RHN_UNITS_QUANTUM_ID_NN;
ALTER TABLE RHN_UNITS MODIFY QUANTUM_ID NOT NULL;

--
-- RHN_UNITS
--
ALTER TABLE RHN_UNITS DROP CONSTRAINT RHN_UNITS_UNIT_ID_NN;
ALTER TABLE RHN_UNITS MODIFY UNIT_ID NOT NULL;

--
-- RHN_URL_PROBE
--
ALTER TABLE RHN_URL_PROBE DROP CONSTRAINT RHN_URLPB_COOKIE_EN_NN;
ALTER TABLE RHN_URL_PROBE MODIFY COOKIE_ENABLED NOT NULL;

--
-- RHN_URL_PROBE
--
ALTER TABLE RHN_URL_PROBE DROP CONSTRAINT RHN_URLPB_MULTI_STEP_NN;
ALTER TABLE RHN_URL_PROBE MODIFY MULTI_STEP NOT NULL;

--
-- RHN_URL_PROBE
--
ALTER TABLE RHN_URL_PROBE DROP CONSTRAINT RHN_URLPB_PROBE_ID_NN;
ALTER TABLE RHN_URL_PROBE MODIFY PROBE_ID NOT NULL;

--
-- RHN_URL_PROBE
--
ALTER TABLE RHN_URL_PROBE DROP CONSTRAINT RHN_URLPB_PROBE_TYPE_NN;
ALTER TABLE RHN_URL_PROBE MODIFY PROBE_TYPE NOT NULL;

--
-- RHN_URL_PROBE
--
ALTER TABLE RHN_URL_PROBE DROP CONSTRAINT RHN_URLPB_RUN_ON_SCOUTS_NN;
ALTER TABLE RHN_URL_PROBE MODIFY RUN_ON_SCOUTS NOT NULL;

--
-- RHN_URL_PROBE_STEP
--
ALTER TABLE RHN_URL_PROBE_STEP DROP CONSTRAINT RHN_URLPS_CONN_CRIT_NN;
ALTER TABLE RHN_URL_PROBE_STEP MODIFY CONNECT_CRIT NOT NULL;

--
-- RHN_URL_PROBE_STEP
--
ALTER TABLE RHN_URL_PROBE_STEP DROP CONSTRAINT RHN_URLPS_CONN_WARN_NN;
ALTER TABLE RHN_URL_PROBE_STEP MODIFY CONNECT_WARN NOT NULL;

--
-- RHN_URL_PROBE_STEP
--
ALTER TABLE RHN_URL_PROBE_STEP DROP CONSTRAINT RHN_URLPS_COOKIE_SEC_NN;
ALTER TABLE RHN_URL_PROBE_STEP MODIFY COOKIE_SECURE NOT NULL;

--
-- RHN_URL_PROBE_STEP
--
ALTER TABLE RHN_URL_PROBE_STEP DROP CONSTRAINT RHN_URLPS_DNS_CRIT_NN;
ALTER TABLE RHN_URL_PROBE_STEP MODIFY DNS_CRIT NOT NULL;

--
-- RHN_URL_PROBE_STEP
--
ALTER TABLE RHN_URL_PROBE_STEP DROP CONSTRAINT RHN_URLPS_DNS_WARN_NN;
ALTER TABLE RHN_URL_PROBE_STEP MODIFY DNS_WARN NOT NULL;

--
-- RHN_URL_PROBE_STEP
--
ALTER TABLE RHN_URL_PROBE_STEP DROP CONSTRAINT RHN_URLPS_LATE_CRIT_NN;
ALTER TABLE RHN_URL_PROBE_STEP MODIFY LATENCY_CRIT NOT NULL;

--
-- RHN_URL_PROBE_STEP
--
ALTER TABLE RHN_URL_PROBE_STEP DROP CONSTRAINT RHN_URLPS_LATE_WARN_NN;
ALTER TABLE RHN_URL_PROBE_STEP MODIFY LATENCY_WARN NOT NULL;

--
-- RHN_URL_PROBE_STEP
--
ALTER TABLE RHN_URL_PROBE_STEP DROP CONSTRAINT RHN_URLPS_LOAD_SUB_NN;
ALTER TABLE RHN_URL_PROBE_STEP MODIFY LOAD_SUBSIDIARY NOT NULL;

--
-- RHN_URL_PROBE_STEP
--
ALTER TABLE RHN_URL_PROBE_STEP DROP CONSTRAINT RHN_URLPS_PROTOCOL_NN;
ALTER TABLE RHN_URL_PROBE_STEP MODIFY PROTOCOL_METHOD NOT NULL;

--
-- RHN_URL_PROBE_STEP
--
ALTER TABLE RHN_URL_PROBE_STEP DROP CONSTRAINT RHN_URLPS_RECID_NN;
ALTER TABLE RHN_URL_PROBE_STEP MODIFY RECID NOT NULL;

--
-- RHN_URL_PROBE_STEP
--
ALTER TABLE RHN_URL_PROBE_STEP DROP CONSTRAINT RHN_URLPS_THRU_CRIT_NN;
ALTER TABLE RHN_URL_PROBE_STEP MODIFY THROUGH_CRIT NOT NULL;

--
-- RHN_URL_PROBE_STEP
--
ALTER TABLE RHN_URL_PROBE_STEP DROP CONSTRAINT RHN_URLPS_THRU_WARN_NN;
ALTER TABLE RHN_URL_PROBE_STEP MODIFY THROUGH_WARN NOT NULL;

--
-- RHN_URL_PROBE_STEP
--
ALTER TABLE RHN_URL_PROBE_STEP DROP CONSTRAINT RHN_URLPS_TOTAL_CRIT_NN;
ALTER TABLE RHN_URL_PROBE_STEP MODIFY TOTAL_CRIT NOT NULL;

--
-- RHN_URL_PROBE_STEP
--
ALTER TABLE RHN_URL_PROBE_STEP DROP CONSTRAINT RHN_URLPS_TOTAL_WARN_NN;
ALTER TABLE RHN_URL_PROBE_STEP MODIFY TOTAL_WARN NOT NULL;

--
-- RHN_URL_PROBE_STEP
--
ALTER TABLE RHN_URL_PROBE_STEP DROP CONSTRAINT RHN_URLPS_TRANS_CRIT_NN;
ALTER TABLE RHN_URL_PROBE_STEP MODIFY TRANS_CRIT NOT NULL;

--
-- RHN_URL_PROBE_STEP
--
ALTER TABLE RHN_URL_PROBE_STEP DROP CONSTRAINT RHN_URLPS_TRANS_WARN_NN;
ALTER TABLE RHN_URL_PROBE_STEP MODIFY TRANS_WARN NOT NULL;

--
-- RHN_URL_PROBE_STEP
--
ALTER TABLE RHN_URL_PROBE_STEP DROP CONSTRAINT RHN_URLPS_URL_NN;
ALTER TABLE RHN_URL_PROBE_STEP MODIFY URL NOT NULL;

--
-- RHN_URL_PROBE_STEP
--
ALTER TABLE RHN_URL_PROBE_STEP DROP CONSTRAINT RHN_URLPS_URL_PROB_ID_NN;
ALTER TABLE RHN_URL_PROBE_STEP MODIFY URL_PROBE_ID NOT NULL;

--
-- RHN_URL_PROBE_STEP
--
ALTER TABLE RHN_URL_PROBE_STEP DROP CONSTRAINT RHN_URLPS_URL_STEP_NO_NN;
ALTER TABLE RHN_URL_PROBE_STEP MODIFY STEP_NUMBER NOT NULL;

--
-- RHN_URL_PROBE_STEP
--
ALTER TABLE RHN_URL_PROBE_STEP DROP CONSTRAINT RHN_URLPS_VER_LINKS_NN;
ALTER TABLE RHN_URL_PROBE_STEP MODIFY VERIFY_LINKS NOT NULL;

--
-- RHNUSERGROUPTYPE
--
ALTER TABLE RHNUSERGROUPTYPE DROP CONSTRAINT RHN_USERGROUPTYPE_CREATED_NN;
ALTER TABLE RHNUSERGROUPTYPE MODIFY CREATED NOT NULL;

--
-- RHNUSERGROUPTYPE
--
ALTER TABLE RHNUSERGROUPTYPE DROP CONSTRAINT RHN_USERGROUPTYPE_ID_NN;
ALTER TABLE RHNUSERGROUPTYPE MODIFY ID NOT NULL;

--
-- RHNUSERGROUPTYPE
--
ALTER TABLE RHNUSERGROUPTYPE DROP CONSTRAINT RHN_USERGROUPTYPE_LABEL_NN;
ALTER TABLE RHNUSERGROUPTYPE MODIFY LABEL NOT NULL;

--
-- RHNUSERGROUPTYPE
--
ALTER TABLE RHNUSERGROUPTYPE DROP CONSTRAINT RHN_USERGROUPTYPE_MODIFIED_NN;
ALTER TABLE RHNUSERGROUPTYPE MODIFY MODIFIED NOT NULL;

--
-- RHNUSERGROUPTYPE
--
ALTER TABLE RHNUSERGROUPTYPE DROP CONSTRAINT RHN_USERGROUPTYPE_NAME_NN;
ALTER TABLE RHNUSERGROUPTYPE MODIFY NAME NOT NULL;

--
-- RHNUSERGROUP
--
ALTER TABLE RHNUSERGROUP DROP CONSTRAINT RHN_USERGROUP_TYPE_CREATED_NN;
ALTER TABLE RHNUSERGROUP MODIFY CREATED NOT NULL;

--
-- RHNUSERGROUP
--
ALTER TABLE RHNUSERGROUP DROP CONSTRAINT RHN_USERGROUP_TYPE_MODIFIED_NN;
ALTER TABLE RHNUSERGROUP MODIFY MODIFIED NOT NULL;

--
-- RHNUSERGROUP
--
ALTER TABLE RHNUSERGROUP DROP CONSTRAINT RHN_USERGROUP_TYPE_NN;
ALTER TABLE RHNUSERGROUP MODIFY GROUP_TYPE NOT NULL;

--
-- RHNUSERSERVERPREFS
--
ALTER TABLE RHNUSERSERVERPREFS DROP CONSTRAINT RHN_USERSERVERPREFS_CREATED_NN;
ALTER TABLE RHNUSERSERVERPREFS MODIFY CREATED NOT NULL;

--
-- RHNUSERSERVERPREFS
--
ALTER TABLE RHNUSERSERVERPREFS DROP CONSTRAINT RHN_USERSERVERPREFS_MOD_NN;
ALTER TABLE RHNUSERSERVERPREFS MODIFY MODIFIED NOT NULL;

--
-- RHNUSERSERVERPREFS
--
ALTER TABLE RHNUSERSERVERPREFS DROP CONSTRAINT RHN_USERSERVERPREFS_NAME_NN;
ALTER TABLE RHNUSERSERVERPREFS MODIFY NAME NOT NULL;

--
-- RHNUSERSERVERPREFS
--
ALTER TABLE RHNUSERSERVERPREFS DROP CONSTRAINT RHN_USERSERVERPREFS_SID_NN;
ALTER TABLE RHNUSERSERVERPREFS MODIFY SERVER_ID NOT NULL;

--
-- RHNUSERSERVERPREFS
--
ALTER TABLE RHNUSERSERVERPREFS DROP CONSTRAINT RHN_USERSERVERPREFS_UID_NN;
ALTER TABLE RHNUSERSERVERPREFS MODIFY USER_ID NOT NULL;

--
-- RHNUSERSERVERPREFS
--
ALTER TABLE RHNUSERSERVERPREFS DROP CONSTRAINT RHN_USERSERVERPREFS_VALUE_NN;
ALTER TABLE RHNUSERSERVERPREFS MODIFY VALUE NOT NULL;

--
-- RHNUSERGROUP
--
ALTER TABLE RHNUSERGROUP DROP CONSTRAINT RHN_USER_GROUP_CM_NN;
ALTER TABLE RHNUSERGROUP MODIFY CURRENT_MEMBERS NOT NULL;

--
-- RHNUSERGROUP
--
ALTER TABLE RHNUSERGROUP DROP CONSTRAINT RHN_USER_GROUP_DESC_NN;
ALTER TABLE RHNUSERGROUP MODIFY DESCRIPTION NOT NULL;

--
-- RHNUSERGROUP
--
ALTER TABLE RHNUSERGROUP DROP CONSTRAINT RHN_USER_GROUP_ID_NN;
ALTER TABLE RHNUSERGROUP MODIFY ID NOT NULL;

--
-- RHNUSERGROUP
--
ALTER TABLE RHNUSERGROUP DROP CONSTRAINT RHN_USER_GROUP_NAME_NN;
ALTER TABLE RHNUSERGROUP MODIFY NAME NOT NULL;

--
-- RHNUSERGROUP
--
ALTER TABLE RHNUSERGROUP DROP CONSTRAINT RHN_USER_GROUP_ORG_ID_NN;
ALTER TABLE RHNUSERGROUP MODIFY ORG_ID NOT NULL;

--
-- RHNUSERINFO
--
ALTER TABLE RHNUSERINFO DROP CONSTRAINT RHN_USER_INFO_AGREED_NN;
ALTER TABLE RHNUSERINFO MODIFY AGREED_TO_TERMS NOT NULL;

--
-- RHNUSERINFO
--
ALTER TABLE RHNUSERINFO DROP CONSTRAINT RHN_USER_INFO_BADEMAIL_NN;
ALTER TABLE RHNUSERINFO MODIFY BAD_EMAIL NOT NULL;

--
-- RHNUSERINFO
--
ALTER TABLE RHNUSERINFO DROP CONSTRAINT RHN_USER_INFO_CLEARSETS_NN;
ALTER TABLE RHNUSERINFO MODIFY NO_CLEAR_SETS NOT NULL;

--
-- RHNUSERINFO
--
ALTER TABLE RHNUSERINFO DROP CONSTRAINT RHN_USER_INFO_CREATED_NN;
ALTER TABLE RHNUSERINFO MODIFY CREATED NOT NULL;

--
-- RHNUSERINFO
--
ALTER TABLE RHNUSERINFO DROP CONSTRAINT RHN_USER_INFO_MODIFIED_NN;
ALTER TABLE RHNUSERINFO MODIFY MODIFIED NOT NULL;

--
-- RHNUSERINFO
--
ALTER TABLE RHNUSERINFO DROP CONSTRAINT RHN_USER_INFO_NOTIFY_NN;
ALTER TABLE RHNUSERINFO MODIFY EMAIL_NOTIFY NOT NULL;

--
-- RHNUSERINFO
--
ALTER TABLE RHNUSERINFO DROP CONSTRAINT RHN_USER_INFO_PAGESIZE_NN;
ALTER TABLE RHNUSERINFO MODIFY PAGE_SIZE NOT NULL;

--
-- RHNUSERINFO
--
ALTER TABLE RHNUSERINFO DROP CONSTRAINT RHN_USER_INFO_PAM_NN;
ALTER TABLE RHNUSERINFO MODIFY USE_PAM_AUTHENTICATION NOT NULL;

--
-- RHNUSERINFO
--
ALTER TABLE RHNUSERINFO DROP CONSTRAINT RHN_USER_INFO_SEA_NN;
ALTER TABLE RHNUSERINFO MODIFY SHOW_APPLIED_ERRATA NOT NULL;

--
-- RHNUSERINFO
--
ALTER TABLE RHNUSERINFO DROP CONSTRAINT RHN_USER_INFO_SSGL_NN;
ALTER TABLE RHNUSERINFO MODIFY SHOW_SYSTEM_GROUP_LIST NOT NULL;

--
-- RHNUSERINFO
--
ALTER TABLE RHNUSERINFO DROP CONSTRAINT RHN_USER_INFO_TZOFFSET_NN;
ALTER TABLE RHNUSERINFO MODIFY TZ_OFFSET NOT NULL;

--
-- RHNUSERINFO
--
ALTER TABLE RHNUSERINFO DROP CONSTRAINT RHN_USER_INFO_USER_NN;
ALTER TABLE RHNUSERINFO MODIFY USER_ID NOT NULL;

--
-- RHNUSERRESERVED
--
ALTER TABLE RHNUSERRESERVED DROP CONSTRAINT RHN_USER_RES_CREATED_NN;
ALTER TABLE RHNUSERRESERVED MODIFY CREATED NOT NULL;

--
-- RHNUSERRESERVED
--
ALTER TABLE RHNUSERRESERVED DROP CONSTRAINT RHN_USER_RES_LOGIN_NN;
ALTER TABLE RHNUSERRESERVED MODIFY LOGIN NOT NULL;

--
-- RHNUSERRESERVED
--
ALTER TABLE RHNUSERRESERVED DROP CONSTRAINT RHN_USER_RES_LOGIN_UC_NN;
ALTER TABLE RHNUSERRESERVED MODIFY LOGIN_UC NOT NULL;

--
-- RHNUSERRESERVED
--
ALTER TABLE RHNUSERRESERVED DROP CONSTRAINT RHN_USER_RES_MODIFIED_NN;
ALTER TABLE RHNUSERRESERVED MODIFY MODIFIED NOT NULL;

--
-- RHNUSERRESERVED
--
ALTER TABLE RHNUSERRESERVED DROP CONSTRAINT RHN_USER_RES_PWD_NN;
ALTER TABLE RHNUSERRESERVED MODIFY PASSWORD NOT NULL;

--
-- RHNUSERSERVERGROUPPERMS
--
ALTER TABLE RHNUSERSERVERGROUPPERMS DROP CONSTRAINT RHN_USGP_CREATED_NN;
ALTER TABLE RHNUSERSERVERGROUPPERMS MODIFY CREATED NOT NULL;

--
-- RHNUSERSERVERGROUPPERMS
--
ALTER TABLE RHNUSERSERVERGROUPPERMS DROP CONSTRAINT RHN_USGP_MODIFIED_NN;
ALTER TABLE RHNUSERSERVERGROUPPERMS MODIFY MODIFIED NOT NULL;

--
-- RHNUSERSERVERGROUPPERMS
--
ALTER TABLE RHNUSERSERVERGROUPPERMS DROP CONSTRAINT RHN_USGP_SERVER_NN;
ALTER TABLE RHNUSERSERVERGROUPPERMS MODIFY SERVER_GROUP_ID NOT NULL;

--
-- RHNUSERSERVERGROUPPERMS
--
ALTER TABLE RHNUSERSERVERGROUPPERMS DROP CONSTRAINT RHN_USGP_USER_NN;
ALTER TABLE RHNUSERSERVERGROUPPERMS MODIFY USER_ID NOT NULL;

--
-- RHNUSERSERVERPERMS
--
ALTER TABLE RHNUSERSERVERPERMS DROP CONSTRAINT RHN_USPERMS_SID_NN;
ALTER TABLE RHNUSERSERVERPERMS MODIFY SERVER_ID NOT NULL;

--
-- RHNUSERSERVERPERMS
--
ALTER TABLE RHNUSERSERVERPERMS DROP CONSTRAINT RHN_USPERMS_UID_NN;
ALTER TABLE RHNUSERSERVERPERMS MODIFY USER_ID NOT NULL;

--
-- RHNUSERINFOPANE
--
ALTER TABLE RHNUSERINFOPANE DROP CONSTRAINT RHN_USR_INFO_PANE_PID_NN;
ALTER TABLE RHNUSERINFOPANE MODIFY PANE_ID NOT NULL;

--
-- RHNUSERINFOPANE
--
ALTER TABLE RHNUSERINFOPANE DROP CONSTRAINT RHN_USR_INFO_PANE_UID_NN;
ALTER TABLE RHNUSERINFOPANE MODIFY USER_ID NOT NULL;

--
-- RHNVERSIONINFO
--
ALTER TABLE RHNVERSIONINFO DROP CONSTRAINT RHN_VERSIONINFO_CREATED_NN;
ALTER TABLE RHNVERSIONINFO MODIFY CREATED NOT NULL;

--
-- RHNVERSIONINFO
--
ALTER TABLE RHNVERSIONINFO DROP CONSTRAINT RHN_VERSIONINFO_EID_NN;
ALTER TABLE RHNVERSIONINFO MODIFY EVR_ID NOT NULL;

--
-- RHNVERSIONINFO
--
ALTER TABLE RHNVERSIONINFO DROP CONSTRAINT RHN_VERSIONINFO_LABEL_NN;
ALTER TABLE RHNVERSIONINFO MODIFY LABEL NOT NULL;

--
-- RHNVERSIONINFO
--
ALTER TABLE RHNVERSIONINFO DROP CONSTRAINT RHN_VERSIONINFO_MODIFIED_NN;
ALTER TABLE RHNVERSIONINFO MODIFY MODIFIED NOT NULL;

--
-- RHNVERSIONINFO
--
ALTER TABLE RHNVERSIONINFO DROP CONSTRAINT RHN_VERSIONINFO_NID_NN;
ALTER TABLE RHNVERSIONINFO MODIFY NAME_ID NOT NULL;

--
-- RHNVIRTUALINSTANCEEVENTLOG
--
ALTER TABLE RHNVIRTUALINSTANCEEVENTLOG DROP CONSTRAINT RHN_VIEL_CREATED_NN;
ALTER TABLE RHNVIRTUALINSTANCEEVENTLOG MODIFY CREATED NOT NULL;

--
-- RHNVIRTUALINSTANCEEVENTLOG
--
ALTER TABLE RHNVIRTUALINSTANCEEVENTLOG DROP CONSTRAINT RHN_VIEL_ET_NN;
ALTER TABLE RHNVIRTUALINSTANCEEVENTLOG MODIFY EVENT_TYPE NOT NULL;

--
-- RHNVIRTUALINSTANCEEVENTLOG
--
ALTER TABLE RHNVIRTUALINSTANCEEVENTLOG DROP CONSTRAINT RHN_VIEL_ID_NN;
ALTER TABLE RHNVIRTUALINSTANCEEVENTLOG MODIFY ID NOT NULL;

--
-- RHNVIRTUALINSTANCEEVENTLOG
--
ALTER TABLE RHNVIRTUALINSTANCEEVENTLOG DROP CONSTRAINT RHN_VIEL_LT_NN;
ALTER TABLE RHNVIRTUALINSTANCEEVENTLOG MODIFY LOCAL_TIMESTAMP NOT NULL;

--
-- RHNVIRTUALINSTANCEEVENTLOG
--
ALTER TABLE RHNVIRTUALINSTANCEEVENTLOG DROP CONSTRAINT RHN_VIEL_MODIFIED_NN;
ALTER TABLE RHNVIRTUALINSTANCEEVENTLOG MODIFY MODIFIED NOT NULL;

--
-- RHNVIRTUALINSTANCEEVENTLOG
--
ALTER TABLE RHNVIRTUALINSTANCEEVENTLOG DROP CONSTRAINT RHN_VIEL_NEW_STATE_NN;
ALTER TABLE RHNVIRTUALINSTANCEEVENTLOG MODIFY NEW_STATE NOT NULL;

--
-- RHNVIRTUALINSTANCEEVENTLOG
--
ALTER TABLE RHNVIRTUALINSTANCEEVENTLOG DROP CONSTRAINT RHN_VIEL_OLD_STATE_NN;
ALTER TABLE RHNVIRTUALINSTANCEEVENTLOG MODIFY OLD_STATE NOT NULL;

--
-- RHNVIRTUALINSTANCEEVENTTYPE
--
ALTER TABLE RHNVIRTUALINSTANCEEVENTTYPE DROP CONSTRAINT RHN_VIET_CREATED_NN;
ALTER TABLE RHNVIRTUALINSTANCEEVENTTYPE MODIFY CREATED NOT NULL;

--
-- RHNVIRTUALINSTANCEEVENTTYPE
--
ALTER TABLE RHNVIRTUALINSTANCEEVENTTYPE DROP CONSTRAINT RHN_VIET_ID_NN;
ALTER TABLE RHNVIRTUALINSTANCEEVENTTYPE MODIFY ID NOT NULL;

--
-- RHNVIRTUALINSTANCEEVENTTYPE
--
ALTER TABLE RHNVIRTUALINSTANCEEVENTTYPE DROP CONSTRAINT RHN_VIET_LABEL_NN;
ALTER TABLE RHNVIRTUALINSTANCEEVENTTYPE MODIFY LABEL NOT NULL;

--
-- RHNVIRTUALINSTANCEEVENTTYPE
--
ALTER TABLE RHNVIRTUALINSTANCEEVENTTYPE DROP CONSTRAINT RHN_VIET_MODIFIED_NN;
ALTER TABLE RHNVIRTUALINSTANCEEVENTTYPE MODIFY MODIFIED NOT NULL;

--
-- RHNVIRTUALINSTANCEEVENTTYPE
--
ALTER TABLE RHNVIRTUALINSTANCEEVENTTYPE DROP CONSTRAINT RHN_VIET_NAME_NN;
ALTER TABLE RHNVIRTUALINSTANCEEVENTTYPE MODIFY NAME NOT NULL;

--
-- RHNVIRTUALINSTANCEINSTALLLOG
--
ALTER TABLE RHNVIRTUALINSTANCEINSTALLLOG DROP CONSTRAINT RHN_VIIL_CREATED_NN;
ALTER TABLE RHNVIRTUALINSTANCEINSTALLLOG MODIFY CREATED NOT NULL;

--
-- RHNVIRTUALINSTANCEINSTALLLOG
--
ALTER TABLE RHNVIRTUALINSTANCEINSTALLLOG DROP CONSTRAINT RHN_VIIL_ID_NN;
ALTER TABLE RHNVIRTUALINSTANCEINSTALLLOG MODIFY ID NOT NULL;

--
-- RHNVIRTUALINSTANCEINSTALLLOG
--
ALTER TABLE RHNVIRTUALINSTANCEINSTALLLOG DROP CONSTRAINT RHN_VIIL_LM_NN;
ALTER TABLE RHNVIRTUALINSTANCEINSTALLLOG MODIFY LOG_MESSAGE NOT NULL;

--
-- RHNVIRTUALINSTANCEINSTALLLOG
--
ALTER TABLE RHNVIRTUALINSTANCEINSTALLLOG DROP CONSTRAINT RHN_VIIL_MODIFIED_NN;
ALTER TABLE RHNVIRTUALINSTANCEINSTALLLOG MODIFY MODIFIED NOT NULL;

--
-- RHNVIRTUALINSTANCEINFO
--
ALTER TABLE RHNVIRTUALINSTANCEINFO DROP CONSTRAINT RHN_VII_CREATED_NN;
ALTER TABLE RHNVIRTUALINSTANCEINFO MODIFY CREATED NOT NULL;

--
-- RHNVIRTUALINSTANCEINFO
--
ALTER TABLE RHNVIRTUALINSTANCEINFO DROP CONSTRAINT RHN_VII_IT_NN;
ALTER TABLE RHNVIRTUALINSTANCEINFO MODIFY INSTANCE_TYPE NOT NULL;

--
-- RHNVIRTUALINSTANCEINFO
--
ALTER TABLE RHNVIRTUALINSTANCEINFO DROP CONSTRAINT RHN_VII_MODIFIED_NN;
ALTER TABLE RHNVIRTUALINSTANCEINFO MODIFY MODIFIED NOT NULL;

--
-- RHNVIRTUALINSTANCEINFO
--
ALTER TABLE RHNVIRTUALINSTANCEINFO DROP CONSTRAINT RHN_VII_STATE_NN;
ALTER TABLE RHNVIRTUALINSTANCEINFO MODIFY STATE NOT NULL;

--
-- RHNVIRTUALINSTANCEINFO
--
ALTER TABLE RHNVIRTUALINSTANCEINFO DROP CONSTRAINT RHN_VII_VIID_NN;
ALTER TABLE RHNVIRTUALINSTANCEINFO MODIFY INSTANCE_ID NOT NULL;

--
-- RHNVIRTUALINSTANCESTATE
--
ALTER TABLE RHNVIRTUALINSTANCESTATE DROP CONSTRAINT RHN_VIS_CREATED_NN;
ALTER TABLE RHNVIRTUALINSTANCESTATE MODIFY CREATED NOT NULL;

--
-- RHNVIRTUALINSTANCESTATE
--
ALTER TABLE RHNVIRTUALINSTANCESTATE DROP CONSTRAINT RHN_VIS_ID_NN;
ALTER TABLE RHNVIRTUALINSTANCESTATE MODIFY ID NOT NULL;

--
-- RHNVIRTUALINSTANCESTATE
--
ALTER TABLE RHNVIRTUALINSTANCESTATE DROP CONSTRAINT RHN_VIS_LABEL_NN;
ALTER TABLE RHNVIRTUALINSTANCESTATE MODIFY LABEL NOT NULL;

--
-- RHNVIRTUALINSTANCESTATE
--
ALTER TABLE RHNVIRTUALINSTANCESTATE DROP CONSTRAINT RHN_VIS_MODIFIED_NN;
ALTER TABLE RHNVIRTUALINSTANCESTATE MODIFY MODIFIED NOT NULL;

--
-- RHNVIRTUALINSTANCESTATE
--
ALTER TABLE RHNVIRTUALINSTANCESTATE DROP CONSTRAINT RHN_VIS_NAME_NN;
ALTER TABLE RHNVIRTUALINSTANCESTATE MODIFY NAME NOT NULL;

--
-- RHNVIRTUALINSTANCETYPE
--
ALTER TABLE RHNVIRTUALINSTANCETYPE DROP CONSTRAINT RHN_VIT_CREATED_NN;
ALTER TABLE RHNVIRTUALINSTANCETYPE MODIFY CREATED NOT NULL;

--
-- RHNVIRTUALINSTANCETYPE
--
ALTER TABLE RHNVIRTUALINSTANCETYPE DROP CONSTRAINT RHN_VIT_ID_NN;
ALTER TABLE RHNVIRTUALINSTANCETYPE MODIFY ID NOT NULL;

--
-- RHNVIRTUALINSTANCETYPE
--
ALTER TABLE RHNVIRTUALINSTANCETYPE DROP CONSTRAINT RHN_VIT_LABEL_NN;
ALTER TABLE RHNVIRTUALINSTANCETYPE MODIFY LABEL NOT NULL;

--
-- RHNVIRTUALINSTANCETYPE
--
ALTER TABLE RHNVIRTUALINSTANCETYPE DROP CONSTRAINT RHN_VIT_MODIFIED_NN;
ALTER TABLE RHNVIRTUALINSTANCETYPE MODIFY MODIFIED NOT NULL;

--
-- RHNVIRTUALINSTANCETYPE
--
ALTER TABLE RHNVIRTUALINSTANCETYPE DROP CONSTRAINT RHN_VIT_NAME_NN;
ALTER TABLE RHNVIRTUALINSTANCETYPE MODIFY NAME NOT NULL;

--
-- RHNVIRTUALINSTANCE
--
ALTER TABLE RHNVIRTUALINSTANCE DROP CONSTRAINT RHN_VI_CREATED_NN;
ALTER TABLE RHNVIRTUALINSTANCE MODIFY CREATED NOT NULL;

--
-- RHNVIRTUALINSTANCE
--
ALTER TABLE RHNVIRTUALINSTANCE DROP CONSTRAINT RHN_VI_C_NN;
ALTER TABLE RHNVIRTUALINSTANCE MODIFY CONFIRMED NOT NULL;

--
-- RHNVIRTUALINSTANCE
--
ALTER TABLE RHNVIRTUALINSTANCE DROP CONSTRAINT RHN_VI_ID_NN;
ALTER TABLE RHNVIRTUALINSTANCE MODIFY ID NOT NULL;

--
-- RHNVIRTUALINSTANCE
--
ALTER TABLE RHNVIRTUALINSTANCE DROP CONSTRAINT RHN_VI_MODIFIED_NN;
ALTER TABLE RHNVIRTUALINSTANCE MODIFY MODIFIED NOT NULL;

--
-- RHNVIRTSUBLEVEL
--
ALTER TABLE RHNVIRTSUBLEVEL DROP CONSTRAINT RHN_VSL_CREATED_NN;
ALTER TABLE RHNVIRTSUBLEVEL MODIFY CREATED NOT NULL;

--
-- RHNVIRTSUBLEVEL
--
ALTER TABLE RHNVIRTSUBLEVEL DROP CONSTRAINT RHN_VSL_LABEL_NN;
ALTER TABLE RHNVIRTSUBLEVEL MODIFY LABEL NOT NULL;

--
-- RHNVIRTSUBLEVEL
--
ALTER TABLE RHNVIRTSUBLEVEL DROP CONSTRAINT RHN_VSL_MODIFIED_NN;
ALTER TABLE RHNVIRTSUBLEVEL MODIFY MODIFIED NOT NULL;

--
-- RHNVIRTSUBLEVEL
--
ALTER TABLE RHNVIRTSUBLEVEL DROP CONSTRAINT RHN_VSL_NAME_NN;
ALTER TABLE RHNVIRTSUBLEVEL MODIFY NAME NOT NULL;

--
-- RHNWEBCONTACTCHANGELOG
--
ALTER TABLE RHNWEBCONTACTCHANGELOG DROP CONSTRAINT RHN_WCON_CL_CHANGE_SID_NN;
ALTER TABLE RHNWEBCONTACTCHANGELOG MODIFY CHANGE_STATE_ID NOT NULL;

--
-- RHNWEBCONTACTCHANGELOG
--
ALTER TABLE RHNWEBCONTACTCHANGELOG DROP CONSTRAINT RHN_WCON_CL_MODIFIED_NN;
ALTER TABLE RHNWEBCONTACTCHANGELOG MODIFY DATE_COMPLETED NOT NULL;

--
-- RHNWEBCONTACTCHANGELOG
--
ALTER TABLE RHNWEBCONTACTCHANGELOG DROP CONSTRAINT RHN_WCON_CL_WCON_ID_NN;
ALTER TABLE RHNWEBCONTACTCHANGELOG MODIFY WEB_CONTACT_ID NOT NULL;

--
-- RHN_WIDGET
--
ALTER TABLE RHN_WIDGET DROP CONSTRAINT RHN_WDGET_DESC_NN;
ALTER TABLE RHN_WIDGET MODIFY DESCRIPTION NOT NULL;

--
-- RHN_WIDGET
--
ALTER TABLE RHN_WIDGET DROP CONSTRAINT RHN_WDGET_NAME_NN;
ALTER TABLE RHN_WIDGET MODIFY NAME NOT NULL;

--
-- STATE_CHANGE
--
ALTER TABLE STATE_CHANGE DROP CONSTRAINT STATE_CHANGE_ETIME_NN;
ALTER TABLE STATE_CHANGE MODIFY ENTRY_TIME NOT NULL;

--
-- STATE_CHANGE
--
ALTER TABLE STATE_CHANGE DROP CONSTRAINT STATE_CHANGE_O_ID_NN;
ALTER TABLE STATE_CHANGE MODIFY O_ID NOT NULL;

--
-- TIME_SERIES
--
ALTER TABLE TIME_SERIES DROP CONSTRAINT TIME_SERIES_ETIME_NN;
ALTER TABLE TIME_SERIES MODIFY ENTRY_TIME NOT NULL;

--
-- TIME_SERIES
--
ALTER TABLE TIME_SERIES DROP CONSTRAINT TIME_SERIES_O_ID_NN;
ALTER TABLE TIME_SERIES MODIFY O_ID NOT NULL;

--
-- WEB_CONTACT
--
ALTER TABLE WEB_CONTACT DROP CONSTRAINT WEB_CONTACT_CREATED_NN;
ALTER TABLE WEB_CONTACT MODIFY CREATED NOT NULL;

--
-- WEB_CONTACT
--
ALTER TABLE WEB_CONTACT DROP CONSTRAINT WEB_CONTACT_IGNORE_NN;
ALTER TABLE WEB_CONTACT MODIFY IGNORE_FLAG NOT NULL;

--
-- WEB_CONTACT
--
ALTER TABLE WEB_CONTACT DROP CONSTRAINT WEB_CONTACT_LOGIN_NN;
ALTER TABLE WEB_CONTACT MODIFY LOGIN NOT NULL;

--
-- WEB_CONTACT
--
ALTER TABLE WEB_CONTACT DROP CONSTRAINT WEB_CONTACT_LOGIN_UC_NN;
ALTER TABLE WEB_CONTACT MODIFY LOGIN_UC NOT NULL;

--
-- WEB_CONTACT
--
ALTER TABLE WEB_CONTACT DROP CONSTRAINT WEB_CONTACT_MODIFIED_NN;
ALTER TABLE WEB_CONTACT MODIFY MODIFIED NOT NULL;

--
-- WEB_CONTACT
--
ALTER TABLE WEB_CONTACT DROP CONSTRAINT WEB_CONTACT_ORG_NN;
ALTER TABLE WEB_CONTACT MODIFY ORG_ID NOT NULL;

--
-- WEB_CONTACT
--
ALTER TABLE WEB_CONTACT DROP CONSTRAINT WEB_CONTACT_PASSWORD_NN;
ALTER TABLE WEB_CONTACT MODIFY PASSWORD NOT NULL;

--
-- WEB_CUSTOMER
--
ALTER TABLE WEB_CUSTOMER DROP CONSTRAINT WEB_CUSTOMER_CREATED_NN;
ALTER TABLE WEB_CUSTOMER MODIFY CREATED NOT NULL;

--
-- WEB_CUSTOMER
--
ALTER TABLE WEB_CUSTOMER DROP CONSTRAINT WEB_CUSTOMER_ID_NN;
ALTER TABLE WEB_CUSTOMER MODIFY ID NOT NULL;

--
-- WEB_CUSTOMER
--
ALTER TABLE WEB_CUSTOMER DROP CONSTRAINT WEB_CUSTOMER_MODIFIED_NN;
ALTER TABLE WEB_CUSTOMER MODIFY MODIFIED NOT NULL;

--
-- WEB_CUSTOMER
--
ALTER TABLE WEB_CUSTOMER DROP CONSTRAINT WEB_CUSTOMER_NAME_NN;
ALTER TABLE WEB_CUSTOMER MODIFY NAME NOT NULL;

--
-- WEB_CUSTOMER
--
ALTER TABLE WEB_CUSTOMER DROP CONSTRAINT WEB_CUSTOMER_TYPE_NN;
ALTER TABLE WEB_CUSTOMER MODIFY CUSTOMER_TYPE NOT NULL;

--
-- WEB_CUSTOMER_NOTIFICATION
--
ALTER TABLE WEB_CUSTOMER_NOTIFICATION DROP CONSTRAINT WEB_CUST_NOT_CREAT_NN;
ALTER TABLE WEB_CUSTOMER_NOTIFICATION MODIFY CREATION_DATE NOT NULL;

--
-- WEB_CUSTOMER_NOTIFICATION
--
ALTER TABLE WEB_CUSTOMER_NOTIFICATION DROP CONSTRAINT WEB_CUST_NOT_EA_NN;
ALTER TABLE WEB_CUSTOMER_NOTIFICATION MODIFY CONTACT_EMAIL_ADDRESS NOT NULL;

--
-- WEB_CUSTOMER_NOTIFICATION
--
ALTER TABLE WEB_CUSTOMER_NOTIFICATION DROP CONSTRAINT WEB_CUST_NOT_ID_NN;
ALTER TABLE WEB_CUSTOMER_NOTIFICATION MODIFY ID NOT NULL;

--
-- WEB_CUSTOMER_NOTIFICATION
--
ALTER TABLE WEB_CUSTOMER_NOTIFICATION DROP CONSTRAINT WEB_CUST_NOT_OID_NN;
ALTER TABLE WEB_CUSTOMER_NOTIFICATION MODIFY ORG_ID NOT NULL;

--
-- WEB_USER_CONTACT_PERMISSION
--
ALTER TABLE WEB_USER_CONTACT_PERMISSION DROP CONSTRAINT WUCP_CREATED_NN;
ALTER TABLE WEB_USER_CONTACT_PERMISSION MODIFY CREATED NOT NULL;

--
-- WEB_USER_CONTACT_PERMISSION
--
ALTER TABLE WEB_USER_CONTACT_PERMISSION DROP CONSTRAINT WUCP_MODIFIED_NN;
ALTER TABLE WEB_USER_CONTACT_PERMISSION MODIFY MODIFIED NOT NULL;

--
-- WEB_USER_CONTACT_PERMISSION
--
ALTER TABLE WEB_USER_CONTACT_PERMISSION DROP CONSTRAINT WUCP_WUID_NN;
ALTER TABLE WEB_USER_CONTACT_PERMISSION MODIFY WEB_USER_ID NOT NULL;

--
-- WEB_USER_PERSONAL_INFO
--
ALTER TABLE WEB_USER_PERSONAL_INFO DROP CONSTRAINT WUPI_CREATED_NN;
ALTER TABLE WEB_USER_PERSONAL_INFO MODIFY CREATED NOT NULL;

--
-- WEB_USER_PERSONAL_INFO
--
ALTER TABLE WEB_USER_PERSONAL_INFO DROP CONSTRAINT WUPI_FN_NN;
ALTER TABLE WEB_USER_PERSONAL_INFO MODIFY FIRST_NAMES NOT NULL;

--
-- WEB_USER_PERSONAL_INFO
--
ALTER TABLE WEB_USER_PERSONAL_INFO DROP CONSTRAINT WUPI_LN_NN;
ALTER TABLE WEB_USER_PERSONAL_INFO MODIFY LAST_NAME NOT NULL;

--
-- WEB_USER_PERSONAL_INFO
--
ALTER TABLE WEB_USER_PERSONAL_INFO DROP CONSTRAINT WUPI_MODIFIED_NN;
ALTER TABLE WEB_USER_PERSONAL_INFO MODIFY MODIFIED NOT NULL;

--
-- WEB_USER_PERSONAL_INFO
--
ALTER TABLE WEB_USER_PERSONAL_INFO DROP CONSTRAINT WUPI_PREFIX_NN;
ALTER TABLE WEB_USER_PERSONAL_INFO MODIFY PREFIX NOT NULL;

--
-- WEB_USER_PERSONAL_INFO
--
ALTER TABLE WEB_USER_PERSONAL_INFO DROP CONSTRAINT WUPI_WUID_NN;
ALTER TABLE WEB_USER_PERSONAL_INFO MODIFY WEB_USER_ID NOT NULL;

--
-- WEB_USER_PREFIX
--
ALTER TABLE WEB_USER_PREFIX DROP CONSTRAINT WUP_TEXT_NN;
ALTER TABLE WEB_USER_PREFIX MODIFY TEXT NOT NULL;

--
-- WEB_USER_SITE_INFO
--
ALTER TABLE WEB_USER_SITE_INFO DROP CONSTRAINT WUSI_ADDR1_NN;
ALTER TABLE WEB_USER_SITE_INFO MODIFY ADDRESS1 NOT NULL;

--
-- WEB_USER_SITE_INFO
--
ALTER TABLE WEB_USER_SITE_INFO DROP CONSTRAINT WUSI_CITY_NN;
ALTER TABLE WEB_USER_SITE_INFO MODIFY CITY NOT NULL;

--
-- WEB_USER_SITE_INFO
--
ALTER TABLE WEB_USER_SITE_INFO DROP CONSTRAINT WUSI_COUNTRY_NN;
ALTER TABLE WEB_USER_SITE_INFO MODIFY COUNTRY NOT NULL;

--
-- WEB_USER_SITE_INFO
--
ALTER TABLE WEB_USER_SITE_INFO DROP CONSTRAINT WUSI_ID_NN;
ALTER TABLE WEB_USER_SITE_INFO MODIFY ID NOT NULL;

--
-- WEB_USER_SITE_TYPE
--
ALTER TABLE WEB_USER_SITE_TYPE DROP CONSTRAINT WUST_DESC_NN;
ALTER TABLE WEB_USER_SITE_TYPE MODIFY DESCRIPTION NOT NULL;

--
-- WEB_USER_SITE_TYPE
--
ALTER TABLE WEB_USER_SITE_TYPE DROP CONSTRAINT WUST_TYPE_NN;
ALTER TABLE WEB_USER_SITE_TYPE MODIFY TYPE NOT NULL;

--
-- RHNCHECKSUMTYPE
--
ALTER TABLE RHNCHECKSUMTYPE DROP CONSTRAINT RHN_CHECKSUMTYPE_ID_NN;
ALTER TABLE RHNCHECKSUMTYPE MODIFY ID NOT NULL;
ALTER TABLE RHNCHECKSUMTYPE DROP CONSTRAINT RHN_CHECKSUMTYPE_LABEL_NN;
ALTER TABLE RHNCHECKSUMTYPE MODIFY LABEL NOT NULL;
ALTER TABLE RHNCHECKSUMTYPE DROP CONSTRAINT RHN_CHECKSUMTYPE_DESC_NN;
ALTER TABLE RHNCHECKSUMTYPE MODIFY DESCRIPTION NOT NULL;
ALTER TABLE RHNCHECKSUMTYPE DROP CONSTRAINT RHN_CHECKSUMTYPE_CREAT_NN;
ALTER TABLE RHNCHECKSUMTYPE MODIFY CREATED NOT NULL;
ALTER TABLE RHNCHECKSUMTYPE DROP CONSTRAINT RHN_CHECKSUMTYPE_MOD_NN;
ALTER TABLE RHNCHECKSUMTYPE MODIFY MODIFIED NOT NULL;

  0707010000040F000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000004800000000susemanager-schema/upgrade/satellite-schema-5.4-to-spacewalk-schema-1.2   07070100000410000081B400000000000000000000000167AE11140000001D000000000000000000000000000000000000006200000000susemanager-schema/upgrade/satellite-schema-5.4-to-spacewalk-schema-1.2/040-queue_errata-drop.sql drop procedure queue_errata;
   07070100000411000081B400000000000000000000000167AE11140000001E000000000000000000000000000000000000006700000000susemanager-schema/upgrade/satellite-schema-5.4-to-spacewalk-schema-1.2/041-rhnSNPErrataQueue-drop.sql    drop table rhnSNPErrataQueue;
  07070100000412000081B400000000000000000000000167AE11140000001E000000000000000000000000000000000000006700000000susemanager-schema/upgrade/satellite-schema-5.4-to-spacewalk-schema-1.2/042-rhnSNPServerQueue-drop.sql    drop table rhnSNPServerQueue;
  07070100000413000081B400000000000000000000000167AE111400002B2A000000000000000000000000000000000000005E00000000susemanager-schema/upgrade/satellite-schema-5.4-to-spacewalk-schema-1.2/057-delete_server.sql --
-- Copyright (c) 2008--2010 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
-- This deletes a server.  All codepaths which delete servers should hit this
-- or delete_server_bulk()

create or replace
procedure delete_server (
	server_id_in in number
) is
	cursor servergroups is
		select	server_id, server_group_id
		from	rhnServerGroupMembers sgm
		where	sgm.server_id = server_id_in;
	cursor configchannels is
		select	cc.id
		from	rhnConfigChannel cc,
			rhnConfigChannelType cct,
			rhnServerConfigChannel scc
		where	1=1
			and scc.server_id = server_id_in
			and scc.config_channel_id = cc.id
			-- these config channel types are reserved
			-- for use by a single server, so we don't
			-- need to check for other servers subscribed
			and cct.label in
				('local_override','server_import')
			and cct.id = cc.confchan_type_id;
        type filelistsid_t is table of rhnServerPreserveFileList.file_list_id%type;
        filelistsid_c filelistsid_t;

        type probesid_t is table of rhn_check_probe.probe_id%type;
        probesid_c probesid_t;

    is_virt number := 0;
begin
	rhn_channel.delete_server_channels(server_id_in);
	-- rhn_channel.clear_subscriptions(server_id_in);

        -- filelists
	select	spfl.file_list_id id bulk collect into filelistsid_c
	  from	rhnServerPreserveFileList spfl
	 where	spfl.server_id = server_id_in
			and not exists (
				select	1
				from	rhnServerPreserveFileList
				where	file_list_id = spfl.file_list_id
					and server_id != server_id_in
				union
				select	1
				from	rhnKickstartPreserveFileList
				where	file_list_id = spfl.file_list_id
			);
        if filelistsid_c.first is not null then
            forall i in filelistsid_c.first..filelistsid_c.last
                delete from rhnFileList where id = filelistsid_c(i);
        end if;

	for configchannel in configchannels loop
		rhn_config.delete_channel(configchannel.id);
	end loop;

      select count(1) into is_virt
        from rhnServerEntitlementView
       where server_id = server_id_in
         and label in ('virtualization_host', 'virtualization_host_platform')
         and rownum <= 1;

	for sgm in servergroups loop
		rhn_server.delete_from_servergroup(
			sgm.server_id, sgm.server_group_id);
	end loop;

    if is_virt = 1 then
        rhn_entitlements.repoll_virt_guest_entitlements(server_id_in);
    end if;

	-- we're handling this instead of letting an "on delete
	-- set null" do it so that we don't run the risk
	-- of setting off the triggers and killing us with a
	-- mutating table

	-- this is merge of two single updates:
        --  update ... set old_server_id = null where old_server_id = server_id_in;
        --  update ... set new_server_id = null where new_server_id = server_id_in;
        -- so we scan rhnKickstartSession table only once
	update rhnKickstartSession
		set old_server_id = case when old_server_id = server_id_in then null else old_server_id end,
		    new_server_id = case when new_server_id = server_id_in then null else new_server_id end
		where old_server_id = server_id_in 
		   or new_server_id = server_id_in;

	rhn_channel.clear_subscriptions(server_id_in,1);

    	-- A little complicated here, but the goal is to
	-- delete records from rhnVirtualInstace only if we don't
	-- care about them anymore.  We don't care about records
	-- in rhnVirtualInstance if we are deleting the host
	-- system and the virtual system is already null, or
	-- vice-versa.  We *do* care about them if either the
	-- host or virtual system is still registered because we
	-- still want them to show up in the UI.
    -- If there's a newer row in rhnVirtualInstance with the same
    -- uuid, this guest must have been re-registered, so we can clean
    -- this data up.
				
        delete from rhnVirtualInstance vi
	      where (host_system_id = server_id_in and virtual_system_id is null)
                 or (virtual_system_id = server_id_in and host_system_id is null)
                 or (vi.virtual_system_id = server_id_in and vi.modified < (select max(vi2.modified)
                    from rhnVirtualInstance vi2 where vi2.uuid = vi.uuid));
						
        -- this is merge of two single updates:
        --  update ... set host_system_id = null where host_system_id = server_id_in;
        --  update ... set virtual_system_id = null where virtual_system_id = server_id_in;
        -- so we scan rhnVirtualInstance table only once
        update rhnVirtualInstance
	   set host_system_id = case when host_system_id = server_id_in then null else host_system_id end,
	       virtual_system_id = case when virtual_system_id = server_id_in then null else virtual_system_id end
	 where host_system_id = server_id_in
	    or virtual_system_id = server_id_in;
		
        -- this is merge of two single updates:
        --  update ... set old_host_system_id = null when old_host_system_id = server_id_in;
        --  update ... set new_host_system_id = null when new_host_system_id = server_id_in;
        -- so we scan rhnVirtualInstanceEventLog table only once
	update rhnVirtualInstanceEventLog
	   set old_host_system_id = case when old_host_system_id = server_id_in then null else old_host_system_id end,
               new_host_system_id = case when new_host_system_id = server_id_in then null else new_host_system_id end
         where old_host_system_id = server_id_in
            or new_host_system_id = server_id_in;
		 
	-- We're deleting everything with a foreign key to rhnServer
	-- here, now.  I'm hoping this will help aleviate our deadlock
	-- problem.

	delete from rhnActionConfigChannel where server_id = server_id_in;
	delete from rhnActionConfigRevision where server_id = server_id_in;
	delete from rhnActionPackageRemovalFailure where server_id = server_id_in;
	delete from rhnClientCapability where server_id = server_id_in;
	delete from rhnCpu where server_id = server_id_in;
	-- there's still a cascade here, because the constraint keeps the
	-- table locked for too long to rebuild it.  Ugh...
	delete from rhnDevice where server_id = server_id_in;
	delete from rhnProxyInfo where server_id = server_id_in;
	delete from rhnRam where server_id = server_id_in;
	delete from rhnRegToken where server_id = server_id_in;
	delete from rhnSatelliteInfo where server_id = server_id_in;
	-- this cascades to rhnActionConfigChannel and rhnActionConfigFileName
	delete from rhnServerAction where server_id = server_id_in;
	delete from rhnServerActionPackageResult where server_id = server_id_in;
	delete from rhnServerActionScriptResult where server_id = server_id_in;
	delete from rhnServerActionVerifyResult where server_id = server_id_in;
	delete from rhnServerActionVerifyMissing where server_id = server_id_in;
	-- counts are handled above.  this should be a delete_ function.
	delete from rhnServerChannel where server_id = server_id_in;
	delete from rhnServerConfigChannel where server_id = server_id_in;
	delete from rhnServerCustomDataValue where server_id = server_id_in;
	delete from rhnServerDMI where server_id = server_id_in;
	delete from rhnServerEvent where server_id = server_id_in;
	delete from rhnServerHistory where server_id = server_id_in;
	delete from rhnServerInfo where server_id = server_id_in;
	delete from rhnServerInstallInfo where server_id = server_id_in;
	delete from rhnServerLocation where server_id = server_id_in;
	delete from rhnServerLock where server_id = server_id_in;
	delete from rhnServerNeededCache where server_id = server_id_in;
	delete from rhnServerNetwork where server_id = server_id_in;
	delete from rhnServerNotes where server_id = server_id_in;
	-- I'm not removing the foreign key from rhnServerPackage; that'll
	-- take forever.  Do the delete anyway.
	delete from rhnServerPackage where server_id = server_id_in;
	delete from rhnServerTokenRegs where server_id = server_id_in;
	delete from rhnSnapshotTag where server_id = server_id_in;
	-- this cascades to:
	--   rhnSnapshotChannel, rhnSnapshotConfigChannel, rhnSnapshotPackage, 
	--   rhnSnapshotConfigRevision, rhnSnapshotServerGroup, 
	--   rhnSnapshotTag.
	-- We may want to consider delete_snapshot() at some point, but
	--   I don't think we need to yet.
	delete from rhnSnapshot where server_id = server_id_in;
	delete from rhnUserServerPrefs where server_id = server_id_in;
	-- hrm, this one's interesting... we _probably_ should delete
	-- everything for the parent server_id when we delete the proxy,
	-- but we don't currently.
	delete from rhnServerPath where server_id_in in (server_id, proxy_server_id);
	delete from rhnUserServerPerms where server_id = server_id_in;

	delete from rhnServerNetInterface where server_id = server_id_in;
	delete from rhn_server_monitoring_info where recid = server_id_in;

	delete from rhnAppInstallSession where server_id = server_id_in;
	delete from rhnServerUuid where server_id = server_id_in;
    -- We delete all the probes running directly against this system
    -- and any probes that were using this Server as a Proxy Scout.
     SELECT CP.probe_id bulk collect into probesid_c
       FROM rhn_check_probe CP  
      WHERE CP.host_id = server_id_in
         OR CP.sat_cluster_id in
    (SELECT SN.sat_cluster_id
       FROM rhn_sat_node SN
      WHERE SN.server_id = server_id_in);

    if probesid_c.first is not null then
        FORALL i IN probesid_c.first..probesid_c.last
            DELETE FROM rhn_probe_state PS WHERE PS.probe_id = probesid_c(i);
        FORALL i IN probesid_c.first..probesid_c.last
            DELETE FROM rhn_probe P  WHERE P.recid = probesid_c(i);
        FORALL i IN probesid_c.first..probesid_c.last
            DELETE /*+index(time_series time_series_probe_id_idx)*/
            FROM time_series
            WHERE substr(o_id, instr(o_id, '-') + 1,
                (instr(o_id, '-', instr(o_id, '-') + 1) - instr(o_id, '-'))	- 1) = probesid_c(i);
    end if;

	delete from rhn_check_probe where host_id = server_id_in;
	delete from rhn_host_probe where host_id = server_id_in;

    delete from rhn_sat_cluster where recid in
      ( select sat_cluster_id from rhn_sat_node where server_id = server_id_in );

	delete from rhn_sat_node where server_id = server_id_in;
	
	-- now get rhnServer itself.
	delete
	from	rhnServer
		where id = server_id_in;

	delete
	from	rhnSet
	where	1=1
		and user_id in (
			select	wc.id
			from	rhnServer rs,
				web_contact wc
			where	rs.id = server_id_in
				and rs.org_id = wc.org_id
		)
		and label = 'system_list'
		and element = server_id_in;
end delete_server;
/
show errors;
  07070100000414000081B400000000000000000000000167AE111400000393000000000000000000000000000000000000006A00000000susemanager-schema/upgrade/satellite-schema-5.4-to-spacewalk-schema-1.2/090-rhnRepoRegenQueue-trigger.sql 
--
-- Copyright (c) 2008--2010 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--

create or replace trigger rhn_repo_regen_queue_mod_trig
before insert or update on rhnRepoRegenQueue
for each row
begin
    if :new.id is null then
        select rhn_repo_regen_queue_id_seq.nextval into :new.id from dual;
    end if;
    :new.modified := sysdate;
end;
/
show errors
 07070100000415000081B400000000000000000000000167AE111400001064000000000000000000000000000000000000006100000000susemanager-schema/upgrade/satellite-schema-5.4-to-spacewalk-schema-1.2/091-rhn_entitlements.sql  --
-- Copyright (c) 2008--2010 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--

create or replace
package rhn_entitlements
is
	body_version varchar2(100) := '';

   type ents_array is varray(10) of rhnServerGroupType.label%TYPE;

    procedure remove_org_entitlements (
        org_id_in number
    );

    function entitlement_grants_service (
	    entitlement_in in varchar2,
		service_level_in in varchar2
	) return number;

	function lookup_entitlement_group (
		org_id_in in number,
		type_label_in in varchar2 := 'sw_mgr_entitled'
	) return number;

	function create_entitlement_group (
		org_id_in in number,
		type_label_in in varchar2 := 'sw_mgr_entitled'
	) return number;

   function can_entitle_server ( 
      server_id_in   in number, 
      type_label_in  in varchar2
   )
   return number;

   function can_switch_base ( 
      server_id_in   in    integer, 
      type_label_in  in    varchar2
   )
   return number;

	procedure entitle_server (
		server_id_in in number,
		type_label_in in varchar2 := 'sw_mgr_entitled'
	);

	procedure remove_server_entitlement (
		server_id_in in number,
		type_label_in in varchar2 := 'sw_mgr_entitled',
        repoll_virt_guests in number := 1
	);

	procedure unentitle_server (
		server_id_in in number
	);

    procedure repoll_virt_guest_entitlements(
        server_id_in in number
    );

	function get_server_entitlement (
		server_id_in in number
	) return ents_array;

	procedure modify_org_service (
		org_id_in in number,
		service_label_in in varchar2,
		enable_in in char
	);

    procedure set_customer_enterprise (
		customer_id_in in number
	);

	procedure set_customer_provisioning (
		customer_id_in in number
	);

	procedure set_customer_nonlinux (
		customer_id_in in number
	);

    procedure unset_customer_enterprise (
		customer_id_in in number
	);

	procedure unset_customer_provisioning (
		customer_id_in in number
	);

	procedure unset_customer_nonlinux (
		customer_id_in in number
	);

    procedure assign_system_entitlement(
        group_label_in in varchar2,
        from_org_id_in in number,
        to_org_id_in in number,
        quantity_in in number
    );

    procedure assign_channel_entitlement(
        channel_family_label_in in varchar2,
        from_org_id_in in number,
        to_org_id_in in number,
        quantity_in in number,
        flex_in in number
    );

    procedure activate_system_entitlement(
        org_id_in in number,
        group_label_in in varchar2,
        quantity_in in number
    );

    procedure activate_channel_entitlement(
        org_id_in in number,
        channel_family_label_in in varchar2,
        quantity_in in number,
        flex_in in number
    );

    procedure set_group_count (
		customer_id_in in number,	-- customer_id
		type_in in char,			-- 'U' or 'S'
		group_type_in in number,	-- rhn[User|Server]GroupType.id
		quantity_in in number,		-- quantity
                update_family_countsYN in number := 1 -- call update_family_counts inside
    );

    procedure set_family_count (
		customer_id_in in number,		-- customer_id
		channel_family_id_in in number,	-- 246
		quantity_in in number,			-- 3
                flex_in in number
    );

    -- this makes NO checks that the quantity is within max,
    -- so we should NEVER run this unless we KNOW that we won't be
    -- violating the max
    procedure entitle_last_modified_servers (
		customer_id_in in number,	-- customer_id
		type_label_in in varchar2,	-- 'enterprise_entitled'
		quantity_in in number		-- 3
    );

	procedure subscribe_newest_servers (
		customer_id_in in number
	);
end rhn_entitlements;
/
show errors

07070100000416000081B400000000000000000000000167AE1114000110AC000000000000000000000000000000000000006600000000susemanager-schema/upgrade/satellite-schema-5.4-to-spacewalk-schema-1.2/092-rhn_entitlements-body.sql --
-- Copyright (c) 2008--2010 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--

create or replace
package body rhn_entitlements
is
    body_version varchar2(100) := '';

   function find_compatible_sg (
      server_id_in    in   number,
      type_label_in   in   varchar2
   ) return number is

      cursor servergroups is
         select sg.id            id
           from rhnServerGroupType             sgt,
                rhnServerGroup                 sg,
                rhnServer                     s,
                rhnServerServerGroupArchCompat ssgac
          where s.id = server_id_in
            and s.org_id = sg.org_id
            and sgt.label = type_label_in
            and sg.group_type = sgt.id
            and ssgac.server_group_type = sgt.id
            and ssgac.server_arch_id = s.server_arch_id
            and not exists ( 
                     select 1
                      from rhnServerGroupMembers sgm
                     where sgm.server_group_id = sg.id 
                       and sgm.server_id = s.id);

         
   begin
      for servergroup in servergroups loop
         return servergroup.id;
      end loop;

      --no servergroup found
      return null;
   end find_compatible_sg;


    -- *******************************************************************
    -- PROCEDURE: remove_org_entitlements
    --
    -- Removes both system entitlements and channel subscriptions
    -- that are currently assigned to an org and re-assigns to the
    -- master org (org_id = 1).
    --
    -- When we call this we expect everything to already be unentitled
    -- which shoul be handled by delete_org.
    --
    -- Called by: delete_org
    -- *******************************************************************
    procedure remove_org_entitlements(
        org_id_in in number
    )
    is

        cursor system_ents is
        select sg.id, sg.max_members, sg.group_type
        from rhnServerGroup sg
        where group_type is not null
          and org_id = org_id_in;

        cursor channel_subs is
        select pcf.channel_family_id, pcf.max_members
        from rhnChannelFamily cf,
             rhnPrivateChannelFamily pcf
        where pcf.org_id = org_id_in
          and pcf.channel_family_id = cf.id
          and cf.org_id is null;

    begin

        for system_ent in system_ents loop
            update rhnServerGroup
            set max_members = max_members + system_ent.max_members
            where org_id = 1
              and group_type = system_ent.group_type;
        end loop;

        update rhnServerGroup
        set max_members = 0
        where org_id = org_id_in;

        for channel_sub in channel_subs loop
            update rhnPrivateChannelFamily
            set max_members = max_members + channel_sub.max_members
            where org_id = 1
              and channel_family_id = channel_sub.channel_family_id;
        end loop;
        
        update rhnPrivateChannelFamily
        set max_members = 0
        where org_id = org_id_in;

    end remove_org_entitlements;
 
    function entitlement_grants_service (
        entitlement_in in varchar2,
        service_level_in in varchar2
    ) return number    is
    begin
        if service_level_in = 'provisioning' then
            if entitlement_in = 'provisioning_entitled' then
                return 1;
            else
                return 0;
            end if;
        elsif service_level_in = 'management' then
            if entitlement_in = 'enterprise_entitled' then
                return 1;
            else
                return 0;
            end if;
        elsif service_level_in = 'monitoring' then
            if entitlement_in = 'monitoring_entitled' then
                return 1;
            end if;
        elsif service_level_in = 'updates' then
            return 1;
        else
            return 0;
        end if;
    end entitlement_grants_service;

    function lookup_entitlement_group (
        org_id_in in number,
        type_label_in in varchar2 := 'sw_mgr_entitled'
    ) return number is
        cursor server_groups is
            select    sg.id                server_group_id
            from    rhnServerGroup        sg,
                    rhnServerGroupType    sgt
            where    sgt.label = type_label_in
                and sgt.id = sg.group_type
                and sg.org_id = org_id_in;
    begin
        for sg in server_groups loop
            return sg.server_group_id;
        end loop;
        return rhn_entitlements.create_entitlement_group(
                org_id_in,
                type_label_in
            );
    end lookup_entitlement_group;

    function create_entitlement_group (
        org_id_in in number,
        type_label_in in varchar2 := 'sw_mgr_entitled'
    ) return number is
        sg_id_val number;
    begin
        select    rhn_server_group_id_seq.nextval
        into    sg_id_val
        from    dual;

        insert into rhnServerGroup (
                id, name, description, max_members, current_members,
                group_type, org_id
            ) (
                select    sg_id_val, sgt.label, sgt.label,
                        0, 0, sgt.id, org_id_in
                from    rhnServerGroupType sgt
                where    sgt.label = type_label_in
            );

        return sg_id_val;
    end create_entitlement_group;

   function can_entitle_server ( 
        server_id_in in number, 
        type_label_in in varchar2 ) 
   return number is
      cursor addon_servergroups (base_label_in in varchar2, 
                                 addon_label_in in varchar2) is
         select
            addon_id
         from
            rhnSGTypeBaseAddonCompat
         where base_id = lookup_sg_type (base_label_in)
           and addon_id = lookup_sg_type (addon_label_in);

      previous_ent        rhn_entitlements.ents_array;
      is_base_in          char   := 'N';
      is_base_current     char   := 'N';
      i                   number := 0;
      sgid                number := 0;

   begin

      previous_ent := rhn_entitlements.ents_array();
      previous_ent := rhn_entitlements.get_server_entitlement(server_id_in);

      select distinct is_base
      into is_base_in
      from rhnServerGroupType
      where label = type_label_in;

      if previous_ent.count = 0 then
         sgid := find_compatible_sg (server_id_in, type_label_in);
         if (is_base_in = 'Y' and sgid is not null) then
            -- rhn_server.insert_into_servergroup (server_id_in, sgid);
            return 1;
         else
            -- rhn_exception.raise_exception ('invalid_base_entitlement');
            return 0;
         end if;

      -- there are previous ents, first make sure we're not trying to entitle a base ent
      elsif is_base_in = 'Y' then
         -- rhn_exception.raise_exception ('invalid_addon_entitlement');
         return 0;

      -- it must be an addon, so proceed with the entitlement
      else

         -- find the servers base ent
         is_base_current := 'N';
         i := 0;
         while is_base_current = 'N' and i <= previous_ent.count
         loop
            i := i + 1;
            select is_base
            into is_base_current
            from rhnServerGroupType
            where label = previous_ent(i);
         end loop;

         -- never found a base ent, that would be strange
         if is_base_current  = 'N' then
            -- rhn_exception.raise_exception ('invalid_base_entitlement');
            return 0;
         end if;

         -- this for loop verifies the validity of the addon path
         for addon_servergroup in addon_servergroups  (previous_ent(i), type_label_in) loop
            -- find an appropriate sgid for the addon and entitle the server
            sgid := find_compatible_sg (server_id_in, type_label_in);
            if sgid is not null then
               -- rhn_server.insert_into_servergroup (server_id_in, sgid);
               return 1;
            else
               -- rhn_exception.raise_exception ('invalid_addon_entitlement');
               return 0;
            end if;
         end loop;

      end if;

      return 0;

   end can_entitle_server;

   function can_switch_base (
      server_id_in   in    integer,
      type_label_in  in    varchar2
   ) return number is

      type_label_in_is_base   char(1);
      sgid                    number;

   begin

      begin
         select is_base into type_label_in_is_base
         from rhnServerGroupType
         where label = type_label_in;
      exception
         when no_data_found then
            rhn_exception.raise_exception ( 'invalid_entitlement' );
      end;

      if type_label_in_is_base = 'N' then
         rhn_exception.raise_exception ( 'invalid_entitlement' );
      else
         sgid := find_compatible_sg ( server_id_in, type_label_in );
         if sgid is not null then
            return 1;
         else
            return 0;
         end if;
      end if;

   end can_switch_base;


    procedure entitle_server (
        server_id_in in number,
        type_label_in in varchar2 := 'sw_mgr_entitled'
    ) is
      sgid  number := 0;
      is_virt number := 0;

    begin

          begin
          select 1 into is_virt
            from rhnServerEntitlementView
           where server_id = server_id_in
             and label in ('virtualization_host', 'virtualization_host_platform');
      exception
            when no_data_found then
              is_virt := 0;
          end;
      
      if is_virt = 0 and (type_label_in = 'virtualization_host' or
                          type_label_in = 'virtualization_host_platform') then

        is_virt := 1;
      end if;



      if rhn_entitlements.can_entitle_server(server_id_in, 
                                             type_label_in) = 1 then
         sgid := find_compatible_sg (server_id_in, type_label_in);
         if sgid is not null then
            insert into rhnServerHistory ( id, server_id, summary, details )
            values ( rhn_event_id_seq.nextval, server_id_in,
                     'added system entitlement ',
                      case type_label_in
                       when 'enterprise_entitled' then 'Management'
                       when 'sw_mgr_entitled' then 'Update'
                       when 'provisioning_entitled' then 'Provisioning'
                       when 'monitoring_entitled' then 'Monitoring'  
                       when 'virtualization_host' then 'Virtualization'
                       when 'virtualization_host_platform' then 
                            'Virtualization Platform' end  );

            rhn_server.insert_into_servergroup (server_id_in, sgid);

            if is_virt = 1 then
              rhn_entitlements.repoll_virt_guest_entitlements(server_id_in);
            end if;

         else
            rhn_exception.raise_exception ('no_available_server_group');
         end if;
      else
         rhn_exception.raise_exception ('invalid_entitlement');
      end if;
   end entitle_server;

    procedure remove_server_entitlement (
        server_id_in in number,
        type_label_in in varchar2 := 'sw_mgr_entitled',
        repoll_virt_guests in number := 1
    ) is
        group_id number;
      type_is_base char;
      is_virt number := 0;
    begin
      begin


      -- would be nice if there were a virt attribute of entitlement types, not have to specify 2 different ones...
        begin
          select 1 into is_virt
            from rhnServerEntitlementView
           where server_id = server_id_in
             and label in ('virtualization_host', 'virtualization_host_platform');
        exception
          when no_data_found then
            is_virt := 0;
        end;

        select    sg.id, sgt.is_base
          into    group_id, type_is_base
          from    rhnServerGroupType sgt,
               rhnServerGroup sg,
                  rhnServerGroupMembers sgm,
                  rhnServer s
          where    s.id = server_id_in
              and s.id = sgm.server_id
              and sgm.server_group_id = sg.id
              and sg.org_id = s.org_id
              and sgt.label = type_label_in
              and sgt.id = sg.group_type;

      if ( type_is_base = 'Y' ) then
         -- unentitle_server should handle everything, don't really need to do anything else special here
         unentitle_server ( server_id_in );
      else

         insert into rhnServerHistory ( id, server_id, summary, details )
         values ( rhn_event_id_seq.nextval, server_id_in,
                  'removed system entitlement ',
                   case type_label_in
                    when 'enterprise_entitled' then 'Management'
                    when 'sw_mgr_entitled' then 'Update'
                    when 'provisioning_entitled' then 'Provisioning'
                    when 'monitoring_entitled' then 'Monitoring'
                    when 'virtualization_host' then 'Virtualization'
                    when 'virtualization_host_platform' then 
                         'Virtualization Platforrm' end  );

         rhn_server.delete_from_servergroup(server_id_in, group_id);

         -- special case: clean up related monitornig data
         if type_label_in = 'monitoring_entitled' then
           DELETE
             FROM state_change
            WHERE o_id IN (SELECT probe_id
                             FROM rhn_check_probe
                            WHERE host_id = server_id_in);
           DELETE /*+index(time_series time_series_probe_id_idx)*/
             FROM time_series
            WHERE SUBSTR(o_id, INSTR(o_id, '-') + 1, 
                        (INSTR(o_id, '-', INSTR(o_id, '-') + 1) - INSTR(o_id, '-')) - 1)
              IN (SELECT to_char(probe_id)
                    FROM rhn_check_probe
                   WHERE host_id = server_id_in);
           DELETE
             FROM rhn_probe
            WHERE recid IN (SELECT probe_id
                              FROM rhn_check_probe
                             WHERE host_id = server_id_in);
         end if;

         if is_virt = 1 and repoll_virt_guests = 1 then
           rhn_entitlements.repoll_virt_guest_entitlements(server_id_in);
         end if;
      end if;

          exception
          when no_data_found then
                  rhn_exception.raise_exception('invalid_server_group_member');
      end;

     end remove_server_entitlement;


   procedure unentitle_server (server_id_in in number) is

      cursor servergroups is
         select distinct sgt.label, sg.id server_group_id
         from  rhnServerGroupType sgt,
               rhnServerGroup sg,
               rhnServer s,
               rhnServerGroupMembers sgm
         where s.id = server_id_in
            and s.org_id = sg.org_id
            and sg.group_type = sgt.id
            and sgm.server_group_id = sg.id
            and sgm.server_id = s.id;
            
     is_virt number := 0;

   begin

      begin
        select 1 into is_virt
          from rhnServerEntitlementView
         where server_id = server_id_in
           and label in ('virtualization_host', 'virtualization_host_platform');
      exception
        when no_data_found then
          is_virt := 0;
      end;

      for servergroup in servergroups loop

         insert into rhnServerHistory ( id, server_id, summary, details )
         values ( rhn_event_id_seq.nextval, server_id_in,
                  'removed system entitlement ',
                   case servergroup.label
                    when 'enterprise_entitled' then 'Management'
                    when 'sw_mgr_entitled' then 'Update'
                    when 'provisioning_entitled' then 'Provisioning'
                    when 'monitoring_entitled' then 'Monitoring'
                    when 'virtualization_host' then 'Virtualization'
                    when 'virtualization_host_platform' then 
                         'Virtualization Platform' end  );
  
         rhn_server.delete_from_servergroup(server_id_in, 
                                            servergroup.server_group_id );
      end loop;

      if is_virt = 1 then
        rhn_entitlements.repoll_virt_guest_entitlements(server_id_in);
      end if;

   end unentitle_server;


    -- *******************************************************************
    -- PROCEDURE: repoll_virt_guest_entitlements
    --
    --   Whenever we add/remove a virtualization_host* entitlement from 
    --   a host, we can call this procedure to update what type of slots
    --   the guests are consuming.  
    -- 
    --   If you're removing the entitlement, it's 
    --   possible the guests will become unentitled if you don't have enough
    --   physical slots to cover them.
    --
    --   If you're adding the entitlement, you end up freeing up physical
    --   slots for other systems.
    --
    -- *******************************************************************
    procedure repoll_virt_guest_entitlements(server_id_in in number)
    is

        -- All channel families associated with the guests of server_id_in
        cursor families is 
            select distinct cfs.channel_family_id
            from
                rhnChannelFamilyServers cfs,
                rhnVirtualInstance vi
            where
                vi.host_system_id = server_id_in
                and vi.virtual_system_id = cfs.server_id;
        
        -- All of server group types associated with the guests of
        -- server_id_in
        cursor group_types is
            select distinct sg.group_type, sgt.label
            from
                rhnServerGroupType sgt,
                rhnServerGroup sg,
                rhnServerGroupMembers sgm,
                rhnVirtualInstance vi
            where
                vi.host_system_id = server_id_in
                and vi.virtual_system_id = sgm.server_id
                and sgm.server_group_id = sg.id
                and sg.group_type = sgt.id;

        -- Virtual servers from a certain family belonging to a speicifc
        -- host that are consuming physical channel slots over the limit.
        cursor virt_servers_cfam(family_id_in in number, quantity_in in number)  is
            select virtual_system_id
            from (
                select rownum, vi.virtual_system_id
                from
                    rhnChannelFamilyMembers cfm,
                    rhnServerChannel sc,
                    rhnVirtualInstance vi
                where
                    vi.host_system_id = server_id_in
                    and vi.virtual_system_id = sc.server_id
                    and sc.channel_id = cfm.channel_id
                    and cfm.channel_family_id = family_id_in
                order by sc.modified desc
                )
            where rownum <= quantity_in;

        -- Virtual servers from a certain family belonging to a speicifc
        -- host that are consuming physical system slots over the limit.
        cursor virt_servers_sgt(group_type_in in number, quantity_in in number)  is
            select virtual_system_id
            from (
                select rownum, vi.virtual_system_id
                from
                    rhnServerGroup sg,
                    rhnServerGroupMembers sgm,
                    rhnVirtualInstance vi
                where
                    vi.host_system_id = server_id_in
                    and vi.virtual_system_id = sgm.server_id
                    and sgm.server_group_id = sg.id
                    and sg.group_type = group_type_in
                order by sgm.modified desc
                )
            where rownum <= quantity_in;
        -- Get the orgs of Virtual guests
        -- Since they may belong to different orgs
        cursor virt_guest_orgs  is
                select  distinct (s.org_id)
                from rhnServer s
                    inner join  rhnVirtualInstance vi on vi.virtual_system_id = s.id
                where
                    vi.host_system_id = server_id_in 
                    and s.org_id <> (select s1.org_id from rhnServer s1 where s1.id = vi.host_system_id) ;


        org_id_val number;
        max_members_val number;
        max_flex_val number;
        current_members_calc number;
        sg_id number;
        is_virt number := 0;
    begin
        begin
          select 1 into is_virt
                from rhnServerEntitlementView
           where server_id = server_id_in
                 and label in ('virtualization_host', 'virtualization_host_platform');
           exception
                when no_data_found then
                  is_virt := 0;
        end;

        select org_id
        into org_id_val
        from rhnServer
        where id = server_id_in;

        -- deal w/ channel entitlements first ...
        for family in families loop
            if is_virt = 0 then
            -- if the host_server does not have virt
            --- find all possible flex slots
            -- and set each of the flex eligible guests to Y
                UPDATE rhnServerChannel sc set sc.is_fve = 'Y'
                where sc.server_id in (
                       select virtual_system_id from (
                            select rownum, vi.virtual_system_id,  sfc.max_members - sfc.current_members as free_slots
                            from rhnServerFveCapable sfc
                                inner join rhnVirtualInstance vi on vi.virtual_system_id = sfc.server_id
                            where vi.host_system_id = server_id_in
                                  and sfc.channel_family_id = family.channel_family_id
                              order by vi.modified desc
                          )
                        where rownum <=  free_slots
                );
            else
            -- if the host_server has virt
            -- set all its flex guests to N
                UPDATE rhnServerChannel sc set sc.is_fve = 'N'
                where 
                    sc.channel_id in (select cfm.channel_id from rhnChannelFamilyMembers cfm
                                      where cfm.CHANNEL_FAMILY_ID = family.channel_family_id)
                    and sc.is_fve = 'Y'
                    and sc.server_id in  
                            (select vi.virtual_system_id  from rhnVirtualInstance vi 
                                    where vi.host_system_id = server_id_in);
            end if;
        
            -- get the current (physical) members of the family
            current_members_calc := 
                rhn_channel.channel_family_current_members(family.channel_family_id,
                                                           org_id_val); -- fixed transposed args

            -- get the max members of the family
            select max_members
            into max_members_val
            from rhnPrivateChannelFamily
            where channel_family_id = family.channel_family_id
            and org_id = org_id_val;

            select fve_max_members
            into max_flex_val
            from rhnPrivateChannelFamily
            where channel_family_id = family.channel_family_id
            and org_id = org_id_val;

            if current_members_calc > max_members_val then
                -- A virtualization_host* ent must have been removed, so we'll
                -- unsubscribe guests from the host first.

                -- hm, i don't think max_members - current_members_calc yielding a negative number
                -- will work w/ rownum, swaping 'em in the body of this if...
                for virt_server in virt_servers_cfam(family.channel_family_id,
                                current_members_calc - max_members_val) loop 

                    rhn_channel.unsubscribe_server_from_family(
                                virt_server.virtual_system_id,
                                family.channel_family_id);
                end loop;                               

                -- if we're still over the limit, which would be odd,
                -- just prune the group to max_members
                --
                -- er... wouldn't we actually have to refresh the values of
                -- current_members_calc and max_members_val to actually ever
                -- *skip this??
                if current_members_calc > max_members_val then
                    -- argh, transposed again?!
                    set_family_count(org_id_val,
                                     family.channel_family_id,
                                     max_members_val, max_flex_val);
                    --TODO calculate this correctly
                end if; 

           end if;

            -- update current_members for the family.  This will set the value
            -- to reflect adding/removing the entitlement.
            --
            -- what's the difference of doing this vs the unavoidable set_family_count above?
            rhn_channel.update_family_counts(family.channel_family_id,
                                             org_id_val);

            -- It is possible that the guests belong  to a different org than the host
            -- so we are going to update the family counts in the guests orgs also
            for org in virt_guest_orgs loop
                    rhn_channel.update_family_counts(family.channel_family_id,
                                             org.org_id);
            end loop;
        end loop;

        for a_group_type in group_types loop
          -- get the current *physical* members of the system entitlement type for the org...
          -- 
          -- unlike channel families, it appears the standard rhnServerGroup.max_members represents
          -- *physical* slots, vs physical+virt ... boy that's confusing...

          select max_members, id
            into max_members_val, sg_id
            from rhnServerGroup
            where group_type = a_group_type.group_type
            and org_id = org_id_val;


      select count(sep.server_id) into current_members_calc
            from rhnServerEntitlementPhysical sep
           where sep.server_group_id = sg_id
             and sep.server_group_type_id = a_group_type.group_type;
          
          if current_members_calc > max_members_val then
            -- A virtualization_host* ent must have been removed, and we're over the limit, so unsubscribe guests
            for virt_server in virt_servers_sgt(a_group_type.group_type,
                                                current_members_calc - max_members_val) loop
              rhn_entitlements.remove_server_entitlement(virt_server.virtual_system_id, a_group_type.label);

              -- decrement current_members_calc, we'll use it to reset current_members for the group at the end...
              current_members_calc := current_members_calc - 1;
            end loop;

          end if;

          update rhnServerGroup set current_members = current_members_calc
           where org_id = org_id_val
             and group_type = a_group_type.group_type;

          -- I think that's all the house-keeping we have to do...
        end loop;

    end repoll_virt_guest_entitlements;


    function get_server_entitlement (
        server_id_in in number
    ) return ents_array is

        cursor server_groups is
            select    sgt.label
            from    rhnServerGroupType        sgt,
                    rhnServerGroup            sg,
                    rhnServerGroupMembers    sgm
            where    1=1
                and sgm.server_id = server_id_in
                and sg.id = sgm.server_group_id
                and sgt.id = sg.group_type
                and sgt.label in (
                    'sw_mgr_entitled','enterprise_entitled',
                    'provisioning_entitled', 'nonlinux_entitled',
                    'monitoring_entitled', 'virtualization_host',
                                        'virtualization_host_platform'
                    );

         ent_array ents_array;

    begin
      
      ent_array := ents_array();

        for sg in server_groups loop
         ent_array.extend;
         ent_array(ent_array.count) := sg.label;
        end loop;

        return ent_array;

    end get_server_entitlement;


    -- this desperately needs to be table driven.
    procedure modify_org_service (
        org_id_in in number,
        service_label_in in varchar2,
        enable_in in char
    ) is
        type roles_v is varray(10) of rhnUserGroupType.label%TYPE;
        roles_to_process roles_v;
        cursor roles(role_label_in in varchar2) is
            select    label, id
            from    rhnUserGroupType
            where    label = role_label_in;
        cursor org_roles(role_label_in in varchar2) is
            select    1
            from    rhnUserGroup ug,
                    rhnUserGroupType ugt
            where    ugt.label = role_label_in
                and ug.org_id = org_id_in
                and ugt.id = ug.group_type;

        type ents_v is varray(10) of rhnOrgEntitlementType.label%TYPE;
        ents_to_process ents_v;
        cursor ents(ent_label_in in varchar2) is
            select    label, id
            from    rhnOrgEntitlementType
            where    label = ent_label_in;
        cursor org_ents(ent_label_in in varchar2) is
            select    1
            from    rhnOrgEntitlements oe,
                    rhnOrgEntitlementType oet
            where    oet.label = ent_label_in
                and oe.org_id = org_id_in
                and oet.id = oe.entitlement_id;
        create_row char(1);
    begin
        ents_to_process := ents_v();
        roles_to_process := roles_v();
        -- a bit kludgy, but only for 3.4 really.  Certainly no
        -- worse than the old code...
        if service_label_in = 'enterprise' or
           service_label_in = 'management' then
            ents_to_process.extend;
            ents_to_process(ents_to_process.count) := 'sw_mgr_enterprise';

            roles_to_process.extend;
            roles_to_process(roles_to_process.count) := 'org_admin';

            roles_to_process.extend;
            roles_to_process(roles_to_process.count) := 'system_group_admin';

            roles_to_process.extend;
            roles_to_process(roles_to_process.count) := 'activation_key_admin';

            roles_to_process.extend;
            roles_to_process(roles_to_process.count) := 'org_applicant';
        elsif service_label_in = 'provisioning' then
            ents_to_process.extend;
            ents_to_process(ents_to_process.count) := 'rhn_provisioning';

            roles_to_process.extend;
            roles_to_process(roles_to_process.count) := 'system_group_admin';

            roles_to_process.extend;
            roles_to_process(roles_to_process.count) := 'activation_key_admin';

            roles_to_process.extend;
            roles_to_process(roles_to_process.count) := 'config_admin';
            -- another nasty special case...
            if enable_in = 'Y' then
                ents_to_process.extend;
                ents_to_process(ents_to_process.count) := 'sw_mgr_enterprise';
            end if;
        elsif service_label_in = 'monitoring' then
            ents_to_process.extend;
            ents_to_process(ents_to_process.count) := 'rhn_monitor';

            roles_to_process.extend;
            roles_to_process(roles_to_process.count) := 'monitoring_admin';
        elsif service_label_in = 'virtualization' then
            ents_to_process.extend;
            ents_to_process(ents_to_process.count) := 'rhn_virtualization';

            roles_to_process.extend;
            roles_to_process(roles_to_process.count) := 'config_admin';
        elsif service_label_in = 'virtualization_platform' then
            ents_to_process.extend;
            ents_to_process(ents_to_process.count) := 'rhn_virtualization_platform';
            roles_to_process.extend;
            roles_to_process(roles_to_process.count) := 'config_admin';
    elsif service_label_in = 'nonlinux' then
            ents_to_process.extend;
            ents_to_process(ents_to_process.count) := 'rhn_nonlinux';
            roles_to_process.extend;
            roles_to_process(roles_to_process.count) := 'config_admin';
        end if;

        if enable_in = 'Y' then
            for i in 1..ents_to_process.count loop
                for ent in ents(ents_to_process(i)) loop
                    create_row := 'Y';
                    for oe in org_ents(ent.label) loop
                        create_row := 'N';
                    end loop;
                    if create_row = 'Y' then
                        insert into rhnOrgEntitlements(org_id, entitlement_id)
                            values (org_id_in, ent.id);
                    end if;
                end loop;
            end loop;
            for i in 1..roles_to_process.count loop
                for role in roles(roles_to_process(i)) loop
                    create_row := 'Y';
                    for o_r in org_roles(role.label) loop
                        create_row := 'N';
                    end loop;
                    if create_row = 'Y' then
                        insert into rhnUserGroup(
                                id, name, description, current_members,
                                group_type, org_id
                            ) (
                                select    rhn_user_group_id_seq.nextval,
                                        ugt.name || 's',
                                        ugt.name || 's for Org ' ||
                                            o.name || ' ('|| o.id ||')',
                                        0, ugt.id, o.id
                                from    rhnUserGroupType ugt,
                                        web_customer o
                                where    o.id = org_id_in
                                    and ugt.id = role.id
                            );
                    end if;
                end loop;
            end loop;
        else
            for i in 1..ents_to_process.count loop
                for ent in ents(ents_to_process(i)) loop
                    delete from rhnOrgEntitlements
                     where org_id = org_id_in
                       and entitlement_id = ent.id;
                end loop;
            end loop;
        end if;
    end modify_org_service;

    procedure set_customer_enterprise (
        customer_id_in in number
    ) is
    begin
        modify_org_service(customer_id_in, 'enterprise', 'Y');
    end set_customer_enterprise;

    procedure set_customer_provisioning (
        customer_id_in in number
    ) is
    begin
        modify_org_service(customer_id_in, 'provisioning', 'Y');
    end set_customer_provisioning;

    procedure set_customer_monitoring (
        customer_id_in in number
    ) is
    begin
        modify_org_service(customer_id_in, 'monitoring', 'Y');
    end set_customer_monitoring;

    procedure set_customer_nonlinux (
        customer_id_in in number
    ) is
    begin
        modify_org_service(customer_id_in, 'nonlinux', 'Y');
    end set_customer_nonlinux;

    procedure unset_customer_enterprise (
        customer_id_in in number
    ) is
    begin
        modify_org_service(customer_id_in, 'enterprise', 'N');
    end unset_customer_enterprise;

    procedure unset_customer_provisioning (
        customer_id_in in number
    ) is
    begin
        modify_org_service(customer_id_in, 'provisioning', 'N');
    end unset_customer_provisioning;

    procedure unset_customer_monitoring (
        customer_id_in in number
    ) is
    begin
        modify_org_service(customer_id_in, 'monitoring', 'N');
    end unset_customer_monitoring;

    procedure unset_customer_nonlinux (
        customer_id_in in number
    ) is
    begin
        modify_org_service(customer_id_in, 'nonlinux', 'N');
    end unset_customer_nonlinux;

    -- *******************************************************************
    -- PROCEDURE: prune_group
    -- Unsubscribes servers consuming physical slots that over the org's
    --   limit.
    -- Called by: set_group_count, repoll_virt_guest_entitlements
    -- *******************************************************************
    procedure prune_group (
        group_id_in in number,
        type_in in char,
        quantity_in in number,
                update_family_countsYN in number := 1
    ) is
        cursor usergroups is
            select    user_id, user_group_id, ugt.label
            from    rhnUserGroupType    ugt,
                    rhnUserGroup        ug,
                    rhnUserGroupMembers    ugm
            where    1=1
                and ugm.user_group_id = group_id_in
                and ugm.user_id in (
                    select    user_id
                    from    (
                        select    rownum row_number,
                                user_id,
                                time
                        from    (
                            select    user_id,
                                    modified time
                            from    rhnUserGroupMembers
                            where    user_group_id = group_id_in
                            order by time asc
                        )
                    )
                    where    row_number > quantity_in
                )
                and ugm.user_group_id = ug.id
                and ug.group_type = ugt.id;
        cursor servergroups is
           select  server_id, server_group_id, sgt.id as group_type_id, sgt.label
            from    rhnServerGroupType              sgt,
                            rhnServerGroup                  sg,
                            rhnServerGroupMembers   sgm
            where   1=1
                    and sgm.server_group_id = group_id_in
                    and sgm.server_id in (
                            select  server_id
                            from    (
                                    select  rownum row_number,
                                                    server_id,
                                                    time
                                    from    (
                                            select  sep.server_id,
                                                    sep.modified time
                                            from
                                                rhnServerEntitlementPhysical sep
                                            where
                                                sep.server_group_id = group_id_in
                                            order by time asc
                                    )
                            )
                            where   row_number > quantity_in
                    )
                    and sgm.server_group_id = sg.id
                    and sg.group_type = sgt.id;
      type_is_base char;
    begin
        if type_in = 'U' then
            update        rhnUserGroup
                set        max_members = quantity_in
                where    id = group_id_in;

            for ug in usergroups loop
                rhn_user.remove_from_usergroup(ug.user_id, ug.user_group_id);
            end loop;
        elsif type_in = 'S' then
            update        rhnServerGroup
                set        max_members = quantity_in
                where    id = group_id_in;

            for sg in servergroups loop
                remove_server_entitlement(sg.server_id, sg.label);
            
            select is_base 
            into type_is_base
            from rhnServerGroupType sgt
            where sgt.id = sg.group_type_id;
 
            -- if we're removing a base ent, then be sure to
            -- remove the server's channel subscriptions.
            if ( type_is_base = 'Y' ) then
                   rhn_channel.clear_subscriptions(sg.server_id,
                                        update_family_countsYN => update_family_countsYN);
            end if;

            end loop;
        end if;
    end prune_group;

    -- *******************************************************************
    -- PROCEDURE: assign_system_entitlement
    --
    -- Moves system entitlements from from_org_id_in to to_org_id_in.
    -- Can raise not_enough_entitlements_in_base_org if from_org_id_in
    -- does not have enough entitlements to cover the move.
    -- Takes care of unentitling systems if necessary by calling 
    -- set_group_count
    -- *******************************************************************
    procedure assign_system_entitlement(
        group_label_in in varchar2,
        from_org_id_in in number,
        to_org_id_in in number,
        quantity_in in number
    )
    is
        prev_ent_count number;
    to_org_prev_ent_count number;
        new_ent_count number;
    new_quantity number;
        group_type number;
    begin

        begin
            select max_members
            into prev_ent_count
            from rhnServerGroupType sgt,
                 rhnServerGroup sg
            where sg.org_id = from_org_id_in
              and sg.group_type = sgt.id
              and sgt.label = group_label_in;
        exception
            when NO_DATA_FOUND then
                rhn_exception.raise_exception(
                              'not_enough_entitlements_in_base_org');
        end;

        begin
            select max_members
            into to_org_prev_ent_count
            from rhnServerGroupType sgt,
                 rhnServerGroup sg
            where sg.org_id = to_org_id_in
              and sg.group_type = sgt.id
              and sgt.label = group_label_in;
        exception
            when NO_DATA_FOUND then
                to_org_prev_ent_count := 0;
        end;

        begin
            select id
            into group_type
            from rhnServerGroupType
            where label = group_label_in;
        exception
            when NO_DATA_FOUND then
                rhn_exception.raise_exception(
                              'invalid_server_group');
        end;

        new_ent_count := prev_ent_count - quantity_in;

        if prev_ent_count > new_ent_count then
            new_quantity := to_org_prev_ent_count + quantity_in;
        end if;

        if new_ent_count < 0 then
            rhn_exception.raise_exception(
                          'not_enough_entitlements_in_base_org');
        end if;


        rhn_entitlements.set_group_count(from_org_id_in,
                                         'S',
                                         group_type,
                                         new_ent_count);

        rhn_entitlements.set_group_count(to_org_id_in,
                                         'S',
                                         group_type,
                                         new_quantity);
        
        -- Create or delete the entries in rhnOrgEntitlementType
        if group_label_in = 'enterprise_entitled' then 
            if new_quantity > 0 then
                set_customer_enterprise(to_org_id_in);
            else
                unset_customer_enterprise(to_org_id_in);
            end if;
        end if;

        if group_label_in = 'provisioning_entitled' then
            if new_quantity > 0 then
                set_customer_provisioning(to_org_id_in);
            else
                unset_customer_provisioning(to_org_id_in);
            end if;
        end if;

        if group_label_in = 'monitoring_entitled' then
            if new_quantity > 0 then
                set_customer_monitoring(to_org_id_in);
            else
                unset_customer_monitoring(to_org_id_in);
            end if;
        end if;

    end assign_system_entitlement;

    -- *******************************************************************
    -- PROCEDURE: assign_channel_entitlement
    --
    -- Moves channel entitlements from from_org_id_in to to_org_id_in.
    -- Can raise not_enough_entitlements_in_base_org if from_org_id_in
    -- does not have enough entitlements to cover the move.
    -- Takes care of unentitling systems if necessary by calling 
    -- set_family_count
    -- *******************************************************************
    procedure assign_channel_entitlement(
        channel_family_label_in in varchar2,
        from_org_id_in in number,
        to_org_id_in in number,
        quantity_in in number,
        flex_in in number
    )
    is
        from_org_prev_ent_count number;
        from_org_prev_ent_count_flex number;
        new_ent_count number;
        new_ent_count_flex number;
        to_org_prev_ent_count number;
        to_org_prev_ent_count_flex number;
        new_quantity number;
        new_flex number;
        cfam_id       number;
    begin

        begin
            select max_members
            into from_org_prev_ent_count
            from rhnChannelFamily cf,
                 rhnPrivateChannelFamily pcf
            where pcf.org_id = from_org_id_in
              and pcf.channel_family_id = cf.id
              and cf.label = channel_family_label_in;
        exception
            when NO_DATA_FOUND then
                rhn_exception.raise_exception(
                              'not_enough_entitlements_in_base_org');
        end;

        begin
            select max_members
            into to_org_prev_ent_count
            from rhnChannelFamily cf,
                 rhnPrivateChannelFamily pcf
            where pcf.org_id = to_org_id_in
              and pcf.channel_family_id = cf.id
              and cf.label = channel_family_label_in;
        exception
            when NO_DATA_FOUND then
                to_org_prev_ent_count := 0;
        end;

        begin
            select fve_max_members
            into from_org_prev_ent_count_flex
            from rhnChannelFamily cf,
                 rhnPrivateChannelFamily pcf
            where pcf.org_id = from_org_id_in
              and pcf.channel_family_id = cf.id
              and cf.label = channel_family_label_in;
        exception
            when NO_DATA_FOUND then
                rhn_exception.raise_exception(
                              'not_enough_flex_entitlements_in_base_org');
        end;

        begin
            select fve_max_members
            into to_org_prev_ent_count_flex
            from rhnChannelFamily cf,
                 rhnPrivateChannelFamily pcf
            where pcf.org_id = to_org_id_in
              and pcf.channel_family_id = cf.id
              and cf.label = channel_family_label_in;
        exception
            when NO_DATA_FOUND then
                to_org_prev_ent_count_flex := 0;
        end;

        begin
            select id
            into cfam_id
            from rhnChannelFamily
            where label = channel_family_label_in;
        exception
            when NO_DATA_FOUND then
                rhn_exception.raise_exception(
                              'invalid_channel_family');
        end;

        new_ent_count := from_org_prev_ent_count - quantity_in;
        new_ent_count_flex := from_org_prev_ent_count_flex - flex_in;

        if from_org_prev_ent_count >= new_ent_count then
            new_quantity := to_org_prev_ent_count + quantity_in;
       end if;

       if from_org_prev_ent_count_flex >= new_ent_count_flex then
            new_flex := to_org_prev_ent_count_flex + flex_in;
       end if;


        if new_ent_count < 0 then
            rhn_exception.raise_exception(
                          'not_enough_entitlements_in_base_org');
        end if;

        if new_ent_count_flex < 0 then
            rhn_exception.raise_exception(
                          'not_enough_flex_entitlements_in_base_org');
        end if;



        rhn_entitlements.set_family_count(from_org_id_in, cfam_id,
                                           new_ent_count, new_ent_count_flex);

        rhn_entitlements.set_family_count(to_org_id_in,
                                          cfam_id,
                                          new_quantity, new_flex);

    end assign_channel_entitlement;

    -- *******************************************************************
    -- PROCEDURE: activate_system_entitlement
    --
    -- Sets the values in rhnServerGroup for a given rhnServerGroupType.
    -- 
    -- Calls: set_group_count to update, prune, or create the group.
    -- Called by: the code that activates a satellite cert. 
    --
    -- Raises not_enough_entitlements_in_base_org if all entitlements
    -- in the org are used so the free entitlements would not cover
    -- the difference when descreasing the number of entitlements.
    -- *******************************************************************
    procedure activate_system_entitlement(
        org_id_in in number,
        group_label_in in varchar2,
        quantity_in in number
    )
    is
        prev_ent_count number; 
        prev_ent_count_sum number; 
        group_type number;
    begin

        -- Fetch the current entitlement count for the org
        -- into prev_ent_count
        begin
            select current_members
            into prev_ent_count
            from rhnServerGroupType sgt,
                 rhnServerGroup sg
            where sg.group_type = sgt.id
              and sgt.label = group_label_in
              and sg.org_id = org_id_in;
        exception
            when NO_DATA_FOUND then
                prev_ent_count := 0;
        end;

        begin
            select id
            into group_type
            from rhnServerGroupType
            where label = group_label_in;
        exception
            when NO_DATA_FOUND then
                rhn_exception.raise_exception(
                              'invalid_server_group');
        end;

        -- If we're setting the total entitlemnt count to a lower value,
        -- and that value is less than the allocated count in this org,
        -- we need to raise an exception.
        if quantity_in < prev_ent_count then
            rhn_exception.raise_exception(
                          'not_enough_entitlements_in_base_org');
        else
            -- don't update family counts after every server
            -- will do bulk update afterwards
            rhn_entitlements.set_group_count(org_id_in,
                                             'S',
                                             group_type,
                                             quantity_in,
                                             update_family_countsYN => 0);
            -- bulk update family counts
            rhn_channel.update_group_family_counts(group_label_in, org_id_in);
        end if;


    end activate_system_entitlement;

    -- *******************************************************************
    -- PROCEDURE: activate_channel_entitlement
    --
    -- Calls: set_family_count to update, prune, or create the family
    --        permission bucket.
    -- Called by: the code that activates a satellite cert. 
    --
    -- Raises not_enough_entitlements_in_base_org if there are not enough
    -- entitlements in the org to cover the difference when you are
    -- descreasing the number of entitlements.
    --
    -- The backend code in Python is expected to do whatever arithmetics
    -- is needed.
    -- *******************************************************************
    procedure activate_channel_entitlement(
        org_id_in in number,
        channel_family_label_in in varchar2,
        quantity_in in number,
        flex_in in number

    )
    is
        prev_ent_count number; 
        prev_flex_count number;
        prev_ent_count_sum number; 
        cfam_id number;
        reduce_quantity number;
        total_flex_capable number;
        cursor to_convert_reg (channel_family_id_val in number, org_id_in in number, quantity in number) 
                is
                     select SC.server_id
                     from rhnServerChannel SC inner join
                          rhnServer S on S.id = SC.server_id
                     where
                         is_fve = 'Y'
                         and S.org_id = org_id_in 
                         and SC.channel_id in
                         (select cfm.channel_id from rhnChannelFamilyMembers cfm
                             where cfm.CHANNEL_FAMILY_ID = channel_family_id_val)
                          and rownum <= quantity;
         cursor to_convert_flex (channel_family_id_val in number, org_id_in in number, quantity in number)
                 is
                   select server_id
                   from rhnServerFveCapable
                       where SERVER_ORG_ID = org_id_in and
                             channel_family_id = cfam_id;

    begin

        -- Fetch the current entitlement count for the org
        -- into prev_ent_count
        begin
            select current_members
            into prev_ent_count
            from rhnChannelFamily cf,
                 rhnPrivateChannelFamily pcf
            where pcf.org_id = org_id_in
              and pcf.channel_family_id = cf.id
              and cf.label = channel_family_label_in;
        exception
            when NO_DATA_FOUND then
                prev_ent_count := 0;
        end;

        begin
            select pcf.fve_current_members
            into prev_flex_count
            from rhnChannelFamily cf,
                 rhnPrivateChannelFamily pcf
            where pcf.org_id = org_id_in
              and pcf.channel_family_id = cf.id
              and cf.label = channel_family_label_in;
        exception
            when NO_DATA_FOUND then
                prev_flex_count := 0;
        end;


        begin
            select id
            into cfam_id
            from rhnChannelFamily
            where label = channel_family_label_in;
        exception
            when NO_DATA_FOUND then
                rhn_exception.raise_exception(
                              'invalid_channel_family');
        end;                              

        -- if there are too few flex entitlements
        if flex_in < prev_flex_count then
            -- and if the extra we need is less than or equal to our extra regular entitlements
            if prev_flex_count - flex_in <= quantity_in - prev_ent_count then
                   reduce_quantity := prev_flex_count - flex_in;
                   -- We need to convert some systems from flex guest to regular
                   for system in to_convert_reg(cfam_id, org_id_in, reduce_quantity) loop
                      --rhn_channel.convert_to_regular(system.server_id, cfam_id);
                      UPDATE rhnServerChannel sc set sc.is_fve = 'N'
                           where sc.server_id = system.server_id;
                   end loop;

                   --reset previous counts 
                   prev_ent_count := prev_ent_count + reduce_quantity;
                   prev_flex_count := prev_flex_count - reduce_quantity; 
            else
                rhn_exception.raise_exception(
                          'not_enough_flex_entitlements_in_base_org');
            end if;
        end if;

        -- if there are too few regular entitlements, and extra flex entitlements
        if quantity_in < prev_ent_count and prev_flex_count < flex_in then
                -- how many flex-capable systems (that aren't using flex) do we have
                select count(*)
                   into total_flex_capable 
                   from rhnServerFveCapable
                       where SERVER_ORG_ID = org_id_in and
                             channel_family_id = cfam_id;
                -- if we have enough flex capable machines that is at least 
                --   as many as what we are over on 
                if total_flex_capable >= prev_ent_count - quantity_in then
                    reduce_quantity := prev_ent_count - quantity_in;
                    for system in to_convert_flex(cfam_id, org_id_in, reduce_quantity) loop 
--                          rhn_channel.convert_to_fve(system.server_id, cfam_id);
                        UPDATE rhnServerChannel sc set sc.is_fve = 'Y'
                           where sc.server_id = system.server_id;
                    end loop;
                    prev_ent_count := prev_ent_count - reduce_quantity;
                    prev_flex_count := prev_flex_count + reduce_quantity;
                end if; 
        end if;




        -- If we're setting the total entitlemnt count to a lower value,
        -- and that value is less than the count in that one org,
        -- we need to raise an exception.
        if quantity_in < prev_ent_count then
            rhn_exception.raise_exception(
                          'not_enough_entitlements_in_base_org');
        else
            -- even if we've manually converted systems to/from flex above
            -- set_family_count should call update_family_counts, to reset
            -- current used slots
            rhn_entitlements.set_family_count(org_id_in, cfam_id,
                                              quantity_in, flex_in);
        end if;

    end activate_channel_entitlement;


    procedure set_group_count (
        customer_id_in in number,
        type_in in char,
        group_type_in in number,
        quantity_in in number,
                update_family_countsYN in number := 1
    ) is
        group_id number;
        quantity number;
    begin
        quantity := quantity_in;
        if quantity is not null and quantity < 0 then
            quantity := 0;
        end if;

        if type_in = 'U' then
            select    rug.id
            into    group_id
            from    rhnUserGroup rug
            where    1=1
                and rug.org_id = customer_id_in
                and rug.group_type = group_type_in;
        elsif type_in = 'S' then
            select    rsg.id
            into    group_id
            from    rhnServerGroup rsg
            where    1=1
                and rsg.org_id = customer_id_in
                and rsg.group_type = group_type_in;
        end if;

        rhn_entitlements.prune_group(
            group_id,
            type_in,
            quantity,
                        update_family_countsYN
        );
    exception
        when no_data_found then
            if type_in = 'U' then
                insert into rhnUserGroup (
                        id, name, description, max_members, current_members,
                        group_type, org_id, created, modified
                    ) (
                        select    rhn_user_group_id_seq.nextval, name, name,
                                quantity, 0, id, customer_id_in,
                                sysdate, sysdate
                        from    rhnUserGroupType
                        where    id = group_type_in
                );
            elsif type_in = 'S' then
                insert into rhnServerGroup (
                        id, name, description, max_members, current_members,
                        group_type, org_id, created, modified
                    ) (
                        select    rhn_server_group_id_seq.nextval, name, name,
                                quantity, 0, id, customer_id_in,
                                sysdate, sysdate
                        from    rhnServerGroupType
                        where    id = group_type_in
                );
            end if;
    end set_group_count;

    -- *******************************************************************
    -- PROCEDURE: prune_family
    -- Unsubscribes servers consuming physical slots from the channel family 
    --   that are over the org's limit.
    -- Called by: set_family_count
    -- *******************************************************************
    procedure prune_family (
        customer_id_in in number,
        channel_family_id_in in number,
        quantity_in in number,
        flex_in in number
    ) is
       is_fve_in char;
       tmp_quantity number;

        cursor serverchannels is
            select    sc.server_id,
                    sc.channel_id
            from    rhnServerChannel sc,
                    rhnChannelFamilyMembers cfm
            where    1=1
                and cfm.channel_family_id = channel_family_id_in
                and cfm.channel_id = sc.channel_id
                and server_id in (
                    select    server_id
                      from    (
                        select server_id, time, rownum row_number
                        from    (
                            select rs.id  server_id, rcfm.modified time
                            from    rhnServerChannel         rsc,
                                    rhnChannelFamilyMembers  rcfm,
                                    rhnServer                rs
                            where    1=1
                                and rs.org_id = customer_id_in
                                and rs.id = rsc.server_id
                                and rsc.channel_id = rcfm.channel_id
                                and rcfm.channel_family_id =  channel_family_id_in
                                and rsc.is_fve = is_fve_in
                                -- we only want to grab servers consuming
                                -- physical slots.
                                and exists (
                                    select 1
                                    from rhnChannelFamilyServerPhysical cfsp
                                    where cfsp.server_id = rs.id
                                    and cfsp.channel_family_id = 
                                        channel_family_id_in
                                    )
                            order by time asc
                        )
                    )
                    where row_number > tmp_quantity
                );
    begin
        -- if we get a null customer_id, this is completely bogus.
        if customer_id_in is null then
            return;
        end if;

        tmp_quantity := quantity_in;
        is_fve_in := 'N';

        for sc in serverchannels loop
            rhn_channel.unsubscribe_server(sc.server_id, sc.channel_id, 1, 1,
                                                       update_family_countsYN => 0);

        tmp_quantity := flex_in;
        is_fve_in := 'Y';
        for sc in serverchannels loop
            rhn_channel.unsubscribe_server(sc.server_id, sc.channel_id, 1, 1,
                                                        update_family_countsYN => 0);
        end loop;



        end loop;
                rhn_channel.update_family_counts(channel_family_id_in, customer_id_in);
    end prune_family;

    procedure set_family_count (
        customer_id_in in number,
        channel_family_id_in in number,
        quantity_in in number,
        flex_in in number
    ) is
        cursor privperms is
            select    1
            from    rhnPrivateChannelFamily
            where    org_id = customer_id_in
                and channel_family_id = channel_family_id_in;
        cursor pubperms is
            select    o.id org_id
            from    web_customer o,
                    rhnPublicChannelFamily pcf
            where    pcf.channel_family_id = channel_family_id_in;
        quantity number;
        done number := 0;
        flex number;
    begin
        quantity := quantity_in;
        if quantity is not null and quantity < 0 then
            quantity := 0;
        end if;
        flex := flex_in;
        if flex is not null and flex < 0 then
            flex := 0;
        end if;


        if customer_id_in is not null then
            for perm in privperms loop
                rhn_entitlements.prune_family(customer_id_in, channel_family_id_in,
                    quantity, flex);

               update rhnPrivateChannelFamily
                    set max_members = quantity
                    where org_id = customer_id_in
                        and channel_family_id = channel_family_id_in;

               update rhnPrivateChannelFamily
                    set fve_max_members = flex
                    where org_id = customer_id_in
                        and channel_family_id = channel_family_id_in;

                return;
            end loop;

            insert into rhnPrivateChannelFamily (
                    channel_family_id, org_id, max_members, current_members, fve_max_members, fve_current_members
                ) values (
                    channel_family_id_in, customer_id_in, quantity, 0, flex, 0 );
            return;
        end if;

        for perm in pubperms loop
            if quantity = 0 then
                rhn_entitlements.prune_family(
                    perm.org_id,
                    channel_family_id_in,
                    quantity,
                    flex
                );
                if done = 0 then
                    delete from rhnPublicChannelFamily
                        where channel_family_id = channel_family_id_in;
                end if;
            end if;
            done := 1;
        end loop;
        -- if done's not 1, then we don't have any entitlements
        if done != 1 then
            insert into rhnPublicChannelFamily (
                    channel_family_id
                ) values (
                    channel_family_id_in
                );
        end if;
    end set_family_count;

    -- this expects quantity_in to be the number of available slots, not the
    -- max_members of the server group.  If you give it too many, it'll fail
    -- and raise servergroup_max_members.
    -- We should NEVER run this unless we're SURE that we won't
    -- be violating the max.
    procedure entitle_last_modified_servers (
        customer_id_in in number,
        type_label_in in varchar2,
        quantity_in in number
    ) is
        -- find the servers that aren't currently in slots
        cursor servers(cid_in in number, quant_in in number) is
            select    server_id
            from    (
                        select    rownum row_number,
                                server_id
                        from    (
                                    select    rs.id server_iD
                                    from    rhnServer rs
                                    where    1=1
                                        and rs.org_id = cid_in
                                        and not exists (
                                            select    1
                                            from    rhnServerGroup sg,
                                                    rhnServerGroupMembers rsgm
                                            where    rsgm.server_id = rs.id
                                                and rsgm.server_group_id = sg.id
                                                and sg.group_type is not null
                                        )
                                        and not exists (
                                            select 1
                                            from rhnVirtualInstance vi
                                            where vi.virtual_system_id =
                                                  rs.id
                                        )                                                                           order by modified desc
                                )
                    )
            where    row_number <= quant_in;
    begin
        for server in servers(customer_id_in, quantity_in) loop
            rhn_entitlements.entitle_server(server.server_id, type_label_in);
        end loop;
    end entitle_last_modified_servers;

    procedure subscribe_newest_servers (
        customer_id_in in number
    ) is
        -- find servers without base channels
        cursor servers(cid_in in number) is
            select    s.id
            from    rhnServer            s
            where    1=1
                and s.org_id = cid_in
                and not exists (
                        select 1
                        from    rhnChannel            c,
                                rhnServerChannel    sc
                        where    sc.server_id = s.id
                            and sc.channel_id = c.id
                            and c.parent_channel is null
                    )
                and not exists (
                        select 1
                        from rhnVirtualInstance vi
                        where vi.virtual_system_id = s.id
                    )                        
            order by s.modified desc;
        channel_id number;
    begin
        for server in servers(customer_id_in) loop
            channel_id := rhn_channel.guess_server_base(server.id);
            if channel_id is not null then
                begin
                    rhn_channel.subscribe_server(server.id, channel_id);
                    commit;
                -- exception is really channel_family_no_subscriptions
                exception
                    when others then
                        null;
                end;
            end if;
        end loop;
    end subscribe_newest_servers;
end rhn_entitlements;
/
show errors

07070100000417000081B400000000000000000000000167AE1114000003E7000000000000000000000000000000000000005E00000000susemanager-schema/upgrade/satellite-schema-5.4-to-spacewalk-schema-1.2/093-rhn_exception.sql --
-- Copyright (c) 2008--2010 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--

CREATE OR REPLACE
PACKAGE rhn_exception
IS
    PROCEDURE raise_exception(exception_label_in IN VARCHAR2);
    procedure raise_exception_val(
	exception_label_in in varchar2,
        val_in in number
    );
    PROCEDURE lookup_exception(exception_label_in IN VARCHAR2, exception_id_out OUT NUMBER, exception_message_out OUT VARCHAR2);
END rhn_exception;
/
SHOW ERRORS

 07070100000418000081B400000000000000000000000167AE111400000941000000000000000000000000000000000000006300000000susemanager-schema/upgrade/satellite-schema-5.4-to-spacewalk-schema-1.2/094-rhn_exception-body.sql    --
-- Copyright (c) 2008--2010 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--

CREATE OR REPLACE
PACKAGE BODY rhn_exception
IS

    PROCEDURE lookup_exception(exception_label_in IN VARCHAR2, exception_id_out OUT NUMBER, exception_message_out OUT VARCHAR2)
    IS
        return_string     VARCHAR2(2000);
    BEGIN
        FOR exc IN (
            SELECT id, label, message
              FROM rhnException
             WHERE label = exception_label_in
        )
        LOOP
            exception_id_out := exc.id;
            exception_message_out := '(' || exc.label || ')' || ' - ' || exc.message;
        END LOOP exception_details;

        IF exception_message_out IS NULL
        THEN
            RAISE NO_DATA_FOUND;
        END IF;

    END lookup_exception;
    
    PROCEDURE raise_exception(exception_label_in IN VARCHAR2)
    IS
        exception_id        NUMBER;
        exception_message   VARCHAR2(2000);
    BEGIN
        lookup_exception(exception_label_in, exception_id, exception_message);
        RAISE_APPLICATION_ERROR(exception_id, exception_message);    
    EXCEPTION
        WHEN NO_DATA_FOUND
        THEN
        RAISE_APPLICATION_ERROR(-20001, 'Unable to lookup exception with label (' || exception_label_in || ')');    
    END raise_exception;

    procedure raise_exception_val(
	exception_label_in in varchar2,
	val_in in number
    ) is
	exception_id        NUMBER;
	exception_message   VARCHAR2(2000);
    begin
	lookup_exception(exception_label_in, exception_id, exception_message);
	RAISE_APPLICATION_ERROR(exception_id, exception_message || ' (' || val_in || ')');
    exception
	when no_data_found then
	RAISE_APPLICATION_ERROR(-20001, 'Unable to lookup exception with label (' || exception_label_in || ')');
    end raise_exception_val;
    
END rhn_exception;
/
SHOW ERRORS

   07070100000419000081B400000000000000000000000167AE1114000002ED000000000000000000000000000000000000006F00000000susemanager-schema/upgrade/satellite-schema-5.4-to-spacewalk-schema-1.2/100-rhnActionType-proxy.deactivate.sql    --
-- Copyright (c) 2010 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--

update rhnActionType set name = 'Deactivate Proxy' where label = 'proxy.deactivate' and name <> 'Deactivate Proxy';
commit;

   0707010000041A000081B400000000000000000000000167AE111400001010000000000000000000000000000000000000007000000000susemanager-schema/upgrade/satellite-schema-5.4-to-spacewalk-schema-1.2/103-rhnPackageChangeLog-refactoring.sql   --
-- Copyright (c) 2010 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnPackageChangeLogData
(
    id          NUMBER NOT NULL
                    CONSTRAINT rhn_pkg_cld_id_pk PRIMARY KEY
                    USING INDEX TABLESPACE [[64k_tbs]],
    name        VARCHAR2(128) NOT NULL,
    text        VARCHAR2(3000) NOT NULL,
    time        DATE NOT NULL,
    created     DATE
                    DEFAULT (sysdate) NOT NULL
)
ENABLE ROW MOVEMENT
;

CREATE INDEX rhn_pkg_cld_nt_idx
    ON rhnPackageChangeLogData (name, time)
    NOLOGGING
    TABLESPACE [[32m_tbs]];

CREATE SEQUENCE rhn_pkg_cld_id_seq;

CREATE TABLE rhnPackageChangeLogRec
(
    id          NUMBER NOT NULL
                    CONSTRAINT rhn_pkg_clr_id_pk PRIMARY KEY
                    USING INDEX TABLESPACE [[64k_tbs]],
    package_id  NUMBER NOT NULL
                    CONSTRAINT rhn_pkg_clr_pid_fk
                        REFERENCES rhnPackage (id)
                        ON DELETE CASCADE,
    changelog_data_id  NUMBER NOT NULL
                    CONSTRAINT rhn_pkg_clr_cld_fk
                        REFERENCES rhnPackageChangeLogData (id),
    created     DATE
                    DEFAULT (sysdate) NOT NULL,
    modified    DATE
                    DEFAULT (sysdate) NOT NULL
)
ENABLE ROW MOVEMENT
;

CREATE UNIQUE INDEX rhn_pkg_clr_pid_cld_uq
    ON rhnPackageChangeLogRec (package_id, changelog_data_id)
    NOLOGGING
    TABLESPACE [[32m_tbs]];

CREATE INDEX rhn_pkg_clr_cld_uq
    ON rhnPackageChangeLogRec (changelog_data_id)
    NOLOGGING
    TABLESPACE [[32m_tbs]];

-- Split rhnPackageChangelog data into the two tables.

insert /*+append*/ into rhnPackageChangeLogData (id, name, text, time, created)
select min(id), name, text, time, min(created)
from rhnPackageChangelog
group by name, text, time;

commit;

declare
	max_id integer;
	i integer;
begin
	select max(id), min(id) into max_id, i from rhnPackageChangeLog;
	while i < max_id loop
		insert /*+append*/ into rhnPackageChangelogRec (id, package_id, changelog_data_id, created, modified)
		select rhnPackageChangeLog.id, rhnPackageChangeLog.package_id, rhnPackageChangeLogData.id, rhnPackageChangeLog.created, rhnPackageChangeLog.created
		from rhnPackageChangeLog, rhnPackageChangeLogData
		where rhnPackageChangeLog.name = rhnPackageChangeLogData.name
			and rhnPackageChangeLog.text = rhnPackageChangeLogData.text
			and rhnPackageChangeLog.time = rhnPackageChangeLogData.time
			and rhnPackageChangeLog.id >= i
			and rhnPackageChangeLog.id < i + 10000;
		commit;
		i := i + 10000;
	end loop;
end;
/

drop table rhnPackageChangelog;

-- Bump up the nextval of rhn_pkg_cld_id_seq to be above
-- the current max valu in rhnPackageChangeLogData.
begin
	for rec in (
		select id - rhn_pkg_cld_id_seq.nextval id from ( select nvl(max(id), 0) id from rhnPackageChangeLogData )
		) loop
		execute immediate 'alter sequence rhn_pkg_cld_id_seq increment by ' || greatest(rec.id, 1);
	end loop;
	for rec in (
		select rhn_pkg_cld_id_seq.nextval from dual
		) loop
		null;
	end loop;
	execute immediate 'alter sequence rhn_pkg_cld_id_seq increment by 1';
end;
/


create view rhnPackageChangeLog
as
select rhnPackageChangeLogRec.id,
	rhnPackageChangeLogRec.package_id,
	rhnPackageChangeLogRec.changelog_data_id,
	rhnPackageChangeLogData.name,
	rhnPackageChangeLogData.text,
	rhnPackageChangeLogData.time,
	rhnPackageChangeLogRec.created,
	rhnPackageChangeLogRec.modified
from rhnPackageChangeLogRec, rhnPackageChangeLogData
where rhnPackageChangeLogRec.changelog_data_id = rhnPackageChangeLogData.id;

0707010000041B000081B400000000000000000000000167AE111400000326000000000000000000000000000000000000006F00000000susemanager-schema/upgrade/satellite-schema-5.4-to-spacewalk-schema-1.2/104-rhnPackageChangeLogRec-trigger.sql    --
-- Copyright (c) 2008--2010 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

create or replace trigger
rhn_package_clog_rec_mod_trig
before insert or update on rhnPackageChangeLogRec
for each row
begin
        :new.modified := sysdate;
end;
/
show errors
  0707010000041C000081B400000000000000000000000167AE111400000437000000000000000000000000000000000000006200000000susemanager-schema/upgrade/satellite-schema-5.4-to-spacewalk-schema-1.2/105-date_diff_in_days.sql --
-- Copyright (c) 2008--2010 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--
--
-- Diffs two dates (date2 - date1) and returns number of dates in the result.
-- Can return fraction digits if dates has different time.
-- Basically this is equivalent of (date2 - date1) but we need to use this
-- function instead of the minus operator because of PostgreSQL compatibility.
--

create or replace function date_diff_in_days(ts1 in date, ts2 in date)
return number is
begin
    return ts2 - ts1;
end date_diff_in_days;
/
show errors

 0707010000041D000081B400000000000000000000000167AE111400000129000000000000000000000000000000000000006F00000000susemanager-schema/upgrade/satellite-schema-5.4-to-spacewalk-schema-1.2/200-rhnActionConfigChannel-indexes.sql    CREATE INDEX rhn_actioncc_sid_idx
    ON rhnActionConfigChannel (server_id)
    TABLESPACE [[4m_tbs]];

CREATE INDEX rhn_act_cc_ccid_idx
    ON rhnActionConfigChannel (config_channel_id)
    TABLESPACE [[4m_tbs]];

DROP INDEX rhn_actioncc_sid_aid_ccid_idx;
DROP INDEX rhn_act_cc_ccid_aid_sid_idx;
   0707010000041E000081B400000000000000000000000167AE111400000093000000000000000000000000000000000000007000000000susemanager-schema/upgrade/satellite-schema-5.4-to-spacewalk-schema-1.2/201-rhnActionConfigFileName-indexes.sql   CREATE INDEX rhn_actioncf_name_sid_idx
    ON rhnActionConfigFileName (server_id)
    TABLESPACE [[2m_tbs]];

DROP INDEX rhn_actioncf_name_sac_uq;
 0707010000041F000081B400000000000000000000000167AE11140000008E000000000000000000000000000000000000007000000000susemanager-schema/upgrade/satellite-schema-5.4-to-spacewalk-schema-1.2/202-rhnActionConfigRevision-indexes.sql   CREATE INDEX rhn_actioncr_sid_idx
    ON rhnActionConfigRevision (server_id)
    TABLESPACE [[2m_tbs]];

DROP INDEX rhn_actioncr_sid_aid_idx;
  07070100000420000081B400000000000000000000000167AE111400000088000000000000000000000000000000000000006E00000000susemanager-schema/upgrade/satellite-schema-5.4-to-spacewalk-schema-1.2/203-rhnActionErrataUpdate-indexes.sql CREATE INDEX rhn_act_eu_eid_idx
    ON rhnActionErrataUpdate (errata_id)
    TABLESPACE [[8m_tbs]];

DROP INDEX rhn_act_eu_eid_aid_idx;
07070100000421000081B400000000000000000000000167AE111400000025000000000000000000000000000000000000006300000000susemanager-schema/upgrade/satellite-schema-5.4-to-spacewalk-schema-1.2/204-rhnChannel-indexes.sql    
drop index rhn_channel_url_id_idx;

   07070100000422000081B400000000000000000000000167AE11140000002D000000000000000000000000000000000000006900000000susemanager-schema/upgrade/satellite-schema-5.4-to-spacewalk-schema-1.2/205-rhnChannelCloned-indexes.sql  
drop index rhn_channelclone_tcid_fcid_idx;

   07070100000423000081B400000000000000000000000167AE11140000001F000000000000000000000000000000000000007000000000susemanager-schema/upgrade/satellite-schema-5.4-to-spacewalk-schema-1.2/206-rhnChannelFamilyMembers-indexes.sql   
drop index rhn_cf_member_uq;

 07070100000424000081B400000000000000000000000167AE111400000020000000000000000000000000000000000000006D00000000susemanager-schema/upgrade/satellite-schema-5.4-to-spacewalk-schema-1.2/207-rhnContentSourceType-indexes.sql  
drop index rhn_ccst_id_l_idx;

07070100000425000081B400000000000000000000000167AE11140000002C000000000000000000000000000000000000006800000000susemanager-schema/upgrade/satellite-schema-5.4-to-spacewalk-schema-1.2/208-rhnErrataCloned-indexes.sql   
drop index rhn_errataclone_teid_feid_idx;

07070100000426000081B400000000000000000000000167AE11140000002B000000000000000000000000000000000000006B00000000susemanager-schema/upgrade/satellite-schema-5.4-to-spacewalk-schema-1.2/209-rhnErrataClonedTmp-indexes.sql    
drop index rhn_eclonedtmp_teid_feid_idx;

 07070100000427000081B400000000000000000000000167AE11140000004B000000000000000000000000000000000000006300000000susemanager-schema/upgrade/satellite-schema-5.4-to-spacewalk-schema-1.2/210-rhnPackage-indexes.sql    
drop index rhn_package_id_nid_paid_idx;
drop index rhn_package_path_idx;

 07070100000428000081B400000000000000000000000167AE111400000021000000000000000000000000000000000000006C00000000susemanager-schema/upgrade/satellite-schema-5.4-to-spacewalk-schema-1.2/211-rhnRegTokenPackages-indexes.sql   
drop index rhn_reg_tok_pkg_uq;

   07070100000429000081B400000000000000000000000167AE111400000025000000000000000000000000000000000000006700000000susemanager-schema/upgrade/satellite-schema-5.4-to-spacewalk-schema-1.2/212-rhnServerGroup-indexes.sql    
drop index rhn_sg_id_oid_name_idx;

   0707010000042A000081B400000000000000000000000167AE111400000029000000000000000000000000000000000000006D00000000susemanager-schema/upgrade/satellite-schema-5.4-to-spacewalk-schema-1.2/213-rhnServerInstallInfo-indexes.sql  
drop index rhn_s_inst_info_sid_im_idx;

   0707010000042B000081B400000000000000000000000167AE111400000021000000000000000000000000000000000000006500000000susemanager-schema/upgrade/satellite-schema-5.4-to-spacewalk-schema-1.2/214-rhnUserGroup-indexes.sql  
drop index rhn_ug_id_name_org;

   0707010000042C000081B400000000000000000000000167AE11140000002A000000000000000000000000000000000000006700000000susemanager-schema/upgrade/satellite-schema-5.4-to-spacewalk-schema-1.2/215-rhnVersionInfo-indexes.sql    
drop index rhn_vinfo_label_eid_nid_idx;

  0707010000042D000081B400000000000000000000000167AE111400000029000000000000000000000000000000000000006800000000susemanager-schema/upgrade/satellite-schema-5.4-to-spacewalk-schema-1.2/216-rhn_check_probe-indexes.sql   
drop index rhn_chkpb_pid_ptype_uq_idx;

   0707010000042E000081B400000000000000000000000167AE11140000007D000000000000000000000000000000000000006E00000000susemanager-schema/upgrade/satellite-schema-5.4-to-spacewalk-schema-1.2/217-rhn_command_parameter-indexes.sql 
alter table rhn_command_parameter drop constraint rhn_cparm_id_p_name_p_type_uq;
drop index rhn_cparm_id_p_name_p_type_uq;

   0707010000042F000081B400000000000000000000000167AE111400000076000000000000000000000000000000000000006B00000000susemanager-schema/upgrade/satellite-schema-5.4-to-spacewalk-schema-1.2/218-rhn_deployed_probe-indexes.sql    
alter table rhn_deployed_probe drop constraint dprob_recid_probe_type_uq;
drop index rhn_dprob_recid_probe_type_uq;

  07070100000430000081B400000000000000000000000167AE111400000027000000000000000000000000000000000000006700000000susemanager-schema/upgrade/satellite-schema-5.4-to-spacewalk-schema-1.2/219-rhn_host_probe-indexes.sql    
drop index rhn_hstpb_pbid_ptype_idx;

 07070100000431000081B400000000000000000000000167AE111400000026000000000000000000000000000000000000006E00000000susemanager-schema/upgrade/satellite-schema-5.4-to-spacewalk-schema-1.2/220-rhn_sat_cluster_probe-indexes.sql 
drop index rhn_sclpb_pid_ptype_idx;

  07070100000432000081B400000000000000000000000167AE111400000026000000000000000000000000000000000000006B00000000susemanager-schema/upgrade/satellite-schema-5.4-to-spacewalk-schema-1.2/221-rhn_sat_node_probe-indexes.sql    
drop index rhn_sndpb_pid_ptype_idx;

  07070100000433000081B400000000000000000000000167AE11140000002A000000000000000000000000000000000000006600000000susemanager-schema/upgrade/satellite-schema-5.4-to-spacewalk-schema-1.2/222-rhn_url_probe-indexes.sql 
drop index rhn_url_probe_pid_ptype_idx;

  07070100000434000081B400000000000000000000000167AE11140000002A000000000000000000000000000000000000006400000000susemanager-schema/upgrade/satellite-schema-5.4-to-spacewalk-schema-1.2/223-web_contact-indexes.sql   
drop index web_contact_id_oid_cust_luc;

  07070100000435000081B400000000000000000000000167AE111400000433000000000000000000000000000000000000006700000000susemanager-schema/upgrade/satellite-schema-5.4-to-spacewalk-schema-1.2/224-rhnChannelArch-indexes.sql    alter table rhnChannel disable constraint rhn_channel_caid_fk;
alter table rhnChannelPackageArchCompat disable constraint rhn_cp_ac_caid_fk;
alter table rhnDistChannelMap disable constraint rhn_dcm_caid_fk;
alter table rhnReleaseChannelMap disable constraint rhn_rcm_caid_fk;
alter table rhnServerChannelArchCompat disable constraint rhn_sc_ac_caid_fk;
alter table rhnChannelArch disable constraint rhn_carch_id_pk;
drop index rhn_carch_id_l_n_idx;
alter table rhnChannelArch enable constraint rhn_carch_id_pk;
alter table rhnChannel enable constraint rhn_channel_caid_fk;
alter table rhnChannelPackageArchCompat enable constraint rhn_cp_ac_caid_fk;
alter table rhnDistChannelMap enable constraint rhn_dcm_caid_fk;
alter table rhnReleaseChannelMap enable constraint rhn_rcm_caid_fk;
alter table rhnServerChannelArchCompat enable constraint rhn_sc_ac_caid_fk;

alter table rhnChannelArch drop CONSTRAINT rhn_carch_label_uq;
drop index rhn_carch_l_id_n_idx;
ALTER TABLE rhnChannelArch
    ADD CONSTRAINT rhn_carch_label_uq UNIQUE (label)
    USING INDEX TABLESPACE [[2m_tbs]];
 07070100000436000081B400000000000000000000000167AE11140000001F000000000000000000000000000000000000006C00000000susemanager-schema/upgrade/satellite-schema-5.4-to-spacewalk-schema-1.2/225-rhnChannelDownloads-indexes.sql   drop index rhn_cd_did_cid_idx;
 07070100000437000081B400000000000000000000000167AE11140000007C000000000000000000000000000000000000006900000000susemanager-schema/upgrade/satellite-schema-5.4-to-spacewalk-schema-1.2/226-rhnChannelErrata-indexes.sql  CREATE INDEX rhn_ce_eid_idx
    ON rhnChannelErrata (errata_id)
    TABLESPACE [[64k_tbs]];

DROP INDEX rhn_ce_eid_cid_idx;
07070100000438000081B400000000000000000000000167AE11140000009B000000000000000000000000000000000000007500000000susemanager-schema/upgrade/satellite-schema-5.4-to-spacewalk-schema-1.2/227-rhnChannelFamilyVirtSubLevel-indexes.sql  CREATE INDEX rhn_cfvsl_vslid_idx
    ON rhnChannelFamilyVirtSubLevel (virt_sub_level_id)
    TABLESPACE [[64k_tbs]];

DROP INDEX rhn_cfvsl_vslid_cfid_idx;
 07070100000439000081B400000000000000000000000167AE1114000000D1000000000000000000000000000000000000007000000000susemanager-schema/upgrade/satellite-schema-5.4-to-spacewalk-schema-1.2/228-rhnChannelNewestPackage-indexes.sql   alter table rhnChannelNewestPackage disable constraint rhn_cnp_cid_nid_uq;
drop index rhn_cnp_cnep_idx;
alter table rhnChannelNewestPackage enable constraint rhn_cnp_cid_nid_uq;

drop index rhn_cnp_necp_idx;

   0707010000043A000081B400000000000000000000000167AE111400000087000000000000000000000000000000000000006A00000000susemanager-schema/upgrade/satellite-schema-5.4-to-spacewalk-schema-1.2/229-rhnChannelPackage-indexes.sql CREATE INDEX rhn_cp_pid_idx
    ON rhnChannelPackage (package_id)
    TABLESPACE [[64k_tbs]]
    NOLOGGING;

DROP INDEX rhn_cp_pc_idx;
 0707010000043B000081B400000000000000000000000167AE111400000020000000000000000000000000000000000000007400000000susemanager-schema/upgrade/satellite-schema-5.4-to-spacewalk-schema-1.2/230-rhnChannelPackageArchCompat-indexes.sql   drop index rhn_cp_ac_paid_caid;
0707010000043C000081B400000000000000000000000167AE1114000000D7000000000000000000000000000000000000006300000000susemanager-schema/upgrade/satellite-schema-5.4-to-spacewalk-schema-1.2/231-rhnCpuArch-indexes.sql    ALTER TABLE rhnCpuArch DROP CONSTRAINT rhn_cpuarch_label_uq;
DROP INDEX rhn_cpuarch_l_id_n_idx;

ALTER TABLE rhnCpuArch
    ADD CONSTRAINT rhn_cpuarch_label_uq UNIQUE (label)
    USING INDEX TABLESPACE [[2m_tbs]];

 0707010000043D000081B400000000000000000000000167AE111400000080000000000000000000000000000000000000006E00000000susemanager-schema/upgrade/satellite-schema-5.4-to-spacewalk-schema-1.2/232-rhnCryptoKeyKickstart-indexes.sql CREATE INDEX rhn_ckey_ks_idx
    ON rhnCryptoKeyKickstart (ksdata_id)
    TABLESPACE [[4m_tbs]];

DROP INDEX rhn_ckey_ks__ckuq;
0707010000043E000081B400000000000000000000000167AE111400000023000000000000000000000000000000000000006800000000susemanager-schema/upgrade/satellite-schema-5.4-to-spacewalk-schema-1.2/233-rhnEmailAddress-indexes.sql   drop index rhn_eaddress_niusa_idx;
 0707010000043F000081B400000000000000000000000167AE1114000000EE000000000000000000000000000000000000006D00000000susemanager-schema/upgrade/satellite-schema-5.4-to-spacewalk-schema-1.2/234-rhnEmailAddressState-indexes.sql  ALTER TABLE rhnEmailAddressState DROP CONSTRAINT rhn_eastate_label_uq;
DROP INDEX rhn_eastate_label_id_idx;

ALTER TABLE rhnEmailAddressState
    ADD CONSTRAINT rhn_eastate_label_uq UNIQUE (label)
    USING INDEX TABLESPACE [[64k_tbs]];

  07070100000440000081B400000000000000000000000167AE11140000008D000000000000000000000000000000000000006500000000susemanager-schema/upgrade/satellite-schema-5.4-to-spacewalk-schema-1.2/235-rhnErrataCVE-indexes.sql  CREATE INDEX rhn_err_cve_cid_idx
    ON rhnErrataCVE (cve_id)
    TABLESPACE [[64k_tbs]]
    NOLOGGING;

DROP INDEX rhn_err_cve_cid_eid_idx;
   07070100000441000081B400000000000000000000000167AE11140000008A000000000000000000000000000000000000006D00000000susemanager-schema/upgrade/satellite-schema-5.4-to-spacewalk-schema-1.2/236-rhnErrataFileChannel-indexes.sql  CREATE INDEX rhn_efilec_cid_idx
    ON rhnErrataFileChannel (channel_id)
    TABLESPACE [[64k_tbs]];

DROP INDEX rhn_efilec_cid_efid_idx;
  07070100000442000081B400000000000000000000000167AE111400000093000000000000000000000000000000000000007000000000susemanager-schema/upgrade/satellite-schema-5.4-to-spacewalk-schema-1.2/237-rhnErrataFileChannelTmp-indexes.sql   CREATE INDEX rhn_efilectmp_cid_idx
    ON rhnErrataFileChannelTmp (channel_id)
    TABLESPACE [[64k_tbs]];

DROP INDEX rhn_efilectmp_cid_efid_idx;
 07070100000443000081B400000000000000000000000167AE1114000000EA000000000000000000000000000000000000006700000000susemanager-schema/upgrade/satellite-schema-5.4-to-spacewalk-schema-1.2/238-rhnChannelComps-unique.sql    
delete from rhnChannelComps
where id not in (
	select max(id)
	from rhnChannelComps
	group by channel_id
);

alter table rhnChannelComps
	add constraint rhn_channelcomps_cid_uq unique(channel_id)
	using index tablespace [[2m_tbs]];

  07070100000444000081B400000000000000000000000167AE111400000155000000000000000000000000000000000000007300000000susemanager-schema/upgrade/satellite-schema-5.4-to-spacewalk-schema-1.2/239-rhnErrataNotificationQueue-indexes.sql    ALTER TABLE rhnErrataNotificationQueue
    disable CONSTRAINT rhn_enqueue_eoid_uq;
drop index rhn_enqueue_eid_idx;
ALTER TABLE rhnErrataNotificationQueue
    enable CONSTRAINT rhn_enqueue_eoid_uq;

CREATE INDEX rhn_enqueue_na_idx
    ON rhnErrataNotificationQueue (next_action)
     TABLESPACE [[8m_tbs]];
drop index rhn_enqueue_na_eid_idx;
   07070100000445000081B400000000000000000000000167AE111400000094000000000000000000000000000000000000006900000000susemanager-schema/upgrade/satellite-schema-5.4-to-spacewalk-schema-1.2/240-rhnErrataPackage-indexes.sql  CREATE INDEX rhn_err_pkg_pid_idx
    ON rhnErrataPackage (package_id)
    TABLESPACE [[64k_tbs]]
    NOLOGGING;
drop index rhn_err_pkg_pid_eid_idx;
07070100000446000081B400000000000000000000000167AE11140000009D000000000000000000000000000000000000006C00000000susemanager-schema/upgrade/satellite-schema-5.4-to-spacewalk-schema-1.2/241-rhnErrataPackageTmp-indexes.sql   CREATE INDEX rhn_err_pkgtmp_pid_idx
    ON rhnErrataPackageTmp (package_id)
    TABLESPACE [[64k_tbs]]
    NOLOGGING;
drop index rhn_err_pkgtmp_pid_eid_idx;
   07070100000447000081B400000000000000000000000167AE1114000000A0000000000000000000000000000000000000007500000000susemanager-schema/upgrade/satellite-schema-5.4-to-spacewalk-schema-1.2/242-rhnKickstartPreserveFileList-indexes.sql  CREATE INDEX rhn_kspreservefl_flid_idx
    ON rhnKickstartPreserveFileList (file_list_id)
    TABLESPACE [[8m_tbs]];
drop index rhn_kspreservefl_flid_ksid_idx;
07070100000448000081B400000000000000000000000167AE1114000000AC000000000000000000000000000000000000006700000000susemanager-schema/upgrade/satellite-schema-5.4-to-spacewalk-schema-1.2/243-rhnPackageArch-indexes.sql    ALTER TABLE rhnPackageArch
    disable CONSTRAINT rhn_parch_label_uq;
drop index rhn_parch_l_id_n_idx;
ALTER TABLE rhnPackageArch
    enable CONSTRAINT rhn_parch_label_uq;
07070100000449000081B400000000000000000000000167AE11140000009F000000000000000000000000000000000000006700000000susemanager-schema/upgrade/satellite-schema-5.4-to-spacewalk-schema-1.2/244-rhnPackageFile-indexes.sql    CREATE INDEX rhn_package_file_cid_idx
    ON rhnPackageFile (capability_id)
    TABLESPACE [[32m_tbs]]
    NOLOGGING;
drop index rhn_package_file_cid_pid_idx;
 0707010000044A000081B400000000000000000000000167AE1114000000A1000000000000000000000000000000000000007000000000susemanager-schema/upgrade/satellite-schema-5.4-to-spacewalk-schema-1.2/245-rhnPrivateChannelFamily-indexes.sql   CREATE INDEX rhn_cfperm_cfid_idx
    ON rhnPrivateChannelFamily (channel_family_id)
    TABLESPACE [[2m_tbs]]
    NOLOGGING;
drop index rhn_cfperm_cfid_oid_idx;
   0707010000044B000081B400000000000000000000000167AE11140000008E000000000000000000000000000000000000006E00000000susemanager-schema/upgrade/satellite-schema-5.4-to-spacewalk-schema-1.2/246-rhnSGTypeVirtSubLevel-indexes.sql CREATE INDEX rhn_sgtvsl_vslid
    ON rhnSGTypeVirtSubLevel (virt_sub_level_id)
    TABLESPACE [[64k_tbs]];
drop index rhn_sgtvsl_vslid_sgtid;
  0707010000044C000081B400000000000000000000000167AE111400000093000000000000000000000000000000000000006800000000susemanager-schema/upgrade/satellite-schema-5.4-to-spacewalk-schema-1.2/248-rhnServerAction-indexes.sql   CREATE INDEX rhn_ser_act_aid_idx
    ON rhnServerAction (action_id)
    TABLESPACE [[8m_tbs]]
    NOLOGGING;
drop index rhn_ser_act_aid_sid_s_idx;
 0707010000044D000081B400000000000000000000000167AE1114000000AA000000000000000000000000000000000000006600000000susemanager-schema/upgrade/satellite-schema-5.4-to-spacewalk-schema-1.2/249-rhnServerArch-indexes.sql ALTER TABLE rhnServerArch
    disable CONSTRAINT rhn_sarch_label_uq;
drop index rhn_sarch_l_id_n_idx;
ALTER TABLE rhnServerArch
    enable CONSTRAINT rhn_sarch_label_uq;
  0707010000044E000081B400000000000000000000000167AE111400000089000000000000000000000000000000000000006900000000susemanager-schema/upgrade/satellite-schema-5.4-to-spacewalk-schema-1.2/250-rhnServerChannel-indexes.sql  CREATE INDEX rhn_sc_cid_idx
    ON rhnServerChannel (channel_id)
    TABLESPACE [[8m_tbs]]
    NOLOGGING;
drop index rhn_sc_cid_sid_idx;
   0707010000044F000081B400000000000000000000000167AE11140000008C000000000000000000000000000000000000007300000000susemanager-schema/upgrade/satellite-schema-5.4-to-spacewalk-schema-1.2/251-rhnServerChannelArchCompat-indexes.sql    CREATE INDEX rhn_sc_ac_caid
    ON rhnServerChannelArchCompat (channel_arch_id)
    TABLESPACE [[64k_tbs]];
drop index rhn_sc_ac_paid_caid;
07070100000450000081B400000000000000000000000167AE111400000069000000000000000000000000000000000000007100000000susemanager-schema/upgrade/satellite-schema-5.4-to-spacewalk-schema-1.2/252-rhnServerCustomDataValue-indexes.sql  CREATE INDEX rhn_scdv_kid_idx
    ON rhnServerCustomDataValue (key_id);
drop index rhn_scdv_kid_sid_idx;
   07070100000451000081B400000000000000000000000167AE111400000046000000000000000000000000000000000000006700000000susemanager-schema/upgrade/satellite-schema-5.4-to-spacewalk-schema-1.2/253-rhnServerGroup-indexes.sql    drop index rhn_sg_oid_id_name_idx;
drop index rhn_sg_oid_type_id_idx;
  07070100000452000081B400000000000000000000000167AE1114000000A3000000000000000000000000000000000000006E00000000susemanager-schema/upgrade/satellite-schema-5.4-to-spacewalk-schema-1.2/254-rhnServerGroupMembers-indexes.sql CREATE INDEX rhn_sgmembers_sgid_idx
    ON rhnServerGroupMembers (server_group_id)
    TABLESPACE [[4m_tbs]]
    NOLOGGING;
drop index rhn_sgmembers_sgid_sid_idx;
 07070100000453000081B400000000000000000000000167AE11140000001C000000000000000000000000000000000000006D00000000susemanager-schema/upgrade/satellite-schema-5.4-to-spacewalk-schema-1.2/255-rhnServerNeededCache-indexes.sql  drop index rhn_snc_sid_idx;
07070100000454000081B400000000000000000000000167AE111400000096000000000000000000000000000000000000007300000000susemanager-schema/upgrade/satellite-schema-5.4-to-spacewalk-schema-1.2/256-rhnServerPackageArchCompat-indexes.sql    CREATE INDEX rhn_sp_ac_paid_pref
    ON rhnServerPackageArchCompat (package_arch_id)
    TABLESPACE [[64k_tbs]];
drop index rhn_sp_ac_paid_said_pref;
  07070100000455000081B400000000000000000000000167AE111400000097000000000000000000000000000000000000007200000000susemanager-schema/upgrade/satellite-schema-5.4-to-spacewalk-schema-1.2/257-rhnServerPreserveFileList-indexes.sql CREATE INDEX rhn_serverpfl_flid_idx
    ON rhnServerPreserveFileList (file_list_id)
    TABLESPACE [[4m_tbs]];
drop index rhn_serverpfl_flid_ksid_idx;
 07070100000456000081B400000000000000000000000167AE1114000000A8000000000000000000000000000000000000007700000000susemanager-schema/upgrade/satellite-schema-5.4-to-spacewalk-schema-1.2/258-rhnServerServerGroupArchCompat-indexes.sql    CREATE INDEX rhn_ssg_ac_sgt_idx
    ON rhnServerServerGroupArchCompat (server_group_type)
    TABLESPACE [[64k_tbs]]
    NOLOGGING;
drop index rhn_ssg_ac_sgt_said_idx;
07070100000457000081B400000000000000000000000167AE11140000009F000000000000000000000000000000000000006B00000000susemanager-schema/upgrade/satellite-schema-5.4-to-spacewalk-schema-1.2/259-rhnServerTokenRegs-indexes.sql    CREATE INDEX RHN_SRVR_TKN_RGS_SID_IDX
    ON rhnServerTokenRegs (server_id)
    TABLESPACE [[64k_tbs]]
    NOLOGGING;
drop index RHN_SRVR_TKN_RGS_SID_TID_IDX;
 07070100000458000081B400000000000000000000000167AE11140000009A000000000000000000000000000000000000007100000000susemanager-schema/upgrade/satellite-schema-5.4-to-spacewalk-schema-1.2/260-rhnSnapshotConfigChannel-indexes.sql  CREATE INDEX rhn_snpsht_cc_ccid_idx
    ON rhnSnapshotConfigChannel (config_channel_id)
    TABLESPACE [[4m_tbs]];
drop index rhn_snpsht_cc_ccid_sid_idx;
  07070100000459000081B400000000000000000000000167AE111400000092000000000000000000000000000000000000007200000000susemanager-schema/upgrade/satellite-schema-5.4-to-spacewalk-schema-1.2/261-rhnSnapshotConfigRevision-indexes.sql CREATE INDEX rhn_sscr_crid_idx
    ON rhnSnapshotConfigRevision (config_revision_id)
    TABLESPACE [[2m_tbs]];
drop index rhn_sscr_crid_sid_idx;
  0707010000045A000081B400000000000000000000000167AE111400000088000000000000000000000000000000000000006700000000susemanager-schema/upgrade/satellite-schema-5.4-to-spacewalk-schema-1.2/262-rhnSnapshotTag-indexes.sql    drop index rhn_ss_tag_tid_ssid_idx;

CREATE INDEX rhn_ss_tag_tid_idx
    ON rhnSnapshotTag (tag_id);
drop index rhn_ss_tag_tid_sid_idx;
0707010000045B000081B400000000000000000000000167AE111400000080000000000000000000000000000000000000007000000000susemanager-schema/upgrade/satellite-schema-5.4-to-spacewalk-schema-1.2/263-rhnSolarisPatchPackages-indexes.sql   CREATE INDEX rhn_solaris_pp_pnid_idx
    ON rhnSolarisPatchPackages (package_nevra_id);
drop index rhn_solaris_pp_pnid_pid_idx;
0707010000045C000081B400000000000000000000000167AE11140000009A000000000000000000000000000000000000007200000000susemanager-schema/upgrade/satellite-schema-5.4-to-spacewalk-schema-1.2/264-rhnSolarisPatchSetMembers-indexes.sql CREATE INDEX rhn_solaris_psm_psid_idx
    ON rhnSolarisPatchSetMembers (patch_set_id)
    TABLESPACE [[4m_tbs]];
drop index rhn_solaris_psm_psid_pid_idx;
  0707010000045D000081B400000000000000000000000167AE111400000090000000000000000000000000000000000000007300000000susemanager-schema/upgrade/satellite-schema-5.4-to-spacewalk-schema-1.2/265-rhnUserDefaultSystemGroups-indexes.sql    CREATE INDEX rhn_udsg_sgid_idx
    ON rhnUserDefaultSystemGroups (system_group_id)
    TABLESPACE [[2m_tbs]];
drop index rhn_udsg_sgid_uid_idx;
0707010000045E000081B400000000000000000000000167AE1114000000E8000000000000000000000000000000000000006500000000susemanager-schema/upgrade/satellite-schema-5.4-to-spacewalk-schema-1.2/266-rhnUserGroup-indexes.sql  drop index rhn_ug_org_id_name_idx;

ALTER TABLE rhnUserGroup
 disable CONSTRAINT rhn_ug_oid_gt_uq;
drop index rhn_ug_org_id_gtype_idx;
ALTER TABLE rhnUserGroup
 enable CONSTRAINT rhn_ug_oid_gt_uq
 USING INDEX TABLESPACE [[8m_tbs]];
0707010000045F000081B400000000000000000000000167AE11140000009F000000000000000000000000000000000000006C00000000susemanager-schema/upgrade/satellite-schema-5.4-to-spacewalk-schema-1.2/267-rhnUserGroupMembers-indexes.sql   CREATE INDEX rhn_ugmembers_ugid_idx
    ON rhnUserGroupMembers (user_group_id)
    TABLESPACE [[8m_tbs]]
    NOLOGGING;
drop index rhn_ugmembers_ugid_uid_idx;
 07070100000460000081B400000000000000000000000167AE111400000097000000000000000000000000000000000000007000000000susemanager-schema/upgrade/satellite-schema-5.4-to-spacewalk-schema-1.2/268-rhnUserServerGroupPerms-indexes.sql   CREATE INDEX rhn_usgp_sg_idx
    ON rhnUserServerGroupPerms (server_group_id)
    TABLESPACE [[4m_tbs]]
    NOLOGGING;
drop index rhn_usgp_sg_u_p_idx;
 07070100000461000081B400000000000000000000000167AE1114000000BD000000000000000000000000000000000000006B00000000susemanager-schema/upgrade/satellite-schema-5.4-to-spacewalk-schema-1.2/269-rhnUserServerPrefs-indexes.sql    drop index rhn_usprefs_n_sid_uid_idx;

CREATE INDEX rhn_usprefs_sid_idx
    ON rhnUserServerPrefs (server_id)
    TABLESPACE [[2m_tbs]]
    NOLOGGING;
drop index rhn_usprefs_sid_uid_n_idx;
   07070100000462000081B400000000000000000000000167AE111400000088000000000000000000000000000000000000006B00000000susemanager-schema/upgrade/satellite-schema-5.4-to-spacewalk-schema-1.2/270-rhnVirtualInstance-indexes.sql    CREATE INDEX rhn_vi_vsid_idx
    ON rhnVirtualInstance (virtual_system_id)
    TABLESPACE [[64k_tbs]];
drop index rhn_vi_vsid_hsid_idx;
07070100000463000081B400000000000000000000000167AE11140000002D000000000000000000000000000000000000006800000000susemanager-schema/upgrade/satellite-schema-5.4-to-spacewalk-schema-1.2/271-rhnPackageNEVRA-indexes.sql   
drop index rhn_pkgnevra_nid_evrid_id_idx ;

   07070100000464000081B400000000000000000000000167AE11140000002E000000000000000000000000000000000000006900000000susemanager-schema/upgrade/satellite-schema-5.4-to-spacewalk-schema-1.2/272-rhnServerProfile-indexes.sql  
drop index rhn_server_profile_o_id_bc_idx ;

  07070100000465000081B400000000000000000000000167AE111400000023000000000000000000000000000000000000006B00000000susemanager-schema/upgrade/satellite-schema-5.4-to-spacewalk-schema-1.2/273-rhnSnapshotPackage-indexes.sql    
drop index rhn_snapshotpkg_sid ;

 07070100000466000081B400000000000000000000000167AE111400000028000000000000000000000000000000000000006F00000000susemanager-schema/upgrade/satellite-schema-5.4-to-spacewalk-schema-1.2/274-rhnSatelliteChannelFamily-drop.sql    
drop table rhnSatelliteChannelFamily;

07070100000467000081B400000000000000000000000167AE111400000046000000000000000000000000000000000000006C00000000susemanager-schema/upgrade/satellite-schema-5.4-to-spacewalk-schema-1.2/400-rhn_schedule_days_norm-drop.sql   
drop synonym schedule_days_norm;
drop table rhn_schedule_days_norm;

  07070100000468000081B400000000000000000000000167AE111400000056000000000000000000000000000000000000007400000000susemanager-schema/upgrade/satellite-schema-5.4-to-spacewalk-schema-1.2/401-rhn_command_queue_instances_bk-drop.sql   
drop synonym command_queue_instances_bk;
drop table rhn_command_queue_instances_bk;

  07070100000469000081B400000000000000000000000167AE11140000004E000000000000000000000000000000000000007000000000susemanager-schema/upgrade/satellite-schema-5.4-to-spacewalk-schema-1.2/402-rhn_command_queue_execs_bk-drop.sql   
drop synonym command_queue_execs_bk;
drop table rhn_command_queue_execs_bk;

  0707010000046A000081B400000000000000000000000167AE11140000004A000000000000000000000000000000000000007000000000susemanager-schema/upgrade/satellite-schema-5.4-to-spacewalk-schema-1.2/403-rhn_command_queue_execs_bk-drop.sql   
drop synonym command_center_state;
drop table rhn_command_center_state;

  0707010000046B000081B400000000000000000000000167AE11140000001D000000000000000000000000000000000000006400000000susemanager-schema/upgrade/satellite-schema-5.4-to-spacewalk-schema-1.2/404-rhnTextMessage-drop.sql   
drop table rhnTextMessage;

   0707010000046C000081B400000000000000000000000167AE111400000020000000000000000000000000000000000000006700000000susemanager-schema/upgrade/satellite-schema-5.4-to-spacewalk-schema-1.2/405-rhnEntitlementLog-drop.sql    
drop table rhnEntitlementLog;

0707010000046D000081B400000000000000000000000167AE11140000001C000000000000000000000000000000000000006300000000susemanager-schema/upgrade/satellite-schema-5.4-to-spacewalk-schema-1.2/406-rhnAllowTrust-drop.sql    
drop table rhnAllowTrust;

0707010000046E000081B400000000000000000000000167AE11140000001E000000000000000000000000000000000000006700000000susemanager-schema/upgrade/satellite-schema-5.4-to-spacewalk-schema-1.2/407-rhnBeehivePathMap-drop.sql    drop table rhnBeehivePathMap;
  0707010000046F000081B400000000000000000000000167AE111400000023000000000000000000000000000000000000006B00000000susemanager-schema/upgrade/satellite-schema-5.4-to-spacewalk-schema-1.2/408-rhnActionTransactions-drop.sql    
drop table rhnActionTransactions;
 07070100000470000081B400000000000000000000000167AE111400000022000000000000000000000000000000000000006B00000000susemanager-schema/upgrade/satellite-schema-5.4-to-spacewalk-schema-1.2/409-rhnTransactionElement-drop.sql    drop table rhnTransactionElement;
  07070100000471000081B400000000000000000000000167AE111400000041000000000000000000000000000000000000006400000000susemanager-schema/upgrade/satellite-schema-5.4-to-spacewalk-schema-1.2/410-rhnTransaction-drop.sql   drop table rhnTransaction;
drop sequence rhn_transaction_id_seq;
   07070100000472000081B400000000000000000000000167AE111400000027000000000000000000000000000000000000006E00000000susemanager-schema/upgrade/satellite-schema-5.4-to-spacewalk-schema-1.2/411-rhn_interface_monitoring-drop.sql 
drop table rhn_interface_monitoring;

 07070100000473000081B400000000000000000000000167AE111400000022000000000000000000000000000000000000006B00000000susemanager-schema/upgrade/satellite-schema-5.4-to-spacewalk-schema-1.2/506-rhnActionPackageOrder-drop.sql    drop table rhnActionPackageOrder;
  07070100000474000081B400000000000000000000000167AE11140000001D000000000000000000000000000000000000006600000000susemanager-schema/upgrade/satellite-schema-5.4-to-spacewalk-schema-1.2/507-rhnChannelParent-drop.sql drop table rhnChannelParent;
   07070100000475000081B400000000000000000000000167AE11140000001F000000000000000000000000000000000000006800000000susemanager-schema/upgrade/satellite-schema-5.4-to-spacewalk-schema-1.2/508-rhnEmailAddressLog-drop.sql   drop table rhnEmailAddressLog;
 07070100000476000081B400000000000000000000000167AE111400000025000000000000000000000000000000000000006E00000000susemanager-schema/upgrade/satellite-schema-5.4-to-spacewalk-schema-1.2/509-rhnGrailComponentChoices-drop.sql drop table rhnGrailComponentChoices;
   07070100000477000081B400000000000000000000000167AE111400000047000000000000000000000000000000000000006800000000susemanager-schema/upgrade/satellite-schema-5.4-to-spacewalk-schema-1.2/510-rhnGrailComponents-drop.sql   drop table rhnGrailComponents;
drop sequence rhn_grail_components_seq;
 07070100000478000081B400000000000000000000000167AE11140000003A000000000000000000000000000000000000006000000000susemanager-schema/upgrade/satellite-schema-5.4-to-spacewalk-schema-1.2/511-rhnMonitor-drop.sql   drop table rhnMonitor;
drop sequence rhn_monitor_bid_seq;
  07070100000479000081B400000000000000000000000167AE11140000001F000000000000000000000000000000000000006800000000susemanager-schema/upgrade/satellite-schema-5.4-to-spacewalk-schema-1.2/512-rhnPackageSenseMap-drop.sql   drop table rhnPackageSenseMap;
 0707010000047A000081B400000000000000000000000167AE11140000001E000000000000000000000000000000000000006700000000susemanager-schema/upgrade/satellite-schema-5.4-to-spacewalk-schema-1.2/513-rhnPathChannelMap-drop.sql    drop table rhnPathChannelMap;
  0707010000047B000081B400000000000000000000000167AE11140000001E000000000000000000000000000000000000006700000000susemanager-schema/upgrade/satellite-schema-5.4-to-spacewalk-schema-1.2/514-rhnProductChannel-drop.sql    drop table rhnProductChannel;
  0707010000047C000081B400000000000000000000000167AE111400000042000000000000000000000000000000000000006900000000susemanager-schema/upgrade/satellite-schema-5.4-to-spacewalk-schema-1.2/515-rhnRelationshipType-drop.sql  drop table rhnRelationshipType;
drop sequence rhn_reltype_id_seq;
  0707010000047D000081B400000000000000000000000167AE111400000041000000000000000000000000000000000000006400000000susemanager-schema/upgrade/satellite-schema-5.4-to-spacewalk-schema-1.2/516-rhnSavedSearch-drop.sql   drop table rhnSavedSearch;
drop sequence rhn_savedsearch_id_seq;
   0707010000047E000081B400000000000000000000000167AE11140000001F000000000000000000000000000000000000006800000000susemanager-schema/upgrade/satellite-schema-5.4-to-spacewalk-schema-1.2/517-rhnServerCacheInfo-drop.sql   drop table rhnServerCacheInfo;
 0707010000047F000081B400000000000000000000000167AE11140000004F000000000000000000000000000000000000006B00000000susemanager-schema/upgrade/satellite-schema-5.4-to-spacewalk-schema-1.2/518-rhnMonitorGranularity-drop.sql    drop table rhnMonitorGranularity;
drop sequence rhn_monitorgranularity_id_seq;
 07070100000480000081B400000000000000000000000167AE111400000039000000000000000000000000000000000000006000000000susemanager-schema/upgrade/satellite-schema-5.4-to-spacewalk-schema-1.2/519-rhnProduct-drop.sql   drop table rhnProduct;
drop sequence rhn_product_id_seq;
   07070100000481000081B400000000000000000000000167AE11140000001C000000000000000000000000000000000000006500000000susemanager-schema/upgrade/satellite-schema-5.4-to-spacewalk-schema-1.2/520-rhnPackageSense-drop.sql  drop table rhnPackageSense;
07070100000482000081B400000000000000000000000167AE111400000040000000000000000000000000000000000000006800000000susemanager-schema/upgrade/satellite-schema-5.4-to-spacewalk-schema-1.2/521-rhnSavedSearchType-drop.sql   drop table rhnSavedSearchType;
drop sequence rhn_sstype_id_seq;
07070100000483000081B400000000000000000000000167AE11140000003F000000000000000000000000000000000000006400000000susemanager-schema/upgrade/satellite-schema-5.4-to-spacewalk-schema-1.2/522-rhnProductLine-drop.sql   drop table rhnProductLine;
drop sequence rhn_prod_line_id_seq;
 07070100000484000081B400000000000000000000000167AE11140000001D000000000000000000000000000000000000006600000000susemanager-schema/upgrade/satellite-schema-5.4-to-spacewalk-schema-1.2/523-rhnServerMessage-drop.sql drop table rhnServerMessage;
   07070100000485000081B400000000000000000000000167AE111400000033000000000000000000000000000000000000006000000000susemanager-schema/upgrade/satellite-schema-5.4-to-spacewalk-schema-1.2/524-rhnMessage-drop.sql   drop table rhnMessage;
drop sequence rhn_m_id_seq;
 07070100000486000081B400000000000000000000000167AE111400000044000000000000000000000000000000000000006800000000susemanager-schema/upgrade/satellite-schema-5.4-to-spacewalk-schema-1.2/525-rhnMessagePriority-drop.sql   drop table rhnMessagePriority;
drop sequence rhn_m_priority_id_seq;
07070100000487000081B400000000000000000000000167AE111400000038000000000000000000000000000000000000006400000000susemanager-schema/upgrade/satellite-schema-5.4-to-spacewalk-schema-1.2/526-rhnMessageType-drop.sql   drop table rhnMessageType;
drop sequence rhn_mt_id_seq;
07070100000488000081B400000000000000000000000167AE111400000024000000000000000000000000000000000000006D00000000susemanager-schema/upgrade/satellite-schema-5.4-to-spacewalk-schema-1.2/527-rhnSatelliteServerGroup-drop.sql  drop table rhnSatelliteServerGroup;
07070100000489000081B400000000000000000000000167AE111400000042000000000000000000000000000000000000006B00000000susemanager-schema/upgrade/satellite-schema-5.4-to-spacewalk-schema-1.2/528-rhn_host_check_suites-drop.sql    drop synonym host_check_suites;
drop table rhn_host_check_suites;
  0707010000048A000081B400000000000000000000000167AE1114000000C2000000000000000000000000000000000000006B00000000susemanager-schema/upgrade/satellite-schema-5.4-to-spacewalk-schema-1.2/530-rhnErrataNotificationQueue.sql    ALTER TABLE rhnErrataNotificationQueue DROP CONSTRAINT rhn_enqueue_eoid_uq;
ALTER TABLE rhnErrataNotificationQueue
    ADD CONSTRAINT rhn_enqueue_eoid_uq UNIQUE (errata_id, channel_id, org_id);
  0707010000048B000081B400000000000000000000000167AE111400000020000000000000000000000000000000000000006A00000000susemanager-schema/upgrade/satellite-schema-5.4-to-spacewalk-schema-1.2/531-rhnPrivateErrataMail-drop.sql drop view rhnPrivateErrataMail;
0707010000048C000081B400000000000000000000000167AE111400000025000000000000000000000000000000000000006F00000000susemanager-schema/upgrade/satellite-schema-5.4-to-spacewalk-schema-1.2/532-rhnChannelPackageOverview-drop.sql    drop view rhnChannelPackageOverview;
   0707010000048D000081B400000000000000000000000167AE111400000021000000000000000000000000000000000000006B00000000susemanager-schema/upgrade/satellite-schema-5.4-to-spacewalk-schema-1.2/533-rhnOrgPackageOverview-drop.sql    drop view rhnOrgPackageOverview;
   0707010000048E000081B400000000000000000000000167AE111400000021000000000000000000000000000000000000006B00000000susemanager-schema/upgrade/satellite-schema-5.4-to-spacewalk-schema-1.2/534-rhnUserAppletOverview-drop.sql    drop view rhnUserAppletOverview;
   0707010000048F000081B400000000000000000000000167AE111400000022000000000000000000000000000000000000006C00000000susemanager-schema/upgrade/satellite-schema-5.4-to-spacewalk-schema-1.2/535-rhnUserGroupMembership-drop.sql   drop view rhnUserGroupMembership;
  07070100000490000081B400000000000000000000000167AE11140000003C000000000000000000000000000000000000006700000000susemanager-schema/upgrade/satellite-schema-5.4-to-spacewalk-schema-1.2/540-rhnPaidErrataTempCache.sql    DROP index rhnpec_u_idx;
DROP TABLE rhnPaidErrataTempCache;
07070100000491000081B400000000000000000000000167AE111400000680000000000000000000000000000000000000005E00000000susemanager-schema/upgrade/satellite-schema-5.4-to-spacewalk-schema-1.2/541-delete_errata.sql --
-- Copyright (c) 2008--2010 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--
--
--
--

create or replace procedure
delete_errata (
	errata_id_in in number
) is
begin
	delete from rhnServerNeededCache where errata_id = errata_id_in;
	delete from rhnErrataFile where errata_id = errata_id_in;
	delete from rhnErrataPackage where errata_id = errata_id_in;
	delete from rhnErrata where id = errata_id_in;
	delete from rhnErrataTmp where id = errata_id_in;
end delete_errata;
/
show errors

--
-- Revision 1.4  2004/12/04 21:24:51  cturner
-- bugzilla: 141768, and another one.  pre-delete from rhnErrataPackage to prevent trigger madness
--
-- Revision 1.3  2004/12/04 21:14:25  cturner
-- bugzilla: 141768, pre-delete from rhnErrataFile to prevent trigger madness
--
-- Revision 1.2  2004/09/13 20:56:44  pjones
-- bugzilla: 117597 --
-- 1) make the constraints look like they do in prod.
-- 2) remove the sat-only errata_id index
-- 3) remove duplicate server_id based index.
-- 4) make a new index that starts with errata
--
-- Revision 1.1  2003/08/15 20:45:44  pjones
-- bugzilla: 102263
--
-- delete_errata()
--
07070100000492000081B400000000000000000000000167AE111400000498000000000000000000000000000000000000006300000000susemanager-schema/upgrade/satellite-schema-5.4-to-spacewalk-schema-1.2/542-lookup_config_info.sql    create or replace function
lookup_config_info (
    username_in     in varchar2,
    groupname_in    in varchar2,
    filemode_in     in number,
    selinux_ctx_in  in varchar2,
    symlink_target_id in number
) return number
deterministic
is
    pragma autonomous_transaction;
    v_id    number;
    cursor lookup_cursor is
        select id
          from rhnConfigInfo
         where 1=1
           and nvl(username, ' ') = nvl(username_in, ' ')
           and nvl(groupname,' ') = nvl(groupname_in, ' ')
           and nvl(filemode, -1) = nvl(filemode_in, -1)
           and nvl(selinux_ctx, ' ') = nvl(selinux_ctx_in, ' ')
           and nvl(symlink_target_filename_id, -1) = nvl(symlink_target_id, -1)
        ;
begin
    for r in lookup_cursor loop
        return r.id;
    end loop;
    -- If we got here, we don't have the id
    select rhn_confinfo_id_seq.nextval
      into v_id
      from dual;
    insert into rhnConfigInfo (id, username, groupname, filemode, selinux_ctx, symlink_target_filename_id)
    values (v_id, username_in, groupname_in, filemode_in, selinux_ctx_in, symlink_target_id);
    commit;
    return v_id;
end lookup_config_info;
/
show errors
07070100000493000081B400000000000000000000000167AE11140000AD56000000000000000000000000000000000000006100000000susemanager-schema/upgrade/satellite-schema-5.4-to-spacewalk-schema-1.2/600-rhn_channel-body.sql  --
-- Copyright (c) 2008--2010 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--

-- we have to do this here in the schema update from sat 5.4 to spacew 1.2 again
-- because the 1.1 to 1.2 update on red hat satellite has a bug in this package

CREATE OR REPLACE
PACKAGE BODY rhn_channel
IS
        body_version varchar2(100) := '';

    -- Cursor that fetches all the possible base channels for a
    -- (server_arch_id, release, org_id) combination
        cursor  base_channel_cursor(
                release_in in varchar2,
                server_arch_id_in in number,
                org_id_in in number
        ) return rhnChannel%ROWTYPE is
                select distinct c.*
                from    rhnDistChannelMap                       dcm,
                                rhnServerChannelArchCompat      scac,
                                rhnChannel                                      c,
                                rhnChannelPermissions           cp
                where   cp.org_id = org_id_in
                        and cp.channel_id = c.id
                        and c.parent_channel is null
                        and c.id = dcm.channel_id
                        and c.channel_arch_id = dcm.channel_arch_id
                        and dcm.release = release_in
                        and scac.server_arch_id = server_arch_id_in
                        and scac.channel_arch_id = c.channel_arch_id;

    procedure obtain_read_lock(channel_family_id_in in number, org_id_in in number)
    is
        read_lock date;

    begin
        select created into read_lock
          from rhnPrivateChannelFamily
         where channel_family_id = channel_family_id_in and org_id = org_id_in
           for update;
    end obtain_read_lock;

    PROCEDURE subscribe_server(server_id_in IN NUMBER, channel_id_in NUMBER, immediate_in NUMBER := 1, user_id_in in number := null, recalcfamily_in number := 1)
    IS
        channel_parent_val      rhnChannel.parent_channel%TYPE;
        parent_subscribed       BOOLEAN;
        server_has_base_chan    BOOLEAN;
        server_already_in_chan  BOOLEAN;
        channel_family_id_val   NUMBER;
        server_org_id_val       NUMBER;
        available_subscriptions NUMBER;
        available_fve_subs      NUMBER;
        consenting_user         NUMBER;
        allowed                 number := 0;
        is_fve                  CHAR(1) := 'N';
    BEGIN
        if user_id_in is not null then
            allowed := rhn_channel.user_role_check(channel_id_in, user_id_in, 'subscribe');
        else
            allowed := 1;
        end if;

        if allowed = 0 then
            rhn_exception.raise_exception('no_subscribe_permissions');
        end if;


        SELECT parent_channel INTO channel_parent_val FROM rhnChannel WHERE id = channel_id_in;

        IF channel_parent_val IS NOT NULL
        THEN    
            -- child channel; if attempting to cross-subscribe a child to the wrong base, silently ignore
            parent_subscribed := FALSE;    

            FOR check_subscription IN check_server_subscription(server_id_in, channel_parent_val)
            LOOP
                parent_subscribed := TRUE;
            END LOOP check_subscription;
        
            IF NOT parent_subscribed
            THEN
                RETURN;
            END IF;
        ELSE
            -- base channel
            server_has_base_chan := FALSE;
            FOR base IN server_base_subscriptions(server_id_in)
            LOOP
                server_has_base_chan := TRUE;
            END LOOP base;
            
            IF server_has_base_chan
            THEN
                rhn_exception.raise_exception('channel_server_one_base');
            END IF;
        END IF;
    
        FOR check_subscription IN check_server_subscription(server_id_in, channel_id_in)
        LOOP
            server_already_in_chan := TRUE;
        END LOOP check_subscription;
    
        IF server_already_in_chan
        THEN
            RETURN;
        END IF;
        
        channel_family_id_val := rhn_channel.family_for_channel(channel_id_in);
        IF channel_family_id_val IS NULL
        THEN
            rhn_exception.raise_exception('channel_subscribe_no_family');
        END IF;

        --
        -- Use the org_id of the server only if the org_id of the channel = NULL.
        -- This is required for subscribing to shared channels.
        --
        SELECT NVL(org_id, (SELECT org_id FROM rhnServer WHERE id = server_id_in))
          INTO server_org_id_val
          FROM rhnChannel
         WHERE id = channel_id_in;
         
        begin
            obtain_read_lock(channel_family_id_val, server_org_id_val);
        exception
            when no_data_found then
                rhn_exception.raise_exception('channel_family_no_subscriptions');
        end;

        available_subscriptions := rhn_channel.available_family_subscriptions(channel_family_id_val, server_org_id_val);
        available_fve_subs := rhn_channel.available_fve_family_subs(channel_family_id_val, server_org_id_val);

        IF available_subscriptions IS NULL OR
            available_subscriptions > 0 or
            can_server_consume_virt_channl(server_id_in, channel_family_id_val) = 1 OR
            (available_fve_subs > 0 AND can_server_consume_fve(server_id_in) = 1)
        THEN
            if can_server_consume_virt_channl(server_id_in, channel_family_id_val) = 0 AND available_fve_subs > 0 AND can_server_consume_fve(server_id_in) = 1 THEN
                is_fve := 'Y';
            END IF;
            insert into rhnServerHistory (id,server_id,summary,details) (
                select  rhn_event_id_seq.nextval,
                        server_id_in,
                        'subscribed to channel ' || SUBSTR(c.label, 0, 106),
                        c.label
                from    rhnChannel c
                where   c.id = channel_id_in
            );
            UPDATE rhnServer SET channels_changed = sysdate WHERE id = server_id_in;
            INSERT INTO rhnServerChannel (server_id, channel_id, is_fve) VALUES (server_id_in, channel_id_in, is_fve);
			IF recalcfamily_in > 0
			THEN
                rhn_channel.update_family_counts(channel_family_id_val, server_org_id_val);
			END IF;
            queue_server(server_id_in, immediate_in);
        ELSE
            rhn_exception.raise_exception('channel_family_no_subscriptions');
        END IF;
            
    END subscribe_server;



    FUNCTION can_convert_to_fve(server_id_in IN NUMBER, channel_family_id_val IN NUMBER)
    RETURN NUMBER
    IS
        CURSOR fve_convertible_entries IS
        select 1  from
            rhnServerFveCapable cap
          where cap.server_id = server_id_in
                AND cap.channel_family_id = channel_family_id_val;
    BEGIN
        FOR entry IN fve_convertible_entries LOOP
            return 1;
        END LOOP;
        RETURN 0;
    END can_convert_to_fve;



    -- Converts server channel_family to use a flex entitlement
    PROCEDURE convert_to_fve(server_id_in IN NUMBER, channel_family_id_val IN NUMBER)
    IS
        available_fve_subs      NUMBER;
        server_org_id_val       NUMBER;        
    BEGIN

        --
        -- Use the org_id of the server only if the org_id of the channel = NULL.
        -- This is required for subscribing to shared channels.
        --
        SELECT org_id
          INTO server_org_id_val
          FROM rhnServer
         WHERE id = server_id_in;
         
        begin
            obtain_read_lock(channel_family_id_val, server_org_id_val);
        exception
            when no_data_found then
                rhn_exception.raise_exception('channel_family_no_subscriptions');
        end;
        IF (can_convert_to_fve(server_id_in, channel_family_id_val ) = 0) 
            THEN
                rhn_exception.raise_exception('server_cannot_convert_to_flex');
        END IF;

        available_fve_subs := rhn_channel.available_fve_family_subs(channel_family_id_val, server_org_id_val);

        IF (available_fve_subs > 0)
        THEN
        
            insert into rhnServerHistory (id,server_id,summary,details) (
                select  rhn_event_id_seq.nextval,
                        server_id_in,
                        'converted to flex entitlement' || SUBSTR(cf.label, 0, 99),
                        cf.label
                from    rhnChannelFamily cf
                where   cf.id = channel_family_id_val
            );

            UPDATE rhnServerChannel sc set sc.is_fve = 'Y' 
                           where sc.server_id = server_id_in and  
                                 sc.channel_id in 
                                    (select cfm.channel_id from rhnChannelFamilyMembers cfm
                                                where cfm.CHANNEL_FAMILY_ID = channel_family_id_val);
            
            rhn_channel.update_family_counts(channel_family_id_val, server_org_id_val);
        ELSE
            rhn_exception.raise_exception('not_enough_flex_entitlements');
        END IF;
            
    END convert_to_fve;    
    
    function can_server_consume_virt_channl(
        server_id_in in number,
        family_id_in in number )
    return number
    is

        cursor server_virt_families is
            select vi.virtual_system_id, cfvsl.channel_family_id
            from
                rhnChannelFamilyVirtSubLevel cfvsl,
                rhnSGTypeVirtSubLevel sgtvsl,
                rhnVirtualInstance vi
            where
                vi.virtual_system_id = server_id_in 
                and sgtvsl.virt_sub_level_id = cfvsl.virt_sub_level_id
                and cfvsl.channel_family_id = family_id_in
                and exists (
                    select 1
                    from rhnServerEntitlementView sev
                    where vi.host_system_id = sev.server_id
                    and sev.server_group_type_id = sgtvsl.server_group_type_id );
    begin

        for server_virt_family in server_virt_families loop
            return 1;
        end loop;

        return 0;

    end;

    FUNCTION can_server_consume_fve(server_id_in IN NUMBER)
    RETURN NUMBER
    IS
        CURSOR vi_entries IS
            SELECT 1
              FROM rhnVirtualInstance vi
             WHERE vi.virtual_system_id = server_id_in
             and not exists(select server_id from rhnServerChannel sc where 
                            sc.server_id = vi.virtual_system_id 
                            and  sc.is_fve='Y');
        vi_count NUMBER;

    BEGIN
        FOR vi_entry IN VI_ENTRIES LOOP
            return 1;
        END LOOP;
        RETURN 0;
    END;

    function guess_server_base(
        server_id_in in number
    ) RETURN number is
        cursor server_cursor is
            select s.server_arch_id, s.release, s.org_id
              from rhnServer s
             where s.id = server_id_in;
    begin
        for s in server_cursor loop
            for channel in base_channel_cursor(s.release,
                s.server_arch_id, s.org_id) 
            loop
                return channel.id;
            end loop base_channel_cursor;
        end loop server_cursor;
        -- Server not found, or no base channel applies to it
        return null;
    end;

    -- Private function
    function normalize_server_arch(server_arch_in in varchar2)
    return varchar2
    deterministic
    is
        suffix VARCHAR2(128) := '-redhat-linux';
        suffix_len NUMBER := length(suffix);
    begin
        if server_arch_in is NULL then
            return NULL;
        end if;
        if instr(server_arch_in, '-') > 0
        then
            -- Suffix already present
            return server_arch_in;
        end if;
        return server_arch_in || suffix;
    end normalize_server_arch;

    --
    --
    -- Raises: 
    --   server_arch_not_found
    --   no_subscribe_permissions
    function base_channel_for_release_arch(
        release_in in varchar2,
        server_arch_in in varchar2,
        org_id_in in number := -1,
        user_id_in in number := null
    ) return number is
        server_arch varchar2(256) := normalize_server_arch(server_arch_in);
        server_arch_id number;
    begin
        -- Look up the server arch
        begin
            select id
              into server_arch_id
              from rhnServerArch
             where label = server_arch;
        exception
            when no_data_found then
                rhn_exception.raise_exception('server_arch_not_found');
        end;
        return base_channel_rel_archid(release_in, server_arch_id,
            org_id_in, user_id_in);
    end base_channel_for_release_arch;

    function base_channel_rel_archid(
        release_in in varchar2,
        server_arch_id_in in number,
        org_id_in in number := -1,
        user_id_in in number := null
    ) return number is
        denied_channel_id number := null;
        valid_org_id number := org_id_in;
        valid_user_id number := user_id_in;
        channel_subscribable number;
    begin
        if org_id_in = -1 and user_id_in is not null then
            -- Get the org id from the user id
            begin
                select org_id
                  into valid_org_id
                  from web_contact
                 where id = user_id_in;
            exception
                when no_data_found then
                    -- User doesn't exist
                    -- XXX Only list public stuff for now
                    valid_user_id := null;
                    valid_org_id := -1;
            end;
        end if;

        for c in base_channel_cursor(release_in, server_arch_id_in, valid_org_id)
        loop
            -- This row is a possible match
            if valid_user_id is null then
                -- User ID not specified, so no user to channel permissions to
                -- check
                return c.id;
            end if;

            -- Check user to channel permissions
            select loose_user_role_check(c.id, user_id_in, 'subscribe')
              into channel_subscribable
              from dual;

            if channel_subscribable = 1 then
                return c.id;
            end if;
                
            -- Base channel exists, but is not subscribable; keep trying
            denied_channel_id := c.id;
        end loop base_channel_fetch;
        
        if denied_channel_id is not null then
            rhn_exception.raise_exception('no_subscribe_permissions');
        end if;
        -- No base channel applies
        return NULL;
    end base_channel_rel_archid;

    PROCEDURE clear_subscriptions(server_id_in IN NUMBER, deleting_server IN NUMBER := 0,
                                update_family_countsYN IN NUMBER := 1)
    IS
        cursor server_channels(server_id_in in number) is
                select  s.org_id, sc.channel_id, cfm.channel_family_id
                from    rhnServer s,
                        rhnServerChannel sc,
                        rhnChannelFamilyMembers cfm
                where   s.id = server_id_in
                        and s.id = sc.server_id
                        and sc.channel_id = cfm.channel_id
                order by cfm.channel_family_id;
        last_channel_family_id rhnChannelFamilyMembers.channel_family_id%type := -1;
        last_channel_org_id    rhnServer.org_id%type := -1;
    BEGIN
        for channel in server_channels(server_id_in)
        loop
                unsubscribe_server(server_id_in, channel.channel_id, 1, 1, deleting_server, 0);
                if update_family_countsYN > 0
                    and channel.channel_family_id != last_channel_family_id then
                    -- update family counts only once
                    -- after all channels with same family has been fetched
                    if last_channel_family_id != -1 then
                        update_family_counts(last_channel_family_id, last_channel_org_id);
                    end if;
                    last_channel_family_id := channel.channel_family_id;
                    last_channel_org_id    := channel.org_id;
                end if;
        end loop channel;
        if update_family_countsYN > 0 and last_channel_family_id != -1 then
            -- update the last family fetched
            update_family_counts(last_channel_family_id, last_channel_org_id);
        end if;
    END clear_subscriptions;

    PROCEDURE unsubscribe_server(server_id_in IN NUMBER, channel_id_in NUMBER, immediate_in NUMBER := 1, unsubscribe_children_in number := 0,
                                 deleting_server IN NUMBER := 0,
                                 update_family_countsYN IN NUMBER := 1)
    IS
        channel_family_id_val   NUMBER;
        server_org_id_val       NUMBER;
        available_subscriptions NUMBER; 
        server_already_in_chan  BOOLEAN;
        cursor  channel_family_is_proxy(channel_family_id_in in number) is
                select  1
                from    rhnChannelFamily
                where   id = channel_family_id_in
                    and label = 'rhn-proxy';
        cursor  channel_family_is_satellite(channel_family_id_in in number) is
                select  1
                from    rhnChannelFamily
                where   id = channel_family_id_in
                    and label = 'rhn-satellite';
        -- this is *EXACTLY* like check_server_parent_membership, but if we recurse
        -- with the package-level one, we get a "cursor already open", so we need a
        -- copy on our call stack instead.  GROAN.
        cursor local_chk_server_parent_memb (
                        server_id_in number,
                        channel_id_in number ) is
                select  c.id
                from    rhnChannel                      c,
                                rhnServerChannel        sc
                where   1=1
                        and c.parent_channel = channel_id_in
                        and c.id = sc.channel_id
                        and sc.server_id = server_id_in;
    BEGIN
        FOR child IN local_chk_server_parent_memb(server_id_in, channel_id_in)
        LOOP
            if unsubscribe_children_in = 1 then
                unsubscribe_server(server_id_in => server_id_in,
                                                                channel_id_in => child.id,
                                                                immediate_in => immediate_in,
                                                                unsubscribe_children_in => unsubscribe_children_in,
                        deleting_server => deleting_server,
                        update_family_countsYN => update_family_countsYN);
            else
                rhn_exception.raise_exception('channel_unsubscribe_child_exists');
            end if;
        END LOOP child;
        
        server_already_in_chan := FALSE;
    
        FOR check_subscription IN check_server_subscription(server_id_in, channel_id_in)
        LOOP
            server_already_in_chan := TRUE;
        END LOOP check_subscription;
    
        IF NOT server_already_in_chan
        THEN
            RETURN;
        END IF;
        
   if deleting_server = 0 then 

      insert into rhnServerHistory (id,server_id,summary,details) (
          select  rhn_event_id_seq.nextval,
                server_id_in,
             'unsubscribed from channel ' || SUBSTR(c.label, 0, 106),
             c.label
          from    rhnChannel c
          where   c.id = channel_id_in
      );

        UPDATE rhnServer SET channels_changed = sysdate WHERE id = server_id_in;
   end if;
        
   DELETE FROM rhnServerChannel WHERE server_id = server_id_in AND channel_id = channel_id_in;

   if deleting_server = 0 then 
        queue_server(server_id_in, immediate_in);
   end if;

        channel_family_id_val := rhn_channel.family_for_channel(channel_id_in);
        IF channel_family_id_val IS NULL
        THEN
            rhn_exception.raise_exception('channel_unsubscribe_no_family');
        END IF;

        for ignore in channel_family_is_satellite(channel_family_id_val) loop
                delete from rhnSatelliteInfo where server_id = server_id_in;
        end loop;

        for ignore in channel_family_is_proxy(channel_family_id_val) loop
                delete from rhnProxyInfo where server_id = server_id_in;
        end loop;
        SELECT org_id INTO server_org_id_val
          FROM rhnServer
         WHERE id = server_id_in;
         
        if update_family_countsYN = 1 then
            rhn_channel.update_family_counts(channel_family_id_val, server_org_id_val);
        end if;
    END unsubscribe_server;


    FUNCTION family_for_channel(channel_id_in IN NUMBER)
    RETURN NUMBER
    IS
        channel_family_id_val NUMBER;
    BEGIN
        SELECT channel_family_id INTO channel_family_id_val
          FROM rhnChannelFamilyMembers
         WHERE channel_id = channel_id_in;
         
        RETURN channel_family_id_val;
    EXCEPTION
        WHEN NO_DATA_FOUND
        THEN
            RETURN NULL;
    END family_for_channel;

    FUNCTION available_family_subscriptions(channel_family_id_in IN NUMBER, org_id_in IN NUMBER)
    RETURN NUMBER
    IS
        cfp channel_family_perm_cursor%ROWTYPE;
        current_members_val NUMBER;
        max_members_val     NUMBER;
        found               NUMBER;
    BEGIN
        IF NOT channel_family_perm_cursor%ISOPEN
        THEN
            OPEN channel_family_perm_cursor(channel_family_id_in, org_id_in);
        END IF;

        FETCH channel_family_perm_cursor INTO cfp;
        
        WHILE channel_family_perm_cursor%FOUND
        LOOP
            found := 1;
            
            current_members_val := cfp.current_members;
            max_members_val := cfp.max_members;
            
            FETCH channel_family_perm_cursor INTO cfp;
        END LOOP;

        IF channel_family_perm_cursor%ISOPEN
        THEN
            CLOSE channel_family_perm_cursor;
        END IF;

        -- not found: either the channel fam doesn't have an entry in cfp, or the org doesn't have access to it.
        -- either way, there are no available subscriptions
        
        IF found IS NULL
        THEN
            RETURN 0;
        END IF;

        -- null max members?  in that case, pass it on; NULL means infinite                     
        IF max_members_val IS NULL
        THEN
            RETURN NULL;
        END IF;

        -- otherwise, return the delta  
        RETURN max_members_val - current_members_val;                   
    END available_family_subscriptions;

    FUNCTION available_fve_family_subs(channel_family_id_in IN NUMBER, org_id_in IN NUMBER)
    RETURN NUMBER
    IS
        cfp channel_family_perm_cursor%ROWTYPE;
        fve_current_members_val NUMBER;
        fve_max_members_val     NUMBER;
        found               NUMBER;

    BEGIN
        IF NOT channel_family_perm_cursor%ISOPEN THEN
            OPEN channel_family_perm_cursor(channel_family_id_in, org_id_in);
        END IF;

        FETCH channel_family_perm_cursor INTO cfp;

        WHILE channel_family_perm_cursor%FOUND LOOP
            found := 1;
            fve_current_members_val := cfp.fve_current_members;
            fve_max_members_val := cfp.fve_max_members;
            FETCH channel_family_perm_cursor INTO cfp;
        END LOOP;

        IF channel_family_perm_cursor%ISOPEN THEN
            CLOSE channel_family_perm_cursor;
        END IF;

        IF found IS NULL THEN
            RETURN 0;
        END IF;

        IF fve_max_members_val IS NULL THEN
            RETURN NULL;
        END IF;

        RETURN fve_max_members_val - fve_current_members_val;

    END available_fve_family_subs;

    
    -- *******************************************************************
    -- FUNCTION: channel_family_current_members
    -- Calculates and returns the actual count of systems consuming
    --   physical channel subscriptions.
    -- Called by: update_family_counts 
    --            rhn_entitlements.repoll_virt_guest_entitlements
    -- *******************************************************************
    function channel_family_current_members(channel_family_id_in IN NUMBER,
                                            org_id_in IN NUMBER)
    return number
    is
        current_members_count number := 0;
    begin
        select  count(distinct server_id)
        into    current_members_count
          from  rhnChannelFamilyServerPhysical cfsp
         where  cfsp.channel_family_id = channel_family_id_in
           and  cfsp.customer_id = org_id_in;
        return current_members_count;
    end;        


    function cfam_curr_fve_members(
        channel_family_id_in IN NUMBER,
        org_id_in IN NUMBER)
    return number
    is
        current_members_count number := 0;

    begin
        select count(sc.server_id)
          into current_members_count
          from rhnServerChannel sc,
               rhnChannelFamilyMembers cfm,
               rhnServer s
         where s.org_id = org_id_in
           and s.id = sc.server_id
           and cfm.channel_family_id = channel_family_id_in
           and cfm.channel_id = sc.channel_id
           and exists (
                select 1
                  from rhnChannelFamilyServerFve cfsp
                 where cfsp.CHANNEL_FAMILY_ID = channel_family_id_in
                   and cfsp.server_id = s.id
                );

        return current_members_count;
    end;
    PROCEDURE update_family_counts(channel_family_id_in IN NUMBER, 
                                   org_id_in IN NUMBER)
    IS
    BEGIN
        update rhnPrivateChannelFamily
           set current_members = ( channel_family_current_members(channel_family_id_in, org_id_in)),
               fve_current_members = ( cfam_curr_fve_members(channel_family_id_in, org_id_in))
         where org_id = org_id_in
           and channel_family_id = channel_family_id_in;
    END update_family_counts;
    
    PROCEDURE update_group_family_counts(group_label_in IN VARCHAR2,
                                   org_id_in IN NUMBER)
    IS
    BEGIN
        FOR i IN (
                SELECT DISTINCT CFM.channel_family_id, SG.org_id
                 FROM rhnChannelFamilyMembers CFM
                 JOIN rhnServerChannel SC
                   ON SC.channel_id = CFM.channel_id
                 JOIN rhnServerGroupMembers SGM
                   ON SC.server_id = SGM.server_id
                 JOIN rhnServerGroup SG
                   ON SGM.server_group_id = SG.id
                 JOIN rhnServerGroupType SGT
                   ON SG.group_type = SGT.id
                WHERE SGT.label = group_label_in
                  AND SG.org_id = org_id_in
                  AND SGT.is_base = 'Y'
        ) LOOP
            rhn_channel.update_family_counts(i.channel_family_id, i.org_id);
        END LOOP;
    END update_group_family_counts;

    FUNCTION available_chan_subscriptions(channel_id_in IN NUMBER, 
                                          org_id_in IN NUMBER)
    RETURN NUMBER
    IS
            channel_family_id_val NUMBER;
    BEGIN
        SELECT channel_family_id INTO channel_family_id_val
            FROM rhnChannelFamilyMembers
            WHERE channel_id = channel_id_in;
         
            RETURN rhn_channel.available_family_subscriptions(
                           channel_family_id_val, org_id_in);
    END available_chan_subscriptions;

	FUNCTION available_fve_chan_subs(channel_id_in IN NUMBER,
                                          org_id_in IN NUMBER)
    RETURN NUMBER
    IS
        channel_family_id_val NUMBER;

    BEGIN
        SELECT channel_family_id INTO channel_family_id_val
          FROM rhnChannelFamilyMembers
         WHERE channel_id = channel_id_in;

        RETURN rhn_channel.available_fve_family_subs( channel_family_id_val, org_id_in);
    END available_fve_chan_subs;

    procedure unsubscribe_server_from_family(server_id_in in number, 
                                             channel_family_id_in in number)
    is
    begin
        delete
        from    rhnServerChannel rsc
        where   rsc.server_id = server_id_in
            and channel_id in (
                select  rcfm.channel_id
                from    rhnChannelFamilyMembers rcfm
                where   rcfm.channel_family_id = channel_family_id_in);
    end;

    function get_org_id(channel_id_in in number)
    return number
    is
        org_id_out number;
    begin
        select org_id into org_id_out
            from rhnChannel
            where id = channel_id_in;
         
            return org_id_out;
    end get_org_id;
    
    function get_cfam_org_access(cfam_id_in in number, org_id_in in number)
    return number
    is
        cursor  families is
                        select  1
                        from    rhnOrgChannelFamilyPermissions cfp
                        where   cfp.org_id = org_id_in;
    begin
                -- the idea: if we get past this query, 
        -- the user has the role, else catch the exception and return 0
                for family in families loop
                return 1;
                end loop;
                return 0;
    end;

    function get_org_access(channel_id_in in number, org_id_in in number)
    return number
    is
        throwaway number;
    begin
        -- the idea: if we get past this query, 
        -- the org has access to the channel, else catch the exception and return 0
        select distinct 1 into throwaway
          from rhnChannelFamilyMembers CFM,
               rhnOrgChannelFamilyPermissions CFP
         where cfp.org_id = org_id_in
           and CFM.channel_family_id = CFP.channel_family_id
           and CFM.channel_id = channel_id_in
           and (CFP.max_members > 0 or CFP.max_members is null or CFP.org_id = 1);
           
        return 1;
        exception
            when no_data_found
            then
            return 0;
    end;
    
    -- check if a user has a given role, or if such a role is inferrable
    function user_role_check_debug(channel_id_in in number, 
                                   user_id_in in number, 
                                   role_in in varchar2, 
                                   reason_out out varchar2)
    return number
    is
        org_id number;
    begin
        org_id := rhn_user.get_org_id(user_id_in);

        -- channel might be shared
        if role_in = 'subscribe' and
           rhn_channel.shared_user_role_check(channel_id_in, user_id_in, role_in) = 1 then
            return 1;
        end if;
        
        if role_in = 'manage' and 
           NVL(rhn_channel.get_org_id(channel_id_in), -1) <> org_id then
                reason_out := 'channel_not_owned';
               return 0;
            end if;
        
        if role_in = 'subscribe' and 
           rhn_channel.get_org_access(channel_id_in, org_id) = 0 then
                reason_out := 'channel_not_available';
                return 0;
            end if;
        
        -- channel admins have all roles
        if rhn_user.check_role_implied(user_id_in, 'channel_admin') = 1 then
            reason_out := 'channel_admin';
            return 1;
            end if;

        -- the subscribe permission is inferred 
    -- UNLESS the not_globally_subscribable flag is set 
        if role_in = 'subscribe'
        then
            if rhn_channel.org_channel_setting(channel_id_in, 
                       org_id,
                       'not_globally_subscribable') = 0 then
                reason_out := 'globally_subscribable';
                    return 1;
            end if;
        end if;
        
        -- all other roles (manage right now) are explicitly granted    
        reason_out := 'direct_permission';
        return rhn_channel.direct_user_role_check(channel_id_in, 
                                              user_id_in, role_in);
    end;
    
    -- same as above, but with no OUT param; useful in views, etc
    function user_role_check(channel_id_in in number, user_id_in in number, role_in in varchar2)
    return number
    is
        throwaway varchar2(256);
    begin
        return rhn_channel.user_role_check_debug(channel_id_in, user_id_in, role_in, throwaway);
    end;

    --
    -- For multiorg phase II, this function simply checks to see if the user's
    -- has a trust relationship that includes this channel by id.
    --
    function shared_user_role_check(channel_id in number, user_id in number, role in varchar2)
    return number
    is
      n number;
      oid number;
    begin
      oid := rhn_user.get_org_id(user_id);
      select 1 into n
      from rhnSharedChannelView s
      where s.id = channel_id and s.org_trust_id = oid;
      return 1;
      exception
        when no_data_found then
          return 0;
    end;

    -- same as above, but returns 1 if user_id_in is null
    -- This is useful in queries where user_id is not specified
    function loose_user_role_check(channel_id_in in number, user_id_in in number, role_in in varchar2)
    return number
    is
    begin
        if user_id_in is null then
            return 1;
        end if;
        return user_role_check(channel_id_in, user_id_in, role_in);
    end loose_user_role_check;
    
    -- directly checks the table, no inferred permissions
    function direct_user_role_check(channel_id_in in number, user_id_in in number, role_in in varchar2)
    return number
    is
        throwaway number;
    begin
        -- the idea: if we get past this query, the user has the role, else catch the exception and return 0
        select 1 into throwaway
          from rhnChannelPermissionRole CPR,
               rhnChannelPermission CP
         where CP.user_id = user_id_in
           and CP.channel_id = channel_id_in
           and CPR.label = role_in
           and CP.role_id = CPR.id;
           
        return 1;
    exception
        when no_data_found
            then
            return 0;
    end;
    
    -- check if an org has a certain setting
    function org_channel_setting(channel_id_in in number, org_id_in in number, setting_in in varchar2)
    return number
    is
        throwaway number;
    begin
        -- the idea: if we get past this query, the org has the setting, else catch the exception and return 0
        select 1 into throwaway
          from rhnOrgChannelSettingsType OCST,
               rhnOrgChannelSettings OCS
         where OCS.org_id = org_id_in
           and OCS.channel_id = channel_id_in
           and OCST.label = setting_in
           and OCS.setting_id = OCST.id;
           
        return 1;
    exception
        when no_data_found
            then
            return 0;
    end;
    
    FUNCTION channel_priority(channel_id_in IN number) 
    RETURN number
    IS
         channel_name varchar2(256);
         priority number;
         end_of_life_val date;
         org_id_val number;
    BEGIN

        select name, end_of_life, org_id
        into channel_name, end_of_life_val, org_id_val
        from rhnChannel
        where id = channel_id_in;

        if end_of_life_val is not null then
          return -400;
        end if;

        if channel_name like 'Red Hat Enterprise Linux%' or channel_name like 'RHEL%' then
          priority := 1000;
          if channel_name not like '%Beta%' then
            priority := priority + 1000;
          end if;

          priority := priority +
            case
              when channel_name like '%v. 5%' then 600
              when channel_name like '%v. 4%' then 500
              when channel_name like '%v. 3%' then 400
              when channel_name like '%v. 2%' then 300
              when channel_name like '%v. 1%' then 200
              else 0
            end;

          priority := priority +
            case
              when channel_name like 'Red Hat Enterprise Linux (v. 5%' then 60
              when (channel_name like '%AS%' and channel_name not like '%Extras%') then 50
              when (channel_name like '%ES%' and channel_name not like '%Extras%') then 40
              when (channel_name like '%WS%' and channel_name not like '%Extras%') then 30
              when (channel_name like '%Desktop%' and channel_name not like '%Extras%') then 20
              when channel_name like '%Extras%' then 10
              else 0
            end; 

          priority := priority +
            case
              when channel_name like '%)' then 5
              else 0
            end;

          priority := priority +
            case
              when channel_name like '%32-bit x86%' then 4
              when channel_name like '%64-bit Intel Itanium%' then 3
              when channel_name like '%64-bit AMD64/Intel EM64T%' then 2
              else 0
            end;
        elsif channel_name like 'Red Hat Desktop%' then
            priority := 900;

            if channel_name not like '%Beta%' then
               priority := priority + 50;
            end if;
 
          priority := priority +
            case
              when channel_name like '%v. 4%' then 40
              when channel_name like '%v. 3%' then 30
              when channel_name like '%v. 2%' then 20
              when channel_name like '%v. 1%' then 10
              else 0
            end;
            
          priority := priority +
            case
              when channel_name like '%32-bit x86%' then 4
              when channel_name like '%64-bit Intel Itanium%' then 3
              when channel_name like '%64-bit AMD64/Intel EM64T%' then 2
              else 0
            end;
         
        elsif org_id_val is not null then
          priority := 600;
        else
          priority := 500;
        end if;
      
      return -priority;

    end channel_priority;

    -- right now this only does the accounting changes; the cascade
    -- actually does the rhnServerChannel delete.
    procedure delete_server_channels(server_id_in in number)
    is
    begin
        update  rhnPrivateChannelFamily
        set     current_members = current_members -1
        where   org_id in (
                        select  org_id
                        from    rhnServer
                        where   id = server_id_in
                )
                and channel_family_id in (
                        select  rcfm.channel_family_id
                        from    rhnChannelFamilyMembers rcfm,
                                rhnServerChannel rsc
                        where   rsc.server_id = server_id_in
                                and rsc.channel_id = rcfm.channel_id
                and not exists (
                    select 1
                    from
                        rhnChannelFamilyVirtSubLevel cfvsl,
                        rhnSGTypeVirtSubLevel sgtvsl,
                        rhnServerEntitlementView sev,
                        rhnVirtualInstance vi
                    where
                        -- system is a virtual instance
                        vi.virtual_system_id = server_id_in
                        and vi.host_system_id = sev.server_id
                        -- system's host has a virt ent
                        and sev.label in ('virtualization_host',
                                          'virtualization_host_platform')
                        and sev.server_group_type_id = 
                            sgtvsl.server_group_type_id
                        -- the host's virt ent grants a cf virt sub level
                        and sgtvsl.virt_sub_level_id = cfvsl.virt_sub_level_id
                        -- the cf is in that virt sub level
                        and cfvsl.channel_family_id = rcfm.channel_family_id
                    )
                );
    end;

        -- this could certainly be optimized to do updates if needs be
        procedure refresh_newest_package(channel_id_in in number, caller_in in varchar2 := '(unknown)')
        is
        begin
                delete from rhnChannelNewestPackage where channel_id = channel_id_in;
                insert into rhnChannelNewestPackage
                        ( channel_id, name_id, evr_id, package_id, package_arch_id ) 
                        (       select  channel_id,
                                                name_id, evr_id,
                                                package_id, package_arch_id
                                from    rhnChannelNewestPackageView
                                where   channel_id = channel_id_in
                        );
                insert into rhnChannelNewestPackageAudit (channel_id, caller)
                    values (channel_id_in, caller_in);
                update rhnChannel 
                    set last_modified = greatest(sysdate, last_modified + 1/86400)
                    where id = channel_id_in; 
        end;

   procedure update_channel ( channel_id_in in number, invalidate_ss in number := 0, 
                              date_to_use in date := sysdate )
   is

   channel_last_modified date;
   last_modified_value date;

   cursor snapshots is
   select  snapshot_id id
   from    rhnSnapshotChannel
   where   channel_id = channel_id_in;

   begin

      select last_modified
      into channel_last_modified
      from rhnChannel
      where id = channel_id_in;
  
      last_modified_value := date_to_use;

      if last_modified_value <= channel_last_modified then
          last_modified_value := last_modified_value + 1/86400;
      end if;

      update rhnChannel set last_modified = last_modified_value
      where id = channel_id_in;

      if invalidate_ss = 1 then 
        for snapshot in snapshots loop
            update rhnSnapshot
            set invalid = lookup_snapshot_invalid_reason('channel_modified')
            where id = snapshot.id;
        end loop;
      end if;

   end update_channel;

   procedure update_channels_by_package ( package_id_in in number, date_to_use in date := sysdate )
   is

   cursor channels is
   select channel_id
   from rhnChannelPackage
   where package_id = package_id_in
   order by channel_id;

   begin
      for channel in channels loop
         -- we want to invalidate the snapshot assocated with the channel when we
         -- do this b/c we know we've added or removed or packages
         rhn_channel.update_channel ( channel.channel_id, 1, date_to_use );
      end loop;
   end update_channels_by_package;

   
   procedure update_channels_by_errata ( errata_id_in number, date_to_use in date := sysdate )
   is

   cursor channels is
   select channel_id
   from rhnChannelErrata
   where errata_id = errata_id_in
   order by channel_id;

   begin
      for channel in channels loop
         -- we won't invalidate snapshots, b/c just changing the errata associated with
         -- a channel shouldn't invalidate snapshots
         rhn_channel.update_channel ( channel.channel_id, 0, date_to_use );
      end loop;
   end update_channels_by_errata;

   procedure update_needed_cache(channel_id_in in number)
   is
       pragma autonomous_transaction;
                -- update of needed cache ican be commited on a per server basis
                -- b/c failure of update for a server means nothing for the other servers
   begin
      -- we intentionaly do a loop here instead of one huge select
      -- b/c we want to break update into smaller transaction to unblock other sessions
      -- querying rhnServerNeededCache
      for server in (
                select sc.server_id as id
                  from rhnServerChannel sc
                 where sc.channel_id = channel_id_in
      ) loop
         rhn_server.update_needed_cache(server.id);
         commit;
      end loop;
   end update_needed_cache;

END rhn_channel;
/
SHOW ERRORS
  07070100000494000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000004800000000susemanager-schema/upgrade/spacewalk-schema-0.2-to-spacewalk-schema-0.3   07070100000495000081B400000000000000000000000167AE1114000000E8000000000000000000000000000000000000006100000000susemanager-schema/upgrade/spacewalk-schema-0.2-to-spacewalk-schema-0.3/100-rhnCpuArch-i86pc.sql  insert into rhnCpuArch (id, label, name) (
    select rhn_cpu_arch_id_seq.nextval, 'i86pc', 'i86pc'
    from dual
    where not exists (
        select 1
        from rhnCpuArch
        where label = 'i86pc' and name = 'i86pc')
);

07070100000496000081B400000000000000000000000167AE1114000000A9000000000000000000000000000000000000006D00000000susemanager-schema/upgrade/spacewalk-schema-0.2-to-spacewalk-schema-0.3/101-rhnKickstartPackage-position.sql  
alter table rhnKickstartPackage
add position number;

update rhnKickstartPackage
set position = 0;

commit;

alter table rhnKickstartPackage
modify position not null;

   07070100000497000081B400000000000000000000000167AE11140000005B000000000000000000000000000000000000006D00000000susemanager-schema/upgrade/spacewalk-schema-0.2-to-spacewalk-schema-0.3/102-rhnIndexerWork-last_modified.sql  
alter table rhnIndexerWork
add last_modified date default (sysdate) not null;

commit;



 07070100000498000081B400000000000000000000000167AE111400000028000000000000000000000000000000000000006D00000000susemanager-schema/upgrade/spacewalk-schema-0.2-to-spacewalk-schema-0.3/103-drop-rhn-clean-current-state.sql  drop procedure RHN_CLEAN_CURRENT_STATE;
07070100000499000081B400000000000000000000000167AE111400000400000000000000000000000000000000000000007300000000susemanager-schema/upgrade/spacewalk-schema-0.2-to-spacewalk-schema-0.3/103-rhn_config_parameter_data-move_opt.sql    
update rhn_config_parameter set value=replace(value, '/opt/nocpulse/TSDBLocalQueue', '/var/log/nocpulse/TSDBLocalQueue');
update rhn_config_parameter set value=replace(value, '/opt/home/nocpulse/var/', '/var/lib/nocpulse/');
update rhn_config_parameter set value=replace(value, '/opt/home/nocpulse/etc', '/etc/nocpulse');
update rhn_config_parameter set value=replace(value, '/opt/home/nocpulse/bin/', '/usr/bin/');
update rhn_config_parameter set value=replace(value, '/opt/home/nocpulse/.ssh', '/var/lib/nocpulse/.ssh');
update rhn_config_parameter set value=replace(value, '/opt/notification/queue', '/var/lib/nocpulse/queue');
update rhn_config_parameter set value=replace(value, '/opt/notification/var', '/var/log/nocpulse');
update rhn_config_parameter set value=replace(value, '/opt/notification/etc', '/etc/nocpulse');
update rhn_config_parameter set value=replace(value, '/opt/notification/tmp', '/var/tmp');
update rhn_config_parameter set value=replace(value, '/opt/notification', '/var/lib/nocpulse');

commit;
0707010000049A000081B400000000000000000000000167AE111400000021000000000000000000000000000000000000006700000000susemanager-schema/upgrade/spacewalk-schema-0.2-to-spacewalk-schema-0.3/104-drop-is-user-org-admin.sql    drop function is_user_org_admin;
   0707010000049B000081B400000000000000000000000167AE111400000054000000000000000000000000000000000000006500000000susemanager-schema/upgrade/spacewalk-schema-0.2-to-spacewalk-schema-0.3/104-rhn_command-move_opt.sql  
alter table rhn_command
modify command_class default '/var/lib/nocpulse/libexec';

0707010000049C000081B400000000000000000000000167AE11140000007B000000000000000000000000000000000000007400000000susemanager-schema/upgrade/spacewalk-schema-0.2-to-spacewalk-schema-0.3/105-rhn_command_queue_commands-move_opt.sql   
update rhn_command_queue_commands set command_line=replace(command_line, '/opt/home/nocpulse/bin/', '/usr/bin/');
commit;
 0707010000049D000081B400000000000000000000000167AE111400000095000000000000000000000000000000000000006B00000000susemanager-schema/upgrade/spacewalk-schema-0.2-to-spacewalk-schema-0.3/110-rhn_contact_groups-cleanup.sql    
delete from rhn_contact_groups
where not exists (
	select 1
	from rhn_contact_group_members
	where rhn_contact_groups.recid = contact_group_id
	);

   0707010000049E000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000004800000000susemanager-schema/upgrade/spacewalk-schema-0.3-to-spacewalk-schema-0.4   0707010000049F000081B400000000000000000000000167AE1114000003C3000000000000000000000000000000000000006400000000susemanager-schema/upgrade/spacewalk-schema-0.3-to-spacewalk-schema-0.4/112-rhnKSData-drop-name.sql   --
-- Copyright (c) 2008 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
-- $Id$
--

ALTER TABLE rhnKSData
DROP CONSTRAINT rhn_ks_oid_name_uq;

ALTER TABLE rhnKSData
DROP COLUMN name;

ALTER TABLE rhnKsData
ADD cobbler_id varchar(64);

show errors

-- $Log$
-- Revision 2  2008/12/02 16:51:05.2 jsherrill
-- Add cobbler_id column
--
-- Revision 1  2008/10/01 7:01:05  mmccune
-- Removed the unused name column
 070701000004A0000081B400000000000000000000000167AE11140000032C000000000000000000000000000000000000006E00000000susemanager-schema/upgrade/spacewalk-schema-0.3-to-spacewalk-schema-0.4/113-rhnActionKickstart-add-kshost.sql --
-- Copyright (c) 2008 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
-- $Id$
--


ALTER TABLE rhnActionKickstart
 ADD kickstart_host varchar2(256);

show errors

-- $Log$
-- Revision 1  2008/10/29 7:01:05  mmccune
-- add new kickstart_host for koan usage
070701000004A1000081B400000000000000000000000167AE111400000691000000000000000000000000000000000000006000000000susemanager-schema/upgrade/spacewalk-schema-0.3-to-spacewalk-schema-0.4/114-rhnChannelTrust.sql   --
-- Copyright (c) 2008 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--
--
-- $Id$
--

create table
rhnChannelTrust
(
	channel_id	number
			constraint rhn_channel_trust_cid_nn not null
			constraint rhn_channel_trust_cid_fk
				references rhnChannel(id)
                                on delete cascade,
	org_trust_id	number
			constraint rhn_channel_trust_otid_nn not null
			constraint rhn_channel_trust_otid_fk
				references web_customer(id)
                                on delete cascade,
        created         date default (sysdate)
                        constraint rhn_channel_trust_created_nn not null,
        modified        date default (sysdate)
                        constraint rhn_channel_trust_modified_nn not null
)
	storage( pctincrease 1 freelists 16)
	enable row movement
	initrans 32;

create unique index rhn_channel_trust_cid_uq
	on rhnChannelTrust(channel_id,org_trust_id)
	tablespace [[2m_tbs]]
	storage( pctincrease 1 freelists 16)
	initrans 32;

create index rhn_channel_trust_org_trust
	on rhnChannelTrust(org_trust_id)
	tablespace [[2m_tbs]]
	storage( pctincrease 1 freelists 16)
	initrans 32;
   070701000004A2000081B400000000000000000000000167AE1114000005AE000000000000000000000000000000000000006D00000000susemanager-schema/upgrade/spacewalk-schema-0.3-to-spacewalk-schema-0.4/115-rhnChannel-add-maint-columns.sql  --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--
alter trigger rhn_channel_mod_trig disable;
ALTER TABLE rhnChannel
ADD channel_access  varchar2(10) default 'private';
alter trigger rhn_channel_mod_trig enable;

ALTER TABLE rhnChannel
ADD maint_name  varchar2(128);

ALTER TABLE rhnChannel
ADD maint_email  varchar2(128);

ALTER TABLE rhnChannel
ADD maint_phone  varchar2(128);

ALTER TABLE rhnChannel
ADD support_policy  varchar2(256);



create index rhn_channel_access_idx
	on rhnChannel(channel_access)
	tablespace [[64k_tbs]]
	storage ( freelists 16 )
	initrans 32
	nologging;

create or replace trigger rhn_channel_access_trig
after update on rhnChannel
for each row
begin
   if :old.channel_access = 'protected' and
      :new.channel_access != 'protected'
   then
      delete from rhnChannelTrust where channel_id = :old.id;
   end if;
end;
/
show errors

  070701000004A3000081B400000000000000000000000167AE1114000005EC000000000000000000000000000000000000005F00000000susemanager-schema/upgrade/spacewalk-schema-0.3-to-spacewalk-schema-0.4/116-rhnTrustedOrgs.sql    --
-- Copyright (c) 2008 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--
--
-- $Id$
--

create table
rhnTrustedOrgs
(
	org_id		number
			constraint rhn_trusted_orgs_oid_nn not null
			constraint rhn_trusted_orgs_oid_fk
				references web_customer(id)
                                on delete cascade,
	org_trust_id	number
			constraint rhn_trusted_orgs_otid_nn not null
			constraint rhn_trusted_orgs_otid_fk
				references web_customer(id)
                                on delete cascade,
        created         date default (sysdate)
                        constraint rhn_trusted_orgs_created_nn not null,
        modified        date default (sysdate)
                        constraint rhn_trusted_orgs_modified_nn not null
)
	storage( pctincrease 1 freelists 16)
	enable row movement
	initrans 32;

create unique index rhn_trusted_orgs_oid_uq
	on rhnTrustedOrgs(org_id,org_trust_id)
	tablespace [[2m_tbs]]
	storage( pctincrease 1 freelists 16)
	initrans 32;
070701000004A4000081B400000000000000000000000167AE11140000067A000000000000000000000000000000000000005E00000000susemanager-schema/upgrade/spacewalk-schema-0.3-to-spacewalk-schema-0.4/117-rhnAllowTrust.sql --
-- Copyright (c) 2008 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--
--
-- $Id$
--

create table
rhnAllowTrust
(
	org_id		number
			constraint rhn_allow_trust_oid_nn not null
			constraint rhn_allow_trust_oid_fk
				references web_customer(id)
                                on delete cascade,
        channel_flag    char(1) default('N')
                        constraint rhn_allow_trust_channelflg_nn not null
                        constraint rhn_allow_trust_channelflg_ck
                                check (channel_flag in ('N','Y')),
        migration_flag  char(1) default('N')
                        constraint rhn_allow_trust_migrflg_nn not null
                        constraint rhn_allow_trust_migrflg_ck
                                check (migration_flag in ('N','Y')),
        created         date default (sysdate)
                        constraint rhn_allow_trust_created_nn not null,
        modified        date default (sysdate)
                        constraint rhn_allow_trust_modified_nn not null
)
	storage( pctincrease 1 freelists 16)
	enable row movement
	initrans 32;
  070701000004A5000081B400000000000000000000000167AE11140000072C000000000000000000000000000000000000006400000000susemanager-schema/upgrade/spacewalk-schema-0.3-to-spacewalk-schema-0.4/118-rhnSystemMigrations.sql   --
-- Copyright (c) 2008 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--
--
-- $Id$
--

create table
rhnSystemMigrations
(
        org_id_to       number
                        constraint rhn_sys_mig_oidto_nn not null
                        constraint rhn_sys_mig_oidto_fk
                                references web_customer(id),
        org_id_from     number
                        constraint rhn_sys_mig_oidfrm_nn not null
                        constraint rhn_sys_mig_oidfrm_fk
                                references web_customer(id),
        server_id       number
                        constraint rhn_sys_mig_sid_nn not null
                        constraint rhn_sys_mig_sid_fk
                                references rhnServer(id)
                                 on delete cascade,
        migrated        date default (sysdate)
                        constraint rhn_sys_mig_migrated_nn not null
)
        storage ( pctincrease 1 freelists 16 )
        enable row movement
        initrans 32;

create index rsm_org_id_to_idx
        on rhnSystemMigrations ( org_id_to )
        storage ( freelists 16 )
        initrans 32;


create index rsm_org_id_from_idx
        on rhnSystemMigrations ( org_id_from )
        storage ( freelists 16 )
        initrans 32;
070701000004A6000081B400000000000000000000000167AE1114000003FC000000000000000000000000000000000000006500000000susemanager-schema/upgrade/spacewalk-schema-0.3-to-spacewalk-schema-0.4/119-rhnSharedChannelView.sql  CREATE OR REPLACE VIEW RHNSHAREDCHANNELVIEW
AS
SELECT 
   CH.ID,
   CH.PARENT_CHANNEL,
   CH.ORG_ID,
   CH.CHANNEL_ARCH_ID,
   CH.LABEL,
   CH.BASEDIR,
   CH.NAME,
   CH.SUMMARY,
   CH.DESCRIPTION,
   CH.PRODUCT_NAME_ID,
   CH.GPG_KEY_URL,
   CH.GPG_KEY_ID,
   CH.GPG_KEY_FP,
   CH.END_OF_LIFE,
   CH.RECEIVING_UPDATES,
   CH.LAST_MODIFIED,
   CH.CHANNEL_PRODUCT_ID,
   CH.CREATED,
   CH.MODIFIED,
   CH.CHANNEL_ACCESS,
   TR.ORG_TRUST_ID
FROM RHNCHANNEL CH,
     RHNTRUSTEDORGS TR
WHERE CH.ORG_ID = TR.ORG_ID AND
      CH.CHANNEL_ACCESS = 'public'
UNION
SELECT
   CH.ID,
   CH.PARENT_CHANNEL,
   CH.ORG_ID,
   CH.CHANNEL_ARCH_ID,
   CH.LABEL,
   CH.BASEDIR,
   CH.NAME,
   CH.SUMMARY,
   CH.DESCRIPTION,
   CH.PRODUCT_NAME_ID,
   CH.GPG_KEY_URL,
   CH.GPG_KEY_ID,
   CH.GPG_KEY_FP,
   CH.END_OF_LIFE,
   CH.RECEIVING_UPDATES,
   CH.LAST_MODIFIED,
   CH.CHANNEL_PRODUCT_ID,
   CH.CREATED,
   CH.MODIFIED,
   CH.CHANNEL_ACCESS,
   TR.ORG_TRUST_ID
FROM RHNCHANNEL CH,
     RHNCHANNELTRUST TR
WHERE CH.ID = TR.CHANNEL_ID
/
070701000004A7000081B400000000000000000000000167AE1114000007BA000000000000000000000000000000000000005F00000000susemanager-schema/upgrade/spacewalk-schema-0.3-to-spacewalk-schema-0.4/120-rhnUserChannel.sql    --
-- Copyright (c) 2008 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--

create or replace view rhnUserChannel
as
select
   cfp.user_id,
   cfp.org_id,
   cfm.channel_id,
   'manage' role
from rhnChannelFamilyMembers cfm,
      rhnUserChannelFamilyPerms cfp
where
   cfp.channel_family_id = cfm.channel_family_id and
   rhn_channel.user_role_check(cfm.channel_id, cfp.user_id, 'manage') = 1
union all
select
   cfp.user_id,
   cfp.org_id,
   cfm.channel_id,
   'subscribe' role
from rhnChannelFamilyMembers cfm,
      rhnUserChannelFamilyPerms cfp
where
   cfp.channel_family_id = cfm.channel_family_id and
   rhn_channel.user_role_check(cfm.channel_id, cfp.user_id, 'subscribe') = 1
union all
select
   w.id as user_id,
   w.org_id,
   s.id as channel_id,
   'subscribe' role
from rhnSharedChannelView s,
      web_contact w
where
   w.org_id = s.org_trust_id and
   rhn_channel.user_role_check(s.id, w.id, 'subscribe') = 1;

--
--
-- Revision 1.15  2004/04/28 14:57:02  pjones
-- bugzilla: 119698 -- Go back to a split version of this, like in 1.13.  We
-- don't need the distinct though; nothing can show up in either table twice.
--
-- Revision 1.13  2004/04/14 15:58:39  pjones
-- bugzilla: none -- make rhnUserChannel work without org_id... (duh...)
--
-- Revision 1.12  2004/04/14 00:09:24  pjones
-- bugzilla: 120761 -- split rhnChannelPermissions into two tables, eliminating
-- a frequent full table scan
--
  070701000004A8000081B400000000000000000000000167AE111400002468000000000000000000000000000000000000006000000000susemanager-schema/upgrade/spacewalk-schema-0.3-to-spacewalk-schema-0.4/121-rhn_channel.pks.sql   --
-- Copyright (c) 2008 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--

CREATE OR REPLACE
PACKAGE rhn_channel
IS
	version varchar2(100) := '';

    CURSOR server_base_subscriptions(server_id_in NUMBER) IS
    	   SELECT C.id
	     FROM rhnChannel C, rhnServerChannel SC
	    WHERE C.id = SC.channel_id
	      AND SC.server_id = server_id_in
	      AND C.parent_channel IS NULL;
	      
    CURSOR check_server_subscription(server_id_in NUMBER, channel_id_in NUMBER) IS 
           SELECT channel_id 
	     FROM rhnServerChannel 
	    WHERE server_id = server_id_in 
	      AND channel_id = channel_id_in;

    CURSOR check_server_parent_membership(server_id_in NUMBER, channel_id_in NUMBER) IS
    	   SELECT C.id
	     FROM rhnChannel C, rhnServerChannel SC
	    WHERE C.parent_channel = channel_id_in
	      AND C.id = SC.channel_id
	      AND SC.server_id = server_id_in;
	    
    CURSOR channel_family_perm_cursor(channel_family_id_in NUMBER, org_id_in NUMBER) IS
           SELECT *
	     FROM rhnOrgChannelFamilyPermissions
	    WHERE channel_family_id = channel_family_id_in
	      AND org_id = org_id_in;

    PROCEDURE license_consent(channel_id_in IN NUMBER, user_id_in IN NUMBER, server_id_in IN NUMBER);
    FUNCTION get_license_path(channel_id_in IN NUMBER) RETURN VARCHAR2;

    PROCEDURE unsubscribe_server(server_id_in IN NUMBER, channel_id_in NUMBER, immediate_in NUMBER := 1, unsubscribe_children_in number := 0,
                                 deleting_server in number := 0 );
    PROCEDURE subscribe_server(server_id_in IN NUMBER, channel_id_in NUMBER, immediate_in NUMBER := 1, user_id_in number := null);

    function can_server_consume_virt_channl(
        server_id_in IN NUMBER,
        family_id_in in number)
    return number;

    FUNCTION guess_server_base(server_id_in IN NUMBER) RETURN NUMBER;

    FUNCTION base_channel_for_release_arch(release_in in varchar2, 
	server_arch_in in varchar2, org_id_in in number := -1, 
	user_id_in in number := null) RETURN number;

    FUNCTION base_channel_rel_archid(release_in in varchar2, 
	server_arch_id_in in number, org_id_in in number := -1, 
	user_id_in in number := null) RETURN number;

    FUNCTION channel_priority(channel_id_in in number) RETURN number;
    
    PROCEDURE bulk_subscribe_server(channel_id_in IN NUMBER, set_label_in IN VARCHAR2, set_uid_in IN NUMBER);
    PROCEDURE bulk_unsubscribe_server(channel_id_in IN NUMBER, set_label_in IN VARCHAR2, set_uid_in IN NUMBER);
    
    PROCEDURE bulk_server_base_change(channel_id_in IN NUMBER, set_label_in IN VARCHAR2, set_uid_in IN NUMBER);
    procedure bulk_server_basechange_from(
	set_label_in in varchar2,
	set_uid_in in number,
	old_channel_id_in in number,
	new_channel_id_in in number);

    procedure bulk_guess_server_base(
	set_label_in in varchar2,
	set_uid_in in number);

    procedure bulk_guess_server_base_from(
	set_label_in in varchar2,
	set_uid_in in number,
	channel_id_in in number);

    PROCEDURE clear_subscriptions(server_id_in IN NUMBER, deleting_server in number := 0 );
    
    FUNCTION available_family_subscriptions(channel_family_id_in IN NUMBER, org_id_in IN NUMBER) RETURN NUMBER;

    function channel_family_current_members(channel_family_id_in IN NUMBER,
                                            org_id_in IN NUMBER)
    return number;

    PROCEDURE update_family_counts(channel_family_id_in IN NUMBER, org_id_in IN NUMBER);
    FUNCTION family_for_channel(channel_id_in IN NUMBER) RETURN NUMBER;

    FUNCTION available_chan_subscriptions(channel_id_in IN NUMBER, org_id_in IN NUMBER) RETURN NUMBER;

    procedure entitle_customer(customer_id_in in number, channel_family_id_in in number, quantity_in in number);
    procedure set_family_maxmembers(customer_id_in in number, channel_family_id_in in number, quantity_in in number);
    procedure unsubscribe_server_from_family(server_id_in in number, channel_family_id_in in number);

    procedure delete_server_channels(server_id_in in number);
    procedure refresh_newest_package(channel_id_in in number, caller_in in varchar2 := '(unknown)');
    
    function get_org_id(channel_id_in in number) return number;
    PRAGMA RESTRICT_REFERENCES(get_org_id, WNDS, RNPS, WNPS);

    function get_org_access(channel_id_in in number, org_id_in in number) return number;
    PRAGMA RESTRICT_REFERENCES(get_org_access, WNDS, RNPS, WNPS);
    
    function get_cfam_org_access(cfam_id_in in number, org_id_in in number) return number;

    function user_role_check_debug(channel_id_in in number, user_id_in in number, role_in in varchar2, reason_out out varchar2)
    	RETURN NUMBER;
    PRAGMA RESTRICT_REFERENCES(user_role_check_debug, WNDS, RNPS, WNPS);

    function user_role_check(channel_id_in in number, user_id_in in number, role_in in varchar2)
    	RETURN NUMBER;
    PRAGMA RESTRICT_REFERENCES(user_role_check, WNDS, RNPS, WNPS);
    
    function loose_user_role_check(channel_id_in in number, user_id_in in number, role_in in varchar2)
    	RETURN NUMBER;
    PRAGMA RESTRICT_REFERENCES(loose_user_role_check, WNDS, RNPS, WNPS);

    function direct_user_role_check(channel_id_in in number, user_id_in in number, role_in in varchar2)
    	RETURN NUMBER;
    PRAGMA RESTRICT_REFERENCES(direct_user_role_check, WNDS, RNPS, WNPS);

    function shared_user_role_check(channel_id in number, user_id in number, role in varchar2)
    	RETURN NUMBER;
    PRAGMA RESTRICT_REFERENCES(shared_user_role_check, WNDS, RNPS, WNPS);

    function org_channel_setting(channel_id_in in number, org_id_in in number, setting_in in varchar2)
    	RETURN NUMBER;

    PROCEDURE update_channel ( channel_id_in in number, invalidate_ss in number := 0, 
                               date_to_use in date := sysdate );

    PROCEDURE  update_channels_by_package ( package_id_in in number, date_to_use in date := sysdate );

     PROCEDURE update_channels_by_errata ( errata_id_in number, date_to_use in date := sysdate );


    PRAGMA RESTRICT_REFERENCES(org_channel_setting, WNDS, RNPS, WNPS);

END rhn_channel;
/
SHOW ERRORS

--
-- Revision 1.37  2004/04/14 00:09:24  pjones
-- bugzilla: 120761 -- split rhnChannelPermissions into two tables, eliminating
-- a frequent full table scan
--
-- Revision 1.36  2004/03/26 18:11:32  rbb
-- Bugzilla:  114057
--
-- Add a script to determine channel priority.
--
-- Revision 1.35  2004/02/17 20:16:52  pjones
-- bugzilla: none -- add cvs tags into the package as long as we're touching
-- it anyway
--
-- Revision 1.34  2003/11/13 18:13:09  cturner
-- pragmas can now return now that rhn_user pragmas are fixed
--
-- Revision 1.32  2003/09/22 21:00:40  cturner
-- add method for easy acl check
--
-- Revision 1.31  2003/09/17 22:14:11  misa
-- bugzilla: 103639  Changes to allow me to move the base channel guess into plsql
--
-- Revision 1.30  2003/07/24 16:44:16  misa
-- bugzilla: none  A function more usable on the rhnapp side
--
-- Revision 1.29  2003/07/24 14:00:17  misa
-- bugzilla: none  PRAGMA RESTRICT_REFERENCES good
--
-- Revision 1.28  2003/07/23 21:59:19  cturner
-- rework how rhnUserChannel works; move to plsql for speed and maintenance
--
-- Revision 1.27  2003/07/21 17:49:12  pjones
-- bugzilla: none
--
-- add optional user for subscribe_server
--
-- Revision 1.26  2002/12/19 18:13:42  misa
-- Added caller with a default value
--
-- Revision 1.25  2002/12/11 22:18:46  pjones
-- rhnChannelNewestPackage
--
-- Revision 1.24  2002/11/21 22:08:11  pjones
-- make unsubscribe_channels have a "unsubscribe_children_in number := 0"
-- argument so that you can tell it to unsubscribe children.
--
-- Also, make it raise an exception instead of silent failure in the
-- other case.
--
-- Revision 1.23  2002/11/18 17:20:50  pjones
-- this should have gone back too
--
-- Revision 1.22  2002/11/13 23:16:18  pjones
-- lookup_*_arch()
--
-- Revision 1.21  2002/10/07 20:01:59  rnorwood
-- guess base channel for ssm and single system
--
-- Revision 1.20  2002/10/02 19:21:03  bretm
-- o  3rd party channel schema changes, no more clobs...
--
-- Revision 1.19  2002/09/20 19:21:58  bretm
-- o  more 3rd party channel stuff...
--
-- Revision 1.18  2002/06/12 22:33:03  pjones
-- procedure bulk_guess_server_base_from(
--     set_label_in in varchar2,
--     set_uid_in in number,
--     channel_id_in in number);
--
-- for bretm
--
-- Revision 1.17  2002/06/12 22:12:25  pjones
-- procedure bulk_guess_server_base(
--     set_label_in in varchar2,
--     set_uid_in in number);
--
-- for bretm
--
-- Revision 1.16  2002/06/12 19:37:55  pjones
-- bulk_server_basechange_from(
-- 	set_label_in in varchar2,
-- 	set_uid_in in number,
-- 	old_channel_id_in in number,
-- 	new_channel_id_in in number
-- );
--
-- for bretm
--
-- Revision 1.15  2002/05/10 22:08:22  pjones
-- id/log
--
070701000004A9000081B400000000000000000000000167AE11140000C7DB000000000000000000000000000000000000006000000000susemanager-schema/upgrade/spacewalk-schema-0.3-to-spacewalk-schema-0.4/122-rhn_channel.pkb.sql   --
-- Copyright (c) 2008 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--

CREATE OR REPLACE
PACKAGE BODY rhn_channel
IS
        body_version varchar2(100) := '';

    -- Cursor that fetches all the possible base channels for a
    -- (server_arch_id, release, org_id) combination
        cursor  base_channel_cursor(
                release_in in varchar2,
                server_arch_id_in in number,
                org_id_in in number
        ) return rhnChannel%ROWTYPE is
                select distinct c.*
                from    rhnDistChannelMap                       dcm,
                                rhnServerChannelArchCompat      scac,
                                rhnChannel                                      c,
                                rhnChannelPermissions           cp
                where   cp.org_id = org_id_in
                        and cp.channel_id = c.id
                        and c.parent_channel is null
                        and c.id = dcm.channel_id
                        and c.channel_arch_id = dcm.channel_arch_id
                        and dcm.release = release_in
                        and scac.server_arch_id = server_arch_id_in
                        and scac.channel_arch_id = c.channel_arch_id;

    FUNCTION get_license_path(channel_id_in IN NUMBER)
    RETURN VARCHAR2
    IS
        license_val VARCHAR2(1000);
    BEGIN
        SELECT CFL.license_path INTO license_val
          FROM rhnChannelFamilyLicense CFL, rhnChannelFamilyMembers CFM
         WHERE CFM.channel_id = channel_id_in
           AND CFM.channel_family_id = CFL.channel_family_id;
    
        RETURN license_val;

    EXCEPTION
        WHEN NO_DATA_FOUND
            THEN
            RETURN NULL;
    END get_license_path;


    PROCEDURE license_consent(channel_id_in IN NUMBER, user_id_in IN NUMBER, server_id_in IN NUMBER)
    IS
        channel_family_id_val NUMBER;
    BEGIN
        channel_family_id_val := rhn_channel.family_for_channel(channel_id_in);
        IF channel_family_id_val IS NULL
        THEN
            rhn_exception.raise_exception('channel_subscribe_no_family');
        END IF;
        
        IF rhn_channel.get_license_path(channel_id_in) IS NULL
        THEN
            rhn_exception.raise_exception('channel_consent_no_license');
        END IF;
        
        INSERT INTO rhnChannelFamilyLicenseConsent (channel_family_id, user_id, server_id)
        VALUES (channel_family_id_val, user_id_in, server_id_in);
    END license_consent;

    PROCEDURE subscribe_server(server_id_in IN NUMBER, channel_id_in NUMBER, immediate_in NUMBER := 1, user_id_in in number := null)
    IS
        channel_parent_val      rhnChannel.parent_channel%TYPE;
        parent_subscribed       BOOLEAN;
        server_has_base_chan    BOOLEAN;
        server_already_in_chan  BOOLEAN;
        channel_family_id_val   NUMBER;
        server_org_id_val       NUMBER;
        available_subscriptions NUMBER;
        consenting_user         NUMBER;
        allowed                 number := 0;
        current_members_val     number;
    BEGIN
        if user_id_in is not null then
            allowed := rhn_channel.user_role_check(channel_id_in, user_id_in, 'subscribe');
        else
            allowed := 1;
        end if;

        if allowed = 0 then
            rhn_exception.raise_exception('no_subscribe_permissions');
        end if;


        SELECT parent_channel INTO channel_parent_val FROM rhnChannel WHERE id = channel_id_in;

        IF channel_parent_val IS NOT NULL
        THEN    
            -- child channel; if attempting to cross-subscribe a child to the wrong base, silently ignore
            parent_subscribed := FALSE;    

            FOR check_subscription IN check_server_subscription(server_id_in, channel_parent_val)
            LOOP
                parent_subscribed := TRUE;
            END LOOP check_subscription;
        
            IF NOT parent_subscribed
            THEN
                RETURN;
            END IF;
        ELSE
            -- base channel
            server_has_base_chan := FALSE;
            FOR base IN server_base_subscriptions(server_id_in)
            LOOP
                server_has_base_chan := TRUE;
            END LOOP base;
            
            IF server_has_base_chan
            THEN
                rhn_exception.raise_exception('channel_server_one_base');
            END IF;
        END IF;
    
        FOR check_subscription IN check_server_subscription(server_id_in, channel_id_in)
        LOOP
            server_already_in_chan := TRUE;
        END LOOP check_subscription;
    
        IF server_already_in_chan
        THEN
            RETURN;
        END IF;
        
        channel_family_id_val := rhn_channel.family_for_channel(channel_id_in);
        IF channel_family_id_val IS NULL
        THEN
            rhn_exception.raise_exception('channel_subscribe_no_family');
        END IF;

        --
        -- Use the org_id of the server only if the org_id of the channel = NULL.
        -- This is required for subscribing to shared channels.
        --
        SELECT NVL(org_id, (SELECT org_id FROM rhnServer WHERE id = server_id_in))
          INTO server_org_id_val
          FROM rhnChannel
         WHERE id = channel_id_in;
         
        select current_members 
        into current_members_val
        from rhnPrivateChannelFamily
        where org_id = server_org_id_val and channel_family_id = channel_family_id_val
        for update of current_members;

        available_subscriptions := rhn_channel.available_family_subscriptions(channel_family_id_val, server_org_id_val);
        
        IF available_subscriptions IS NULL OR 
           available_subscriptions > 0 or
           can_server_consume_virt_channl(server_id_in, channel_family_id_val) = 1
        THEN
        
            IF rhn_channel.get_license_path(channel_id_in) IS NOT NULL
            THEN
                BEGIN
                
                SELECT user_id INTO consenting_user
                  FROM rhnChannelFamilyLicenseConsent
                 WHERE channel_family_id = channel_family_id_val
                   AND server_id = server_id_in;
                
                EXCEPTION
                    WHEN NO_DATA_FOUND THEN
                        rhn_exception.raise_exception('channel_subscribe_no_consent');
                END;
            END IF;
        
            insert into rhnServerHistory (id,server_id,summary,details) (
                select  rhn_event_id_seq.nextval,
                        server_id_in,
                        'subscribed to channel ' || SUBSTR(c.label, 0, 106),
                        c.label
                from    rhnChannel c
                where   c.id = channel_id_in
            );
            UPDATE rhnServer SET channels_changed = sysdate WHERE id = server_id_in;
            INSERT INTO rhnServerChannel (server_id, channel_id) VALUES (server_id_in, channel_id_in);

            rhn_channel.update_family_counts(channel_family_id_val, server_org_id_val);
            queue_server(server_id_in, immediate_in);
        ELSE
            rhn_exception.raise_exception('channel_family_no_subscriptions');
        END IF;
            
    END subscribe_server;
    
    function can_server_consume_virt_channl(
        server_id_in in number,
        family_id_in in number )
    return number
    is

        cursor server_virt_families is
            select vi.virtual_system_id, cfvsl.channel_family_id
            from
                rhnChannelFamilyVirtSubLevel cfvsl,
                rhnSGTypeVirtSubLevel sgtvsl,
                rhnVirtualInstance vi
            where
                vi.virtual_system_id = server_id_in 
                and sgtvsl.virt_sub_level_id = cfvsl.virt_sub_level_id
                and cfvsl.channel_family_id = family_id_in
                and exists (
                    select 1
                    from rhnServerEntitlementView sev
                    where vi.host_system_id = sev.server_id
                    and sev.server_group_type_id = sgtvsl.server_group_type_id );
    begin

        for server_virt_family in server_virt_families loop
            return 1;
        end loop;

        return 0;

    end;


    PROCEDURE bulk_subscribe_server(channel_id_in IN NUMBER, set_label_in IN VARCHAR2, set_uid_in IN NUMBER)
    IS
    BEGIN
        FOR server IN rhn_set.set_iterator(set_label_in, set_uid_in)
        LOOP
            rhn_channel.subscribe_server(server.element, channel_id_in, 0, set_uid_in);
        END LOOP server;
    END bulk_subscribe_server;

    PROCEDURE bulk_server_base_change(channel_id_in IN NUMBER, set_label_in IN VARCHAR2, set_uid_in IN NUMBER)
    IS
    BEGIN
        FOR server IN rhn_set.set_iterator(set_label_in, set_uid_in)
        LOOP
            IF rhn_server.can_change_base_channel(server.element) = 1
            THEN
                rhn_channel.clear_subscriptions(TO_NUMBER(server.element));
                rhn_channel.subscribe_server(server.element, channel_id_in, 0, set_uid_in);
            END IF;
        END LOOP server;
    END bulk_server_base_change;

    procedure bulk_server_basechange_from(
        set_label_in in varchar2,
        set_uid_in in number,
        old_channel_id_in in number,
        new_channel_id_in in number
    ) is
    cursor servers is
        select  sc.server_id id
        from    rhnChannel nc,
                rhnServerChannelArchCompat scac,
                rhnServer s,
                rhnChannel oc,
                rhnServerChannel sc,
                rhnSet st
        where   1=1
            -- first, find the servers we're looking for.
            and st.label = set_label_in
            and st.user_id = set_uid_in
            and st.element = sc.server_id
            -- now, filter out anything that's not in the
            -- old base channel.
            and sc.channel_id = old_channel_id_in
            and sc.channel_id = oc.id
            and oc.parent_channel is null
            -- now, see if it's compatible with the new base channel
            and nc.id = new_channel_id_in
            and nc.parent_channel is null
            and sc.server_id = s.id
            and s.server_arch_id = scac.server_arch_id
            and scac.channel_arch_id = nc.channel_arch_id;
    begin
        for s in servers loop
            insert into rhnSet (
                    user_id, label, element
                ) values (
                    set_uid_in,
                    set_label_in || 'basechange', 
                    s.id
                );
        end loop channel;
        bulk_server_base_change(new_channel_id_in,
                                set_label_in || 'basechange',
                                set_uid_in);
        delete from rhnSet
            where   label = set_label_in||'basechange'
                and user_id = set_uid_in;
    end bulk_server_basechange_from;

    procedure bulk_guess_server_base(
        set_label_in in varchar2,
        set_uid_in in number
    ) is
        channel_id number;
    begin
        for server in rhn_set.set_iterator(set_label_in, set_uid_in)
        loop
            -- anything that doesn't work, we just ignore
            begin
                if rhn_server.can_change_base_channel(server.element) = 1
                then
                    channel_id := guess_server_base(TO_NUMBER(server.element));
                    rhn_channel.clear_subscriptions(TO_NUMBER(server.element));
                    rhn_channel.subscribe_server(TO_NUMBER(server.element), channel_id, 0, set_uid_in);
                end if;
            exception when others then
                null;
            end;
        end loop server;
    end;

    function guess_server_base(
        server_id_in in number
    ) RETURN number is
        cursor server_cursor is
            select s.server_arch_id, s.release, s.org_id
              from rhnServer s
             where s.id = server_id_in;
    begin
        for s in server_cursor loop
            for channel in base_channel_cursor(s.release,
                s.server_arch_id, s.org_id) 
            loop
                return channel.id;
            end loop base_channel_cursor;
        end loop server_cursor;
        -- Server not found, or no base channel applies to it
        return null;
    end;

    -- Private function
    function normalize_server_arch(server_arch_in in varchar2)
    return varchar2
    deterministic
    is
        suffix VARCHAR2(128) := '-redhat-linux';
        suffix_len NUMBER := length(suffix);
    begin
        if server_arch_in is NULL then
            return NULL;
        end if;
        if instr(server_arch_in, '-') > 0
        then
            -- Suffix already present
            return server_arch_in;
        end if;
        return server_arch_in || suffix;
    end normalize_server_arch;

    --
    --
    -- Raises: 
    --   server_arch_not_found
    --   no_subscribe_permissions
    function base_channel_for_release_arch(
        release_in in varchar2,
        server_arch_in in varchar2,
        org_id_in in number := -1,
        user_id_in in number := null
    ) return number is
        server_arch varchar2(256) := normalize_server_arch(server_arch_in);
        server_arch_id number;
    begin
        -- Look up the server arch
        begin
            select id
              into server_arch_id
              from rhnServerArch
             where label = server_arch;
        exception
            when no_data_found then
                rhn_exception.raise_exception('server_arch_not_found');
        end;
        return base_channel_rel_archid(release_in, server_arch_id,
            org_id_in, user_id_in);
    end base_channel_for_release_arch;

    function base_channel_rel_archid(
        release_in in varchar2,
        server_arch_id_in in number,
        org_id_in in number := -1,
        user_id_in in number := null
    ) return number is
        denied_channel_id number := null;
        valid_org_id number := org_id_in;
        valid_user_id number := user_id_in;
        channel_subscribable number;
    begin
        if org_id_in = -1 and user_id_in is not null then
            -- Get the org id from the user id
            begin
                select org_id
                  into valid_org_id
                  from web_contact
                 where id = user_id_in;
            exception
                when no_data_found then
                    -- User doesn't exist
                    -- XXX Only list public stuff for now
                    valid_user_id := null;
                    valid_org_id := -1;
            end;
        end if;

        for c in base_channel_cursor(release_in, server_arch_id_in, valid_org_id)
        loop
            -- This row is a possible match
            if valid_user_id is null then
                -- User ID not specified, so no user to channel permissions to
                -- check
                return c.id;
            end if;

            -- Check user to channel permissions
            select loose_user_role_check(c.id, user_id_in, 'subscribe')
              into channel_subscribable
              from dual;

            if channel_subscribable = 1 then
                return c.id;
            end if;
                
            -- Base channel exists, but is not subscribable; keep trying
            denied_channel_id := c.id;
        end loop base_channel_fetch;
        
        if denied_channel_id is not null then
            rhn_exception.raise_exception('no_subscribe_permissions');
        end if;
        -- No base channel applies
        return NULL;
    end base_channel_rel_archid;

    procedure bulk_guess_server_base_from(
        set_label_in in varchar2,
        set_uid_in in number,
        channel_id_in in number
    ) is
        cursor channels(server_id_in in number) is
            select      rsc.channel_id
            from        rhnServerChannel rsc,
                        rhnChannel rc
            where       server_id_in = rsc.server_id
                        and rsc.channel_id = rc.id
                        and rc.parent_channel is null;
    begin
        for server in rhn_set.set_iterator(set_label_in, set_uid_in)
        loop
            for channel in channels(server.element)
            loop
                if channel.channel_id = channel_id_in
                then
                    insert into rhnSet (user_id, label, element) values (set_uid_in, set_label_in || 'baseguess', server.element);
                end if;
            end loop channel;
        end loop server;
        bulk_guess_server_base(set_label_in||'baseguess',set_uid_in);
        delete from rhnSet where label = set_label_in||'baseguess' and user_id = set_uid_in;
    end;


    PROCEDURE clear_subscriptions(server_id_in IN NUMBER, deleting_server IN NUMBER := 0 )
    IS
        cursor server_channels(server_id_in in number) is
                select  s.org_id, sc.channel_id, cfm.channel_family_id
                from    rhnServer s,
                        rhnServerChannel sc,
                        rhnChannelFamilyMembers cfm
                where   s.id = server_id_in
                        and s.id = sc.server_id
                        and sc.channel_id = cfm.channel_id;
    BEGIN
        for channel in server_channels(server_id_in)
        loop
                unsubscribe_server(server_id_in, channel.channel_id, 1, 1, deleting_server);
                rhn_channel.update_family_counts(channel.channel_family_id, channel.org_id);
        end loop channel;
    END clear_subscriptions;

    PROCEDURE unsubscribe_server(server_id_in IN NUMBER, channel_id_in NUMBER, immediate_in NUMBER := 1, unsubscribe_children_in number := 0,
                                 deleting_server IN NUMBER := 0 )
    IS
        channel_family_id_val   NUMBER;
        server_org_id_val       NUMBER;
        available_subscriptions NUMBER; 
        server_already_in_chan  BOOLEAN;
        cursor  channel_family_is_proxy(channel_family_id_in in number) is
                select  1
                from    rhnChannelFamily
                where   id = channel_family_id_in
                    and label = 'rhn-proxy';
        cursor  channel_family_is_satellite(channel_family_id_in in number) is
                select  1
                from    rhnChannelFamily
                where   id = channel_family_id_in
                    and label = 'rhn-satellite';
        -- this is *EXACTLY* like check_server_parent_membership, but if we recurse
        -- with the package-level one, we get a "cursor already open", so we need a
        -- copy on our call stack instead.  GROAN.
        cursor local_chk_server_parent_memb (
                        server_id_in number,
                        channel_id_in number ) is
                select  c.id
                from    rhnChannel                      c,
                                rhnServerChannel        sc
                where   1=1
                        and c.parent_channel = channel_id_in
                        and c.id = sc.channel_id
                        and sc.server_id = server_id_in;
    BEGIN
        FOR child IN local_chk_server_parent_memb(server_id_in, channel_id_in)
        LOOP
            if unsubscribe_children_in = 1 then
                unsubscribe_server(server_id_in => server_id_in,
                                                                channel_id_in => child.id,
                                                                immediate_in => immediate_in,
                                                                unsubscribe_children_in => unsubscribe_children_in,
                        deleting_server => deleting_server);
            else
                rhn_exception.raise_exception('channel_unsubscribe_child_exists');
            end if;
        END LOOP child;
        
        server_already_in_chan := FALSE;
    
        FOR check_subscription IN check_server_subscription(server_id_in, channel_id_in)
        LOOP
            server_already_in_chan := TRUE;
        END LOOP check_subscription;
    
        IF NOT server_already_in_chan
        THEN
            RETURN;
        END IF;
        
   if deleting_server = 0 then 

      insert into rhnServerHistory (id,server_id,summary,details) (
          select  rhn_event_id_seq.nextval,
                server_id_in,
             'unsubscribed from channel ' || SUBSTR(c.label, 0, 106),
             c.label
          from    rhnChannel c
          where   c.id = channel_id_in
      );

        UPDATE rhnServer SET channels_changed = sysdate WHERE id = server_id_in;
   end if;
        
   DELETE FROM rhnServerChannel WHERE server_id = server_id_in AND channel_id = channel_id_in;

   if deleting_server = 0 then 
        queue_server(server_id_in, immediate_in);
   end if;

        channel_family_id_val := rhn_channel.family_for_channel(channel_id_in);
        IF channel_family_id_val IS NULL
        THEN
            rhn_exception.raise_exception('channel_unsubscribe_no_family');
        END IF;

        for ignore in channel_family_is_satellite(channel_family_id_val) loop
                delete from rhnSatelliteInfo where server_id = server_id_in;
                delete from rhnSatelliteChannelFamily where server_id = server_id_in;
        end loop;

        for ignore in channel_family_is_proxy(channel_family_id_val) loop
                delete from rhnProxyInfo where server_id = server_id_in;
        end loop;

        DELETE FROM rhnChannelFamilyLicenseConsent
         WHERE channel_family_id = channel_family_id_val
           AND server_id = server_id_in;
                        
        SELECT org_id INTO server_org_id_val
          FROM rhnServer
         WHERE id = server_id_in;
         
        rhn_channel.update_family_counts(channel_family_id_val, server_org_id_val);
    END unsubscribe_server;

    PROCEDURE bulk_unsubscribe_server(channel_id_in IN NUMBER, set_label_in IN VARCHAR2, set_uid_in IN NUMBER)
    IS
    BEGIN
        FOR server IN rhn_set.set_iterator(set_label_in, set_uid_in)
        LOOP
            rhn_channel.unsubscribe_server(server.element, channel_id_in, 0);
        END LOOP server;
    END bulk_unsubscribe_server;

    FUNCTION family_for_channel(channel_id_in IN NUMBER)
    RETURN NUMBER
    IS
        channel_family_id_val NUMBER;
    BEGIN
        SELECT channel_family_id INTO channel_family_id_val
          FROM rhnChannelFamilyMembers
         WHERE channel_id = channel_id_in;
         
        RETURN channel_family_id_val;
    EXCEPTION
        WHEN NO_DATA_FOUND
        THEN
            RETURN NULL;
    END family_for_channel;

    FUNCTION available_family_subscriptions(channel_family_id_in IN NUMBER, org_id_in IN NUMBER)
    RETURN NUMBER
    IS
        cfp channel_family_perm_cursor%ROWTYPE;
        current_members_val NUMBER;
        max_members_val     NUMBER;
        found               NUMBER;
    BEGIN
        IF NOT channel_family_perm_cursor%ISOPEN
        THEN
            OPEN channel_family_perm_cursor(channel_family_id_in, org_id_in);
        END IF;

        FETCH channel_family_perm_cursor INTO cfp;
        
        WHILE channel_family_perm_cursor%FOUND
        LOOP
            found := 1;
            
            current_members_val := cfp.current_members;
            max_members_val := cfp.max_members;
            
            FETCH channel_family_perm_cursor INTO cfp;
        END LOOP;

        IF channel_family_perm_cursor%ISOPEN
        THEN
            CLOSE channel_family_perm_cursor;
        END IF;

        -- not found: either the channel fam doesn't have an entry in cfp, or the org doesn't have access to it.
        -- either way, there are no available subscriptions
        
        IF found IS NULL
        THEN
            RETURN 0;
        END IF;

        -- null max members?  in that case, pass it on; NULL means infinite                     
        IF max_members_val IS NULL
        THEN
            RETURN NULL;
        END IF;

        -- otherwise, return the delta  
        RETURN max_members_val - current_members_val;                   
    END available_family_subscriptions;
    
    -- *******************************************************************
    -- FUNCTION: channel_family_current_members
    -- Calculates and returns the actual count of systems consuming
    --   physical channel subscriptions.
    -- Called by: update_family_counts 
    --            rhn_entitlements.repoll_virt_guest_entitlements
    -- *******************************************************************
    function channel_family_current_members(channel_family_id_in IN NUMBER,
                                            org_id_in IN NUMBER)
    return number
    is
        current_members_count number := 0;
    begin
        select  count(sc.server_id)
        into    current_members_count
        from    rhnChannelFamilyMembers cfm,
                rhnServerChannel sc,
                rhnServer s
        where   s.org_id = org_id_in
            and s.id = sc.server_id
            and cfm.channel_family_id = channel_family_id_in
            and cfm.channel_id = sc.channel_id
            and exists ( 
                select 1
                from rhnChannelFamilyServerPhysical cfsp
                where cfsp.CHANNEL_FAMILY_ID = channel_family_id_in
                    and cfsp.server_id = s.id
                );

        return current_members_count;
    end;        

    PROCEDURE update_family_counts(channel_family_id_in IN NUMBER, 
                                   org_id_in IN NUMBER)
    IS
    BEGIN
                update rhnPrivateChannelFamily
                set current_members = (
                channel_family_current_members(channel_family_id_in, org_id_in)
                )
                        where org_id = org_id_in
                                and channel_family_id = channel_family_id_in;
    END update_family_counts;
    
    FUNCTION available_chan_subscriptions(channel_id_in IN NUMBER, 
                                          org_id_in IN NUMBER)
    RETURN NUMBER
    IS
            channel_family_id_val NUMBER;
    BEGIN
        SELECT channel_family_id INTO channel_family_id_val
            FROM rhnChannelFamilyMembers
            WHERE channel_id = channel_id_in;
         
            RETURN rhn_channel.available_family_subscriptions(
                           channel_family_id_val, org_id_in);
    END available_chan_subscriptions;

    -- *******************************************************************
    -- PROCEDURE: entitle_customer
    -- Creates a chan fam bucket, or sets max_members for an existing bucket
    -- Called by: rhn_ep.poll_customer_internal
    -- Calls: set_family_maxmembers + update_family_counts if the row
    --        already exists, else it creates it in rhnPrivateChannelFamily.
    -- *******************************************************************
    procedure entitle_customer(customer_id_in in number, 
                               channel_family_id_in in number, 
                               quantity_in in number)
    is
                cursor permissions is
                        select  1
                        from    rhnPrivateChannelFamily pcf
                        where   pcf.org_id = customer_id_in
                                and     pcf.channel_family_id = channel_family_id_in; 
    begin
                for perm in permissions loop
                        set_family_maxmembers(
                                customer_id_in,
                                channel_family_id_in,
                                quantity_in
                        );
                        rhn_channel.update_family_counts(
                                channel_family_id_in,
                                customer_id_in
                        );
                        return;
                end loop;
        
                insert into rhnPrivateChannelFamily pcf (
                                channel_family_id, org_id, max_members, current_members
                        ) values (
                                channel_family_id_in, customer_id_in, quantity_in, 0
                        );
    end;

    -- *******************************************************************
    -- PROCEDURE: set_family_maxmembers
    -- Prunes an existing channel family bucket by unsubscribing the
    --   necessary servers and sets max_members.
    -- Called by: rhn_channel.entitle_customer
    -- Calls: unsubscribe_server_from_family
    -- *******************************************************************
    procedure set_family_maxmembers(customer_id_in in number, 
                                    channel_family_id_in in number, 
                                    quantity_in in number)
    is
        cursor servers is
            select  server_id from (
            select      rownum row_number, server_id, modified from (
                select  rcfsp.server_id,
                        rcfsp.modified
                from    rhnChannelFamilyServerPhysical rcfsp
                where   rcfsp.customer_id = customer_id_in
                    and rcfsp.channel_family_id = channel_family_id_in
                order by modified
            )
            where rownum > quantity_in
            );
    begin
            -- prune subscribed servers
        for server in servers loop
            rhn_channel.unsubscribe_server_from_family(server.server_id, 
                                                       channel_family_id_in);
        end loop;

        update  rhnPrivateChannelFamily pcf
        set     pcf.max_members = quantity_in
        where   pcf.org_id = customer_id_in
            and pcf.channel_family_id = channel_family_id_in;
    end;

    procedure unsubscribe_server_from_family(server_id_in in number, 
                                             channel_family_id_in in number)
    is
    begin
        delete
        from    rhnServerChannel rsc
        where   rsc.server_id = server_id_in
            and channel_id in (
                select  rcfm.channel_id
                from    rhnChannelFamilyMembers rcfm
                where   rcfm.channel_family_id = channel_family_id_in);
    end;

    function get_org_id(channel_id_in in number)
    return number
    is
        org_id_out number;
    begin
        select org_id into org_id_out
            from rhnChannel
            where id = channel_id_in;
         
            return org_id_out;
    end get_org_id;
    
    function get_cfam_org_access(cfam_id_in in number, org_id_in in number)
    return number
    is
        cursor  families is
                        select  1
                        from    rhnOrgChannelFamilyPermissions cfp
                        where   cfp.org_id = org_id_in;
    begin
                -- the idea: if we get past this query, 
        -- the user has the role, else catch the exception and return 0
                for family in families loop
                return 1;
                end loop;
                return 0;
    end;

    function get_org_access(channel_id_in in number, org_id_in in number)
    return number
    is
        throwaway number;
    begin
        -- the idea: if we get past this query, 
        -- the org has access to the channel, else catch the exception and return 0
        select distinct 1 into throwaway
          from rhnChannelFamilyMembers CFM,
               rhnOrgChannelFamilyPermissions CFP
         where cfp.org_id = org_id_in
           and CFM.channel_family_id = CFP.channel_family_id
           and CFM.channel_id = channel_id_in
           and (CFP.max_members > 0 or CFP.max_members is null or CFP.org_id = 1);
           
        return 1;
        exception
            when no_data_found
            then
            return 0;
    end;
    
    -- check if a user has a given role, or if such a role is inferrable
    function user_role_check_debug(channel_id_in in number, 
                                   user_id_in in number, 
                                   role_in in varchar2, 
                                   reason_out out varchar2)
    return number
    is
        org_id number;
    begin
        org_id := rhn_user.get_org_id(user_id_in);

        -- channel might be shared
        if role_in = 'subscribe' and
           rhn_channel.shared_user_role_check(channel_id_in, user_id_in, role_in) = 1 then
            return 1;
        end if;
        
        if role_in = 'manage' and 
           NVL(rhn_channel.get_org_id(channel_id_in), -1) <> org_id then
                reason_out := 'channel_not_owned';
               return 0;
            end if;
        
        if role_in = 'subscribe' and 
           rhn_channel.get_org_access(channel_id_in, org_id) = 0 then
                reason_out := 'channel_not_available';
                return 0;
            end if;
        
        -- channel admins have all roles
        if rhn_user.check_role_implied(user_id_in, 'channel_admin') = 1 then
            reason_out := 'channel_admin';
            return 1;
            end if;

        -- the subscribe permission is inferred 
    -- UNLESS the not_globally_subscribable flag is set 
        if role_in = 'subscribe'
        then
            if rhn_channel.org_channel_setting(channel_id_in, 
                       org_id,
                       'not_globally_subscribable') = 0 then
                reason_out := 'globally_subscribable';
                    return 1;
            end if;
        end if;
        
        -- all other roles (manage right now) are explicitly granted    
        reason_out := 'direct_permission';
        return rhn_channel.direct_user_role_check(channel_id_in, 
                                              user_id_in, role_in);
    end;
    
    -- same as above, but with no OUT param; useful in views, etc
    function user_role_check(channel_id_in in number, user_id_in in number, role_in in varchar2)
    return number
    is
        throwaway varchar2(256);
    begin
        return rhn_channel.user_role_check_debug(channel_id_in, user_id_in, role_in, throwaway);
    end;

    --
    -- For multiorg phase II, this function simply checks to see if the user's
    -- has a trust relationship that includes this channel by id.
    --
    function shared_user_role_check(channel_id in number, user_id in number, role in varchar2)
    return number
    is
      n number;
      oid number;
    begin
      oid := rhn_user.get_org_id(user_id);
      select 1 into n
      from rhnSharedChannelView s
      where s.id = channel_id and s.org_trust_id = oid;
      return 1;
      exception
        when no_data_found then
          return 0;
    end;

    -- same as above, but returns 1 if user_id_in is null
    -- This is useful in queries where user_id is not specified
    function loose_user_role_check(channel_id_in in number, user_id_in in number, role_in in varchar2)
    return number
    is
    begin
        if user_id_in is null then
            return 1;
        end if;
        return user_role_check(channel_id_in, user_id_in, role_in);
    end loose_user_role_check;
    
    -- directly checks the table, no inferred permissions
    function direct_user_role_check(channel_id_in in number, user_id_in in number, role_in in varchar2)
    return number
    is
        throwaway number;
    begin
        -- the idea: if we get past this query, the user has the role, else catch the exception and return 0
        select 1 into throwaway
          from rhnChannelPermissionRole CPR,
               rhnChannelPermission CP
         where CP.user_id = user_id_in
           and CP.channel_id = channel_id_in
           and CPR.label = role_in
           and CP.role_id = CPR.id;
           
        return 1;
    exception
        when no_data_found
            then
            return 0;
    end;
    
    -- check if an org has a certain setting
    function org_channel_setting(channel_id_in in number, org_id_in in number, setting_in in varchar2)
    return number
    is
        throwaway number;
    begin
        -- the idea: if we get past this query, the org has the setting, else catch the exception and return 0
        select 1 into throwaway
          from rhnOrgChannelSettingsType OCST,
               rhnOrgChannelSettings OCS
         where OCS.org_id = org_id_in
           and OCS.channel_id = channel_id_in
           and OCST.label = setting_in
           and OCS.setting_id = OCST.id;
           
        return 1;
    exception
        when no_data_found
            then
            return 0;
    end;
    
    FUNCTION channel_priority(channel_id_in IN number) 
    RETURN number
    IS
         channel_name varchar2(64);
         priority number;
         end_of_life_val date;
         org_id_val number;
    BEGIN

        select name, end_of_life, org_id
        into channel_name, end_of_life_val, org_id_val
        from rhnChannel
        where id = channel_id_in;

        if end_of_life_val is not null then
          return -400;
        end if;

        if channel_name like 'Red Hat Enterprise Linux%' or channel_name like 'RHEL%' then
          priority := 1000;
          if channel_name not like '%Beta%' then
            priority := priority + 1000;
          end if;

          priority := priority +
            case
              when channel_name like '%v. 5%' then 600
              when channel_name like '%v. 4%' then 500
              when channel_name like '%v. 3%' then 400
              when channel_name like '%v. 2%' then 300
              when channel_name like '%v. 1%' then 200
              else 0
            end;

          priority := priority +
            case
              when channel_name like 'Red Hat Enterprise Linux (v. 5%' then 60
              when (channel_name like '%AS%' and channel_name not like '%Extras%') then 50
              when (channel_name like '%ES%' and channel_name not like '%Extras%') then 40
              when (channel_name like '%WS%' and channel_name not like '%Extras%') then 30
              when (channel_name like '%Desktop%' and channel_name not like '%Extras%') then 20
              when channel_name like '%Extras%' then 10
              else 0
            end; 

          priority := priority +
            case
              when channel_name like '%)' then 5
              else 0
            end;

          priority := priority +
            case
              when channel_name like '%32-bit x86%' then 4
              when channel_name like '%64-bit Intel Itanium%' then 3
              when channel_name like '%64-bit AMD64/Intel EM64T%' then 2
              else 0
            end;
        elsif channel_name like 'Red Hat Desktop%' then
            priority := 900;

            if channel_name not like '%Beta%' then
               priority := priority + 50;
            end if;
 
          priority := priority +
            case
              when channel_name like '%v. 4%' then 40
              when channel_name like '%v. 3%' then 30
              when channel_name like '%v. 2%' then 20
              when channel_name like '%v. 1%' then 10
              else 0
            end;
            
          priority := priority +
            case
              when channel_name like '%32-bit x86%' then 4
              when channel_name like '%64-bit Intel Itanium%' then 3
              when channel_name like '%64-bit AMD64/Intel EM64T%' then 2
              else 0
            end;
         
        elsif org_id_val is not null then
          priority := 600;
        else
          priority := 500;
        end if;
      
      return -priority;

    end channel_priority;

    -- right now this only does the accounting changes; the cascade
    -- actually does the rhnServerChannel delete.
    procedure delete_server_channels(server_id_in in number)
    is
    begin
        update  rhnPrivateChannelFamily
        set     current_members = current_members -1
        where   org_id in (
                        select  org_id
                        from    rhnServer
                        where   id = server_id_in
                )
                and channel_family_id in (
                        select  rcfm.channel_family_id
                        from    rhnChannelFamilyMembers rcfm,
                                rhnServerChannel rsc
                        where   rsc.server_id = server_id_in
                                and rsc.channel_id = rcfm.channel_id
                and not exists (
                    select 1
                    from
                        rhnChannelFamilyVirtSubLevel cfvsl,
                        rhnSGTypeVirtSubLevel sgtvsl,
                        rhnServerEntitlementView sev,
                        rhnVirtualInstance vi
                    where
                        -- system is a virtual instance
                        vi.virtual_system_id = server_id_in
                        and vi.host_system_id = sev.server_id
                        -- system's host has a virt ent
                        and sev.label in ('virtualization_host',
                                          'virtualization_host_platform')
                        and sev.server_group_type_id = 
                            sgtvsl.server_group_type_id
                        -- the host's virt ent grants a cf virt sub level
                        and sgtvsl.virt_sub_level_id = cfvsl.virt_sub_level_id
                        -- the cf is in that virt sub level
                        and cfvsl.channel_family_id = rcfm.channel_family_id
                    )
                );
    end;

        -- this could certainly be optimized to do updates if needs be
        procedure refresh_newest_package(channel_id_in in number, caller_in in varchar2 := '(unknown)')
        is
        begin
                delete from rhnChannelNewestPackage where channel_id = channel_id_in;
                insert into rhnChannelNewestPackage
                        ( channel_id, name_id, evr_id, package_id, package_arch_id ) 
                        (       select  channel_id,
                                                name_id, evr_id,
                                                package_id, package_arch_id
                                from    rhnChannelNewestPackageView
                                where   channel_id = channel_id_in
                        );
                insert into rhnChannelNewestPackageAudit (channel_id, caller)
                    values (channel_id_in, caller_in);
                update rhnChannel 
                    set last_modified = greatest(sysdate, last_modified + 1/86400)
                    where id = channel_id_in; 
        end;

   procedure update_channel ( channel_id_in in number, invalidate_ss in number := 0, 
                              date_to_use in date := sysdate )
   is

   channel_last_modified date;
   last_modified_value date;

   cursor snapshots is
   select  snapshot_id id
   from    rhnSnapshotChannel
   where   channel_id = channel_id_in;

   begin

      select last_modified
      into channel_last_modified
      from rhnChannel
      where id = channel_id_in;
  
      last_modified_value := date_to_use;

      if last_modified_value <= channel_last_modified then
          last_modified_value := last_modified_value + 1/86400;
      end if;

      update rhnChannel set last_modified = last_modified_value
      where id = channel_id_in;

      if invalidate_ss = 1 then 
        for snapshot in snapshots loop
            update rhnSnapshot
            set invalid = lookup_snapshot_invalid_reason('channel_modified')
            where id = snapshot.id;
        end loop;
      end if;

   end update_channel;

   procedure update_channels_by_package ( package_id_in in number, date_to_use in date := sysdate )
   is

   cursor channels is
   select channel_id
   from rhnChannelPackage
   where package_id = package_id_in
   order by channel_id;

   begin
      for channel in channels loop
         -- we want to invalidate the snapshot assocated with the channel when we
         -- do this b/c we know we've added or removed or packages
         rhn_channel.update_channel ( channel.channel_id, 1, date_to_use );
      end loop;
   end update_channels_by_package;

   
   procedure update_channels_by_errata ( errata_id_in number, date_to_use in date := sysdate )
   is

   cursor channels is
   select channel_id
   from rhnChannelErrata
   where errata_id = errata_id_in
   order by channel_id;

   begin
      for channel in channels loop
         -- we won't invalidate snapshots, b/c just changing the errata associated with
         -- a channel shouldn't invalidate snapshots
         rhn_channel.update_channel ( channel.channel_id, 0, date_to_use );
      end loop;
   end update_channels_by_errata;

END rhn_channel;
/
SHOW ERRORS

--
-- Revision 1.75  2005/03/04 00:04:19  jslagle
-- bz #147617
-- Made Red Hat Desktop sort a little better.
--
-- Revision 1.74  2005/02/22 03:24:47  jslagle
-- bz #147617
-- Improve channel_priority function to order channels better.
--
-- Revision 1.73  2004/08/16 20:39:30  pjones
-- bugzilla: 129889 -- make bulk_server_basechange_from() actually work.
--
-- Revision 1.72  2004/04/14 00:09:24  pjones
-- bugzilla: 120761 -- split rhnChannelPermissions into two tables, eliminating
-- a frequent full table scan
--
-- Revision 1.71  2004/04/13 16:28:36  bretm
-- bugzilla:  119871
--
-- keep track of rhnServer.channels_changed through the pl/sql fns
--
-- Revision 1.70  2004/03/26 18:11:32  rbb
-- Bugzilla:  114057
--
-- Add a script to determine channel priority.
--
-- Revision 1.69  2004/02/17 20:16:52  pjones
-- bugzilla: none -- add cvs tags into the package as long as we're touching
-- it anyway
--
-- Revision 1.68  2004/02/17 20:05:38  pjones
-- bugzilla: 115782 -- make bulk_server_basechange_from() filter out servers
-- with arches incompatible with the target channel
--
-- Revision 1.67  2004/02/06 02:36:10  misa
-- Changed normalize_server_arch to allow for solaris arches
--
-- Revision 1.66  2003/11/13 16:58:34  cturner
-- make use of new rhn_user.check_role_implied call; pragmas broke, removed them for now since I have no idea how to fix them
--
-- Revision 1.65  2003/10/23 20:26:24  bretm
-- bugzilla:  none
--
-- note the channel label when we unsubscribe, too
--
-- Revision 1.64  2003/10/15 14:47:17  bretm
-- bugzilla:  none
--
-- add the channel label to the server history summary line when we log a channel change
--
-- Revision 1.63  2003/09/24 19:25:56  pjones
-- this wasn't the right fix, put it back
--
-- Revision 1.62  2003/09/24 17:42:19  pjones
-- bugzilla: none
--
-- limit our server base channel guess to channels with available permissions
--
-- Revision 1.61  2003/09/22 21:00:40  cturner
-- add method for easy acl check
--
-- Revision 1.60  2003/09/17 22:14:11  misa
-- bugzilla: 103639  Changes to allow me to move the base channel guess into plsql
--
-- Revision 1.59  2003/08/21 13:41:17  cturner
-- bugzilla: 99187.  properly test for satellite and proxy in bulk_guess_server_base; reorg code for better reuse
--
-- Revision 1.58  2003/07/24 16:46:22  cturner
-- bugzilla: 100723, the perm check was returning duplicates, so now it just calls the function it should have called anyway
--
-- Revision 1.57  2003/07/24 16:44:16  misa
-- bugzilla: none  A function more usable on the rhnapp side
--
-- Revision 1.56  2003/07/23 22:36:51  cturner
-- argh, max returns null even when now rows; use distinct.  how revolting
--
-- Revision 1.55  2003/07/23 22:01:31  cturner
-- oops, this one can return multiple rows; eliminate that in a lazy way
--
-- Revision 1.54  2003/07/23 21:59:19  cturner
-- rework how rhnUserChannel works; move to plsql for speed and maintenance
--
-- Revision 1.53  2003/07/21 17:49:12  pjones
-- bugzilla: none
--
-- add optional user for subscribe_server
--
-- Revision 1.52  2003/07/14 22:19:29  misa
-- bugzilla: none  Updating guess_base_channel to work more like the rhnapp server code
--
-- Revision 1.51  2003/06/26 22:09:04  pjones
-- bugzilla: none
--
-- log subscribe and unsubscribe
--
-- Revision 1.50  2003/06/05 19:31:15  pjones
-- bugzilla: 88278 -- make the cursor name smaller
--
-- Revision 1.49  2003/06/05 19:18:21  pjones
-- bugzilla: 88278
--
-- unsubscribe_server() opens the package-level cursor when it invokes itself,
-- so we're using a local copy instead.
--
-- Revision 1.48  2003/06/04 16:41:39  pjones
-- bugzilla: none
--
-- make bulk_guess_server_base() silently ignore unguessables
--
-- Revision 1.47  2003/06/04 16:27:03  pjones
-- bugzilla: 88822
--
-- eliminate the last outliers that remove things from channels without using
-- unsubscribe_server, I think.
--
-- Revision 1.46  2003/06/03 20:49:37  pjones
-- bugzilla: 88822
-- unsubscribing from rhn-satellite now clears rhnSatelliteChannelFamily
-- for the server in question
--
-- Revision 1.45  2003/06/02 20:41:45  pjones
-- bugzilla: none - fix rhnProxyInfo/rhnSatelliteInfo channel unsubscribe
-- problem.  Basicly, if you're out of the channel for any reason, you're
-- also out of rhnProxyInfo/rhnProxyInfo
--
-- Revision 1.44  2003/03/24 15:26:28  pjones
-- bugzilla: 85812
--
-- bulk_server_base_change silently ignores servers that are satellites
-- or proxies, as requested.
--
-- Revision 1.43  2003/02/26 20:28:17  pjones
-- rhn_channel.update_family_counts() in rhn_channel.entitle_customer()
-- the old codepath is:
--
-- ep ->
-- rhn_ep.entitlement_run_me() ->
-- rhn_ep.poll_customer() ->
-- rhn_channel.entitle_customer()
--
-- which doesn't change current_members, even though it may remove servers
-- from the family.
--
-- There's another bug here:  currently, we don't try to order forced
-- unsubscribes in any way; we just use
-- rhn_channel.unsubscribe_server_from_family .  If there are any child
-- channel subscriptions, this will leave them subscribed.  We really need
-- to iterate across the channels again, and subscribe any channel for which
-- there are no parent channel subscriptions.
--
-- Ugh.
--
-- Revision 1.42  2003/01/28 00:19:45  pjones
-- fix clear_subscriptions; AFAICT, this is only hit on the
-- bulk_server_base_change / bulk_server_base_guess codepaths, which puts
-- it infrequent enough that it could be our "bad count" culprit.
--
-- Revision 1.41  2003/01/14 19:51:45  pjones
-- make setting current_members on rhnChannelFamilyPermissions work when
-- a server is in more than one channel in a single family.
 070701000004AA000081B400000000000000000000000167AE111400000592000000000000000000000000000000000000007200000000susemanager-schema/upgrade/spacewalk-schema-0.3-to-spacewalk-schema-0.4/123-rhnServerActionVerify-chg-indexes.sql --
-- Copyright (c) 2008 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
-- $Id$
--

drop index rhn_sactionvm_sanec_uq;
create unique index rhn_sactionvm_sanec_uq
        on rhnServerActionVerifyMissing(
                server_id, action_id,
                package_name_id, package_evr_id, package_arch_id,
                package_capability_id )
        tablespace [[4m_tbs]]
        storage ( freelists 16 )
        initrans 32;

drop index rhn_sactionvr_sanec_uq;
create unique index rhn_sactionvr_sanec_uq
        on rhnServerActionVerifyResult(
                server_id, action_id,
                package_name_id, package_evr_id, package_arch_id,
                package_capability_id )
        tablespace [[4m_tbs]]
        storage ( freelists 16 )
        initrans 32;

-- $Log$
-- Revision 1  2008/11/03
-- bugzilla: 456539 -- adding package_arch_id to indexes

  070701000004AB000081B400000000000000000000000167AE111400002CD2000000000000000000000000000000000000005E00000000susemanager-schema/upgrade/spacewalk-schema-0.3-to-spacewalk-schema-0.4/130-delete_server.sql --
-- Copyright (c) 2008 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
-- This deletes a server.  All codepaths which delete servers should hit this
-- or delete_server_bulk()

create or replace
procedure delete_server (
	server_id_in in number
) is
	cursor servergroups is
		select	server_id, server_group_id
		from	rhnServerGroupMembers sgm
		where	sgm.server_id = server_id_in;
	cursor configchannels is
		select	cc.id
		from	rhnConfigChannel cc,
			rhnConfigChannelType cct,
			rhnServerConfigChannel scc
		where	1=1
			and scc.server_id = server_id_in
			and scc.config_channel_id = cc.id
			-- these config channel types are reserved
			-- for use by a single server, so we don't
			-- need to check for other servers subscribed
			and cct.label in
				('local_override','server_import')
			and cct.id = cc.confchan_type_id;
        type filelistsid_t is table of rhnServerPreserveFileList.file_list_id%type;
        filelistsid_c filelistsid_t;

        type probesid_t is table of rhn_check_probe.probe_id%type;
        probesid_c probesid_t;

    is_virt number := 0;
begin
	rhn_channel.delete_server_channels(server_id_in);
	-- rhn_channel.clear_subscriptions(server_id_in);

        -- filelists
	select	spfl.file_list_id id bulk collect into filelistsid_c
	  from	rhnServerPreserveFileList spfl
	 where	spfl.server_id = server_id_in
			and not exists (
				select	1
				from	rhnServerPreserveFileList
				where	file_list_id = spfl.file_list_id
					and server_id != server_id_in
				union
				select	1
				from	rhnKickstartPreserveFileList
				where	file_list_id = spfl.file_list_id
			);
        if filelistsid_c.first is not null then
            forall i in filelistsid_c.first..filelistsid_c.last
                delete from rhnFileList where id = filelistsid_c(i);
        end if;

	for configchannel in configchannels loop
		rhn_config.delete_channel(configchannel.id);
	end loop;

      select count(1) into is_virt
        from rhnServerEntitlementView
       where server_id = server_id_in
         and label in ('virtualization_host', 'virtualization_host_platform')
         and rownum <= 1;

	for sgm in servergroups loop
		rhn_server.delete_from_servergroup(
			sgm.server_id, sgm.server_group_id);
	end loop;

    if is_virt = 1 then
        rhn_entitlements.repoll_virt_guest_entitlements(server_id_in);
    end if;

	-- we're handling this instead of letting an "on delete
	-- set null" do it so that we don't run the risk
	-- of setting off the triggers and killing us with a
	-- mutating table

	-- this is merge of two single updates:
        --  update ... set old_server_id = null where old_server_id = server_id_in;
        --  update ... set new_server_id = null where new_server_id = server_id_in;
        -- so we scan rhnKickstartSession table only once
	update rhnKickstartSession
		set old_server_id = case when old_server_id = server_id_in then null else old_server_id end,
		    new_server_id = case when new_server_id = server_id_in then null else new_server_id end
		where old_server_id = server_id_in 
		   or new_server_id = server_id_in;

	rhn_channel.clear_subscriptions(server_id_in,1);

    	-- A little complicated here, but the goal is to
	-- delete records from rhnVirtualInstace only if we don't
	-- care about them anymore.  We don't care about records
	-- in rhnVirtualInstance if we are deleting the host
	-- system and the virtual system is already null, or
	-- vice-versa.  We *do* care about them if either the
	-- host or virtual system is still registered because we
	-- still want them to show up in the UI.
    -- If there's a newer row in rhnVirtualInstance with the same
    -- uuid, this guest must have been re-registered, so we can clean
    -- this data up.
				
        delete from rhnVirtualInstance vi
	      where (host_system_id = server_id_in and virtual_system_id is null)
                 or (virtual_system_id = server_id_in and host_system_id is null)
                 or (vi.virtual_system_id = server_id_in and vi.modified < (select max(vi2.modified)
                    from rhnVirtualInstance vi2 where vi2.uuid = vi.uuid));
						
        -- this is merge of two single updates:
        --  update ... set host_system_id = null where host_system_id = server_id_in;
        --  update ... set virtual_system_id = null where virtual_system_id = server_id_in;
        -- so we scan rhnVirtualInstance table only once
        update rhnVirtualInstance
	   set host_system_id = case when host_system_id = server_id_in then null else host_system_id end,
	       virtual_system_id = case when virtual_system_id = server_id_in then null else virtual_system_id end
	 where host_system_id = server_id_in
	    or virtual_system_id = server_id_in;
		
        -- this is merge of two single updates:
        --  update ... set old_host_system_id = null when old_host_system_id = server_id_in;
        --  update ... set new_host_system_id = null when new_host_system_id = server_id_in;
        -- so we scan rhnVirtualInstanceEventLog table only once
	update rhnVirtualInstanceEventLog
	   set old_host_system_id = case when old_host_system_id = server_id_in then null else old_host_system_id end,
               new_host_system_id = case when new_host_system_id = server_id_in then null else new_host_system_id end
         where old_host_system_id = server_id_in
            or new_host_system_id = server_id_in;
		 
	-- We're deleting everything with a foreign key to rhnServer
	-- here, now.  I'm hoping this will help aleviate our deadlock
	-- problem.

	delete from rhnActionConfigChannel where server_id = server_id_in;
	delete from rhnActionConfigRevision where server_id = server_id_in;
	delete from rhnActionPackageRemovalFailure where server_id = server_id_in;
	delete from rhnChannelFamilyLicenseConsent where server_id = server_id_in;
	delete from rhnClientCapability where server_id = server_id_in;
	delete from rhnCpu where server_id = server_id_in;
	-- there's still a cascade here, because the constraint keeps the
	-- table locked for too long to rebuild it.  Ugh...
	delete from rhnDevice where server_id = server_id_in;
	delete from rhnProxyInfo where server_id = server_id_in;
	delete from rhnRam where server_id = server_id_in;
	delete from rhnRegToken where server_id = server_id_in;
	delete from rhnSNPServerQueue where server_id = server_id_in;
	delete from rhnSatelliteChannelFamily where server_id = server_id_in;
	delete from rhnSatelliteInfo where server_id = server_id_in;
	-- this cascades to rhnActionConfigChannel and rhnActionConfigFileName
	delete from rhnServerAction where server_id = server_id_in;
	delete from rhnServerActionPackageResult where server_id = server_id_in;
	delete from rhnServerActionScriptResult where server_id = server_id_in;
	delete from rhnServerActionVerifyResult where server_id = server_id_in;
	delete from rhnServerActionVerifyMissing where server_id = server_id_in;
	-- counts are handled above.  this should be a delete_ function.
	delete from rhnServerChannel where server_id = server_id_in;
	delete from rhnServerConfigChannel where server_id = server_id_in;
	delete from rhnServerCustomDataValue where server_id = server_id_in;
	delete from rhnServerDMI where server_id = server_id_in;
	delete from rhnServerMessage where server_id = server_id_in;
	-- this gets rhnServerMessage (only) on cascade; it's handled just above
	delete from rhnServerEvent where server_id = server_id_in;
	delete from rhnServerHistory where server_id = server_id_in;
	delete from rhnServerInfo where server_id = server_id_in;
	delete from rhnServerInstallInfo where server_id = server_id_in;
	delete from rhnServerLocation where server_id = server_id_in;
	delete from rhnServerLock where server_id = server_id_in;
	delete from rhnServerNeededPackageCache where server_id = server_id_in;
	delete from rhnServerNeededErrataCache where server_id = server_id_in;
	delete from rhnServerNetwork where server_id = server_id_in;
	delete from rhnServerNotes where server_id = server_id_in;
	-- I'm not removing the foreign key from rhnServerPackage; that'll
	-- take forever.  Do the delete anyway.
	delete from rhnServerPackage where server_id = server_id_in;
	delete from rhnServerTokenRegs where server_id = server_id_in;
	delete from rhnSnapshotTag where server_id = server_id_in;
	-- this cascades to:
	--   rhnSnapshotChannel, rhnSnapshotConfigChannel, rhnSnapshotPackage, 
	--   rhnSnapshotConfigRevision, rhnSnapshotServerGroup, 
	--   rhnSnapshotTag.
	-- We may want to consider delete_snapshot() at some point, but
	--   I don't think we need to yet.
	delete from rhnSnapshot where server_id = server_id_in;
	delete from rhnTransaction where server_id = server_id_in;
	delete from rhnUserServerPrefs where server_id = server_id_in;
	-- hrm, this one's interesting... we _probably_ should delete
	-- everything for the parent server_id when we delete the proxy,
	-- but we don't currently.
	delete from rhnServerPath where server_id_in in (server_id, proxy_server_id);
	delete from rhnUserServerPerms where server_id = server_id_in;

	delete from rhn_interface_monitoring where server_id = server_id_in;
	delete from rhnServerNetInterface where server_id = server_id_in;
	delete from rhn_server_monitoring_info where recid = server_id_in;

	delete from rhnAppInstallSession where server_id = server_id_in;
	delete from rhnServerUuid where server_id = server_id_in;
    -- We delete all the probes running directly against this system
    -- and any probes that were using this Server as a Proxy Scout.
     SELECT CP.probe_id bulk collect into probesid_c
       FROM rhn_check_probe CP  
      WHERE CP.host_id = server_id_in
         OR CP.sat_cluster_id in
    (SELECT SN.sat_cluster_id
       FROM rhn_sat_node SN
      WHERE SN.server_id = server_id_in);

    if probesid_c.first is not null then
        FORALL i IN probesid_c.first..probesid_c.last
            DELETE FROM rhn_probe_state PS WHERE PS.probe_id = probesid_c(i);
        FORALL i IN probesid_c.first..probesid_c.last
            DELETE FROM rhn_probe P  WHERE P.recid = probesid_c(i);
    end if;

	delete from rhn_check_probe where host_id = server_id_in;
	delete from rhn_host_probe where host_id = server_id_in;

    delete from rhn_sat_cluster where recid in
      ( select sat_cluster_id from rhn_sat_node where server_id = server_id_in );

	delete from rhn_sat_node where server_id = server_id_in;
	
	-- now get rhnServer itself.
	delete
	from	rhnServer
		where id = server_id_in;

	delete
	from	rhnSet
	where	1=1
		and user_id in (
			select	wc.id
			from	rhnServer rs,
				web_contact wc
			where	rs.id = server_id_in
				and rs.org_id = wc.org_id
		)
		and label = 'system_list'
		and element = server_id_in;
end delete_server;
/
show errors;

--
-- Revision 1.25  2004/11/01 17:53:03  pjones
-- bugzilla: 136124 -- Fix the "no data found" when deleting rhn_sat_cluster
--
--
--
--
-- This deletes a list of server. 
--
  070701000004AC000081B400000000000000000000000167AE111400000458000000000000000000000000000000000000006300000000susemanager-schema/upgrade/spacewalk-schema-0.3-to-spacewalk-schema-0.4/131-delete_server_bulk.sql    --
-- Copyright (c) 2008 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
-- Revision 1.25  2004/11/01 17:53:03  pjones
-- bugzilla: 136124 -- Fix the "no data found" when deleting rhn_sat_cluster
--
--
--
--
-- This deletes a list of server. 
--

create or replace
procedure delete_server_bulk (
	user_id_in in number
) is
	cursor systems is
		select	s.element id
		from	rhnSet s
		where	s.user_id = user_id_in
			and s.label = 'system_list';
begin
	for s in systems loop
                delete_server(s.id);
	end loop;
end delete_server_bulk;
/
show errors;
070701000004AD000081B400000000000000000000000167AE111400000405000000000000000000000000000000000000007300000000susemanager-schema/upgrade/spacewalk-schema-0.3-to-spacewalk-schema-0.4/132-rhnActionKickstartGuest-add-kshost.sql    --
-- Copyright (c) 2008 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
-- $Id$
--

ALTER TABLE rhnActionKickstartGuest
 ADD kickstart_host varchar2(256);

ALTER TABLE rhnActionKickstartGuest
 ADD disk_path varchar2(256);

ALTER TABLE rhnActionKickstartGuest
 ADD virt_bridge varchar2(256);

ALTER TABLE rhnActionKickstartGuest
 ADD cobbler_system_name varchar2(256);

show errors

-- $Log$
-- Revision 1  2008/10/29 7:01:05  mmccune
-- add new kickstart_host for koan usage
   070701000004AE000081B400000000000000000000000167AE11140000056C000000000000000000000000000000000000007600000000susemanager-schema/upgrade/spacewalk-schema-0.3-to-spacewalk-schema-0.4/133-rhnKickstartVirtualizationType-update.sql --
-- Copyright (c) 2008 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
-- $Id$
--

update rhnKickstartVirtualizationType
    set label = 'xenpv' where label = 'para_guest';

update rhnKickstartVirtualizationType
    set label = 'auto' where label = 'none';

update rhnKickstartVirtualizationType
    set name = 'Auto' where label = 'auto';

update rhnKickstartVirtualizationType
    set name = 'XEN Para-Virtualized Guest' where label = 'xenpv';

insert into rhnKickstartVirtualizationType (id, name, label)
    values (rhn_kvt_id_seq.nextval, 'KVM Virtualized Guest', 'qemu');

insert into rhnKickstartVirtualizationType (id, name, label)
    values (rhn_kvt_id_seq.nextval, 'XEN Fully-Virtualized Guest', 'xenfv');

commit;

show errors

-- $Log$
-- Revision 1  2008/10/29 7:01:05  mmccune
-- add new kickstart_host for koan usage
070701000004AF000081B400000000000000000000000167AE111400000215000000000000000000000000000000000000006600000000susemanager-schema/upgrade/spacewalk-schema-0.3-to-spacewalk-schema-0.4/135-rhn_config_macro_data.sql 
update rhn_config_macro set definition='/usr/bin' where name='NPBIN';
update rhn_config_macro set definition='/etc/nocpulse' where name='NPETC';
update rhn_config_macro set definition='/var/lib/%{USER}' where name='NPHOME';
update rhn_config_macro set definition='/var/log/%{USER}' where name='NPVAR';

insert into rhn_config_macro(environment,name,definition,description,editable,last_update_user,last_update_date)     values ( 'ALL', 'NPLIB', '/var/lib/%{USER}', 'Production user data directory', '0', 'system',sysdate);

commit;
   070701000004B0000081B400000000000000000000000167AE111400000971000000000000000000000000000000000000006A00000000susemanager-schema/upgrade/spacewalk-schema-0.3-to-spacewalk-schema-0.4/136-rhn_config_parameter_data.sql 

update rhn_config_parameter set value='/var/lib/notification/queue/ack_queue' where name='ack_queue_dir';
update rhn_config_parameter set value='/var/lib/notification/queue/alert_queue' where name='alert_queue_dir';

update rhn_config_parameter set value='/etc/notification' where group_name='notification' and name='config_dir';


update rhn_config_parameter set value='%{NPLIB}/trapReceiver/config' where group_name='trapReceiver' and name='config';
update rhn_config_parameter set value='%{NPLIB}/trapReceiver/mibs' where group_name='trapReceiver' and name='cust_mibdir';
update rhn_config_parameter set value='%{NPLIB}/trapReceiver/traps' where group_name='trapReceiver' and name='trapdir';
update rhn_config_parameter set value='%{NPLIB}/ProbeState' where group_name='ProbeFramework' and name='databaseDirectory';
update rhn_config_parameter set value='%{NPLIB}/.gripes.gdbm' where group_name='queues' and name='gritchdb';
update rhn_config_parameter set value='%{NPLIB}/queue' where group_name='queues' and name='queuedir';
update rhn_config_parameter set value='%{NPLIB}/queue/snmp/LAST_SENT' where group_name='queues' and name='snmplast';
update rhn_config_parameter set value='%{NPLIB}/commands/.gripes.gdbm' where group_name='CommandQueue' and name='gritchdb';
update rhn_config_parameter set value='%{NPLIB}/commands/heartbeat' where group_name='CommandQueue' and name='heartbeatFile';
update rhn_config_parameter set value='%{NPLIB}/commands/last_completed' where group_name='CommandQueue' and name='lastCompletedFile';
update rhn_config_parameter set value='%{NPLIB}/commands/last_started' where group_name='CommandQueue' and name='lastStartedFile';
update rhn_config_parameter set value='%{NPLIB}/last_state_push' where group_name='current_state' and name='last_success';
update rhn_config_parameter set value='%{NPLIB}/events.frozen' where group_name='satellite' and name='eventsFile';
update rhn_config_parameter set value='%{NPLIB}/.gripes-probe-code.gdbm' where group_name='satellite' and name='gritchdb';
update rhn_config_parameter set value='%{NPLIB}/scheduler.xml' where group_name='satellite' and name='schedulerConfigFile';
update rhn_config_parameter set value='%{NPLIB}/reload.please' where group_name='satellite' and name='schedulerReloadFlagFile';
update rhn_config_parameter set value='%{NPLIB}/commands/execute_commands.log' where group_name='CommandQueue' and name='exelog';

commit;
   070701000004B1000081B400000000000000000000000167AE11140000035C000000000000000000000000000000000000006500000000susemanager-schema/upgrade/spacewalk-schema-0.3-to-spacewalk-schema-0.4/137-rhnKickstartableTree.sql  --
-- Copyright (c) 2008 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
-- $Id$
--



ALTER TABLE rhnKickstartableTree
ADD cobbler_id varchar2(64);

ALTER TABLE rhnKickstartableTree
ADD cobbler_xen_id varchar2(64);

show errors

-- $Log$
-- Revision 1  2008/12/02 16:51 jsherrill
-- Add cobbler_id column

070701000004B2000081B400000000000000000000000167AE1114000005F3000000000000000000000000000000000000006400000000susemanager-schema/upgrade/spacewalk-schema-0.3-to-spacewalk-schema-0.4/138-rhnRegTokenPackages.sql   --
-- Copyright (c) 2008 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
-- $Id$
--


ALTER TABLE rhnRegTokenPackages ADD id number;

CREATE SEQUENCE rhn_reg_tok_pkg_id_seq;

UPDATE rhnRegTokenPackages SET id = rhn_reg_tok_pkg_id_seq.nextval;

ALTER TABLE rhnRegTokenPackages ADD CONSTRAINT rhn_reg_tok_pkg_id_nn  CHECK ("ID" IS NOT NULL);

ALTER TABLE rhnRegTokenPackages ADD CONSTRAINT rhn_reg_tok_pkg_id_pk primary key ( id );

ALTER TABLE rhnRegTokenPackages ADD (arch_id number);

ALTER TABLE rhnRegTokenPackages ADD CONSTRAINT rhn_reg_tok_pkg_aid_fk FOREIGN KEY (arch_id) REFERENCES rhnPackageArch (id) ON DELETE CASCADE;

DROP index rhn_reg_tok_pkg_uq;

create unique index rhn_reg_tok_pkg_uq
        on rhnRegTokenPackages(id, token_id, name_id, arch_id)
        tablespace [[4m_tbs]]
        storage( freelists 16 )
        initrans 32;


show errors

-- $Log$
-- Revision 1  2008/12/04 10:44 pkilambi
-- Arch support for activation key based package installs

 070701000004B3000081B400000000000000000000000167AE1114000003E5000000000000000000000000000000000000006600000000susemanager-schema/upgrade/spacewalk-schema-0.3-to-spacewalk-schema-0.4/139-rhnKickstartableTrees.sql --
-- Copyright (c) 2008--2010 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
-- $Id$
--

alter trigger rhn_kstree_mod_trig disable;
update rhnKickstartableTree set boot_image='spacewalk-koan';
alter trigger rhn_kstree_mod_trig enable;

ALTER TABLE rhnKickstartableTree 
    MODIFY( boot_image  varchar2(128) default('spacewalk-koan')); 

show errors
-- $Log$
-- Revision 1  2008/12/04 6:38 pkilambi
-- Added support to create boot image... 

   070701000004B4000081B400000000000000000000000167AE11140000031E000000000000000000000000000000000000007200000000susemanager-schema/upgrade/spacewalk-schema-0.3-to-spacewalk-schema-0.4/140-rhnActionKickstart-drop-kstree_id.sql --
-- Copyright (c) 2008 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
-- $Id$
--

ALTER TABLE rhnActionKickstart
DROP COLUMN kstree_id;


show errors

-- $Log$
--
-- Revision 1  2008/12/05 6:56:45  paji
-- Removed the unused kstree_id column
  070701000004B5000081B400000000000000000000000167AE111400000323000000000000000000000000000000000000007700000000susemanager-schema/upgrade/spacewalk-schema-0.3-to-spacewalk-schema-0.4/141-rhnActionKickstartGuest-drop-kstree_id.sql    --
-- Copyright (c) 2008 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
-- $Id$
--

ALTER TABLE rhnActionKickstartGuest
DROP COLUMN kstree_id;


show errors

-- $Log$
--
-- Revision 1  2008/12/05 6:56:45  paji
-- Removed the unused kstree_id column
 070701000004B6000081B400000000000000000000000167AE111400000380000000000000000000000000000000000000006400000000susemanager-schema/upgrade/spacewalk-schema-0.3-to-spacewalk-schema-0.4/142-rhnSet-add-element3.sql   --
-- Copyright (c) 2008 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--
--
-- $Id$
--

alter table rhnSet add element_three NUMBER;
alter table rhnSet drop constraint rhn_set_user_label_elem_unq drop index;
alter table rhnSet add constraint rhn_set_user_label_elem_unq
     unique(user_id, label, element, element_two, element_three);


-- $Log$

070701000004B7000081B400000000000000000000000167AE111400000310000000000000000000000000000000000000007100000000susemanager-schema/upgrade/spacewalk-schema-0.3-to-spacewalk-schema-0.4/143-rhnServerProfilePackage-add-arch.sql  --
-- Copyright (c) 2008 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--
--
--
--
alter table rhnServerProfilePackage
add package_arch_id number
    constraint rhn_sprofile_package_fk
        references rhnPackageArch(id);

show errors
070701000004B8000081B400000000000000000000000167AE11140000062B000000000000000000000000000000000000006900000000susemanager-schema/upgrade/spacewalk-schema-0.3-to-spacewalk-schema-0.4/144-rhnSharedChannelTreeView.sql  --
-- Copyright (c) 2008 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--

CREATE OR REPLACE VIEW RHNSHAREDCHANNELTREEVIEW
(
  ORG_ID,
  ID,
  DEPTH,
  NAME,
  PADDED_NAME,
  CHANNEL_ARCH_ID,
  LAST_MODIFIED,
  LABEL,
  PARENT_OR_SELF_LABEL,
  PARENT_OR_SELF_ID,
  END_OF_LIFE
)
AS
SELECT * FROM (
  SELECT
    C.ORG_TRUST_ID AS ORG_ID,
    C.ID,
    1 AS DEPTH,
    C.NAME,
    '  '||C.NAME AS PADDED_NAME,
    C.CHANNEL_ARCH_ID,
    C.LAST_MODIFIED,
    C.LABEL,
    C.LABEL AS PARENT_OR_SELF_LABEL,
    C.ID AS PARENT_OR_SELF_ID,
    C.END_OF_LIFE
  FROM RHNSHAREDCHANNELVIEW C
  WHERE C.PARENT_CHANNEL IS NULL
  UNION
  SELECT
    C.ORG_TRUST_ID AS ORG_ID,
    C.ID,
    2 AS DEPTH,
    c.name,
    ''||C.NAME AS PADDED_NAME,
    C.CHANNEL_ARCH_ID,
    C.LAST_MODIFIED,
    C.LABEL,
    C.LABEL AS PARENT_OR_SELF_LABEL,
    C.ID AS PARENT_OR_SELF_ID,
    C.END_OF_LIFE
  FROM RHNSHAREDCHANNELVIEW PC,
       RHNSHAREDCHANNELVIEW C
  WHERE C.PARENT_CHANNEL = PC.ID
) ORDER BY PARENT_OR_SELF_LABEL, PARENT_OR_SELF_ID;

 070701000004B9000081B400000000000000000000000167AE111400000832000000000000000000000000000000000000006500000000susemanager-schema/upgrade/spacewalk-schema-0.3-to-spacewalk-schema-0.4/145-rhnAvailableChannels.sql  --
-- Copyright (c) 2008 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
-- tricky view.  it explodes to a full cartesian product when
-- not queried via org_id, so DO NOT DO THAT :)

create or replace view
rhnAvailableChannels
(
    org_id,
    channel_id,
    channel_depth,
    channel_name,
    channel_arch_id,
    padded_name,
    current_members,
    available_members,
    last_modified,
    channel_label,
    parent_or_self_label,
    parent_or_self_id 
)
as
SELECT
    CT.org_id,
    CT.id, 
    CT.depth, 
    CT.name, 
    CT.channel_arch_id, 
    CT.padded_name,
    (SELECT COUNT(1)
     FROM rhnServer S 
     INNER JOIN rhnServerChannel SC
       ON SC.server_id = S.id
     WHERE SC.channel_id = CT.id AND
           S.org_id = CT.org_id),
    rhn_channel.available_chan_subscriptions(CT.id, CT.org_id),
    CT.last_modified,
    CT.label,
    CT.parent_or_self_label,
    CT.parent_or_self_id
FROM
    rhnOrgChannelTreeView CT
UNION
SELECT
    CT.org_id,
    CT.id,
    CT.depth,
    CT.name,
    CT.channel_arch_id,
    CT.padded_name,
    (SELECT COUNT(1)
     FROM rhnServer S 
     INNER JOIN rhnServerChannel SC
       ON SC.server_id = S.id
     WHERE SC.channel_id = CT.id AND
           S.org_id = CT.org_id),
    NULL,
    CT.last_modified,
    CT.label,
    CT.parent_or_self_label,
    CT.parent_or_self_id
FROM
    rhnSharedChannelTreeView CT
/

--
--
-- Revision 1.17  2004/04/14 00:09:24  pjones
-- bugzilla: 120761 -- split rhnChannelPermissions into two tables, eliminating
-- a frequent full table scan
--
  070701000004BA000081B400000000000000000000000167AE11140000042C000000000000000000000000000000000000006300000000susemanager-schema/upgrade/spacewalk-schema-0.3-to-spacewalk-schema-0.4/146-rhnKSData-add-type.sql    --
-- Copyright (c) 2008 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
-- $Id$
--

ALTER TABLE rhnKsData
ADD ks_type varchar(8);

UPDATE rhnKsData SET ks_type = 'wizard';

ALTER TABLE rhnKsData 
MODIFY ks_type CONSTRAINT rhn_ks_type_nn NOT NULL;

ALTER TABLE rhnKsData 
ADD CONSTRAINT rhn_ks_type_ck CHECK (ks_type in ('wizard', 'raw'));

show errors

-- $Log$
-- Revision 2  2008/12/02 16:51:05.2 jsherrill
-- Add cobbler_id column
--
-- Revision 1  2008/10/01 7:01:05  mmccune
-- Removed the unused name column
070701000004BB000081B400000000000000000000000167AE111400002581000000000000000000000000000000000000005C00000000susemanager-schema/upgrade/spacewalk-schema-0.3-to-spacewalk-schema-0.4/150-rhn_org.pkb.sql   --
-- Copyright (c) 2008 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--

CREATE OR REPLACE
PACKAGE BODY rhn_org
IS
	body_version varchar2(100) := '';

    FUNCTION find_server_group_by_type(org_id_in NUMBER, group_label_in VARCHAR2) 
    RETURN NUMBER
    IS
	server_group       server_group_by_label%ROWTYPE;
    BEGIN
    	OPEN server_group_by_label(org_id_in, group_label_in);
	FETCH server_group_by_label INTO server_group;
	CLOSE server_group_by_label;

	RETURN server_group.id;
    END find_server_group_by_type;
    
    procedure delete_org (
        org_id_in in number
    )
    is

        cursor users is
        select id
        from web_contact
        where org_id = org_id_in;

		cursor servers(org_id_in in number) is
        select	id
        from	rhnServer
        where	org_id = org_id_in;

        cursor config_channels is
        select id
        from rhnConfigChannel
        where org_id = org_id_in;

    begin

        if org_id_in = 1 then
            rhn_exception.raise_exception('cannot_delete_base_org');
        end if;

        -- Delete all users.
        for u in users loop
            rhn_org.delete_user(u.id, 1);
        end loop;

        -- Delete all servers.
        for s in servers(org_id_in) loop
            delete_server(s.id);
        end loop;

        -- Delete all config channels.
        for c in config_channels loop
            rhn_config.delete_channel(c.id);
        end loop;

        -- Give the org's entitlements back to the main org.
        rhn_entitlements.remove_org_entitlements(org_id_in);

        -- Clean up tables where we don't have a cascading delete.
        delete from rhnChannel where org_id = org_id_in;
        delete from rhnDailySummaryQueue where org_id = org_id_in;
        delete from rhnOrgQuota where org_id = org_id_in;
        delete from rhnOrgInfo where org_id = org_id_in;
        delete from rhnFileList where org_id = org_id_in;
        delete from rhnServerGroup where org_id = org_id_in;
        delete from rhn_check_suites where customer_id = org_id_in;
        delete from rhn_command_target where customer_id = org_id_in;
        delete from rhn_contact_groups where customer_id = org_id_in;
        delete from rhn_notification_formats where customer_id = org_id_in;
        delete from rhn_probe where customer_id = org_id_in;
        delete from rhn_redirects where customer_id = org_id_in;
        delete from rhn_sat_cluster where customer_id = org_id_in;
        delete from rhn_schedules where customer_id = org_id_in;

        -- Delete the org.
        delete from web_customer where id = org_id_in;

    end delete_org;

	procedure delete_user(user_id_in in number, deleting_org in number := 0) is
		cursor is_admin is
			select	1
			from	rhnUserGroupType	ugt,
					rhnUserGroup		ug,
					rhnUserGroupMembers	ugm
			where	ugm.user_id = user_id_in
				and ugm.user_group_id = ug.id
				and ug.group_type = ugt.id
				and ugt.label = 'org_admin';
		cursor servergroups_needing_admins is
			select	usgp.server_group_id	server_group_id
			from	rhnUserServerGroupPerms	usgp
			where	1=1
				and usgp.user_id = user_id_in
				and not exists (
					select	1
					from	rhnUserServerGroupPerms	sq_usgp
					where	1=1
						and sq_usgp.server_group_id = usgp.server_group_id
						and	sq_usgp.user_id != user_id_in
				);
		cursor messages is
			select	message_id id
			from	rhnUserMessage
			where	user_id = user_id_in;
		users			number;
		our_org_id		number;
		other_users		number;
		other_org_admin	number;
        other_user_id  number;
	begin
		select	wc.org_id
		into	our_org_id
		from	web_contact wc
		where	id = user_id_in;

		-- find any other users
		begin
			select	id, 1
			into	other_user_id, other_users
			from	web_contact
			where	1=1
				and org_id = our_org_id
				and id != user_id_in
				and rownum = 1;
		exception
			when no_data_found then
				other_users := 0;
		end;

		-- now do org admin stuff
		if other_users != 0 then
			for ignore in is_admin loop
				begin 
					select	new_ugm.user_id
					into	other_org_admin
					from	rhnUserGroupMembers	new_ugm,
							rhnUserGroupType	ugt,
							rhnUserGroup		ug,
							rhnUserGroupMembers	ugm
					where	ugm.user_id = user_id_in
						and ugm.user_group_id = ug.id
						and ug.group_type = ugt.id
						and ugt.label = 'org_admin'
						and ug.id = new_ugm.user_group_id
						and new_ugm.user_id != user_id_in
						and rownum = 1;
				exception
					when no_data_found then
                        -- If we're deleting the org, we don't want to raise
                        -- the exception.
                        if deleting_org = 0 then
    						rhn_exception.raise_exception('cannot_delete_user');
                        end if;
				end;

				for sg in servergroups_needing_admins loop
					rhn_user.add_servergroup_perm(other_org_admin,
						sg.server_group_id);
				end loop;
			end loop;
		end if;

		-- and now things for every user
		for message in messages loop
			delete
				from	rhnUserMessage
				where	user_id = user_id_in
					and message_id = message.id;
			begin
				select	1
				into	users
				from	rhnUserMessage
				where	message_id = message.id
					and rownum = 1;
				delete
					from	rhnMessage
					where	id = message.id;
			exception
				when no_data_found then
					null;
			end;
		end loop;
		delete from rhn_command_queue_sessions where contact_id = user_id_in;
		delete from rhn_contact_groups
		where recid in (
			select contact_group_id
			from rhn_contact_group_members
			where member_contact_method_id in (
				select recid from rhn_contact_methods
				where contact_id = user_id_in
				)
			)
			and not exists (
				select 1
				from rhn_contact_group_members, rhn_contact_methods
				where rhn_contact_groups.recid = rhn_contact_group_members.contact_group_id
					and rhn_contact_group_members.member_contact_method_id = rhn_contact_methods.recid
					and rhn_contact_methods.contact_id <> user_id_in
			);
		delete from rhn_contact_methods where contact_id = user_id_in;
		delete from rhn_redirects where contact_id = user_id_in;
		delete from rhnUserServerPerms where user_id = user_id_in;
                delete from rhnAppInstallSession where user_id = user_id_in;
		if other_users != 0 then
			update		rhnRegToken
				set		user_id = nvl(other_org_admin, other_user_id)
				where	org_id = our_org_id
					and user_id = user_id_in;
			begin
				delete from web_contact where id = user_id_in;
			exception
				when others then
					rhn_exception.raise_exception('cannot_delete_user');
			end;
        -- Just Delete the user
		else
            begin
                delete from web_contact where id = user_id_in;
		    exception
				when others then
					rhn_exception.raise_exception('cannot_delete_user');
			end;
		end if;
		return;
	end delete_user;

END rhn_org;
/
SHOW ERRORS

--
-- Revision 1.22  2004/10/29 04:50:49  pjones
-- bugzilla: 135179 -- fix org admin swapping during user deletion
--
-- Revision 1.21  2004/07/13 22:46:04  pjones
-- bugzilla: 125938 -- nothing uses update_errata_cache() any more, remove it
--
-- Revision 1.20  2004/07/02 22:24:38  pjones
-- bugzilla: none -- typo fix
--
-- Revision 1.19  2004/07/02 19:19:02  pjones
-- bugzilla: 125937 -- use rhn_user to grant roles to users
--
-- Revision 1.18  2004/05/28 22:21:36  pjones
-- bugzilla: none -- update for monitoring schema
--
-- Revision 1.17  2004/04/05 16:31:07  pjones
-- bugzilla: 120032 -- raise "cannot_delete_user" if web_contact or web_customer
-- has a cascade problem
--
-- Revision 1.16  2004/03/15 17:10:28  pjones
-- bugzilla: 118244 -- delete servers explicitly while deleting lone users
--
-- Revision 1.15  2004/02/09 17:14:54  pjones
-- bugzilla: none -- fix log garbage
--
-- Revision 1.14  2004/01/22 19:44:42  pjones
-- bugzilla: 106562 -- fix exceptions on delete_user()
--
-- Revision 1.13  2004/01/20 17:00:48  pjones
-- bugzilla: none -- try to make delete_user() succeed when there are
-- server groups that have been snapshotted
--
-- Revision 1.12  2004/01/14 20:22:03  pjones
-- bugzilla: 113344 -- no deleting from rhnServerGroup, use the api instead
--
-- Revision 1.11  2003/03/20 17:08:16  pjones
-- avoid the server group members trigger that updates last_modified; it'll
-- cause a mutating table error
--
-- Revision 1.10  2003/03/17 16:31:25  pjones
-- use "on delete set null" where applicable
--
-- Revision 1.9  2003/03/15 00:31:07  pjones
-- bugzilla: none
--
-- tested wrong table for perms on a server group
--
-- Revision 1.8  2003/03/15 00:23:36  pjones
-- bugzilla: 83631
--
-- working delete_user
--
-- Revision 1.7  2003/03/03 23:39:36  pjones
-- different delete_user; this one might actually work.
--
-- Takes about 18 seconds, which seems kindof slow, but isn't
-- intolerable I don't think...
--
-- Revision 1.6  2003/03/02 18:07:00  pjones
-- make it use marty's test instead of is_satellite(); in the sat env,
-- marty's test _is_ is_satellite()
--
-- Revision 1.5  2003/02/18 16:35:45  pjones
-- delete_user
--
-- Revision 1.4  2002/05/10 22:08:23  pjones
-- id/log
--
   070701000004BC000081B400000000000000000000000167AE11140000030B000000000000000000000000000000000000006900000000susemanager-schema/upgrade/spacewalk-schema-0.3-to-spacewalk-schema-0.4/151-rhnServer-add-cobbler_id.sql  --
-- Copyright (c) 2008 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
-- $Id$
--



ALTER TABLE rhnServer
ADD cobbler_id varchar(64);

show errors

-- $Log$
-- Revision 1  2009/01/06 16:51 mmccune
-- Add cobbler_id column

 070701000004BD000081B400000000000000000000000167AE111400000497000000000000000000000000000000000000006D00000000susemanager-schema/upgrade/spacewalk-schema-0.3-to-spacewalk-schema-0.4/152-rhnKSInstallType-add-generic.sql  --
-- Copyright (c) 2008 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
-- $Id$
--

insert into rhnKSInstallType (id, label, name)
        values (rhn_ksinstalltype_id_seq.nextval,
                'fedora_8','Fedora 8'
        );

insert into rhnKSInstallType (id, label, name)
        values (rhn_ksinstalltype_id_seq.nextval,
                'fedora_10','Fedora 10'
        );

insert into rhnKSInstallType (id, label, name)
        values (rhn_ksinstalltype_id_seq.nextval,
                'generic_rpm','Generic RPM'
        );

show errors

-- $Log$
-- Revision 1  2009/01/06 16:51 mmccune
-- Add cobbler_id column

 070701000004BE000081B400000000000000000000000167AE1114000002BC000000000000000000000000000000000000006C00000000susemanager-schema/upgrade/spacewalk-schema-0.3-to-spacewalk-schema-0.4/153-rhnErrata-increase-advisory.sql   --
-- Copyright (c) 2008 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--
--
-- $Id$
--

ALTER TABLE rhnErrata MODIFY advisory varchar2(37);
show errors
070701000004BF000081B400000000000000000000000167AE1114000002BF000000000000000000000000000000000000006F00000000susemanager-schema/upgrade/spacewalk-schema-0.3-to-spacewalk-schema-0.4/154-rhnErrataTmp-increase-advisory.sql    --
-- Copyright (c) 2008 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--
--
-- $Id$
--

ALTER TABLE rhnErrataTmp MODIFY advisory varchar2(37);
show errors
 070701000004C0000081B400000000000000000000000167AE1114000002C5000000000000000000000000000000000000007300000000susemanager-schema/upgrade/spacewalk-schema-0.3-to-spacewalk-schema-0.4/155-rhnPackageCapability-increase-name.sql    --
-- Copyright (c) 2008 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--
--
-- $Id$
--

ALTER TABLE rhnPackageCapability MODIFY name varchar2(4000);
show errors
   070701000004C1000081B400000000000000000000000167AE1114000003B3000000000000000000000000000000000000006900000000susemanager-schema/upgrade/spacewalk-schema-0.3-to-spacewalk-schema-0.4/156-rhnPackage-compat-number.sql  --
-- Copyright (c) 2008--2010 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--
--
-- $Id$
--

alter trigger rhn_package_mod_trig disable;
alter TABLE rhnPackage add (compat_new number(1) default 0);
update rhnPackage set compat_new = compat;
alter trigger rhn_package_mod_trig enable;
alter TABLE rhnPackage drop column compat;
alter TABLE rhnPackage rename column compat_new to compat;
show errors
 070701000004C2000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000004800000000susemanager-schema/upgrade/spacewalk-schema-0.4-to-spacewalk-schema-0.5   070701000004C3000081B400000000000000000000000167AE111400003AE1000000000000000000000000000000000000005D00000000susemanager-schema/upgrade/spacewalk-schema-0.4-to-spacewalk-schema-0.5/100-errata-cache.sql  

drop index rhn_snec_eid_sid_idx;
drop index rhn_snec_sid_eid_idx;
drop index rhn_snec_oid_eid_sid_idx;
drop table rhnServerNeededErrataCache;


/* Remove org id, we don't need it */
ALTER TABLE rhnServerNeededPackageCache DROP CONSTRAINT rhn_sncp_oid_nn;
ALTER TABLE rhnServerNeededPackageCache DROP CONSTRAINT rhn_sncp_oid_fk;
drop index rhn_snpc_oid_idx;
alter table  rhnServerNeededPackageCache drop column  org_id;

/* drop old indexes */
drop index rhn_snpc_pid_idx;
drop index rhn_snpc_sid_idx;
drop index rhn_snpc_eid_idx;


/* rename table */
alter table
   rhnServerNeededPackageCache
  rename to
   rhnServerNeededCache;


/* create new indexes */
create index rhn_snc_pid_idx
        on rhnServerNeededCache(package_id)
        parallel
        tablespace [[128m_tbs]]
        nologging;

create index rhn_snc_sid_idx
        on rhnServerNeededCache(server_id)
        parallel
        tablespace [[128m_tbs]]
        nologging;

create index rhn_snc_eid_idx
        on rhnServerNeededCache(errata_id)
        parallel
        tablespace [[128m_tbs]]
        nologging;


create index rhn_snc_speid_idx
        on rhnServerNeededCache(server_id, package_id, errata_id)
        parallel
        tablespace [[128m_tbs]]
        nologging;



create or replace view
rhnServerNeededPackageCache
(
    server_id,
    package_id,
    errata_id
)
as
select
        server_id, 
        package_id,
        max(errata_id) as errata_id
        from rhnServerNeededCache 
        group by server_id, package_id;


create or replace view
rhnServerNeededErrataCache
(
    server_id,
    errata_id
)
as
select
   distinct  server_id, errata_id
   from rhnServerNeededCache;


CREATE OR REPLACE VIEW
rhnServerNeededView
(
    org_id,
    server_id,
    errata_id,
    package_id,
    package_name_id
)
AS
SELECT   distinct  S.org_id,
         S.id,
         PE.errata_id,
         P.id,
         P.name_id
FROM
         rhnPackage P,
         rhnServerPackageArchCompat SPAC,
         rhnPackageEVR P_EVR,
         rhnPackageEVR SP_EVR,
         rhnServerPackage SP,
         rhnChannelPackage CP,
         rhnServerChannel SC,
         rhnServer S,
         rhnErrataPackage PE,
         rhnChannelErrata EC
WHERE
         SC.server_id = S.id
  AND    SC.channel_id = CP.channel_id
  AND    CP.package_id = P.id
  AND    P.id = PE.package_id
  AND    PE.errata_id = EC.errata_id
  AND    EC.channel_id = SC.channel_id
  AND    p.package_arch_id = spac.package_arch_id
  AND    spac.server_arch_id = s.server_arch_id
  AND    SP_EVR.id = SP.evr_id
  AND    P_EVR.id = P.evr_id
  AND    SP.server_id = S.id
  AND    SP.name_id = P.name_id
  AND    SP.evr_id != P.evr_id
  AND    SP_EVR.evr < P_EVR.evr
  AND    SP_EVR.evr = (SELECT MAX(PE.evr) FROM rhnServerPackage SP2, rhnPackageEvr PE WHERE PE.id = SP2.evr_id AND SP2.server_id = SP.server_id AND SP2.name_id = SP.name_id)
  UNION
SELECT   distinct  S.org_id,
         S.id,
         NULL as errata_id,
         P.id,
         P.name_id
FROM
         rhnPackage P,
         rhnServerPackageArchCompat SPAC,
         rhnPackageEVR P_EVR,
         rhnPackageEVR SP_EVR,
         rhnServerPackage SP,
         rhnChannelPackage CP,
         rhnServerChannel SC,
         rhnServer S
WHERE
         SC.server_id = S.id
  AND    SC.channel_id = CP.channel_id
  AND    CP.package_id = P.id
  AND    P.id not in
                ( select EP.package_id
                        from rhnErrataPackage EP inner join
                                rhnChannelErrata EC on EP.errata_id = EC.errata_id
                        where  EC.channel_id = SC.channel_id)
  AND    p.package_arch_id = spac.package_arch_id
  AND    spac.server_arch_id = s.server_arch_id
  AND    SP_EVR.id = SP.evr_id
  AND    P_EVR.id = P.evr_id
  AND    SP.server_id = S.id
  AND    SP.name_id = P.name_id
  AND    SP.evr_id != P.evr_id
  AND    SP_EVR.evr < P_EVR.evr
  AND    SP_EVR.evr = (SELECT MAX(PE.evr) FROM rhnServerPackage SP2, rhnPackageEvr PE WHERE PE.id = SP2.evr_id AND SP2.server_id = SP.server_id AND SP2.name_id = SP.name_id);



CREATE OR REPLACE VIEW rhnServerErrataTypeView
(
        server_id,
        errata_id,
        errata_type
)
AS
SELECT
        SNEC.server_id,
        SNEC.errata_id,
        E.advisory_type
FROM    rhnErrata E,
        rhnServerNeededErrataCache SNEC
WHERE   E.id = SNEC.errata_id
GROUP BY SNEC.server_id, SNEC.errata_id, E.advisory_type;


CREATE OR REPLACE PROCEDURE
queue_server(server_id_in IN NUMBER, immediate_in IN NUMBER := 1)
IS
    org_id_tmp NUMBER;
BEGIN
    IF immediate_in > 0
    THEN
        DELETE FROM rhnServerNeededCache WHERE server_id = server_id_in;
        INSERT INTO rhnServerNeededCache
            (SELECT server_id, errata_id, package_id
               FROM rhnServerNeededView
              WHERE server_id = server_id_in);

    ELSE
          SELECT org_id INTO org_id_tmp FROM rhnServer WHERE id = server_id_in;

          INSERT
            INTO rhnTaskQueue
                 (org_id, task_name, task_data)
          VALUES (org_id_tmp,
                  'update_server_errata_cache',
                  server_id_in);
    END IF;
END queue_server;

/

create or replace procedure
delete_errata (
        errata_id_in in number
) is
begin
        delete from rhnServerNeededCache where errata_id = errata_id_in;
        delete from rhnPaidErrataTempCache where errata_id = errata_id_in;
        delete from rhnErrataFile where errata_id = errata_id_in;
        delete from rhnErrataPackage where errata_id = errata_id_in;
        delete from rhnErrata where id = errata_id_in;
        delete from rhnErrataTmp where id = errata_id_in;
end delete_errata;
/

create or replace
procedure delete_server (
	server_id_in in number
) is
	cursor servergroups is
		select	server_id, server_group_id
		from	rhnServerGroupMembers sgm
		where	sgm.server_id = server_id_in;
	cursor configchannels is
		select	cc.id
		from	rhnConfigChannel cc,
			rhnConfigChannelType cct,
			rhnServerConfigChannel scc
		where	1=1
			and scc.server_id = server_id_in
			and scc.config_channel_id = cc.id
			-- these config channel types are reserved
			-- for use by a single server, so we don't
			-- need to check for other servers subscribed
			and cct.label in
				('local_override','server_import')
			and cct.id = cc.confchan_type_id;
        type filelistsid_t is table of rhnServerPreserveFileList.file_list_id%type;
        filelistsid_c filelistsid_t;

        type probesid_t is table of rhn_check_probe.probe_id%type;
        probesid_c probesid_t;

    is_virt number := 0;
begin
	rhn_channel.delete_server_channels(server_id_in);
	-- rhn_channel.clear_subscriptions(server_id_in);

        -- filelists
	select	spfl.file_list_id id bulk collect into filelistsid_c
	  from	rhnServerPreserveFileList spfl
	 where	spfl.server_id = server_id_in
			and not exists (
				select	1
				from	rhnServerPreserveFileList
				where	file_list_id = spfl.file_list_id
					and server_id != server_id_in
				union
				select	1
				from	rhnKickstartPreserveFileList
				where	file_list_id = spfl.file_list_id
			);
        if filelistsid_c.first is not null then
            forall i in filelistsid_c.first..filelistsid_c.last
                delete from rhnFileList where id = filelistsid_c(i);
        end if;

	for configchannel in configchannels loop
		rhn_config.delete_channel(configchannel.id);
	end loop;

      select count(1) into is_virt
        from rhnServerEntitlementView
       where server_id = server_id_in
         and label in ('virtualization_host', 'virtualization_host_platform')
         and rownum <= 1;

	for sgm in servergroups loop
		rhn_server.delete_from_servergroup(
			sgm.server_id, sgm.server_group_id);
	end loop;

    if is_virt = 1 then
        rhn_entitlements.repoll_virt_guest_entitlements(server_id_in);
    end if;
	update rhnKickstartSession
		set old_server_id = case when old_server_id = server_id_in then null else old_server_id end,
		    new_server_id = case when new_server_id = server_id_in then null else new_server_id end
		where old_server_id = server_id_in 
		   or new_server_id = server_id_in;

	rhn_channel.clear_subscriptions(server_id_in,1);
        delete from rhnVirtualInstance vi
	      where (host_system_id = server_id_in and virtual_system_id is null)
                 or (virtual_system_id = server_id_in and host_system_id is null)
                 or (vi.virtual_system_id = server_id_in and vi.modified < (select max(vi2.modified)
                    from rhnVirtualInstance vi2 where vi2.uuid = vi.uuid));
						
        -- this is merge of two single updates:
        --  update ... set host_system_id = null where host_system_id = server_id_in;
        --  update ... set virtual_system_id = null where virtual_system_id = server_id_in;
        -- so we scan rhnVirtualInstance table only once
        update rhnVirtualInstance
	   set host_system_id = case when host_system_id = server_id_in then null else host_system_id end,
	       virtual_system_id = case when virtual_system_id = server_id_in then null else virtual_system_id end
	 where host_system_id = server_id_in
	    or virtual_system_id = server_id_in;
		
        -- this is merge of two single updates:
        --  update ... set old_host_system_id = null when old_host_system_id = server_id_in;
        --  update ... set new_host_system_id = null when new_host_system_id = server_id_in;
        -- so we scan rhnVirtualInstanceEventLog table only once
	update rhnVirtualInstanceEventLog
	   set old_host_system_id = case when old_host_system_id = server_id_in then null else old_host_system_id end,
               new_host_system_id = case when new_host_system_id = server_id_in then null else new_host_system_id end
         where old_host_system_id = server_id_in
            or new_host_system_id = server_id_in;
		 
	-- We're deleting everything with a foreign key to rhnServer
	-- here, now.  I'm hoping this will help aleviate our deadlock
	-- problem.

	delete from rhnActionConfigChannel where server_id = server_id_in;
	delete from rhnActionConfigRevision where server_id = server_id_in;
	delete from rhnActionPackageRemovalFailure where server_id = server_id_in;
	delete from rhnChannelFamilyLicenseConsent where server_id = server_id_in;
	delete from rhnClientCapability where server_id = server_id_in;
	delete from rhnCpu where server_id = server_id_in;
	-- there's still a cascade here, because the constraint keeps the
	-- table locked for too long to rebuild it.  Ugh...
	delete from rhnDevice where server_id = server_id_in;
	delete from rhnProxyInfo where server_id = server_id_in;
	delete from rhnRam where server_id = server_id_in;
	delete from rhnRegToken where server_id = server_id_in;
	delete from rhnSNPServerQueue where server_id = server_id_in;
	delete from rhnSatelliteChannelFamily where server_id = server_id_in;
	delete from rhnSatelliteInfo where server_id = server_id_in;
	-- this cascades to rhnActionConfigChannel and rhnActionConfigFileName
	delete from rhnServerAction where server_id = server_id_in;
	delete from rhnServerActionPackageResult where server_id = server_id_in;
	delete from rhnServerActionScriptResult where server_id = server_id_in;
	delete from rhnServerActionVerifyResult where server_id = server_id_in;
	delete from rhnServerActionVerifyMissing where server_id = server_id_in;
	-- counts are handled above.  this should be a delete_ function.
	delete from rhnServerChannel where server_id = server_id_in;
	delete from rhnServerConfigChannel where server_id = server_id_in;
	delete from rhnServerCustomDataValue where server_id = server_id_in;
	delete from rhnServerDMI where server_id = server_id_in;
	delete from rhnServerMessage where server_id = server_id_in;
	-- this gets rhnServerMessage (only) on cascade; it's handled just above
	delete from rhnServerEvent where server_id = server_id_in;
	delete from rhnServerHistory where server_id = server_id_in;
	delete from rhnServerInfo where server_id = server_id_in;
	delete from rhnServerInstallInfo where server_id = server_id_in;
	delete from rhnServerLocation where server_id = server_id_in;
	delete from rhnServerLock where server_id = server_id_in;
	delete from rhnServerNeededCache where server_id = server_id_in;
	delete from rhnServerNetwork where server_id = server_id_in;
	delete from rhnServerNotes where server_id = server_id_in;
	-- I'm not removing the foreign key from rhnServerPackage; that'll
	-- take forever.  Do the delete anyway.
	delete from rhnServerPackage where server_id = server_id_in;
	delete from rhnServerTokenRegs where server_id = server_id_in;
	delete from rhnSnapshotTag where server_id = server_id_in;
	-- this cascades to:
	--   rhnSnapshotChannel, rhnSnapshotConfigChannel, rhnSnapshotPackage, 
	--   rhnSnapshotConfigRevision, rhnSnapshotServerGroup, 
	--   rhnSnapshotTag.
	-- We may want to consider delete_snapshot() at some point, but
	--   I don't think we need to yet.
	delete from rhnSnapshot where server_id = server_id_in;
	delete from rhnTransaction where server_id = server_id_in;
	delete from rhnUserServerPrefs where server_id = server_id_in;
	-- hrm, this one's interesting... we _probably_ should delete
	-- everything for the parent server_id when we delete the proxy,
	-- but we don't currently.
	delete from rhnServerPath where server_id_in in (server_id, proxy_server_id);
	delete from rhnUserServerPerms where server_id = server_id_in;

	delete from rhn_interface_monitoring where server_id = server_id_in;
	delete from rhnServerNetInterface where server_id = server_id_in;
	delete from rhn_server_monitoring_info where recid = server_id_in;

	delete from rhnAppInstallSession where server_id = server_id_in;
	delete from rhnServerUuid where server_id = server_id_in;
    -- We delete all the probes running directly against this system
    -- and any probes that were using this Server as a Proxy Scout.
     SELECT CP.probe_id bulk collect into probesid_c
       FROM rhn_check_probe CP  
      WHERE CP.host_id = server_id_in
         OR CP.sat_cluster_id in
    (SELECT SN.sat_cluster_id
       FROM rhn_sat_node SN
      WHERE SN.server_id = server_id_in);

    if probesid_c.first is not null then
        FORALL i IN probesid_c.first..probesid_c.last
            DELETE FROM rhn_probe_state PS WHERE PS.probe_id = probesid_c(i);
        FORALL i IN probesid_c.first..probesid_c.last
            DELETE FROM rhn_probe P  WHERE P.recid = probesid_c(i);
    end if;

	delete from rhn_check_probe where host_id = server_id_in;
	delete from rhn_host_probe where host_id = server_id_in;

    delete from rhn_sat_cluster where recid in
      ( select sat_cluster_id from rhn_sat_node where server_id = server_id_in );

	delete from rhn_sat_node where server_id = server_id_in;
	
	-- now get rhnServer itself.
	delete
	from	rhnServer
		where id = server_id_in;

	delete
	from	rhnSet
	where	1=1
		and user_id in (
			select	wc.id
			from	rhnServer rs,
				web_contact wc
			where	rs.id = server_id_in
				and rs.org_id = wc.org_id
		)
		and label = 'system_list'
		and element = server_id_in;
end delete_server;
/
   070701000004C4000081B400000000000000000000000167AE1114000009D8000000000000000000000000000000000000006400000000susemanager-schema/upgrade/spacewalk-schema-0.4-to-spacewalk-schema-0.5/150-rhnMultiorg-sharing.sql   --
-- Copyright (c) 2008 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
-- $Id$
--
ALTER TABLE rhnPackageChangeLog
  DROP constraint rhn_pkg_changelog_pid_fk;

ALTER TABLE rhnPackageChangeLog
  ADD constraint rhn_pkg_changelog_pid_fk
    foreign key (package_id)
    references rhnPackage (id)
    on delete cascade;

ALTER TABLE rhnPackageFile
  DROP constraint rhn_package_file_pid_fk;

ALTER TABLE rhnPackageFile
  ADD constraint rhn_package_file_pid_fk
    foreign key (package_id)
    references rhnPackage (id)
    on delete cascade;

ALTER TABLE rhnPackageObsoletes
  DROP constraint rhn_pkg_obsoletes_package_fk;

ALTER TABLE rhnPackageObsoletes
  ADD constraint rhn_pkg_obsoletes_package_fk
    foreign key (package_id)
    references rhnPackage (id)
    on delete cascade;

ALTER TABLE rhnPackageConflicts
  DROP constraint rhn_pkg_conflicts_package_fk;

ALTER TABLE rhnPackageConflicts
  ADD constraint rhn_pkg_conflicts_package_fk
    foreign key (package_id)
    references rhnPackage (id)
    on delete cascade;

ALTER TABLE rhnPackageProvides
  DROP constraint rhn_pkg_provides_package_fk;

ALTER TABLE rhnPackageProvides
  ADD constraint rhn_pkg_provides_package_fk
    foreign key (package_id)
    references rhnPackage (id)
    on delete cascade;

ALTER TABLE rhnPackageRequires
  DROP constraint rhn_pkg_requires_package_fk;

ALTER TABLE rhnPackageRequires
  ADD constraint rhn_pkg_requires_package_fk
    foreign key (package_id)
    references rhnPackage (id)
    on delete cascade;

ALTER TABLE rhnSystemMigrations
  DROP constraint rhn_sys_mig_oidto_fk;

ALTER TABLE rhnSystemMigrations
  ADD constraint rhn_sys_mig_oidto_fk
    foreign key (org_id_to)
    references web_customer (id)
    on delete set null;

ALTER TABLE rhnSystemMigrations
  DROP constraint rhn_sys_mig_oidfrm_fk;

ALTER TABLE rhnSystemMigrations
  ADD constraint rhn_sys_mig_oidfrm_fk
    foreign key (org_id_from)
    references web_customer (id)
    on delete set null;
070701000004C5000081B400000000000000000000000167AE111400002836000000000000000000000000000000000000005C00000000susemanager-schema/upgrade/spacewalk-schema-0.4-to-spacewalk-schema-0.5/151-rhn_org.pkb.sql   --
-- Copyright (c) 2008 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--

CREATE OR REPLACE
PACKAGE BODY rhn_org
IS
	body_version varchar2(100) := '';

    FUNCTION find_server_group_by_type(org_id_in NUMBER, group_label_in VARCHAR2) 
    RETURN NUMBER
    IS
	server_group       server_group_by_label%ROWTYPE;
    BEGIN
    	OPEN server_group_by_label(org_id_in, group_label_in);
	FETCH server_group_by_label INTO server_group;
	CLOSE server_group_by_label;

	RETURN server_group.id;
    END find_server_group_by_type;
    
    procedure delete_org (
        org_id_in in number
    )
    is
        cursor users is
        select id
        from web_contact
        where org_id = org_id_in;

	cursor servers(org_id_in in number) is
        select	id
        from	rhnServer
        where	org_id = org_id_in;

        cursor config_channels is
        select id
        from rhnConfigChannel
        where org_id = org_id_in;

	cursor custom_channels is
        select	id
        from	rhnChannel
        where	org_id = org_id_in;

	cursor errata is
		select id
		from   rhnErrata
		where  org_id = org_id_in;

    begin

        if org_id_in = 1 then
            rhn_exception.raise_exception('cannot_delete_base_org');
        end if;

        -- Delete all users.
        for u in users loop
            rhn_org.delete_user(u.id, 1);
        end loop;

        -- Delete all servers.
        for s in servers(org_id_in) loop
            delete_server(s.id);
        end loop;

        -- Delete all config channels.
        for c in config_channels loop
            rhn_config.delete_channel(c.id);
        end loop;

        -- Delete all custom channels.
        for cc in custom_channels loop
          delete from rhnServerChannel where channel_id = cc.id;
          delete from rhnServerProfilePackage where server_profile_id in (
            select id from rhnServerProfile where base_channel = cc.id
          );
          delete from rhnServerProfile where base_channel = cc.id;
        end loop;

		-- Delete all errata packages
		for e in errata loop
			delete from rhnErrataPackage where errata_id = e.id;
		end loop;

        -- Give the org's entitlements back to the main org.
        rhn_entitlements.remove_org_entitlements(org_id_in);

        -- Clean up tables where we don't have a cascading delete.
        delete from rhnChannel where org_id = org_id_in;
        delete from rhnDailySummaryQueue where org_id = org_id_in;
        delete from rhnOrgQuota where org_id = org_id_in;
        delete from rhnOrgInfo where org_id = org_id_in;
        delete from rhnFileList where org_id = org_id_in;
        delete from rhnServerGroup where org_id = org_id_in;
        delete from rhn_check_suites where customer_id = org_id_in;
        delete from rhn_command_target where customer_id = org_id_in;
        delete from rhn_contact_groups where customer_id = org_id_in;
        delete from rhn_notification_formats where customer_id = org_id_in;
        delete from rhn_probe where customer_id = org_id_in;
        delete from rhn_redirects where customer_id = org_id_in;
        delete from rhn_sat_cluster where customer_id = org_id_in;
        delete from rhn_schedules where customer_id = org_id_in;

        -- Delete the org.
        delete from web_customer where id = org_id_in;

    end delete_org;

	procedure delete_user(user_id_in in number, deleting_org in number := 0) is
		cursor is_admin is
			select	1
			from	rhnUserGroupType	ugt,
					rhnUserGroup		ug,
					rhnUserGroupMembers	ugm
			where	ugm.user_id = user_id_in
				and ugm.user_group_id = ug.id
				and ug.group_type = ugt.id
				and ugt.label = 'org_admin';
		cursor servergroups_needing_admins is
			select	usgp.server_group_id	server_group_id
			from	rhnUserServerGroupPerms	usgp
			where	1=1
				and usgp.user_id = user_id_in
				and not exists (
					select	1
					from	rhnUserServerGroupPerms	sq_usgp
					where	1=1
						and sq_usgp.server_group_id = usgp.server_group_id
						and	sq_usgp.user_id != user_id_in
				);
		cursor messages is
			select	message_id id
			from	rhnUserMessage
			where	user_id = user_id_in;
		users			number;
		our_org_id		number;
		other_users		number;
		other_org_admin	number;
        other_user_id  number;
	begin
		select	wc.org_id
		into	our_org_id
		from	web_contact wc
		where	id = user_id_in;

		-- find any other users
		begin
			select	id, 1
			into	other_user_id, other_users
			from	web_contact
			where	1=1
				and org_id = our_org_id
				and id != user_id_in
				and rownum = 1;
		exception
			when no_data_found then
				other_users := 0;
		end;

		-- now do org admin stuff
		if other_users != 0 then
			for ignore in is_admin loop
				begin 
					select	new_ugm.user_id
					into	other_org_admin
					from	rhnUserGroupMembers	new_ugm,
							rhnUserGroupType	ugt,
							rhnUserGroup		ug,
							rhnUserGroupMembers	ugm
					where	ugm.user_id = user_id_in
						and ugm.user_group_id = ug.id
						and ug.group_type = ugt.id
						and ugt.label = 'org_admin'
						and ug.id = new_ugm.user_group_id
						and new_ugm.user_id != user_id_in
						and rownum = 1;
				exception
					when no_data_found then
                        -- If we're deleting the org, we don't want to raise
                        -- the exception.
                        if deleting_org = 0 then
    						rhn_exception.raise_exception('cannot_delete_user');
                        end if;
				end;

				for sg in servergroups_needing_admins loop
					rhn_user.add_servergroup_perm(other_org_admin,
						sg.server_group_id);
				end loop;
			end loop;
		end if;

		-- and now things for every user
		for message in messages loop
			delete
				from	rhnUserMessage
				where	user_id = user_id_in
					and message_id = message.id;
			begin
				select	1
				into	users
				from	rhnUserMessage
				where	message_id = message.id
					and rownum = 1;
				delete
					from	rhnMessage
					where	id = message.id;
			exception
				when no_data_found then
					null;
			end;
		end loop;
		delete from rhn_command_queue_sessions where contact_id = user_id_in;
		delete from rhn_contact_groups
		where recid in (
			select contact_group_id
			from rhn_contact_group_members
			where member_contact_method_id in (
				select recid from rhn_contact_methods
				where contact_id = user_id_in
				)
			)
			and not exists (
				select 1
				from rhn_contact_group_members, rhn_contact_methods
				where rhn_contact_groups.recid = rhn_contact_group_members.contact_group_id
					and rhn_contact_group_members.member_contact_method_id = rhn_contact_methods.recid
					and rhn_contact_methods.contact_id <> user_id_in
			);
		delete from rhn_contact_methods where contact_id = user_id_in;
		delete from rhn_redirects where contact_id = user_id_in;
		delete from rhnUserServerPerms where user_id = user_id_in;
                delete from rhnAppInstallSession where user_id = user_id_in;
		if other_users != 0 then
			update		rhnRegToken
				set		user_id = nvl(other_org_admin, other_user_id)
				where	org_id = our_org_id
					and user_id = user_id_in;
			begin
				delete from web_contact where id = user_id_in;
			exception
				when others then
					rhn_exception.raise_exception('cannot_delete_user');
			end;
        -- Just Delete the user
		else
            begin
                delete from web_contact where id = user_id_in;
		    exception
				when others then
					rhn_exception.raise_exception('cannot_delete_user');
			end;
		end if;
		return;
	end delete_user;

END rhn_org;
/
SHOW ERRORS

--
-- Revision 1.22  2004/10/29 04:50:49  pjones
-- bugzilla: 135179 -- fix org admin swapping during user deletion
--
-- Revision 1.21  2004/07/13 22:46:04  pjones
-- bugzilla: 125938 -- nothing uses update_errata_cache() any more, remove it
--
-- Revision 1.20  2004/07/02 22:24:38  pjones
-- bugzilla: none -- typo fix
--
-- Revision 1.19  2004/07/02 19:19:02  pjones
-- bugzilla: 125937 -- use rhn_user to grant roles to users
--
-- Revision 1.18  2004/05/28 22:21:36  pjones
-- bugzilla: none -- update for monitoring schema
--
-- Revision 1.17  2004/04/05 16:31:07  pjones
-- bugzilla: 120032 -- raise "cannot_delete_user" if web_contact or web_customer
-- has a cascade problem
--
-- Revision 1.16  2004/03/15 17:10:28  pjones
-- bugzilla: 118244 -- delete servers explicitly while deleting lone users
--
-- Revision 1.15  2004/02/09 17:14:54  pjones
-- bugzilla: none -- fix log garbage
--
-- Revision 1.14  2004/01/22 19:44:42  pjones
-- bugzilla: 106562 -- fix exceptions on delete_user()
--
-- Revision 1.13  2004/01/20 17:00:48  pjones
-- bugzilla: none -- try to make delete_user() succeed when there are
-- server groups that have been snapshotted
--
-- Revision 1.12  2004/01/14 20:22:03  pjones
-- bugzilla: 113344 -- no deleting from rhnServerGroup, use the api instead
--
-- Revision 1.11  2003/03/20 17:08:16  pjones
-- avoid the server group members trigger that updates last_modified; it'll
-- cause a mutating table error
--
-- Revision 1.10  2003/03/17 16:31:25  pjones
-- use "on delete set null" where applicable
--
-- Revision 1.9  2003/03/15 00:31:07  pjones
-- bugzilla: none
--
-- tested wrong table for perms on a server group
--
-- Revision 1.8  2003/03/15 00:23:36  pjones
-- bugzilla: 83631
--
-- working delete_user
--
-- Revision 1.7  2003/03/03 23:39:36  pjones
-- different delete_user; this one might actually work.
--
-- Takes about 18 seconds, which seems kindof slow, but isn't
-- intolerable I don't think...
--
-- Revision 1.6  2003/03/02 18:07:00  pjones
-- make it use marty's test instead of is_satellite(); in the sat env,
-- marty's test _is_ is_satellite()
--
-- Revision 1.5  2003/02/18 16:35:45  pjones
-- delete_user
--
-- Revision 1.4  2002/05/10 22:08:23  pjones
-- id/log
--
  070701000004C6000081B400000000000000000000000167AE11140000052F000000000000000000000000000000000000006000000000susemanager-schema/upgrade/spacewalk-schema-0.4-to-spacewalk-schema-0.5/152-rhnSsmOperation.sql   create table
rhnSsmOperation
(
    id          number
                constraint rhn_ssmop_id_nn not null
                constraint rhn_ssmop_id_pk primary key
                    using index tablespace [[4m_tbs]],
    user_id     number
                constraint rhn_ssmop_user_nn not null
                constraint rhn_ssmop_user_fk
                    references rhnUser(id)
                    on delete cascade,
    description varchar2(256)
                constraint rhn_ssmop_desc_nn not null,
    status      varchar2(32)
                constraint rhn_ssmop_st_nn not null,
    started     date
                constraint rhn_ssmop_strt_nn not null,
    modified    date default (sysdate)
                constraint rhn_ssmop_mod_nn not null
)
;


create sequence rhn_ss_op_seq;

create or replace trigger
rhn_ssmop_mod_trig
before insert or update on rhnSsmOperation
for each row
begin
    :new.modified := sysdate;
end;
/
show errors

create table
rhnSsmOperationServer
(
    operation_id   number
                   constraint rhn_ssmops_ssmop_fk
                       references rhnSsmOperation(id)
                       on delete cascade,
    server_id      number
                   constraint rhn_ssmops_ser_fk
                       references rhnServer(id)
                       on delete cascade
)
;

 070701000004C7000081B400000000000000000000000167AE1114000002BD000000000000000000000000000000000000006300000000susemanager-schema/upgrade/spacewalk-schema-0.4-to-spacewalk-schema-0.5/153-rhnPackage-pathidx.sql    --
-- Copyright (c) 2008 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
-- $Id$
--


CREATE INDEX rhn_package_path_idx
ON rhnPackage(id, path);



   070701000004C8000081B400000000000000000000000167AE1114000000E0000000000000000000000000000000000000005D00000000susemanager-schema/upgrade/spacewalk-schema-0.4-to-spacewalk-schema-0.5/160-rhnSourceRPM.sql  --
-- Double the package name from
-- 128 -> 256 to resolve customer issue with custom
-- package names.
--

ALTER TABLE rhnSourceRpm
MODIFY
    name VARCHAR2(256);

ALTER TABLE rhnPackageName
MODIFY
    name VARCHAR2(256);
070701000004C9000081B400000000000000000000000167AE111400000511000000000000000000000000000000000000007600000000susemanager-schema/upgrade/spacewalk-schema-0.4-to-spacewalk-schema-0.5/161-rhnKickstartVirtualizationType-update.sql --
-- Copyright (c) 2008 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
-- $Id$
--


-- move all auto -> xenpv
update rhnKickstartDefaults set virtualization_type = 
 (select id from rhnkickstartvirtualizationtype 
  where label = 'qemu')
where virtualization_type = (select id from rhnkickstartvirtualizationtype 
  where label = 'auto');

update rhnKickstartSession set virtualization_type = 
 (select id from rhnkickstartvirtualizationtype 
  where label = 'qemu')
where virtualization_type = (select id from rhnkickstartvirtualizationtype 
  where label = 'auto');
  

  
delete from rhnKickstartVirtualizationType
  where label = 'auto';
  
commit;

show errors

-- $Log$
-- Revision 1  2008/10/29 7:01:05  mmccune
-- add get rid of auto
   070701000004CA000081B400000000000000000000000167AE111400000401000000000000000000000000000000000000006200000000susemanager-schema/upgrade/spacewalk-schema-0.4-to-spacewalk-schema-0.5/162-rhnRepoRegenQueue.sql create table 
rhnRepoRegenQueue
( 
       id                 number 
                          constraint rhn_reporegenq_id_nn not null enable 
                          constraint rhn_reporegenq_id_pk primary key,
       channel_label      varchar2(128)
                          constraint rhn_reporegenq_chan_label_nn not null enable,
       client             varchar2(128),
       reason             varchar2(128),
       force              char(1),
       bypass_filters     char(1),
       next_action        date default (sysdate),
       created            date default (sysdate) 
                          constraint rhn_reporegenq_created_nn not null enable,
       modified           date default (sysdate) 
                          constraint rhn_reporegenq_modified_nn not null enable
  );

create sequence rhn_repo_regen_queue_id_seq start with 101;

create or replace trigger rhn_repo_regen_queue_mod_trig
before insert or update on rhnRepoRegenQueue
for each row
begin
    :new.modified := sysdate;
end;
/

   070701000004CB000081B400000000000000000000000167AE111400000238000000000000000000000000000000000000006A00000000susemanager-schema/upgrade/spacewalk-schema-0.4-to-spacewalk-schema-0.5/163-rhn_config_parameter_data.sql 
UPDATE rhn_config_parameter SET value='/var/log/nocpulse/enqueue.log' 
        WHERE group_name='notification' AND name='enqueue_log';
UPDATE rhn_config_parameter SET value='/var/log/nocpulse/ack_handler.log' 
		WHERE group_name='notification' AND name='ack_handler_log';
UPDATE rhn_config_parameter SET value='--cd=/var/log/nocpulse --dir=/var/log/nocpulse/archive /var/log/nocpulse/ack_handler.log enqueue.log generate_config.log notifserver.log.save notifserver-error.log --recreate=ticketlog'
		WHERE group_name='notification' AND name='archive_params';

commit;
070701000004CC000081B400000000000000000000000167AE111400000054000000000000000000000000000000000000006B00000000susemanager-schema/upgrade/spacewalk-schema-0.4-to-spacewalk-schema-0.5/170-rhnErrataNotificationQueue.sql    ALTER TABLE rhnErrataNotificationQueue
    MODIFY
    next_action default(sysdate);
070701000004CD000081B400000000000000000000000167AE1114000000BA000000000000000000000000000000000000006700000000susemanager-schema/upgrade/spacewalk-schema-0.4-to-spacewalk-schema-0.5/180-rhnServerGroup_indexes.sql    
alter index rhn_sg_id_oid_name_idx noparallel;
alter index rhn_sg_oid_id_name_idx noparallel;
alter index rhn_sg_type_id_idx noparallel;
alter index rhn_sg_oid_type_id_idx noparallel;

  070701000004CE000081B400000000000000000000000167AE111400000035000000000000000000000000000000000000006E00000000susemanager-schema/upgrade/spacewalk-schema-0.4-to-spacewalk-schema-0.5/181-rhnServerGroupMembers_indexes.sql 
alter index rhn_sgmembers_sgid_sid_idx noparallel;

   070701000004CF000081B400000000000000000000000167AE111400000079000000000000000000000000000000000000006D00000000susemanager-schema/upgrade/spacewalk-schema-0.4-to-spacewalk-schema-0.5/182-rhnServerNeededCache_indexes.sql  
alter index rhn_snc_pid_idx noparallel;
alter index rhn_snc_sid_idx noparallel;
alter index rhn_snc_eid_idx noparallel;
   070701000004D0000081B400000000000000000000000167AE11140000002A000000000000000000000000000000000000006900000000susemanager-schema/upgrade/spacewalk-schema-0.4-to-spacewalk-schema-0.5/183-rhnServerPackage_indexes.sql  
alter index rhn_sp_snep_idx noparallel;

  070701000004D1000081B400000000000000000000000167AE1114000000BB000000000000000000000000000000000000006500000000susemanager-schema/upgrade/spacewalk-schema-0.4-to-spacewalk-schema-0.5/184-rhnUserGroup_indexes.sql  
alter index rhn_ug_id_name_org noparallel;
alter index rhn_ug_org_id_name_idx noparallel;
alter index rhn_ug_org_id_type_idx noparallel;
alter index rhn_ug_org_id_gtype_idx noparallel;

 070701000004D2000081B400000000000000000000000167AE111400000067000000000000000000000000000000000000006C00000000susemanager-schema/upgrade/spacewalk-schema-0.4-to-spacewalk-schema-0.5/185-rhnUserGroupMembers_indexes.sql   
alter index rhn_ugmembers_uid_ugid_uq noparallel;
alter index rhn_ugmembers_ugid_uid_idx noparallel;

 070701000004D3000081B400000000000000000000000167AE111400000061000000000000000000000000000000000000006400000000susemanager-schema/upgrade/spacewalk-schema-0.4-to-spacewalk-schema-0.5/186-web_contact_indexes.sql   
alter index web_contact_oid_id noparallel;
alter index web_contact_id_oid_cust_luc noparallel;

   070701000004D4000081B400000000000000000000000167AE111400000032000000000000000000000000000000000000006900000000susemanager-schema/upgrade/spacewalk-schema-0.4-to-spacewalk-schema-0.5/187-web_user_site_info_index.sql  
alter index web_user_site_info_wuid noparallel;

  070701000004D5000081B400000000000000000000000167AE1114000002B6000000000000000000000000000000000000006100000000susemanager-schema/upgrade/spacewalk-schema-0.4-to-spacewalk-schema-0.5/188-rhnUserInfo_data.sql  --
-- Copyright (c) 2009 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
-- $Id$
--
update rhnUserInfo set page_size=25 where page_size=20;

  070701000004D6000081B400000000000000000000000167AE11140000007D000000000000000000000000000000000000006C00000000susemanager-schema/upgrade/spacewalk-schema-0.4-to-spacewalk-schema-0.5/189-rhnReleaseChannelMap-unique.sql   ALTER TABLE rhnReleaseChannelMap
ADD CONSTRAINT rhn_rcm_pva_def_uniq
UNIQUE (product, version, channel_arch_id, is_default);
   070701000004D7000081B400000000000000000000000167AE111400000097000000000000000000000000000000000000006400000000susemanager-schema/upgrade/spacewalk-schema-0.4-to-spacewalk-schema-0.5/99-rhnPackage-Copyright.sql   --
-- Double the copyright from
-- 64 -> 128 to resolve rhnpush 
-- for centos packages
--

ALTER TABLE rhnPackage
MODIFY
    COPYRIGHT VARCHAR2(128);
 070701000004D8000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000004800000000susemanager-schema/upgrade/spacewalk-schema-0.5-to-spacewalk-schema-0.6   070701000004D9000081B400000000000000000000000167AE11140000024C000000000000000000000000000000000000006D00000000susemanager-schema/upgrade/spacewalk-schema-0.5-to-spacewalk-schema-0.6/100-rhnServerNeededCache_indexes.sql  -- rhn_snc_speid_idx index is also created during 0.4 -> 0.5 schema upgrades,
-- but is left out of the base 0.5 schema.

declare
	name_used exception;
	pragma exception_init(name_used, -00955);
begin
	execute immediate 'create index rhn_snc_speid_idx
		on rhnServerNeededCache(server_id, package_id, errata_id)
		noparallel
		tablespace [[128m_tbs]]
		nologging';
exception
	when name_used then
		execute immediate 'alter index rhn_snc_speid_idx noparallel';
end;
/

alter index rhn_snc_pid_idx noparallel;
alter index rhn_snc_sid_idx noparallel;
alter index rhn_snc_eid_idx noparallel;
070701000004DA000081B400000000000000000000000167AE1114000000B9000000000000000000000000000000000000006200000000susemanager-schema/upgrade/spacewalk-schema-0.5-to-spacewalk-schema-0.6/101-rhnErrata_indexes.sql create index rhn_errata_udate_index
	on rhnErrata( update_date )
	tablespace [[64k_tbs]]
  ;
	
create index rhn_errata_syn_index
	on rhnErrata( synopsis )
	tablespace [[64k_tbs]]
  ;
	
   070701000004DB000081B400000000000000000000000167AE111400000050000000000000000000000000000000000000006100000000susemanager-schema/upgrade/spacewalk-schema-0.5-to-spacewalk-schema-0.6/102-drop-rhnfaqclass.sql  drop table rhnfaqclass cascade constraints;
drop sequence RHN_FAQ_CLASS_ID_SEQ;
070701000004DC000081B400000000000000000000000167AE111400000045000000000000000000000000000000000000005C00000000susemanager-schema/upgrade/spacewalk-schema-0.5-to-spacewalk-schema-0.6/103-drop-rhnfaq.sql   drop table rhnfaq cascade constraints;
drop sequence rhn_faq_id_seq;
   070701000004DD000081B400000000000000000000000167AE111400002486000000000000000000000000000000000000006000000000susemanager-schema/upgrade/spacewalk-schema-0.5-to-spacewalk-schema-0.6/104-rhn_channel.pks.sql   --
-- Copyright (c) 2008 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--

CREATE OR REPLACE
PACKAGE rhn_channel
IS
	version varchar2(100) := '';

    CURSOR server_base_subscriptions(server_id_in NUMBER) IS
    	   SELECT C.id
	     FROM rhnChannel C, rhnServerChannel SC
	    WHERE C.id = SC.channel_id
	      AND SC.server_id = server_id_in
	      AND C.parent_channel IS NULL;
	      
    CURSOR check_server_subscription(server_id_in NUMBER, channel_id_in NUMBER) IS 
           SELECT channel_id 
	     FROM rhnServerChannel 
	    WHERE server_id = server_id_in 
	      AND channel_id = channel_id_in;

    CURSOR check_server_parent_membership(server_id_in NUMBER, channel_id_in NUMBER) IS
    	   SELECT C.id
	     FROM rhnChannel C, rhnServerChannel SC
	    WHERE C.parent_channel = channel_id_in
	      AND C.id = SC.channel_id
	      AND SC.server_id = server_id_in;
	    
    CURSOR channel_family_perm_cursor(channel_family_id_in NUMBER, org_id_in NUMBER) IS
           SELECT *
	     FROM rhnOrgChannelFamilyPermissions
	    WHERE channel_family_id = channel_family_id_in
	      AND org_id = org_id_in;

    PROCEDURE license_consent(channel_id_in IN NUMBER, user_id_in IN NUMBER, server_id_in IN NUMBER);
    FUNCTION get_license_path(channel_id_in IN NUMBER) RETURN VARCHAR2;

    PROCEDURE unsubscribe_server(server_id_in IN NUMBER, channel_id_in NUMBER, immediate_in NUMBER := 1, unsubscribe_children_in number := 0,
                                 deleting_server in number := 0 );
    PROCEDURE subscribe_server(server_id_in IN NUMBER, channel_id_in NUMBER, immediate_in NUMBER := 1, user_id_in number := null, recalcfamily_in number := 1);
	
    function can_server_consume_virt_channl(
        server_id_in IN NUMBER,
        family_id_in in number)
    return number;

    FUNCTION guess_server_base(server_id_in IN NUMBER) RETURN NUMBER;

    FUNCTION base_channel_for_release_arch(release_in in varchar2, 
	server_arch_in in varchar2, org_id_in in number := -1, 
	user_id_in in number := null) RETURN number;

    FUNCTION base_channel_rel_archid(release_in in varchar2, 
	server_arch_id_in in number, org_id_in in number := -1, 
	user_id_in in number := null) RETURN number;

    FUNCTION channel_priority(channel_id_in in number) RETURN number;
    
    PROCEDURE bulk_subscribe_server(channel_id_in IN NUMBER, set_label_in IN VARCHAR2, set_uid_in IN NUMBER);
    PROCEDURE bulk_unsubscribe_server(channel_id_in IN NUMBER, set_label_in IN VARCHAR2, set_uid_in IN NUMBER);
    
    PROCEDURE bulk_server_base_change(channel_id_in IN NUMBER, set_label_in IN VARCHAR2, set_uid_in IN NUMBER);
    procedure bulk_server_basechange_from(
	set_label_in in varchar2,
	set_uid_in in number,
	old_channel_id_in in number,
	new_channel_id_in in number);

    procedure bulk_guess_server_base(
	set_label_in in varchar2,
	set_uid_in in number);

    procedure bulk_guess_server_base_from(
	set_label_in in varchar2,
	set_uid_in in number,
	channel_id_in in number);

    PROCEDURE clear_subscriptions(server_id_in IN NUMBER, deleting_server in number := 0 );
    
    FUNCTION available_family_subscriptions(channel_family_id_in IN NUMBER, org_id_in IN NUMBER) RETURN NUMBER;

    function channel_family_current_members(channel_family_id_in IN NUMBER,
                                            org_id_in IN NUMBER)
    return number;

    PROCEDURE update_family_counts(channel_family_id_in IN NUMBER, org_id_in IN NUMBER);
    FUNCTION family_for_channel(channel_id_in IN NUMBER) RETURN NUMBER;

    FUNCTION available_chan_subscriptions(channel_id_in IN NUMBER, org_id_in IN NUMBER) RETURN NUMBER;

    procedure entitle_customer(customer_id_in in number, channel_family_id_in in number, quantity_in in number);
    procedure set_family_maxmembers(customer_id_in in number, channel_family_id_in in number, quantity_in in number);
    procedure unsubscribe_server_from_family(server_id_in in number, channel_family_id_in in number);

    procedure delete_server_channels(server_id_in in number);
    procedure refresh_newest_package(channel_id_in in number, caller_in in varchar2 := '(unknown)');
    
    function get_org_id(channel_id_in in number) return number;
    PRAGMA RESTRICT_REFERENCES(get_org_id, WNDS, RNPS, WNPS);

    function get_org_access(channel_id_in in number, org_id_in in number) return number;
    PRAGMA RESTRICT_REFERENCES(get_org_access, WNDS, RNPS, WNPS);
    
    function get_cfam_org_access(cfam_id_in in number, org_id_in in number) return number;

    function user_role_check_debug(channel_id_in in number, user_id_in in number, role_in in varchar2, reason_out out varchar2)
    	RETURN NUMBER;
    PRAGMA RESTRICT_REFERENCES(user_role_check_debug, WNDS, RNPS, WNPS);

    function user_role_check(channel_id_in in number, user_id_in in number, role_in in varchar2)
    	RETURN NUMBER;
    PRAGMA RESTRICT_REFERENCES(user_role_check, WNDS, RNPS, WNPS);
    
    function loose_user_role_check(channel_id_in in number, user_id_in in number, role_in in varchar2)
    	RETURN NUMBER;
    PRAGMA RESTRICT_REFERENCES(loose_user_role_check, WNDS, RNPS, WNPS);

    function direct_user_role_check(channel_id_in in number, user_id_in in number, role_in in varchar2)
    	RETURN NUMBER;
    PRAGMA RESTRICT_REFERENCES(direct_user_role_check, WNDS, RNPS, WNPS);

    function shared_user_role_check(channel_id in number, user_id in number, role in varchar2)
    	RETURN NUMBER;
    PRAGMA RESTRICT_REFERENCES(shared_user_role_check, WNDS, RNPS, WNPS);

    function org_channel_setting(channel_id_in in number, org_id_in in number, setting_in in varchar2)
    	RETURN NUMBER;

    PROCEDURE update_channel ( channel_id_in in number, invalidate_ss in number := 0, 
                               date_to_use in date := sysdate );

    PROCEDURE  update_channels_by_package ( package_id_in in number, date_to_use in date := sysdate );

     PROCEDURE update_channels_by_errata ( errata_id_in number, date_to_use in date := sysdate );


    PRAGMA RESTRICT_REFERENCES(org_channel_setting, WNDS, RNPS, WNPS);

END rhn_channel;
/
SHOW ERRORS

--
-- Revision 1.37  2004/04/14 00:09:24  pjones
-- bugzilla: 120761 -- split rhnChannelPermissions into two tables, eliminating
-- a frequent full table scan
--
-- Revision 1.36  2004/03/26 18:11:32  rbb
-- Bugzilla:  114057
--
-- Add a script to determine channel priority.
--
-- Revision 1.35  2004/02/17 20:16:52  pjones
-- bugzilla: none -- add cvs tags into the package as long as we're touching
-- it anyway
--
-- Revision 1.34  2003/11/13 18:13:09  cturner
-- pragmas can now return now that rhn_user pragmas are fixed
--
-- Revision 1.32  2003/09/22 21:00:40  cturner
-- add method for easy acl check
--
-- Revision 1.31  2003/09/17 22:14:11  misa
-- bugzilla: 103639  Changes to allow me to move the base channel guess into plsql
--
-- Revision 1.30  2003/07/24 16:44:16  misa
-- bugzilla: none  A function more usable on the rhnapp side
--
-- Revision 1.29  2003/07/24 14:00:17  misa
-- bugzilla: none  PRAGMA RESTRICT_REFERENCES good
--
-- Revision 1.28  2003/07/23 21:59:19  cturner
-- rework how rhnUserChannel works; move to plsql for speed and maintenance
--
-- Revision 1.27  2003/07/21 17:49:12  pjones
-- bugzilla: none
--
-- add optional user for subscribe_server
--
-- Revision 1.26  2002/12/19 18:13:42  misa
-- Added caller with a default value
--
-- Revision 1.25  2002/12/11 22:18:46  pjones
-- rhnChannelNewestPackage
--
-- Revision 1.24  2002/11/21 22:08:11  pjones
-- make unsubscribe_channels have a "unsubscribe_children_in number := 0"
-- argument so that you can tell it to unsubscribe children.
--
-- Also, make it raise an exception instead of silent failure in the
-- other case.
--
-- Revision 1.23  2002/11/18 17:20:50  pjones
-- this should have gone back too
--
-- Revision 1.22  2002/11/13 23:16:18  pjones
-- lookup_*_arch()
--
-- Revision 1.21  2002/10/07 20:01:59  rnorwood
-- guess base channel for ssm and single system
--
-- Revision 1.20  2002/10/02 19:21:03  bretm
-- o  3rd party channel schema changes, no more clobs...
--
-- Revision 1.19  2002/09/20 19:21:58  bretm
-- o  more 3rd party channel stuff...
--
-- Revision 1.18  2002/06/12 22:33:03  pjones
-- procedure bulk_guess_server_base_from(
--     set_label_in in varchar2,
--     set_uid_in in number,
--     channel_id_in in number);
--
-- for bretm
--
-- Revision 1.17  2002/06/12 22:12:25  pjones
-- procedure bulk_guess_server_base(
--     set_label_in in varchar2,
--     set_uid_in in number);
--
-- for bretm
--
-- Revision 1.16  2002/06/12 19:37:55  pjones
-- bulk_server_basechange_from(
-- 	set_label_in in varchar2,
-- 	set_uid_in in number,
-- 	old_channel_id_in in number,
-- 	new_channel_id_in in number
-- );
--
-- for bretm
--
-- Revision 1.15  2002/05/10 22:08:22  pjones
-- id/log
--
  070701000004DE000081B400000000000000000000000167AE11140000C832000000000000000000000000000000000000006000000000susemanager-schema/upgrade/spacewalk-schema-0.5-to-spacewalk-schema-0.6/105-rhn_channel.pkb.sql   --
-- Copyright (c) 2008 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--

CREATE OR REPLACE
PACKAGE BODY rhn_channel
IS
        body_version varchar2(100) := '';

    -- Cursor that fetches all the possible base channels for a
    -- (server_arch_id, release, org_id) combination
        cursor  base_channel_cursor(
                release_in in varchar2,
                server_arch_id_in in number,
                org_id_in in number
        ) return rhnChannel%ROWTYPE is
                select distinct c.*
                from    rhnDistChannelMap                       dcm,
                                rhnServerChannelArchCompat      scac,
                                rhnChannel                                      c,
                                rhnChannelPermissions           cp
                where   cp.org_id = org_id_in
                        and cp.channel_id = c.id
                        and c.parent_channel is null
                        and c.id = dcm.channel_id
                        and c.channel_arch_id = dcm.channel_arch_id
                        and dcm.release = release_in
                        and scac.server_arch_id = server_arch_id_in
                        and scac.channel_arch_id = c.channel_arch_id;

    FUNCTION get_license_path(channel_id_in IN NUMBER)
    RETURN VARCHAR2
    IS
        license_val VARCHAR2(1000);
    BEGIN
        SELECT CFL.license_path INTO license_val
          FROM rhnChannelFamilyLicense CFL, rhnChannelFamilyMembers CFM
         WHERE CFM.channel_id = channel_id_in
           AND CFM.channel_family_id = CFL.channel_family_id;
    
        RETURN license_val;

    EXCEPTION
        WHEN NO_DATA_FOUND
            THEN
            RETURN NULL;
    END get_license_path;


    PROCEDURE license_consent(channel_id_in IN NUMBER, user_id_in IN NUMBER, server_id_in IN NUMBER)
    IS
        channel_family_id_val NUMBER;
    BEGIN
        channel_family_id_val := rhn_channel.family_for_channel(channel_id_in);
        IF channel_family_id_val IS NULL
        THEN
            rhn_exception.raise_exception('channel_subscribe_no_family');
        END IF;
        
        IF rhn_channel.get_license_path(channel_id_in) IS NULL
        THEN
            rhn_exception.raise_exception('channel_consent_no_license');
        END IF;
        
        INSERT INTO rhnChannelFamilyLicenseConsent (channel_family_id, user_id, server_id)
        VALUES (channel_family_id_val, user_id_in, server_id_in);
    END license_consent;

    PROCEDURE subscribe_server(server_id_in IN NUMBER, channel_id_in NUMBER, immediate_in NUMBER := 1, user_id_in in number := null, recalcfamily_in NUMBER := 1)
    IS
        channel_parent_val      rhnChannel.parent_channel%TYPE;
        parent_subscribed       BOOLEAN;
        server_has_base_chan    BOOLEAN;
        server_already_in_chan  BOOLEAN;
        channel_family_id_val   NUMBER;
        server_org_id_val       NUMBER;
        available_subscriptions NUMBER;
        consenting_user         NUMBER;
        allowed                 number := 0;
        current_members_val     number;
    BEGIN
        if user_id_in is not null then
            allowed := rhn_channel.user_role_check(channel_id_in, user_id_in, 'subscribe');
        else
            allowed := 1;
        end if;

        if allowed = 0 then
            rhn_exception.raise_exception('no_subscribe_permissions');
        end if;


        SELECT parent_channel INTO channel_parent_val FROM rhnChannel WHERE id = channel_id_in;

        IF channel_parent_val IS NOT NULL
        THEN    
            -- child channel; if attempting to cross-subscribe a child to the wrong base, silently ignore
            parent_subscribed := FALSE;    

            FOR check_subscription IN check_server_subscription(server_id_in, channel_parent_val)
            LOOP
                parent_subscribed := TRUE;
            END LOOP check_subscription;
        
            IF NOT parent_subscribed
            THEN
                RETURN;
            END IF;
        ELSE
            -- base channel
            server_has_base_chan := FALSE;
            FOR base IN server_base_subscriptions(server_id_in)
            LOOP
                server_has_base_chan := TRUE;
            END LOOP base;
            
            IF server_has_base_chan
            THEN
                rhn_exception.raise_exception('channel_server_one_base');
            END IF;
        END IF;
    
        FOR check_subscription IN check_server_subscription(server_id_in, channel_id_in)
        LOOP
            server_already_in_chan := TRUE;
        END LOOP check_subscription;
    
        IF server_already_in_chan
        THEN
            RETURN;
        END IF;
        
        channel_family_id_val := rhn_channel.family_for_channel(channel_id_in);
        IF channel_family_id_val IS NULL
        THEN
            rhn_exception.raise_exception('channel_subscribe_no_family');
        END IF;

        --
        -- Use the org_id of the server only if the org_id of the channel = NULL.
        -- This is required for subscribing to shared channels.
        --
        SELECT NVL(org_id, (SELECT org_id FROM rhnServer WHERE id = server_id_in))
          INTO server_org_id_val
          FROM rhnChannel
         WHERE id = channel_id_in;
         
        select current_members 
        into current_members_val
        from rhnPrivateChannelFamily
        where org_id = server_org_id_val and channel_family_id = channel_family_id_val
        for update of current_members;

        available_subscriptions := rhn_channel.available_family_subscriptions(channel_family_id_val, server_org_id_val);
        
        IF available_subscriptions IS NULL OR 
           available_subscriptions > 0 or
           can_server_consume_virt_channl(server_id_in, channel_family_id_val) = 1
        THEN
        
            IF rhn_channel.get_license_path(channel_id_in) IS NOT NULL
            THEN
                BEGIN
                
                SELECT user_id INTO consenting_user
                  FROM rhnChannelFamilyLicenseConsent
                 WHERE channel_family_id = channel_family_id_val
                   AND server_id = server_id_in;
                
                EXCEPTION
                    WHEN NO_DATA_FOUND THEN
                        rhn_exception.raise_exception('channel_subscribe_no_consent');
                END;
            END IF;
        
            insert into rhnServerHistory (id,server_id,summary,details) (
                select  rhn_event_id_seq.nextval,
                        server_id_in,
                        'subscribed to channel ' || SUBSTR(c.label, 0, 106),
                        c.label
                from    rhnChannel c
                where   c.id = channel_id_in
            );
            UPDATE rhnServer SET channels_changed = sysdate WHERE id = server_id_in;
            INSERT INTO rhnServerChannel (server_id, channel_id) VALUES (server_id_in, channel_id_in);
			IF recalcfamily_in > 0
			THEN
                rhn_channel.update_family_counts(channel_family_id_val, server_org_id_val);
			END IF;
            queue_server(server_id_in, immediate_in);
        ELSE
            rhn_exception.raise_exception('channel_family_no_subscriptions');
        END IF;
            
    END subscribe_server;
    
    function can_server_consume_virt_channl(
        server_id_in in number,
        family_id_in in number )
    return number
    is

        cursor server_virt_families is
            select vi.virtual_system_id, cfvsl.channel_family_id
            from
                rhnChannelFamilyVirtSubLevel cfvsl,
                rhnSGTypeVirtSubLevel sgtvsl,
                rhnVirtualInstance vi
            where
                vi.virtual_system_id = server_id_in 
                and sgtvsl.virt_sub_level_id = cfvsl.virt_sub_level_id
                and cfvsl.channel_family_id = family_id_in
                and exists (
                    select 1
                    from rhnServerEntitlementView sev
                    where vi.host_system_id = sev.server_id
                    and sev.server_group_type_id = sgtvsl.server_group_type_id );
    begin

        for server_virt_family in server_virt_families loop
            return 1;
        end loop;

        return 0;

    end;


    PROCEDURE bulk_subscribe_server(channel_id_in IN NUMBER, set_label_in IN VARCHAR2, set_uid_in IN NUMBER)
    IS
    BEGIN
        FOR server IN rhn_set.set_iterator(set_label_in, set_uid_in)
        LOOP
            rhn_channel.subscribe_server(server.element, channel_id_in, 0, set_uid_in);
        END LOOP server;
    END bulk_subscribe_server;

    PROCEDURE bulk_server_base_change(channel_id_in IN NUMBER, set_label_in IN VARCHAR2, set_uid_in IN NUMBER)
    IS
    BEGIN
        FOR server IN rhn_set.set_iterator(set_label_in, set_uid_in)
        LOOP
            IF rhn_server.can_change_base_channel(server.element) = 1
            THEN
                rhn_channel.clear_subscriptions(TO_NUMBER(server.element));
                rhn_channel.subscribe_server(server.element, channel_id_in, 0, set_uid_in);
            END IF;
        END LOOP server;
    END bulk_server_base_change;

    procedure bulk_server_basechange_from(
        set_label_in in varchar2,
        set_uid_in in number,
        old_channel_id_in in number,
        new_channel_id_in in number
    ) is
    cursor servers is
        select  sc.server_id id
        from    rhnChannel nc,
                rhnServerChannelArchCompat scac,
                rhnServer s,
                rhnChannel oc,
                rhnServerChannel sc,
                rhnSet st
        where   1=1
            -- first, find the servers we're looking for.
            and st.label = set_label_in
            and st.user_id = set_uid_in
            and st.element = sc.server_id
            -- now, filter out anything that's not in the
            -- old base channel.
            and sc.channel_id = old_channel_id_in
            and sc.channel_id = oc.id
            and oc.parent_channel is null
            -- now, see if it's compatible with the new base channel
            and nc.id = new_channel_id_in
            and nc.parent_channel is null
            and sc.server_id = s.id
            and s.server_arch_id = scac.server_arch_id
            and scac.channel_arch_id = nc.channel_arch_id;
    begin
        for s in servers loop
            insert into rhnSet (
                    user_id, label, element
                ) values (
                    set_uid_in,
                    set_label_in || 'basechange', 
                    s.id
                );
        end loop channel;
        bulk_server_base_change(new_channel_id_in,
                                set_label_in || 'basechange',
                                set_uid_in);
        delete from rhnSet
            where   label = set_label_in||'basechange'
                and user_id = set_uid_in;
    end bulk_server_basechange_from;

    procedure bulk_guess_server_base(
        set_label_in in varchar2,
        set_uid_in in number
    ) is
        channel_id number;
    begin
        for server in rhn_set.set_iterator(set_label_in, set_uid_in)
        loop
            -- anything that doesn't work, we just ignore
            begin
                if rhn_server.can_change_base_channel(server.element) = 1
                then
                    channel_id := guess_server_base(TO_NUMBER(server.element));
                    rhn_channel.clear_subscriptions(TO_NUMBER(server.element));
                    rhn_channel.subscribe_server(TO_NUMBER(server.element), channel_id, 0, set_uid_in);
                end if;
            exception when others then
                null;
            end;
        end loop server;
    end;

    function guess_server_base(
        server_id_in in number
    ) RETURN number is
        cursor server_cursor is
            select s.server_arch_id, s.release, s.org_id
              from rhnServer s
             where s.id = server_id_in;
    begin
        for s in server_cursor loop
            for channel in base_channel_cursor(s.release,
                s.server_arch_id, s.org_id) 
            loop
                return channel.id;
            end loop base_channel_cursor;
        end loop server_cursor;
        -- Server not found, or no base channel applies to it
        return null;
    end;

    -- Private function
    function normalize_server_arch(server_arch_in in varchar2)
    return varchar2
    deterministic
    is
        suffix VARCHAR2(128) := '-redhat-linux';
        suffix_len NUMBER := length(suffix);
    begin
        if server_arch_in is NULL then
            return NULL;
        end if;
        if instr(server_arch_in, '-') > 0
        then
            -- Suffix already present
            return server_arch_in;
        end if;
        return server_arch_in || suffix;
    end normalize_server_arch;

    --
    --
    -- Raises: 
    --   server_arch_not_found
    --   no_subscribe_permissions
    function base_channel_for_release_arch(
        release_in in varchar2,
        server_arch_in in varchar2,
        org_id_in in number := -1,
        user_id_in in number := null
    ) return number is
        server_arch varchar2(256) := normalize_server_arch(server_arch_in);
        server_arch_id number;
    begin
        -- Look up the server arch
        begin
            select id
              into server_arch_id
              from rhnServerArch
             where label = server_arch;
        exception
            when no_data_found then
                rhn_exception.raise_exception('server_arch_not_found');
        end;
        return base_channel_rel_archid(release_in, server_arch_id,
            org_id_in, user_id_in);
    end base_channel_for_release_arch;

    function base_channel_rel_archid(
        release_in in varchar2,
        server_arch_id_in in number,
        org_id_in in number := -1,
        user_id_in in number := null
    ) return number is
        denied_channel_id number := null;
        valid_org_id number := org_id_in;
        valid_user_id number := user_id_in;
        channel_subscribable number;
    begin
        if org_id_in = -1 and user_id_in is not null then
            -- Get the org id from the user id
            begin
                select org_id
                  into valid_org_id
                  from web_contact
                 where id = user_id_in;
            exception
                when no_data_found then
                    -- User doesn't exist
                    -- XXX Only list public stuff for now
                    valid_user_id := null;
                    valid_org_id := -1;
            end;
        end if;

        for c in base_channel_cursor(release_in, server_arch_id_in, valid_org_id)
        loop
            -- This row is a possible match
            if valid_user_id is null then
                -- User ID not specified, so no user to channel permissions to
                -- check
                return c.id;
            end if;

            -- Check user to channel permissions
            select loose_user_role_check(c.id, user_id_in, 'subscribe')
              into channel_subscribable
              from dual;

            if channel_subscribable = 1 then
                return c.id;
            end if;
                
            -- Base channel exists, but is not subscribable; keep trying
            denied_channel_id := c.id;
        end loop base_channel_fetch;
        
        if denied_channel_id is not null then
            rhn_exception.raise_exception('no_subscribe_permissions');
        end if;
        -- No base channel applies
        return NULL;
    end base_channel_rel_archid;

    procedure bulk_guess_server_base_from(
        set_label_in in varchar2,
        set_uid_in in number,
        channel_id_in in number
    ) is
        cursor channels(server_id_in in number) is
            select      rsc.channel_id
            from        rhnServerChannel rsc,
                        rhnChannel rc
            where       server_id_in = rsc.server_id
                        and rsc.channel_id = rc.id
                        and rc.parent_channel is null;
    begin
        for server in rhn_set.set_iterator(set_label_in, set_uid_in)
        loop
            for channel in channels(server.element)
            loop
                if channel.channel_id = channel_id_in
                then
                    insert into rhnSet (user_id, label, element) values (set_uid_in, set_label_in || 'baseguess', server.element);
                end if;
            end loop channel;
        end loop server;
        bulk_guess_server_base(set_label_in||'baseguess',set_uid_in);
        delete from rhnSet where label = set_label_in||'baseguess' and user_id = set_uid_in;
    end;


    PROCEDURE clear_subscriptions(server_id_in IN NUMBER, deleting_server IN NUMBER := 0 )
    IS
        cursor server_channels(server_id_in in number) is
                select  s.org_id, sc.channel_id, cfm.channel_family_id
                from    rhnServer s,
                        rhnServerChannel sc,
                        rhnChannelFamilyMembers cfm
                where   s.id = server_id_in
                        and s.id = sc.server_id
                        and sc.channel_id = cfm.channel_id;
    BEGIN
        for channel in server_channels(server_id_in)
        loop
                unsubscribe_server(server_id_in, channel.channel_id, 1, 1, deleting_server);
                rhn_channel.update_family_counts(channel.channel_family_id, channel.org_id);
        end loop channel;
    END clear_subscriptions;

    PROCEDURE unsubscribe_server(server_id_in IN NUMBER, channel_id_in NUMBER, immediate_in NUMBER := 1, unsubscribe_children_in number := 0,
                                 deleting_server IN NUMBER := 0 )
    IS
        channel_family_id_val   NUMBER;
        server_org_id_val       NUMBER;
        available_subscriptions NUMBER; 
        server_already_in_chan  BOOLEAN;
        cursor  channel_family_is_proxy(channel_family_id_in in number) is
                select  1
                from    rhnChannelFamily
                where   id = channel_family_id_in
                    and label = 'rhn-proxy';
        cursor  channel_family_is_satellite(channel_family_id_in in number) is
                select  1
                from    rhnChannelFamily
                where   id = channel_family_id_in
                    and label = 'rhn-satellite';
        -- this is *EXACTLY* like check_server_parent_membership, but if we recurse
        -- with the package-level one, we get a "cursor already open", so we need a
        -- copy on our call stack instead.  GROAN.
        cursor local_chk_server_parent_memb (
                        server_id_in number,
                        channel_id_in number ) is
                select  c.id
                from    rhnChannel                      c,
                                rhnServerChannel        sc
                where   1=1
                        and c.parent_channel = channel_id_in
                        and c.id = sc.channel_id
                        and sc.server_id = server_id_in;
    BEGIN
        FOR child IN local_chk_server_parent_memb(server_id_in, channel_id_in)
        LOOP
            if unsubscribe_children_in = 1 then
                unsubscribe_server(server_id_in => server_id_in,
                                                                channel_id_in => child.id,
                                                                immediate_in => immediate_in,
                                                                unsubscribe_children_in => unsubscribe_children_in,
                        deleting_server => deleting_server);
            else
                rhn_exception.raise_exception('channel_unsubscribe_child_exists');
            end if;
        END LOOP child;
        
        server_already_in_chan := FALSE;
    
        FOR check_subscription IN check_server_subscription(server_id_in, channel_id_in)
        LOOP
            server_already_in_chan := TRUE;
        END LOOP check_subscription;
    
        IF NOT server_already_in_chan
        THEN
            RETURN;
        END IF;
        
   if deleting_server = 0 then 

      insert into rhnServerHistory (id,server_id,summary,details) (
          select  rhn_event_id_seq.nextval,
                server_id_in,
             'unsubscribed from channel ' || SUBSTR(c.label, 0, 106),
             c.label
          from    rhnChannel c
          where   c.id = channel_id_in
      );

        UPDATE rhnServer SET channels_changed = sysdate WHERE id = server_id_in;
   end if;
        
   DELETE FROM rhnServerChannel WHERE server_id = server_id_in AND channel_id = channel_id_in;

   if deleting_server = 0 then 
        queue_server(server_id_in, immediate_in);
   end if;

        channel_family_id_val := rhn_channel.family_for_channel(channel_id_in);
        IF channel_family_id_val IS NULL
        THEN
            rhn_exception.raise_exception('channel_unsubscribe_no_family');
        END IF;

        for ignore in channel_family_is_satellite(channel_family_id_val) loop
                delete from rhnSatelliteInfo where server_id = server_id_in;
                delete from rhnSatelliteChannelFamily where server_id = server_id_in;
        end loop;

        for ignore in channel_family_is_proxy(channel_family_id_val) loop
                delete from rhnProxyInfo where server_id = server_id_in;
        end loop;

        DELETE FROM rhnChannelFamilyLicenseConsent
         WHERE channel_family_id = channel_family_id_val
           AND server_id = server_id_in;
                        
        SELECT org_id INTO server_org_id_val
          FROM rhnServer
         WHERE id = server_id_in;
         
        rhn_channel.update_family_counts(channel_family_id_val, server_org_id_val);
    END unsubscribe_server;

    PROCEDURE bulk_unsubscribe_server(channel_id_in IN NUMBER, set_label_in IN VARCHAR2, set_uid_in IN NUMBER)
    IS
    BEGIN
        FOR server IN rhn_set.set_iterator(set_label_in, set_uid_in)
        LOOP
            rhn_channel.unsubscribe_server(server.element, channel_id_in, 0);
        END LOOP server;
    END bulk_unsubscribe_server;

    FUNCTION family_for_channel(channel_id_in IN NUMBER)
    RETURN NUMBER
    IS
        channel_family_id_val NUMBER;
    BEGIN
        SELECT channel_family_id INTO channel_family_id_val
          FROM rhnChannelFamilyMembers
         WHERE channel_id = channel_id_in;
         
        RETURN channel_family_id_val;
    EXCEPTION
        WHEN NO_DATA_FOUND
        THEN
            RETURN NULL;
    END family_for_channel;

    FUNCTION available_family_subscriptions(channel_family_id_in IN NUMBER, org_id_in IN NUMBER)
    RETURN NUMBER
    IS
        cfp channel_family_perm_cursor%ROWTYPE;
        current_members_val NUMBER;
        max_members_val     NUMBER;
        found               NUMBER;
    BEGIN
        IF NOT channel_family_perm_cursor%ISOPEN
        THEN
            OPEN channel_family_perm_cursor(channel_family_id_in, org_id_in);
        END IF;

        FETCH channel_family_perm_cursor INTO cfp;
        
        WHILE channel_family_perm_cursor%FOUND
        LOOP
            found := 1;
            
            current_members_val := cfp.current_members;
            max_members_val := cfp.max_members;
            
            FETCH channel_family_perm_cursor INTO cfp;
        END LOOP;

        IF channel_family_perm_cursor%ISOPEN
        THEN
            CLOSE channel_family_perm_cursor;
        END IF;

        -- not found: either the channel fam doesn't have an entry in cfp, or the org doesn't have access to it.
        -- either way, there are no available subscriptions
        
        IF found IS NULL
        THEN
            RETURN 0;
        END IF;

        -- null max members?  in that case, pass it on; NULL means infinite                     
        IF max_members_val IS NULL
        THEN
            RETURN NULL;
        END IF;

        -- otherwise, return the delta  
        RETURN max_members_val - current_members_val;                   
    END available_family_subscriptions;
    
    -- *******************************************************************
    -- FUNCTION: channel_family_current_members
    -- Calculates and returns the actual count of systems consuming
    --   physical channel subscriptions.
    -- Called by: update_family_counts 
    --            rhn_entitlements.repoll_virt_guest_entitlements
    -- *******************************************************************
    function channel_family_current_members(channel_family_id_in IN NUMBER,
                                            org_id_in IN NUMBER)
    return number
    is
        current_members_count number := 0;
    begin
        select  count(distinct sc.server_id)
        into    current_members_count
        from    rhnChannelFamilyMembers cfm,
                rhnServerChannel sc,
                rhnServer s
        where   s.org_id = org_id_in
            and s.id = sc.server_id
            and cfm.channel_family_id = channel_family_id_in
            and cfm.channel_id = sc.channel_id
            and exists ( 
                select 1
                from rhnChannelFamilyServerPhysical cfsp
                where cfsp.CHANNEL_FAMILY_ID = channel_family_id_in
                    and cfsp.server_id = s.id
                );

        return current_members_count;
    end;        

    PROCEDURE update_family_counts(channel_family_id_in IN NUMBER, 
                                   org_id_in IN NUMBER)
    IS
    BEGIN
                update rhnPrivateChannelFamily
                set current_members = (
                channel_family_current_members(channel_family_id_in, org_id_in)
                )
                        where org_id = org_id_in
                                and channel_family_id = channel_family_id_in;

    END update_family_counts;
    
    FUNCTION available_chan_subscriptions(channel_id_in IN NUMBER, 
                                          org_id_in IN NUMBER)
    RETURN NUMBER
    IS
            channel_family_id_val NUMBER;
    BEGIN
        SELECT channel_family_id INTO channel_family_id_val
            FROM rhnChannelFamilyMembers
            WHERE channel_id = channel_id_in;
         
            RETURN rhn_channel.available_family_subscriptions(
                           channel_family_id_val, org_id_in);
    END available_chan_subscriptions;

    -- *******************************************************************
    -- PROCEDURE: entitle_customer
    -- Creates a chan fam bucket, or sets max_members for an existing bucket
    -- Called by: rhn_ep.poll_customer_internal
    -- Calls: set_family_maxmembers + update_family_counts if the row
    --        already exists, else it creates it in rhnPrivateChannelFamily.
    -- *******************************************************************
    procedure entitle_customer(customer_id_in in number, 
                               channel_family_id_in in number, 
                               quantity_in in number)
    is
                cursor permissions is
                        select  1
                        from    rhnPrivateChannelFamily pcf
                        where   pcf.org_id = customer_id_in
                                and     pcf.channel_family_id = channel_family_id_in; 
    begin
                for perm in permissions loop
                        set_family_maxmembers(
                                customer_id_in,
                                channel_family_id_in,
                                quantity_in
                        );
                        rhn_channel.update_family_counts(
                                channel_family_id_in,
                                customer_id_in
                        );
                        return;
                end loop;
        
                insert into rhnPrivateChannelFamily pcf (
                                channel_family_id, org_id, max_members, current_members
                        ) values (
                                channel_family_id_in, customer_id_in, quantity_in, 0
                        );
    end;

    -- *******************************************************************
    -- PROCEDURE: set_family_maxmembers
    -- Prunes an existing channel family bucket by unsubscribing the
    --   necessary servers and sets max_members.
    -- Called by: rhn_channel.entitle_customer
    -- Calls: unsubscribe_server_from_family
    -- *******************************************************************
    procedure set_family_maxmembers(customer_id_in in number, 
                                    channel_family_id_in in number, 
                                    quantity_in in number)
    is
        cursor servers is
            select  server_id from (
            select      rownum row_number, server_id, modified from (
                select  rcfsp.server_id,
                        rcfsp.modified
                from    rhnChannelFamilyServerPhysical rcfsp
                where   rcfsp.customer_id = customer_id_in
                    and rcfsp.channel_family_id = channel_family_id_in
                order by modified
            )
            where rownum > quantity_in
            );
    begin
            -- prune subscribed servers
        for server in servers loop
            rhn_channel.unsubscribe_server_from_family(server.server_id, 
                                                       channel_family_id_in);
        end loop;

        update  rhnPrivateChannelFamily pcf
        set     pcf.max_members = quantity_in
        where   pcf.org_id = customer_id_in
            and pcf.channel_family_id = channel_family_id_in;
    end;

    procedure unsubscribe_server_from_family(server_id_in in number, 
                                             channel_family_id_in in number)
    is
    begin
        delete
        from    rhnServerChannel rsc
        where   rsc.server_id = server_id_in
            and channel_id in (
                select  rcfm.channel_id
                from    rhnChannelFamilyMembers rcfm
                where   rcfm.channel_family_id = channel_family_id_in);
    end;

    function get_org_id(channel_id_in in number)
    return number
    is
        org_id_out number;
    begin
        select org_id into org_id_out
            from rhnChannel
            where id = channel_id_in;
         
            return org_id_out;
    end get_org_id;
    
    function get_cfam_org_access(cfam_id_in in number, org_id_in in number)
    return number
    is
        cursor  families is
                        select  1
                        from    rhnOrgChannelFamilyPermissions cfp
                        where   cfp.org_id = org_id_in;
    begin
                -- the idea: if we get past this query, 
        -- the user has the role, else catch the exception and return 0
                for family in families loop
                return 1;
                end loop;
                return 0;
    end;

    function get_org_access(channel_id_in in number, org_id_in in number)
    return number
    is
        throwaway number;
    begin
        -- the idea: if we get past this query, 
        -- the org has access to the channel, else catch the exception and return 0
        select distinct 1 into throwaway
          from rhnChannelFamilyMembers CFM,
               rhnOrgChannelFamilyPermissions CFP
         where cfp.org_id = org_id_in
           and CFM.channel_family_id = CFP.channel_family_id
           and CFM.channel_id = channel_id_in
           and (CFP.max_members > 0 or CFP.max_members is null or CFP.org_id = 1);
           
        return 1;
        exception
            when no_data_found
            then
            return 0;
    end;
    
    -- check if a user has a given role, or if such a role is inferrable
    function user_role_check_debug(channel_id_in in number, 
                                   user_id_in in number, 
                                   role_in in varchar2, 
                                   reason_out out varchar2)
    return number
    is
        org_id number;
    begin
        org_id := rhn_user.get_org_id(user_id_in);

        -- channel might be shared
        if role_in = 'subscribe' and
           rhn_channel.shared_user_role_check(channel_id_in, user_id_in, role_in) = 1 then
            return 1;
        end if;
        
        if role_in = 'manage' and 
           NVL(rhn_channel.get_org_id(channel_id_in), -1) <> org_id then
                reason_out := 'channel_not_owned';
               return 0;
            end if;
        
        if role_in = 'subscribe' and 
           rhn_channel.get_org_access(channel_id_in, org_id) = 0 then
                reason_out := 'channel_not_available';
                return 0;
            end if;
        
        -- channel admins have all roles
        if rhn_user.check_role_implied(user_id_in, 'channel_admin') = 1 then
            reason_out := 'channel_admin';
            return 1;
            end if;

        -- the subscribe permission is inferred 
    -- UNLESS the not_globally_subscribable flag is set 
        if role_in = 'subscribe'
        then
            if rhn_channel.org_channel_setting(channel_id_in, 
                       org_id,
                       'not_globally_subscribable') = 0 then
                reason_out := 'globally_subscribable';
                    return 1;
            end if;
        end if;
        
        -- all other roles (manage right now) are explicitly granted    
        reason_out := 'direct_permission';
        return rhn_channel.direct_user_role_check(channel_id_in, 
                                              user_id_in, role_in);
    end;
    
    -- same as above, but with no OUT param; useful in views, etc
    function user_role_check(channel_id_in in number, user_id_in in number, role_in in varchar2)
    return number
    is
        throwaway varchar2(256);
    begin
        return rhn_channel.user_role_check_debug(channel_id_in, user_id_in, role_in, throwaway);
    end;

    --
    -- For multiorg phase II, this function simply checks to see if the user's
    -- has a trust relationship that includes this channel by id.
    --
    function shared_user_role_check(channel_id in number, user_id in number, role in varchar2)
    return number
    is
      n number;
      oid number;
    begin
      oid := rhn_user.get_org_id(user_id);
      select 1 into n
      from rhnSharedChannelView s
      where s.id = channel_id and s.org_trust_id = oid;
      return 1;
      exception
        when no_data_found then
          return 0;
    end;

    -- same as above, but returns 1 if user_id_in is null
    -- This is useful in queries where user_id is not specified
    function loose_user_role_check(channel_id_in in number, user_id_in in number, role_in in varchar2)
    return number
    is
    begin
        if user_id_in is null then
            return 1;
        end if;
        return user_role_check(channel_id_in, user_id_in, role_in);
    end loose_user_role_check;
    
    -- directly checks the table, no inferred permissions
    function direct_user_role_check(channel_id_in in number, user_id_in in number, role_in in varchar2)
    return number
    is
        throwaway number;
    begin
        -- the idea: if we get past this query, the user has the role, else catch the exception and return 0
        select 1 into throwaway
          from rhnChannelPermissionRole CPR,
               rhnChannelPermission CP
         where CP.user_id = user_id_in
           and CP.channel_id = channel_id_in
           and CPR.label = role_in
           and CP.role_id = CPR.id;
           
        return 1;
    exception
        when no_data_found
            then
            return 0;
    end;
    
    -- check if an org has a certain setting
    function org_channel_setting(channel_id_in in number, org_id_in in number, setting_in in varchar2)
    return number
    is
        throwaway number;
    begin
        -- the idea: if we get past this query, the org has the setting, else catch the exception and return 0
        select 1 into throwaway
          from rhnOrgChannelSettingsType OCST,
               rhnOrgChannelSettings OCS
         where OCS.org_id = org_id_in
           and OCS.channel_id = channel_id_in
           and OCST.label = setting_in
           and OCS.setting_id = OCST.id;
           
        return 1;
    exception
        when no_data_found
            then
            return 0;
    end;
    
    FUNCTION channel_priority(channel_id_in IN number) 
    RETURN number
    IS
         channel_name varchar2(64);
         priority number;
         end_of_life_val date;
         org_id_val number;
    BEGIN

        select name, end_of_life, org_id
        into channel_name, end_of_life_val, org_id_val
        from rhnChannel
        where id = channel_id_in;

        if end_of_life_val is not null then
          return -400;
        end if;

        if channel_name like 'Red Hat Enterprise Linux%' or channel_name like 'RHEL%' then
          priority := 1000;
          if channel_name not like '%Beta%' then
            priority := priority + 1000;
          end if;

          priority := priority +
            case
              when channel_name like '%v. 5%' then 600
              when channel_name like '%v. 4%' then 500
              when channel_name like '%v. 3%' then 400
              when channel_name like '%v. 2%' then 300
              when channel_name like '%v. 1%' then 200
              else 0
            end;

          priority := priority +
            case
              when channel_name like 'Red Hat Enterprise Linux (v. 5%' then 60
              when (channel_name like '%AS%' and channel_name not like '%Extras%') then 50
              when (channel_name like '%ES%' and channel_name not like '%Extras%') then 40
              when (channel_name like '%WS%' and channel_name not like '%Extras%') then 30
              when (channel_name like '%Desktop%' and channel_name not like '%Extras%') then 20
              when channel_name like '%Extras%' then 10
              else 0
            end; 

          priority := priority +
            case
              when channel_name like '%)' then 5
              else 0
            end;

          priority := priority +
            case
              when channel_name like '%32-bit x86%' then 4
              when channel_name like '%64-bit Intel Itanium%' then 3
              when channel_name like '%64-bit AMD64/Intel EM64T%' then 2
              else 0
            end;
        elsif channel_name like 'Red Hat Desktop%' then
            priority := 900;

            if channel_name not like '%Beta%' then
               priority := priority + 50;
            end if;
 
          priority := priority +
            case
              when channel_name like '%v. 4%' then 40
              when channel_name like '%v. 3%' then 30
              when channel_name like '%v. 2%' then 20
              when channel_name like '%v. 1%' then 10
              else 0
            end;
            
          priority := priority +
            case
              when channel_name like '%32-bit x86%' then 4
              when channel_name like '%64-bit Intel Itanium%' then 3
              when channel_name like '%64-bit AMD64/Intel EM64T%' then 2
              else 0
            end;
         
        elsif org_id_val is not null then
          priority := 600;
        else
          priority := 500;
        end if;
      
      return -priority;

    end channel_priority;

    -- right now this only does the accounting changes; the cascade
    -- actually does the rhnServerChannel delete.
    procedure delete_server_channels(server_id_in in number)
    is
    begin
        update  rhnPrivateChannelFamily
        set     current_members = current_members -1
        where   org_id in (
                        select  org_id
                        from    rhnServer
                        where   id = server_id_in
                )
                and channel_family_id in (
                        select  rcfm.channel_family_id
                        from    rhnChannelFamilyMembers rcfm,
                                rhnServerChannel rsc
                        where   rsc.server_id = server_id_in
                                and rsc.channel_id = rcfm.channel_id
                and not exists (
                    select 1
                    from
                        rhnChannelFamilyVirtSubLevel cfvsl,
                        rhnSGTypeVirtSubLevel sgtvsl,
                        rhnServerEntitlementView sev,
                        rhnVirtualInstance vi
                    where
                        -- system is a virtual instance
                        vi.virtual_system_id = server_id_in
                        and vi.host_system_id = sev.server_id
                        -- system's host has a virt ent
                        and sev.label in ('virtualization_host',
                                          'virtualization_host_platform')
                        and sev.server_group_type_id = 
                            sgtvsl.server_group_type_id
                        -- the host's virt ent grants a cf virt sub level
                        and sgtvsl.virt_sub_level_id = cfvsl.virt_sub_level_id
                        -- the cf is in that virt sub level
                        and cfvsl.channel_family_id = rcfm.channel_family_id
                    )
                );
    end;

        -- this could certainly be optimized to do updates if needs be
        procedure refresh_newest_package(channel_id_in in number, caller_in in varchar2 := '(unknown)')
        is
        begin
                delete from rhnChannelNewestPackage where channel_id = channel_id_in;
                insert into rhnChannelNewestPackage
                        ( channel_id, name_id, evr_id, package_id, package_arch_id ) 
                        (       select  channel_id,
                                                name_id, evr_id,
                                                package_id, package_arch_id
                                from    rhnChannelNewestPackageView
                                where   channel_id = channel_id_in
                        );
                insert into rhnChannelNewestPackageAudit (channel_id, caller)
                    values (channel_id_in, caller_in);
                update rhnChannel 
                    set last_modified = greatest(sysdate, last_modified + 1/86400)
                    where id = channel_id_in; 
        end;

   procedure update_channel ( channel_id_in in number, invalidate_ss in number := 0, 
                              date_to_use in date := sysdate )
   is

   channel_last_modified date;
   last_modified_value date;

   cursor snapshots is
   select  snapshot_id id
   from    rhnSnapshotChannel
   where   channel_id = channel_id_in;

   begin

      select last_modified
      into channel_last_modified
      from rhnChannel
      where id = channel_id_in;
  
      last_modified_value := date_to_use;

      if last_modified_value <= channel_last_modified then
          last_modified_value := last_modified_value + 1/86400;
      end if;

      update rhnChannel set last_modified = last_modified_value
      where id = channel_id_in;

      if invalidate_ss = 1 then 
        for snapshot in snapshots loop
            update rhnSnapshot
            set invalid = lookup_snapshot_invalid_reason('channel_modified')
            where id = snapshot.id;
        end loop;
      end if;

   end update_channel;

   procedure update_channels_by_package ( package_id_in in number, date_to_use in date := sysdate )
   is

   cursor channels is
   select channel_id
   from rhnChannelPackage
   where package_id = package_id_in
   order by channel_id;

   begin
      for channel in channels loop
         -- we want to invalidate the snapshot assocated with the channel when we
         -- do this b/c we know we've added or removed or packages
         rhn_channel.update_channel ( channel.channel_id, 1, date_to_use );
      end loop;
   end update_channels_by_package;

   
   procedure update_channels_by_errata ( errata_id_in number, date_to_use in date := sysdate )
   is

   cursor channels is
   select channel_id
   from rhnChannelErrata
   where errata_id = errata_id_in
   order by channel_id;

   begin
      for channel in channels loop
         -- we won't invalidate snapshots, b/c just changing the errata associated with
         -- a channel shouldn't invalidate snapshots
         rhn_channel.update_channel ( channel.channel_id, 0, date_to_use );
      end loop;
   end update_channels_by_errata;

END rhn_channel;
/
SHOW ERRORS

--
-- Revision 1.75  2005/03/04 00:04:19  jslagle
-- bz #147617
-- Made Red Hat Desktop sort a little better.
--
-- Revision 1.74  2005/02/22 03:24:47  jslagle
-- bz #147617
-- Improve channel_priority function to order channels better.
--
-- Revision 1.73  2004/08/16 20:39:30  pjones
-- bugzilla: 129889 -- make bulk_server_basechange_from() actually work.
--
-- Revision 1.72  2004/04/14 00:09:24  pjones
-- bugzilla: 120761 -- split rhnChannelPermissions into two tables, eliminating
-- a frequent full table scan
--
-- Revision 1.71  2004/04/13 16:28:36  bretm
-- bugzilla:  119871
--
-- keep track of rhnServer.channels_changed through the pl/sql fns
--
-- Revision 1.70  2004/03/26 18:11:32  rbb
-- Bugzilla:  114057
--
-- Add a script to determine channel priority.
--
-- Revision 1.69  2004/02/17 20:16:52  pjones
-- bugzilla: none -- add cvs tags into the package as long as we're touching
-- it anyway
--
-- Revision 1.68  2004/02/17 20:05:38  pjones
-- bugzilla: 115782 -- make bulk_server_basechange_from() filter out servers
-- with arches incompatible with the target channel
--
-- Revision 1.67  2004/02/06 02:36:10  misa
-- Changed normalize_server_arch to allow for solaris arches
--
-- Revision 1.66  2003/11/13 16:58:34  cturner
-- make use of new rhn_user.check_role_implied call; pragmas broke, removed them for now since I have no idea how to fix them
--
-- Revision 1.65  2003/10/23 20:26:24  bretm
-- bugzilla:  none
--
-- note the channel label when we unsubscribe, too
--
-- Revision 1.64  2003/10/15 14:47:17  bretm
-- bugzilla:  none
--
-- add the channel label to the server history summary line when we log a channel change
--
-- Revision 1.63  2003/09/24 19:25:56  pjones
-- this wasn't the right fix, put it back
--
-- Revision 1.62  2003/09/24 17:42:19  pjones
-- bugzilla: none
--
-- limit our server base channel guess to channels with available permissions
--
-- Revision 1.61  2003/09/22 21:00:40  cturner
-- add method for easy acl check
--
-- Revision 1.60  2003/09/17 22:14:11  misa
-- bugzilla: 103639  Changes to allow me to move the base channel guess into plsql
--
-- Revision 1.59  2003/08/21 13:41:17  cturner
-- bugzilla: 99187.  properly test for satellite and proxy in bulk_guess_server_base; reorg code for better reuse
--
-- Revision 1.58  2003/07/24 16:46:22  cturner
-- bugzilla: 100723, the perm check was returning duplicates, so now it just calls the function it should have called anyway
--
-- Revision 1.57  2003/07/24 16:44:16  misa
-- bugzilla: none  A function more usable on the rhnapp side
--
-- Revision 1.56  2003/07/23 22:36:51  cturner
-- argh, max returns null even when now rows; use distinct.  how revolting
--
-- Revision 1.55  2003/07/23 22:01:31  cturner
-- oops, this one can return multiple rows; eliminate that in a lazy way
--
-- Revision 1.54  2003/07/23 21:59:19  cturner
-- rework how rhnUserChannel works; move to plsql for speed and maintenance
--
-- Revision 1.53  2003/07/21 17:49:12  pjones
-- bugzilla: none
--
-- add optional user for subscribe_server
--
-- Revision 1.52  2003/07/14 22:19:29  misa
-- bugzilla: none  Updating guess_base_channel to work more like the rhnapp server code
--
-- Revision 1.51  2003/06/26 22:09:04  pjones
-- bugzilla: none
--
-- log subscribe and unsubscribe
--
-- Revision 1.50  2003/06/05 19:31:15  pjones
-- bugzilla: 88278 -- make the cursor name smaller
--
-- Revision 1.49  2003/06/05 19:18:21  pjones
-- bugzilla: 88278
--
-- unsubscribe_server() opens the package-level cursor when it invokes itself,
-- so we're using a local copy instead.
--
-- Revision 1.48  2003/06/04 16:41:39  pjones
-- bugzilla: none
--
-- make bulk_guess_server_base() silently ignore unguessables
--
-- Revision 1.47  2003/06/04 16:27:03  pjones
-- bugzilla: 88822
--
-- eliminate the last outliers that remove things from channels without using
-- unsubscribe_server, I think.
--
-- Revision 1.46  2003/06/03 20:49:37  pjones
-- bugzilla: 88822
-- unsubscribing from rhn-satellite now clears rhnSatelliteChannelFamily
-- for the server in question
--
-- Revision 1.45  2003/06/02 20:41:45  pjones
-- bugzilla: none - fix rhnProxyInfo/rhnSatelliteInfo channel unsubscribe
-- problem.  Basicly, if you're out of the channel for any reason, you're
-- also out of rhnProxyInfo/rhnProxyInfo
--
-- Revision 1.44  2003/03/24 15:26:28  pjones
-- bugzilla: 85812
--
-- bulk_server_base_change silently ignores servers that are satellites
-- or proxies, as requested.
--
-- Revision 1.43  2003/02/26 20:28:17  pjones
-- rhn_channel.update_family_counts() in rhn_channel.entitle_customer()
-- the old codepath is:
--
-- ep ->
-- rhn_ep.entitlement_run_me() ->
-- rhn_ep.poll_customer() ->
-- rhn_channel.entitle_customer()
--
-- which doesn't change current_members, even though it may remove servers
-- from the family.
--
-- There's another bug here:  currently, we don't try to order forced
-- unsubscribes in any way; we just use
-- rhn_channel.unsubscribe_server_from_family .  If there are any child
-- channel subscriptions, this will leave them subscribed.  We really need
-- to iterate across the channels again, and subscribe any channel for which
-- there are no parent channel subscriptions.
--
-- Ugh.
--
-- Revision 1.42  2003/01/28 00:19:45  pjones
-- fix clear_subscriptions; AFAICT, this is only hit on the
-- bulk_server_base_change / bulk_server_base_guess codepaths, which puts
-- it infrequent enough that it could be our "bad count" culprit.
--
-- Revision 1.41  2003/01/14 19:51:45  pjones
-- make setting current_members on rhnChannelFamilyPermissions work when
-- a server is in more than one channel in a single family.
  070701000004DF000081B400000000000000000000000167AE11140000019F000000000000000000000000000000000000005F00000000susemanager-schema/upgrade/spacewalk-schema-0.5-to-spacewalk-schema-0.6/106-rhnErrataQueue.sql    -- Clear any preexisting tasks before the upgrade
delete from rhnErrataQueue;

-- Add a channel_id column, whcih is non null 
-- and fk to rhnChannel
ALTER TABLE rhnErrataQueue
  ADD channel_id number
CONSTRAINT rhn_equeue_cid_nn NOT NULL
CONSTRAINT rhn_equeue_cid_fk
    REFERENCES rhnChannel(id);

-- Drop unique constraint on errata_id
ALTER TABLE rhnErrataQueue DROP CONSTRAINT rhn_equeue_eoid_uq;

show errors
 070701000004E0000081B400000000000000000000000167AE11140000014E000000000000000000000000000000000000006B00000000susemanager-schema/upgrade/spacewalk-schema-0.5-to-spacewalk-schema-0.6/107-rhnErrataNotificationQueue.sql    -- Clear any preexisting tasks before the upgrade
delete from rhnErrataNotificationQueue;

-- Add a channel_id column, whcih is non null
-- and fk to rhnChannel
ALTER TABLE rhnErrataNotificationQueue
  ADD channel_id number
CONSTRAINT rhn_enqueue_nn NOT NULL
CONSTRAINT rhn_enqueue_cid_fk
    REFERENCES rhnChannel(id);

show errors

  070701000004E1000081B400000000000000000000000167AE11140000018E000000000000000000000000000000000000006600000000susemanager-schema/upgrade/spacewalk-schema-0.5-to-spacewalk-schema-0.6/108-rhn_command_parameter.sql -- In Satellite 5.1.0 (svn rev. 136500, bug #429529) input field for
-- "SNMP Community String" was mistakenly changed from 'text' to
-- 'password'. This caused web forms for creating "General: SNMP Check"
-- and "General: Uptime (SNMP)" to be rendered incorrectly.

update rhn_command_parameter
	set field_widget_name = 'text' where
	command_id in (16, 113) and param_name = 'community';

commit;
  070701000004E2000081B400000000000000000000000167AE111400000074000000000000000000000000000000000000006300000000susemanager-schema/upgrade/spacewalk-schema-0.5-to-spacewalk-schema-0.6/109-rhnActionKickstart.sql    -- Adding system record for reprovisioning

ALTER TABLE rhnActionKickstart
 ADD cobbler_system_name varchar2(256);

070701000004E3000081B400000000000000000000000167AE11140000011D000000000000000000000000000000000000006900000000susemanager-schema/upgrade/spacewalk-schema-0.5-to-spacewalk-schema-0.6/110-time_series_probe_id_idx.sql  -- bugzilla 497477
-- we need function based index to lookup in that non-1st-NF o_id column

create index time_series_probe_id_idx
on time_series(SUBSTR(O_ID, INSTR(O_ID, '-') + 1,
 (INSTR(O_ID, '-', INSTR(O_ID, '-') + 1) - INSTR(O_ID, '-')) - 1
 ))
tablespace [[64k_tbs]]
nologging;

   070701000004E4000081B400000000000000000000000167AE11140000DC77000000000000000000000000000000000000006500000000susemanager-schema/upgrade/spacewalk-schema-0.5-to-spacewalk-schema-0.6/111-rhn_entitlements.pkb.sql  --
-- Copyright (c) 2008 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--

create or replace
package body rhn_entitlements
is
	body_version varchar2(100) := '';


    -- *******************************************************************
    -- PROCEDURE: remove_org_entitlements
    --
    -- Removes both system entitlements and channel subscriptions
    -- that are currently assigned to an org and re-assigns to the
    -- master org (org_id = 1).
    --
    -- When we call this we expect everything to already be unentitled
    -- which shoul be handled by delete_org.
    --
    -- Called by: delete_org
    -- *******************************************************************
    procedure remove_org_entitlements(
        org_id_in in number
    )
    is

        cursor system_ents is
        select sg.id, sg.max_members, sg.group_type
        from rhnServerGroup sg
        where group_type is not null
          and org_id = org_id_in;

        cursor channel_subs is
        select pcf.channel_family_id, pcf.max_members
        from rhnChannelFamily cf,
             rhnPrivateChannelFamily pcf
        where pcf.org_id = org_id_in
          and pcf.channel_family_id = cf.id
          and cf.org_id is null;

    begin

        for system_ent in system_ents loop
            update rhnServerGroup
            set max_members = max_members + system_ent.max_members
            where org_id = 1
              and group_type = system_ent.group_type;
        end loop;

        update rhnServerGroup
        set max_members = 0
        where org_id = org_id_in;

        for channel_sub in channel_subs loop
            update rhnPrivateChannelFamily
            set max_members = max_members + channel_sub.max_members
            where org_id = 1
              and channel_family_id = channel_sub.channel_family_id;
        end loop;
        
        update rhnPrivateChannelFamily
        set max_members = 0
        where org_id = org_id_in;

    end remove_org_entitlements;
 
	function entitlement_grants_service (
	    entitlement_in in varchar2,
	    service_level_in in varchar2
	) return number	is
	begin
		if service_level_in = 'provisioning' then
			if entitlement_in = 'provisioning_entitled' then
				return 1;
			else
				return 0;
			end if;
		elsif service_level_in = 'management' then
			if entitlement_in = 'enterprise_entitled' then
				return 1;
			else
				return 0;
			end if;
		elsif service_level_in = 'monitoring' then
			if entitlement_in = 'monitoring_entitled' then
				return 1;
			end if;
		elsif service_level_in = 'updates' then
			return 1;			
		else
			return 0;
		end if;
	end entitlement_grants_service;

	function lookup_entitlement_group (
		org_id_in in number,
		type_label_in in varchar2 := 'sw_mgr_entitled'
	) return number is
		cursor server_groups is
			select	sg.id				server_group_id
			from	rhnServerGroup		sg,
					rhnServerGroupType	sgt
			where	sgt.label = type_label_in
				and sgt.id = sg.group_type
				and sg.org_id = org_id_in;
	begin
		for sg in server_groups loop
			return sg.server_group_id;
		end loop;
		return rhn_entitlements.create_entitlement_group(
				org_id_in, 
				type_label_in
			);
	end lookup_entitlement_group;

	function create_entitlement_group (
		org_id_in in number,
		type_label_in in varchar2 := 'sw_mgr_entitled'
	) return number is
		sg_id_val number;
	begin
		select	rhn_server_group_id_seq.nextval
		into	sg_id_val
		from	dual;

		insert into rhnServerGroup (
				id, name, description, max_members, current_members,
				group_type, org_id
			) (
				select	sg_id_val, sgt.label, sgt.label,
						0, 0, sgt.id, org_id_in
				from	rhnServerGroupType sgt
				where	sgt.label = type_label_in
			);

		return sg_id_val;
	end create_entitlement_group;

   function can_entitle_server ( 
        server_id_in in number, 
        type_label_in in varchar2 ) 
   return number is
      cursor addon_servergroups (base_label_in in varchar2, 
                                 addon_label_in in varchar2) is
         select
            addon_id
         from
            rhnSGTypeBaseAddonCompat
         where base_id = lookup_sg_type (base_label_in)
           and addon_id = lookup_sg_type (addon_label_in);

      previous_ent        rhn_entitlements.ents_array;
      is_base_in          char   := 'N';
      is_base_current     char   := 'N';
      i                   number := 0;
      sgid                number := 0;

   begin

      previous_ent := rhn_entitlements.ents_array();
      previous_ent := rhn_entitlements.get_server_entitlement(server_id_in);

      select distinct is_base
      into is_base_in
      from rhnServerGroupType
      where label = type_label_in;

      if previous_ent.count = 0 then
         if (is_base_in = 'Y' and rhn_entitlements.find_compatible_sg (server_id_in, type_label_in, sgid)) then
            -- rhn_server.insert_into_servergroup (server_id_in, sgid);
            return 1;
         else
            -- rhn_exception.raise_exception ('invalid_base_entitlement');
            return 0;
         end if;

      -- there are previous ents, first make sure we're not trying to entitle a base ent
      elsif is_base_in = 'Y' then
         -- rhn_exception.raise_exception ('invalid_addon_entitlement');
         return 0;

      -- it must be an addon, so proceed with the entitlement
      else

         -- find the servers base ent
         is_base_current := 'N';
         i := 0;
         while is_base_current = 'N' and i <= previous_ent.count
         loop
            i := i + 1;
            select is_base
            into is_base_current
            from rhnServerGroupType
            where label = previous_ent(i);
         end loop;

         -- never found a base ent, that would be strange
         if is_base_current  = 'N' then
            -- rhn_exception.raise_exception ('invalid_base_entitlement');
            return 0;
         end if;

         -- this for loop verifies the validity of the addon path
         for addon_servergroup in addon_servergroups  (previous_ent(i), type_label_in) loop
            -- find an appropriate sgid for the addon and entitle the server
            if rhn_entitlements.find_compatible_sg (server_id_in, type_label_in, sgid) then
               -- rhn_server.insert_into_servergroup (server_id_in, sgid);
               return 1;
            else
               -- rhn_exception.raise_exception ('invalid_addon_entitlement');
               return 0;
            end if;
         end loop;

      end if;

      return 0;

   end can_entitle_server;

   function can_switch_base (
      server_id_in   in    integer,
      type_label_in  in    varchar2
   ) return number is

      type_label_in_is_base   char(1);
      sgid                    number;

   begin

      begin
         select is_base into type_label_in_is_base
         from rhnServerGroupType
         where label = type_label_in;
      exception
         when no_data_found then
            rhn_exception.raise_exception ( 'invalid_entitlement' );
      end;

      if type_label_in_is_base = 'N' then
         rhn_exception.raise_exception ( 'invalid_entitlement' );
      elsif rhn_entitlements.find_compatible_sg ( server_id_in, 
                                                  type_label_in, sgid ) then
         return 1;
      else
         return 0;
      end if;

   end can_switch_base;


   function find_compatible_sg (
      server_id_in    in   number,
      type_label_in   in   varchar2,
      sgid_out        out  number
   ) return boolean is

      cursor servergroups is
         select sg.id            id
           from rhnServerGroupType             sgt,
                rhnServerGroup                 sg,
                rhnServer                     s,
                rhnServerServerGroupArchCompat ssgac
          where s.id = server_id_in
            and s.org_id = sg.org_id
            and sgt.label = type_label_in
            and sg.group_type = sgt.id
            and ssgac.server_group_type = sgt.id
            and ssgac.server_arch_id = s.server_arch_id
            and not exists ( 
                     select 1
                      from rhnServerGroupMembers sgm
                     where sgm.server_group_id = sg.id 
                       and sgm.server_id = s.id);

         
   begin
      for servergroup in servergroups loop
         sgid_out := servergroup.id;
         return true;      
      end loop;

      --no servergroup found
      sgid_out := 0;
      return false;
   end find_compatible_sg;

	procedure entitle_server (
		server_id_in in number,
		type_label_in in varchar2 := 'sw_mgr_entitled'
	) is
      sgid  number := 0;
      is_virt number := 0;

	begin

          begin
          select 1 into is_virt
            from rhnServerEntitlementView
           where server_id = server_id_in
             and label in ('virtualization_host', 'virtualization_host_platform');
	  exception
            when no_data_found then
              is_virt := 0;
          end;
      
      if is_virt = 0 and (type_label_in = 'virtualization_host' or
                          type_label_in = 'virtualization_host_platform') then

        is_virt := 1;
      end if;



      if rhn_entitlements.can_entitle_server(server_id_in, 
                                             type_label_in) = 1 then
         if rhn_entitlements.find_compatible_sg (server_id_in, 
                                                 type_label_in, sgid) then
            insert into rhnServerHistory ( id, server_id, summary, details )
            values ( rhn_event_id_seq.nextval, server_id_in,
                     'added system entitlement ',
                      case type_label_in
                       when 'enterprise_entitled' then 'Management'
                       when 'sw_mgr_entitled' then 'Update'
                       when 'provisioning_entitled' then 'Provisioning'
                       when 'monitoring_entitled' then 'Monitoring'  
                       when 'virtualization_host' then 'Virtualization'
                       when 'virtualization_host_platform' then 
                            'Virtualization Platform' end  );

            rhn_server.insert_into_servergroup (server_id_in, sgid);

            if is_virt = 1 then
              rhn_entitlements.repoll_virt_guest_entitlements(server_id_in);
            end if;

         else
            rhn_exception.raise_exception ('no_available_server_group');
         end if;
      else
         rhn_exception.raise_exception ('invalid_entitlement');
      end if;
   end entitle_server;

	procedure remove_server_entitlement (
		server_id_in in number,
		type_label_in in varchar2 := 'sw_mgr_entitled',
        repoll_virt_guests in number := 1
	) is
		group_id number;
      type_is_base char;
      is_virt number := 0;
	begin
      begin


      -- would be nice if there were a virt attribute of entitlement types, not have to specify 2 different ones...
        begin
          select 1 into is_virt
            from rhnServerEntitlementView
           where server_id = server_id_in
             and label in ('virtualization_host', 'virtualization_host_platform');
        exception
          when no_data_found then
            is_virt := 0;
        end;

		select	sg.id, sgt.is_base
  		into	group_id, type_is_base
  		from	rhnServerGroupType sgt,
   			rhnServerGroup sg,
  				rhnServerGroupMembers sgm,
  				rhnServer s
  		where	s.id = server_id_in
  			and s.id = sgm.server_id
  			and sgm.server_group_id = sg.id
  			and sg.org_id = s.org_id
  			and sgt.label = type_label_in
  			and sgt.id = sg.group_type;

      if ( type_is_base = 'Y' ) then
         -- unentitle_server should handle everything, don't really need to do anything else special here
         unentitle_server ( server_id_in );
      else

         insert into rhnServerHistory ( id, server_id, summary, details )
         values ( rhn_event_id_seq.nextval, server_id_in,
                  'removed system entitlement ',
                   case type_label_in
                    when 'enterprise_entitled' then 'Management'
                    when 'sw_mgr_entitled' then 'Update'
                    when 'provisioning_entitled' then 'Provisioning'
                    when 'monitoring_entitled' then 'Monitoring'
                    when 'virtualization_host' then 'Virtualization'
                    when 'virtualization_host_platform' then 
                         'Virtualization Platforrm' end  );

         rhn_server.delete_from_servergroup(server_id_in, group_id);

         -- special case: clean up related monitornig data
         if type_label_in = 'monitoring_entitled' then
           DELETE
             FROM state_change
            WHERE o_id IN (SELECT probe_id
                             FROM rhn_check_probe
                            WHERE host_id = server_id_in);
           DELETE /*+index(time_series time_series_probe_id_idx)*/
             FROM time_series
            WHERE SUBSTR(o_id, INSTR(o_id, '-') + 1, 
                        (INSTR(o_id, '-', INSTR(o_id, '-') + 1) - INSTR(o_id, '-')) - 1)
              IN (SELECT to_char(probe_id)
                    FROM rhn_check_probe
                   WHERE host_id = server_id_in);
           DELETE
             FROM rhn_probe
            WHERE recid IN (SELECT probe_id
                              FROM rhn_check_probe
                             WHERE host_id = server_id_in);
         end if;

         if is_virt = 1 and repoll_virt_guests = 1 then
           rhn_entitlements.repoll_virt_guest_entitlements(server_id_in);
         end if;
      end if;

  		exception
  		when no_data_found then
  				rhn_exception.raise_exception('invalid_server_group_member');	
      end;

 	end remove_server_entitlement;


   procedure unentitle_server (server_id_in in number) is

      cursor servergroups is
         select distinct sgt.label, sg.id server_group_id
         from  rhnServerGroupType sgt,
               rhnServerGroup sg,
               rhnServer s,
               rhnServerGroupMembers sgm
         where s.id = server_id_in
            and s.org_id = sg.org_id
            and sg.group_type = sgt.id
            and sgm.server_group_id = sg.id
            and sgm.server_id = s.id;
            
     is_virt number := 0;

   begin

      begin
        select 1 into is_virt
          from rhnServerEntitlementView
         where server_id = server_id_in
           and label in ('virtualization_host', 'virtualization_host_platform');
      exception
        when no_data_found then
          is_virt := 0;
      end;

      for servergroup in servergroups loop

         insert into rhnServerHistory ( id, server_id, summary, details )
         values ( rhn_event_id_seq.nextval, server_id_in,
                  'removed system entitlement ',
                   case servergroup.label
                    when 'enterprise_entitled' then 'Management'
                    when 'sw_mgr_entitled' then 'Update'
                    when 'provisioning_entitled' then 'Provisioning'
                    when 'monitoring_entitled' then 'Monitoring'
                    when 'virtualization_host' then 'Virtualization'
                    when 'virtualization_host_platform' then 
                         'Virtualization Platform' end  );
  
         rhn_server.delete_from_servergroup(server_id_in, 
                                            servergroup.server_group_id );
      end loop;

      if is_virt = 1 then
        rhn_entitlements.repoll_virt_guest_entitlements(server_id_in);
      end if;

   end unentitle_server;


    -- *******************************************************************
    -- PROCEDURE: repoll_virt_guest_entitlements
    --
    --   Whenever we add/remove a virtualization_host* entitlement from 
    --   a host, we can call this procedure to update what type of slots
    --   the guests are consuming.  
    -- 
    --   If you're removing the entitlement, it's 
    --   possible the guests will become unentitled if you don't have enough
    --   physical slots to cover them.
    --
    --   If you're adding the entitlement, you end up freeing up physical
    --   slots for other systems.
    --
    -- *******************************************************************
    procedure repoll_virt_guest_entitlements(server_id_in in number)
    is

        -- All channel families associated with the guests of server_id_in
        cursor families is 
            select distinct cfs.channel_family_id
            from
                rhnChannelFamilyServers cfs,
                rhnVirtualInstance vi
            where
                vi.host_system_id = server_id_in
                and vi.virtual_system_id = cfs.server_id;
        
        -- All of server group types associated with the guests of
        -- server_id_in
        cursor group_types is
            select distinct sg.group_type, sgt.label
            from
                rhnServerGroupType sgt,
                rhnServerGroup sg,
                rhnServerGroupMembers sgm,
                rhnVirtualInstance vi
            where
                vi.host_system_id = server_id_in
                and vi.virtual_system_id = sgm.server_id
                and sgm.server_group_id = sg.id
                and sg.group_type = sgt.id;

        -- Virtual servers from a certain family belonging to a speicifc
        -- host that are consuming physical channel slots over the limit.
        cursor virt_servers_cfam(family_id_in in number, quantity_in in number)  is
            select virtual_system_id
            from (
                select rownum, vi.virtual_system_id
                from
                    rhnChannelFamilyMembers cfm,
                    rhnServerChannel sc,
                    rhnVirtualInstance vi
                where
                    vi.host_system_id = server_id_in
                    and vi.virtual_system_id = sc.server_id
                    and sc.channel_id = cfm.channel_id
                    and cfm.channel_family_id = family_id_in
                order by sc.modified desc
                )
            where rownum <= quantity_in;                

        -- Virtual servers from a certain family belonging to a speicifc
        -- host that are consuming physical system slots over the limit.
        cursor virt_servers_sgt(group_type_in in number, quantity_in in number)  is
            select virtual_system_id
            from (
                select rownum, vi.virtual_system_id
                from
                    rhnServerGroup sg,
                    rhnServerGroupMembers sgm,
                    rhnVirtualInstance vi
                where
                    vi.host_system_id = server_id_in
                    and vi.virtual_system_id = sgm.server_id
                    and sgm.server_group_id = sg.id
                    and sg.group_type = group_type_in
                order by sgm.modified desc
                )
            where rownum <= quantity_in;                
        
        org_id_val number;
        max_members_val number;
        current_members_calc number;
        sg_id number;

    begin

        select org_id
        into org_id_val
        from rhnServer
        where id = server_id_in;

        -- deal w/ channel entitlements first ...
        for family in families loop
            -- get the current (physical) members of the family
            current_members_calc := 
                rhn_channel.channel_family_current_members(family.channel_family_id,
                                                           org_id_val); -- fixed transposed args

            -- get the max members of the family
            select max_members
            into max_members_val
            from rhnPrivateChannelFamily
            where channel_family_id = family.channel_family_id
            and org_id = org_id_val;

            if current_members_calc > max_members_val then
                -- A virtualization_host* ent must have been removed, so we'll
                -- unsubscribe guests from the host first.

                -- hm, i don't think max_members - current_members_calc yielding a negative number
                -- will work w/ rownum, swaping 'em in the body of this if...
                for virt_server in virt_servers_cfam(family.channel_family_id,
                                current_members_calc - max_members_val) loop 

                    rhn_channel.unsubscribe_server_from_family(
                                virt_server.virtual_system_id,
                                family.channel_family_id);
                end loop;                               

                -- if we're still over the limit, which would be odd,
                -- just prune the group to max_members
                --
                -- er... wouldn't we actually have to refresh the values of
                -- current_members_calc and max_members_val to actually ever
                -- *skip this??
                if current_members_calc > max_members_val then
                    -- argh, transposed again?!
                    set_family_count(org_id_val,
                                     family.channel_family_id,
                                     max_members_val);
                end if; 

           end if;

            -- update current_members for the family.  This will set the value
            -- to reflect adding/removing the entitlement.
            --
            -- what's the difference of doing this vs the unavoidable set_family_count above?
            rhn_channel.update_family_counts(family.channel_family_id,
                                             org_id_val);
        end loop;

        for a_group_type in group_types loop
          -- get the current *physical* members of the system entitlement type for the org...
          -- 
          -- unlike channel families, it appears the standard rhnServerGroup.max_members represents
          -- *physical* slots, vs physical+virt ... boy that's confusing...

          select max_members, id
            into max_members_val, sg_id
            from rhnServerGroup
            where group_type = a_group_type.group_type
            and org_id = org_id_val;


	  select count(sep.server_id) into current_members_calc
            from rhnServerEntitlementPhysical sep
           where sep.server_group_id = sg_id
             and sep.server_group_type_id = a_group_type.group_type;
          
          if current_members_calc > max_members_val then
            -- A virtualization_host* ent must have been removed, and we're over the limit, so unsubscribe guests
            for virt_server in virt_servers_sgt(a_group_type.group_type,
                                                current_members_calc - max_members_val) loop
              rhn_entitlements.remove_server_entitlement(virt_server.virtual_system_id, a_group_type.label);

              -- decrement current_members_calc, we'll use it to reset current_members for the group at the end...
              current_members_calc := current_members_calc - 1;
            end loop;

          end if;

          update rhnServerGroup set current_members = current_members_calc
           where org_id = org_id_val
             and group_type = a_group_type.group_type;

          -- I think that's all the house-keeping we have to do...
        end loop;

    end repoll_virt_guest_entitlements;


	function get_server_entitlement (
		server_id_in in number
	) return ents_array is

		cursor server_groups is
			select	sgt.label
			from	rhnServerGroupType		sgt,
					rhnServerGroup			sg,
					rhnServerGroupMembers	sgm
			where	1=1
				and sgm.server_id = server_id_in
				and sg.id = sgm.server_group_id
				and sgt.id = sg.group_type
				and sgt.label in (
					'sw_mgr_entitled','enterprise_entitled',
					'provisioning_entitled', 'nonlinux_entitled',
					'monitoring_entitled', 'virtualization_host',
                                        'virtualization_host_platform'
					);

         ent_array ents_array;

	begin
      
      ent_array := ents_array();

		for sg in server_groups loop
         ent_array.extend;
         ent_array(ent_array.count) := sg.label;
		end loop;

		return ent_array;

	end get_server_entitlement;


	-- this desperately needs to be table driven.
	procedure modify_org_service (
		org_id_in in number,
		service_label_in in varchar2,
		enable_in in char
	) is
		type roles_v is varray(10) of rhnUserGroupType.label%TYPE;
		roles_to_process roles_v;
		cursor roles(role_label_in in varchar2) is
			select	label, id
			from	rhnUserGroupType
			where	label = role_label_in;
		cursor org_roles(role_label_in in varchar2) is
			select	1
			from	rhnUserGroup ug,
					rhnUserGroupType ugt
			where	ugt.label = role_label_in
				and ug.org_id = org_id_in
				and ugt.id = ug.group_type;
				
		type ents_v is varray(10) of rhnOrgEntitlementType.label%TYPE;
		ents_to_process ents_v;
		cursor ents(ent_label_in in varchar2) is
			select	label, id
			from	rhnOrgEntitlementType
			where	label = ent_label_in;
		cursor org_ents(ent_label_in in varchar2) is
			select	1
			from	rhnOrgEntitlements oe,
					rhnOrgEntitlementType oet
			where	oet.label = ent_label_in
				and oe.org_id = org_id_in
				and oet.id = oe.entitlement_id;
		create_row char(1);
	begin
		ents_to_process := ents_v();
		roles_to_process := roles_v();
		-- a bit kludgy, but only for 3.4 really.  Certainly no
		-- worse than the old code...
		if service_label_in = 'enterprise' or 
           service_label_in = 'management' then
			ents_to_process.extend;
			ents_to_process(ents_to_process.count) := 'sw_mgr_enterprise';

			roles_to_process.extend;
			roles_to_process(roles_to_process.count) := 'org_admin';

			roles_to_process.extend;
			roles_to_process(roles_to_process.count) := 'system_group_admin';

			roles_to_process.extend;
			roles_to_process(roles_to_process.count) := 'activation_key_admin';

			roles_to_process.extend;
			roles_to_process(roles_to_process.count) := 'org_applicant';
		elsif service_label_in = 'provisioning' then
			ents_to_process.extend;
			ents_to_process(ents_to_process.count) := 'rhn_provisioning';

			roles_to_process.extend;
			roles_to_process(roles_to_process.count) := 'system_group_admin';

			roles_to_process.extend;
			roles_to_process(roles_to_process.count) := 'activation_key_admin';

			roles_to_process.extend;
			roles_to_process(roles_to_process.count) := 'config_admin';
			-- another nasty special case...
			if enable_in = 'Y' then
				ents_to_process.extend;
				ents_to_process(ents_to_process.count) := 'sw_mgr_enterprise';
			end if;
		elsif service_label_in = 'monitoring' then
			ents_to_process.extend;
			ents_to_process(ents_to_process.count) := 'rhn_monitor';

			roles_to_process.extend;
			roles_to_process(roles_to_process.count) := 'monitoring_admin';
		elsif service_label_in = 'virtualization' then
			ents_to_process.extend;
			ents_to_process(ents_to_process.count) := 'rhn_virtualization';

			roles_to_process.extend;
			roles_to_process(roles_to_process.count) := 'config_admin';
        elsif service_label_in = 'virtualization_platform' then
			ents_to_process.extend;
			ents_to_process(ents_to_process.count) := 'rhn_virtualization_platform'; 
			roles_to_process.extend;
			roles_to_process(roles_to_process.count) := 'config_admin';
	elsif service_label_in = 'nonlinux' then
			ents_to_process.extend;
			ents_to_process(ents_to_process.count) := 'rhn_nonlinux';
			roles_to_process.extend;
			roles_to_process(roles_to_process.count) := 'config_admin';
		end if;

		if enable_in = 'Y' then
			for i in 1..ents_to_process.count loop
				for ent in ents(ents_to_process(i)) loop
					create_row := 'Y';
					for oe in org_ents(ent.label) loop
						create_row := 'N';
					end loop;
					if create_row = 'Y' then
						insert into rhnOrgEntitlements(org_id, entitlement_id)
							values (org_id_in, ent.id);
					end if;
				end loop;
			end loop;
			for i in 1..roles_to_process.count loop
				for role in roles(roles_to_process(i)) loop
					create_row := 'Y';
					for o_r in org_roles(role.label) loop
						create_row := 'N';
					end loop;
					if create_row = 'Y' then
						insert into rhnUserGroup(
								id, name, description, current_members,
								group_type, org_id
							) (
								select	rhn_user_group_id_seq.nextval,
										ugt.name || 's',
										ugt.name || 's for Org ' ||
											o.name || ' ('|| o.id ||')',
										0, ugt.id, o.id
								from	rhnUserGroupType ugt,
										web_customer o
								where	o.id = org_id_in
									and ugt.id = role.id
							);
					end if;
				end loop;
			end loop;
		else
			for i in 1..ents_to_process.count loop
				for ent in ents(ents_to_process(i)) loop
					delete from rhnOrgEntitlements
					 where org_id = org_id_in
					   and entitlement_id = ent.id;
				end loop;
			end loop;
		end if;
	end modify_org_service;

	procedure set_customer_enterprise (
		customer_id_in in number
	) is
	begin
		modify_org_service(customer_id_in, 'enterprise', 'Y');
	end set_customer_enterprise;

	procedure set_customer_provisioning (
		customer_id_in in number
	) is
	begin
		modify_org_service(customer_id_in, 'provisioning', 'Y');
	end set_customer_provisioning;

	procedure set_customer_monitoring (
		customer_id_in in number
	) is
	begin
		modify_org_service(customer_id_in, 'monitoring', 'Y');
	end set_customer_monitoring;

	procedure set_customer_nonlinux (
		customer_id_in in number
	) is
	begin
		modify_org_service(customer_id_in, 'nonlinux', 'Y');
	end set_customer_nonlinux;

	procedure unset_customer_enterprise (
		customer_id_in in number
	) is
	begin
		modify_org_service(customer_id_in, 'enterprise', 'N');
	end unset_customer_enterprise;

	procedure unset_customer_provisioning (
		customer_id_in in number
	) is
	begin
		modify_org_service(customer_id_in, 'provisioning', 'N');
	end unset_customer_provisioning;

	procedure unset_customer_monitoring (
		customer_id_in in number
	) is
	begin
		modify_org_service(customer_id_in, 'monitoring', 'N');
	end unset_customer_monitoring;

	procedure unset_customer_nonlinux (
		customer_id_in in number
	) is
	begin
		modify_org_service(customer_id_in, 'nonlinux', 'N');
	end unset_customer_nonlinux;

    -- *******************************************************************
    -- PROCEDURE: prune_group
    -- Unsubscribes servers consuming physical slots that over the org's
    --   limit.
    -- Called by: set_group_count, prune_everything, repoll_virt_guest_entitlements
    -- *******************************************************************
	procedure prune_group (
		group_id_in in number,
		type_in in char,
		quantity_in in number
	) is
		cursor usergroups is
			select	user_id, user_group_id, ugt.label
			from	rhnUserGroupType	ugt,
					rhnUserGroup		ug,
					rhnUserGroupMembers	ugm
			where	1=1
				and ugm.user_group_id = group_id_in
				and ugm.user_id in (
					select	user_id
					from	(
						select	rownum row_number,
								user_id,
								time
						from	(
							select	user_id,
									modified time
							from	rhnUserGroupMembers
							where	user_group_id = group_id_in
							order by time asc
						)
					)
					where	row_number > quantity_in
				)
				and ugm.user_group_id = ug.id
				and ug.group_type = ugt.id;
        cursor servergroups is
           select  server_id, server_group_id, sgt.id group_type_id, sgt.label
            from    rhnServerGroupType              sgt,
                            rhnServerGroup                  sg,
                            rhnServerGroupMembers   sgm
            where   1=1
                    and sgm.server_group_id = group_id_in
                    and sgm.server_id in (
                            select  server_id
                            from    (
                                    select  rownum row_number,
                                                    server_id,
                                                    time
                                    from    (
                                            select  sep.server_id,
                                                    sep.modified time
                                            from
                                                rhnServerEntitlementPhysical sep
                                            where
                                                sep.server_group_id = group_id_in
                                            order by time asc
                                    )
                            )
                            where   row_number > quantity_in
                    )
                    and sgm.server_group_id = sg.id
                    and sg.group_type = sgt.id;
      type_is_base char;
	begin
		if type_in = 'U' then
			update		rhnUserGroup
				set		max_members = quantity_in
				where	id = group_id_in;

			for ug in usergroups loop
				rhn_user.remove_from_usergroup(ug.user_id, ug.user_group_id);
			end loop;
		elsif type_in = 'S' then
			update		rhnServerGroup
				set		max_members = quantity_in
				where	id = group_id_in;

			for sg in servergroups loop
				remove_server_entitlement(sg.server_id, sg.label);
            
            select is_base 
            into type_is_base
            from rhnServerGroupType sgt
            where sgt.id = sg.group_type_id;
 
            -- if we're removing a base ent, then be sure to
            -- remove the server's channel subscriptions.
            if ( type_is_base = 'Y' ) then
				   rhn_channel.clear_subscriptions(sg.server_id);
            end if;

			end loop;
		end if;
	end prune_group;

    -- *******************************************************************
    -- PROCEDURE: assign_system_entitlement
    --
    -- Moves system entitlements from from_org_id_in to to_org_id_in.
    -- Can raise not_enough_entitlements_in_base_org if from_org_id_in
    -- does not have enough entitlements to cover the move.
    -- Takes care of unentitling systems if necessary by calling 
    -- set_group_count
    -- *******************************************************************
    procedure assign_system_entitlement(
        group_label_in in varchar2,
        from_org_id_in in number,
        to_org_id_in in number,
        quantity_in in number
    )
    is
        prev_ent_count number;
	to_org_prev_ent_count number;
        new_ent_count number;
	new_quantity number;
        group_type number;
    begin

        begin
            select max_members
            into prev_ent_count
            from rhnServerGroupType sgt,
                 rhnServerGroup sg
            where sg.org_id = from_org_id_in
              and sg.group_type = sgt.id
              and sgt.label = group_label_in;
        exception
            when NO_DATA_FOUND then
                rhn_exception.raise_exception(
                              'not_enough_entitlements_in_base_org');
        end;

        begin
            select max_members
            into to_org_prev_ent_count
            from rhnServerGroupType sgt,
                 rhnServerGroup sg
            where sg.org_id = to_org_id_in
              and sg.group_type = sgt.id
              and sgt.label = group_label_in;
        exception
            when NO_DATA_FOUND then
                to_org_prev_ent_count := 0;
        end;
	
        begin
            select id
            into group_type
            from rhnServerGroupType
            where label = group_label_in;
        exception
            when NO_DATA_FOUND then
                rhn_exception.raise_exception(
                              'invalid_server_group');
        end;

        new_ent_count := prev_ent_count - quantity_in;
	
        if prev_ent_count > new_ent_count then
            new_quantity := to_org_prev_ent_count + quantity_in;
        end if;
	
        if new_ent_count < 0 then
            rhn_exception.raise_exception(
                          'not_enough_entitlements_in_base_org');
        end if;


        rhn_entitlements.set_group_count(from_org_id_in,
                                         'S',
                                         group_type,
                                         new_ent_count);

        rhn_entitlements.set_group_count(to_org_id_in,
                                         'S',
                                         group_type,
                                         new_quantity);
        
        -- Create or delete the entries in rhnOrgEntitlementType
        if group_label_in = 'enterprise_entitled' then 
            if new_quantity > 0 then
                set_customer_enterprise(to_org_id_in);
            else
                unset_customer_enterprise(to_org_id_in);
            end if;
        end if;

        if group_label_in = 'provisioning_entitled' then
            if new_quantity > 0 then
                set_customer_provisioning(to_org_id_in);
            else
                unset_customer_provisioning(to_org_id_in);
            end if;
        end if;

        if group_label_in = 'monitoring_entitled' then
            if new_quantity > 0 then
                set_customer_monitoring(to_org_id_in);
            else
                unset_customer_monitoring(to_org_id_in);
            end if;
        end if;

    end assign_system_entitlement;

    -- *******************************************************************
    -- PROCEDURE: assign_channel_entitlement
    --
    -- Moves channel entitlements from from_org_id_in to to_org_id_in.
    -- Can raise not_enough_entitlements_in_base_org if from_org_id_in
    -- does not have enough entitlements to cover the move.
    -- Takes care of unentitling systems if necessary by calling 
    -- set_family_count
    -- *******************************************************************
    procedure assign_channel_entitlement(
        channel_family_label_in in varchar2,
        from_org_id_in in number,
        to_org_id_in in number,
        quantity_in in number
    )
    is
        prev_ent_count number;
        new_ent_count number;
	to_org_prev_ent_count number;
	new_quantity number;
        cfam_id       number;
    begin

        begin
            select max_members
            into prev_ent_count
            from rhnChannelFamily cf,
                 rhnPrivateChannelFamily pcf
            where pcf.org_id = from_org_id_in
              and pcf.channel_family_id = cf.id
              and cf.label = channel_family_label_in;
        exception
            when NO_DATA_FOUND then
                rhn_exception.raise_exception(
                              'not_enough_entitlements_in_base_org');
        end;
	
        begin
            select max_members
            into to_org_prev_ent_count
            from rhnChannelFamily cf,
                 rhnPrivateChannelFamily pcf
            where pcf.org_id = to_org_id_in
              and pcf.channel_family_id = cf.id
              and cf.label = channel_family_label_in;
        exception
            when NO_DATA_FOUND then
                to_org_prev_ent_count := 0;
        end;
	

        begin
            select id
            into cfam_id
            from rhnChannelFamily
            where label = channel_family_label_in;
        exception
            when NO_DATA_FOUND then
                rhn_exception.raise_exception(
                              'invalid_channel_family');
        end;                              

        new_ent_count := prev_ent_count - quantity_in;
	
	if prev_ent_count > new_ent_count then
            new_quantity := to_org_prev_ent_count + quantity_in;
	end if;
	

        if new_ent_count < 0 then
            rhn_exception.raise_exception(
                          'not_enough_entitlements_in_base_org');
        end if;

        rhn_entitlements.set_family_count(from_org_id_in,
                                          cfam_id,
                                          new_ent_count);

        rhn_entitlements.set_family_count(to_org_id_in,
                                          cfam_id,
                                          new_quantity);

    end assign_channel_entitlement;

    -- *******************************************************************
    -- PROCEDURE: activate_system_entitlement
    --
    -- Sets the values in rhnServerGroup for a given rhnServerGroupType.
    -- 
    -- Calls: set_group_count to update, prune, or create the group.
    -- Called by: the code that activates a satellite cert. 
    --
    -- Raises not_enough_entitlements_in_base_org if all entitlements
    -- in the org are used so the free entitlements would not cover
    -- the difference when descreasing the number of entitlements.
    -- *******************************************************************
    procedure activate_system_entitlement(
        org_id_in in number,
        group_label_in in varchar2,
        quantity_in in number
    )
    is
        prev_ent_count number; 
        prev_ent_count_sum number; 
        group_type number;
    begin

        -- Fetch the current entitlement count for the org
        -- into prev_ent_count
        begin
            select current_members
            into prev_ent_count
            from rhnServerGroupType sgt,
                 rhnServerGroup sg
            where sg.group_type = sgt.id
              and sgt.label = group_label_in
              and sg.org_id = org_id_in;
        exception
            when NO_DATA_FOUND then
                prev_ent_count := 0;
        end;

        begin
            select id
            into group_type
            from rhnServerGroupType
            where label = group_label_in;
        exception
            when NO_DATA_FOUND then
                rhn_exception.raise_exception(
                              'invalid_server_group');
        end;

        -- If we're setting the total entitlemnt count to a lower value,
        -- and that value is less than the allocated count in this org,
        -- we need to raise an exception.
        if quantity_in < prev_ent_count then
            rhn_exception.raise_exception(
                          'not_enough_entitlements_in_base_org');
        else
            rhn_entitlements.set_group_count(org_id_in,
                                             'S',
                                             group_type,
                                             quantity_in);
        end if;


    end activate_system_entitlement;

    -- *******************************************************************
    -- PROCEDURE: activate_channel_entitlement
    --
    -- Calls: set_family_count to update, prune, or create the family
    --        permission bucket.
    -- Called by: the code that activates a satellite cert. 
    --
    -- Raises not_enough_entitlements_in_base_org if there are not enough
    -- entitlements in the org to cover the difference when you are
    -- descreasing the number of entitlements.
    --
    -- The backend code in Python is expected to do whatever arithmetics
    -- is needed.
    -- *******************************************************************
    procedure activate_channel_entitlement(
        org_id_in in number,
        channel_family_label_in in varchar2,
        quantity_in in number
    )
    is
        prev_ent_count number; 
        prev_ent_count_sum number; 
        cfam_id number;
    begin

        -- Fetch the current entitlement count for the org
        -- into prev_ent_count
        begin
            select current_members
            into prev_ent_count
            from rhnChannelFamily cf,
                 rhnPrivateChannelFamily pcf
            where pcf.org_id = org_id_in
              and pcf.channel_family_id = cf.id
              and cf.label = channel_family_label_in;
        exception
            when NO_DATA_FOUND then
                prev_ent_count := 0;
        end;

        begin
            select id
            into cfam_id
            from rhnChannelFamily
            where label = channel_family_label_in;
        exception
            when NO_DATA_FOUND then
                rhn_exception.raise_exception(
                              'invalid_channel_family');
        end;                              

        -- If we're setting the total entitlemnt count to a lower value,
        -- and that value is less than the count in that one org,
        -- we need to raise an exception.
        if quantity_in < prev_ent_count then
            rhn_exception.raise_exception(
                          'not_enough_entitlements_in_base_org');
        else
            rhn_entitlements.set_family_count(org_id_in,
                                              cfam_id,
                                              quantity_in);
        end if;

    end activate_channel_entitlement;


	procedure set_group_count (
		customer_id_in in number,
		type_in in char,
		group_type_in in number,
		quantity_in in number
	) is
		group_id number;
		quantity number;
	begin
		quantity := quantity_in;
		if quantity is not null and quantity < 0 then
			quantity := 0;
		end if;

		if type_in = 'U' then
			select	rug.id
			into	group_id
			from	rhnUserGroup rug
			where	1=1
				and rug.org_id = customer_id_in
				and rug.group_type = group_type_in;
		elsif type_in = 'S' then
			select	rsg.id
			into	group_id
			from	rhnServerGroup rsg
			where	1=1
				and rsg.org_id = customer_id_in
				and rsg.group_type = group_type_in;
		end if;

		rhn_entitlements.prune_group(
			group_id,
			type_in,
			quantity
		);
	exception
		when no_data_found then
			if type_in = 'U' then
				insert into rhnUserGroup (
						id, name, description, max_members, current_members,
						group_type, org_id, created, modified
					) (
						select	rhn_user_group_id_seq.nextval, name, name,
								quantity, 0, id, customer_id_in,
								sysdate, sysdate
						from	rhnUserGroupType
						where	id = group_type_in
				);
			elsif type_in = 'S' then
				insert into rhnServerGroup (
						id, name, description, max_members, current_members,
						group_type, org_id, created, modified
					) (
						select	rhn_server_group_id_seq.nextval, name, name,
								quantity, 0, id, customer_id_in,
								sysdate, sysdate
						from	rhnServerGroupType
						where	id = group_type_in
				);
			end if;
	end set_group_count;

    -- *******************************************************************
    -- PROCEDURE: prune_family
    -- Unsubscribes servers consuming physical slots from the channel family 
    --   that are over the org's limit.
    -- Called by: set_family_count, prune_everything
    -- *******************************************************************
	procedure prune_family (
		customer_id_in in number,
		channel_family_id_in in number,
		quantity_in in number
	) is
		cursor serverchannels is
			select	sc.server_id,
					sc.channel_id
			from	rhnServerChannel sc,
					rhnChannelFamilyMembers cfm
			where	1=1
				and cfm.channel_family_id = channel_family_id_in
				and cfm.channel_id = sc.channel_id
				and server_id in (
					select	server_id
					from	(
						select	server_id,
								time,
								rownum row_number
						from	(
							select	rs.id					server_id,
									rcfm.modified			time
							from	
									rhnServerChannel		rsc,
									rhnChannelFamilyMembers	rcfm,
                                    rhnServer				rs
							where	1=1
								and rs.org_id = customer_id_in
								and rs.id = rsc.server_id
								and rsc.channel_id = rcfm.channel_id
								and rcfm.channel_family_id =
									channel_family_id_in
                                -- we only want to grab servers consuming
                                -- physical slots.
                                and exists (
                                    select 1
                                    from rhnChannelFamilyServerPhysical cfsp
                                    where cfsp.server_id = rs.id
                                    and cfsp.channel_family_id = 
                                        channel_family_id_in
                                    )
							order by time asc
						)
					)
					where row_number > quantity_in
				);
	begin
		-- if we get a null customer_id, this is completely bogus.
		if customer_id_in is null then
			return;
		end if;

		update		rhnPrivateChannelFamily
			set		max_members = quantity_in
			where	1=1
				and org_id = customer_id_in
				and channel_family_id = channel_family_id_in;

		for sc in serverchannels loop
			rhn_channel.unsubscribe_server(sc.server_id, sc.channel_id, 1, 1);
		end loop;
	end prune_family;
		
	procedure set_family_count (
		customer_id_in in number,
		channel_family_id_in in number,
		quantity_in in number
	) is
		cursor privperms is
			select	1
			from	rhnPrivateChannelFamily
			where	org_id = customer_id_in
				and channel_family_id = channel_family_id_in;
		cursor pubperms is
			select	o.id org_id
			from	web_customer o,
					rhnPublicChannelFamily pcf
			where	pcf.channel_family_id = channel_family_id_in;
		quantity number;
		done number := 0;
	begin
		quantity := quantity_in;
		if quantity is not null and quantity < 0 then
			quantity := 0;
		end if;

		if customer_id_in is not null then
			for perm in privperms loop
				rhn_entitlements.prune_family(
					customer_id_in,
					channel_family_id_in,
					quantity
				);
				update rhnPrivateChannelFamily
					set max_members = quantity
					where org_id = customer_id_in
						and channel_family_id = channel_family_id_in;
				return;
			end loop;
			
			insert into rhnPrivateChannelFamily (
					channel_family_id, org_id, max_members, current_members
				) values (
					channel_family_id_in, customer_id_in, quantity, 0
				);
			return;
		end if;

		for perm in pubperms loop
			if quantity = 0 then
				rhn_entitlements.prune_family(
					perm.org_id,
					channel_family_id_in,
					quantity
				);
				if done = 0 then
					delete from rhnPublicChannelFamily
						where channel_family_id = channel_family_id_in;
				end if;
			end if;
			done := 1;
		end loop;
		-- if done's not 1, then we don't have any entitlements
		if done != 1 then
			insert into rhnPublicChannelFamily (
					channel_family_id
				) values (
					channel_family_id_in
				);
		end if;
	end set_family_count;

	-- this expects quantity_in to be the number of available slots, not the
	-- max_members of the server group.  If you give it too many, it'll fail
	-- and raise servergroup_max_members.
	-- We should NEVER run this unless we're SURE that we won't
	-- be violating the max.
	procedure entitle_last_modified_servers (
		customer_id_in in number,
		type_label_in in varchar2,
		quantity_in in number
	) is
		-- find the servers that aren't currently in slots
		cursor servers(cid_in in number, quant_in in number) is
			select	server_id
			from	(
						select	rownum row_number,
								server_id
						from	(
									select	rs.id server_iD
									from	rhnServer rs
									where	1=1
										and rs.org_id = cid_in
										and not exists (
											select	1
											from	rhnServerGroup sg,
													rhnServerGroupMembers rsgm
											where	rsgm.server_id = rs.id
												and rsgm.server_group_id = sg.id
												and sg.group_type is not null
										)
                                        and not exists (
                                            select 1
                                            from rhnVirtualInstance vi
                                            where vi.virtual_system_id =
                                                  rs.id
                                        )                                                                           order by modified desc
								)
					)
			where	row_number <= quant_in;
	begin
		for server in servers(customer_id_in, quantity_in) loop
			rhn_entitlements.entitle_server(server.server_id, type_label_in);
		end loop;
	end entitle_last_modified_servers;

	procedure prune_everything (
		customer_id_in in number
	) is
		cursor everything is
			-- all our server groups
			select	sg.id					id,
					'S'						type,
					sg.max_members			quantity
			from	rhnServerGroup			sg
			where	sg.org_id = customer_id_in
			union
			-- all our user groups
			select	ug.id					id,
					'U'						type,
					ug.max_members 			quantity
			from	rhnUserGroup			ug
			where	ug.org_id = customer_id_in
			union ( 
			-- all the channel families we have perms to
			select	cfp.channel_family_id	id,
					'C'						type,
					cfp.max_members			quantity
			from	rhnOrgChannelFamilyPermissions cfp
			where	cfp.org_id = customer_id_in
			union
			-- plus all the ones we're using that we have no perms for
			select	cfm.channel_family_id	id,
					'C'						type,
					0						quantity
			from	rhnChannelFamily		cf,
					rhnChannelFamilyMembers	cfm,
					rhnServerChannel		sc,
					rhnServer				s
			where	s.org_id = customer_id_in
				and s.id = sc.server_id
				and sc.channel_id = cfm.channel_id
				and cfm.channel_family_id = cf.id
				and cf.org_id is not null
				and cf.org_id != customer_id_in
				and not exists (
					select	1
					from	rhnOrgChannelFamilyPermissions cfp
					where	cfp.org_id = customer_id_in
						and cfp.channel_family_id = cfm.channel_family_id
					)
			);
	begin
		for one in everything loop
			if one.type in ('U','S') then
				prune_group(one.id, one.type, one.quantity);
			else
				prune_family(customer_id_in, one.id, one.quantity);
			end if;
		end loop;
	end prune_everything;

	procedure subscribe_newest_servers (
		customer_id_in in number
	) is
		-- find servers without base channels
		cursor servers(cid_in in number) is
			select	s.id
			from	rhnServer			s
			where	1=1
				and s.org_id = cid_in
				and not exists (
						select 1
						from	rhnChannel			c,
								rhnServerChannel	sc
						where	sc.server_id = s.id
							and sc.channel_id = c.id
							and c.parent_channel is null
					)
                and not exists (
                        select 1
                        from rhnVirtualInstance vi
                        where vi.virtual_system_id = s.id
                    )                        
			order by s.modified desc;
		channel_id number;
	begin
		for server in servers(customer_id_in) loop
			channel_id := rhn_channel.guess_server_base(server.id);
			if channel_id is not null then
				begin
					rhn_channel.subscribe_server(server.id, channel_id);
					commit;
				-- exception is really channel_family_no_subscriptions
				exception
					when others then
						null;
				end;
			end if;
		end loop;
	end subscribe_newest_servers;
end rhn_entitlements;
/
show errors

--
--
-- Revision 1.56  2004/07/21 21:27:36  nhansen
-- bug 128196: use rhn_monitor instead of rhn_monitoring as the rhnOrgEntitlementType
--
-- Revision 1.55  2004/07/20 15:38:57  pjones
-- bugzilla: 128196 -- make entitling "monitoring" work.
--
-- Revision 1.54  2004/07/14 19:13:13  pjones
-- bugzilla: 126461 -- entitlement changes for new user roles
--
-- Revision 1.53  2004/07/02 19:18:20  pjones
-- bugzilla: 125937 -- use rhn_user to remove user roles
--
-- Revision 1.52  2004/05/26 19:45:48  pjones
-- bugzilla: 123639
-- 1) reformat "entitlement_grants_service"
-- 2) make the .pks and .pkb be in the same order.
-- 3) add "modify_org_service" (to be used instead of set_customer_SERVICELEVEL)
-- 4) add monitoring specific data.
--
-- Revision 1.51  2004/04/19 18:18:51  pjones
-- bugzilla: none -- misa's using set_family_count() to set null org entitlements
--
-- Revision 1.50  2004/04/14 00:09:24  pjones
-- bugzilla: 120761 -- split rhnChannelPermissions into two tables, eliminating
-- a frequent full table scan
--
-- Revision 1.49  2004/03/26 16:53:42  pjones
-- bugzilla: none -- make rhn_nonlinux give config_admin too on sat.
--
-- Revision 1.48  2004/03/25 22:29:56  pjones
-- bugzilla: none -- only create config_admin in set_customer_prov if we're
-- on a satellite
 070701000004E5000081B400000000000000000000000167AE1114000010B4000000000000000000000000000000000000006500000000susemanager-schema/upgrade/spacewalk-schema-0.5-to-spacewalk-schema-0.6/112-rhnPrivateErrataMail.sql  --
-- Copyright (c) 2008 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
-- This view is used for extracting data needed by the errata mailer
-- for private errata mails
--
--

create or replace view
rhnPrivateErrataMail
as
select
   w.id user_id,
   s.id server_id,
   w.org_id org_id,
   sc.channel_id channel_id,
   ce.errata_id errata_id
from
   rhnServer s,
   web_user_personal_info wpi,
   rhnUserInfo ui,
   rhnChannelErrata ce,
   web_contact w, 
   rhnServerChannel sc,
   rhnUserServerPerms usp
where
   -- we plan on starting with org_id, and server group is the 
   -- best place to find that that's near servers
   -- filter out servers that aren't in useful channels
   sc.channel_id = ce.channel_id
   -- find the server, so we can do s.arch comparisons
   and sc.server_id = s.id
   -- filter out users who don't want/can't get email
   and w.id = wpi.web_user_id
   and wpi.email is not null
   and w.id = ui.user_id
   and s.id = usp.server_id
   and usp.user_id = w.id
   -- filter out users who don't want mail about this server
   -- they get an entry if they _don't_ want mail
   and not exists (
      select   usprefs.server_id 
               from  rhnUserServerPrefs usprefs
         where w.id = usprefs.user_id 
               and sc.server_id = usprefs.server_id 
               and usprefs.name = 'receive_notifications'
   )
   and ui.email_notify = 1
      -- check permissions. For this query being an org admin is the
      -- most common thing, so we test for that first
   and exists (
         select 1
      from
            rhnPackageEVR        p_evr,
            rhnPackageEVR        sp_evr,
            rhnServerPackage     sp,
            rhnChannelPackage    cp,
            rhnPackage        p,
            rhnErrataPackage     ep,
            rhnServerPackageArchCompat spac
      where 1=1
         -- packages from channels this server is subscribed to
         and sc.channel_id = cp.channel_id
         and cp.package_id = p.id
         -- part of an errata
         and ce.errata_id = ep.errata_id
         and ep.package_id = p.id
         -- and that errata maps back to the server channel
         and sc.channel_id = ce.channel_id
         and ce.errata_id = ep.errata_id
         -- also installed on this server
         and sc.server_id = sp.server_id
         and sp.name_id = p.name_id
         and sp.evr_id = sp_evr.id
         -- different evr
         and p.evr_id = p_evr.id
         and sp.evr_id != p.evr_id
         -- and newer evr
         and sp_evr.evr < p_evr.evr
         and sp_evr.evr = (
            select max(sq2_pe.evr) max_evr
                from  rhnServerPackage  sq2_sp,
                rhnPackageEVR     sq2_pe
                where sq2_sp.evr_id = sq2_pe.id and
                  sq2_sp.server_id = sp.server_id and
                  sp.name_id = sq2_sp.name_id
	            group by sq2_sp.server_id, sq2_sp.name_id
         )
         -- compat arch
         and p.package_arch_id = spac.package_arch_id
         and s.server_arch_id = spac.server_arch_id
   )
   and not exists ( select 1
                      from rhnWebContactDisabled wcd
                     where wcd.id = w.id )
/


--select count(*) from rhnMailErrataView
--where org_id = 1 and errata_id = 916;

--
-- Revision 1.2  2003/02/21 20:56:00  pjones
-- change the comments to match the code ;)
--
-- Revision 1.1  2003/02/21 20:45:00  pjones
-- private errata mail
--
-- Revision 1.4  2003/02/12 18:49:11  pjones
-- note about old errata
--
-- Revision 1.3  2002/11/14 17:20:34  pjones
-- arch -> *_arch_id and archCompat changes
--
-- Revision 1.2  2002/11/11 20:49:46  pjones
-- that line's a typo
--
-- Revision 1.1  2002/09/24 22:42:17  pjones
-- free vs paid
--
070701000004E6000081B400000000000000000000000167AE111400002A76000000000000000000000000000000000000005E00000000susemanager-schema/upgrade/spacewalk-schema-0.5-to-spacewalk-schema-0.6/113-delete_server.sql -- 461704 - we need to wipe out all relevant entries for a probe from time_series
-- table whenever we're deleting server

create or replace
procedure delete_server (
	server_id_in in number
) is
	cursor servergroups is
		select	server_id, server_group_id
		from	rhnServerGroupMembers sgm
		where	sgm.server_id = server_id_in;
	cursor configchannels is
		select	cc.id
		from	rhnConfigChannel cc,
			rhnConfigChannelType cct,
			rhnServerConfigChannel scc
		where	1=1
			and scc.server_id = server_id_in
			and scc.config_channel_id = cc.id
			-- these config channel types are reserved
			-- for use by a single server, so we don't
			-- need to check for other servers subscribed
			and cct.label in
				('local_override','server_import')
			and cct.id = cc.confchan_type_id;
        type filelistsid_t is table of rhnServerPreserveFileList.file_list_id%type;
        filelistsid_c filelistsid_t;

        type probesid_t is table of rhn_check_probe.probe_id%type;
        probesid_c probesid_t;

    is_virt number := 0;
begin
	rhn_channel.delete_server_channels(server_id_in);
	-- rhn_channel.clear_subscriptions(server_id_in);

        -- filelists
	select	spfl.file_list_id id bulk collect into filelistsid_c
	  from	rhnServerPreserveFileList spfl
	 where	spfl.server_id = server_id_in
			and not exists (
				select	1
				from	rhnServerPreserveFileList
				where	file_list_id = spfl.file_list_id
					and server_id != server_id_in
				union
				select	1
				from	rhnKickstartPreserveFileList
				where	file_list_id = spfl.file_list_id
			);
        if filelistsid_c.first is not null then
            forall i in filelistsid_c.first..filelistsid_c.last
                delete from rhnFileList where id = filelistsid_c(i);
        end if;

	for configchannel in configchannels loop
		rhn_config.delete_channel(configchannel.id);
	end loop;

      select count(1) into is_virt
        from rhnServerEntitlementView
       where server_id = server_id_in
         and label in ('virtualization_host', 'virtualization_host_platform')
         and rownum <= 1;

	for sgm in servergroups loop
		rhn_server.delete_from_servergroup(
			sgm.server_id, sgm.server_group_id);
	end loop;

    if is_virt = 1 then
        rhn_entitlements.repoll_virt_guest_entitlements(server_id_in);
    end if;

	-- we're handling this instead of letting an "on delete
	-- set null" do it so that we don't run the risk
	-- of setting off the triggers and killing us with a
	-- mutating table

	-- this is merge of two single updates:
        --  update ... set old_server_id = null where old_server_id = server_id_in;
        --  update ... set new_server_id = null where new_server_id = server_id_in;
        -- so we scan rhnKickstartSession table only once
	update rhnKickstartSession
		set old_server_id = case when old_server_id = server_id_in then null else old_server_id end,
		    new_server_id = case when new_server_id = server_id_in then null else new_server_id end
		where old_server_id = server_id_in
		   or new_server_id = server_id_in;

	rhn_channel.clear_subscriptions(server_id_in,1);

	-- A little complicated here, but the goal is to
	-- delete records from rhnVirtualInstace only if we don't
	-- care about them anymore.  We don't care about records
	-- in rhnVirtualInstance if we are deleting the host
	-- system and the virtual system is already null, or
	-- vice-versa.  We *do* care about them if either the
	-- host or virtual system is still registered because we
	-- still want them to show up in the UI.
    -- If there's a newer row in rhnVirtualInstance with the same
    -- uuid, this guest must have been re-registered, so we can clean
    -- this data up.

        delete from rhnVirtualInstance vi
	      where (host_system_id = server_id_in and virtual_system_id is null)
                 or (virtual_system_id = server_id_in and host_system_id is null)
                 or (vi.virtual_system_id = server_id_in and vi.modified < (select max(vi2.modified)
                    from rhnVirtualInstance vi2 where vi2.uuid = vi.uuid));

        -- this is merge of two single updates:
        --  update ... set host_system_id = null where host_system_id = server_id_in;
        --  update ... set virtual_system_id = null where virtual_system_id = server_id_in;
        -- so we scan rhnVirtualInstance table only once
        update rhnVirtualInstance
	   set host_system_id = case when host_system_id = server_id_in then null else host_system_id end,
	       virtual_system_id = case when virtual_system_id = server_id_in then null else virtual_system_id end
	 where host_system_id = server_id_in
	    or virtual_system_id = server_id_in;

        -- this is merge of two single updates:
        --  update ... set old_host_system_id = null when old_host_system_id = server_id_in;
        --  update ... set new_host_system_id = null when new_host_system_id = server_id_in;
        -- so we scan rhnVirtualInstanceEventLog table only once
	update rhnVirtualInstanceEventLog
	   set old_host_system_id = case when old_host_system_id = server_id_in then null else old_host_system_id end,
               new_host_system_id = case when new_host_system_id = server_id_in then null else new_host_system_id end
         where old_host_system_id = server_id_in
            or new_host_system_id = server_id_in;

	-- We're deleting everything with a foreign key to rhnServer
	-- here, now.  I'm hoping this will help aleviate our deadlock
	-- problem.

	delete from rhnActionConfigChannel where server_id = server_id_in;
	delete from rhnActionConfigRevision where server_id = server_id_in;
	delete from rhnActionPackageRemovalFailure where server_id = server_id_in;
	delete from rhnChannelFamilyLicenseConsent where server_id = server_id_in;
	delete from rhnClientCapability where server_id = server_id_in;
	delete from rhnCpu where server_id = server_id_in;
	-- there's still a cascade here, because the constraint keeps the
	-- table locked for too long to rebuild it.  Ugh...
	delete from rhnDevice where server_id = server_id_in;
	delete from rhnProxyInfo where server_id = server_id_in;
	delete from rhnRam where server_id = server_id_in;
	delete from rhnRegToken where server_id = server_id_in;
	delete from rhnSNPServerQueue where server_id = server_id_in;
	delete from rhnSatelliteChannelFamily where server_id = server_id_in;
	delete from rhnSatelliteInfo where server_id = server_id_in;
	-- this cascades to rhnActionConfigChannel and rhnActionConfigFileName
	delete from rhnServerAction where server_id = server_id_in;
	delete from rhnServerActionPackageResult where server_id = server_id_in;
	delete from rhnServerActionScriptResult where server_id = server_id_in;
	delete from rhnServerActionVerifyResult where server_id = server_id_in;
	delete from rhnServerActionVerifyMissing where server_id = server_id_in;
	-- counts are handled above.  this should be a delete_ function.
	delete from rhnServerChannel where server_id = server_id_in;
	delete from rhnServerConfigChannel where server_id = server_id_in;
	delete from rhnServerCustomDataValue where server_id = server_id_in;
	delete from rhnServerDMI where server_id = server_id_in;
	delete from rhnServerMessage where server_id = server_id_in;
	-- this gets rhnServerMessage (only) on cascade; it's handled just above
	delete from rhnServerEvent where server_id = server_id_in;
	delete from rhnServerHistory where server_id = server_id_in;
	delete from rhnServerInfo where server_id = server_id_in;
	delete from rhnServerInstallInfo where server_id = server_id_in;
	delete from rhnServerLocation where server_id = server_id_in;
	delete from rhnServerLock where server_id = server_id_in;
	delete from rhnServerNeededCache where server_id = server_id_in;
	delete from rhnServerNetwork where server_id = server_id_in;
	delete from rhnServerNotes where server_id = server_id_in;
	-- I'm not removing the foreign key from rhnServerPackage; that'll
	-- take forever.  Do the delete anyway.
	delete from rhnServerPackage where server_id = server_id_in;
	delete from rhnServerTokenRegs where server_id = server_id_in;
	delete from rhnSnapshotTag where server_id = server_id_in;
	-- this cascades to:
	--   rhnSnapshotChannel, rhnSnapshotConfigChannel, rhnSnapshotPackage,
	--   rhnSnapshotConfigRevision, rhnSnapshotServerGroup,
	--   rhnSnapshotTag.
	-- We may want to consider delete_snapshot() at some point, but
	--   I don't think we need to yet.
	delete from rhnSnapshot where server_id = server_id_in;
	delete from rhnTransaction where server_id = server_id_in;
	delete from rhnUserServerPrefs where server_id = server_id_in;
	-- hrm, this one's interesting... we _probably_ should delete
	-- everything for the parent server_id when we delete the proxy,
	-- but we don't currently.
	delete from rhnServerPath where server_id_in in (server_id, proxy_server_id);
	delete from rhnUserServerPerms where server_id = server_id_in;

	delete from rhn_interface_monitoring where server_id = server_id_in;
	delete from rhnServerNetInterface where server_id = server_id_in;
	delete from rhn_server_monitoring_info where recid = server_id_in;

	delete from rhnAppInstallSession where server_id = server_id_in;
	delete from rhnServerUuid where server_id = server_id_in;
    -- We delete all the probes running directly against this system
    -- and any probes that were using this Server as a Proxy Scout.
     SELECT CP.probe_id bulk collect into probesid_c
       FROM rhn_check_probe CP
      WHERE CP.host_id = server_id_in
         OR CP.sat_cluster_id in
    (SELECT SN.sat_cluster_id
       FROM rhn_sat_node SN
      WHERE SN.server_id = server_id_in);

    if probesid_c.first is not null then
        FORALL i IN probesid_c.first..probesid_c.last
            DELETE FROM rhn_probe_state PS WHERE PS.probe_id = probesid_c(i);
        FORALL i IN probesid_c.first..probesid_c.last
            DELETE FROM rhn_probe P  WHERE P.recid = probesid_c(i);
        FORALL i IN probesid_c.first..probesid_c.last
            DELETE /*+index(time_series time_series_probe_id_idx)*/
            FROM time_series
            WHERE substr(o_id, instr(o_id, '-') + 1,
                (instr(o_id, '-', instr(o_id, '-') + 1) - instr(o_id, '-'))	- 1) = probesid_c(i);
    end if;

	delete from rhn_check_probe where host_id = server_id_in;
	delete from rhn_host_probe where host_id = server_id_in;

    delete from rhn_sat_cluster where recid in
      ( select sat_cluster_id from rhn_sat_node where server_id = server_id_in );

	delete from rhn_sat_node where server_id = server_id_in;

	-- now get rhnServer itself.
	delete
	from	rhnServer
		where id = server_id_in;

	delete
	from	rhnSet
	where	1=1
		and user_id in (
			select	wc.id
			from	rhnServer rs,
				web_contact wc
			where	rs.id = server_id_in
				and rs.org_id = wc.org_id
		)
		and label = 'system_list'
		and element = server_id_in;
end delete_server;
/
  070701000004E7000081B400000000000000000000000167AE1114000000A2000000000000000000000000000000000000006300000000susemanager-schema/upgrade/spacewalk-schema-0.5-to-spacewalk-schema-0.6/114-rhnKickstartScript.sql    alter table rhnKickstartScript  add (
      raw_script char(1) default('Y')
      constraint rhn_ksscript_raw_nn not null
      check (raw_script in ('Y','N')));
  070701000004E8000081B400000000000000000000000167AE111400000033000000000000000000000000000000000000005B00000000susemanager-schema/upgrade/spacewalk-schema-0.5-to-spacewalk-schema-0.6/115-rhnChannel.sql    alter table rhnChannel
modify name varchar2(256);

 070701000004E9000081B400000000000000000000000167AE111400000094000000000000000000000000000000000000005D00000000susemanager-schema/upgrade/spacewalk-schema-0.5-to-spacewalk-schema-0.6/116-rhn_sat_node.sql  drop index rhn_sat_node_sid_idx;
create unique index rhn_sat_node_sid_idx
on rhn_sat_node ( server_id )
   tablespace [[64k_tbs]]
   nologging
  ;

070701000004EA000081B400000000000000000000000167AE111400000074000000000000000000000000000000000000006F00000000susemanager-schema/upgrade/spacewalk-schema-0.5-to-spacewalk-schema-0.6/117-rhnKickstartVirtualizationType.sql    insert into rhnKickstartVirtualizationType (id, name, label)
    values (rhn_kvt_id_seq.nextval,  'None', 'none');

070701000004EB000081B400000000000000000000000167AE11140000C833000000000000000000000000000000000000006000000000susemanager-schema/upgrade/spacewalk-schema-0.5-to-spacewalk-schema-0.6/118-rhn_channel.pkb.sql   --
-- Copyright (c) 2008 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--

CREATE OR REPLACE
PACKAGE BODY rhn_channel
IS
        body_version varchar2(100) := '';

    -- Cursor that fetches all the possible base channels for a
    -- (server_arch_id, release, org_id) combination
        cursor  base_channel_cursor(
                release_in in varchar2,
                server_arch_id_in in number,
                org_id_in in number
        ) return rhnChannel%ROWTYPE is
                select distinct c.*
                from    rhnDistChannelMap                       dcm,
                                rhnServerChannelArchCompat      scac,
                                rhnChannel                                      c,
                                rhnChannelPermissions           cp
                where   cp.org_id = org_id_in
                        and cp.channel_id = c.id
                        and c.parent_channel is null
                        and c.id = dcm.channel_id
                        and c.channel_arch_id = dcm.channel_arch_id
                        and dcm.release = release_in
                        and scac.server_arch_id = server_arch_id_in
                        and scac.channel_arch_id = c.channel_arch_id;

    FUNCTION get_license_path(channel_id_in IN NUMBER)
    RETURN VARCHAR2
    IS
        license_val VARCHAR2(1000);
    BEGIN
        SELECT CFL.license_path INTO license_val
          FROM rhnChannelFamilyLicense CFL, rhnChannelFamilyMembers CFM
         WHERE CFM.channel_id = channel_id_in
           AND CFM.channel_family_id = CFL.channel_family_id;
    
        RETURN license_val;

    EXCEPTION
        WHEN NO_DATA_FOUND
            THEN
            RETURN NULL;
    END get_license_path;


    PROCEDURE license_consent(channel_id_in IN NUMBER, user_id_in IN NUMBER, server_id_in IN NUMBER)
    IS
        channel_family_id_val NUMBER;
    BEGIN
        channel_family_id_val := rhn_channel.family_for_channel(channel_id_in);
        IF channel_family_id_val IS NULL
        THEN
            rhn_exception.raise_exception('channel_subscribe_no_family');
        END IF;
        
        IF rhn_channel.get_license_path(channel_id_in) IS NULL
        THEN
            rhn_exception.raise_exception('channel_consent_no_license');
        END IF;
        
        INSERT INTO rhnChannelFamilyLicenseConsent (channel_family_id, user_id, server_id)
        VALUES (channel_family_id_val, user_id_in, server_id_in);
    END license_consent;

    PROCEDURE subscribe_server(server_id_in IN NUMBER, channel_id_in NUMBER, immediate_in NUMBER := 1, user_id_in in number := null, recalcfamily_in NUMBER := 1)
    IS
        channel_parent_val      rhnChannel.parent_channel%TYPE;
        parent_subscribed       BOOLEAN;
        server_has_base_chan    BOOLEAN;
        server_already_in_chan  BOOLEAN;
        channel_family_id_val   NUMBER;
        server_org_id_val       NUMBER;
        available_subscriptions NUMBER;
        consenting_user         NUMBER;
        allowed                 number := 0;
        current_members_val     number;
    BEGIN
        if user_id_in is not null then
            allowed := rhn_channel.user_role_check(channel_id_in, user_id_in, 'subscribe');
        else
            allowed := 1;
        end if;

        if allowed = 0 then
            rhn_exception.raise_exception('no_subscribe_permissions');
        end if;


        SELECT parent_channel INTO channel_parent_val FROM rhnChannel WHERE id = channel_id_in;

        IF channel_parent_val IS NOT NULL
        THEN    
            -- child channel; if attempting to cross-subscribe a child to the wrong base, silently ignore
            parent_subscribed := FALSE;    

            FOR check_subscription IN check_server_subscription(server_id_in, channel_parent_val)
            LOOP
                parent_subscribed := TRUE;
            END LOOP check_subscription;
        
            IF NOT parent_subscribed
            THEN
                RETURN;
            END IF;
        ELSE
            -- base channel
            server_has_base_chan := FALSE;
            FOR base IN server_base_subscriptions(server_id_in)
            LOOP
                server_has_base_chan := TRUE;
            END LOOP base;
            
            IF server_has_base_chan
            THEN
                rhn_exception.raise_exception('channel_server_one_base');
            END IF;
        END IF;
    
        FOR check_subscription IN check_server_subscription(server_id_in, channel_id_in)
        LOOP
            server_already_in_chan := TRUE;
        END LOOP check_subscription;
    
        IF server_already_in_chan
        THEN
            RETURN;
        END IF;
        
        channel_family_id_val := rhn_channel.family_for_channel(channel_id_in);
        IF channel_family_id_val IS NULL
        THEN
            rhn_exception.raise_exception('channel_subscribe_no_family');
        END IF;

        --
        -- Use the org_id of the server only if the org_id of the channel = NULL.
        -- This is required for subscribing to shared channels.
        --
        SELECT NVL(org_id, (SELECT org_id FROM rhnServer WHERE id = server_id_in))
          INTO server_org_id_val
          FROM rhnChannel
         WHERE id = channel_id_in;
         
        select current_members 
        into current_members_val
        from rhnPrivateChannelFamily
        where org_id = server_org_id_val and channel_family_id = channel_family_id_val
        for update of current_members;

        available_subscriptions := rhn_channel.available_family_subscriptions(channel_family_id_val, server_org_id_val);
        
        IF available_subscriptions IS NULL OR 
           available_subscriptions > 0 or
           can_server_consume_virt_channl(server_id_in, channel_family_id_val) = 1
        THEN
        
            IF rhn_channel.get_license_path(channel_id_in) IS NOT NULL
            THEN
                BEGIN
                
                SELECT user_id INTO consenting_user
                  FROM rhnChannelFamilyLicenseConsent
                 WHERE channel_family_id = channel_family_id_val
                   AND server_id = server_id_in;
                
                EXCEPTION
                    WHEN NO_DATA_FOUND THEN
                        rhn_exception.raise_exception('channel_subscribe_no_consent');
                END;
            END IF;
        
            insert into rhnServerHistory (id,server_id,summary,details) (
                select  rhn_event_id_seq.nextval,
                        server_id_in,
                        'subscribed to channel ' || SUBSTR(c.label, 0, 106),
                        c.label
                from    rhnChannel c
                where   c.id = channel_id_in
            );
            UPDATE rhnServer SET channels_changed = sysdate WHERE id = server_id_in;
            INSERT INTO rhnServerChannel (server_id, channel_id) VALUES (server_id_in, channel_id_in);
			IF recalcfamily_in > 0
			THEN
                rhn_channel.update_family_counts(channel_family_id_val, server_org_id_val);
			END IF;
            queue_server(server_id_in, immediate_in);
        ELSE
            rhn_exception.raise_exception('channel_family_no_subscriptions');
        END IF;
            
    END subscribe_server;
    
    function can_server_consume_virt_channl(
        server_id_in in number,
        family_id_in in number )
    return number
    is

        cursor server_virt_families is
            select vi.virtual_system_id, cfvsl.channel_family_id
            from
                rhnChannelFamilyVirtSubLevel cfvsl,
                rhnSGTypeVirtSubLevel sgtvsl,
                rhnVirtualInstance vi
            where
                vi.virtual_system_id = server_id_in 
                and sgtvsl.virt_sub_level_id = cfvsl.virt_sub_level_id
                and cfvsl.channel_family_id = family_id_in
                and exists (
                    select 1
                    from rhnServerEntitlementView sev
                    where vi.host_system_id = sev.server_id
                    and sev.server_group_type_id = sgtvsl.server_group_type_id );
    begin

        for server_virt_family in server_virt_families loop
            return 1;
        end loop;

        return 0;

    end;


    PROCEDURE bulk_subscribe_server(channel_id_in IN NUMBER, set_label_in IN VARCHAR2, set_uid_in IN NUMBER)
    IS
    BEGIN
        FOR server IN rhn_set.set_iterator(set_label_in, set_uid_in)
        LOOP
            rhn_channel.subscribe_server(server.element, channel_id_in, 0, set_uid_in);
        END LOOP server;
    END bulk_subscribe_server;

    PROCEDURE bulk_server_base_change(channel_id_in IN NUMBER, set_label_in IN VARCHAR2, set_uid_in IN NUMBER)
    IS
    BEGIN
        FOR server IN rhn_set.set_iterator(set_label_in, set_uid_in)
        LOOP
            IF rhn_server.can_change_base_channel(server.element) = 1
            THEN
                rhn_channel.clear_subscriptions(TO_NUMBER(server.element));
                rhn_channel.subscribe_server(server.element, channel_id_in, 0, set_uid_in);
            END IF;
        END LOOP server;
    END bulk_server_base_change;

    procedure bulk_server_basechange_from(
        set_label_in in varchar2,
        set_uid_in in number,
        old_channel_id_in in number,
        new_channel_id_in in number
    ) is
    cursor servers is
        select  sc.server_id id
        from    rhnChannel nc,
                rhnServerChannelArchCompat scac,
                rhnServer s,
                rhnChannel oc,
                rhnServerChannel sc,
                rhnSet st
        where   1=1
            -- first, find the servers we're looking for.
            and st.label = set_label_in
            and st.user_id = set_uid_in
            and st.element = sc.server_id
            -- now, filter out anything that's not in the
            -- old base channel.
            and sc.channel_id = old_channel_id_in
            and sc.channel_id = oc.id
            and oc.parent_channel is null
            -- now, see if it's compatible with the new base channel
            and nc.id = new_channel_id_in
            and nc.parent_channel is null
            and sc.server_id = s.id
            and s.server_arch_id = scac.server_arch_id
            and scac.channel_arch_id = nc.channel_arch_id;
    begin
        for s in servers loop
            insert into rhnSet (
                    user_id, label, element
                ) values (
                    set_uid_in,
                    set_label_in || 'basechange', 
                    s.id
                );
        end loop channel;
        bulk_server_base_change(new_channel_id_in,
                                set_label_in || 'basechange',
                                set_uid_in);
        delete from rhnSet
            where   label = set_label_in||'basechange'
                and user_id = set_uid_in;
    end bulk_server_basechange_from;

    procedure bulk_guess_server_base(
        set_label_in in varchar2,
        set_uid_in in number
    ) is
        channel_id number;
    begin
        for server in rhn_set.set_iterator(set_label_in, set_uid_in)
        loop
            -- anything that doesn't work, we just ignore
            begin
                if rhn_server.can_change_base_channel(server.element) = 1
                then
                    channel_id := guess_server_base(TO_NUMBER(server.element));
                    rhn_channel.clear_subscriptions(TO_NUMBER(server.element));
                    rhn_channel.subscribe_server(TO_NUMBER(server.element), channel_id, 0, set_uid_in);
                end if;
            exception when others then
                null;
            end;
        end loop server;
    end;

    function guess_server_base(
        server_id_in in number
    ) RETURN number is
        cursor server_cursor is
            select s.server_arch_id, s.release, s.org_id
              from rhnServer s
             where s.id = server_id_in;
    begin
        for s in server_cursor loop
            for channel in base_channel_cursor(s.release,
                s.server_arch_id, s.org_id) 
            loop
                return channel.id;
            end loop base_channel_cursor;
        end loop server_cursor;
        -- Server not found, or no base channel applies to it
        return null;
    end;

    -- Private function
    function normalize_server_arch(server_arch_in in varchar2)
    return varchar2
    deterministic
    is
        suffix VARCHAR2(128) := '-redhat-linux';
        suffix_len NUMBER := length(suffix);
    begin
        if server_arch_in is NULL then
            return NULL;
        end if;
        if instr(server_arch_in, '-') > 0
        then
            -- Suffix already present
            return server_arch_in;
        end if;
        return server_arch_in || suffix;
    end normalize_server_arch;

    --
    --
    -- Raises: 
    --   server_arch_not_found
    --   no_subscribe_permissions
    function base_channel_for_release_arch(
        release_in in varchar2,
        server_arch_in in varchar2,
        org_id_in in number := -1,
        user_id_in in number := null
    ) return number is
        server_arch varchar2(256) := normalize_server_arch(server_arch_in);
        server_arch_id number;
    begin
        -- Look up the server arch
        begin
            select id
              into server_arch_id
              from rhnServerArch
             where label = server_arch;
        exception
            when no_data_found then
                rhn_exception.raise_exception('server_arch_not_found');
        end;
        return base_channel_rel_archid(release_in, server_arch_id,
            org_id_in, user_id_in);
    end base_channel_for_release_arch;

    function base_channel_rel_archid(
        release_in in varchar2,
        server_arch_id_in in number,
        org_id_in in number := -1,
        user_id_in in number := null
    ) return number is
        denied_channel_id number := null;
        valid_org_id number := org_id_in;
        valid_user_id number := user_id_in;
        channel_subscribable number;
    begin
        if org_id_in = -1 and user_id_in is not null then
            -- Get the org id from the user id
            begin
                select org_id
                  into valid_org_id
                  from web_contact
                 where id = user_id_in;
            exception
                when no_data_found then
                    -- User doesn't exist
                    -- XXX Only list public stuff for now
                    valid_user_id := null;
                    valid_org_id := -1;
            end;
        end if;

        for c in base_channel_cursor(release_in, server_arch_id_in, valid_org_id)
        loop
            -- This row is a possible match
            if valid_user_id is null then
                -- User ID not specified, so no user to channel permissions to
                -- check
                return c.id;
            end if;

            -- Check user to channel permissions
            select loose_user_role_check(c.id, user_id_in, 'subscribe')
              into channel_subscribable
              from dual;

            if channel_subscribable = 1 then
                return c.id;
            end if;
                
            -- Base channel exists, but is not subscribable; keep trying
            denied_channel_id := c.id;
        end loop base_channel_fetch;
        
        if denied_channel_id is not null then
            rhn_exception.raise_exception('no_subscribe_permissions');
        end if;
        -- No base channel applies
        return NULL;
    end base_channel_rel_archid;

    procedure bulk_guess_server_base_from(
        set_label_in in varchar2,
        set_uid_in in number,
        channel_id_in in number
    ) is
        cursor channels(server_id_in in number) is
            select      rsc.channel_id
            from        rhnServerChannel rsc,
                        rhnChannel rc
            where       server_id_in = rsc.server_id
                        and rsc.channel_id = rc.id
                        and rc.parent_channel is null;
    begin
        for server in rhn_set.set_iterator(set_label_in, set_uid_in)
        loop
            for channel in channels(server.element)
            loop
                if channel.channel_id = channel_id_in
                then
                    insert into rhnSet (user_id, label, element) values (set_uid_in, set_label_in || 'baseguess', server.element);
                end if;
            end loop channel;
        end loop server;
        bulk_guess_server_base(set_label_in||'baseguess',set_uid_in);
        delete from rhnSet where label = set_label_in||'baseguess' and user_id = set_uid_in;
    end;


    PROCEDURE clear_subscriptions(server_id_in IN NUMBER, deleting_server IN NUMBER := 0 )
    IS
        cursor server_channels(server_id_in in number) is
                select  s.org_id, sc.channel_id, cfm.channel_family_id
                from    rhnServer s,
                        rhnServerChannel sc,
                        rhnChannelFamilyMembers cfm
                where   s.id = server_id_in
                        and s.id = sc.server_id
                        and sc.channel_id = cfm.channel_id;
    BEGIN
        for channel in server_channels(server_id_in)
        loop
                unsubscribe_server(server_id_in, channel.channel_id, 1, 1, deleting_server);
                rhn_channel.update_family_counts(channel.channel_family_id, channel.org_id);
        end loop channel;
    END clear_subscriptions;

    PROCEDURE unsubscribe_server(server_id_in IN NUMBER, channel_id_in NUMBER, immediate_in NUMBER := 1, unsubscribe_children_in number := 0,
                                 deleting_server IN NUMBER := 0 )
    IS
        channel_family_id_val   NUMBER;
        server_org_id_val       NUMBER;
        available_subscriptions NUMBER; 
        server_already_in_chan  BOOLEAN;
        cursor  channel_family_is_proxy(channel_family_id_in in number) is
                select  1
                from    rhnChannelFamily
                where   id = channel_family_id_in
                    and label = 'rhn-proxy';
        cursor  channel_family_is_satellite(channel_family_id_in in number) is
                select  1
                from    rhnChannelFamily
                where   id = channel_family_id_in
                    and label = 'rhn-satellite';
        -- this is *EXACTLY* like check_server_parent_membership, but if we recurse
        -- with the package-level one, we get a "cursor already open", so we need a
        -- copy on our call stack instead.  GROAN.
        cursor local_chk_server_parent_memb (
                        server_id_in number,
                        channel_id_in number ) is
                select  c.id
                from    rhnChannel                      c,
                                rhnServerChannel        sc
                where   1=1
                        and c.parent_channel = channel_id_in
                        and c.id = sc.channel_id
                        and sc.server_id = server_id_in;
    BEGIN
        FOR child IN local_chk_server_parent_memb(server_id_in, channel_id_in)
        LOOP
            if unsubscribe_children_in = 1 then
                unsubscribe_server(server_id_in => server_id_in,
                                                                channel_id_in => child.id,
                                                                immediate_in => immediate_in,
                                                                unsubscribe_children_in => unsubscribe_children_in,
                        deleting_server => deleting_server);
            else
                rhn_exception.raise_exception('channel_unsubscribe_child_exists');
            end if;
        END LOOP child;
        
        server_already_in_chan := FALSE;
    
        FOR check_subscription IN check_server_subscription(server_id_in, channel_id_in)
        LOOP
            server_already_in_chan := TRUE;
        END LOOP check_subscription;
    
        IF NOT server_already_in_chan
        THEN
            RETURN;
        END IF;
        
   if deleting_server = 0 then 

      insert into rhnServerHistory (id,server_id,summary,details) (
          select  rhn_event_id_seq.nextval,
                server_id_in,
             'unsubscribed from channel ' || SUBSTR(c.label, 0, 106),
             c.label
          from    rhnChannel c
          where   c.id = channel_id_in
      );

        UPDATE rhnServer SET channels_changed = sysdate WHERE id = server_id_in;
   end if;
        
   DELETE FROM rhnServerChannel WHERE server_id = server_id_in AND channel_id = channel_id_in;

   if deleting_server = 0 then 
        queue_server(server_id_in, immediate_in);
   end if;

        channel_family_id_val := rhn_channel.family_for_channel(channel_id_in);
        IF channel_family_id_val IS NULL
        THEN
            rhn_exception.raise_exception('channel_unsubscribe_no_family');
        END IF;

        for ignore in channel_family_is_satellite(channel_family_id_val) loop
                delete from rhnSatelliteInfo where server_id = server_id_in;
                delete from rhnSatelliteChannelFamily where server_id = server_id_in;
        end loop;

        for ignore in channel_family_is_proxy(channel_family_id_val) loop
                delete from rhnProxyInfo where server_id = server_id_in;
        end loop;

        DELETE FROM rhnChannelFamilyLicenseConsent
         WHERE channel_family_id = channel_family_id_val
           AND server_id = server_id_in;
                        
        SELECT org_id INTO server_org_id_val
          FROM rhnServer
         WHERE id = server_id_in;
         
        rhn_channel.update_family_counts(channel_family_id_val, server_org_id_val);
    END unsubscribe_server;

    PROCEDURE bulk_unsubscribe_server(channel_id_in IN NUMBER, set_label_in IN VARCHAR2, set_uid_in IN NUMBER)
    IS
    BEGIN
        FOR server IN rhn_set.set_iterator(set_label_in, set_uid_in)
        LOOP
            rhn_channel.unsubscribe_server(server.element, channel_id_in, 0);
        END LOOP server;
    END bulk_unsubscribe_server;

    FUNCTION family_for_channel(channel_id_in IN NUMBER)
    RETURN NUMBER
    IS
        channel_family_id_val NUMBER;
    BEGIN
        SELECT channel_family_id INTO channel_family_id_val
          FROM rhnChannelFamilyMembers
         WHERE channel_id = channel_id_in;
         
        RETURN channel_family_id_val;
    EXCEPTION
        WHEN NO_DATA_FOUND
        THEN
            RETURN NULL;
    END family_for_channel;

    FUNCTION available_family_subscriptions(channel_family_id_in IN NUMBER, org_id_in IN NUMBER)
    RETURN NUMBER
    IS
        cfp channel_family_perm_cursor%ROWTYPE;
        current_members_val NUMBER;
        max_members_val     NUMBER;
        found               NUMBER;
    BEGIN
        IF NOT channel_family_perm_cursor%ISOPEN
        THEN
            OPEN channel_family_perm_cursor(channel_family_id_in, org_id_in);
        END IF;

        FETCH channel_family_perm_cursor INTO cfp;
        
        WHILE channel_family_perm_cursor%FOUND
        LOOP
            found := 1;
            
            current_members_val := cfp.current_members;
            max_members_val := cfp.max_members;
            
            FETCH channel_family_perm_cursor INTO cfp;
        END LOOP;

        IF channel_family_perm_cursor%ISOPEN
        THEN
            CLOSE channel_family_perm_cursor;
        END IF;

        -- not found: either the channel fam doesn't have an entry in cfp, or the org doesn't have access to it.
        -- either way, there are no available subscriptions
        
        IF found IS NULL
        THEN
            RETURN 0;
        END IF;

        -- null max members?  in that case, pass it on; NULL means infinite                     
        IF max_members_val IS NULL
        THEN
            RETURN NULL;
        END IF;

        -- otherwise, return the delta  
        RETURN max_members_val - current_members_val;                   
    END available_family_subscriptions;
    
    -- *******************************************************************
    -- FUNCTION: channel_family_current_members
    -- Calculates and returns the actual count of systems consuming
    --   physical channel subscriptions.
    -- Called by: update_family_counts 
    --            rhn_entitlements.repoll_virt_guest_entitlements
    -- *******************************************************************
    function channel_family_current_members(channel_family_id_in IN NUMBER,
                                            org_id_in IN NUMBER)
    return number
    is
        current_members_count number := 0;
    begin
        select  count(distinct sc.server_id)
        into    current_members_count
        from    rhnChannelFamilyMembers cfm,
                rhnServerChannel sc,
                rhnServer s
        where   s.org_id = org_id_in
            and s.id = sc.server_id
            and cfm.channel_family_id = channel_family_id_in
            and cfm.channel_id = sc.channel_id
            and exists ( 
                select 1
                from rhnChannelFamilyServerPhysical cfsp
                where cfsp.CHANNEL_FAMILY_ID = channel_family_id_in
                    and cfsp.server_id = s.id
                );

        return current_members_count;
    end;        

    PROCEDURE update_family_counts(channel_family_id_in IN NUMBER, 
                                   org_id_in IN NUMBER)
    IS
    BEGIN
                update rhnPrivateChannelFamily
                set current_members = (
                channel_family_current_members(channel_family_id_in, org_id_in)
                )
                        where org_id = org_id_in
                                and channel_family_id = channel_family_id_in;

    END update_family_counts;
    
    FUNCTION available_chan_subscriptions(channel_id_in IN NUMBER, 
                                          org_id_in IN NUMBER)
    RETURN NUMBER
    IS
            channel_family_id_val NUMBER;
    BEGIN
        SELECT channel_family_id INTO channel_family_id_val
            FROM rhnChannelFamilyMembers
            WHERE channel_id = channel_id_in;
         
            RETURN rhn_channel.available_family_subscriptions(
                           channel_family_id_val, org_id_in);
    END available_chan_subscriptions;

    -- *******************************************************************
    -- PROCEDURE: entitle_customer
    -- Creates a chan fam bucket, or sets max_members for an existing bucket
    -- Called by: rhn_ep.poll_customer_internal
    -- Calls: set_family_maxmembers + update_family_counts if the row
    --        already exists, else it creates it in rhnPrivateChannelFamily.
    -- *******************************************************************
    procedure entitle_customer(customer_id_in in number, 
                               channel_family_id_in in number, 
                               quantity_in in number)
    is
                cursor permissions is
                        select  1
                        from    rhnPrivateChannelFamily pcf
                        where   pcf.org_id = customer_id_in
                                and     pcf.channel_family_id = channel_family_id_in; 
    begin
                for perm in permissions loop
                        set_family_maxmembers(
                                customer_id_in,
                                channel_family_id_in,
                                quantity_in
                        );
                        rhn_channel.update_family_counts(
                                channel_family_id_in,
                                customer_id_in
                        );
                        return;
                end loop;
        
                insert into rhnPrivateChannelFamily pcf (
                                channel_family_id, org_id, max_members, current_members
                        ) values (
                                channel_family_id_in, customer_id_in, quantity_in, 0
                        );
    end;

    -- *******************************************************************
    -- PROCEDURE: set_family_maxmembers
    -- Prunes an existing channel family bucket by unsubscribing the
    --   necessary servers and sets max_members.
    -- Called by: rhn_channel.entitle_customer
    -- Calls: unsubscribe_server_from_family
    -- *******************************************************************
    procedure set_family_maxmembers(customer_id_in in number, 
                                    channel_family_id_in in number, 
                                    quantity_in in number)
    is
        cursor servers is
            select  server_id from (
            select      rownum row_number, server_id, modified from (
                select  rcfsp.server_id,
                        rcfsp.modified
                from    rhnChannelFamilyServerPhysical rcfsp
                where   rcfsp.customer_id = customer_id_in
                    and rcfsp.channel_family_id = channel_family_id_in
                order by modified
            )
            where rownum > quantity_in
            );
    begin
            -- prune subscribed servers
        for server in servers loop
            rhn_channel.unsubscribe_server_from_family(server.server_id, 
                                                       channel_family_id_in);
        end loop;

        update  rhnPrivateChannelFamily pcf
        set     pcf.max_members = quantity_in
        where   pcf.org_id = customer_id_in
            and pcf.channel_family_id = channel_family_id_in;
    end;

    procedure unsubscribe_server_from_family(server_id_in in number, 
                                             channel_family_id_in in number)
    is
    begin
        delete
        from    rhnServerChannel rsc
        where   rsc.server_id = server_id_in
            and channel_id in (
                select  rcfm.channel_id
                from    rhnChannelFamilyMembers rcfm
                where   rcfm.channel_family_id = channel_family_id_in);
    end;

    function get_org_id(channel_id_in in number)
    return number
    is
        org_id_out number;
    begin
        select org_id into org_id_out
            from rhnChannel
            where id = channel_id_in;
         
            return org_id_out;
    end get_org_id;
    
    function get_cfam_org_access(cfam_id_in in number, org_id_in in number)
    return number
    is
        cursor  families is
                        select  1
                        from    rhnOrgChannelFamilyPermissions cfp
                        where   cfp.org_id = org_id_in;
    begin
                -- the idea: if we get past this query, 
        -- the user has the role, else catch the exception and return 0
                for family in families loop
                return 1;
                end loop;
                return 0;
    end;

    function get_org_access(channel_id_in in number, org_id_in in number)
    return number
    is
        throwaway number;
    begin
        -- the idea: if we get past this query, 
        -- the org has access to the channel, else catch the exception and return 0
        select distinct 1 into throwaway
          from rhnChannelFamilyMembers CFM,
               rhnOrgChannelFamilyPermissions CFP
         where cfp.org_id = org_id_in
           and CFM.channel_family_id = CFP.channel_family_id
           and CFM.channel_id = channel_id_in
           and (CFP.max_members > 0 or CFP.max_members is null or CFP.org_id = 1);
           
        return 1;
        exception
            when no_data_found
            then
            return 0;
    end;
    
    -- check if a user has a given role, or if such a role is inferrable
    function user_role_check_debug(channel_id_in in number, 
                                   user_id_in in number, 
                                   role_in in varchar2, 
                                   reason_out out varchar2)
    return number
    is
        org_id number;
    begin
        org_id := rhn_user.get_org_id(user_id_in);

        -- channel might be shared
        if role_in = 'subscribe' and
           rhn_channel.shared_user_role_check(channel_id_in, user_id_in, role_in) = 1 then
            return 1;
        end if;
        
        if role_in = 'manage' and 
           NVL(rhn_channel.get_org_id(channel_id_in), -1) <> org_id then
                reason_out := 'channel_not_owned';
               return 0;
            end if;
        
        if role_in = 'subscribe' and 
           rhn_channel.get_org_access(channel_id_in, org_id) = 0 then
                reason_out := 'channel_not_available';
                return 0;
            end if;
        
        -- channel admins have all roles
        if rhn_user.check_role_implied(user_id_in, 'channel_admin') = 1 then
            reason_out := 'channel_admin';
            return 1;
            end if;

        -- the subscribe permission is inferred 
    -- UNLESS the not_globally_subscribable flag is set 
        if role_in = 'subscribe'
        then
            if rhn_channel.org_channel_setting(channel_id_in, 
                       org_id,
                       'not_globally_subscribable') = 0 then
                reason_out := 'globally_subscribable';
                    return 1;
            end if;
        end if;
        
        -- all other roles (manage right now) are explicitly granted    
        reason_out := 'direct_permission';
        return rhn_channel.direct_user_role_check(channel_id_in, 
                                              user_id_in, role_in);
    end;
    
    -- same as above, but with no OUT param; useful in views, etc
    function user_role_check(channel_id_in in number, user_id_in in number, role_in in varchar2)
    return number
    is
        throwaway varchar2(256);
    begin
        return rhn_channel.user_role_check_debug(channel_id_in, user_id_in, role_in, throwaway);
    end;

    --
    -- For multiorg phase II, this function simply checks to see if the user's
    -- has a trust relationship that includes this channel by id.
    --
    function shared_user_role_check(channel_id in number, user_id in number, role in varchar2)
    return number
    is
      n number;
      oid number;
    begin
      oid := rhn_user.get_org_id(user_id);
      select 1 into n
      from rhnSharedChannelView s
      where s.id = channel_id and s.org_trust_id = oid;
      return 1;
      exception
        when no_data_found then
          return 0;
    end;

    -- same as above, but returns 1 if user_id_in is null
    -- This is useful in queries where user_id is not specified
    function loose_user_role_check(channel_id_in in number, user_id_in in number, role_in in varchar2)
    return number
    is
    begin
        if user_id_in is null then
            return 1;
        end if;
        return user_role_check(channel_id_in, user_id_in, role_in);
    end loose_user_role_check;
    
    -- directly checks the table, no inferred permissions
    function direct_user_role_check(channel_id_in in number, user_id_in in number, role_in in varchar2)
    return number
    is
        throwaway number;
    begin
        -- the idea: if we get past this query, the user has the role, else catch the exception and return 0
        select 1 into throwaway
          from rhnChannelPermissionRole CPR,
               rhnChannelPermission CP
         where CP.user_id = user_id_in
           and CP.channel_id = channel_id_in
           and CPR.label = role_in
           and CP.role_id = CPR.id;
           
        return 1;
    exception
        when no_data_found
            then
            return 0;
    end;
    
    -- check if an org has a certain setting
    function org_channel_setting(channel_id_in in number, org_id_in in number, setting_in in varchar2)
    return number
    is
        throwaway number;
    begin
        -- the idea: if we get past this query, the org has the setting, else catch the exception and return 0
        select 1 into throwaway
          from rhnOrgChannelSettingsType OCST,
               rhnOrgChannelSettings OCS
         where OCS.org_id = org_id_in
           and OCS.channel_id = channel_id_in
           and OCST.label = setting_in
           and OCS.setting_id = OCST.id;
           
        return 1;
    exception
        when no_data_found
            then
            return 0;
    end;
    
    FUNCTION channel_priority(channel_id_in IN number) 
    RETURN number
    IS
         channel_name varchar2(256);
         priority number;
         end_of_life_val date;
         org_id_val number;
    BEGIN

        select name, end_of_life, org_id
        into channel_name, end_of_life_val, org_id_val
        from rhnChannel
        where id = channel_id_in;

        if end_of_life_val is not null then
          return -400;
        end if;

        if channel_name like 'Red Hat Enterprise Linux%' or channel_name like 'RHEL%' then
          priority := 1000;
          if channel_name not like '%Beta%' then
            priority := priority + 1000;
          end if;

          priority := priority +
            case
              when channel_name like '%v. 5%' then 600
              when channel_name like '%v. 4%' then 500
              when channel_name like '%v. 3%' then 400
              when channel_name like '%v. 2%' then 300
              when channel_name like '%v. 1%' then 200
              else 0
            end;

          priority := priority +
            case
              when channel_name like 'Red Hat Enterprise Linux (v. 5%' then 60
              when (channel_name like '%AS%' and channel_name not like '%Extras%') then 50
              when (channel_name like '%ES%' and channel_name not like '%Extras%') then 40
              when (channel_name like '%WS%' and channel_name not like '%Extras%') then 30
              when (channel_name like '%Desktop%' and channel_name not like '%Extras%') then 20
              when channel_name like '%Extras%' then 10
              else 0
            end; 

          priority := priority +
            case
              when channel_name like '%)' then 5
              else 0
            end;

          priority := priority +
            case
              when channel_name like '%32-bit x86%' then 4
              when channel_name like '%64-bit Intel Itanium%' then 3
              when channel_name like '%64-bit AMD64/Intel EM64T%' then 2
              else 0
            end;
        elsif channel_name like 'Red Hat Desktop%' then
            priority := 900;

            if channel_name not like '%Beta%' then
               priority := priority + 50;
            end if;
 
          priority := priority +
            case
              when channel_name like '%v. 4%' then 40
              when channel_name like '%v. 3%' then 30
              when channel_name like '%v. 2%' then 20
              when channel_name like '%v. 1%' then 10
              else 0
            end;
            
          priority := priority +
            case
              when channel_name like '%32-bit x86%' then 4
              when channel_name like '%64-bit Intel Itanium%' then 3
              when channel_name like '%64-bit AMD64/Intel EM64T%' then 2
              else 0
            end;
         
        elsif org_id_val is not null then
          priority := 600;
        else
          priority := 500;
        end if;
      
      return -priority;

    end channel_priority;

    -- right now this only does the accounting changes; the cascade
    -- actually does the rhnServerChannel delete.
    procedure delete_server_channels(server_id_in in number)
    is
    begin
        update  rhnPrivateChannelFamily
        set     current_members = current_members -1
        where   org_id in (
                        select  org_id
                        from    rhnServer
                        where   id = server_id_in
                )
                and channel_family_id in (
                        select  rcfm.channel_family_id
                        from    rhnChannelFamilyMembers rcfm,
                                rhnServerChannel rsc
                        where   rsc.server_id = server_id_in
                                and rsc.channel_id = rcfm.channel_id
                and not exists (
                    select 1
                    from
                        rhnChannelFamilyVirtSubLevel cfvsl,
                        rhnSGTypeVirtSubLevel sgtvsl,
                        rhnServerEntitlementView sev,
                        rhnVirtualInstance vi
                    where
                        -- system is a virtual instance
                        vi.virtual_system_id = server_id_in
                        and vi.host_system_id = sev.server_id
                        -- system's host has a virt ent
                        and sev.label in ('virtualization_host',
                                          'virtualization_host_platform')
                        and sev.server_group_type_id = 
                            sgtvsl.server_group_type_id
                        -- the host's virt ent grants a cf virt sub level
                        and sgtvsl.virt_sub_level_id = cfvsl.virt_sub_level_id
                        -- the cf is in that virt sub level
                        and cfvsl.channel_family_id = rcfm.channel_family_id
                    )
                );
    end;

        -- this could certainly be optimized to do updates if needs be
        procedure refresh_newest_package(channel_id_in in number, caller_in in varchar2 := '(unknown)')
        is
        begin
                delete from rhnChannelNewestPackage where channel_id = channel_id_in;
                insert into rhnChannelNewestPackage
                        ( channel_id, name_id, evr_id, package_id, package_arch_id ) 
                        (       select  channel_id,
                                                name_id, evr_id,
                                                package_id, package_arch_id
                                from    rhnChannelNewestPackageView
                                where   channel_id = channel_id_in
                        );
                insert into rhnChannelNewestPackageAudit (channel_id, caller)
                    values (channel_id_in, caller_in);
                update rhnChannel 
                    set last_modified = greatest(sysdate, last_modified + 1/86400)
                    where id = channel_id_in; 
        end;

   procedure update_channel ( channel_id_in in number, invalidate_ss in number := 0, 
                              date_to_use in date := sysdate )
   is

   channel_last_modified date;
   last_modified_value date;

   cursor snapshots is
   select  snapshot_id id
   from    rhnSnapshotChannel
   where   channel_id = channel_id_in;

   begin

      select last_modified
      into channel_last_modified
      from rhnChannel
      where id = channel_id_in;
  
      last_modified_value := date_to_use;

      if last_modified_value <= channel_last_modified then
          last_modified_value := last_modified_value + 1/86400;
      end if;

      update rhnChannel set last_modified = last_modified_value
      where id = channel_id_in;

      if invalidate_ss = 1 then 
        for snapshot in snapshots loop
            update rhnSnapshot
            set invalid = lookup_snapshot_invalid_reason('channel_modified')
            where id = snapshot.id;
        end loop;
      end if;

   end update_channel;

   procedure update_channels_by_package ( package_id_in in number, date_to_use in date := sysdate )
   is

   cursor channels is
   select channel_id
   from rhnChannelPackage
   where package_id = package_id_in
   order by channel_id;

   begin
      for channel in channels loop
         -- we want to invalidate the snapshot assocated with the channel when we
         -- do this b/c we know we've added or removed or packages
         rhn_channel.update_channel ( channel.channel_id, 1, date_to_use );
      end loop;
   end update_channels_by_package;

   
   procedure update_channels_by_errata ( errata_id_in number, date_to_use in date := sysdate )
   is

   cursor channels is
   select channel_id
   from rhnChannelErrata
   where errata_id = errata_id_in
   order by channel_id;

   begin
      for channel in channels loop
         -- we won't invalidate snapshots, b/c just changing the errata associated with
         -- a channel shouldn't invalidate snapshots
         rhn_channel.update_channel ( channel.channel_id, 0, date_to_use );
      end loop;
   end update_channels_by_errata;

END rhn_channel;
/
SHOW ERRORS

--
-- Revision 1.75  2005/03/04 00:04:19  jslagle
-- bz #147617
-- Made Red Hat Desktop sort a little better.
--
-- Revision 1.74  2005/02/22 03:24:47  jslagle
-- bz #147617
-- Improve channel_priority function to order channels better.
--
-- Revision 1.73  2004/08/16 20:39:30  pjones
-- bugzilla: 129889 -- make bulk_server_basechange_from() actually work.
--
-- Revision 1.72  2004/04/14 00:09:24  pjones
-- bugzilla: 120761 -- split rhnChannelPermissions into two tables, eliminating
-- a frequent full table scan
--
-- Revision 1.71  2004/04/13 16:28:36  bretm
-- bugzilla:  119871
--
-- keep track of rhnServer.channels_changed through the pl/sql fns
--
-- Revision 1.70  2004/03/26 18:11:32  rbb
-- Bugzilla:  114057
--
-- Add a script to determine channel priority.
--
-- Revision 1.69  2004/02/17 20:16:52  pjones
-- bugzilla: none -- add cvs tags into the package as long as we're touching
-- it anyway
--
-- Revision 1.68  2004/02/17 20:05:38  pjones
-- bugzilla: 115782 -- make bulk_server_basechange_from() filter out servers
-- with arches incompatible with the target channel
--
-- Revision 1.67  2004/02/06 02:36:10  misa
-- Changed normalize_server_arch to allow for solaris arches
--
-- Revision 1.66  2003/11/13 16:58:34  cturner
-- make use of new rhn_user.check_role_implied call; pragmas broke, removed them for now since I have no idea how to fix them
--
-- Revision 1.65  2003/10/23 20:26:24  bretm
-- bugzilla:  none
--
-- note the channel label when we unsubscribe, too
--
-- Revision 1.64  2003/10/15 14:47:17  bretm
-- bugzilla:  none
--
-- add the channel label to the server history summary line when we log a channel change
--
-- Revision 1.63  2003/09/24 19:25:56  pjones
-- this wasn't the right fix, put it back
--
-- Revision 1.62  2003/09/24 17:42:19  pjones
-- bugzilla: none
--
-- limit our server base channel guess to channels with available permissions
--
-- Revision 1.61  2003/09/22 21:00:40  cturner
-- add method for easy acl check
--
-- Revision 1.60  2003/09/17 22:14:11  misa
-- bugzilla: 103639  Changes to allow me to move the base channel guess into plsql
--
-- Revision 1.59  2003/08/21 13:41:17  cturner
-- bugzilla: 99187.  properly test for satellite and proxy in bulk_guess_server_base; reorg code for better reuse
--
-- Revision 1.58  2003/07/24 16:46:22  cturner
-- bugzilla: 100723, the perm check was returning duplicates, so now it just calls the function it should have called anyway
--
-- Revision 1.57  2003/07/24 16:44:16  misa
-- bugzilla: none  A function more usable on the rhnapp side
--
-- Revision 1.56  2003/07/23 22:36:51  cturner
-- argh, max returns null even when now rows; use distinct.  how revolting
--
-- Revision 1.55  2003/07/23 22:01:31  cturner
-- oops, this one can return multiple rows; eliminate that in a lazy way
--
-- Revision 1.54  2003/07/23 21:59:19  cturner
-- rework how rhnUserChannel works; move to plsql for speed and maintenance
--
-- Revision 1.53  2003/07/21 17:49:12  pjones
-- bugzilla: none
--
-- add optional user for subscribe_server
--
-- Revision 1.52  2003/07/14 22:19:29  misa
-- bugzilla: none  Updating guess_base_channel to work more like the rhnapp server code
--
-- Revision 1.51  2003/06/26 22:09:04  pjones
-- bugzilla: none
--
-- log subscribe and unsubscribe
--
-- Revision 1.50  2003/06/05 19:31:15  pjones
-- bugzilla: 88278 -- make the cursor name smaller
--
-- Revision 1.49  2003/06/05 19:18:21  pjones
-- bugzilla: 88278
--
-- unsubscribe_server() opens the package-level cursor when it invokes itself,
-- so we're using a local copy instead.
--
-- Revision 1.48  2003/06/04 16:41:39  pjones
-- bugzilla: none
--
-- make bulk_guess_server_base() silently ignore unguessables
--
-- Revision 1.47  2003/06/04 16:27:03  pjones
-- bugzilla: 88822
--
-- eliminate the last outliers that remove things from channels without using
-- unsubscribe_server, I think.
--
-- Revision 1.46  2003/06/03 20:49:37  pjones
-- bugzilla: 88822
-- unsubscribing from rhn-satellite now clears rhnSatelliteChannelFamily
-- for the server in question
--
-- Revision 1.45  2003/06/02 20:41:45  pjones
-- bugzilla: none - fix rhnProxyInfo/rhnSatelliteInfo channel unsubscribe
-- problem.  Basicly, if you're out of the channel for any reason, you're
-- also out of rhnProxyInfo/rhnProxyInfo
--
-- Revision 1.44  2003/03/24 15:26:28  pjones
-- bugzilla: 85812
--
-- bulk_server_base_change silently ignores servers that are satellites
-- or proxies, as requested.
--
-- Revision 1.43  2003/02/26 20:28:17  pjones
-- rhn_channel.update_family_counts() in rhn_channel.entitle_customer()
-- the old codepath is:
--
-- ep ->
-- rhn_ep.entitlement_run_me() ->
-- rhn_ep.poll_customer() ->
-- rhn_channel.entitle_customer()
--
-- which doesn't change current_members, even though it may remove servers
-- from the family.
--
-- There's another bug here:  currently, we don't try to order forced
-- unsubscribes in any way; we just use
-- rhn_channel.unsubscribe_server_from_family .  If there are any child
-- channel subscriptions, this will leave them subscribed.  We really need
-- to iterate across the channels again, and subscribe any channel for which
-- there are no parent channel subscriptions.
--
-- Ugh.
--
-- Revision 1.42  2003/01/28 00:19:45  pjones
-- fix clear_subscriptions; AFAICT, this is only hit on the
-- bulk_server_base_change / bulk_server_base_guess codepaths, which puts
-- it infrequent enough that it could be our "bad count" culprit.
--
-- Revision 1.41  2003/01/14 19:51:45  pjones
-- make setting current_members on rhnChannelFamilyPermissions work when
-- a server is in more than one channel in a single family.
 070701000004EC000081B400000000000000000000000167AE11140000030D000000000000000000000000000000000000006400000000susemanager-schema/upgrade/spacewalk-schema-0.5-to-spacewalk-schema-0.6/119-rhnSystemMigrations.sql   --
-- Copyright (c) 2008 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--
--
-- $Id$
--
ALTER TABLE rhnSystemMigrations
  DROP constraint rhn_sys_mig_oidto_nn;

ALTER TABLE rhnSystemMigrations
  DROP constraint rhn_sys_mig_oidfrm_nn;
   070701000004ED000081B400000000000000000000000167AE111400000081000000000000000000000000000000000000006500000000susemanager-schema/upgrade/spacewalk-schema-0.5-to-spacewalk-schema-0.6/120-rhn_config_parameter.sql  update rhn_config_parameter
	set value = '%{NPVAR}/execute_commands.log'
	where group_name = 'CommandQueue' and name = 'exelog';
   070701000004EE000081B400000000000000000000000167AE1114000000F8000000000000000000000000000000000000006500000000susemanager-schema/upgrade/spacewalk-schema-0.5-to-spacewalk-schema-0.6/121-rhnReleaseChannelMap.sql  ALTER TABLE rhnReleaseChannelMap DROP CONSTRAINT rhn_rcm_pva_def_uniq;
ALTER TABLE rhnReleaseChannelMap DROP COLUMN is_default;
ALTER TABLE rhnReleaseChannelMap 
ADD CONSTRAINT rhn_rcm_pvar_uniq
unique (product, version, channel_arch_id, release);
070701000004EF000081B400000000000000000000000167AE111400000858000000000000000000000000000000000000006400000000susemanager-schema/upgrade/spacewalk-schema-0.5-to-spacewalk-schema-0.6/122-rhnServerNeededView.sql   --
-- Copyright (c) 2008 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--


-- A view that displays an uncached version of rhnServerNeededCache


CREATE OR REPLACE VIEW
rhnServerNeededView
(
    org_id,
    server_id,
    errata_id,
    package_id,
    package_name_id,
    channel_id
)
AS
SELECT DISTINCT S.org_id,
     S.id as server_id,
     ep.errata_id as errata_id,
     P.id as package_id,
     P.name_id as package_name_id,
     CP.channel_id as channel_id
FROM
    rhnPackage P
    inner join rhnPackageEVR P_EVR on P_EVR.id = P.evr_id
    inner join rhnPackageEVR SP_EVR on SP_EVR.evr < P_EVR.evr  
    inner join rhnServerPackage SP on SP.name_id = P.name_id 
               and SP.evr_id = SP_EVR.id
               AND SP.evr_id != P.evr_id
    inner join rhnServer S on SP.server_id = S.id
    inner join rhnServerPackageArchCompat SPAC on spac.server_arch_id = s.server_arch_id 
               AND p.package_arch_id = spac.package_arch_id
    inner join rhnServerChannel SC on SC.server_id = S.id 
    inner join rhnChannelPackage CP on CP.package_id = P.id 
               and SC.channel_id = CP.channel_id
    left outer join rhnErrataPackage EP on EP.package_id = P.id
                   AND EXISTS 
                   (SELECT 1 from rhnChannelErrata CE where ce.channel_id = SC.channel_id
                    AND CE.errata_id = EP.errata_id) 
    where SP_EVR.evr = (SELECT MAX(PE.evr) FROM rhnServerPackage SP2, rhnPackageEvr PE 
                       WHERE PE.id = SP2.evr_id AND SP2.server_id = SP.server_id AND 
                        SP2.name_id = SP.name_id)
/
070701000004F0000081B400000000000000000000000167AE1114000005F6000000000000000000000000000000000000006300000000susemanager-schema/upgrade/spacewalk-schema-0.5-to-spacewalk-schema-0.6/123-rhnActionType_data.sql    --
-- Copyright (c) 2008 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--
--
--
--

update rhnActionType
set name = 'Initiate a kickstart for a virtual guest.'
where label = 'kickstart_guest.initiate';

update rhnActionType
set name = 'Shuts down a virtual domain.'
where label = 'virt.shutdown';

update rhnActionType
set name = 'Starts up a virtual domain.'
where label = 'virt.start';

update rhnActionType
set name = 'Suspends a virtual domain.'
where label = 'virt.suspend';

update rhnActionType
set name = 'Resumes a virtual domain.'
where label = 'virt.resume';

update rhnActionType
set name = 'Reboots a virtual domain.'
where label = 'virt.reboot';

update rhnActionType
set name = 'Destroys a virtual domain.'
where label = 'virt.destroy';

update rhnActionType
set name = 'Sets the maximum memory usage for a virtual domain.'
where label = 'virt.setMemory';

update rhnActionType
set name = 'Sets the Vcpu usage for a virtual domain.'
where label = 'virt.setVCPUs';
  070701000004F1000081B400000000000000000000000167AE111400000449000000000000000000000000000000000000006600000000susemanager-schema/upgrade/spacewalk-schema-0.5-to-spacewalk-schema-0.6/124-rhn_probe_param_value.sql DECLARE
        type result_type is record (
                probe_id NUMBER,
                command_id NUMBER
        );
        one_row result_type;
BEGIN
FOR one_row IN (
        select probe_id, command_id from rhn_probe_param_value
                where
                        command_id in (25, 26, 27, 28, 29, 30, 31, 99, 105, 106, 107, 109, 117, 118, 123, 226, 228, 230, 249, 274, 304)
                group by probe_id, command_id
                having (probe_id, command_id) not in (
                        select probe_id, command_id from rhn_probe_param_value  where
                                command_id in (25, 26, 27, 28, 29, 30, 31, 99, 105, 106, 107, 109, 117, 118, 123, 226, 228, 230, 249, 274, 304)
                                AND param_name = 'sshbannerignore'
               )
        )
LOOP
        insert into rhn_probe_param_value
                (probe_id, command_id, param_name, value, last_update_user, last_update_date) values
                (one_row.probe_id, one_row.command_id, 'sshbannerignore', '0', 'upgrade', SYSDATE());
END LOOP;
END;
/

commit;
   070701000004F2000081B400000000000000000000000167AE1114000003F9000000000000000000000000000000000000006000000000susemanager-schema/upgrade/spacewalk-schema-0.5-to-spacewalk-schema-0.6/125-rhnChecksumType.sql   create sequence rhn_checksum_id_seq;

create table
rhnChecksumType
(
	id			number
				constraint rhn_checksumtype_id_nn not null,
	label			varchar2(32)
				constraint rhn_checksumtype_label_nn not null,
	description		varchar2(64)
				constraint rhn_checksumtype_desc_nn not null,
	created			date default(sysdate)
				constraint rhn_checksumtype_creat_nn not null,
	modified		date default(sysdate)
				constraint rhn_checksumtype_mod_nn not null
)
	enable row movement
  ;

create index rhn_checksumtype_label_id_idx
	on rhnChecksumType( label, id )
	tablespace [[64k_tbs]]
  ;
alter table rhnChecksumType add constraint rhn_checksumtype_id_pk 
        primary key ( id );
alter table rhnChecksumType add constraint rhn_checksumtype_label_uq
	unique ( label );

create or replace trigger
rhn_checksumtype_mod_trig
before insert or update on rhnChecksumType
for each row
begin
	:new.modified := sysdate;
end;
/
show errors

--
--
-- Revision 1.1  2009/06/26 10:39:17  pkilambi
--  add schema to hold checksum types
--

   070701000004F3000081B400000000000000000000000167AE111400000521000000000000000000000000000000000000006500000000susemanager-schema/upgrade/spacewalk-schema-0.5-to-spacewalk-schema-0.6/126-rhnChecksumType_data.sql  --
-- Copyright (c) 2008 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--


insert into rhnChecksumType (id, label, description) values
            (rhn_checksum_id_seq.nextval, 'md5', 'md5' );
insert into rhnChecksumType (id, label, description) values
            (rhn_checksum_id_seq.nextval, 'sha1', 'sha' );
insert into rhnChecksumType (id, label, description) values
            (rhn_checksum_id_seq.nextval, 'sha-256', 'sha256' );
insert into rhnChecksumType (id, label, description) values
            (rhn_checksum_id_seq.nextval, 'sha-384', 'sha384' );
insert into rhnChecksumType (id, label, description) values
            (rhn_checksum_id_seq.nextval, 'sha-512', 'sha512' );

commit;

--
--
-- Revision 1.1  2009/06/26 11:00:17  pkilambi
--

   070701000004F4000081B400000000000000000000000167AE1114000004CB000000000000000000000000000000000000006600000000susemanager-schema/upgrade/spacewalk-schema-0.5-to-spacewalk-schema-0.6/150-rhnConfigInfo_selinux.sql --
-- Add in a column for selinux context
--

ALTER TABLE rhnConfigInfo
  ADD selinux_ctx VARCHAR(64);

DROP INDEX RHN_CONFINFO_UGF_UQ;

CREATE UNIQUE INDEX rhn_confinfo_ugf_uq
    ON rhnConfigInfo( username, groupname, filemode, selinux_ctx )
    tablespace [[4m_tbs]]
  ;

CREATE OR REPLACE FUNCTION
lookup_config_info (
    username_in     IN VARCHAR2,
    groupname_in    IN VARCHAR2,
    filemode_in     IN VARCHAR2,
    selinux_ctx_in  IN VARCHAR2
) RETURN NUMBER
DETERMINISTIC
IS
    PRAGMA AUTONOMOUS_TRANSACTION;
    v_id    NUMBER;
    CURSOR lookup_cursor IS
        SELECT id
          FROM rhnConfigInfo
         WHERE 1=1
           AND username = username_in
           AND groupname = groupname_in
           AND filemode = filemode_in
           AND nvl(selinux_ctx, ' ') = nvl(selinux_ctx_in, ' ');
BEGIN
    FOR r IN lookup_cursor LOOP
        RETURN r.id;
    END LOOP;
    -- If we got here, we don't have the id
    SELECT rhn_confinfo_id_seq.nextval
      INTO v_id
      FROM dual;
    INSERT INTO rhnConfigInfo (id, username, groupname, filemode, selinux_ctx)
    VALUES (v_id, username_in, groupname_in, filemode_in, selinux_ctx_in);
    COMMIT;
    RETURN v_id;
END lookup_config_info;
/
show errors
 070701000004F5000081B400000000000000000000000167AE111400000623000000000000000000000000000000000000006900000000susemanager-schema/upgrade/spacewalk-schema-0.5-to-spacewalk-schema-0.6/190-rhnSharedChannelTreeView.sql  --
-- Copyright (c) 2008 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--

CREATE OR REPLACE VIEW RHNSHAREDCHANNELTREEVIEW
(
  ORG_ID,
  ID,
  DEPTH,
  NAME,
  PADDED_NAME,
  CHANNEL_ARCH_ID,
  LAST_MODIFIED,
  LABEL,
  PARENT_OR_SELF_LABEL,
  PARENT_OR_SELF_ID,
  END_OF_LIFE
)
AS
SELECT * FROM (
  SELECT
    C.ORG_TRUST_ID AS ORG_ID,
    C.ID,
    1 AS DEPTH,
    C.NAME,
    '  '||C.NAME AS PADDED_NAME,
    C.CHANNEL_ARCH_ID,
    C.LAST_MODIFIED,
    C.LABEL,
    C.LABEL AS PARENT_OR_SELF_LABEL,
    C.ID AS PARENT_OR_SELF_ID,
    C.END_OF_LIFE
  FROM RHNSHAREDCHANNELVIEW C
  WHERE C.PARENT_CHANNEL IS NULL
  UNION
  SELECT
    C.ORG_TRUST_ID AS ORG_ID,
    C.ID,
    2 AS DEPTH,
    c.name,
    ''||C.NAME AS PADDED_NAME,
    C.CHANNEL_ARCH_ID,
    C.LAST_MODIFIED,
    C.LABEL,
    PC.LABEL AS PARENT_OR_SELF_LABEL,
    PC.ID AS PARENT_OR_SELF_ID,
    C.END_OF_LIFE
  FROM RHNCHANNEL PC,
       RHNSHAREDCHANNELVIEW C
  WHERE C.PARENT_CHANNEL = PC.ID
) ORDER BY PARENT_OR_SELF_LABEL, PARENT_OR_SELF_ID;

 070701000004F6000081B400000000000000000000000167AE111400000203000000000000000000000000000000000000005B00000000susemanager-schema/upgrade/spacewalk-schema-0.5-to-spacewalk-schema-0.6/191-rhnChannel.sql    -- Add a checksum_type_id column, and fk to rhnChecksumType
ALTER TABLE rhnChannel
  ADD checksum_type_id number
CONSTRAINT rhn_channel_checksum_fk
    REFERENCES rhnChecksumType(id);

alter trigger rhn_channel_mod_trig disable;

-- Update any existing channels that are not set
UPDATE rhnChannel SET 
  checksum_type_id = (select id 
                        from rhnChecksumType 
                       where LABEL = 'sha1')
WHERE checksum_type_id is null;

alter trigger rhn_channel_mod_trig enable;

show errors
 070701000004F7000081B400000000000000000000000167AE111400000507000000000000000000000000000000000000006500000000susemanager-schema/upgrade/spacewalk-schema-0.5-to-spacewalk-schema-0.6/191-rhnContentSourceType.sql  --
-- Copyright (c) 2008 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--

create table
rhnContentSourceType
(
        id              number NOT NULL
                        constraint rhn_cst_id_pk primary key,
        label           varchar2(32) NOT NULL
                        constraint rhn_cst_label_uq unique,
        created         date default(sysdate) NOT NULL,
        modified        date default(sysdate) NOT NULL
)
        enable row movement
  ;



create sequence rhn_content_source_type_id_seq start with 500;

create index rhn_ccst_id_l_idx
	on rhnContentSourceType(id,label)
	tablespace [[64k_tbs]]
  ;


insert into rhnContentSourceType (id, label) values
(rhn_content_source_type_id_seq.nextval, 'yum');

 070701000004F8000081B400000000000000000000000167AE1114000002E8000000000000000000000000000000000000006B00000000susemanager-schema/upgrade/spacewalk-schema-0.5-to-spacewalk-schema-0.6/191-upgrade_kickstart_profiles.sql    --
-- Copyright (c) 2008 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--

INSERT INTO rhnTaskQueue (org_id, task_name, task_data)
VALUES (1, 'upgrade_satellite_kickstart_profiles', 0);
070701000004F9000081B400000000000000000000000167AE111400000621000000000000000000000000000000000000006800000000susemanager-schema/upgrade/spacewalk-schema-0.5-to-spacewalk-schema-0.6/192-rhnChannelContentSource.sql   --
-- Copyright (c) 2008 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--


create table
rhnChannelContentSource
(
        id              number NOT NULL
                        constraint rhn_ccs_id_pk primary key,
        channel_id      number NOT NULL
                        constraint rhn_ccs_c_fk
                                references rhnChannel(id) on delete cascade,
        type_id         number NOT NULL
                        constraint rhn_ccs_type_fk
                                references rhnContentSourceType(id),
        source_url      varchar2(512) NOT NULL,
        label           varchar2(64) NOT NULL,
        last_synced     date,
        created         date default(sysdate) NOT NULL,
        modified        date default(sysdate) NOT NULL
)
        enable row movement
  ;



create sequence rhn_chan_content_src_id_seq start with 500;


create unique index rhn_ccs_uq
	on rhnChannelContentSource(channel_id, type_id, source_url)
	tablespace [[64k_tbs]]
  ;

show errors

   070701000004FA000081B400000000000000000000000167AE1114000000BE000000000000000000000000000000000000005F00000000susemanager-schema/upgrade/spacewalk-schema-0.5-to-spacewalk-schema-0.6/193-rhn-PackageKey.sql    insert into rhnPackageKey (id, key_id, key_type_id, provider_id) values 
   (rhn_pkey_id_seq.nextval, '1dc5c758d22e77f2', lookup_package_key_type('gpg'), lookup_package_provider('Fedora'));
  070701000004FB000081B400000000000000000000000167AE11140000057C000000000000000000000000000000000000006F00000000susemanager-schema/upgrade/spacewalk-schema-0.5-to-spacewalk-schema-0.6/998-postgresql-compatability-procs.sql    ---
--- Add stored procedures for PostgreSQL compatability.
---

create or replace function evr_t_as_vre( a evr_t )
  return varchar2
is
begin
        return a.as_vre;
end;
/
show errors

create or replace function evr_t_as_vre_simple( a evr_t )
  return VARCHAR2
is
begin
    return a.as_vre_simple;
end;
/
show errors

create or replace function sequence_currval( seq_name varchar2 ) return number as
       ret number;
begin
       execute immediate 'select '|| seq_name || '.currval from dual'
               into ret;
       return ret;
end;
/
show errors

create or replace function sequence_nextval( seq_name varchar2 ) return number as
       ret number;
begin
       execute immediate 'select '|| seq_name || '.nextval from dual'
               into ret;
       return ret;
end;
/
show errors


CREATE OR REPLACE VIEW
rhnServerOutdatedPackages
(
    server_id,
    package_name_id,
    package_evr_id,    
    package_nvre,
    errata_id,
    errata_advisory
)
AS
SELECT DISTINCT SNPC.server_id,
       P.name_id, 
       P.evr_id, 
       PN.name || '-' || evr_t_as_vre_simple( PE.evr ),
       E.id,
       E.advisory
  FROM rhnPackageName PN,
       rhnPackageEVR PE,
       rhnPackage P,
       rhnServerNeededPackageCache SNPC
         left outer join
        rhnErrata E
          on SNPC.errata_id = E.id
 WHERE SNPC.package_id = P.id
   AND P.name_id = PN.id
   AND P.evr_id = PE.id;



070701000004FC000081B400000000000000000000000167AE11140003F81E000000000000000000000000000000000000005700000000susemanager-schema/upgrade/spacewalk-schema-0.5-to-spacewalk-schema-0.6/999-pgport.sql    --
-- Postgres compatability script.
-- Replaces named NOT NULL constraints with anonymous constraits via keyword.
-- Required so that upgraded schema matches fresh install.
--

--
-- RHNPRODUCTNAME
--
ALTER TABLE RHNPRODUCTNAME DROP CONSTRAINT PRODUCT_NAME_CREATED_NN;
ALTER TABLE RHNPRODUCTNAME MODIFY CREATED NOT NULL;

--
-- RHNPRODUCTNAME
--
ALTER TABLE RHNPRODUCTNAME DROP CONSTRAINT PRODUCT_NAME_MODIFIED_NN;
ALTER TABLE RHNPRODUCTNAME MODIFY MODIFIED NOT NULL;

--
-- PXTSESSIONS
--
ALTER TABLE PXTSESSIONS DROP CONSTRAINT PXTSESSIONS_EXPIRES_NN;
ALTER TABLE PXTSESSIONS MODIFY EXPIRES NOT NULL;

--
-- PXTSESSIONS
--
ALTER TABLE PXTSESSIONS DROP CONSTRAINT PXTSESSIONS_VALUE_NN;
ALTER TABLE PXTSESSIONS MODIFY VALUE NOT NULL;

--
-- RHNACTIONCONFIGCHANNEL
--
ALTER TABLE RHNACTIONCONFIGCHANNEL DROP CONSTRAINT RHN_ACTIONCC_AID_NN;
ALTER TABLE RHNACTIONCONFIGCHANNEL MODIFY ACTION_ID NOT NULL;

--
-- RHNACTIONCONFIGCHANNEL
--
ALTER TABLE RHNACTIONCONFIGCHANNEL DROP CONSTRAINT RHN_ACTIONCC_CCID_NN;
ALTER TABLE RHNACTIONCONFIGCHANNEL MODIFY CONFIG_CHANNEL_ID NOT NULL;

--
-- RHNACTIONCONFIGCHANNEL
--
ALTER TABLE RHNACTIONCONFIGCHANNEL DROP CONSTRAINT RHN_ACTIONCC_CREAT_NN;
ALTER TABLE RHNACTIONCONFIGCHANNEL MODIFY CREATED NOT NULL;

--
-- RHNACTIONCONFIGCHANNEL
--
ALTER TABLE RHNACTIONCONFIGCHANNEL DROP CONSTRAINT RHN_ACTIONCC_MOD_NN;
ALTER TABLE RHNACTIONCONFIGCHANNEL MODIFY MODIFIED NOT NULL;

--
-- RHNACTIONCONFIGCHANNEL
--
ALTER TABLE RHNACTIONCONFIGCHANNEL DROP CONSTRAINT RHN_ACTIONCC_SID_NN;
ALTER TABLE RHNACTIONCONFIGCHANNEL MODIFY SERVER_ID NOT NULL;

--
-- RHNACTIONCONFIGDATE
--
ALTER TABLE RHNACTIONCONFIGDATE DROP CONSTRAINT RHN_ACTIONCD_AID_NN;
ALTER TABLE RHNACTIONCONFIGDATE MODIFY ACTION_ID NOT NULL;

--
-- RHNACTIONCONFIGDATE
--
ALTER TABLE RHNACTIONCONFIGDATE DROP CONSTRAINT RHN_ACTIONCD_CREAT_NN;
ALTER TABLE RHNACTIONCONFIGDATE MODIFY CREATED NOT NULL;

--
-- RHNACTIONCONFIGDATEFILE
--
ALTER TABLE RHNACTIONCONFIGDATEFILE DROP CONSTRAINT RHN_ACTIONCD_FILE_AID_NN;
ALTER TABLE RHNACTIONCONFIGDATEFILE MODIFY ACTION_ID NOT NULL;

--
-- RHNACTIONCONFIGDATEFILE
--
ALTER TABLE RHNACTIONCONFIGDATEFILE DROP CONSTRAINT RHN_ACTIONCD_FILE_CREAT_NN;
ALTER TABLE RHNACTIONCONFIGDATEFILE MODIFY CREATED NOT NULL;

--
-- RHNACTIONCONFIGDATEFILE
--
ALTER TABLE RHNACTIONCONFIGDATEFILE DROP CONSTRAINT RHN_ACTIONCD_FILE_FN_NN;
ALTER TABLE RHNACTIONCONFIGDATEFILE MODIFY FILE_NAME NOT NULL;

--
-- RHNACTIONCONFIGDATEFILE
--
ALTER TABLE RHNACTIONCONFIGDATEFILE DROP CONSTRAINT RHN_ACTIONCD_FILE_FT_NN;
ALTER TABLE RHNACTIONCONFIGDATEFILE MODIFY FILE_TYPE NOT NULL;

--
-- RHNACTIONCONFIGDATE
--
ALTER TABLE RHNACTIONCONFIGDATE DROP CONSTRAINT RHN_ACTIONCD_FILE_IC_NN;
ALTER TABLE RHNACTIONCONFIGDATE MODIFY IMPORT_CONTENTS NOT NULL;

--
-- RHNACTIONCONFIGDATEFILE
--
ALTER TABLE RHNACTIONCONFIGDATEFILE DROP CONSTRAINT RHN_ACTIONCD_FILE_MOD_NN;
ALTER TABLE RHNACTIONCONFIGDATEFILE MODIFY MODIFIED NOT NULL;

--
-- RHNACTIONCONFIGDATE
--
ALTER TABLE RHNACTIONCONFIGDATE DROP CONSTRAINT RHN_ACTIONCD_MOD_NN;
ALTER TABLE RHNACTIONCONFIGDATE MODIFY MODIFIED NOT NULL;

--
-- RHNACTIONCONFIGDATE
--
ALTER TABLE RHNACTIONCONFIGDATE DROP CONSTRAINT RHN_ACTIONCD_START_NN;
ALTER TABLE RHNACTIONCONFIGDATE MODIFY START_DATE NOT NULL;

--
-- RHNACTIONCONFIGREVISIONRESULT
--
ALTER TABLE RHNACTIONCONFIGREVISIONRESULT DROP CONSTRAINT RHN_ACTIONCFR_ACRID_NN;
ALTER TABLE RHNACTIONCONFIGREVISIONRESULT MODIFY ACTION_CONFIG_REVISION_ID NOT NULL;

--
-- RHNACTIONCONFIGREVISIONRESULT
--
ALTER TABLE RHNACTIONCONFIGREVISIONRESULT DROP CONSTRAINT RHN_ACTIONCFR_CREAT_NN;
ALTER TABLE RHNACTIONCONFIGREVISIONRESULT MODIFY CREATED NOT NULL;

--
-- RHNACTIONCONFIGREVISIONRESULT
--
ALTER TABLE RHNACTIONCONFIGREVISIONRESULT DROP CONSTRAINT RHN_ACTIONCFR_MOD_NN;
ALTER TABLE RHNACTIONCONFIGREVISIONRESULT MODIFY MODIFIED NOT NULL;

--
-- RHNACTIONCONFIGFILENAME
--
ALTER TABLE RHNACTIONCONFIGFILENAME DROP CONSTRAINT RHN_ACTIONCF_CREAT_NN;
ALTER TABLE RHNACTIONCONFIGFILENAME MODIFY CREATED NOT NULL;

--
-- RHNACTIONCONFIGFILENAME
--
ALTER TABLE RHNACTIONCONFIGFILENAME DROP CONSTRAINT RHN_ACTIONCF_MOD_NN;
ALTER TABLE RHNACTIONCONFIGFILENAME MODIFY MODIFIED NOT NULL;

--
-- RHNACTIONCONFIGFILENAME
--
ALTER TABLE RHNACTIONCONFIGFILENAME DROP CONSTRAINT RHN_ACTIONCF_NAME_AID_NN;
ALTER TABLE RHNACTIONCONFIGFILENAME MODIFY ACTION_ID NOT NULL;

--
-- RHNACTIONCONFIGFILENAME
--
ALTER TABLE RHNACTIONCONFIGFILENAME DROP CONSTRAINT RHN_ACTIONCF_NAME_CFNID_NN;
ALTER TABLE RHNACTIONCONFIGFILENAME MODIFY CONFIG_FILE_NAME_ID NOT NULL;

--
-- RHNACTIONCONFIGFILENAME
--
ALTER TABLE RHNACTIONCONFIGFILENAME DROP CONSTRAINT RHN_ACTIONCF_NAME_SID_NN;
ALTER TABLE RHNACTIONCONFIGFILENAME MODIFY SERVER_ID NOT NULL;

--
-- RHNACTIONCONFIGREVISION
--
ALTER TABLE RHNACTIONCONFIGREVISION DROP CONSTRAINT RHN_ACTIONCR_AID_NN;
ALTER TABLE RHNACTIONCONFIGREVISION MODIFY ACTION_ID NOT NULL;

--
-- RHNACTIONCONFIGREVISION
--
ALTER TABLE RHNACTIONCONFIGREVISION DROP CONSTRAINT RHN_ACTIONCR_CREAT_NN;
ALTER TABLE RHNACTIONCONFIGREVISION MODIFY CREATED NOT NULL;

--
-- RHNACTIONCONFIGREVISION
--
ALTER TABLE RHNACTIONCONFIGREVISION DROP CONSTRAINT RHN_ACTIONCR_CRID_NN;
ALTER TABLE RHNACTIONCONFIGREVISION MODIFY CONFIG_REVISION_ID NOT NULL;

--
-- RHNACTIONCONFIGREVISION
--
ALTER TABLE RHNACTIONCONFIGREVISION DROP CONSTRAINT RHN_ACTIONCR_ID_NN;
ALTER TABLE RHNACTIONCONFIGREVISION MODIFY ID NOT NULL;

--
-- RHNACTIONCONFIGREVISION
--
ALTER TABLE RHNACTIONCONFIGREVISION DROP CONSTRAINT RHN_ACTIONCR_MOD_NN;
ALTER TABLE RHNACTIONCONFIGREVISION MODIFY MODIFIED NOT NULL;

--
-- RHNACTIONCONFIGREVISION
--
ALTER TABLE RHNACTIONCONFIGREVISION DROP CONSTRAINT RHN_ACTIONCR_SID_NN;
ALTER TABLE RHNACTIONCONFIGREVISION MODIFY SERVER_ID NOT NULL;

--
-- RHNACTIONDAEMONCONFIG
--
ALTER TABLE RHNACTIONDAEMONCONFIG DROP CONSTRAINT RHN_ACTIONDC_AID_NN;
ALTER TABLE RHNACTIONDAEMONCONFIG MODIFY ACTION_ID NOT NULL;

--
-- RHNACTIONDAEMONCONFIG
--
ALTER TABLE RHNACTIONDAEMONCONFIG DROP CONSTRAINT RHN_ACTIONDC_CREAT_NN;
ALTER TABLE RHNACTIONDAEMONCONFIG MODIFY CREATED NOT NULL;

--
-- RHNACTIONDAEMONCONFIG
--
ALTER TABLE RHNACTIONDAEMONCONFIG DROP CONSTRAINT RHN_ACTIONDC_INT_NN;
ALTER TABLE RHNACTIONDAEMONCONFIG MODIFY INTERVAL NOT NULL;

--
-- RHNACTIONDAEMONCONFIG
--
ALTER TABLE RHNACTIONDAEMONCONFIG DROP CONSTRAINT RHN_ACTIONDC_MOD_NN;
ALTER TABLE RHNACTIONDAEMONCONFIG MODIFY MODIFIED NOT NULL;

--
-- RHNACTIONDAEMONCONFIG
--
ALTER TABLE RHNACTIONDAEMONCONFIG DROP CONSTRAINT RHN_ACTIONDC_REST_NN;
ALTER TABLE RHNACTIONDAEMONCONFIG MODIFY RESTART NOT NULL;

--
-- RHNACTIONKICKSTARTFILELIST
--
ALTER TABLE RHNACTIONKICKSTARTFILELIST DROP CONSTRAINT RHN_ACTIONKSFL_AKSID_NN;
ALTER TABLE RHNACTIONKICKSTARTFILELIST MODIFY ACTION_KS_ID NOT NULL;

--
-- RHNACTIONKICKSTARTFILELIST
--
ALTER TABLE RHNACTIONKICKSTARTFILELIST DROP CONSTRAINT RHN_ACTIONKSFL_CREAT_NN;
ALTER TABLE RHNACTIONKICKSTARTFILELIST MODIFY CREATED NOT NULL;

--
-- RHNACTIONKICKSTARTFILELIST
--
ALTER TABLE RHNACTIONKICKSTARTFILELIST DROP CONSTRAINT RHN_ACTIONKSFL_FLID_NN;
ALTER TABLE RHNACTIONKICKSTARTFILELIST MODIFY FILE_LIST_ID NOT NULL;

--
-- RHNACTIONKICKSTARTFILELIST
--
ALTER TABLE RHNACTIONKICKSTARTFILELIST DROP CONSTRAINT RHN_ACTIONKSFL_MOD_NN;
ALTER TABLE RHNACTIONKICKSTARTFILELIST MODIFY MODIFIED NOT NULL;

--
-- RHNACTIONKICKSTART
--
ALTER TABLE RHNACTIONKICKSTART DROP CONSTRAINT RHN_ACTIONKS_AID_NN;
ALTER TABLE RHNACTIONKICKSTART MODIFY ACTION_ID NOT NULL;

--
-- RHNACTIONKICKSTART
--
ALTER TABLE RHNACTIONKICKSTART DROP CONSTRAINT RHN_ACTIONKS_CREAT_NN;
ALTER TABLE RHNACTIONKICKSTART MODIFY CREATED NOT NULL;

--
-- RHNACTIONKICKSTART
--
ALTER TABLE RHNACTIONKICKSTART DROP CONSTRAINT RHN_ACTIONKS_ID_NN;
ALTER TABLE RHNACTIONKICKSTART MODIFY ID NOT NULL;

--
-- RHNACTIONKICKSTART
--
ALTER TABLE RHNACTIONKICKSTART DROP CONSTRAINT RHN_ACTIONKS_MOD_NN;
ALTER TABLE RHNACTIONKICKSTART MODIFY MODIFIED NOT NULL;

--
-- RHNACTIONKICKSTARTGUEST
--
ALTER TABLE RHNACTIONKICKSTARTGUEST DROP CONSTRAINT RHN_ACTIONKS_XENGUEST_AID_NN;
ALTER TABLE RHNACTIONKICKSTARTGUEST MODIFY ACTION_ID NOT NULL;

--
-- RHNACTIONKICKSTARTGUEST
--
ALTER TABLE RHNACTIONKICKSTARTGUEST DROP CONSTRAINT RHN_ACTIONKS_XENGUEST_CREAT_NN;
ALTER TABLE RHNACTIONKICKSTARTGUEST MODIFY CREATED NOT NULL;

--
-- RHNACTIONKICKSTARTGUEST
--
ALTER TABLE RHNACTIONKICKSTARTGUEST DROP CONSTRAINT RHN_ACTIONKS_XENGUEST_ID_NN;
ALTER TABLE RHNACTIONKICKSTARTGUEST MODIFY ID NOT NULL;

--
-- RHNACTIONKICKSTARTGUEST
--
ALTER TABLE RHNACTIONKICKSTARTGUEST DROP CONSTRAINT RHN_ACTIONKS_XENGUEST_MOD_NN;
ALTER TABLE RHNACTIONKICKSTARTGUEST MODIFY MODIFIED NOT NULL;

--
-- RHNACTION
--
ALTER TABLE RHNACTION DROP CONSTRAINT RHN_ACTION_ARCHIVED_NN;
ALTER TABLE RHNACTION MODIFY ARCHIVED NOT NULL;

--
-- RHNACTION
--
ALTER TABLE RHNACTION DROP CONSTRAINT RHN_ACTION_AT_NN;
ALTER TABLE RHNACTION MODIFY ACTION_TYPE NOT NULL;

--
-- RHNACTION
--
ALTER TABLE RHNACTION DROP CONSTRAINT RHN_ACTION_CREATED_NN;
ALTER TABLE RHNACTION MODIFY CREATED NOT NULL;

--
-- RHNACTION
--
ALTER TABLE RHNACTION DROP CONSTRAINT RHN_ACTION_EA_NN;
ALTER TABLE RHNACTION MODIFY EARLIEST_ACTION NOT NULL;

--
-- RHNACTION
--
ALTER TABLE RHNACTION DROP CONSTRAINT RHN_ACTION_ID_NN;
ALTER TABLE RHNACTION MODIFY ID NOT NULL;

--
-- RHNACTION
--
ALTER TABLE RHNACTION DROP CONSTRAINT RHN_ACTION_MODIFIED_NN;
ALTER TABLE RHNACTION MODIFY MODIFIED NOT NULL;

--
-- RHNACTION
--
ALTER TABLE RHNACTION DROP CONSTRAINT RHN_ACTION_OID_NN;
ALTER TABLE RHNACTION MODIFY ORG_ID NOT NULL;

--
-- RHNACTIONSTATUS
--
ALTER TABLE RHNACTIONSTATUS DROP CONSTRAINT RHN_ACTION_STATUS_CREATED_NN;
ALTER TABLE RHNACTIONSTATUS MODIFY CREATED NOT NULL;

--
-- RHNACTIONSTATUS
--
ALTER TABLE RHNACTIONSTATUS DROP CONSTRAINT RHN_ACTION_STATUS_ID_NN;
ALTER TABLE RHNACTIONSTATUS MODIFY ID NOT NULL;

--
-- RHNACTIONSTATUS
--
ALTER TABLE RHNACTIONSTATUS DROP CONSTRAINT RHN_ACTION_STATUS_MODIFIED_NN;
ALTER TABLE RHNACTIONSTATUS MODIFY MODIFIED NOT NULL;

--
-- RHNACTIONTYPE
--
ALTER TABLE RHNACTIONTYPE DROP CONSTRAINT RHN_ACTION_TYPE_ID_NN;
ALTER TABLE RHNACTIONTYPE MODIFY ID NOT NULL;

--
-- RHNACTIONTYPE
--
ALTER TABLE RHNACTIONTYPE DROP CONSTRAINT RHN_ACTION_TYPE_LABEL_NN;
ALTER TABLE RHNACTIONTYPE MODIFY LABEL NOT NULL;

--
-- RHNACTIONTYPE
--
ALTER TABLE RHNACTIONTYPE DROP CONSTRAINT RHN_ACTION_TYPE_NAME_NN;
ALTER TABLE RHNACTIONTYPE MODIFY NAME NOT NULL;

--
-- RHNACTIONTYPE
--
ALTER TABLE RHNACTIONTYPE DROP CONSTRAINT RHN_ACTION_TYPE_TRIGSNAP_NN;
ALTER TABLE RHNACTIONTYPE MODIFY TRIGGER_SNAPSHOT NOT NULL;

--
-- RHNACTIONTYPE
--
ALTER TABLE RHNACTIONTYPE DROP CONSTRAINT RHN_ACTION_TYPE_UNLCK_NN;
ALTER TABLE RHNACTIONTYPE MODIFY UNLOCKED_ONLY NOT NULL;

--
-- RHNACTION
--
ALTER TABLE RHNACTION DROP CONSTRAINT RHN_ACTION_VERSION_NN;
ALTER TABLE RHNACTION MODIFY VERSION NOT NULL;

--
-- RHNACTIONSCRIPT
--
ALTER TABLE RHNACTIONSCRIPT DROP CONSTRAINT RHN_ACTSCRIPT_AID_NN;
ALTER TABLE RHNACTIONSCRIPT MODIFY ACTION_ID NOT NULL;

--
-- RHNACTIONSCRIPT
--
ALTER TABLE RHNACTIONSCRIPT DROP CONSTRAINT RHN_ACTSCRIPT_CREAT_NN;
ALTER TABLE RHNACTIONSCRIPT MODIFY CREATED NOT NULL;

--
-- RHNACTIONSCRIPT
--
ALTER TABLE RHNACTIONSCRIPT DROP CONSTRAINT RHN_ACTSCRIPT_GROUP_NN;
ALTER TABLE RHNACTIONSCRIPT MODIFY GROUPNAME NOT NULL;

--
-- RHNACTIONSCRIPT
--
ALTER TABLE RHNACTIONSCRIPT DROP CONSTRAINT RHN_ACTSCRIPT_ID_NN;
ALTER TABLE RHNACTIONSCRIPT MODIFY ID NOT NULL;

--
-- RHNACTIONSCRIPT
--
ALTER TABLE RHNACTIONSCRIPT DROP CONSTRAINT RHN_ACTSCRIPT_MOD_NN;
ALTER TABLE RHNACTIONSCRIPT MODIFY MODIFIED NOT NULL;

--
-- RHNACTIONSCRIPT
--
ALTER TABLE RHNACTIONSCRIPT DROP CONSTRAINT RHN_ACTSCRIPT_USER_NN;
ALTER TABLE RHNACTIONSCRIPT MODIFY USERNAME NOT NULL;

--
-- RHNACTIONERRATAUPDATE
--
ALTER TABLE RHNACTIONERRATAUPDATE DROP CONSTRAINT RHN_ACT_EU_ACT_NN;
ALTER TABLE RHNACTIONERRATAUPDATE MODIFY ACTION_ID NOT NULL;

--
-- RHNACTIONERRATAUPDATE
--
ALTER TABLE RHNACTIONERRATAUPDATE DROP CONSTRAINT RHN_ACT_EU_ERR_NN;
ALTER TABLE RHNACTIONERRATAUPDATE MODIFY ERRATA_ID NOT NULL;

--
-- RHNACTIVATIONKEY
--
ALTER TABLE RHNACTIVATIONKEY DROP CONSTRAINT RHN_ACT_KEY_CREATED_NN;
ALTER TABLE RHNACTIVATIONKEY MODIFY CREATED NOT NULL;

--
-- RHNACTIVATIONKEY
--
ALTER TABLE RHNACTIVATIONKEY DROP CONSTRAINT RHN_ACT_KEY_MODIFIED_NN;
ALTER TABLE RHNACTIVATIONKEY MODIFY MODIFIED NOT NULL;

--
-- RHNACTIVATIONKEY
--
ALTER TABLE RHNACTIVATIONKEY DROP CONSTRAINT RHN_ACT_KEY_REG_TID_NN;
ALTER TABLE RHNACTIVATIONKEY MODIFY REG_TOKEN_ID NOT NULL;

--
-- RHNACTIVATIONKEY
--
ALTER TABLE RHNACTIVATIONKEY DROP CONSTRAINT RHN_ACT_KEY_TOKEN_NN;
ALTER TABLE RHNACTIVATIONKEY MODIFY TOKEN NOT NULL;

--
-- RHNACTIONPACKAGEDELTA
--
ALTER TABLE RHNACTIONPACKAGEDELTA DROP CONSTRAINT RHN_ACT_PD_AID_NN;
ALTER TABLE RHNACTIONPACKAGEDELTA MODIFY ACTION_ID NOT NULL;

--
-- RHNACTIONPACKAGEDELTA
--
ALTER TABLE RHNACTIONPACKAGEDELTA DROP CONSTRAINT RHN_ACT_PD_PDID_NN;
ALTER TABLE RHNACTIONPACKAGEDELTA MODIFY PACKAGE_DELTA_ID NOT NULL;

--
-- RHNACTIONPACKAGEORDER
--
ALTER TABLE RHNACTIONPACKAGEORDER DROP CONSTRAINT RHN_ACT_PKG_APID_NN;
ALTER TABLE RHNACTIONPACKAGEORDER MODIFY ACTION_PACKAGE_ID NOT NULL;

--
-- RHNACTIONPACKAGEORDER
--
ALTER TABLE RHNACTIONPACKAGEORDER DROP CONSTRAINT RHN_ACT_PKG_ORDER_NN;
ALTER TABLE RHNACTIONPACKAGEORDER MODIFY PACKAGE_ORDER NOT NULL;

--
-- RHNACTIONPACKAGE
--
ALTER TABLE RHNACTIONPACKAGE DROP CONSTRAINT RHN_ACT_P_ACT_NN;
ALTER TABLE RHNACTIONPACKAGE MODIFY ACTION_ID NOT NULL;

--
-- RHNACTIONPACKAGEANSWERFILE
--
ALTER TABLE RHNACTIONPACKAGEANSWERFILE DROP CONSTRAINT RHN_ACT_P_AF_APID_NN;
ALTER TABLE RHNACTIONPACKAGEANSWERFILE MODIFY ACTION_PACKAGE_ID NOT NULL;

--
-- RHNACTIONPACKAGEANSWERFILE
--
ALTER TABLE RHNACTIONPACKAGEANSWERFILE DROP CONSTRAINT RHN_ACT_P_AF_CREAT_NN;
ALTER TABLE RHNACTIONPACKAGEANSWERFILE MODIFY CREATED NOT NULL;

--
-- RHNACTIONPACKAGEANSWERFILE
--
ALTER TABLE RHNACTIONPACKAGEANSWERFILE DROP CONSTRAINT RHN_ACT_P_AF_MOD_NN;
ALTER TABLE RHNACTIONPACKAGEANSWERFILE MODIFY MODIFIED NOT NULL;

--
-- RHNACTIONPACKAGE
--
ALTER TABLE RHNACTIONPACKAGE DROP CONSTRAINT RHN_ACT_P_ID_NN;
ALTER TABLE RHNACTIONPACKAGE MODIFY ID NOT NULL;

--
-- RHNACTIONPACKAGE
--
ALTER TABLE RHNACTIONPACKAGE DROP CONSTRAINT RHN_ACT_P_NAME_NN;
ALTER TABLE RHNACTIONPACKAGE MODIFY NAME_ID NOT NULL;

--
-- RHNACTIONPACKAGE
--
ALTER TABLE RHNACTIONPACKAGE DROP CONSTRAINT RHN_ACT_P_PARAM_NN;
ALTER TABLE RHNACTIONPACKAGE MODIFY PARAMETER NOT NULL;

--
-- RHNALLOWTRUST
--
ALTER TABLE RHNALLOWTRUST DROP CONSTRAINT RHN_ALLOW_TRUST_CHANNELFLG_NN;
ALTER TABLE RHNALLOWTRUST MODIFY CHANNEL_FLAG NOT NULL;

--
-- RHNALLOWTRUST
--
ALTER TABLE RHNALLOWTRUST DROP CONSTRAINT RHN_ALLOW_TRUST_CREATED_NN;
ALTER TABLE RHNALLOWTRUST MODIFY CREATED NOT NULL;

--
-- RHNALLOWTRUST
--
ALTER TABLE RHNALLOWTRUST DROP CONSTRAINT RHN_ALLOW_TRUST_MIGRFLG_NN;
ALTER TABLE RHNALLOWTRUST MODIFY MIGRATION_FLAG NOT NULL;

--
-- RHNALLOWTRUST
--
ALTER TABLE RHNALLOWTRUST DROP CONSTRAINT RHN_ALLOW_TRUST_MODIFIED_NN;
ALTER TABLE RHNALLOWTRUST MODIFY MODIFIED NOT NULL;

--
-- RHNALLOWTRUST
--
ALTER TABLE RHNALLOWTRUST DROP CONSTRAINT RHN_ALLOW_TRUST_OID_NN;
ALTER TABLE RHNALLOWTRUST MODIFY ORG_ID NOT NULL;

--
-- RHN_CURRENT_ALERTS
--
ALTER TABLE RHN_CURRENT_ALERTS DROP CONSTRAINT RHN_ALRTS_CUST_ID_NN;
ALTER TABLE RHN_CURRENT_ALERTS MODIFY CUSTOMER_ID NOT NULL;

--
-- RHN_CURRENT_ALERTS
--
ALTER TABLE RHN_CURRENT_ALERTS DROP CONSTRAINT RHN_ALRTS_IN_PROG_NN;
ALTER TABLE RHN_CURRENT_ALERTS MODIFY IN_PROGRESS NOT NULL;

--
-- RHN_CURRENT_ALERTS
--
ALTER TABLE RHN_CURRENT_ALERTS DROP CONSTRAINT RHN_ALRTS_RECID_NN;
ALTER TABLE RHN_CURRENT_ALERTS MODIFY RECID NOT NULL;

--
-- RHNAPPINSTALLINSTANCE
--
ALTER TABLE RHNAPPINSTALLINSTANCE DROP CONSTRAINT RHN_APPINST_INSTANCE_CREAT_NN;
ALTER TABLE RHNAPPINSTALLINSTANCE MODIFY CREATED NOT NULL;

--
-- RHNAPPINSTALLINSTANCE
--
ALTER TABLE RHNAPPINSTALLINSTANCE DROP CONSTRAINT RHN_APPINST_INSTANCE_ID_NN;
ALTER TABLE RHNAPPINSTALLINSTANCE MODIFY ID NOT NULL;

--
-- RHNAPPINSTALLINSTANCE
--
ALTER TABLE RHNAPPINSTALLINSTANCE DROP CONSTRAINT RHN_APPINST_INSTANCE_LABEL_NN;
ALTER TABLE RHNAPPINSTALLINSTANCE MODIFY LABEL NOT NULL;

--
-- RHNAPPINSTALLINSTANCE
--
ALTER TABLE RHNAPPINSTALLINSTANCE DROP CONSTRAINT RHN_APPINST_INSTANCE_MOD_NN;
ALTER TABLE RHNAPPINSTALLINSTANCE MODIFY MODIFIED NOT NULL;

--
-- RHNAPPINSTALLINSTANCE
--
ALTER TABLE RHNAPPINSTALLINSTANCE DROP CONSTRAINT RHN_APPINST_INSTANCE_NAME_NN;
ALTER TABLE RHNAPPINSTALLINSTANCE MODIFY NAME NOT NULL;

--
-- RHNAPPINSTALLINSTANCE
--
ALTER TABLE RHNAPPINSTALLINSTANCE DROP CONSTRAINT RHN_APPINST_INSTANCE_VERS_NN;
ALTER TABLE RHNAPPINSTALLINSTANCE MODIFY VERSION NOT NULL;

--
-- RHNAPPINSTALLSESSIONDATA
--
ALTER TABLE RHNAPPINSTALLSESSIONDATA DROP CONSTRAINT RHN_APPINST_SDATA_CREAT_NN;
ALTER TABLE RHNAPPINSTALLSESSIONDATA MODIFY CREATED NOT NULL;

--
-- RHNAPPINSTALLSESSIONDATA
--
ALTER TABLE RHNAPPINSTALLSESSIONDATA DROP CONSTRAINT RHN_APPINST_SDATA_ID_NN;
ALTER TABLE RHNAPPINSTALLSESSIONDATA MODIFY ID NOT NULL;

--
-- RHNAPPINSTALLSESSIONDATA
--
ALTER TABLE RHNAPPINSTALLSESSIONDATA DROP CONSTRAINT RHN_APPINST_SDATA_K_NN;
ALTER TABLE RHNAPPINSTALLSESSIONDATA MODIFY KEY NOT NULL;

--
-- RHNAPPINSTALLSESSIONDATA
--
ALTER TABLE RHNAPPINSTALLSESSIONDATA DROP CONSTRAINT RHN_APPINST_SDATA_MOD_NN;
ALTER TABLE RHNAPPINSTALLSESSIONDATA MODIFY MODIFIED NOT NULL;

--
-- RHNAPPINSTALLSESSIONDATA
--
ALTER TABLE RHNAPPINSTALLSESSIONDATA DROP CONSTRAINT RHN_APPINST_SDATA_SID_NN;
ALTER TABLE RHNAPPINSTALLSESSIONDATA MODIFY SESSION_ID NOT NULL;

--
-- RHNAPPINSTALLSESSION
--
ALTER TABLE RHNAPPINSTALLSESSION DROP CONSTRAINT RHN_APPINST_SESSION_CREAT_NN;
ALTER TABLE RHNAPPINSTALLSESSION MODIFY CREATED NOT NULL;

--
-- RHNAPPINSTALLSESSION
--
ALTER TABLE RHNAPPINSTALLSESSION DROP CONSTRAINT RHN_APPINST_SESSION_ID_NN;
ALTER TABLE RHNAPPINSTALLSESSION MODIFY ID NOT NULL;

--
-- RHNAPPINSTALLSESSION
--
ALTER TABLE RHNAPPINSTALLSESSION DROP CONSTRAINT RHN_APPINST_SESSION_IID_NN;
ALTER TABLE RHNAPPINSTALLSESSION MODIFY INSTANCE_ID NOT NULL;

--
-- RHNAPPINSTALLSESSION
--
ALTER TABLE RHNAPPINSTALLSESSION DROP CONSTRAINT RHN_APPINST_SESSION_MOD_NN;
ALTER TABLE RHNAPPINSTALLSESSION MODIFY MODIFIED NOT NULL;

--
-- RHNAPPINSTALLSESSION
--
ALTER TABLE RHNAPPINSTALLSESSION DROP CONSTRAINT RHN_APPINST_SESSION_SID_NN;
ALTER TABLE RHNAPPINSTALLSESSION MODIFY SERVER_ID NOT NULL;

--
-- RHNAPPINSTALLSESSION
--
ALTER TABLE RHNAPPINSTALLSESSION DROP CONSTRAINT RHN_APPINST_SESSION_UID_NN;
ALTER TABLE RHNAPPINSTALLSESSION MODIFY USER_ID NOT NULL;

--
-- RHNACTIONPACKAGEREMOVALFAILURE
--
ALTER TABLE RHNACTIONPACKAGEREMOVALFAILURE DROP CONSTRAINT RHN_APR_FAILURE_AID_NN;
ALTER TABLE RHNACTIONPACKAGEREMOVALFAILURE MODIFY ACTION_ID NOT NULL;

--
-- RHNACTIONPACKAGEREMOVALFAILURE
--
ALTER TABLE RHNACTIONPACKAGEREMOVALFAILURE DROP CONSTRAINT RHN_APR_FAILURE_CAPID_NN;
ALTER TABLE RHNACTIONPACKAGEREMOVALFAILURE MODIFY CAPABILITY_ID NOT NULL;

--
-- RHNACTIONPACKAGEREMOVALFAILURE
--
ALTER TABLE RHNACTIONPACKAGEREMOVALFAILURE DROP CONSTRAINT RHN_APR_FAILURE_EID_NN;
ALTER TABLE RHNACTIONPACKAGEREMOVALFAILURE MODIFY EVR_ID NOT NULL;

--
-- RHNACTIONPACKAGEREMOVALFAILURE
--
ALTER TABLE RHNACTIONPACKAGEREMOVALFAILURE DROP CONSTRAINT RHN_APR_FAILURE_FLAGS_NN;
ALTER TABLE RHNACTIONPACKAGEREMOVALFAILURE MODIFY FLAGS NOT NULL;

--
-- RHNACTIONPACKAGEREMOVALFAILURE
--
ALTER TABLE RHNACTIONPACKAGEREMOVALFAILURE DROP CONSTRAINT RHN_APR_FAILURE_NID_NN;
ALTER TABLE RHNACTIONPACKAGEREMOVALFAILURE MODIFY NAME_ID NOT NULL;

--
-- RHNACTIONPACKAGEREMOVALFAILURE
--
ALTER TABLE RHNACTIONPACKAGEREMOVALFAILURE DROP CONSTRAINT RHN_APR_FAILURE_SENSE_NN;
ALTER TABLE RHNACTIONPACKAGEREMOVALFAILURE MODIFY SENSE NOT NULL;

--
-- RHNACTIONPACKAGEREMOVALFAILURE
--
ALTER TABLE RHNACTIONPACKAGEREMOVALFAILURE DROP CONSTRAINT RHN_APR_FAILURE_SID_NN;
ALTER TABLE RHNACTIONPACKAGEREMOVALFAILURE MODIFY SERVER_ID NOT NULL;

--
-- RHNARCHTYPEACTIONS
--
ALTER TABLE RHNARCHTYPEACTIONS DROP CONSTRAINT RHN_ARCHTYPEACTS_ACTID_NN;
ALTER TABLE RHNARCHTYPEACTIONS MODIFY ACTION_TYPE_ID NOT NULL;

--
-- RHNARCHTYPEACTIONS
--
ALTER TABLE RHNARCHTYPEACTIONS DROP CONSTRAINT RHN_ARCHTYPEACTS_AS_NN;
ALTER TABLE RHNARCHTYPEACTIONS MODIFY ACTION_STYLE NOT NULL;

--
-- RHNARCHTYPEACTIONS
--
ALTER TABLE RHNARCHTYPEACTIONS DROP CONSTRAINT RHN_ARCHTYPEACTS_ATID_NN;
ALTER TABLE RHNARCHTYPEACTIONS MODIFY ARCH_TYPE_ID NOT NULL;

--
-- RHNARCHTYPEACTIONS
--
ALTER TABLE RHNARCHTYPEACTIONS DROP CONSTRAINT RHN_ARCHTYPEACTS_CREAT_NN;
ALTER TABLE RHNARCHTYPEACTIONS MODIFY CREATED NOT NULL;

--
-- RHNARCHTYPEACTIONS
--
ALTER TABLE RHNARCHTYPEACTIONS DROP CONSTRAINT RHN_ARCHTYPEACTS_MOD_NN;
ALTER TABLE RHNARCHTYPEACTIONS MODIFY MODIFIED NOT NULL;

--
-- RHNARCHTYPE
--
ALTER TABLE RHNARCHTYPE DROP CONSTRAINT RHN_ARCHTYPE_CREAT_NN;
ALTER TABLE RHNARCHTYPE MODIFY CREATED NOT NULL;

--
-- RHNARCHTYPE
--
ALTER TABLE RHNARCHTYPE DROP CONSTRAINT RHN_ARCHTYPE_ID_NN;
ALTER TABLE RHNARCHTYPE MODIFY ID NOT NULL;

--
-- RHNARCHTYPE
--
ALTER TABLE RHNARCHTYPE DROP CONSTRAINT RHN_ARCHTYPE_LABEL_NN;
ALTER TABLE RHNARCHTYPE MODIFY LABEL NOT NULL;

--
-- RHNARCHTYPE
--
ALTER TABLE RHNARCHTYPE DROP CONSTRAINT RHN_ARCHTYPE_MOD_NN;
ALTER TABLE RHNARCHTYPE MODIFY MODIFIED NOT NULL;

--
-- RHNARCHTYPE
--
ALTER TABLE RHNARCHTYPE DROP CONSTRAINT RHN_ARCHTYPE_NAME_NN;
ALTER TABLE RHNARCHTYPE MODIFY NAME NOT NULL;

--
-- RHNACTIONTRANSACTIONS
--
ALTER TABLE RHNACTIONTRANSACTIONS DROP CONSTRAINT RHN_AT_AID_NN;
ALTER TABLE RHNACTIONTRANSACTIONS MODIFY ACTION_ID NOT NULL;

--
-- RHNACTIONTRANSACTIONS
--
ALTER TABLE RHNACTIONTRANSACTIONS DROP CONSTRAINT RHN_AT_FTID_NN;
ALTER TABLE RHNACTIONTRANSACTIONS MODIFY FROM_TRANS_ID NOT NULL;

--
-- RHNACTIONTRANSACTIONS
--
ALTER TABLE RHNACTIONTRANSACTIONS DROP CONSTRAINT RHN_AT_TTID_NN;
ALTER TABLE RHNACTIONTRANSACTIONS MODIFY TO_TRANS_ID NOT NULL;

--
-- RHNACTIONVIRTVCPU
--
ALTER TABLE RHNACTIONVIRTVCPU DROP CONSTRAINT RHN_AVCPU_AID_NN;
ALTER TABLE RHNACTIONVIRTVCPU MODIFY ACTION_ID NOT NULL;

--
-- RHNACTIONVIRTVCPU
--
ALTER TABLE RHNACTIONVIRTVCPU DROP CONSTRAINT RHN_AVCPU_CREAT_NN;
ALTER TABLE RHNACTIONVIRTVCPU MODIFY CREATED NOT NULL;

--
-- RHNACTIONVIRTVCPU
--
ALTER TABLE RHNACTIONVIRTVCPU DROP CONSTRAINT RHN_AVCPU_MOD_NN;
ALTER TABLE RHNACTIONVIRTVCPU MODIFY MODIFIED NOT NULL;

--
-- RHNACTIONVIRTVCPU
--
ALTER TABLE RHNACTIONVIRTVCPU DROP CONSTRAINT RHN_AVCPU_UUID_NN;
ALTER TABLE RHNACTIONVIRTVCPU MODIFY UUID NOT NULL;

--
-- RHNACTIONVIRTVCPU
--
ALTER TABLE RHNACTIONVIRTVCPU DROP CONSTRAINT RHN_AVCPU_VCPUS_NN;
ALTER TABLE RHNACTIONVIRTVCPU MODIFY VCPU NOT NULL;

--
-- RHNACTIONVIRTDESTROY
--
ALTER TABLE RHNACTIONVIRTDESTROY DROP CONSTRAINT RHN_AVD_AID_NN;
ALTER TABLE RHNACTIONVIRTDESTROY MODIFY ACTION_ID NOT NULL;

--
-- RHNACTIONVIRTDESTROY
--
ALTER TABLE RHNACTIONVIRTDESTROY DROP CONSTRAINT RHN_AVD_CREAT_NN;
ALTER TABLE RHNACTIONVIRTDESTROY MODIFY CREATED NOT NULL;

--
-- RHNACTIONVIRTDESTROY
--
ALTER TABLE RHNACTIONVIRTDESTROY DROP CONSTRAINT RHN_AVD_MOD_NN;
ALTER TABLE RHNACTIONVIRTDESTROY MODIFY MODIFIED NOT NULL;

--
-- RHNACTIONVIRTDESTROY
--
ALTER TABLE RHNACTIONVIRTDESTROY DROP CONSTRAINT RHN_AVD_UUID_NN;
ALTER TABLE RHNACTIONVIRTDESTROY MODIFY UUID NOT NULL;

--
-- RHNACTIONVIRTREBOOT
--
ALTER TABLE RHNACTIONVIRTREBOOT DROP CONSTRAINT RHN_AVREBOOT_AID_NN;
ALTER TABLE RHNACTIONVIRTREBOOT MODIFY ACTION_ID NOT NULL;

--
-- RHNACTIONVIRTREBOOT
--
ALTER TABLE RHNACTIONVIRTREBOOT DROP CONSTRAINT RHN_AVREBOOT_CREAT_NN;
ALTER TABLE RHNACTIONVIRTREBOOT MODIFY CREATED NOT NULL;

--
-- RHNACTIONVIRTREBOOT
--
ALTER TABLE RHNACTIONVIRTREBOOT DROP CONSTRAINT RHN_AVREBOOT_MOD_NN;
ALTER TABLE RHNACTIONVIRTREBOOT MODIFY MODIFIED NOT NULL;

--
-- RHNACTIONVIRTREBOOT
--
ALTER TABLE RHNACTIONVIRTREBOOT DROP CONSTRAINT RHN_AVREBOOT_UUID_NN;
ALTER TABLE RHNACTIONVIRTREBOOT MODIFY UUID NOT NULL;

--
-- RHNACTIONVIRTREFRESH
--
ALTER TABLE RHNACTIONVIRTREFRESH DROP CONSTRAINT RHN_AVREFRESH_AID_NN;
ALTER TABLE RHNACTIONVIRTREFRESH MODIFY ACTION_ID NOT NULL;

--
-- RHNACTIONVIRTREFRESH
--
ALTER TABLE RHNACTIONVIRTREFRESH DROP CONSTRAINT RHN_AVREFRESH_CREAT_NN;
ALTER TABLE RHNACTIONVIRTREFRESH MODIFY CREATED NOT NULL;

--
-- RHNACTIONVIRTREFRESH
--
ALTER TABLE RHNACTIONVIRTREFRESH DROP CONSTRAINT RHN_AVREFRESH_MOD_NN;
ALTER TABLE RHNACTIONVIRTREFRESH MODIFY MODIFIED NOT NULL;

--
-- RHNACTIONVIRTRESUME
--
ALTER TABLE RHNACTIONVIRTRESUME DROP CONSTRAINT RHN_AVRESUME_AID_NN;
ALTER TABLE RHNACTIONVIRTRESUME MODIFY ACTION_ID NOT NULL;

--
-- RHNACTIONVIRTRESUME
--
ALTER TABLE RHNACTIONVIRTRESUME DROP CONSTRAINT RHN_AVRESUME_CREAT_NN;
ALTER TABLE RHNACTIONVIRTRESUME MODIFY CREATED NOT NULL;

--
-- RHNACTIONVIRTRESUME
--
ALTER TABLE RHNACTIONVIRTRESUME DROP CONSTRAINT RHN_AVRESUME_MOD_NN;
ALTER TABLE RHNACTIONVIRTRESUME MODIFY MODIFIED NOT NULL;

--
-- RHNACTIONVIRTRESUME
--
ALTER TABLE RHNACTIONVIRTRESUME DROP CONSTRAINT RHN_AVRESUME_UUID_NN;
ALTER TABLE RHNACTIONVIRTRESUME MODIFY UUID NOT NULL;

--
-- RHNACTIONVIRTSHUTDOWN
--
ALTER TABLE RHNACTIONVIRTSHUTDOWN DROP CONSTRAINT RHN_AVSHUTDOWN_AID_NN;
ALTER TABLE RHNACTIONVIRTSHUTDOWN MODIFY ACTION_ID NOT NULL;

--
-- RHNACTIONVIRTSHUTDOWN
--
ALTER TABLE RHNACTIONVIRTSHUTDOWN DROP CONSTRAINT RHN_AVSHUTDOWN_CREAT_NN;
ALTER TABLE RHNACTIONVIRTSHUTDOWN MODIFY CREATED NOT NULL;

--
-- RHNACTIONVIRTSHUTDOWN
--
ALTER TABLE RHNACTIONVIRTSHUTDOWN DROP CONSTRAINT RHN_AVSHUTDOWN_MOD_NN;
ALTER TABLE RHNACTIONVIRTSHUTDOWN MODIFY MODIFIED NOT NULL;

--
-- RHNACTIONVIRTSHUTDOWN
--
ALTER TABLE RHNACTIONVIRTSHUTDOWN DROP CONSTRAINT RHN_AVSHUTDOWN_UUID_NN;
ALTER TABLE RHNACTIONVIRTSHUTDOWN MODIFY UUID NOT NULL;

--
-- RHNACTIONVIRTSETMEMORY
--
ALTER TABLE RHNACTIONVIRTSETMEMORY DROP CONSTRAINT RHN_AVSM_AID_NN;
ALTER TABLE RHNACTIONVIRTSETMEMORY MODIFY ACTION_ID NOT NULL;

--
-- RHNACTIONVIRTSETMEMORY
--
ALTER TABLE RHNACTIONVIRTSETMEMORY DROP CONSTRAINT RHN_AVSM_CREAT_NN;
ALTER TABLE RHNACTIONVIRTSETMEMORY MODIFY CREATED NOT NULL;

--
-- RHNACTIONVIRTSETMEMORY
--
ALTER TABLE RHNACTIONVIRTSETMEMORY DROP CONSTRAINT RHN_AVSM_MEM_NN;
ALTER TABLE RHNACTIONVIRTSETMEMORY MODIFY MEMORY NOT NULL;

--
-- RHNACTIONVIRTSETMEMORY
--
ALTER TABLE RHNACTIONVIRTSETMEMORY DROP CONSTRAINT RHN_AVSM_MOD_NN;
ALTER TABLE RHNACTIONVIRTSETMEMORY MODIFY MODIFIED NOT NULL;

--
-- RHNACTIONVIRTSETMEMORY
--
ALTER TABLE RHNACTIONVIRTSETMEMORY DROP CONSTRAINT RHN_AVSM_UUID_NN;
ALTER TABLE RHNACTIONVIRTSETMEMORY MODIFY UUID NOT NULL;

--
-- RHNACTIONVIRTSCHEDULEPOLLER
--
ALTER TABLE RHNACTIONVIRTSCHEDULEPOLLER DROP CONSTRAINT RHN_AVSP_AID_NN;
ALTER TABLE RHNACTIONVIRTSCHEDULEPOLLER MODIFY ACTION_ID NOT NULL;

--
-- RHNACTIONVIRTSCHEDULEPOLLER
--
ALTER TABLE RHNACTIONVIRTSCHEDULEPOLLER DROP CONSTRAINT RHN_AVSP_CREAT_NN;
ALTER TABLE RHNACTIONVIRTSCHEDULEPOLLER MODIFY CREATED NOT NULL;

--
-- RHNACTIONVIRTSCHEDULEPOLLER
--
ALTER TABLE RHNACTIONVIRTSCHEDULEPOLLER DROP CONSTRAINT RHN_AVSP_MOD_NN;
ALTER TABLE RHNACTIONVIRTSCHEDULEPOLLER MODIFY MODIFIED NOT NULL;

--
-- RHNACTIONVIRTSTART
--
ALTER TABLE RHNACTIONVIRTSTART DROP CONSTRAINT RHN_AVSTART_AID_NN;
ALTER TABLE RHNACTIONVIRTSTART MODIFY ACTION_ID NOT NULL;

--
-- RHNACTIONVIRTSTART
--
ALTER TABLE RHNACTIONVIRTSTART DROP CONSTRAINT RHN_AVSTART_CREAT_NN;
ALTER TABLE RHNACTIONVIRTSTART MODIFY CREATED NOT NULL;

--
-- RHNACTIONVIRTSTART
--
ALTER TABLE RHNACTIONVIRTSTART DROP CONSTRAINT RHN_AVSTART_MOD_NN;
ALTER TABLE RHNACTIONVIRTSTART MODIFY MODIFIED NOT NULL;

--
-- RHNACTIONVIRTSTART
--
ALTER TABLE RHNACTIONVIRTSTART DROP CONSTRAINT RHN_AVSTART_UUID_NN;
ALTER TABLE RHNACTIONVIRTSTART MODIFY UUID NOT NULL;

--
-- RHNACTIONVIRTSUSPEND
--
ALTER TABLE RHNACTIONVIRTSUSPEND DROP CONSTRAINT RHN_AVSUSPEND_AID_NN;
ALTER TABLE RHNACTIONVIRTSUSPEND MODIFY ACTION_ID NOT NULL;

--
-- RHNACTIONVIRTSUSPEND
--
ALTER TABLE RHNACTIONVIRTSUSPEND DROP CONSTRAINT RHN_AVSUSPEND_CREAT_NN;
ALTER TABLE RHNACTIONVIRTSUSPEND MODIFY CREATED NOT NULL;

--
-- RHNACTIONVIRTSUSPEND
--
ALTER TABLE RHNACTIONVIRTSUSPEND DROP CONSTRAINT RHN_AVSUSPEND_MOD_NN;
ALTER TABLE RHNACTIONVIRTSUSPEND MODIFY MODIFIED NOT NULL;

--
-- RHNACTIONVIRTSUSPEND
--
ALTER TABLE RHNACTIONVIRTSUSPEND DROP CONSTRAINT RHN_AVSUSPEND_UUID_NN;
ALTER TABLE RHNACTIONVIRTSUSPEND MODIFY UUID NOT NULL;

--
-- RHNBEEHIVEPATHMAP
--
ALTER TABLE RHNBEEHIVEPATHMAP DROP CONSTRAINT RHN_BEEHIVE_PATH_MAP_BP_NN;
ALTER TABLE RHNBEEHIVEPATHMAP MODIFY BEEHIVE_PATH NOT NULL;

--
-- RHNBEEHIVEPATHMAP
--
ALTER TABLE RHNBEEHIVEPATHMAP DROP CONSTRAINT RHN_BEEHIVE_PATH_MAP_FP_NN;
ALTER TABLE RHNBEEHIVEPATHMAP MODIFY FTP_PATH NOT NULL;

--
-- RHNBEEHIVEPATHMAP
--
ALTER TABLE RHNBEEHIVEPATHMAP DROP CONSTRAINT RHN_BEEHIVE_PATH_MAP_P_NN;
ALTER TABLE RHNBEEHIVEPATHMAP MODIFY PATH NOT NULL;

--
-- RHNBLACKLISTOBSOLETES
--
ALTER TABLE RHNBLACKLISTOBSOLETES DROP CONSTRAINT RHN_BL_OBS_CREATED_NN;
ALTER TABLE RHNBLACKLISTOBSOLETES MODIFY CREATED NOT NULL;

--
-- RHNBLACKLISTOBSOLETES
--
ALTER TABLE RHNBLACKLISTOBSOLETES DROP CONSTRAINT RHN_BL_OBS_EID_NN;
ALTER TABLE RHNBLACKLISTOBSOLETES MODIFY EVR_ID NOT NULL;

--
-- RHNBLACKLISTOBSOLETES
--
ALTER TABLE RHNBLACKLISTOBSOLETES DROP CONSTRAINT RHN_BL_OBS_INID_NN;
ALTER TABLE RHNBLACKLISTOBSOLETES MODIFY IGNORE_NAME_ID NOT NULL;

--
-- RHNBLACKLISTOBSOLETES
--
ALTER TABLE RHNBLACKLISTOBSOLETES DROP CONSTRAINT RHN_BL_OBS_MODIFIED_NN;
ALTER TABLE RHNBLACKLISTOBSOLETES MODIFY MODIFIED NOT NULL;

--
-- RHNBLACKLISTOBSOLETES
--
ALTER TABLE RHNBLACKLISTOBSOLETES DROP CONSTRAINT RHN_BL_OBS_NID_NN;
ALTER TABLE RHNBLACKLISTOBSOLETES MODIFY NAME_ID NOT NULL;

--
-- RHNBLACKLISTOBSOLETES
--
ALTER TABLE RHNBLACKLISTOBSOLETES DROP CONSTRAINT RHN_BL_OBS_PAID_NN;
ALTER TABLE RHNBLACKLISTOBSOLETES MODIFY PACKAGE_ARCH_ID NOT NULL;

--
-- RHNCHANNELARCH
--
ALTER TABLE RHNCHANNELARCH DROP CONSTRAINT RHN_CARCH_ATID_NN;
ALTER TABLE RHNCHANNELARCH MODIFY ARCH_TYPE_ID NOT NULL;

--
-- RHNCHANNELARCH
--
ALTER TABLE RHNCHANNELARCH DROP CONSTRAINT RHN_CARCH_CREATED_NN;
ALTER TABLE RHNCHANNELARCH MODIFY CREATED NOT NULL;

--
-- RHNCHANNELARCH
--
ALTER TABLE RHNCHANNELARCH DROP CONSTRAINT RHN_CARCH_ID_NN;
ALTER TABLE RHNCHANNELARCH MODIFY ID NOT NULL;

--
-- RHNCHANNELARCH
--
ALTER TABLE RHNCHANNELARCH DROP CONSTRAINT RHN_CARCH_LABEL_NN;
ALTER TABLE RHNCHANNELARCH MODIFY LABEL NOT NULL;

--
-- RHNCHANNELARCH
--
ALTER TABLE RHNCHANNELARCH DROP CONSTRAINT RHN_CARCH_MODIFIED_NN;
ALTER TABLE RHNCHANNELARCH MODIFY MODIFIED NOT NULL;

--
-- RHNCHANNELARCH
--
ALTER TABLE RHNCHANNELARCH DROP CONSTRAINT RHN_CARCH_NAME_NN;
ALTER TABLE RHNCHANNELARCH MODIFY NAME NOT NULL;

--
-- RHNCUSTOMDATAKEY
--
ALTER TABLE RHNCUSTOMDATAKEY DROP CONSTRAINT RHN_CDATAKEY_CREATED_NN;
ALTER TABLE RHNCUSTOMDATAKEY MODIFY CREATED NOT NULL;

--
-- RHNCUSTOMDATAKEY
--
ALTER TABLE RHNCUSTOMDATAKEY DROP CONSTRAINT RHN_CDATAKEY_DESC_NN;
ALTER TABLE RHNCUSTOMDATAKEY MODIFY DESCRIPTION NOT NULL;

--
-- RHNCUSTOMDATAKEY
--
ALTER TABLE RHNCUSTOMDATAKEY DROP CONSTRAINT RHN_CDATAKEY_ID_NN;
ALTER TABLE RHNCUSTOMDATAKEY MODIFY ID NOT NULL;

--
-- RHNCUSTOMDATAKEY
--
ALTER TABLE RHNCUSTOMDATAKEY DROP CONSTRAINT RHN_CDATAKEY_LABEL_NN;
ALTER TABLE RHNCUSTOMDATAKEY MODIFY LABEL NOT NULL;

--
-- RHNCUSTOMDATAKEY
--
ALTER TABLE RHNCUSTOMDATAKEY DROP CONSTRAINT RHN_CDATAKEY_MODIFIED_NN;
ALTER TABLE RHNCUSTOMDATAKEY MODIFY MODIFIED NOT NULL;

--
-- RHNCUSTOMDATAKEY
--
ALTER TABLE RHNCUSTOMDATAKEY DROP CONSTRAINT RHN_CDATAKEY_OID_NN;
ALTER TABLE RHNCUSTOMDATAKEY MODIFY ORG_ID NOT NULL;

--
-- RHNCHANNELDOWNLOADS
--
ALTER TABLE RHNCHANNELDOWNLOADS DROP CONSTRAINT RHN_CD_CID_NN;
ALTER TABLE RHNCHANNELDOWNLOADS MODIFY CHANNEL_ID NOT NULL;

--
-- RHNCHANNELDOWNLOADS
--
ALTER TABLE RHNCHANNELDOWNLOADS DROP CONSTRAINT RHN_CD_CREATED_NN;
ALTER TABLE RHNCHANNELDOWNLOADS MODIFY CREATED NOT NULL;

--
-- RHNCHANNELDOWNLOADS
--
ALTER TABLE RHNCHANNELDOWNLOADS DROP CONSTRAINT RHN_CD_DID_NN;
ALTER TABLE RHNCHANNELDOWNLOADS MODIFY DOWNLOADS_ID NOT NULL;

--
-- RHNCHANNELDOWNLOADS
--
ALTER TABLE RHNCHANNELDOWNLOADS DROP CONSTRAINT RHN_CD_MODIFIED_NN;
ALTER TABLE RHNCHANNELDOWNLOADS MODIFY MODIFIED NOT NULL;

--
-- RHNCHANNELERRATA
--
ALTER TABLE RHNCHANNELERRATA DROP CONSTRAINT RHN_CE_CID_NN;
ALTER TABLE RHNCHANNELERRATA MODIFY CHANNEL_ID NOT NULL;

--
-- RHNCHANNELERRATA
--
ALTER TABLE RHNCHANNELERRATA DROP CONSTRAINT RHN_CE_CREATED_NN;
ALTER TABLE RHNCHANNELERRATA MODIFY CREATED NOT NULL;

--
-- RHNCHANNELERRATA
--
ALTER TABLE RHNCHANNELERRATA DROP CONSTRAINT RHN_CE_EID_NN;
ALTER TABLE RHNCHANNELERRATA MODIFY ERRATA_ID NOT NULL;

--
-- RHNCHANNELERRATA
--
ALTER TABLE RHNCHANNELERRATA DROP CONSTRAINT RHN_CE_MODIFIED_NN;
ALTER TABLE RHNCHANNELERRATA MODIFY MODIFIED NOT NULL;

--
-- RHNCHANNELFAMILYLICENSE
--
ALTER TABLE RHNCHANNELFAMILYLICENSE DROP CONSTRAINT RHN_CFL_CFID_NN;
ALTER TABLE RHNCHANNELFAMILYLICENSE MODIFY CHANNEL_FAMILY_ID NOT NULL;

--
-- RHNCHANNELFAMILYLICENSECONSENT
--
ALTER TABLE RHNCHANNELFAMILYLICENSECONSENT DROP CONSTRAINT RHN_CFL_CONSENT_CFID_NN;
ALTER TABLE RHNCHANNELFAMILYLICENSECONSENT MODIFY CHANNEL_FAMILY_ID NOT NULL;

--
-- RHNCHANNELFAMILYLICENSECONSENT
--
ALTER TABLE RHNCHANNELFAMILYLICENSECONSENT DROP CONSTRAINT RHN_CFL_CONSENT_CREATED_NN;
ALTER TABLE RHNCHANNELFAMILYLICENSECONSENT MODIFY CREATED NOT NULL;

--
-- RHNCHANNELFAMILYLICENSECONSENT
--
ALTER TABLE RHNCHANNELFAMILYLICENSECONSENT DROP CONSTRAINT RHN_CFL_CONSENT_MODIFIED_NN;
ALTER TABLE RHNCHANNELFAMILYLICENSECONSENT MODIFY MODIFIED NOT NULL;

--
-- RHNCHANNELFAMILYLICENSECONSENT
--
ALTER TABLE RHNCHANNELFAMILYLICENSECONSENT DROP CONSTRAINT RHN_CFL_CONSENT_SID_NN;
ALTER TABLE RHNCHANNELFAMILYLICENSECONSENT MODIFY SERVER_ID NOT NULL;

--
-- RHNCHANNELFAMILYLICENSECONSENT
--
ALTER TABLE RHNCHANNELFAMILYLICENSECONSENT DROP CONSTRAINT RHN_CFL_CONSENT_UID_NN;
ALTER TABLE RHNCHANNELFAMILYLICENSECONSENT MODIFY USER_ID NOT NULL;

--
-- RHNCHANNELFAMILYLICENSE
--
ALTER TABLE RHNCHANNELFAMILYLICENSE DROP CONSTRAINT RHN_CFL_CREATED_NN;
ALTER TABLE RHNCHANNELFAMILYLICENSE MODIFY CREATED NOT NULL;

--
-- RHNCHANNELFAMILYLICENSE
--
ALTER TABLE RHNCHANNELFAMILYLICENSE DROP CONSTRAINT RHN_CFL_LICENSE_NN;
ALTER TABLE RHNCHANNELFAMILYLICENSE MODIFY LICENSE_PATH NOT NULL;

--
-- RHNCHANNELFAMILYLICENSE
--
ALTER TABLE RHNCHANNELFAMILYLICENSE DROP CONSTRAINT RHN_CFL_MODIFIED_NN;
ALTER TABLE RHNCHANNELFAMILYLICENSE MODIFY MODIFIED NOT NULL;

--
-- RHNCONFIGFILENAME
--
ALTER TABLE RHNCONFIGFILENAME DROP CONSTRAINT RHN_CFNAME_CREATED_NN;
ALTER TABLE RHNCONFIGFILENAME MODIFY CREATED NOT NULL;

--
-- RHNCONFIGFILENAME
--
ALTER TABLE RHNCONFIGFILENAME DROP CONSTRAINT RHN_CFNAME_ID_NN;
ALTER TABLE RHNCONFIGFILENAME MODIFY ID NOT NULL;

--
-- RHNCONFIGFILENAME
--
ALTER TABLE RHNCONFIGFILENAME DROP CONSTRAINT RHN_CFNAME_MODIFIED_NN;
ALTER TABLE RHNCONFIGFILENAME MODIFY MODIFIED NOT NULL;

--
-- RHNCONFIGFILENAME
--
ALTER TABLE RHNCONFIGFILENAME DROP CONSTRAINT RHN_CFNAME_PATH_NN;
ALTER TABLE RHNCONFIGFILENAME MODIFY PATH NOT NULL;

--
-- RHNCONFIGFILESTATE
--
ALTER TABLE RHNCONFIGFILESTATE DROP CONSTRAINT RHN_CFSTATE_CREAT_NN;
ALTER TABLE RHNCONFIGFILESTATE MODIFY CREATED NOT NULL;

--
-- RHNCONFIGFILESTATE
--
ALTER TABLE RHNCONFIGFILESTATE DROP CONSTRAINT RHN_CFSTATE_ID_NN;
ALTER TABLE RHNCONFIGFILESTATE MODIFY ID NOT NULL;

--
-- RHNCONFIGFILESTATE
--
ALTER TABLE RHNCONFIGFILESTATE DROP CONSTRAINT RHN_CFSTATE_LABEL_NN;
ALTER TABLE RHNCONFIGFILESTATE MODIFY LABEL NOT NULL;

--
-- RHNCONFIGFILESTATE
--
ALTER TABLE RHNCONFIGFILESTATE DROP CONSTRAINT RHN_CFSTATE_MOD_NN;
ALTER TABLE RHNCONFIGFILESTATE MODIFY MODIFIED NOT NULL;

--
-- RHNCONFIGFILESTATE
--
ALTER TABLE RHNCONFIGFILESTATE DROP CONSTRAINT RHN_CFSTATE_NAME_NN;
ALTER TABLE RHNCONFIGFILESTATE MODIFY NAME NOT NULL;

--
-- RHNCHANNELFAMILYVIRTSUBLEVEL
--
ALTER TABLE RHNCHANNELFAMILYVIRTSUBLEVEL DROP CONSTRAINT RHN_CFVSL_CFID_NN;
ALTER TABLE RHNCHANNELFAMILYVIRTSUBLEVEL MODIFY CHANNEL_FAMILY_ID NOT NULL;

--
-- RHNCHANNELFAMILYVIRTSUBLEVEL
--
ALTER TABLE RHNCHANNELFAMILYVIRTSUBLEVEL DROP CONSTRAINT RHN_CFVSL_CREATED_NN;
ALTER TABLE RHNCHANNELFAMILYVIRTSUBLEVEL MODIFY CREATED NOT NULL;

--
-- RHNCHANNELFAMILYVIRTSUBLEVEL
--
ALTER TABLE RHNCHANNELFAMILYVIRTSUBLEVEL DROP CONSTRAINT RHN_CFVSL_MODIFIED_NN;
ALTER TABLE RHNCHANNELFAMILYVIRTSUBLEVEL MODIFY MODIFIED NOT NULL;

--
-- RHNCHANNELFAMILYVIRTSUBLEVEL
--
ALTER TABLE RHNCHANNELFAMILYVIRTSUBLEVEL DROP CONSTRAINT RHN_CFVSL_VSLID_NN;
ALTER TABLE RHNCHANNELFAMILYVIRTSUBLEVEL MODIFY VIRT_SUB_LEVEL_ID NOT NULL;

--
-- RHNCHANNELFAMILYMEMBERS
--
ALTER TABLE RHNCHANNELFAMILYMEMBERS DROP CONSTRAINT RHN_CF_FAMILY_NN;
ALTER TABLE RHNCHANNELFAMILYMEMBERS MODIFY CHANNEL_FAMILY_ID NOT NULL;

--
-- RHNCHANNELFAMILYMEMBERS
--
ALTER TABLE RHNCHANNELFAMILYMEMBERS DROP CONSTRAINT RHN_CF_MEMBERS_C_NN;
ALTER TABLE RHNCHANNELFAMILYMEMBERS MODIFY CHANNEL_ID NOT NULL;

--
-- RHNCHANNELFAMILYMEMBERS
--
ALTER TABLE RHNCHANNELFAMILYMEMBERS DROP CONSTRAINT RHN_CF_MEMBER_CRE_NN;
ALTER TABLE RHNCHANNELFAMILYMEMBERS MODIFY CREATED NOT NULL;

--
-- RHNCHANNELFAMILYMEMBERS
--
ALTER TABLE RHNCHANNELFAMILYMEMBERS DROP CONSTRAINT RHN_CF_MEMBER_MOD_NN;
ALTER TABLE RHNCHANNELFAMILYMEMBERS MODIFY MODIFIED NOT NULL;

--
-- RHNCHANNELCLONED
--
ALTER TABLE RHNCHANNELCLONED DROP CONSTRAINT RHN_CHANNELCLONE_CREATED_NN;
ALTER TABLE RHNCHANNELCLONED MODIFY CREATED NOT NULL;

--
-- RHNCHANNELCLONED
--
ALTER TABLE RHNCHANNELCLONED DROP CONSTRAINT RHN_CHANNELCLONE_FCID_NN;
ALTER TABLE RHNCHANNELCLONED MODIFY ORIGINAL_ID NOT NULL;

--
-- RHNCHANNELCLONED
--
ALTER TABLE RHNCHANNELCLONED DROP CONSTRAINT RHN_CHANNELCLONE_MODIFIED_NN;
ALTER TABLE RHNCHANNELCLONED MODIFY MODIFIED NOT NULL;

--
-- RHNCHANNELCLONED
--
ALTER TABLE RHNCHANNELCLONED DROP CONSTRAINT RHN_CHANNELCLONE_TCID_NN;
ALTER TABLE RHNCHANNELCLONED MODIFY ID NOT NULL;

--
-- RHNCHANNELCOMPS
--
ALTER TABLE RHNCHANNELCOMPS DROP CONSTRAINT RHN_CHANNELCOMPS_CID_NN;
ALTER TABLE RHNCHANNELCOMPS MODIFY CHANNEL_ID NOT NULL;

--
-- RHNCHANNELCOMPS
--
ALTER TABLE RHNCHANNELCOMPS DROP CONSTRAINT RHN_CHANNELCOMPS_CREATED_NN;
ALTER TABLE RHNCHANNELCOMPS MODIFY CREATED NOT NULL;

--
-- RHNCHANNELCOMPS
--
ALTER TABLE RHNCHANNELCOMPS DROP CONSTRAINT RHN_CHANNELCOMPS_ID_NN;
ALTER TABLE RHNCHANNELCOMPS MODIFY ID NOT NULL;

--
-- RHNCHANNELCOMPS
--
ALTER TABLE RHNCHANNELCOMPS DROP CONSTRAINT RHN_CHANNELCOMPS_LASTMOD_NN;
ALTER TABLE RHNCHANNELCOMPS MODIFY LAST_MODIFIED NOT NULL;

--
-- RHNCHANNELCOMPS
--
ALTER TABLE RHNCHANNELCOMPS DROP CONSTRAINT RHN_CHANNELCOMPS_MODIFIED_NN;
ALTER TABLE RHNCHANNELCOMPS MODIFY MODIFIED NOT NULL;

--
-- RHNCHANNELCOMPS
--
ALTER TABLE RHNCHANNELCOMPS DROP CONSTRAINT RHN_CHANNELCOMPS_RFN_NN;
ALTER TABLE RHNCHANNELCOMPS MODIFY RELATIVE_FILENAME NOT NULL;

--
-- RHNCHANNELPRODUCT
--
ALTER TABLE RHNCHANNELPRODUCT DROP CONSTRAINT RHN_CHANNELPROD_BETA_NN;
ALTER TABLE RHNCHANNELPRODUCT MODIFY BETA NOT NULL;

--
-- RHNCHANNELPRODUCT
--
ALTER TABLE RHNCHANNELPRODUCT DROP CONSTRAINT RHN_CHANNELPROD_CREATED_NN;
ALTER TABLE RHNCHANNELPRODUCT MODIFY CREATED NOT NULL;

--
-- RHNCHANNELPRODUCT
--
ALTER TABLE RHNCHANNELPRODUCT DROP CONSTRAINT RHN_CHANNELPROD_ID_NN;
ALTER TABLE RHNCHANNELPRODUCT MODIFY ID NOT NULL;

--
-- RHNCHANNELPRODUCT
--
ALTER TABLE RHNCHANNELPRODUCT DROP CONSTRAINT RHN_CHANNELPROD_MODIFIED_NN;
ALTER TABLE RHNCHANNELPRODUCT MODIFY MODIFIED NOT NULL;

--
-- RHNCHANNELPRODUCT
--
ALTER TABLE RHNCHANNELPRODUCT DROP CONSTRAINT RHN_CHANNELPROD_PRODUCT_NN;
ALTER TABLE RHNCHANNELPRODUCT MODIFY PRODUCT NOT NULL;

--
-- RHNCHANNELPRODUCT
--
ALTER TABLE RHNCHANNELPRODUCT DROP CONSTRAINT RHN_CHANNELPROD_VERSION_NN;
ALTER TABLE RHNCHANNELPRODUCT MODIFY VERSION NOT NULL;

--
-- RHNCHANNEL
--
ALTER TABLE RHNCHANNEL DROP CONSTRAINT RHN_CHANNEL_BASEDIR_NN;
ALTER TABLE RHNCHANNEL MODIFY BASEDIR NOT NULL;

--
-- RHNCHANNEL
--
ALTER TABLE RHNCHANNEL DROP CONSTRAINT RHN_CHANNEL_CAID_NN;
ALTER TABLE RHNCHANNEL MODIFY CHANNEL_ARCH_ID NOT NULL;

--
-- RHNCHANNEL
--
ALTER TABLE RHNCHANNEL DROP CONSTRAINT RHN_CHANNEL_CREATED_NN;
ALTER TABLE RHNCHANNEL MODIFY CREATED NOT NULL;

--
-- RHNCHANNELFAMILY
--
ALTER TABLE RHNCHANNELFAMILY DROP CONSTRAINT RHN_CHANNEL_FAMILY_CREATED_NN;
ALTER TABLE RHNCHANNELFAMILY MODIFY CREATED NOT NULL;

--
-- RHNCHANNELFAMILY
--
ALTER TABLE RHNCHANNELFAMILY DROP CONSTRAINT RHN_CHANNEL_FAMILY_ID_NN;
ALTER TABLE RHNCHANNELFAMILY MODIFY ID NOT NULL;

--
-- RHNCHANNELFAMILY
--
ALTER TABLE RHNCHANNELFAMILY DROP CONSTRAINT RHN_CHANNEL_FAMILY_LABEL_NN;
ALTER TABLE RHNCHANNELFAMILY MODIFY LABEL NOT NULL;

--
-- RHNCHANNELFAMILY
--
ALTER TABLE RHNCHANNELFAMILY DROP CONSTRAINT RHN_CHANNEL_FAMILY_MODIFIED_NN;
ALTER TABLE RHNCHANNELFAMILY MODIFY MODIFIED NOT NULL;

--
-- RHNCHANNELFAMILY
--
ALTER TABLE RHNCHANNELFAMILY DROP CONSTRAINT RHN_CHANNEL_FAMILY_NAME_NN;
ALTER TABLE RHNCHANNELFAMILY MODIFY NAME NOT NULL;

--
-- RHNCHANNELFAMILY
--
ALTER TABLE RHNCHANNELFAMILY DROP CONSTRAINT RHN_CHANNEL_FAMILY_URL_NN;
ALTER TABLE RHNCHANNELFAMILY MODIFY PRODUCT_URL NOT NULL;

--
-- RHNCHANNEL
--
ALTER TABLE RHNCHANNEL DROP CONSTRAINT RHN_CHANNEL_ID_NN;
ALTER TABLE RHNCHANNEL MODIFY ID NOT NULL;

--
-- RHNCHANNEL
--
ALTER TABLE RHNCHANNEL DROP CONSTRAINT RHN_CHANNEL_LABEL_NN;
ALTER TABLE RHNCHANNEL MODIFY LABEL NOT NULL;

--
-- RHNCHANNEL
--
ALTER TABLE RHNCHANNEL DROP CONSTRAINT RHN_CHANNEL_LM_NN;
ALTER TABLE RHNCHANNEL MODIFY LAST_MODIFIED NOT NULL;

--
-- RHNCHANNEL
--
ALTER TABLE RHNCHANNEL DROP CONSTRAINT RHN_CHANNEL_MODIFIED_NN;
ALTER TABLE RHNCHANNEL MODIFY MODIFIED NOT NULL;

--
-- RHNCHANNEL
--
ALTER TABLE RHNCHANNEL DROP CONSTRAINT RHN_CHANNEL_NAME_NN;
ALTER TABLE RHNCHANNEL MODIFY NAME NOT NULL;

--
-- RHNCHANNEL
--
ALTER TABLE RHNCHANNEL DROP CONSTRAINT RHN_CHANNEL_RU_NN;
ALTER TABLE RHNCHANNEL MODIFY RECEIVING_UPDATES NOT NULL;

--
-- RHNCHANNEL
--
ALTER TABLE RHNCHANNEL DROP CONSTRAINT RHN_CHANNEL_SUMMARY_NN;
ALTER TABLE RHNCHANNEL MODIFY SUMMARY NOT NULL;

--
-- RHNCHANNELTRUST
--
ALTER TABLE RHNCHANNELTRUST DROP CONSTRAINT RHN_CHANNEL_TRUST_CID_NN;
ALTER TABLE RHNCHANNELTRUST MODIFY CHANNEL_ID NOT NULL;

--
-- RHNCHANNELTRUST
--
ALTER TABLE RHNCHANNELTRUST DROP CONSTRAINT RHN_CHANNEL_TRUST_CREATED_NN;
ALTER TABLE RHNCHANNELTRUST MODIFY CREATED NOT NULL;

--
-- RHNCHANNELTRUST
--
ALTER TABLE RHNCHANNELTRUST DROP CONSTRAINT RHN_CHANNEL_TRUST_MODIFIED_NN;
ALTER TABLE RHNCHANNELTRUST MODIFY MODIFIED NOT NULL;

--
-- RHNCHANNELTRUST
--
ALTER TABLE RHNCHANNELTRUST DROP CONSTRAINT RHN_CHANNEL_TRUST_OTID_NN;
ALTER TABLE RHNCHANNELTRUST MODIFY ORG_TRUST_ID NOT NULL;

--
-- RHN_CHECK_PROBE
--
ALTER TABLE RHN_CHECK_PROBE DROP CONSTRAINT RHN_CHKPB_PROBE_ID_NN;
ALTER TABLE RHN_CHECK_PROBE MODIFY PROBE_ID NOT NULL;

--
-- RHN_CHECK_PROBE
--
ALTER TABLE RHN_CHECK_PROBE DROP CONSTRAINT RHN_CHK_HOST_ID_NN;
ALTER TABLE RHN_CHECK_PROBE MODIFY HOST_ID NOT NULL;

--
-- RHN_CHECK_PROBE
--
ALTER TABLE RHN_CHECK_PROBE DROP CONSTRAINT RHN_CHK_PROBE_TYPE_NN;
ALTER TABLE RHN_CHECK_PROBE MODIFY PROBE_TYPE NOT NULL;

--
-- RHN_CHECK_PROBE
--
ALTER TABLE RHN_CHECK_PROBE DROP CONSTRAINT RHN_CHK_SAT_CLUSTER_ID_NN;
ALTER TABLE RHN_CHECK_PROBE MODIFY SAT_CLUSTER_ID NOT NULL;

--
-- RHNCHANNELPARENT
--
ALTER TABLE RHNCHANNELPARENT DROP CONSTRAINT RHN_CHP_CREATED_NN;
ALTER TABLE RHNCHANNELPARENT MODIFY CREATED NOT NULL;

--
-- RHNCHANNELPARENT
--
ALTER TABLE RHNCHANNELPARENT DROP CONSTRAINT RHN_CHP_MODIFIED_NN;
ALTER TABLE RHNCHANNELPARENT MODIFY MODIFIED NOT NULL;

--
-- RHNCRYPTOKEYKICKSTART
--
ALTER TABLE RHNCRYPTOKEYKICKSTART DROP CONSTRAINT RHN_CKEY_KS_CKID_NN;
ALTER TABLE RHNCRYPTOKEYKICKSTART MODIFY CRYPTO_KEY_ID NOT NULL;

--
-- RHNCRYPTOKEYKICKSTART
--
ALTER TABLE RHNCRYPTOKEYKICKSTART DROP CONSTRAINT RHN_CKEY_KS_KSD_NN;
ALTER TABLE RHNCRYPTOKEYKICKSTART MODIFY KSDATA_ID NOT NULL;

--
-- RHN_CHECK_SUITE_PROBE
--
ALTER TABLE RHN_CHECK_SUITE_PROBE DROP CONSTRAINT RHN_CKSPB_CHECK_SUITE_ID_NN;
ALTER TABLE RHN_CHECK_SUITE_PROBE MODIFY CHECK_SUITE_ID NOT NULL;

--
-- RHN_CHECK_SUITE_PROBE
--
ALTER TABLE RHN_CHECK_SUITE_PROBE DROP CONSTRAINT RHN_CKSPB_PROBE_ID_NN;
ALTER TABLE RHN_CHECK_SUITE_PROBE MODIFY PROBE_ID NOT NULL;

--
-- RHN_CHECK_SUITE_PROBE
--
ALTER TABLE RHN_CHECK_SUITE_PROBE DROP CONSTRAINT RHN_CKSPB_PROBE_TYPE_NN;
ALTER TABLE RHN_CHECK_SUITE_PROBE MODIFY PROBE_TYPE NOT NULL;

--
-- RHN_CHECK_SUITES
--
ALTER TABLE RHN_CHECK_SUITES DROP CONSTRAINT RHN_CKSUT_CUSTID_NN;
ALTER TABLE RHN_CHECK_SUITES MODIFY CUSTOMER_ID NOT NULL;

--
-- RHN_CHECK_SUITES
--
ALTER TABLE RHN_CHECK_SUITES DROP CONSTRAINT RHN_CKSUT_LAST_DATE_NN;
ALTER TABLE RHN_CHECK_SUITES MODIFY LAST_UPDATE_DATE NOT NULL;

--
-- RHN_CHECK_SUITES
--
ALTER TABLE RHN_CHECK_SUITES DROP CONSTRAINT RHN_CKSUT_LAST_USER_NN;
ALTER TABLE RHN_CHECK_SUITES MODIFY LAST_UPDATE_USER NOT NULL;

--
-- RHN_CHECK_SUITES
--
ALTER TABLE RHN_CHECK_SUITES DROP CONSTRAINT RHN_CKSUT_RECID_NN;
ALTER TABLE RHN_CHECK_SUITES MODIFY RECID NOT NULL;

--
-- RHN_CHECK_SUITES
--
ALTER TABLE RHN_CHECK_SUITES DROP CONSTRAINT RHN_CKSUT_SUITE_NAME_NN;
ALTER TABLE RHN_CHECK_SUITES MODIFY SUITE_NAME NOT NULL;

--
-- RHNCLIENTCAPABILITYNAME
--
ALTER TABLE RHNCLIENTCAPABILITYNAME DROP CONSTRAINT RHN_CLIENTCAPNAM_ID_NN;
ALTER TABLE RHNCLIENTCAPABILITYNAME MODIFY ID NOT NULL;

--
-- RHNCLIENTCAPABILITYNAME
--
ALTER TABLE RHNCLIENTCAPABILITYNAME DROP CONSTRAINT RHN_CLIENTCAPNAM_NAME_NN;
ALTER TABLE RHNCLIENTCAPABILITYNAME MODIFY NAME NOT NULL;

--
-- RHNCLIENTCAPABILITY
--
ALTER TABLE RHNCLIENTCAPABILITY DROP CONSTRAINT RHN_CLIENTCAP_CAP_NID_NN;
ALTER TABLE RHNCLIENTCAPABILITY MODIFY CAPABILITY_NAME_ID NOT NULL;

--
-- RHNCLIENTCAPABILITY
--
ALTER TABLE RHNCLIENTCAPABILITY DROP CONSTRAINT RHN_CLIENTCAP_CREATED_NN;
ALTER TABLE RHNCLIENTCAPABILITY MODIFY CREATED NOT NULL;

--
-- RHNCLIENTCAPABILITY
--
ALTER TABLE RHNCLIENTCAPABILITY DROP CONSTRAINT RHN_CLIENTCAP_MODIFIED_NN;
ALTER TABLE RHNCLIENTCAPABILITY MODIFY MODIFIED NOT NULL;

--
-- RHNCLIENTCAPABILITY
--
ALTER TABLE RHNCLIENTCAPABILITY DROP CONSTRAINT RHN_CLIENTCAP_SID_NN;
ALTER TABLE RHNCLIENTCAPABILITY MODIFY SERVER_ID NOT NULL;

--
-- RHNCLIENTCAPABILITY
--
ALTER TABLE RHNCLIENTCAPABILITY DROP CONSTRAINT RHN_CLIENTCAP_VER_NN;
ALTER TABLE RHNCLIENTCAPABILITY MODIFY VERSION NOT NULL;

--
-- RHN_COMMAND_CENTER_STATE
--
ALTER TABLE RHN_COMMAND_CENTER_STATE DROP CONSTRAINT RHN_CMDCS_ALLOWED_NN;
ALTER TABLE RHN_COMMAND_CENTER_STATE MODIFY CUST_ADMIN_ACCESS_ALLOWED NOT NULL;

--
-- RHN_COMMAND_CENTER_STATE
--
ALTER TABLE RHN_COMMAND_CENTER_STATE DROP CONSTRAINT RHN_CMDCS_LAST_DATE_NN;
ALTER TABLE RHN_COMMAND_CENTER_STATE MODIFY LAST_UPDATE_DATE NOT NULL;

--
-- RHN_COMMAND_CENTER_STATE
--
ALTER TABLE RHN_COMMAND_CENTER_STATE DROP CONSTRAINT RHN_CMDCS_LAST_USER_NN;
ALTER TABLE RHN_COMMAND_CENTER_STATE MODIFY LAST_UPDATE_USER NOT NULL;

--
-- RHN_COMMAND_CENTER_STATE
--
ALTER TABLE RHN_COMMAND_CENTER_STATE DROP CONSTRAINT RHN_CMDCS_REASON_NN;
ALTER TABLE RHN_COMMAND_CENTER_STATE MODIFY REASON NOT NULL;

--
-- RHN_COMMAND_GROUPS
--
ALTER TABLE RHN_COMMAND_GROUPS DROP CONSTRAINT RHN_CMDGR_GROUP_NAME_NN;
ALTER TABLE RHN_COMMAND_GROUPS MODIFY GROUP_NAME NOT NULL;

--
-- RHN_COMMAND_TARGET
--
ALTER TABLE RHN_COMMAND_TARGET DROP CONSTRAINT RHN_CMDTG_CUST_ID_NN;
ALTER TABLE RHN_COMMAND_TARGET MODIFY CUSTOMER_ID NOT NULL;

--
-- RHN_COMMAND_TARGET
--
ALTER TABLE RHN_COMMAND_TARGET DROP CONSTRAINT RHN_CMDTG_RECID_NN;
ALTER TABLE RHN_COMMAND_TARGET MODIFY RECID NOT NULL;

--
-- RHN_COMMAND_TARGET
--
ALTER TABLE RHN_COMMAND_TARGET DROP CONSTRAINT RHN_CMDTG_TARGET_TY_NN;
ALTER TABLE RHN_COMMAND_TARGET MODIFY TARGET_TYPE NOT NULL;

--
-- RHN_CONTACT_METHODS
--
ALTER TABLE RHN_CONTACT_METHODS DROP CONSTRAINT RHN_CMETH_CONTACT_ID_NN;
ALTER TABLE RHN_CONTACT_METHODS MODIFY CONTACT_ID NOT NULL;

--
-- RHN_CONTACT_METHODS
--
ALTER TABLE RHN_CONTACT_METHODS DROP CONSTRAINT RHN_CMETH_METH_TYPE_NN;
ALTER TABLE RHN_CONTACT_METHODS MODIFY METHOD_TYPE_ID NOT NULL;

--
-- RHN_CONTACT_METHODS
--
ALTER TABLE RHN_CONTACT_METHODS DROP CONSTRAINT RHN_CMETH_NOTIF_FMT_NN;
ALTER TABLE RHN_CONTACT_METHODS MODIFY NOTIFICATION_FORMAT_ID NOT NULL;

--
-- RHN_CONTACT_METHODS
--
ALTER TABLE RHN_CONTACT_METHODS DROP CONSTRAINT RHN_CMETH_RECID_NN;
ALTER TABLE RHN_CONTACT_METHODS MODIFY RECID NOT NULL;

--
-- RHN_COMMAND
--
ALTER TABLE RHN_COMMAND DROP CONSTRAINT RHN_CMMND_ALLOWED_NN;
ALTER TABLE RHN_COMMAND MODIFY ALLOWED_IN_SUITE NOT NULL;

--
-- RHN_COMMAND
--
ALTER TABLE RHN_COMMAND DROP CONSTRAINT RHN_CMMND_CLASS_NN;
ALTER TABLE RHN_COMMAND MODIFY COMMAND_CLASS NOT NULL;

--
-- RHN_COMMAND
--
ALTER TABLE RHN_COMMAND DROP CONSTRAINT RHN_CMMND_DESC_NN;
ALTER TABLE RHN_COMMAND MODIFY DESCRIPTION NOT NULL;

--
-- RHN_COMMAND
--
ALTER TABLE RHN_COMMAND DROP CONSTRAINT RHN_CMMND_ENABLED_NN;
ALTER TABLE RHN_COMMAND MODIFY ENABLED NOT NULL;

--
-- RHN_COMMAND
--
ALTER TABLE RHN_COMMAND DROP CONSTRAINT RHN_CMMND_HOST_PROBE_NN;
ALTER TABLE RHN_COMMAND MODIFY FOR_HOST_PROBE NOT NULL;

--
-- RHN_COMMAND
--
ALTER TABLE RHN_COMMAND DROP CONSTRAINT RHN_CMMND_NAME_NN;
ALTER TABLE RHN_COMMAND MODIFY NAME NOT NULL;

--
-- RHN_COMMAND
--
ALTER TABLE RHN_COMMAND DROP CONSTRAINT RHN_CMMND_RECID_NN;
ALTER TABLE RHN_COMMAND MODIFY RECID NOT NULL;

--
-- RHNCHANNELNEWESTPACKAGEAUDIT
--
ALTER TABLE RHNCHANNELNEWESTPACKAGEAUDIT DROP CONSTRAINT RHN_CNP_AT_CALLER_NN;
ALTER TABLE RHNCHANNELNEWESTPACKAGEAUDIT MODIFY CALLER NOT NULL;

--
-- RHNCHANNELNEWESTPACKAGEAUDIT
--
ALTER TABLE RHNCHANNELNEWESTPACKAGEAUDIT DROP CONSTRAINT RHN_CNP_AT_CID_NN;
ALTER TABLE RHNCHANNELNEWESTPACKAGEAUDIT MODIFY CHANNEL_ID NOT NULL;

--
-- RHNCHANNELNEWESTPACKAGEAUDIT
--
ALTER TABLE RHNCHANNELNEWESTPACKAGEAUDIT DROP CONSTRAINT RHN_CNP_AT_RT_NN;
ALTER TABLE RHNCHANNELNEWESTPACKAGEAUDIT MODIFY REFRESH_TIME NOT NULL;

--
-- RHNCHANNELNEWESTPACKAGE
--
ALTER TABLE RHNCHANNELNEWESTPACKAGE DROP CONSTRAINT RHN_CNP_CID_NN;
ALTER TABLE RHNCHANNELNEWESTPACKAGE MODIFY CHANNEL_ID NOT NULL;

--
-- RHNCHANNELNEWESTPACKAGE
--
ALTER TABLE RHNCHANNELNEWESTPACKAGE DROP CONSTRAINT RHN_CNP_EID_NN;
ALTER TABLE RHNCHANNELNEWESTPACKAGE MODIFY EVR_ID NOT NULL;

--
-- RHNCHANNELNEWESTPACKAGE
--
ALTER TABLE RHNCHANNELNEWESTPACKAGE DROP CONSTRAINT RHN_CNP_NID_NN;
ALTER TABLE RHNCHANNELNEWESTPACKAGE MODIFY NAME_ID NOT NULL;

--
-- RHNCHANNELNEWESTPACKAGE
--
ALTER TABLE RHNCHANNELNEWESTPACKAGE DROP CONSTRAINT RHN_CNP_PAID_NN;
ALTER TABLE RHNCHANNELNEWESTPACKAGE MODIFY PACKAGE_ARCH_ID NOT NULL;

--
-- RHNCHANNELNEWESTPACKAGE
--
ALTER TABLE RHNCHANNELNEWESTPACKAGE DROP CONSTRAINT RHN_CNP_PID_NN;
ALTER TABLE RHNCHANNELNEWESTPACKAGE MODIFY PACKAGE_ID NOT NULL;

--
-- RHN_CONTACT_GROUP_MEMBERS
--
ALTER TABLE RHN_CONTACT_GROUP_MEMBERS DROP CONSTRAINT RHN_CNTGM_CGID_NN;
ALTER TABLE RHN_CONTACT_GROUP_MEMBERS MODIFY CONTACT_GROUP_ID NOT NULL;

--
-- RHN_CONTACT_GROUP_MEMBERS
--
ALTER TABLE RHN_CONTACT_GROUP_MEMBERS DROP CONSTRAINT RHN_CNTGM_LAST_DATE_NN;
ALTER TABLE RHN_CONTACT_GROUP_MEMBERS MODIFY LAST_UPDATE_DATE NOT NULL;

--
-- RHN_CONTACT_GROUP_MEMBERS
--
ALTER TABLE RHN_CONTACT_GROUP_MEMBERS DROP CONSTRAINT RHN_CNTGM_LAST_USER_NN;
ALTER TABLE RHN_CONTACT_GROUP_MEMBERS MODIFY LAST_UPDATE_USER NOT NULL;

--
-- RHN_CONTACT_GROUP_MEMBERS
--
ALTER TABLE RHN_CONTACT_GROUP_MEMBERS DROP CONSTRAINT RHN_CNTGM_ON_NN;
ALTER TABLE RHN_CONTACT_GROUP_MEMBERS MODIFY ORDER_NUMBER NOT NULL;

--
-- RHN_CONTACT_GROUPS
--
ALTER TABLE RHN_CONTACT_GROUPS DROP CONSTRAINT RHN_CNTGP_ACK_WAIT_NN;
ALTER TABLE RHN_CONTACT_GROUPS MODIFY ACK_WAIT NOT NULL;

--
-- RHN_CONTACT_GROUPS
--
ALTER TABLE RHN_CONTACT_GROUPS DROP CONSTRAINT RHN_CNTGP_CUST_ID_NN;
ALTER TABLE RHN_CONTACT_GROUPS MODIFY CUSTOMER_ID NOT NULL;

--
-- RHN_CONTACT_GROUPS
--
ALTER TABLE RHN_CONTACT_GROUPS DROP CONSTRAINT RHN_CNTGP_GROUP_NAME_NN;
ALTER TABLE RHN_CONTACT_GROUPS MODIFY CONTACT_GROUP_NAME NOT NULL;

--
-- RHN_CONTACT_GROUPS
--
ALTER TABLE RHN_CONTACT_GROUPS DROP CONSTRAINT RHN_CNTGP_LAST_DATE_NN;
ALTER TABLE RHN_CONTACT_GROUPS MODIFY LAST_UPDATE_DATE NOT NULL;

--
-- RHN_CONTACT_GROUPS
--
ALTER TABLE RHN_CONTACT_GROUPS DROP CONSTRAINT RHN_CNTGP_LAST_USER_NN;
ALTER TABLE RHN_CONTACT_GROUPS MODIFY LAST_UPDATE_USER NOT NULL;

--
-- RHN_CONTACT_GROUPS
--
ALTER TABLE RHN_CONTACT_GROUPS DROP CONSTRAINT RHN_CNTGP_NOTIF_FMT_NN;
ALTER TABLE RHN_CONTACT_GROUPS MODIFY NOTIFICATION_FORMAT_ID NOT NULL;

--
-- RHN_CONTACT_GROUPS
--
ALTER TABLE RHN_CONTACT_GROUPS DROP CONSTRAINT RHN_CNTGP_RECID_NN;
ALTER TABLE RHN_CONTACT_GROUPS MODIFY RECID NOT NULL;

--
-- RHN_CONTACT_GROUPS
--
ALTER TABLE RHN_CONTACT_GROUPS DROP CONSTRAINT RHN_CNTGP_ROTATE_F_NN;
ALTER TABLE RHN_CONTACT_GROUPS MODIFY ROTATE_FIRST NOT NULL;

--
-- RHN_CONTACT_GROUPS
--
ALTER TABLE RHN_CONTACT_GROUPS DROP CONSTRAINT RHN_CNTGP_STRAT_ID_NN;
ALTER TABLE RHN_CONTACT_GROUPS MODIFY STRATEGY_ID NOT NULL;

--
-- RHN_COMMAND_CLASS
--
ALTER TABLE RHN_COMMAND_CLASS DROP CONSTRAINT RHN_COMCL_CLASS_NAME_NN;
ALTER TABLE RHN_COMMAND_CLASS MODIFY CLASS_NAME NOT NULL;

--
-- RHN_CONFIG_SECURITY_TYPE
--
ALTER TABLE RHN_CONFIG_SECURITY_TYPE DROP CONSTRAINT RHN_CONCT_NAME_NN;
ALTER TABLE RHN_CONFIG_SECURITY_TYPE MODIFY NAME NOT NULL;

--
-- RHNCONFIGCHANNELTYPE
--
ALTER TABLE RHNCONFIGCHANNELTYPE DROP CONSTRAINT RHN_CONFCHANTYPE_CREAT_NN;
ALTER TABLE RHNCONFIGCHANNELTYPE MODIFY CREATED NOT NULL;

--
-- RHNCONFIGCHANNELTYPE
--
ALTER TABLE RHNCONFIGCHANNELTYPE DROP CONSTRAINT RHN_CONFCHANTYPE_ID_NN;
ALTER TABLE RHNCONFIGCHANNELTYPE MODIFY ID NOT NULL;

--
-- RHNCONFIGCHANNELTYPE
--
ALTER TABLE RHNCONFIGCHANNELTYPE DROP CONSTRAINT RHN_CONFCHANTYPE_LABEL_NN;
ALTER TABLE RHNCONFIGCHANNELTYPE MODIFY LABEL NOT NULL;

--
-- RHNCONFIGCHANNELTYPE
--
ALTER TABLE RHNCONFIGCHANNELTYPE DROP CONSTRAINT RHN_CONFCHANTYPE_MOD_NN;
ALTER TABLE RHNCONFIGCHANNELTYPE MODIFY MODIFIED NOT NULL;

--
-- RHNCONFIGCHANNELTYPE
--
ALTER TABLE RHNCONFIGCHANNELTYPE DROP CONSTRAINT RHN_CONFCHANTYPE_NAME_NN;
ALTER TABLE RHNCONFIGCHANNELTYPE MODIFY NAME NOT NULL;

--
-- RHNCONFIGCHANNELTYPE
--
ALTER TABLE RHNCONFIGCHANNELTYPE DROP CONSTRAINT RHN_CONFCHANTYPE_PRI_NN;
ALTER TABLE RHNCONFIGCHANNELTYPE MODIFY PRIORITY NOT NULL;

--
-- RHNCONFIGCHANNEL
--
ALTER TABLE RHNCONFIGCHANNEL DROP CONSTRAINT RHN_CONFCHAN_CREAT_NN;
ALTER TABLE RHNCONFIGCHANNEL MODIFY CREATED NOT NULL;

--
-- RHNCONFIGCHANNEL
--
ALTER TABLE RHNCONFIGCHANNEL DROP CONSTRAINT RHN_CONFCHAN_CTID_NN;
ALTER TABLE RHNCONFIGCHANNEL MODIFY CONFCHAN_TYPE_ID NOT NULL;

--
-- RHNCONFIGCHANNEL
--
ALTER TABLE RHNCONFIGCHANNEL DROP CONSTRAINT RHN_CONFCHAN_DESC_NN;
ALTER TABLE RHNCONFIGCHANNEL MODIFY DESCRIPTION NOT NULL;

--
-- RHNCONFIGCHANNEL
--
ALTER TABLE RHNCONFIGCHANNEL DROP CONSTRAINT RHN_CONFCHAN_ID_NN;
ALTER TABLE RHNCONFIGCHANNEL MODIFY ID NOT NULL;

--
-- RHNCONFIGCHANNEL
--
ALTER TABLE RHNCONFIGCHANNEL DROP CONSTRAINT RHN_CONFCHAN_LABEL_NN;
ALTER TABLE RHNCONFIGCHANNEL MODIFY LABEL NOT NULL;

--
-- RHNCONFIGCHANNEL
--
ALTER TABLE RHNCONFIGCHANNEL DROP CONSTRAINT RHN_CONFCHAN_MOD_NN;
ALTER TABLE RHNCONFIGCHANNEL MODIFY MODIFIED NOT NULL;

--
-- RHNCONFIGCHANNEL
--
ALTER TABLE RHNCONFIGCHANNEL DROP CONSTRAINT RHN_CONFCHAN_NAME_NN;
ALTER TABLE RHNCONFIGCHANNEL MODIFY NAME NOT NULL;

--
-- RHNCONFIGCHANNEL
--
ALTER TABLE RHNCONFIGCHANNEL DROP CONSTRAINT RHN_CONFCHAN_OID_NN;
ALTER TABLE RHNCONFIGCHANNEL MODIFY ORG_ID NOT NULL;

--
-- RHNCONFIGCONTENT
--
ALTER TABLE RHNCONFIGCONTENT DROP CONSTRAINT RHN_CONFCONTENT_CREAT_NN;
ALTER TABLE RHNCONFIGCONTENT MODIFY CREATED NOT NULL;

--
-- RHNCONFIGCONTENT
--
ALTER TABLE RHNCONFIGCONTENT DROP CONSTRAINT RHN_CONFCONTENT_ID_NN;
ALTER TABLE RHNCONFIGCONTENT MODIFY ID NOT NULL;

--
-- RHNCONFIGCONTENT
--
ALTER TABLE RHNCONFIGCONTENT DROP CONSTRAINT RHN_CONFCONTENT_ISBIN_NN;
ALTER TABLE RHNCONFIGCONTENT MODIFY IS_BINARY NOT NULL;

--
-- RHNCONFIGCONTENT
--
ALTER TABLE RHNCONFIGCONTENT DROP CONSTRAINT RHN_CONFCONTENT_MD5_NN;
ALTER TABLE RHNCONFIGCONTENT MODIFY MD5SUM NOT NULL;

--
-- RHNCONFIGCONTENT
--
ALTER TABLE RHNCONFIGCONTENT DROP CONSTRAINT RHN_CONFCONTENT_MOD_NN;
ALTER TABLE RHNCONFIGCONTENT MODIFY MODIFIED NOT NULL;

--
-- RHNCONFIGFILETYPE
--
ALTER TABLE RHNCONFIGFILETYPE DROP CONSTRAINT RHN_CONFFILETYPE_CREAT_NN;
ALTER TABLE RHNCONFIGFILETYPE MODIFY CREATED NOT NULL;

--
-- RHNCONFIGFILETYPE
--
ALTER TABLE RHNCONFIGFILETYPE DROP CONSTRAINT RHN_CONFFILETYPE_ID_NN;
ALTER TABLE RHNCONFIGFILETYPE MODIFY ID NOT NULL;

--
-- RHNCONFIGFILETYPE
--
ALTER TABLE RHNCONFIGFILETYPE DROP CONSTRAINT RHN_CONFFILETYPE_LABEL_NN;
ALTER TABLE RHNCONFIGFILETYPE MODIFY LABEL NOT NULL;

--
-- RHNCONFIGFILETYPE
--
ALTER TABLE RHNCONFIGFILETYPE DROP CONSTRAINT RHN_CONFFILETYPE_MOD_NN;
ALTER TABLE RHNCONFIGFILETYPE MODIFY MODIFIED NOT NULL;

--
-- RHNCONFIGFILETYPE
--
ALTER TABLE RHNCONFIGFILETYPE DROP CONSTRAINT RHN_CONFFILETYPE_NAME_NN;
ALTER TABLE RHNCONFIGFILETYPE MODIFY NAME NOT NULL;

--
-- RHNCONFIGFILE
--
ALTER TABLE RHNCONFIGFILE DROP CONSTRAINT RHN_CONFFILE_CCID_NN;
ALTER TABLE RHNCONFIGFILE MODIFY CONFIG_CHANNEL_ID NOT NULL;

--
-- RHNCONFIGFILE
--
ALTER TABLE RHNCONFIGFILE DROP CONSTRAINT RHN_CONFFILE_CFNID_NN;
ALTER TABLE RHNCONFIGFILE MODIFY CONFIG_FILE_NAME_ID NOT NULL;

--
-- RHNCONFIGFILE
--
ALTER TABLE RHNCONFIGFILE DROP CONSTRAINT RHN_CONFFILE_CREAT_NN;
ALTER TABLE RHNCONFIGFILE MODIFY CREATED NOT NULL;

--
-- RHNCONFIGFILEFAILURE
--
ALTER TABLE RHNCONFIGFILEFAILURE DROP CONSTRAINT RHN_CONFFILE_FAIL_CREAT_NN;
ALTER TABLE RHNCONFIGFILEFAILURE MODIFY CREATED NOT NULL;

--
-- RHNCONFIGFILEFAILURE
--
ALTER TABLE RHNCONFIGFILEFAILURE DROP CONSTRAINT RHN_CONFFILE_FAIL_ID_NN;
ALTER TABLE RHNCONFIGFILEFAILURE MODIFY ID NOT NULL;

--
-- RHNCONFIGFILEFAILURE
--
ALTER TABLE RHNCONFIGFILEFAILURE DROP CONSTRAINT RHN_CONFFILE_FAIL_LABEL_NN;
ALTER TABLE RHNCONFIGFILEFAILURE MODIFY LABEL NOT NULL;

--
-- RHNCONFIGFILEFAILURE
--
ALTER TABLE RHNCONFIGFILEFAILURE DROP CONSTRAINT RHN_CONFFILE_FAIL_MOD_NN;
ALTER TABLE RHNCONFIGFILEFAILURE MODIFY MODIFIED NOT NULL;

--
-- RHNCONFIGFILEFAILURE
--
ALTER TABLE RHNCONFIGFILEFAILURE DROP CONSTRAINT RHN_CONFFILE_FAIL_NAME_NN;
ALTER TABLE RHNCONFIGFILEFAILURE MODIFY NAME NOT NULL;

--
-- RHNCONFIGFILE
--
ALTER TABLE RHNCONFIGFILE DROP CONSTRAINT RHN_CONFFILE_ID_NN;
ALTER TABLE RHNCONFIGFILE MODIFY ID NOT NULL;

--
-- RHNCONFIGFILE
--
ALTER TABLE RHNCONFIGFILE DROP CONSTRAINT RHN_CONFFILE_MOD_NN;
ALTER TABLE RHNCONFIGFILE MODIFY MODIFIED NOT NULL;

--
-- RHNCONFIGFILE
--
ALTER TABLE RHNCONFIGFILE DROP CONSTRAINT RHN_CONFFILE_SID_NN;
ALTER TABLE RHNCONFIGFILE MODIFY STATE_ID NOT NULL;

--
-- RHN_CONFIG_GROUP
--
ALTER TABLE RHN_CONFIG_GROUP DROP CONSTRAINT RHN_CONFG_NAME_NN;
ALTER TABLE RHN_CONFIG_GROUP MODIFY NAME NOT NULL;

--
-- RHNCONFIGINFO
--
ALTER TABLE RHNCONFIGINFO DROP CONSTRAINT RHN_CONFINFO_CREAT_NN;
ALTER TABLE RHNCONFIGINFO MODIFY CREATED NOT NULL;

--
-- RHNCONFIGINFO
--
ALTER TABLE RHNCONFIGINFO DROP CONSTRAINT RHN_CONFINFO_FILEMODE_NN;
ALTER TABLE RHNCONFIGINFO MODIFY FILEMODE NOT NULL;

--
-- RHNCONFIGINFO
--
ALTER TABLE RHNCONFIGINFO DROP CONSTRAINT RHN_CONFINFO_GROUPNAME_NN;
ALTER TABLE RHNCONFIGINFO MODIFY GROUPNAME NOT NULL;

--
-- RHNCONFIGINFO
--
ALTER TABLE RHNCONFIGINFO DROP CONSTRAINT RHN_CONFINFO_ID_NN;
ALTER TABLE RHNCONFIGINFO MODIFY ID NOT NULL;

--
-- RHNCONFIGINFO
--
ALTER TABLE RHNCONFIGINFO DROP CONSTRAINT RHN_CONFINFO_MOD_NN;
ALTER TABLE RHNCONFIGINFO MODIFY MODIFIED NOT NULL;

--
-- RHNCONFIGINFO
--
ALTER TABLE RHNCONFIGINFO DROP CONSTRAINT RHN_CONFINFO_USERNAME_NN;
ALTER TABLE RHNCONFIGINFO MODIFY USERNAME NOT NULL;

--
-- RHN_CONFIG_MACRO
--
ALTER TABLE RHN_CONFIG_MACRO DROP CONSTRAINT RHN_CONFM_EDITABLE_NN;
ALTER TABLE RHN_CONFIG_MACRO MODIFY EDITABLE NOT NULL;

--
-- RHN_CONFIG_MACRO
--
ALTER TABLE RHN_CONFIG_MACRO DROP CONSTRAINT RHN_CONFM_ENV_NN;
ALTER TABLE RHN_CONFIG_MACRO MODIFY ENVIRONMENT NOT NULL;

--
-- RHN_CONFIG_MACRO
--
ALTER TABLE RHN_CONFIG_MACRO DROP CONSTRAINT RHN_CONFM_NAME_NN;
ALTER TABLE RHN_CONFIG_MACRO MODIFY NAME NOT NULL;

--
-- RHN_CONFIG_PARAMETER
--
ALTER TABLE RHN_CONFIG_PARAMETER DROP CONSTRAINT RHN_CONFP_GROUP_NAME_NN;
ALTER TABLE RHN_CONFIG_PARAMETER MODIFY GROUP_NAME NOT NULL;

--
-- RHN_CONFIG_PARAMETER
--
ALTER TABLE RHN_CONFIG_PARAMETER DROP CONSTRAINT RHN_CONFP_NAME_NN;
ALTER TABLE RHN_CONFIG_PARAMETER MODIFY NAME NOT NULL;

--
-- RHN_CONFIG_PARAMETER
--
ALTER TABLE RHN_CONFIG_PARAMETER DROP CONSTRAINT RHN_CONFP_SECURITY_TYPE_NN;
ALTER TABLE RHN_CONFIG_PARAMETER MODIFY SECURITY_TYPE NOT NULL;

--
-- RHNCONFIGREVISION
--
ALTER TABLE RHNCONFIGREVISION DROP CONSTRAINT RHN_CONFREVISION_CCID_NN;
ALTER TABLE RHNCONFIGREVISION MODIFY CONFIG_CONTENT_ID NOT NULL;

--
-- RHNCONFIGREVISION
--
ALTER TABLE RHNCONFIGREVISION DROP CONSTRAINT RHN_CONFREVISION_CFID_NN;
ALTER TABLE RHNCONFIGREVISION MODIFY CONFIG_FILE_ID NOT NULL;

--
-- RHNCONFIGREVISION
--
ALTER TABLE RHNCONFIGREVISION DROP CONSTRAINT RHN_CONFREVISION_CIID_NN;
ALTER TABLE RHNCONFIGREVISION MODIFY CONFIG_INFO_ID NOT NULL;

--
-- RHNCONFIGREVISION
--
ALTER TABLE RHNCONFIGREVISION DROP CONSTRAINT RHN_CONFREVISION_CREAT_NN;
ALTER TABLE RHNCONFIGREVISION MODIFY CREATED NOT NULL;

--
-- RHNCONFIGREVISION
--
ALTER TABLE RHNCONFIGREVISION DROP CONSTRAINT RHN_CONFREVISION_DEND_NN;
ALTER TABLE RHNCONFIGREVISION MODIFY DELIM_END NOT NULL;

--
-- RHNCONFIGREVISION
--
ALTER TABLE RHNCONFIGREVISION DROP CONSTRAINT RHN_CONFREVISION_DSTART_NN;
ALTER TABLE RHNCONFIGREVISION MODIFY DELIM_START NOT NULL;

--
-- RHNCONFIGREVISION
--
ALTER TABLE RHNCONFIGREVISION DROP CONSTRAINT RHN_CONFREVISION_ID_NN;
ALTER TABLE RHNCONFIGREVISION MODIFY ID NOT NULL;

--
-- RHNCONFIGREVISION
--
ALTER TABLE RHNCONFIGREVISION DROP CONSTRAINT RHN_CONFREVISION_MOD_NN;
ALTER TABLE RHNCONFIGREVISION MODIFY MODIFIED NOT NULL;

--
-- RHNCONFIGREVISION
--
ALTER TABLE RHNCONFIGREVISION DROP CONSTRAINT RHN_CONFREVISION_REV_NN;
ALTER TABLE RHNCONFIGREVISION MODIFY REVISION NOT NULL;

--
-- RHNCONFIGREVISION
--
ALTER TABLE RHNCONFIGREVISION DROP CONSTRAINT RHN_CONF_REV_CFTI_NN;
ALTER TABLE RHNCONFIGREVISION MODIFY CONFIG_FILE_TYPE_ID NOT NULL;

--
-- RHNWEBCONTACTCHANGESTATE
--
ALTER TABLE RHNWEBCONTACTCHANGESTATE DROP CONSTRAINT RHN_CONT_CHANGE_STATE_NN;
ALTER TABLE RHNWEBCONTACTCHANGESTATE MODIFY LABEL NOT NULL;

--
-- RHN_COMMAND_PARAM_THRESHOLD
--
ALTER TABLE RHN_COMMAND_PARAM_THRESHOLD DROP CONSTRAINT RHN_COPTR_COMMAND_CLASS_NN;
ALTER TABLE RHN_COMMAND_PARAM_THRESHOLD MODIFY COMMAND_CLASS NOT NULL;

--
-- RHN_COMMAND_PARAM_THRESHOLD
--
ALTER TABLE RHN_COMMAND_PARAM_THRESHOLD DROP CONSTRAINT RHN_COPTR_COMMAND_ID_NN;
ALTER TABLE RHN_COMMAND_PARAM_THRESHOLD MODIFY COMMAND_ID NOT NULL;

--
-- RHN_COMMAND_PARAM_THRESHOLD
--
ALTER TABLE RHN_COMMAND_PARAM_THRESHOLD DROP CONSTRAINT RHN_COPTR_PARAM_NAME_NN;
ALTER TABLE RHN_COMMAND_PARAM_THRESHOLD MODIFY PARAM_NAME NOT NULL;

--
-- RHN_COMMAND_PARAM_THRESHOLD
--
ALTER TABLE RHN_COMMAND_PARAM_THRESHOLD DROP CONSTRAINT RHN_COPTR_PARAM_TYPE_NN;
ALTER TABLE RHN_COMMAND_PARAM_THRESHOLD MODIFY PARAM_TYPE NOT NULL;

--
-- RHN_COMMAND_PARAM_THRESHOLD
--
ALTER TABLE RHN_COMMAND_PARAM_THRESHOLD DROP CONSTRAINT RHN_COPTR_THRES_MET_ID_NN;
ALTER TABLE RHN_COMMAND_PARAM_THRESHOLD MODIFY THRESHOLD_METRIC_ID NOT NULL;

--
-- RHN_COMMAND_PARAM_THRESHOLD
--
ALTER TABLE RHN_COMMAND_PARAM_THRESHOLD DROP CONSTRAINT RHN_COPTR_THRES_NAME_NN;
ALTER TABLE RHN_COMMAND_PARAM_THRESHOLD MODIFY THRESHOLD_TYPE_NAME NOT NULL;

--
-- RHN_COMMAND_PARAMETER
--
ALTER TABLE RHN_COMMAND_PARAMETER DROP CONSTRAINT RHN_CPARM_COMMAND_ID_NN;
ALTER TABLE RHN_COMMAND_PARAMETER MODIFY COMMAND_ID NOT NULL;

--
-- RHN_COMMAND_PARAMETER
--
ALTER TABLE RHN_COMMAND_PARAMETER DROP CONSTRAINT RHN_CPARM_DATA_TYPE_NAME_NN;
ALTER TABLE RHN_COMMAND_PARAMETER MODIFY DATA_TYPE_NAME NOT NULL;

--
-- RHN_COMMAND_PARAMETER
--
ALTER TABLE RHN_COMMAND_PARAMETER DROP CONSTRAINT RHN_CPARM_DEF_VALUE_VIS_NN;
ALTER TABLE RHN_COMMAND_PARAMETER MODIFY DEFAULT_VALUE_VISIBLE NOT NULL;

--
-- RHN_COMMAND_PARAMETER
--
ALTER TABLE RHN_COMMAND_PARAMETER DROP CONSTRAINT RHN_CPARM_DESCRIPTION_NN;
ALTER TABLE RHN_COMMAND_PARAMETER MODIFY DESCRIPTION NOT NULL;

--
-- RHN_COMMAND_PARAMETER
--
ALTER TABLE RHN_COMMAND_PARAMETER DROP CONSTRAINT RHN_CPARM_FIELD_ORDER_NN;
ALTER TABLE RHN_COMMAND_PARAMETER MODIFY FIELD_ORDER NOT NULL;

--
-- RHN_COMMAND_PARAMETER
--
ALTER TABLE RHN_COMMAND_PARAMETER DROP CONSTRAINT RHN_CPARM_FIELD_VISIBLE_NN;
ALTER TABLE RHN_COMMAND_PARAMETER MODIFY FIELD_VISIBLE NOT NULL;

--
-- RHN_COMMAND_PARAMETER
--
ALTER TABLE RHN_COMMAND_PARAMETER DROP CONSTRAINT RHN_CPARM_FIELD_WIDGET_NAME_NN;
ALTER TABLE RHN_COMMAND_PARAMETER MODIFY FIELD_WIDGET_NAME NOT NULL;

--
-- RHN_COMMAND_PARAMETER
--
ALTER TABLE RHN_COMMAND_PARAMETER DROP CONSTRAINT RHN_CPARM_MANDATORY_NN;
ALTER TABLE RHN_COMMAND_PARAMETER MODIFY MANDATORY NOT NULL;

--
-- RHN_COMMAND_PARAMETER
--
ALTER TABLE RHN_COMMAND_PARAMETER DROP CONSTRAINT RHN_CPARM_PARAM_NAME_NN;
ALTER TABLE RHN_COMMAND_PARAMETER MODIFY PARAM_NAME NOT NULL;

--
-- RHN_COMMAND_PARAMETER
--
ALTER TABLE RHN_COMMAND_PARAMETER DROP CONSTRAINT RHN_CPARM_PARAM_TYPE_NN;
ALTER TABLE RHN_COMMAND_PARAMETER MODIFY PARAM_TYPE NOT NULL;

--
-- RHNCHANNELPERMISSION
--
ALTER TABLE RHNCHANNELPERMISSION DROP CONSTRAINT RHN_CPERM_CID_NN;
ALTER TABLE RHNCHANNELPERMISSION MODIFY CHANNEL_ID NOT NULL;

--
-- RHNCHANNELPERMISSION
--
ALTER TABLE RHNCHANNELPERMISSION DROP CONSTRAINT RHN_CPERM_CREATED_NN;
ALTER TABLE RHNCHANNELPERMISSION MODIFY CREATED NOT NULL;

--
-- RHNCHANNELPERMISSION
--
ALTER TABLE RHNCHANNELPERMISSION DROP CONSTRAINT RHN_CPERM_MODIFIED_NN;
ALTER TABLE RHNCHANNELPERMISSION MODIFY MODIFIED NOT NULL;

--
-- RHNCHANNELPERMISSION
--
ALTER TABLE RHNCHANNELPERMISSION DROP CONSTRAINT RHN_CPERM_RID_NN;
ALTER TABLE RHNCHANNELPERMISSION MODIFY ROLE_ID NOT NULL;

--
-- RHNCHANNELPERMISSIONROLE
--
ALTER TABLE RHNCHANNELPERMISSIONROLE DROP CONSTRAINT RHN_CPERM_ROLE_CREATED_NN;
ALTER TABLE RHNCHANNELPERMISSIONROLE MODIFY CREATED NOT NULL;

--
-- RHNCHANNELPERMISSIONROLE
--
ALTER TABLE RHNCHANNELPERMISSIONROLE DROP CONSTRAINT RHN_CPERM_ROLE_DESC_NN;
ALTER TABLE RHNCHANNELPERMISSIONROLE MODIFY DESCRIPTION NOT NULL;

--
-- RHNCHANNELPERMISSIONROLE
--
ALTER TABLE RHNCHANNELPERMISSIONROLE DROP CONSTRAINT RHN_CPERM_ROLE_ID_NN;
ALTER TABLE RHNCHANNELPERMISSIONROLE MODIFY ID NOT NULL;

--
-- RHNCHANNELPERMISSIONROLE
--
ALTER TABLE RHNCHANNELPERMISSIONROLE DROP CONSTRAINT RHN_CPERM_ROLE_LABEL_NN;
ALTER TABLE RHNCHANNELPERMISSIONROLE MODIFY LABEL NOT NULL;

--
-- RHNCHANNELPERMISSIONROLE
--
ALTER TABLE RHNCHANNELPERMISSIONROLE DROP CONSTRAINT RHN_CPERM_ROLE_MODIFIED_NN;
ALTER TABLE RHNCHANNELPERMISSIONROLE MODIFY MODIFIED NOT NULL;

--
-- RHNCHANNELPERMISSION
--
ALTER TABLE RHNCHANNELPERMISSION DROP CONSTRAINT RHN_CPERM_UID_NN;
ALTER TABLE RHNCHANNELPERMISSION MODIFY USER_ID NOT NULL;

--
-- RHNCPUARCH
--
ALTER TABLE RHNCPUARCH DROP CONSTRAINT RHN_CPUARCH_CREATED_NN;
ALTER TABLE RHNCPUARCH MODIFY CREATED NOT NULL;

--
-- RHNCPUARCH
--
ALTER TABLE RHNCPUARCH DROP CONSTRAINT RHN_CPUARCH_ID_NN;
ALTER TABLE RHNCPUARCH MODIFY ID NOT NULL;

--
-- RHNCPUARCH
--
ALTER TABLE RHNCPUARCH DROP CONSTRAINT RHN_CPUARCH_LABEL_NN;
ALTER TABLE RHNCPUARCH MODIFY LABEL NOT NULL;

--
-- RHNCPUARCH
--
ALTER TABLE RHNCPUARCH DROP CONSTRAINT RHN_CPUARCH_MODIFIED_NN;
ALTER TABLE RHNCPUARCH MODIFY MODIFIED NOT NULL;

--
-- RHNCPUARCH
--
ALTER TABLE RHNCPUARCH DROP CONSTRAINT RHN_CPUARCH_NAME_NN;
ALTER TABLE RHNCPUARCH MODIFY NAME NOT NULL;

--
-- RHNCPU
--
ALTER TABLE RHNCPU DROP CONSTRAINT RHN_CPU_CAID_NN;
ALTER TABLE RHNCPU MODIFY CPU_ARCH_ID NOT NULL;

--
-- RHNCPU
--
ALTER TABLE RHNCPU DROP CONSTRAINT RHN_CPU_CREATED_NN;
ALTER TABLE RHNCPU MODIFY CREATED NOT NULL;

--
-- RHNCPU
--
ALTER TABLE RHNCPU DROP CONSTRAINT RHN_CPU_ID_NN;
ALTER TABLE RHNCPU MODIFY ID NOT NULL;

--
-- RHNCPU
--
ALTER TABLE RHNCPU DROP CONSTRAINT RHN_CPU_MODIFIED_NN;
ALTER TABLE RHNCPU MODIFY MODIFIED NOT NULL;

--
-- RHNCPU
--
ALTER TABLE RHNCPU DROP CONSTRAINT RHN_CPU_SERVER_NN;
ALTER TABLE RHNCPU MODIFY SERVER_ID NOT NULL;

--
-- RHNCHANNELPACKAGEARCHCOMPAT
--
ALTER TABLE RHNCHANNELPACKAGEARCHCOMPAT DROP CONSTRAINT RHN_CP_AC_CAID_NN;
ALTER TABLE RHNCHANNELPACKAGEARCHCOMPAT MODIFY CHANNEL_ARCH_ID NOT NULL;

--
-- RHNCHANNELPACKAGEARCHCOMPAT
--
ALTER TABLE RHNCHANNELPACKAGEARCHCOMPAT DROP CONSTRAINT RHN_CP_AC_CREATED_NN;
ALTER TABLE RHNCHANNELPACKAGEARCHCOMPAT MODIFY CREATED NOT NULL;

--
-- RHNCHANNELPACKAGEARCHCOMPAT
--
ALTER TABLE RHNCHANNELPACKAGEARCHCOMPAT DROP CONSTRAINT RHN_CP_AC_MODIFIED_NN;
ALTER TABLE RHNCHANNELPACKAGEARCHCOMPAT MODIFY MODIFIED NOT NULL;

--
-- RHNCHANNELPACKAGEARCHCOMPAT
--
ALTER TABLE RHNCHANNELPACKAGEARCHCOMPAT DROP CONSTRAINT RHN_CP_AC_PAID_NN;
ALTER TABLE RHNCHANNELPACKAGEARCHCOMPAT MODIFY PACKAGE_ARCH_ID NOT NULL;

--
-- RHNCHANNELPARENT
--
ALTER TABLE RHNCHANNELPARENT DROP CONSTRAINT RHN_CP_CH_NN;
ALTER TABLE RHNCHANNELPARENT MODIFY CHANNEL NOT NULL;

--
-- RHNCHANNELPACKAGE
--
ALTER TABLE RHNCHANNELPACKAGE DROP CONSTRAINT RHN_CP_CID_NN;
ALTER TABLE RHNCHANNELPACKAGE MODIFY CHANNEL_ID NOT NULL;

--
-- RHNCHANNELPACKAGE
--
ALTER TABLE RHNCHANNELPACKAGE DROP CONSTRAINT RHN_CP_CREATED_NN;
ALTER TABLE RHNCHANNELPACKAGE MODIFY CREATED NOT NULL;

--
-- RHNCHANNELPACKAGE
--
ALTER TABLE RHNCHANNELPACKAGE DROP CONSTRAINT RHN_CP_MODIFIED_NN;
ALTER TABLE RHNCHANNELPACKAGE MODIFY MODIFIED NOT NULL;

--
-- RHNCHANNELPARENT
--
ALTER TABLE RHNCHANNELPARENT DROP CONSTRAINT RHN_CP_PARENT_CH_NN;
ALTER TABLE RHNCHANNELPARENT MODIFY PARENT_CHANNEL NOT NULL;

--
-- RHNCHANNELPACKAGE
--
ALTER TABLE RHNCHANNELPACKAGE DROP CONSTRAINT RHN_CP_PID_NN;
ALTER TABLE RHNCHANNELPACKAGE MODIFY PACKAGE_ID NOT NULL;

--
-- RHN_COMMAND_QUEUE_EXECS_BK
--
ALTER TABLE RHN_COMMAND_QUEUE_EXECS_BK DROP CONSTRAINT RHN_CQCMDBK_INSTANCE_ID_NN;
ALTER TABLE RHN_COMMAND_QUEUE_EXECS_BK MODIFY INSTANCE_ID NOT NULL;

--
-- RHN_COMMAND_QUEUE_EXECS_BK
--
ALTER TABLE RHN_COMMAND_QUEUE_EXECS_BK DROP CONSTRAINT RHN_CQCMDBK_NETSAINT_ID_NN;
ALTER TABLE RHN_COMMAND_QUEUE_EXECS_BK MODIFY NETSAINT_ID NOT NULL;

--
-- RHN_COMMAND_QUEUE_EXECS_BK
--
ALTER TABLE RHN_COMMAND_QUEUE_EXECS_BK DROP CONSTRAINT RHN_CQCMDBK_TARGET_TYPE_NN;
ALTER TABLE RHN_COMMAND_QUEUE_EXECS_BK MODIFY TARGET_TYPE NOT NULL;

--
-- RHN_COMMAND_QUEUE_COMMANDS
--
ALTER TABLE RHN_COMMAND_QUEUE_COMMANDS DROP CONSTRAINT RHN_CQCMD_COMMAND_LINE_NN;
ALTER TABLE RHN_COMMAND_QUEUE_COMMANDS MODIFY COMMAND_LINE NOT NULL;

--
-- RHN_COMMAND_QUEUE_COMMANDS
--
ALTER TABLE RHN_COMMAND_QUEUE_COMMANDS DROP CONSTRAINT RHN_CQCMD_DESCRIPTION_NN;
ALTER TABLE RHN_COMMAND_QUEUE_COMMANDS MODIFY DESCRIPTION NOT NULL;

--
-- RHN_COMMAND_QUEUE_COMMANDS
--
ALTER TABLE RHN_COMMAND_QUEUE_COMMANDS DROP CONSTRAINT RHN_CQCMD_EFFECTIVE_GRP_NN;
ALTER TABLE RHN_COMMAND_QUEUE_COMMANDS MODIFY EFFECTIVE_GROUP NOT NULL;

--
-- RHN_COMMAND_QUEUE_COMMANDS
--
ALTER TABLE RHN_COMMAND_QUEUE_COMMANDS DROP CONSTRAINT RHN_CQCMD_EFFECTIVE_USR_NN;
ALTER TABLE RHN_COMMAND_QUEUE_COMMANDS MODIFY EFFECTIVE_USER NOT NULL;

--
-- RHN_COMMAND_QUEUE_COMMANDS
--
ALTER TABLE RHN_COMMAND_QUEUE_COMMANDS DROP CONSTRAINT RHN_CQCMD_PERMANENT_NN;
ALTER TABLE RHN_COMMAND_QUEUE_COMMANDS MODIFY PERMANENT NOT NULL;

--
-- RHN_COMMAND_QUEUE_COMMANDS
--
ALTER TABLE RHN_COMMAND_QUEUE_COMMANDS DROP CONSTRAINT RHN_CQCMD_RECID_NN;
ALTER TABLE RHN_COMMAND_QUEUE_COMMANDS MODIFY RECID NOT NULL;

--
-- RHN_COMMAND_QUEUE_COMMANDS
--
ALTER TABLE RHN_COMMAND_QUEUE_COMMANDS DROP CONSTRAINT RHN_CQCMD_RESTARTABLE_NN;
ALTER TABLE RHN_COMMAND_QUEUE_COMMANDS MODIFY RESTARTABLE NOT NULL;

--
-- RHN_COMMAND_QUEUE_EXECS
--
ALTER TABLE RHN_COMMAND_QUEUE_EXECS DROP CONSTRAINT RHN_CQEXE_INSTANCE_ID_NN;
ALTER TABLE RHN_COMMAND_QUEUE_EXECS MODIFY INSTANCE_ID NOT NULL;

--
-- RHN_COMMAND_QUEUE_EXECS
--
ALTER TABLE RHN_COMMAND_QUEUE_EXECS DROP CONSTRAINT RHN_CQEXE_NETSAINT_ID_NN;
ALTER TABLE RHN_COMMAND_QUEUE_EXECS MODIFY NETSAINT_ID NOT NULL;

--
-- RHN_COMMAND_QUEUE_EXECS
--
ALTER TABLE RHN_COMMAND_QUEUE_EXECS DROP CONSTRAINT RHN_CQEXE_TARGET_TYPE_NN;
ALTER TABLE RHN_COMMAND_QUEUE_EXECS MODIFY TARGET_TYPE NOT NULL;

--
-- RHN_COMMAND_QUEUE_INSTANCES_BK
--
ALTER TABLE RHN_COMMAND_QUEUE_INSTANCES_BK DROP CONSTRAINT RHN_CQINSBK_COMMAND_ID_NN;
ALTER TABLE RHN_COMMAND_QUEUE_INSTANCES_BK MODIFY COMMAND_ID NOT NULL;

--
-- RHN_COMMAND_QUEUE_INSTANCES_BK
--
ALTER TABLE RHN_COMMAND_QUEUE_INSTANCES_BK DROP CONSTRAINT RHN_CQINSBK_DATE_SUB_NN;
ALTER TABLE RHN_COMMAND_QUEUE_INSTANCES_BK MODIFY DATE_SUBMITTED NOT NULL;

--
-- RHN_COMMAND_QUEUE_INSTANCES_BK
--
ALTER TABLE RHN_COMMAND_QUEUE_INSTANCES_BK DROP CONSTRAINT RHN_CQINSBK_EXP_DATE_NN;
ALTER TABLE RHN_COMMAND_QUEUE_INSTANCES_BK MODIFY EXPIRATION_DATE NOT NULL;

--
-- RHN_COMMAND_QUEUE_INSTANCES_BK
--
ALTER TABLE RHN_COMMAND_QUEUE_INSTANCES_BK DROP CONSTRAINT RHN_CQINSBK_RECID_NN;
ALTER TABLE RHN_COMMAND_QUEUE_INSTANCES_BK MODIFY RECID NOT NULL;

--
-- RHN_COMMAND_QUEUE_INSTANCES
--
ALTER TABLE RHN_COMMAND_QUEUE_INSTANCES DROP CONSTRAINT RHN_CQINS_COMMAND_ID_NN;
ALTER TABLE RHN_COMMAND_QUEUE_INSTANCES MODIFY COMMAND_ID NOT NULL;

--
-- RHN_COMMAND_QUEUE_INSTANCES
--
ALTER TABLE RHN_COMMAND_QUEUE_INSTANCES DROP CONSTRAINT RHN_CQINS_DATE_SUBMITTED_NN;
ALTER TABLE RHN_COMMAND_QUEUE_INSTANCES MODIFY DATE_SUBMITTED NOT NULL;

--
-- RHN_COMMAND_QUEUE_INSTANCES
--
ALTER TABLE RHN_COMMAND_QUEUE_INSTANCES DROP CONSTRAINT RHN_CQINS_EXPIRATION_DATE_NN;
ALTER TABLE RHN_COMMAND_QUEUE_INSTANCES MODIFY EXPIRATION_DATE NOT NULL;

--
-- RHN_COMMAND_QUEUE_INSTANCES
--
ALTER TABLE RHN_COMMAND_QUEUE_INSTANCES DROP CONSTRAINT RHN_CQINS_RECID_NN;
ALTER TABLE RHN_COMMAND_QUEUE_INSTANCES MODIFY RECID NOT NULL;

--
-- RHN_COMMAND_QUEUE_PARAMS
--
ALTER TABLE RHN_COMMAND_QUEUE_PARAMS DROP CONSTRAINT RHN_CQPRM_INSTANCE_ID_NN;
ALTER TABLE RHN_COMMAND_QUEUE_PARAMS MODIFY INSTANCE_ID NOT NULL;

--
-- RHN_COMMAND_QUEUE_PARAMS
--
ALTER TABLE RHN_COMMAND_QUEUE_PARAMS DROP CONSTRAINT RHN_CQPRM_ORD_NN;
ALTER TABLE RHN_COMMAND_QUEUE_PARAMS MODIFY ORD NOT NULL;

--
-- RHN_COMMAND_QUEUE_SESSIONS
--
ALTER TABLE RHN_COMMAND_QUEUE_SESSIONS DROP CONSTRAINT RHN_CQSES_CONTACT_ID_NN;
ALTER TABLE RHN_COMMAND_QUEUE_SESSIONS MODIFY CONTACT_ID NOT NULL;

--
-- RHN_COMMAND_REQUIREMENTS
--
ALTER TABLE RHN_COMMAND_REQUIREMENTS DROP CONSTRAINT RHN_CREQS_DESCRIPTION_NN;
ALTER TABLE RHN_COMMAND_REQUIREMENTS MODIFY DESCRIPTION NOT NULL;

--
-- RHN_COMMAND_REQUIREMENTS
--
ALTER TABLE RHN_COMMAND_REQUIREMENTS DROP CONSTRAINT RHN_CREQS_NAME_NN;
ALTER TABLE RHN_COMMAND_REQUIREMENTS MODIFY NAME NOT NULL;

--
-- RHNCRYPTOKEYTYPE
--
ALTER TABLE RHNCRYPTOKEYTYPE DROP CONSTRAINT RHN_CRYPTOKEYTYPE_CREAT_NN;
ALTER TABLE RHNCRYPTOKEYTYPE MODIFY CREATED NOT NULL;

--
-- RHNCRYPTOKEYTYPE
--
ALTER TABLE RHNCRYPTOKEYTYPE DROP CONSTRAINT RHN_CRYPTOKEYTYPE_DESC_NN;
ALTER TABLE RHNCRYPTOKEYTYPE MODIFY DESCRIPTION NOT NULL;

--
-- RHNCRYPTOKEYTYPE
--
ALTER TABLE RHNCRYPTOKEYTYPE DROP CONSTRAINT RHN_CRYPTOKEYTYPE_ID_NN;
ALTER TABLE RHNCRYPTOKEYTYPE MODIFY ID NOT NULL;

--
-- RHNCRYPTOKEYTYPE
--
ALTER TABLE RHNCRYPTOKEYTYPE DROP CONSTRAINT RHN_CRYPTOKEYTYPE_LABEL_NN;
ALTER TABLE RHNCRYPTOKEYTYPE MODIFY LABEL NOT NULL;

--
-- RHNCRYPTOKEYTYPE
--
ALTER TABLE RHNCRYPTOKEYTYPE DROP CONSTRAINT RHN_CRYPTOKEYTYPE_MOD_NN;
ALTER TABLE RHNCRYPTOKEYTYPE MODIFY MODIFIED NOT NULL;

--
-- RHNCRYPTOKEY
--
ALTER TABLE RHNCRYPTOKEY DROP CONSTRAINT RHN_CRYPTOKEY_CKTID_NN;
ALTER TABLE RHNCRYPTOKEY MODIFY CRYPTO_KEY_TYPE_ID NOT NULL;

--
-- RHNCRYPTOKEY
--
ALTER TABLE RHNCRYPTOKEY DROP CONSTRAINT RHN_CRYPTOKEY_DESC_NN;
ALTER TABLE RHNCRYPTOKEY MODIFY DESCRIPTION NOT NULL;

--
-- RHNCRYPTOKEY
--
ALTER TABLE RHNCRYPTOKEY DROP CONSTRAINT RHN_CRYPTOKEY_ID_NN;
ALTER TABLE RHNCRYPTOKEY MODIFY ID NOT NULL;

--
-- RHNCRYPTOKEY
--
ALTER TABLE RHNCRYPTOKEY DROP CONSTRAINT RHN_CRYPTOKEY_OID_NN;
ALTER TABLE RHNCRYPTOKEY MODIFY ORG_ID NOT NULL;

--
-- RHN_CURRENT_STATE_SUMMARIES
--
ALTER TABLE RHN_CURRENT_STATE_SUMMARIES DROP CONSTRAINT RHN_CURSU_CUST_ID_NN;
ALTER TABLE RHN_CURRENT_STATE_SUMMARIES MODIFY CUSTOMER_ID NOT NULL;

--
-- RHN_CURRENT_STATE_SUMMARIES
--
ALTER TABLE RHN_CURRENT_STATE_SUMMARIES DROP CONSTRAINT RHN_CURSU_STATE_NN;
ALTER TABLE RHN_CURRENT_STATE_SUMMARIES MODIFY STATE NOT NULL;

--
-- RHN_CURRENT_STATE_SUMMARIES
--
ALTER TABLE RHN_CURRENT_STATE_SUMMARIES DROP CONSTRAINT RHN_CURSU_TEMPLATE_ID_NN;
ALTER TABLE RHN_CURRENT_STATE_SUMMARIES MODIFY TEMPLATE_ID NOT NULL;

--
-- RHNCVE
--
ALTER TABLE RHNCVE DROP CONSTRAINT RHN_CVE_ID_NN;
ALTER TABLE RHNCVE MODIFY ID NOT NULL;

--
-- RHNCVE
--
ALTER TABLE RHNCVE DROP CONSTRAINT RHN_CVE_NAME_NN;
ALTER TABLE RHNCVE MODIFY NAME NOT NULL;

--
-- RHNDAEMONSTATE
--
ALTER TABLE RHNDAEMONSTATE DROP CONSTRAINT RHN_DAEMONSTATE_LABEL_NN;
ALTER TABLE RHNDAEMONSTATE MODIFY LABEL NOT NULL;

--
-- RHNDAEMONSTATE
--
ALTER TABLE RHNDAEMONSTATE DROP CONSTRAINT RHN_DAEMONSTATE_LP_NN;
ALTER TABLE RHNDAEMONSTATE MODIFY LAST_POLL NOT NULL;

--
-- RHN_DB_ENVIRONMENT
--
ALTER TABLE RHN_DB_ENVIRONMENT DROP CONSTRAINT RHN_DBENV_DB_NAME_NN;
ALTER TABLE RHN_DB_ENVIRONMENT MODIFY DB_NAME NOT NULL;

--
-- RHNDISTCHANNELMAP
--
ALTER TABLE RHNDISTCHANNELMAP DROP CONSTRAINT RHN_DCM_CAID_NN;
ALTER TABLE RHNDISTCHANNELMAP MODIFY CHANNEL_ARCH_ID NOT NULL;

--
-- RHNDISTCHANNELMAP
--
ALTER TABLE RHNDISTCHANNELMAP DROP CONSTRAINT RHN_DCM_CID_NN;
ALTER TABLE RHNDISTCHANNELMAP MODIFY CHANNEL_ID NOT NULL;

--
-- RHNDISTCHANNELMAP
--
ALTER TABLE RHNDISTCHANNELMAP DROP CONSTRAINT RHN_DCM_OS_NN;
ALTER TABLE RHNDISTCHANNELMAP MODIFY OS NOT NULL;

--
-- RHNDISTCHANNELMAP
--
ALTER TABLE RHNDISTCHANNELMAP DROP CONSTRAINT RHN_DCM_RELEASE_NN;
ALTER TABLE RHNDISTCHANNELMAP MODIFY RELEASE NOT NULL;

--
-- RHNDEVICE
--
ALTER TABLE RHNDEVICE DROP CONSTRAINT RHN_DEVICE_CREATED_NN;
ALTER TABLE RHNDEVICE MODIFY CREATED NOT NULL;

--
-- RHNDEVICE
--
ALTER TABLE RHNDEVICE DROP CONSTRAINT RHN_DEVICE_ID_NN;
ALTER TABLE RHNDEVICE MODIFY ID NOT NULL;

--
-- RHNDEVICE
--
ALTER TABLE RHNDEVICE DROP CONSTRAINT RHN_DEVICE_MODIFIED_NN;
ALTER TABLE RHNDEVICE MODIFY MODIFIED NOT NULL;

--
-- RHNDEVICE
--
ALTER TABLE RHNDEVICE DROP CONSTRAINT RHN_DEVICE_SID_NN;
ALTER TABLE RHNDEVICE MODIFY SERVER_ID NOT NULL;

--
-- RHNDOWNLOADS
--
ALTER TABLE RHNDOWNLOADS DROP CONSTRAINT RHN_DL_CAT_NN;
ALTER TABLE RHNDOWNLOADS MODIFY CATEGORY NOT NULL;

--
-- RHNDOWNLOADS
--
ALTER TABLE RHNDOWNLOADS DROP CONSTRAINT RHN_DL_CFID_NN;
ALTER TABLE RHNDOWNLOADS MODIFY CHANNEL_FAMILY_ID NOT NULL;

--
-- RHNDOWNLOADS
--
ALTER TABLE RHNDOWNLOADS DROP CONSTRAINT RHN_DL_CREATED_NN;
ALTER TABLE RHNDOWNLOADS MODIFY CREATED NOT NULL;

--
-- RHNDOWNLOADS
--
ALTER TABLE RHNDOWNLOADS DROP CONSTRAINT RHN_DL_FID_NN;
ALTER TABLE RHNDOWNLOADS MODIFY FILE_ID NOT NULL;

--
-- RHNDOWNLOADS
--
ALTER TABLE RHNDOWNLOADS DROP CONSTRAINT RHN_DL_ID_NN;
ALTER TABLE RHNDOWNLOADS MODIFY ID NOT NULL;

--
-- RHNDOWNLOADS
--
ALTER TABLE RHNDOWNLOADS DROP CONSTRAINT RHN_DL_MODIFIED_NN;
ALTER TABLE RHNDOWNLOADS MODIFY MODIFIED NOT NULL;

--
-- RHNDOWNLOADS
--
ALTER TABLE RHNDOWNLOADS DROP CONSTRAINT RHN_DL_NAME_NN;
ALTER TABLE RHNDOWNLOADS MODIFY NAME NOT NULL;

--
-- RHNDOWNLOADS
--
ALTER TABLE RHNDOWNLOADS DROP CONSTRAINT RHN_DL_ORD_NN;
ALTER TABLE RHNDOWNLOADS MODIFY ORDERING NOT NULL;

--
-- RHNDOWNLOADTYPE
--
ALTER TABLE RHNDOWNLOADTYPE DROP CONSTRAINT RHN_DOWNLOAD_TYPE_ID_NN;
ALTER TABLE RHNDOWNLOADTYPE MODIFY ID NOT NULL;

--
-- RHNDOWNLOADTYPE
--
ALTER TABLE RHNDOWNLOADTYPE DROP CONSTRAINT RHN_DOWNLOAD_TYPE_LABEL_NN;
ALTER TABLE RHNDOWNLOADTYPE MODIFY LABEL NOT NULL;

--
-- RHNDOWNLOADTYPE
--
ALTER TABLE RHNDOWNLOADTYPE DROP CONSTRAINT RHN_DOWNLOAD_TYPE_NAME_NN;
ALTER TABLE RHNDOWNLOADTYPE MODIFY NAME NOT NULL;

--
-- RHN_DEPLOYED_PROBE
--
ALTER TABLE RHN_DEPLOYED_PROBE DROP CONSTRAINT RHN_DPROB_CHECK_INT_NN;
ALTER TABLE RHN_DEPLOYED_PROBE MODIFY CHECK_INTERVAL_MINUTES NOT NULL;

--
-- RHN_DEPLOYED_PROBE
--
ALTER TABLE RHN_DEPLOYED_PROBE DROP CONSTRAINT RHN_DPROB_COMMAND_ID_NN;
ALTER TABLE RHN_DEPLOYED_PROBE MODIFY COMMAND_ID NOT NULL;

--
-- RHN_DEPLOYED_PROBE
--
ALTER TABLE RHN_DEPLOYED_PROBE DROP CONSTRAINT RHN_DPROB_CUST_ID_NN;
ALTER TABLE RHN_DEPLOYED_PROBE MODIFY CUSTOMER_ID NOT NULL;

--
-- RHN_DEPLOYED_PROBE
--
ALTER TABLE RHN_DEPLOYED_PROBE DROP CONSTRAINT RHN_DPROB_PROBE_TYPE_NN;
ALTER TABLE RHN_DEPLOYED_PROBE MODIFY PROBE_TYPE NOT NULL;

--
-- RHN_DEPLOYED_PROBE
--
ALTER TABLE RHN_DEPLOYED_PROBE DROP CONSTRAINT RHN_DPROB_RECID_NN;
ALTER TABLE RHN_DEPLOYED_PROBE MODIFY RECID NOT NULL;

--
-- RHN_DEPLOYED_PROBE
--
ALTER TABLE RHN_DEPLOYED_PROBE DROP CONSTRAINT RHN_DPROB_RETRY_INT_NN;
ALTER TABLE RHN_DEPLOYED_PROBE MODIFY RETRY_INTERVAL_MINUTES NOT NULL;

--
-- RHNDAILYSUMMARYQUEUE
--
ALTER TABLE RHNDAILYSUMMARYQUEUE DROP CONSTRAINT RHN_DSQUEUE_CREATED_NN;
ALTER TABLE RHNDAILYSUMMARYQUEUE MODIFY CREATED NOT NULL;

--
-- RHNDAILYSUMMARYQUEUE
--
ALTER TABLE RHNDAILYSUMMARYQUEUE DROP CONSTRAINT RHN_DSQUEUE_MODIFIED_NN;
ALTER TABLE RHNDAILYSUMMARYQUEUE MODIFY MODIFIED NOT NULL;

--
-- RHNDAILYSUMMARYQUEUE
--
ALTER TABLE RHNDAILYSUMMARYQUEUE DROP CONSTRAINT RHN_DSQUEUE_OID_NN;
ALTER TABLE RHNDAILYSUMMARYQUEUE MODIFY ORG_ID NOT NULL;

--
-- RHNEMAILADDRESSLOG
--
ALTER TABLE RHNEMAILADDRESSLOG DROP CONSTRAINT RHN_EADDRESSLOG_A_NN;
ALTER TABLE RHNEMAILADDRESSLOG MODIFY ADDRESS NOT NULL;

--
-- RHNEMAILADDRESSLOG
--
ALTER TABLE RHNEMAILADDRESSLOG DROP CONSTRAINT RHN_EADDRESSLOG_CREATED_NN;
ALTER TABLE RHNEMAILADDRESSLOG MODIFY CREATED NOT NULL;

--
-- RHNEMAILADDRESSLOG
--
ALTER TABLE RHNEMAILADDRESSLOG DROP CONSTRAINT RHN_EADDRESSLOG_UID_NN;
ALTER TABLE RHNEMAILADDRESSLOG MODIFY USER_ID NOT NULL;

--
-- RHNEMAILADDRESS
--
ALTER TABLE RHNEMAILADDRESS DROP CONSTRAINT RHN_EADDRESS_A_NN;
ALTER TABLE RHNEMAILADDRESS MODIFY ADDRESS NOT NULL;

--
-- RHNEMAILADDRESS
--
ALTER TABLE RHNEMAILADDRESS DROP CONSTRAINT RHN_EADDRESS_CREATED_NN;
ALTER TABLE RHNEMAILADDRESS MODIFY CREATED NOT NULL;

--
-- RHNEMAILADDRESS
--
ALTER TABLE RHNEMAILADDRESS DROP CONSTRAINT RHN_EADDRESS_ID_NN;
ALTER TABLE RHNEMAILADDRESS MODIFY ID NOT NULL;

--
-- RHNEMAILADDRESS
--
ALTER TABLE RHNEMAILADDRESS DROP CONSTRAINT RHN_EADDRESS_MODIFIED_NN;
ALTER TABLE RHNEMAILADDRESS MODIFY MODIFIED NOT NULL;

--
-- RHNEMAILADDRESS
--
ALTER TABLE RHNEMAILADDRESS DROP CONSTRAINT RHN_EADDRESS_SID_NN;
ALTER TABLE RHNEMAILADDRESS MODIFY STATE_ID NOT NULL;

--
-- RHNEMAILADDRESS
--
ALTER TABLE RHNEMAILADDRESS DROP CONSTRAINT RHN_EADDRESS_UID_NN;
ALTER TABLE RHNEMAILADDRESS MODIFY USER_ID NOT NULL;

--
-- RHNEMAILADDRESSSTATE
--
ALTER TABLE RHNEMAILADDRESSSTATE DROP CONSTRAINT RHN_EASTATE_CREATED_NN;
ALTER TABLE RHNEMAILADDRESSSTATE MODIFY CREATED NOT NULL;

--
-- RHNEMAILADDRESSSTATE
--
ALTER TABLE RHNEMAILADDRESSSTATE DROP CONSTRAINT RHN_EASTATE_ID_NN;
ALTER TABLE RHNEMAILADDRESSSTATE MODIFY ID NOT NULL;

--
-- RHNEMAILADDRESSSTATE
--
ALTER TABLE RHNEMAILADDRESSSTATE DROP CONSTRAINT RHN_EASTATE_LABEL_NN;
ALTER TABLE RHNEMAILADDRESSSTATE MODIFY LABEL NOT NULL;

--
-- RHNEMAILADDRESSSTATE
--
ALTER TABLE RHNEMAILADDRESSSTATE DROP CONSTRAINT RHN_EASTATE_MODIFIED_NN;
ALTER TABLE RHNEMAILADDRESSSTATE MODIFY MODIFIED NOT NULL;

--
-- RHNERRATACLONEDTMP
--
ALTER TABLE RHNERRATACLONEDTMP DROP CONSTRAINT RHN_ECLONEDTMP_CREATED_NN;
ALTER TABLE RHNERRATACLONEDTMP MODIFY CREATED NOT NULL;

--
-- RHNERRATACLONEDTMP
--
ALTER TABLE RHNERRATACLONEDTMP DROP CONSTRAINT RHN_ECLONEDTMP_FEID_NN;
ALTER TABLE RHNERRATACLONEDTMP MODIFY ORIGINAL_ID NOT NULL;

--
-- RHNERRATACLONEDTMP
--
ALTER TABLE RHNERRATACLONEDTMP DROP CONSTRAINT RHN_ECLONEDTMP_MODIFIED_NN;
ALTER TABLE RHNERRATACLONEDTMP MODIFY MODIFIED NOT NULL;

--
-- RHNERRATACLONEDTMP
--
ALTER TABLE RHNERRATACLONEDTMP DROP CONSTRAINT RHN_ECLONEDTMP_TEID_NN;
ALTER TABLE RHNERRATACLONEDTMP MODIFY ID NOT NULL;

--
-- RHNERRATAFILECHANNELTMP
--
ALTER TABLE RHNERRATAFILECHANNELTMP DROP CONSTRAINT RHN_EFILECTMP_CID_NN;
ALTER TABLE RHNERRATAFILECHANNELTMP MODIFY CHANNEL_ID NOT NULL;

--
-- RHNERRATAFILECHANNELTMP
--
ALTER TABLE RHNERRATAFILECHANNELTMP DROP CONSTRAINT RHN_EFILECTMP_CREATED_NN;
ALTER TABLE RHNERRATAFILECHANNELTMP MODIFY CREATED NOT NULL;

--
-- RHNERRATAFILECHANNELTMP
--
ALTER TABLE RHNERRATAFILECHANNELTMP DROP CONSTRAINT RHN_EFILECTMP_EID_NN;
ALTER TABLE RHNERRATAFILECHANNELTMP MODIFY ERRATA_FILE_ID NOT NULL;

--
-- RHNERRATAFILECHANNELTMP
--
ALTER TABLE RHNERRATAFILECHANNELTMP DROP CONSTRAINT RHN_EFILECTMP_MODIFIED_NN;
ALTER TABLE RHNERRATAFILECHANNELTMP MODIFY MODIFIED NOT NULL;

--
-- RHNERRATAFILECHANNEL
--
ALTER TABLE RHNERRATAFILECHANNEL DROP CONSTRAINT RHN_EFILEC_CID_NN;
ALTER TABLE RHNERRATAFILECHANNEL MODIFY CHANNEL_ID NOT NULL;

--
-- RHNERRATAFILECHANNEL
--
ALTER TABLE RHNERRATAFILECHANNEL DROP CONSTRAINT RHN_EFILEC_CREATED_NN;
ALTER TABLE RHNERRATAFILECHANNEL MODIFY CREATED NOT NULL;

--
-- RHNERRATAFILECHANNEL
--
ALTER TABLE RHNERRATAFILECHANNEL DROP CONSTRAINT RHN_EFILEC_EID_NN;
ALTER TABLE RHNERRATAFILECHANNEL MODIFY ERRATA_FILE_ID NOT NULL;

--
-- RHNERRATAFILECHANNEL
--
ALTER TABLE RHNERRATAFILECHANNEL DROP CONSTRAINT RHN_EFILEC_MODIFIED_NN;
ALTER TABLE RHNERRATAFILECHANNEL MODIFY MODIFIED NOT NULL;

--
-- RHNERRATAFILEPACKAGESOURCE
--
ALTER TABLE RHNERRATAFILEPACKAGESOURCE DROP CONSTRAINT RHN_EFILEPS_CREATED_NN;
ALTER TABLE RHNERRATAFILEPACKAGESOURCE MODIFY CREATED NOT NULL;

--
-- RHNERRATAFILEPACKAGESOURCE
--
ALTER TABLE RHNERRATAFILEPACKAGESOURCE DROP CONSTRAINT RHN_EFILEPS_FILEID_NN;
ALTER TABLE RHNERRATAFILEPACKAGESOURCE MODIFY ERRATA_FILE_ID NOT NULL;

--
-- RHNERRATAFILEPACKAGESOURCE
--
ALTER TABLE RHNERRATAFILEPACKAGESOURCE DROP CONSTRAINT RHN_EFILEPS_MODIFIED_NN;
ALTER TABLE RHNERRATAFILEPACKAGESOURCE MODIFY MODIFIED NOT NULL;

--
-- RHNERRATAFILEPACKAGESOURCE
--
ALTER TABLE RHNERRATAFILEPACKAGESOURCE DROP CONSTRAINT RHN_EFILEPS_PID_NN;
ALTER TABLE RHNERRATAFILEPACKAGESOURCE MODIFY PACKAGE_ID NOT NULL;

--
-- RHNERRATAFILEPACKAGETMP
--
ALTER TABLE RHNERRATAFILEPACKAGETMP DROP CONSTRAINT RHN_EFILEPTMP_CREATED_NN;
ALTER TABLE RHNERRATAFILEPACKAGETMP MODIFY CREATED NOT NULL;

--
-- RHNERRATAFILEPACKAGETMP
--
ALTER TABLE RHNERRATAFILEPACKAGETMP DROP CONSTRAINT RHN_EFILEPTMP_FILEID_NN;
ALTER TABLE RHNERRATAFILEPACKAGETMP MODIFY ERRATA_FILE_ID NOT NULL;

--
-- RHNERRATAFILEPACKAGETMP
--
ALTER TABLE RHNERRATAFILEPACKAGETMP DROP CONSTRAINT RHN_EFILEPTMP_MODIFIED_NN;
ALTER TABLE RHNERRATAFILEPACKAGETMP MODIFY MODIFIED NOT NULL;

--
-- RHNERRATAFILEPACKAGETMP
--
ALTER TABLE RHNERRATAFILEPACKAGETMP DROP CONSTRAINT RHN_EFILEPTMP_PID_NN;
ALTER TABLE RHNERRATAFILEPACKAGETMP MODIFY PACKAGE_ID NOT NULL;

--
-- RHNERRATAFILEPACKAGE
--
ALTER TABLE RHNERRATAFILEPACKAGE DROP CONSTRAINT RHN_EFILEP_CREATED_NN;
ALTER TABLE RHNERRATAFILEPACKAGE MODIFY CREATED NOT NULL;

--
-- RHNERRATAFILEPACKAGE
--
ALTER TABLE RHNERRATAFILEPACKAGE DROP CONSTRAINT RHN_EFILEP_FILEID_NN;
ALTER TABLE RHNERRATAFILEPACKAGE MODIFY ERRATA_FILE_ID NOT NULL;

--
-- RHNERRATAFILEPACKAGE
--
ALTER TABLE RHNERRATAFILEPACKAGE DROP CONSTRAINT RHN_EFILEP_MODIFIED_NN;
ALTER TABLE RHNERRATAFILEPACKAGE MODIFY MODIFIED NOT NULL;

--
-- RHNERRATAFILEPACKAGE
--
ALTER TABLE RHNERRATAFILEPACKAGE DROP CONSTRAINT RHN_EFILEP_PID_NN;
ALTER TABLE RHNERRATAFILEPACKAGE MODIFY PACKAGE_ID NOT NULL;

--
-- RHNERRATANOTIFICATIONQUEUE
--
ALTER TABLE RHNERRATANOTIFICATIONQUEUE DROP CONSTRAINT RHN_ENQUEUE_CREATED_NN;
ALTER TABLE RHNERRATANOTIFICATIONQUEUE MODIFY CREATED NOT NULL;

--
-- RHNERRATANOTIFICATIONQUEUE
--
ALTER TABLE RHNERRATANOTIFICATIONQUEUE DROP CONSTRAINT RHN_ENQUEUE_EID_NN;
ALTER TABLE RHNERRATANOTIFICATIONQUEUE MODIFY ERRATA_ID NOT NULL;

--
-- RHNERRATANOTIFICATIONQUEUE
--
ALTER TABLE RHNERRATANOTIFICATIONQUEUE DROP CONSTRAINT RHN_ENQUEUE_MODIFIED_NN;
ALTER TABLE RHNERRATANOTIFICATIONQUEUE MODIFY MODIFIED NOT NULL;

--
-- RHNERRATANOTIFICATIONQUEUE
--
ALTER TABLE RHNERRATANOTIFICATIONQUEUE DROP CONSTRAINT RHN_ENQUEUE_NN;
ALTER TABLE RHNERRATANOTIFICATIONQUEUE MODIFY CHANNEL_ID NOT NULL;

--
-- RHNERRATANOTIFICATIONQUEUE
--
ALTER TABLE RHNERRATANOTIFICATIONQUEUE DROP CONSTRAINT RHN_ENQUEUE_OID_NN;
ALTER TABLE RHNERRATANOTIFICATIONQUEUE MODIFY ORG_ID NOT NULL;

--
-- RHNENTITLEMENTLOG
--
ALTER TABLE RHNENTITLEMENTLOG DROP CONSTRAINT RHN_ENTITLEMENT_LOG_BDATE_NN;
ALTER TABLE RHNENTITLEMENTLOG MODIFY BDATE NOT NULL;

--
-- RHNENTITLEMENTLOG
--
ALTER TABLE RHNENTITLEMENTLOG DROP CONSTRAINT RHN_ENTITLEMENT_LOG_EDATE_NN;
ALTER TABLE RHNENTITLEMENTLOG MODIFY EDATE NOT NULL;

--
-- RHNENTITLEMENTLOG
--
ALTER TABLE RHNENTITLEMENTLOG DROP CONSTRAINT RHN_ENTITLEMENT_LOG_RT_NN;
ALTER TABLE RHNENTITLEMENTLOG MODIFY RUN_TIME NOT NULL;

--
-- RHN_ENVIRONMENT
--
ALTER TABLE RHN_ENVIRONMENT DROP CONSTRAINT RHN_ENVIR_NAME_NN;
ALTER TABLE RHN_ENVIRONMENT MODIFY NAME NOT NULL;

--
-- RHNERRATAQUEUE
--
ALTER TABLE RHNERRATAQUEUE DROP CONSTRAINT RHN_EQUEUE_CID_NN;
ALTER TABLE RHNERRATAQUEUE MODIFY CHANNEL_ID NOT NULL;

--
-- RHNERRATAQUEUE
--
ALTER TABLE RHNERRATAQUEUE DROP CONSTRAINT RHN_EQUEUE_CREATED_NN;
ALTER TABLE RHNERRATAQUEUE MODIFY CREATED NOT NULL;

--
-- RHNERRATAQUEUE
--
ALTER TABLE RHNERRATAQUEUE DROP CONSTRAINT RHN_EQUEUE_EID_NN;
ALTER TABLE RHNERRATAQUEUE MODIFY ERRATA_ID NOT NULL;

--
-- RHNERRATAQUEUE
--
ALTER TABLE RHNERRATAQUEUE DROP CONSTRAINT RHN_EQUEUE_MODIFIED_NN;
ALTER TABLE RHNERRATAQUEUE MODIFY MODIFIED NOT NULL;

--
-- RHNERRATACLONED
--
ALTER TABLE RHNERRATACLONED DROP CONSTRAINT RHN_ERRATACLONE_CREATED_NN;
ALTER TABLE RHNERRATACLONED MODIFY CREATED NOT NULL;

--
-- RHNERRATACLONED
--
ALTER TABLE RHNERRATACLONED DROP CONSTRAINT RHN_ERRATACLONE_FEID_NN;
ALTER TABLE RHNERRATACLONED MODIFY ORIGINAL_ID NOT NULL;

--
-- RHNERRATACLONED
--
ALTER TABLE RHNERRATACLONED DROP CONSTRAINT RHN_ERRATACLONE_MODIFIED_NN;
ALTER TABLE RHNERRATACLONED MODIFY MODIFIED NOT NULL;

--
-- RHNERRATACLONED
--
ALTER TABLE RHNERRATACLONED DROP CONSTRAINT RHN_ERRATACLONE_TEID_NN;
ALTER TABLE RHNERRATACLONED MODIFY ID NOT NULL;

--
-- RHNERRATAFILETMP
--
ALTER TABLE RHNERRATAFILETMP DROP CONSTRAINT RHN_ERRATAFILETMP_CREATED_NN;
ALTER TABLE RHNERRATAFILETMP MODIFY CREATED NOT NULL;

--
-- RHNERRATAFILETMP
--
ALTER TABLE RHNERRATAFILETMP DROP CONSTRAINT RHN_ERRATAFILETMP_ERRATA_NN;
ALTER TABLE RHNERRATAFILETMP MODIFY ERRATA_ID NOT NULL;

--
-- RHNERRATAFILETMP
--
ALTER TABLE RHNERRATAFILETMP DROP CONSTRAINT RHN_ERRATAFILETMP_ID_NN;
ALTER TABLE RHNERRATAFILETMP MODIFY ID NOT NULL;

--
-- RHNERRATAFILETMP
--
ALTER TABLE RHNERRATAFILETMP DROP CONSTRAINT RHN_ERRATAFILETMP_MD5_NN;
ALTER TABLE RHNERRATAFILETMP MODIFY MD5SUM NOT NULL;

--
-- RHNERRATAFILETMP
--
ALTER TABLE RHNERRATAFILETMP DROP CONSTRAINT RHN_ERRATAFILETMP_MODIFIED_NN;
ALTER TABLE RHNERRATAFILETMP MODIFY MODIFIED NOT NULL;

--
-- RHNERRATAFILETMP
--
ALTER TABLE RHNERRATAFILETMP DROP CONSTRAINT RHN_ERRATAFILETMP_NAME_NN;
ALTER TABLE RHNERRATAFILETMP MODIFY FILENAME NOT NULL;

--
-- RHNERRATAFILETMP
--
ALTER TABLE RHNERRATAFILETMP DROP CONSTRAINT RHN_ERRATAFILETMP_TYPE_NN;
ALTER TABLE RHNERRATAFILETMP MODIFY TYPE NOT NULL;

--
-- RHNERRATAFILE
--
ALTER TABLE RHNERRATAFILE DROP CONSTRAINT RHN_ERRATAFILE_CREATED_NN;
ALTER TABLE RHNERRATAFILE MODIFY CREATED NOT NULL;

--
-- RHNERRATAFILE
--
ALTER TABLE RHNERRATAFILE DROP CONSTRAINT RHN_ERRATAFILE_ERRATA_NN;
ALTER TABLE RHNERRATAFILE MODIFY ERRATA_ID NOT NULL;

--
-- RHNERRATAFILE
--
ALTER TABLE RHNERRATAFILE DROP CONSTRAINT RHN_ERRATAFILE_ID_NN;
ALTER TABLE RHNERRATAFILE MODIFY ID NOT NULL;

--
-- RHNERRATAFILE
--
ALTER TABLE RHNERRATAFILE DROP CONSTRAINT RHN_ERRATAFILE_MD5_NN;
ALTER TABLE RHNERRATAFILE MODIFY MD5SUM NOT NULL;

--
-- RHNERRATAFILE
--
ALTER TABLE RHNERRATAFILE DROP CONSTRAINT RHN_ERRATAFILE_MODIFIED_NN;
ALTER TABLE RHNERRATAFILE MODIFY MODIFIED NOT NULL;

--
-- RHNERRATAFILE
--
ALTER TABLE RHNERRATAFILE DROP CONSTRAINT RHN_ERRATAFILE_NAME_NN;
ALTER TABLE RHNERRATAFILE MODIFY FILENAME NOT NULL;

--
-- RHNERRATAFILETYPE
--
ALTER TABLE RHNERRATAFILETYPE DROP CONSTRAINT RHN_ERRATAFILE_TYPE_ID_NN;
ALTER TABLE RHNERRATAFILETYPE MODIFY ID NOT NULL;

--
-- RHNERRATAFILETYPE
--
ALTER TABLE RHNERRATAFILETYPE DROP CONSTRAINT RHN_ERRATAFILE_TYPE_LABEL_NN;
ALTER TABLE RHNERRATAFILETYPE MODIFY LABEL NOT NULL;

--
-- RHNERRATAFILE
--
ALTER TABLE RHNERRATAFILE DROP CONSTRAINT RHN_ERRATAFILE_TYPE_NN;
ALTER TABLE RHNERRATAFILE MODIFY TYPE NOT NULL;

--
-- RHNERRATATMP
--
ALTER TABLE RHNERRATATMP DROP CONSTRAINT RHN_ERRATATMP_ADVISORY_NAME_NN;
ALTER TABLE RHNERRATATMP MODIFY ADVISORY_NAME NOT NULL;

--
-- RHNERRATATMP
--
ALTER TABLE RHNERRATATMP DROP CONSTRAINT RHN_ERRATATMP_ADVISORY_NN;
ALTER TABLE RHNERRATATMP MODIFY ADVISORY NOT NULL;

--
-- RHNERRATATMP
--
ALTER TABLE RHNERRATATMP DROP CONSTRAINT RHN_ERRATATMP_ADVISORY_REL_NN;
ALTER TABLE RHNERRATATMP MODIFY ADVISORY_REL NOT NULL;

--
-- RHNERRATATMP
--
ALTER TABLE RHNERRATATMP DROP CONSTRAINT RHN_ERRATATMP_ADV_TYPE_NN;
ALTER TABLE RHNERRATATMP MODIFY ADVISORY_TYPE NOT NULL;

--
-- RHNERRATATMP
--
ALTER TABLE RHNERRATATMP DROP CONSTRAINT RHN_ERRATATMP_CREATED_NN;
ALTER TABLE RHNERRATATMP MODIFY CREATED NOT NULL;

--
-- RHNERRATATMP
--
ALTER TABLE RHNERRATATMP DROP CONSTRAINT RHN_ERRATATMP_ID_NN;
ALTER TABLE RHNERRATATMP MODIFY ID NOT NULL;

--
-- RHNERRATATMP
--
ALTER TABLE RHNERRATATMP DROP CONSTRAINT RHN_ERRATATMP_ISSUE_NN;
ALTER TABLE RHNERRATATMP MODIFY ISSUE_DATE NOT NULL;

--
-- RHNERRATATMP
--
ALTER TABLE RHNERRATATMP DROP CONSTRAINT RHN_ERRATATMP_LAST_MOD_NN;
ALTER TABLE RHNERRATATMP MODIFY LAST_MODIFIED NOT NULL;

--
-- RHNERRATATMP
--
ALTER TABLE RHNERRATATMP DROP CONSTRAINT RHN_ERRATATMP_MODIFIED_NN;
ALTER TABLE RHNERRATATMP MODIFY MODIFIED NOT NULL;

--
-- RHNERRATATMP
--
ALTER TABLE RHNERRATATMP DROP CONSTRAINT RHN_ERRATATMP_UPDATE_NN;
ALTER TABLE RHNERRATATMP MODIFY UPDATE_DATE NOT NULL;

--
-- RHNERRATA
--
ALTER TABLE RHNERRATA DROP CONSTRAINT RHN_ERRATA_ADVISORY_NAME_NN;
ALTER TABLE RHNERRATA MODIFY ADVISORY_NAME NOT NULL;

--
-- RHNERRATA
--
ALTER TABLE RHNERRATA DROP CONSTRAINT RHN_ERRATA_ADVISORY_NN;
ALTER TABLE RHNERRATA MODIFY ADVISORY NOT NULL;

--
-- RHNERRATA
--
ALTER TABLE RHNERRATA DROP CONSTRAINT RHN_ERRATA_ADVISORY_REL_NN;
ALTER TABLE RHNERRATA MODIFY ADVISORY_REL NOT NULL;

--
-- RHNERRATA
--
ALTER TABLE RHNERRATA DROP CONSTRAINT RHN_ERRATA_ADV_TYPE_NN;
ALTER TABLE RHNERRATA MODIFY ADVISORY_TYPE NOT NULL;

--
-- RHNERRATABUGLISTTMP
--
ALTER TABLE RHNERRATABUGLISTTMP DROP CONSTRAINT RHN_ERRATA_BUGLISTTMP_BID_NN;
ALTER TABLE RHNERRATABUGLISTTMP MODIFY BUG_ID NOT NULL;

--
-- RHNERRATABUGLISTTMP
--
ALTER TABLE RHNERRATABUGLISTTMP DROP CONSTRAINT RHN_ERRATA_BUGLISTTMP_C_NN;
ALTER TABLE RHNERRATABUGLISTTMP MODIFY CREATED NOT NULL;

--
-- RHNERRATABUGLISTTMP
--
ALTER TABLE RHNERRATABUGLISTTMP DROP CONSTRAINT RHN_ERRATA_BUGLISTTMP_EID_NN;
ALTER TABLE RHNERRATABUGLISTTMP MODIFY ERRATA_ID NOT NULL;

--
-- RHNERRATABUGLISTTMP
--
ALTER TABLE RHNERRATABUGLISTTMP DROP CONSTRAINT RHN_ERRATA_BUGLISTTMP_M_NN;
ALTER TABLE RHNERRATABUGLISTTMP MODIFY MODIFIED NOT NULL;

--
-- RHNERRATABUGLIST
--
ALTER TABLE RHNERRATABUGLIST DROP CONSTRAINT RHN_ERRATA_BUGLIST_BUG_NN;
ALTER TABLE RHNERRATABUGLIST MODIFY BUG_ID NOT NULL;

--
-- RHNERRATABUGLIST
--
ALTER TABLE RHNERRATABUGLIST DROP CONSTRAINT RHN_ERRATA_BUGLIST_CREATED_NN;
ALTER TABLE RHNERRATABUGLIST MODIFY CREATED NOT NULL;

--
-- RHNERRATABUGLIST
--
ALTER TABLE RHNERRATABUGLIST DROP CONSTRAINT RHN_ERRATA_BUGLIST_ERRATA_NN;
ALTER TABLE RHNERRATABUGLIST MODIFY ERRATA_ID NOT NULL;

--
-- RHNERRATABUGLIST
--
ALTER TABLE RHNERRATABUGLIST DROP CONSTRAINT RHN_ERRATA_BUGLIST_MODIFIED_NN;
ALTER TABLE RHNERRATABUGLIST MODIFY MODIFIED NOT NULL;

--
-- RHNERRATA
--
ALTER TABLE RHNERRATA DROP CONSTRAINT RHN_ERRATA_CREATED_NN;
ALTER TABLE RHNERRATA MODIFY CREATED NOT NULL;

--
-- RHNERRATA
--
ALTER TABLE RHNERRATA DROP CONSTRAINT RHN_ERRATA_ID_NN;
ALTER TABLE RHNERRATA MODIFY ID NOT NULL;

--
-- RHNERRATA
--
ALTER TABLE RHNERRATA DROP CONSTRAINT RHN_ERRATA_ISSUE_NN;
ALTER TABLE RHNERRATA MODIFY ISSUE_DATE NOT NULL;

--
-- RHNERRATA
--
ALTER TABLE RHNERRATA DROP CONSTRAINT RHN_ERRATA_LAST_MOD_NN;
ALTER TABLE RHNERRATA MODIFY LAST_MODIFIED NOT NULL;

--
-- RHNERRATA
--
ALTER TABLE RHNERRATA DROP CONSTRAINT RHN_ERRATA_MODIFIED_NN;
ALTER TABLE RHNERRATA MODIFY MODIFIED NOT NULL;

--
-- RHNERRATA
--
ALTER TABLE RHNERRATA DROP CONSTRAINT RHN_ERRATA_PRODUCT_NN;
ALTER TABLE RHNERRATA MODIFY PRODUCT NOT NULL;

--
-- RHNERRATASEVERITY
--
ALTER TABLE RHNERRATASEVERITY DROP CONSTRAINT RHN_ERRATA_SEV_ID_NN;
ALTER TABLE RHNERRATASEVERITY MODIFY ID NOT NULL;

--
-- RHNERRATASEVERITY
--
ALTER TABLE RHNERRATASEVERITY DROP CONSTRAINT RHN_ERRATA_SEV_LABEL_NN;
ALTER TABLE RHNERRATASEVERITY MODIFY LABEL NOT NULL;

--
-- RHNERRATASEVERITY
--
ALTER TABLE RHNERRATASEVERITY DROP CONSTRAINT RHN_ERRATA_SEV_RANK_NN;
ALTER TABLE RHNERRATASEVERITY MODIFY RANK NOT NULL;

--
-- RHNERRATA
--
ALTER TABLE RHNERRATA DROP CONSTRAINT RHN_ERRATA_SOLUTION_NN;
ALTER TABLE RHNERRATA MODIFY SOLUTION NOT NULL;

--
-- RHNERRATA
--
ALTER TABLE RHNERRATA DROP CONSTRAINT RHN_ERRATA_SYNOPSIS_NN;
ALTER TABLE RHNERRATA MODIFY SYNOPSIS NOT NULL;

--
-- RHNERRATA
--
ALTER TABLE RHNERRATA DROP CONSTRAINT RHN_ERRATA_UPDATE_NN;
ALTER TABLE RHNERRATA MODIFY UPDATE_DATE NOT NULL;

--
-- RHNERRATACVE
--
ALTER TABLE RHNERRATACVE DROP CONSTRAINT RHN_ERR_CVE_CID_NN;
ALTER TABLE RHNERRATACVE MODIFY CVE_ID NOT NULL;

--
-- RHNERRATACVE
--
ALTER TABLE RHNERRATACVE DROP CONSTRAINT RHN_ERR_CVE_CREATED_NN;
ALTER TABLE RHNERRATACVE MODIFY CREATED NOT NULL;

--
-- RHNERRATACVE
--
ALTER TABLE RHNERRATACVE DROP CONSTRAINT RHN_ERR_CVE_EID_NN;
ALTER TABLE RHNERRATACVE MODIFY ERRATA_ID NOT NULL;

--
-- RHNERRATACVE
--
ALTER TABLE RHNERRATACVE DROP CONSTRAINT RHN_ERR_CVE_MODIFIED_NN;
ALTER TABLE RHNERRATACVE MODIFY MODIFIED NOT NULL;

--
-- RHNERRATAKEYWORDTMP
--
ALTER TABLE RHNERRATAKEYWORDTMP DROP CONSTRAINT RHN_ERR_KEYWORDTMP_CREATED_NN;
ALTER TABLE RHNERRATAKEYWORDTMP MODIFY CREATED NOT NULL;

--
-- RHNERRATAKEYWORDTMP
--
ALTER TABLE RHNERRATAKEYWORDTMP DROP CONSTRAINT RHN_ERR_KEYWORDTMP_EID_NN;
ALTER TABLE RHNERRATAKEYWORDTMP MODIFY ERRATA_ID NOT NULL;

--
-- RHNERRATAKEYWORDTMP
--
ALTER TABLE RHNERRATAKEYWORDTMP DROP CONSTRAINT RHN_ERR_KEYWORDTMP_MODIFIED_NN;
ALTER TABLE RHNERRATAKEYWORDTMP MODIFY MODIFIED NOT NULL;

--
-- RHNERRATAKEYWORD
--
ALTER TABLE RHNERRATAKEYWORD DROP CONSTRAINT RHN_ERR_KEYWORD_CREATED_NN;
ALTER TABLE RHNERRATAKEYWORD MODIFY CREATED NOT NULL;

--
-- RHNERRATAKEYWORD
--
ALTER TABLE RHNERRATAKEYWORD DROP CONSTRAINT RHN_ERR_KEYWORD_EID_NN;
ALTER TABLE RHNERRATAKEYWORD MODIFY ERRATA_ID NOT NULL;

--
-- RHNERRATAKEYWORD
--
ALTER TABLE RHNERRATAKEYWORD DROP CONSTRAINT RHN_ERR_KEYWORD_MODIFIED_NN;
ALTER TABLE RHNERRATAKEYWORD MODIFY MODIFIED NOT NULL;

--
-- RHNERRATAPACKAGETMP
--
ALTER TABLE RHNERRATAPACKAGETMP DROP CONSTRAINT RHN_ERR_PKGTMP_CREATED_NN;
ALTER TABLE RHNERRATAPACKAGETMP MODIFY CREATED NOT NULL;

--
-- RHNERRATAPACKAGETMP
--
ALTER TABLE RHNERRATAPACKAGETMP DROP CONSTRAINT RHN_ERR_PKGTMP_EID_NN;
ALTER TABLE RHNERRATAPACKAGETMP MODIFY ERRATA_ID NOT NULL;

--
-- RHNERRATAPACKAGETMP
--
ALTER TABLE RHNERRATAPACKAGETMP DROP CONSTRAINT RHN_ERR_PKGTMP_MODIFIED_NN;
ALTER TABLE RHNERRATAPACKAGETMP MODIFY MODIFIED NOT NULL;

--
-- RHNERRATAPACKAGETMP
--
ALTER TABLE RHNERRATAPACKAGETMP DROP CONSTRAINT RHN_ERR_PKGTMP_PID_NN;
ALTER TABLE RHNERRATAPACKAGETMP MODIFY PACKAGE_ID NOT NULL;

--
-- RHNERRATAPACKAGE
--
ALTER TABLE RHNERRATAPACKAGE DROP CONSTRAINT RHN_ERR_PKG_CREATED_NN;
ALTER TABLE RHNERRATAPACKAGE MODIFY CREATED NOT NULL;

--
-- RHNERRATAPACKAGE
--
ALTER TABLE RHNERRATAPACKAGE DROP CONSTRAINT RHN_ERR_PKG_EID_NN;
ALTER TABLE RHNERRATAPACKAGE MODIFY ERRATA_ID NOT NULL;

--
-- RHNERRATAPACKAGE
--
ALTER TABLE RHNERRATAPACKAGE DROP CONSTRAINT RHN_ERR_PKG_MODIFIED_NN;
ALTER TABLE RHNERRATAPACKAGE MODIFY MODIFIED NOT NULL;

--
-- RHNERRATAPACKAGE
--
ALTER TABLE RHNERRATAPACKAGE DROP CONSTRAINT RHN_ERR_PKG_PID_NN;
ALTER TABLE RHNERRATAPACKAGE MODIFY PACKAGE_ID NOT NULL;

--
-- RHNEXCEPTION
--
ALTER TABLE RHNEXCEPTION DROP CONSTRAINT RHN_EXC_ID_NN;
ALTER TABLE RHNEXCEPTION MODIFY ID NOT NULL;

--
-- RHNEXCEPTION
--
ALTER TABLE RHNEXCEPTION DROP CONSTRAINT RHN_EXC_LABEL_NN;
ALTER TABLE RHNEXCEPTION MODIFY LABEL NOT NULL;

--
-- RHNEXCEPTION
--
ALTER TABLE RHNEXCEPTION DROP CONSTRAINT RHN_EXC_MSG_NN;
ALTER TABLE RHNEXCEPTION MODIFY MESSAGE NOT NULL;

--
-- RHNFEATURE
--
ALTER TABLE RHNFEATURE DROP CONSTRAINT RHN_FEATURE_CREATED_NN;
ALTER TABLE RHNFEATURE MODIFY CREATED NOT NULL;

--
-- RHNFEATURE
--
ALTER TABLE RHNFEATURE DROP CONSTRAINT RHN_FEATURE_LABEL_NN;
ALTER TABLE RHNFEATURE MODIFY LABEL NOT NULL;

--
-- RHNFEATURE
--
ALTER TABLE RHNFEATURE DROP CONSTRAINT RHN_FEATURE_MODIFIED_NN;
ALTER TABLE RHNFEATURE MODIFY MODIFIED NOT NULL;

--
-- RHNFEATURE
--
ALTER TABLE RHNFEATURE DROP CONSTRAINT RHN_FEATURE_NAME_NN;
ALTER TABLE RHNFEATURE MODIFY NAME NOT NULL;

--
-- RHNFILEDOWNLOAD
--
ALTER TABLE RHNFILEDOWNLOAD DROP CONSTRAINT RHN_FILEDL_FID_NN;
ALTER TABLE RHNFILEDOWNLOAD MODIFY FILE_ID NOT NULL;

--
-- RHNFILEDOWNLOAD
--
ALTER TABLE RHNFILEDOWNLOAD DROP CONSTRAINT RHN_FILEDL_LOCATION_NN;
ALTER TABLE RHNFILEDOWNLOAD MODIFY LOCATION NOT NULL;

--
-- RHNFILEDOWNLOAD
--
ALTER TABLE RHNFILEDOWNLOAD DROP CONSTRAINT RHN_FILEDL_RIP_NN;
ALTER TABLE RHNFILEDOWNLOAD MODIFY REQUESTOR_IP NOT NULL;

--
-- RHNFILEDOWNLOAD
--
ALTER TABLE RHNFILEDOWNLOAD DROP CONSTRAINT RHN_FILEDL_START_NN;
ALTER TABLE RHNFILEDOWNLOAD MODIFY START_TIME NOT NULL;

--
-- RHNFILELIST
--
ALTER TABLE RHNFILELIST DROP CONSTRAINT RHN_FILELIST_CREAT_NN;
ALTER TABLE RHNFILELIST MODIFY CREATED NOT NULL;

--
-- RHNFILELIST
--
ALTER TABLE RHNFILELIST DROP CONSTRAINT RHN_FILELIST_ID_NN;
ALTER TABLE RHNFILELIST MODIFY ID NOT NULL;

--
-- RHNFILELIST
--
ALTER TABLE RHNFILELIST DROP CONSTRAINT RHN_FILELIST_L_NN;
ALTER TABLE RHNFILELIST MODIFY LABEL NOT NULL;

--
-- RHNFILELIST
--
ALTER TABLE RHNFILELIST DROP CONSTRAINT RHN_FILELIST_MOD_NN;
ALTER TABLE RHNFILELIST MODIFY MODIFIED NOT NULL;

--
-- RHNFILELIST
--
ALTER TABLE RHNFILELIST DROP CONSTRAINT RHN_FILELIST_OID_NN;
ALTER TABLE RHNFILELIST MODIFY ORG_ID NOT NULL;

--
-- RHNFILELOCATION
--
ALTER TABLE RHNFILELOCATION DROP CONSTRAINT RHN_FILELOC_FID_NN;
ALTER TABLE RHNFILELOCATION MODIFY FILE_ID NOT NULL;

--
-- RHNFILELOCATION
--
ALTER TABLE RHNFILELOCATION DROP CONSTRAINT RHN_FILELOC_LOC_NN;
ALTER TABLE RHNFILELOCATION MODIFY LOCATION NOT NULL;

--
-- RHNFILE
--
ALTER TABLE RHNFILE DROP CONSTRAINT RHN_FILE_CREATED_NN;
ALTER TABLE RHNFILE MODIFY CREATED NOT NULL;

--
-- RHNFILE
--
ALTER TABLE RHNFILE DROP CONSTRAINT RHN_FILE_FS_NN;
ALTER TABLE RHNFILE MODIFY FILE_SIZE NOT NULL;

--
-- RHNFILE
--
ALTER TABLE RHNFILE DROP CONSTRAINT RHN_FILE_ID_NN;
ALTER TABLE RHNFILE MODIFY ID NOT NULL;

--
-- RHNFILE
--
ALTER TABLE RHNFILE DROP CONSTRAINT RHN_FILE_MD5SUM_NN;
ALTER TABLE RHNFILE MODIFY MD5SUM NOT NULL;

--
-- RHNFILE
--
ALTER TABLE RHNFILE DROP CONSTRAINT RHN_FILE_MODIFIED_NN;
ALTER TABLE RHNFILE MODIFY MODIFIED NOT NULL;

--
-- RHNFILE
--
ALTER TABLE RHNFILE DROP CONSTRAINT RHN_FILE_PATH_NN;
ALTER TABLE RHNFILE MODIFY PATH NOT NULL;

--
-- RHNFILELISTMEMBERS
--
ALTER TABLE RHNFILELISTMEMBERS DROP CONSTRAINT RHN_FLMEMBERS_CFNID_NN;
ALTER TABLE RHNFILELISTMEMBERS MODIFY CONFIG_FILE_NAME_ID NOT NULL;

--
-- RHNFILELISTMEMBERS
--
ALTER TABLE RHNFILELISTMEMBERS DROP CONSTRAINT RHN_FLMEMBERS_CREAT_NN;
ALTER TABLE RHNFILELISTMEMBERS MODIFY CREATED NOT NULL;

--
-- RHNFILELISTMEMBERS
--
ALTER TABLE RHNFILELISTMEMBERS DROP CONSTRAINT RHN_FLMEMBERS_FLID_NN;
ALTER TABLE RHNFILELISTMEMBERS MODIFY FILE_LIST_ID NOT NULL;

--
-- RHNFILELISTMEMBERS
--
ALTER TABLE RHNFILELISTMEMBERS DROP CONSTRAINT RHN_FLMEMBERS_MOD_NN;
ALTER TABLE RHNFILELISTMEMBERS MODIFY MODIFIED NOT NULL;

--
-- RHNGRAILCOMPONENTCHOICES
--
ALTER TABLE RHNGRAILCOMPONENTCHOICES DROP CONSTRAINT RHN_GRAIL_COMP_CH_MODE_NN;
ALTER TABLE RHNGRAILCOMPONENTCHOICES MODIFY COMPONENT_MODE NOT NULL;

--
-- RHNGRAILCOMPONENTCHOICES
--
ALTER TABLE RHNGRAILCOMPONENTCHOICES DROP CONSTRAINT RHN_GRAIL_COMP_CH_NN;
ALTER TABLE RHNGRAILCOMPONENTCHOICES MODIFY USER_ID NOT NULL;

--
-- RHNGRAILCOMPONENTCHOICES
--
ALTER TABLE RHNGRAILCOMPONENTCHOICES DROP CONSTRAINT RHN_GRAIL_COMP_CH_ORDER_NN;
ALTER TABLE RHNGRAILCOMPONENTCHOICES MODIFY ORDERING NOT NULL;

--
-- RHNGRAILCOMPONENTCHOICES
--
ALTER TABLE RHNGRAILCOMPONENTCHOICES DROP CONSTRAINT RHN_GRAIL_COMP_CH_PKG_NN;
ALTER TABLE RHNGRAILCOMPONENTCHOICES MODIFY COMPONENT_PKG NOT NULL;

--
-- RHNGRAILCOMPONENTS
--
ALTER TABLE RHNGRAILCOMPONENTS DROP CONSTRAINT RHN_GRAIL_COMP_MODE_NN;
ALTER TABLE RHNGRAILCOMPONENTS MODIFY COMPONENT_MODE NOT NULL;

--
-- RHNGRAILCOMPONENTS
--
ALTER TABLE RHNGRAILCOMPONENTS DROP CONSTRAINT RHN_GRAIL_COMP_PKG_NN;
ALTER TABLE RHNGRAILCOMPONENTS MODIFY COMPONENT_PKG NOT NULL;

--
-- RHN_SERVER_MONITORING_INFO
--
ALTER TABLE RHN_SERVER_MONITORING_INFO DROP CONSTRAINT RHN_HOST_RECID_NN;
ALTER TABLE RHN_SERVER_MONITORING_INFO MODIFY RECID NOT NULL;

--
-- RHN_HOST_CHECK_SUITES
--
ALTER TABLE RHN_HOST_CHECK_SUITES DROP CONSTRAINT RHN_HSTCK_HOST_PROBE_NN;
ALTER TABLE RHN_HOST_CHECK_SUITES MODIFY HOST_PROBE_ID NOT NULL;

--
-- RHN_HOST_CHECK_SUITES
--
ALTER TABLE RHN_HOST_CHECK_SUITES DROP CONSTRAINT RHN_HSTCK_SUITE_ID_NN;
ALTER TABLE RHN_HOST_CHECK_SUITES MODIFY SUITE_ID NOT NULL;

--
-- RHN_HOST_PROBE
--
ALTER TABLE RHN_HOST_PROBE DROP CONSTRAINT RHN_HSTPB_HOST_ID_NN;
ALTER TABLE RHN_HOST_PROBE MODIFY HOST_ID NOT NULL;

--
-- RHN_HOST_PROBE
--
ALTER TABLE RHN_HOST_PROBE DROP CONSTRAINT RHN_HSTPB_PROBE_ID_NN;
ALTER TABLE RHN_HOST_PROBE MODIFY PROBE_ID NOT NULL;

--
-- RHN_HOST_PROBE
--
ALTER TABLE RHN_HOST_PROBE DROP CONSTRAINT RHN_HSTPB_PROBE_TYPE_NN;
ALTER TABLE RHN_HOST_PROBE MODIFY PROBE_TYPE NOT NULL;

--
-- RHN_HOST_PROBE
--
ALTER TABLE RHN_HOST_PROBE DROP CONSTRAINT RHN_HSTPB_SAT_CL_ID_NN;
ALTER TABLE RHN_HOST_PROBE MODIFY SAT_CLUSTER_ID NOT NULL;

--
-- RHNINFOPANE
--
ALTER TABLE RHNINFOPANE DROP CONSTRAINT RHN_INFO_PANE_LABL_NN;
ALTER TABLE RHNINFOPANE MODIFY LABEL NOT NULL;

--
-- RHNKICKSTARTCOMMANDNAME
--
ALTER TABLE RHNKICKSTARTCOMMANDNAME DROP CONSTRAINT RHN_KSCOMMANDNAME_ID_NN;
ALTER TABLE RHNKICKSTARTCOMMANDNAME MODIFY ID NOT NULL;

--
-- RHNKICKSTARTCOMMANDNAME
--
ALTER TABLE RHNKICKSTARTCOMMANDNAME DROP CONSTRAINT RHN_KSCOMMANDNAME_REQRD_NN;
ALTER TABLE RHNKICKSTARTCOMMANDNAME MODIFY REQUIRED NOT NULL;

--
-- RHNKICKSTARTCOMMANDNAME
--
ALTER TABLE RHNKICKSTARTCOMMANDNAME DROP CONSTRAINT RHN_KSCOMMANDNAME_SORTORDR_NN;
ALTER TABLE RHNKICKSTARTCOMMANDNAME MODIFY SORT_ORDER NOT NULL;

--
-- RHNKICKSTARTCOMMANDNAME
--
ALTER TABLE RHNKICKSTARTCOMMANDNAME DROP CONSTRAINT RHN_KSCOMMANDNAME_USES_ARGS_NN;
ALTER TABLE RHNKICKSTARTCOMMANDNAME MODIFY USES_ARGUMENTS NOT NULL;

--
-- RHNKICKSTARTCOMMAND
--
ALTER TABLE RHNKICKSTARTCOMMAND DROP CONSTRAINT RHN_KSCOMMAND_CREATED_NN;
ALTER TABLE RHNKICKSTARTCOMMAND MODIFY CREATED NOT NULL;

--
-- RHNKICKSTARTCOMMAND
--
ALTER TABLE RHNKICKSTARTCOMMAND DROP CONSTRAINT RHN_KSCOMMAND_KCNID_NN;
ALTER TABLE RHNKICKSTARTCOMMAND MODIFY KS_COMMAND_NAME_ID NOT NULL;

--
-- RHNKICKSTARTCOMMAND
--
ALTER TABLE RHNKICKSTARTCOMMAND DROP CONSTRAINT RHN_KSCOMMAND_KSID_NN;
ALTER TABLE RHNKICKSTARTCOMMAND MODIFY KICKSTART_ID NOT NULL;

--
-- RHNKICKSTARTCOMMAND
--
ALTER TABLE RHNKICKSTARTCOMMAND DROP CONSTRAINT RHN_KSCOMMAND_MODIFIED_NN;
ALTER TABLE RHNKICKSTARTCOMMAND MODIFY MODIFIED NOT NULL;

--
-- RHNKICKSTARTCOMMANDNAME
--
ALTER TABLE RHNKICKSTARTCOMMANDNAME DROP CONSTRAINT RHN_KSCOMMAND_NAME_NN;
ALTER TABLE RHNKICKSTARTCOMMANDNAME MODIFY NAME NOT NULL;

--
-- RHNKICKSTARTDEFAULTREGTOKEN
--
ALTER TABLE RHNKICKSTARTDEFAULTREGTOKEN DROP CONSTRAINT RHN_KSDRT_CREAT_NN;
ALTER TABLE RHNKICKSTARTDEFAULTREGTOKEN MODIFY CREATED NOT NULL;

--
-- RHNKICKSTARTDEFAULTREGTOKEN
--
ALTER TABLE RHNKICKSTARTDEFAULTREGTOKEN DROP CONSTRAINT RHN_KSDRT_KSID_NN;
ALTER TABLE RHNKICKSTARTDEFAULTREGTOKEN MODIFY KICKSTART_ID NOT NULL;

--
-- RHNKICKSTARTDEFAULTREGTOKEN
--
ALTER TABLE RHNKICKSTARTDEFAULTREGTOKEN DROP CONSTRAINT RHN_KSDRT_MOD_NN;
ALTER TABLE RHNKICKSTARTDEFAULTREGTOKEN MODIFY MODIFIED NOT NULL;

--
-- RHNKICKSTARTDEFAULTREGTOKEN
--
ALTER TABLE RHNKICKSTARTDEFAULTREGTOKEN DROP CONSTRAINT RHN_KSDRT_RTID_NN;
ALTER TABLE RHNKICKSTARTDEFAULTREGTOKEN MODIFY REGTOKEN_ID NOT NULL;

--
-- RHNKICKSTARTDEFAULTS
--
ALTER TABLE RHNKICKSTARTDEFAULTS DROP CONSTRAINT RHN_KSD_CMF_NN;
ALTER TABLE RHNKICKSTARTDEFAULTS MODIFY CFG_MANAGEMENT_FLAG NOT NULL;

--
-- RHNKICKSTARTDEFAULTS
--
ALTER TABLE RHNKICKSTARTDEFAULTS DROP CONSTRAINT RHN_KSD_CREATED_NN;
ALTER TABLE RHNKICKSTARTDEFAULTS MODIFY CREATED NOT NULL;

--
-- RHNKICKSTARTDEFAULTS
--
ALTER TABLE RHNKICKSTARTDEFAULTS DROP CONSTRAINT RHN_KSD_KSID_NN;
ALTER TABLE RHNKICKSTARTDEFAULTS MODIFY KICKSTART_ID NOT NULL;

--
-- RHNKICKSTARTDEFAULTS
--
ALTER TABLE RHNKICKSTARTDEFAULTS DROP CONSTRAINT RHN_KSD_KSTID_NN;
ALTER TABLE RHNKICKSTARTDEFAULTS MODIFY KSTREE_ID NOT NULL;

--
-- RHNKICKSTARTDEFAULTS
--
ALTER TABLE RHNKICKSTARTDEFAULTS DROP CONSTRAINT RHN_KSD_KVT_NN;
ALTER TABLE RHNKICKSTARTDEFAULTS MODIFY VIRTUALIZATION_TYPE NOT NULL;

--
-- RHNKICKSTARTDEFAULTS
--
ALTER TABLE RHNKICKSTARTDEFAULTS DROP CONSTRAINT RHN_KSD_MODIFIED_NN;
ALTER TABLE RHNKICKSTARTDEFAULTS MODIFY MODIFIED NOT NULL;

--
-- RHNKICKSTARTDEFAULTS
--
ALTER TABLE RHNKICKSTARTDEFAULTS DROP CONSTRAINT RHN_KSD_RMF_NN;
ALTER TABLE RHNKICKSTARTDEFAULTS MODIFY REMOTE_COMMAND_FLAG NOT NULL;

--
-- RHNKSINSTALLTYPE
--
ALTER TABLE RHNKSINSTALLTYPE DROP CONSTRAINT RHN_KSINSTALLTYPE_CREATED_NN;
ALTER TABLE RHNKSINSTALLTYPE MODIFY CREATED NOT NULL;

--
-- RHNKSINSTALLTYPE
--
ALTER TABLE RHNKSINSTALLTYPE DROP CONSTRAINT RHN_KSINSTALLTYPE_ID_NN;
ALTER TABLE RHNKSINSTALLTYPE MODIFY ID NOT NULL;

--
-- RHNKSINSTALLTYPE
--
ALTER TABLE RHNKSINSTALLTYPE DROP CONSTRAINT RHN_KSINSTALLTYPE_LABEL_NN;
ALTER TABLE RHNKSINSTALLTYPE MODIFY LABEL NOT NULL;

--
-- RHNKSINSTALLTYPE
--
ALTER TABLE RHNKSINSTALLTYPE DROP CONSTRAINT RHN_KSINSTALLTYPE_MOD_NN;
ALTER TABLE RHNKSINSTALLTYPE MODIFY MODIFIED NOT NULL;

--
-- RHNKSINSTALLTYPE
--
ALTER TABLE RHNKSINSTALLTYPE DROP CONSTRAINT RHN_KSINSTALLTYPE_NAME_NN;
ALTER TABLE RHNKSINSTALLTYPE MODIFY NAME NOT NULL;

--
-- RHNKICKSTARTIPRANGE
--
ALTER TABLE RHNKICKSTARTIPRANGE DROP CONSTRAINT RHN_KSIP_CREATED_NN;
ALTER TABLE RHNKICKSTARTIPRANGE MODIFY CREATED NOT NULL;

--
-- RHNKICKSTARTIPRANGE
--
ALTER TABLE RHNKICKSTARTIPRANGE DROP CONSTRAINT RHN_KSIP_KSID_NN;
ALTER TABLE RHNKICKSTARTIPRANGE MODIFY KICKSTART_ID NOT NULL;

--
-- RHNKICKSTARTIPRANGE
--
ALTER TABLE RHNKICKSTARTIPRANGE DROP CONSTRAINT RHN_KSIP_MAX_NN;
ALTER TABLE RHNKICKSTARTIPRANGE MODIFY MAX NOT NULL;

--
-- RHNKICKSTARTIPRANGE
--
ALTER TABLE RHNKICKSTARTIPRANGE DROP CONSTRAINT RHN_KSIP_MIN_NN;
ALTER TABLE RHNKICKSTARTIPRANGE MODIFY MIN NOT NULL;

--
-- RHNKICKSTARTIPRANGE
--
ALTER TABLE RHNKICKSTARTIPRANGE DROP CONSTRAINT RHN_KSIP_MODIFIED_NN;
ALTER TABLE RHNKICKSTARTIPRANGE MODIFY MODIFIED NOT NULL;

--
-- RHNKICKSTARTIPRANGE
--
ALTER TABLE RHNKICKSTARTIPRANGE DROP CONSTRAINT RHN_KSIP_OID_NN;
ALTER TABLE RHNKICKSTARTIPRANGE MODIFY ORG_ID NOT NULL;

--
-- RHNKICKSTARTPACKAGE
--
ALTER TABLE RHNKICKSTARTPACKAGE DROP CONSTRAINT RHN_KSPACKAGE_CREATED_NN;
ALTER TABLE RHNKICKSTARTPACKAGE MODIFY CREATED NOT NULL;

--
-- RHNKICKSTARTPACKAGE
--
ALTER TABLE RHNKICKSTARTPACKAGE DROP CONSTRAINT RHN_KSPACKAGE_KSID_NN;
ALTER TABLE RHNKICKSTARTPACKAGE MODIFY KICKSTART_ID NOT NULL;

--
-- RHNKICKSTARTPACKAGE
--
ALTER TABLE RHNKICKSTARTPACKAGE DROP CONSTRAINT RHN_KSPACKAGE_MODIFIED_NN;
ALTER TABLE RHNKICKSTARTPACKAGE MODIFY MODIFIED NOT NULL;

--
-- RHNKICKSTARTPACKAGE
--
ALTER TABLE RHNKICKSTARTPACKAGE DROP CONSTRAINT RHN_KSPACKAGE_PNID_NN;
ALTER TABLE RHNKICKSTARTPACKAGE MODIFY PACKAGE_NAME_ID NOT NULL;

--
-- RHNKICKSTARTPRESERVEFILELIST
--
ALTER TABLE RHNKICKSTARTPRESERVEFILELIST DROP CONSTRAINT RHN_KSPRESERVEFL_CREAT_NN;
ALTER TABLE RHNKICKSTARTPRESERVEFILELIST MODIFY CREATED NOT NULL;

--
-- RHNKICKSTARTPRESERVEFILELIST
--
ALTER TABLE RHNKICKSTARTPRESERVEFILELIST DROP CONSTRAINT RHN_KSPRESERVEFL_FLID_NN;
ALTER TABLE RHNKICKSTARTPRESERVEFILELIST MODIFY FILE_LIST_ID NOT NULL;

--
-- RHNKICKSTARTPRESERVEFILELIST
--
ALTER TABLE RHNKICKSTARTPRESERVEFILELIST DROP CONSTRAINT RHN_KSPRESERVEFL_KSID_NN;
ALTER TABLE RHNKICKSTARTPRESERVEFILELIST MODIFY KICKSTART_ID NOT NULL;

--
-- RHNKICKSTARTPRESERVEFILELIST
--
ALTER TABLE RHNKICKSTARTPRESERVEFILELIST DROP CONSTRAINT RHN_KSPRESERVEFL_MOD_NN;
ALTER TABLE RHNKICKSTARTPRESERVEFILELIST MODIFY MODIFIED NOT NULL;

--
-- RHNKICKSTARTSCRIPT
--
ALTER TABLE RHNKICKSTARTSCRIPT DROP CONSTRAINT RHN_KSSCRIPT_CHROOT_NN;
ALTER TABLE RHNKICKSTARTSCRIPT MODIFY CHROOT NOT NULL;

--
-- RHNKICKSTARTSCRIPT
--
ALTER TABLE RHNKICKSTARTSCRIPT DROP CONSTRAINT RHN_KSSCRIPT_CREAT_NN;
ALTER TABLE RHNKICKSTARTSCRIPT MODIFY CREATED NOT NULL;

--
-- RHNKICKSTARTSCRIPT
--
ALTER TABLE RHNKICKSTARTSCRIPT DROP CONSTRAINT RHN_KSSCRIPT_ID_NN;
ALTER TABLE RHNKICKSTARTSCRIPT MODIFY ID NOT NULL;

--
-- RHNKICKSTARTSCRIPT
--
ALTER TABLE RHNKICKSTARTSCRIPT DROP CONSTRAINT RHN_KSSCRIPT_KSID_NN;
ALTER TABLE RHNKICKSTARTSCRIPT MODIFY KICKSTART_ID NOT NULL;

--
-- RHNKICKSTARTSCRIPT
--
ALTER TABLE RHNKICKSTARTSCRIPT DROP CONSTRAINT RHN_KSSCRIPT_MOD_NN;
ALTER TABLE RHNKICKSTARTSCRIPT MODIFY MODIFIED NOT NULL;

--
-- RHNKICKSTARTSCRIPT
--
ALTER TABLE RHNKICKSTARTSCRIPT DROP CONSTRAINT RHN_KSSCRIPT_POS_NN;
ALTER TABLE RHNKICKSTARTSCRIPT MODIFY POSITION NOT NULL;

--
-- RHNKICKSTARTSCRIPT
--
ALTER TABLE RHNKICKSTARTSCRIPT DROP CONSTRAINT RHN_KSSCRIPT_RAW_NN;
ALTER TABLE RHNKICKSTARTSCRIPT MODIFY RAW_SCRIPT NOT NULL;

--
-- RHNKICKSTARTSCRIPT
--
ALTER TABLE RHNKICKSTARTSCRIPT DROP CONSTRAINT RHN_KSSCRIPT_ST_NN;
ALTER TABLE RHNKICKSTARTSCRIPT MODIFY SCRIPT_TYPE NOT NULL;

--
-- RHNKICKSTARTSESSION
--
ALTER TABLE RHNKICKSTARTSESSION DROP CONSTRAINT RHN_KSS_KVT_NN;
ALTER TABLE RHNKICKSTARTSESSION MODIFY VIRTUALIZATION_TYPE NOT NULL;

--
-- RHNKSTREEFILE
--
ALTER TABLE RHNKSTREEFILE DROP CONSTRAINT RHN_KSTREEFILE_CREATED_NN;
ALTER TABLE RHNKSTREEFILE MODIFY CREATED NOT NULL;

--
-- RHNKSTREEFILE
--
ALTER TABLE RHNKSTREEFILE DROP CONSTRAINT RHN_KSTREEFILE_FILE_SIZE_NN;
ALTER TABLE RHNKSTREEFILE MODIFY FILE_SIZE NOT NULL;

--
-- RHNKSTREEFILE
--
ALTER TABLE RHNKSTREEFILE DROP CONSTRAINT RHN_KSTREEFILE_KID_NN;
ALTER TABLE RHNKSTREEFILE MODIFY KSTREE_ID NOT NULL;

--
-- RHNKSTREEFILE
--
ALTER TABLE RHNKSTREEFILE DROP CONSTRAINT RHN_KSTREEFILE_LASTMOD_NN;
ALTER TABLE RHNKSTREEFILE MODIFY LAST_MODIFIED NOT NULL;

--
-- RHNKSTREEFILE
--
ALTER TABLE RHNKSTREEFILE DROP CONSTRAINT RHN_KSTREEFILE_MD5SUM_NN;
ALTER TABLE RHNKSTREEFILE MODIFY MD5SUM NOT NULL;

--
-- RHNKSTREEFILE
--
ALTER TABLE RHNKSTREEFILE DROP CONSTRAINT RHN_KSTREEFILE_MODIFIED_NN;
ALTER TABLE RHNKSTREEFILE MODIFY MODIFIED NOT NULL;

--
-- RHNKSTREEFILE
--
ALTER TABLE RHNKSTREEFILE DROP CONSTRAINT RHN_KSTREEFILE_RFN_NN;
ALTER TABLE RHNKSTREEFILE MODIFY RELATIVE_FILENAME NOT NULL;

--
-- RHNKSTREETYPE
--
ALTER TABLE RHNKSTREETYPE DROP CONSTRAINT RHN_KSTREETYPE_CREATED_NN;
ALTER TABLE RHNKSTREETYPE MODIFY CREATED NOT NULL;

--
-- RHNKSTREETYPE
--
ALTER TABLE RHNKSTREETYPE DROP CONSTRAINT RHN_KSTREETYPE_ID_NN;
ALTER TABLE RHNKSTREETYPE MODIFY ID NOT NULL;

--
-- RHNKSTREETYPE
--
ALTER TABLE RHNKSTREETYPE DROP CONSTRAINT RHN_KSTREETYPE_LABEL_NN;
ALTER TABLE RHNKSTREETYPE MODIFY LABEL NOT NULL;

--
-- RHNKSTREETYPE
--
ALTER TABLE RHNKSTREETYPE DROP CONSTRAINT RHN_KSTREETYPE_MOD_NN;
ALTER TABLE RHNKSTREETYPE MODIFY MODIFIED NOT NULL;

--
-- RHNKSTREETYPE
--
ALTER TABLE RHNKSTREETYPE DROP CONSTRAINT RHN_KSTREETYPE_NAME_NN;
ALTER TABLE RHNKSTREETYPE MODIFY NAME NOT NULL;

--
-- RHNKICKSTARTABLETREE
--
ALTER TABLE RHNKICKSTARTABLETREE DROP CONSTRAINT RHN_KSTREE_BP_NN;
ALTER TABLE RHNKICKSTARTABLETREE MODIFY BASE_PATH NOT NULL;

--
-- RHNKICKSTARTABLETREE
--
ALTER TABLE RHNKICKSTARTABLETREE DROP CONSTRAINT RHN_KSTREE_CID_NN;
ALTER TABLE RHNKICKSTARTABLETREE MODIFY CHANNEL_ID NOT NULL;

--
-- RHNKICKSTARTABLETREE
--
ALTER TABLE RHNKICKSTARTABLETREE DROP CONSTRAINT RHN_KSTREE_CREATED_NN;
ALTER TABLE RHNKICKSTARTABLETREE MODIFY CREATED NOT NULL;

--
-- RHNKICKSTARTABLETREE
--
ALTER TABLE RHNKICKSTARTABLETREE DROP CONSTRAINT RHN_KSTREE_ID_NN;
ALTER TABLE RHNKICKSTARTABLETREE MODIFY ID NOT NULL;

--
-- RHNKICKSTARTABLETREE
--
ALTER TABLE RHNKICKSTARTABLETREE DROP CONSTRAINT RHN_KSTREE_IT_NN;
ALTER TABLE RHNKICKSTARTABLETREE MODIFY INSTALL_TYPE NOT NULL;

--
-- RHNKICKSTARTABLETREE
--
ALTER TABLE RHNKICKSTARTABLETREE DROP CONSTRAINT RHN_KSTREE_KSTREETYPE_NN;
ALTER TABLE RHNKICKSTARTABLETREE MODIFY KSTREE_TYPE NOT NULL;

--
-- RHNKICKSTARTABLETREE
--
ALTER TABLE RHNKICKSTARTABLETREE DROP CONSTRAINT RHN_KSTREE_LABEL_NN;
ALTER TABLE RHNKICKSTARTABLETREE MODIFY LABEL NOT NULL;

--
-- RHNKICKSTARTABLETREE
--
ALTER TABLE RHNKICKSTARTABLETREE DROP CONSTRAINT RHN_KSTREE_LASTMOD_NN;
ALTER TABLE RHNKICKSTARTABLETREE MODIFY LAST_MODIFIED NOT NULL;

--
-- RHNKICKSTARTABLETREE
--
ALTER TABLE RHNKICKSTARTABLETREE DROP CONSTRAINT RHN_KSTREE_MODIFIED_NN;
ALTER TABLE RHNKICKSTARTABLETREE MODIFY MODIFIED NOT NULL;

--
-- RHNKSDATA
--
ALTER TABLE RHNKSDATA DROP CONSTRAINT RHN_KS_ACTIVE_NN;
ALTER TABLE RHNKSDATA MODIFY ACTIVE NOT NULL;

--
-- RHNKICKSTARTCHILDCHANNEL
--
ALTER TABLE RHNKICKSTARTCHILDCHANNEL DROP CONSTRAINT RHN_KS_CC_CID_NN;
ALTER TABLE RHNKICKSTARTCHILDCHANNEL MODIFY CHANNEL_ID NOT NULL;

--
-- RHNKICKSTARTCHILDCHANNEL
--
ALTER TABLE RHNKICKSTARTCHILDCHANNEL DROP CONSTRAINT RHN_KS_CC_CRE_NN;
ALTER TABLE RHNKICKSTARTCHILDCHANNEL MODIFY CREATED NOT NULL;

--
-- RHNKICKSTARTCHILDCHANNEL
--
ALTER TABLE RHNKICKSTARTCHILDCHANNEL DROP CONSTRAINT RHN_KS_CC_KSD_NN;
ALTER TABLE RHNKICKSTARTCHILDCHANNEL MODIFY KSDATA_ID NOT NULL;

--
-- RHNKICKSTARTCHILDCHANNEL
--
ALTER TABLE RHNKICKSTARTCHILDCHANNEL DROP CONSTRAINT RHN_KS_CC_MOD_NN;
ALTER TABLE RHNKICKSTARTCHILDCHANNEL MODIFY MODIFIED NOT NULL;

--
-- RHNKSDATA
--
ALTER TABLE RHNKSDATA DROP CONSTRAINT RHN_KS_CFG_SAVE_NN;
ALTER TABLE RHNKSDATA MODIFY KSCFG NOT NULL;

--
-- RHNKSDATA
--
ALTER TABLE RHNKSDATA DROP CONSTRAINT RHN_KS_CREATED_NN;
ALTER TABLE RHNKSDATA MODIFY CREATED NOT NULL;

--
-- RHNKSDATA
--
ALTER TABLE RHNKSDATA DROP CONSTRAINT RHN_KS_DEFAULT_NN;
ALTER TABLE RHNKSDATA MODIFY IS_ORG_DEFAULT NOT NULL;

--
-- RHNKSDATA
--
ALTER TABLE RHNKSDATA DROP CONSTRAINT RHN_KS_ID_NN;
ALTER TABLE RHNKSDATA MODIFY ID NOT NULL;

--
-- RHNKSDATA
--
ALTER TABLE RHNKSDATA DROP CONSTRAINT RHN_KS_LABEL_NN;
ALTER TABLE RHNKSDATA MODIFY LABEL NOT NULL;

--
-- RHNKSDATA
--
ALTER TABLE RHNKSDATA DROP CONSTRAINT RHN_KS_MODIFIED_NN;
ALTER TABLE RHNKSDATA MODIFY MODIFIED NOT NULL;

--
-- RHNKSDATA
--
ALTER TABLE RHNKSDATA DROP CONSTRAINT RHN_KS_NONCHROOT_POST_NN;
ALTER TABLE RHNKSDATA MODIFY NONCHROOTPOST NOT NULL;

--
-- RHNKSDATA
--
ALTER TABLE RHNKSDATA DROP CONSTRAINT RHN_KS_OID_NN;
ALTER TABLE RHNKSDATA MODIFY ORG_ID NOT NULL;

--
-- RHNKSDATA
--
ALTER TABLE RHNKSDATA DROP CONSTRAINT RHN_KS_POST_LOG_NN;
ALTER TABLE RHNKSDATA MODIFY POSTLOG NOT NULL;

--
-- RHNKSDATA
--
ALTER TABLE RHNKSDATA DROP CONSTRAINT RHN_KS_PRE_LOG_NN;
ALTER TABLE RHNKSDATA MODIFY PRELOG NOT NULL;

--
-- RHNKICKSTARTSESSIONHISTORY
--
ALTER TABLE RHNKICKSTARTSESSIONHISTORY DROP CONSTRAINT RHN_KS_SESSIONHIST_CREAT_NN;
ALTER TABLE RHNKICKSTARTSESSIONHISTORY MODIFY CREATED NOT NULL;

--
-- RHNKICKSTARTSESSIONHISTORY
--
ALTER TABLE RHNKICKSTARTSESSIONHISTORY DROP CONSTRAINT RHN_KS_SESSIONHIST_ID_NN;
ALTER TABLE RHNKICKSTARTSESSIONHISTORY MODIFY ID NOT NULL;

--
-- RHNKICKSTARTSESSIONHISTORY
--
ALTER TABLE RHNKICKSTARTSESSIONHISTORY DROP CONSTRAINT RHN_KS_SESSIONHIST_KSID_NN;
ALTER TABLE RHNKICKSTARTSESSIONHISTORY MODIFY KICKSTART_SESSION_ID NOT NULL;

--
-- RHNKICKSTARTSESSIONHISTORY
--
ALTER TABLE RHNKICKSTARTSESSIONHISTORY DROP CONSTRAINT RHN_KS_SESSIONHIST_MOD_NN;
ALTER TABLE RHNKICKSTARTSESSIONHISTORY MODIFY MODIFIED NOT NULL;

--
-- RHNKICKSTARTSESSIONHISTORY
--
ALTER TABLE RHNKICKSTARTSESSIONHISTORY DROP CONSTRAINT RHN_KS_SESSIONHIST_STAT_NN;
ALTER TABLE RHNKICKSTARTSESSIONHISTORY MODIFY STATE_ID NOT NULL;

--
-- RHNKICKSTARTSESSIONHISTORY
--
ALTER TABLE RHNKICKSTARTSESSIONHISTORY DROP CONSTRAINT RHN_KS_SESSIONHIST_TIME_NN;
ALTER TABLE RHNKICKSTARTSESSIONHISTORY MODIFY TIME NOT NULL;

--
-- RHNKICKSTARTSESSION
--
ALTER TABLE RHNKICKSTARTSESSION DROP CONSTRAINT RHN_KS_SESSION_CREATED_NN;
ALTER TABLE RHNKICKSTARTSESSION MODIFY CREATED NOT NULL;

--
-- RHNKICKSTARTSESSION
--
ALTER TABLE RHNKICKSTARTSESSION DROP CONSTRAINT RHN_KS_SESSION_DC_NN;
ALTER TABLE RHNKICKSTARTSESSION MODIFY DEPLOY_CONFIGS NOT NULL;

--
-- RHNKICKSTARTSESSION
--
ALTER TABLE RHNKICKSTARTSESSION DROP CONSTRAINT RHN_KS_SESSION_ID_NN;
ALTER TABLE RHNKICKSTARTSESSION MODIFY ID NOT NULL;

--
-- RHNKICKSTARTSESSION
--
ALTER TABLE RHNKICKSTARTSESSION DROP CONSTRAINT RHN_KS_SESSION_KSSSID_NN;
ALTER TABLE RHNKICKSTARTSESSION MODIFY STATE_ID NOT NULL;

--
-- RHNKICKSTARTSESSION
--
ALTER TABLE RHNKICKSTARTSESSION DROP CONSTRAINT RHN_KS_SESSION_LAST_ACTION_NN;
ALTER TABLE RHNKICKSTARTSESSION MODIFY LAST_ACTION NOT NULL;

--
-- RHNKICKSTARTSESSION
--
ALTER TABLE RHNKICKSTARTSESSION DROP CONSTRAINT RHN_KS_SESSION_MODIFIED_NN;
ALTER TABLE RHNKICKSTARTSESSION MODIFY MODIFIED NOT NULL;

--
-- RHNKICKSTARTSESSION
--
ALTER TABLE RHNKICKSTARTSESSION DROP CONSTRAINT RHN_KS_SESSION_OID_NN;
ALTER TABLE RHNKICKSTARTSESSION MODIFY ORG_ID NOT NULL;

--
-- RHNKICKSTARTSESSION
--
ALTER TABLE RHNKICKSTARTSESSION DROP CONSTRAINT RHN_KS_SESSION_PFC_NN;
ALTER TABLE RHNKICKSTARTSESSION MODIFY PACKAGE_FETCH_COUNT NOT NULL;

--
-- RHNKICKSTARTSESSIONSTATE
--
ALTER TABLE RHNKICKSTARTSESSIONSTATE DROP CONSTRAINT RHN_KS_SESSION_STATE_CREAT_NN;
ALTER TABLE RHNKICKSTARTSESSIONSTATE MODIFY CREATED NOT NULL;

--
-- RHNKICKSTARTSESSIONSTATE
--
ALTER TABLE RHNKICKSTARTSESSIONSTATE DROP CONSTRAINT RHN_KS_SESSION_STATE_DESC_NN;
ALTER TABLE RHNKICKSTARTSESSIONSTATE MODIFY DESCRIPTION NOT NULL;

--
-- RHNKICKSTARTSESSIONSTATE
--
ALTER TABLE RHNKICKSTARTSESSIONSTATE DROP CONSTRAINT RHN_KS_SESSION_STATE_ID_NN;
ALTER TABLE RHNKICKSTARTSESSIONSTATE MODIFY ID NOT NULL;

--
-- RHNKICKSTARTSESSIONSTATE
--
ALTER TABLE RHNKICKSTARTSESSIONSTATE DROP CONSTRAINT RHN_KS_SESSION_STATE_LABEL_NN;
ALTER TABLE RHNKICKSTARTSESSIONSTATE MODIFY LABEL NOT NULL;

--
-- RHNKICKSTARTSESSIONSTATE
--
ALTER TABLE RHNKICKSTARTSESSIONSTATE DROP CONSTRAINT RHN_KS_SESSION_STATE_MOD_NN;
ALTER TABLE RHNKICKSTARTSESSIONSTATE MODIFY MODIFIED NOT NULL;

--
-- RHNKICKSTARTSESSIONSTATE
--
ALTER TABLE RHNKICKSTARTSESSIONSTATE DROP CONSTRAINT RHN_KS_SESSION_STATE_NAME_NN;
ALTER TABLE RHNKICKSTARTSESSIONSTATE MODIFY NAME NOT NULL;

--
-- RHNKICKSTARTTIMEZONE
--
ALTER TABLE RHNKICKSTARTTIMEZONE DROP CONSTRAINT RHN_KS_TIMEZONE_ID_NN;
ALTER TABLE RHNKICKSTARTTIMEZONE MODIFY ID NOT NULL;

--
-- RHNKICKSTARTTIMEZONE
--
ALTER TABLE RHNKICKSTARTTIMEZONE DROP CONSTRAINT RHN_KS_TIMEZONE_IT_NN;
ALTER TABLE RHNKICKSTARTTIMEZONE MODIFY INSTALL_TYPE NOT NULL;

--
-- RHNKICKSTARTTIMEZONE
--
ALTER TABLE RHNKICKSTARTTIMEZONE DROP CONSTRAINT RHN_KS_TIMEZONE_LABEL_NN;
ALTER TABLE RHNKICKSTARTTIMEZONE MODIFY LABEL NOT NULL;

--
-- RHNKICKSTARTTIMEZONE
--
ALTER TABLE RHNKICKSTARTTIMEZONE DROP CONSTRAINT RHN_KS_TIMEZONE_NAME_NN;
ALTER TABLE RHNKICKSTARTTIMEZONE MODIFY NAME NOT NULL;

--
-- RHNKSDATA
--
ALTER TABLE RHNKSDATA DROP CONSTRAINT RHN_KS_TYPE_NN;
ALTER TABLE RHNKSDATA MODIFY KS_TYPE NOT NULL;

--
-- RHNKSDATA
--
ALTER TABLE RHNKSDATA DROP CONSTRAINT RHN_KS_VERBOSE_UP2DATE_NN;
ALTER TABLE RHNKSDATA MODIFY VERBOSEUP2DATE NOT NULL;

--
-- RHNKICKSTARTVIRTUALIZATIONTYPE
--
ALTER TABLE RHNKICKSTARTVIRTUALIZATIONTYPE DROP CONSTRAINT RHN_KVT_CREATED_NN;
ALTER TABLE RHNKICKSTARTVIRTUALIZATIONTYPE MODIFY CREATED NOT NULL;

--
-- RHNKICKSTARTVIRTUALIZATIONTYPE
--
ALTER TABLE RHNKICKSTARTVIRTUALIZATIONTYPE DROP CONSTRAINT RHN_KVT_ID_NN;
ALTER TABLE RHNKICKSTARTVIRTUALIZATIONTYPE MODIFY ID NOT NULL;

--
-- RHNKICKSTARTVIRTUALIZATIONTYPE
--
ALTER TABLE RHNKICKSTARTVIRTUALIZATIONTYPE DROP CONSTRAINT RHN_KVT_LABEL_NN;
ALTER TABLE RHNKICKSTARTVIRTUALIZATIONTYPE MODIFY LABEL NOT NULL;

--
-- RHNKICKSTARTVIRTUALIZATIONTYPE
--
ALTER TABLE RHNKICKSTARTVIRTUALIZATIONTYPE DROP CONSTRAINT RHN_KVT_MODIFIED_NN;
ALTER TABLE RHNKICKSTARTVIRTUALIZATIONTYPE MODIFY MODIFIED NOT NULL;

--
-- RHNKICKSTARTVIRTUALIZATIONTYPE
--
ALTER TABLE RHNKICKSTARTVIRTUALIZATIONTYPE DROP CONSTRAINT RHN_KVT_NAME_NN;
ALTER TABLE RHNKICKSTARTVIRTUALIZATIONTYPE MODIFY NAME NOT NULL;

--
-- RHN_LL_NETSAINT
--
ALTER TABLE RHN_LL_NETSAINT DROP CONSTRAINT RHN_LLNET_NETSAINT_ID_NN;
ALTER TABLE RHN_LL_NETSAINT MODIFY NETSAINT_ID NOT NULL;

--
-- RHN_METRICS
--
ALTER TABLE RHN_METRICS DROP CONSTRAINT RHN_METRIC_CMD_CLASS_NN;
ALTER TABLE RHN_METRICS MODIFY COMMAND_CLASS NOT NULL;

--
-- RHN_METRICS
--
ALTER TABLE RHN_METRICS DROP CONSTRAINT RHN_METRIC_METRIC_ID_NN;
ALTER TABLE RHN_METRICS MODIFY METRIC_ID NOT NULL;

--
-- RHN_METRICS
--
ALTER TABLE RHN_METRICS DROP CONSTRAINT RHN_METRIC_STORAGE_ID_NN;
ALTER TABLE RHN_METRICS MODIFY STORAGE_UNIT_ID NOT NULL;

--
-- RHN_INTERFACE_MONITORING
--
ALTER TABLE RHN_INTERFACE_MONITORING DROP CONSTRAINT RHN_MONIF_SERVER_ID_NN;
ALTER TABLE RHN_INTERFACE_MONITORING MODIFY SERVER_ID NOT NULL;

--
-- RHN_INTERFACE_MONITORING
--
ALTER TABLE RHN_INTERFACE_MONITORING DROP CONSTRAINT RHN_MONIF_SERVER_NAME_NN;
ALTER TABLE RHN_INTERFACE_MONITORING MODIFY SERVER_NAME NOT NULL;

--
-- RHNMONITORGRANULARITY
--
ALTER TABLE RHNMONITORGRANULARITY DROP CONSTRAINT RHN_MONITORGRAN_ID_NN;
ALTER TABLE RHNMONITORGRANULARITY MODIFY ID NOT NULL;

--
-- RHNMONITORGRANULARITY
--
ALTER TABLE RHNMONITORGRANULARITY DROP CONSTRAINT RHN_MONITORGRAN_LABEL_NN;
ALTER TABLE RHNMONITORGRANULARITY MODIFY LABEL NOT NULL;

--
-- RHNMONITOR
--
ALTER TABLE RHNMONITOR DROP CONSTRAINT RHN_MONITOR_BID_NN;
ALTER TABLE RHNMONITOR MODIFY BATCH_ID NOT NULL;

--
-- RHNMONITOR
--
ALTER TABLE RHNMONITOR DROP CONSTRAINT RHN_MONITOR_GRANULARITY_NN;
ALTER TABLE RHNMONITOR MODIFY GRANULARITY NOT NULL;

--
-- RHNMONITOR
--
ALTER TABLE RHNMONITOR DROP CONSTRAINT RHN_MONITOR_PROBE_NN;
ALTER TABLE RHNMONITOR MODIFY PROBE_ID NOT NULL;

--
-- RHNMONITOR
--
ALTER TABLE RHNMONITOR DROP CONSTRAINT RHN_MONITOR_SID_NN;
ALTER TABLE RHNMONITOR MODIFY SERVER_ID NOT NULL;

--
-- RHNMONITOR
--
ALTER TABLE RHNMONITOR DROP CONSTRAINT RHN_MONITOR_TS_NN;
ALTER TABLE RHNMONITOR MODIFY TIMESTAMP NOT NULL;

--
-- RHN_MULTI_SCOUT_THRESHOLD
--
ALTER TABLE RHN_MULTI_SCOUT_THRESHOLD DROP CONSTRAINT RHN_MSTHR_PROBE_ID_NN;
ALTER TABLE RHN_MULTI_SCOUT_THRESHOLD MODIFY PROBE_ID NOT NULL;

--
-- RHN_METHOD_TYPES
--
ALTER TABLE RHN_METHOD_TYPES DROP CONSTRAINT RHN_MTHTP_NOTIF_FMT_NN;
ALTER TABLE RHN_METHOD_TYPES MODIFY NOTIFICATION_FORMAT_ID NOT NULL;

--
-- RHN_METHOD_TYPES
--
ALTER TABLE RHN_METHOD_TYPES DROP CONSTRAINT RHN_MTHTP_RECID_NN;
ALTER TABLE RHN_METHOD_TYPES MODIFY RECID NOT NULL;

--
-- RHNMESSAGE
--
ALTER TABLE RHNMESSAGE DROP CONSTRAINT RHN_M_CREATED_NN;
ALTER TABLE RHNMESSAGE MODIFY CREATED NOT NULL;

--
-- RHNMESSAGE
--
ALTER TABLE RHNMESSAGE DROP CONSTRAINT RHN_M_ID_NN;
ALTER TABLE RHNMESSAGE MODIFY ID NOT NULL;

--
-- RHNMESSAGE
--
ALTER TABLE RHNMESSAGE DROP CONSTRAINT RHN_M_MODIFIED_NN;
ALTER TABLE RHNMESSAGE MODIFY MODIFIED NOT NULL;

--
-- RHNMESSAGE
--
ALTER TABLE RHNMESSAGE DROP CONSTRAINT RHN_M_MT_NN;
ALTER TABLE RHNMESSAGE MODIFY MESSAGE_TYPE NOT NULL;

--
-- RHNMESSAGEPRIORITY
--
ALTER TABLE RHNMESSAGEPRIORITY DROP CONSTRAINT RHN_M_PRIORITY_ID_NN;
ALTER TABLE RHNMESSAGEPRIORITY MODIFY ID NOT NULL;

--
-- RHNMESSAGEPRIORITY
--
ALTER TABLE RHNMESSAGEPRIORITY DROP CONSTRAINT RHN_M_PRIORITY_LABEL_NN;
ALTER TABLE RHNMESSAGEPRIORITY MODIFY LABEL NOT NULL;

--
-- RHNMESSAGE
--
ALTER TABLE RHNMESSAGE DROP CONSTRAINT RHN_M_PRIORITY_NN;
ALTER TABLE RHNMESSAGE MODIFY PRIORITY NOT NULL;

--
-- RHNMESSAGETYPE
--
ALTER TABLE RHNMESSAGETYPE DROP CONSTRAINT RHN_M_TYPE_ID_NN;
ALTER TABLE RHNMESSAGETYPE MODIFY ID NOT NULL;

--
-- RHNMESSAGETYPE
--
ALTER TABLE RHNMESSAGETYPE DROP CONSTRAINT RHN_M_TYPE_LABEL_NN;
ALTER TABLE RHNMESSAGETYPE MODIFY LABEL NOT NULL;

--
-- RHNMESSAGETYPE
--
ALTER TABLE RHNMESSAGETYPE DROP CONSTRAINT RHN_M_TYPE_NAME_NN;
ALTER TABLE RHNMESSAGETYPE MODIFY NAME NOT NULL;

--
-- RHN_NOTIFSERVERS
--
ALTER TABLE RHN_NOTIFSERVERS DROP CONSTRAINT RHN_NOTSV_RECID_NN;
ALTER TABLE RHN_NOTIFSERVERS MODIFY RECID NOT NULL;

--
-- RHN_NOTIFICATION_FORMATS
--
ALTER TABLE RHN_NOTIFICATION_FORMATS DROP CONSTRAINT RHN_NTFMT_BODY_FMT_NN;
ALTER TABLE RHN_NOTIFICATION_FORMATS MODIFY BODY_FORMAT NOT NULL;

--
-- RHN_NOTIFICATION_FORMATS
--
ALTER TABLE RHN_NOTIFICATION_FORMATS DROP CONSTRAINT RHN_NTFMT_DESC_NN;
ALTER TABLE RHN_NOTIFICATION_FORMATS MODIFY DESCRIPTION NOT NULL;

--
-- RHN_NOTIFICATION_FORMATS
--
ALTER TABLE RHN_NOTIFICATION_FORMATS DROP CONSTRAINT RHN_NTFMT_MAX_BODY_NN;
ALTER TABLE RHN_NOTIFICATION_FORMATS MODIFY MAX_BODY_LENGTH NOT NULL;

--
-- RHN_NOTIFICATION_FORMATS
--
ALTER TABLE RHN_NOTIFICATION_FORMATS DROP CONSTRAINT RHN_NTFMT_RECID_NN;
ALTER TABLE RHN_NOTIFICATION_FORMATS MODIFY RECID NOT NULL;

--
-- RHNORGCHANNELSETTINGSTYPE
--
ALTER TABLE RHNORGCHANNELSETTINGSTYPE DROP CONSTRAINT RHN_OCSTNGS_TYPE_CREATED_NN;
ALTER TABLE RHNORGCHANNELSETTINGSTYPE MODIFY CREATED NOT NULL;

--
-- RHNORGCHANNELSETTINGSTYPE
--
ALTER TABLE RHNORGCHANNELSETTINGSTYPE DROP CONSTRAINT RHN_OCSTNGS_TYPE_ID_NN;
ALTER TABLE RHNORGCHANNELSETTINGSTYPE MODIFY ID NOT NULL;

--
-- RHNORGCHANNELSETTINGSTYPE
--
ALTER TABLE RHNORGCHANNELSETTINGSTYPE DROP CONSTRAINT RHN_OCSTNGS_TYPE_LABEL_NN;
ALTER TABLE RHNORGCHANNELSETTINGSTYPE MODIFY LABEL NOT NULL;

--
-- RHNORGCHANNELSETTINGSTYPE
--
ALTER TABLE RHNORGCHANNELSETTINGSTYPE DROP CONSTRAINT RHN_OCSTNGS_TYPE_MODIFIED_NN;
ALTER TABLE RHNORGCHANNELSETTINGSTYPE MODIFY MODIFIED NOT NULL;

--
-- RHNORGERRATACACHEQUEUE
--
ALTER TABLE RHNORGERRATACACHEQUEUE DROP CONSTRAINT RHN_OECQ_OID_NN;
ALTER TABLE RHNORGERRATACACHEQUEUE MODIFY ORG_ID NOT NULL;

--
-- RHNORGERRATACACHEQUEUE
--
ALTER TABLE RHNORGERRATACACHEQUEUE DROP CONSTRAINT RHN_OECQ_OID_PROCESSED_NN;
ALTER TABLE RHNORGERRATACACHEQUEUE MODIFY PROCESSED NOT NULL;

--
-- RHNORGERRATACACHEQUEUE
--
ALTER TABLE RHNORGERRATACACHEQUEUE DROP CONSTRAINT RHN_OECQ_SC_NN;
ALTER TABLE RHNORGERRATACACHEQUEUE MODIFY SERVER_COUNT NOT NULL;

--
-- RHNORGCHANNELSETTINGS
--
ALTER TABLE RHNORGCHANNELSETTINGS DROP CONSTRAINT RHN_ORGCSETTINGS_CID_NN;
ALTER TABLE RHNORGCHANNELSETTINGS MODIFY CHANNEL_ID NOT NULL;

--
-- RHNORGCHANNELSETTINGS
--
ALTER TABLE RHNORGCHANNELSETTINGS DROP CONSTRAINT RHN_ORGCSETTINGS_CREATED_NN;
ALTER TABLE RHNORGCHANNELSETTINGS MODIFY CREATED NOT NULL;

--
-- RHNORGCHANNELSETTINGS
--
ALTER TABLE RHNORGCHANNELSETTINGS DROP CONSTRAINT RHN_ORGCSETTINGS_MODIFIED_NN;
ALTER TABLE RHNORGCHANNELSETTINGS MODIFY MODIFIED NOT NULL;

--
-- RHNORGCHANNELSETTINGS
--
ALTER TABLE RHNORGCHANNELSETTINGS DROP CONSTRAINT RHN_ORGCSETTINGS_OID_NN;
ALTER TABLE RHNORGCHANNELSETTINGS MODIFY ORG_ID NOT NULL;

--
-- RHNORGCHANNELSETTINGS
--
ALTER TABLE RHNORGCHANNELSETTINGS DROP CONSTRAINT RHN_ORGCSETTINGS_SID_NN;
ALTER TABLE RHNORGCHANNELSETTINGS MODIFY SETTING_ID NOT NULL;

--
-- RHNORGINFO
--
ALTER TABLE RHNORGINFO DROP CONSTRAINT RHN_ORGINFO_CREATED_NN;
ALTER TABLE RHNORGINFO MODIFY CREATED NOT NULL;

--
-- RHNORGINFO
--
ALTER TABLE RHNORGINFO DROP CONSTRAINT RHN_ORGINFO_DGT_NN;
ALTER TABLE RHNORGINFO MODIFY DEFAULT_GROUP_TYPE NOT NULL;

--
-- RHNORGINFO
--
ALTER TABLE RHNORGINFO DROP CONSTRAINT RHN_ORGINFO_MODIFIED_NN;
ALTER TABLE RHNORGINFO MODIFY MODIFIED NOT NULL;

--
-- RHNORGINFO
--
ALTER TABLE RHNORGINFO DROP CONSTRAINT RHN_ORGINFO_OID_NN;
ALTER TABLE RHNORGINFO MODIFY ORG_ID NOT NULL;

--
-- RHNORGQUOTA
--
ALTER TABLE RHNORGQUOTA DROP CONSTRAINT RHN_ORGQUOTA_BONUS_NN;
ALTER TABLE RHNORGQUOTA MODIFY BONUS NOT NULL;

--
-- RHNORGQUOTA
--
ALTER TABLE RHNORGQUOTA DROP CONSTRAINT RHN_ORGQUOTA_CREAT_NN;
ALTER TABLE RHNORGQUOTA MODIFY CREATED NOT NULL;

--
-- RHNORGQUOTA
--
ALTER TABLE RHNORGQUOTA DROP CONSTRAINT RHN_ORGQUOTA_MOD_NN;
ALTER TABLE RHNORGQUOTA MODIFY MODIFIED NOT NULL;

--
-- RHNORGQUOTA
--
ALTER TABLE RHNORGQUOTA DROP CONSTRAINT RHN_ORGQUOTA_OID_NN;
ALTER TABLE RHNORGQUOTA MODIFY ORG_ID NOT NULL;

--
-- RHNORGQUOTA
--
ALTER TABLE RHNORGQUOTA DROP CONSTRAINT RHN_ORGQUOTA_TOTAL_NN;
ALTER TABLE RHNORGQUOTA MODIFY TOTAL NOT NULL;

--
-- RHNORGQUOTA
--
ALTER TABLE RHNORGQUOTA DROP CONSTRAINT RHN_ORGQUOTA_USED_NN;
ALTER TABLE RHNORGQUOTA MODIFY USED NOT NULL;

--
-- RHNORGENTITLEMENTS
--
ALTER TABLE RHNORGENTITLEMENTS DROP CONSTRAINT RHN_ORG_ENT_CRE_NN;
ALTER TABLE RHNORGENTITLEMENTS MODIFY CREATED NOT NULL;

--
-- RHNORGENTITLEMENTS
--
ALTER TABLE RHNORGENTITLEMENTS DROP CONSTRAINT RHN_ORG_ENT_EID_NN;
ALTER TABLE RHNORGENTITLEMENTS MODIFY ENTITLEMENT_ID NOT NULL;

--
-- RHNORGENTITLEMENTS
--
ALTER TABLE RHNORGENTITLEMENTS DROP CONSTRAINT RHN_ORG_ENT_MOD_NN;
ALTER TABLE RHNORGENTITLEMENTS MODIFY MODIFIED NOT NULL;

--
-- RHNORGENTITLEMENTS
--
ALTER TABLE RHNORGENTITLEMENTS DROP CONSTRAINT RHN_ORG_ENT_NN;
ALTER TABLE RHNORGENTITLEMENTS MODIFY ORG_ID NOT NULL;

--
-- RHNORGENTITLEMENTTYPE
--
ALTER TABLE RHNORGENTITLEMENTTYPE DROP CONSTRAINT RHN_ORG_ENT_TYPE_CREATED_NN;
ALTER TABLE RHNORGENTITLEMENTTYPE MODIFY CREATED NOT NULL;

--
-- RHNORGENTITLEMENTTYPE
--
ALTER TABLE RHNORGENTITLEMENTTYPE DROP CONSTRAINT RHN_ORG_ENT_TYPE_ID_NN;
ALTER TABLE RHNORGENTITLEMENTTYPE MODIFY ID NOT NULL;

--
-- RHNORGENTITLEMENTTYPE
--
ALTER TABLE RHNORGENTITLEMENTTYPE DROP CONSTRAINT RHN_ORG_ENT_TYPE_LABEL_NN;
ALTER TABLE RHNORGENTITLEMENTTYPE MODIFY LABEL NOT NULL;

--
-- RHNORGENTITLEMENTTYPE
--
ALTER TABLE RHNORGENTITLEMENTTYPE DROP CONSTRAINT RHN_ORG_ENT_TYPE_MOD_NN;
ALTER TABLE RHNORGENTITLEMENTTYPE MODIFY MODIFIED NOT NULL;

--
-- RHNORGENTITLEMENTTYPE
--
ALTER TABLE RHNORGENTITLEMENTTYPE DROP CONSTRAINT RHN_ORG_ENT_TYPE_NAME_NN;
ALTER TABLE RHNORGENTITLEMENTTYPE MODIFY NAME NOT NULL;

--
-- RHN_OS
--
ALTER TABLE RHN_OS DROP CONSTRAINT RHN_OS000_RECID_NN;
ALTER TABLE RHN_OS MODIFY RECID NOT NULL;

--
-- RHN_OS_COMMANDS_XREF
--
ALTER TABLE RHN_OS_COMMANDS_XREF DROP CONSTRAINT RHN_OSCXR_COMMANDS_ID_NN;
ALTER TABLE RHN_OS_COMMANDS_XREF MODIFY COMMANDS_ID NOT NULL;

--
-- RHN_OS_COMMANDS_XREF
--
ALTER TABLE RHN_OS_COMMANDS_XREF DROP CONSTRAINT RHN_OSCXR_OS_ID_NN;
ALTER TABLE RHN_OS_COMMANDS_XREF MODIFY OS_ID NOT NULL;

--
-- RHNPACKAGEDELTA
--
ALTER TABLE RHNPACKAGEDELTA DROP CONSTRAINT RHN_PACKAGEDELTA_CREATED_NN;
ALTER TABLE RHNPACKAGEDELTA MODIFY CREATED NOT NULL;

--
-- RHNPACKAGEDELTA
--
ALTER TABLE RHNPACKAGEDELTA DROP CONSTRAINT RHN_PACKAGEDELTA_ID_NN;
ALTER TABLE RHNPACKAGEDELTA MODIFY ID NOT NULL;

--
-- RHNPACKAGEDELTA
--
ALTER TABLE RHNPACKAGEDELTA DROP CONSTRAINT RHN_PACKAGEDELTA_LABEL_NN;
ALTER TABLE RHNPACKAGEDELTA MODIFY LABEL NOT NULL;

--
-- RHNPACKAGEDELTA
--
ALTER TABLE RHNPACKAGEDELTA DROP CONSTRAINT RHN_PACKAGEDELTA_MODIFIED_NN;
ALTER TABLE RHNPACKAGEDELTA MODIFY MODIFIED NOT NULL;

--
-- RHNPACKAGESYNCBLACKLIST
--
ALTER TABLE RHNPACKAGESYNCBLACKLIST DROP CONSTRAINT RHN_PACKAGESYNCBL_CREAT_NN;
ALTER TABLE RHNPACKAGESYNCBLACKLIST MODIFY CREATED NOT NULL;

--
-- RHNPACKAGESYNCBLACKLIST
--
ALTER TABLE RHNPACKAGESYNCBLACKLIST DROP CONSTRAINT RHN_PACKAGESYNCBL_MOD_NN;
ALTER TABLE RHNPACKAGESYNCBLACKLIST MODIFY MODIFIED NOT NULL;

--
-- RHNPACKAGESYNCBLACKLIST
--
ALTER TABLE RHNPACKAGESYNCBLACKLIST DROP CONSTRAINT RHN_PACKAGESYNCBL_PNID_NN;
ALTER TABLE RHNPACKAGESYNCBLACKLIST MODIFY PACKAGE_NAME_ID NOT NULL;

--
-- RHNPACKAGE
--
ALTER TABLE RHNPACKAGE DROP CONSTRAINT RHN_PACKAGE_CREATED_NN;
ALTER TABLE RHNPACKAGE MODIFY CREATED NOT NULL;

--
-- RHNPACKAGE
--
ALTER TABLE RHNPACKAGE DROP CONSTRAINT RHN_PACKAGE_EID_NN;
ALTER TABLE RHNPACKAGE MODIFY EVR_ID NOT NULL;

--
-- RHNPACKAGEFILE
--
ALTER TABLE RHNPACKAGEFILE DROP CONSTRAINT RHN_PACKAGE_FILE_CID_NN;
ALTER TABLE RHNPACKAGEFILE MODIFY CAPABILITY_ID NOT NULL;

--
-- RHNPACKAGEFILE
--
ALTER TABLE RHNPACKAGEFILE DROP CONSTRAINT RHN_PACKAGE_FILE_CREATED_NN;
ALTER TABLE RHNPACKAGEFILE MODIFY CREATED NOT NULL;

--
-- RHNPACKAGEFILE
--
ALTER TABLE RHNPACKAGEFILE DROP CONSTRAINT RHN_PACKAGE_FILE_DEVICES_NN;
ALTER TABLE RHNPACKAGEFILE MODIFY DEVICE NOT NULL;

--
-- RHNPACKAGEFILE
--
ALTER TABLE RHNPACKAGEFILE DROP CONSTRAINT RHN_PACKAGE_FILE_DEV_NN;
ALTER TABLE RHNPACKAGEFILE MODIFY RDEV NOT NULL;

--
-- RHNPACKAGEFILE
--
ALTER TABLE RHNPACKAGEFILE DROP CONSTRAINT RHN_PACKAGE_FILE_FLAGS_NN;
ALTER TABLE RHNPACKAGEFILE MODIFY FLAGS NOT NULL;

--
-- RHNPACKAGEFILE
--
ALTER TABLE RHNPACKAGEFILE DROP CONSTRAINT RHN_PACKAGE_FILE_GROUPNAME_NN;
ALTER TABLE RHNPACKAGEFILE MODIFY GROUPNAME NOT NULL;

--
-- RHNPACKAGEFILE
--
ALTER TABLE RHNPACKAGEFILE DROP CONSTRAINT RHN_PACKAGE_FILE_INODE_NN;
ALTER TABLE RHNPACKAGEFILE MODIFY INODE NOT NULL;

--
-- RHNPACKAGEFILE
--
ALTER TABLE RHNPACKAGEFILE DROP CONSTRAINT RHN_PACKAGE_FILE_MODE_NN;
ALTER TABLE RHNPACKAGEFILE MODIFY FILE_MODE NOT NULL;

--
-- RHNPACKAGEFILE
--
ALTER TABLE RHNPACKAGEFILE DROP CONSTRAINT RHN_PACKAGE_FILE_MODIFIED_NN;
ALTER TABLE RHNPACKAGEFILE MODIFY MODIFIED NOT NULL;

--
-- RHNPACKAGEFILE
--
ALTER TABLE RHNPACKAGEFILE DROP CONSTRAINT RHN_PACKAGE_FILE_MTIME_NN;
ALTER TABLE RHNPACKAGEFILE MODIFY MTIME NOT NULL;

--
-- RHNPACKAGEFILE
--
ALTER TABLE RHNPACKAGEFILE DROP CONSTRAINT RHN_PACKAGE_FILE_PID_NN;
ALTER TABLE RHNPACKAGEFILE MODIFY PACKAGE_ID NOT NULL;

--
-- RHNPACKAGEFILE
--
ALTER TABLE RHNPACKAGEFILE DROP CONSTRAINT RHN_PACKAGE_FILE_SIZE_NN;
ALTER TABLE RHNPACKAGEFILE MODIFY FILE_SIZE NOT NULL;

--
-- RHNPACKAGEFILE
--
ALTER TABLE RHNPACKAGEFILE DROP CONSTRAINT RHN_PACKAGE_FILE_USERNAME_NN;
ALTER TABLE RHNPACKAGEFILE MODIFY USERNAME NOT NULL;

--
-- RHNPACKAGEFILE
--
ALTER TABLE RHNPACKAGEFILE DROP CONSTRAINT RHN_PACKAGE_FILE_VERIFY_NN;
ALTER TABLE RHNPACKAGEFILE MODIFY VERIFYFLAGS NOT NULL;

--
-- RHNPACKAGEGROUP
--
ALTER TABLE RHNPACKAGEGROUP DROP CONSTRAINT RHN_PACKAGE_GROUP_CREATED_NN;
ALTER TABLE RHNPACKAGEGROUP MODIFY CREATED NOT NULL;

--
-- RHNPACKAGEGROUP
--
ALTER TABLE RHNPACKAGEGROUP DROP CONSTRAINT RHN_PACKAGE_GROUP_ID_NN;
ALTER TABLE RHNPACKAGEGROUP MODIFY ID NOT NULL;

--
-- RHNPACKAGEGROUP
--
ALTER TABLE RHNPACKAGEGROUP DROP CONSTRAINT RHN_PACKAGE_GROUP_MODIFIED_NN;
ALTER TABLE RHNPACKAGEGROUP MODIFY MODIFIED NOT NULL;

--
-- RHNPACKAGEGROUP
--
ALTER TABLE RHNPACKAGEGROUP DROP CONSTRAINT RHN_PACKAGE_GROUP_NAME_NN;
ALTER TABLE RHNPACKAGEGROUP MODIFY NAME NOT NULL;

--
-- RHNPACKAGE
--
ALTER TABLE RHNPACKAGE DROP CONSTRAINT RHN_PACKAGE_HE_NN;
ALTER TABLE RHNPACKAGE MODIFY HEADER_END NOT NULL;

--
-- RHNPACKAGE
--
ALTER TABLE RHNPACKAGE DROP CONSTRAINT RHN_PACKAGE_HS_NN;
ALTER TABLE RHNPACKAGE MODIFY HEADER_START NOT NULL;

--
-- RHNPACKAGE
--
ALTER TABLE RHNPACKAGE DROP CONSTRAINT RHN_PACKAGE_ID_NN;
ALTER TABLE RHNPACKAGE MODIFY ID NOT NULL;

--
-- RHNPACKAGE
--
ALTER TABLE RHNPACKAGE DROP CONSTRAINT RHN_PACKAGE_LM_NN;
ALTER TABLE RHNPACKAGE MODIFY LAST_MODIFIED NOT NULL;

--
-- RHNPACKAGE
--
ALTER TABLE RHNPACKAGE DROP CONSTRAINT RHN_PACKAGE_MD5_NN;
ALTER TABLE RHNPACKAGE MODIFY MD5SUM NOT NULL;

--
-- RHNPACKAGE
--
ALTER TABLE RHNPACKAGE DROP CONSTRAINT RHN_PACKAGE_MODIFIED_NN;
ALTER TABLE RHNPACKAGE MODIFY MODIFIED NOT NULL;

--
-- RHNPACKAGE
--
ALTER TABLE RHNPACKAGE DROP CONSTRAINT RHN_PACKAGE_NID_NN;
ALTER TABLE RHNPACKAGE MODIFY NAME_ID NOT NULL;

--
-- RHNPACKAGE
--
ALTER TABLE RHNPACKAGE DROP CONSTRAINT RHN_PACKAGE_PAID_NN;
ALTER TABLE RHNPACKAGE MODIFY PACKAGE_ARCH_ID NOT NULL;

--
-- RHNPACKAGE
--
ALTER TABLE RHNPACKAGE DROP CONSTRAINT RHN_PACKAGE_PKG_SIZE_NN;
ALTER TABLE RHNPACKAGE MODIFY PACKAGE_SIZE NOT NULL;

--
-- RHNPACKAGESOURCE
--
ALTER TABLE RHNPACKAGESOURCE DROP CONSTRAINT RHN_PACKAGE_SIGMD5_NN;
ALTER TABLE RHNPACKAGESOURCE MODIFY SIGMD5 NOT NULL;

--
-- RHNPACKAGE
--
ALTER TABLE RHNPACKAGE DROP CONSTRAINT RHN_PACKAGE_VENDOR_NN;
ALTER TABLE RHNPACKAGE MODIFY VENDOR NOT NULL;

--
-- RHNPACKAGEARCH
--
ALTER TABLE RHNPACKAGEARCH DROP CONSTRAINT RHN_PARCH_ATID_NN;
ALTER TABLE RHNPACKAGEARCH MODIFY ARCH_TYPE_ID NOT NULL;

--
-- RHNPACKAGEARCH
--
ALTER TABLE RHNPACKAGEARCH DROP CONSTRAINT RHN_PARCH_CREATED_NN;
ALTER TABLE RHNPACKAGEARCH MODIFY CREATED NOT NULL;

--
-- RHNPACKAGEARCH
--
ALTER TABLE RHNPACKAGEARCH DROP CONSTRAINT RHN_PARCH_ID_NN;
ALTER TABLE RHNPACKAGEARCH MODIFY ID NOT NULL;

--
-- RHNPACKAGEARCH
--
ALTER TABLE RHNPACKAGEARCH DROP CONSTRAINT RHN_PARCH_LABEL_NN;
ALTER TABLE RHNPACKAGEARCH MODIFY LABEL NOT NULL;

--
-- RHNPACKAGEARCH
--
ALTER TABLE RHNPACKAGEARCH DROP CONSTRAINT RHN_PARCH_MODIFIED_NN;
ALTER TABLE RHNPACKAGEARCH MODIFY MODIFIED NOT NULL;

--
-- RHNPACKAGEARCH
--
ALTER TABLE RHNPACKAGEARCH DROP CONSTRAINT RHN_PARCH_NAME_NN;
ALTER TABLE RHNPACKAGEARCH MODIFY NAME NOT NULL;

--
-- RHNPATHCHANNELMAP
--
ALTER TABLE RHNPATHCHANNELMAP DROP CONSTRAINT RHN_PATH_CHANNEL_MAP_CID_NN;
ALTER TABLE RHNPATHCHANNELMAP MODIFY CHANNEL_ID NOT NULL;

--
-- RHNPATHCHANNELMAP
--
ALTER TABLE RHNPATHCHANNELMAP DROP CONSTRAINT RHN_PATH_CHANNEL_MAP_P_NN;
ALTER TABLE RHNPATHCHANNELMAP MODIFY PATH NOT NULL;

--
-- RHNPUSHCLIENT
--
ALTER TABLE RHNPUSHCLIENT DROP CONSTRAINT RHN_PCLIENT_CREATED_NN;
ALTER TABLE RHNPUSHCLIENT MODIFY CREATED NOT NULL;

--
-- RHNPUSHCLIENT
--
ALTER TABLE RHNPUSHCLIENT DROP CONSTRAINT RHN_PCLIENT_ID_NN;
ALTER TABLE RHNPUSHCLIENT MODIFY ID NOT NULL;

--
-- RHNPUSHCLIENT
--
ALTER TABLE RHNPUSHCLIENT DROP CONSTRAINT RHN_PCLIENT_MODIFIED_NN;
ALTER TABLE RHNPUSHCLIENT MODIFY MODIFIED NOT NULL;

--
-- RHNPUSHCLIENT
--
ALTER TABLE RHNPUSHCLIENT DROP CONSTRAINT RHN_PCLIENT_NAME_NN;
ALTER TABLE RHNPUSHCLIENT MODIFY NAME NOT NULL;

--
-- RHNPUSHCLIENT
--
ALTER TABLE RHNPUSHCLIENT DROP CONSTRAINT RHN_PCLIENT_SID_NN;
ALTER TABLE RHNPUSHCLIENT MODIFY SERVER_ID NOT NULL;

--
-- RHNPUSHCLIENT
--
ALTER TABLE RHNPUSHCLIENT DROP CONSTRAINT RHN_PCLIENT_SKEY_NN;
ALTER TABLE RHNPUSHCLIENT MODIFY SHARED_KEY NOT NULL;

--
-- RHNPUSHCLIENTSTATE
--
ALTER TABLE RHNPUSHCLIENTSTATE DROP CONSTRAINT RHN_PCLIENT_STATE_CREATED_NN;
ALTER TABLE RHNPUSHCLIENTSTATE MODIFY CREATED NOT NULL;

--
-- RHNPUSHCLIENTSTATE
--
ALTER TABLE RHNPUSHCLIENTSTATE DROP CONSTRAINT RHN_PCLIENT_STATE_ID_NN;
ALTER TABLE RHNPUSHCLIENTSTATE MODIFY ID NOT NULL;

--
-- RHNPUSHCLIENTSTATE
--
ALTER TABLE RHNPUSHCLIENTSTATE DROP CONSTRAINT RHN_PCLIENT_STATE_LABEL_NN;
ALTER TABLE RHNPUSHCLIENTSTATE MODIFY LABEL NOT NULL;

--
-- RHNPUSHCLIENTSTATE
--
ALTER TABLE RHNPUSHCLIENTSTATE DROP CONSTRAINT RHN_PCLIENT_STATE_MODIFIED_NN;
ALTER TABLE RHNPUSHCLIENTSTATE MODIFY MODIFIED NOT NULL;

--
-- RHNPUSHCLIENTSTATE
--
ALTER TABLE RHNPUSHCLIENTSTATE DROP CONSTRAINT RHN_PCLIENT_STATE_NAME_NN;
ALTER TABLE RHNPUSHCLIENTSTATE MODIFY NAME NOT NULL;

--
-- RHNPUSHCLIENT
--
ALTER TABLE RHNPUSHCLIENT DROP CONSTRAINT RHN_PCLIENT_STID_NN;
ALTER TABLE RHNPUSHCLIENT MODIFY STATE_ID NOT NULL;

--
-- RHNPRODUCTCHANNEL
--
ALTER TABLE RHNPRODUCTCHANNEL DROP CONSTRAINT RHN_PC_CID_NN;
ALTER TABLE RHNPRODUCTCHANNEL MODIFY CHANNEL_ID NOT NULL;

--
-- RHNPRODUCTCHANNEL
--
ALTER TABLE RHNPRODUCTCHANNEL DROP CONSTRAINT RHN_PC_CREATED_NN;
ALTER TABLE RHNPRODUCTCHANNEL MODIFY CREATED NOT NULL;

--
-- RHNPRODUCTCHANNEL
--
ALTER TABLE RHNPRODUCTCHANNEL DROP CONSTRAINT RHN_PC_MODIFIED_NN;
ALTER TABLE RHNPRODUCTCHANNEL MODIFY MODIFIED NOT NULL;

--
-- RHNPRODUCTCHANNEL
--
ALTER TABLE RHNPRODUCTCHANNEL DROP CONSTRAINT RHN_PC_PID_NN;
ALTER TABLE RHNPRODUCTCHANNEL MODIFY PRODUCT_ID NOT NULL;

--
-- RHNPACKAGEDELTAELEMENT
--
ALTER TABLE RHNPACKAGEDELTAELEMENT DROP CONSTRAINT RHN_PDELEMENT_PDID_NN;
ALTER TABLE RHNPACKAGEDELTAELEMENT MODIFY PACKAGE_DELTA_ID NOT NULL;

--
-- RHNPACKAGEDELTAELEMENT
--
ALTER TABLE RHNPACKAGEDELTAELEMENT DROP CONSTRAINT RHN_PDELEMENT_TPID_NN;
ALTER TABLE RHNPACKAGEDELTAELEMENT MODIFY TRANSACTION_PACKAGE_ID NOT NULL;

--
-- RHNPACKAGEEVR
--
ALTER TABLE RHNPACKAGEEVR DROP CONSTRAINT RHN_PE_ID_NN;
ALTER TABLE RHNPACKAGEEVR MODIFY ID NOT NULL;

--
-- RHNPACKAGEEVR
--
ALTER TABLE RHNPACKAGEEVR DROP CONSTRAINT RHN_PE_RELEASE_NN;
ALTER TABLE RHNPACKAGEEVR MODIFY RELEASE NOT NULL;

--
-- RHNPACKAGEEVR
--
ALTER TABLE RHNPACKAGEEVR DROP CONSTRAINT RHN_PE_VERSION_NN;
ALTER TABLE RHNPACKAGEEVR MODIFY VERSION NOT NULL;

--
-- RHNPACKAGEFILEDELETEQUEUE
--
ALTER TABLE RHNPACKAGEFILEDELETEQUEUE DROP CONSTRAINT RHN_PFDQUEUE_CREATED_NN;
ALTER TABLE RHNPACKAGEFILEDELETEQUEUE MODIFY CREATED NOT NULL;

--
-- RHN_PAGER_TYPES
--
ALTER TABLE RHN_PAGER_TYPES DROP CONSTRAINT RHN_PGRTP_RECID_NN;
ALTER TABLE RHN_PAGER_TYPES MODIFY RECID NOT NULL;

--
-- RHN_PHYSICAL_LOCATION
--
ALTER TABLE RHN_PHYSICAL_LOCATION DROP CONSTRAINT RHN_PHSLC_CUST_ID_NN;
ALTER TABLE RHN_PHYSICAL_LOCATION MODIFY CUSTOMER_ID NOT NULL;

--
-- RHN_PHYSICAL_LOCATION
--
ALTER TABLE RHN_PHYSICAL_LOCATION DROP CONSTRAINT RHN_PHSLC_RECID_NN;
ALTER TABLE RHN_PHYSICAL_LOCATION MODIFY RECID NOT NULL;

--
-- RHNPACKAGEKEYASSOCIATION
--
ALTER TABLE RHNPACKAGEKEYASSOCIATION DROP CONSTRAINT RHN_PKEYA_CREATED_NN;
ALTER TABLE RHNPACKAGEKEYASSOCIATION MODIFY CREATED NOT NULL;

--
-- RHNPACKAGEKEYASSOCIATION
--
ALTER TABLE RHNPACKAGEKEYASSOCIATION DROP CONSTRAINT RHN_PKEYA_KID_NN;
ALTER TABLE RHNPACKAGEKEYASSOCIATION MODIFY KEY_ID NOT NULL;

--
-- RHNPACKAGEKEYASSOCIATION
--
ALTER TABLE RHNPACKAGEKEYASSOCIATION DROP CONSTRAINT RHN_PKEYA_MODIFIED_NN;
ALTER TABLE RHNPACKAGEKEYASSOCIATION MODIFY MODIFIED NOT NULL;

--
-- RHNPACKAGEKEYASSOCIATION
--
ALTER TABLE RHNPACKAGEKEYASSOCIATION DROP CONSTRAINT RHN_PKEYA_PID_NN;
ALTER TABLE RHNPACKAGEKEYASSOCIATION MODIFY PACKAGE_ID NOT NULL;

--
-- RHNPACKAGEKEY
--
ALTER TABLE RHNPACKAGEKEY DROP CONSTRAINT RHN_PKEY_CREATED_NN;
ALTER TABLE RHNPACKAGEKEY MODIFY CREATED NOT NULL;

--
-- RHNPACKAGEKEY
--
ALTER TABLE RHNPACKAGEKEY DROP CONSTRAINT RHN_PKEY_ID_NN;
ALTER TABLE RHNPACKAGEKEY MODIFY ID NOT NULL;

--
-- RHNPACKAGEKEY
--
ALTER TABLE RHNPACKAGEKEY DROP CONSTRAINT RHN_PKEY_KEY_NN;
ALTER TABLE RHNPACKAGEKEY MODIFY KEY_ID NOT NULL;

--
-- RHNPACKAGEKEY
--
ALTER TABLE RHNPACKAGEKEY DROP CONSTRAINT RHN_PKEY_MODIFIED_NN;
ALTER TABLE RHNPACKAGEKEY MODIFY MODIFIED NOT NULL;

--
-- RHNPACKAGEKEY
--
ALTER TABLE RHNPACKAGEKEY DROP CONSTRAINT RHN_PKEY_TYPE_ID_NN;
ALTER TABLE RHNPACKAGEKEY MODIFY KEY_TYPE_ID NOT NULL;

--
-- RHNPACKAGENEVRA
--
ALTER TABLE RHNPACKAGENEVRA DROP CONSTRAINT RHN_PKGNEVRA_EID_NN;
ALTER TABLE RHNPACKAGENEVRA MODIFY EVR_ID NOT NULL;

--
-- RHNPACKAGENEVRA
--
ALTER TABLE RHNPACKAGENEVRA DROP CONSTRAINT RHN_PKGNEVRA_ID_NN;
ALTER TABLE RHNPACKAGENEVRA MODIFY ID NOT NULL;

--
-- RHNPACKAGENEVRA
--
ALTER TABLE RHNPACKAGENEVRA DROP CONSTRAINT RHN_PKGNEVRA_NID_NN;
ALTER TABLE RHNPACKAGENEVRA MODIFY NAME_ID NOT NULL;

--
-- RHNPACKAGESOURCE
--
ALTER TABLE RHNPACKAGESOURCE DROP CONSTRAINT RHN_PKGSRC_BH_NN;
ALTER TABLE RHNPACKAGESOURCE MODIFY BUILD_HOST NOT NULL;

--
-- RHNPACKAGESOURCE
--
ALTER TABLE RHNPACKAGESOURCE DROP CONSTRAINT RHN_PKGSRC_BT_NN;
ALTER TABLE RHNPACKAGESOURCE MODIFY BUILD_TIME NOT NULL;

--
-- RHNPACKAGESOURCE
--
ALTER TABLE RHNPACKAGESOURCE DROP CONSTRAINT RHN_PKGSRC_COOKIE_NN;
ALTER TABLE RHNPACKAGESOURCE MODIFY COOKIE NOT NULL;

--
-- RHNPACKAGESOURCE
--
ALTER TABLE RHNPACKAGESOURCE DROP CONSTRAINT RHN_PKGSRC_CREATED_NN;
ALTER TABLE RHNPACKAGESOURCE MODIFY CREATED NOT NULL;

--
-- RHNPACKAGESOURCE
--
ALTER TABLE RHNPACKAGESOURCE DROP CONSTRAINT RHN_PKGSRC_GROUP_NN;
ALTER TABLE RHNPACKAGESOURCE MODIFY PACKAGE_GROUP NOT NULL;

--
-- RHNPACKAGESOURCE
--
ALTER TABLE RHNPACKAGESOURCE DROP CONSTRAINT RHN_PKGSRC_ID_NN;
ALTER TABLE RHNPACKAGESOURCE MODIFY ID NOT NULL;

--
-- RHNPACKAGESOURCE
--
ALTER TABLE RHNPACKAGESOURCE DROP CONSTRAINT RHN_PKGSRC_LM_NN;
ALTER TABLE RHNPACKAGESOURCE MODIFY LAST_MODIFIED NOT NULL;

--
-- RHNPACKAGESOURCE
--
ALTER TABLE RHNPACKAGESOURCE DROP CONSTRAINT RHN_PKGSRC_MD5SUM_NN;
ALTER TABLE RHNPACKAGESOURCE MODIFY MD5SUM NOT NULL;

--
-- RHNPACKAGESOURCE
--
ALTER TABLE RHNPACKAGESOURCE DROP CONSTRAINT RHN_PKGSRC_MODIFIED_NN;
ALTER TABLE RHNPACKAGESOURCE MODIFY MODIFIED NOT NULL;

--
-- RHNPACKAGESOURCE
--
ALTER TABLE RHNPACKAGESOURCE DROP CONSTRAINT RHN_PKGSRC_PAYSIZE_NN;
ALTER TABLE RHNPACKAGESOURCE MODIFY PAYLOAD_SIZE NOT NULL;

--
-- RHNPACKAGESOURCE
--
ALTER TABLE RHNPACKAGESOURCE DROP CONSTRAINT RHN_PKGSRC_PS_NN;
ALTER TABLE RHNPACKAGESOURCE MODIFY PACKAGE_SIZE NOT NULL;

--
-- RHNPACKAGESOURCE
--
ALTER TABLE RHNPACKAGESOURCE DROP CONSTRAINT RHN_PKGSRC_RPM_VER_NN;
ALTER TABLE RHNPACKAGESOURCE MODIFY RPM_VERSION NOT NULL;

--
-- RHNPACKAGESOURCE
--
ALTER TABLE RHNPACKAGESOURCE DROP CONSTRAINT RHN_PKGSRC_SRID_NN;
ALTER TABLE RHNPACKAGESOURCE MODIFY SOURCE_RPM_ID NOT NULL;

--
-- RHNPACKAGESOURCE
--
ALTER TABLE RHNPACKAGESOURCE DROP CONSTRAINT RHN_PKGSRC_VENDOR_NN;
ALTER TABLE RHNPACKAGESOURCE MODIFY VENDOR NOT NULL;

--
-- RHNPACKAGECAPABILITY
--
ALTER TABLE RHNPACKAGECAPABILITY DROP CONSTRAINT RHN_PKG_CAPABILITY_CREATED_NN;
ALTER TABLE RHNPACKAGECAPABILITY MODIFY CREATED NOT NULL;

--
-- RHNPACKAGECAPABILITY
--
ALTER TABLE RHNPACKAGECAPABILITY DROP CONSTRAINT RHN_PKG_CAPABILITY_ID_NN;
ALTER TABLE RHNPACKAGECAPABILITY MODIFY ID NOT NULL;

--
-- RHNPACKAGECAPABILITY
--
ALTER TABLE RHNPACKAGECAPABILITY DROP CONSTRAINT RHN_PKG_CAPABILITY_MODIFIED_NN;
ALTER TABLE RHNPACKAGECAPABILITY MODIFY MODIFIED NOT NULL;

--
-- RHNPACKAGECAPABILITY
--
ALTER TABLE RHNPACKAGECAPABILITY DROP CONSTRAINT RHN_PKG_CAPABILITY_NAME_NN;
ALTER TABLE RHNPACKAGECAPABILITY MODIFY NAME NOT NULL;

--
-- RHNPACKAGECHANGELOG
--
ALTER TABLE RHNPACKAGECHANGELOG DROP CONSTRAINT RHN_PKG_CHANGELOG_CREATED_NN;
ALTER TABLE RHNPACKAGECHANGELOG MODIFY CREATED NOT NULL;

--
-- RHNPACKAGECHANGELOG
--
ALTER TABLE RHNPACKAGECHANGELOG DROP CONSTRAINT RHN_PKG_CHANGELOG_MODIFIED_NN;
ALTER TABLE RHNPACKAGECHANGELOG MODIFY MODIFIED NOT NULL;

--
-- RHNPACKAGECHANGELOG
--
ALTER TABLE RHNPACKAGECHANGELOG DROP CONSTRAINT RHN_PKG_CHANGELOG_NAME;
ALTER TABLE RHNPACKAGECHANGELOG MODIFY NAME NOT NULL;

--
-- RHNPACKAGECHANGELOG
--
ALTER TABLE RHNPACKAGECHANGELOG DROP CONSTRAINT RHN_PKG_CHANGELOG_PID_NN;
ALTER TABLE RHNPACKAGECHANGELOG MODIFY PACKAGE_ID NOT NULL;

--
-- RHNPACKAGECHANGELOG
--
ALTER TABLE RHNPACKAGECHANGELOG DROP CONSTRAINT RHN_PKG_CHANGELOG_TEXT;
ALTER TABLE RHNPACKAGECHANGELOG MODIFY TEXT NOT NULL;

--
-- RHNPACKAGECHANGELOG
--
ALTER TABLE RHNPACKAGECHANGELOG DROP CONSTRAINT RHN_PKG_CHANGELOG_TIME;
ALTER TABLE RHNPACKAGECHANGELOG MODIFY TIME NOT NULL;

--
-- RHNPACKAGECHANGELOG
--
ALTER TABLE RHNPACKAGECHANGELOG DROP CONSTRAINT RHN_PKG_CL_ID_NN;
ALTER TABLE RHNPACKAGECHANGELOG MODIFY ID NOT NULL;

--
-- RHNPACKAGECONFLICTS
--
ALTER TABLE RHNPACKAGECONFLICTS DROP CONSTRAINT RHN_PKG_CONFLICTS_CID_NN;
ALTER TABLE RHNPACKAGECONFLICTS MODIFY CAPABILITY_ID NOT NULL;

--
-- RHNPACKAGECONFLICTS
--
ALTER TABLE RHNPACKAGECONFLICTS DROP CONSTRAINT RHN_PKG_CONFLICTS_CTIME_NN;
ALTER TABLE RHNPACKAGECONFLICTS MODIFY CREATED NOT NULL;

--
-- RHNPACKAGECONFLICTS
--
ALTER TABLE RHNPACKAGECONFLICTS DROP CONSTRAINT RHN_PKG_CONFLICTS_MTIME_NN;
ALTER TABLE RHNPACKAGECONFLICTS MODIFY MODIFIED NOT NULL;

--
-- RHNPACKAGECONFLICTS
--
ALTER TABLE RHNPACKAGECONFLICTS DROP CONSTRAINT RHN_PKG_CONFLICTS_PID_NN;
ALTER TABLE RHNPACKAGECONFLICTS MODIFY PACKAGE_ID NOT NULL;

--
-- RHNPACKAGECONFLICTS
--
ALTER TABLE RHNPACKAGECONFLICTS DROP CONSTRAINT RHN_PKG_CONFLICTS_SENSE_NN;
ALTER TABLE RHNPACKAGECONFLICTS MODIFY SENSE NOT NULL;

--
-- RHNPACKAGEKEYTYPE
--
ALTER TABLE RHNPACKAGEKEYTYPE DROP CONSTRAINT RHN_PKG_KEY_TYPE_CREATED_NN;
ALTER TABLE RHNPACKAGEKEYTYPE MODIFY CREATED NOT NULL;

--
-- RHNPACKAGEKEYTYPE
--
ALTER TABLE RHNPACKAGEKEYTYPE DROP CONSTRAINT RHN_PKG_KEY_TYPE_ID_NN;
ALTER TABLE RHNPACKAGEKEYTYPE MODIFY ID NOT NULL;

--
-- RHNPACKAGEKEYTYPE
--
ALTER TABLE RHNPACKAGEKEYTYPE DROP CONSTRAINT RHN_PKG_KEY_TYPE_LABEL_NN;
ALTER TABLE RHNPACKAGEKEYTYPE MODIFY LABEL NOT NULL;

--
-- RHNPACKAGEKEYTYPE
--
ALTER TABLE RHNPACKAGEKEYTYPE DROP CONSTRAINT RHN_PKG_KEY_TYPE_MODIFIED_NN;
ALTER TABLE RHNPACKAGEKEYTYPE MODIFY MODIFIED NOT NULL;

--
-- RHNPACKAGEOBSOLETES
--
ALTER TABLE RHNPACKAGEOBSOLETES DROP CONSTRAINT RHN_PKG_OBSOLETES_CID_NN;
ALTER TABLE RHNPACKAGEOBSOLETES MODIFY CAPABILITY_ID NOT NULL;

--
-- RHNPACKAGEOBSOLETES
--
ALTER TABLE RHNPACKAGEOBSOLETES DROP CONSTRAINT RHN_PKG_OBSOLETES_CTIME_NN;
ALTER TABLE RHNPACKAGEOBSOLETES MODIFY CREATED NOT NULL;

--
-- RHNPACKAGEOBSOLETES
--
ALTER TABLE RHNPACKAGEOBSOLETES DROP CONSTRAINT RHN_PKG_OBSOLETES_MTIME_NN;
ALTER TABLE RHNPACKAGEOBSOLETES MODIFY MODIFIED NOT NULL;

--
-- RHNPACKAGEOBSOLETES
--
ALTER TABLE RHNPACKAGEOBSOLETES DROP CONSTRAINT RHN_PKG_OBSOLETES_PID_NN;
ALTER TABLE RHNPACKAGEOBSOLETES MODIFY PACKAGE_ID NOT NULL;

--
-- RHNPACKAGEOBSOLETES
--
ALTER TABLE RHNPACKAGEOBSOLETES DROP CONSTRAINT RHN_PKG_OBSOLETES_SENSE_NN;
ALTER TABLE RHNPACKAGEOBSOLETES MODIFY SENSE NOT NULL;

--
-- RHNPACKAGEPROVIDER
--
ALTER TABLE RHNPACKAGEPROVIDER DROP CONSTRAINT RHN_PKG_PROVIDER_CREATED_NN;
ALTER TABLE RHNPACKAGEPROVIDER MODIFY CREATED NOT NULL;

--
-- RHNPACKAGEPROVIDER
--
ALTER TABLE RHNPACKAGEPROVIDER DROP CONSTRAINT RHN_PKG_PROVIDER_ID_NN;
ALTER TABLE RHNPACKAGEPROVIDER MODIFY ID NOT NULL;

--
-- RHNPACKAGEPROVIDER
--
ALTER TABLE RHNPACKAGEPROVIDER DROP CONSTRAINT RHN_PKG_PROVIDER_KEY_NN;
ALTER TABLE RHNPACKAGEPROVIDER MODIFY NAME NOT NULL;

--
-- RHNPACKAGEPROVIDER
--
ALTER TABLE RHNPACKAGEPROVIDER DROP CONSTRAINT RHN_PKG_PROVIDER_MODIFIED_NN;
ALTER TABLE RHNPACKAGEPROVIDER MODIFY MODIFIED NOT NULL;

--
-- RHNPACKAGEPROVIDES
--
ALTER TABLE RHNPACKAGEPROVIDES DROP CONSTRAINT RHN_PKG_PROVIDES_CID_NN;
ALTER TABLE RHNPACKAGEPROVIDES MODIFY CAPABILITY_ID NOT NULL;

--
-- RHNPACKAGEPROVIDES
--
ALTER TABLE RHNPACKAGEPROVIDES DROP CONSTRAINT RHN_PKG_PROVIDES_CTIME_NN;
ALTER TABLE RHNPACKAGEPROVIDES MODIFY CREATED NOT NULL;

--
-- RHNPACKAGEPROVIDES
--
ALTER TABLE RHNPACKAGEPROVIDES DROP CONSTRAINT RHN_PKG_PROVIDES_MTIME_NN;
ALTER TABLE RHNPACKAGEPROVIDES MODIFY MODIFIED NOT NULL;

--
-- RHNPACKAGEPROVIDES
--
ALTER TABLE RHNPACKAGEPROVIDES DROP CONSTRAINT RHN_PKG_PROVIDES_PID_NN;
ALTER TABLE RHNPACKAGEPROVIDES MODIFY PACKAGE_ID NOT NULL;

--
-- RHNPACKAGEPROVIDES
--
ALTER TABLE RHNPACKAGEPROVIDES DROP CONSTRAINT RHN_PKG_PROVIDES_SENSE_NN;
ALTER TABLE RHNPACKAGEPROVIDES MODIFY SENSE NOT NULL;

--
-- RHNPACKAGEREQUIRES
--
ALTER TABLE RHNPACKAGEREQUIRES DROP CONSTRAINT RHN_PKG_REQUIRES_CID_NN;
ALTER TABLE RHNPACKAGEREQUIRES MODIFY CAPABILITY_ID NOT NULL;

--
-- RHNPACKAGEREQUIRES
--
ALTER TABLE RHNPACKAGEREQUIRES DROP CONSTRAINT RHN_PKG_REQUIRES_CTIME_NN;
ALTER TABLE RHNPACKAGEREQUIRES MODIFY CREATED NOT NULL;

--
-- RHNPACKAGEREQUIRES
--
ALTER TABLE RHNPACKAGEREQUIRES DROP CONSTRAINT RHN_PKG_REQUIRES_MTIME_NN;
ALTER TABLE RHNPACKAGEREQUIRES MODIFY MODIFIED NOT NULL;

--
-- RHNPACKAGEREQUIRES
--
ALTER TABLE RHNPACKAGEREQUIRES DROP CONSTRAINT RHN_PKG_REQUIRES_PID_NN;
ALTER TABLE RHNPACKAGEREQUIRES MODIFY PACKAGE_ID NOT NULL;

--
-- RHNPACKAGEREQUIRES
--
ALTER TABLE RHNPACKAGEREQUIRES DROP CONSTRAINT RHN_PKG_REQUIRES_SENSE_NN;
ALTER TABLE RHNPACKAGEREQUIRES MODIFY SENSE NOT NULL;

--
-- RHNPACKAGESENSEMAP
--
ALTER TABLE RHNPACKAGESENSEMAP DROP CONSTRAINT RHN_PKG_SENSEMAP_SENSE_NN;
ALTER TABLE RHNPACKAGESENSEMAP MODIFY SENSE NOT NULL;

--
-- RHNPACKAGESENSEMAP
--
ALTER TABLE RHNPACKAGESENSEMAP DROP CONSTRAINT RHN_PKG_SENSEMAP_SID_NN;
ALTER TABLE RHNPACKAGESENSEMAP MODIFY SENSE_ID NOT NULL;

--
-- RHNPACKAGESENSE
--
ALTER TABLE RHNPACKAGESENSE DROP CONSTRAINT RHN_PKG_SENSE_ID_NN;
ALTER TABLE RHNPACKAGESENSE MODIFY ID NOT NULL;

--
-- RHNPACKAGESENSE
--
ALTER TABLE RHNPACKAGESENSE DROP CONSTRAINT RHN_PKG_SENSE_LABEL_NN;
ALTER TABLE RHNPACKAGESENSE MODIFY LABEL NOT NULL;

--
-- RHNPACKAGENAME
--
ALTER TABLE RHNPACKAGENAME DROP CONSTRAINT RHN_PN_ID_NN;
ALTER TABLE RHNPACKAGENAME MODIFY ID NOT NULL;

--
-- RHNPACKAGENAME
--
ALTER TABLE RHNPACKAGENAME DROP CONSTRAINT RHN_PN_NAME_NN;
ALTER TABLE RHNPACKAGENAME MODIFY NAME NOT NULL;

--
-- RHN_PROBE_PARAM_VALUE
--
ALTER TABLE RHN_PROBE_PARAM_VALUE DROP CONSTRAINT RHN_PPVAL_COMMAND_ID_NN;
ALTER TABLE RHN_PROBE_PARAM_VALUE MODIFY COMMAND_ID NOT NULL;

--
-- RHN_PROBE_PARAM_VALUE
--
ALTER TABLE RHN_PROBE_PARAM_VALUE DROP CONSTRAINT RHN_PPVAL_PARAM_NAME_NN;
ALTER TABLE RHN_PROBE_PARAM_VALUE MODIFY PARAM_NAME NOT NULL;

--
-- RHN_PROBE_PARAM_VALUE
--
ALTER TABLE RHN_PROBE_PARAM_VALUE DROP CONSTRAINT RHN_PPVAL_PROBE_ID_NN;
ALTER TABLE RHN_PROBE_PARAM_VALUE MODIFY PROBE_ID NOT NULL;

--
-- RHN_PROBE_STATE
--
ALTER TABLE RHN_PROBE_STATE DROP CONSTRAINT RHN_PRBST_PROBE_ID_NN;
ALTER TABLE RHN_PROBE_STATE MODIFY PROBE_ID NOT NULL;

--
-- RHN_PROBE_STATE
--
ALTER TABLE RHN_PROBE_STATE DROP CONSTRAINT RHN_PRBST_SCOUT_ID_NN;
ALTER TABLE RHN_PROBE_STATE MODIFY SCOUT_ID NOT NULL;

--
-- RHN_PROBE_TYPES
--
ALTER TABLE RHN_PROBE_TYPES DROP CONSTRAINT RHN_PRBTP_PROBE_TYPE_NN;
ALTER TABLE RHN_PROBE_TYPES MODIFY PROBE_TYPE NOT NULL;

--
-- RHN_PROBE_TYPES
--
ALTER TABLE RHN_PROBE_TYPES DROP CONSTRAINT RHN_PRBTP_TYPE_DESC_NN;
ALTER TABLE RHN_PROBE_TYPES MODIFY TYPE_DESCRIPTION NOT NULL;

--
-- RHNPRIVATECHANNELFAMILY
--
ALTER TABLE RHNPRIVATECHANNELFAMILY DROP CONSTRAINT RHN_PRIVCF_CFID_NN;
ALTER TABLE RHNPRIVATECHANNELFAMILY MODIFY CHANNEL_FAMILY_ID NOT NULL;

--
-- RHNPRIVATECHANNELFAMILY
--
ALTER TABLE RHNPRIVATECHANNELFAMILY DROP CONSTRAINT RHN_PRIVCF_CREATED_NN;
ALTER TABLE RHNPRIVATECHANNELFAMILY MODIFY CREATED NOT NULL;

--
-- RHNPRIVATECHANNELFAMILY
--
ALTER TABLE RHNPRIVATECHANNELFAMILY DROP CONSTRAINT RHN_PRIVCF_CURMEMBERS_NN;
ALTER TABLE RHNPRIVATECHANNELFAMILY MODIFY CURRENT_MEMBERS NOT NULL;

--
-- RHNPRIVATECHANNELFAMILY
--
ALTER TABLE RHNPRIVATECHANNELFAMILY DROP CONSTRAINT RHN_PRIVCF_MODIFIED_NN;
ALTER TABLE RHNPRIVATECHANNELFAMILY MODIFY MODIFIED NOT NULL;

--
-- RHNPRIVATECHANNELFAMILY
--
ALTER TABLE RHNPRIVATECHANNELFAMILY DROP CONSTRAINT RHN_PRIVCF_OID_NN;
ALTER TABLE RHNPRIVATECHANNELFAMILY MODIFY ORG_ID NOT NULL;

--
-- RHN_PROBE
--
ALTER TABLE RHN_PROBE DROP CONSTRAINT RHN_PROBE_CHK_INT_NN;
ALTER TABLE RHN_PROBE MODIFY CHECK_INTERVAL_MINUTES NOT NULL;

--
-- RHN_PROBE
--
ALTER TABLE RHN_PROBE DROP CONSTRAINT RHN_PROBE_COMMAND_ID_NN;
ALTER TABLE RHN_PROBE MODIFY COMMAND_ID NOT NULL;

--
-- RHN_PROBE
--
ALTER TABLE RHN_PROBE DROP CONSTRAINT RHN_PROBE_CUST_ID_NN;
ALTER TABLE RHN_PROBE MODIFY CUSTOMER_ID NOT NULL;

--
-- RHN_PROBE
--
ALTER TABLE RHN_PROBE DROP CONSTRAINT RHN_PROBE_DESCRIPTION_NN;
ALTER TABLE RHN_PROBE MODIFY DESCRIPTION NOT NULL;

--
-- RHN_PROBE
--
ALTER TABLE RHN_PROBE DROP CONSTRAINT RHN_PROBE_PROBE_TYPE_NN;
ALTER TABLE RHN_PROBE MODIFY PROBE_TYPE NOT NULL;

--
-- RHN_PROBE
--
ALTER TABLE RHN_PROBE DROP CONSTRAINT RHN_PROBE_RECID_NN;
ALTER TABLE RHN_PROBE MODIFY RECID NOT NULL;

--
-- RHN_PROBE
--
ALTER TABLE RHN_PROBE DROP CONSTRAINT RHN_PROBE_RETRY_INT_NN;
ALTER TABLE RHN_PROBE MODIFY RETRY_INTERVAL_MINUTES NOT NULL;

--
-- RHNPRODUCTNAME
--
ALTER TABLE RHNPRODUCTNAME DROP CONSTRAINT RHN_PRODUCTNAME_ID_NN;
ALTER TABLE RHNPRODUCTNAME MODIFY ID NOT NULL;

--
-- RHNPRODUCTNAME
--
ALTER TABLE RHNPRODUCTNAME DROP CONSTRAINT RHN_PRODUCTNAME_LBL_NN;
ALTER TABLE RHNPRODUCTNAME MODIFY LABEL NOT NULL;

--
-- RHNPRODUCTNAME
--
ALTER TABLE RHNPRODUCTNAME DROP CONSTRAINT RHN_PRODUCTNAME_NAME_NN;
ALTER TABLE RHNPRODUCTNAME MODIFY NAME NOT NULL;

--
-- RHNPRODUCT
--
ALTER TABLE RHNPRODUCT DROP CONSTRAINT RHN_PRODUCT_CAT_NN;
ALTER TABLE RHNPRODUCT MODIFY PRODUCT_LINE_ID NOT NULL;

--
-- RHNPRODUCT
--
ALTER TABLE RHNPRODUCT DROP CONSTRAINT RHN_PRODUCT_CREATED_NN;
ALTER TABLE RHNPRODUCT MODIFY CREATED NOT NULL;

--
-- RHNPRODUCT
--
ALTER TABLE RHNPRODUCT DROP CONSTRAINT RHN_PRODUCT_ID_NN;
ALTER TABLE RHNPRODUCT MODIFY ID NOT NULL;

--
-- RHNPRODUCT
--
ALTER TABLE RHNPRODUCT DROP CONSTRAINT RHN_PRODUCT_LABEL_NN;
ALTER TABLE RHNPRODUCT MODIFY LABEL NOT NULL;

--
-- RHNPRODUCT
--
ALTER TABLE RHNPRODUCT DROP CONSTRAINT RHN_PRODUCT_LM_NN;
ALTER TABLE RHNPRODUCT MODIFY LAST_MODIFIED NOT NULL;

--
-- RHNPRODUCT
--
ALTER TABLE RHNPRODUCT DROP CONSTRAINT RHN_PRODUCT_MODIFIED_NN;
ALTER TABLE RHNPRODUCT MODIFY MODIFIED NOT NULL;

--
-- RHNPRODUCT
--
ALTER TABLE RHNPRODUCT DROP CONSTRAINT RHN_PRODUCT_NAME_NN;
ALTER TABLE RHNPRODUCT MODIFY NAME NOT NULL;

--
-- RHNPRODUCTLINE
--
ALTER TABLE RHNPRODUCTLINE DROP CONSTRAINT RHN_PROD_LINE_CREATED_NN;
ALTER TABLE RHNPRODUCTLINE MODIFY CREATED NOT NULL;

--
-- RHNPRODUCTLINE
--
ALTER TABLE RHNPRODUCTLINE DROP CONSTRAINT RHN_PROD_LINE_ID_NN;
ALTER TABLE RHNPRODUCTLINE MODIFY ID NOT NULL;

--
-- RHNPRODUCTLINE
--
ALTER TABLE RHNPRODUCTLINE DROP CONSTRAINT RHN_PROD_LINE_LABEL_NN;
ALTER TABLE RHNPRODUCTLINE MODIFY LABEL NOT NULL;

--
-- RHNPRODUCTLINE
--
ALTER TABLE RHNPRODUCTLINE DROP CONSTRAINT RHN_PROD_LINE_LM_NN;
ALTER TABLE RHNPRODUCTLINE MODIFY LAST_MODIFIED NOT NULL;

--
-- RHNPRODUCTLINE
--
ALTER TABLE RHNPRODUCTLINE DROP CONSTRAINT RHN_PROD_LINE_MODIFIED_NN;
ALTER TABLE RHNPRODUCTLINE MODIFY MODIFIED NOT NULL;

--
-- RHNPRODUCTLINE
--
ALTER TABLE RHNPRODUCTLINE DROP CONSTRAINT RHN_PROD_LINE_NAME_NN;
ALTER TABLE RHNPRODUCTLINE MODIFY NAME NOT NULL;

--
-- RHNPROVISIONSTATE
--
ALTER TABLE RHNPROVISIONSTATE DROP CONSTRAINT RHN_PROVSTATE_CREAT_NN;
ALTER TABLE RHNPROVISIONSTATE MODIFY CREATED NOT NULL;

--
-- RHNPROVISIONSTATE
--
ALTER TABLE RHNPROVISIONSTATE DROP CONSTRAINT RHN_PROVSTATE_DESC_NN;
ALTER TABLE RHNPROVISIONSTATE MODIFY DESCRIPTION NOT NULL;

--
-- RHNPROVISIONSTATE
--
ALTER TABLE RHNPROVISIONSTATE DROP CONSTRAINT RHN_PROVSTATE_ID_NN;
ALTER TABLE RHNPROVISIONSTATE MODIFY ID NOT NULL;

--
-- RHNPROVISIONSTATE
--
ALTER TABLE RHNPROVISIONSTATE DROP CONSTRAINT RHN_PROVSTATE_LABEL_NN;
ALTER TABLE RHNPROVISIONSTATE MODIFY LABEL NOT NULL;

--
-- RHNPROVISIONSTATE
--
ALTER TABLE RHNPROVISIONSTATE DROP CONSTRAINT RHN_PROVSTATE_MOD_NN;
ALTER TABLE RHNPROVISIONSTATE MODIFY MODIFIED NOT NULL;

--
-- RHNPROXYINFO
--
ALTER TABLE RHNPROXYINFO DROP CONSTRAINT RHN_PROXY_INFO_SID_NN;
ALTER TABLE RHNPROXYINFO MODIFY SERVER_ID NOT NULL;

--
-- RHNPUBLICCHANNELFAMILY
--
ALTER TABLE RHNPUBLICCHANNELFAMILY DROP CONSTRAINT RHN_PUBCF_CFID_NN;
ALTER TABLE RHNPUBLICCHANNELFAMILY MODIFY CHANNEL_FAMILY_ID NOT NULL;

--
-- RHNPUBLICCHANNELFAMILY
--
ALTER TABLE RHNPUBLICCHANNELFAMILY DROP CONSTRAINT RHN_PUBCF_CREAT_NN;
ALTER TABLE RHNPUBLICCHANNELFAMILY MODIFY CREATED NOT NULL;

--
-- RHNPUBLICCHANNELFAMILY
--
ALTER TABLE RHNPUBLICCHANNELFAMILY DROP CONSTRAINT RHN_PUBCF_MOD_NN;
ALTER TABLE RHNPUBLICCHANNELFAMILY MODIFY MODIFIED NOT NULL;

--
-- RHNPUSHDISPATCHER
--
ALTER TABLE RHNPUSHDISPATCHER DROP CONSTRAINT RHN_PUSHDISPATCH_CREAT_NN;
ALTER TABLE RHNPUSHDISPATCHER MODIFY CREATED NOT NULL;

--
-- RHNPUSHDISPATCHER
--
ALTER TABLE RHNPUSHDISPATCHER DROP CONSTRAINT RHN_PUSHDISPATCH_HN_NN;
ALTER TABLE RHNPUSHDISPATCHER MODIFY HOSTNAME NOT NULL;

--
-- RHNPUSHDISPATCHER
--
ALTER TABLE RHNPUSHDISPATCHER DROP CONSTRAINT RHN_PUSHDISPATCH_ID_NN;
ALTER TABLE RHNPUSHDISPATCHER MODIFY ID NOT NULL;

--
-- RHNPUSHDISPATCHER
--
ALTER TABLE RHNPUSHDISPATCHER DROP CONSTRAINT RHN_PUSHDISPATCH_JID_NN;
ALTER TABLE RHNPUSHDISPATCHER MODIFY JABBER_ID NOT NULL;

--
-- RHNPUSHDISPATCHER
--
ALTER TABLE RHNPUSHDISPATCHER DROP CONSTRAINT RHN_PUSHDISPATCH_LC_NN;
ALTER TABLE RHNPUSHDISPATCHER MODIFY LAST_CHECKIN NOT NULL;

--
-- RHNPUSHDISPATCHER
--
ALTER TABLE RHNPUSHDISPATCHER DROP CONSTRAINT RHN_PUSHDISPATCH_MOD_NN;
ALTER TABLE RHNPUSHDISPATCHER MODIFY MODIFIED NOT NULL;

--
-- RHNPUSHDISPATCHER
--
ALTER TABLE RHNPUSHDISPATCHER DROP CONSTRAINT RHN_PUSHDISPATCH_PORT_NN;
ALTER TABLE RHNPUSHDISPATCHER MODIFY PORT NOT NULL;

--
-- RHN_QUANTA
--
ALTER TABLE RHN_QUANTA DROP CONSTRAINT RHN_QNTA0_QUANTUM_ID_NN;
ALTER TABLE RHN_QUANTA MODIFY QUANTUM_ID NOT NULL;

--
-- RHNRAM
--
ALTER TABLE RHNRAM DROP CONSTRAINT RHN_RAM_CREATED_NN;
ALTER TABLE RHNRAM MODIFY CREATED NOT NULL;

--
-- RHNRAM
--
ALTER TABLE RHNRAM DROP CONSTRAINT RHN_RAM_ID_NN;
ALTER TABLE RHNRAM MODIFY ID NOT NULL;

--
-- RHNRAM
--
ALTER TABLE RHNRAM DROP CONSTRAINT RHN_RAM_MODIFIED_NN;
ALTER TABLE RHNRAM MODIFY MODIFIED NOT NULL;

--
-- RHNRAM
--
ALTER TABLE RHNRAM DROP CONSTRAINT RHN_RAM_RAM_NN;
ALTER TABLE RHNRAM MODIFY RAM NOT NULL;

--
-- RHNRAM
--
ALTER TABLE RHNRAM DROP CONSTRAINT RHN_RAM_SERVER_NN;
ALTER TABLE RHNRAM MODIFY SERVER_ID NOT NULL;

--
-- RHNRAM
--
ALTER TABLE RHNRAM DROP CONSTRAINT RHN_RAM_SWAP_NN;
ALTER TABLE RHNRAM MODIFY SWAP NOT NULL;

--
-- RHNRELEASECHANNELMAP
--
ALTER TABLE RHNRELEASECHANNELMAP DROP CONSTRAINT RHN_RCM_CAID_NN;
ALTER TABLE RHNRELEASECHANNELMAP MODIFY CHANNEL_ARCH_ID NOT NULL;

--
-- RHNRELEASECHANNELMAP
--
ALTER TABLE RHNRELEASECHANNELMAP DROP CONSTRAINT RHN_RCM_CID_NN;
ALTER TABLE RHNRELEASECHANNELMAP MODIFY CHANNEL_ID NOT NULL;

--
-- RHNRELEASECHANNELMAP
--
ALTER TABLE RHNRELEASECHANNELMAP DROP CONSTRAINT RHN_RCM_PRODCT_NN;
ALTER TABLE RHNRELEASECHANNELMAP MODIFY PRODUCT NOT NULL;

--
-- RHNRELEASECHANNELMAP
--
ALTER TABLE RHNRELEASECHANNELMAP DROP CONSTRAINT RHN_RCM_RELSE_NN;
ALTER TABLE RHNRELEASECHANNELMAP MODIFY RELEASE NOT NULL;

--
-- RHNRELEASECHANNELMAP
--
ALTER TABLE RHNRELEASECHANNELMAP DROP CONSTRAINT RHN_RCM_VERSN_NN;
ALTER TABLE RHNRELEASECHANNELMAP MODIFY VERSION NOT NULL;

--
-- RHN_REDIRECT_CRITERIA
--
ALTER TABLE RHN_REDIRECT_CRITERIA DROP CONSTRAINT RHN_RDRCR_INVERTED_NN;
ALTER TABLE RHN_REDIRECT_CRITERIA MODIFY INVERTED NOT NULL;

--
-- RHN_REDIRECT_CRITERIA
--
ALTER TABLE RHN_REDIRECT_CRITERIA DROP CONSTRAINT RHN_RDRCR_MATCH_PARAM_NN;
ALTER TABLE RHN_REDIRECT_CRITERIA MODIFY MATCH_PARAM NOT NULL;

--
-- RHN_REDIRECT_CRITERIA
--
ALTER TABLE RHN_REDIRECT_CRITERIA DROP CONSTRAINT RHN_RDRCR_RECID_NN;
ALTER TABLE RHN_REDIRECT_CRITERIA MODIFY RECID NOT NULL;

--
-- RHN_REDIRECT_CRITERIA
--
ALTER TABLE RHN_REDIRECT_CRITERIA DROP CONSTRAINT RHN_RDRCR_REDIRECT_ID_NN;
ALTER TABLE RHN_REDIRECT_CRITERIA MODIFY REDIRECT_ID NOT NULL;

--
-- RHN_REDIRECTS
--
ALTER TABLE RHN_REDIRECTS DROP CONSTRAINT RHN_RDRCT_EXPIRATION_NN;
ALTER TABLE RHN_REDIRECTS MODIFY EXPIRATION NOT NULL;

--
-- RHN_REDIRECTS
--
ALTER TABLE RHN_REDIRECTS DROP CONSTRAINT RHN_RDRCT_RECID_NN;
ALTER TABLE RHN_REDIRECTS MODIFY RECID NOT NULL;

--
-- RHN_REDIRECTS
--
ALTER TABLE RHN_REDIRECTS DROP CONSTRAINT RHN_RDRCT_RECURRING_NN;
ALTER TABLE RHN_REDIRECTS MODIFY RECURRING NOT NULL;

--
-- RHN_REDIRECTS
--
ALTER TABLE RHN_REDIRECTS DROP CONSTRAINT RHN_RDRCT_REDIRECT_TYPE_NN;
ALTER TABLE RHN_REDIRECTS MODIFY REDIRECT_TYPE NOT NULL;

--
-- RHN_REDIRECTS
--
ALTER TABLE RHN_REDIRECTS DROP CONSTRAINT RHN_RDRCT_START_DATE_NN;
ALTER TABLE RHN_REDIRECTS MODIFY START_DATE NOT NULL;

--
-- RHN_REDIRECT_EMAIL_TARGETS
--
ALTER TABLE RHN_REDIRECT_EMAIL_TARGETS DROP CONSTRAINT RHN_RDRET_EMAIL_ADDR_NN;
ALTER TABLE RHN_REDIRECT_EMAIL_TARGETS MODIFY EMAIL_ADDRESS NOT NULL;

--
-- RHN_REDIRECT_EMAIL_TARGETS
--
ALTER TABLE RHN_REDIRECT_EMAIL_TARGETS DROP CONSTRAINT RHN_RDRET_REDIRECT_ID_NN;
ALTER TABLE RHN_REDIRECT_EMAIL_TARGETS MODIFY REDIRECT_ID NOT NULL;

--
-- RHN_REDIRECT_GROUP_TARGETS
--
ALTER TABLE RHN_REDIRECT_GROUP_TARGETS DROP CONSTRAINT RHN_RDRGT_GROUP_ID_NN;
ALTER TABLE RHN_REDIRECT_GROUP_TARGETS MODIFY CONTACT_GROUP_ID NOT NULL;

--
-- RHN_REDIRECT_GROUP_TARGETS
--
ALTER TABLE RHN_REDIRECT_GROUP_TARGETS DROP CONSTRAINT RHN_RDRGT_REDIRECT_ID_NN;
ALTER TABLE RHN_REDIRECT_GROUP_TARGETS MODIFY REDIRECT_ID NOT NULL;

--
-- RHN_REDIRECT_METHOD_TARGETS
--
ALTER TABLE RHN_REDIRECT_METHOD_TARGETS DROP CONSTRAINT RHN_RDRME_METHOD_ID;
ALTER TABLE RHN_REDIRECT_METHOD_TARGETS MODIFY CONTACT_METHOD_ID NOT NULL;

--
-- RHN_REDIRECT_METHOD_TARGETS
--
ALTER TABLE RHN_REDIRECT_METHOD_TARGETS DROP CONSTRAINT RHN_RDRME_REDIRECT_ID;
ALTER TABLE RHN_REDIRECT_METHOD_TARGETS MODIFY REDIRECT_ID NOT NULL;

--
-- RHN_REDIRECT_MATCH_TYPES
--
ALTER TABLE RHN_REDIRECT_MATCH_TYPES DROP CONSTRAINT RHN_RDRMT_NAME_NN;
ALTER TABLE RHN_REDIRECT_MATCH_TYPES MODIFY NAME NOT NULL;

--
-- RHN_REDIRECT_TYPES
--
ALTER TABLE RHN_REDIRECT_TYPES DROP CONSTRAINT RHN_RDRTP_NAME_NN;
ALTER TABLE RHN_REDIRECT_TYPES MODIFY NAME NOT NULL;

--
-- RHNREGTOKENCONFIGCHANNELS
--
ALTER TABLE RHNREGTOKENCONFIGCHANNELS DROP CONSTRAINT RHN_REGTOK_CONFCHAN_CCID_NN;
ALTER TABLE RHNREGTOKENCONFIGCHANNELS MODIFY CONFIG_CHANNEL_ID NOT NULL;

--
-- RHNREGTOKENCONFIGCHANNELS
--
ALTER TABLE RHNREGTOKENCONFIGCHANNELS DROP CONSTRAINT RHN_REGTOK_CONFCHAN_POS_NN;
ALTER TABLE RHNREGTOKENCONFIGCHANNELS MODIFY POSITION NOT NULL;

--
-- RHNREGTOKENCONFIGCHANNELS
--
ALTER TABLE RHNREGTOKENCONFIGCHANNELS DROP CONSTRAINT RHN_REGTOK_CONFCHAN_TID_NN;
ALTER TABLE RHNREGTOKENCONFIGCHANNELS MODIFY TOKEN_ID NOT NULL;

--
-- RHNREGTOKEN
--
ALTER TABLE RHNREGTOKEN DROP CONSTRAINT RHN_REG_TOKEN_DEF_NN;
ALTER TABLE RHNREGTOKEN MODIFY DISABLED NOT NULL;

--
-- RHNREGTOKENORGDEFAULT
--
ALTER TABLE RHNREGTOKENORGDEFAULT DROP CONSTRAINT RHN_REG_TOKEN_DEF_OID_NN;
ALTER TABLE RHNREGTOKENORGDEFAULT MODIFY ORG_ID NOT NULL;

--
-- RHNREGTOKEN
--
ALTER TABLE RHNREGTOKEN DROP CONSTRAINT RHN_REG_TOKEN_DEPLOYCONFS_NN;
ALTER TABLE RHNREGTOKEN MODIFY DEPLOY_CONFIGS NOT NULL;

--
-- RHNREGTOKEN
--
ALTER TABLE RHNREGTOKEN DROP CONSTRAINT RHN_REG_TOKEN_ID_NN;
ALTER TABLE RHNREGTOKEN MODIFY ID NOT NULL;

--
-- RHNREGTOKEN
--
ALTER TABLE RHNREGTOKEN DROP CONSTRAINT RHN_REG_TOKEN_NOTE_NN;
ALTER TABLE RHNREGTOKEN MODIFY NOTE NOT NULL;

--
-- RHNREGTOKEN
--
ALTER TABLE RHNREGTOKEN DROP CONSTRAINT RHN_REG_TOKEN_OID_NN;
ALTER TABLE RHNREGTOKEN MODIFY ORG_ID NOT NULL;

--
-- RHNREGTOKENCHANNELS
--
ALTER TABLE RHNREGTOKENCHANNELS DROP CONSTRAINT RHN_REG_TOK_CHN_SG_NN;
ALTER TABLE RHNREGTOKENCHANNELS MODIFY CHANNEL_ID NOT NULL;

--
-- RHNREGTOKENCHANNELS
--
ALTER TABLE RHNREGTOKENCHANNELS DROP CONSTRAINT RHN_REG_TOK_CHN_TID_NN;
ALTER TABLE RHNREGTOKENCHANNELS MODIFY TOKEN_ID NOT NULL;

--
-- RHNREGTOKENENTITLEMENT
--
ALTER TABLE RHNREGTOKENENTITLEMENT DROP CONSTRAINT RHN_REG_TOK_ENT_RTID_NN;
ALTER TABLE RHNREGTOKENENTITLEMENT MODIFY REG_TOKEN_ID NOT NULL;

--
-- RHNREGTOKENENTITLEMENT
--
ALTER TABLE RHNREGTOKENENTITLEMENT DROP CONSTRAINT RHN_REG_TOK_ENT_SGTID_NN;
ALTER TABLE RHNREGTOKENENTITLEMENT MODIFY SERVER_GROUP_TYPE_ID NOT NULL;

--
-- RHNREGTOKENGROUPS
--
ALTER TABLE RHNREGTOKENGROUPS DROP CONSTRAINT RHN_REG_TOK_GRP_SG_NN;
ALTER TABLE RHNREGTOKENGROUPS MODIFY SERVER_GROUP_ID NOT NULL;

--
-- RHNREGTOKENGROUPS
--
ALTER TABLE RHNREGTOKENGROUPS DROP CONSTRAINT RHN_REG_TOK_GRP_TID_NN;
ALTER TABLE RHNREGTOKENGROUPS MODIFY TOKEN_ID NOT NULL;

--
-- RHNREGTOKENPACKAGES
--
ALTER TABLE RHNREGTOKENPACKAGES DROP CONSTRAINT RHN_REG_TOK_PKG_ID_NN;
ALTER TABLE RHNREGTOKENPACKAGES MODIFY ID NOT NULL;

--
-- RHNREGTOKENPACKAGES
--
ALTER TABLE RHNREGTOKENPACKAGES DROP CONSTRAINT RHN_REG_TOK_PKG_SG_NN;
ALTER TABLE RHNREGTOKENPACKAGES MODIFY NAME_ID NOT NULL;

--
-- RHNREGTOKENPACKAGES
--
ALTER TABLE RHNREGTOKENPACKAGES DROP CONSTRAINT RHN_REG_TOK_PKG_TID_NN;
ALTER TABLE RHNREGTOKENPACKAGES MODIFY TOKEN_ID NOT NULL;

--
-- RHNRELATIONSHIPTYPE
--
ALTER TABLE RHNRELATIONSHIPTYPE DROP CONSTRAINT RHN_RELTYPE_CREATED_NN;
ALTER TABLE RHNRELATIONSHIPTYPE MODIFY CREATED NOT NULL;

--
-- RHNRELATIONSHIPTYPE
--
ALTER TABLE RHNRELATIONSHIPTYPE DROP CONSTRAINT RHN_RELTYPE_ID_NN;
ALTER TABLE RHNRELATIONSHIPTYPE MODIFY ID NOT NULL;

--
-- RHNRELATIONSHIPTYPE
--
ALTER TABLE RHNRELATIONSHIPTYPE DROP CONSTRAINT RHN_RELTYPE_LABEL_NN;
ALTER TABLE RHNRELATIONSHIPTYPE MODIFY LABEL NOT NULL;

--
-- RHNRELATIONSHIPTYPE
--
ALTER TABLE RHNRELATIONSHIPTYPE DROP CONSTRAINT RHN_RELTYPE_MODIFIED_NN;
ALTER TABLE RHNRELATIONSHIPTYPE MODIFY MODIFIED NOT NULL;

--
-- RHNREPOREGENQUEUE
--
ALTER TABLE RHNREPOREGENQUEUE DROP CONSTRAINT RHN_REPOREGENQ_CHAN_LABEL_NN;
ALTER TABLE RHNREPOREGENQUEUE MODIFY CHANNEL_LABEL NOT NULL;

--
-- RHNREPOREGENQUEUE
--
ALTER TABLE RHNREPOREGENQUEUE DROP CONSTRAINT RHN_REPOREGENQ_CREATED_NN;
ALTER TABLE RHNREPOREGENQUEUE MODIFY CREATED NOT NULL;

--
-- RHNREPOREGENQUEUE
--
ALTER TABLE RHNREPOREGENQUEUE DROP CONSTRAINT RHN_REPOREGENQ_ID_NN;
-- ALTER TABLE RHNREPOREGENQUEUE MODIFY ID NOT NULL;

--
-- RHNREPOREGENQUEUE
--
ALTER TABLE RHNREPOREGENQUEUE DROP CONSTRAINT RHN_REPOREGENQ_MODIFIED_NN;
ALTER TABLE RHNREPOREGENQUEUE MODIFY MODIFIED NOT NULL;

--
-- RHNREDHATCANONVERSION
--
ALTER TABLE RHNREDHATCANONVERSION DROP CONSTRAINT RHN_RH_CANON_VER_CREATED_NN;
ALTER TABLE RHNREDHATCANONVERSION MODIFY CREATED NOT NULL;

--
-- RHNREDHATCANONVERSION
--
ALTER TABLE RHNREDHATCANONVERSION DROP CONSTRAINT RHN_RH_CANON_VER_CV_NN;
ALTER TABLE RHNREDHATCANONVERSION MODIFY CANON_VERSION NOT NULL;

--
-- RHNREDHATCANONVERSION
--
ALTER TABLE RHNREDHATCANONVERSION DROP CONSTRAINT RHN_RH_CANON_VER_MODIFIED_NN;
ALTER TABLE RHNREDHATCANONVERSION MODIFY MODIFIED NOT NULL;

--
-- RHNREDHATCANONVERSION
--
ALTER TABLE RHNREDHATCANONVERSION DROP CONSTRAINT RHN_RH_CANON_VER_V_NN;
ALTER TABLE RHNREDHATCANONVERSION MODIFY VERSION NOT NULL;

--
-- RHNSERVERACTIONVERIFYMISSING
--
ALTER TABLE RHNSERVERACTIONVERIFYMISSING DROP CONSTRAINT RHN_SACTIONVM_AID_NN;
ALTER TABLE RHNSERVERACTIONVERIFYMISSING MODIFY ACTION_ID NOT NULL;

--
-- RHNSERVERACTIONVERIFYMISSING
--
ALTER TABLE RHNSERVERACTIONVERIFYMISSING DROP CONSTRAINT RHN_SACTIONVM_CREAT_NN;
ALTER TABLE RHNSERVERACTIONVERIFYMISSING MODIFY CREATED NOT NULL;

--
-- RHNSERVERACTIONVERIFYMISSING
--
ALTER TABLE RHNSERVERACTIONVERIFYMISSING DROP CONSTRAINT RHN_SACTIONVM_MOD_NN;
ALTER TABLE RHNSERVERACTIONVERIFYMISSING MODIFY MODIFIED NOT NULL;

--
-- RHNSERVERACTIONVERIFYMISSING
--
ALTER TABLE RHNSERVERACTIONVERIFYMISSING DROP CONSTRAINT RHN_SACTIONVM_PAID_NN;
ALTER TABLE RHNSERVERACTIONVERIFYMISSING MODIFY PACKAGE_ARCH_ID NOT NULL;

--
-- RHNSERVERACTIONVERIFYMISSING
--
ALTER TABLE RHNSERVERACTIONVERIFYMISSING DROP CONSTRAINT RHN_SACTIONVM_PCID_NN;
ALTER TABLE RHNSERVERACTIONVERIFYMISSING MODIFY PACKAGE_CAPABILITY_ID NOT NULL;

--
-- RHNSERVERACTIONVERIFYMISSING
--
ALTER TABLE RHNSERVERACTIONVERIFYMISSING DROP CONSTRAINT RHN_SACTIONVM_PEID_NN;
ALTER TABLE RHNSERVERACTIONVERIFYMISSING MODIFY PACKAGE_EVR_ID NOT NULL;

--
-- RHNSERVERACTIONVERIFYMISSING
--
ALTER TABLE RHNSERVERACTIONVERIFYMISSING DROP CONSTRAINT RHN_SACTIONVM_PNID_NN;
ALTER TABLE RHNSERVERACTIONVERIFYMISSING MODIFY PACKAGE_NAME_ID NOT NULL;

--
-- RHNSERVERACTIONVERIFYMISSING
--
ALTER TABLE RHNSERVERACTIONVERIFYMISSING DROP CONSTRAINT RHN_SACTIONVM_SID_NN;
ALTER TABLE RHNSERVERACTIONVERIFYMISSING MODIFY SERVER_ID NOT NULL;

--
-- RHNSERVERACTIONVERIFYRESULT
--
ALTER TABLE RHNSERVERACTIONVERIFYRESULT DROP CONSTRAINT RHN_SACTIONVR_AID_NN;
ALTER TABLE RHNSERVERACTIONVERIFYRESULT MODIFY ACTION_ID NOT NULL;

--
-- RHNSERVERACTIONVERIFYRESULT
--
ALTER TABLE RHNSERVERACTIONVERIFYRESULT DROP CONSTRAINT RHN_SACTIONVR_CREAT_NN;
ALTER TABLE RHNSERVERACTIONVERIFYRESULT MODIFY CREATED NOT NULL;

--
-- RHNSERVERACTIONVERIFYRESULT
--
ALTER TABLE RHNSERVERACTIONVERIFYRESULT DROP CONSTRAINT RHN_SACTIONVR_DEVNUM_NN;
ALTER TABLE RHNSERVERACTIONVERIFYRESULT MODIFY DEVNUM_DIFFERS NOT NULL;

--
-- RHNSERVERACTIONVERIFYRESULT
--
ALTER TABLE RHNSERVERACTIONVERIFYRESULT DROP CONSTRAINT RHN_SACTIONVR_GID_NN;
ALTER TABLE RHNSERVERACTIONVERIFYRESULT MODIFY GID_DIFFERS NOT NULL;

--
-- RHNSERVERACTIONVERIFYRESULT
--
ALTER TABLE RHNSERVERACTIONVERIFYRESULT DROP CONSTRAINT RHN_SACTIONVR_MD5_NN;
ALTER TABLE RHNSERVERACTIONVERIFYRESULT MODIFY MD5_DIFFERS NOT NULL;

--
-- RHNSERVERACTIONVERIFYRESULT
--
ALTER TABLE RHNSERVERACTIONVERIFYRESULT DROP CONSTRAINT RHN_SACTIONVR_MODE_NN;
ALTER TABLE RHNSERVERACTIONVERIFYRESULT MODIFY MODE_DIFFERS NOT NULL;

--
-- RHNSERVERACTIONVERIFYRESULT
--
ALTER TABLE RHNSERVERACTIONVERIFYRESULT DROP CONSTRAINT RHN_SACTIONVR_MOD_NN;
ALTER TABLE RHNSERVERACTIONVERIFYRESULT MODIFY MODIFIED NOT NULL;

--
-- RHNSERVERACTIONVERIFYRESULT
--
ALTER TABLE RHNSERVERACTIONVERIFYRESULT DROP CONSTRAINT RHN_SACTIONVR_MTIME_NN;
ALTER TABLE RHNSERVERACTIONVERIFYRESULT MODIFY MTIME_DIFFERS NOT NULL;

--
-- RHNSERVERACTIONVERIFYRESULT
--
ALTER TABLE RHNSERVERACTIONVERIFYRESULT DROP CONSTRAINT RHN_SACTIONVR_PAID_NN;
ALTER TABLE RHNSERVERACTIONVERIFYRESULT MODIFY PACKAGE_ARCH_ID NOT NULL;

--
-- RHNSERVERACTIONVERIFYRESULT
--
ALTER TABLE RHNSERVERACTIONVERIFYRESULT DROP CONSTRAINT RHN_SACTIONVR_PCID_NN;
ALTER TABLE RHNSERVERACTIONVERIFYRESULT MODIFY PACKAGE_CAPABILITY_ID NOT NULL;

--
-- RHNSERVERACTIONVERIFYRESULT
--
ALTER TABLE RHNSERVERACTIONVERIFYRESULT DROP CONSTRAINT RHN_SACTIONVR_PEID_NN;
ALTER TABLE RHNSERVERACTIONVERIFYRESULT MODIFY PACKAGE_EVR_ID NOT NULL;

--
-- RHNSERVERACTIONVERIFYRESULT
--
ALTER TABLE RHNSERVERACTIONVERIFYRESULT DROP CONSTRAINT RHN_SACTIONVR_PNID_NN;
ALTER TABLE RHNSERVERACTIONVERIFYRESULT MODIFY PACKAGE_NAME_ID NOT NULL;

--
-- RHNSERVERACTIONVERIFYRESULT
--
ALTER TABLE RHNSERVERACTIONVERIFYRESULT DROP CONSTRAINT RHN_SACTIONVR_READLINK_NN;
ALTER TABLE RHNSERVERACTIONVERIFYRESULT MODIFY READLINK_DIFFERS NOT NULL;

--
-- RHNSERVERACTIONVERIFYRESULT
--
ALTER TABLE RHNSERVERACTIONVERIFYRESULT DROP CONSTRAINT RHN_SACTIONVR_SID_NN;
ALTER TABLE RHNSERVERACTIONVERIFYRESULT MODIFY SERVER_ID NOT NULL;

--
-- RHNSERVERACTIONVERIFYRESULT
--
ALTER TABLE RHNSERVERACTIONVERIFYRESULT DROP CONSTRAINT RHN_SACTIONVR_SIZE_NN;
ALTER TABLE RHNSERVERACTIONVERIFYRESULT MODIFY SIZE_DIFFERS NOT NULL;

--
-- RHNSERVERACTIONVERIFYRESULT
--
ALTER TABLE RHNSERVERACTIONVERIFYRESULT DROP CONSTRAINT RHN_SACTIONVR_UID_NN;
ALTER TABLE RHNSERVERACTIONVERIFYRESULT MODIFY UID_DIFFERS NOT NULL;

--
-- RHNSERVERACTIONPACKAGERESULT
--
ALTER TABLE RHNSERVERACTIONPACKAGERESULT DROP CONSTRAINT RHN_SAP_RESULT_APID_NN;
ALTER TABLE RHNSERVERACTIONPACKAGERESULT MODIFY ACTION_PACKAGE_ID NOT NULL;

--
-- RHNSERVERACTIONPACKAGERESULT
--
ALTER TABLE RHNSERVERACTIONPACKAGERESULT DROP CONSTRAINT RHN_SAP_RESULT_CREAT_NN;
ALTER TABLE RHNSERVERACTIONPACKAGERESULT MODIFY CREATED NOT NULL;

--
-- RHNSERVERACTIONPACKAGERESULT
--
ALTER TABLE RHNSERVERACTIONPACKAGERESULT DROP CONSTRAINT RHN_SAP_RESULT_MOD_NN;
ALTER TABLE RHNSERVERACTIONPACKAGERESULT MODIFY MODIFIED NOT NULL;

--
-- RHNSERVERACTIONPACKAGERESULT
--
ALTER TABLE RHNSERVERACTIONPACKAGERESULT DROP CONSTRAINT RHN_SAP_RESULT_RC_NN;
ALTER TABLE RHNSERVERACTIONPACKAGERESULT MODIFY RESULT_CODE NOT NULL;

--
-- RHNSERVERACTIONPACKAGERESULT
--
ALTER TABLE RHNSERVERACTIONPACKAGERESULT DROP CONSTRAINT RHN_SAP_RESULT_SID_NN;
ALTER TABLE RHNSERVERACTIONPACKAGERESULT MODIFY SERVER_ID NOT NULL;

--
-- RHNSERVERARCH
--
ALTER TABLE RHNSERVERARCH DROP CONSTRAINT RHN_SARCH_ATID_NN;
ALTER TABLE RHNSERVERARCH MODIFY ARCH_TYPE_ID NOT NULL;

--
-- RHNSERVERARCH
--
ALTER TABLE RHNSERVERARCH DROP CONSTRAINT RHN_SARCH_CREATED_NN;
ALTER TABLE RHNSERVERARCH MODIFY CREATED NOT NULL;

--
-- RHNSERVERARCH
--
ALTER TABLE RHNSERVERARCH DROP CONSTRAINT RHN_SARCH_ID_NN;
ALTER TABLE RHNSERVERARCH MODIFY ID NOT NULL;

--
-- RHNSERVERARCH
--
ALTER TABLE RHNSERVERARCH DROP CONSTRAINT RHN_SARCH_LABEL_NN;
ALTER TABLE RHNSERVERARCH MODIFY LABEL NOT NULL;

--
-- RHNSERVERARCH
--
ALTER TABLE RHNSERVERARCH DROP CONSTRAINT RHN_SARCH_MODIFIED_NN;
ALTER TABLE RHNSERVERARCH MODIFY MODIFIED NOT NULL;

--
-- RHNSERVERARCH
--
ALTER TABLE RHNSERVERARCH DROP CONSTRAINT RHN_SARCH_NAME_NN;
ALTER TABLE RHNSERVERARCH MODIFY NAME NOT NULL;

--
-- RHNSATELLITECERT
--
ALTER TABLE RHNSATELLITECERT DROP CONSTRAINT RHN_SATCERT_CERT_NN;
ALTER TABLE RHNSATELLITECERT MODIFY CERT NOT NULL;

--
-- RHNSATELLITECERT
--
ALTER TABLE RHNSATELLITECERT DROP CONSTRAINT RHN_SATCERT_CREATED_NN;
ALTER TABLE RHNSATELLITECERT MODIFY CREATED NOT NULL;

--
-- RHNSATELLITECERT
--
ALTER TABLE RHNSATELLITECERT DROP CONSTRAINT RHN_SATCERT_LABEL_NN;
ALTER TABLE RHNSATELLITECERT MODIFY LABEL NOT NULL;

--
-- RHNSATELLITECERT
--
ALTER TABLE RHNSATELLITECERT DROP CONSTRAINT RHN_SATCERT_MODIFIED_NN;
ALTER TABLE RHNSATELLITECERT MODIFY MODIFIED NOT NULL;

--
-- RHN_SAT_CLUSTER
--
ALTER TABLE RHN_SAT_CLUSTER DROP CONSTRAINT RHN_SATCL_CUST_ID_NN;
ALTER TABLE RHN_SAT_CLUSTER MODIFY CUSTOMER_ID NOT NULL;

--
-- RHN_SAT_CLUSTER
--
ALTER TABLE RHN_SAT_CLUSTER DROP CONSTRAINT RHN_SATCL_DEPLOYED_NN;
ALTER TABLE RHN_SAT_CLUSTER MODIFY DEPLOYED NOT NULL;

--
-- RHN_SAT_CLUSTER
--
ALTER TABLE RHN_SAT_CLUSTER DROP CONSTRAINT RHN_SATCL_DESC_NN;
ALTER TABLE RHN_SAT_CLUSTER MODIFY DESCRIPTION NOT NULL;

--
-- RHN_SAT_CLUSTER
--
ALTER TABLE RHN_SAT_CLUSTER DROP CONSTRAINT RHN_SATCL_LOCATION_ID_NN;
ALTER TABLE RHN_SAT_CLUSTER MODIFY PHYSICAL_LOCATION_ID NOT NULL;

--
-- RHN_SAT_CLUSTER
--
ALTER TABLE RHN_SAT_CLUSTER DROP CONSTRAINT RHN_SATCL_RECID_NN;
ALTER TABLE RHN_SAT_CLUSTER MODIFY RECID NOT NULL;

--
-- RHN_SAT_CLUSTER
--
ALTER TABLE RHN_SAT_CLUSTER DROP CONSTRAINT RHN_SATCL_TARGET_TYPE_NN;
ALTER TABLE RHN_SAT_CLUSTER MODIFY TARGET_TYPE NOT NULL;

--
-- RHNSATELLITEINFO
--
ALTER TABLE RHNSATELLITEINFO DROP CONSTRAINT RHN_SATELLITE_INFO_CERT_NN;
ALTER TABLE RHNSATELLITEINFO MODIFY CERT NOT NULL;

--
-- RHNSATELLITEINFO
--
ALTER TABLE RHNSATELLITEINFO DROP CONSTRAINT RHN_SATELLITE_INFO_CREATED_NN;
ALTER TABLE RHNSATELLITEINFO MODIFY CREATED NOT NULL;

--
-- RHNSATELLITEINFO
--
ALTER TABLE RHNSATELLITEINFO DROP CONSTRAINT RHN_SATELLITE_INFO_MODIFIED_NN;
ALTER TABLE RHNSATELLITEINFO MODIFY MODIFIED NOT NULL;

--
-- RHNSATELLITEINFO
--
ALTER TABLE RHNSATELLITEINFO DROP CONSTRAINT RHN_SATELLITE_INFO_OWNER_NN;
ALTER TABLE RHNSATELLITEINFO MODIFY OWNER NOT NULL;

--
-- RHNSATELLITEINFO
--
ALTER TABLE RHNSATELLITEINFO DROP CONSTRAINT RHN_SATELLITE_INFO_PRODUCT_NN;
ALTER TABLE RHNSATELLITEINFO MODIFY PRODUCT NOT NULL;

--
-- RHNSATELLITEINFO
--
ALTER TABLE RHNSATELLITEINFO DROP CONSTRAINT RHN_SATELLITE_INFO_SID_NN;
ALTER TABLE RHNSATELLITEINFO MODIFY SERVER_ID NOT NULL;

--
-- RHN_SAT_NODE
--
ALTER TABLE RHN_SAT_NODE DROP CONSTRAINT RHN_SATND_DQ_LOG_LEVEL_NN;
ALTER TABLE RHN_SAT_NODE MODIFY DQ_LOG_LEVEL NOT NULL;

--
-- RHN_SAT_NODE
--
ALTER TABLE RHN_SAT_NODE DROP CONSTRAINT RHN_SATND_MAC_ADDRESS_NN;
ALTER TABLE RHN_SAT_NODE MODIFY MAC_ADDRESS NOT NULL;

--
-- RHN_SAT_NODE
--
ALTER TABLE RHN_SAT_NODE DROP CONSTRAINT RHN_SATND_RECID_NN;
ALTER TABLE RHN_SAT_NODE MODIFY RECID NOT NULL;

--
-- RHN_SAT_NODE
--
ALTER TABLE RHN_SAT_NODE DROP CONSTRAINT RHN_SATND_SAT_CLUSTER_ID_NN;
ALTER TABLE RHN_SAT_NODE MODIFY SAT_CLUSTER_ID NOT NULL;

--
-- RHN_SAT_NODE
--
ALTER TABLE RHN_SAT_NODE DROP CONSTRAINT RHN_SATND_SCHED_LOG_LEVEL_NN;
ALTER TABLE RHN_SAT_NODE MODIFY SCHED_LOG_LEVEL NOT NULL;

--
-- RHN_SAT_NODE
--
ALTER TABLE RHN_SAT_NODE DROP CONSTRAINT RHN_SATND_SPUT_LOG_LEVEL_NN;
ALTER TABLE RHN_SAT_NODE MODIFY SPUT_LOG_LEVEL NOT NULL;

--
-- RHN_SAT_NODE
--
ALTER TABLE RHN_SAT_NODE DROP CONSTRAINT RHN_SATND_SSK_NN;
ALTER TABLE RHN_SAT_NODE MODIFY SCOUT_SHARED_KEY NOT NULL;

--
-- RHN_SAT_NODE
--
ALTER TABLE RHN_SAT_NODE DROP CONSTRAINT RHN_SATND_TARGET_TYPE_NN;
ALTER TABLE RHN_SAT_NODE MODIFY TARGET_TYPE NOT NULL;

--
-- RHNSATELLITESERVERGROUP
--
ALTER TABLE RHNSATELLITESERVERGROUP DROP CONSTRAINT RHN_SATSG_CREAT_NN;
ALTER TABLE RHNSATELLITESERVERGROUP MODIFY CREATED NOT NULL;

--
-- RHNSATELLITESERVERGROUP
--
ALTER TABLE RHNSATELLITESERVERGROUP DROP CONSTRAINT RHN_SATSG_MOD_NN;
ALTER TABLE RHNSATELLITESERVERGROUP MODIFY MODIFIED NOT NULL;

--
-- RHNSATELLITESERVERGROUP
--
ALTER TABLE RHNSATELLITESERVERGROUP DROP CONSTRAINT RHN_SATSG_SGTYPE_NN;
ALTER TABLE RHNSATELLITESERVERGROUP MODIFY SERVER_GROUP_TYPE NOT NULL;

--
-- RHNSATELLITESERVERGROUP
--
ALTER TABLE RHNSATELLITESERVERGROUP DROP CONSTRAINT RHN_SATSG_SID_NN;
ALTER TABLE RHNSATELLITESERVERGROUP MODIFY SERVER_ID NOT NULL;

--
-- RHN_SATELLITE_STATE
--
ALTER TABLE RHN_SATELLITE_STATE DROP CONSTRAINT RHN_SATST_SAT_ID_NN;
ALTER TABLE RHN_SATELLITE_STATE MODIFY SATELLITE_ID NOT NULL;

--
-- RHNSATELLITECHANNELFAMILY
--
ALTER TABLE RHNSATELLITECHANNELFAMILY DROP CONSTRAINT RHN_SAT_CF_CFID_NN;
ALTER TABLE RHNSATELLITECHANNELFAMILY MODIFY CHANNEL_FAMILY_ID NOT NULL;

--
-- RHNSATELLITECHANNELFAMILY
--
ALTER TABLE RHNSATELLITECHANNELFAMILY DROP CONSTRAINT RHN_SAT_CF_CREATED_NN;
ALTER TABLE RHNSATELLITECHANNELFAMILY MODIFY CREATED NOT NULL;

--
-- RHNSATELLITECHANNELFAMILY
--
ALTER TABLE RHNSATELLITECHANNELFAMILY DROP CONSTRAINT RHN_SAT_CF_MODIFIED_NN;
ALTER TABLE RHNSATELLITECHANNELFAMILY MODIFY MODIFIED NOT NULL;

--
-- RHNSATELLITECHANNELFAMILY
--
ALTER TABLE RHNSATELLITECHANNELFAMILY DROP CONSTRAINT RHN_SAT_CF_SID_NN;
ALTER TABLE RHNSATELLITECHANNELFAMILY MODIFY SERVER_ID NOT NULL;

--
-- RHNSAVEDSEARCH
--
ALTER TABLE RHNSAVEDSEARCH DROP CONSTRAINT RHN_SAVEDSEARCH_ID_NN;
ALTER TABLE RHNSAVEDSEARCH MODIFY ID NOT NULL;

--
-- RHNSAVEDSEARCH
--
ALTER TABLE RHNSAVEDSEARCH DROP CONSTRAINT RHN_SAVEDSEARCH_INVERT_NN;
ALTER TABLE RHNSAVEDSEARCH MODIFY INVERT NOT NULL;

--
-- RHNSAVEDSEARCH
--
ALTER TABLE RHNSAVEDSEARCH DROP CONSTRAINT RHN_SAVEDSEARCH_NAME_NN;
ALTER TABLE RHNSAVEDSEARCH MODIFY NAME NOT NULL;

--
-- RHNSAVEDSEARCH
--
ALTER TABLE RHNSAVEDSEARCH DROP CONSTRAINT RHN_SAVEDSEARCH_SFIELD_NN;
ALTER TABLE RHNSAVEDSEARCH MODIFY SEARCH_FIELD NOT NULL;

--
-- RHNSAVEDSEARCH
--
ALTER TABLE RHNSAVEDSEARCH DROP CONSTRAINT RHN_SAVEDSEARCH_SSET_NN;
ALTER TABLE RHNSAVEDSEARCH MODIFY SEARCH_SET NOT NULL;

--
-- RHNSAVEDSEARCH
--
ALTER TABLE RHNSAVEDSEARCH DROP CONSTRAINT RHN_SAVEDSEARCH_SSTRING_NN;
ALTER TABLE RHNSAVEDSEARCH MODIFY SEARCH_STRING NOT NULL;

--
-- RHNSAVEDSEARCH
--
ALTER TABLE RHNSAVEDSEARCH DROP CONSTRAINT RHN_SAVEDSEARCH_TYPE_NN;
ALTER TABLE RHNSAVEDSEARCH MODIFY TYPE NOT NULL;

--
-- RHNSAVEDSEARCH
--
ALTER TABLE RHNSAVEDSEARCH DROP CONSTRAINT RHN_SAVEDSEARCH_WCID_NN;
ALTER TABLE RHNSAVEDSEARCH MODIFY WEB_CONTACT_ID NOT NULL;

--
-- RHNSERVERCUSTOMDATAVALUE
--
ALTER TABLE RHNSERVERCUSTOMDATAVALUE DROP CONSTRAINT RHN_SCDV_CREATED_NN;
ALTER TABLE RHNSERVERCUSTOMDATAVALUE MODIFY CREATED NOT NULL;

--
-- RHNSERVERCUSTOMDATAVALUE
--
ALTER TABLE RHNSERVERCUSTOMDATAVALUE DROP CONSTRAINT RHN_SCDV_KID_NN;
ALTER TABLE RHNSERVERCUSTOMDATAVALUE MODIFY KEY_ID NOT NULL;

--
-- RHNSERVERCUSTOMDATAVALUE
--
ALTER TABLE RHNSERVERCUSTOMDATAVALUE DROP CONSTRAINT RHN_SCDV_MODIFIED_NN;
ALTER TABLE RHNSERVERCUSTOMDATAVALUE MODIFY MODIFIED NOT NULL;

--
-- RHNSERVERCUSTOMDATAVALUE
--
ALTER TABLE RHNSERVERCUSTOMDATAVALUE DROP CONSTRAINT RHN_SCDV_SID_NN;
ALTER TABLE RHNSERVERCUSTOMDATAVALUE MODIFY SERVER_ID NOT NULL;

--
-- RHN_SCHEDULE_DAYS
--
ALTER TABLE RHN_SCHEDULE_DAYS DROP CONSTRAINT RHN_SCHDY_RECID_NN;
ALTER TABLE RHN_SCHEDULE_DAYS MODIFY RECID NOT NULL;

--
-- RHN_SCHEDULES
--
ALTER TABLE RHN_SCHEDULES DROP CONSTRAINT RHN_SCHED_DESC_NN;
ALTER TABLE RHN_SCHEDULES MODIFY DESCRIPTION NOT NULL;

--
-- RHN_SCHEDULES
--
ALTER TABLE RHN_SCHEDULES DROP CONSTRAINT RHN_SCHED_RECID_NN;
ALTER TABLE RHN_SCHEDULES MODIFY RECID NOT NULL;

--
-- RHN_SCHEDULES
--
ALTER TABLE RHN_SCHEDULES DROP CONSTRAINT RHN_SCHED_TYPE_ID_NN;
ALTER TABLE RHN_SCHEDULES MODIFY SCHEDULE_TYPE_ID NOT NULL;

--
-- RHN_SCHEDULE_TYPES
--
ALTER TABLE RHN_SCHEDULE_TYPES DROP CONSTRAINT RHN_SCHTP_RECID_NN;
ALTER TABLE RHN_SCHEDULE_TYPES MODIFY RECID NOT NULL;

--
-- RHN_SCHEDULE_WEEKS
--
ALTER TABLE RHN_SCHEDULE_WEEKS DROP CONSTRAINT RHN_SCHWK_RECID_NN;
ALTER TABLE RHN_SCHEDULE_WEEKS MODIFY RECID NOT NULL;

--
-- RHN_SCHEDULE_WEEKS
--
ALTER TABLE RHN_SCHEDULE_WEEKS DROP CONSTRAINT RHN_SCHWK_SCHED_ID_NN;
ALTER TABLE RHN_SCHEDULE_WEEKS MODIFY SCHEDULE_ID NOT NULL;

--
-- RHN_SAT_CLUSTER_PROBE
--
ALTER TABLE RHN_SAT_CLUSTER_PROBE DROP CONSTRAINT RHN_SCLPB_PROBE_ID_NN;
ALTER TABLE RHN_SAT_CLUSTER_PROBE MODIFY PROBE_ID NOT NULL;

--
-- RHN_SAT_CLUSTER_PROBE
--
ALTER TABLE RHN_SAT_CLUSTER_PROBE DROP CONSTRAINT RHN_SCLPB_PROBE_TYPE_NN;
ALTER TABLE RHN_SAT_CLUSTER_PROBE MODIFY PROBE_TYPE NOT NULL;

--
-- RHN_SAT_CLUSTER_PROBE
--
ALTER TABLE RHN_SAT_CLUSTER_PROBE DROP CONSTRAINT RHN_SCLPB_SAT_CLUSTER_ID_NN;
ALTER TABLE RHN_SAT_CLUSTER_PROBE MODIFY SAT_CLUSTER_ID NOT NULL;

--
-- RHNSERVERCHANNELARCHCOMPAT
--
ALTER TABLE RHNSERVERCHANNELARCHCOMPAT DROP CONSTRAINT RHN_SC_AC_CAID_NN;
ALTER TABLE RHNSERVERCHANNELARCHCOMPAT MODIFY CHANNEL_ARCH_ID NOT NULL;

--
-- RHNSERVERCHANNELARCHCOMPAT
--
ALTER TABLE RHNSERVERCHANNELARCHCOMPAT DROP CONSTRAINT RHN_SC_AC_CREATED_NN;
ALTER TABLE RHNSERVERCHANNELARCHCOMPAT MODIFY CREATED NOT NULL;

--
-- RHNSERVERCHANNELARCHCOMPAT
--
ALTER TABLE RHNSERVERCHANNELARCHCOMPAT DROP CONSTRAINT RHN_SC_AC_MODIFIED_NN;
ALTER TABLE RHNSERVERCHANNELARCHCOMPAT MODIFY MODIFIED NOT NULL;

--
-- RHNSERVERCHANNELARCHCOMPAT
--
ALTER TABLE RHNSERVERCHANNELARCHCOMPAT DROP CONSTRAINT RHN_SC_AC_SAID_NN;
ALTER TABLE RHNSERVERCHANNELARCHCOMPAT MODIFY SERVER_ARCH_ID NOT NULL;

--
-- RHNSERVERCHANNEL
--
ALTER TABLE RHNSERVERCHANNEL DROP CONSTRAINT RHN_SC_CID_NN;
ALTER TABLE RHNSERVERCHANNEL MODIFY CHANNEL_ID NOT NULL;

--
-- RHNSERVERCHANNEL
--
ALTER TABLE RHNSERVERCHANNEL DROP CONSTRAINT RHN_SC_CREATED_NN;
ALTER TABLE RHNSERVERCHANNEL MODIFY CREATED NOT NULL;

--
-- RHNSERVERCHANNEL
--
ALTER TABLE RHNSERVERCHANNEL DROP CONSTRAINT RHN_SC_MODIFIED_NN;
ALTER TABLE RHNSERVERCHANNEL MODIFY MODIFIED NOT NULL;

--
-- RHNSERVERCHANNEL
--
ALTER TABLE RHNSERVERCHANNEL DROP CONSTRAINT RHN_SC_SID_NN;
ALTER TABLE RHNSERVERCHANNEL MODIFY SERVER_ID NOT NULL;

--
-- RHN_SEMANTIC_DATA_TYPE
--
ALTER TABLE RHN_SEMANTIC_DATA_TYPE DROP CONSTRAINT RHN_SDTYP_DESC_NN;
ALTER TABLE RHN_SEMANTIC_DATA_TYPE MODIFY DESCRIPTION NOT NULL;

--
-- RHN_SEMANTIC_DATA_TYPE
--
ALTER TABLE RHN_SEMANTIC_DATA_TYPE DROP CONSTRAINT RHN_SDTYP_NAME_NN;
ALTER TABLE RHN_SEMANTIC_DATA_TYPE MODIFY NAME NOT NULL;

--
-- RHNSNPSERVERQUEUE
--
ALTER TABLE RHNSNPSERVERQUEUE DROP CONSTRAINT RHN_SEC_NP_PROCESSED_NN;
ALTER TABLE RHNSNPSERVERQUEUE MODIFY PROCESSED NOT NULL;

--
-- RHNSNPSERVERQUEUE
--
ALTER TABLE RHNSNPSERVERQUEUE DROP CONSTRAINT RHN_SEC_NP_SID_NN;
ALTER TABLE RHNSNPSERVERQUEUE MODIFY SERVER_ID NOT NULL;

--
-- RHNSERVERACTIONSCRIPTRESULT
--
ALTER TABLE RHNSERVERACTIONSCRIPTRESULT DROP CONSTRAINT RHN_SERVERAS_RESULT_ASID_NN;
ALTER TABLE RHNSERVERACTIONSCRIPTRESULT MODIFY ACTION_SCRIPT_ID NOT NULL;

--
-- RHNSERVERACTIONSCRIPTRESULT
--
ALTER TABLE RHNSERVERACTIONSCRIPTRESULT DROP CONSTRAINT RHN_SERVERAS_RESULT_CREAT_NN;
ALTER TABLE RHNSERVERACTIONSCRIPTRESULT MODIFY CREATED NOT NULL;

--
-- RHNSERVERACTIONSCRIPTRESULT
--
ALTER TABLE RHNSERVERACTIONSCRIPTRESULT DROP CONSTRAINT RHN_SERVERAS_RESULT_MOD_NN;
ALTER TABLE RHNSERVERACTIONSCRIPTRESULT MODIFY MODIFIED NOT NULL;

--
-- RHNSERVERACTIONSCRIPTRESULT
--
ALTER TABLE RHNSERVERACTIONSCRIPTRESULT DROP CONSTRAINT RHN_SERVERAS_RESULT_RETURN_NN;
ALTER TABLE RHNSERVERACTIONSCRIPTRESULT MODIFY RETURN_CODE NOT NULL;

--
-- RHNSERVERACTIONSCRIPTRESULT
--
ALTER TABLE RHNSERVERACTIONSCRIPTRESULT DROP CONSTRAINT RHN_SERVERAS_RESULT_SID_NN;
ALTER TABLE RHNSERVERACTIONSCRIPTRESULT MODIFY SERVER_ID NOT NULL;

--
-- RHNSERVERACTIONSCRIPTRESULT
--
ALTER TABLE RHNSERVERACTIONSCRIPTRESULT DROP CONSTRAINT RHN_SERVERAS_RESULT_START_NN;
ALTER TABLE RHNSERVERACTIONSCRIPTRESULT MODIFY START_DATE NOT NULL;

--
-- RHNSERVERACTIONSCRIPTRESULT
--
ALTER TABLE RHNSERVERACTIONSCRIPTRESULT DROP CONSTRAINT RHN_SERVERAS_RESULT_STOP_NN;
ALTER TABLE RHNSERVERACTIONSCRIPTRESULT MODIFY STOP_DATE NOT NULL;

--
-- RHNSERVERCONFIGCHANNEL
--
ALTER TABLE RHNSERVERCONFIGCHANNEL DROP CONSTRAINT RHN_SERVERCC_CCID_NN;
ALTER TABLE RHNSERVERCONFIGCHANNEL MODIFY CONFIG_CHANNEL_ID NOT NULL;

--
-- RHNSERVERCONFIGCHANNEL
--
ALTER TABLE RHNSERVERCONFIGCHANNEL DROP CONSTRAINT RHN_SERVERCC_CREAT_NN;
ALTER TABLE RHNSERVERCONFIGCHANNEL MODIFY CREATED NOT NULL;

--
-- RHNSERVERCONFIGCHANNEL
--
ALTER TABLE RHNSERVERCONFIGCHANNEL DROP CONSTRAINT RHN_SERVERCC_MOD_NN;
ALTER TABLE RHNSERVERCONFIGCHANNEL MODIFY MODIFIED NOT NULL;

--
-- RHNSERVERCONFIGCHANNEL
--
ALTER TABLE RHNSERVERCONFIGCHANNEL DROP CONSTRAINT RHN_SERVERCC_SID_NN;
ALTER TABLE RHNSERVERCONFIGCHANNEL MODIFY SERVER_ID NOT NULL;

--
-- RHNSERVERGROUPTYPE
--
ALTER TABLE RHNSERVERGROUPTYPE DROP CONSTRAINT RHN_SERVERGROUPTYPE_CREATED_NN;
ALTER TABLE RHNSERVERGROUPTYPE MODIFY CREATED NOT NULL;

--
-- RHNSERVERGROUPTYPE
--
ALTER TABLE RHNSERVERGROUPTYPE DROP CONSTRAINT RHN_SERVERGROUPTYPE_ID_NN;
ALTER TABLE RHNSERVERGROUPTYPE MODIFY ID NOT NULL;

--
-- RHNSERVERGROUPTYPE
--
ALTER TABLE RHNSERVERGROUPTYPE DROP CONSTRAINT RHN_SERVERGROUPTYPE_ISBASE_NN;
ALTER TABLE RHNSERVERGROUPTYPE MODIFY IS_BASE NOT NULL;

--
-- RHNSERVERGROUPTYPE
--
ALTER TABLE RHNSERVERGROUPTYPE DROP CONSTRAINT RHN_SERVERGROUPTYPE_LABEL_NN;
ALTER TABLE RHNSERVERGROUPTYPE MODIFY LABEL NOT NULL;

--
-- RHNSERVERGROUPTYPE
--
ALTER TABLE RHNSERVERGROUPTYPE DROP CONSTRAINT RHN_SERVERGROUPTYPE_MOD_NN;
ALTER TABLE RHNSERVERGROUPTYPE MODIFY MODIFIED NOT NULL;

--
-- RHNSERVERGROUPTYPE
--
ALTER TABLE RHNSERVERGROUPTYPE DROP CONSTRAINT RHN_SERVERGROUPTYPE_NAME_NN;
ALTER TABLE RHNSERVERGROUPTYPE MODIFY NAME NOT NULL;

--
-- RHNSERVERGROUPTYPE
--
ALTER TABLE RHNSERVERGROUPTYPE DROP CONSTRAINT RHN_SERVERGROUPTYPE_PERM_NN;
ALTER TABLE RHNSERVERGROUPTYPE MODIFY PERMANENT NOT NULL;

--
-- RHNSERVERGROUP
--
ALTER TABLE RHNSERVERGROUP DROP CONSTRAINT RHN_SERVERGROUP_CREATED_NN;
ALTER TABLE RHNSERVERGROUP MODIFY CREATED NOT NULL;

--
-- RHNSERVERGROUP
--
ALTER TABLE RHNSERVERGROUP DROP CONSTRAINT RHN_SERVERGROUP_CURMEMBERS_NN;
ALTER TABLE RHNSERVERGROUP MODIFY CURRENT_MEMBERS NOT NULL;

--
-- RHNSERVERGROUP
--
ALTER TABLE RHNSERVERGROUP DROP CONSTRAINT RHN_SERVERGROUP_DESC_NN;
ALTER TABLE RHNSERVERGROUP MODIFY DESCRIPTION NOT NULL;

--
-- RHNSERVERGROUP
--
ALTER TABLE RHNSERVERGROUP DROP CONSTRAINT RHN_SERVERGROUP_ID_NN;
ALTER TABLE RHNSERVERGROUP MODIFY ID NOT NULL;

--
-- RHNSERVERGROUP
--
ALTER TABLE RHNSERVERGROUP DROP CONSTRAINT RHN_SERVERGROUP_MODIFIED_NN;
ALTER TABLE RHNSERVERGROUP MODIFY MODIFIED NOT NULL;

--
-- RHNSERVERGROUP
--
ALTER TABLE RHNSERVERGROUP DROP CONSTRAINT RHN_SERVERGROUP_NAME_NN;
ALTER TABLE RHNSERVERGROUP MODIFY NAME NOT NULL;

--
-- RHNSERVERGROUP
--
ALTER TABLE RHNSERVERGROUP DROP CONSTRAINT RHN_SERVERGROUP_OID_NN;
ALTER TABLE RHNSERVERGROUP MODIFY ORG_ID NOT NULL;

--
-- RHNSERVERGROUPNOTES
--
ALTER TABLE RHNSERVERGROUPNOTES DROP CONSTRAINT RHN_SERVERGRP_NOTE_CREATED_NN;
ALTER TABLE RHNSERVERGROUPNOTES MODIFY CREATED NOT NULL;

--
-- RHNSERVERGROUPNOTES
--
ALTER TABLE RHNSERVERGROUPNOTES DROP CONSTRAINT RHN_SERVERGRP_NOTE_ID_NN;
ALTER TABLE RHNSERVERGROUPNOTES MODIFY ID NOT NULL;

--
-- RHNSERVERGROUPNOTES
--
ALTER TABLE RHNSERVERGROUPNOTES DROP CONSTRAINT RHN_SERVERGRP_NOTE_MODIFIED_NN;
ALTER TABLE RHNSERVERGROUPNOTES MODIFY MODIFIED NOT NULL;

--
-- RHNSERVERGROUPNOTES
--
ALTER TABLE RHNSERVERGROUPNOTES DROP CONSTRAINT RHN_SERVERGRP_NOTE_NN;
ALTER TABLE RHNSERVERGROUPNOTES MODIFY SERVER_GROUP_ID NOT NULL;

--
-- RHNSERVERGROUPNOTES
--
ALTER TABLE RHNSERVERGROUPNOTES DROP CONSTRAINT RHN_SERVERGRP_NOTE_NOTE_NN;
ALTER TABLE RHNSERVERGROUPNOTES MODIFY NOTE NOT NULL;

--
-- RHNSERVERGROUPNOTES
--
ALTER TABLE RHNSERVERGROUPNOTES DROP CONSTRAINT RHN_SERVERGRP_NOTE_SUBJECT_NN;
ALTER TABLE RHNSERVERGROUPNOTES MODIFY SUBJECT NOT NULL;

--
-- RHNSERVERHISTORY
--
ALTER TABLE RHNSERVERHISTORY DROP CONSTRAINT RHN_SERVERHISTORY_CREATED_NN;
ALTER TABLE RHNSERVERHISTORY MODIFY CREATED NOT NULL;

--
-- RHNSERVERHISTORY
--
ALTER TABLE RHNSERVERHISTORY DROP CONSTRAINT RHN_SERVERHISTORY_ID_NN;
ALTER TABLE RHNSERVERHISTORY MODIFY ID NOT NULL;

--
-- RHNSERVERHISTORY
--
ALTER TABLE RHNSERVERHISTORY DROP CONSTRAINT RHN_SERVERHISTORY_MODIFIED_NN;
ALTER TABLE RHNSERVERHISTORY MODIFY MODIFIED NOT NULL;

--
-- RHNSERVERHISTORY
--
ALTER TABLE RHNSERVERHISTORY DROP CONSTRAINT RHN_SERVERHISTORY_SID_NN;
ALTER TABLE RHNSERVERHISTORY MODIFY SERVER_ID NOT NULL;

--
-- RHNSERVERHISTORY
--
ALTER TABLE RHNSERVERHISTORY DROP CONSTRAINT RHN_SERVERHISTORY_SUMMARY_NN;
ALTER TABLE RHNSERVERHISTORY MODIFY SUMMARY NOT NULL;

--
-- RHNSERVERLOCATION
--
ALTER TABLE RHNSERVERLOCATION DROP CONSTRAINT RHN_SERVERLOCATION_CREATED_NN;
ALTER TABLE RHNSERVERLOCATION MODIFY CREATED NOT NULL;

--
-- RHNSERVERLOCATION
--
ALTER TABLE RHNSERVERLOCATION DROP CONSTRAINT RHN_SERVERLOCATION_ID_NN;
ALTER TABLE RHNSERVERLOCATION MODIFY ID NOT NULL;

--
-- RHNSERVERLOCATION
--
ALTER TABLE RHNSERVERLOCATION DROP CONSTRAINT RHN_SERVERLOCATION_MODIFIED_NN;
ALTER TABLE RHNSERVERLOCATION MODIFY MODIFIED NOT NULL;

--
-- RHNSERVERLOCATION
--
ALTER TABLE RHNSERVERLOCATION DROP CONSTRAINT RHN_SERVERLOCATION_SID_NN;
ALTER TABLE RHNSERVERLOCATION MODIFY SERVER_ID NOT NULL;

--
-- RHNSERVERNETWORK
--
ALTER TABLE RHNSERVERNETWORK DROP CONSTRAINT RHN_SERVERNETWORK_CREATED_NN;
ALTER TABLE RHNSERVERNETWORK MODIFY CREATED NOT NULL;

--
-- RHNSERVERNETWORK
--
ALTER TABLE RHNSERVERNETWORK DROP CONSTRAINT RHN_SERVERNETWORK_ID_NN;
ALTER TABLE RHNSERVERNETWORK MODIFY ID NOT NULL;

--
-- RHNSERVERNETWORK
--
ALTER TABLE RHNSERVERNETWORK DROP CONSTRAINT RHN_SERVERNETWORK_MODIFIED_NN;
ALTER TABLE RHNSERVERNETWORK MODIFY MODIFIED NOT NULL;

--
-- RHNSERVERNETWORK
--
ALTER TABLE RHNSERVERNETWORK DROP CONSTRAINT RHN_SERVERNETWORK_SID_NN;
ALTER TABLE RHNSERVERNETWORK MODIFY SERVER_ID NOT NULL;

--
-- RHNSERVERNOTES
--
ALTER TABLE RHNSERVERNOTES DROP CONSTRAINT RHN_SERVERNOTES_CREATED_NN;
ALTER TABLE RHNSERVERNOTES MODIFY CREATED NOT NULL;

--
-- RHNSERVERNOTES
--
ALTER TABLE RHNSERVERNOTES DROP CONSTRAINT RHN_SERVERNOTES_ID_NN;
ALTER TABLE RHNSERVERNOTES MODIFY ID NOT NULL;

--
-- RHNSERVERNOTES
--
ALTER TABLE RHNSERVERNOTES DROP CONSTRAINT RHN_SERVERNOTES_MODIFIED_NN;
ALTER TABLE RHNSERVERNOTES MODIFY MODIFIED NOT NULL;

--
-- RHNSERVERNOTES
--
ALTER TABLE RHNSERVERNOTES DROP CONSTRAINT RHN_SERVERNOTES_SID_NN;
ALTER TABLE RHNSERVERNOTES MODIFY SERVER_ID NOT NULL;

--
-- RHNSERVERNOTES
--
ALTER TABLE RHNSERVERNOTES DROP CONSTRAINT RHN_SERVERNOTES_SUBJECT_NN;
ALTER TABLE RHNSERVERNOTES MODIFY SUBJECT NOT NULL;

--
-- RHNSERVERPACKAGE
--
ALTER TABLE RHNSERVERPACKAGE DROP CONSTRAINT RHN_SERVERPACKAGE_EID_NN;
ALTER TABLE RHNSERVERPACKAGE MODIFY EVR_ID NOT NULL;

--
-- RHNSERVERPACKAGE
--
ALTER TABLE RHNSERVERPACKAGE DROP CONSTRAINT RHN_SERVERPACKAGE_NID_NN;
ALTER TABLE RHNSERVERPACKAGE MODIFY NAME_ID NOT NULL;

--
-- RHNSERVERPACKAGE
--
ALTER TABLE RHNSERVERPACKAGE DROP CONSTRAINT RHN_SERVERPACKAGE_SID_NN;
ALTER TABLE RHNSERVERPACKAGE MODIFY SERVER_ID NOT NULL;

--
-- RHNSERVERPATH
--
ALTER TABLE RHNSERVERPATH DROP CONSTRAINT RHN_SERVERPATH_CREAT_NN;
ALTER TABLE RHNSERVERPATH MODIFY CREATED NOT NULL;

--
-- RHNSERVERPATH
--
ALTER TABLE RHNSERVERPATH DROP CONSTRAINT RHN_SERVERPATH_HOSTNAME_NN;
ALTER TABLE RHNSERVERPATH MODIFY HOSTNAME NOT NULL;

--
-- RHNSERVERPATH
--
ALTER TABLE RHNSERVERPATH DROP CONSTRAINT RHN_SERVERPATH_MOD_NN;
ALTER TABLE RHNSERVERPATH MODIFY MODIFIED NOT NULL;

--
-- RHNSERVERPATH
--
ALTER TABLE RHNSERVERPATH DROP CONSTRAINT RHN_SERVERPATH_POS_NN;
ALTER TABLE RHNSERVERPATH MODIFY POSITION NOT NULL;

--
-- RHNSERVERPATH
--
ALTER TABLE RHNSERVERPATH DROP CONSTRAINT RHN_SERVERPATH_PSID_NN;
ALTER TABLE RHNSERVERPATH MODIFY PROXY_SERVER_ID NOT NULL;

--
-- RHNSERVERPATH
--
ALTER TABLE RHNSERVERPATH DROP CONSTRAINT RHN_SERVERPATH_SID_NN;
ALTER TABLE RHNSERVERPATH MODIFY SERVER_ID NOT NULL;

--
-- RHNSERVERPRESERVEFILELIST
--
ALTER TABLE RHNSERVERPRESERVEFILELIST DROP CONSTRAINT RHN_SERVERPFL_CREAT_NN;
ALTER TABLE RHNSERVERPRESERVEFILELIST MODIFY CREATED NOT NULL;

--
-- RHNSERVERPRESERVEFILELIST
--
ALTER TABLE RHNSERVERPRESERVEFILELIST DROP CONSTRAINT RHN_SERVERPFL_FLID_NN;
ALTER TABLE RHNSERVERPRESERVEFILELIST MODIFY FILE_LIST_ID NOT NULL;

--
-- RHNSERVERPRESERVEFILELIST
--
ALTER TABLE RHNSERVERPRESERVEFILELIST DROP CONSTRAINT RHN_SERVERPFL_KSID_NN;
ALTER TABLE RHNSERVERPRESERVEFILELIST MODIFY SERVER_ID NOT NULL;

--
-- RHNSERVERPRESERVEFILELIST
--
ALTER TABLE RHNSERVERPRESERVEFILELIST DROP CONSTRAINT RHN_SERVERPFL_MOD_NN;
ALTER TABLE RHNSERVERPRESERVEFILELIST MODIFY MODIFIED NOT NULL;

--
-- RHNSERVERACTION
--
ALTER TABLE RHNSERVERACTION DROP CONSTRAINT RHN_SERVER_ACTION_AID_NN;
ALTER TABLE RHNSERVERACTION MODIFY ACTION_ID NOT NULL;

--
-- RHNSERVERACTION
--
ALTER TABLE RHNSERVERACTION DROP CONSTRAINT RHN_SERVER_ACTION_CREATED_NN;
ALTER TABLE RHNSERVERACTION MODIFY CREATED NOT NULL;

--
-- RHNSERVERACTION
--
ALTER TABLE RHNSERVERACTION DROP CONSTRAINT RHN_SERVER_ACTION_MODIFIED_NN;
ALTER TABLE RHNSERVERACTION MODIFY MODIFIED NOT NULL;

--
-- RHNSERVERACTION
--
ALTER TABLE RHNSERVERACTION DROP CONSTRAINT RHN_SERVER_ACTION_REMAINING_NN;
ALTER TABLE RHNSERVERACTION MODIFY REMAINING_TRIES NOT NULL;

--
-- RHNSERVERACTION
--
ALTER TABLE RHNSERVERACTION DROP CONSTRAINT RHN_SERVER_ACTION_SID_NN;
ALTER TABLE RHNSERVERACTION MODIFY SERVER_ID NOT NULL;

--
-- RHNSERVERACTION
--
ALTER TABLE RHNSERVERACTION DROP CONSTRAINT RHN_SERVER_ACTION_STATUS_NN;
ALTER TABLE RHNSERVERACTION MODIFY STATUS NOT NULL;

--
-- RHNSERVER
--
ALTER TABLE RHNSERVER DROP CONSTRAINT RHN_SERVER_AUTO_DELIVER_NN;
ALTER TABLE RHNSERVER MODIFY AUTO_DELIVER NOT NULL;

--
-- RHNSERVER
--
ALTER TABLE RHNSERVER DROP CONSTRAINT RHN_SERVER_AUTO_UPDATE_NN;
ALTER TABLE RHNSERVER MODIFY AUTO_UPDATE NOT NULL;

--
-- RHNSERVERCACHEINFO
--
ALTER TABLE RHNSERVERCACHEINFO DROP CONSTRAINT RHN_SERVER_CACHE_INFO_SID_NN;
ALTER TABLE RHNSERVERCACHEINFO MODIFY SERVER_ID NOT NULL;

--
-- RHNSERVER
--
ALTER TABLE RHNSERVER DROP CONSTRAINT RHN_SERVER_CREATED_NN;
ALTER TABLE RHNSERVER MODIFY CREATED NOT NULL;

--
-- RHNSERVERDMI
--
ALTER TABLE RHNSERVERDMI DROP CONSTRAINT RHN_SERVER_DMI_CREATED_NN;
ALTER TABLE RHNSERVERDMI MODIFY CREATED NOT NULL;

--
-- RHNSERVERDMI
--
ALTER TABLE RHNSERVERDMI DROP CONSTRAINT RHN_SERVER_DMI_ID_NN;
ALTER TABLE RHNSERVERDMI MODIFY ID NOT NULL;

--
-- RHNSERVERDMI
--
ALTER TABLE RHNSERVERDMI DROP CONSTRAINT RHN_SERVER_DMI_MODIFIED_NN;
ALTER TABLE RHNSERVERDMI MODIFY MODIFIED NOT NULL;

--
-- RHNSERVERDMI
--
ALTER TABLE RHNSERVERDMI DROP CONSTRAINT RHN_SERVER_DMI_SID_NN;
ALTER TABLE RHNSERVERDMI MODIFY SERVER_ID NOT NULL;

--
-- RHNSERVER
--
ALTER TABLE RHNSERVER DROP CONSTRAINT RHN_SERVER_DSI_NN;
ALTER TABLE RHNSERVER MODIFY DIGITAL_SERVER_ID NOT NULL;

--
-- RHNSERVER
--
ALTER TABLE RHNSERVER DROP CONSTRAINT RHN_SERVER_ID_NN;
ALTER TABLE RHNSERVER MODIFY ID NOT NULL;

--
-- RHNSERVERINFO
--
ALTER TABLE RHNSERVERINFO DROP CONSTRAINT RHN_SERVER_INFO_SID_NN;
ALTER TABLE RHNSERVERINFO MODIFY SERVER_ID NOT NULL;

--
-- RHNSERVERINSTALLINFO
--
ALTER TABLE RHNSERVERINSTALLINFO DROP CONSTRAINT RHN_SERVER_INSTALL_INFO_CR_NN;
ALTER TABLE RHNSERVERINSTALLINFO MODIFY CREATED NOT NULL;

--
-- RHNSERVERINSTALLINFO
--
ALTER TABLE RHNSERVERINSTALLINFO DROP CONSTRAINT RHN_SERVER_INSTALL_INFO_ID_NN;
ALTER TABLE RHNSERVERINSTALLINFO MODIFY ID NOT NULL;

--
-- RHNSERVERINSTALLINFO
--
ALTER TABLE RHNSERVERINSTALLINFO DROP CONSTRAINT RHN_SERVER_INSTALL_INFO_IM_NN;
ALTER TABLE RHNSERVERINSTALLINFO MODIFY INSTALL_METHOD NOT NULL;

--
-- RHNSERVERINSTALLINFO
--
ALTER TABLE RHNSERVERINSTALLINFO DROP CONSTRAINT RHN_SERVER_INSTALL_INFO_MD_NN;
ALTER TABLE RHNSERVERINSTALLINFO MODIFY MODIFIED NOT NULL;

--
-- RHNSERVERINSTALLINFO
--
ALTER TABLE RHNSERVERINSTALLINFO DROP CONSTRAINT RHN_SERVER_INSTALL_INFO_SID_NN;
ALTER TABLE RHNSERVERINSTALLINFO MODIFY SERVER_ID NOT NULL;

--
-- RHNSERVER
--
ALTER TABLE RHNSERVER DROP CONSTRAINT RHN_SERVER_LB_NN;
ALTER TABLE RHNSERVER MODIFY LAST_BOOT NOT NULL;

--
-- RHNSERVERLOCK
--
ALTER TABLE RHNSERVERLOCK DROP CONSTRAINT RHN_SERVER_LOCK_CREATED_NN;
ALTER TABLE RHNSERVERLOCK MODIFY CREATED NOT NULL;

--
-- RHNSERVERLOCK
--
ALTER TABLE RHNSERVERLOCK DROP CONSTRAINT RHN_SERVER_LOCK_SID_NN;
ALTER TABLE RHNSERVERLOCK MODIFY SERVER_ID NOT NULL;

--
-- RHNSERVER
--
ALTER TABLE RHNSERVER DROP CONSTRAINT RHN_SERVER_MODIFIED_NN;
ALTER TABLE RHNSERVER MODIFY MODIFIED NOT NULL;

--
-- RHNSERVER
--
ALTER TABLE RHNSERVER DROP CONSTRAINT RHN_SERVER_OID_NN;
ALTER TABLE RHNSERVER MODIFY ORG_ID NOT NULL;

--
-- RHNSERVER
--
ALTER TABLE RHNSERVER DROP CONSTRAINT RHN_SERVER_OS_NN;
ALTER TABLE RHNSERVER MODIFY OS NOT NULL;

--
-- RHNSERVERPROFILE
--
ALTER TABLE RHNSERVERPROFILE DROP CONSTRAINT RHN_SERVER_PROFILE_BCID_NN;
ALTER TABLE RHNSERVERPROFILE MODIFY BASE_CHANNEL NOT NULL;

--
-- RHNSERVERPROFILE
--
ALTER TABLE RHNSERVERPROFILE DROP CONSTRAINT RHN_SERVER_PROFILE_CREATED_NN;
ALTER TABLE RHNSERVERPROFILE MODIFY CREATED NOT NULL;

--
-- RHNSERVERPROFILE
--
ALTER TABLE RHNSERVERPROFILE DROP CONSTRAINT RHN_SERVER_PROFILE_ID_NN;
ALTER TABLE RHNSERVERPROFILE MODIFY ID NOT NULL;

--
-- RHNSERVERPROFILE
--
ALTER TABLE RHNSERVERPROFILE DROP CONSTRAINT RHN_SERVER_PROFILE_MODIFIED_NN;
ALTER TABLE RHNSERVERPROFILE MODIFY MODIFIED NOT NULL;

--
-- RHNSERVERPROFILE
--
ALTER TABLE RHNSERVERPROFILE DROP CONSTRAINT RHN_SERVER_PROFILE_OID_NN;
ALTER TABLE RHNSERVERPROFILE MODIFY ORG_ID NOT NULL;

--
-- RHNSERVERPROFILE
--
ALTER TABLE RHNSERVERPROFILE DROP CONSTRAINT RHN_SERVER_PROFILE_PTYPE_NN;
ALTER TABLE RHNSERVERPROFILE MODIFY PROFILE_TYPE_ID NOT NULL;

--
-- RHNSERVER
--
ALTER TABLE RHNSERVER DROP CONSTRAINT RHN_SERVER_RELEASE_NN;
ALTER TABLE RHNSERVER MODIFY RELEASE NOT NULL;

--
-- RHNSERVER
--
ALTER TABLE RHNSERVER DROP CONSTRAINT RHN_SERVER_SAID_NN;
ALTER TABLE RHNSERVER MODIFY SERVER_ARCH_ID NOT NULL;

--
-- RHNSERVER
--
ALTER TABLE RHNSERVER DROP CONSTRAINT RHN_SERVER_SECRET_NN;
ALTER TABLE RHNSERVER MODIFY SECRET NOT NULL;

--
-- RHNSERVERUUID
--
ALTER TABLE RHNSERVERUUID DROP CONSTRAINT RHN_SERVER_UUID_SID_NN;
ALTER TABLE RHNSERVERUUID MODIFY SERVER_ID NOT NULL;

--
-- RHNSERVERUUID
--
ALTER TABLE RHNSERVERUUID DROP CONSTRAINT RHN_SERVER_UUID_UUID_NN;
ALTER TABLE RHNSERVERUUID MODIFY UUID NOT NULL;

--
-- RHNSET
--
ALTER TABLE RHNSET DROP CONSTRAINT RHN_SET_ELEM_NN;
ALTER TABLE RHNSET MODIFY "ELEMENT" NOT NULL;

--
-- RHNSET
--
ALTER TABLE RHNSET DROP CONSTRAINT RHN_SET_LABEL_NN;
ALTER TABLE RHNSET MODIFY LABEL NOT NULL;

--
-- RHNSET
--
ALTER TABLE RHNSET DROP CONSTRAINT RHN_SET_USER_NN;
ALTER TABLE RHNSET MODIFY USER_ID NOT NULL;

--
-- RHNSERVEREVENT
--
ALTER TABLE RHNSERVEREVENT DROP CONSTRAINT RHN_SE_CREATED_NN;
ALTER TABLE RHNSERVEREVENT MODIFY CREATED NOT NULL;

--
-- RHNSERVEREVENT
--
ALTER TABLE RHNSERVEREVENT DROP CONSTRAINT RHN_SE_DETAILS_NN;
ALTER TABLE RHNSERVEREVENT MODIFY DETAILS NOT NULL;

--
-- RHNSERVEREVENT
--
ALTER TABLE RHNSERVEREVENT DROP CONSTRAINT RHN_SE_ID_NN;
ALTER TABLE RHNSERVEREVENT MODIFY ID NOT NULL;

--
-- RHNSERVEREVENT
--
ALTER TABLE RHNSERVEREVENT DROP CONSTRAINT RHN_SE_MODIFIED_NN;
ALTER TABLE RHNSERVEREVENT MODIFY MODIFIED NOT NULL;

--
-- RHNSERVEREVENT
--
ALTER TABLE RHNSERVEREVENT DROP CONSTRAINT RHN_SE_SERVER_ID_NN;
ALTER TABLE RHNSERVEREVENT MODIFY SERVER_ID NOT NULL;

--
-- RHNSGTYPEVIRTSUBLEVEL
--
ALTER TABLE RHNSGTYPEVIRTSUBLEVEL DROP CONSTRAINT RHN_SGTVSL_CREATED_NN;
ALTER TABLE RHNSGTYPEVIRTSUBLEVEL MODIFY CREATED NOT NULL;

--
-- RHNSGTYPEVIRTSUBLEVEL
--
ALTER TABLE RHNSGTYPEVIRTSUBLEVEL DROP CONSTRAINT RHN_SGTVSL_MODIFIED_NN;
ALTER TABLE RHNSGTYPEVIRTSUBLEVEL MODIFY MODIFIED NOT NULL;

--
-- RHNSGTYPEVIRTSUBLEVEL
--
ALTER TABLE RHNSGTYPEVIRTSUBLEVEL DROP CONSTRAINT RHN_SGTVSL_SGTID_NN;
ALTER TABLE RHNSGTYPEVIRTSUBLEVEL MODIFY SERVER_GROUP_TYPE_ID NOT NULL;

--
-- RHNSGTYPEVIRTSUBLEVEL
--
ALTER TABLE RHNSGTYPEVIRTSUBLEVEL DROP CONSTRAINT RHN_SGTVSL_VSLID_NN;
ALTER TABLE RHNSGTYPEVIRTSUBLEVEL MODIFY VIRT_SUB_LEVEL_ID NOT NULL;

--
-- RHNSGTYPEBASEADDONCOMPAT
--
ALTER TABLE RHNSGTYPEBASEADDONCOMPAT DROP CONSTRAINT RHN_SGT_BAC_AID_NN;
ALTER TABLE RHNSGTYPEBASEADDONCOMPAT MODIFY ADDON_ID NOT NULL;

--
-- RHNSGTYPEBASEADDONCOMPAT
--
ALTER TABLE RHNSGTYPEBASEADDONCOMPAT DROP CONSTRAINT RHN_SGT_BAC_BID_NN;
ALTER TABLE RHNSGTYPEBASEADDONCOMPAT MODIFY BASE_ID NOT NULL;

--
-- RHNSERVERGROUPTYPEFEATURE
--
ALTER TABLE RHNSERVERGROUPTYPEFEATURE DROP CONSTRAINT RHN_SGT_FEAT_CREATED_NN;
ALTER TABLE RHNSERVERGROUPTYPEFEATURE MODIFY CREATED NOT NULL;

--
-- RHNSERVERGROUPTYPEFEATURE
--
ALTER TABLE RHNSERVERGROUPTYPEFEATURE DROP CONSTRAINT RHN_SGT_FEAT_MOD_NN;
ALTER TABLE RHNSERVERGROUPTYPEFEATURE MODIFY MODIFIED NOT NULL;

--
-- RHNSERVERGROUPTYPEFEATURE
--
ALTER TABLE RHNSERVERGROUPTYPEFEATURE DROP CONSTRAINT RHN_SGT_FID_NN;
ALTER TABLE RHNSERVERGROUPTYPEFEATURE MODIFY FEATURE_ID NOT NULL;

--
-- RHNSERVERGROUPTYPEFEATURE
--
ALTER TABLE RHNSERVERGROUPTYPEFEATURE DROP CONSTRAINT RHN_SGT_SGTID_NN;
ALTER TABLE RHNSERVERGROUPTYPEFEATURE MODIFY SERVER_GROUP_TYPE_ID NOT NULL;

--
-- RHNSERVERGROUPMEMBERS
--
ALTER TABLE RHNSERVERGROUPMEMBERS DROP CONSTRAINT RHN_SG_GROUP_NN;
ALTER TABLE RHNSERVERGROUPMEMBERS MODIFY SERVER_GROUP_ID NOT NULL;

--
-- RHNSERVERGROUPMEMBERS
--
ALTER TABLE RHNSERVERGROUPMEMBERS DROP CONSTRAINT RHN_SG_MEMBERS_NN;
ALTER TABLE RHNSERVERGROUPMEMBERS MODIFY SERVER_ID NOT NULL;

--
-- RHNSERVERGROUPMEMBERS
--
ALTER TABLE RHNSERVERGROUPMEMBERS DROP CONSTRAINT RHN_SG_MEMBER_CRE_NN;
ALTER TABLE RHNSERVERGROUPMEMBERS MODIFY CREATED NOT NULL;

--
-- RHNSERVERGROUPMEMBERS
--
ALTER TABLE RHNSERVERGROUPMEMBERS DROP CONSTRAINT RHN_SG_MEMBER_MOD_NN;
ALTER TABLE RHNSERVERGROUPMEMBERS MODIFY MODIFIED NOT NULL;

--
-- RHNSERVERMESSAGE
--
ALTER TABLE RHNSERVERMESSAGE DROP CONSTRAINT RHN_SM_CREATED_NN;
ALTER TABLE RHNSERVERMESSAGE MODIFY CREATED NOT NULL;

--
-- RHNSERVERMESSAGE
--
ALTER TABLE RHNSERVERMESSAGE DROP CONSTRAINT RHN_SM_MESSAGE_ID_NN;
ALTER TABLE RHNSERVERMESSAGE MODIFY MESSAGE_ID NOT NULL;

--
-- RHNSERVERMESSAGE
--
ALTER TABLE RHNSERVERMESSAGE DROP CONSTRAINT RHN_SM_MODIFIED_NN;
ALTER TABLE RHNSERVERMESSAGE MODIFY MODIFIED NOT NULL;

--
-- RHNSERVERMESSAGE
--
ALTER TABLE RHNSERVERMESSAGE DROP CONSTRAINT RHN_SM_SERVER_ID_NN;
ALTER TABLE RHNSERVERMESSAGE MODIFY SERVER_ID NOT NULL;

--
-- RHNSNAPSHOTCHANNEL
--
ALTER TABLE RHNSNAPSHOTCHANNEL DROP CONSTRAINT RHN_SNAPCHAN_CID_NN;
ALTER TABLE RHNSNAPSHOTCHANNEL MODIFY CHANNEL_ID NOT NULL;

--
-- RHNSNAPSHOTCHANNEL
--
ALTER TABLE RHNSNAPSHOTCHANNEL DROP CONSTRAINT RHN_SNAPCHAN_SID_NN;
ALTER TABLE RHNSNAPSHOTCHANNEL MODIFY SNAPSHOT_ID NOT NULL;

--
-- RHNSNAPSHOTCONFIGCHANNEL
--
ALTER TABLE RHNSNAPSHOTCONFIGCHANNEL DROP CONSTRAINT RHN_SNAPSHOTCC_CCID_NN;
ALTER TABLE RHNSNAPSHOTCONFIGCHANNEL MODIFY CONFIG_CHANNEL_ID NOT NULL;

--
-- RHNSNAPSHOTCONFIGCHANNEL
--
ALTER TABLE RHNSNAPSHOTCONFIGCHANNEL DROP CONSTRAINT RHN_SNAPSHOTCC_CREAT_NN;
ALTER TABLE RHNSNAPSHOTCONFIGCHANNEL MODIFY CREATED NOT NULL;

--
-- RHNSNAPSHOTCONFIGCHANNEL
--
ALTER TABLE RHNSNAPSHOTCONFIGCHANNEL DROP CONSTRAINT RHN_SNAPSHOTCC_MOD_NN;
ALTER TABLE RHNSNAPSHOTCONFIGCHANNEL MODIFY MODIFIED NOT NULL;

--
-- RHNSNAPSHOTCONFIGCHANNEL
--
ALTER TABLE RHNSNAPSHOTCONFIGCHANNEL DROP CONSTRAINT RHN_SNAPSHOTCC_SID_NN;
ALTER TABLE RHNSNAPSHOTCONFIGCHANNEL MODIFY SNAPSHOT_ID NOT NULL;

--
-- RHNSNAPSHOTCONFIGREVISION
--
ALTER TABLE RHNSNAPSHOTCONFIGREVISION DROP CONSTRAINT RHN_SNAPSHOTCR_CREAT_NN;
ALTER TABLE RHNSNAPSHOTCONFIGREVISION MODIFY CREATED NOT NULL;

--
-- RHNSNAPSHOTCONFIGREVISION
--
ALTER TABLE RHNSNAPSHOTCONFIGREVISION DROP CONSTRAINT RHN_SNAPSHOTCR_CRID_NN;
ALTER TABLE RHNSNAPSHOTCONFIGREVISION MODIFY CONFIG_REVISION_ID NOT NULL;

--
-- RHNSNAPSHOTCONFIGREVISION
--
ALTER TABLE RHNSNAPSHOTCONFIGREVISION DROP CONSTRAINT RHN_SNAPSHOTCR_MOD_NN;
ALTER TABLE RHNSNAPSHOTCONFIGREVISION MODIFY MODIFIED NOT NULL;

--
-- RHNSNAPSHOTCONFIGREVISION
--
ALTER TABLE RHNSNAPSHOTCONFIGREVISION DROP CONSTRAINT RHN_SNAPSHOTCR_SID_NN;
ALTER TABLE RHNSNAPSHOTCONFIGREVISION MODIFY SNAPSHOT_ID NOT NULL;

--
-- RHNSNAPSHOTPACKAGE
--
ALTER TABLE RHNSNAPSHOTPACKAGE DROP CONSTRAINT RHN_SNAPSHOTPKG_NID_NN;
ALTER TABLE RHNSNAPSHOTPACKAGE MODIFY NEVRA_ID NOT NULL;

--
-- RHNSNAPSHOTPACKAGE
--
ALTER TABLE RHNSNAPSHOTPACKAGE DROP CONSTRAINT RHN_SNAPSHOTPKG_SID_NN;
ALTER TABLE RHNSNAPSHOTPACKAGE MODIFY SNAPSHOT_ID NOT NULL;

--
-- RHNSNAPSHOTSERVERGROUP
--
ALTER TABLE RHNSNAPSHOTSERVERGROUP DROP CONSTRAINT RHN_SNAPSHOTSG_SGID_NN;
ALTER TABLE RHNSNAPSHOTSERVERGROUP MODIFY SERVER_GROUP_ID NOT NULL;

--
-- RHNSNAPSHOTSERVERGROUP
--
ALTER TABLE RHNSNAPSHOTSERVERGROUP DROP CONSTRAINT RHN_SNAPSHOTSG_SID_NN;
ALTER TABLE RHNSNAPSHOTSERVERGROUP MODIFY SNAPSHOT_ID NOT NULL;

--
-- RHNSNAPSHOT
--
ALTER TABLE RHNSNAPSHOT DROP CONSTRAINT RHN_SNAPSHOT_CREATED_NN;
ALTER TABLE RHNSNAPSHOT MODIFY CREATED NOT NULL;

--
-- RHNSNAPSHOT
--
ALTER TABLE RHNSNAPSHOT DROP CONSTRAINT RHN_SNAPSHOT_ID_NN;
ALTER TABLE RHNSNAPSHOT MODIFY ID NOT NULL;

--
-- RHNSNAPSHOT
--
ALTER TABLE RHNSNAPSHOT DROP CONSTRAINT RHN_SNAPSHOT_MODIFIED_NN;
ALTER TABLE RHNSNAPSHOT MODIFY MODIFIED NOT NULL;

--
-- RHNSNAPSHOT
--
ALTER TABLE RHNSNAPSHOT DROP CONSTRAINT RHN_SNAPSHOT_OID_NN;
ALTER TABLE RHNSNAPSHOT MODIFY ORG_ID NOT NULL;

--
-- RHNSNAPSHOT
--
ALTER TABLE RHNSNAPSHOT DROP CONSTRAINT RHN_SNAPSHOT_REASON_NN;
ALTER TABLE RHNSNAPSHOT MODIFY REASON NOT NULL;

--
-- RHNSNAPSHOT
--
ALTER TABLE RHNSNAPSHOT DROP CONSTRAINT RHN_SNAPSHOT_SID_NN;
ALTER TABLE RHNSNAPSHOT MODIFY SERVER_ID NOT NULL;

--
-- RHNSERVERNEEDEDCACHE
--
ALTER TABLE RHNSERVERNEEDEDCACHE DROP CONSTRAINT RHN_SNCP_PID_NN;
ALTER TABLE RHNSERVERNEEDEDCACHE MODIFY PACKAGE_ID NOT NULL;

--
-- RHNSERVERNEEDEDCACHE
--
ALTER TABLE RHNSERVERNEEDEDCACHE DROP CONSTRAINT RHN_SNCP_SID_NN;
ALTER TABLE RHNSERVERNEEDEDCACHE MODIFY SERVER_ID NOT NULL;

--
-- RHN_SAT_NODE_PROBE
--
ALTER TABLE RHN_SAT_NODE_PROBE DROP CONSTRAINT RHN_SNDPB_PROBE_ID_NN;
ALTER TABLE RHN_SAT_NODE_PROBE MODIFY PROBE_ID NOT NULL;

--
-- RHN_SAT_NODE_PROBE
--
ALTER TABLE RHN_SAT_NODE_PROBE DROP CONSTRAINT RHN_SNDPB_PROBE_TYPE_NN;
ALTER TABLE RHN_SAT_NODE_PROBE MODIFY PROBE_TYPE NOT NULL;

--
-- RHN_SAT_NODE_PROBE
--
ALTER TABLE RHN_SAT_NODE_PROBE DROP CONSTRAINT RHN_SNDPB_SAT_NODE_ID_NN;
ALTER TABLE RHN_SAT_NODE_PROBE MODIFY SAT_NODE_ID NOT NULL;

--
-- RHN_SNMP_ALERT
--
ALTER TABLE RHN_SNMP_ALERT DROP CONSTRAINT RHN_SNMPA_DEST_IP_NN;
ALTER TABLE RHN_SNMP_ALERT MODIFY DEST_IP NOT NULL;

--
-- RHN_SNMP_ALERT
--
ALTER TABLE RHN_SNMP_ALERT DROP CONSTRAINT RHN_SNMPA_DEST_PORT_NN;
ALTER TABLE RHN_SNMP_ALERT MODIFY DEST_PORT NOT NULL;

--
-- RHN_SNMP_ALERT
--
ALTER TABLE RHN_SNMP_ALERT DROP CONSTRAINT RHN_SNMPA_RECID_NN;
ALTER TABLE RHN_SNMP_ALERT MODIFY RECID NOT NULL;

--
-- RHN_SNMP_ALERT
--
ALTER TABLE RHN_SNMP_ALERT DROP CONSTRAINT RHN_SNMPA_SEND_CLUST_ID_NN;
ALTER TABLE RHN_SNMP_ALERT MODIFY SENDER_CLUSTER_ID NOT NULL;

--
-- RHNSNPERRATAQUEUE
--
ALTER TABLE RHNSNPERRATAQUEUE DROP CONSTRAINT RHN_SNPERRQUEUE_EID_NN;
ALTER TABLE RHNSNPERRATAQUEUE MODIFY ERRATA_ID NOT NULL;

--
-- RHNSNPERRATAQUEUE
--
ALTER TABLE RHNSNPERRATAQUEUE DROP CONSTRAINT RHN_SNPERRQUEUE_PROCESSED_NN;
ALTER TABLE RHNSNPERRATAQUEUE MODIFY PROCESSED NOT NULL;

--
-- RHNSOLARISPATCHEDPACKAGE
--
ALTER TABLE RHNSOLARISPATCHEDPACKAGE DROP CONSTRAINT RHN_SOLARIS_PATCHEDP_PID_NN;
ALTER TABLE RHNSOLARISPATCHEDPACKAGE MODIFY PATCH_ID NOT NULL;

--
-- RHNSOLARISPATCHEDPACKAGE
--
ALTER TABLE RHNSOLARISPATCHEDPACKAGE DROP CONSTRAINT RHN_SOLARIS_PATCHEDP_PNID_NN;
ALTER TABLE RHNSOLARISPATCHEDPACKAGE MODIFY PACKAGE_NEVRA_ID NOT NULL;

--
-- RHNSOLARISPATCHEDPACKAGE
--
ALTER TABLE RHNSOLARISPATCHEDPACKAGE DROP CONSTRAINT RHN_SOLARIS_PATCHEDP_SID_NN;
ALTER TABLE RHNSOLARISPATCHEDPACKAGE MODIFY SERVER_ID NOT NULL;

--
-- RHNSOLARISPACKAGE
--
ALTER TABLE RHNSOLARISPACKAGE DROP CONSTRAINT RHN_SOLARIS_PKG_CAT_NN;
ALTER TABLE RHNSOLARISPACKAGE MODIFY CATEGORY NOT NULL;

--
-- RHNSOLARISPATCHPACKAGES
--
ALTER TABLE RHNSOLARISPATCHPACKAGES DROP CONSTRAINT RHN_SOLARIS_PNID_NN;
ALTER TABLE RHNSOLARISPATCHPACKAGES MODIFY PACKAGE_NEVRA_ID NOT NULL;

--
-- RHNSOLARISPATCHPACKAGES
--
ALTER TABLE RHNSOLARISPATCHPACKAGES DROP CONSTRAINT RHN_SOLARIS_PP_NN;
ALTER TABLE RHNSOLARISPATCHPACKAGES MODIFY PATCH_ID NOT NULL;

--
-- RHNSOLARISPATCHSETMEMBERS
--
ALTER TABLE RHNSOLARISPATCHSETMEMBERS DROP CONSTRAINT RHN_SOLARIS_PSM_CREATED_NN;
ALTER TABLE RHNSOLARISPATCHSETMEMBERS MODIFY CREATED NOT NULL;

--
-- RHNSOLARISPATCHSETMEMBERS
--
ALTER TABLE RHNSOLARISPATCHSETMEMBERS DROP CONSTRAINT RHN_SOLARIS_PSM_MODIFIED_NN;
ALTER TABLE RHNSOLARISPATCHSETMEMBERS MODIFY MODIFIED NOT NULL;

--
-- RHNSOLARISPATCHSETMEMBERS
--
ALTER TABLE RHNSOLARISPATCHSETMEMBERS DROP CONSTRAINT RHN_SOLARIS_PSM_PID_NN;
ALTER TABLE RHNSOLARISPATCHSETMEMBERS MODIFY PATCH_ID NOT NULL;

--
-- RHNSOLARISPATCHSETMEMBERS
--
ALTER TABLE RHNSOLARISPATCHSETMEMBERS DROP CONSTRAINT RHN_SOLARIS_PSM_PSID_NN;
ALTER TABLE RHNSOLARISPATCHSETMEMBERS MODIFY PATCH_SET_ID NOT NULL;

--
-- RHNSOLARISPATCHSET
--
ALTER TABLE RHNSOLARISPATCHSET DROP CONSTRAINT RHN_SOLARIS_PS_CREATED_NN;
ALTER TABLE RHNSOLARISPATCHSET MODIFY CREATED NOT NULL;

--
-- RHNSOLARISPATCHSET
--
ALTER TABLE RHNSOLARISPATCHSET DROP CONSTRAINT RHN_SOLARIS_PS_MODIFIED_NN;
ALTER TABLE RHNSOLARISPATCHSET MODIFY MODIFIED NOT NULL;

--
-- RHNSOLARISPATCHSET
--
ALTER TABLE RHNSOLARISPATCHSET DROP CONSTRAINT RHN_SOLARIS_PS_SD_NN;
ALTER TABLE RHNSOLARISPATCHSET MODIFY SET_DATE NOT NULL;

--
-- RHNSOLARISPATCHTYPE
--
ALTER TABLE RHNSOLARISPATCHTYPE DROP CONSTRAINT RHN_SOLARIS_PT_LABEL_NN;
ALTER TABLE RHNSOLARISPATCHTYPE MODIFY LABEL NOT NULL;

--
-- RHNSOLARISPATCHTYPE
--
ALTER TABLE RHNSOLARISPATCHTYPE DROP CONSTRAINT RHN_SOLARIS_PT_NAME_NN;
ALTER TABLE RHNSOLARISPATCHTYPE MODIFY NAME NOT NULL;

--
-- RHNSOLARISPATCH
--
ALTER TABLE RHNSOLARISPATCH DROP CONSTRAINT RHN_SOLARIS_P_CREATED_NN;
ALTER TABLE RHNSOLARISPATCH MODIFY CREATED NOT NULL;

--
-- RHNSOLARISPATCH
--
ALTER TABLE RHNSOLARISPATCH DROP CONSTRAINT RHN_SOLARIS_P_MODIFIED_NN;
ALTER TABLE RHNSOLARISPATCH MODIFY MODIFIED NOT NULL;

--
-- RHNSOLARISPATCH
--
ALTER TABLE RHNSOLARISPATCH DROP CONSTRAINT RHN_SOLARIS_P_PT_NN;
ALTER TABLE RHNSOLARISPATCH MODIFY PATCH_TYPE NOT NULL;

--
-- RHNSOLARISPATCH
--
ALTER TABLE RHNSOLARISPATCH DROP CONSTRAINT RHN_SOLARIS_P_RDME_NN;
ALTER TABLE RHNSOLARISPATCH MODIFY README NOT NULL;

--
-- RHNSOURCERPM
--
ALTER TABLE RHNSOURCERPM DROP CONSTRAINT RHN_SOURCERPM_ID_NN;
ALTER TABLE RHNSOURCERPM MODIFY ID NOT NULL;

--
-- RHNSOURCERPM
--
ALTER TABLE RHNSOURCERPM DROP CONSTRAINT RHN_SOURCERPM_NAME_NN;
ALTER TABLE RHNSOURCERPM MODIFY NAME NOT NULL;

--
-- RHNSERVERPROFILEPACKAGE
--
ALTER TABLE RHNSERVERPROFILEPACKAGE DROP CONSTRAINT RHN_SPROFILE_EVRID_NN;
ALTER TABLE RHNSERVERPROFILEPACKAGE MODIFY EVR_ID NOT NULL;

--
-- RHNSERVERPROFILEPACKAGE
--
ALTER TABLE RHNSERVERPROFILEPACKAGE DROP CONSTRAINT RHN_SPROFILE_NID_NN;
ALTER TABLE RHNSERVERPROFILEPACKAGE MODIFY NAME_ID NOT NULL;

--
-- RHNSERVERPROFILEPACKAGE
--
ALTER TABLE RHNSERVERPROFILEPACKAGE DROP CONSTRAINT RHN_SPROFILE_SPID_NN;
ALTER TABLE RHNSERVERPROFILEPACKAGE MODIFY SERVER_PROFILE_ID NOT NULL;

--
-- RHNSERVERPROFILETYPE
--
ALTER TABLE RHNSERVERPROFILETYPE DROP CONSTRAINT RHN_SPROFTYPE_CREAT_NN;
ALTER TABLE RHNSERVERPROFILETYPE MODIFY CREATED NOT NULL;

--
-- RHNSERVERPROFILETYPE
--
ALTER TABLE RHNSERVERPROFILETYPE DROP CONSTRAINT RHN_SPROFTYPE_ID_NN;
ALTER TABLE RHNSERVERPROFILETYPE MODIFY ID NOT NULL;

--
-- RHNSERVERPROFILETYPE
--
ALTER TABLE RHNSERVERPROFILETYPE DROP CONSTRAINT RHN_SPROFTYPE_LABEL_NN;
ALTER TABLE RHNSERVERPROFILETYPE MODIFY LABEL NOT NULL;

--
-- RHNSERVERPROFILETYPE
--
ALTER TABLE RHNSERVERPROFILETYPE DROP CONSTRAINT RHN_SPROFTYPE_MOD_NN;
ALTER TABLE RHNSERVERPROFILETYPE MODIFY MODIFIED NOT NULL;

--
-- RHNSERVERPROFILETYPE
--
ALTER TABLE RHNSERVERPROFILETYPE DROP CONSTRAINT RHN_SPROFTYPE_NAME_NN;
ALTER TABLE RHNSERVERPROFILETYPE MODIFY NAME NOT NULL;

--
-- RHNSERVERPACKAGEARCHCOMPAT
--
ALTER TABLE RHNSERVERPACKAGEARCHCOMPAT DROP CONSTRAINT RHN_SP_AC_CREATED_NN;
ALTER TABLE RHNSERVERPACKAGEARCHCOMPAT MODIFY CREATED NOT NULL;

--
-- RHNSERVERPACKAGEARCHCOMPAT
--
ALTER TABLE RHNSERVERPACKAGEARCHCOMPAT DROP CONSTRAINT RHN_SP_AC_MODIFIED_NN;
ALTER TABLE RHNSERVERPACKAGEARCHCOMPAT MODIFY MODIFIED NOT NULL;

--
-- RHNSERVERPACKAGEARCHCOMPAT
--
ALTER TABLE RHNSERVERPACKAGEARCHCOMPAT DROP CONSTRAINT RHN_SP_AC_PAID_NN;
ALTER TABLE RHNSERVERPACKAGEARCHCOMPAT MODIFY PACKAGE_ARCH_ID NOT NULL;

--
-- RHNSERVERPACKAGEARCHCOMPAT
--
ALTER TABLE RHNSERVERPACKAGEARCHCOMPAT DROP CONSTRAINT RHN_SP_AC_PREF_NN;
ALTER TABLE RHNSERVERPACKAGEARCHCOMPAT MODIFY PREFERENCE NOT NULL;

--
-- RHNSERVERPACKAGEARCHCOMPAT
--
ALTER TABLE RHNSERVERPACKAGEARCHCOMPAT DROP CONSTRAINT RHN_SP_AC_SAID_NN;
ALTER TABLE RHNSERVERPACKAGEARCHCOMPAT MODIFY SERVER_ARCH_ID NOT NULL;

--
-- RHN_SERVICE_PROBE_ORIGINS
--
ALTER TABLE RHN_SERVICE_PROBE_ORIGINS DROP CONSTRAINT RHN_SRVPO_DECOUPLED_NN;
ALTER TABLE RHN_SERVICE_PROBE_ORIGINS MODIFY DECOUPLED NOT NULL;

--
-- RHN_SERVICE_PROBE_ORIGINS
--
ALTER TABLE RHN_SERVICE_PROBE_ORIGINS DROP CONSTRAINT RHN_SRVPO_SERV_P_ID_NN;
ALTER TABLE RHN_SERVICE_PROBE_ORIGINS MODIFY SERVICE_PROBE_ID NOT NULL;

--
-- RHNSERVERNETINTERFACE
--
ALTER TABLE RHNSERVERNETINTERFACE DROP CONSTRAINT RHN_SRV_NET_IFACE_CREATED_NN;
ALTER TABLE RHNSERVERNETINTERFACE MODIFY CREATED NOT NULL;

--
-- RHNSERVERNETINTERFACE
--
ALTER TABLE RHNSERVERNETINTERFACE DROP CONSTRAINT RHN_SRV_NET_IFACE_MODIFIED_NN;
ALTER TABLE RHNSERVERNETINTERFACE MODIFY MODIFIED NOT NULL;

--
-- RHNSERVERNETINTERFACE
--
ALTER TABLE RHNSERVERNETINTERFACE DROP CONSTRAINT RHN_SRV_NET_IFACE_NAME_NN;
ALTER TABLE RHNSERVERNETINTERFACE MODIFY NAME NOT NULL;

--
-- RHNSERVERNETINTERFACE
--
ALTER TABLE RHNSERVERNETINTERFACE DROP CONSTRAINT RHN_SRV_NET_IFACE_SID_NN;
ALTER TABLE RHNSERVERNETINTERFACE MODIFY SERVER_ID NOT NULL;

--
-- RHNSERVERTOKENREGS
--
ALTER TABLE RHNSERVERTOKENREGS DROP CONSTRAINT RHN_SRV_REG_TOK_SID_NN;
ALTER TABLE RHNSERVERTOKENREGS MODIFY SERVER_ID NOT NULL;

--
-- RHNSERVERTOKENREGS
--
ALTER TABLE RHNSERVERTOKENREGS DROP CONSTRAINT RHN_SRV_REG_TOK_TID_NN;
ALTER TABLE RHNSERVERTOKENREGS MODIFY TOKEN_ID NOT NULL;

--
-- RHNSERVERSERVERGROUPARCHCOMPAT
--
ALTER TABLE RHNSERVERSERVERGROUPARCHCOMPAT DROP CONSTRAINT RHN_SSG_AC_CREATED_NN;
ALTER TABLE RHNSERVERSERVERGROUPARCHCOMPAT MODIFY CREATED NOT NULL;

--
-- RHNSERVERSERVERGROUPARCHCOMPAT
--
ALTER TABLE RHNSERVERSERVERGROUPARCHCOMPAT DROP CONSTRAINT RHN_SSG_AC_MODIFIED_NN;
ALTER TABLE RHNSERVERSERVERGROUPARCHCOMPAT MODIFY MODIFIED NOT NULL;

--
-- RHNSERVERSERVERGROUPARCHCOMPAT
--
ALTER TABLE RHNSERVERSERVERGROUPARCHCOMPAT DROP CONSTRAINT RHN_SSG_AC_SAID_NN;
ALTER TABLE RHNSERVERSERVERGROUPARCHCOMPAT MODIFY SERVER_ARCH_ID NOT NULL;

--
-- RHNSERVERSERVERGROUPARCHCOMPAT
--
ALTER TABLE RHNSERVERSERVERGROUPARCHCOMPAT DROP CONSTRAINT RHN_SSG_AC_SGT_NN;
ALTER TABLE RHNSERVERSERVERGROUPARCHCOMPAT MODIFY SERVER_GROUP_TYPE NOT NULL;

--
-- RHNSNAPSHOTINVALIDREASON
--
ALTER TABLE RHNSNAPSHOTINVALIDREASON DROP CONSTRAINT RHN_SSINVALID_CREATED_NN;
ALTER TABLE RHNSNAPSHOTINVALIDREASON MODIFY CREATED NOT NULL;

--
-- RHNSNAPSHOTINVALIDREASON
--
ALTER TABLE RHNSNAPSHOTINVALIDREASON DROP CONSTRAINT RHN_SSINVALID_ID_NN;
ALTER TABLE RHNSNAPSHOTINVALIDREASON MODIFY ID NOT NULL;

--
-- RHNSNAPSHOTINVALIDREASON
--
ALTER TABLE RHNSNAPSHOTINVALIDREASON DROP CONSTRAINT RHN_SSINVALID_LABEL_NN;
ALTER TABLE RHNSNAPSHOTINVALIDREASON MODIFY LABEL NOT NULL;

--
-- RHNSNAPSHOTINVALIDREASON
--
ALTER TABLE RHNSNAPSHOTINVALIDREASON DROP CONSTRAINT RHN_SSINVALID_MODIFIED_NN;
ALTER TABLE RHNSNAPSHOTINVALIDREASON MODIFY MODIFIED NOT NULL;

--
-- RHNSNAPSHOTINVALIDREASON
--
ALTER TABLE RHNSNAPSHOTINVALIDREASON DROP CONSTRAINT RHN_SSINVALID_NAME_NN;
ALTER TABLE RHNSNAPSHOTINVALIDREASON MODIFY NAME NOT NULL;

--
-- RHNSSMOPERATION
--
ALTER TABLE RHNSSMOPERATION DROP CONSTRAINT RHN_SSMOP_DESC_NN;
ALTER TABLE RHNSSMOPERATION MODIFY DESCRIPTION NOT NULL;

--
-- RHNSSMOPERATION
--
ALTER TABLE RHNSSMOPERATION DROP CONSTRAINT RHN_SSMOP_ID_NN;
ALTER TABLE RHNSSMOPERATION MODIFY ID NOT NULL;

--
-- RHNSSMOPERATION
--
ALTER TABLE RHNSSMOPERATION DROP CONSTRAINT RHN_SSMOP_MOD_NN;
ALTER TABLE RHNSSMOPERATION MODIFY MODIFIED NOT NULL;

--
-- RHNSSMOPERATION
--
ALTER TABLE RHNSSMOPERATION DROP CONSTRAINT RHN_SSMOP_STRT_NN;
ALTER TABLE RHNSSMOPERATION MODIFY STARTED NOT NULL;

--
-- RHNSSMOPERATION
--
ALTER TABLE RHNSSMOPERATION DROP CONSTRAINT RHN_SSMOP_ST_NN;
ALTER TABLE RHNSSMOPERATION MODIFY STATUS NOT NULL;

--
-- RHNSSMOPERATION
--
ALTER TABLE RHNSSMOPERATION DROP CONSTRAINT RHN_SSMOP_USER_NN;
ALTER TABLE RHNSSMOPERATION MODIFY USER_ID NOT NULL;

--
-- RHNSAVEDSEARCHTYPE
--
ALTER TABLE RHNSAVEDSEARCHTYPE DROP CONSTRAINT RHN_SSTYPE_CREATED_NN;
ALTER TABLE RHNSAVEDSEARCHTYPE MODIFY CREATED NOT NULL;

--
-- RHNSAVEDSEARCHTYPE
--
ALTER TABLE RHNSAVEDSEARCHTYPE DROP CONSTRAINT RHN_SSTYPE_ID_NN;
ALTER TABLE RHNSAVEDSEARCHTYPE MODIFY ID NOT NULL;

--
-- RHNSAVEDSEARCHTYPE
--
ALTER TABLE RHNSAVEDSEARCHTYPE DROP CONSTRAINT RHN_SSTYPE_LABEL_NN;
ALTER TABLE RHNSAVEDSEARCHTYPE MODIFY LABEL NOT NULL;

--
-- RHNSAVEDSEARCHTYPE
--
ALTER TABLE RHNSAVEDSEARCHTYPE DROP CONSTRAINT RHN_SSTYPE_MODIFIED_NN;
ALTER TABLE RHNSAVEDSEARCHTYPE MODIFY MODIFIED NOT NULL;

--
-- RHN_STRATEGIES
--
ALTER TABLE RHN_STRATEGIES DROP CONSTRAINT RHN_STRAT_RECID_NN;
ALTER TABLE RHN_STRATEGIES MODIFY RECID NOT NULL;

--
-- RHNSNAPSHOTTAG
--
ALTER TABLE RHNSNAPSHOTTAG DROP CONSTRAINT RHN_ST_CREATED_NN;
ALTER TABLE RHNSNAPSHOTTAG MODIFY CREATED NOT NULL;

--
-- RHNSNAPSHOTTAG
--
ALTER TABLE RHNSNAPSHOTTAG DROP CONSTRAINT RHN_ST_MODIFIED_NN;
ALTER TABLE RHNSNAPSHOTTAG MODIFY MODIFIED NOT NULL;

--
-- RHNSNAPSHOTTAG
--
ALTER TABLE RHNSNAPSHOTTAG DROP CONSTRAINT RHN_ST_SSID_NN;
ALTER TABLE RHNSNAPSHOTTAG MODIFY SNAPSHOT_ID NOT NULL;

--
-- RHNSNAPSHOTTAG
--
ALTER TABLE RHNSNAPSHOTTAG DROP CONSTRAINT RHN_ST_TID_NN;
ALTER TABLE RHNSNAPSHOTTAG MODIFY TAG_ID NOT NULL;

--
-- RHNSYSTEMMIGRATIONS
--
ALTER TABLE RHNSYSTEMMIGRATIONS DROP CONSTRAINT RHN_SYS_MIG_MIGRATED_NN;
ALTER TABLE RHNSYSTEMMIGRATIONS MODIFY MIGRATED NOT NULL;

--
-- RHNSYSTEMMIGRATIONS
--
ALTER TABLE RHNSYSTEMMIGRATIONS DROP CONSTRAINT RHN_SYS_MIG_SID_NN;
ALTER TABLE RHNSYSTEMMIGRATIONS MODIFY SERVER_ID NOT NULL;

--
-- RHNTAG
--
ALTER TABLE RHNTAG DROP CONSTRAINT RHN_TAG_CREATED_NN;
ALTER TABLE RHNTAG MODIFY CREATED NOT NULL;

--
-- RHNTAG
--
ALTER TABLE RHNTAG DROP CONSTRAINT RHN_TAG_ID_NN;
ALTER TABLE RHNTAG MODIFY ID NOT NULL;

--
-- RHNTAG
--
ALTER TABLE RHNTAG DROP CONSTRAINT RHN_TAG_MODIFIED_NN;
ALTER TABLE RHNTAG MODIFY MODIFIED NOT NULL;

--
-- RHNTAG
--
ALTER TABLE RHNTAG DROP CONSTRAINT RHN_TAG_NID_NN;
ALTER TABLE RHNTAG MODIFY NAME_ID NOT NULL;

--
-- RHNTAG
--
ALTER TABLE RHNTAG DROP CONSTRAINT RHN_TAG_OID_NN;
ALTER TABLE RHNTAG MODIFY ORG_ID NOT NULL;

--
-- RHNTASKQUEUE
--
ALTER TABLE RHNTASKQUEUE DROP CONSTRAINT RHN_TASK_QUEUE_EARLIEST_NN;
ALTER TABLE RHNTASKQUEUE MODIFY EARLIEST NOT NULL;

--
-- RHNTASKQUEUE
--
ALTER TABLE RHNTASKQUEUE DROP CONSTRAINT RHN_TASK_QUEUE_ORG_ID_NN;
ALTER TABLE RHNTASKQUEUE MODIFY ORG_ID NOT NULL;

--
-- RHNTASKQUEUE
--
ALTER TABLE RHNTASKQUEUE DROP CONSTRAINT RHN_TASK_QUEUE_TASK_NAME_NN;
ALTER TABLE RHNTASKQUEUE MODIFY TASK_NAME NOT NULL;

--
-- RHNTEMPLATECATEGORY
--
ALTER TABLE RHNTEMPLATECATEGORY DROP CONSTRAINT RHN_TEMPLATE_CAT_CREATED_NN;
ALTER TABLE RHNTEMPLATECATEGORY MODIFY CREATED NOT NULL;

--
-- RHNTEMPLATECATEGORY
--
ALTER TABLE RHNTEMPLATECATEGORY DROP CONSTRAINT RHN_TEMPLATE_CAT_DESC_NN;
ALTER TABLE RHNTEMPLATECATEGORY MODIFY DESCRIPTION NOT NULL;

--
-- RHNTEMPLATECATEGORY
--
ALTER TABLE RHNTEMPLATECATEGORY DROP CONSTRAINT RHN_TEMPLATE_CAT_ID_NN;
ALTER TABLE RHNTEMPLATECATEGORY MODIFY ID NOT NULL;

--
-- RHNTEMPLATECATEGORY
--
ALTER TABLE RHNTEMPLATECATEGORY DROP CONSTRAINT RHN_TEMPLATE_CAT_LABEL_NN;
ALTER TABLE RHNTEMPLATECATEGORY MODIFY LABEL NOT NULL;

--
-- RHNTEMPLATECATEGORY
--
ALTER TABLE RHNTEMPLATECATEGORY DROP CONSTRAINT RHN_TEMPLATE_CAT_MODIFIED_NN;
ALTER TABLE RHNTEMPLATECATEGORY MODIFY MODIFIED NOT NULL;

--
-- RHNTEMPLATESTRING
--
ALTER TABLE RHNTEMPLATESTRING DROP CONSTRAINT RHN_TEMPLATE_STR_CID_NN;
ALTER TABLE RHNTEMPLATESTRING MODIFY CATEGORY_ID NOT NULL;

--
-- RHNTEMPLATESTRING
--
ALTER TABLE RHNTEMPLATESTRING DROP CONSTRAINT RHN_TEMPLATE_STR_CREATED_NN;
ALTER TABLE RHNTEMPLATESTRING MODIFY CREATED NOT NULL;

--
-- RHNTEMPLATESTRING
--
ALTER TABLE RHNTEMPLATESTRING DROP CONSTRAINT RHN_TEMPLATE_STR_DESC_NN;
ALTER TABLE RHNTEMPLATESTRING MODIFY DESCRIPTION NOT NULL;

--
-- RHNTEMPLATESTRING
--
ALTER TABLE RHNTEMPLATESTRING DROP CONSTRAINT RHN_TEMPLATE_STR_ID_NN;
ALTER TABLE RHNTEMPLATESTRING MODIFY ID NOT NULL;

--
-- RHNTEMPLATESTRING
--
ALTER TABLE RHNTEMPLATESTRING DROP CONSTRAINT RHN_TEMPLATE_STR_KEY_NN;
ALTER TABLE RHNTEMPLATESTRING MODIFY LABEL NOT NULL;

--
-- RHNTEMPLATESTRING
--
ALTER TABLE RHNTEMPLATESTRING DROP CONSTRAINT RHN_TEMPLATE_STR_MODIFIED_NN;
ALTER TABLE RHNTEMPLATESTRING MODIFY MODIFIED NOT NULL;

--
-- RHNTIMEZONE
--
ALTER TABLE RHNTIMEZONE DROP CONSTRAINT RHN_TIMEZONE_DISPLAY_NN;
ALTER TABLE RHNTIMEZONE MODIFY DISPLAY_NAME NOT NULL;

--
-- RHNTIMEZONE
--
ALTER TABLE RHNTIMEZONE DROP CONSTRAINT RHN_TIMEZONE_ID_NN;
ALTER TABLE RHNTIMEZONE MODIFY ID NOT NULL;

--
-- RHNTIMEZONE
--
ALTER TABLE RHNTIMEZONE DROP CONSTRAINT RHN_TIMEZONE_OLSON_NN;
ALTER TABLE RHNTIMEZONE MODIFY OLSON_NAME NOT NULL;

--
-- RHNTEXTMESSAGE
--
ALTER TABLE RHNTEXTMESSAGE DROP CONSTRAINT RHN_TM_CREATED_NN;
ALTER TABLE RHNTEXTMESSAGE MODIFY CREATED NOT NULL;

--
-- RHNTEXTMESSAGE
--
ALTER TABLE RHNTEXTMESSAGE DROP CONSTRAINT RHN_TM_MESSAGE_BODY_NN;
ALTER TABLE RHNTEXTMESSAGE MODIFY MESSAGE_BODY NOT NULL;

--
-- RHNTEXTMESSAGE
--
ALTER TABLE RHNTEXTMESSAGE DROP CONSTRAINT RHN_TM_MESSAGE_ID_NN;
ALTER TABLE RHNTEXTMESSAGE MODIFY MESSAGE_ID NOT NULL;

--
-- RHNTEXTMESSAGE
--
ALTER TABLE RHNTEXTMESSAGE DROP CONSTRAINT RHN_TM_MODIFIED_NN;
ALTER TABLE RHNTEXTMESSAGE MODIFY MODIFIED NOT NULL;

--
-- RHNTAGNAME
--
ALTER TABLE RHNTAGNAME DROP CONSTRAINT RHN_TN_CREATED_NN;
ALTER TABLE RHNTAGNAME MODIFY CREATED NOT NULL;

--
-- RHNTAGNAME
--
ALTER TABLE RHNTAGNAME DROP CONSTRAINT RHN_TN_ID_NN;
ALTER TABLE RHNTAGNAME MODIFY ID NOT NULL;

--
-- RHNTAGNAME
--
ALTER TABLE RHNTAGNAME DROP CONSTRAINT RHN_TN_MODIFIED_NN;
ALTER TABLE RHNTAGNAME MODIFY MODIFIED NOT NULL;

--
-- RHNTAGNAME
--
ALTER TABLE RHNTAGNAME DROP CONSTRAINT RHN_TN_NAME_NN;
ALTER TABLE RHNTAGNAME MODIFY NAME NOT NULL;

--
-- RHNTRANSACTIONELEMENT
--
ALTER TABLE RHNTRANSACTIONELEMENT DROP CONSTRAINT RHN_TRANSELEM_TID_NN;
ALTER TABLE RHNTRANSACTIONELEMENT MODIFY TRANSACTION_ID NOT NULL;

--
-- RHNTRANSACTIONELEMENT
--
ALTER TABLE RHNTRANSACTIONELEMENT DROP CONSTRAINT RHN_TRANSELEM_TPID_NN;
ALTER TABLE RHNTRANSACTIONELEMENT MODIFY TRANSACTION_PACKAGE_ID NOT NULL;

--
-- RHNTRANSACTIONOPERATION
--
ALTER TABLE RHNTRANSACTIONOPERATION DROP CONSTRAINT RHN_TRANSOP_CREATED_NN;
ALTER TABLE RHNTRANSACTIONOPERATION MODIFY CREATED NOT NULL;

--
-- RHNTRANSACTIONOPERATION
--
ALTER TABLE RHNTRANSACTIONOPERATION DROP CONSTRAINT RHN_TRANSOP_ID_NN;
ALTER TABLE RHNTRANSACTIONOPERATION MODIFY ID NOT NULL;

--
-- RHNTRANSACTIONOPERATION
--
ALTER TABLE RHNTRANSACTIONOPERATION DROP CONSTRAINT RHN_TRANSOP_LABEL_NN;
ALTER TABLE RHNTRANSACTIONOPERATION MODIFY LABEL NOT NULL;

--
-- RHNTRANSACTIONOPERATION
--
ALTER TABLE RHNTRANSACTIONOPERATION DROP CONSTRAINT RHN_TRANSOP_MODIFIED_NN;
ALTER TABLE RHNTRANSACTIONOPERATION MODIFY MODIFIED NOT NULL;

--
-- RHNTRANSACTIONPACKAGE
--
ALTER TABLE RHNTRANSACTIONPACKAGE DROP CONSTRAINT RHN_TRANSPACK_EID_NN;
ALTER TABLE RHNTRANSACTIONPACKAGE MODIFY EVR_ID NOT NULL;

--
-- RHNTRANSACTIONPACKAGE
--
ALTER TABLE RHNTRANSACTIONPACKAGE DROP CONSTRAINT RHN_TRANSPACK_ID_NN;
ALTER TABLE RHNTRANSACTIONPACKAGE MODIFY ID NOT NULL;

--
-- RHNTRANSACTIONPACKAGE
--
ALTER TABLE RHNTRANSACTIONPACKAGE DROP CONSTRAINT RHN_TRANSPACK_NID_NN;
ALTER TABLE RHNTRANSACTIONPACKAGE MODIFY NAME_ID NOT NULL;

--
-- RHNTRANSACTIONPACKAGE
--
ALTER TABLE RHNTRANSACTIONPACKAGE DROP CONSTRAINT RHN_TRANSPACK_OP_NN;
ALTER TABLE RHNTRANSACTIONPACKAGE MODIFY OPERATION NOT NULL;

--
-- RHNTRANSACTION
--
ALTER TABLE RHNTRANSACTION DROP CONSTRAINT RHN_TRANS_CREATED_NN;
ALTER TABLE RHNTRANSACTION MODIFY CREATED NOT NULL;

--
-- RHNTRANSACTION
--
ALTER TABLE RHNTRANSACTION DROP CONSTRAINT RHN_TRANS_ID_NN;
ALTER TABLE RHNTRANSACTION MODIFY ID NOT NULL;

--
-- RHNTRANSACTION
--
ALTER TABLE RHNTRANSACTION DROP CONSTRAINT RHN_TRANS_MODIFIED_NN;
ALTER TABLE RHNTRANSACTION MODIFY MODIFIED NOT NULL;

--
-- RHNTRANSACTION
--
ALTER TABLE RHNTRANSACTION DROP CONSTRAINT RHN_TRANS_RTI_NN;
ALTER TABLE RHNTRANSACTION MODIFY RPM_TRANS_ID NOT NULL;

--
-- RHNTRANSACTION
--
ALTER TABLE RHNTRANSACTION DROP CONSTRAINT RHN_TRANS_SID_NN;
ALTER TABLE RHNTRANSACTION MODIFY SERVER_ID NOT NULL;

--
-- RHNTRANSACTION
--
ALTER TABLE RHNTRANSACTION DROP CONSTRAINT RHN_TRANS_TS_NN;
ALTER TABLE RHNTRANSACTION MODIFY TIMESTAMP NOT NULL;

--
-- RHN_THRESHOLD_TYPE
--
ALTER TABLE RHN_THRESHOLD_TYPE DROP CONSTRAINT RHN_TRTYP_DESC_NN;
ALTER TABLE RHN_THRESHOLD_TYPE MODIFY DESCRIPTION NOT NULL;

--
-- RHN_THRESHOLD_TYPE
--
ALTER TABLE RHN_THRESHOLD_TYPE DROP CONSTRAINT RHN_TRTYP_NAME_NN;
ALTER TABLE RHN_THRESHOLD_TYPE MODIFY NAME NOT NULL;

--
-- RHN_THRESHOLD_TYPE
--
ALTER TABLE RHN_THRESHOLD_TYPE DROP CONSTRAINT RHN_TRTYP_ORD_NN;
ALTER TABLE RHN_THRESHOLD_TYPE MODIFY ORDINAL NOT NULL;

--
-- RHNTRUSTEDORGS
--
ALTER TABLE RHNTRUSTEDORGS DROP CONSTRAINT RHN_TRUSTED_ORGS_CREATED_NN;
ALTER TABLE RHNTRUSTEDORGS MODIFY CREATED NOT NULL;

--
-- RHNTRUSTEDORGS
--
ALTER TABLE RHNTRUSTEDORGS DROP CONSTRAINT RHN_TRUSTED_ORGS_MODIFIED_NN;
ALTER TABLE RHNTRUSTEDORGS MODIFY MODIFIED NOT NULL;

--
-- RHNTRUSTEDORGS
--
ALTER TABLE RHNTRUSTEDORGS DROP CONSTRAINT RHN_TRUSTED_ORGS_OID_NN;
ALTER TABLE RHNTRUSTEDORGS MODIFY ORG_ID NOT NULL;

--
-- RHNTRUSTEDORGS
--
ALTER TABLE RHNTRUSTEDORGS DROP CONSTRAINT RHN_TRUSTED_ORGS_OTID_NN;
ALTER TABLE RHNTRUSTEDORGS MODIFY ORG_TRUST_ID NOT NULL;

--
-- RHNTINYURL
--
ALTER TABLE RHNTINYURL DROP CONSTRAINT RHN_TU_CREATED_NN;
ALTER TABLE RHNTINYURL MODIFY CREATED NOT NULL;

--
-- RHNTINYURL
--
ALTER TABLE RHNTINYURL DROP CONSTRAINT RHN_TU_ENABLED_NN;
ALTER TABLE RHNTINYURL MODIFY ENABLED NOT NULL;

--
-- RHNTINYURL
--
ALTER TABLE RHNTINYURL DROP CONSTRAINT RHN_TU_EXPIRES_NN;
ALTER TABLE RHNTINYURL MODIFY EXPIRES NOT NULL;

--
-- RHNTINYURL
--
ALTER TABLE RHNTINYURL DROP CONSTRAINT RHN_TU_TOKEN_NN;
ALTER TABLE RHNTINYURL MODIFY TOKEN NOT NULL;

--
-- RHNTINYURL
--
ALTER TABLE RHNTINYURL DROP CONSTRAINT RHN_TU_URL_NN;
ALTER TABLE RHNTINYURL MODIFY URL NOT NULL;

--
-- RHN_TIME_ZONE_NAMES
--
ALTER TABLE RHN_TIME_ZONE_NAMES DROP CONSTRAINT RHN_TZNMS_DISPLAY_NAME_NN;
ALTER TABLE RHN_TIME_ZONE_NAMES MODIFY DISPLAY_NAME NOT NULL;

--
-- RHN_TIME_ZONE_NAMES
--
ALTER TABLE RHN_TIME_ZONE_NAMES DROP CONSTRAINT RHN_TZNMS_GMT_OFFSET_NN;
ALTER TABLE RHN_TIME_ZONE_NAMES MODIFY GMT_OFFSET_MINUTES NOT NULL;

--
-- RHN_TIME_ZONE_NAMES
--
ALTER TABLE RHN_TIME_ZONE_NAMES DROP CONSTRAINT RHN_TZNMS_JAVA_ID_NN;
ALTER TABLE RHN_TIME_ZONE_NAMES MODIFY JAVA_ID NOT NULL;

--
-- RHN_TIME_ZONE_NAMES
--
ALTER TABLE RHN_TIME_ZONE_NAMES DROP CONSTRAINT RHN_TZNMS_RECID_NN;
ALTER TABLE RHN_TIME_ZONE_NAMES MODIFY RECID NOT NULL;

--
-- RHN_TIME_ZONE_NAMES
--
ALTER TABLE RHN_TIME_ZONE_NAMES DROP CONSTRAINT RHN_TZNMS_USE_DST_NN;
ALTER TABLE RHN_TIME_ZONE_NAMES MODIFY USE_DAYLIGHT_TIME NOT NULL;

--
-- RHNUSERDEFAULTSYSTEMGROUPS
--
ALTER TABLE RHNUSERDEFAULTSYSTEMGROUPS DROP CONSTRAINT RHN_UDSG_CID_NN;
ALTER TABLE RHNUSERDEFAULTSYSTEMGROUPS MODIFY SYSTEM_GROUP_ID NOT NULL;

--
-- RHNUSERDEFAULTSYSTEMGROUPS
--
ALTER TABLE RHNUSERDEFAULTSYSTEMGROUPS DROP CONSTRAINT RHN_UDSG_UID_NN;
ALTER TABLE RHNUSERDEFAULTSYSTEMGROUPS MODIFY USER_ID NOT NULL;

--
-- RHNUSERGROUPMEMBERS
--
ALTER TABLE RHNUSERGROUPMEMBERS DROP CONSTRAINT RHN_UGMEMBERS_CREATED_NN;
ALTER TABLE RHNUSERGROUPMEMBERS MODIFY CREATED NOT NULL;

--
-- RHNUSERGROUPMEMBERS
--
ALTER TABLE RHNUSERGROUPMEMBERS DROP CONSTRAINT RHN_UGMEMBERS_MODIFIED_NN;
ALTER TABLE RHNUSERGROUPMEMBERS MODIFY MODIFIED NOT NULL;

--
-- RHNUSERGROUPMEMBERS
--
ALTER TABLE RHNUSERGROUPMEMBERS DROP CONSTRAINT RHN_UGMEMBERS_UGID_NN;
ALTER TABLE RHNUSERGROUPMEMBERS MODIFY USER_GROUP_ID NOT NULL;

--
-- RHNUSERGROUPMEMBERS
--
ALTER TABLE RHNUSERGROUPMEMBERS DROP CONSTRAINT RHN_UGMEMBERS_UID_NN;
ALTER TABLE RHNUSERGROUPMEMBERS MODIFY USER_ID NOT NULL;

--
-- RHNUSERMESSAGE
--
ALTER TABLE RHNUSERMESSAGE DROP CONSTRAINT RHN_UM_MESSAGE_ID_NN;
ALTER TABLE RHNUSERMESSAGE MODIFY MESSAGE_ID NOT NULL;

--
-- RHNUSERMESSAGESTATUS
--
ALTER TABLE RHNUSERMESSAGESTATUS DROP CONSTRAINT RHN_UM_STATUS_ID_NN;
ALTER TABLE RHNUSERMESSAGESTATUS MODIFY ID NOT NULL;

--
-- RHNUSERMESSAGESTATUS
--
ALTER TABLE RHNUSERMESSAGESTATUS DROP CONSTRAINT RHN_UM_STATUS_LABEL_NN;
ALTER TABLE RHNUSERMESSAGESTATUS MODIFY LABEL NOT NULL;

--
-- RHNUSERMESSAGE
--
ALTER TABLE RHNUSERMESSAGE DROP CONSTRAINT RHN_UM_STATUS_NN;
ALTER TABLE RHNUSERMESSAGE MODIFY STATUS NOT NULL;

--
-- RHNUSERMESSAGETYPE
--
ALTER TABLE RHNUSERMESSAGETYPE DROP CONSTRAINT RHN_UM_TYPE_ID_NN;
ALTER TABLE RHNUSERMESSAGETYPE MODIFY ID NOT NULL;

--
-- RHNUSERMESSAGETYPE
--
ALTER TABLE RHNUSERMESSAGETYPE DROP CONSTRAINT RHN_UM_TYPE_LABEL_NN;
ALTER TABLE RHNUSERMESSAGETYPE MODIFY LABEL NOT NULL;

--
-- RHNUSERMESSAGETYPE
--
ALTER TABLE RHNUSERMESSAGETYPE DROP CONSTRAINT RHN_UM_TYPE_NAME_NN;
ALTER TABLE RHNUSERMESSAGETYPE MODIFY NAME NOT NULL;

--
-- RHNUSERMESSAGE
--
ALTER TABLE RHNUSERMESSAGE DROP CONSTRAINT RHN_UM_USER_ID_NN;
ALTER TABLE RHNUSERMESSAGE MODIFY USER_ID NOT NULL;

--
-- RHN_UNITS
--
ALTER TABLE RHN_UNITS DROP CONSTRAINT RHN_UNITS_QUANTUM_ID_NN;
ALTER TABLE RHN_UNITS MODIFY QUANTUM_ID NOT NULL;

--
-- RHN_UNITS
--
ALTER TABLE RHN_UNITS DROP CONSTRAINT RHN_UNITS_UNIT_ID_NN;
ALTER TABLE RHN_UNITS MODIFY UNIT_ID NOT NULL;

--
-- RHN_URL_PROBE
--
ALTER TABLE RHN_URL_PROBE DROP CONSTRAINT RHN_URLPB_COOKIE_EN_NN;
ALTER TABLE RHN_URL_PROBE MODIFY COOKIE_ENABLED NOT NULL;

--
-- RHN_URL_PROBE
--
ALTER TABLE RHN_URL_PROBE DROP CONSTRAINT RHN_URLPB_MULTI_STEP_NN;
ALTER TABLE RHN_URL_PROBE MODIFY MULTI_STEP NOT NULL;

--
-- RHN_URL_PROBE
--
ALTER TABLE RHN_URL_PROBE DROP CONSTRAINT RHN_URLPB_PROBE_ID_NN;
ALTER TABLE RHN_URL_PROBE MODIFY PROBE_ID NOT NULL;

--
-- RHN_URL_PROBE
--
ALTER TABLE RHN_URL_PROBE DROP CONSTRAINT RHN_URLPB_PROBE_TYPE_NN;
ALTER TABLE RHN_URL_PROBE MODIFY PROBE_TYPE NOT NULL;

--
-- RHN_URL_PROBE
--
ALTER TABLE RHN_URL_PROBE DROP CONSTRAINT RHN_URLPB_RUN_ON_SCOUTS_NN;
ALTER TABLE RHN_URL_PROBE MODIFY RUN_ON_SCOUTS NOT NULL;

--
-- RHN_URL_PROBE_STEP
--
ALTER TABLE RHN_URL_PROBE_STEP DROP CONSTRAINT RHN_URLPS_CONN_CRIT_NN;
ALTER TABLE RHN_URL_PROBE_STEP MODIFY CONNECT_CRIT NOT NULL;

--
-- RHN_URL_PROBE_STEP
--
ALTER TABLE RHN_URL_PROBE_STEP DROP CONSTRAINT RHN_URLPS_CONN_WARN_NN;
ALTER TABLE RHN_URL_PROBE_STEP MODIFY CONNECT_WARN NOT NULL;

--
-- RHN_URL_PROBE_STEP
--
ALTER TABLE RHN_URL_PROBE_STEP DROP CONSTRAINT RHN_URLPS_COOKIE_SEC_NN;
ALTER TABLE RHN_URL_PROBE_STEP MODIFY COOKIE_SECURE NOT NULL;

--
-- RHN_URL_PROBE_STEP
--
ALTER TABLE RHN_URL_PROBE_STEP DROP CONSTRAINT RHN_URLPS_DNS_CRIT_NN;
ALTER TABLE RHN_URL_PROBE_STEP MODIFY DNS_CRIT NOT NULL;

--
-- RHN_URL_PROBE_STEP
--
ALTER TABLE RHN_URL_PROBE_STEP DROP CONSTRAINT RHN_URLPS_DNS_WARN_NN;
ALTER TABLE RHN_URL_PROBE_STEP MODIFY DNS_WARN NOT NULL;

--
-- RHN_URL_PROBE_STEP
--
ALTER TABLE RHN_URL_PROBE_STEP DROP CONSTRAINT RHN_URLPS_LATE_CRIT_NN;
ALTER TABLE RHN_URL_PROBE_STEP MODIFY LATENCY_CRIT NOT NULL;

--
-- RHN_URL_PROBE_STEP
--
ALTER TABLE RHN_URL_PROBE_STEP DROP CONSTRAINT RHN_URLPS_LATE_WARN_NN;
ALTER TABLE RHN_URL_PROBE_STEP MODIFY LATENCY_WARN NOT NULL;

--
-- RHN_URL_PROBE_STEP
--
ALTER TABLE RHN_URL_PROBE_STEP DROP CONSTRAINT RHN_URLPS_LOAD_SUB_NN;
ALTER TABLE RHN_URL_PROBE_STEP MODIFY LOAD_SUBSIDIARY NOT NULL;

--
-- RHN_URL_PROBE_STEP
--
ALTER TABLE RHN_URL_PROBE_STEP DROP CONSTRAINT RHN_URLPS_PROTOCOL_NN;
ALTER TABLE RHN_URL_PROBE_STEP MODIFY PROTOCOL_METHOD NOT NULL;

--
-- RHN_URL_PROBE_STEP
--
ALTER TABLE RHN_URL_PROBE_STEP DROP CONSTRAINT RHN_URLPS_RECID_NN;
ALTER TABLE RHN_URL_PROBE_STEP MODIFY RECID NOT NULL;

--
-- RHN_URL_PROBE_STEP
--
ALTER TABLE RHN_URL_PROBE_STEP DROP CONSTRAINT RHN_URLPS_THRU_CRIT_NN;
ALTER TABLE RHN_URL_PROBE_STEP MODIFY THROUGH_CRIT NOT NULL;

--
-- RHN_URL_PROBE_STEP
--
ALTER TABLE RHN_URL_PROBE_STEP DROP CONSTRAINT RHN_URLPS_THRU_WARN_NN;
ALTER TABLE RHN_URL_PROBE_STEP MODIFY THROUGH_WARN NOT NULL;

--
-- RHN_URL_PROBE_STEP
--
ALTER TABLE RHN_URL_PROBE_STEP DROP CONSTRAINT RHN_URLPS_TOTAL_CRIT_NN;
ALTER TABLE RHN_URL_PROBE_STEP MODIFY TOTAL_CRIT NOT NULL;

--
-- RHN_URL_PROBE_STEP
--
ALTER TABLE RHN_URL_PROBE_STEP DROP CONSTRAINT RHN_URLPS_TOTAL_WARN_NN;
ALTER TABLE RHN_URL_PROBE_STEP MODIFY TOTAL_WARN NOT NULL;

--
-- RHN_URL_PROBE_STEP
--
ALTER TABLE RHN_URL_PROBE_STEP DROP CONSTRAINT RHN_URLPS_TRANS_CRIT_NN;
ALTER TABLE RHN_URL_PROBE_STEP MODIFY TRANS_CRIT NOT NULL;

--
-- RHN_URL_PROBE_STEP
--
ALTER TABLE RHN_URL_PROBE_STEP DROP CONSTRAINT RHN_URLPS_TRANS_WARN_NN;
ALTER TABLE RHN_URL_PROBE_STEP MODIFY TRANS_WARN NOT NULL;

--
-- RHN_URL_PROBE_STEP
--
ALTER TABLE RHN_URL_PROBE_STEP DROP CONSTRAINT RHN_URLPS_URL_NN;
ALTER TABLE RHN_URL_PROBE_STEP MODIFY URL NOT NULL;

--
-- RHN_URL_PROBE_STEP
--
ALTER TABLE RHN_URL_PROBE_STEP DROP CONSTRAINT RHN_URLPS_URL_PROB_ID_NN;
ALTER TABLE RHN_URL_PROBE_STEP MODIFY URL_PROBE_ID NOT NULL;

--
-- RHN_URL_PROBE_STEP
--
ALTER TABLE RHN_URL_PROBE_STEP DROP CONSTRAINT RHN_URLPS_URL_STEP_NO_NN;
ALTER TABLE RHN_URL_PROBE_STEP MODIFY STEP_NUMBER NOT NULL;

--
-- RHN_URL_PROBE_STEP
--
ALTER TABLE RHN_URL_PROBE_STEP DROP CONSTRAINT RHN_URLPS_VER_LINKS_NN;
ALTER TABLE RHN_URL_PROBE_STEP MODIFY VERIFY_LINKS NOT NULL;

--
-- RHNUSERGROUPTYPE
--
ALTER TABLE RHNUSERGROUPTYPE DROP CONSTRAINT RHN_USERGROUPTYPE_CREATED_NN;
ALTER TABLE RHNUSERGROUPTYPE MODIFY CREATED NOT NULL;

--
-- RHNUSERGROUPTYPE
--
ALTER TABLE RHNUSERGROUPTYPE DROP CONSTRAINT RHN_USERGROUPTYPE_ID_NN;
ALTER TABLE RHNUSERGROUPTYPE MODIFY ID NOT NULL;

--
-- RHNUSERGROUPTYPE
--
ALTER TABLE RHNUSERGROUPTYPE DROP CONSTRAINT RHN_USERGROUPTYPE_LABEL_NN;
ALTER TABLE RHNUSERGROUPTYPE MODIFY LABEL NOT NULL;

--
-- RHNUSERGROUPTYPE
--
ALTER TABLE RHNUSERGROUPTYPE DROP CONSTRAINT RHN_USERGROUPTYPE_MODIFIED_NN;
ALTER TABLE RHNUSERGROUPTYPE MODIFY MODIFIED NOT NULL;

--
-- RHNUSERGROUPTYPE
--
ALTER TABLE RHNUSERGROUPTYPE DROP CONSTRAINT RHN_USERGROUPTYPE_NAME_NN;
ALTER TABLE RHNUSERGROUPTYPE MODIFY NAME NOT NULL;

--
-- RHNUSERGROUP
--
ALTER TABLE RHNUSERGROUP DROP CONSTRAINT RHN_USERGROUP_TYPE_CREATED_NN;
ALTER TABLE RHNUSERGROUP MODIFY CREATED NOT NULL;

--
-- RHNUSERGROUP
--
ALTER TABLE RHNUSERGROUP DROP CONSTRAINT RHN_USERGROUP_TYPE_MODIFIED_NN;
ALTER TABLE RHNUSERGROUP MODIFY MODIFIED NOT NULL;

--
-- RHNUSERGROUP
--
ALTER TABLE RHNUSERGROUP DROP CONSTRAINT RHN_USERGROUP_TYPE_NN;
ALTER TABLE RHNUSERGROUP MODIFY GROUP_TYPE NOT NULL;

--
-- RHNUSERSERVERPREFS
--
ALTER TABLE RHNUSERSERVERPREFS DROP CONSTRAINT RHN_USERSERVERPREFS_CREATED_NN;
ALTER TABLE RHNUSERSERVERPREFS MODIFY CREATED NOT NULL;

--
-- RHNUSERSERVERPREFS
--
ALTER TABLE RHNUSERSERVERPREFS DROP CONSTRAINT RHN_USERSERVERPREFS_MOD_NN;
ALTER TABLE RHNUSERSERVERPREFS MODIFY MODIFIED NOT NULL;

--
-- RHNUSERSERVERPREFS
--
ALTER TABLE RHNUSERSERVERPREFS DROP CONSTRAINT RHN_USERSERVERPREFS_NAME_NN;
ALTER TABLE RHNUSERSERVERPREFS MODIFY NAME NOT NULL;

--
-- RHNUSERSERVERPREFS
--
ALTER TABLE RHNUSERSERVERPREFS DROP CONSTRAINT RHN_USERSERVERPREFS_SID_NN;
ALTER TABLE RHNUSERSERVERPREFS MODIFY SERVER_ID NOT NULL;

--
-- RHNUSERSERVERPREFS
--
ALTER TABLE RHNUSERSERVERPREFS DROP CONSTRAINT RHN_USERSERVERPREFS_UID_NN;
ALTER TABLE RHNUSERSERVERPREFS MODIFY USER_ID NOT NULL;

--
-- RHNUSERSERVERPREFS
--
ALTER TABLE RHNUSERSERVERPREFS DROP CONSTRAINT RHN_USERSERVERPREFS_VALUE_NN;
ALTER TABLE RHNUSERSERVERPREFS MODIFY VALUE NOT NULL;

--
-- RHNUSERGROUP
--
ALTER TABLE RHNUSERGROUP DROP CONSTRAINT RHN_USER_GROUP_CM_NN;
ALTER TABLE RHNUSERGROUP MODIFY CURRENT_MEMBERS NOT NULL;

--
-- RHNUSERGROUP
--
ALTER TABLE RHNUSERGROUP DROP CONSTRAINT RHN_USER_GROUP_DESC_NN;
ALTER TABLE RHNUSERGROUP MODIFY DESCRIPTION NOT NULL;

--
-- RHNUSERGROUP
--
ALTER TABLE RHNUSERGROUP DROP CONSTRAINT RHN_USER_GROUP_ID_NN;
ALTER TABLE RHNUSERGROUP MODIFY ID NOT NULL;

--
-- RHNUSERGROUP
--
ALTER TABLE RHNUSERGROUP DROP CONSTRAINT RHN_USER_GROUP_NAME_NN;
ALTER TABLE RHNUSERGROUP MODIFY NAME NOT NULL;

--
-- RHNUSERGROUP
--
ALTER TABLE RHNUSERGROUP DROP CONSTRAINT RHN_USER_GROUP_ORG_ID_NN;
ALTER TABLE RHNUSERGROUP MODIFY ORG_ID NOT NULL;

--
-- RHNUSERINFO
--
ALTER TABLE RHNUSERINFO DROP CONSTRAINT RHN_USER_INFO_AGREED_NN;
ALTER TABLE RHNUSERINFO MODIFY AGREED_TO_TERMS NOT NULL;

--
-- RHNUSERINFO
--
ALTER TABLE RHNUSERINFO DROP CONSTRAINT RHN_USER_INFO_BADEMAIL_NN;
ALTER TABLE RHNUSERINFO MODIFY BAD_EMAIL NOT NULL;

--
-- RHNUSERINFO
--
ALTER TABLE RHNUSERINFO DROP CONSTRAINT RHN_USER_INFO_CLEARSETS_NN;
ALTER TABLE RHNUSERINFO MODIFY NO_CLEAR_SETS NOT NULL;

--
-- RHNUSERINFO
--
ALTER TABLE RHNUSERINFO DROP CONSTRAINT RHN_USER_INFO_CREATED_NN;
ALTER TABLE RHNUSERINFO MODIFY CREATED NOT NULL;

--
-- RHNUSERINFO
--
ALTER TABLE RHNUSERINFO DROP CONSTRAINT RHN_USER_INFO_MODIFIED_NN;
ALTER TABLE RHNUSERINFO MODIFY MODIFIED NOT NULL;

--
-- RHNUSERINFO
--
ALTER TABLE RHNUSERINFO DROP CONSTRAINT RHN_USER_INFO_NOTIFY_NN;
ALTER TABLE RHNUSERINFO MODIFY EMAIL_NOTIFY NOT NULL;

--
-- RHNUSERINFO
--
ALTER TABLE RHNUSERINFO DROP CONSTRAINT RHN_USER_INFO_PAGESIZE_NN;
ALTER TABLE RHNUSERINFO MODIFY PAGE_SIZE NOT NULL;

--
-- RHNUSERINFO
--
ALTER TABLE RHNUSERINFO DROP CONSTRAINT RHN_USER_INFO_PAM_NN;
ALTER TABLE RHNUSERINFO MODIFY USE_PAM_AUTHENTICATION NOT NULL;

--
-- RHNUSERINFO
--
ALTER TABLE RHNUSERINFO DROP CONSTRAINT RHN_USER_INFO_SEA_NN;
ALTER TABLE RHNUSERINFO MODIFY SHOW_APPLIED_ERRATA NOT NULL;

--
-- RHNUSERINFO
--
ALTER TABLE RHNUSERINFO DROP CONSTRAINT RHN_USER_INFO_SSGL_NN;
ALTER TABLE RHNUSERINFO MODIFY SHOW_SYSTEM_GROUP_LIST NOT NULL;

--
-- RHNUSERINFO
--
ALTER TABLE RHNUSERINFO DROP CONSTRAINT RHN_USER_INFO_TZOFFSET_NN;
ALTER TABLE RHNUSERINFO MODIFY TZ_OFFSET NOT NULL;

--
-- RHNUSERINFO
--
ALTER TABLE RHNUSERINFO DROP CONSTRAINT RHN_USER_INFO_USER_NN;
ALTER TABLE RHNUSERINFO MODIFY USER_ID NOT NULL;

--
-- RHNUSERRESERVED
--
ALTER TABLE RHNUSERRESERVED DROP CONSTRAINT RHN_USER_RES_CREATED_NN;
ALTER TABLE RHNUSERRESERVED MODIFY CREATED NOT NULL;

--
-- RHNUSERRESERVED
--
ALTER TABLE RHNUSERRESERVED DROP CONSTRAINT RHN_USER_RES_LOGIN_NN;
ALTER TABLE RHNUSERRESERVED MODIFY LOGIN NOT NULL;

--
-- RHNUSERRESERVED
--
ALTER TABLE RHNUSERRESERVED DROP CONSTRAINT RHN_USER_RES_LOGIN_UC_NN;
ALTER TABLE RHNUSERRESERVED MODIFY LOGIN_UC NOT NULL;

--
-- RHNUSERRESERVED
--
ALTER TABLE RHNUSERRESERVED DROP CONSTRAINT RHN_USER_RES_MODIFIED_NN;
ALTER TABLE RHNUSERRESERVED MODIFY MODIFIED NOT NULL;

--
-- RHNUSERRESERVED
--
ALTER TABLE RHNUSERRESERVED DROP CONSTRAINT RHN_USER_RES_PWD_NN;
ALTER TABLE RHNUSERRESERVED MODIFY PASSWORD NOT NULL;

--
-- RHNUSERSERVERGROUPPERMS
--
ALTER TABLE RHNUSERSERVERGROUPPERMS DROP CONSTRAINT RHN_USGP_CREATED_NN;
ALTER TABLE RHNUSERSERVERGROUPPERMS MODIFY CREATED NOT NULL;

--
-- RHNUSERSERVERGROUPPERMS
--
ALTER TABLE RHNUSERSERVERGROUPPERMS DROP CONSTRAINT RHN_USGP_MODIFIED_NN;
ALTER TABLE RHNUSERSERVERGROUPPERMS MODIFY MODIFIED NOT NULL;

--
-- RHNUSERSERVERGROUPPERMS
--
ALTER TABLE RHNUSERSERVERGROUPPERMS DROP CONSTRAINT RHN_USGP_SERVER_NN;
ALTER TABLE RHNUSERSERVERGROUPPERMS MODIFY SERVER_GROUP_ID NOT NULL;

--
-- RHNUSERSERVERGROUPPERMS
--
ALTER TABLE RHNUSERSERVERGROUPPERMS DROP CONSTRAINT RHN_USGP_USER_NN;
ALTER TABLE RHNUSERSERVERGROUPPERMS MODIFY USER_ID NOT NULL;

--
-- RHNUSERSERVERPERMS
--
ALTER TABLE RHNUSERSERVERPERMS DROP CONSTRAINT RHN_USPERMS_SID_NN;
ALTER TABLE RHNUSERSERVERPERMS MODIFY SERVER_ID NOT NULL;

--
-- RHNUSERSERVERPERMS
--
ALTER TABLE RHNUSERSERVERPERMS DROP CONSTRAINT RHN_USPERMS_UID_NN;
ALTER TABLE RHNUSERSERVERPERMS MODIFY USER_ID NOT NULL;

--
-- RHNUSERINFOPANE
--
ALTER TABLE RHNUSERINFOPANE DROP CONSTRAINT RHN_USR_INFO_PANE_PID_NN;
ALTER TABLE RHNUSERINFOPANE MODIFY PANE_ID NOT NULL;

--
-- RHNUSERINFOPANE
--
ALTER TABLE RHNUSERINFOPANE DROP CONSTRAINT RHN_USR_INFO_PANE_UID_NN;
ALTER TABLE RHNUSERINFOPANE MODIFY USER_ID NOT NULL;

--
-- RHNVERSIONINFO
--
ALTER TABLE RHNVERSIONINFO DROP CONSTRAINT RHN_VERSIONINFO_CREATED_NN;
ALTER TABLE RHNVERSIONINFO MODIFY CREATED NOT NULL;

--
-- RHNVERSIONINFO
--
ALTER TABLE RHNVERSIONINFO DROP CONSTRAINT RHN_VERSIONINFO_EID_NN;
ALTER TABLE RHNVERSIONINFO MODIFY EVR_ID NOT NULL;

--
-- RHNVERSIONINFO
--
ALTER TABLE RHNVERSIONINFO DROP CONSTRAINT RHN_VERSIONINFO_LABEL_NN;
ALTER TABLE RHNVERSIONINFO MODIFY LABEL NOT NULL;

--
-- RHNVERSIONINFO
--
ALTER TABLE RHNVERSIONINFO DROP CONSTRAINT RHN_VERSIONINFO_MODIFIED_NN;
ALTER TABLE RHNVERSIONINFO MODIFY MODIFIED NOT NULL;

--
-- RHNVERSIONINFO
--
ALTER TABLE RHNVERSIONINFO DROP CONSTRAINT RHN_VERSIONINFO_NID_NN;
ALTER TABLE RHNVERSIONINFO MODIFY NAME_ID NOT NULL;

--
-- RHNVIRTUALINSTANCEEVENTLOG
--
ALTER TABLE RHNVIRTUALINSTANCEEVENTLOG DROP CONSTRAINT RHN_VIEL_CREATED_NN;
ALTER TABLE RHNVIRTUALINSTANCEEVENTLOG MODIFY CREATED NOT NULL;

--
-- RHNVIRTUALINSTANCEEVENTLOG
--
ALTER TABLE RHNVIRTUALINSTANCEEVENTLOG DROP CONSTRAINT RHN_VIEL_ET_NN;
ALTER TABLE RHNVIRTUALINSTANCEEVENTLOG MODIFY EVENT_TYPE NOT NULL;

--
-- RHNVIRTUALINSTANCEEVENTLOG
--
ALTER TABLE RHNVIRTUALINSTANCEEVENTLOG DROP CONSTRAINT RHN_VIEL_ID_NN;
ALTER TABLE RHNVIRTUALINSTANCEEVENTLOG MODIFY ID NOT NULL;

--
-- RHNVIRTUALINSTANCEEVENTLOG
--
ALTER TABLE RHNVIRTUALINSTANCEEVENTLOG DROP CONSTRAINT RHN_VIEL_LT_NN;
ALTER TABLE RHNVIRTUALINSTANCEEVENTLOG MODIFY LOCAL_TIMESTAMP NOT NULL;

--
-- RHNVIRTUALINSTANCEEVENTLOG
--
ALTER TABLE RHNVIRTUALINSTANCEEVENTLOG DROP CONSTRAINT RHN_VIEL_MODIFIED_NN;
ALTER TABLE RHNVIRTUALINSTANCEEVENTLOG MODIFY MODIFIED NOT NULL;

--
-- RHNVIRTUALINSTANCEEVENTLOG
--
ALTER TABLE RHNVIRTUALINSTANCEEVENTLOG DROP CONSTRAINT RHN_VIEL_NEW_STATE_NN;
ALTER TABLE RHNVIRTUALINSTANCEEVENTLOG MODIFY NEW_STATE NOT NULL;

--
-- RHNVIRTUALINSTANCEEVENTLOG
--
ALTER TABLE RHNVIRTUALINSTANCEEVENTLOG DROP CONSTRAINT RHN_VIEL_OLD_STATE_NN;
ALTER TABLE RHNVIRTUALINSTANCEEVENTLOG MODIFY OLD_STATE NOT NULL;

--
-- RHNVIRTUALINSTANCEEVENTTYPE
--
ALTER TABLE RHNVIRTUALINSTANCEEVENTTYPE DROP CONSTRAINT RHN_VIET_CREATED_NN;
ALTER TABLE RHNVIRTUALINSTANCEEVENTTYPE MODIFY CREATED NOT NULL;

--
-- RHNVIRTUALINSTANCEEVENTTYPE
--
ALTER TABLE RHNVIRTUALINSTANCEEVENTTYPE DROP CONSTRAINT RHN_VIET_ID_NN;
ALTER TABLE RHNVIRTUALINSTANCEEVENTTYPE MODIFY ID NOT NULL;

--
-- RHNVIRTUALINSTANCEEVENTTYPE
--
ALTER TABLE RHNVIRTUALINSTANCEEVENTTYPE DROP CONSTRAINT RHN_VIET_LABEL_NN;
ALTER TABLE RHNVIRTUALINSTANCEEVENTTYPE MODIFY LABEL NOT NULL;

--
-- RHNVIRTUALINSTANCEEVENTTYPE
--
ALTER TABLE RHNVIRTUALINSTANCEEVENTTYPE DROP CONSTRAINT RHN_VIET_MODIFIED_NN;
ALTER TABLE RHNVIRTUALINSTANCEEVENTTYPE MODIFY MODIFIED NOT NULL;

--
-- RHNVIRTUALINSTANCEEVENTTYPE
--
ALTER TABLE RHNVIRTUALINSTANCEEVENTTYPE DROP CONSTRAINT RHN_VIET_NAME_NN;
ALTER TABLE RHNVIRTUALINSTANCEEVENTTYPE MODIFY NAME NOT NULL;

--
-- RHNVIRTUALINSTANCEINSTALLLOG
--
ALTER TABLE RHNVIRTUALINSTANCEINSTALLLOG DROP CONSTRAINT RHN_VIIL_CREATED_NN;
ALTER TABLE RHNVIRTUALINSTANCEINSTALLLOG MODIFY CREATED NOT NULL;

--
-- RHNVIRTUALINSTANCEINSTALLLOG
--
ALTER TABLE RHNVIRTUALINSTANCEINSTALLLOG DROP CONSTRAINT RHN_VIIL_ID_NN;
ALTER TABLE RHNVIRTUALINSTANCEINSTALLLOG MODIFY ID NOT NULL;

--
-- RHNVIRTUALINSTANCEINSTALLLOG
--
ALTER TABLE RHNVIRTUALINSTANCEINSTALLLOG DROP CONSTRAINT RHN_VIIL_LM_NN;
ALTER TABLE RHNVIRTUALINSTANCEINSTALLLOG MODIFY LOG_MESSAGE NOT NULL;

--
-- RHNVIRTUALINSTANCEINSTALLLOG
--
ALTER TABLE RHNVIRTUALINSTANCEINSTALLLOG DROP CONSTRAINT RHN_VIIL_MODIFIED_NN;
ALTER TABLE RHNVIRTUALINSTANCEINSTALLLOG MODIFY MODIFIED NOT NULL;

--
-- RHNVIRTUALINSTANCEINFO
--
ALTER TABLE RHNVIRTUALINSTANCEINFO DROP CONSTRAINT RHN_VII_CREATED_NN;
ALTER TABLE RHNVIRTUALINSTANCEINFO MODIFY CREATED NOT NULL;

--
-- RHNVIRTUALINSTANCEINFO
--
ALTER TABLE RHNVIRTUALINSTANCEINFO DROP CONSTRAINT RHN_VII_IT_NN;
ALTER TABLE RHNVIRTUALINSTANCEINFO MODIFY INSTANCE_TYPE NOT NULL;

--
-- RHNVIRTUALINSTANCEINFO
--
ALTER TABLE RHNVIRTUALINSTANCEINFO DROP CONSTRAINT RHN_VII_MODIFIED_NN;
ALTER TABLE RHNVIRTUALINSTANCEINFO MODIFY MODIFIED NOT NULL;

--
-- RHNVIRTUALINSTANCEINFO
--
ALTER TABLE RHNVIRTUALINSTANCEINFO DROP CONSTRAINT RHN_VII_STATE_NN;
ALTER TABLE RHNVIRTUALINSTANCEINFO MODIFY STATE NOT NULL;

--
-- RHNVIRTUALINSTANCEINFO
--
ALTER TABLE RHNVIRTUALINSTANCEINFO DROP CONSTRAINT RHN_VII_VIID_NN;
ALTER TABLE RHNVIRTUALINSTANCEINFO MODIFY INSTANCE_ID NOT NULL;

--
-- RHNVIRTUALINSTANCESTATE
--
ALTER TABLE RHNVIRTUALINSTANCESTATE DROP CONSTRAINT RHN_VIS_CREATED_NN;
ALTER TABLE RHNVIRTUALINSTANCESTATE MODIFY CREATED NOT NULL;

--
-- RHNVIRTUALINSTANCESTATE
--
ALTER TABLE RHNVIRTUALINSTANCESTATE DROP CONSTRAINT RHN_VIS_ID_NN;
ALTER TABLE RHNVIRTUALINSTANCESTATE MODIFY ID NOT NULL;

--
-- RHNVIRTUALINSTANCESTATE
--
ALTER TABLE RHNVIRTUALINSTANCESTATE DROP CONSTRAINT RHN_VIS_LABEL_NN;
ALTER TABLE RHNVIRTUALINSTANCESTATE MODIFY LABEL NOT NULL;

--
-- RHNVIRTUALINSTANCESTATE
--
ALTER TABLE RHNVIRTUALINSTANCESTATE DROP CONSTRAINT RHN_VIS_MODIFIED_NN;
ALTER TABLE RHNVIRTUALINSTANCESTATE MODIFY MODIFIED NOT NULL;

--
-- RHNVIRTUALINSTANCESTATE
--
ALTER TABLE RHNVIRTUALINSTANCESTATE DROP CONSTRAINT RHN_VIS_NAME_NN;
ALTER TABLE RHNVIRTUALINSTANCESTATE MODIFY NAME NOT NULL;

--
-- RHNVIRTUALINSTANCETYPE
--
ALTER TABLE RHNVIRTUALINSTANCETYPE DROP CONSTRAINT RHN_VIT_CREATED_NN;
ALTER TABLE RHNVIRTUALINSTANCETYPE MODIFY CREATED NOT NULL;

--
-- RHNVIRTUALINSTANCETYPE
--
ALTER TABLE RHNVIRTUALINSTANCETYPE DROP CONSTRAINT RHN_VIT_ID_NN;
ALTER TABLE RHNVIRTUALINSTANCETYPE MODIFY ID NOT NULL;

--
-- RHNVIRTUALINSTANCETYPE
--
ALTER TABLE RHNVIRTUALINSTANCETYPE DROP CONSTRAINT RHN_VIT_LABEL_NN;
ALTER TABLE RHNVIRTUALINSTANCETYPE MODIFY LABEL NOT NULL;

--
-- RHNVIRTUALINSTANCETYPE
--
ALTER TABLE RHNVIRTUALINSTANCETYPE DROP CONSTRAINT RHN_VIT_MODIFIED_NN;
ALTER TABLE RHNVIRTUALINSTANCETYPE MODIFY MODIFIED NOT NULL;

--
-- RHNVIRTUALINSTANCETYPE
--
ALTER TABLE RHNVIRTUALINSTANCETYPE DROP CONSTRAINT RHN_VIT_NAME_NN;
ALTER TABLE RHNVIRTUALINSTANCETYPE MODIFY NAME NOT NULL;

--
-- RHNVIRTUALINSTANCE
--
ALTER TABLE RHNVIRTUALINSTANCE DROP CONSTRAINT RHN_VI_CREATED_NN;
ALTER TABLE RHNVIRTUALINSTANCE MODIFY CREATED NOT NULL;

--
-- RHNVIRTUALINSTANCE
--
ALTER TABLE RHNVIRTUALINSTANCE DROP CONSTRAINT RHN_VI_C_NN;
ALTER TABLE RHNVIRTUALINSTANCE MODIFY CONFIRMED NOT NULL;

--
-- RHNVIRTUALINSTANCE
--
ALTER TABLE RHNVIRTUALINSTANCE DROP CONSTRAINT RHN_VI_ID_NN;
ALTER TABLE RHNVIRTUALINSTANCE MODIFY ID NOT NULL;

--
-- RHNVIRTUALINSTANCE
--
ALTER TABLE RHNVIRTUALINSTANCE DROP CONSTRAINT RHN_VI_MODIFIED_NN;
ALTER TABLE RHNVIRTUALINSTANCE MODIFY MODIFIED NOT NULL;

--
-- RHNVIRTSUBLEVEL
--
ALTER TABLE RHNVIRTSUBLEVEL DROP CONSTRAINT RHN_VSL_CREATED_NN;
ALTER TABLE RHNVIRTSUBLEVEL MODIFY CREATED NOT NULL;

--
-- RHNVIRTSUBLEVEL
--
ALTER TABLE RHNVIRTSUBLEVEL DROP CONSTRAINT RHN_VSL_LABEL_NN;
ALTER TABLE RHNVIRTSUBLEVEL MODIFY LABEL NOT NULL;

--
-- RHNVIRTSUBLEVEL
--
ALTER TABLE RHNVIRTSUBLEVEL DROP CONSTRAINT RHN_VSL_MODIFIED_NN;
ALTER TABLE RHNVIRTSUBLEVEL MODIFY MODIFIED NOT NULL;

--
-- RHNVIRTSUBLEVEL
--
ALTER TABLE RHNVIRTSUBLEVEL DROP CONSTRAINT RHN_VSL_NAME_NN;
ALTER TABLE RHNVIRTSUBLEVEL MODIFY NAME NOT NULL;

--
-- RHNWEBCONTACTCHANGELOG
--
ALTER TABLE RHNWEBCONTACTCHANGELOG DROP CONSTRAINT RHN_WCON_CL_CHANGE_SID_NN;
ALTER TABLE RHNWEBCONTACTCHANGELOG MODIFY CHANGE_STATE_ID NOT NULL;

--
-- RHNWEBCONTACTCHANGELOG
--
ALTER TABLE RHNWEBCONTACTCHANGELOG DROP CONSTRAINT RHN_WCON_CL_MODIFIED_NN;
ALTER TABLE RHNWEBCONTACTCHANGELOG MODIFY DATE_COMPLETED NOT NULL;

--
-- RHNWEBCONTACTCHANGELOG
--
ALTER TABLE RHNWEBCONTACTCHANGELOG DROP CONSTRAINT RHN_WCON_CL_WCON_ID_NN;
ALTER TABLE RHNWEBCONTACTCHANGELOG MODIFY WEB_CONTACT_ID NOT NULL;

--
-- RHN_WIDGET
--
ALTER TABLE RHN_WIDGET DROP CONSTRAINT RHN_WDGET_DESC_NN;
ALTER TABLE RHN_WIDGET MODIFY DESCRIPTION NOT NULL;

--
-- RHN_WIDGET
--
ALTER TABLE RHN_WIDGET DROP CONSTRAINT RHN_WDGET_NAME_NN;
ALTER TABLE RHN_WIDGET MODIFY NAME NOT NULL;

--
-- STATE_CHANGE
--
ALTER TABLE STATE_CHANGE DROP CONSTRAINT STATE_CHANGE_ETIME_NN;
ALTER TABLE STATE_CHANGE MODIFY ENTRY_TIME NOT NULL;

--
-- STATE_CHANGE
--
ALTER TABLE STATE_CHANGE DROP CONSTRAINT STATE_CHANGE_O_ID_NN;
ALTER TABLE STATE_CHANGE MODIFY O_ID NOT NULL;

--
-- TIME_SERIES
--
ALTER TABLE TIME_SERIES DROP CONSTRAINT TIME_SERIES_ETIME_NN;
ALTER TABLE TIME_SERIES MODIFY ENTRY_TIME NOT NULL;

--
-- TIME_SERIES
--
ALTER TABLE TIME_SERIES DROP CONSTRAINT TIME_SERIES_O_ID_NN;
ALTER TABLE TIME_SERIES MODIFY O_ID NOT NULL;

--
-- WEB_CONTACT
--
ALTER TABLE WEB_CONTACT DROP CONSTRAINT WEB_CONTACT_CREATED_NN;
ALTER TABLE WEB_CONTACT MODIFY CREATED NOT NULL;

--
-- WEB_CONTACT
--
ALTER TABLE WEB_CONTACT DROP CONSTRAINT WEB_CONTACT_IGNORE_NN;
ALTER TABLE WEB_CONTACT MODIFY IGNORE_FLAG NOT NULL;

--
-- WEB_CONTACT
--
ALTER TABLE WEB_CONTACT DROP CONSTRAINT WEB_CONTACT_LOGIN_NN;
ALTER TABLE WEB_CONTACT MODIFY LOGIN NOT NULL;

--
-- WEB_CONTACT
--
ALTER TABLE WEB_CONTACT DROP CONSTRAINT WEB_CONTACT_LOGIN_UC_NN;
ALTER TABLE WEB_CONTACT MODIFY LOGIN_UC NOT NULL;

--
-- WEB_CONTACT
--
ALTER TABLE WEB_CONTACT DROP CONSTRAINT WEB_CONTACT_MODIFIED_NN;
ALTER TABLE WEB_CONTACT MODIFY MODIFIED NOT NULL;

--
-- WEB_CONTACT
--
ALTER TABLE WEB_CONTACT DROP CONSTRAINT WEB_CONTACT_ORG_NN;
ALTER TABLE WEB_CONTACT MODIFY ORG_ID NOT NULL;

--
-- WEB_CONTACT
--
ALTER TABLE WEB_CONTACT DROP CONSTRAINT WEB_CONTACT_PASSWORD_NN;
ALTER TABLE WEB_CONTACT MODIFY PASSWORD NOT NULL;

--
-- WEB_CUSTOMER
--
ALTER TABLE WEB_CUSTOMER DROP CONSTRAINT WEB_CUSTOMER_CREATED_NN;
ALTER TABLE WEB_CUSTOMER MODIFY CREATED NOT NULL;

--
-- WEB_CUSTOMER
--
ALTER TABLE WEB_CUSTOMER DROP CONSTRAINT WEB_CUSTOMER_ID_NN;
ALTER TABLE WEB_CUSTOMER MODIFY ID NOT NULL;

--
-- WEB_CUSTOMER
--
ALTER TABLE WEB_CUSTOMER DROP CONSTRAINT WEB_CUSTOMER_MODIFIED_NN;
ALTER TABLE WEB_CUSTOMER MODIFY MODIFIED NOT NULL;

--
-- WEB_CUSTOMER
--
ALTER TABLE WEB_CUSTOMER DROP CONSTRAINT WEB_CUSTOMER_NAME_NN;
ALTER TABLE WEB_CUSTOMER MODIFY NAME NOT NULL;

--
-- WEB_CUSTOMER
--
ALTER TABLE WEB_CUSTOMER DROP CONSTRAINT WEB_CUSTOMER_TYPE_NN;
ALTER TABLE WEB_CUSTOMER MODIFY CUSTOMER_TYPE NOT NULL;

--
-- WEB_CUSTOMER_NOTIFICATION
--
ALTER TABLE WEB_CUSTOMER_NOTIFICATION DROP CONSTRAINT WEB_CUST_NOT_CREAT_NN;
ALTER TABLE WEB_CUSTOMER_NOTIFICATION MODIFY CREATION_DATE NOT NULL;

--
-- WEB_CUSTOMER_NOTIFICATION
--
ALTER TABLE WEB_CUSTOMER_NOTIFICATION DROP CONSTRAINT WEB_CUST_NOT_EA_NN;
ALTER TABLE WEB_CUSTOMER_NOTIFICATION MODIFY CONTACT_EMAIL_ADDRESS NOT NULL;

--
-- WEB_CUSTOMER_NOTIFICATION
--
ALTER TABLE WEB_CUSTOMER_NOTIFICATION DROP CONSTRAINT WEB_CUST_NOT_ID_NN;
ALTER TABLE WEB_CUSTOMER_NOTIFICATION MODIFY ID NOT NULL;

--
-- WEB_CUSTOMER_NOTIFICATION
--
ALTER TABLE WEB_CUSTOMER_NOTIFICATION DROP CONSTRAINT WEB_CUST_NOT_OID_NN;
ALTER TABLE WEB_CUSTOMER_NOTIFICATION MODIFY ORG_ID NOT NULL;

--
-- WEB_USER_CONTACT_PERMISSION
--
ALTER TABLE WEB_USER_CONTACT_PERMISSION DROP CONSTRAINT WUCP_CREATED_NN;
ALTER TABLE WEB_USER_CONTACT_PERMISSION MODIFY CREATED NOT NULL;

--
-- WEB_USER_CONTACT_PERMISSION
--
ALTER TABLE WEB_USER_CONTACT_PERMISSION DROP CONSTRAINT WUCP_MODIFIED_NN;
ALTER TABLE WEB_USER_CONTACT_PERMISSION MODIFY MODIFIED NOT NULL;

--
-- WEB_USER_CONTACT_PERMISSION
--
ALTER TABLE WEB_USER_CONTACT_PERMISSION DROP CONSTRAINT WUCP_WUID_NN;
ALTER TABLE WEB_USER_CONTACT_PERMISSION MODIFY WEB_USER_ID NOT NULL;

--
-- WEB_USER_PERSONAL_INFO
--
ALTER TABLE WEB_USER_PERSONAL_INFO DROP CONSTRAINT WUPI_CREATED_NN;
ALTER TABLE WEB_USER_PERSONAL_INFO MODIFY CREATED NOT NULL;

--
-- WEB_USER_PERSONAL_INFO
--
ALTER TABLE WEB_USER_PERSONAL_INFO DROP CONSTRAINT WUPI_FN_NN;
ALTER TABLE WEB_USER_PERSONAL_INFO MODIFY FIRST_NAMES NOT NULL;

--
-- WEB_USER_PERSONAL_INFO
--
ALTER TABLE WEB_USER_PERSONAL_INFO DROP CONSTRAINT WUPI_LN_NN;
ALTER TABLE WEB_USER_PERSONAL_INFO MODIFY LAST_NAME NOT NULL;

--
-- WEB_USER_PERSONAL_INFO
--
ALTER TABLE WEB_USER_PERSONAL_INFO DROP CONSTRAINT WUPI_MODIFIED_NN;
ALTER TABLE WEB_USER_PERSONAL_INFO MODIFY MODIFIED NOT NULL;

--
-- WEB_USER_PERSONAL_INFO
--
ALTER TABLE WEB_USER_PERSONAL_INFO DROP CONSTRAINT WUPI_PREFIX_NN;
ALTER TABLE WEB_USER_PERSONAL_INFO MODIFY PREFIX NOT NULL;

--
-- WEB_USER_PERSONAL_INFO
--
ALTER TABLE WEB_USER_PERSONAL_INFO DROP CONSTRAINT WUPI_WUID_NN;
ALTER TABLE WEB_USER_PERSONAL_INFO MODIFY WEB_USER_ID NOT NULL;

--
-- WEB_USER_PREFIX
--
ALTER TABLE WEB_USER_PREFIX DROP CONSTRAINT WUP_TEXT_NN;
ALTER TABLE WEB_USER_PREFIX MODIFY TEXT NOT NULL;

--
-- WEB_USER_SITE_INFO
--
ALTER TABLE WEB_USER_SITE_INFO DROP CONSTRAINT WUSI_ADDR1_NN;
ALTER TABLE WEB_USER_SITE_INFO MODIFY ADDRESS1 NOT NULL;

--
-- WEB_USER_SITE_INFO
--
ALTER TABLE WEB_USER_SITE_INFO DROP CONSTRAINT WUSI_CITY_NN;
ALTER TABLE WEB_USER_SITE_INFO MODIFY CITY NOT NULL;

--
-- WEB_USER_SITE_INFO
--
ALTER TABLE WEB_USER_SITE_INFO DROP CONSTRAINT WUSI_COUNTRY_NN;
ALTER TABLE WEB_USER_SITE_INFO MODIFY COUNTRY NOT NULL;

--
-- WEB_USER_SITE_INFO
--
ALTER TABLE WEB_USER_SITE_INFO DROP CONSTRAINT WUSI_ID_NN;
ALTER TABLE WEB_USER_SITE_INFO MODIFY ID NOT NULL;

--
-- WEB_USER_SITE_TYPE
--
ALTER TABLE WEB_USER_SITE_TYPE DROP CONSTRAINT WUST_DESC_NN;
ALTER TABLE WEB_USER_SITE_TYPE MODIFY DESCRIPTION NOT NULL;

--
-- WEB_USER_SITE_TYPE
--
ALTER TABLE WEB_USER_SITE_TYPE DROP CONSTRAINT WUST_TYPE_NN;
ALTER TABLE WEB_USER_SITE_TYPE MODIFY TYPE NOT NULL;

--
-- RHNCHECKSUMTYPE
--
ALTER TABLE RHNCHECKSUMTYPE DROP CONSTRAINT RHN_CHECKSUMTYPE_ID_NN;
ALTER TABLE RHNCHECKSUMTYPE MODIFY ID NOT NULL;
ALTER TABLE RHNCHECKSUMTYPE DROP CONSTRAINT RHN_CHECKSUMTYPE_LABEL_NN;
ALTER TABLE RHNCHECKSUMTYPE MODIFY LABEL NOT NULL;
ALTER TABLE RHNCHECKSUMTYPE DROP CONSTRAINT RHN_CHECKSUMTYPE_DESC_NN;
ALTER TABLE RHNCHECKSUMTYPE MODIFY DESCRIPTION NOT NULL;
ALTER TABLE RHNCHECKSUMTYPE DROP CONSTRAINT RHN_CHECKSUMTYPE_CREAT_NN;
ALTER TABLE RHNCHECKSUMTYPE MODIFY CREATED NOT NULL;
ALTER TABLE RHNCHECKSUMTYPE DROP CONSTRAINT RHN_CHECKSUMTYPE_MOD_NN;
ALTER TABLE RHNCHECKSUMTYPE MODIFY MODIFIED NOT NULL;

  070701000004FD000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000004800000000susemanager-schema/upgrade/spacewalk-schema-0.6-to-spacewalk-schema-0.7   070701000004FE000081B400000000000000000000000167AE111400000205000000000000000000000000000000000000007800000000susemanager-schema/upgrade/spacewalk-schema-0.6-to-spacewalk-schema-0.7/002-rhn_db_environment-rhn_environment-drop.sql   alter table rhn_config_macro drop constraint rhn_confm_envir_environment_fk;
alter table rhn_config_macro drop primary key;
drop index rhn_confm_environment_name_pk;

create unique index rhn_confm_name_pk
    on rhn_config_macro (name) 
    tablespace [[2m_tbs]];
alter table rhn_config_macro add constraint rhn_confm_name_pk primary key (name);

alter table rhn_config_macro drop column environment;

drop table rhn_db_environment;
drop table rhn_environment;

drop synonym db_environment;
drop synonym environment;
   070701000004FF000081B400000000000000000000000167AE11140000013A000000000000000000000000000000000000006800000000susemanager-schema/upgrade/spacewalk-schema-0.6-to-spacewalk-schema-0.7/003-rhnKickstartCommandName.sql   insert into rhnKickstartCommandName
    select rhn_kscommandname_id_seq.nextval as id,
          'custom_partition' as name,
          'Y' as uses_arguments,
           53 as sort_order, 'N' as required
    from dual
    where NOT EXISTS (select id from rhnKickstartCommandName where name = 'custom_partition');


  07070100000500000081B400000000000000000000000167AE111400000031000000000000000000000000000000000000006B00000000susemanager-schema/upgrade/spacewalk-schema-0.6-to-spacewalk-schema-0.7/004-1-rhnServerPackage_created.sql    ALTER TABLE rhnServerPackage
 ADD created DATE;

   07070100000501000081B400000000000000000000000167AE1114000000C0000000000000000000000000000000000000007000000000susemanager-schema/upgrade/spacewalk-schema-0.6-to-spacewalk-schema-0.7/004-2-rhnServerPackage_created-data.sql   begin
  loop
    update rhnServerPackage
       set created = sysdate
     where created is null and rownum <= 1000000;
  exit when sql%rowcount = 0;
    commit;
  end loop;
  commit;
end;
/

07070100000502000081B400000000000000000000000167AE11140000004F000000000000000000000000000000000000007400000000susemanager-schema/upgrade/spacewalk-schema-0.6-to-spacewalk-schema-0.7/004-3-rhnServerPackage_created-not-null.sql   ALTER TABLE rhnServerPackage
 MODIFY created DATE DEFAULT (sysdate) NOT NULL;

 07070100000503000081B400000000000000000000000167AE111400000035000000000000000000000000000000000000006B00000000susemanager-schema/upgrade/spacewalk-schema-0.6-to-spacewalk-schema-0.7/005-rhnServerPackage_installed.sql    ALTER TABLE rhnServerPackage
 ADD installtime DATE;

   07070100000504000081B400000000000000000000000167AE11140000007A000000000000000000000000000000000000006B00000000susemanager-schema/upgrade/spacewalk-schema-0.6-to-spacewalk-schema-0.7/150-rhnConfigFileType_symlinks.sql    --
-- Add in an entry for symlinks
--

insert into rhnConfigFileType values (3, 'symlink', 'Symlink', sysdate, sysdate);

  07070100000505000081B400000000000000000000000167AE111400000C03000000000000000000000000000000000000006200000000susemanager-schema/upgrade/spacewalk-schema-0.6-to-spacewalk-schema-0.7/151-rhnServerOverview.sql --
-- Add in config_files_with_differences
--

create or replace view
rhnServerOverview
(
    org_id,
    server_id,
    server_name,
    note_count,
    modified,
    server_admins,
    group_count,
    channel_id,
    channel_labels,
    history_count,
    security_errata,
    bug_errata,
    enhancement_errata,
    outdated_packages,
    config_files_with_differences,
    last_checkin_days_ago,
    last_checkin,
    pending_updates,
    os,
    release,
    server_arch_name,
    locked
)
as
select
    s.org_id, s.id, s.name, 0, s.modified,
    ( select count(user_id) from rhnUserServerPerms ap
      where server_id = s.id ),
    ( select count(server_group_id) from rhnVisibleServerGroupMembers
      where server_id = s.id ),
    ( select C.id
        from rhnChannel C,
	     rhnServerChannel SC
       where SC.server_id = S.id
         and SC.channel_id = C.id
	 and C.parent_channel IS NULL),
    NVL(( select C.name
        from rhnChannel C,
	     rhnServerChannel SC
       where SC.server_id = S.id
         and SC.channel_id = C.id
	 and C.parent_channel IS NULL), '(none)'),
    ( select count(id) from rhnServerHistory
      where
            server_id = S.id),
    ( select count(*) from rhnServerErrataTypeView setv
      where
            setv.server_id = s.id
        and setv.errata_type = 'Security Advisory'),
    ( select count(*) from rhnServerErrataTypeView setv
      where
            setv.server_id = s.id
        and setv.errata_type = 'Bug Fix Advisory'),
    ( select count(*) from rhnServerErrataTypeView setv
      where
            setv.server_id = s.id
        and setv.errata_type = 'Product Enhancement Advisory'),
    ( select count(distinct p.name_id) from rhnPackage p, rhnServerNeededPackageCache snpc
      where
             snpc.server_id = S.id
	 and p.id = snpc.package_id
	 ),
    ( select count(*)
        from rhnActionConfigRevision ACR
             INNER JOIN rhnActionConfigRevisionResult ACRR on ACR.id = ACRR.action_config_revision_id
       where ACR.server_id = S.id
         and ACR.action_id = (
              select MAX(rA.id)
                from rhnAction rA
                     INNER JOIN rhnServerAction rSA on rSA.action_id = rA.id
                     INNER JOIN rhnActionStatus rAS on rAS.id = rSA.status
                     INNER JOIN rhnActionType rAT on rAT.id = rA.action_type
               where rSA.server_id = S.id
                 and rAS.name in ('Completed', 'Failed')
                 and rAT.label = 'configfiles.diff'
         )
         and ACR.failure_id is null
         and ACRR.result is not null
        ),
    ( select sysdate - checkin from rhnServerInfo where server_id = S.id ),
    ( select TO_CHAR(checkin, 'YYYY-MM-DD HH24:MI:SS') from rhnServerInfo where server_id = S.id ),
    ( select count(1)
        from rhnServerAction
       where server_id = S.id
         and status in (0, 1)),
    os,
    release,
    ( select name from rhnServerArch where id = s.server_arch_id),
    NVL((select 1 from rhnServerLock SL WHERE SL.server_id = S.id), 0)
from
    rhnServer S
/

 07070100000506000081B400000000000000000000000167AE111400000ED1000000000000000000000000000000000000005E00000000susemanager-schema/upgrade/spacewalk-schema-0.6-to-spacewalk-schema-0.7/160-rhn_cache.pkb.sql --
-- Copyright (c) 2008 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--
--
--
--

create or replace package body
rhn_cache
is
	body_version varchar2(100) := '';

	-- this searches out all users who get perms...
	procedure update_perms_for_server(
		server_id_in in number
	) is
	begin
                -- delete rows which are no more valid
		delete from rhnUserServerPerms p
                      where server_id = server_id_in
                        and user_id not in (select user_id
                                              from rhnUserServerPermsDupes d
                                             where p.server_id = d.server_id);
                -- insert newly added rows
		insert into rhnUserServerPerms(user_id, server_id) (
			select distinct user_id, server_id_in
				   from	rhnUserServerPermsDupes d
                                  where server_id = server_id_in
                                    and user_id not in (
                                                select user_id
                                                  from rhnUserServerPerms p
                                                 where p.server_id = d.server_id)
			);
	end update_perms_for_server;

        -- update rhnUserServerPerms cache from rhnUserServerPermsDupes
	procedure update_perms_for_user(
		user_id_in in number
	) is
	begin
                -- first delete rows which are not in rhnUserServerPermsDupes
                delete from rhnUserServerPerms up
                 where user_id = user_id_in
                   and not exists (
                       select 1
                         from rhnUserServerPermsDupes uspd
                        where uspd.user_id = up.user_id
                          and uspd.server_id = up.server_id);

                -- then insert rest of rows from rhnUserServerPermsDupes
                insert into rhnUserServerPerms (user_id, server_id)
                       select distinct user_id_in, server_id
                         from rhnUserServerPermsDupes uspd
                        where uspd.user_id = user_id_in
                          and not exists (
                              select 1
                                from rhnUserServerPerms usp
                               where usp.user_id = user_id_in
                                 and usp.server_id = uspd.server_id);
	end update_perms_for_user;

	-- this means a server got added or removed, so we
	-- can't key off of a server anywhere.
	procedure update_perms_for_server_group(
		server_group_id_in in number
	) is
		cursor users is
			-- org admins aren't affected, so don't test for them
			select	usgp.user_id id
			from	rhnUserServerGroupPerms usgp
			where	usgp.server_group_id = server_group_id_in
				and not exists (
					select	1
					from	rhnUserGroup ug,
							rhnUserGroupMembers ugm,
							rhnServerGroup sg,
							rhnUserGroupType ugt
					where	ugt.label = 'org_admin'
						and ugt.id = ug.group_type
						and sg.id = server_group_id_in
						and ugm.user_id = usgp.user_id
						and ug.org_id = sg.org_id
						and ugm.user_group_id = ug.id
					);
	begin
		for u in users loop
			update_perms_for_user(u.id);
		end loop;
	end update_perms_for_server_group;
end rhn_cache;
/
show errors
   07070100000507000081B400000000000000000000000167AE1114000053E2000000000000000000000000000000000000005F00000000susemanager-schema/upgrade/spacewalk-schema-0.6-to-spacewalk-schema-0.7/161-rhn_server.pkb.sql    --
-- Copyright (c) 2008 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--

create or replace
package body rhn_server
is
    function system_service_level(
    	server_id_in in number,
	service_level_in in varchar2
    ) return number is

    cursor ents is 
      select label from rhnServerEntitlementView
      where server_id = server_id_in;

    retval number := 0;

    begin
         for ent in ents loop
            retval := rhn_entitlements.entitlement_grants_service (ent.label, service_level_in);
            if retval = 1 then
               return retval;
            end if;
         end loop;

         return retval;

    end system_service_level;

        
    function can_change_base_channel(server_id_in IN NUMBER)
    return number
    is
    	throwaway number;
    begin
    	-- the idea: if we get past this query, the server is
	-- neither sat nor proxy, so base channel is changeable
	
	select 1 into throwaway
	  from rhnServer S
	 where S.id = server_id_in
	   and not exists (select 1 from rhnSatelliteInfo SI where SI.server_id = S.id)
	   and not exists (select 1 from rhnProxyInfo PI where PI.server_id = S.id);
	   
	return 1;
    exception
    	when no_data_found
	    then
	    return 0;
    end can_change_base_channel;
	        
    procedure set_custom_value(
    	server_id_in in number,
	user_id_in in number,
	key_label_in in varchar2,
	value_in in varchar2
    ) is
    	key_id_val number;
    begin
    	select CDK.id into key_id_val
	  from rhnCustomDataKey CDK,
	       rhnServer S
	 where S.id = server_id_in
	   and S.org_id = CDK.org_id
	   and CDK.label = key_label_in;
	   
	begin
	    insert into rhnServerCustomDataValue (server_id, key_id, value, created_by, last_modified_by)
	    values (server_id_in, key_id_val, value_in, user_id_in, user_id_in);
	exception
	    when DUP_VAL_ON_INDEX
	    	then
		update rhnServerCustomDataValue
		   set value = value_in,
		       last_modified_by = user_id_in
		 where server_id = server_id_in
		   and key_id = key_id_val;		   
	end;
	
    end set_custom_value;
    
    function bulk_set_custom_value(
    	key_label_in in varchar2,
	value_in in varchar2,
	set_label_in in varchar2,
	set_uid_in in number
    )
    return integer
    is
    i integer := 0;
    begin
        i := 0;
    	for server in rhn_set.set_iterator(set_label_in, set_uid_in)
	loop
	    if rhn_server.system_service_level(server.element, 'provisioning') = 1 then
	    	rhn_server.set_custom_value(server.element, set_uid_in, key_label_in, value_in);
            i := i + 1;
	    end if;
	end loop server;
    return i;
    end bulk_set_custom_value;

    procedure bulk_snapshot_tag(
    	org_id_in in number,
        tagname_in in varchar2,
	set_label_in in varchar2,
	set_uid_in in number
    ) is
    	snapshot_id number;
    begin
    	for server in rhn_set.set_iterator(set_label_in, set_uid_in)
	loop
	    if rhn_server.system_service_level(server.element, 'provisioning') = 1 then
	    	begin
	    	    select max(id) into snapshot_id
	    	    from rhnSnapshot
	    	    where server_id = server.element;
	    	exception
	    	    when NO_DATA_FOUND then
		    	rhn_server.snapshot_server(server.element, 'tagging system:  ' || tagname_in);
			
			select max(id) into snapshot_id
			from rhnSnapshot
			where server_id = server.element;
		end;
		 
		-- now have a snapshot_id to work with...
		begin
		    rhn_server.tag_snapshot(snapshot_id, org_id_in, tagname_in);
		exception
		    when DUP_VAL_ON_INDEX
		    	then
			-- do nothing, be forgiving...
			null;
		end;
	    end if;
	end loop server;    
    end bulk_snapshot_tag;

    procedure tag_delete(
    	server_id_in in number,
	tag_id_in in number
    ) is
    	cursor snapshots is
		select	snapshot_id
		from	rhnSnapshotTag
		where	tag_id = tag_id_in;
	tag_id_tmp number;
    begin
    	select	id into tag_id_tmp
	from	rhnTag
	where	id = tag_id_in
	for update;

	delete
		from	rhnSnapshotTag
		where	server_id = server_id_in
			and tag_id = tag_id_in;
	for snapshot in snapshots loop
		return;
	end loop;
	delete
		from rhnTag
		where id = tag_id_in;
    end tag_delete;

    procedure tag_snapshot(
        snapshot_id_in in number,
	org_id_in in number,
	tagname_in in varchar2
    ) is
    begin
    	insert into rhnSnapshotTag (snapshot_id, server_id, tag_id)
	select snapshot_id_in, server_id, lookup_tag(org_id_in, tagname_in)
	from rhnSnapshot
	where id = snapshot_id_in;
    end tag_snapshot;

    procedure bulk_snapshot(
    	reason_in in varchar2,
	set_label_in in varchar2,
	set_uid_in in number
    ) is
    begin
    	for server in rhn_set.set_iterator(set_label_in, set_uid_in)
	loop
    	    if rhn_server.system_service_level(server.element, 'provisioning') = 1 then
	    	rhn_server.snapshot_server(server.element, reason_in);
	    end if;
	end loop server;
    end bulk_snapshot;

    procedure snapshot_server(
    	server_id_in in number,
	reason_in in varchar2
    ) is
    	snapshot_id number;
	cursor revisions is
		select distinct
			cr.id
		from	rhnConfigRevision	cr,
			rhnConfigFileName	cfn,
			rhnConfigFile		cf,
			rhnConfigChannel	cc,
			rhnServerConfigChannel	scc
		where	1=1
			and scc.server_id = server_id_in
			and scc.config_channel_id = cc.id
			and cc.id = cf.config_channel_id
			and cf.id = cr.config_file_id
			and cr.id = cf.latest_config_revision_id
			and cf.config_file_name_id = cfn.id
			and cf.id = lookup_first_matching_cf(scc.server_id, cfn.path);
	locked integer;
    begin
    	select rhn_snapshot_id_seq.nextval into snapshot_id from dual;

	insert into rhnSnapshot (id, org_id, server_id, reason) (
		select	snapshot_id,
			s.org_id,
			server_id_in,
			reason_in
		from	rhnServer s
		where	s.id = server_id_in
	);
	insert into rhnSnapshotChannel (snapshot_id, channel_id) (
		select	snapshot_id, sc.channel_id
		from	rhnServerChannel sc
		where	sc.server_id = server_id_in
	);
	insert into rhnSnapshotServerGroup (snapshot_id, server_group_id) (
		select	snapshot_id, sgm.server_group_id
		from	rhnServerGroupMembers sgm
		where	sgm.server_id = server_id_in
	);
        locked := 0;
        while true loop
            begin
                insert into rhnPackageNEVRA (id, name_id, evr_id, package_arch_id)
                select rhn_pkgnevra_id_seq.nextval, sp.name_id, sp.evr_id, sp.package_arch_id
                from rhnServerPackage sp
                where sp.server_id = server_id_in
                        and not exists
                        (select 1
                                from rhnPackageNEVRA nevra
                                where nevra.name_id = sp.name_id
                                        and nevra.evr_id = sp.evr_id
                                        and (nevra.package_arch_id = sp.package_arch_id
                                            or (nevra.package_arch_id is null
                                                and sp.package_arch_id is null)));
                exit;
            exception when dup_val_on_index then
                if locked = 1 then
                    raise;
                else
                    lock table rhnPackageNEVRA in exclusive mode;
                    locked := 1;
                end if;
            end;
        end loop;
	insert into rhnSnapshotPackage (snapshot_id, nevra_id) (
                select distinct snapshot_id, nevra.id
                from    rhnServerPackage sp, rhnPackageNEVRA nevra
                where   sp.server_id = server_id_in
                        and nevra.name_id = sp.name_id
                        and nevra.evr_id = sp.evr_id
                        and (nevra.package_arch_id = sp.package_arch_id
                            or (nevra.package_arch_id is null
                                and sp.package_arch_id is null))
	);

	insert into rhnSnapshotConfigChannel ( snapshot_id, config_channel_id ) (
		select	snapshot_id, scc.config_channel_id
		from	rhnServerConfigChannel scc
		where	server_id = server_id_in
	);

	for revision in revisions loop
		insert into rhnSnapshotConfigRevision (
				snapshot_id, config_revision_id
			) values (
				snapshot_id, revision.id
			);
	end loop;
    end snapshot_server;

    procedure remove_action(
    	server_id_in in number,
	action_id_in in number
    ) is
    	-- this really wants "nulls last", but 8.1.7.3.0 sucks ass.
	-- instead, we make a local table that holds our
	-- list of ids with null prereqs.  There's surely a better way
	-- (an array instead of a table maybe?  who knows...)
	-- but I've got code to do this handy that I can look at ;)
    	cursor chained_actions is
		select	id, prerequisite
		from	rhnAction
		start with id = action_id_in
		connect by prior id = prerequisite
		order by prerequisite desc;
	cursor sessions is
		select	s.id
		from	rhnKickstartSession s
		where	server_id_in in (s.old_server_id, s.new_server_id)
			and s.action_id = action_id_in
			and not exists (
				select	1
				from	rhnKickstartSessionState ss
				where	ss.id = s.state_id
					and ss.label in ('failed','complete')
			);
	type chain_end_type is table of number index by binary_integer;
	chain_ends chain_end_type;
	i number;
	prereq number := 1;
    begin
	select	prerequisite
	into	prereq
	from	rhnAction
	where	id = action_id_in;

	if prereq is not null then
		rhn_exception.raise_exception('action_is_child');
	end if;

	i := 0;
	for action in chained_actions loop
		if action.prerequisite is null then
			chain_ends(i) := action.id;
			i := i + 1;
		else
			delete from rhnServerAction
				where server_id = server_id_in
				and action_id = action.id;
		end if;
	end loop;
	i := chain_ends.first;
	while i is not null loop
		delete from rhnServerAction
			where server_id = server_id_in
			and action_id = chain_ends(i);
		i := chain_ends.next(i);
	end loop;
	for s in sessions loop
		update rhnKickstartSession
			set 	state_id = (
					select	id
					from	rhnKickstartSessionState
					where	label = 'failed'
				),
				action_id = null
			where	id = s.id;
		set_ks_session_history_message(s.id, 'failed', 'Kickstart cancelled due to action removal');
	end loop;
    end remove_action;
   
    function check_user_access(server_id_in in number, user_id_in in number)
    return number
    is
    	has_access number;
    begin
    	-- first check; if this returns no rows, then the server/user are in different orgs, and we bail
        select 1 into has_access
	  from rhnServer S,
	       web_contact wc
	 where wc.org_id = s.org_id
	   and s.id = server_id_in
	   and wc.id = user_id_in;

	-- okay, so they're in the same org.  if we have an org admin, they get a free pass
    	if rhn_user.check_role(user_id_in, 'org_admin') = 1
	then
	    return 1;
	end if;
		   
    	select 1 into has_access
	  from rhnServerGroupMembers SGM,
	       rhnUserServerGroupPerms USG
	 where SGM.server_group_id = USG.server_group_id
	   and SGM.server_id = server_id_in
	   and USG.user_id = user_id_in
	   and rownum = 1;
	   
	return 1;
    exception
    	when no_data_found
	    then
	    return 0;
    end check_user_access;

    -- *******************************************************************
    -- FUNCTION: can_server_consume_virt_slot
    -- Returns 1 if the server id is eligible to consume a virtual slot,
    --   else returns 0.
    -- Called by: insert_into_servergroup, delete_from_servergroup
    -- *******************************************************************
    function can_server_consume_virt_slot(server_id_in in number,
                                           group_type_in in
                                           rhnServerGroupType.label%TYPE)
    return number                                           
    is

        cursor server_virt_slots is
            select vi.VIRTUAL_SYSTEM_ID
            from
                rhnVirtualInstance vi
            where
                -- server id is a virtual instance
                vi.VIRTUAL_SYSTEM_ID = server_id_in
                -- server id's host is virt entitled
                and exists ( select 1
                     from rhnServerEntitlementView sev
                 where vi.HOST_SYSTEM_ID = sev.server_id
                 and sev.label in ('virtualization_host',
                                   'virtualization_host_platform') )
                -- server id's host also has the ent we want
                and exists ( select 1
                     from rhnServerEntitlementView sev2
                 where vi.HOST_SYSTEM_ID = sev2.server_id
                 and sev2.label = group_type_in );

    begin
        for server_virt_slot in server_virt_slots loop
            return 1;
        end loop;
        return 0;
    end can_server_consume_virt_slot;


    procedure insert_into_servergroup (
		server_id_in in number,
		server_group_id_in in number
    ) is
		used_slots number;
		max_slots number;
		org_id number;
		mgmt_available number;
		mgmt_upgrade number;
		mgmt_sgid number;
		prov_available number;
		prov_upgrade number;
		prov_sgid number;
		group_label rhnServerGroupType.label%TYPE;
		group_type number;
	begin
		-- frist, group_type = null, because it's easy...

		-- this will rowlock the servergroup we're trying to change;
		-- we probably need to lock the other one, but I think the chances
		-- of it being a real issue are very small for now...
		select	sg.group_type, sg.org_id, sg.current_members, sg.max_members
		into	group_type, org_id, used_slots, max_slots
		from	rhnServerGroup sg
		where	sg.id = server_group_id_in
		for update of sg.current_members;

		if group_type is null then
			if used_slots >= max_slots then
				rhn_exception.raise_exception('servergroup_max_members');
			end if;

			insert into rhnServerGroupMembers(
					server_id, server_group_id
				) values (
					server_id_in, server_group_id_in
				);
			update rhnServerGroup
				set current_members = current_members + 1
				where id = server_group_id_in;

			rhn_cache.update_perms_for_server_group(server_group_id_in);
			return;
		end if;

		-- now for group_type != null
		-- 
		select	label
		into	group_label
		from	rhnServerGroupType	sgt
		where	sgt.id = group_type;

		-- the naive easy path that gets hit most often and has to be quickest.
		if group_label in ('sw_mgr_entitled',
                           'enterprise_entitled',
                           'monitoring_entitled',
                           'provisioning_entitled',
                           'virtualization_host',
                           'virtualization_host_platform') then
			if used_slots >= max_slots and 
               (can_server_consume_virt_slot(server_id_in, group_label) != 1) 
               then
				rhn_exception.raise_exception('servergroup_max_members');
			end if;

			insert into rhnServerGroupMembers(
					server_id, server_group_id
				) values (
					server_id_in, server_group_id_in
				);

            -- Only update current members if the system in consuming a 
            -- physical slot.
            if can_server_consume_virt_slot(server_id_in, group_label) = 0 then
                update rhnServerGroup
                set current_members = current_members + 1
                where id = server_group_id_in;
            end if;                

			return;
		end if;
	end;

	function insert_into_servergroup_maybe (
		server_id_in in number,
		server_group_id_in in number
	) return number is 
		retval number := 0;
		cursor servergroups is
			select	s.id	server_id,
					sg.id	server_group_id
			from	rhnServerGroup	sg,
					rhnServer		s
			where	s.id = server_id_in
				and sg.id = server_group_id_in
				and s.org_id = sg.org_id
				and not exists (
					select	1
					from	rhnServerGroupMembers sgm
					where	sgm.server_id = s.id
						and sgm.server_group_id = sg.id
				);
	begin
		for sgm in servergroups loop
			rhn_server.insert_into_servergroup(sgm.server_id, sgm.server_group_id);
			retval := retval + 1;
		end loop;
		return retval;
	end insert_into_servergroup_maybe;

	procedure insert_set_into_servergroup (
		server_group_id_in in number,
		user_id_in in number,
		set_label_in in varchar2
	) is
		cursor servers is
			select	st.element	id
			from	rhnSet		st
			where	st.user_id = user_id_in
				and st.label = set_label_in
				and exists (
					select	1
					from	rhnUserManagedServerGroups umsg
					where	umsg.server_group_id = server_group_id_in
						and umsg.user_id = user_id_in
					)
				and not exists (
					select	1
					from	rhnServerGroupMembers sgm
					where	sgm.server_id = st.element
						and sgm.server_group_id = server_group_id_in
				);
	begin
		for s in servers loop
			rhn_server.insert_into_servergroup(s.id, server_group_id_in);
		end loop;
	end insert_set_into_servergroup;
		
    procedure delete_from_servergroup (
    	server_id_in in number,
		server_group_id_in in number
    ) is
        cursor server_virt_groups is
            select 1
            from rhnServerEntitlementVirtual sev
            where sev.server_id = server_id_in
            and sev.server_group_id = server_group_id_in;

		oid number;
		mgmt_sgid number;
		label rhnServerGroupType.label%TYPE;
		group_type number;
	begin
		begin
			select	sg.group_type, sg.org_id
			into	group_type,	oid
			from	rhnServerGroupMembers	sgm,
					rhnServerGroup			sg
			where	sg.id = server_group_id_in
				and sg.id = sgm.server_group_id
				and sgm.server_id = server_id_in
			for update of sg.current_members;
		exception
			when no_data_found then
				rhn_exception.raise_exception('server_not_in_group');
		end;

		-- do group_type is null first
		if group_type is null then
			delete from rhnServerGroupMembers
				where server_group_id = server_group_id_in
				and	server_id = server_id_in;
			update rhnServerGroup
				set current_members = current_members - 1
				where id = server_group_id_in;
			rhn_cache.update_perms_for_server_group(server_group_id_in);
			return;
		end if;

		select	sgt.label
		into	label
		from	rhnServerGroupType sgt
		where	sgt.id = group_type;

		if label in ('sw_mgr_entitled',
                     'enterprise_entitled', 
                     'provisioning_entitled', 
                     'monitoring_entitled',
                     'virtualization_host',
                     'virtualization_host_platform') then

            -- Only update current members if the system is consuming
            -- a physical slot.
            for server_virt_group in server_virt_groups loop                
                delete from rhnServerGroupMembers
                where server_group_id = server_group_id_in
                and	server_id = server_id_in;
                return;
            end loop;                

            delete from rhnServerGroupMembers
            where server_group_id = server_group_id_in
            and	server_id = server_id_in;

            update rhnServerGroup
            set current_members = current_members - 1
            where id = server_group_id_in;
 
		end if;
	end;

	procedure delete_set_from_servergroup (
		server_group_id_in in number,
		user_id_in in number,
		set_label_in in varchar2
	) is
		cursor servergroups is
			select	sgm.server_id, sgm.server_group_id
			from	rhnSet st,
					rhnServerGroupMembers sgm
			where	sgm.server_group_id = server_group_id_in
				and st.user_id = user_id_in
				and st.label = set_label_in
				and sgm.server_id = st.element
				and exists (
					select	1
					from	rhnUserManagedServerGroups usgp
					where	usgp.server_group_id = server_group_id_in
						and usgp.user_id = user_id_in
				);
	begin
		for sgm in servergroups loop
			rhn_server.delete_from_servergroup(sgm.server_id, server_group_id_in);
		end loop;
	end delete_set_from_servergroup;

	procedure clear_servergroup (
		server_group_id_in in number
	) is
		cursor servers is
			select	sgm.server_id	id
			from	rhnServerGroupMembers sgm
			where	sgm.server_group_id = server_group_id_in;
	begin
		for s in servers loop
			rhn_server.delete_from_servergroup(s.id, server_group_id_in);
		end loop;
	end clear_servergroup;

	procedure delete_from_org_servergroups (
		server_id_in in number
	) is
		cursor servergroups is
			select	sgm.server_group_id id
			from	rhnServerGroup sg,
					rhnServerGroupMembers sgm
			where	sgm.server_id = server_id_in
				and sgm.server_group_id = sg.id
				and sg.group_type is null;
	begin
		for sg in servergroups loop
			rhn_server.delete_from_servergroup(server_id_in, sg.id);
		end loop;
	end delete_from_org_servergroups;

	function get_ip_address (
		server_id_in in number
	) return varchar2 is
		cursor interfaces is
			select	name, ip_addr
			from	rhnServerNetInterface
			where	server_id = server_id_in
				and ip_addr != '127.0.0.1';
		cursor addresses is
			select	ipaddr ip_addr
			from	rhnServerNetwork
			where	server_id = server_id_in
				and ipaddr != '127.0.0.1';
	begin
		for addr in addresses loop
			return addr.ip_addr;
		end loop;
		for iface in interfaces loop
			return iface.ip_addr;
		end loop;
		return NULL;
	end get_ip_address;
end rhn_server;
/
SHOW ERRORS
  07070100000508000081B400000000000000000000000167AE11140000B0B3000000000000000000000000000000000000006000000000susemanager-schema/upgrade/spacewalk-schema-0.6-to-spacewalk-schema-0.7/162-rhn_channel.pkb.sql   --
-- Copyright (c) 2008 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--

CREATE OR REPLACE
PACKAGE BODY rhn_channel
IS
        body_version varchar2(100) := '';

    -- Cursor that fetches all the possible base channels for a
    -- (server_arch_id, release, org_id) combination
        cursor  base_channel_cursor(
                release_in in varchar2,
                server_arch_id_in in number,
                org_id_in in number
        ) return rhnChannel%ROWTYPE is
                select distinct c.*
                from    rhnDistChannelMap                       dcm,
                                rhnServerChannelArchCompat      scac,
                                rhnChannel                                      c,
                                rhnChannelPermissions           cp
                where   cp.org_id = org_id_in
                        and cp.channel_id = c.id
                        and c.parent_channel is null
                        and c.id = dcm.channel_id
                        and c.channel_arch_id = dcm.channel_arch_id
                        and dcm.release = release_in
                        and scac.server_arch_id = server_arch_id_in
                        and scac.channel_arch_id = c.channel_arch_id;

    FUNCTION get_license_path(channel_id_in IN NUMBER)
    RETURN VARCHAR2
    IS
        license_val VARCHAR2(1000);
    BEGIN
        SELECT CFL.license_path INTO license_val
          FROM rhnChannelFamilyLicense CFL, rhnChannelFamilyMembers CFM
         WHERE CFM.channel_id = channel_id_in
           AND CFM.channel_family_id = CFL.channel_family_id;
    
        RETURN license_val;

    EXCEPTION
        WHEN NO_DATA_FOUND
            THEN
            RETURN NULL;
    END get_license_path;


    PROCEDURE license_consent(channel_id_in IN NUMBER, user_id_in IN NUMBER, server_id_in IN NUMBER)
    IS
        channel_family_id_val NUMBER;
    BEGIN
        channel_family_id_val := rhn_channel.family_for_channel(channel_id_in);
        IF channel_family_id_val IS NULL
        THEN
            rhn_exception.raise_exception('channel_subscribe_no_family');
        END IF;
        
        IF rhn_channel.get_license_path(channel_id_in) IS NULL
        THEN
            rhn_exception.raise_exception('channel_consent_no_license');
        END IF;
        
        INSERT INTO rhnChannelFamilyLicenseConsent (channel_family_id, user_id, server_id)
        VALUES (channel_family_id_val, user_id_in, server_id_in);
    END license_consent;

    PROCEDURE subscribe_server(server_id_in IN NUMBER, channel_id_in NUMBER, immediate_in NUMBER := 1, user_id_in in number := null, recalcfamily_in NUMBER := 1)
    IS
        channel_parent_val      rhnChannel.parent_channel%TYPE;
        parent_subscribed       BOOLEAN;
        server_has_base_chan    BOOLEAN;
        server_already_in_chan  BOOLEAN;
        channel_family_id_val   NUMBER;
        server_org_id_val       NUMBER;
        available_subscriptions NUMBER;
        consenting_user         NUMBER;
        allowed                 number := 0;
        current_members_val     number;
    BEGIN
        if user_id_in is not null then
            allowed := rhn_channel.user_role_check(channel_id_in, user_id_in, 'subscribe');
        else
            allowed := 1;
        end if;

        if allowed = 0 then
            rhn_exception.raise_exception('no_subscribe_permissions');
        end if;


        SELECT parent_channel INTO channel_parent_val FROM rhnChannel WHERE id = channel_id_in;

        IF channel_parent_val IS NOT NULL
        THEN    
            -- child channel; if attempting to cross-subscribe a child to the wrong base, silently ignore
            parent_subscribed := FALSE;    

            FOR check_subscription IN check_server_subscription(server_id_in, channel_parent_val)
            LOOP
                parent_subscribed := TRUE;
            END LOOP check_subscription;
        
            IF NOT parent_subscribed
            THEN
                RETURN;
            END IF;
        ELSE
            -- base channel
            server_has_base_chan := FALSE;
            FOR base IN server_base_subscriptions(server_id_in)
            LOOP
                server_has_base_chan := TRUE;
            END LOOP base;
            
            IF server_has_base_chan
            THEN
                rhn_exception.raise_exception('channel_server_one_base');
            END IF;
        END IF;
    
        FOR check_subscription IN check_server_subscription(server_id_in, channel_id_in)
        LOOP
            server_already_in_chan := TRUE;
        END LOOP check_subscription;
    
        IF server_already_in_chan
        THEN
            RETURN;
        END IF;
        
        channel_family_id_val := rhn_channel.family_for_channel(channel_id_in);
        IF channel_family_id_val IS NULL
        THEN
            rhn_exception.raise_exception('channel_subscribe_no_family');
        END IF;

        --
        -- Use the org_id of the server only if the org_id of the channel = NULL.
        -- This is required for subscribing to shared channels.
        --
        SELECT NVL(org_id, (SELECT org_id FROM rhnServer WHERE id = server_id_in))
          INTO server_org_id_val
          FROM rhnChannel
         WHERE id = channel_id_in;
         
        select current_members 
        into current_members_val
        from rhnPrivateChannelFamily
        where org_id = server_org_id_val and channel_family_id = channel_family_id_val
        for update of current_members;

        available_subscriptions := rhn_channel.available_family_subscriptions(channel_family_id_val, server_org_id_val);
        
        IF available_subscriptions IS NULL OR 
           available_subscriptions > 0 or
           can_server_consume_virt_channl(server_id_in, channel_family_id_val) = 1
        THEN
        
            IF rhn_channel.get_license_path(channel_id_in) IS NOT NULL
            THEN
                BEGIN
                
                SELECT user_id INTO consenting_user
                  FROM rhnChannelFamilyLicenseConsent
                 WHERE channel_family_id = channel_family_id_val
                   AND server_id = server_id_in;
                
                EXCEPTION
                    WHEN NO_DATA_FOUND THEN
                        rhn_exception.raise_exception('channel_subscribe_no_consent');
                END;
            END IF;
        
            insert into rhnServerHistory (id,server_id,summary,details) (
                select  rhn_event_id_seq.nextval,
                        server_id_in,
                        'subscribed to channel ' || SUBSTR(c.label, 0, 106),
                        c.label
                from    rhnChannel c
                where   c.id = channel_id_in
            );
            UPDATE rhnServer SET channels_changed = sysdate WHERE id = server_id_in;
            INSERT INTO rhnServerChannel (server_id, channel_id) VALUES (server_id_in, channel_id_in);
			IF recalcfamily_in > 0
			THEN
                rhn_channel.update_family_counts(channel_family_id_val, server_org_id_val);
			END IF;
            queue_server(server_id_in, immediate_in);
        ELSE
            rhn_exception.raise_exception('channel_family_no_subscriptions');
        END IF;
            
    END subscribe_server;
    
    function can_server_consume_virt_channl(
        server_id_in in number,
        family_id_in in number )
    return number
    is

        cursor server_virt_families is
            select vi.virtual_system_id, cfvsl.channel_family_id
            from
                rhnChannelFamilyVirtSubLevel cfvsl,
                rhnSGTypeVirtSubLevel sgtvsl,
                rhnVirtualInstance vi
            where
                vi.virtual_system_id = server_id_in 
                and sgtvsl.virt_sub_level_id = cfvsl.virt_sub_level_id
                and cfvsl.channel_family_id = family_id_in
                and exists (
                    select 1
                    from rhnServerEntitlementView sev
                    where vi.host_system_id = sev.server_id
                    and sev.server_group_type_id = sgtvsl.server_group_type_id );
    begin

        for server_virt_family in server_virt_families loop
            return 1;
        end loop;

        return 0;

    end;


    PROCEDURE bulk_subscribe_server(channel_id_in IN NUMBER, set_label_in IN VARCHAR2, set_uid_in IN NUMBER)
    IS
    BEGIN
        FOR server IN rhn_set.set_iterator(set_label_in, set_uid_in)
        LOOP
            rhn_channel.subscribe_server(server.element, channel_id_in, 0, set_uid_in);
        END LOOP server;
    END bulk_subscribe_server;

    PROCEDURE bulk_server_base_change(channel_id_in IN NUMBER, set_label_in IN VARCHAR2, set_uid_in IN NUMBER)
    IS
    BEGIN
        FOR server IN rhn_set.set_iterator(set_label_in, set_uid_in)
        LOOP
            IF rhn_server.can_change_base_channel(server.element) = 1
            THEN
                rhn_channel.clear_subscriptions(TO_NUMBER(server.element));
                rhn_channel.subscribe_server(server.element, channel_id_in, 0, set_uid_in);
            END IF;
        END LOOP server;
    END bulk_server_base_change;

    procedure bulk_server_basechange_from(
        set_label_in in varchar2,
        set_uid_in in number,
        old_channel_id_in in number,
        new_channel_id_in in number
    ) is
    cursor servers is
        select  sc.server_id id
        from    rhnChannel nc,
                rhnServerChannelArchCompat scac,
                rhnServer s,
                rhnChannel oc,
                rhnServerChannel sc,
                rhnSet st
        where   1=1
            -- first, find the servers we're looking for.
            and st.label = set_label_in
            and st.user_id = set_uid_in
            and st.element = sc.server_id
            -- now, filter out anything that's not in the
            -- old base channel.
            and sc.channel_id = old_channel_id_in
            and sc.channel_id = oc.id
            and oc.parent_channel is null
            -- now, see if it's compatible with the new base channel
            and nc.id = new_channel_id_in
            and nc.parent_channel is null
            and sc.server_id = s.id
            and s.server_arch_id = scac.server_arch_id
            and scac.channel_arch_id = nc.channel_arch_id;
    begin
        for s in servers loop
            insert into rhnSet (
                    user_id, label, element
                ) values (
                    set_uid_in,
                    set_label_in || 'basechange', 
                    s.id
                );
        end loop channel;
        bulk_server_base_change(new_channel_id_in,
                                set_label_in || 'basechange',
                                set_uid_in);
        delete from rhnSet
            where   label = set_label_in||'basechange'
                and user_id = set_uid_in;
    end bulk_server_basechange_from;

    procedure bulk_guess_server_base(
        set_label_in in varchar2,
        set_uid_in in number
    ) is
        channel_id number;
    begin
        for server in rhn_set.set_iterator(set_label_in, set_uid_in)
        loop
            -- anything that doesn't work, we just ignore
            begin
                if rhn_server.can_change_base_channel(server.element) = 1
                then
                    channel_id := guess_server_base(TO_NUMBER(server.element));
                    rhn_channel.clear_subscriptions(TO_NUMBER(server.element));
                    rhn_channel.subscribe_server(TO_NUMBER(server.element), channel_id, 0, set_uid_in);
                end if;
            exception when others then
                null;
            end;
        end loop server;
    end;

    function guess_server_base(
        server_id_in in number
    ) RETURN number is
        cursor server_cursor is
            select s.server_arch_id, s.release, s.org_id
              from rhnServer s
             where s.id = server_id_in;
    begin
        for s in server_cursor loop
            for channel in base_channel_cursor(s.release,
                s.server_arch_id, s.org_id) 
            loop
                return channel.id;
            end loop base_channel_cursor;
        end loop server_cursor;
        -- Server not found, or no base channel applies to it
        return null;
    end;

    -- Private function
    function normalize_server_arch(server_arch_in in varchar2)
    return varchar2
    deterministic
    is
        suffix VARCHAR2(128) := '-redhat-linux';
        suffix_len NUMBER := length(suffix);
    begin
        if server_arch_in is NULL then
            return NULL;
        end if;
        if instr(server_arch_in, '-') > 0
        then
            -- Suffix already present
            return server_arch_in;
        end if;
        return server_arch_in || suffix;
    end normalize_server_arch;

    --
    --
    -- Raises: 
    --   server_arch_not_found
    --   no_subscribe_permissions
    function base_channel_for_release_arch(
        release_in in varchar2,
        server_arch_in in varchar2,
        org_id_in in number := -1,
        user_id_in in number := null
    ) return number is
        server_arch varchar2(256) := normalize_server_arch(server_arch_in);
        server_arch_id number;
    begin
        -- Look up the server arch
        begin
            select id
              into server_arch_id
              from rhnServerArch
             where label = server_arch;
        exception
            when no_data_found then
                rhn_exception.raise_exception('server_arch_not_found');
        end;
        return base_channel_rel_archid(release_in, server_arch_id,
            org_id_in, user_id_in);
    end base_channel_for_release_arch;

    function base_channel_rel_archid(
        release_in in varchar2,
        server_arch_id_in in number,
        org_id_in in number := -1,
        user_id_in in number := null
    ) return number is
        denied_channel_id number := null;
        valid_org_id number := org_id_in;
        valid_user_id number := user_id_in;
        channel_subscribable number;
    begin
        if org_id_in = -1 and user_id_in is not null then
            -- Get the org id from the user id
            begin
                select org_id
                  into valid_org_id
                  from web_contact
                 where id = user_id_in;
            exception
                when no_data_found then
                    -- User doesn't exist
                    -- XXX Only list public stuff for now
                    valid_user_id := null;
                    valid_org_id := -1;
            end;
        end if;

        for c in base_channel_cursor(release_in, server_arch_id_in, valid_org_id)
        loop
            -- This row is a possible match
            if valid_user_id is null then
                -- User ID not specified, so no user to channel permissions to
                -- check
                return c.id;
            end if;

            -- Check user to channel permissions
            select loose_user_role_check(c.id, user_id_in, 'subscribe')
              into channel_subscribable
              from dual;

            if channel_subscribable = 1 then
                return c.id;
            end if;
                
            -- Base channel exists, but is not subscribable; keep trying
            denied_channel_id := c.id;
        end loop base_channel_fetch;
        
        if denied_channel_id is not null then
            rhn_exception.raise_exception('no_subscribe_permissions');
        end if;
        -- No base channel applies
        return NULL;
    end base_channel_rel_archid;

    procedure bulk_guess_server_base_from(
        set_label_in in varchar2,
        set_uid_in in number,
        channel_id_in in number
    ) is
        cursor channels(server_id_in in number) is
            select      rsc.channel_id
            from        rhnServerChannel rsc,
                        rhnChannel rc
            where       server_id_in = rsc.server_id
                        and rsc.channel_id = rc.id
                        and rc.parent_channel is null;
    begin
        for server in rhn_set.set_iterator(set_label_in, set_uid_in)
        loop
            for channel in channels(server.element)
            loop
                if channel.channel_id = channel_id_in
                then
                    insert into rhnSet (user_id, label, element) values (set_uid_in, set_label_in || 'baseguess', server.element);
                end if;
            end loop channel;
        end loop server;
        bulk_guess_server_base(set_label_in||'baseguess',set_uid_in);
        delete from rhnSet where label = set_label_in||'baseguess' and user_id = set_uid_in;
    end;


    PROCEDURE clear_subscriptions(server_id_in IN NUMBER, deleting_server IN NUMBER := 0 )
    IS
        cursor server_channels(server_id_in in number) is
                select  s.org_id, sc.channel_id, cfm.channel_family_id
                from    rhnServer s,
                        rhnServerChannel sc,
                        rhnChannelFamilyMembers cfm
                where   s.id = server_id_in
                        and s.id = sc.server_id
                        and sc.channel_id = cfm.channel_id;
    BEGIN
        for channel in server_channels(server_id_in)
        loop
                unsubscribe_server(server_id_in, channel.channel_id, 1, 1, deleting_server);
                rhn_channel.update_family_counts(channel.channel_family_id, channel.org_id);
        end loop channel;
    END clear_subscriptions;

    PROCEDURE unsubscribe_server(server_id_in IN NUMBER, channel_id_in NUMBER, immediate_in NUMBER := 1, unsubscribe_children_in number := 0,
                                 deleting_server IN NUMBER := 0 )
    IS
        channel_family_id_val   NUMBER;
        server_org_id_val       NUMBER;
        available_subscriptions NUMBER; 
        server_already_in_chan  BOOLEAN;
        cursor  channel_family_is_proxy(channel_family_id_in in number) is
                select  1
                from    rhnChannelFamily
                where   id = channel_family_id_in
                    and label = 'rhn-proxy';
        cursor  channel_family_is_satellite(channel_family_id_in in number) is
                select  1
                from    rhnChannelFamily
                where   id = channel_family_id_in
                    and label = 'rhn-satellite';
        -- this is *EXACTLY* like check_server_parent_membership, but if we recurse
        -- with the package-level one, we get a "cursor already open", so we need a
        -- copy on our call stack instead.  GROAN.
        cursor local_chk_server_parent_memb (
                        server_id_in number,
                        channel_id_in number ) is
                select  c.id
                from    rhnChannel                      c,
                                rhnServerChannel        sc
                where   1=1
                        and c.parent_channel = channel_id_in
                        and c.id = sc.channel_id
                        and sc.server_id = server_id_in;
    BEGIN
        FOR child IN local_chk_server_parent_memb(server_id_in, channel_id_in)
        LOOP
            if unsubscribe_children_in = 1 then
                unsubscribe_server(server_id_in => server_id_in,
                                                                channel_id_in => child.id,
                                                                immediate_in => immediate_in,
                                                                unsubscribe_children_in => unsubscribe_children_in,
                        deleting_server => deleting_server);
            else
                rhn_exception.raise_exception('channel_unsubscribe_child_exists');
            end if;
        END LOOP child;
        
        server_already_in_chan := FALSE;
    
        FOR check_subscription IN check_server_subscription(server_id_in, channel_id_in)
        LOOP
            server_already_in_chan := TRUE;
        END LOOP check_subscription;
    
        IF NOT server_already_in_chan
        THEN
            RETURN;
        END IF;
        
   if deleting_server = 0 then 

      insert into rhnServerHistory (id,server_id,summary,details) (
          select  rhn_event_id_seq.nextval,
                server_id_in,
             'unsubscribed from channel ' || SUBSTR(c.label, 0, 106),
             c.label
          from    rhnChannel c
          where   c.id = channel_id_in
      );

        UPDATE rhnServer SET channels_changed = sysdate WHERE id = server_id_in;
   end if;
        
   DELETE FROM rhnServerChannel WHERE server_id = server_id_in AND channel_id = channel_id_in;

   if deleting_server = 0 then 
        queue_server(server_id_in, immediate_in);
   end if;

        channel_family_id_val := rhn_channel.family_for_channel(channel_id_in);
        IF channel_family_id_val IS NULL
        THEN
            rhn_exception.raise_exception('channel_unsubscribe_no_family');
        END IF;

        for ignore in channel_family_is_satellite(channel_family_id_val) loop
                delete from rhnSatelliteInfo where server_id = server_id_in;
                delete from rhnSatelliteChannelFamily where server_id = server_id_in;
        end loop;

        for ignore in channel_family_is_proxy(channel_family_id_val) loop
                delete from rhnProxyInfo where server_id = server_id_in;
        end loop;

        DELETE FROM rhnChannelFamilyLicenseConsent
         WHERE channel_family_id = channel_family_id_val
           AND server_id = server_id_in;
                        
        SELECT org_id INTO server_org_id_val
          FROM rhnServer
         WHERE id = server_id_in;
         
        rhn_channel.update_family_counts(channel_family_id_val, server_org_id_val);
    END unsubscribe_server;

    PROCEDURE bulk_unsubscribe_server(channel_id_in IN NUMBER, set_label_in IN VARCHAR2, set_uid_in IN NUMBER)
    IS
    BEGIN
        FOR server IN rhn_set.set_iterator(set_label_in, set_uid_in)
        LOOP
            rhn_channel.unsubscribe_server(server.element, channel_id_in, 0);
        END LOOP server;
    END bulk_unsubscribe_server;

    FUNCTION family_for_channel(channel_id_in IN NUMBER)
    RETURN NUMBER
    IS
        channel_family_id_val NUMBER;
    BEGIN
        SELECT channel_family_id INTO channel_family_id_val
          FROM rhnChannelFamilyMembers
         WHERE channel_id = channel_id_in;
         
        RETURN channel_family_id_val;
    EXCEPTION
        WHEN NO_DATA_FOUND
        THEN
            RETURN NULL;
    END family_for_channel;

    FUNCTION available_family_subscriptions(channel_family_id_in IN NUMBER, org_id_in IN NUMBER)
    RETURN NUMBER
    IS
        cfp channel_family_perm_cursor%ROWTYPE;
        current_members_val NUMBER;
        max_members_val     NUMBER;
        found               NUMBER;
    BEGIN
        IF NOT channel_family_perm_cursor%ISOPEN
        THEN
            OPEN channel_family_perm_cursor(channel_family_id_in, org_id_in);
        END IF;

        FETCH channel_family_perm_cursor INTO cfp;
        
        WHILE channel_family_perm_cursor%FOUND
        LOOP
            found := 1;
            
            current_members_val := cfp.current_members;
            max_members_val := cfp.max_members;
            
            FETCH channel_family_perm_cursor INTO cfp;
        END LOOP;

        IF channel_family_perm_cursor%ISOPEN
        THEN
            CLOSE channel_family_perm_cursor;
        END IF;

        -- not found: either the channel fam doesn't have an entry in cfp, or the org doesn't have access to it.
        -- either way, there are no available subscriptions
        
        IF found IS NULL
        THEN
            RETURN 0;
        END IF;

        -- null max members?  in that case, pass it on; NULL means infinite                     
        IF max_members_val IS NULL
        THEN
            RETURN NULL;
        END IF;

        -- otherwise, return the delta  
        RETURN max_members_val - current_members_val;                   
    END available_family_subscriptions;
    
    -- *******************************************************************
    -- FUNCTION: channel_family_current_members
    -- Calculates and returns the actual count of systems consuming
    --   physical channel subscriptions.
    -- Called by: update_family_counts 
    --            rhn_entitlements.repoll_virt_guest_entitlements
    -- *******************************************************************
    function channel_family_current_members(channel_family_id_in IN NUMBER,
                                            org_id_in IN NUMBER)
    return number
    is
        current_members_count number := 0;
    begin
        select  count(distinct server_id)
        into    current_members_count
          from  rhnChannelFamilyServerPhysical cfsp
         where  cfsp.channel_family_id = channel_family_id_in
           and  cfsp.customer_id = org_id_in;
        return current_members_count;
    end;        

    PROCEDURE update_family_counts(channel_family_id_in IN NUMBER, 
                                   org_id_in IN NUMBER)
    IS
    BEGIN
                update rhnPrivateChannelFamily
                set current_members = (
                channel_family_current_members(channel_family_id_in, org_id_in)
                )
                        where org_id = org_id_in
                                and channel_family_id = channel_family_id_in;

    END update_family_counts;
    
    FUNCTION available_chan_subscriptions(channel_id_in IN NUMBER, 
                                          org_id_in IN NUMBER)
    RETURN NUMBER
    IS
            channel_family_id_val NUMBER;
    BEGIN
        SELECT channel_family_id INTO channel_family_id_val
            FROM rhnChannelFamilyMembers
            WHERE channel_id = channel_id_in;
         
            RETURN rhn_channel.available_family_subscriptions(
                           channel_family_id_val, org_id_in);
    END available_chan_subscriptions;

    -- *******************************************************************
    -- PROCEDURE: entitle_customer
    -- Creates a chan fam bucket, or sets max_members for an existing bucket
    -- Called by: rhn_ep.poll_customer_internal
    -- Calls: set_family_maxmembers + update_family_counts if the row
    --        already exists, else it creates it in rhnPrivateChannelFamily.
    -- *******************************************************************
    procedure entitle_customer(customer_id_in in number, 
                               channel_family_id_in in number, 
                               quantity_in in number)
    is
                cursor permissions is
                        select  1
                        from    rhnPrivateChannelFamily pcf
                        where   pcf.org_id = customer_id_in
                                and     pcf.channel_family_id = channel_family_id_in; 
    begin
                for perm in permissions loop
                        set_family_maxmembers(
                                customer_id_in,
                                channel_family_id_in,
                                quantity_in
                        );
                        rhn_channel.update_family_counts(
                                channel_family_id_in,
                                customer_id_in
                        );
                        return;
                end loop;
        
                insert into rhnPrivateChannelFamily pcf (
                                channel_family_id, org_id, max_members, current_members
                        ) values (
                                channel_family_id_in, customer_id_in, quantity_in, 0
                        );
    end;

    -- *******************************************************************
    -- PROCEDURE: set_family_maxmembers
    -- Prunes an existing channel family bucket by unsubscribing the
    --   necessary servers and sets max_members.
    -- Called by: rhn_channel.entitle_customer
    -- Calls: unsubscribe_server_from_family
    -- *******************************************************************
    procedure set_family_maxmembers(customer_id_in in number, 
                                    channel_family_id_in in number, 
                                    quantity_in in number)
    is
        cursor servers is
            select  server_id from (
            select      rownum row_number, server_id, modified from (
                select  rcfsp.server_id,
                        rcfsp.modified
                from    rhnChannelFamilyServerPhysical rcfsp
                where   rcfsp.customer_id = customer_id_in
                    and rcfsp.channel_family_id = channel_family_id_in
                order by modified
            )
            where rownum > quantity_in
            );
    begin
            -- prune subscribed servers
        for server in servers loop
            rhn_channel.unsubscribe_server_from_family(server.server_id, 
                                                       channel_family_id_in);
        end loop;

        update  rhnPrivateChannelFamily pcf
        set     pcf.max_members = quantity_in
        where   pcf.org_id = customer_id_in
            and pcf.channel_family_id = channel_family_id_in;
    end;

    procedure unsubscribe_server_from_family(server_id_in in number, 
                                             channel_family_id_in in number)
    is
    begin
        delete
        from    rhnServerChannel rsc
        where   rsc.server_id = server_id_in
            and channel_id in (
                select  rcfm.channel_id
                from    rhnChannelFamilyMembers rcfm
                where   rcfm.channel_family_id = channel_family_id_in);
    end;

    function get_org_id(channel_id_in in number)
    return number
    is
        org_id_out number;
    begin
        select org_id into org_id_out
            from rhnChannel
            where id = channel_id_in;
         
            return org_id_out;
    end get_org_id;
    
    function get_cfam_org_access(cfam_id_in in number, org_id_in in number)
    return number
    is
        cursor  families is
                        select  1
                        from    rhnOrgChannelFamilyPermissions cfp
                        where   cfp.org_id = org_id_in;
    begin
                -- the idea: if we get past this query, 
        -- the user has the role, else catch the exception and return 0
                for family in families loop
                return 1;
                end loop;
                return 0;
    end;

    function get_org_access(channel_id_in in number, org_id_in in number)
    return number
    is
        throwaway number;
    begin
        -- the idea: if we get past this query, 
        -- the org has access to the channel, else catch the exception and return 0
        select distinct 1 into throwaway
          from rhnChannelFamilyMembers CFM,
               rhnOrgChannelFamilyPermissions CFP
         where cfp.org_id = org_id_in
           and CFM.channel_family_id = CFP.channel_family_id
           and CFM.channel_id = channel_id_in
           and (CFP.max_members > 0 or CFP.max_members is null or CFP.org_id = 1);
           
        return 1;
        exception
            when no_data_found
            then
            return 0;
    end;
    
    -- check if a user has a given role, or if such a role is inferrable
    function user_role_check_debug(channel_id_in in number, 
                                   user_id_in in number, 
                                   role_in in varchar2, 
                                   reason_out out varchar2)
    return number
    is
        org_id number;
    begin
        org_id := rhn_user.get_org_id(user_id_in);

        -- channel might be shared
        if role_in = 'subscribe' and
           rhn_channel.shared_user_role_check(channel_id_in, user_id_in, role_in) = 1 then
            return 1;
        end if;
        
        if role_in = 'manage' and 
           NVL(rhn_channel.get_org_id(channel_id_in), -1) <> org_id then
                reason_out := 'channel_not_owned';
               return 0;
            end if;
        
        if role_in = 'subscribe' and 
           rhn_channel.get_org_access(channel_id_in, org_id) = 0 then
                reason_out := 'channel_not_available';
                return 0;
            end if;
        
        -- channel admins have all roles
        if rhn_user.check_role_implied(user_id_in, 'channel_admin') = 1 then
            reason_out := 'channel_admin';
            return 1;
            end if;

        -- the subscribe permission is inferred 
    -- UNLESS the not_globally_subscribable flag is set 
        if role_in = 'subscribe'
        then
            if rhn_channel.org_channel_setting(channel_id_in, 
                       org_id,
                       'not_globally_subscribable') = 0 then
                reason_out := 'globally_subscribable';
                    return 1;
            end if;
        end if;
        
        -- all other roles (manage right now) are explicitly granted    
        reason_out := 'direct_permission';
        return rhn_channel.direct_user_role_check(channel_id_in, 
                                              user_id_in, role_in);
    end;
    
    -- same as above, but with no OUT param; useful in views, etc
    function user_role_check(channel_id_in in number, user_id_in in number, role_in in varchar2)
    return number
    is
        throwaway varchar2(256);
    begin
        return rhn_channel.user_role_check_debug(channel_id_in, user_id_in, role_in, throwaway);
    end;

    --
    -- For multiorg phase II, this function simply checks to see if the user's
    -- has a trust relationship that includes this channel by id.
    --
    function shared_user_role_check(channel_id in number, user_id in number, role in varchar2)
    return number
    is
      n number;
      oid number;
    begin
      oid := rhn_user.get_org_id(user_id);
      select 1 into n
      from rhnSharedChannelView s
      where s.id = channel_id and s.org_trust_id = oid;
      return 1;
      exception
        when no_data_found then
          return 0;
    end;

    -- same as above, but returns 1 if user_id_in is null
    -- This is useful in queries where user_id is not specified
    function loose_user_role_check(channel_id_in in number, user_id_in in number, role_in in varchar2)
    return number
    is
    begin
        if user_id_in is null then
            return 1;
        end if;
        return user_role_check(channel_id_in, user_id_in, role_in);
    end loose_user_role_check;
    
    -- directly checks the table, no inferred permissions
    function direct_user_role_check(channel_id_in in number, user_id_in in number, role_in in varchar2)
    return number
    is
        throwaway number;
    begin
        -- the idea: if we get past this query, the user has the role, else catch the exception and return 0
        select 1 into throwaway
          from rhnChannelPermissionRole CPR,
               rhnChannelPermission CP
         where CP.user_id = user_id_in
           and CP.channel_id = channel_id_in
           and CPR.label = role_in
           and CP.role_id = CPR.id;
           
        return 1;
    exception
        when no_data_found
            then
            return 0;
    end;
    
    -- check if an org has a certain setting
    function org_channel_setting(channel_id_in in number, org_id_in in number, setting_in in varchar2)
    return number
    is
        throwaway number;
    begin
        -- the idea: if we get past this query, the org has the setting, else catch the exception and return 0
        select 1 into throwaway
          from rhnOrgChannelSettingsType OCST,
               rhnOrgChannelSettings OCS
         where OCS.org_id = org_id_in
           and OCS.channel_id = channel_id_in
           and OCST.label = setting_in
           and OCS.setting_id = OCST.id;
           
        return 1;
    exception
        when no_data_found
            then
            return 0;
    end;
    
    FUNCTION channel_priority(channel_id_in IN number) 
    RETURN number
    IS
         channel_name varchar2(256);
         priority number;
         end_of_life_val date;
         org_id_val number;
    BEGIN

        select name, end_of_life, org_id
        into channel_name, end_of_life_val, org_id_val
        from rhnChannel
        where id = channel_id_in;

        if end_of_life_val is not null then
          return -400;
        end if;

        if channel_name like 'Red Hat Enterprise Linux%' or channel_name like 'RHEL%' then
          priority := 1000;
          if channel_name not like '%Beta%' then
            priority := priority + 1000;
          end if;

          priority := priority +
            case
              when channel_name like '%v. 5%' then 600
              when channel_name like '%v. 4%' then 500
              when channel_name like '%v. 3%' then 400
              when channel_name like '%v. 2%' then 300
              when channel_name like '%v. 1%' then 200
              else 0
            end;

          priority := priority +
            case
              when channel_name like 'Red Hat Enterprise Linux (v. 5%' then 60
              when (channel_name like '%AS%' and channel_name not like '%Extras%') then 50
              when (channel_name like '%ES%' and channel_name not like '%Extras%') then 40
              when (channel_name like '%WS%' and channel_name not like '%Extras%') then 30
              when (channel_name like '%Desktop%' and channel_name not like '%Extras%') then 20
              when channel_name like '%Extras%' then 10
              else 0
            end; 

          priority := priority +
            case
              when channel_name like '%)' then 5
              else 0
            end;

          priority := priority +
            case
              when channel_name like '%32-bit x86%' then 4
              when channel_name like '%64-bit Intel Itanium%' then 3
              when channel_name like '%64-bit AMD64/Intel EM64T%' then 2
              else 0
            end;
        elsif channel_name like 'Red Hat Desktop%' then
            priority := 900;

            if channel_name not like '%Beta%' then
               priority := priority + 50;
            end if;
 
          priority := priority +
            case
              when channel_name like '%v. 4%' then 40
              when channel_name like '%v. 3%' then 30
              when channel_name like '%v. 2%' then 20
              when channel_name like '%v. 1%' then 10
              else 0
            end;
            
          priority := priority +
            case
              when channel_name like '%32-bit x86%' then 4
              when channel_name like '%64-bit Intel Itanium%' then 3
              when channel_name like '%64-bit AMD64/Intel EM64T%' then 2
              else 0
            end;
         
        elsif org_id_val is not null then
          priority := 600;
        else
          priority := 500;
        end if;
      
      return -priority;

    end channel_priority;

    -- right now this only does the accounting changes; the cascade
    -- actually does the rhnServerChannel delete.
    procedure delete_server_channels(server_id_in in number)
    is
    begin
        update  rhnPrivateChannelFamily
        set     current_members = current_members -1
        where   org_id in (
                        select  org_id
                        from    rhnServer
                        where   id = server_id_in
                )
                and channel_family_id in (
                        select  rcfm.channel_family_id
                        from    rhnChannelFamilyMembers rcfm,
                                rhnServerChannel rsc
                        where   rsc.server_id = server_id_in
                                and rsc.channel_id = rcfm.channel_id
                and not exists (
                    select 1
                    from
                        rhnChannelFamilyVirtSubLevel cfvsl,
                        rhnSGTypeVirtSubLevel sgtvsl,
                        rhnServerEntitlementView sev,
                        rhnVirtualInstance vi
                    where
                        -- system is a virtual instance
                        vi.virtual_system_id = server_id_in
                        and vi.host_system_id = sev.server_id
                        -- system's host has a virt ent
                        and sev.label in ('virtualization_host',
                                          'virtualization_host_platform')
                        and sev.server_group_type_id = 
                            sgtvsl.server_group_type_id
                        -- the host's virt ent grants a cf virt sub level
                        and sgtvsl.virt_sub_level_id = cfvsl.virt_sub_level_id
                        -- the cf is in that virt sub level
                        and cfvsl.channel_family_id = rcfm.channel_family_id
                    )
                );
    end;

        -- this could certainly be optimized to do updates if needs be
        procedure refresh_newest_package(channel_id_in in number, caller_in in varchar2 := '(unknown)')
        is
        begin
                delete from rhnChannelNewestPackage where channel_id = channel_id_in;
                insert into rhnChannelNewestPackage
                        ( channel_id, name_id, evr_id, package_id, package_arch_id ) 
                        (       select  channel_id,
                                                name_id, evr_id,
                                                package_id, package_arch_id
                                from    rhnChannelNewestPackageView
                                where   channel_id = channel_id_in
                        );
                insert into rhnChannelNewestPackageAudit (channel_id, caller)
                    values (channel_id_in, caller_in);
                update rhnChannel 
                    set last_modified = greatest(sysdate, last_modified + 1/86400)
                    where id = channel_id_in; 
        end;

   procedure update_channel ( channel_id_in in number, invalidate_ss in number := 0, 
                              date_to_use in date := sysdate )
   is

   channel_last_modified date;
   last_modified_value date;

   cursor snapshots is
   select  snapshot_id id
   from    rhnSnapshotChannel
   where   channel_id = channel_id_in;

   begin

      select last_modified
      into channel_last_modified
      from rhnChannel
      where id = channel_id_in;
  
      last_modified_value := date_to_use;

      if last_modified_value <= channel_last_modified then
          last_modified_value := last_modified_value + 1/86400;
      end if;

      update rhnChannel set last_modified = last_modified_value
      where id = channel_id_in;

      if invalidate_ss = 1 then 
        for snapshot in snapshots loop
            update rhnSnapshot
            set invalid = lookup_snapshot_invalid_reason('channel_modified')
            where id = snapshot.id;
        end loop;
      end if;

   end update_channel;

   procedure update_channels_by_package ( package_id_in in number, date_to_use in date := sysdate )
   is

   cursor channels is
   select channel_id
   from rhnChannelPackage
   where package_id = package_id_in
   order by channel_id;

   begin
      for channel in channels loop
         -- we want to invalidate the snapshot assocated with the channel when we
         -- do this b/c we know we've added or removed or packages
         rhn_channel.update_channel ( channel.channel_id, 1, date_to_use );
      end loop;
   end update_channels_by_package;

   
   procedure update_channels_by_errata ( errata_id_in number, date_to_use in date := sysdate )
   is

   cursor channels is
   select channel_id
   from rhnChannelErrata
   where errata_id = errata_id_in
   order by channel_id;

   begin
      for channel in channels loop
         -- we won't invalidate snapshots, b/c just changing the errata associated with
         -- a channel shouldn't invalidate snapshots
         rhn_channel.update_channel ( channel.channel_id, 0, date_to_use );
      end loop;
   end update_channels_by_errata;

END rhn_channel;
/
SHOW ERRORS
 07070100000509000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000004800000000susemanager-schema/upgrade/spacewalk-schema-0.7-to-spacewalk-schema-0.8   0707010000050A000081B400000000000000000000000167AE111400000091000000000000000000000000000000000000006700000000susemanager-schema/upgrade/spacewalk-schema-0.7-to-spacewalk-schema-0.8/004-2-rhnChecksumType-data.sql    update rhnChecksumType
   set label = translate(label, ' -', ' ');

update rhnChecksumType
   set description = upper(label) || 'sum';

commit;

   0707010000050B000081B400000000000000000000000167AE1114000004D6000000000000000000000000000000000000006200000000susemanager-schema/upgrade/spacewalk-schema-0.7-to-spacewalk-schema-0.8/005-rhnChecksum-table.sql --
-- Copyright (c) 2009--2010 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--
--
-- The checksum associated with a package/file/etc...

create table
rhnChecksum
(
        id              number not null
                        constraint rhnChecksum_pk primary key,
        checksum_type_id        number not null
                        constraint rhnChecksum_typeid_fk
                        references rhnChecksumType(id),
        checksum        varchar2(128) not null
)
        enable row movement
;

alter table rhnChecksum add constraint rhnChecksum_chsum_uq
        unique (checksum, checksum_type_id)
        using index tablespace [[32m_tbs]];

CREATE SEQUENCE rhnChecksum_seq;
  0707010000050C000081B400000000000000000000000167AE11140000032A000000000000000000000000000000000000006000000000susemanager-schema/upgrade/spacewalk-schema-0.7-to-spacewalk-schema-0.8/007-rhnChecksumView.sql   --
-- Copyright (c) 2009 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

create or replace view rhnChecksumView
as
select c.id,
       ct.label checksum_type,
       c.checksum
  from rhnChecksum c,
       rhnChecksumType ct
 where c.checksum_type_id = ct.id;

  0707010000050D000081B400000000000000000000000167AE1114000005E3000000000000000000000000000000000000006000000000susemanager-schema/upgrade/spacewalk-schema-0.7-to-spacewalk-schema-0.8/008-lookup_checksum.sql   --
-- Copyright (c) 2009 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--
--
--
--

CREATE OR REPLACE FUNCTION
LOOKUP_CHECKSUM(checksum_type_in IN VARCHAR2, checksum_in IN VARCHAR2)
RETURN NUMBER
IS
        PRAGMA AUTONOMOUS_TRANSACTION;
        checksum_id     NUMBER;
BEGIN
        if checksum_in is null then
                return null;
        end if;

        SELECT c.id
          INTO checksum_id
          FROM rhnChecksumView c
         WHERE c.checksum = checksum_in
           AND c.checksum_type = checksum_type_in;

        RETURN checksum_id;
EXCEPTION
        WHEN NO_DATA_FOUND THEN
            INSERT INTO rhnChecksum (id, checksum_type_id, checksum)
                 VALUES (rhnChecksum_seq.nextval,
                        (select id from rhnChecksumType where label = checksum_type_in),
                        checksum_in)
                RETURNING id INTO checksum_id;
            COMMIT;
        RETURN checksum_id;
END;
/
SHOW ERRORS

 0707010000050E000081B400000000000000000000000167AE1114000001E9000000000000000000000000000000000000006900000000susemanager-schema/upgrade/spacewalk-schema-0.7-to-spacewalk-schema-0.8/009-rhnChannel-checksum_type.sql  alter trigger rhn_channel_mod_trig disable;
update rhnChannel
   set checksum_type_id = (select id from rhnChecksumType where label = 'sha1')
 where checksum_type_id is null
   and (label like 'rhel-%-server-5'
     or label like 'rhel-%-client-5'
     or parent_channel in (select id from rhnChannel
                                    where label like 'rhel-%-server-5'
                                       or label like 'rhel-%-client-5'));
alter trigger rhn_channel_mod_trig enable;
   0707010000050F000081B400000000000000000000000167AE111400000075000000000000000000000000000000000000006300000000susemanager-schema/upgrade/spacewalk-schema-0.7-to-spacewalk-schema-0.8/010-1-rhnFile-checksum.sql    alter table rhnFile add checksum_id NUMBER
        CONSTRAINT rhn_file_chsum_fk
        REFERENCES rhnChecksum (id);
   07070100000510000081B400000000000000000000000167AE1114000002BD000000000000000000000000000000000000005F00000000susemanager-schema/upgrade/spacewalk-schema-0.7-to-spacewalk-schema-0.8/010-2-rhnFile-data.sql    declare
 md5_id number;
begin
  select id
    into md5_id
    from rhnChecksumType
   where label = 'md5';

  insert into rhnChecksum (id, checksum_type_id, checksum)
         (select rhnChecksum_seq.nextval, md5_id, csum
            from (select distinct md5sum as csum
                    from rhnFile
                   minus
                  select checksum as csum
                    from rhnChecksum
                   where checksum_type_id = md5_id));
  commit;
  update rhnFile p
     set checksum_id = (select id
                          from rhnChecksum c
                         where checksum_type_id = md5_id
                           and p.md5sum =  c.checksum);
  commit;
end;
/

   07070100000511000081B400000000000000000000000167AE111400000029000000000000000000000000000000000000005E00000000susemanager-schema/upgrade/spacewalk-schema-0.7-to-spacewalk-schema-0.8/010-3-rhnFile-md5.sql alter table rhnFile drop column md5sum;

   07070100000512000081B400000000000000000000000167AE111400000038000000000000000000000000000000000000006300000000susemanager-schema/upgrade/spacewalk-schema-0.7-to-spacewalk-schema-0.8/010-4-rhnFile-checksum.sql    alter table rhnFile modify checksum_id NUMBER NOT NULL;
07070100000513000081B400000000000000000000000167AE11140000007B000000000000000000000000000000000000006600000000susemanager-schema/upgrade/spacewalk-schema-0.7-to-spacewalk-schema-0.8/011-1-rhnPackage-checksum.sql alter table rhnPackage add checksum_id NUMBER
        CONSTRAINT rhn_package_chsum_fk
        REFERENCES rhnChecksum (id);
 07070100000514000081B400000000000000000000000167AE1114000003AE000000000000000000000000000000000000006200000000susemanager-schema/upgrade/spacewalk-schema-0.7-to-spacewalk-schema-0.8/011-2-rhnPackage-data.sql -- 650129: we need to disable the trigger to prevent it from
-- automatically updating rhnPackage.last_modified values
alter trigger rhn_package_mod_trig disable;

declare
 md5_id number;
begin
  select id
    into md5_id
    from rhnChecksumType
   where label = 'md5';

  insert into rhnChecksum (id, checksum_type_id, checksum)
         (select rhnChecksum_seq.nextval, md5_id, csum
            from (select distinct md5sum as csum
                    from rhnPackage
                   minus
                  select checksum as csum
                    from rhnChecksum
                   where checksum_type_id = md5_id));
  commit;
  update rhnPackage p
     set checksum_id = (select id
                          from rhnChecksum c
                         where checksum_type_id = md5_id
                           and p.md5sum =  c.checksum);
  commit;
end;
/

-- enable the trigger again
alter trigger rhn_package_mod_trig enable;
  07070100000515000081B400000000000000000000000167AE11140000002B000000000000000000000000000000000000006100000000susemanager-schema/upgrade/spacewalk-schema-0.7-to-spacewalk-schema-0.8/011-3-rhnPackage-md5.sql  alter table rhnPackage drop column md5sum;
 07070100000516000081B400000000000000000000000167AE11140000003B000000000000000000000000000000000000006600000000susemanager-schema/upgrade/spacewalk-schema-0.7-to-spacewalk-schema-0.8/011-4-rhnPackage-checksum.sql alter table rhnPackage modify checksum_id NUMBER NOT NULL;
 07070100000517000081B400000000000000000000000167AE111400000084000000000000000000000000000000000000006A00000000susemanager-schema/upgrade/spacewalk-schema-0.7-to-spacewalk-schema-0.8/012-1-rhnPackageFile-checksum.sql alter table rhnPackageFile add checksum_id NUMBER
        CONSTRAINT rhn_package_file_chsum_fk
        REFERENCES rhnChecksum (id);
07070100000518000081B400000000000000000000000167AE1114000006A6000000000000000000000000000000000000006600000000susemanager-schema/upgrade/spacewalk-schema-0.7-to-spacewalk-schema-0.8/012-2-rhnPackageFile-data.sql declare
 md5_id number;
 min_pid number;
 max_pid number;
 lmin number;
 lmax number;
 incr number;
begin
  select id
    into md5_id
    from rhnChecksumType
   where label = 'md5';

  select min(package_id)
    into min_pid
    from rhnPackageFile;
  select max(package_id)
    into max_pid
    from rhnPackageFile;

  incr := 80000;
  lmin := min_pid;
  lmax := lmin + incr - 1;
  while lmin < max_pid loop
    insert into rhnChecksum (id, checksum_type_id, checksum)
           (select rhnChecksum_seq.nextval, md5_id, csum
              from (select /*+ index(p rhn_package_file_pid_cid_uq) */
                           distinct md5 as csum
                      from rhnPackageFile p
                     where package_id between lmin and lmax
                       and md5 is not null
                       and not exists (select /*+ index(c rhnChecksum_chsum_uq) */ 1
                                         from rhnChecksum c
                                        where p.md5 = c.checksum
                                          and c.checksum_type_id = md5_id)
                   )
           );
    commit;
    lmin := lmax + 1;
    lmax := lmin + incr -1;
  end loop;

  incr := 10000;
  lmin := min_pid;
  lmax := lmin + incr - 1;
  while lmin < max_pid loop
    update /*+ index(p rhn_package_file_pid_cid_uq) */ rhnPackageFile p
       set checksum_id = (select id
                            from rhnChecksum c
                           where checksum_type_id = md5_id
                             and p.md5 =  c.checksum)
     where package_id between lmin and lmax
       and md5 is not null;
    commit;
    lmin := lmax + 1;
    lmax := lmin + incr -1;
  end loop;
end;
/

  07070100000519000081B400000000000000000000000167AE111400000032000000000000000000000000000000000000006500000000susemanager-schema/upgrade/spacewalk-schema-0.7-to-spacewalk-schema-0.8/012-3-rhnPackageFile-md5.sql  alter table rhnPackageFile set unused column md5;
  0707010000051A000081B400000000000000000000000167AE111400000081000000000000000000000000000000000000006900000000susemanager-schema/upgrade/spacewalk-schema-0.7-to-spacewalk-schema-0.8/013-1-rhnErrataFile-checksum.sql  alter table rhnErrataFile add checksum_id NUMBER
        CONSTRAINT rhn_erratafile_chsum_fk
        REFERENCES rhnChecksum (id);
   0707010000051B000081B400000000000000000000000167AE111400000329000000000000000000000000000000000000006500000000susemanager-schema/upgrade/spacewalk-schema-0.7-to-spacewalk-schema-0.8/013-2-rhnErrataFile-data.sql  alter trigger rhn_errata_file_mod_trig disable;

declare
 md5_id number;
begin
  select id
    into md5_id
    from rhnChecksumType
   where label = 'md5';

  insert into rhnChecksum (id, checksum_type_id, checksum)
         (select rhnChecksum_seq.nextval, md5_id, csum
            from (select distinct md5sum as csum
                    from rhnErrataFile
                   minus
                  select checksum as csum
                    from rhnChecksum
                   where checksum_type_id = md5_id));
  commit;
  update rhnErrataFile p
     set checksum_id = (select id
                          from rhnChecksum c
                         where checksum_type_id = md5_id
                           and p.md5sum =  c.checksum);
  commit;
end;
/

alter trigger rhn_errata_file_mod_trig enable;
   0707010000051C000081B400000000000000000000000167AE11140000002E000000000000000000000000000000000000006400000000susemanager-schema/upgrade/spacewalk-schema-0.7-to-spacewalk-schema-0.8/013-3-rhnErrataFile-md5.sql   alter table rhnErrataFile drop column md5sum;
  0707010000051D000081B400000000000000000000000167AE11140000003E000000000000000000000000000000000000006900000000susemanager-schema/upgrade/spacewalk-schema-0.7-to-spacewalk-schema-0.8/013-4-rhnErrataFile-checksum.sql  alter table rhnErrataFile modify checksum_id NUMBER NOT NULL;
  0707010000051E000081B400000000000000000000000167AE111400000087000000000000000000000000000000000000006C00000000susemanager-schema/upgrade/spacewalk-schema-0.7-to-spacewalk-schema-0.8/014-1-rhnErrataFileTmp-checksum.sql   alter table rhnErrataFileTmp add checksum_id NUMBER
        CONSTRAINT rhn_erratafiletmp_chsum_fk
        REFERENCES rhnChecksum (id);
 0707010000051F000081B400000000000000000000000167AE111400000333000000000000000000000000000000000000006800000000susemanager-schema/upgrade/spacewalk-schema-0.7-to-spacewalk-schema-0.8/014-2-rhnErrataFileTmp-data.sql   alter trigger rhn_erratafiletmp_mod_trig disable;

declare
 md5_id number;
begin
  select id
    into md5_id
    from rhnChecksumType
   where label = 'md5';

  insert into rhnChecksum (id, checksum_type_id, checksum)
         (select rhnChecksum_seq.nextval, md5_id, csum
            from (select distinct md5sum as csum
                    from rhnErrataFileTmp
                   minus
                  select checksum as csum
                    from rhnChecksum
                   where checksum_type_id = md5_id));
  commit;
  update rhnErrataFileTmp p
     set checksum_id = (select id
                          from rhnChecksum c
                         where checksum_type_id = md5_id
                           and p.md5sum =  c.checksum);
  commit;
end;
/

alter trigger rhn_erratafiletmp_mod_trig enable;
 07070100000520000081B400000000000000000000000167AE111400000031000000000000000000000000000000000000006700000000susemanager-schema/upgrade/spacewalk-schema-0.7-to-spacewalk-schema-0.8/014-3-rhnErrataFileTmp-md5.sql    alter table rhnErrataFileTmp drop column md5sum;
   07070100000521000081B400000000000000000000000167AE111400000041000000000000000000000000000000000000006C00000000susemanager-schema/upgrade/spacewalk-schema-0.7-to-spacewalk-schema-0.8/014-4-rhnErrataFileTmp-checksum.sql   alter table rhnErrataFileTmp modify checksum_id NUMBER NOT NULL;
   07070100000522000081B400000000000000000000000167AE111400000081000000000000000000000000000000000000006900000000susemanager-schema/upgrade/spacewalk-schema-0.7-to-spacewalk-schema-0.8/015-1-rhnKSTreeFile-checksum.sql  alter table rhnKSTreeFile add checksum_id NUMBER
        CONSTRAINT rhn_kstreefile_chsum_fk
        REFERENCES rhnChecksum (id);
   07070100000523000081B400000000000000000000000167AE1114000003CD000000000000000000000000000000000000006500000000susemanager-schema/upgrade/spacewalk-schema-0.7-to-spacewalk-schema-0.8/015-2-rhnKSTreeFile-data.sql  -- 650129: we need to disable the trigger here to prevent it from
-- automatically updating rhnKSTreeFile.last_modified values
alter trigger rhn_kstreefile_mod_trig disable;

declare
 md5_id number;
begin
  select id
    into md5_id
    from rhnChecksumType
   where label = 'md5';

  insert into rhnChecksum (id, checksum_type_id, checksum)
         (select rhnChecksum_seq.nextval, md5_id, csum
            from (select distinct md5sum as csum
                    from rhnKSTreeFile
                   minus
                  select checksum as csum
                    from rhnChecksum
                   where checksum_type_id = md5_id));
  commit;
  update rhnKSTreeFile p
     set checksum_id = (select id
                          from rhnChecksum c
                         where checksum_type_id = md5_id
                           and p.md5sum =  c.checksum);
  commit;
end;
/

-- we need to enable the trigger again
alter trigger rhn_kstreefile_mod_trig enable;
   07070100000524000081B400000000000000000000000167AE11140000002E000000000000000000000000000000000000006400000000susemanager-schema/upgrade/spacewalk-schema-0.7-to-spacewalk-schema-0.8/015-3-rhnKSTreeFile-md5.sql   alter table rhnKSTreeFile drop column md5sum;
  07070100000525000081B400000000000000000000000167AE11140000003E000000000000000000000000000000000000006900000000susemanager-schema/upgrade/spacewalk-schema-0.7-to-spacewalk-schema-0.8/015-4-rhnKSTreeFile-checksum.sql  alter table rhnKSTreeFile modify checksum_id NUMBER NOT NULL;
  07070100000526000081B400000000000000000000000167AE111400000085000000000000000000000000000000000000006C00000000susemanager-schema/upgrade/spacewalk-schema-0.7-to-spacewalk-schema-0.8/016-1-rhnConfigContent-checksum.sql   alter table rhnConfigContent add checksum_id NUMBER
        CONSTRAINT rhn_confcontent_chsum_fk
        REFERENCES rhnChecksum (id);
   07070100000527000081B400000000000000000000000167AE11140000032F000000000000000000000000000000000000006800000000susemanager-schema/upgrade/spacewalk-schema-0.7-to-spacewalk-schema-0.8/016-2-rhnConfigContent-data.sql   alter trigger rhn_confcontent_mod_trig disable;

declare
 md5_id number;
begin
  select id
    into md5_id
    from rhnChecksumType
   where label = 'md5';

  insert into rhnChecksum (id, checksum_type_id, checksum)
         (select rhnChecksum_seq.nextval, md5_id, csum
            from (select distinct md5sum as csum
                    from rhnConfigContent
                   minus
                  select checksum as csum
                    from rhnChecksum
                   where checksum_type_id = md5_id));
  commit;
  update rhnConfigContent p
     set checksum_id = (select id
                          from rhnChecksum c
                         where checksum_type_id = md5_id
                           and p.md5sum =  c.checksum);
  commit;
end;
/

alter trigger rhn_confcontent_mod_trig enable;
 07070100000528000081B400000000000000000000000167AE111400000031000000000000000000000000000000000000006700000000susemanager-schema/upgrade/spacewalk-schema-0.7-to-spacewalk-schema-0.8/016-3-rhnConfigContent-md5.sql    alter table rhnConfigContent drop column md5sum;
   07070100000529000081B400000000000000000000000167AE111400000041000000000000000000000000000000000000006C00000000susemanager-schema/upgrade/spacewalk-schema-0.7-to-spacewalk-schema-0.8/016-4-rhnConfigContent-checksum.sql   alter table rhnConfigContent modify checksum_id NUMBER NOT NULL;
   0707010000052A000081B400000000000000000000000167AE111400000106000000000000000000000000000000000000006C00000000susemanager-schema/upgrade/spacewalk-schema-0.7-to-spacewalk-schema-0.8/017-1-rhnPackageSource-checksum.sql   alter table rhnPackageSource add sigchecksum_id NUMBER
        CONSTRAINT rhn_pkgsrc_sigchsum_fk
        REFERENCES rhnChecksum (id);
alter table rhnPackageSource add checksum_id NUMBER
        CONSTRAINT rhn_pkgsrc_chsum_fk
        REFERENCES rhnChecksum (id);
  0707010000052B000081B400000000000000000000000167AE11140000055D000000000000000000000000000000000000006800000000susemanager-schema/upgrade/spacewalk-schema-0.7-to-spacewalk-schema-0.8/017-2-rhnPackageSource-data.sql   alter trigger rhn_pkgsrc_mod_trig disable;

declare
 md5_id number;
begin
  select id
    into md5_id
    from rhnChecksumType
   where label = 'md5';

  insert into rhnChecksum (id, checksum_type_id, checksum)
         (select rhnChecksum_seq.nextval, md5_id, csum
            from (select distinct sigmd5 as csum
                    from rhnPackageSource
                   minus
                  select checksum as csum
                    from rhnChecksum
                   where checksum_type_id = md5_id));
  commit;
  insert into rhnChecksum (id, checksum_type_id, checksum)
         (select rhnChecksum_seq.nextval, md5_id, csum
            from (select distinct md5sum as csum
                    from rhnPackageSource
                   minus
                  select checksum as csum
                    from rhnChecksum
                   where checksum_type_id = md5_id));
  commit;
  update rhnPackageSource p
     set sigchecksum_id = (select id
                          from rhnChecksum c
                         where checksum_type_id = md5_id
                           and p.sigmd5 =  c.checksum),
         checksum_id = (select id
                          from rhnChecksum c
                         where checksum_type_id = md5_id
                           and p.md5sum =  c.checksum);
  commit;
end;
/

alter trigger rhn_pkgsrc_mod_trig enable;
   0707010000052C000081B400000000000000000000000167AE111400000062000000000000000000000000000000000000006700000000susemanager-schema/upgrade/spacewalk-schema-0.7-to-spacewalk-schema-0.8/017-3-rhnPackageSource-md5.sql    alter table rhnPackageSource drop column sigmd5;
alter table rhnPackageSource drop column md5sum;
  0707010000052D000081B400000000000000000000000167AE111400000085000000000000000000000000000000000000006C00000000susemanager-schema/upgrade/spacewalk-schema-0.7-to-spacewalk-schema-0.8/017-4-rhnPackageSource-checksum.sql   alter table rhnPackageSource modify sigchecksum_id NUMBER NOT NULL;
alter table rhnPackageSource modify checksum_id NUMBER NOT NULL;
   0707010000052E000081B400000000000000000000000167AE11140000008D000000000000000000000000000000000000007000000000susemanager-schema/upgrade/spacewalk-schema-0.7-to-spacewalk-schema-0.8/018-1-rhnAppInstallSession-checksum.sql   alter table rhnAppInstallSession add checksum_id NUMBER
        CONSTRAINT rhn_appinst_session_chsum_fk
        REFERENCES rhnChecksum (id);
   0707010000052F000081B400000000000000000000000167AE11140000031F000000000000000000000000000000000000006C00000000susemanager-schema/upgrade/spacewalk-schema-0.7-to-spacewalk-schema-0.8/018-2-rhnAppInstallSession-data.sql   declare
 md5_id number;
begin
  select id
    into md5_id
    from rhnChecksumType
   where label = 'md5';

  insert into rhnChecksum (id, checksum_type_id, checksum)
         (select rhnChecksum_seq.nextval, md5_id, csum
            from (select distinct md5sum as csum
                    from rhnAppInstallSession
                   where md5sum is not null
                   minus
                  select checksum as csum
                    from rhnChecksum
                   where checksum_type_id = md5_id));
  commit;
  update rhnAppInstallSession p
     set checksum_id = (select id
                          from rhnChecksum c
                         where checksum_type_id = md5_id
                           and p.md5sum =  c.checksum)
   where md5sum is not null;
  commit;
end;
/

 07070100000530000081B400000000000000000000000167AE111400000035000000000000000000000000000000000000006B00000000susemanager-schema/upgrade/spacewalk-schema-0.7-to-spacewalk-schema-0.8/018-3-rhnAppInstallSession-md5.sql    alter table rhnAppInstallSession drop column md5sum;
   07070100000531000081B400000000000000000000000167AE111400000144000000000000000000000000000000000000007700000000susemanager-schema/upgrade/spacewalk-schema-0.7-to-spacewalk-schema-0.8/019-1-rhnServerActionVerifyResult-checksum.sql    alter table rhnServerActionVerifyResult
        rename column md5_differs to checksum_differs;
alter table rhnServerActionVerifyResult
        drop constraint rhn_sactionvr_md5_ck;
alter table rhnServerActionVerifyResult
        add constraint rhn_sactionvr_chsum_ck
        CHECK (checksum_differs in ( 'Y' , 'N' , '?' ));
07070100000532000081B400000000000000000000000167AE111400000299000000000000000000000000000000000000006600000000susemanager-schema/upgrade/spacewalk-schema-0.7-to-spacewalk-schema-0.8/020-1-rhnKickstartPackage.sql declare
  i number;
begin
  for rec in (
    select kickstart_id kid
    from rhnKickstartPackage
    where position = 0
    group by kickstart_id
    having count(*) > 1
  ) loop
    i := 0;
    for erec in (
      select rhnKickstartPackage.rowid rid
      from rhnKickstartPackage, rhnPackageName
      where rhnKickstartPackage.package_name_id = rhnPackageName.id
        and rhnKickstartPackage.kickstart_id = rec.kid
      order by rhnKickstartPackage.position, rhnPackageName.name
    ) loop
      update rhnKickstartPackage
      set position = i
      where rhnKickstartPackage.rowid = erec.rid;
      i := i + 1;
    end loop;
  end loop;
end;
/

commit;
   07070100000533000081B400000000000000000000000167AE1114000000B1000000000000000000000000000000000000006600000000susemanager-schema/upgrade/spacewalk-schema-0.7-to-spacewalk-schema-0.8/020-2-rhnKickstartPackage.sql DROP INDEX rhn_kspackage_id_idx;

ALTER TABLE rhnKickstartPackage
    ADD CONSTRAINT rhn_kspackage_pos_uq UNIQUE (kickstart_id, position)
    USING INDEX TABLESPACE [[4m_tbs]];
   07070100000534000081B400000000000000000000000167AE111400002524000000000000000000000000000000000000006200000000susemanager-schema/upgrade/spacewalk-schema-0.7-to-spacewalk-schema-0.8/050-1-rhn_channel.pks.sql --
-- Copyright (c) 2008--2010 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--
--
--
--

CREATE OR REPLACE
PACKAGE rhn_channel
IS
	version varchar2(100) := '';

    CURSOR server_base_subscriptions(server_id_in NUMBER) IS
	   SELECT C.id
	     FROM rhnChannel C, rhnServerChannel SC
	    WHERE C.id = SC.channel_id
	      AND SC.server_id = server_id_in
	      AND C.parent_channel IS NULL;

    CURSOR check_server_subscription(server_id_in NUMBER, channel_id_in NUMBER) IS
           SELECT channel_id
	     FROM rhnServerChannel
	    WHERE server_id = server_id_in
	      AND channel_id = channel_id_in;

    CURSOR check_server_parent_membership(server_id_in NUMBER, channel_id_in NUMBER) IS
	   SELECT C.id
	     FROM rhnChannel C, rhnServerChannel SC
	    WHERE C.parent_channel = channel_id_in
	      AND C.id = SC.channel_id
	      AND SC.server_id = server_id_in;

    CURSOR channel_family_perm_cursor(channel_family_id_in NUMBER, org_id_in NUMBER) IS
           SELECT *
	     FROM rhnOrgChannelFamilyPermissions
	    WHERE channel_family_id = channel_family_id_in
	      AND org_id = org_id_in;

    PROCEDURE license_consent(channel_id_in IN NUMBER, user_id_in IN NUMBER, server_id_in IN NUMBER);
    FUNCTION get_license_path(channel_id_in IN NUMBER) RETURN VARCHAR2;

    PROCEDURE unsubscribe_server(server_id_in IN NUMBER, channel_id_in NUMBER, immediate_in NUMBER := 1, unsubscribe_children_in number := 0,
                                 deleting_server in number := 0,
                                 update_family_countsYN IN NUMBER := 1);
    PROCEDURE subscribe_server(server_id_in IN NUMBER, channel_id_in NUMBER, immediate_in NUMBER := 1, user_id_in number := null, recalcfamily_in number := 1);

    function can_server_consume_virt_channl(
        server_id_in IN NUMBER,
        family_id_in in number)
    return number;

    FUNCTION guess_server_base(server_id_in IN NUMBER) RETURN NUMBER;

    FUNCTION base_channel_for_release_arch(release_in in varchar2,
	server_arch_in in varchar2, org_id_in in number := -1,
	user_id_in in number := null) RETURN number;

    FUNCTION base_channel_rel_archid(release_in in varchar2,
	server_arch_id_in in number, org_id_in in number := -1,
	user_id_in in number := null) RETURN number;

    FUNCTION channel_priority(channel_id_in in number) RETURN number;

    PROCEDURE bulk_subscribe_server(channel_id_in IN NUMBER, set_label_in IN VARCHAR2, set_uid_in IN NUMBER);
    PROCEDURE bulk_unsubscribe_server(channel_id_in IN NUMBER, set_label_in IN VARCHAR2, set_uid_in IN NUMBER);

    PROCEDURE bulk_server_base_change(channel_id_in IN NUMBER, set_label_in IN VARCHAR2, set_uid_in IN NUMBER);
    procedure bulk_server_basechange_from(
	set_label_in in varchar2,
	set_uid_in in number,
	old_channel_id_in in number,
	new_channel_id_in in number);

    procedure bulk_guess_server_base(
	set_label_in in varchar2,
	set_uid_in in number);

    procedure bulk_guess_server_base_from(
	set_label_in in varchar2,
	set_uid_in in number,
	channel_id_in in number);

    PROCEDURE clear_subscriptions(server_id_in IN NUMBER, deleting_server in number := 0,
                                update_family_countsYN IN NUMBER := 1);

    FUNCTION available_family_subscriptions(channel_family_id_in IN NUMBER, org_id_in IN NUMBER) RETURN NUMBER;

    function channel_family_current_members(channel_family_id_in IN NUMBER,
                                            org_id_in IN NUMBER)
    return number;

    PROCEDURE update_family_counts(channel_family_id_in IN NUMBER, org_id_in IN NUMBER);
    PROCEDURE update_group_family_counts(group_label_in IN VARCHAR2, org_id_in IN NUMBER);
    FUNCTION family_for_channel(channel_id_in IN NUMBER) RETURN NUMBER;

    FUNCTION available_chan_subscriptions(channel_id_in IN NUMBER, org_id_in IN NUMBER) RETURN NUMBER;

    procedure entitle_customer(customer_id_in in number, channel_family_id_in in number, quantity_in in number);
    procedure set_family_maxmembers(customer_id_in in number, channel_family_id_in in number, quantity_in in number);
    procedure unsubscribe_server_from_family(server_id_in in number, channel_family_id_in in number);

    procedure delete_server_channels(server_id_in in number);
    procedure refresh_newest_package(channel_id_in in number, caller_in in varchar2 := '(unknown)');

    function get_org_id(channel_id_in in number) return number;
    PRAGMA RESTRICT_REFERENCES(get_org_id, WNDS, RNPS, WNPS);

    function get_org_access(channel_id_in in number, org_id_in in number) return number;
    PRAGMA RESTRICT_REFERENCES(get_org_access, WNDS, RNPS, WNPS);

    function get_cfam_org_access(cfam_id_in in number, org_id_in in number) return number;

    function user_role_check_debug(channel_id_in in number, user_id_in in number, role_in in varchar2, reason_out out varchar2)
	RETURN NUMBER;
    PRAGMA RESTRICT_REFERENCES(user_role_check_debug, WNDS, RNPS, WNPS);

    function user_role_check(channel_id_in in number, user_id_in in number, role_in in varchar2)
	RETURN NUMBER;
    PRAGMA RESTRICT_REFERENCES(user_role_check, WNDS, RNPS, WNPS);

    function loose_user_role_check(channel_id_in in number, user_id_in in number, role_in in varchar2)
	RETURN NUMBER;
    PRAGMA RESTRICT_REFERENCES(loose_user_role_check, WNDS, RNPS, WNPS);

    function direct_user_role_check(channel_id_in in number, user_id_in in number, role_in in varchar2)
	RETURN NUMBER;
    PRAGMA RESTRICT_REFERENCES(direct_user_role_check, WNDS, RNPS, WNPS);

    function shared_user_role_check(channel_id in number, user_id in number, role in varchar2)
	RETURN NUMBER;
    PRAGMA RESTRICT_REFERENCES(shared_user_role_check, WNDS, RNPS, WNPS);

    function org_channel_setting(channel_id_in in number, org_id_in in number, setting_in in varchar2)
	RETURN NUMBER;

    PROCEDURE update_channel ( channel_id_in in number, invalidate_ss in number := 0,
                               date_to_use in date := sysdate );

    PROCEDURE  update_channels_by_package ( package_id_in in number, date_to_use in date := sysdate );

     PROCEDURE update_channels_by_errata ( errata_id_in number, date_to_use in date := sysdate );


    PRAGMA RESTRICT_REFERENCES(org_channel_setting, WNDS, RNPS, WNPS);

END rhn_channel;
/
SHOW ERRORS

--
-- Revision 1.37  2004/04/14 00:09:24  pjones
-- bugzilla: 120761 -- split rhnChannelPermissions into two tables, eliminating
-- a frequent full table scan
--
-- Revision 1.36  2004/03/26 18:11:32  rbb
-- Bugzilla:  114057
--
-- Add a script to determine channel priority.
--
-- Revision 1.35  2004/02/17 20:16:52  pjones
-- bugzilla: none -- add cvs tags into the package as long as we're touching
-- it anyway
--
-- Revision 1.34  2003/11/13 18:13:09  cturner
-- pragmas can now return now that rhn_user pragmas are fixed
--
-- Revision 1.32  2003/09/22 21:00:40  cturner
-- add method for easy acl check
--
-- Revision 1.31  2003/09/17 22:14:11  misa
-- bugzilla: 103639  Changes to allow me to move the base channel guess into plsql
--
-- Revision 1.30  2003/07/24 16:44:16  misa
-- bugzilla: none  A function more usable on the rhnapp side
--
-- Revision 1.29  2003/07/24 14:00:17  misa
-- bugzilla: none  PRAGMA RESTRICT_REFERENCES good
--
-- Revision 1.28  2003/07/23 21:59:19  cturner
-- rework how rhnUserChannel works; move to plsql for speed and maintenance
--
-- Revision 1.27  2003/07/21 17:49:12  pjones
-- bugzilla: none
--
-- add optional user for subscribe_server
--
-- Revision 1.26  2002/12/19 18:13:42  misa
-- Added caller with a default value
--
-- Revision 1.25  2002/12/11 22:18:46  pjones
-- rhnChannelNewestPackage
--
-- Revision 1.24  2002/11/21 22:08:11  pjones
-- make unsubscribe_channels have a "unsubscribe_children_in number := 0"
-- argument so that you can tell it to unsubscribe children.
--
-- Also, make it raise an exception instead of silent failure in the
-- other case.
--
-- Revision 1.23  2002/11/18 17:20:50  pjones
-- this should have gone back too
--
-- Revision 1.22  2002/11/13 23:16:18  pjones
-- lookup_*_arch()
--
-- Revision 1.21  2002/10/07 20:01:59  rnorwood
-- guess base channel for ssm and single system
--
-- Revision 1.20  2002/10/02 19:21:03  bretm
-- o  3rd party channel schema changes, no more clobs...
--
-- Revision 1.19  2002/09/20 19:21:58  bretm
-- o  more 3rd party channel stuff...
--
-- Revision 1.18  2002/06/12 22:33:03  pjones
-- procedure bulk_guess_server_base_from(
--     set_label_in in varchar2,
--     set_uid_in in number,
--     channel_id_in in number);
--
-- for bretm
--
-- Revision 1.17  2002/06/12 22:12:25  pjones
-- procedure bulk_guess_server_base(
--     set_label_in in varchar2,
--     set_uid_in in number);
--
-- for bretm
--
-- Revision 1.16  2002/06/12 19:37:55  pjones
-- bulk_server_basechange_from(
-- 	set_label_in in varchar2,
-- 	set_uid_in in number,
-- 	old_channel_id_in in number,
-- 	new_channel_id_in in number
-- );
--
-- for bretm
--
-- Revision 1.15  2002/05/10 22:08:22  pjones
-- id/log
--
07070100000535000081B400000000000000000000000167AE11140000C91F000000000000000000000000000000000000006200000000susemanager-schema/upgrade/spacewalk-schema-0.7-to-spacewalk-schema-0.8/050-2-rhn_channel.pkb.sql --
-- Copyright (c) 2008--2010 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--
--
--
--

CREATE OR REPLACE
PACKAGE BODY rhn_channel
IS
        body_version varchar2(100) := '';

    -- Cursor that fetches all the possible base channels for a
    -- (server_arch_id, release, org_id) combination
        cursor  base_channel_cursor(
                release_in in varchar2,
                server_arch_id_in in number,
                org_id_in in number
        ) return rhnChannel%ROWTYPE is
                select distinct c.*
                from    rhnDistChannelMap                       dcm,
                                rhnServerChannelArchCompat      scac,
                                rhnChannel                                      c,
                                rhnChannelPermissions           cp
                where   cp.org_id = org_id_in
                        and cp.channel_id = c.id
                        and c.parent_channel is null
                        and c.id = dcm.channel_id
                        and c.channel_arch_id = dcm.channel_arch_id
                        and dcm.release = release_in
                        and scac.server_arch_id = server_arch_id_in
                        and scac.channel_arch_id = c.channel_arch_id;

    FUNCTION get_license_path(channel_id_in IN NUMBER)
    RETURN VARCHAR2
    IS
        license_val VARCHAR2(1000);
    BEGIN
        SELECT CFL.license_path INTO license_val
          FROM rhnChannelFamilyLicense CFL, rhnChannelFamilyMembers CFM
         WHERE CFM.channel_id = channel_id_in
           AND CFM.channel_family_id = CFL.channel_family_id;

        RETURN license_val;

    EXCEPTION
        WHEN NO_DATA_FOUND
            THEN
            RETURN NULL;
    END get_license_path;


    PROCEDURE license_consent(channel_id_in IN NUMBER, user_id_in IN NUMBER, server_id_in IN NUMBER)
    IS
        channel_family_id_val NUMBER;
    BEGIN
        channel_family_id_val := rhn_channel.family_for_channel(channel_id_in);
        IF channel_family_id_val IS NULL
        THEN
            rhn_exception.raise_exception('channel_subscribe_no_family');
        END IF;

        IF rhn_channel.get_license_path(channel_id_in) IS NULL
        THEN
            rhn_exception.raise_exception('channel_consent_no_license');
        END IF;

        INSERT INTO rhnChannelFamilyLicenseConsent (channel_family_id, user_id, server_id)
        VALUES (channel_family_id_val, user_id_in, server_id_in);
    END license_consent;

    PROCEDURE subscribe_server(server_id_in IN NUMBER, channel_id_in NUMBER, immediate_in NUMBER := 1, user_id_in in number := null, recalcfamily_in NUMBER := 1)
    IS
        channel_parent_val      rhnChannel.parent_channel%TYPE;
        parent_subscribed       BOOLEAN;
        server_has_base_chan    BOOLEAN;
        server_already_in_chan  BOOLEAN;
        channel_family_id_val   NUMBER;
        server_org_id_val       NUMBER;
        available_subscriptions NUMBER;
        consenting_user         NUMBER;
        allowed                 number := 0;
        current_members_val     number;
    BEGIN
        if user_id_in is not null then
            allowed := rhn_channel.user_role_check(channel_id_in, user_id_in, 'subscribe');
        else
            allowed := 1;
        end if;

        if allowed = 0 then
            rhn_exception.raise_exception('no_subscribe_permissions');
        end if;


        SELECT parent_channel INTO channel_parent_val FROM rhnChannel WHERE id = channel_id_in;

        IF channel_parent_val IS NOT NULL
        THEN
            -- child channel; if attempting to cross-subscribe a child to the wrong base, silently ignore
            parent_subscribed := FALSE;

            FOR check_subscription IN check_server_subscription(server_id_in, channel_parent_val)
            LOOP
                parent_subscribed := TRUE;
            END LOOP check_subscription;

            IF NOT parent_subscribed
            THEN
                RETURN;
            END IF;
        ELSE
            -- base channel
            server_has_base_chan := FALSE;
            FOR base IN server_base_subscriptions(server_id_in)
            LOOP
                server_has_base_chan := TRUE;
            END LOOP base;

            IF server_has_base_chan
            THEN
                rhn_exception.raise_exception('channel_server_one_base');
            END IF;
        END IF;

        FOR check_subscription IN check_server_subscription(server_id_in, channel_id_in)
        LOOP
            server_already_in_chan := TRUE;
        END LOOP check_subscription;

        IF server_already_in_chan
        THEN
            RETURN;
        END IF;

        channel_family_id_val := rhn_channel.family_for_channel(channel_id_in);
        IF channel_family_id_val IS NULL
        THEN
            rhn_exception.raise_exception('channel_subscribe_no_family');
        END IF;

        --
        -- Use the org_id of the server only if the org_id of the channel = NULL.
        -- This is required for subscribing to shared channels.
        --
        SELECT NVL(org_id, (SELECT org_id FROM rhnServer WHERE id = server_id_in))
          INTO server_org_id_val
          FROM rhnChannel
         WHERE id = channel_id_in;

        select current_members
        into current_members_val
        from rhnPrivateChannelFamily
        where org_id = server_org_id_val and channel_family_id = channel_family_id_val
        for update of current_members;

        available_subscriptions := rhn_channel.available_family_subscriptions(channel_family_id_val, server_org_id_val);

        IF available_subscriptions IS NULL OR
           available_subscriptions > 0 or
           can_server_consume_virt_channl(server_id_in, channel_family_id_val) = 1
        THEN

            IF rhn_channel.get_license_path(channel_id_in) IS NOT NULL
            THEN
                BEGIN

                SELECT user_id INTO consenting_user
                  FROM rhnChannelFamilyLicenseConsent
                 WHERE channel_family_id = channel_family_id_val
                   AND server_id = server_id_in;

                EXCEPTION
                    WHEN NO_DATA_FOUND THEN
                        rhn_exception.raise_exception('channel_subscribe_no_consent');
                END;
            END IF;

            insert into rhnServerHistory (id,server_id,summary,details) (
                select  rhn_event_id_seq.nextval,
                        server_id_in,
                        'subscribed to channel ' || SUBSTR(c.label, 0, 106),
                        c.label
                from    rhnChannel c
                where   c.id = channel_id_in
            );
            UPDATE rhnServer SET channels_changed = sysdate WHERE id = server_id_in;
            INSERT INTO rhnServerChannel (server_id, channel_id) VALUES (server_id_in, channel_id_in);
			IF recalcfamily_in > 0
			THEN
                rhn_channel.update_family_counts(channel_family_id_val, server_org_id_val);
			END IF;
            queue_server(server_id_in, immediate_in);
        ELSE
            rhn_exception.raise_exception('channel_family_no_subscriptions');
        END IF;

    END subscribe_server;

    function can_server_consume_virt_channl(
        server_id_in in number,
        family_id_in in number )
    return number
    is

        cursor server_virt_families is
            select vi.virtual_system_id, cfvsl.channel_family_id
            from
                rhnChannelFamilyVirtSubLevel cfvsl,
                rhnSGTypeVirtSubLevel sgtvsl,
                rhnVirtualInstance vi
            where
                vi.virtual_system_id = server_id_in
                and sgtvsl.virt_sub_level_id = cfvsl.virt_sub_level_id
                and cfvsl.channel_family_id = family_id_in
                and exists (
                    select 1
                    from rhnServerEntitlementView sev
                    where vi.host_system_id = sev.server_id
                    and sev.server_group_type_id = sgtvsl.server_group_type_id );
    begin

        for server_virt_family in server_virt_families loop
            return 1;
        end loop;

        return 0;

    end;


    PROCEDURE bulk_subscribe_server(channel_id_in IN NUMBER, set_label_in IN VARCHAR2, set_uid_in IN NUMBER)
    IS
    BEGIN
        FOR server IN rhn_set.set_iterator(set_label_in, set_uid_in)
        LOOP
            rhn_channel.subscribe_server(server.element, channel_id_in, 0, set_uid_in);
        END LOOP server;
    END bulk_subscribe_server;

    PROCEDURE bulk_server_base_change(channel_id_in IN NUMBER, set_label_in IN VARCHAR2, set_uid_in IN NUMBER)
    IS
    BEGIN
        FOR server IN rhn_set.set_iterator(set_label_in, set_uid_in)
        LOOP
            IF rhn_server.can_change_base_channel(server.element) = 1
            THEN
                rhn_channel.clear_subscriptions(TO_NUMBER(server.element));
                rhn_channel.subscribe_server(server.element, channel_id_in, 0, set_uid_in);
            END IF;
        END LOOP server;
    END bulk_server_base_change;

    procedure bulk_server_basechange_from(
        set_label_in in varchar2,
        set_uid_in in number,
        old_channel_id_in in number,
        new_channel_id_in in number
    ) is
    cursor servers is
        select  sc.server_id id
        from    rhnChannel nc,
                rhnServerChannelArchCompat scac,
                rhnServer s,
                rhnChannel oc,
                rhnServerChannel sc,
                rhnSet st
        where   1=1
            -- first, find the servers we're looking for.
            and st.label = set_label_in
            and st.user_id = set_uid_in
            and st.element = sc.server_id
            -- now, filter out anything that's not in the
            -- old base channel.
            and sc.channel_id = old_channel_id_in
            and sc.channel_id = oc.id
            and oc.parent_channel is null
            -- now, see if it's compatible with the new base channel
            and nc.id = new_channel_id_in
            and nc.parent_channel is null
            and sc.server_id = s.id
            and s.server_arch_id = scac.server_arch_id
            and scac.channel_arch_id = nc.channel_arch_id;
    begin
        for s in servers loop
            insert into rhnSet (
                    user_id, label, element
                ) values (
                    set_uid_in,
                    set_label_in || 'basechange',
                    s.id
                );
        end loop channel;
        bulk_server_base_change(new_channel_id_in,
                                set_label_in || 'basechange',
                                set_uid_in);
        delete from rhnSet
            where   label = set_label_in||'basechange'
                and user_id = set_uid_in;
    end bulk_server_basechange_from;

    procedure bulk_guess_server_base(
        set_label_in in varchar2,
        set_uid_in in number
    ) is
        channel_id number;
    begin
        for server in rhn_set.set_iterator(set_label_in, set_uid_in)
        loop
            -- anything that doesn't work, we just ignore
            begin
                if rhn_server.can_change_base_channel(server.element) = 1
                then
                    channel_id := guess_server_base(TO_NUMBER(server.element));
                    rhn_channel.clear_subscriptions(TO_NUMBER(server.element));
                    rhn_channel.subscribe_server(TO_NUMBER(server.element), channel_id, 0, set_uid_in);
                end if;
            exception when others then
                null;
            end;
        end loop server;
    end;

    function guess_server_base(
        server_id_in in number
    ) RETURN number is
        cursor server_cursor is
            select s.server_arch_id, s.release, s.org_id
              from rhnServer s
             where s.id = server_id_in;
    begin
        for s in server_cursor loop
            for channel in base_channel_cursor(s.release,
                s.server_arch_id, s.org_id)
            loop
                return channel.id;
            end loop base_channel_cursor;
        end loop server_cursor;
        -- Server not found, or no base channel applies to it
        return null;
    end;

    -- Private function
    function normalize_server_arch(server_arch_in in varchar2)
    return varchar2
    deterministic
    is
        suffix VARCHAR2(128) := '-redhat-linux';
        suffix_len NUMBER := length(suffix);
    begin
        if server_arch_in is NULL then
            return NULL;
        end if;
        if instr(server_arch_in, '-') > 0
        then
            -- Suffix already present
            return server_arch_in;
        end if;
        return server_arch_in || suffix;
    end normalize_server_arch;

    --
    --
    -- Raises:
    --   server_arch_not_found
    --   no_subscribe_permissions
    function base_channel_for_release_arch(
        release_in in varchar2,
        server_arch_in in varchar2,
        org_id_in in number := -1,
        user_id_in in number := null
    ) return number is
        server_arch varchar2(256) := normalize_server_arch(server_arch_in);
        server_arch_id number;
    begin
        -- Look up the server arch
        begin
            select id
              into server_arch_id
              from rhnServerArch
             where label = server_arch;
        exception
            when no_data_found then
                rhn_exception.raise_exception('server_arch_not_found');
        end;
        return base_channel_rel_archid(release_in, server_arch_id,
            org_id_in, user_id_in);
    end base_channel_for_release_arch;

    function base_channel_rel_archid(
        release_in in varchar2,
        server_arch_id_in in number,
        org_id_in in number := -1,
        user_id_in in number := null
    ) return number is
        denied_channel_id number := null;
        valid_org_id number := org_id_in;
        valid_user_id number := user_id_in;
        channel_subscribable number;
    begin
        if org_id_in = -1 and user_id_in is not null then
            -- Get the org id from the user id
            begin
                select org_id
                  into valid_org_id
                  from web_contact
                 where id = user_id_in;
            exception
                when no_data_found then
                    -- User doesn't exist
                    -- XXX Only list public stuff for now
                    valid_user_id := null;
                    valid_org_id := -1;
            end;
        end if;

        for c in base_channel_cursor(release_in, server_arch_id_in, valid_org_id)
        loop
            -- This row is a possible match
            if valid_user_id is null then
                -- User ID not specified, so no user to channel permissions to
                -- check
                return c.id;
            end if;

            -- Check user to channel permissions
            select loose_user_role_check(c.id, user_id_in, 'subscribe')
              into channel_subscribable
              from dual;

            if channel_subscribable = 1 then
                return c.id;
            end if;

            -- Base channel exists, but is not subscribable; keep trying
            denied_channel_id := c.id;
        end loop base_channel_fetch;

        if denied_channel_id is not null then
            rhn_exception.raise_exception('no_subscribe_permissions');
        end if;
        -- No base channel applies
        return NULL;
    end base_channel_rel_archid;

    procedure bulk_guess_server_base_from(
        set_label_in in varchar2,
        set_uid_in in number,
        channel_id_in in number
    ) is
        cursor channels(server_id_in in number) is
            select      rsc.channel_id
            from        rhnServerChannel rsc,
                        rhnChannel rc
            where       server_id_in = rsc.server_id
                        and rsc.channel_id = rc.id
                        and rc.parent_channel is null;
    begin
        for server in rhn_set.set_iterator(set_label_in, set_uid_in)
        loop
            for channel in channels(server.element)
            loop
                if channel.channel_id = channel_id_in
                then
                    insert into rhnSet (user_id, label, element) values (set_uid_in, set_label_in || 'baseguess', server.element);
                end if;
            end loop channel;
        end loop server;
        bulk_guess_server_base(set_label_in||'baseguess',set_uid_in);
        delete from rhnSet where label = set_label_in||'baseguess' and user_id = set_uid_in;
    end;


    PROCEDURE clear_subscriptions(server_id_in IN NUMBER, deleting_server IN NUMBER := 0,
                                update_family_countsYN IN NUMBER := 1)
    IS
        cursor server_channels(server_id_in in number) is
                select  s.org_id, sc.channel_id, cfm.channel_family_id
                from    rhnServer s,
                        rhnServerChannel sc,
                        rhnChannelFamilyMembers cfm
                where   s.id = server_id_in
                        and s.id = sc.server_id
                        and sc.channel_id = cfm.channel_id;
    BEGIN
        for channel in server_channels(server_id_in)
        loop
                unsubscribe_server(server_id_in, channel.channel_id, 1, 1, deleting_server, update_family_countsYN);
        end loop channel;
    END clear_subscriptions;

    PROCEDURE unsubscribe_server(server_id_in IN NUMBER, channel_id_in NUMBER, immediate_in NUMBER := 1, unsubscribe_children_in number := 0,
                                 deleting_server IN NUMBER := 0,
                                 update_family_countsYN IN NUMBER := 1)
    IS
        channel_family_id_val   NUMBER;
        server_org_id_val       NUMBER;
        available_subscriptions NUMBER;
        server_already_in_chan  BOOLEAN;
        cursor  channel_family_is_proxy(channel_family_id_in in number) is
                select  1
                from    rhnChannelFamily
                where   id = channel_family_id_in
                    and label = 'rhn-proxy';
        cursor  channel_family_is_satellite(channel_family_id_in in number) is
                select  1
                from    rhnChannelFamily
                where   id = channel_family_id_in
                    and label = 'rhn-satellite';
        -- this is *EXACTLY* like check_server_parent_membership, but if we recurse
        -- with the package-level one, we get a "cursor already open", so we need a
        -- copy on our call stack instead.  GROAN.
        cursor local_chk_server_parent_memb (
                        server_id_in number,
                        channel_id_in number ) is
                select  c.id
                from    rhnChannel                      c,
                                rhnServerChannel        sc
                where   1=1
                        and c.parent_channel = channel_id_in
                        and c.id = sc.channel_id
                        and sc.server_id = server_id_in;
    BEGIN
        FOR child IN local_chk_server_parent_memb(server_id_in, channel_id_in)
        LOOP
            if unsubscribe_children_in = 1 then
                unsubscribe_server(server_id_in => server_id_in,
                                                                channel_id_in => child.id,
                                                                immediate_in => immediate_in,
                                                                unsubscribe_children_in => unsubscribe_children_in,
                        deleting_server => deleting_server,
                        update_family_countsYN => update_family_countsYN);
            else
                rhn_exception.raise_exception('channel_unsubscribe_child_exists');
            end if;
        END LOOP child;

        server_already_in_chan := FALSE;

        FOR check_subscription IN check_server_subscription(server_id_in, channel_id_in)
        LOOP
            server_already_in_chan := TRUE;
        END LOOP check_subscription;

        IF NOT server_already_in_chan
        THEN
            RETURN;
        END IF;

   if deleting_server = 0 then

      insert into rhnServerHistory (id,server_id,summary,details) (
          select  rhn_event_id_seq.nextval,
                server_id_in,
             'unsubscribed from channel ' || SUBSTR(c.label, 0, 106),
             c.label
          from    rhnChannel c
          where   c.id = channel_id_in
      );

        UPDATE rhnServer SET channels_changed = sysdate WHERE id = server_id_in;
   end if;

   DELETE FROM rhnServerChannel WHERE server_id = server_id_in AND channel_id = channel_id_in;

   if deleting_server = 0 then
        queue_server(server_id_in, immediate_in);
   end if;

        channel_family_id_val := rhn_channel.family_for_channel(channel_id_in);
        IF channel_family_id_val IS NULL
        THEN
            rhn_exception.raise_exception('channel_unsubscribe_no_family');
        END IF;

        for ignore in channel_family_is_satellite(channel_family_id_val) loop
                delete from rhnSatelliteInfo where server_id = server_id_in;
                delete from rhnSatelliteChannelFamily where server_id = server_id_in;
        end loop;

        for ignore in channel_family_is_proxy(channel_family_id_val) loop
                delete from rhnProxyInfo where server_id = server_id_in;
        end loop;

        DELETE FROM rhnChannelFamilyLicenseConsent
         WHERE channel_family_id = channel_family_id_val
           AND server_id = server_id_in;

        SELECT org_id INTO server_org_id_val
          FROM rhnServer
         WHERE id = server_id_in;

        if update_family_countsYN = 1 then
            rhn_channel.update_family_counts(channel_family_id_val, server_org_id_val);
        end if;
    END unsubscribe_server;

    PROCEDURE bulk_unsubscribe_server(channel_id_in IN NUMBER, set_label_in IN VARCHAR2, set_uid_in IN NUMBER)
    IS
    BEGIN
        FOR server IN rhn_set.set_iterator(set_label_in, set_uid_in)
        LOOP
            rhn_channel.unsubscribe_server(server.element, channel_id_in, 0);
        END LOOP server;
    END bulk_unsubscribe_server;

    FUNCTION family_for_channel(channel_id_in IN NUMBER)
    RETURN NUMBER
    IS
        channel_family_id_val NUMBER;
    BEGIN
        SELECT channel_family_id INTO channel_family_id_val
          FROM rhnChannelFamilyMembers
         WHERE channel_id = channel_id_in;

        RETURN channel_family_id_val;
    EXCEPTION
        WHEN NO_DATA_FOUND
        THEN
            RETURN NULL;
    END family_for_channel;

    FUNCTION available_family_subscriptions(channel_family_id_in IN NUMBER, org_id_in IN NUMBER)
    RETURN NUMBER
    IS
        cfp channel_family_perm_cursor%ROWTYPE;
        current_members_val NUMBER;
        max_members_val     NUMBER;
        found               NUMBER;
    BEGIN
        IF NOT channel_family_perm_cursor%ISOPEN
        THEN
            OPEN channel_family_perm_cursor(channel_family_id_in, org_id_in);
        END IF;

        FETCH channel_family_perm_cursor INTO cfp;

        WHILE channel_family_perm_cursor%FOUND
        LOOP
            found := 1;

            current_members_val := cfp.current_members;
            max_members_val := cfp.max_members;

            FETCH channel_family_perm_cursor INTO cfp;
        END LOOP;

        IF channel_family_perm_cursor%ISOPEN
        THEN
            CLOSE channel_family_perm_cursor;
        END IF;

        -- not found: either the channel fam doesn't have an entry in cfp, or the org doesn't have access to it.
        -- either way, there are no available subscriptions

        IF found IS NULL
        THEN
            RETURN 0;
        END IF;

        -- null max members?  in that case, pass it on; NULL means infinite
        IF max_members_val IS NULL
        THEN
            RETURN NULL;
        END IF;

        -- otherwise, return the delta
        RETURN max_members_val - current_members_val;
    END available_family_subscriptions;

    -- *******************************************************************
    -- FUNCTION: channel_family_current_members
    -- Calculates and returns the actual count of systems consuming
    --   physical channel subscriptions.
    -- Called by: update_family_counts
    --            rhn_entitlements.repoll_virt_guest_entitlements
    -- *******************************************************************
    function channel_family_current_members(channel_family_id_in IN NUMBER,
                                            org_id_in IN NUMBER)
    return number
    is
        current_members_count number := 0;
    begin
        select  count(distinct server_id)
        into    current_members_count
          from  rhnChannelFamilyServerPhysical cfsp
         where  cfsp.channel_family_id = channel_family_id_in
           and  cfsp.customer_id = org_id_in;
        return current_members_count;
    end;

    PROCEDURE update_family_counts(channel_family_id_in IN NUMBER,
                                   org_id_in IN NUMBER)
    IS
    BEGIN
                update rhnPrivateChannelFamily
                set current_members = (
                channel_family_current_members(channel_family_id_in, org_id_in)
                )
                        where org_id = org_id_in
                                and channel_family_id = channel_family_id_in;

    END update_family_counts;

    PROCEDURE update_group_family_counts(group_label_in IN VARCHAR2,
                                   org_id_in IN NUMBER)
    IS
    BEGIN
        FOR i IN (
                SELECT DISTINCT CFM.channel_family_id, SG.org_id
                 FROM rhnChannelFamilyMembers CFM
                 JOIN rhnServerChannel SC
                   ON SC.channel_id = CFM.channel_id
                 JOIN rhnServerGroupMembers SGM
                   ON SC.server_id = SGM.server_id
                 JOIN rhnServerGroup SG
                   ON SGM.server_group_id = SG.id
                 JOIN rhnServerGroupType SGT
                   ON SG.group_type = SGT.id
                WHERE SGT.label = group_label_in
                  AND SG.org_id = org_id_in
                  AND SGT.is_base = 'Y'
        ) LOOP
            rhn_channel.update_family_counts(i.channel_family_id, i.org_id);
        END LOOP;
    END update_group_family_counts;

    FUNCTION available_chan_subscriptions(channel_id_in IN NUMBER,
                                          org_id_in IN NUMBER)
    RETURN NUMBER
    IS
            channel_family_id_val NUMBER;
    BEGIN
        SELECT channel_family_id INTO channel_family_id_val
            FROM rhnChannelFamilyMembers
            WHERE channel_id = channel_id_in;

            RETURN rhn_channel.available_family_subscriptions(
                           channel_family_id_val, org_id_in);
    END available_chan_subscriptions;

    -- *******************************************************************
    -- PROCEDURE: entitle_customer
    -- Creates a chan fam bucket, or sets max_members for an existing bucket
    -- Called by: rhn_ep.poll_customer_internal
    -- Calls: set_family_maxmembers + update_family_counts if the row
    --        already exists, else it creates it in rhnPrivateChannelFamily.
    -- *******************************************************************
    procedure entitle_customer(customer_id_in in number,
                               channel_family_id_in in number,
                               quantity_in in number)
    is
                cursor permissions is
                        select  1
                        from    rhnPrivateChannelFamily pcf
                        where   pcf.org_id = customer_id_in
                                and     pcf.channel_family_id = channel_family_id_in;
    begin
                for perm in permissions loop
                        set_family_maxmembers(
                                customer_id_in,
                                channel_family_id_in,
                                quantity_in
                        );
                        rhn_channel.update_family_counts(
                                channel_family_id_in,
                                customer_id_in
                        );
                        return;
                end loop;

                insert into rhnPrivateChannelFamily pcf (
                                channel_family_id, org_id, max_members, current_members
                        ) values (
                                channel_family_id_in, customer_id_in, quantity_in, 0
                        );
    end;

    -- *******************************************************************
    -- PROCEDURE: set_family_maxmembers
    -- Prunes an existing channel family bucket by unsubscribing the
    --   necessary servers and sets max_members.
    -- Called by: rhn_channel.entitle_customer
    -- Calls: unsubscribe_server_from_family
    -- *******************************************************************
    procedure set_family_maxmembers(customer_id_in in number,
                                    channel_family_id_in in number,
                                    quantity_in in number)
    is
        cursor servers is
            select  server_id from (
            select      rownum row_number, server_id, modified from (
                select  rcfsp.server_id,
                        rcfsp.modified
                from    rhnChannelFamilyServerPhysical rcfsp
                where   rcfsp.customer_id = customer_id_in
                    and rcfsp.channel_family_id = channel_family_id_in
                order by modified
            )
            where rownum > quantity_in
            );
    begin
            -- prune subscribed servers
        for server in servers loop
            rhn_channel.unsubscribe_server_from_family(server.server_id,
                                                       channel_family_id_in);
        end loop;

        update  rhnPrivateChannelFamily pcf
        set     pcf.max_members = quantity_in
        where   pcf.org_id = customer_id_in
            and pcf.channel_family_id = channel_family_id_in;
    end;

    procedure unsubscribe_server_from_family(server_id_in in number,
                                             channel_family_id_in in number)
    is
    begin
        delete
        from    rhnServerChannel rsc
        where   rsc.server_id = server_id_in
            and channel_id in (
                select  rcfm.channel_id
                from    rhnChannelFamilyMembers rcfm
                where   rcfm.channel_family_id = channel_family_id_in);
    end;

    function get_org_id(channel_id_in in number)
    return number
    is
        org_id_out number;
    begin
        select org_id into org_id_out
            from rhnChannel
            where id = channel_id_in;

            return org_id_out;
    end get_org_id;

    function get_cfam_org_access(cfam_id_in in number, org_id_in in number)
    return number
    is
        cursor  families is
                        select  1
                        from    rhnOrgChannelFamilyPermissions cfp
                        where   cfp.org_id = org_id_in;
    begin
                -- the idea: if we get past this query,
        -- the user has the role, else catch the exception and return 0
                for family in families loop
                return 1;
                end loop;
                return 0;
    end;

    function get_org_access(channel_id_in in number, org_id_in in number)
    return number
    is
        throwaway number;
    begin
        -- the idea: if we get past this query,
        -- the org has access to the channel, else catch the exception and return 0
        select distinct 1 into throwaway
          from rhnChannelFamilyMembers CFM,
               rhnOrgChannelFamilyPermissions CFP
         where cfp.org_id = org_id_in
           and CFM.channel_family_id = CFP.channel_family_id
           and CFM.channel_id = channel_id_in
           and (CFP.max_members > 0 or CFP.max_members is null or CFP.org_id = 1);

        return 1;
        exception
            when no_data_found
            then
            return 0;
    end;

    -- check if a user has a given role, or if such a role is inferrable
    function user_role_check_debug(channel_id_in in number,
                                   user_id_in in number,
                                   role_in in varchar2,
                                   reason_out out varchar2)
    return number
    is
        org_id number;
    begin
        org_id := rhn_user.get_org_id(user_id_in);

        -- channel might be shared
        if role_in = 'subscribe' and
           rhn_channel.shared_user_role_check(channel_id_in, user_id_in, role_in) = 1 then
            return 1;
        end if;

        if role_in = 'manage' and
           NVL(rhn_channel.get_org_id(channel_id_in), -1) <> org_id then
                reason_out := 'channel_not_owned';
               return 0;
            end if;

        if role_in = 'subscribe' and
           rhn_channel.get_org_access(channel_id_in, org_id) = 0 then
                reason_out := 'channel_not_available';
                return 0;
            end if;

        -- channel admins have all roles
        if rhn_user.check_role_implied(user_id_in, 'channel_admin') = 1 then
            reason_out := 'channel_admin';
            return 1;
            end if;

        -- the subscribe permission is inferred
    -- UNLESS the not_globally_subscribable flag is set
        if role_in = 'subscribe'
        then
            if rhn_channel.org_channel_setting(channel_id_in,
                       org_id,
                       'not_globally_subscribable') = 0 then
                reason_out := 'globally_subscribable';
                    return 1;
            end if;
        end if;

        -- all other roles (manage right now) are explicitly granted
        reason_out := 'direct_permission';
        return rhn_channel.direct_user_role_check(channel_id_in,
                                              user_id_in, role_in);
    end;

    -- same as above, but with no OUT param; useful in views, etc
    function user_role_check(channel_id_in in number, user_id_in in number, role_in in varchar2)
    return number
    is
        throwaway varchar2(256);
    begin
        return rhn_channel.user_role_check_debug(channel_id_in, user_id_in, role_in, throwaway);
    end;

    --
    -- For multiorg phase II, this function simply checks to see if the user's
    -- has a trust relationship that includes this channel by id.
    --
    function shared_user_role_check(channel_id in number, user_id in number, role in varchar2)
    return number
    is
      n number;
      oid number;
    begin
      oid := rhn_user.get_org_id(user_id);
      select 1 into n
      from rhnSharedChannelView s
      where s.id = channel_id and s.org_trust_id = oid;
      return 1;
      exception
        when no_data_found then
          return 0;
    end;

    -- same as above, but returns 1 if user_id_in is null
    -- This is useful in queries where user_id is not specified
    function loose_user_role_check(channel_id_in in number, user_id_in in number, role_in in varchar2)
    return number
    is
    begin
        if user_id_in is null then
            return 1;
        end if;
        return user_role_check(channel_id_in, user_id_in, role_in);
    end loose_user_role_check;

    -- directly checks the table, no inferred permissions
    function direct_user_role_check(channel_id_in in number, user_id_in in number, role_in in varchar2)
    return number
    is
        throwaway number;
    begin
        -- the idea: if we get past this query, the user has the role, else catch the exception and return 0
        select 1 into throwaway
          from rhnChannelPermissionRole CPR,
               rhnChannelPermission CP
         where CP.user_id = user_id_in
           and CP.channel_id = channel_id_in
           and CPR.label = role_in
           and CP.role_id = CPR.id;

        return 1;
    exception
        when no_data_found
            then
            return 0;
    end;

    -- check if an org has a certain setting
    function org_channel_setting(channel_id_in in number, org_id_in in number, setting_in in varchar2)
    return number
    is
        throwaway number;
    begin
        -- the idea: if we get past this query, the org has the setting, else catch the exception and return 0
        select 1 into throwaway
          from rhnOrgChannelSettingsType OCST,
               rhnOrgChannelSettings OCS
         where OCS.org_id = org_id_in
           and OCS.channel_id = channel_id_in
           and OCST.label = setting_in
           and OCS.setting_id = OCST.id;

        return 1;
    exception
        when no_data_found
            then
            return 0;
    end;

    FUNCTION channel_priority(channel_id_in IN number)
    RETURN number
    IS
         channel_name varchar2(256);
         priority number;
         end_of_life_val date;
         org_id_val number;
    BEGIN

        select name, end_of_life, org_id
        into channel_name, end_of_life_val, org_id_val
        from rhnChannel
        where id = channel_id_in;

        if end_of_life_val is not null then
          return -400;
        end if;

        if channel_name like 'Red Hat Enterprise Linux%' or channel_name like 'RHEL%' then
          priority := 1000;
          if channel_name not like '%Beta%' then
            priority := priority + 1000;
          end if;

          priority := priority +
            case
              when channel_name like '%v. 5%' then 600
              when channel_name like '%v. 4%' then 500
              when channel_name like '%v. 3%' then 400
              when channel_name like '%v. 2%' then 300
              when channel_name like '%v. 1%' then 200
              else 0
            end;

          priority := priority +
            case
              when channel_name like 'Red Hat Enterprise Linux (v. 5%' then 60
              when (channel_name like '%AS%' and channel_name not like '%Extras%') then 50
              when (channel_name like '%ES%' and channel_name not like '%Extras%') then 40
              when (channel_name like '%WS%' and channel_name not like '%Extras%') then 30
              when (channel_name like '%Desktop%' and channel_name not like '%Extras%') then 20
              when channel_name like '%Extras%' then 10
              else 0
            end;

          priority := priority +
            case
              when channel_name like '%)' then 5
              else 0
            end;

          priority := priority +
            case
              when channel_name like '%32-bit x86%' then 4
              when channel_name like '%64-bit Intel Itanium%' then 3
              when channel_name like '%64-bit AMD64/Intel EM64T%' then 2
              else 0
            end;
        elsif channel_name like 'Red Hat Desktop%' then
            priority := 900;

            if channel_name not like '%Beta%' then
               priority := priority + 50;
            end if;

          priority := priority +
            case
              when channel_name like '%v. 4%' then 40
              when channel_name like '%v. 3%' then 30
              when channel_name like '%v. 2%' then 20
              when channel_name like '%v. 1%' then 10
              else 0
            end;

          priority := priority +
            case
              when channel_name like '%32-bit x86%' then 4
              when channel_name like '%64-bit Intel Itanium%' then 3
              when channel_name like '%64-bit AMD64/Intel EM64T%' then 2
              else 0
            end;

        elsif org_id_val is not null then
          priority := 600;
        else
          priority := 500;
        end if;

      return -priority;

    end channel_priority;

    -- right now this only does the accounting changes; the cascade
    -- actually does the rhnServerChannel delete.
    procedure delete_server_channels(server_id_in in number)
    is
    begin
        update  rhnPrivateChannelFamily
        set     current_members = current_members -1
        where   org_id in (
                        select  org_id
                        from    rhnServer
                        where   id = server_id_in
                )
                and channel_family_id in (
                        select  rcfm.channel_family_id
                        from    rhnChannelFamilyMembers rcfm,
                                rhnServerChannel rsc
                        where   rsc.server_id = server_id_in
                                and rsc.channel_id = rcfm.channel_id
                and not exists (
                    select 1
                    from
                        rhnChannelFamilyVirtSubLevel cfvsl,
                        rhnSGTypeVirtSubLevel sgtvsl,
                        rhnServerEntitlementView sev,
                        rhnVirtualInstance vi
                    where
                        -- system is a virtual instance
                        vi.virtual_system_id = server_id_in
                        and vi.host_system_id = sev.server_id
                        -- system's host has a virt ent
                        and sev.label in ('virtualization_host',
                                          'virtualization_host_platform')
                        and sev.server_group_type_id =
                            sgtvsl.server_group_type_id
                        -- the host's virt ent grants a cf virt sub level
                        and sgtvsl.virt_sub_level_id = cfvsl.virt_sub_level_id
                        -- the cf is in that virt sub level
                        and cfvsl.channel_family_id = rcfm.channel_family_id
                    )
                );
    end;

        -- this could certainly be optimized to do updates if needs be
        procedure refresh_newest_package(channel_id_in in number, caller_in in varchar2 := '(unknown)')
        is
        begin
                delete from rhnChannelNewestPackage where channel_id = channel_id_in;
                insert into rhnChannelNewestPackage
                        ( channel_id, name_id, evr_id, package_id, package_arch_id )
                        (       select  channel_id,
                                                name_id, evr_id,
                                                package_id, package_arch_id
                                from    rhnChannelNewestPackageView
                                where   channel_id = channel_id_in
                        );
                insert into rhnChannelNewestPackageAudit (channel_id, caller)
                    values (channel_id_in, caller_in);
                update rhnChannel
                    set last_modified = greatest(sysdate, last_modified + 1/86400)
                    where id = channel_id_in;
        end;

   procedure update_channel ( channel_id_in in number, invalidate_ss in number := 0,
                              date_to_use in date := sysdate )
   is

   channel_last_modified date;
   last_modified_value date;

   cursor snapshots is
   select  snapshot_id id
   from    rhnSnapshotChannel
   where   channel_id = channel_id_in;

   begin

      select last_modified
      into channel_last_modified
      from rhnChannel
      where id = channel_id_in;

      last_modified_value := date_to_use;

      if last_modified_value <= channel_last_modified then
          last_modified_value := last_modified_value + 1/86400;
      end if;

      update rhnChannel set last_modified = last_modified_value
      where id = channel_id_in;

      if invalidate_ss = 1 then
        for snapshot in snapshots loop
            update rhnSnapshot
            set invalid = lookup_snapshot_invalid_reason('channel_modified')
            where id = snapshot.id;
        end loop;
      end if;

   end update_channel;

   procedure update_channels_by_package ( package_id_in in number, date_to_use in date := sysdate )
   is

   cursor channels is
   select channel_id
   from rhnChannelPackage
   where package_id = package_id_in
   order by channel_id;

   begin
      for channel in channels loop
         -- we want to invalidate the snapshot assocated with the channel when we
         -- do this b/c we know we've added or removed or packages
         rhn_channel.update_channel ( channel.channel_id, 1, date_to_use );
      end loop;
   end update_channels_by_package;


   procedure update_channels_by_errata ( errata_id_in number, date_to_use in date := sysdate )
   is

   cursor channels is
   select channel_id
   from rhnChannelErrata
   where errata_id = errata_id_in
   order by channel_id;

   begin
      for channel in channels loop
         -- we won't invalidate snapshots, b/c just changing the errata associated with
         -- a channel shouldn't invalidate snapshots
         rhn_channel.update_channel ( channel.channel_id, 0, date_to_use );
      end loop;
   end update_channels_by_errata;

END rhn_channel;
/
SHOW ERRORS

--
-- Revision 1.75  2005/03/04 00:04:19  jslagle
-- bz #147617
-- Made Red Hat Desktop sort a little better.
--
-- Revision 1.74  2005/02/22 03:24:47  jslagle
-- bz #147617
-- Improve channel_priority function to order channels better.
--
-- Revision 1.73  2004/08/16 20:39:30  pjones
-- bugzilla: 129889 -- make bulk_server_basechange_from() actually work.
--
-- Revision 1.72  2004/04/14 00:09:24  pjones
-- bugzilla: 120761 -- split rhnChannelPermissions into two tables, eliminating
-- a frequent full table scan
--
-- Revision 1.71  2004/04/13 16:28:36  bretm
-- bugzilla:  119871
--
-- keep track of rhnServer.channels_changed through the pl/sql fns
--
-- Revision 1.70  2004/03/26 18:11:32  rbb
-- Bugzilla:  114057
--
-- Add a script to determine channel priority.
--
-- Revision 1.69  2004/02/17 20:16:52  pjones
-- bugzilla: none -- add cvs tags into the package as long as we're touching
-- it anyway
--
-- Revision 1.68  2004/02/17 20:05:38  pjones
-- bugzilla: 115782 -- make bulk_server_basechange_from() filter out servers
-- with arches incompatible with the target channel
--
-- Revision 1.67  2004/02/06 02:36:10  misa
-- Changed normalize_server_arch to allow for solaris arches
--
-- Revision 1.66  2003/11/13 16:58:34  cturner
-- make use of new rhn_user.check_role_implied call; pragmas broke, removed them for now since I have no idea how to fix them
--
-- Revision 1.65  2003/10/23 20:26:24  bretm
-- bugzilla:  none
--
-- note the channel label when we unsubscribe, too
--
-- Revision 1.64  2003/10/15 14:47:17  bretm
-- bugzilla:  none
--
-- add the channel label to the server history summary line when we log a channel change
--
-- Revision 1.63  2003/09/24 19:25:56  pjones
-- this wasn't the right fix, put it back
--
-- Revision 1.62  2003/09/24 17:42:19  pjones
-- bugzilla: none
--
-- limit our server base channel guess to channels with available permissions
--
-- Revision 1.61  2003/09/22 21:00:40  cturner
-- add method for easy acl check
--
-- Revision 1.60  2003/09/17 22:14:11  misa
-- bugzilla: 103639  Changes to allow me to move the base channel guess into plsql
--
-- Revision 1.59  2003/08/21 13:41:17  cturner
-- bugzilla: 99187.  properly test for satellite and proxy in bulk_guess_server_base; reorg code for better reuse
--
-- Revision 1.58  2003/07/24 16:46:22  cturner
-- bugzilla: 100723, the perm check was returning duplicates, so now it just calls the function it should have called anyway
--
-- Revision 1.57  2003/07/24 16:44:16  misa
-- bugzilla: none  A function more usable on the rhnapp side
--
-- Revision 1.56  2003/07/23 22:36:51  cturner
-- argh, max returns null even when now rows; use distinct.  how revolting
--
-- Revision 1.55  2003/07/23 22:01:31  cturner
-- oops, this one can return multiple rows; eliminate that in a lazy way
--
-- Revision 1.54  2003/07/23 21:59:19  cturner
-- rework how rhnUserChannel works; move to plsql for speed and maintenance
--
-- Revision 1.53  2003/07/21 17:49:12  pjones
-- bugzilla: none
--
-- add optional user for subscribe_server
--
-- Revision 1.52  2003/07/14 22:19:29  misa
-- bugzilla: none  Updating guess_base_channel to work more like the rhnapp server code
--
-- Revision 1.51  2003/06/26 22:09:04  pjones
-- bugzilla: none
--
-- log subscribe and unsubscribe
--
-- Revision 1.50  2003/06/05 19:31:15  pjones
-- bugzilla: 88278 -- make the cursor name smaller
--
-- Revision 1.49  2003/06/05 19:18:21  pjones
-- bugzilla: 88278
--
-- unsubscribe_server() opens the package-level cursor when it invokes itself,
-- so we're using a local copy instead.
--
-- Revision 1.48  2003/06/04 16:41:39  pjones
-- bugzilla: none
--
-- make bulk_guess_server_base() silently ignore unguessables
--
-- Revision 1.47  2003/06/04 16:27:03  pjones
-- bugzilla: 88822
--
-- eliminate the last outliers that remove things from channels without using
-- unsubscribe_server, I think.
--
-- Revision 1.46  2003/06/03 20:49:37  pjones
-- bugzilla: 88822
-- unsubscribing from rhn-satellite now clears rhnSatelliteChannelFamily
-- for the server in question
--
-- Revision 1.45  2003/06/02 20:41:45  pjones
-- bugzilla: none - fix rhnProxyInfo/rhnSatelliteInfo channel unsubscribe
-- problem.  Basicly, if you're out of the channel for any reason, you're
-- also out of rhnProxyInfo/rhnProxyInfo
--
-- Revision 1.44  2003/03/24 15:26:28  pjones
-- bugzilla: 85812
--
-- bulk_server_base_change silently ignores servers that are satellites
-- or proxies, as requested.
--
-- Revision 1.43  2003/02/26 20:28:17  pjones
-- rhn_channel.update_family_counts() in rhn_channel.entitle_customer()
-- the old codepath is:
--
-- ep ->
-- rhn_ep.entitlement_run_me() ->
-- rhn_ep.poll_customer() ->
-- rhn_channel.entitle_customer()
--
-- which doesn't change current_members, even though it may remove servers
-- from the family.
--
-- There's another bug here:  currently, we don't try to order forced
-- unsubscribes in any way; we just use
-- rhn_channel.unsubscribe_server_from_family .  If there are any child
-- channel subscriptions, this will leave them subscribed.  We really need
-- to iterate across the channels again, and subscribe any channel for which
-- there are no parent channel subscriptions.
--
-- Ugh.
--
-- Revision 1.42  2003/01/28 00:19:45  pjones
-- fix clear_subscriptions; AFAICT, this is only hit on the
-- bulk_server_base_change / bulk_server_base_guess codepaths, which puts
-- it infrequent enough that it could be our "bad count" culprit.
--
-- Revision 1.41  2003/01/14 19:51:45  pjones
-- make setting current_members on rhnChannelFamilyPermissions work when
-- a server is in more than one channel in a single family.
 07070100000536000081B400000000000000000000000167AE1114000016BE000000000000000000000000000000000000006700000000susemanager-schema/upgrade/spacewalk-schema-0.7-to-spacewalk-schema-0.8/051-1-rhn_entitlements.pks.sql    --
-- Copyright (c) 2008--2010 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--
--
--
--

create or replace
package rhn_entitlements
is
	body_version varchar2(100) := '';

   type ents_array is varray(10) of rhnServerGroupType.label%TYPE;

    procedure remove_org_entitlements (
        org_id_in number
    );

    function entitlement_grants_service (
	    entitlement_in in varchar2,
		service_level_in in varchar2
	) return number;

	function lookup_entitlement_group (
		org_id_in in number,
		type_label_in in varchar2 := 'sw_mgr_entitled'
	) return number;

	function create_entitlement_group (
		org_id_in in number,
		type_label_in in varchar2 := 'sw_mgr_entitled'
	) return number;

   function can_entitle_server (
      server_id_in   in number,
      type_label_in  in varchar2
   )
   return number;

   function can_switch_base (
      server_id_in   in    integer,
      type_label_in  in    varchar2
   )
   return number;

   function find_compatible_sg (
      server_id_in in number,
      type_label_in in varchar2,
      sgid_out out number
   )
   return boolean;

	procedure entitle_server (
		server_id_in in number,
		type_label_in in varchar2 := 'sw_mgr_entitled'
	);

	procedure remove_server_entitlement (
		server_id_in in number,
		type_label_in in varchar2 := 'sw_mgr_entitled',
        repoll_virt_guests in number := 1
	);

	procedure unentitle_server (
		server_id_in in number
	);

    procedure repoll_virt_guest_entitlements(
        server_id_in in number
    );

	function get_server_entitlement (
		server_id_in in number
	) return ents_array;

	procedure modify_org_service (
		org_id_in in number,
		service_label_in in varchar2,
		enable_in in char
	);

    procedure set_customer_enterprise (
		customer_id_in in number
	);

	procedure set_customer_provisioning (
		customer_id_in in number
	);

	procedure set_customer_nonlinux (
		customer_id_in in number
	);

    procedure unset_customer_enterprise (
		customer_id_in in number
	);

	procedure unset_customer_provisioning (
		customer_id_in in number
	);

	procedure unset_customer_nonlinux (
		customer_id_in in number
	);

    procedure assign_system_entitlement(
        group_label_in in varchar2,
        from_org_id_in in number,
        to_org_id_in in number,
        quantity_in in number
    );

    procedure assign_channel_entitlement(
        channel_family_label_in in varchar2,
        from_org_id_in in number,
        to_org_id_in in number,
        quantity_in in number
    );

    procedure activate_system_entitlement(
        org_id_in in number,
        group_label_in in varchar2,
        quantity_in in number
    );

    procedure activate_channel_entitlement(
        org_id_in in number,
        channel_family_label_in in varchar2,
        quantity_in in number
    );

    procedure set_group_count (
		customer_id_in in number,	-- customer_id
		type_in in char,			-- 'U' or 'S'
		group_type_in in number,	-- rhn[User|Server]GroupType.id
		quantity_in in number,		-- quantity
                update_family_countsYN in number := 1 -- call update_family_counts inside
    );

    procedure set_family_count (
		customer_id_in in number,		-- customer_id
		channel_family_id_in in number,	-- 246
		quantity_in in number			-- 3
    );

    -- this makes NO checks that the quantity is within max,
    -- so we should NEVER run this unless we KNOW that we won't be
    -- violating the max
    procedure entitle_last_modified_servers (
		customer_id_in in number,	-- customer_id
		type_label_in in varchar2,	-- 'enterprise_entitled'
		quantity_in in number		-- 3
    );

	procedure prune_everything (
		customer_id_in in number
	);

	procedure subscribe_newest_servers (
		customer_id_in in number
	);
end rhn_entitlements;
/
show errors

--
-- Revision 1.19  2004/05/26 19:45:48  pjones
-- bugzilla: 123639
-- 1) reformat "entitlement_grants_service"
-- 2) make the .pks and .pkb be in the same order.
-- 3) add "modify_org_service" (to be used instead of set_customer_SERVICELEVEL)
-- 4) add monitoring specific data.
--
-- Revision 1.18  2004/02/19 20:17:49  pjones
-- bugzilla: 115896 -- add sgt and oet data for nonlinux, add
-- [un]set_customer_nonlinux
--
-- Revision 1.17  2004/01/13 23:37:08  pjones
-- bugzilla: none -- mate provisioning and management slots.
--
-- Revision 1.16  2003/09/23 22:14:41  bretm
-- bugzilla:  103655
--
-- need something in the db that knows provisioning boxes are management boxes too, etc.
--
-- Revision 1.15  2003/09/19 22:35:07  pjones
-- bugzilla: none
--
-- provisioning and config management entitlement support
--
-- Revision 1.14  2003/09/02 22:22:54  pjones
-- bugzilla: none
--
-- attempt to autoentitle upon entitlement changes
--
-- Revision 1.13  2003/06/05 21:43:40  pjones
-- bugzilla: none
--
-- add rhn_entitlements.prune_everything(customer_id_in in number);
--
-- Revision 1.12  2003/05/22 16:01:14  pjones
-- reformat
-- remove update_[server|user]group_counts (unused)
--
-- Revision 1.11  2002/06/03 16:07:29  pjones
-- make prune_group and prune_family update respective max_members
-- correctly.
--
-- Revision 1.10  2002/05/29 19:10:31  pjones
-- code to entitle the last N modified servers to a particular service
-- level
--
-- Revision 1.9  2002/05/10 22:08:23  pjones
-- id/log
--
  07070100000537000081B400000000000000000000000167AE11140000DDFA000000000000000000000000000000000000006700000000susemanager-schema/upgrade/spacewalk-schema-0.7-to-spacewalk-schema-0.8/051-2-rhn_entitlements.pkb.sql    --
-- Copyright (c) 2008--2010 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--
--
--
--

create or replace
package body rhn_entitlements
is
	body_version varchar2(100) := '';


    -- *******************************************************************
    -- PROCEDURE: remove_org_entitlements
    --
    -- Removes both system entitlements and channel subscriptions
    -- that are currently assigned to an org and re-assigns to the
    -- master org (org_id = 1).
    --
    -- When we call this we expect everything to already be unentitled
    -- which shoul be handled by delete_org.
    --
    -- Called by: delete_org
    -- *******************************************************************
    procedure remove_org_entitlements(
        org_id_in in number
    )
    is

        cursor system_ents is
        select sg.id, sg.max_members, sg.group_type
        from rhnServerGroup sg
        where group_type is not null
          and org_id = org_id_in;

        cursor channel_subs is
        select pcf.channel_family_id, pcf.max_members
        from rhnChannelFamily cf,
             rhnPrivateChannelFamily pcf
        where pcf.org_id = org_id_in
          and pcf.channel_family_id = cf.id
          and cf.org_id is null;

    begin

        for system_ent in system_ents loop
            update rhnServerGroup
            set max_members = max_members + system_ent.max_members
            where org_id = 1
              and group_type = system_ent.group_type;
        end loop;

        update rhnServerGroup
        set max_members = 0
        where org_id = org_id_in;

        for channel_sub in channel_subs loop
            update rhnPrivateChannelFamily
            set max_members = max_members + channel_sub.max_members
            where org_id = 1
              and channel_family_id = channel_sub.channel_family_id;
        end loop;

        update rhnPrivateChannelFamily
        set max_members = 0
        where org_id = org_id_in;

    end remove_org_entitlements;

	function entitlement_grants_service (
	    entitlement_in in varchar2,
	    service_level_in in varchar2
	) return number	is
	begin
		if service_level_in = 'provisioning' then
			if entitlement_in = 'provisioning_entitled' then
				return 1;
			else
				return 0;
			end if;
		elsif service_level_in = 'management' then
			if entitlement_in = 'enterprise_entitled' then
				return 1;
			else
				return 0;
			end if;
		elsif service_level_in = 'monitoring' then
			if entitlement_in = 'monitoring_entitled' then
				return 1;
			end if;
		elsif service_level_in = 'updates' then
			return 1;
		else
			return 0;
		end if;
	end entitlement_grants_service;

	function lookup_entitlement_group (
		org_id_in in number,
		type_label_in in varchar2 := 'sw_mgr_entitled'
	) return number is
		cursor server_groups is
			select	sg.id				server_group_id
			from	rhnServerGroup		sg,
					rhnServerGroupType	sgt
			where	sgt.label = type_label_in
				and sgt.id = sg.group_type
				and sg.org_id = org_id_in;
	begin
		for sg in server_groups loop
			return sg.server_group_id;
		end loop;
		return rhn_entitlements.create_entitlement_group(
				org_id_in,
				type_label_in
			);
	end lookup_entitlement_group;

	function create_entitlement_group (
		org_id_in in number,
		type_label_in in varchar2 := 'sw_mgr_entitled'
	) return number is
		sg_id_val number;
	begin
		select	rhn_server_group_id_seq.nextval
		into	sg_id_val
		from	dual;

		insert into rhnServerGroup (
				id, name, description, max_members, current_members,
				group_type, org_id
			) (
				select	sg_id_val, sgt.label, sgt.label,
						0, 0, sgt.id, org_id_in
				from	rhnServerGroupType sgt
				where	sgt.label = type_label_in
			);

		return sg_id_val;
	end create_entitlement_group;

   function can_entitle_server (
        server_id_in in number,
        type_label_in in varchar2 )
   return number is
      cursor addon_servergroups (base_label_in in varchar2,
                                 addon_label_in in varchar2) is
         select
            addon_id
         from
            rhnSGTypeBaseAddonCompat
         where base_id = lookup_sg_type (base_label_in)
           and addon_id = lookup_sg_type (addon_label_in);

      previous_ent        rhn_entitlements.ents_array;
      is_base_in          char   := 'N';
      is_base_current     char   := 'N';
      i                   number := 0;
      sgid                number := 0;

   begin

      previous_ent := rhn_entitlements.ents_array();
      previous_ent := rhn_entitlements.get_server_entitlement(server_id_in);

      select distinct is_base
      into is_base_in
      from rhnServerGroupType
      where label = type_label_in;

      if previous_ent.count = 0 then
         if (is_base_in = 'Y' and rhn_entitlements.find_compatible_sg (server_id_in, type_label_in, sgid)) then
            -- rhn_server.insert_into_servergroup (server_id_in, sgid);
            return 1;
         else
            -- rhn_exception.raise_exception ('invalid_base_entitlement');
            return 0;
         end if;

      -- there are previous ents, first make sure we're not trying to entitle a base ent
      elsif is_base_in = 'Y' then
         -- rhn_exception.raise_exception ('invalid_addon_entitlement');
         return 0;

      -- it must be an addon, so proceed with the entitlement
      else

         -- find the servers base ent
         is_base_current := 'N';
         i := 0;
         while is_base_current = 'N' and i <= previous_ent.count
         loop
            i := i + 1;
            select is_base
            into is_base_current
            from rhnServerGroupType
            where label = previous_ent(i);
         end loop;

         -- never found a base ent, that would be strange
         if is_base_current  = 'N' then
            -- rhn_exception.raise_exception ('invalid_base_entitlement');
            return 0;
         end if;

         -- this for loop verifies the validity of the addon path
         for addon_servergroup in addon_servergroups  (previous_ent(i), type_label_in) loop
            -- find an appropriate sgid for the addon and entitle the server
            if rhn_entitlements.find_compatible_sg (server_id_in, type_label_in, sgid) then
               -- rhn_server.insert_into_servergroup (server_id_in, sgid);
               return 1;
            else
               -- rhn_exception.raise_exception ('invalid_addon_entitlement');
               return 0;
            end if;
         end loop;

      end if;

      return 0;

   end can_entitle_server;

   function can_switch_base (
      server_id_in   in    integer,
      type_label_in  in    varchar2
   ) return number is

      type_label_in_is_base   char(1);
      sgid                    number;

   begin

      begin
         select is_base into type_label_in_is_base
         from rhnServerGroupType
         where label = type_label_in;
      exception
         when no_data_found then
            rhn_exception.raise_exception ( 'invalid_entitlement' );
      end;

      if type_label_in_is_base = 'N' then
         rhn_exception.raise_exception ( 'invalid_entitlement' );
      elsif rhn_entitlements.find_compatible_sg ( server_id_in,
                                                  type_label_in, sgid ) then
         return 1;
      else
         return 0;
      end if;

   end can_switch_base;


   function find_compatible_sg (
      server_id_in    in   number,
      type_label_in   in   varchar2,
      sgid_out        out  number
   ) return boolean is

      cursor servergroups is
         select sg.id            id
           from rhnServerGroupType             sgt,
                rhnServerGroup                 sg,
                rhnServer                     s,
                rhnServerServerGroupArchCompat ssgac
          where s.id = server_id_in
            and s.org_id = sg.org_id
            and sgt.label = type_label_in
            and sg.group_type = sgt.id
            and ssgac.server_group_type = sgt.id
            and ssgac.server_arch_id = s.server_arch_id
            and not exists (
                     select 1
                      from rhnServerGroupMembers sgm
                     where sgm.server_group_id = sg.id
                       and sgm.server_id = s.id);


   begin
      for servergroup in servergroups loop
         sgid_out := servergroup.id;
         return true;
      end loop;

      --no servergroup found
      sgid_out := 0;
      return false;
   end find_compatible_sg;

	procedure entitle_server (
		server_id_in in number,
		type_label_in in varchar2 := 'sw_mgr_entitled'
	) is
      sgid  number := 0;
      is_virt number := 0;

	begin

          begin
          select 1 into is_virt
            from rhnServerEntitlementView
           where server_id = server_id_in
             and label in ('virtualization_host', 'virtualization_host_platform');
	  exception
            when no_data_found then
              is_virt := 0;
          end;

      if is_virt = 0 and (type_label_in = 'virtualization_host' or
                          type_label_in = 'virtualization_host_platform') then

        is_virt := 1;
      end if;



      if rhn_entitlements.can_entitle_server(server_id_in,
                                             type_label_in) = 1 then
         if rhn_entitlements.find_compatible_sg (server_id_in,
                                                 type_label_in, sgid) then
            insert into rhnServerHistory ( id, server_id, summary, details )
            values ( rhn_event_id_seq.nextval, server_id_in,
                     'added system entitlement ',
                      case type_label_in
                       when 'enterprise_entitled' then 'Management'
                       when 'sw_mgr_entitled' then 'Update'
                       when 'provisioning_entitled' then 'Provisioning'
                       when 'monitoring_entitled' then 'Monitoring'
                       when 'virtualization_host' then 'Virtualization'
                       when 'virtualization_host_platform' then
                            'Virtualization Platform' end  );

            rhn_server.insert_into_servergroup (server_id_in, sgid);

            if is_virt = 1 then
              rhn_entitlements.repoll_virt_guest_entitlements(server_id_in);
            end if;

         else
            rhn_exception.raise_exception ('no_available_server_group');
         end if;
      else
         rhn_exception.raise_exception ('invalid_entitlement');
      end if;
   end entitle_server;

	procedure remove_server_entitlement (
		server_id_in in number,
		type_label_in in varchar2 := 'sw_mgr_entitled',
        repoll_virt_guests in number := 1
	) is
		group_id number;
      type_is_base char;
      is_virt number := 0;
	begin
      begin


      -- would be nice if there were a virt attribute of entitlement types, not have to specify 2 different ones...
        begin
          select 1 into is_virt
            from rhnServerEntitlementView
           where server_id = server_id_in
             and label in ('virtualization_host', 'virtualization_host_platform');
        exception
          when no_data_found then
            is_virt := 0;
        end;

		select	sg.id, sgt.is_base
		into	group_id, type_is_base
		from	rhnServerGroupType sgt,
			rhnServerGroup sg,
				rhnServerGroupMembers sgm,
				rhnServer s
		where	s.id = server_id_in
			and s.id = sgm.server_id
			and sgm.server_group_id = sg.id
			and sg.org_id = s.org_id
			and sgt.label = type_label_in
			and sgt.id = sg.group_type;

      if ( type_is_base = 'Y' ) then
         -- unentitle_server should handle everything, don't really need to do anything else special here
         unentitle_server ( server_id_in );
      else

         insert into rhnServerHistory ( id, server_id, summary, details )
         values ( rhn_event_id_seq.nextval, server_id_in,
                  'removed system entitlement ',
                   case type_label_in
                    when 'enterprise_entitled' then 'Management'
                    when 'sw_mgr_entitled' then 'Update'
                    when 'provisioning_entitled' then 'Provisioning'
                    when 'monitoring_entitled' then 'Monitoring'
                    when 'virtualization_host' then 'Virtualization'
                    when 'virtualization_host_platform' then
                         'Virtualization Platforrm' end  );

         rhn_server.delete_from_servergroup(server_id_in, group_id);

         -- special case: clean up related monitornig data
         if type_label_in = 'monitoring_entitled' then
           DELETE
             FROM state_change
            WHERE o_id IN (SELECT probe_id
                             FROM rhn_check_probe
                            WHERE host_id = server_id_in);
           DELETE /*+index(time_series time_series_probe_id_idx)*/
             FROM time_series
            WHERE SUBSTR(o_id, INSTR(o_id, '-') + 1,
                        (INSTR(o_id, '-', INSTR(o_id, '-') + 1) - INSTR(o_id, '-')) - 1)
              IN (SELECT to_char(probe_id)
                    FROM rhn_check_probe
                   WHERE host_id = server_id_in);
           DELETE
             FROM rhn_probe
            WHERE recid IN (SELECT probe_id
                              FROM rhn_check_probe
                             WHERE host_id = server_id_in);
         end if;

         if is_virt = 1 and repoll_virt_guests = 1 then
           rhn_entitlements.repoll_virt_guest_entitlements(server_id_in);
         end if;
      end if;

		exception
		when no_data_found then
				rhn_exception.raise_exception('invalid_server_group_member');
      end;

	end remove_server_entitlement;


   procedure unentitle_server (server_id_in in number) is

      cursor servergroups is
         select distinct sgt.label, sg.id server_group_id
         from  rhnServerGroupType sgt,
               rhnServerGroup sg,
               rhnServer s,
               rhnServerGroupMembers sgm
         where s.id = server_id_in
            and s.org_id = sg.org_id
            and sg.group_type = sgt.id
            and sgm.server_group_id = sg.id
            and sgm.server_id = s.id;

     is_virt number := 0;

   begin

      begin
        select 1 into is_virt
          from rhnServerEntitlementView
         where server_id = server_id_in
           and label in ('virtualization_host', 'virtualization_host_platform');
      exception
        when no_data_found then
          is_virt := 0;
      end;

      for servergroup in servergroups loop

         insert into rhnServerHistory ( id, server_id, summary, details )
         values ( rhn_event_id_seq.nextval, server_id_in,
                  'removed system entitlement ',
                   case servergroup.label
                    when 'enterprise_entitled' then 'Management'
                    when 'sw_mgr_entitled' then 'Update'
                    when 'provisioning_entitled' then 'Provisioning'
                    when 'monitoring_entitled' then 'Monitoring'
                    when 'virtualization_host' then 'Virtualization'
                    when 'virtualization_host_platform' then
                         'Virtualization Platform' end  );

         rhn_server.delete_from_servergroup(server_id_in,
                                            servergroup.server_group_id );
      end loop;

      if is_virt = 1 then
        rhn_entitlements.repoll_virt_guest_entitlements(server_id_in);
      end if;

   end unentitle_server;


    -- *******************************************************************
    -- PROCEDURE: repoll_virt_guest_entitlements
    --
    --   Whenever we add/remove a virtualization_host* entitlement from
    --   a host, we can call this procedure to update what type of slots
    --   the guests are consuming.
    --
    --   If you're removing the entitlement, it's
    --   possible the guests will become unentitled if you don't have enough
    --   physical slots to cover them.
    --
    --   If you're adding the entitlement, you end up freeing up physical
    --   slots for other systems.
    --
    -- *******************************************************************
    procedure repoll_virt_guest_entitlements(server_id_in in number)
    is

        -- All channel families associated with the guests of server_id_in
        cursor families is
            select distinct cfs.channel_family_id
            from
                rhnChannelFamilyServers cfs,
                rhnVirtualInstance vi
            where
                vi.host_system_id = server_id_in
                and vi.virtual_system_id = cfs.server_id;

        -- All of server group types associated with the guests of
        -- server_id_in
        cursor group_types is
            select distinct sg.group_type, sgt.label
            from
                rhnServerGroupType sgt,
                rhnServerGroup sg,
                rhnServerGroupMembers sgm,
                rhnVirtualInstance vi
            where
                vi.host_system_id = server_id_in
                and vi.virtual_system_id = sgm.server_id
                and sgm.server_group_id = sg.id
                and sg.group_type = sgt.id;

        -- Virtual servers from a certain family belonging to a speicifc
        -- host that are consuming physical channel slots over the limit.
        cursor virt_servers_cfam(family_id_in in number, quantity_in in number)  is
            select virtual_system_id
            from (
                select rownum, vi.virtual_system_id
                from
                    rhnChannelFamilyMembers cfm,
                    rhnServerChannel sc,
                    rhnVirtualInstance vi
                where
                    vi.host_system_id = server_id_in
                    and vi.virtual_system_id = sc.server_id
                    and sc.channel_id = cfm.channel_id
                    and cfm.channel_family_id = family_id_in
                order by sc.modified desc
                )
            where rownum <= quantity_in;

        -- Virtual servers from a certain family belonging to a speicifc
        -- host that are consuming physical system slots over the limit.
        cursor virt_servers_sgt(group_type_in in number, quantity_in in number)  is
            select virtual_system_id
            from (
                select rownum, vi.virtual_system_id
                from
                    rhnServerGroup sg,
                    rhnServerGroupMembers sgm,
                    rhnVirtualInstance vi
                where
                    vi.host_system_id = server_id_in
                    and vi.virtual_system_id = sgm.server_id
                    and sgm.server_group_id = sg.id
                    and sg.group_type = group_type_in
                order by sgm.modified desc
                )
            where rownum <= quantity_in;

        org_id_val number;
        max_members_val number;
        current_members_calc number;
        sg_id number;

    begin

        select org_id
        into org_id_val
        from rhnServer
        where id = server_id_in;

        -- deal w/ channel entitlements first ...
        for family in families loop
            -- get the current (physical) members of the family
            current_members_calc :=
                rhn_channel.channel_family_current_members(family.channel_family_id,
                                                           org_id_val); -- fixed transposed args

            -- get the max members of the family
            select max_members
            into max_members_val
            from rhnPrivateChannelFamily
            where channel_family_id = family.channel_family_id
            and org_id = org_id_val;

            if current_members_calc > max_members_val then
                -- A virtualization_host* ent must have been removed, so we'll
                -- unsubscribe guests from the host first.

                -- hm, i don't think max_members - current_members_calc yielding a negative number
                -- will work w/ rownum, swaping 'em in the body of this if...
                for virt_server in virt_servers_cfam(family.channel_family_id,
                                current_members_calc - max_members_val) loop

                    rhn_channel.unsubscribe_server_from_family(
                                virt_server.virtual_system_id,
                                family.channel_family_id);
                end loop;

                -- if we're still over the limit, which would be odd,
                -- just prune the group to max_members
                --
                -- er... wouldn't we actually have to refresh the values of
                -- current_members_calc and max_members_val to actually ever
                -- *skip this??
                if current_members_calc > max_members_val then
                    -- argh, transposed again?!
                    set_family_count(org_id_val,
                                     family.channel_family_id,
                                     max_members_val);
                end if;

           end if;

            -- update current_members for the family.  This will set the value
            -- to reflect adding/removing the entitlement.
            --
            -- what's the difference of doing this vs the unavoidable set_family_count above?
            rhn_channel.update_family_counts(family.channel_family_id,
                                             org_id_val);
        end loop;

        for a_group_type in group_types loop
          -- get the current *physical* members of the system entitlement type for the org...
          --
          -- unlike channel families, it appears the standard rhnServerGroup.max_members represents
          -- *physical* slots, vs physical+virt ... boy that's confusing...

          select max_members, id
            into max_members_val, sg_id
            from rhnServerGroup
            where group_type = a_group_type.group_type
            and org_id = org_id_val;


	  select count(sep.server_id) into current_members_calc
            from rhnServerEntitlementPhysical sep
           where sep.server_group_id = sg_id
             and sep.server_group_type_id = a_group_type.group_type;

          if current_members_calc > max_members_val then
            -- A virtualization_host* ent must have been removed, and we're over the limit, so unsubscribe guests
            for virt_server in virt_servers_sgt(a_group_type.group_type,
                                                current_members_calc - max_members_val) loop
              rhn_entitlements.remove_server_entitlement(virt_server.virtual_system_id, a_group_type.label);

              -- decrement current_members_calc, we'll use it to reset current_members for the group at the end...
              current_members_calc := current_members_calc - 1;
            end loop;

          end if;

          update rhnServerGroup set current_members = current_members_calc
           where org_id = org_id_val
             and group_type = a_group_type.group_type;

          -- I think that's all the house-keeping we have to do...
        end loop;

    end repoll_virt_guest_entitlements;


	function get_server_entitlement (
		server_id_in in number
	) return ents_array is

		cursor server_groups is
			select	sgt.label
			from	rhnServerGroupType		sgt,
					rhnServerGroup			sg,
					rhnServerGroupMembers	sgm
			where	1=1
				and sgm.server_id = server_id_in
				and sg.id = sgm.server_group_id
				and sgt.id = sg.group_type
				and sgt.label in (
					'sw_mgr_entitled','enterprise_entitled',
					'provisioning_entitled', 'nonlinux_entitled',
					'monitoring_entitled', 'virtualization_host',
                                        'virtualization_host_platform'
					);

         ent_array ents_array;

	begin

      ent_array := ents_array();

		for sg in server_groups loop
         ent_array.extend;
         ent_array(ent_array.count) := sg.label;
		end loop;

		return ent_array;

	end get_server_entitlement;


	-- this desperately needs to be table driven.
	procedure modify_org_service (
		org_id_in in number,
		service_label_in in varchar2,
		enable_in in char
	) is
		type roles_v is varray(10) of rhnUserGroupType.label%TYPE;
		roles_to_process roles_v;
		cursor roles(role_label_in in varchar2) is
			select	label, id
			from	rhnUserGroupType
			where	label = role_label_in;
		cursor org_roles(role_label_in in varchar2) is
			select	1
			from	rhnUserGroup ug,
					rhnUserGroupType ugt
			where	ugt.label = role_label_in
				and ug.org_id = org_id_in
				and ugt.id = ug.group_type;

		type ents_v is varray(10) of rhnOrgEntitlementType.label%TYPE;
		ents_to_process ents_v;
		cursor ents(ent_label_in in varchar2) is
			select	label, id
			from	rhnOrgEntitlementType
			where	label = ent_label_in;
		cursor org_ents(ent_label_in in varchar2) is
			select	1
			from	rhnOrgEntitlements oe,
					rhnOrgEntitlementType oet
			where	oet.label = ent_label_in
				and oe.org_id = org_id_in
				and oet.id = oe.entitlement_id;
		create_row char(1);
	begin
		ents_to_process := ents_v();
		roles_to_process := roles_v();
		-- a bit kludgy, but only for 3.4 really.  Certainly no
		-- worse than the old code...
		if service_label_in = 'enterprise' or
           service_label_in = 'management' then
			ents_to_process.extend;
			ents_to_process(ents_to_process.count) := 'sw_mgr_enterprise';

			roles_to_process.extend;
			roles_to_process(roles_to_process.count) := 'org_admin';

			roles_to_process.extend;
			roles_to_process(roles_to_process.count) := 'system_group_admin';

			roles_to_process.extend;
			roles_to_process(roles_to_process.count) := 'activation_key_admin';

			roles_to_process.extend;
			roles_to_process(roles_to_process.count) := 'org_applicant';
		elsif service_label_in = 'provisioning' then
			ents_to_process.extend;
			ents_to_process(ents_to_process.count) := 'rhn_provisioning';

			roles_to_process.extend;
			roles_to_process(roles_to_process.count) := 'system_group_admin';

			roles_to_process.extend;
			roles_to_process(roles_to_process.count) := 'activation_key_admin';

			roles_to_process.extend;
			roles_to_process(roles_to_process.count) := 'config_admin';
			-- another nasty special case...
			if enable_in = 'Y' then
				ents_to_process.extend;
				ents_to_process(ents_to_process.count) := 'sw_mgr_enterprise';
			end if;
		elsif service_label_in = 'monitoring' then
			ents_to_process.extend;
			ents_to_process(ents_to_process.count) := 'rhn_monitor';

			roles_to_process.extend;
			roles_to_process(roles_to_process.count) := 'monitoring_admin';
		elsif service_label_in = 'virtualization' then
			ents_to_process.extend;
			ents_to_process(ents_to_process.count) := 'rhn_virtualization';

			roles_to_process.extend;
			roles_to_process(roles_to_process.count) := 'config_admin';
        elsif service_label_in = 'virtualization_platform' then
			ents_to_process.extend;
			ents_to_process(ents_to_process.count) := 'rhn_virtualization_platform';
			roles_to_process.extend;
			roles_to_process(roles_to_process.count) := 'config_admin';
	elsif service_label_in = 'nonlinux' then
			ents_to_process.extend;
			ents_to_process(ents_to_process.count) := 'rhn_nonlinux';
			roles_to_process.extend;
			roles_to_process(roles_to_process.count) := 'config_admin';
		end if;

		if enable_in = 'Y' then
			for i in 1..ents_to_process.count loop
				for ent in ents(ents_to_process(i)) loop
					create_row := 'Y';
					for oe in org_ents(ent.label) loop
						create_row := 'N';
					end loop;
					if create_row = 'Y' then
						insert into rhnOrgEntitlements(org_id, entitlement_id)
							values (org_id_in, ent.id);
					end if;
				end loop;
			end loop;
			for i in 1..roles_to_process.count loop
				for role in roles(roles_to_process(i)) loop
					create_row := 'Y';
					for o_r in org_roles(role.label) loop
						create_row := 'N';
					end loop;
					if create_row = 'Y' then
						insert into rhnUserGroup(
								id, name, description, current_members,
								group_type, org_id
							) (
								select	rhn_user_group_id_seq.nextval,
										ugt.name || 's',
										ugt.name || 's for Org ' ||
											o.name || ' ('|| o.id ||')',
										0, ugt.id, o.id
								from	rhnUserGroupType ugt,
										web_customer o
								where	o.id = org_id_in
									and ugt.id = role.id
							);
					end if;
				end loop;
			end loop;
		else
			for i in 1..ents_to_process.count loop
				for ent in ents(ents_to_process(i)) loop
					delete from rhnOrgEntitlements
					 where org_id = org_id_in
					   and entitlement_id = ent.id;
				end loop;
			end loop;
		end if;
	end modify_org_service;

	procedure set_customer_enterprise (
		customer_id_in in number
	) is
	begin
		modify_org_service(customer_id_in, 'enterprise', 'Y');
	end set_customer_enterprise;

	procedure set_customer_provisioning (
		customer_id_in in number
	) is
	begin
		modify_org_service(customer_id_in, 'provisioning', 'Y');
	end set_customer_provisioning;

	procedure set_customer_monitoring (
		customer_id_in in number
	) is
	begin
		modify_org_service(customer_id_in, 'monitoring', 'Y');
	end set_customer_monitoring;

	procedure set_customer_nonlinux (
		customer_id_in in number
	) is
	begin
		modify_org_service(customer_id_in, 'nonlinux', 'Y');
	end set_customer_nonlinux;

	procedure unset_customer_enterprise (
		customer_id_in in number
	) is
	begin
		modify_org_service(customer_id_in, 'enterprise', 'N');
	end unset_customer_enterprise;

	procedure unset_customer_provisioning (
		customer_id_in in number
	) is
	begin
		modify_org_service(customer_id_in, 'provisioning', 'N');
	end unset_customer_provisioning;

	procedure unset_customer_monitoring (
		customer_id_in in number
	) is
	begin
		modify_org_service(customer_id_in, 'monitoring', 'N');
	end unset_customer_monitoring;

	procedure unset_customer_nonlinux (
		customer_id_in in number
	) is
	begin
		modify_org_service(customer_id_in, 'nonlinux', 'N');
	end unset_customer_nonlinux;

    -- *******************************************************************
    -- PROCEDURE: prune_group
    -- Unsubscribes servers consuming physical slots that over the org's
    --   limit.
    -- Called by: set_group_count, prune_everything, repoll_virt_guest_entitlements
    -- *******************************************************************
	procedure prune_group (
		group_id_in in number,
		type_in in char,
		quantity_in in number,
                update_family_countsYN in number := 1
	) is
		cursor usergroups is
			select	user_id, user_group_id, ugt.label
			from	rhnUserGroupType	ugt,
					rhnUserGroup		ug,
					rhnUserGroupMembers	ugm
			where	1=1
				and ugm.user_group_id = group_id_in
				and ugm.user_id in (
					select	user_id
					from	(
						select	rownum row_number,
								user_id,
								time
						from	(
							select	user_id,
									modified time
							from	rhnUserGroupMembers
							where	user_group_id = group_id_in
							order by time asc
						)
					)
					where	row_number > quantity_in
				)
				and ugm.user_group_id = ug.id
				and ug.group_type = ugt.id;
        cursor servergroups is
           select  server_id, server_group_id, sgt.id group_type_id, sgt.label
            from    rhnServerGroupType              sgt,
                            rhnServerGroup                  sg,
                            rhnServerGroupMembers   sgm
            where   1=1
                    and sgm.server_group_id = group_id_in
                    and sgm.server_id in (
                            select  server_id
                            from    (
                                    select  rownum row_number,
                                                    server_id,
                                                    time
                                    from    (
                                            select  sep.server_id,
                                                    sep.modified time
                                            from
                                                rhnServerEntitlementPhysical sep
                                            where
                                                sep.server_group_id = group_id_in
                                            order by time asc
                                    )
                            )
                            where   row_number > quantity_in
                    )
                    and sgm.server_group_id = sg.id
                    and sg.group_type = sgt.id;
      type_is_base char;
	begin
		if type_in = 'U' then
			update		rhnUserGroup
				set		max_members = quantity_in
				where	id = group_id_in;

			for ug in usergroups loop
				rhn_user.remove_from_usergroup(ug.user_id, ug.user_group_id);
			end loop;
		elsif type_in = 'S' then
			update		rhnServerGroup
				set		max_members = quantity_in
				where	id = group_id_in;

			for sg in servergroups loop
				remove_server_entitlement(sg.server_id, sg.label);

            select is_base
            into type_is_base
            from rhnServerGroupType sgt
            where sgt.id = sg.group_type_id;

            -- if we're removing a base ent, then be sure to
            -- remove the server's channel subscriptions.
            if ( type_is_base = 'Y' ) then
				   rhn_channel.clear_subscriptions(sg.server_id,
                                        update_family_countsYN => update_family_countsYN);
            end if;

			end loop;
		end if;
	end prune_group;

    -- *******************************************************************
    -- PROCEDURE: assign_system_entitlement
    --
    -- Moves system entitlements from from_org_id_in to to_org_id_in.
    -- Can raise not_enough_entitlements_in_base_org if from_org_id_in
    -- does not have enough entitlements to cover the move.
    -- Takes care of unentitling systems if necessary by calling
    -- set_group_count
    -- *******************************************************************
    procedure assign_system_entitlement(
        group_label_in in varchar2,
        from_org_id_in in number,
        to_org_id_in in number,
        quantity_in in number
    )
    is
        prev_ent_count number;
	to_org_prev_ent_count number;
        new_ent_count number;
	new_quantity number;
        group_type number;
    begin

        begin
            select max_members
            into prev_ent_count
            from rhnServerGroupType sgt,
                 rhnServerGroup sg
            where sg.org_id = from_org_id_in
              and sg.group_type = sgt.id
              and sgt.label = group_label_in;
        exception
            when NO_DATA_FOUND then
                rhn_exception.raise_exception(
                              'not_enough_entitlements_in_base_org');
        end;

        begin
            select max_members
            into to_org_prev_ent_count
            from rhnServerGroupType sgt,
                 rhnServerGroup sg
            where sg.org_id = to_org_id_in
              and sg.group_type = sgt.id
              and sgt.label = group_label_in;
        exception
            when NO_DATA_FOUND then
                to_org_prev_ent_count := 0;
        end;

        begin
            select id
            into group_type
            from rhnServerGroupType
            where label = group_label_in;
        exception
            when NO_DATA_FOUND then
                rhn_exception.raise_exception(
                              'invalid_server_group');
        end;

        new_ent_count := prev_ent_count - quantity_in;

        if prev_ent_count > new_ent_count then
            new_quantity := to_org_prev_ent_count + quantity_in;
        end if;

        if new_ent_count < 0 then
            rhn_exception.raise_exception(
                          'not_enough_entitlements_in_base_org');
        end if;


        rhn_entitlements.set_group_count(from_org_id_in,
                                         'S',
                                         group_type,
                                         new_ent_count);

        rhn_entitlements.set_group_count(to_org_id_in,
                                         'S',
                                         group_type,
                                         new_quantity);

        -- Create or delete the entries in rhnOrgEntitlementType
        if group_label_in = 'enterprise_entitled' then
            if new_quantity > 0 then
                set_customer_enterprise(to_org_id_in);
            else
                unset_customer_enterprise(to_org_id_in);
            end if;
        end if;

        if group_label_in = 'provisioning_entitled' then
            if new_quantity > 0 then
                set_customer_provisioning(to_org_id_in);
            else
                unset_customer_provisioning(to_org_id_in);
            end if;
        end if;

        if group_label_in = 'monitoring_entitled' then
            if new_quantity > 0 then
                set_customer_monitoring(to_org_id_in);
            else
                unset_customer_monitoring(to_org_id_in);
            end if;
        end if;

    end assign_system_entitlement;

    -- *******************************************************************
    -- PROCEDURE: assign_channel_entitlement
    --
    -- Moves channel entitlements from from_org_id_in to to_org_id_in.
    -- Can raise not_enough_entitlements_in_base_org if from_org_id_in
    -- does not have enough entitlements to cover the move.
    -- Takes care of unentitling systems if necessary by calling
    -- set_family_count
    -- *******************************************************************
    procedure assign_channel_entitlement(
        channel_family_label_in in varchar2,
        from_org_id_in in number,
        to_org_id_in in number,
        quantity_in in number
    )
    is
        prev_ent_count number;
        new_ent_count number;
	to_org_prev_ent_count number;
	new_quantity number;
        cfam_id       number;
    begin

        begin
            select max_members
            into prev_ent_count
            from rhnChannelFamily cf,
                 rhnPrivateChannelFamily pcf
            where pcf.org_id = from_org_id_in
              and pcf.channel_family_id = cf.id
              and cf.label = channel_family_label_in;
        exception
            when NO_DATA_FOUND then
                rhn_exception.raise_exception(
                              'not_enough_entitlements_in_base_org');
        end;

        begin
            select max_members
            into to_org_prev_ent_count
            from rhnChannelFamily cf,
                 rhnPrivateChannelFamily pcf
            where pcf.org_id = to_org_id_in
              and pcf.channel_family_id = cf.id
              and cf.label = channel_family_label_in;
        exception
            when NO_DATA_FOUND then
                to_org_prev_ent_count := 0;
        end;


        begin
            select id
            into cfam_id
            from rhnChannelFamily
            where label = channel_family_label_in;
        exception
            when NO_DATA_FOUND then
                rhn_exception.raise_exception(
                              'invalid_channel_family');
        end;

        new_ent_count := prev_ent_count - quantity_in;

	if prev_ent_count > new_ent_count then
            new_quantity := to_org_prev_ent_count + quantity_in;
	end if;


        if new_ent_count < 0 then
            rhn_exception.raise_exception(
                          'not_enough_entitlements_in_base_org');
        end if;

        rhn_entitlements.set_family_count(from_org_id_in,
                                          cfam_id,
                                          new_ent_count);

        rhn_entitlements.set_family_count(to_org_id_in,
                                          cfam_id,
                                          new_quantity);

    end assign_channel_entitlement;

    -- *******************************************************************
    -- PROCEDURE: activate_system_entitlement
    --
    -- Sets the values in rhnServerGroup for a given rhnServerGroupType.
    --
    -- Calls: set_group_count to update, prune, or create the group.
    -- Called by: the code that activates a satellite cert.
    --
    -- Raises not_enough_entitlements_in_base_org if all entitlements
    -- in the org are used so the free entitlements would not cover
    -- the difference when descreasing the number of entitlements.
    -- *******************************************************************
    procedure activate_system_entitlement(
        org_id_in in number,
        group_label_in in varchar2,
        quantity_in in number
    )
    is
        prev_ent_count number;
        prev_ent_count_sum number;
        group_type number;
    begin

        -- Fetch the current entitlement count for the org
        -- into prev_ent_count
        begin
            select current_members
            into prev_ent_count
            from rhnServerGroupType sgt,
                 rhnServerGroup sg
            where sg.group_type = sgt.id
              and sgt.label = group_label_in
              and sg.org_id = org_id_in;
        exception
            when NO_DATA_FOUND then
                prev_ent_count := 0;
        end;

        begin
            select id
            into group_type
            from rhnServerGroupType
            where label = group_label_in;
        exception
            when NO_DATA_FOUND then
                rhn_exception.raise_exception(
                              'invalid_server_group');
        end;

        -- If we're setting the total entitlemnt count to a lower value,
        -- and that value is less than the allocated count in this org,
        -- we need to raise an exception.
        if quantity_in < prev_ent_count then
            rhn_exception.raise_exception(
                          'not_enough_entitlements_in_base_org');
        else
            -- don't update family counts after every server
            -- will do bulk update afterwards
            rhn_entitlements.set_group_count(org_id_in,
                                             'S',
                                             group_type,
                                             quantity_in,
                                             update_family_countsYN => 0);
            -- bulk update family counts
            rhn_channel.update_group_family_counts(group_label_in, org_id_in);
        end if;


    end activate_system_entitlement;

    -- *******************************************************************
    -- PROCEDURE: activate_channel_entitlement
    --
    -- Calls: set_family_count to update, prune, or create the family
    --        permission bucket.
    -- Called by: the code that activates a satellite cert.
    --
    -- Raises not_enough_entitlements_in_base_org if there are not enough
    -- entitlements in the org to cover the difference when you are
    -- descreasing the number of entitlements.
    --
    -- The backend code in Python is expected to do whatever arithmetics
    -- is needed.
    -- *******************************************************************
    procedure activate_channel_entitlement(
        org_id_in in number,
        channel_family_label_in in varchar2,
        quantity_in in number
    )
    is
        prev_ent_count number;
        prev_ent_count_sum number;
        cfam_id number;
    begin

        -- Fetch the current entitlement count for the org
        -- into prev_ent_count
        begin
            select current_members
            into prev_ent_count
            from rhnChannelFamily cf,
                 rhnPrivateChannelFamily pcf
            where pcf.org_id = org_id_in
              and pcf.channel_family_id = cf.id
              and cf.label = channel_family_label_in;
        exception
            when NO_DATA_FOUND then
                prev_ent_count := 0;
        end;

        begin
            select id
            into cfam_id
            from rhnChannelFamily
            where label = channel_family_label_in;
        exception
            when NO_DATA_FOUND then
                rhn_exception.raise_exception(
                              'invalid_channel_family');
        end;

        -- If we're setting the total entitlemnt count to a lower value,
        -- and that value is less than the count in that one org,
        -- we need to raise an exception.
        if quantity_in < prev_ent_count then
            rhn_exception.raise_exception(
                          'not_enough_entitlements_in_base_org');
        else
            rhn_entitlements.set_family_count(org_id_in,
                                              cfam_id,
                                              quantity_in);
        end if;

    end activate_channel_entitlement;


	procedure set_group_count (
		customer_id_in in number,
		type_in in char,
		group_type_in in number,
		quantity_in in number,
                update_family_countsYN in number := 1
	) is
		group_id number;
		quantity number;
	begin
		quantity := quantity_in;
		if quantity is not null and quantity < 0 then
			quantity := 0;
		end if;

		if type_in = 'U' then
			select	rug.id
			into	group_id
			from	rhnUserGroup rug
			where	1=1
				and rug.org_id = customer_id_in
				and rug.group_type = group_type_in;
		elsif type_in = 'S' then
			select	rsg.id
			into	group_id
			from	rhnServerGroup rsg
			where	1=1
				and rsg.org_id = customer_id_in
				and rsg.group_type = group_type_in;
		end if;

		rhn_entitlements.prune_group(
			group_id,
			type_in,
			quantity,
                        update_family_countsYN
		);
	exception
		when no_data_found then
			if type_in = 'U' then
				insert into rhnUserGroup (
						id, name, description, max_members, current_members,
						group_type, org_id, created, modified
					) (
						select	rhn_user_group_id_seq.nextval, name, name,
								quantity, 0, id, customer_id_in,
								sysdate, sysdate
						from	rhnUserGroupType
						where	id = group_type_in
				);
			elsif type_in = 'S' then
				insert into rhnServerGroup (
						id, name, description, max_members, current_members,
						group_type, org_id, created, modified
					) (
						select	rhn_server_group_id_seq.nextval, name, name,
								quantity, 0, id, customer_id_in,
								sysdate, sysdate
						from	rhnServerGroupType
						where	id = group_type_in
				);
			end if;
	end set_group_count;

    -- *******************************************************************
    -- PROCEDURE: prune_family
    -- Unsubscribes servers consuming physical slots from the channel family
    --   that are over the org's limit.
    -- Called by: set_family_count, prune_everything
    -- *******************************************************************
	procedure prune_family (
		customer_id_in in number,
		channel_family_id_in in number,
		quantity_in in number
	) is
		cursor serverchannels is
			select	sc.server_id,
					sc.channel_id
			from	rhnServerChannel sc,
					rhnChannelFamilyMembers cfm
			where	1=1
				and cfm.channel_family_id = channel_family_id_in
				and cfm.channel_id = sc.channel_id
				and server_id in (
					select	server_id
					from	(
						select	server_id,
								time,
								rownum row_number
						from	(
							select	rs.id					server_id,
									rcfm.modified			time
							from
									rhnServerChannel		rsc,
									rhnChannelFamilyMembers	rcfm,
                                    rhnServer				rs
							where	1=1
								and rs.org_id = customer_id_in
								and rs.id = rsc.server_id
								and rsc.channel_id = rcfm.channel_id
								and rcfm.channel_family_id =
									channel_family_id_in
                                -- we only want to grab servers consuming
                                -- physical slots.
                                and exists (
                                    select 1
                                    from rhnChannelFamilyServerPhysical cfsp
                                    where cfsp.server_id = rs.id
                                    and cfsp.channel_family_id =
                                        channel_family_id_in
                                    )
							order by time asc
						)
					)
					where row_number > quantity_in
				);
	begin
		-- if we get a null customer_id, this is completely bogus.
		if customer_id_in is null then
			return;
		end if;

		update		rhnPrivateChannelFamily
			set		max_members = quantity_in
			where	1=1
				and org_id = customer_id_in
				and channel_family_id = channel_family_id_in;

		for sc in serverchannels loop
			rhn_channel.unsubscribe_server(sc.server_id, sc.channel_id, 1, 1,
                                                       update_family_countsYN => 0);
		end loop;
                rhn_channel.update_family_counts(channel_family_id_in, customer_id_in);
	end prune_family;

	procedure set_family_count (
		customer_id_in in number,
		channel_family_id_in in number,
		quantity_in in number
	) is
		cursor privperms is
			select	1
			from	rhnPrivateChannelFamily
			where	org_id = customer_id_in
				and channel_family_id = channel_family_id_in;
		cursor pubperms is
			select	o.id org_id
			from	web_customer o,
					rhnPublicChannelFamily pcf
			where	pcf.channel_family_id = channel_family_id_in;
		quantity number;
		done number := 0;
	begin
		quantity := quantity_in;
		if quantity is not null and quantity < 0 then
			quantity := 0;
		end if;

		if customer_id_in is not null then
			for perm in privperms loop
				rhn_entitlements.prune_family(
					customer_id_in,
					channel_family_id_in,
					quantity
				);
				update rhnPrivateChannelFamily
					set max_members = quantity
					where org_id = customer_id_in
						and channel_family_id = channel_family_id_in;
				return;
			end loop;

			insert into rhnPrivateChannelFamily (
					channel_family_id, org_id, max_members, current_members
				) values (
					channel_family_id_in, customer_id_in, quantity, 0
				);
			return;
		end if;

		for perm in pubperms loop
			if quantity = 0 then
				rhn_entitlements.prune_family(
					perm.org_id,
					channel_family_id_in,
					quantity
				);
				if done = 0 then
					delete from rhnPublicChannelFamily
						where channel_family_id = channel_family_id_in;
				end if;
			end if;
			done := 1;
		end loop;
		-- if done's not 1, then we don't have any entitlements
		if done != 1 then
			insert into rhnPublicChannelFamily (
					channel_family_id
				) values (
					channel_family_id_in
				);
		end if;
	end set_family_count;

	-- this expects quantity_in to be the number of available slots, not the
	-- max_members of the server group.  If you give it too many, it'll fail
	-- and raise servergroup_max_members.
	-- We should NEVER run this unless we're SURE that we won't
	-- be violating the max.
	procedure entitle_last_modified_servers (
		customer_id_in in number,
		type_label_in in varchar2,
		quantity_in in number
	) is
		-- find the servers that aren't currently in slots
		cursor servers(cid_in in number, quant_in in number) is
			select	server_id
			from	(
						select	rownum row_number,
								server_id
						from	(
									select	rs.id server_iD
									from	rhnServer rs
									where	1=1
										and rs.org_id = cid_in
										and not exists (
											select	1
											from	rhnServerGroup sg,
													rhnServerGroupMembers rsgm
											where	rsgm.server_id = rs.id
												and rsgm.server_group_id = sg.id
												and sg.group_type is not null
										)
                                        and not exists (
                                            select 1
                                            from rhnVirtualInstance vi
                                            where vi.virtual_system_id =
                                                  rs.id
                                        )                                                                           order by modified desc
								)
					)
			where	row_number <= quant_in;
	begin
		for server in servers(customer_id_in, quantity_in) loop
			rhn_entitlements.entitle_server(server.server_id, type_label_in);
		end loop;
	end entitle_last_modified_servers;

	procedure prune_everything (
		customer_id_in in number
	) is
		cursor everything is
			-- all our server groups
			select	sg.id					id,
					'S'						type,
					sg.max_members			quantity
			from	rhnServerGroup			sg
			where	sg.org_id = customer_id_in
			union
			-- all our user groups
			select	ug.id					id,
					'U'						type,
					ug.max_members 			quantity
			from	rhnUserGroup			ug
			where	ug.org_id = customer_id_in
			union (
			-- all the channel families we have perms to
			select	cfp.channel_family_id	id,
					'C'						type,
					cfp.max_members			quantity
			from	rhnOrgChannelFamilyPermissions cfp
			where	cfp.org_id = customer_id_in
			union
			-- plus all the ones we're using that we have no perms for
			select	cfm.channel_family_id	id,
					'C'						type,
					0						quantity
			from	rhnChannelFamily		cf,
					rhnChannelFamilyMembers	cfm,
					rhnServerChannel		sc,
					rhnServer				s
			where	s.org_id = customer_id_in
				and s.id = sc.server_id
				and sc.channel_id = cfm.channel_id
				and cfm.channel_family_id = cf.id
				and cf.org_id is not null
				and cf.org_id != customer_id_in
				and not exists (
					select	1
					from	rhnOrgChannelFamilyPermissions cfp
					where	cfp.org_id = customer_id_in
						and cfp.channel_family_id = cfm.channel_family_id
					)
			);
	begin
		for one in everything loop
			if one.type in ('U','S') then
				prune_group(one.id, one.type, one.quantity);
			else
				prune_family(customer_id_in, one.id, one.quantity);
			end if;
		end loop;
	end prune_everything;

	procedure subscribe_newest_servers (
		customer_id_in in number
	) is
		-- find servers without base channels
		cursor servers(cid_in in number) is
			select	s.id
			from	rhnServer			s
			where	1=1
				and s.org_id = cid_in
				and not exists (
						select 1
						from	rhnChannel			c,
								rhnServerChannel	sc
						where	sc.server_id = s.id
							and sc.channel_id = c.id
							and c.parent_channel is null
					)
                and not exists (
                        select 1
                        from rhnVirtualInstance vi
                        where vi.virtual_system_id = s.id
                    )
			order by s.modified desc;
		channel_id number;
	begin
		for server in servers(customer_id_in) loop
			channel_id := rhn_channel.guess_server_base(server.id);
			if channel_id is not null then
				begin
					rhn_channel.subscribe_server(server.id, channel_id);
					commit;
				-- exception is really channel_family_no_subscriptions
				exception
					when others then
						null;
				end;
			end if;
		end loop;
	end subscribe_newest_servers;
end rhn_entitlements;
/
show errors

--
--
-- Revision 1.56  2004/07/21 21:27:36  nhansen
-- bug 128196: use rhn_monitor instead of rhn_monitoring as the rhnOrgEntitlementType
--
-- Revision 1.55  2004/07/20 15:38:57  pjones
-- bugzilla: 128196 -- make entitling "monitoring" work.
--
-- Revision 1.54  2004/07/14 19:13:13  pjones
-- bugzilla: 126461 -- entitlement changes for new user roles
--
-- Revision 1.53  2004/07/02 19:18:20  pjones
-- bugzilla: 125937 -- use rhn_user to remove user roles
--
-- Revision 1.52  2004/05/26 19:45:48  pjones
-- bugzilla: 123639
-- 1) reformat "entitlement_grants_service"
-- 2) make the .pks and .pkb be in the same order.
-- 3) add "modify_org_service" (to be used instead of set_customer_SERVICELEVEL)
-- 4) add monitoring specific data.
--
-- Revision 1.51  2004/04/19 18:18:51  pjones
-- bugzilla: none -- misa's using set_family_count() to set null org entitlements
--
-- Revision 1.50  2004/04/14 00:09:24  pjones
-- bugzilla: 120761 -- split rhnChannelPermissions into two tables, eliminating
-- a frequent full table scan
--
-- Revision 1.49  2004/03/26 16:53:42  pjones
-- bugzilla: none -- make rhn_nonlinux give config_admin too on sat.
--
-- Revision 1.48  2004/03/25 22:29:56  pjones
-- bugzilla: none -- only create config_admin in set_customer_prov if we're
-- on a satellite
  07070100000538000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000004800000000susemanager-schema/upgrade/spacewalk-schema-0.8-to-spacewalk-schema-1.0   07070100000539000081B400000000000000000000000167AE1114000057D5000000000000000000000000000000000000005F00000000susemanager-schema/upgrade/spacewalk-schema-0.8-to-spacewalk-schema-1.0/001-debian-support.sql    --
-- Add new rows for debian support
--


insert into rhnArchType (id, label, name) values
	(rhn_archtype_id_seq.nextval, 'deb', 'DEB');

commit;

insert into rhnChannelArch (id, label, name, arch_type_id) values
(rhn_channel_arch_id_seq.nextval, 'channel-ia32-deb', 'IA-32 Debian', lookup_arch_type('deb'));
insert into rhnChannelArch (id, label, name, arch_type_id) values
(rhn_channel_arch_id_seq.nextval, 'channel-ia64-deb', 'IA-64 Debian', lookup_arch_type('deb'));
insert into rhnChannelArch (id, label, name, arch_type_id) values
(rhn_channel_arch_id_seq.nextval, 'channel-amd64-deb', 'AMD64 Debian', lookup_arch_type('deb'));
insert into rhnChannelArch (id, label, name, arch_type_id) values
(rhn_channel_arch_id_seq.nextval, 'channel-sparc-deb', 'Sparc Debian', lookup_arch_type('deb'));
insert into rhnChannelArch (id, label, name, arch_type_id) values
(rhn_channel_arch_id_seq.nextval, 'channel-alpha-deb', 'Alpha Debian', lookup_arch_type('deb'));
insert into rhnChannelArch (id, label, name, arch_type_id) values
(rhn_channel_arch_id_seq.nextval, 'channel-s390-deb', 's390 Debian', lookup_arch_type('deb'));
insert into rhnChannelArch (id, label, name, arch_type_id) values
(rhn_channel_arch_id_seq.nextval, 'channel-powerpc-deb', 'PowerPC Debian', lookup_arch_type('deb'));
insert into rhnChannelArch (id, label, name, arch_type_id) values
(rhn_channel_arch_id_seq.nextval, 'channel-arm-deb', 'arm Debian', lookup_arch_type('deb'));
insert into rhnChannelArch (id, label, name, arch_type_id) values
(rhn_channel_arch_id_seq.nextval, 'channel-mips-deb', 'mips Debian', lookup_arch_type('deb'));

commit;

insert into rhnPackageArch (id, label, name, arch_type_id) values
(rhn_package_arch_id_seq.nextval, 'all-deb', 'all-deb', lookup_arch_type('deb'));
insert into rhnPackageArch (id, label, name, arch_type_id) values
(rhn_package_arch_id_seq.nextval, 'i386-deb', 'i386-deb', lookup_arch_type('deb'));
insert into rhnPackageArch (id, label, name, arch_type_id) values
(rhn_package_arch_id_seq.nextval, 'alpha-deb', 'alpha-deb', lookup_arch_type('deb'));
insert into rhnPackageArch (id, label, name, arch_type_id) values
(rhn_package_arch_id_seq.nextval, 'ia64-deb', 'ia64-deb', lookup_arch_type('deb'));
insert into rhnPackageArch (id, label, name, arch_type_id) values
(rhn_package_arch_id_seq.nextval, 'sparc-deb', 'sparc-deb', lookup_arch_type('deb'));
insert into rhnPackageArch (id, label, name, arch_type_id) values
(rhn_package_arch_id_seq.nextval, 'src-deb', 'src-deb', lookup_arch_type('deb'));
insert into rhnPackageArch (id, label, name, arch_type_id) values
(rhn_package_arch_id_seq.nextval, 's390-deb', 's390-deb', lookup_arch_type('deb'));
insert into rhnPackageArch (id, label, name, arch_type_id) values
(rhn_package_arch_id_seq.nextval, 'powerpc-deb', 'powerpc-deb', lookup_arch_type('deb'));
insert into rhnPackageArch (id, label, name, arch_type_id) values
(rhn_package_arch_id_seq.nextval, 'arm-deb', 'arm-deb', lookup_arch_type('deb'));
insert into rhnPackageArch (id, label, name, arch_type_id) values
(rhn_package_arch_id_seq.nextval, 'mips-deb', 'mips-deb', lookup_arch_type('deb'));
insert into rhnPackageArch (id, label, name, arch_type_id) values
(rhn_package_arch_id_seq.nextval, 'amd64-deb', 'AMD64-deb', lookup_arch_type('deb'));

commit;

insert into rhnChannelPackageArchCompat (channel_arch_id, package_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-ia32-deb'), LOOKUP_PACKAGE_ARCH('all-deb'));
insert into rhnChannelPackageArchCompat (channel_arch_id, package_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-ia32-deb'), LOOKUP_PACKAGE_ARCH('i386-deb'));
insert into rhnChannelPackageArchCompat (channel_arch_id, package_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-ia32-deb'), LOOKUP_PACKAGE_ARCH('src-deb'));

insert into rhnChannelPackageArchCompat (channel_arch_id, package_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-ia64-deb'), LOOKUP_PACKAGE_ARCH('all-deb'));
insert into rhnChannelPackageArchCompat (channel_arch_id, package_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-ia64-deb'), LOOKUP_PACKAGE_ARCH('i386-deb'));
insert into rhnChannelPackageArchCompat (channel_arch_id, package_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-ia64-deb'), LOOKUP_PACKAGE_ARCH('ia64-deb'));
insert into rhnChannelPackageArchCompat (channel_arch_id, package_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-ia64-deb'), LOOKUP_PACKAGE_ARCH('src-deb'));

insert into rhnChannelPackageArchCompat (channel_arch_id, package_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-sparc-deb'), LOOKUP_PACKAGE_ARCH('all-deb'));
insert into rhnChannelPackageArchCompat (channel_arch_id, package_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-sparc-deb'), LOOKUP_PACKAGE_ARCH('sparc-deb'));
insert into rhnChannelPackageArchCompat (channel_arch_id, package_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-sparc-deb'), LOOKUP_PACKAGE_ARCH('src-deb'));

insert into rhnChannelPackageArchCompat (channel_arch_id, package_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-alpha-deb'), LOOKUP_PACKAGE_ARCH('all-deb'));
insert into rhnChannelPackageArchCompat (channel_arch_id, package_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-alpha-deb'), LOOKUP_PACKAGE_ARCH('alpha-deb'));
insert into rhnChannelPackageArchCompat (channel_arch_id, package_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-alpha-deb'), LOOKUP_PACKAGE_ARCH('src-deb'));

insert into rhnChannelPackageArchCompat (channel_arch_id, package_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-s390-deb'), LOOKUP_PACKAGE_ARCH('all-deb'));
insert into rhnChannelPackageArchCompat (channel_arch_id, package_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-s390-deb'), LOOKUP_PACKAGE_ARCH('s390-deb'));
insert into rhnChannelPackageArchCompat (channel_arch_id, package_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-s390-deb'), LOOKUP_PACKAGE_ARCH('src-deb'));

insert into rhnChannelPackageArchCompat (channel_arch_id, package_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-amd64-deb'), LOOKUP_PACKAGE_ARCH('all-deb'));
insert into rhnChannelPackageArchCompat (channel_arch_id, package_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-amd64-deb'), LOOKUP_PACKAGE_ARCH('i386-deb'));
insert into rhnChannelPackageArchCompat (channel_arch_id, package_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-amd64-deb'), LOOKUP_PACKAGE_ARCH('amd64-deb'));
insert into rhnChannelPackageArchCompat (channel_arch_id, package_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-amd64-deb'), LOOKUP_PACKAGE_ARCH('src-deb'));

insert into rhnChannelPackageArchCompat (channel_arch_id, package_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-powerpc-deb'), LOOKUP_PACKAGE_ARCH('all-deb'));
insert into rhnChannelPackageArchCompat (channel_arch_id, package_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-powerpc-deb'), LOOKUP_PACKAGE_ARCH('powerpc-deb'));
insert into rhnChannelPackageArchCompat (channel_arch_id, package_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-powerpc-deb'), LOOKUP_PACKAGE_ARCH('src-deb'));

insert into rhnChannelPackageArchCompat (channel_arch_id, package_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-arm-deb'), LOOKUP_PACKAGE_ARCH('all-deb'));
insert into rhnChannelPackageArchCompat (channel_arch_id, package_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-arm-deb'), LOOKUP_PACKAGE_ARCH('arm-deb'));
insert into rhnChannelPackageArchCompat (channel_arch_id, package_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-arm-deb'), LOOKUP_PACKAGE_ARCH('src-deb'));

insert into rhnChannelPackageArchCompat (channel_arch_id, package_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-mips-deb'), LOOKUP_PACKAGE_ARCH('all-deb'));
insert into rhnChannelPackageArchCompat (channel_arch_id, package_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-mips-deb'), LOOKUP_PACKAGE_ARCH('mips-deb'));
insert into rhnChannelPackageArchCompat (channel_arch_id, package_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-mips-deb'), LOOKUP_PACKAGE_ARCH('src-deb'));

commit;


insert into rhnServerArch (id, label, name, arch_type_id) values
(rhn_server_arch_id_seq.nextval, 'i386-debian-linux', 'i386 Debian', lookup_arch_type('deb'));
insert into rhnServerArch (id, label, name, arch_type_id) values
(rhn_server_arch_id_seq.nextval, 'alpha-debian-linux', 'alpha Debian', lookup_arch_type('deb'));
insert into rhnServerArch (id, label, name, arch_type_id) values
(rhn_server_arch_id_seq.nextval, 'ia64-debian-linux', 'ia64 Debian', lookup_arch_type('deb'));
insert into rhnServerArch (id, label, name, arch_type_id) values
(rhn_server_arch_id_seq.nextval, 'sparc-debian-linux', 'sparc Debian', lookup_arch_type('deb'));
insert into rhnServerArch (id, label, name, arch_type_id) values
(rhn_server_arch_id_seq.nextval, 's390-debian-linux', 's390 Debian', lookup_arch_type('deb'));
insert into rhnServerArch (id, label, name, arch_type_id) values
(rhn_server_arch_id_seq.nextval, 'powerpc-debian-linux', 'powerpc Debian', lookup_arch_type('deb'));
insert into rhnServerArch (id, label, name, arch_type_id) values
(rhn_server_arch_id_seq.nextval, 'amd64-debian-linux', 'AMD64 Debian', lookup_arch_type('deb'));
insert into rhnServerArch (id, label, name, arch_type_id) values
(rhn_server_arch_id_seq.nextval, 'arm-debian-linux', 'arm Debian', lookup_arch_type('deb'));
insert into rhnServerArch (id, label, name, arch_type_id) values
(rhn_server_arch_id_seq.nextval, 'mips-debian-linux', 'mips Debian', lookup_arch_type('deb'));

commit;

insert into rhnServerPackageArchCompat
 (server_arch_id, package_arch_id, preference) values
 (LOOKUP_SERVER_ARCH('i386-debian-linux'), LOOKUP_PACKAGE_ARCH('i386-deb'), 0);
insert into rhnServerPackageArchCompat
 (server_arch_id, package_arch_id, preference) values
 (LOOKUP_SERVER_ARCH('i386-debian-linux'), LOOKUP_PACKAGE_ARCH('all-deb'), 1000);

insert into rhnServerPackageArchCompat
 (server_arch_id, package_arch_id, preference) values
 (LOOKUP_SERVER_ARCH('alpha-debian-linux'), LOOKUP_PACKAGE_ARCH('alpha-deb'), 0);
insert into rhnServerPackageArchCompat
 (server_arch_id, package_arch_id, preference) values
 (LOOKUP_SERVER_ARCH('alpha-debian-linux'), LOOKUP_PACKAGE_ARCH('all-deb'), 1000);

insert into rhnServerPackageArchCompat
 (server_arch_id, package_arch_id, preference) values
 (LOOKUP_SERVER_ARCH('ia64-debian-linux'), LOOKUP_PACKAGE_ARCH('ia64-deb'), 0);
insert into rhnServerPackageArchCompat
 (server_arch_id, package_arch_id, preference) values
 (LOOKUP_SERVER_ARCH('ia64-debian-linux'), LOOKUP_PACKAGE_ARCH('i386-deb'), 100);
insert into rhnServerPackageArchCompat
 (server_arch_id, package_arch_id, preference) values
 (LOOKUP_SERVER_ARCH('ia64-debian-linux'), LOOKUP_PACKAGE_ARCH('all-deb'), 1000);

insert into rhnServerPackageArchCompat
 (server_arch_id, package_arch_id, preference) values
 (LOOKUP_SERVER_ARCH('sparc-debian-linux'), LOOKUP_PACKAGE_ARCH('sparc-deb'), 0);
insert into rhnServerPackageArchCompat
 (server_arch_id, package_arch_id, preference) values
 (LOOKUP_SERVER_ARCH('sparc-debian-linux'), LOOKUP_PACKAGE_ARCH('all-deb'), 1000);

insert into rhnServerPackageArchCompat
 (server_arch_id, package_arch_id, preference) values
 (LOOKUP_SERVER_ARCH('s390-debian-linux'), LOOKUP_PACKAGE_ARCH('s390-deb'), 0);
insert into rhnServerPackageArchCompat
 (server_arch_id, package_arch_id, preference) values
 (LOOKUP_SERVER_ARCH('s390-debian-linux'), LOOKUP_PACKAGE_ARCH('all-deb'), 1000);

insert into rhnServerPackageArchCompat
 (server_arch_id, package_arch_id, preference) values
 (LOOKUP_SERVER_ARCH('powerpc-debian-linux'), LOOKUP_PACKAGE_ARCH('powerpc-deb'), 0);
insert into rhnServerPackageArchCompat
 (server_arch_id, package_arch_id, preference) values
 (LOOKUP_SERVER_ARCH('powerpc-debian-linux'), LOOKUP_PACKAGE_ARCH('all-deb'), 1000);

insert into rhnServerPackageArchCompat
 (server_arch_id, package_arch_id, preference) values
 (LOOKUP_SERVER_ARCH('arm-debian-linux'), LOOKUP_PACKAGE_ARCH('arm-deb'), 0);
insert into rhnServerPackageArchCompat
 (server_arch_id, package_arch_id, preference) values
 (LOOKUP_SERVER_ARCH('arm-debian-linux'), LOOKUP_PACKAGE_ARCH('all-deb'), 1000);

insert into rhnServerPackageArchCompat
 (server_arch_id, package_arch_id, preference) values
 (LOOKUP_SERVER_ARCH('mips-debian-linux'), LOOKUP_PACKAGE_ARCH('mips-deb'), 0);
insert into rhnServerPackageArchCompat
 (server_arch_id, package_arch_id, preference) values
 (LOOKUP_SERVER_ARCH('mips-debian-linux'), LOOKUP_PACKAGE_ARCH('all-deb'), 1000);

insert into rhnServerPackageArchCompat
 (server_arch_id, package_arch_id, preference) values
 (LOOKUP_SERVER_ARCH('amd64-debian-linux'), LOOKUP_PACKAGE_ARCH('amd64-deb'), 0);
insert into rhnServerPackageArchCompat
 (server_arch_id, package_arch_id, preference) values
 (LOOKUP_SERVER_ARCH('amd64-debian-linux'), LOOKUP_PACKAGE_ARCH('i386-deb'), 140);
insert into rhnServerPackageArchCompat
 (server_arch_id, package_arch_id, preference) values
 (LOOKUP_SERVER_ARCH('amd64-debian-linux'), LOOKUP_PACKAGE_ARCH('all-deb'), 1000);

commit;

insert into rhnServerChannelArchCompat (server_arch_id, channel_arch_id) values
(LOOKUP_SERVER_ARCH('i386-debian-linux'), LOOKUP_CHANNEL_ARCH('channel-ia32-deb'));

insert into rhnServerChannelArchCompat (server_arch_id, channel_arch_id) values
(LOOKUP_SERVER_ARCH('alpha-debian-linux'), LOOKUP_CHANNEL_ARCH('channel-alpha-deb'));

insert into rhnServerChannelArchCompat (server_arch_id, channel_arch_id) values
(LOOKUP_SERVER_ARCH('ia64-debian-linux'), LOOKUP_CHANNEL_ARCH('channel-ia64-deb'));

insert into rhnServerChannelArchCompat (server_arch_id, channel_arch_id) values
(LOOKUP_SERVER_ARCH('sparc-debian-linux'), LOOKUP_CHANNEL_ARCH('channel-sparc-deb'));

insert into rhnServerChannelArchCompat (server_arch_id, channel_arch_id) values
(LOOKUP_SERVER_ARCH('s390-debian-linux'), LOOKUP_CHANNEL_ARCH('channel-s390-deb'));

insert into rhnServerChannelArchCompat (server_arch_id, channel_arch_id) values
(LOOKUP_SERVER_ARCH('powerpc-debian-linux'), LOOKUP_CHANNEL_ARCH('channel-powerpc-deb'));

insert into rhnServerChannelArchCompat (server_arch_id, channel_arch_id) values
(LOOKUP_SERVER_ARCH('amd64-debian-linux'), LOOKUP_CHANNEL_ARCH('channel-amd64-deb'));

insert into rhnServerChannelArchCompat (server_arch_id, channel_arch_id) values
(LOOKUP_SERVER_ARCH('arm-debian-linux'), LOOKUP_CHANNEL_ARCH('channel-arm-deb'));

insert into rhnServerChannelArchCompat (server_arch_id, channel_arch_id) values
(LOOKUP_SERVER_ARCH('mips-debian-linux'), LOOKUP_CHANNEL_ARCH('channel-mips-deb'));

commit;

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('i386-debian-linux'),
            lookup_sg_type('sw_mgr_entitled'));
insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('alpha-debian-linux'),
            lookup_sg_type('sw_mgr_entitled'));
insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('ia64-debian-linux'),
            lookup_sg_type('sw_mgr_entitled'));
insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('sparc-debian-linux'),
            lookup_sg_type('sw_mgr_entitled'));
insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('s390-debian-linux'),
            lookup_sg_type('sw_mgr_entitled'));
insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('powerpc-debian-linux'),
            lookup_sg_type('sw_mgr_entitled'));
insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('amd64-debian-linux'),
            lookup_sg_type('sw_mgr_entitled'));
insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('arm-debian-linux'),
            lookup_sg_type('sw_mgr_entitled'));
insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('mips-debian-linux'),
            lookup_sg_type('sw_mgr_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('i386-debian-linux'),
            lookup_sg_type('enterprise_entitled'));
insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('alpha-debian-linux'),
            lookup_sg_type('enterprise_entitled'));
insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('ia64-debian-linux'),
            lookup_sg_type('enterprise_entitled'));
insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('sparc-debian-linux'),
            lookup_sg_type('enterprise_entitled'));
insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('s390-debian-linux'),
            lookup_sg_type('enterprise_entitled'));
insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('powerpc-debian-linux'),
            lookup_sg_type('enterprise_entitled'));
insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('amd64-debian-linux'),
            lookup_sg_type('enterprise_entitled'));
insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('arm-debian-linux'),
            lookup_sg_type('enterprise_entitled'));
insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('mips-debian-linux'),
            lookup_sg_type('enterprise_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('i386-debian-linux'),
            lookup_sg_type('provisioning_entitled'));
insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('alpha-debian-linux'),
            lookup_sg_type('provisioning_entitled'));
insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('ia64-debian-linux'),
            lookup_sg_type('provisioning_entitled'));
insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('sparc-debian-linux'),
            lookup_sg_type('provisioning_entitled'));
insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('s390-debian-linux'),
            lookup_sg_type('provisioning_entitled'));
insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('powerpc-debian-linux'),
            lookup_sg_type('provisioning_entitled'));
insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('amd64-debian-linux'),
            lookup_sg_type('provisioning_entitled'));
insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('arm-debian-linux'),
            lookup_sg_type('provisioning_entitled'));
insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('mips-debian-linux'),
            lookup_sg_type('provisioning_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('i386-debian-linux'),
            lookup_sg_type('monitoring_entitled'));
insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('alpha-debian-linux'),
            lookup_sg_type('monitoring_entitled'));
insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('ia64-debian-linux'),
            lookup_sg_type('monitoring_entitled'));
insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('sparc-debian-linux'),
            lookup_sg_type('monitoring_entitled'));
insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('s390-debian-linux'),
            lookup_sg_type('monitoring_entitled'));
insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('powerpc-debian-linux'),
            lookup_sg_type('monitoring_entitled'));
insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('amd64-debian-linux'),
            lookup_sg_type('monitoring_entitled'));
insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('arm-debian-linux'),
            lookup_sg_type('monitoring_entitled'));
insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('mips-debian-linux'),
            lookup_sg_type('monitoring_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type)
    values (lookup_server_arch('i386-debian-linux'),
            lookup_sg_type('virtualization_host'));
insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type)
    values (lookup_server_arch('amd64-debian-linux'),
            lookup_sg_type('virtualization_host'));
insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type)
    values (lookup_server_arch('ia64-debian-linux'),
            lookup_sg_type('virtualization_host'));
insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type)
    values (lookup_server_arch('s390-debian-linux'),
            lookup_sg_type('virtualization_host'));
insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type)
    values (lookup_server_arch('powerpc-debian-linux'),
            lookup_sg_type('virtualization_host'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type)
    values (lookup_server_arch('i386-debian-linux'),
            lookup_sg_type('virtualization_host_platform'));
insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type)
    values (lookup_server_arch('amd64-debian-linux'),
            lookup_sg_type('virtualization_host_platform'));
insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type)
    values (lookup_server_arch('ia64-debian-linux'),
            lookup_sg_type('virtualization_host_platform'));

commit;
   0707010000053A000081B400000000000000000000000167AE111400000470000000000000000000000000000000000000006300000000susemanager-schema/upgrade/spacewalk-schema-0.8-to-spacewalk-schema-1.0/002-rhnPackageRepoData.sql    --
-- Copyright (c) 2008--2010 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnPackageRepodata
(
    package_id  NUMBER NOT NULL
                    CONSTRAINT rhnPackageRepodata_pk
                        PRIMARY KEY
                    CONSTRAINT rhn_pkey_rd_pid_fk
                        REFERENCES rhnPackage (id)
                        ON DELETE CASCADE,
    primary     BLOB,
    filelist    BLOB, 
    other       BLOB,
    created     DATE
                    DEFAULT (sysdate) NOT NULL,
    modified    DATE
                    DEFAULT (sysdate) NOT NULL
)
;
0707010000053B000081B400000000000000000000000167AE11140000019A000000000000000000000000000000000000006300000000susemanager-schema/upgrade/spacewalk-schema-0.8-to-spacewalk-schema-1.0/003-rhnChecksum-unique.sql    declare
  index_not_exists exception;
  pragma exception_init(index_not_exists, -01418);
begin
  execute immediate 'drop index rhnChecksum_chsum_idx';
  execute immediate 'alter table rhnChecksum add constraint rhnChecksum_chsum_uq
          unique (checksum, checksum_type_id)
          using index tablespace [[32m_tbs]]';
exception
  when index_not_exists then
    null; -- index was already dropped
end;
/
  0707010000053C000081B400000000000000000000000167AE1114000000F4000000000000000000000000000000000000006500000000susemanager-schema/upgrade/spacewalk-schema-0.8-to-spacewalk-schema-1.0/003-rhnReleaseChannelMap.sql  alter table rhnReleaseChannelMap add CONSTRAINT rhn_rcm_cid_fk  FOREIGN KEY (channel_id) REFERENCES rhnChannel (id);
alter table rhnReleaseChannelMap add CONSTRAINT rhn_rcm_caid_fk  FOREIGN KEY (channel_arch_id) REFERENCES rhnChannelArch (id);
0707010000053D000081B400000000000000000000000167AE11140000012E000000000000000000000000000000000000006900000000susemanager-schema/upgrade/spacewalk-schema-0.8-to-spacewalk-schema-1.0/004-rhnPackageKey-drop-index.sql  alter table rhnPackageKeyAssociation disable constraint rhn_pkeya_kid_fk;
alter table rhnPackageKey disable constraint rhn_pkey_id_pk;
drop index rhn_pkey_id_k_pid_idx;
alter table rhnPackageKey enable constraint rhn_pkey_id_pk;
alter table rhnPackageKeyAssociation enable constraint rhn_pkeya_kid_fk;
  0707010000053E000081B400000000000000000000000167AE1114000000FB000000000000000000000000000000000000006A00000000susemanager-schema/upgrade/spacewalk-schema-0.8-to-spacewalk-schema-1.0/005-1-rhnPackageProvider-data.sql -- Spacewalk
merge into rhnPackageProvider p
     using (select 'Spacewalk' name from dual) s
        on (p.name = s.name)
      WHEN NOT MATCHED THEN INSERT (id, name)
                            VALUES (rhn_package_provider_id_seq.nextval, s.name);
 0707010000053F000081B400000000000000000000000167AE11140000048E000000000000000000000000000000000000006500000000susemanager-schema/upgrade/spacewalk-schema-0.8-to-spacewalk-schema-1.0/005-2-rhnPackageKey-data.sql  -- Fedora 12
merge into rhnpackagekey k
     using (select '9d1cc34857bbccba' key_id,
                   lookup_package_key_type('gpg') key_type_id,
                   lookup_package_provider('Fedora') provider_id
              from dual) s
        on (k.key_id = s.key_id)
      WHEN MATCHED THEN UPDATE SET k.key_type_id = s.key_type_id,
                                   k.provider_id = s.provider_id
      WHEN NOT MATCHED THEN INSERT (id, key_id, key_type_id, provider_id)
                            VALUES (rhn_pkey_id_seq.nextval, s.key_id, s.key_type_id, s.provider_id);

-- Spacewalk
merge into rhnpackagekey k
     using (select '95423d4e430a1c35' key_id,
                   lookup_package_key_type('gpg') key_type_id,
                   lookup_package_provider('Spacewalk') provider_id
              from dual) s
        on (k.key_id = s.key_id)
      WHEN MATCHED THEN UPDATE SET k.key_type_id = s.key_type_id,
                                   k.provider_id = s.provider_id
      WHEN NOT MATCHED THEN INSERT (id, key_id, key_type_id, provider_id)
                            VALUES (rhn_pkey_id_seq.nextval, s.key_id, s.key_type_id, s.provider_id);
  07070100000540000081B400000000000000000000000167AE1114000002D9000000000000000000000000000000000000006100000000susemanager-schema/upgrade/spacewalk-schema-0.8-to-spacewalk-schema-1.0/006-rhnKSInstallType.sql  
insert into rhnKSInstallType (id, label, name) values (rhn_ksinstalltype_id_seq.nextval, 'fedora', 'Fedora');

-- 650129: we need to disable the trigger to prevent it from automatically
-- updating rhnKickstartableTree.last_modified values
alter trigger rhn_kstree_mod_trig disable;

update rhnKickstartableTree K set K.INSTALL_TYPE = (select id from rhnKSInstallType where label = 'fedora') where K.INSTALL_TYPE in (select id from rhnKSInstallType where label like '%fedora%');

-- we need to enable the trigger again
alter trigger rhn_kstree_mod_trig enable;

delete from rhnKSInstallType where label = 'fedora_8';
delete from rhnKSInstallType where label = 'fedora_9';
delete from rhnKSInstallType where label = 'fedora_10';
   07070100000541000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000004800000000susemanager-schema/upgrade/spacewalk-schema-1.0-to-spacewalk-schema-1.1   07070100000542000081B400000000000000000000000167AE1114000009F4000000000000000000000000000000000000005A00000000susemanager-schema/upgrade/spacewalk-schema-1.0-to-spacewalk-schema-1.1/001-repo-sync.sql 
ALTER table rhnChannelContentSource rename to rhnContentSource;

-- remove unique index; prepare for rhnChannelContentSource uq
drop index rhn_ccs_uq;
create unique index rhn_cs_uq
	on rhnContentSource(id, type_id, source_url)
	tablespace [[64k_tbs]]
  ;
-- rename constraints
ALTER TABLE rhnContentSource
    RENAME CONSTRAINT rhn_ccs_type_fk to rhn_cs_type_fk;
ALTER TABLE rhnContentSource
    RENAME CONSTRAINT rhn_ccs_id_pk to rhn_cs_id_pk;
alter index rhn_ccs_id_pk rename to rhn_cs_id_pk;

-- create new table for mapping channels and repos
CREATE TABLE rhnChannelContentSource
(
    source_id     NUMBER NOT NULL
                         CONSTRAINT rhn_ccs_src_id_fk
                             REFERENCES rhnContentSource (id)
                             ON DELETE CASCADE,
    channel_id    NUMBER NOT NULL
                         CONSTRAINT rhn_ccs_cid_fk
                             REFERENCES rhnChannel (id)
                             ON DELETE CASCADE,
    created          DATE
                         DEFAULT (sysdate) NOT NULL,
    modified         DATE
                         DEFAULT (sysdate) NOT NULL
)
ENABLE ROW MOVEMENT
;

-- add the contraints
ALTER TABLE rhnChannelContentSource
    ADD CONSTRAINT rhn_ccs_uq UNIQUE (source_id, channel_id)
    USING INDEX TABLESPACE [[4m_tbs]];

ALTER TABLE rhnContentSource
    ADD org_id number
        CONSTRAINT rhn_cs_org_fk
        REFERENCES WEB_CUSTOMER(id);
-- add sync column to rhnChannel
ALTER TABLE rhnChannel
    ADD last_synced date;

DECLARE
  -- grab any rows that need the channel to be migrated to new channel content mapping tbl
  CURSOR content is
    select cs.id, cs.channel_id, cs.last_synced, c.org_id
    from rhnContentSource cs, rhnChannel c
    where 1=1
    AND c.id = cs.channel_id;
BEGIN
  FOR content_rec IN content
  LOOP
      -- add mapping
      INSERT INTO rhnChannelContentSource (source_id, channel_id)
             VALUES (content_rec.id, content_rec.channel_id);

      -- save org id
      UPDATE rhnContentSource set org_id = content_rec.org_id
      WHERE 1=1
      AND channel_id = content_rec.channel_id;

      -- migrate sync date to channel
      UPDATE rhnChannel set last_synced = content_rec.last_synced
      WHERE id = content_rec.channel_id;

  END LOOP;
  commit;
END;
/

-- we don't need the channel_id column anymore since mapping table will handle it
ALTER TABLE rhnContentSource DROP (channel_id);
-- remove last_synced since rhnChannel will now take care of this data
ALTER TABLE rhnContentSource DROP (last_synced);
07070100000543000081B400000000000000000000000167AE111400000E16000000000000000000000000000000000000006400000000susemanager-schema/upgrade/spacewalk-schema-1.0-to-spacewalk-schema-1.1/002-rhnServerNeededView.sql   --
-- Copyright (c) 2008--2010 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--


-- A view that displays an uncached version of rhnServerNeededCache

CREATE OR REPLACE VIEW
rhnServerNeededView
(
    org_id,
    server_id,
    errata_id,
    package_id,
    package_name_id,
    channel_id
)
AS
SELECT DISTINCT S.org_id,
     S.id as server_id,
     ep.errata_id as errata_id,
     P.id as package_id,
     P.name_id as package_name_id,
     CP.channel_id as channel_id
FROM
    rhnPackage P
    inner join rhnPackageEVR P_EVR on P_EVR.id = P.evr_id
    inner join rhnPackageEVR SP_EVR on SP_EVR.evr < P_EVR.evr  
    inner join rhnServerPackage SP on SP.name_id = P.name_id 
               and SP.evr_id = SP_EVR.id
               AND SP.evr_id != P.evr_id
    inner join rhnServer S on SP.server_id = S.id
    inner join rhnServerPackageArchCompat SPAC on spac.server_arch_id = s.server_arch_id 
               AND p.package_arch_id = spac.package_arch_id
    inner join rhnServerChannel SC on SC.server_id = S.id 
    inner join rhnChannelPackage CP on CP.package_id = P.id 
               and SC.channel_id = CP.channel_id
    left outer join rhnErrataPackage EP on EP.package_id = P.id
                   AND EXISTS 
                   (SELECT 1 from rhnChannelErrata CE where ce.channel_id = SC.channel_id
                    AND CE.errata_id = EP.errata_id) 
    where
           --- If the channel has more than 1 package with the same NVRE but different arches
           ---  Then we need to add an additional join condition (the server's package arch id) 
           P.package_arch_id = NVL2(
                                   (select distinct 1
                                       from rhnPackage P2 inner join rhnChannelPackage CP2
                                            on P2.id = CP2.package_id
                                         where CP2.channel_id = SC.channel_id and
                                               P2.id = CP2.package_id and
                                               P2.name_id = P.name_id
                                          group by P2.evr_id having count(*) > 1),
                                    NVL(SP.package_arch_id, P.package_arch_id),
                                    P.package_arch_id
                               )
           AND
           ---  If we can use arch to find the MAX EVR, use that 
           ---  Otherwise just use whatever they have 
           SP_EVR.evr =
                  NVL(
                     (SELECT MAX(PE.evr) FROM rhnServerPackage SP2, rhnPackageEvr PE
                       WHERE PE.id = SP2.evr_id AND SP2.server_id = SP.server_id AND
                         SP2.name_id = SP.name_id
                         AND NVL(SP2.package_arch_id, P.package_arch_id) = P.package_arch_id
                     ),
                     (SELECT MAX(PE.evr) FROM rhnServerPackage SP2, rhnPackageEvr PE
                       WHERE PE.id = SP2.evr_id AND SP2.server_id = SP.server_id AND
                      SP2.name_id = SP.name_id)
                    )
/
  07070100000544000081B400000000000000000000000167AE111400000103000000000000000000000000000000000000006800000000susemanager-schema/upgrade/spacewalk-schema-1.0-to-spacewalk-schema-1.1/003-rhnPrivateChannelFamily.sql   
alter trigger rhn_privcf_mod_trig disable;
alter table rhnPrivateChannelFamily add FVE_MAX_MEMBERS NUMBER default (0);
alter table rhnPrivateChannelFamily add FVE_CURRENT_MEMBERS NUMBER
        DEFAULT (0) NOT NULL;
alter trigger rhn_privcf_mod_trig enable;
 07070100000545000081B400000000000000000000000167AE11140000011E000000000000000000000000000000000000006100000000susemanager-schema/upgrade/spacewalk-schema-1.0-to-spacewalk-schema-1.1/004-rhnServerChannel.sql  
alter trigger rhn_server_channel_mod_trig disable;
alter TABLE rhnServerChannel add is_fve  char default 'N' 
   CONSTRAINT rhn_server_channel_is_fve_nn NOT NULL
   CONSTRAINT rhn_server_channel_is_fve_ck CHECK (IS_FVE IN ('Y', 'N'));
alter trigger rhn_server_channel_mod_trig enable;
  07070100000546000081B400000000000000000000000167AE111400000436000000000000000000000000000000000000006700000000susemanager-schema/upgrade/spacewalk-schema-1.0-to-spacewalk-schema-1.1/005-rhnVirtualInstanceType.sql    --
-- Copyright (c) 2010 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--

INSERT INTO rhnVirtualInstanceType (ID, NAME, LABEL) values (rhn_vit_id_seq.nextval, 'KVM/QEMU', 'qemu');

insert into rhnVirtualInstanceType (id, name, label) 
    values (rhn_vit_id_seq.nextval, 'VMware', 'vmware');

insert into rhnVirtualInstanceType (id, name, label)
    values (rhn_vit_id_seq.nextval, 'Hyper-V', 'hyperv');

insert into rhnVirtualInstanceType (id, name, label)
    values (rhn_vit_id_seq.nextval, 'Virtage', 'virtage');


  07070100000547000081B400000000000000000000000167AE111400000587000000000000000000000000000000000000006900000000susemanager-schema/upgrade/spacewalk-schema-1.0-to-spacewalk-schema-1.1/006-rhnChannelFamilyOverview.sql  --
-- Copyright (c) 2008--2010 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--

-- semantics of this view are much different from what the old
-- documentation said, and were before I rewrote it.  The critical
-- change was the "where exists" clause, which means we can never
-- not have any permissions if we show up here.

-- That makes it not so special any more.

create or replace view rhnChannelFamilyOverview as
select	pcf.org_id				as org_id,
	f.id					as id,
	f.name					as name,
	f.product_url				as url,
	f.label					as label,
	coalesce(pcf.current_members,0)		as current_members,
	pcf.max_members				as max_members,
	coalesce(pcf.fve_current_members,0)		as fve_current_members,
	pcf.fve_max_members				as fve_max_members,
	1					as has_subscription
from	rhnChannelFamily			f,
	rhnPrivateChannelFamily			pcf
where	pcf.channel_family_id = f.id;

 07070100000548000081B400000000000000000000000167AE1114000005E2000000000000000000000000000000000000006F00000000susemanager-schema/upgrade/spacewalk-schema-1.0-to-spacewalk-schema-1.1/007-rhnOrgChannelFamilyPermissions.sql    --
-- Copyright (c) 2008--2010 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--

create or replace view rhnOrgChannelFamilyPermissions as
	select	pcf.channel_family_id,
		u.org_id org_id,
		to_number(null) max_members,
		0 current_members,
		to_number(null) fve_max_members,
		0 fve_current_members,
		pcf.created,
		pcf.modified
	from	rhnPublicChannelFamily pcf,
		web_contact u
	union
	select	channel_family_id,
		org_id,
		max_members,
		current_members,
		fve_max_members,
		fve_current_members,
		created,
		modified
	from	rhnPrivateChannelFamily;

--
--
-- Revision 1.2  2004/04/16 16:07:12  pjones
-- bugzilla: none -- 8.1.7 won't let you use "null foo" as a column in a view
-- that gets unioned with a typed column.  you have to use "to_number(null) foo".  What a load of crap.
--
-- Revision 1.1  2004/04/14 00:09:24  pjones
-- bugzilla: 120761 -- split rhnChannelPermissions into two tables, eliminating
-- a frequent full table scan
--
  07070100000549000081B400000000000000000000000167AE111400000806000000000000000000000000000000000000006F00000000susemanager-schema/upgrade/spacewalk-schema-1.0-to-spacewalk-schema-1.1/008-rhnChannelFamilyServerPhysical.sql    --
-- Copyright (c) 2008--2013 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--

create or replace view rhnChannelFamilyServerPhysical as
	select	rs.org_id			as customer_id,
		rcfm.channel_family_id		as channel_family_id,
		rsc.server_id			as server_id,
		rsc.created			as created,
		rsc.modified			as modified
	from	rhnChannelFamilyMembers		rcfm,
		rhnServerChannel		rsc,
		rhnServer			rs
	where
		rcfm.channel_id = rsc.channel_id
		and rsc.server_id = rs.id
         and rsc.is_fve = 'N'
        and not exists (
                select 1
                from 
                    rhnChannelFamilyVirtSubLevel cfvsl, 
                    rhnSGTypeVirtSubLevel sgtvsl,
                    rhnServerEntitlementView sev,
                    rhnVirtualInstance vi
                where 
                    -- system is a virtual instance
                    vi.virtual_system_id = rs.id
                    and vi.host_system_id = sev.server_id
                    -- system's host has a virt ent
                    and sev.label in ('virtualization_host',
                                      'virtualization_host_platform')
                    and sev.server_group_type_id = sgtvsl.server_group_type_id
                    -- the host's virt ent grants a cf virt sub level
                    and sgtvsl.virt_sub_level_id = cfvsl.virt_sub_level_id
                    -- the cf is in that virt sub level
                    and cfvsl.channel_family_id = rcfm.channel_family_id
                );

  0707010000054A000081B400000000000000000000000167AE11140000082F000000000000000000000000000000000000006E00000000susemanager-schema/upgrade/spacewalk-schema-1.0-to-spacewalk-schema-1.1/009-rhnChannelFamilyServerVirtual.sql --
-- Copyright (c) 2008--2013 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--

create or replace view rhnChannelFamilyServerVirtual as
	select	rs.org_id			as customer_id,
		rcfm.channel_family_id		as channel_family_id,
		rsc.server_id			as server_id,
		rsc.created			as created,
		rsc.modified			as modified
	from	rhnChannelFamilyMembers		rcfm,
		rhnChannelFamily		rcf,
		rhnServerChannel		rsc,
		rhnServer			rs
	where
		rcfm.channel_id = rsc.channel_id
		and rcfm.channel_family_id = rcf.id
		and rsc.server_id = rs.id
        and rsc.is_fve = 'N'
        and exists (
                select 1
                from 
                    rhnChannelFamilyVirtSubLevel cfvsl, 
                    rhnSGTypeVirtSubLevel sgtvsl,
                    rhnServerEntitlementView sev,
                    rhnVirtualInstance vi
                where 
                    -- system is a virtual instance
                    vi.virtual_system_id = rs.id
                    and vi.host_system_id = sev.server_id
                    -- system's host has a virt ent
                    and sev.label in ('virtualization_host',
                                      'virtualization_host_platform')
                    and sev.server_group_type_id = sgtvsl.server_group_type_id
                    -- the host's virt ent grants a cf virt sub level
                    and sgtvsl.virt_sub_level_id = cfvsl.virt_sub_level_id
                    -- the cf is in that virt sub level
                    and cfvsl.channel_family_id = rcf.id
                );

 0707010000054B000081B400000000000000000000000167AE11140000043D000000000000000000000000000000000000006A00000000susemanager-schema/upgrade/spacewalk-schema-1.0-to-spacewalk-schema-1.1/010-rhnChannelFamilyServerFve.sql --
-- Copyright (c) 2008--2010 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--

create or replace view rhnChannelFamilyServerFve as
	select	rs.org_id			customer_id,
		rcfm.channel_family_id	channel_family_id,
		rsc.server_id			server_id,
		rsc.created			created,
		rsc.modified			modified
	from	rhnChannelFamilyMembers		rcfm,
		rhnChannelFamily		rcf,
		rhnServerChannel		rsc,
		rhnServer			rs
	where
		rcfm.channel_id = rsc.channel_id
		and rcfm.channel_family_id = rcf.id
		and rsc.server_id = rs.id
		and rsc.is_fve = 'Y';

   0707010000054C000081B400000000000000000000000167AE111400000480000000000000000000000000000000000000006C00000000susemanager-schema/upgrade/spacewalk-schema-1.0-to-spacewalk-schema-1.1/011-rhnChannelFamilyPermissions.sql   --
-- Copyright (c) 2008--2010 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--

create or replace view rhnChannelFamilyPermissions as
	select	channel_family_id,
		to_number(null, null) as org_id,
		to_number(null, null) as max_members,
		0 as current_members,
                0 as fve_max_members,
                0 as fve_current_members,
		created,
		modified
	from	rhnPublicChannelFamily
	union
	select	channel_family_id,
		org_id,
		max_members,
		current_members,
                fve_max_members,
                fve_current_members,
		created,
		modified
	from	rhnPrivateChannelFamily;

0707010000054D000081B400000000000000000000000167AE11140000043A000000000000000000000000000000000000006200000000susemanager-schema/upgrade/spacewalk-schema-1.0-to-spacewalk-schema-1.1/012-rhnException_data.sql --
-- Copyright (c) 2008--2010 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--
-- data for rhnException

insert into rhnException values (-20294, 'not_enough_flex_entitlements_in_base_org', 'You do not have enough entitlements in the base org.');
insert into rhnException values (-20295, 'server_cannot_convert_to_flex', 'The given server cannot be converted to a flex entitlement.');

insert into rhnException values (-20296, 'not_enough_flex_entitlements', 'You do not have enough entitlements in your org..');
commit;


  0707010000054E000081B400000000000000000000000167AE111400002D6B000000000000000000000000000000000000005E00000000susemanager-schema/upgrade/spacewalk-schema-1.0-to-spacewalk-schema-1.1/013-delete_server.sql --
-- Copyright (c) 2008--2010 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
-- This deletes a server.  All codepaths which delete servers should hit this
-- or delete_server_bulk()

create or replace
procedure delete_server (
	server_id_in in number
) is
	cursor servergroups is
		select	server_id, server_group_id
		from	rhnServerGroupMembers sgm
		where	sgm.server_id = server_id_in;
	cursor configchannels is
		select	cc.id
		from	rhnConfigChannel cc,
			rhnConfigChannelType cct,
			rhnServerConfigChannel scc
		where	1=1
			and scc.server_id = server_id_in
			and scc.config_channel_id = cc.id
			-- these config channel types are reserved
			-- for use by a single server, so we don't
			-- need to check for other servers subscribed
			and cct.label in
				('local_override','server_import')
			and cct.id = cc.confchan_type_id;
        type filelistsid_t is table of rhnServerPreserveFileList.file_list_id%type;
        filelistsid_c filelistsid_t;

        type probesid_t is table of rhn_check_probe.probe_id%type;
        probesid_c probesid_t;

    is_virt number := 0;
begin
	rhn_channel.delete_server_channels(server_id_in);
	-- rhn_channel.clear_subscriptions(server_id_in);

        -- filelists
	select	spfl.file_list_id id bulk collect into filelistsid_c
	  from	rhnServerPreserveFileList spfl
	 where	spfl.server_id = server_id_in
			and not exists (
				select	1
				from	rhnServerPreserveFileList
				where	file_list_id = spfl.file_list_id
					and server_id != server_id_in
				union
				select	1
				from	rhnKickstartPreserveFileList
				where	file_list_id = spfl.file_list_id
			);
        if filelistsid_c.first is not null then
            forall i in filelistsid_c.first..filelistsid_c.last
                delete from rhnFileList where id = filelistsid_c(i);
        end if;

	for configchannel in configchannels loop
		rhn_config.delete_channel(configchannel.id);
	end loop;

      select count(1) into is_virt
        from rhnServerEntitlementView
       where server_id = server_id_in
         and label in ('virtualization_host', 'virtualization_host_platform')
         and rownum <= 1;

	for sgm in servergroups loop
		rhn_server.delete_from_servergroup(
			sgm.server_id, sgm.server_group_id);
	end loop;

    if is_virt = 1 then
        rhn_entitlements.repoll_virt_guest_entitlements(server_id_in);
    end if;

	-- we're handling this instead of letting an "on delete
	-- set null" do it so that we don't run the risk
	-- of setting off the triggers and killing us with a
	-- mutating table

	-- this is merge of two single updates:
        --  update ... set old_server_id = null where old_server_id = server_id_in;
        --  update ... set new_server_id = null where new_server_id = server_id_in;
        -- so we scan rhnKickstartSession table only once
	update rhnKickstartSession
		set old_server_id = case when old_server_id = server_id_in then null else old_server_id end,
		    new_server_id = case when new_server_id = server_id_in then null else new_server_id end
		where old_server_id = server_id_in 
		   or new_server_id = server_id_in;

	rhn_channel.clear_subscriptions(server_id_in,1);

    	-- A little complicated here, but the goal is to
	-- delete records from rhnVirtualInstace only if we don't
	-- care about them anymore.  We don't care about records
	-- in rhnVirtualInstance if we are deleting the host
	-- system and the virtual system is already null, or
	-- vice-versa.  We *do* care about them if either the
	-- host or virtual system is still registered because we
	-- still want them to show up in the UI.
    -- If there's a newer row in rhnVirtualInstance with the same
    -- uuid, this guest must have been re-registered, so we can clean
    -- this data up.
				
        delete from rhnVirtualInstance vi
	      where (host_system_id = server_id_in and virtual_system_id is null)
                 or (virtual_system_id = server_id_in and host_system_id is null)
                 or (vi.virtual_system_id = server_id_in and vi.modified < (select max(vi2.modified)
                    from rhnVirtualInstance vi2 where vi2.uuid = vi.uuid));
						
        -- this is merge of two single updates:
        --  update ... set host_system_id = null where host_system_id = server_id_in;
        --  update ... set virtual_system_id = null where virtual_system_id = server_id_in;
        -- so we scan rhnVirtualInstance table only once
        update rhnVirtualInstance
	   set host_system_id = case when host_system_id = server_id_in then null else host_system_id end,
	       virtual_system_id = case when virtual_system_id = server_id_in then null else virtual_system_id end
	 where host_system_id = server_id_in
	    or virtual_system_id = server_id_in;
		
        -- this is merge of two single updates:
        --  update ... set old_host_system_id = null when old_host_system_id = server_id_in;
        --  update ... set new_host_system_id = null when new_host_system_id = server_id_in;
        -- so we scan rhnVirtualInstanceEventLog table only once
	update rhnVirtualInstanceEventLog
	   set old_host_system_id = case when old_host_system_id = server_id_in then null else old_host_system_id end,
               new_host_system_id = case when new_host_system_id = server_id_in then null else new_host_system_id end
         where old_host_system_id = server_id_in
            or new_host_system_id = server_id_in;
		 
	-- We're deleting everything with a foreign key to rhnServer
	-- here, now.  I'm hoping this will help aleviate our deadlock
	-- problem.

	delete from rhnActionConfigChannel where server_id = server_id_in;
	delete from rhnActionConfigRevision where server_id = server_id_in;
	delete from rhnActionPackageRemovalFailure where server_id = server_id_in;
	delete from rhnClientCapability where server_id = server_id_in;
	delete from rhnCpu where server_id = server_id_in;
	-- there's still a cascade here, because the constraint keeps the
	-- table locked for too long to rebuild it.  Ugh...
	delete from rhnDevice where server_id = server_id_in;
	delete from rhnProxyInfo where server_id = server_id_in;
	delete from rhnRam where server_id = server_id_in;
	delete from rhnRegToken where server_id = server_id_in;
	delete from rhnSNPServerQueue where server_id = server_id_in;
	delete from rhnSatelliteChannelFamily where server_id = server_id_in;
	delete from rhnSatelliteInfo where server_id = server_id_in;
	-- this cascades to rhnActionConfigChannel and rhnActionConfigFileName
	delete from rhnServerAction where server_id = server_id_in;
	delete from rhnServerActionPackageResult where server_id = server_id_in;
	delete from rhnServerActionScriptResult where server_id = server_id_in;
	delete from rhnServerActionVerifyResult where server_id = server_id_in;
	delete from rhnServerActionVerifyMissing where server_id = server_id_in;
	-- counts are handled above.  this should be a delete_ function.
	delete from rhnServerChannel where server_id = server_id_in;
	delete from rhnServerConfigChannel where server_id = server_id_in;
	delete from rhnServerCustomDataValue where server_id = server_id_in;
	delete from rhnServerDMI where server_id = server_id_in;
	delete from rhnServerMessage where server_id = server_id_in;
	-- this gets rhnServerMessage (only) on cascade; it's handled just above
	delete from rhnServerEvent where server_id = server_id_in;
	delete from rhnServerHistory where server_id = server_id_in;
	delete from rhnServerInfo where server_id = server_id_in;
	delete from rhnServerInstallInfo where server_id = server_id_in;
	delete from rhnServerLocation where server_id = server_id_in;
	delete from rhnServerLock where server_id = server_id_in;
	delete from rhnServerNeededCache where server_id = server_id_in;
	delete from rhnServerNetwork where server_id = server_id_in;
	delete from rhnServerNotes where server_id = server_id_in;
	-- I'm not removing the foreign key from rhnServerPackage; that'll
	-- take forever.  Do the delete anyway.
	delete from rhnServerPackage where server_id = server_id_in;
	delete from rhnServerTokenRegs where server_id = server_id_in;
	delete from rhnSnapshotTag where server_id = server_id_in;
	-- this cascades to:
	--   rhnSnapshotChannel, rhnSnapshotConfigChannel, rhnSnapshotPackage, 
	--   rhnSnapshotConfigRevision, rhnSnapshotServerGroup, 
	--   rhnSnapshotTag.
	-- We may want to consider delete_snapshot() at some point, but
	--   I don't think we need to yet.
	delete from rhnSnapshot where server_id = server_id_in;
	delete from rhnTransaction where server_id = server_id_in;
	delete from rhnUserServerPrefs where server_id = server_id_in;
	-- hrm, this one's interesting... we _probably_ should delete
	-- everything for the parent server_id when we delete the proxy,
	-- but we don't currently.
	delete from rhnServerPath where server_id_in in (server_id, proxy_server_id);
	delete from rhnUserServerPerms where server_id = server_id_in;

	delete from rhn_interface_monitoring where server_id = server_id_in;
	delete from rhnServerNetInterface where server_id = server_id_in;
	delete from rhn_server_monitoring_info where recid = server_id_in;

	delete from rhnAppInstallSession where server_id = server_id_in;
	delete from rhnServerUuid where server_id = server_id_in;
    -- We delete all the probes running directly against this system
    -- and any probes that were using this Server as a Proxy Scout.
     SELECT CP.probe_id bulk collect into probesid_c
       FROM rhn_check_probe CP  
      WHERE CP.host_id = server_id_in
         OR CP.sat_cluster_id in
    (SELECT SN.sat_cluster_id
       FROM rhn_sat_node SN
      WHERE SN.server_id = server_id_in);

    if probesid_c.first is not null then
        FORALL i IN probesid_c.first..probesid_c.last
            DELETE FROM rhn_probe_state PS WHERE PS.probe_id = probesid_c(i);
        FORALL i IN probesid_c.first..probesid_c.last
            DELETE FROM rhn_probe P  WHERE P.recid = probesid_c(i);
        FORALL i IN probesid_c.first..probesid_c.last
            DELETE /*+index(time_series time_series_probe_id_idx)*/
            FROM time_series
            WHERE substr(o_id, instr(o_id, '-') + 1,
                (instr(o_id, '-', instr(o_id, '-') + 1) - instr(o_id, '-'))	- 1) = probesid_c(i);
    end if;

	delete from rhn_check_probe where host_id = server_id_in;
	delete from rhn_host_probe where host_id = server_id_in;

    delete from rhn_sat_cluster where recid in
      ( select sat_cluster_id from rhn_sat_node where server_id = server_id_in );

	delete from rhn_sat_node where server_id = server_id_in;
	
	-- now get rhnServer itself.
	delete
	from	rhnServer
		where id = server_id_in;

	delete
	from	rhnSet
	where	1=1
		and user_id in (
			select	wc.id
			from	rhnServer rs,
				web_contact wc
			where	rs.id = server_id_in
				and rs.org_id = wc.org_id
		)
		and label = 'system_list'
		and element = server_id_in;
end delete_server;
/
show errors;

--
-- Revision 1.25  2004/11/01 17:53:03  pjones
-- bugzilla: 136124 -- Fix the "no data found" when deleting rhn_sat_cluster
--
--
--
--
-- This deletes a list of server. 
--
 0707010000054F000081B400000000000000000000000167AE111400000831000000000000000000000000000000000000006400000000susemanager-schema/upgrade/spacewalk-schema-1.0-to-spacewalk-schema-1.1/013-rhnServerFveCapable.sql   --
-- Copyright (c) 2008--2010 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--
-- A view to list systems that fve capable but that are not actually using
--    and fve entitlement
create or replace view 
rhnServerFveCapable (
 server_id,
 server_org_id,
 channel_family_id,
 current_members,
 max_members,
 channel_family_name
)
as
select  S.id as server_id,
        S.org_id as server_org_id,
        cf.id as channel_family_id,
        pcf.FVE_CURRENT_MEMBERS as current_members,
        pcf.FVE_MAX_MEMBERS as max_members,
        cf.name as channel_family_name
from
     RhnVirtualInstance vi
     inner join rhnServer s on vi.virtual_system_id = s.id
     inner join rhnServerChannel sc on sc.server_id = s.id
     inner join rhnChannelFamilyMembers cfm on cfm.channel_id = sc.channel_id
     inner join rhnChannelFamily cf on cf.id = cfm.channel_family_id
     inner join rhnPrivateChannelFamily pcf on pcf.channel_family_id  = cf.id and pcf.org_id = s.org_id
where sc.is_fve = 'N'
     AND (vi.host_system_id is null OR
     exists (
          select sg.id 
            from rhnServerGroupMembers sgm
                 inner join rhnServerGroup sg on sgm.server_group_id = sg.id
                 inner join rhnServerGroupType sgt on sgt.id = sg.group_type
                 inner join rhnServer s2 on s2.id = sgm.server_id
             where
                 s2.org_id = s.org_id
                 and s2.id = vi.host_system_id
                 and sgt.label not in ('virtualization_host' ,'virtualization_host_platform') )
      );

   07070100000550000081B400000000000000000000000167AE111400002334000000000000000000000000000000000000006000000000susemanager-schema/upgrade/spacewalk-schema-1.0-to-spacewalk-schema-1.1/014-rhn_channel-pks.sql   --
-- Copyright (c) 2008--2010 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--

CREATE OR REPLACE
PACKAGE rhn_channel
IS
	version varchar2(100) := '';

    CURSOR server_base_subscriptions(server_id_in NUMBER) IS
    	   SELECT C.id
	     FROM rhnChannel C, rhnServerChannel SC
	    WHERE C.id = SC.channel_id
	      AND SC.server_id = server_id_in
	      AND C.parent_channel IS NULL;
	      
    CURSOR check_server_subscription(server_id_in NUMBER, channel_id_in NUMBER) IS 
           SELECT channel_id 
	     FROM rhnServerChannel 
	    WHERE server_id = server_id_in 
	      AND channel_id = channel_id_in;

    CURSOR check_server_parent_membership(server_id_in NUMBER, channel_id_in NUMBER) IS
    	   SELECT C.id
	     FROM rhnChannel C, rhnServerChannel SC
	    WHERE C.parent_channel = channel_id_in
	      AND C.id = SC.channel_id
	      AND SC.server_id = server_id_in;
	    
    CURSOR channel_family_perm_cursor(channel_family_id_in NUMBER, org_id_in NUMBER) IS
           SELECT *
	     FROM rhnOrgChannelFamilyPermissions
	    WHERE channel_family_id = channel_family_id_in
	      AND org_id = org_id_in;


    PROCEDURE unsubscribe_server(server_id_in IN NUMBER, channel_id_in NUMBER, immediate_in NUMBER := 1, unsubscribe_children_in number := 0,
                                 deleting_server in number := 0,
                                 update_family_countsYN IN NUMBER := 1);
    PROCEDURE subscribe_server(server_id_in IN NUMBER, channel_id_in NUMBER, immediate_in NUMBER := 1, user_id_in number := null, recalcfamily_in number := 1);
    
    PROCEDURE convert_to_fve(server_id_in IN NUMBER, channel_family_id_val IN NUMBER);

    FUNCTION can_convert_to_fve(server_id_in IN NUMBER, channel_family_id_val IN NUMBER)  RETURN NUMBER;
	
    function can_server_consume_virt_channl(
        server_id_in IN NUMBER,
        family_id_in in number)
    return number;
    FUNCTION can_server_consume_fve( server_id_in IN NUMBER) RETURN NUMBER;

    FUNCTION guess_server_base(server_id_in IN NUMBER) RETURN NUMBER;

    FUNCTION base_channel_for_release_arch(release_in in varchar2, 
	server_arch_in in varchar2, org_id_in in number := -1, 
	user_id_in in number := null) RETURN number;

    FUNCTION base_channel_rel_archid(release_in in varchar2, 
	server_arch_id_in in number, org_id_in in number := -1, 
	user_id_in in number := null) RETURN number;

    FUNCTION channel_priority(channel_id_in in number) RETURN number;
    
    PROCEDURE clear_subscriptions(server_id_in IN NUMBER, deleting_server in number := 0,
                                update_family_countsYN IN NUMBER := 1);
    
    FUNCTION available_family_subscriptions(channel_family_id_in IN NUMBER, org_id_in IN NUMBER) RETURN NUMBER;

    FUNCTION available_fve_family_subs(channel_family_id_in IN NUMBER, org_id_in IN NUMBER) RETURN NUMBER;

    FUNCTION channel_family_current_members(channel_family_id_in IN NUMBER, org_id_in IN NUMBER) return number;

    FUNCTION cfam_curr_fve_members(channel_family_id_in IN NUMBER, org_id_in IN NUMBER) return number;

    PROCEDURE update_family_counts(channel_family_id_in IN NUMBER, org_id_in IN NUMBER);
    PROCEDURE update_group_family_counts(group_label_in IN VARCHAR2, org_id_in IN NUMBER);
    FUNCTION family_for_channel(channel_id_in IN NUMBER) RETURN NUMBER;

    FUNCTION available_chan_subscriptions(channel_id_in IN NUMBER, org_id_in IN NUMBER) RETURN NUMBER;

    FUNCTION available_fve_chan_subs(channel_id_in IN NUMBER, org_id_in IN NUMBER) RETURN NUMBER;

    PROCEDURE unsubscribe_server_from_family(server_id_in in number, channel_family_id_in in number);

    PROCEDURE delete_server_channels(server_id_in in number);

    PROCEDURE refresh_newest_package(channel_id_in in number, caller_in in varchar2 := '(unknown)');

    FUNCTION get_org_id(channel_id_in in number) return number;
    PRAGMA RESTRICT_REFERENCES(get_org_id, WNDS, RNPS, WNPS);

    function get_org_access(channel_id_in in number, org_id_in in number) return number;
    PRAGMA RESTRICT_REFERENCES(get_org_access, WNDS, RNPS, WNPS);
    
    function get_cfam_org_access(cfam_id_in in number, org_id_in in number) return number;

    function user_role_check_debug(channel_id_in in number, user_id_in in number, role_in in varchar2, reason_out out varchar2)
    	RETURN NUMBER;
    PRAGMA RESTRICT_REFERENCES(user_role_check_debug, WNDS, RNPS, WNPS);

    function user_role_check(channel_id_in in number, user_id_in in number, role_in in varchar2)
    	RETURN NUMBER;
    PRAGMA RESTRICT_REFERENCES(user_role_check, WNDS, RNPS, WNPS);
    
    function loose_user_role_check(channel_id_in in number, user_id_in in number, role_in in varchar2)
    	RETURN NUMBER;
    PRAGMA RESTRICT_REFERENCES(loose_user_role_check, WNDS, RNPS, WNPS);

    function direct_user_role_check(channel_id_in in number, user_id_in in number, role_in in varchar2)
    	RETURN NUMBER;
    PRAGMA RESTRICT_REFERENCES(direct_user_role_check, WNDS, RNPS, WNPS);

    function shared_user_role_check(channel_id in number, user_id in number, role in varchar2)
    	RETURN NUMBER;
    PRAGMA RESTRICT_REFERENCES(shared_user_role_check, WNDS, RNPS, WNPS);

    function org_channel_setting(channel_id_in in number, org_id_in in number, setting_in in varchar2)
    	RETURN NUMBER;

    PROCEDURE update_channel ( channel_id_in in number, invalidate_ss in number := 0, 
                               date_to_use in date := sysdate );

    PROCEDURE  update_channels_by_package ( package_id_in in number, date_to_use in date := sysdate );

     PROCEDURE update_channels_by_errata ( errata_id_in number, date_to_use in date := sysdate );


    PRAGMA RESTRICT_REFERENCES(org_channel_setting, WNDS, RNPS, WNPS);

END rhn_channel;
/
SHOW ERRORS

--
-- Revision 1.37  2004/04/14 00:09:24  pjones
-- bugzilla: 120761 -- split rhnChannelPermissions into two tables, eliminating
-- a frequent full table scan
--
-- Revision 1.36  2004/03/26 18:11:32  rbb
-- Bugzilla:  114057
--
-- Add a script to determine channel priority.
--
-- Revision 1.35  2004/02/17 20:16:52  pjones
-- bugzilla: none -- add cvs tags into the package as long as we're touching
-- it anyway
--
-- Revision 1.34  2003/11/13 18:13:09  cturner
-- pragmas can now return now that rhn_user pragmas are fixed
--
-- Revision 1.32  2003/09/22 21:00:40  cturner
-- add method for easy acl check
--
-- Revision 1.31  2003/09/17 22:14:11  misa
-- bugzilla: 103639  Changes to allow me to move the base channel guess into plsql
--
-- Revision 1.30  2003/07/24 16:44:16  misa
-- bugzilla: none  A function more usable on the rhnapp side
--
-- Revision 1.29  2003/07/24 14:00:17  misa
-- bugzilla: none  PRAGMA RESTRICT_REFERENCES good
--
-- Revision 1.28  2003/07/23 21:59:19  cturner
-- rework how rhnUserChannel works; move to plsql for speed and maintenance
--
-- Revision 1.27  2003/07/21 17:49:12  pjones
-- bugzilla: none
--
-- add optional user for subscribe_server
--
-- Revision 1.26  2002/12/19 18:13:42  misa
-- Added caller with a default value
--
-- Revision 1.25  2002/12/11 22:18:46  pjones
-- rhnChannelNewestPackage
--
-- Revision 1.24  2002/11/21 22:08:11  pjones
-- make unsubscribe_channels have a "unsubscribe_children_in number := 0"
-- argument so that you can tell it to unsubscribe children.
--
-- Also, make it raise an exception instead of silent failure in the
-- other case.
--
-- Revision 1.23  2002/11/18 17:20:50  pjones
-- this should have gone back too
--
-- Revision 1.22  2002/11/13 23:16:18  pjones
-- lookup_*_arch()
--
-- Revision 1.21  2002/10/07 20:01:59  rnorwood
-- guess base channel for ssm and single system
--
-- Revision 1.20  2002/10/02 19:21:03  bretm
-- o  3rd party channel schema changes, no more clobs...
--
-- Revision 1.19  2002/09/20 19:21:58  bretm
-- o  more 3rd party channel stuff...
--
-- Revision 1.18  2002/06/12 22:33:03  pjones
-- procedure bulk_guess_server_base_from(
--     set_label_in in varchar2,
--     set_uid_in in number,
--     channel_id_in in number);
--
-- for bretm
--
-- Revision 1.17  2002/06/12 22:12:25  pjones
-- procedure bulk_guess_server_base(
--     set_label_in in varchar2,
--     set_uid_in in number);
--
-- for bretm
--
-- Revision 1.16  2002/06/12 19:37:55  pjones
-- bulk_server_basechange_from(
-- 	set_label_in in varchar2,
-- 	set_uid_in in number,
-- 	old_channel_id_in in number,
-- 	new_channel_id_in in number
-- );
--
-- for bretm
--
-- Revision 1.15  2002/05/10 22:08:22  pjones
-- id/log
--
07070100000551000081B400000000000000000000000167AE11140000C020000000000000000000000000000000000000006000000000susemanager-schema/upgrade/spacewalk-schema-1.0-to-spacewalk-schema-1.1/015-rhn_channel-pkb.sql   --
-- Copyright (c) 2008--2010 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--

CREATE OR REPLACE
PACKAGE BODY rhn_channel
IS
        body_version varchar2(100) := '';

    -- Cursor that fetches all the possible base channels for a
    -- (server_arch_id, release, org_id) combination
        cursor  base_channel_cursor(
                release_in in varchar2,
                server_arch_id_in in number,
                org_id_in in number
        ) return rhnChannel%ROWTYPE is
                select distinct c.*
                from    rhnDistChannelMap                       dcm,
                                rhnServerChannelArchCompat      scac,
                                rhnChannel                                      c,
                                rhnChannelPermissions           cp
                where   cp.org_id = org_id_in
                        and cp.channel_id = c.id
                        and c.parent_channel is null
                        and c.id = dcm.channel_id
                        and c.channel_arch_id = dcm.channel_arch_id
                        and dcm.release = release_in
                        and scac.server_arch_id = server_arch_id_in
                        and scac.channel_arch_id = c.channel_arch_id;

    procedure obtain_read_lock(channel_family_id_in in number, org_id_in in number)
    is
        read_lock date;

    begin
        select created into read_lock
          from rhnPrivateChannelFamily
         where channel_family_id = channel_family_id_in and org_id = org_id_in
           for update;
    end obtain_read_lock;

    PROCEDURE subscribe_server(server_id_in IN NUMBER, channel_id_in NUMBER, immediate_in NUMBER := 1, user_id_in in number := null, recalcfamily_in number := 1)
    IS
        channel_parent_val      rhnChannel.parent_channel%TYPE;
        parent_subscribed       BOOLEAN;
        server_has_base_chan    BOOLEAN;
        server_already_in_chan  BOOLEAN;
        channel_family_id_val   NUMBER;
        server_org_id_val       NUMBER;
        available_subscriptions NUMBER;
        available_fve_subs      NUMBER;
        consenting_user         NUMBER;
        allowed                 number := 0;
        is_fve                  CHAR(1) := 'N';
    BEGIN
        if user_id_in is not null then
            allowed := rhn_channel.user_role_check(channel_id_in, user_id_in, 'subscribe');
        else
            allowed := 1;
        end if;

        if allowed = 0 then
            rhn_exception.raise_exception('no_subscribe_permissions');
        end if;


        SELECT parent_channel INTO channel_parent_val FROM rhnChannel WHERE id = channel_id_in;

        IF channel_parent_val IS NOT NULL
        THEN    
            -- child channel; if attempting to cross-subscribe a child to the wrong base, silently ignore
            parent_subscribed := FALSE;    

            FOR check_subscription IN check_server_subscription(server_id_in, channel_parent_val)
            LOOP
                parent_subscribed := TRUE;
            END LOOP check_subscription;
        
            IF NOT parent_subscribed
            THEN
                RETURN;
            END IF;
        ELSE
            -- base channel
            server_has_base_chan := FALSE;
            FOR base IN server_base_subscriptions(server_id_in)
            LOOP
                server_has_base_chan := TRUE;
            END LOOP base;
            
            IF server_has_base_chan
            THEN
                rhn_exception.raise_exception('channel_server_one_base');
            END IF;
        END IF;
    
        FOR check_subscription IN check_server_subscription(server_id_in, channel_id_in)
        LOOP
            server_already_in_chan := TRUE;
        END LOOP check_subscription;
    
        IF server_already_in_chan
        THEN
            RETURN;
        END IF;
        
        channel_family_id_val := rhn_channel.family_for_channel(channel_id_in);
        IF channel_family_id_val IS NULL
        THEN
            rhn_exception.raise_exception('channel_subscribe_no_family');
        END IF;

        --
        -- Use the org_id of the server only if the org_id of the channel = NULL.
        -- This is required for subscribing to shared channels.
        --
        SELECT NVL(org_id, (SELECT org_id FROM rhnServer WHERE id = server_id_in))
          INTO server_org_id_val
          FROM rhnChannel
         WHERE id = channel_id_in;
         
        begin
            obtain_read_lock(channel_family_id_val, server_org_id_val);
        exception
            when no_data_found then
                rhn_exception.raise_exception('channel_family_no_subscriptions');
        end;

        available_subscriptions := rhn_channel.available_family_subscriptions(channel_family_id_val, server_org_id_val);
        available_fve_subs := rhn_channel.available_fve_family_subs(channel_family_id_val, server_org_id_val);

        IF available_subscriptions IS NULL OR
            available_subscriptions > 0 or
            can_server_consume_virt_channl(server_id_in, channel_family_id_val) = 1 OR
            (available_fve_subs > 0 AND can_server_consume_fve(server_id_in) = 1)
        THEN
            if can_server_consume_virt_channl(server_id_in, channel_family_id_val) = 0 AND available_fve_subs > 0 AND can_server_consume_fve(server_id_in) = 1 THEN
                is_fve := 'Y';
            END IF;
            insert into rhnServerHistory (id,server_id,summary,details) (
                select  rhn_event_id_seq.nextval,
                        server_id_in,
                        'subscribed to channel ' || SUBSTR(c.label, 0, 106),
                        c.label
                from    rhnChannel c
                where   c.id = channel_id_in
            );
            UPDATE rhnServer SET channels_changed = sysdate WHERE id = server_id_in;
            INSERT INTO rhnServerChannel (server_id, channel_id, is_fve) VALUES (server_id_in, channel_id_in, is_fve);
			IF recalcfamily_in > 0
			THEN
                rhn_channel.update_family_counts(channel_family_id_val, server_org_id_val);
			END IF;
            queue_server(server_id_in, immediate_in);
        ELSE
            rhn_exception.raise_exception('channel_family_no_subscriptions');
        END IF;
            
    END subscribe_server;



    FUNCTION can_convert_to_fve(server_id_in IN NUMBER, channel_family_id_val IN NUMBER)
    RETURN NUMBER
    IS
        CURSOR fve_convertible_entries IS
        select 1  from
            rhnServerFveCapable cap
          where cap.server_id = server_id_in
                AND cap.channel_family_id = channel_family_id_val;
    BEGIN
        FOR entry IN fve_convertible_entries LOOP
            return 1;
        END LOOP;
        RETURN 0;
    END can_convert_to_fve;



    -- Converts server channel_family to use a flex entitlement
    PROCEDURE convert_to_fve(server_id_in IN NUMBER, channel_family_id_val IN NUMBER)
    IS
        available_fve_subs      NUMBER;
        server_org_id_val       NUMBER;        
    BEGIN

        --
        -- Use the org_id of the server only if the org_id of the channel = NULL.
        -- This is required for subscribing to shared channels.
        --
        SELECT org_id
          INTO server_org_id_val
          FROM rhnServer
         WHERE id = server_id_in;
         
        begin
            obtain_read_lock(channel_family_id_val, server_org_id_val);
        exception
            when no_data_found then
                rhn_exception.raise_exception('channel_family_no_subscriptions');
        end;
        IF (can_convert_to_fve(server_id_in, channel_family_id_val ) = 0) 
            THEN
                rhn_exception.raise_exception('server_cannot_convert_to_flex');
        END IF;

        available_fve_subs := rhn_channel.available_fve_family_subs(channel_family_id_val, server_org_id_val);

        IF (available_fve_subs > 0)
        THEN
        
            insert into rhnServerHistory (id,server_id,summary,details) (
                select  rhn_event_id_seq.nextval,
                        server_id_in,
                        'converted to flex entitlement' || SUBSTR(cf.label, 0, 99),
                        cf.label
                from    rhnChannelFamily cf
                where   cf.id = channel_family_id_val
            );

            UPDATE rhnServerChannel sc set sc.is_fve = 'Y' 
                           where sc.server_id = server_id_in and  
                                 sc.channel_id in 
                                    (select cfm.channel_id from rhnChannelFamilyMembers cfm
                                                where cfm.CHANNEL_FAMILY_ID = channel_family_id_val);
            
            rhn_channel.update_family_counts(channel_family_id_val, server_org_id_val);
        ELSE
            rhn_exception.raise_exception('not_enough_flex_entitlements');
        END IF;
            
    END convert_to_fve;    
    
    function can_server_consume_virt_channl(
        server_id_in in number,
        family_id_in in number )
    return number
    is

        cursor server_virt_families is
            select vi.virtual_system_id, cfvsl.channel_family_id
            from
                rhnChannelFamilyVirtSubLevel cfvsl,
                rhnSGTypeVirtSubLevel sgtvsl,
                rhnVirtualInstance vi
            where
                vi.virtual_system_id = server_id_in 
                and sgtvsl.virt_sub_level_id = cfvsl.virt_sub_level_id
                and cfvsl.channel_family_id = family_id_in
                and exists (
                    select 1
                    from rhnServerEntitlementView sev
                    where vi.host_system_id = sev.server_id
                    and sev.server_group_type_id = sgtvsl.server_group_type_id );
    begin

        for server_virt_family in server_virt_families loop
            return 1;
        end loop;

        return 0;

    end;

    FUNCTION can_server_consume_fve(server_id_in IN NUMBER)
    RETURN NUMBER
    IS
        CURSOR vi_entries IS
            SELECT 1
              FROM rhnVirtualInstance vi
             WHERE vi.virtual_system_id = server_id_in
             and not exists(select server_id from rhnServerChannel sc where 
                            sc.server_id = vi.virtual_system_id 
                            and  sc.is_fve='Y');
        vi_count NUMBER;

    BEGIN
        FOR vi_entry IN VI_ENTRIES LOOP
            return 1;
        END LOOP;
        RETURN 0;
    END;

    function guess_server_base(
        server_id_in in number
    ) RETURN number is
        cursor server_cursor is
            select s.server_arch_id, s.release, s.org_id
              from rhnServer s
             where s.id = server_id_in;
    begin
        for s in server_cursor loop
            for channel in base_channel_cursor(s.release,
                s.server_arch_id, s.org_id) 
            loop
                return channel.id;
            end loop base_channel_cursor;
        end loop server_cursor;
        -- Server not found, or no base channel applies to it
        return null;
    end;

    -- Private function
    function normalize_server_arch(server_arch_in in varchar2)
    return varchar2
    deterministic
    is
        suffix VARCHAR2(128) := '-redhat-linux';
        suffix_len NUMBER := length(suffix);
    begin
        if server_arch_in is NULL then
            return NULL;
        end if;
        if instr(server_arch_in, '-') > 0
        then
            -- Suffix already present
            return server_arch_in;
        end if;
        return server_arch_in || suffix;
    end normalize_server_arch;

    --
    --
    -- Raises: 
    --   server_arch_not_found
    --   no_subscribe_permissions
    function base_channel_for_release_arch(
        release_in in varchar2,
        server_arch_in in varchar2,
        org_id_in in number := -1,
        user_id_in in number := null
    ) return number is
        server_arch varchar2(256) := normalize_server_arch(server_arch_in);
        server_arch_id number;
    begin
        -- Look up the server arch
        begin
            select id
              into server_arch_id
              from rhnServerArch
             where label = server_arch;
        exception
            when no_data_found then
                rhn_exception.raise_exception('server_arch_not_found');
        end;
        return base_channel_rel_archid(release_in, server_arch_id,
            org_id_in, user_id_in);
    end base_channel_for_release_arch;

    function base_channel_rel_archid(
        release_in in varchar2,
        server_arch_id_in in number,
        org_id_in in number := -1,
        user_id_in in number := null
    ) return number is
        denied_channel_id number := null;
        valid_org_id number := org_id_in;
        valid_user_id number := user_id_in;
        channel_subscribable number;
    begin
        if org_id_in = -1 and user_id_in is not null then
            -- Get the org id from the user id
            begin
                select org_id
                  into valid_org_id
                  from web_contact
                 where id = user_id_in;
            exception
                when no_data_found then
                    -- User doesn't exist
                    -- XXX Only list public stuff for now
                    valid_user_id := null;
                    valid_org_id := -1;
            end;
        end if;

        for c in base_channel_cursor(release_in, server_arch_id_in, valid_org_id)
        loop
            -- This row is a possible match
            if valid_user_id is null then
                -- User ID not specified, so no user to channel permissions to
                -- check
                return c.id;
            end if;

            -- Check user to channel permissions
            select loose_user_role_check(c.id, user_id_in, 'subscribe')
              into channel_subscribable
              from dual;

            if channel_subscribable = 1 then
                return c.id;
            end if;
                
            -- Base channel exists, but is not subscribable; keep trying
            denied_channel_id := c.id;
        end loop base_channel_fetch;
        
        if denied_channel_id is not null then
            rhn_exception.raise_exception('no_subscribe_permissions');
        end if;
        -- No base channel applies
        return NULL;
    end base_channel_rel_archid;

    PROCEDURE clear_subscriptions(server_id_in IN NUMBER, deleting_server IN NUMBER := 0,
                                update_family_countsYN IN NUMBER := 1)
    IS
        cursor server_channels(server_id_in in number) is
                select  s.org_id, sc.channel_id, cfm.channel_family_id
                from    rhnServer s,
                        rhnServerChannel sc,
                        rhnChannelFamilyMembers cfm
                where   s.id = server_id_in
                        and s.id = sc.server_id
                        and sc.channel_id = cfm.channel_id
                order by cfm.channel_family_id;
        last_channel_family_id rhnChannelFamilyMembers.channel_family_id%type := -1;
        last_channel_org_id    rhnServer.org_id%type := -1;
    BEGIN
        for channel in server_channels(server_id_in)
        loop
                unsubscribe_server(server_id_in, channel.channel_id, 1, 1, deleting_server, 0);
                if update_family_countsYN > 0
                    and channel.channel_family_id != last_channel_family_id then
                    -- update family counts only once
                    -- after all channels with same family has been fetched
                    if last_channel_family_id != -1 then
                        update_family_counts(last_channel_family_id, last_channel_org_id);
                    end if;
                    last_channel_family_id := channel.channel_family_id;
                    last_channel_org_id    := channel.org_id;
                end if;
        end loop channel;
        if update_family_countsYN > 0 and last_channel_family_id != -1 then
            -- update the last family fetched
            update_family_counts(last_channel_family_id, last_channel_org_id);
        end if;
    END clear_subscriptions;

    PROCEDURE unsubscribe_server(server_id_in IN NUMBER, channel_id_in NUMBER, immediate_in NUMBER := 1, unsubscribe_children_in number := 0,
                                 deleting_server IN NUMBER := 0,
                                 update_family_countsYN IN NUMBER := 1)
    IS
        channel_family_id_val   NUMBER;
        server_org_id_val       NUMBER;
        available_subscriptions NUMBER; 
        server_already_in_chan  BOOLEAN;
        cursor  channel_family_is_proxy(channel_family_id_in in number) is
                select  1
                from    rhnChannelFamily
                where   id = channel_family_id_in
                    and label = 'rhn-proxy';
        cursor  channel_family_is_satellite(channel_family_id_in in number) is
                select  1
                from    rhnChannelFamily
                where   id = channel_family_id_in
                    and label = 'rhn-satellite';
        -- this is *EXACTLY* like check_server_parent_membership, but if we recurse
        -- with the package-level one, we get a "cursor already open", so we need a
        -- copy on our call stack instead.  GROAN.
        cursor local_chk_server_parent_memb (
                        server_id_in number,
                        channel_id_in number ) is
                select  c.id
                from    rhnChannel                      c,
                                rhnServerChannel        sc
                where   1=1
                        and c.parent_channel = channel_id_in
                        and c.id = sc.channel_id
                        and sc.server_id = server_id_in;
    BEGIN
        FOR child IN local_chk_server_parent_memb(server_id_in, channel_id_in)
        LOOP
            if unsubscribe_children_in = 1 then
                unsubscribe_server(server_id_in => server_id_in,
                                                                channel_id_in => child.id,
                                                                immediate_in => immediate_in,
                                                                unsubscribe_children_in => unsubscribe_children_in,
                        deleting_server => deleting_server,
                        update_family_countsYN => update_family_countsYN);
            else
                rhn_exception.raise_exception('channel_unsubscribe_child_exists');
            end if;
        END LOOP child;
        
        server_already_in_chan := FALSE;
    
        FOR check_subscription IN check_server_subscription(server_id_in, channel_id_in)
        LOOP
            server_already_in_chan := TRUE;
        END LOOP check_subscription;
    
        IF NOT server_already_in_chan
        THEN
            RETURN;
        END IF;
        
   if deleting_server = 0 then 

      insert into rhnServerHistory (id,server_id,summary,details) (
          select  rhn_event_id_seq.nextval,
                server_id_in,
             'unsubscribed from channel ' || SUBSTR(c.label, 0, 106),
             c.label
          from    rhnChannel c
          where   c.id = channel_id_in
      );

        UPDATE rhnServer SET channels_changed = sysdate WHERE id = server_id_in;
   end if;
        
   DELETE FROM rhnServerChannel WHERE server_id = server_id_in AND channel_id = channel_id_in;

   if deleting_server = 0 then 
        queue_server(server_id_in, immediate_in);
   end if;

        channel_family_id_val := rhn_channel.family_for_channel(channel_id_in);
        IF channel_family_id_val IS NULL
        THEN
            rhn_exception.raise_exception('channel_unsubscribe_no_family');
        END IF;

        for ignore in channel_family_is_satellite(channel_family_id_val) loop
                delete from rhnSatelliteInfo where server_id = server_id_in;
                delete from rhnSatelliteChannelFamily where server_id = server_id_in;
        end loop;

        for ignore in channel_family_is_proxy(channel_family_id_val) loop
                delete from rhnProxyInfo where server_id = server_id_in;
        end loop;
        SELECT org_id INTO server_org_id_val
          FROM rhnServer
         WHERE id = server_id_in;
         
        if update_family_countsYN = 1 then
            rhn_channel.update_family_counts(channel_family_id_val, server_org_id_val);
        end if;
    END unsubscribe_server;


    FUNCTION family_for_channel(channel_id_in IN NUMBER)
    RETURN NUMBER
    IS
        channel_family_id_val NUMBER;
    BEGIN
        SELECT channel_family_id INTO channel_family_id_val
          FROM rhnChannelFamilyMembers
         WHERE channel_id = channel_id_in;
         
        RETURN channel_family_id_val;
    EXCEPTION
        WHEN NO_DATA_FOUND
        THEN
            RETURN NULL;
    END family_for_channel;

    FUNCTION available_family_subscriptions(channel_family_id_in IN NUMBER, org_id_in IN NUMBER)
    RETURN NUMBER
    IS
        cfp channel_family_perm_cursor%ROWTYPE;
        current_members_val NUMBER;
        max_members_val     NUMBER;
        found               NUMBER;
    BEGIN
        IF NOT channel_family_perm_cursor%ISOPEN
        THEN
            OPEN channel_family_perm_cursor(channel_family_id_in, org_id_in);
        END IF;

        FETCH channel_family_perm_cursor INTO cfp;
        
        WHILE channel_family_perm_cursor%FOUND
        LOOP
            found := 1;
            
            current_members_val := cfp.current_members;
            max_members_val := cfp.max_members;
            
            FETCH channel_family_perm_cursor INTO cfp;
        END LOOP;

        IF channel_family_perm_cursor%ISOPEN
        THEN
            CLOSE channel_family_perm_cursor;
        END IF;

        -- not found: either the channel fam doesn't have an entry in cfp, or the org doesn't have access to it.
        -- either way, there are no available subscriptions
        
        IF found IS NULL
        THEN
            RETURN 0;
        END IF;

        -- null max members?  in that case, pass it on; NULL means infinite                     
        IF max_members_val IS NULL
        THEN
            RETURN NULL;
        END IF;

        -- otherwise, return the delta  
        RETURN max_members_val - current_members_val;                   
    END available_family_subscriptions;

    FUNCTION available_fve_family_subs(channel_family_id_in IN NUMBER, org_id_in IN NUMBER)
    RETURN NUMBER
    IS
        cfp channel_family_perm_cursor%ROWTYPE;
        fve_current_members_val NUMBER;
        fve_max_members_val     NUMBER;
        found               NUMBER;

    BEGIN
        IF NOT channel_family_perm_cursor%ISOPEN THEN
            OPEN channel_family_perm_cursor(channel_family_id_in, org_id_in);
        END IF;

        FETCH channel_family_perm_cursor INTO cfp;

        WHILE channel_family_perm_cursor%FOUND LOOP
            found := 1;
            fve_current_members_val := cfp.fve_current_members;
            fve_max_members_val := cfp.fve_max_members;
            FETCH channel_family_perm_cursor INTO cfp;
        END LOOP;

        IF channel_family_perm_cursor%ISOPEN THEN
            CLOSE channel_family_perm_cursor;
        END IF;

        IF found IS NULL THEN
            RETURN 0;
        END IF;

        IF fve_max_members_val IS NULL THEN
            RETURN NULL;
        END IF;

        RETURN fve_max_members_val - fve_current_members_val;

    END available_fve_family_subs;

    
    -- *******************************************************************
    -- FUNCTION: channel_family_current_members
    -- Calculates and returns the actual count of systems consuming
    --   physical channel subscriptions.
    -- Called by: update_family_counts 
    --            rhn_entitlements.repoll_virt_guest_entitlements
    -- *******************************************************************
    function channel_family_current_members(channel_family_id_in IN NUMBER,
                                            org_id_in IN NUMBER)
    return number
    is
        current_members_count number := 0;
    begin
        select  count(distinct server_id)
        into    current_members_count
          from  rhnChannelFamilyServerPhysical cfsp
         where  cfsp.channel_family_id = channel_family_id_in
           and  cfsp.customer_id = org_id_in;
        return current_members_count;
    end;        


    function cfam_curr_fve_members(
        channel_family_id_in IN NUMBER,
        org_id_in IN NUMBER)
    return number
    is
        current_members_count number := 0;

    begin
        select count(sc.server_id)
          into current_members_count
          from rhnServerChannel sc,
               rhnChannelFamilyMembers cfm,
               rhnServer s
         where s.org_id = org_id_in
           and s.id = sc.server_id
           and cfm.channel_family_id = channel_family_id_in
           and cfm.channel_id = sc.channel_id
           and exists (
                select 1
                  from rhnChannelFamilyServerFve cfsp
                 where cfsp.CHANNEL_FAMILY_ID = channel_family_id_in
                   and cfsp.server_id = s.id
                );

        return current_members_count;
    end;
    PROCEDURE update_family_counts(channel_family_id_in IN NUMBER, 
                                   org_id_in IN NUMBER)
    IS
    BEGIN
        update rhnPrivateChannelFamily
           set current_members = ( channel_family_current_members(channel_family_id_in, org_id_in)),
               fve_current_members = ( cfam_curr_fve_members(channel_family_id_in, org_id_in))
         where org_id = org_id_in
           and channel_family_id = channel_family_id_in;
    END update_family_counts;
    
    PROCEDURE update_group_family_counts(group_label_in IN VARCHAR2,
                                   org_id_in IN NUMBER)
    IS
    BEGIN
        FOR i IN (
                SELECT DISTINCT CFM.channel_family_id, SG.org_id
                 FROM rhnChannelFamilyMembers CFM
                 JOIN rhnServerChannel SC
                   ON SC.channel_id = CFM.channel_id
                 JOIN rhnServerGroupMembers SGM
                   ON SC.server_id = SGM.server_id
                 JOIN rhnServerGroup SG
                   ON SGM.server_group_id = SG.id
                 JOIN rhnServerGroupType SGT
                   ON SG.group_type = SGT.id
                WHERE SGT.label = group_label_in
                  AND SG.org_id = org_id_in
                  AND SGT.is_base = 'Y'
        ) LOOP
            rhn_channel.update_family_counts(i.channel_family_id, i.org_id);
        END LOOP;
    END update_group_family_counts;

    FUNCTION available_chan_subscriptions(channel_id_in IN NUMBER, 
                                          org_id_in IN NUMBER)
    RETURN NUMBER
    IS
            channel_family_id_val NUMBER;
    BEGIN
        SELECT channel_family_id INTO channel_family_id_val
            FROM rhnChannelFamilyMembers
            WHERE channel_id = channel_id_in;
         
            RETURN rhn_channel.available_family_subscriptions(
                           channel_family_id_val, org_id_in);
    END available_chan_subscriptions;

	FUNCTION available_fve_chan_subs(channel_id_in IN NUMBER,
                                          org_id_in IN NUMBER)
    RETURN NUMBER
    IS
        channel_family_id_val NUMBER;

    BEGIN
        SELECT channel_family_id INTO channel_family_id_val
          FROM rhnChannelFamilyMembers
         WHERE channel_id = channel_id_in;

        RETURN rhn_channel.available_fve_family_subs( channel_family_id_val, org_id_in);
    END available_fve_chan_subs;

    procedure unsubscribe_server_from_family(server_id_in in number, 
                                             channel_family_id_in in number)
    is
    begin
        delete
        from    rhnServerChannel rsc
        where   rsc.server_id = server_id_in
            and channel_id in (
                select  rcfm.channel_id
                from    rhnChannelFamilyMembers rcfm
                where   rcfm.channel_family_id = channel_family_id_in);
    end;

    function get_org_id(channel_id_in in number)
    return number
    is
        org_id_out number;
    begin
        select org_id into org_id_out
            from rhnChannel
            where id = channel_id_in;
         
            return org_id_out;
    end get_org_id;
    
    function get_cfam_org_access(cfam_id_in in number, org_id_in in number)
    return number
    is
        cursor  families is
                        select  1
                        from    rhnOrgChannelFamilyPermissions cfp
                        where   cfp.org_id = org_id_in;
    begin
                -- the idea: if we get past this query, 
        -- the user has the role, else catch the exception and return 0
                for family in families loop
                return 1;
                end loop;
                return 0;
    end;

    function get_org_access(channel_id_in in number, org_id_in in number)
    return number
    is
        throwaway number;
    begin
        -- the idea: if we get past this query, 
        -- the org has access to the channel, else catch the exception and return 0
        select distinct 1 into throwaway
          from rhnChannelFamilyMembers CFM,
               rhnOrgChannelFamilyPermissions CFP
         where cfp.org_id = org_id_in
           and CFM.channel_family_id = CFP.channel_family_id
           and CFM.channel_id = channel_id_in
           and (CFP.max_members > 0 or CFP.max_members is null or CFP.org_id = 1);
           
        return 1;
        exception
            when no_data_found
            then
            return 0;
    end;
    
    -- check if a user has a given role, or if such a role is inferrable
    function user_role_check_debug(channel_id_in in number, 
                                   user_id_in in number, 
                                   role_in in varchar2, 
                                   reason_out out varchar2)
    return number
    is
        org_id number;
    begin
        org_id := rhn_user.get_org_id(user_id_in);

        -- channel might be shared
        if role_in = 'subscribe' and
           rhn_channel.shared_user_role_check(channel_id_in, user_id_in, role_in) = 1 then
            return 1;
        end if;
        
        if role_in = 'manage' and 
           NVL(rhn_channel.get_org_id(channel_id_in), -1) <> org_id then
                reason_out := 'channel_not_owned';
               return 0;
            end if;
        
        if role_in = 'subscribe' and 
           rhn_channel.get_org_access(channel_id_in, org_id) = 0 then
                reason_out := 'channel_not_available';
                return 0;
            end if;
        
        -- channel admins have all roles
        if rhn_user.check_role_implied(user_id_in, 'channel_admin') = 1 then
            reason_out := 'channel_admin';
            return 1;
            end if;

        -- the subscribe permission is inferred 
    -- UNLESS the not_globally_subscribable flag is set 
        if role_in = 'subscribe'
        then
            if rhn_channel.org_channel_setting(channel_id_in, 
                       org_id,
                       'not_globally_subscribable') = 0 then
                reason_out := 'globally_subscribable';
                    return 1;
            end if;
        end if;
        
        -- all other roles (manage right now) are explicitly granted    
        reason_out := 'direct_permission';
        return rhn_channel.direct_user_role_check(channel_id_in, 
                                              user_id_in, role_in);
    end;
    
    -- same as above, but with no OUT param; useful in views, etc
    function user_role_check(channel_id_in in number, user_id_in in number, role_in in varchar2)
    return number
    is
        throwaway varchar2(256);
    begin
        return rhn_channel.user_role_check_debug(channel_id_in, user_id_in, role_in, throwaway);
    end;

    --
    -- For multiorg phase II, this function simply checks to see if the user's
    -- has a trust relationship that includes this channel by id.
    --
    function shared_user_role_check(channel_id in number, user_id in number, role in varchar2)
    return number
    is
      n number;
      oid number;
    begin
      oid := rhn_user.get_org_id(user_id);
      select 1 into n
      from rhnSharedChannelView s
      where s.id = channel_id and s.org_trust_id = oid;
      return 1;
      exception
        when no_data_found then
          return 0;
    end;

    -- same as above, but returns 1 if user_id_in is null
    -- This is useful in queries where user_id is not specified
    function loose_user_role_check(channel_id_in in number, user_id_in in number, role_in in varchar2)
    return number
    is
    begin
        if user_id_in is null then
            return 1;
        end if;
        return user_role_check(channel_id_in, user_id_in, role_in);
    end loose_user_role_check;
    
    -- directly checks the table, no inferred permissions
    function direct_user_role_check(channel_id_in in number, user_id_in in number, role_in in varchar2)
    return number
    is
        throwaway number;
    begin
        -- the idea: if we get past this query, the user has the role, else catch the exception and return 0
        select 1 into throwaway
          from rhnChannelPermissionRole CPR,
               rhnChannelPermission CP
         where CP.user_id = user_id_in
           and CP.channel_id = channel_id_in
           and CPR.label = role_in
           and CP.role_id = CPR.id;
           
        return 1;
    exception
        when no_data_found
            then
            return 0;
    end;
    
    -- check if an org has a certain setting
    function org_channel_setting(channel_id_in in number, org_id_in in number, setting_in in varchar2)
    return number
    is
        throwaway number;
    begin
        -- the idea: if we get past this query, the org has the setting, else catch the exception and return 0
        select 1 into throwaway
          from rhnOrgChannelSettingsType OCST,
               rhnOrgChannelSettings OCS
         where OCS.org_id = org_id_in
           and OCS.channel_id = channel_id_in
           and OCST.label = setting_in
           and OCS.setting_id = OCST.id;
           
        return 1;
    exception
        when no_data_found
            then
            return 0;
    end;
    
    FUNCTION channel_priority(channel_id_in IN number) 
    RETURN number
    IS
         channel_name varchar2(256);
         priority number;
         end_of_life_val date;
         org_id_val number;
    BEGIN

        select name, end_of_life, org_id
        into channel_name, end_of_life_val, org_id_val
        from rhnChannel
        where id = channel_id_in;

        if end_of_life_val is not null then
          return -400;
        end if;

        if channel_name like 'Red Hat Enterprise Linux%' or channel_name like 'RHEL%' then
          priority := 1000;
          if channel_name not like '%Beta%' then
            priority := priority + 1000;
          end if;

          priority := priority +
            case
              when channel_name like '%v. 5%' then 600
              when channel_name like '%v. 4%' then 500
              when channel_name like '%v. 3%' then 400
              when channel_name like '%v. 2%' then 300
              when channel_name like '%v. 1%' then 200
              else 0
            end;

          priority := priority +
            case
              when channel_name like 'Red Hat Enterprise Linux (v. 5%' then 60
              when (channel_name like '%AS%' and channel_name not like '%Extras%') then 50
              when (channel_name like '%ES%' and channel_name not like '%Extras%') then 40
              when (channel_name like '%WS%' and channel_name not like '%Extras%') then 30
              when (channel_name like '%Desktop%' and channel_name not like '%Extras%') then 20
              when channel_name like '%Extras%' then 10
              else 0
            end; 

          priority := priority +
            case
              when channel_name like '%)' then 5
              else 0
            end;

          priority := priority +
            case
              when channel_name like '%32-bit x86%' then 4
              when channel_name like '%64-bit Intel Itanium%' then 3
              when channel_name like '%64-bit AMD64/Intel EM64T%' then 2
              else 0
            end;
        elsif channel_name like 'Red Hat Desktop%' then
            priority := 900;

            if channel_name not like '%Beta%' then
               priority := priority + 50;
            end if;
 
          priority := priority +
            case
              when channel_name like '%v. 4%' then 40
              when channel_name like '%v. 3%' then 30
              when channel_name like '%v. 2%' then 20
              when channel_name like '%v. 1%' then 10
              else 0
            end;
            
          priority := priority +
            case
              when channel_name like '%32-bit x86%' then 4
              when channel_name like '%64-bit Intel Itanium%' then 3
              when channel_name like '%64-bit AMD64/Intel EM64T%' then 2
              else 0
            end;
         
        elsif org_id_val is not null then
          priority := 600;
        else
          priority := 500;
        end if;
      
      return -priority;

    end channel_priority;

    -- right now this only does the accounting changes; the cascade
    -- actually does the rhnServerChannel delete.
    procedure delete_server_channels(server_id_in in number)
    is
    begin
        update  rhnPrivateChannelFamily
        set     current_members = current_members -1
        where   org_id in (
                        select  org_id
                        from    rhnServer
                        where   id = server_id_in
                )
                and channel_family_id in (
                        select  rcfm.channel_family_id
                        from    rhnChannelFamilyMembers rcfm,
                                rhnServerChannel rsc
                        where   rsc.server_id = server_id_in
                                and rsc.channel_id = rcfm.channel_id
                and not exists (
                    select 1
                    from
                        rhnChannelFamilyVirtSubLevel cfvsl,
                        rhnSGTypeVirtSubLevel sgtvsl,
                        rhnServerEntitlementView sev,
                        rhnVirtualInstance vi
                    where
                        -- system is a virtual instance
                        vi.virtual_system_id = server_id_in
                        and vi.host_system_id = sev.server_id
                        -- system's host has a virt ent
                        and sev.label in ('virtualization_host',
                                          'virtualization_host_platform')
                        and sev.server_group_type_id = 
                            sgtvsl.server_group_type_id
                        -- the host's virt ent grants a cf virt sub level
                        and sgtvsl.virt_sub_level_id = cfvsl.virt_sub_level_id
                        -- the cf is in that virt sub level
                        and cfvsl.channel_family_id = rcfm.channel_family_id
                    )
                );
    end;

        -- this could certainly be optimized to do updates if needs be
        procedure refresh_newest_package(channel_id_in in number, caller_in in varchar2 := '(unknown)')
        is
        begin
                delete from rhnChannelNewestPackage where channel_id = channel_id_in;
                insert into rhnChannelNewestPackage
                        ( channel_id, name_id, evr_id, package_id, package_arch_id ) 
                        (       select  channel_id,
                                                name_id, evr_id,
                                                package_id, package_arch_id
                                from    rhnChannelNewestPackageView
                                where   channel_id = channel_id_in
                        );
                insert into rhnChannelNewestPackageAudit (channel_id, caller)
                    values (channel_id_in, caller_in);
                update rhnChannel 
                    set last_modified = greatest(sysdate, last_modified + 1/86400)
                    where id = channel_id_in; 
        end;

   procedure update_channel ( channel_id_in in number, invalidate_ss in number := 0, 
                              date_to_use in date := sysdate )
   is

   channel_last_modified date;
   last_modified_value date;

   cursor snapshots is
   select  snapshot_id id
   from    rhnSnapshotChannel
   where   channel_id = channel_id_in;

   begin

      select last_modified
      into channel_last_modified
      from rhnChannel
      where id = channel_id_in;
  
      last_modified_value := date_to_use;

      if last_modified_value <= channel_last_modified then
          last_modified_value := last_modified_value + 1/86400;
      end if;

      update rhnChannel set last_modified = last_modified_value
      where id = channel_id_in;

      if invalidate_ss = 1 then 
        for snapshot in snapshots loop
            update rhnSnapshot
            set invalid = lookup_snapshot_invalid_reason('channel_modified')
            where id = snapshot.id;
        end loop;
      end if;

   end update_channel;

   procedure update_channels_by_package ( package_id_in in number, date_to_use in date := sysdate )
   is

   cursor channels is
   select channel_id
   from rhnChannelPackage
   where package_id = package_id_in
   order by channel_id;

   begin
      for channel in channels loop
         -- we want to invalidate the snapshot assocated with the channel when we
         -- do this b/c we know we've added or removed or packages
         rhn_channel.update_channel ( channel.channel_id, 1, date_to_use );
      end loop;
   end update_channels_by_package;

   
   procedure update_channels_by_errata ( errata_id_in number, date_to_use in date := sysdate )
   is

   cursor channels is
   select channel_id
   from rhnChannelErrata
   where errata_id = errata_id_in
   order by channel_id;

   begin
      for channel in channels loop
         -- we won't invalidate snapshots, b/c just changing the errata associated with
         -- a channel shouldn't invalidate snapshots
         rhn_channel.update_channel ( channel.channel_id, 0, date_to_use );
      end loop;
   end update_channels_by_errata;

END rhn_channel;
/
SHOW ERRORS

--
-- Revision 1.75  2005/03/04 00:04:19  jslagle
-- bz #147617
-- Made Red Hat Desktop sort a little better.
--
-- Revision 1.74  2005/02/22 03:24:47  jslagle
-- bz #147617
-- Improve channel_priority function to order channels better.
--
-- Revision 1.73  2004/08/16 20:39:30  pjones
-- bugzilla: 129889 -- make bulk_server_basechange_from() actually work.
--
-- Revision 1.72  2004/04/14 00:09:24  pjones
-- bugzilla: 120761 -- split rhnChannelPermissions into two tables, eliminating
-- a frequent full table scan
--
-- Revision 1.71  2004/04/13 16:28:36  bretm
-- bugzilla:  119871
--
-- keep track of rhnServer.channels_changed through the pl/sql fns
--
-- Revision 1.70  2004/03/26 18:11:32  rbb
-- Bugzilla:  114057
--
-- Add a script to determine channel priority.
--
-- Revision 1.69  2004/02/17 20:16:52  pjones
-- bugzilla: none -- add cvs tags into the package as long as we're touching
-- it anyway
--
-- Revision 1.68  2004/02/17 20:05:38  pjones
-- bugzilla: 115782 -- make bulk_server_basechange_from() filter out servers
-- with arches incompatible with the target channel
--
-- Revision 1.67  2004/02/06 02:36:10  misa
-- Changed normalize_server_arch to allow for solaris arches
--
-- Revision 1.66  2003/11/13 16:58:34  cturner
-- make use of new rhn_user.check_role_implied call; pragmas broke, removed them for now since I have no idea how to fix them
--
-- Revision 1.65  2003/10/23 20:26:24  bretm
-- bugzilla:  none
--
-- note the channel label when we unsubscribe, too
--
-- Revision 1.64  2003/10/15 14:47:17  bretm
-- bugzilla:  none
--
-- add the channel label to the server history summary line when we log a channel change
--
-- Revision 1.63  2003/09/24 19:25:56  pjones
-- this wasn't the right fix, put it back
--
-- Revision 1.62  2003/09/24 17:42:19  pjones
-- bugzilla: none
--
-- limit our server base channel guess to channels with available permissions
--
-- Revision 1.61  2003/09/22 21:00:40  cturner
-- add method for easy acl check
--
-- Revision 1.60  2003/09/17 22:14:11  misa
-- bugzilla: 103639  Changes to allow me to move the base channel guess into plsql
--
-- Revision 1.59  2003/08/21 13:41:17  cturner
-- bugzilla: 99187.  properly test for satellite and proxy in bulk_guess_server_base; reorg code for better reuse
--
-- Revision 1.58  2003/07/24 16:46:22  cturner
-- bugzilla: 100723, the perm check was returning duplicates, so now it just calls the function it should have called anyway
--
-- Revision 1.57  2003/07/24 16:44:16  misa
-- bugzilla: none  A function more usable on the rhnapp side
--
-- Revision 1.56  2003/07/23 22:36:51  cturner
-- argh, max returns null even when now rows; use distinct.  how revolting
--
-- Revision 1.55  2003/07/23 22:01:31  cturner
-- oops, this one can return multiple rows; eliminate that in a lazy way
--
-- Revision 1.54  2003/07/23 21:59:19  cturner
-- rework how rhnUserChannel works; move to plsql for speed and maintenance
--
-- Revision 1.53  2003/07/21 17:49:12  pjones
-- bugzilla: none
--
-- add optional user for subscribe_server
--
-- Revision 1.52  2003/07/14 22:19:29  misa
-- bugzilla: none  Updating guess_base_channel to work more like the rhnapp server code
--
-- Revision 1.51  2003/06/26 22:09:04  pjones
-- bugzilla: none
--
-- log subscribe and unsubscribe
--
-- Revision 1.50  2003/06/05 19:31:15  pjones
-- bugzilla: 88278 -- make the cursor name smaller
--
-- Revision 1.49  2003/06/05 19:18:21  pjones
-- bugzilla: 88278
--
-- unsubscribe_server() opens the package-level cursor when it invokes itself,
-- so we're using a local copy instead.
--
-- Revision 1.48  2003/06/04 16:41:39  pjones
-- bugzilla: none
--
-- make bulk_guess_server_base() silently ignore unguessables
--
-- Revision 1.47  2003/06/04 16:27:03  pjones
-- bugzilla: 88822
--
-- eliminate the last outliers that remove things from channels without using
-- unsubscribe_server, I think.
--
-- Revision 1.46  2003/06/03 20:49:37  pjones
-- bugzilla: 88822
-- unsubscribing from rhn-satellite now clears rhnSatelliteChannelFamily
-- for the server in question
--
-- Revision 1.45  2003/06/02 20:41:45  pjones
-- bugzilla: none - fix rhnProxyInfo/rhnSatelliteInfo channel unsubscribe
-- problem.  Basicly, if you're out of the channel for any reason, you're
-- also out of rhnProxyInfo/rhnProxyInfo
--
-- Revision 1.44  2003/03/24 15:26:28  pjones
-- bugzilla: 85812
--
-- bulk_server_base_change silently ignores servers that are satellites
-- or proxies, as requested.
--
-- Revision 1.43  2003/02/26 20:28:17  pjones
-- rhn_channel.update_family_counts() in rhn_channel.entitle_customer()
-- the old codepath is:
--
-- ep ->
-- rhn_ep.entitlement_run_me() ->
-- rhn_ep.poll_customer() ->
-- rhn_channel.entitle_customer()
--
-- which doesn't change current_members, even though it may remove servers
-- from the family.
--
-- There's another bug here:  currently, we don't try to order forced
-- unsubscribes in any way; we just use
-- rhn_channel.unsubscribe_server_from_family .  If there are any child
-- channel subscriptions, this will leave them subscribed.  We really need
-- to iterate across the channels again, and subscribe any channel for which
-- there are no parent channel subscriptions.
--
-- Ugh.
--
-- Revision 1.42  2003/01/28 00:19:45  pjones
-- fix clear_subscriptions; AFAICT, this is only hit on the
-- bulk_server_base_change / bulk_server_base_guess codepaths, which puts
-- it infrequent enough that it could be our "bad count" culprit.
--
-- Revision 1.41  2003/01/14 19:51:45  pjones
-- make setting current_members on rhnChannelFamilyPermissions work when
-- a server is in more than one channel in a single family.
07070100000552000081B400000000000000000000000167AE1114000016DF000000000000000000000000000000000000006500000000susemanager-schema/upgrade/spacewalk-schema-1.0-to-spacewalk-schema-1.1/016-rhn_entitlements-pks.sql  --
-- Copyright (c) 2008--2010 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--

create or replace
package rhn_entitlements
is
	body_version varchar2(100) := '';

   type ents_array is varray(10) of rhnServerGroupType.label%TYPE;

    procedure remove_org_entitlements (
        org_id_in number
    );

    function entitlement_grants_service (
	    entitlement_in in varchar2,
		service_level_in in varchar2
	) return number;

	function lookup_entitlement_group (
		org_id_in in number,
		type_label_in in varchar2 := 'sw_mgr_entitled'
	) return number;

	function create_entitlement_group (
		org_id_in in number,
		type_label_in in varchar2 := 'sw_mgr_entitled'
	) return number;

   function can_entitle_server ( 
      server_id_in   in number, 
      type_label_in  in varchar2
   )
   return number;

   function can_switch_base ( 
      server_id_in   in    integer, 
      type_label_in  in    varchar2
   )
   return number;

   function find_compatible_sg (
      server_id_in in number,
      type_label_in in varchar2,
      sgid_out out number
   )
   return boolean;

	procedure entitle_server (
		server_id_in in number,
		type_label_in in varchar2 := 'sw_mgr_entitled'
	);

	procedure remove_server_entitlement (
		server_id_in in number,
		type_label_in in varchar2 := 'sw_mgr_entitled',
        repoll_virt_guests in number := 1
	);

	procedure unentitle_server (
		server_id_in in number
	);

    procedure repoll_virt_guest_entitlements(
        server_id_in in number
    );

	function get_server_entitlement (
		server_id_in in number
	) return ents_array;

	procedure modify_org_service (
		org_id_in in number,
		service_label_in in varchar2,
		enable_in in char
	);

    procedure set_customer_enterprise (
		customer_id_in in number
	);

	procedure set_customer_provisioning (
		customer_id_in in number
	);

	procedure set_customer_nonlinux (
		customer_id_in in number
	);

    procedure unset_customer_enterprise (
		customer_id_in in number
	);

	procedure unset_customer_provisioning (
		customer_id_in in number
	);

	procedure unset_customer_nonlinux (
		customer_id_in in number
	);

    procedure assign_system_entitlement(
        group_label_in in varchar2,
        from_org_id_in in number,
        to_org_id_in in number,
        quantity_in in number
    );

    procedure assign_channel_entitlement(
        channel_family_label_in in varchar2,
        from_org_id_in in number,
        to_org_id_in in number,
        quantity_in in number,
        flex_in in number
    );

    procedure activate_system_entitlement(
        org_id_in in number,
        group_label_in in varchar2,
        quantity_in in number
    );

    procedure activate_channel_entitlement(
        org_id_in in number,
        channel_family_label_in in varchar2,
        quantity_in in number,
        flex_in in number
    );

    procedure set_group_count (
		customer_id_in in number,	-- customer_id
		type_in in char,			-- 'U' or 'S'
		group_type_in in number,	-- rhn[User|Server]GroupType.id
		quantity_in in number,		-- quantity
                update_family_countsYN in number := 1 -- call update_family_counts inside
    );

    procedure set_family_count (
		customer_id_in in number,		-- customer_id
		channel_family_id_in in number,	-- 246
		quantity_in in number,			-- 3
                flex_in in number
    );

    -- this makes NO checks that the quantity is within max,
    -- so we should NEVER run this unless we KNOW that we won't be
    -- violating the max
    procedure entitle_last_modified_servers (
		customer_id_in in number,	-- customer_id
		type_label_in in varchar2,	-- 'enterprise_entitled'
		quantity_in in number		-- 3
    );

	procedure subscribe_newest_servers (
		customer_id_in in number
	);
end rhn_entitlements;
/
show errors

--
-- Revision 1.19  2004/05/26 19:45:48  pjones
-- bugzilla: 123639
-- 1) reformat "entitlement_grants_service"
-- 2) make the .pks and .pkb be in the same order.
-- 3) add "modify_org_service" (to be used instead of set_customer_SERVICELEVEL)
-- 4) add monitoring specific data.
--
-- Revision 1.18  2004/02/19 20:17:49  pjones
-- bugzilla: 115896 -- add sgt and oet data for nonlinux, add
-- [un]set_customer_nonlinux
--
-- Revision 1.17  2004/01/13 23:37:08  pjones
-- bugzilla: none -- mate provisioning and management slots.
--
-- Revision 1.16  2003/09/23 22:14:41  bretm
-- bugzilla:  103655
--
-- need something in the db that knows provisioning boxes are management boxes too, etc.
--
-- Revision 1.15  2003/09/19 22:35:07  pjones
-- bugzilla: none
--
-- provisioning and config management entitlement support
--
-- Revision 1.14  2003/09/02 22:22:54  pjones
-- bugzilla: none
--
-- attempt to autoentitle upon entitlement changes
--
-- Revision 1.13  2003/06/05 21:43:40  pjones
-- bugzilla: none
--
-- add rhn_entitlements.prune_everything(customer_id_in in number);
--
-- Revision 1.12  2003/05/22 16:01:14  pjones
-- reformat
-- remove update_[server|user]group_counts (unused)
--
-- Revision 1.11  2002/06/03 16:07:29  pjones
-- make prune_group and prune_family update respective max_members
-- correctly.
--
-- Revision 1.10  2002/05/29 19:10:31  pjones
-- code to entitle the last N modified servers to a particular service
-- level
--
-- Revision 1.9  2002/05/10 22:08:23  pjones
-- id/log
--
 07070100000553000081B400000000000000000000000167AE111400011646000000000000000000000000000000000000006500000000susemanager-schema/upgrade/spacewalk-schema-1.0-to-spacewalk-schema-1.1/017-rhn_entitlements-pkb.sql  --
-- Copyright (c) 2008--2010 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--

create or replace
package body rhn_entitlements
is
    body_version varchar2(100) := '';


    -- *******************************************************************
    -- PROCEDURE: remove_org_entitlements
    --
    -- Removes both system entitlements and channel subscriptions
    -- that are currently assigned to an org and re-assigns to the
    -- master org (org_id = 1).
    --
    -- When we call this we expect everything to already be unentitled
    -- which shoul be handled by delete_org.
    --
    -- Called by: delete_org
    -- *******************************************************************
    procedure remove_org_entitlements(
        org_id_in in number
    )
    is

        cursor system_ents is
        select sg.id, sg.max_members, sg.group_type
        from rhnServerGroup sg
        where group_type is not null
          and org_id = org_id_in;

        cursor channel_subs is
        select pcf.channel_family_id, pcf.max_members
        from rhnChannelFamily cf,
             rhnPrivateChannelFamily pcf
        where pcf.org_id = org_id_in
          and pcf.channel_family_id = cf.id
          and cf.org_id is null;

    begin

        for system_ent in system_ents loop
            update rhnServerGroup
            set max_members = max_members + system_ent.max_members
            where org_id = 1
              and group_type = system_ent.group_type;
        end loop;

        update rhnServerGroup
        set max_members = 0
        where org_id = org_id_in;

        for channel_sub in channel_subs loop
            update rhnPrivateChannelFamily
            set max_members = max_members + channel_sub.max_members
            where org_id = 1
              and channel_family_id = channel_sub.channel_family_id;
        end loop;
        
        update rhnPrivateChannelFamily
        set max_members = 0
        where org_id = org_id_in;

    end remove_org_entitlements;
 
    function entitlement_grants_service (
        entitlement_in in varchar2,
        service_level_in in varchar2
    ) return number    is
    begin
        if service_level_in = 'provisioning' then
            if entitlement_in = 'provisioning_entitled' then
                return 1;
            else
                return 0;
            end if;
        elsif service_level_in = 'management' then
            if entitlement_in = 'enterprise_entitled' then
                return 1;
            else
                return 0;
            end if;
        elsif service_level_in = 'monitoring' then
            if entitlement_in = 'monitoring_entitled' then
                return 1;
            end if;
        elsif service_level_in = 'updates' then
            return 1;
        else
            return 0;
        end if;
    end entitlement_grants_service;

    function lookup_entitlement_group (
        org_id_in in number,
        type_label_in in varchar2 := 'sw_mgr_entitled'
    ) return number is
        cursor server_groups is
            select    sg.id                server_group_id
            from    rhnServerGroup        sg,
                    rhnServerGroupType    sgt
            where    sgt.label = type_label_in
                and sgt.id = sg.group_type
                and sg.org_id = org_id_in;
    begin
        for sg in server_groups loop
            return sg.server_group_id;
        end loop;
        return rhn_entitlements.create_entitlement_group(
                org_id_in,
                type_label_in
            );
    end lookup_entitlement_group;

    function create_entitlement_group (
        org_id_in in number,
        type_label_in in varchar2 := 'sw_mgr_entitled'
    ) return number is
        sg_id_val number;
    begin
        select    rhn_server_group_id_seq.nextval
        into    sg_id_val
        from    dual;

        insert into rhnServerGroup (
                id, name, description, max_members, current_members,
                group_type, org_id
            ) (
                select    sg_id_val, sgt.label, sgt.label,
                        0, 0, sgt.id, org_id_in
                from    rhnServerGroupType sgt
                where    sgt.label = type_label_in
            );

        return sg_id_val;
    end create_entitlement_group;

   function can_entitle_server ( 
        server_id_in in number, 
        type_label_in in varchar2 ) 
   return number is
      cursor addon_servergroups (base_label_in in varchar2, 
                                 addon_label_in in varchar2) is
         select
            addon_id
         from
            rhnSGTypeBaseAddonCompat
         where base_id = lookup_sg_type (base_label_in)
           and addon_id = lookup_sg_type (addon_label_in);

      previous_ent        rhn_entitlements.ents_array;
      is_base_in          char   := 'N';
      is_base_current     char   := 'N';
      i                   number := 0;
      sgid                number := 0;

   begin

      previous_ent := rhn_entitlements.ents_array();
      previous_ent := rhn_entitlements.get_server_entitlement(server_id_in);

      select distinct is_base
      into is_base_in
      from rhnServerGroupType
      where label = type_label_in;

      if previous_ent.count = 0 then
         if (is_base_in = 'Y' and rhn_entitlements.find_compatible_sg (server_id_in, type_label_in, sgid)) then
            -- rhn_server.insert_into_servergroup (server_id_in, sgid);
            return 1;
         else
            -- rhn_exception.raise_exception ('invalid_base_entitlement');
            return 0;
         end if;

      -- there are previous ents, first make sure we're not trying to entitle a base ent
      elsif is_base_in = 'Y' then
         -- rhn_exception.raise_exception ('invalid_addon_entitlement');
         return 0;

      -- it must be an addon, so proceed with the entitlement
      else

         -- find the servers base ent
         is_base_current := 'N';
         i := 0;
         while is_base_current = 'N' and i <= previous_ent.count
         loop
            i := i + 1;
            select is_base
            into is_base_current
            from rhnServerGroupType
            where label = previous_ent(i);
         end loop;

         -- never found a base ent, that would be strange
         if is_base_current  = 'N' then
            -- rhn_exception.raise_exception ('invalid_base_entitlement');
            return 0;
         end if;

         -- this for loop verifies the validity of the addon path
         for addon_servergroup in addon_servergroups  (previous_ent(i), type_label_in) loop
            -- find an appropriate sgid for the addon and entitle the server
            if rhn_entitlements.find_compatible_sg (server_id_in, type_label_in, sgid) then
               -- rhn_server.insert_into_servergroup (server_id_in, sgid);
               return 1;
            else
               -- rhn_exception.raise_exception ('invalid_addon_entitlement');
               return 0;
            end if;
         end loop;

      end if;

      return 0;

   end can_entitle_server;

   function can_switch_base (
      server_id_in   in    integer,
      type_label_in  in    varchar2
   ) return number is

      type_label_in_is_base   char(1);
      sgid                    number;

   begin

      begin
         select is_base into type_label_in_is_base
         from rhnServerGroupType
         where label = type_label_in;
      exception
         when no_data_found then
            rhn_exception.raise_exception ( 'invalid_entitlement' );
      end;

      if type_label_in_is_base = 'N' then
         rhn_exception.raise_exception ( 'invalid_entitlement' );
      elsif rhn_entitlements.find_compatible_sg ( server_id_in, 
                                                  type_label_in, sgid ) then
         return 1;
      else
         return 0;
      end if;

   end can_switch_base;


   function find_compatible_sg (
      server_id_in    in   number,
      type_label_in   in   varchar2,
      sgid_out        out  number
   ) return boolean is

      cursor servergroups is
         select sg.id            id
           from rhnServerGroupType             sgt,
                rhnServerGroup                 sg,
                rhnServer                     s,
                rhnServerServerGroupArchCompat ssgac
          where s.id = server_id_in
            and s.org_id = sg.org_id
            and sgt.label = type_label_in
            and sg.group_type = sgt.id
            and ssgac.server_group_type = sgt.id
            and ssgac.server_arch_id = s.server_arch_id
            and not exists ( 
                     select 1
                      from rhnServerGroupMembers sgm
                     where sgm.server_group_id = sg.id 
                       and sgm.server_id = s.id);

         
   begin
      for servergroup in servergroups loop
         sgid_out := servergroup.id;
         return true;      
      end loop;

      --no servergroup found
      sgid_out := 0;
      return false;
   end find_compatible_sg;

    procedure entitle_server (
        server_id_in in number,
        type_label_in in varchar2 := 'sw_mgr_entitled'
    ) is
      sgid  number := 0;
      is_virt number := 0;

    begin

          begin
          select 1 into is_virt
            from rhnServerEntitlementView
           where server_id = server_id_in
             and label in ('virtualization_host', 'virtualization_host_platform');
      exception
            when no_data_found then
              is_virt := 0;
          end;
      
      if is_virt = 0 and (type_label_in = 'virtualization_host' or
                          type_label_in = 'virtualization_host_platform') then

        is_virt := 1;
      end if;



      if rhn_entitlements.can_entitle_server(server_id_in, 
                                             type_label_in) = 1 then
         if rhn_entitlements.find_compatible_sg (server_id_in, 
                                                 type_label_in, sgid) then
            insert into rhnServerHistory ( id, server_id, summary, details )
            values ( rhn_event_id_seq.nextval, server_id_in,
                     'added system entitlement ',
                      case type_label_in
                       when 'enterprise_entitled' then 'Management'
                       when 'sw_mgr_entitled' then 'Update'
                       when 'provisioning_entitled' then 'Provisioning'
                       when 'monitoring_entitled' then 'Monitoring'  
                       when 'virtualization_host' then 'Virtualization'
                       when 'virtualization_host_platform' then 
                            'Virtualization Platform' end  );

            rhn_server.insert_into_servergroup (server_id_in, sgid);

            if is_virt = 1 then
              rhn_entitlements.repoll_virt_guest_entitlements(server_id_in);
            end if;

         else
            rhn_exception.raise_exception ('no_available_server_group');
         end if;
      else
         rhn_exception.raise_exception ('invalid_entitlement');
      end if;
   end entitle_server;

    procedure remove_server_entitlement (
        server_id_in in number,
        type_label_in in varchar2 := 'sw_mgr_entitled',
        repoll_virt_guests in number := 1
    ) is
        group_id number;
      type_is_base char;
      is_virt number := 0;
    begin
      begin


      -- would be nice if there were a virt attribute of entitlement types, not have to specify 2 different ones...
        begin
          select 1 into is_virt
            from rhnServerEntitlementView
           where server_id = server_id_in
             and label in ('virtualization_host', 'virtualization_host_platform');
        exception
          when no_data_found then
            is_virt := 0;
        end;

        select    sg.id, sgt.is_base
          into    group_id, type_is_base
          from    rhnServerGroupType sgt,
               rhnServerGroup sg,
                  rhnServerGroupMembers sgm,
                  rhnServer s
          where    s.id = server_id_in
              and s.id = sgm.server_id
              and sgm.server_group_id = sg.id
              and sg.org_id = s.org_id
              and sgt.label = type_label_in
              and sgt.id = sg.group_type;

      if ( type_is_base = 'Y' ) then
         -- unentitle_server should handle everything, don't really need to do anything else special here
         unentitle_server ( server_id_in );
      else

         insert into rhnServerHistory ( id, server_id, summary, details )
         values ( rhn_event_id_seq.nextval, server_id_in,
                  'removed system entitlement ',
                   case type_label_in
                    when 'enterprise_entitled' then 'Management'
                    when 'sw_mgr_entitled' then 'Update'
                    when 'provisioning_entitled' then 'Provisioning'
                    when 'monitoring_entitled' then 'Monitoring'
                    when 'virtualization_host' then 'Virtualization'
                    when 'virtualization_host_platform' then 
                         'Virtualization Platforrm' end  );

         rhn_server.delete_from_servergroup(server_id_in, group_id);

         -- special case: clean up related monitornig data
         if type_label_in = 'monitoring_entitled' then
           DELETE
             FROM state_change
            WHERE o_id IN (SELECT probe_id
                             FROM rhn_check_probe
                            WHERE host_id = server_id_in);
           DELETE /*+index(time_series time_series_probe_id_idx)*/
             FROM time_series
            WHERE SUBSTR(o_id, INSTR(o_id, '-') + 1, 
                        (INSTR(o_id, '-', INSTR(o_id, '-') + 1) - INSTR(o_id, '-')) - 1)
              IN (SELECT to_char(probe_id)
                    FROM rhn_check_probe
                   WHERE host_id = server_id_in);
           DELETE
             FROM rhn_probe
            WHERE recid IN (SELECT probe_id
                              FROM rhn_check_probe
                             WHERE host_id = server_id_in);
         end if;

         if is_virt = 1 and repoll_virt_guests = 1 then
           rhn_entitlements.repoll_virt_guest_entitlements(server_id_in);
         end if;
      end if;

          exception
          when no_data_found then
                  rhn_exception.raise_exception('invalid_server_group_member');
      end;

     end remove_server_entitlement;


   procedure unentitle_server (server_id_in in number) is

      cursor servergroups is
         select distinct sgt.label, sg.id server_group_id
         from  rhnServerGroupType sgt,
               rhnServerGroup sg,
               rhnServer s,
               rhnServerGroupMembers sgm
         where s.id = server_id_in
            and s.org_id = sg.org_id
            and sg.group_type = sgt.id
            and sgm.server_group_id = sg.id
            and sgm.server_id = s.id;
            
     is_virt number := 0;

   begin

      begin
        select 1 into is_virt
          from rhnServerEntitlementView
         where server_id = server_id_in
           and label in ('virtualization_host', 'virtualization_host_platform');
      exception
        when no_data_found then
          is_virt := 0;
      end;

      for servergroup in servergroups loop

         insert into rhnServerHistory ( id, server_id, summary, details )
         values ( rhn_event_id_seq.nextval, server_id_in,
                  'removed system entitlement ',
                   case servergroup.label
                    when 'enterprise_entitled' then 'Management'
                    when 'sw_mgr_entitled' then 'Update'
                    when 'provisioning_entitled' then 'Provisioning'
                    when 'monitoring_entitled' then 'Monitoring'
                    when 'virtualization_host' then 'Virtualization'
                    when 'virtualization_host_platform' then 
                         'Virtualization Platform' end  );
  
         rhn_server.delete_from_servergroup(server_id_in, 
                                            servergroup.server_group_id );
      end loop;

      if is_virt = 1 then
        rhn_entitlements.repoll_virt_guest_entitlements(server_id_in);
      end if;

   end unentitle_server;


    -- *******************************************************************
    -- PROCEDURE: repoll_virt_guest_entitlements
    --
    --   Whenever we add/remove a virtualization_host* entitlement from 
    --   a host, we can call this procedure to update what type of slots
    --   the guests are consuming.  
    -- 
    --   If you're removing the entitlement, it's 
    --   possible the guests will become unentitled if you don't have enough
    --   physical slots to cover them.
    --
    --   If you're adding the entitlement, you end up freeing up physical
    --   slots for other systems.
    --
    -- *******************************************************************
    procedure repoll_virt_guest_entitlements(server_id_in in number)
    is

        -- All channel families associated with the guests of server_id_in
        cursor families is 
            select distinct cfs.channel_family_id
            from
                rhnChannelFamilyServers cfs,
                rhnVirtualInstance vi
            where
                vi.host_system_id = server_id_in
                and vi.virtual_system_id = cfs.server_id;
        
        -- All of server group types associated with the guests of
        -- server_id_in
        cursor group_types is
            select distinct sg.group_type, sgt.label
            from
                rhnServerGroupType sgt,
                rhnServerGroup sg,
                rhnServerGroupMembers sgm,
                rhnVirtualInstance vi
            where
                vi.host_system_id = server_id_in
                and vi.virtual_system_id = sgm.server_id
                and sgm.server_group_id = sg.id
                and sg.group_type = sgt.id;

        -- Virtual servers from a certain family belonging to a speicifc
        -- host that are consuming physical channel slots over the limit.
        cursor virt_servers_cfam(family_id_in in number, quantity_in in number)  is
            select virtual_system_id
            from (
                select rownum, vi.virtual_system_id
                from
                    rhnChannelFamilyMembers cfm,
                    rhnServerChannel sc,
                    rhnVirtualInstance vi
                where
                    vi.host_system_id = server_id_in
                    and vi.virtual_system_id = sc.server_id
                    and sc.channel_id = cfm.channel_id
                    and cfm.channel_family_id = family_id_in
                order by sc.modified desc
                )
            where rownum <= quantity_in;

        -- Virtual servers from a certain family belonging to a speicifc
        -- host that are consuming physical system slots over the limit.
        cursor virt_servers_sgt(group_type_in in number, quantity_in in number)  is
            select virtual_system_id
            from (
                select rownum, vi.virtual_system_id
                from
                    rhnServerGroup sg,
                    rhnServerGroupMembers sgm,
                    rhnVirtualInstance vi
                where
                    vi.host_system_id = server_id_in
                    and vi.virtual_system_id = sgm.server_id
                    and sgm.server_group_id = sg.id
                    and sg.group_type = group_type_in
                order by sgm.modified desc
                )
            where rownum <= quantity_in;
        -- Get the orgs of Virtual guests
        -- Since they may belong to different orgs
        cursor virt_guest_orgs  is
                select  distinct (s.org_id)
                from rhnServer s
                    inner join  rhnVirtualInstance vi on vi.virtual_system_id = s.id
                where
                    vi.host_system_id = server_id_in 
                    and s.org_id <> (select s1.org_id from rhnServer s1 where s1.id = vi.host_system_id) ;


        org_id_val number;
        max_members_val number;
        max_flex_val number;
        current_members_calc number;
        sg_id number;
        is_virt number := 0;
    begin
        begin
          select 1 into is_virt
                from rhnServerEntitlementView
           where server_id = server_id_in
                 and label in ('virtualization_host', 'virtualization_host_platform');
           exception
                when no_data_found then
                  is_virt := 0;
        end;

        select org_id
        into org_id_val
        from rhnServer
        where id = server_id_in;

        -- deal w/ channel entitlements first ...
        for family in families loop
            if is_virt = 0 then
            -- if the host_server does not have virt
            --- find all possible flex slots
            -- and set each of the flex eligible guests to Y
                UPDATE rhnServerChannel sc set sc.is_fve = 'Y'
                where sc.server_id in (
                       select virtual_system_id from (
                            select rownum, vi.virtual_system_id,  sfc.max_members - sfc.current_members as free_slots
                            from rhnServerFveCapable sfc
                                inner join rhnVirtualInstance vi on vi.virtual_system_id = sfc.server_id
                            where vi.host_system_id = server_id_in
                                  and sfc.channel_family_id = family.channel_family_id
                              order by vi.modified desc
                          )
                        where rownum <=  free_slots
                );
            else
            -- if the host_server has virt
            -- set all its flex guests to N
                UPDATE rhnServerChannel sc set sc.is_fve = 'N'
                where 
                    sc.channel_id in (select cfm.channel_id from rhnChannelFamilyMembers cfm
                                      where cfm.CHANNEL_FAMILY_ID = family.channel_family_id)
                    and sc.is_fve = 'Y'
                    and sc.server_id in  
                            (select vi.virtual_system_id  from rhnVirtualInstance vi 
                                    where vi.host_system_id = server_id_in);
            end if;
        
            -- get the current (physical) members of the family
            current_members_calc := 
                rhn_channel.channel_family_current_members(family.channel_family_id,
                                                           org_id_val); -- fixed transposed args

            -- get the max members of the family
            select max_members
            into max_members_val
            from rhnPrivateChannelFamily
            where channel_family_id = family.channel_family_id
            and org_id = org_id_val;

            select fve_max_members
            into max_flex_val
            from rhnPrivateChannelFamily
            where channel_family_id = family.channel_family_id
            and org_id = org_id_val;

            if current_members_calc > max_members_val then
                -- A virtualization_host* ent must have been removed, so we'll
                -- unsubscribe guests from the host first.

                -- hm, i don't think max_members - current_members_calc yielding a negative number
                -- will work w/ rownum, swaping 'em in the body of this if...
                for virt_server in virt_servers_cfam(family.channel_family_id,
                                current_members_calc - max_members_val) loop 

                    rhn_channel.unsubscribe_server_from_family(
                                virt_server.virtual_system_id,
                                family.channel_family_id);
                end loop;                               

                -- if we're still over the limit, which would be odd,
                -- just prune the group to max_members
                --
                -- er... wouldn't we actually have to refresh the values of
                -- current_members_calc and max_members_val to actually ever
                -- *skip this??
                if current_members_calc > max_members_val then
                    -- argh, transposed again?!
                    set_family_count(org_id_val,
                                     family.channel_family_id,
                                     max_members_val, max_flex_val);
                    --TODO calculate this correctly
                end if; 

           end if;

            -- update current_members for the family.  This will set the value
            -- to reflect adding/removing the entitlement.
            --
            -- what's the difference of doing this vs the unavoidable set_family_count above?
            rhn_channel.update_family_counts(family.channel_family_id,
                                             org_id_val);

            -- It is possible that the guests belong  to a different org than the host
            -- so we are going to update the family counts in the guests orgs also
            for org in virt_guest_orgs loop
                    rhn_channel.update_family_counts(family.channel_family_id,
                                             org.org_id);
            end loop;
        end loop;

        for a_group_type in group_types loop
          -- get the current *physical* members of the system entitlement type for the org...
          -- 
          -- unlike channel families, it appears the standard rhnServerGroup.max_members represents
          -- *physical* slots, vs physical+virt ... boy that's confusing...

          select max_members, id
            into max_members_val, sg_id
            from rhnServerGroup
            where group_type = a_group_type.group_type
            and org_id = org_id_val;


      select count(sep.server_id) into current_members_calc
            from rhnServerEntitlementPhysical sep
           where sep.server_group_id = sg_id
             and sep.server_group_type_id = a_group_type.group_type;
          
          if current_members_calc > max_members_val then
            -- A virtualization_host* ent must have been removed, and we're over the limit, so unsubscribe guests
            for virt_server in virt_servers_sgt(a_group_type.group_type,
                                                current_members_calc - max_members_val) loop
              rhn_entitlements.remove_server_entitlement(virt_server.virtual_system_id, a_group_type.label);

              -- decrement current_members_calc, we'll use it to reset current_members for the group at the end...
              current_members_calc := current_members_calc - 1;
            end loop;

          end if;

          update rhnServerGroup set current_members = current_members_calc
           where org_id = org_id_val
             and group_type = a_group_type.group_type;

          -- I think that's all the house-keeping we have to do...
        end loop;

    end repoll_virt_guest_entitlements;


    function get_server_entitlement (
        server_id_in in number
    ) return ents_array is

        cursor server_groups is
            select    sgt.label
            from    rhnServerGroupType        sgt,
                    rhnServerGroup            sg,
                    rhnServerGroupMembers    sgm
            where    1=1
                and sgm.server_id = server_id_in
                and sg.id = sgm.server_group_id
                and sgt.id = sg.group_type
                and sgt.label in (
                    'sw_mgr_entitled','enterprise_entitled',
                    'provisioning_entitled', 'nonlinux_entitled',
                    'monitoring_entitled', 'virtualization_host',
                                        'virtualization_host_platform'
                    );

         ent_array ents_array;

    begin
      
      ent_array := ents_array();

        for sg in server_groups loop
         ent_array.extend;
         ent_array(ent_array.count) := sg.label;
        end loop;

        return ent_array;

    end get_server_entitlement;


    -- this desperately needs to be table driven.
    procedure modify_org_service (
        org_id_in in number,
        service_label_in in varchar2,
        enable_in in char
    ) is
        type roles_v is varray(10) of rhnUserGroupType.label%TYPE;
        roles_to_process roles_v;
        cursor roles(role_label_in in varchar2) is
            select    label, id
            from    rhnUserGroupType
            where    label = role_label_in;
        cursor org_roles(role_label_in in varchar2) is
            select    1
            from    rhnUserGroup ug,
                    rhnUserGroupType ugt
            where    ugt.label = role_label_in
                and ug.org_id = org_id_in
                and ugt.id = ug.group_type;

        type ents_v is varray(10) of rhnOrgEntitlementType.label%TYPE;
        ents_to_process ents_v;
        cursor ents(ent_label_in in varchar2) is
            select    label, id
            from    rhnOrgEntitlementType
            where    label = ent_label_in;
        cursor org_ents(ent_label_in in varchar2) is
            select    1
            from    rhnOrgEntitlements oe,
                    rhnOrgEntitlementType oet
            where    oet.label = ent_label_in
                and oe.org_id = org_id_in
                and oet.id = oe.entitlement_id;
        create_row char(1);
    begin
        ents_to_process := ents_v();
        roles_to_process := roles_v();
        -- a bit kludgy, but only for 3.4 really.  Certainly no
        -- worse than the old code...
        if service_label_in = 'enterprise' or
           service_label_in = 'management' then
            ents_to_process.extend;
            ents_to_process(ents_to_process.count) := 'sw_mgr_enterprise';

            roles_to_process.extend;
            roles_to_process(roles_to_process.count) := 'org_admin';

            roles_to_process.extend;
            roles_to_process(roles_to_process.count) := 'system_group_admin';

            roles_to_process.extend;
            roles_to_process(roles_to_process.count) := 'activation_key_admin';

            roles_to_process.extend;
            roles_to_process(roles_to_process.count) := 'org_applicant';
        elsif service_label_in = 'provisioning' then
            ents_to_process.extend;
            ents_to_process(ents_to_process.count) := 'rhn_provisioning';

            roles_to_process.extend;
            roles_to_process(roles_to_process.count) := 'system_group_admin';

            roles_to_process.extend;
            roles_to_process(roles_to_process.count) := 'activation_key_admin';

            roles_to_process.extend;
            roles_to_process(roles_to_process.count) := 'config_admin';
            -- another nasty special case...
            if enable_in = 'Y' then
                ents_to_process.extend;
                ents_to_process(ents_to_process.count) := 'sw_mgr_enterprise';
            end if;
        elsif service_label_in = 'monitoring' then
            ents_to_process.extend;
            ents_to_process(ents_to_process.count) := 'rhn_monitor';

            roles_to_process.extend;
            roles_to_process(roles_to_process.count) := 'monitoring_admin';
        elsif service_label_in = 'virtualization' then
            ents_to_process.extend;
            ents_to_process(ents_to_process.count) := 'rhn_virtualization';

            roles_to_process.extend;
            roles_to_process(roles_to_process.count) := 'config_admin';
        elsif service_label_in = 'virtualization_platform' then
            ents_to_process.extend;
            ents_to_process(ents_to_process.count) := 'rhn_virtualization_platform';
            roles_to_process.extend;
            roles_to_process(roles_to_process.count) := 'config_admin';
    elsif service_label_in = 'nonlinux' then
            ents_to_process.extend;
            ents_to_process(ents_to_process.count) := 'rhn_nonlinux';
            roles_to_process.extend;
            roles_to_process(roles_to_process.count) := 'config_admin';
        end if;

        if enable_in = 'Y' then
            for i in 1..ents_to_process.count loop
                for ent in ents(ents_to_process(i)) loop
                    create_row := 'Y';
                    for oe in org_ents(ent.label) loop
                        create_row := 'N';
                    end loop;
                    if create_row = 'Y' then
                        insert into rhnOrgEntitlements(org_id, entitlement_id)
                            values (org_id_in, ent.id);
                    end if;
                end loop;
            end loop;
            for i in 1..roles_to_process.count loop
                for role in roles(roles_to_process(i)) loop
                    create_row := 'Y';
                    for o_r in org_roles(role.label) loop
                        create_row := 'N';
                    end loop;
                    if create_row = 'Y' then
                        insert into rhnUserGroup(
                                id, name, description, current_members,
                                group_type, org_id
                            ) (
                                select    rhn_user_group_id_seq.nextval,
                                        ugt.name || 's',
                                        ugt.name || 's for Org ' ||
                                            o.name || ' ('|| o.id ||')',
                                        0, ugt.id, o.id
                                from    rhnUserGroupType ugt,
                                        web_customer o
                                where    o.id = org_id_in
                                    and ugt.id = role.id
                            );
                    end if;
                end loop;
            end loop;
        else
            for i in 1..ents_to_process.count loop
                for ent in ents(ents_to_process(i)) loop
                    delete from rhnOrgEntitlements
                     where org_id = org_id_in
                       and entitlement_id = ent.id;
                end loop;
            end loop;
        end if;
    end modify_org_service;

    procedure set_customer_enterprise (
        customer_id_in in number
    ) is
    begin
        modify_org_service(customer_id_in, 'enterprise', 'Y');
    end set_customer_enterprise;

    procedure set_customer_provisioning (
        customer_id_in in number
    ) is
    begin
        modify_org_service(customer_id_in, 'provisioning', 'Y');
    end set_customer_provisioning;

    procedure set_customer_monitoring (
        customer_id_in in number
    ) is
    begin
        modify_org_service(customer_id_in, 'monitoring', 'Y');
    end set_customer_monitoring;

    procedure set_customer_nonlinux (
        customer_id_in in number
    ) is
    begin
        modify_org_service(customer_id_in, 'nonlinux', 'Y');
    end set_customer_nonlinux;

    procedure unset_customer_enterprise (
        customer_id_in in number
    ) is
    begin
        modify_org_service(customer_id_in, 'enterprise', 'N');
    end unset_customer_enterprise;

    procedure unset_customer_provisioning (
        customer_id_in in number
    ) is
    begin
        modify_org_service(customer_id_in, 'provisioning', 'N');
    end unset_customer_provisioning;

    procedure unset_customer_monitoring (
        customer_id_in in number
    ) is
    begin
        modify_org_service(customer_id_in, 'monitoring', 'N');
    end unset_customer_monitoring;

    procedure unset_customer_nonlinux (
        customer_id_in in number
    ) is
    begin
        modify_org_service(customer_id_in, 'nonlinux', 'N');
    end unset_customer_nonlinux;

    -- *******************************************************************
    -- PROCEDURE: prune_group
    -- Unsubscribes servers consuming physical slots that over the org's
    --   limit.
    -- Called by: set_group_count, prune_everything, repoll_virt_guest_entitlements
    -- *******************************************************************
    procedure prune_group (
        group_id_in in number,
        type_in in char,
        quantity_in in number,
                update_family_countsYN in number := 1
    ) is
        cursor usergroups is
            select    user_id, user_group_id, ugt.label
            from    rhnUserGroupType    ugt,
                    rhnUserGroup        ug,
                    rhnUserGroupMembers    ugm
            where    1=1
                and ugm.user_group_id = group_id_in
                and ugm.user_id in (
                    select    user_id
                    from    (
                        select    rownum row_number,
                                user_id,
                                time
                        from    (
                            select    user_id,
                                    modified time
                            from    rhnUserGroupMembers
                            where    user_group_id = group_id_in
                            order by time asc
                        )
                    )
                    where    row_number > quantity_in
                )
                and ugm.user_group_id = ug.id
                and ug.group_type = ugt.id;
        cursor servergroups is
           select  server_id, server_group_id, sgt.id as group_type_id, sgt.label
            from    rhnServerGroupType              sgt,
                            rhnServerGroup                  sg,
                            rhnServerGroupMembers   sgm
            where   1=1
                    and sgm.server_group_id = group_id_in
                    and sgm.server_id in (
                            select  server_id
                            from    (
                                    select  rownum row_number,
                                                    server_id,
                                                    time
                                    from    (
                                            select  sep.server_id,
                                                    sep.modified time
                                            from
                                                rhnServerEntitlementPhysical sep
                                            where
                                                sep.server_group_id = group_id_in
                                            order by time asc
                                    )
                            )
                            where   row_number > quantity_in
                    )
                    and sgm.server_group_id = sg.id
                    and sg.group_type = sgt.id;
      type_is_base char;
    begin
        if type_in = 'U' then
            update        rhnUserGroup
                set        max_members = quantity_in
                where    id = group_id_in;

            for ug in usergroups loop
                rhn_user.remove_from_usergroup(ug.user_id, ug.user_group_id);
            end loop;
        elsif type_in = 'S' then
            update        rhnServerGroup
                set        max_members = quantity_in
                where    id = group_id_in;

            for sg in servergroups loop
                remove_server_entitlement(sg.server_id, sg.label);
            
            select is_base 
            into type_is_base
            from rhnServerGroupType sgt
            where sgt.id = sg.group_type_id;
 
            -- if we're removing a base ent, then be sure to
            -- remove the server's channel subscriptions.
            if ( type_is_base = 'Y' ) then
                   rhn_channel.clear_subscriptions(sg.server_id,
                                        update_family_countsYN => update_family_countsYN);
            end if;

            end loop;
        end if;
    end prune_group;

    -- *******************************************************************
    -- PROCEDURE: assign_system_entitlement
    --
    -- Moves system entitlements from from_org_id_in to to_org_id_in.
    -- Can raise not_enough_entitlements_in_base_org if from_org_id_in
    -- does not have enough entitlements to cover the move.
    -- Takes care of unentitling systems if necessary by calling 
    -- set_group_count
    -- *******************************************************************
    procedure assign_system_entitlement(
        group_label_in in varchar2,
        from_org_id_in in number,
        to_org_id_in in number,
        quantity_in in number
    )
    is
        prev_ent_count number;
    to_org_prev_ent_count number;
        new_ent_count number;
    new_quantity number;
        group_type number;
    begin

        begin
            select max_members
            into prev_ent_count
            from rhnServerGroupType sgt,
                 rhnServerGroup sg
            where sg.org_id = from_org_id_in
              and sg.group_type = sgt.id
              and sgt.label = group_label_in;
        exception
            when NO_DATA_FOUND then
                rhn_exception.raise_exception(
                              'not_enough_entitlements_in_base_org');
        end;

        begin
            select max_members
            into to_org_prev_ent_count
            from rhnServerGroupType sgt,
                 rhnServerGroup sg
            where sg.org_id = to_org_id_in
              and sg.group_type = sgt.id
              and sgt.label = group_label_in;
        exception
            when NO_DATA_FOUND then
                to_org_prev_ent_count := 0;
        end;

        begin
            select id
            into group_type
            from rhnServerGroupType
            where label = group_label_in;
        exception
            when NO_DATA_FOUND then
                rhn_exception.raise_exception(
                              'invalid_server_group');
        end;

        new_ent_count := prev_ent_count - quantity_in;

        if prev_ent_count > new_ent_count then
            new_quantity := to_org_prev_ent_count + quantity_in;
        end if;

        if new_ent_count < 0 then
            rhn_exception.raise_exception(
                          'not_enough_entitlements_in_base_org');
        end if;


        rhn_entitlements.set_group_count(from_org_id_in,
                                         'S',
                                         group_type,
                                         new_ent_count);

        rhn_entitlements.set_group_count(to_org_id_in,
                                         'S',
                                         group_type,
                                         new_quantity);
        
        -- Create or delete the entries in rhnOrgEntitlementType
        if group_label_in = 'enterprise_entitled' then 
            if new_quantity > 0 then
                set_customer_enterprise(to_org_id_in);
            else
                unset_customer_enterprise(to_org_id_in);
            end if;
        end if;

        if group_label_in = 'provisioning_entitled' then
            if new_quantity > 0 then
                set_customer_provisioning(to_org_id_in);
            else
                unset_customer_provisioning(to_org_id_in);
            end if;
        end if;

        if group_label_in = 'monitoring_entitled' then
            if new_quantity > 0 then
                set_customer_monitoring(to_org_id_in);
            else
                unset_customer_monitoring(to_org_id_in);
            end if;
        end if;

    end assign_system_entitlement;

    -- *******************************************************************
    -- PROCEDURE: assign_channel_entitlement
    --
    -- Moves channel entitlements from from_org_id_in to to_org_id_in.
    -- Can raise not_enough_entitlements_in_base_org if from_org_id_in
    -- does not have enough entitlements to cover the move.
    -- Takes care of unentitling systems if necessary by calling 
    -- set_family_count
    -- *******************************************************************
    procedure assign_channel_entitlement(
        channel_family_label_in in varchar2,
        from_org_id_in in number,
        to_org_id_in in number,
        quantity_in in number,
        flex_in in number
    )
    is
        from_org_prev_ent_count number;
        from_org_prev_ent_count_flex number;
        new_ent_count number;
        new_ent_count_flex number;
        to_org_prev_ent_count number;
        to_org_prev_ent_count_flex number;
        new_quantity number;
        new_flex number;
        cfam_id       number;
    begin

        begin
            select max_members
            into from_org_prev_ent_count
            from rhnChannelFamily cf,
                 rhnPrivateChannelFamily pcf
            where pcf.org_id = from_org_id_in
              and pcf.channel_family_id = cf.id
              and cf.label = channel_family_label_in;
        exception
            when NO_DATA_FOUND then
                rhn_exception.raise_exception(
                              'not_enough_entitlements_in_base_org');
        end;

        begin
            select max_members
            into to_org_prev_ent_count
            from rhnChannelFamily cf,
                 rhnPrivateChannelFamily pcf
            where pcf.org_id = to_org_id_in
              and pcf.channel_family_id = cf.id
              and cf.label = channel_family_label_in;
        exception
            when NO_DATA_FOUND then
                to_org_prev_ent_count := 0;
        end;

        begin
            select fve_max_members
            into from_org_prev_ent_count_flex
            from rhnChannelFamily cf,
                 rhnPrivateChannelFamily pcf
            where pcf.org_id = from_org_id_in
              and pcf.channel_family_id = cf.id
              and cf.label = channel_family_label_in;
        exception
            when NO_DATA_FOUND then
                rhn_exception.raise_exception(
                              'not_enough_flex_entitlements_in_base_org');
        end;

        begin
            select fve_max_members
            into to_org_prev_ent_count_flex
            from rhnChannelFamily cf,
                 rhnPrivateChannelFamily pcf
            where pcf.org_id = to_org_id_in
              and pcf.channel_family_id = cf.id
              and cf.label = channel_family_label_in;
        exception
            when NO_DATA_FOUND then
                to_org_prev_ent_count_flex := 0;
        end;

        begin
            select id
            into cfam_id
            from rhnChannelFamily
            where label = channel_family_label_in;
        exception
            when NO_DATA_FOUND then
                rhn_exception.raise_exception(
                              'invalid_channel_family');
        end;

        new_ent_count := from_org_prev_ent_count - quantity_in;
        new_ent_count_flex := from_org_prev_ent_count_flex - flex_in;

        if from_org_prev_ent_count >= new_ent_count then
            new_quantity := to_org_prev_ent_count + quantity_in;
       end if;

       if from_org_prev_ent_count_flex >= new_ent_count_flex then
            new_flex := to_org_prev_ent_count_flex + flex_in;
       end if;


        if new_ent_count < 0 then
            rhn_exception.raise_exception(
                          'not_enough_entitlements_in_base_org');
        end if;

        if new_ent_count_flex < 0 then
            rhn_exception.raise_exception(
                          'not_enough_flex_entitlements_in_base_org');
        end if;



        rhn_entitlements.set_family_count(from_org_id_in, cfam_id,
                                           new_ent_count, new_ent_count_flex);

        rhn_entitlements.set_family_count(to_org_id_in,
                                          cfam_id,
                                          new_quantity, new_flex);

    end assign_channel_entitlement;

    -- *******************************************************************
    -- PROCEDURE: activate_system_entitlement
    --
    -- Sets the values in rhnServerGroup for a given rhnServerGroupType.
    -- 
    -- Calls: set_group_count to update, prune, or create the group.
    -- Called by: the code that activates a satellite cert. 
    --
    -- Raises not_enough_entitlements_in_base_org if all entitlements
    -- in the org are used so the free entitlements would not cover
    -- the difference when descreasing the number of entitlements.
    -- *******************************************************************
    procedure activate_system_entitlement(
        org_id_in in number,
        group_label_in in varchar2,
        quantity_in in number
    )
    is
        prev_ent_count number; 
        prev_ent_count_sum number; 
        group_type number;
    begin

        -- Fetch the current entitlement count for the org
        -- into prev_ent_count
        begin
            select current_members
            into prev_ent_count
            from rhnServerGroupType sgt,
                 rhnServerGroup sg
            where sg.group_type = sgt.id
              and sgt.label = group_label_in
              and sg.org_id = org_id_in;
        exception
            when NO_DATA_FOUND then
                prev_ent_count := 0;
        end;

        begin
            select id
            into group_type
            from rhnServerGroupType
            where label = group_label_in;
        exception
            when NO_DATA_FOUND then
                rhn_exception.raise_exception(
                              'invalid_server_group');
        end;

        -- If we're setting the total entitlemnt count to a lower value,
        -- and that value is less than the allocated count in this org,
        -- we need to raise an exception.
        if quantity_in < prev_ent_count then
            rhn_exception.raise_exception(
                          'not_enough_entitlements_in_base_org');
        else
            -- don't update family counts after every server
            -- will do bulk update afterwards
            rhn_entitlements.set_group_count(org_id_in,
                                             'S',
                                             group_type,
                                             quantity_in,
                                             update_family_countsYN => 0);
            -- bulk update family counts
            rhn_channel.update_group_family_counts(group_label_in, org_id_in);
        end if;


    end activate_system_entitlement;

    -- *******************************************************************
    -- PROCEDURE: activate_channel_entitlement
    --
    -- Calls: set_family_count to update, prune, or create the family
    --        permission bucket.
    -- Called by: the code that activates a satellite cert. 
    --
    -- Raises not_enough_entitlements_in_base_org if there are not enough
    -- entitlements in the org to cover the difference when you are
    -- descreasing the number of entitlements.
    --
    -- The backend code in Python is expected to do whatever arithmetics
    -- is needed.
    -- *******************************************************************
    procedure activate_channel_entitlement(
        org_id_in in number,
        channel_family_label_in in varchar2,
        quantity_in in number,
        flex_in in number

    )
    is
        prev_ent_count number; 
        prev_flex_count number;
        prev_ent_count_sum number; 
        cfam_id number;
        reduce_quantity number;
        total_flex_capable number;
        cursor to_convert_reg (channel_family_id_val in number, org_id_in in number, quantity in number) 
                is
                     select SC.server_id
                     from rhnServerChannel SC inner join
                          rhnServer S on S.id = SC.server_id
                     where
                         is_fve = 'Y'
                         and S.org_id = org_id_in 
                         and SC.channel_id in
                         (select cfm.channel_id from rhnChannelFamilyMembers cfm
                             where cfm.CHANNEL_FAMILY_ID = channel_family_id_val)
                          and rownum <= quantity;
         cursor to_convert_flex (channel_family_id_val in number, org_id_in in number, quantity in number)
                 is
                   select server_id
                   from rhnServerFveCapable
                       where SERVER_ORG_ID = org_id_in and
                             channel_family_id = cfam_id;

    begin

        -- Fetch the current entitlement count for the org
        -- into prev_ent_count
        begin
            select current_members
            into prev_ent_count
            from rhnChannelFamily cf,
                 rhnPrivateChannelFamily pcf
            where pcf.org_id = org_id_in
              and pcf.channel_family_id = cf.id
              and cf.label = channel_family_label_in;
        exception
            when NO_DATA_FOUND then
                prev_ent_count := 0;
        end;

        begin
            select pcf.fve_current_members
            into prev_flex_count
            from rhnChannelFamily cf,
                 rhnPrivateChannelFamily pcf
            where pcf.org_id = org_id_in
              and pcf.channel_family_id = cf.id
              and cf.label = channel_family_label_in;
        exception
            when NO_DATA_FOUND then
                prev_flex_count := 0;
        end;


        begin
            select id
            into cfam_id
            from rhnChannelFamily
            where label = channel_family_label_in;
        exception
            when NO_DATA_FOUND then
                rhn_exception.raise_exception(
                              'invalid_channel_family');
        end;                              

        -- if there are too few flex entitlements
        if flex_in < prev_flex_count then
            -- and if the extra we need is less than or equal to our extra regular entitlements
            if prev_flex_count - flex_in <= quantity_in - prev_ent_count then
                   reduce_quantity := prev_flex_count - flex_in;
                   -- We need to convert some systems from flex guest to regular
                   for system in to_convert_reg(cfam_id, org_id_in, reduce_quantity) loop
                      --rhn_channel.convert_to_regular(system.server_id, cfam_id);
                      UPDATE rhnServerChannel sc set sc.is_fve = 'N'
                           where sc.server_id = system.server_id;
                   end loop;

                   --reset previous counts 
                   prev_ent_count := prev_ent_count + reduce_quantity;
                   prev_flex_count := prev_flex_count - reduce_quantity; 
            else
                rhn_exception.raise_exception(
                          'not_enough_flex_entitlements_in_base_org');
            end if;
        end if;

        -- if there are too few regular entitlements, and extra flex entitlements
        if quantity_in < prev_ent_count and prev_flex_count < flex_in then
                -- how many flex-capable systems (that aren't using flex) do we have
                select count(*)
                   into total_flex_capable 
                   from rhnServerFveCapable
                       where SERVER_ORG_ID = org_id_in and
                             channel_family_id = cfam_id;
                -- if we have enough flex capable machines that is at least 
                --   as many as what we are over on 
                if total_flex_capable >= prev_ent_count - quantity_in then
                    reduce_quantity := prev_ent_count - quantity_in;
                    for system in to_convert_flex(cfam_id, org_id_in, reduce_quantity) loop 
--                          rhn_channel.convert_to_fve(system.server_id, cfam_id);
                        UPDATE rhnServerChannel sc set sc.is_fve = 'Y'
                           where sc.server_id = system.server_id;
                    end loop;
                    prev_ent_count := prev_ent_count - reduce_quantity;
                    prev_flex_count := prev_flex_count + reduce_quantity;
                end if; 
        end if;




        -- If we're setting the total entitlemnt count to a lower value,
        -- and that value is less than the count in that one org,
        -- we need to raise an exception.
        if quantity_in < prev_ent_count then
            rhn_exception.raise_exception(
                          'not_enough_entitlements_in_base_org');
        else
            -- even if we've manually converted systems to/from flex above
            -- set_family_count should call update_family_counts, to reset
            -- current used slots
            rhn_entitlements.set_family_count(org_id_in, cfam_id,
                                              quantity_in, flex_in);
        end if;

    end activate_channel_entitlement;


    procedure set_group_count (
        customer_id_in in number,
        type_in in char,
        group_type_in in number,
        quantity_in in number,
                update_family_countsYN in number := 1
    ) is
        group_id number;
        quantity number;
    begin
        quantity := quantity_in;
        if quantity is not null and quantity < 0 then
            quantity := 0;
        end if;

        if type_in = 'U' then
            select    rug.id
            into    group_id
            from    rhnUserGroup rug
            where    1=1
                and rug.org_id = customer_id_in
                and rug.group_type = group_type_in;
        elsif type_in = 'S' then
            select    rsg.id
            into    group_id
            from    rhnServerGroup rsg
            where    1=1
                and rsg.org_id = customer_id_in
                and rsg.group_type = group_type_in;
        end if;

        rhn_entitlements.prune_group(
            group_id,
            type_in,
            quantity,
                        update_family_countsYN
        );
    exception
        when no_data_found then
            if type_in = 'U' then
                insert into rhnUserGroup (
                        id, name, description, max_members, current_members,
                        group_type, org_id, created, modified
                    ) (
                        select    rhn_user_group_id_seq.nextval, name, name,
                                quantity, 0, id, customer_id_in,
                                sysdate, sysdate
                        from    rhnUserGroupType
                        where    id = group_type_in
                );
            elsif type_in = 'S' then
                insert into rhnServerGroup (
                        id, name, description, max_members, current_members,
                        group_type, org_id, created, modified
                    ) (
                        select    rhn_server_group_id_seq.nextval, name, name,
                                quantity, 0, id, customer_id_in,
                                sysdate, sysdate
                        from    rhnServerGroupType
                        where    id = group_type_in
                );
            end if;
    end set_group_count;

    -- *******************************************************************
    -- PROCEDURE: prune_family
    -- Unsubscribes servers consuming physical slots from the channel family 
    --   that are over the org's limit.
    -- Called by: set_family_count, prune_everything
    -- *******************************************************************
    procedure prune_family (
        customer_id_in in number,
        channel_family_id_in in number,
        quantity_in in number,
        flex_in in number
    ) is
       is_fve_in char;
       tmp_quantity number;

        cursor serverchannels is
            select    sc.server_id,
                    sc.channel_id
            from    rhnServerChannel sc,
                    rhnChannelFamilyMembers cfm
            where    1=1
                and cfm.channel_family_id = channel_family_id_in
                and cfm.channel_id = sc.channel_id
                and server_id in (
                    select    server_id
                      from    (
                        select server_id, time, rownum row_number
                        from    (
                            select rs.id  server_id, rcfm.modified time
                            from    rhnServerChannel         rsc,
                                    rhnChannelFamilyMembers  rcfm,
                                    rhnServer                rs
                            where    1=1
                                and rs.org_id = customer_id_in
                                and rs.id = rsc.server_id
                                and rsc.channel_id = rcfm.channel_id
                                and rcfm.channel_family_id =  channel_family_id_in
                                and rsc.is_fve = is_fve_in
                                -- we only want to grab servers consuming
                                -- physical slots.
                                and exists (
                                    select 1
                                    from rhnChannelFamilyServerPhysical cfsp
                                    where cfsp.server_id = rs.id
                                    and cfsp.channel_family_id = 
                                        channel_family_id_in
                                    )
                            order by time asc
                        )
                    )
                    where row_number > tmp_quantity
                );
    begin
        -- if we get a null customer_id, this is completely bogus.
        if customer_id_in is null then
            return;
        end if;

        tmp_quantity := quantity_in;
        is_fve_in := 'N';

        for sc in serverchannels loop
            rhn_channel.unsubscribe_server(sc.server_id, sc.channel_id, 1, 1,
                                                       update_family_countsYN => 0);

        tmp_quantity := flex_in;
        is_fve_in := 'Y';
        for sc in serverchannels loop
            rhn_channel.unsubscribe_server(sc.server_id, sc.channel_id, 1, 1,
                                                        update_family_countsYN => 0);
        end loop;



        end loop;
                rhn_channel.update_family_counts(channel_family_id_in, customer_id_in);
    end prune_family;

    procedure set_family_count (
        customer_id_in in number,
        channel_family_id_in in number,
        quantity_in in number,
        flex_in in number
    ) is
        cursor privperms is
            select    1
            from    rhnPrivateChannelFamily
            where    org_id = customer_id_in
                and channel_family_id = channel_family_id_in;
        cursor pubperms is
            select    o.id org_id
            from    web_customer o,
                    rhnPublicChannelFamily pcf
            where    pcf.channel_family_id = channel_family_id_in;
        quantity number;
        done number := 0;
        flex number;
    begin
        quantity := quantity_in;
        if quantity is not null and quantity < 0 then
            quantity := 0;
        end if;
        flex := flex_in;
        if flex is not null and flex < 0 then
            flex := 0;
        end if;


        if customer_id_in is not null then
            for perm in privperms loop
                rhn_entitlements.prune_family(customer_id_in, channel_family_id_in,
                    quantity, flex);

               update rhnPrivateChannelFamily
                    set max_members = quantity
                    where org_id = customer_id_in
                        and channel_family_id = channel_family_id_in;

               update rhnPrivateChannelFamily
                    set fve_max_members = flex
                    where org_id = customer_id_in
                        and channel_family_id = channel_family_id_in;

                return;
            end loop;

            insert into rhnPrivateChannelFamily (
                    channel_family_id, org_id, max_members, current_members, fve_max_members, fve_current_members
                ) values (
                    channel_family_id_in, customer_id_in, quantity, 0, flex, 0 );
            return;
        end if;

        for perm in pubperms loop
            if quantity = 0 then
                rhn_entitlements.prune_family(
                    perm.org_id,
                    channel_family_id_in,
                    quantity,
                    flex
                );
                if done = 0 then
                    delete from rhnPublicChannelFamily
                        where channel_family_id = channel_family_id_in;
                end if;
            end if;
            done := 1;
        end loop;
        -- if done's not 1, then we don't have any entitlements
        if done != 1 then
            insert into rhnPublicChannelFamily (
                    channel_family_id
                ) values (
                    channel_family_id_in
                );
        end if;
    end set_family_count;

    -- this expects quantity_in to be the number of available slots, not the
    -- max_members of the server group.  If you give it too many, it'll fail
    -- and raise servergroup_max_members.
    -- We should NEVER run this unless we're SURE that we won't
    -- be violating the max.
    procedure entitle_last_modified_servers (
        customer_id_in in number,
        type_label_in in varchar2,
        quantity_in in number
    ) is
        -- find the servers that aren't currently in slots
        cursor servers(cid_in in number, quant_in in number) is
            select    server_id
            from    (
                        select    rownum row_number,
                                server_id
                        from    (
                                    select    rs.id server_iD
                                    from    rhnServer rs
                                    where    1=1
                                        and rs.org_id = cid_in
                                        and not exists (
                                            select    1
                                            from    rhnServerGroup sg,
                                                    rhnServerGroupMembers rsgm
                                            where    rsgm.server_id = rs.id
                                                and rsgm.server_group_id = sg.id
                                                and sg.group_type is not null
                                        )
                                        and not exists (
                                            select 1
                                            from rhnVirtualInstance vi
                                            where vi.virtual_system_id =
                                                  rs.id
                                        )                                                                           order by modified desc
                                )
                    )
            where    row_number <= quant_in;
    begin
        for server in servers(customer_id_in, quantity_in) loop
            rhn_entitlements.entitle_server(server.server_id, type_label_in);
        end loop;
    end entitle_last_modified_servers;

    procedure subscribe_newest_servers (
        customer_id_in in number
    ) is
        -- find servers without base channels
        cursor servers(cid_in in number) is
            select    s.id
            from    rhnServer            s
            where    1=1
                and s.org_id = cid_in
                and not exists (
                        select 1
                        from    rhnChannel            c,
                                rhnServerChannel    sc
                        where    sc.server_id = s.id
                            and sc.channel_id = c.id
                            and c.parent_channel is null
                    )
                and not exists (
                        select 1
                        from rhnVirtualInstance vi
                        where vi.virtual_system_id = s.id
                    )                        
            order by s.modified desc;
        channel_id number;
    begin
        for server in servers(customer_id_in) loop
            channel_id := rhn_channel.guess_server_base(server.id);
            if channel_id is not null then
                begin
                    rhn_channel.subscribe_server(server.id, channel_id);
                    commit;
                -- exception is really channel_family_no_subscriptions
                exception
                    when others then
                        null;
                end;
            end if;
        end loop;
    end subscribe_newest_servers;
end rhn_entitlements;
/
show errors

--
--
-- Revision 1.56  2004/07/21 21:27:36  nhansen
-- bug 128196: use rhn_monitor instead of rhn_monitoring as the rhnOrgEntitlementType
--
-- Revision 1.55  2004/07/20 15:38:57  pjones
-- bugzilla: 128196 -- make entitling "monitoring" work.
--
-- Revision 1.54  2004/07/14 19:13:13  pjones
-- bugzilla: 126461 -- entitlement changes for new user roles
--
-- Revision 1.53  2004/07/02 19:18:20  pjones
-- bugzilla: 125937 -- use rhn_user to remove user roles
--
-- Revision 1.52  2004/05/26 19:45:48  pjones
-- bugzilla: 123639
-- 1) reformat "entitlement_grants_service"
-- 2) make the .pks and .pkb be in the same order.
-- 3) add "modify_org_service" (to be used instead of set_customer_SERVICELEVEL)
-- 4) add monitoring specific data.
--
-- Revision 1.51  2004/04/19 18:18:51  pjones
-- bugzilla: none -- misa's using set_family_count() to set null org entitlements
--
-- Revision 1.50  2004/04/14 00:09:24  pjones
-- bugzilla: 120761 -- split rhnChannelPermissions into two tables, eliminating
-- a frequent full table scan
--
-- Revision 1.49  2004/03/26 16:53:42  pjones
-- bugzilla: none -- make rhn_nonlinux give config_admin too on sat.
--
-- Revision 1.48  2004/03/25 22:29:56  pjones
-- bugzilla: none -- only create config_admin in set_customer_prov if we're
-- on a satellite
  07070100000554000081B400000000000000000000000167AE111400000045000000000000000000000000000000000000006300000000susemanager-schema/upgrade/spacewalk-schema-1.0-to-spacewalk-schema-1.1/018-rhnPackageRepodata.sql    alter table rhnPackageRepodata rename column primary to primary_xml;
   07070100000555000081B400000000000000000000000167AE111400000178000000000000000000000000000000000000006700000000susemanager-schema/upgrade/spacewalk-schema-1.0-to-spacewalk-schema-1.1/019-rhnServerPackage-index.sql    DELETE FROM rhnServerPackage A
WHERE rowid NOT IN (SELECT min(rowid) min_rowid
                      FROM rhnServerPackage
                     GROUP BY server_id, name_id, evr_id, package_arch_id);

DROP INDEX rhn_sp_snep_idx;
CREATE UNIQUE INDEX rhn_sp_snep_uq
    ON rhnServerPackage (server_id, name_id, evr_id, package_arch_id)
    TABLESPACE [[128m_tbs]]
    NOLOGGING;
07070100000556000081B400000000000000000000000167AE111400000799000000000000000000000000000000000000006500000000susemanager-schema/upgrade/spacewalk-schema-1.0-to-spacewalk-schema-1.1/020-rhnAvailableChannels.sql  --
-- Copyright (c) 2008--2010 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
-- tricky view.  it explodes to a full cartesian product when
-- not queried via org_id, so DO NOT DO THAT :)

create or replace view
rhnAvailableChannels
(
    	org_id,
	channel_id,
	channel_depth,
	channel_name,
	channel_arch_id,
	padded_name,
	current_members,
	available_members,
        last_modified,
        channel_label,
	parent_or_self_label,
	parent_or_self_id 
)
as
select
     ct.org_id,
     ct.id,
     CT.depth,
     CT.name,
     CT.channel_arch_id,
     CT.padded_name,
    (SELECT COUNT(1)
     FROM rhnServer S 
     INNER JOIN rhnServerChannel SC
       ON SC.server_id = S.id
     WHERE SC.channel_id = CT.id AND
           S.org_id = CT.org_id),
     rhn_channel.available_chan_subscriptions(ct.id, ct.org_id),
     CT.last_modified,
     CT.label,
     CT.parent_or_self_label,
     CT.parent_or_self_id
from
     rhnOrgChannelTreeView CT
UNION ALL
select
     ct.org_id,
     ct.id,
     CT.depth,
     CT.name,
     CT.channel_arch_id,
     CT.padded_name,
    (SELECT COUNT(1)
     FROM rhnServer S 
     INNER JOIN rhnServerChannel SC
       ON SC.server_id = S.id
     WHERE SC.channel_id = CT.id AND
           S.org_id = CT.org_id),
     NULL,
     CT.last_modified,
     CT.label,
     CT.parent_or_self_label,
     CT.parent_or_self_id
from
     rhnSharedChannelTreeView CT
;

   07070100000557000081B400000000000000000000000167AE111400001F7D000000000000000000000000000000000000005B00000000susemanager-schema/upgrade/spacewalk-schema-1.0-to-spacewalk-schema-1.1/021-rhnOrgInfo.sql    --
-- Copyright (c) 2008--2010 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--

CREATE OR REPLACE
PACKAGE BODY rhn_org
IS
	body_version varchar2(100) := '';

    FUNCTION find_server_group_by_type(org_id_in NUMBER, group_label_in VARCHAR2)
    RETURN NUMBER
    IS
	server_group       server_group_by_label%ROWTYPE;
    BEGIN
	OPEN server_group_by_label(org_id_in, group_label_in);
	FETCH server_group_by_label INTO server_group;
	CLOSE server_group_by_label;

	RETURN server_group.id;
    END find_server_group_by_type;

    procedure delete_org (
        org_id_in in number
    )
    is
        cursor users is
        select id
        from web_contact
        where org_id = org_id_in;

	cursor servers(org_id_in in number) is
        select	id
        from	rhnServer
        where	org_id = org_id_in;

        cursor config_channels is
        select id
        from rhnConfigChannel
        where org_id = org_id_in;

	cursor custom_channels is
        select	id
        from	rhnChannel
        where	org_id = org_id_in;

	cursor errata is
        select	id
        from	rhnErrata
        where	org_id = org_id_in;

    begin

        if org_id_in = 1 then
            rhn_exception.raise_exception('cannot_delete_base_org');
        end if;

        -- Delete all users.
        for u in users loop
            rhn_org.delete_user(u.id, 1);
        end loop;

        -- Delete all servers.
        for s in servers(org_id_in) loop
            delete_server(s.id);
        end loop;

        -- Delete all config channels.
        for c in config_channels loop
            rhn_config.delete_channel(c.id);
        end loop;

        -- Delete all custom channels.
        for cc in custom_channels loop
          delete from rhnServerChannel where channel_id = cc.id;
          delete from rhnServerProfilePackage where server_profile_id in (
            select id from rhnServerProfile where base_channel = cc.id
          );
          delete from rhnServerProfile where base_channel = cc.id;
        end loop;

        -- Delete all errata packages
        for e in errata loop
            delete from rhnErrataPackage where errata_id = e.id;
        end loop;

        -- Give the org's entitlements back to the main org.
        rhn_entitlements.remove_org_entitlements(org_id_in);

        -- Clean up tables where we don't have a cascading delete.
        delete from rhnChannel where org_id = org_id_in;
        delete from rhnDailySummaryQueue where org_id = org_id_in;
        delete from rhnOrgQuota where org_id = org_id_in;
        delete from rhnFileList where org_id = org_id_in;
        delete from rhnServerGroup where org_id = org_id_in;
        delete from rhn_check_suites where customer_id = org_id_in;
        delete from rhn_command_target where customer_id = org_id_in;
        delete from rhn_contact_groups where customer_id = org_id_in;
        delete from rhn_notification_formats where customer_id = org_id_in;
        delete from rhn_probe where customer_id = org_id_in;
        delete from rhn_redirects where customer_id = org_id_in;
        delete from rhn_sat_cluster where customer_id = org_id_in;
        delete from rhn_schedules where customer_id = org_id_in;

        -- Delete the org.
        delete from web_customer where id = org_id_in;

    end delete_org;

	procedure delete_user(user_id_in in number, deleting_org in number := 0) is
		cursor is_admin is
			select	1
			from	rhnUserGroupType	ugt,
					rhnUserGroup		ug,
					rhnUserGroupMembers	ugm
			where	ugm.user_id = user_id_in
				and ugm.user_group_id = ug.id
				and ug.group_type = ugt.id
				and ugt.label = 'org_admin';
		cursor servergroups_needing_admins is
			select	usgp.server_group_id	server_group_id
			from	rhnUserServerGroupPerms	usgp
			where	1=1
				and usgp.user_id = user_id_in
				and not exists (
					select	1
					from	rhnUserServerGroupPerms	sq_usgp
					where	1=1
						and sq_usgp.server_group_id = usgp.server_group_id
						and	sq_usgp.user_id != user_id_in
				);
		cursor messages is
			select	message_id id
			from	rhnUserMessage
			where	user_id = user_id_in;
		users			number;
		our_org_id		number;
		other_users		number;
		other_org_admin	number;
        other_user_id  number;
	begin
		select	wc.org_id
		into	our_org_id
		from	web_contact wc
		where	id = user_id_in;

		-- find any other users
		begin
			select	id, 1
			into	other_user_id, other_users
			from	web_contact
			where	1=1
				and org_id = our_org_id
				and id != user_id_in
				and rownum = 1;
		exception
			when no_data_found then
				other_users := 0;
		end;

		-- now do org admin stuff
		if other_users != 0 then
			for ignore in is_admin loop
				begin
					select	new_ugm.user_id
					into	other_org_admin
					from	rhnUserGroupMembers	new_ugm,
							rhnUserGroupType	ugt,
							rhnUserGroup		ug,
							rhnUserGroupMembers	ugm
					where	ugm.user_id = user_id_in
						and ugm.user_group_id = ug.id
						and ug.group_type = ugt.id
						and ugt.label = 'org_admin'
						and ug.id = new_ugm.user_group_id
						and new_ugm.user_id != user_id_in
						and rownum = 1;
				exception
					when no_data_found then
                        -- If we're deleting the org, we don't want to raise
                        -- the exception.
                        if deleting_org = 0 then
						rhn_exception.raise_exception('cannot_delete_user');
                        end if;
				end;

				for sg in servergroups_needing_admins loop
					rhn_user.add_servergroup_perm(other_org_admin,
						sg.server_group_id);
				end loop;
			end loop;
		end if;

		-- and now things for every user
		for message in messages loop
			delete
				from	rhnUserMessage
				where	user_id = user_id_in
					and message_id = message.id;
			begin
				select	1
				into	users
				from	rhnUserMessage
				where	message_id = message.id
					and rownum = 1;
				delete
					from	rhnMessage
					where	id = message.id;
			exception
				when no_data_found then
					null;
			end;
		end loop;
		delete from rhn_command_queue_sessions where contact_id = user_id_in;
		delete from rhn_contact_groups
		where recid in (
			select contact_group_id
			from rhn_contact_group_members
			where member_contact_method_id in (
				select recid from rhn_contact_methods
				where contact_id = user_id_in
				)
			)
			and not exists (
				select 1
				from rhn_contact_group_members, rhn_contact_methods
				where rhn_contact_groups.recid = rhn_contact_group_members.contact_group_id
					and rhn_contact_group_members.member_contact_method_id = rhn_contact_methods.recid
					and rhn_contact_methods.contact_id <> user_id_in
			);
		delete from rhn_contact_methods where contact_id = user_id_in;
		delete from rhn_redirects where contact_id = user_id_in;
		delete from rhnUserServerPerms where user_id = user_id_in;
                delete from rhnAppInstallSession where user_id = user_id_in;
		if other_users != 0 then
			update		rhnRegToken
				set		user_id = nvl(other_org_admin, other_user_id)
				where	org_id = our_org_id
					and user_id = user_id_in;
			begin
				delete from web_contact where id = user_id_in;
			exception
				when others then
					rhn_exception.raise_exception('cannot_delete_user');
			end;
        -- Just Delete the user
		else
            begin
                delete from web_contact where id = user_id_in;
		    exception
				when others then
					rhn_exception.raise_exception('cannot_delete_user');
			end;
		end if;
		return;
	end delete_user;

END rhn_org;
/
SHOW ERRORS

drop table rhnOrgInfo;
   07070100000558000081B400000000000000000000000167AE1114000004B0000000000000000000000000000000000000005D00000000susemanager-schema/upgrade/spacewalk-schema-1.0-to-spacewalk-schema-1.1/022-web_customer.sql  --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--

alter trigger web_customer_mod_trig disable;
alter table web_customer add
        staging_content_enabled CHAR(1)
                    DEFAULT ('N') NOT NULL
                CONSTRAINT web_customer_stage_content_chk
                CHECK (staging_content_enabled in ( 'Y' , 'N' ));
alter trigger web_customer_mod_trig enable;

alter table web_customer drop column oracle_customer_id;
alter table web_customer drop column oracle_customer_number;
alter table web_customer drop column customer_type;
alter table web_customer drop column credit_application_completed;

07070100000559000081B400000000000000000000000167AE111400000F58000000000000000000000000000000000000006100000000susemanager-schema/upgrade/spacewalk-schema-1.0-to-spacewalk-schema-1.1/023-create_first_org.sql  --
-- Copyright (c) 2008--2010 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
-- This creates an org with ID of 1, and errors if there already is one
--



create or replace procedure
create_first_org
(
	name_in in varchar2,
	password_in in varchar2
) is
	ug_type			number;
	group_val		number;
begin
	insert into web_customer (
		id, name
	) values (
		1, name_in
	);

	select rhn_user_group_id_seq.nextval into group_val from dual;

	select	id
	into	ug_type
	from	rhnUserGroupType
	where	label = 'org_admin';

	insert into rhnUserGroup (
		id, name,
		description,
		max_members, group_type, org_id
	) values (
		group_val, 'Organization Administrators',
		'Organization Administrators for Org ' || name_in || ' (1)',
		NULL, ug_type, 1
	);

	select rhn_user_group_id_seq.nextval into group_val from dual;

	select	id
	into	ug_type
	from	rhnUserGroupType
	where	label = 'org_applicant';

	insert into rhnUserGroup (
		id, name,
		description,
		max_members, group_type, org_id
	) VALues (
		group_val, 'Organization Applicants',
		'Organization Applicants for Org ' || name_in || ' (1)',
		NULL, ug_type, 1
	);

	select rhn_user_group_id_seq.nextval into group_val from dual;

	select	id
	into	ug_type
	from	rhnUserGroupType
	where	label = 'system_group_admin';

	insert into rhnUserGroup (
		id, name,
		description,
		max_members, group_type, org_id
	) values (
		group_val, 'System Group Administrators',
		'System Group Administrators for Org ' || name_in || ' (1)',
		NULL, ug_type, 1
	);


	select rhn_user_group_id_seq.nextval into group_val from dual;

	select	id
	into	ug_type
	from	rhnUserGroupType
	where	label = 'activation_key_admin';

	insert into rhnUserGroup (
		id, name,
		description,
		max_members, group_type, org_id
	) values (
		group_val, 'Activation Key Administrators',
		'Activation Key Administrators for Org ' || name_in || ' (1)',
		NULL, ug_type, 1
	);

	-- config admin is special; it gets created in
	-- rhn_entitlements.set_customer_provisioning instead.
	
	select rhn_user_group_id_seq.nextval into group_val from dual;

	select	id
	into	ug_type
	from	rhnUserGroupType
	where	label = 'channel_admin';

	insert into rhnUserGroup (
		id, name,
		description,
		max_members, group_type, org_id
	) values (
		group_val, 'Channel Administrators',
		'Channel Administrators for Org ' || name_in || ' (1)',
		NULL, ug_type, 1
	);

	select rhn_user_group_id_seq.nextval into group_val from dual;

	select	id
	into	ug_type
	from	rhnUserGroupType
	where	label = 'satellite_admin';

	insert into rhnUserGroup (
		id, name,
		description,
		max_members, group_type, org_id
	) values (
		group_val, 'Satellite Administrators',
		'Satellite Administrators for Org ' || name_in || ' (1)',
		NULL, ug_type, 1
	);


	-- if they need more than 16GB, they'll call us and we'll whip
	-- out a "can be null" patch, which we should do for next
	-- version anyway.  (I thought we did that for this version?)
	insert into rhnOrgQuota(
		org_id, total
	) values (
		1, 1024*1024*1024*16
	);
	
	
	-- there aren't any users yet, so we don't need to update
	-- rhnUserServerPerms
        insert into rhnServerGroup 
		( id, name, description, max_members, group_type, org_id )
		select rhn_server_group_id_seq.nextval, sgt.name, sgt.name, 
			0, sgt.id, 1
		from rhnServerGroupType sgt
		where sgt.label = 'sw_mgr_entitled';
		
end create_first_org;
/
show errors;

0707010000055A000081B400000000000000000000000167AE111400000D41000000000000000000000000000000000000005F00000000susemanager-schema/upgrade/spacewalk-schema-1.0-to-spacewalk-schema-1.1/024-create_new_org.sql    --
-- Copyright (c) 2008--2013 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--

create or replace procedure
create_new_org
(
	name_in      in varchar2,
	password_in  in varchar2,
	org_id_out   out number
) is
	ug_type			number;
	group_val		number;
	new_org_id              number;
begin
    
        select web_customer_id_seq.nextval into new_org_id from dual;

	insert into web_customer (
		id, name

	
	) values (
		new_org_id, name_in
	);

	select rhn_user_group_id_seq.nextval into group_val from dual;

	select	id
	into	ug_type
	from	rhnUserGroupType
	where	label = 'org_admin';

	insert into rhnUserGroup (
		id, name,
		description,
		max_members, group_type, org_id
	) values (
		group_val, 'Organization Administrators',
		'Organization Administrators for Org ' || name_in,
		NULL, ug_type, new_org_id
	);

	select rhn_user_group_id_seq.nextval into group_val from dual;

	select	id
	into	ug_type
	from	rhnUserGroupType
	where	label = 'org_applicant';

	insert into rhnUserGroup (
		id, name,
		description,
		max_members, group_type, org_id
	) VALues (
		group_val, 'Organization Applicants',
		'Organization Applicants for Org ' || name_in,
		NULL, ug_type, new_org_id
	);

	select rhn_user_group_id_seq.nextval into group_val from dual;

	select	id
	into	ug_type
	from	rhnUserGroupType
	where	label = 'system_group_admin';

	insert into rhnUserGroup (
		id, name,
		description,
		max_members, group_type, org_id
	) values (
		group_val, 'System Group Administrators',
		'System Group Administrators for Org ' || name_in,
		NULL, ug_type, new_org_id
	);


	select rhn_user_group_id_seq.nextval into group_val from dual;

	select	id
	into	ug_type
	from	rhnUserGroupType
	where	label = 'activation_key_admin';

	insert into rhnUserGroup (
		id, name,
		description,
		max_members, group_type, org_id
	) values (
		group_val, 'Activation Key Administrators',
		'Activation Key Administrators for Org ' || name_in,
		NULL, ug_type, new_org_id
	);

	-- config admin is special; it gets created in
	-- rhn_entitlements.set_customer_provisioning instead.
	
	select rhn_user_group_id_seq.nextval into group_val from dual;

	select	id
	into	ug_type
	from	rhnUserGroupType
	where	label = 'channel_admin';

	insert into rhnUserGroup (
		id, name,
		description,
		max_members, group_type, org_id
	) values (
		group_val, 'Channel Administrators',
		'Channel Administrators for Org ' || name_in,
		NULL, ug_type, new_org_id
	);

	-- there aren't any users yet, so we don't need to update
	-- rhnUserServerPerms
        insert into rhnServerGroup 
		( id, name, description, max_members, group_type, org_id )
		select rhn_server_group_id_seq.nextval, sgt.name, sgt.name, 
			0, sgt.id, new_org_id
		from rhnServerGroupType sgt
		where sgt.label = 'sw_mgr_entitled';
	
	org_id_out := new_org_id;
		
end create_new_org;
/
show errors;

   0707010000055B000081B400000000000000000000000167AE1114000002AD000000000000000000000000000000000000005F00000000susemanager-schema/upgrade/spacewalk-schema-1.0-to-spacewalk-schema-1.1/025-drop_paid_orgs.sql    --
-- Copyright (c) 2008--2010 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--
drop view rhnPaidOrgs;
drop package rhn_bel;


   0707010000055C000081B400000000000000000000000167AE1114000002AD000000000000000000000000000000000000005F00000000susemanager-schema/upgrade/spacewalk-schema-1.0-to-spacewalk-schema-1.1/026-drop_demo_orgs.sql    --
-- Copyright (c) 2008--2010 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--
drop view rhnDemoOrgs;
drop table demo_log;



   0707010000055D000081B400000000000000000000000167AE111400000033000000000000000000000000000000000000006700000000susemanager-schema/upgrade/spacewalk-schema-1.0-to-spacewalk-schema-1.1/030-rhnDevice-alter-device.sql    alter table rhnDevice modify device VARCHAR2(256);
 0707010000055E000081B400000000000000000000000167AE11140000031C000000000000000000000000000000000000007400000000susemanager-schema/upgrade/spacewalk-schema-1.0-to-spacewalk-schema-1.1/100-drop-rhnChannelFamilyLicense-tables.sql   --
-- Copyright (c) 2008--2010 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--
drop trigger rhn_cf_license_mod_trig;
drop trigger rhn_cfl_consent_mod_trig;
drop table rhnChannelFamilyLicense;
drop table rhnChannelFamilyLicenseConsent;


0707010000055F000081B400000000000000000000000167AE1114000009CF000000000000000000000000000000000000006500000000susemanager-schema/upgrade/spacewalk-schema-1.0-to-spacewalk-schema-1.1/101-update-config-schema.sql  --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

alter table rhnConfigInfo add SYMLINK_TARGET_FILENAME_ID NUMBER
                CONSTRAINT rhn_confinfo_symlink_fk
                    REFERENCES rhnConfigFileName (id);
alter table rhnConfigInfo modify username  NULL;
alter table rhnConfigInfo modify groupname  NULL;
alter table rhnConfigInfo modify filemode  NULL;
drop index rhn_confinfo_ugf_uq;
CREATE UNIQUE INDEX rhn_confinfo_ugf_uq
    ON rhnConfigInfo (username, groupname, filemode, selinux_ctx, symlink_target_filename_id);


alter table rhnConfigContent     add delim_start    VARCHAR2(16);
alter table rhnConfigContent     add delim_end      VARCHAR2(16);

alter trigger rhn_confcontent_mod_trig disable;
DECLARE
     CURSOR config_content_delimeters is
       select CONFIG_CONTENT_ID, DELIM_START, DELIM_END 
        from rhnConfigRevision;
BEGIN
  FOR content IN config_content_delimeters
  LOOP
      update rhnConfigContent set DELIM_START = content.DELIM_START
        where id = content.CONFIG_CONTENT_ID;
        
      update rhnConfigContent set DELIM_END = content.DELIM_END
        where id = content.CONFIG_CONTENT_ID;        

  END LOOP;
  commit;
END;
/
alter trigger rhn_confcontent_mod_trig enable;

alter table rhnConfigContent modify delim_start   not null;
alter table rhnConfigContent modify delim_end     not null;

alter table rhnConfigRevision modify config_content_id  NULL;
alter table rhnConfigRevision drop column delim_start;
alter table rhnConfigRevision drop column delim_end;

update rhnConfigRevision set CONFIG_CONTENT_ID = null 
    where CONFIG_CONTENT_ID in
    (select cr.CONFIG_CONTENT_ID 
        from rhnConfigRevision cr 
                inner join rhnConfigFileType cft on cft.id = cr.config_file_type_id and cft.label ='directory');

delete from rhnConfigContent where id not in 
    (select CONFIG_CONTENT_ID from rhnConfigRevision cr where CONFIG_CONTENT_ID is not null);

 07070100000560000081B400000000000000000000000167AE111400000A85000000000000000000000000000000000000005F00000000susemanager-schema/upgrade/spacewalk-schema-1.0-to-spacewalk-schema-1.1/102-rhn_config-pks.sql    --
-- Copyright (c) 2008--2010 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--

create or replace package
rhn_config
is
	procedure prune_org_configs (
		org_id_in in number,
		total_in in number
	);

	function insert_revision (
		revision_in in number,
		config_file_id_in in number,
		config_content_id_in in number,
		config_info_id_in in number,
      config_file_type_id_in number := 1
	) return number;

	procedure delete_revision (
		config_revision_id_in in number,
		org_id_in in number := -1
	);

	function get_latest_revision (
		config_file_id_in in number
	) return number;

	function insert_file (
		config_channel_id_in in number,
		name_in in varchar2
	) return number;

	procedure delete_file (
		config_file_id_in in number
	);

	function insert_channel (
		org_id_in in number,
		type_in in varchar2,
		name_in in varchar2,
		label_in in varchar2,
		description_in in varchar2
	) return number;

	procedure delete_channel (
		config_channel_id_in in number
	);
end rhn_config;
/
show errors

--
--
-- Revision 1.8  2005/02/16 14:03:35  jslagle
-- bz #148844
-- Changed insert_revision function to take a config_file_type_id instead of label
--
-- Revision 1.7  2005/02/15 02:42:59  jslagle
-- bz #147860
-- insert_revision function now takes a rhnConfigFileType label as a parameter instead of an id
--
-- Revision 1.6  2005/02/14 22:45:23  jslagle
-- bz#147860
-- Update rhn_config package body and specification for additional column to rhnConfigRevision
--
-- Revision 1.5  2004/01/09 17:39:45  pjones
-- bugzilla: 113029 -- need to do functions for deleting rhnConfigChannel,
-- too, or we can't prune rhnConfigFile when we do.
--
-- Revision 1.4  2004/01/08 19:46:31  pjones
-- bugzilla: 113029 -- insert/delete for rhnConfigFile and rhnConfigRevision
--
-- Revision 1.3  2004/01/08 00:30:10  pjones
-- bugzilla: 113029 -- more deletion of config files and revisions
--
-- Revision 1.2  2004/01/08 00:03:37  pjones
-- bugzilla: 113029 -- rhn_config.delete_revision() and delete trigger on
-- rhnConfigFile
--
-- Revision 1.1  2003/12/19 22:07:30  pjones
-- bugzilla: 112392 -- quota support for config files
--
   07070100000561000081B400000000000000000000000167AE111400001EAE000000000000000000000000000000000000005F00000000susemanager-schema/upgrade/spacewalk-schema-1.0-to-spacewalk-schema-1.1/103-rhn_config-pkb.sql    --
-- Copyright (c) 2008--2010 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--

create or replace package body
rhn_config
is
	-- just a stub for now
	procedure prune_org_configs (
		org_id_in in number,
		total_in in number
	) is
	begin
		null;
	end prune_org_configs;

	function insert_revision (
		revision_in in number,
		config_file_id_in in number,
		config_content_id_in in number,
		config_info_id_in in number,
      config_file_type_id_in in number := 1
	) return number is
		retval number;
		cursor affected_orgs is
			select	cc.org_id id
			from	rhnConfigChannel cc,
					rhnConfigFile cf
			where	cf.id = config_file_id_in
				and cf.config_channel_id = cc.id;
	begin
      
		insert into rhnConfigRevision(id, revision, config_file_id,
				config_content_id, config_info_id, config_file_type_id
			) values (
				rhn_confrevision_id_seq.nextval, revision_in, config_file_id_in,
				config_content_id_in, config_info_id_in, config_file_type_id_in
			)
			returning id into retval;

		for org in affected_orgs loop
			rhn_quota.update_org_quota(org.id);
		end loop;

		return retval;
	end insert_revision;

	procedure delete_revision (
		config_revision_id_in in number,
		org_id_in in number := -1
	) is
		cfid number;
		ccid number;
		oid number;
		latest_crid number;
		others number := 0;
		cursor snapshots is
			select	scr.snapshot_id id
			from	rhnSnapshot s,
					rhnSnapshotConfigRevision scr
			where	scr.config_revision_id = config_revision_id_in
					and scr.snapshot_id = s.id
					and s.invalid is null;
		cursor other_revisions(config_content_id_in in number) is
			select	1
			from	rhnConfigRevision
			where	config_content_id = config_content_id_in;
	begin
		for snapshot in snapshots loop
			update		rhnSnapshot s
				set		s.invalid =
							lookup_snapshot_invalid_reason('cr_removed')
				where	s.id = snapshot.id;
		end loop;

		if org_id_in < 0 then
			select	cr.config_content_id, cc.org_id
			into	ccid, oid
			from	rhnConfigChannel cc,
					rhnConfigFile cf,
					rhnConfigRevision cr
			where	cr.id = config_revision_id_in
				and cr.config_file_id = cf.id
				and cf.config_channel_id = cc.id;
		else
			select	cr.config_content_id, org_id_in
			into	ccid, oid
			from	rhnConfigRevision cr
			where	cr.id = config_revision_id_in;
		end if;

		-- right now this will set rhnActionConfigFileName.config_revision_id
		-- to null, and will remove an entry from rhnActionConfigRevision.
		-- might we want to prune and/or kill the action in some way?  maybe
		-- mark it failed or something?
		delete from rhnConfigRevision where id = config_revision_id_in;

		-- now prune away content if there aren't any other revisions pointing
		-- at it
		for other_revision in other_revisions(ccid) loop
			others := 1;
			exit;
		end loop;
		if others = 0 then
			delete from rhnConfigContent where id = ccid;
		end if;

		-- now make sure rhnConfigFile points at a valid revision;
		-- if there isn't one, we're deleting it, _unless_ org_id_in is
		-- >= 0, in which case we're in the delete trigger anyway
		if org_id_in < 0 then
			select	cf.latest_config_revision_id,
					cf.id
			into	latest_crid,
					cfid
			from	rhnConfigFile cf,
					rhnConfigRevision cr
			where	cr.id = config_revision_id_in
				and cr.config_file_id = cf.id;

			if latest_crid = config_revision_id_in then
				latest_crid := rhn_config.get_latest_revision(cfid);
				if latest_crid is not null then
					update rhnConfigFile set latest_config_revision_id = latest_crid
						where id = cfid;
				else
					delete from rhnConfigFile where id = cfid;
				end if;
			end if;

		end if;
		rhn_quota.update_org_quota(oid);
	end delete_revision;

	function get_latest_revision (
		config_file_id_in in number
	) return number is
		cursor revisions is
			select	cr.id
			from	rhnConfigRevision cr
			where	cr.config_file_id = config_file_id_in
			order by revision desc;
	begin
		for revision in revisions loop
			return revision.id;
		end loop;
		return null;
	end get_latest_revision;

	function insert_file (
		config_channel_id_in in number,
		name_in in varchar2
	) return number is
		retval number;
	begin
		select	rhn_conffile_id_seq.nextval
		into	retval
		from	dual;

		insert into rhnConfigFile(id, config_channel_id, config_file_name_id, 
				state_id
			) (
				select	retval,
						config_channel_id_in,
						lookup_config_filename(name_in),
						id
				from	rhnConfigFileState
				where	label = 'alive'
			);

		return retval;
	end insert_file;

	procedure delete_file (
		config_file_id_in in number
	) is
		cursor revisions is
			select	cr.id, cc.org_id
			from	rhnConfigChannel cc,
					rhnConfigRevision cr,
					rhnConfigFile cf
			where	cf.id = config_file_id_in
				and cf.config_channel_id = cc.id
				and cr.config_file_id = cf.id;
		org_id number;
	begin
		for revision in revisions loop
			rhn_config.delete_revision(revision.id, revision.org_id);
			org_id := revision.org_id;
		end loop;
		rhn_quota.update_org_quota(org_id);
		delete from rhnConfigFile where id = config_file_id_in;
	end delete_file;

	function insert_channel (
		org_id_in in number,
		type_in in varchar2,
		name_in in varchar2,
		label_in in varchar2,
		description_in in varchar2
	) return number is
		retval number;
	begin
		select	rhn_confchan_id_seq.nextval
		into	retval
		from	dual;

		insert into rhnConfigChannel(id, org_id, confchan_type_id,
				name, label, description
			) (
				select	retval,
						org_id_in,
						cct.id,
						name_in,
						label_in,
						description_in
				from	rhnConfigChannelType cct
				where	label = type_in
			);
		return retval;
	end insert_channel;

	procedure delete_channel (
		config_channel_id_in in number
	) is
		cursor config_files is
			select	id
			from	rhnConfigFile
			where	config_channel_id = config_channel_id_in;
	begin
		for config_file in config_files loop
			rhn_config.delete_file(config_file.id);
		end loop;
		delete from rhnConfigChannel where id = config_channel_id_in;
	end delete_channel;
end rhn_config;
/
show errors

--
--
-- Revision 1.9  2005/02/16 14:03:35  jslagle
-- bz #148844
-- Changed insert_revision function to take a config_file_type_id instead of label
--
-- Revision 1.8  2005/02/15 02:42:59  jslagle
-- bz #147860
-- insert_revision function now takes a rhnConfigFileType label as a parameter instead of an id
--
-- Revision 1.7  2005/02/14 22:45:23  jslagle
-- bz#147860
-- Update rhn_config package body and specification for additional column to rhnConfigRevision
--
-- Revision 1.6  2004/10/11 14:02:53  pjones
-- bugzilla: 133169 -- somehow, we just never update the quota in this case.
-- Amazingly, I thought this worked _and_ QA passed it...
--
-- Revision 1.5  2004/01/09 17:39:45  pjones
-- bugzilla: 113029 -- need to do functions for deleting rhnConfigChannel,
-- too, or we can't prune rhnConfigFile when we do.
--
-- Revision 1.4  2004/01/08 19:46:31  pjones
-- bugzilla: 113029 -- insert/delete for rhnConfigFile and rhnConfigRevision
--
-- Revision 1.3  2004/01/08 00:30:10  pjones
-- bugzilla: 113029 -- more deletion of config files and revisions
--
-- Revision 1.2  2004/01/08 00:03:37  pjones
-- bugzilla: 113029 -- rhn_config.delete_revision() and delete trigger on
-- rhnConfigFile
--
-- Revision 1.1  2003/12/19 22:07:30  pjones
-- bugzilla: 112392 -- quota support for config files
--
  07070100000562000081B400000000000000000000000167AE111400000B01000000000000000000000000000000000000006A00000000susemanager-schema/upgrade/spacewalk-schema-1.0-to-spacewalk-schema-1.1/104-rhnconfigrevision-trigger.sql --
-- Copyright (c) 2008--2010 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--

create or replace trigger
rhn_confrevision_mod_trig
before insert or update on rhnConfigRevision
for each row
begin
	:new.modified := sysdate;
end;
/
show errors

-- right now we're not doing accounting for rhnConfigRevision updates.
-- we shouldn't ever _do_ updates, but right now the perms exist.
create or replace trigger
rhn_confrevision_acct_trig
after insert on rhnConfigRevision
for each row
declare
	org_id number;
	available number := 0;
	added number := 0;
begin
	-- find the current amount of quota available
    begin
	select	cc.org_id id,
			oq.total + oq.bonus - oq.used available,
			content.file_size added
	into	org_id, available, added
	from	rhnConfigContent	content,
			rhnOrgQuota			oq,
			rhnConfigChannel	cc,
			rhnConfigFile		cf
	where	cf.id = :new.config_file_id
			and cf.config_channel_id = cc.id
			and cc.org_id = oq.org_id
            and :new.config_file_type_id = (select id from rhnConfigFileType where label='file')
			and :new.config_content_id = content.id;
    exception
            when no_data_found then
                added := 0;
                available := 0;
    end;            
	if added > available then
		rhn_exception.raise_exception('not_enough_quota');
	end if;
end;
/
show errors

create or replace trigger
rhn_confrevision_del_trig
before delete on rhnConfigRevision
for each row
declare
	cursor snapshots is
		select	snapshot_id id
		from	rhnSnapshotConfigRevision
		where	config_revision_id = :old.id;
begin
	for snapshot in snapshots loop
		update rhnSnapshot
			set invalid = lookup_snapshot_invalid_reason('cr_removed')
			where id = snapshot.id;
		delete from rhnSnapshotConfigRevision
			where snapshot_id = snapshot.id
				and config_revision_id = :old.id;
	end loop;
end;
/
show errors

--
--
-- Revision 1.4  2004/01/07 20:49:12  pjones
-- bugzilla: none -- this needs to be done in application code
--
-- Revision 1.3  2004/01/05 20:35:41  pjones
-- bugzilla: 112553 -- fix the insert case for quota
--
-- Revision 1.2  2003/12/19 22:07:30  pjones
-- bugzilla: 112392 -- quota support for config files
--
-- Revision 1.1  2003/11/14 21:00:44  pjones
-- bugzilla: none -- snapshot invalid on config rev removal
--
   07070100000563000081B400000000000000000000000167AE1114000007F0000000000000000000000000000000000000006300000000susemanager-schema/upgrade/spacewalk-schema-1.0-to-spacewalk-schema-1.1/105-lookup_config_info.sql    --
-- Copyright (c) 2008--2010 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--

create or replace function
lookup_config_info (
    username_in     in varchar2,
    groupname_in    in varchar2,
    filemode_in     in varchar2,
    selinux_ctx_in  in varchar2,
    symlink_target_id in number
) return number
deterministic
is
    pragma autonomous_transaction;
    v_id    number;
    cursor lookup_cursor is
        select id
          from rhnConfigInfo
         where 1=1
           and nvl(username, ' ') = nvl(username_in, ' ')
           and nvl(groupname,' ') = nvl(groupname_in, ' ')
           and nvl(filemode, -1) = nvl(filemode_in, -1)
           and nvl(selinux_ctx, ' ') = nvl(selinux_ctx_in, ' ')
           and nvl(symlink_target_filename_id, -1) = nvl(symlink_target_id, -1)
        ;
begin
    for r in lookup_cursor loop
        return r.id;
    end loop;
    -- If we got here, we don't have the id
    select rhn_confinfo_id_seq.nextval
      into v_id
      from dual;
    insert into rhnConfigInfo (id, username, groupname, filemode, selinux_ctx, symlink_target_filename_id)
    values (v_id, username_in, groupname_in, filemode_in, selinux_ctx_in, symlink_target_id);
    commit;
    return v_id;
end lookup_config_info;
/
show errors

--
-- Revision 1.1  2003/11/10 15:36:27  pjones
-- bugzilla: 109083 -- lookup for rhnConfigInfo
--
-- Revision 1.1  2003/10/15 18:30:34  misa
-- bugzilla: 106911 Added a lookup function for rhnConfigFileInfo
--
--
07070100000564000081B400000000000000000000000167AE11140000042A000000000000000000000000000000000000006D00000000susemanager-schema/upgrade/spacewalk-schema-1.0-to-spacewalk-schema-1.1/106-rhnKickstartableTree-trigger.sql  
--
-- Copyright (c) 2008--2010 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

create or replace trigger
rhn_kstree_mod_trig
before insert or update on rhnKickstartableTree
for each row
begin
     if (:new.cobbler_id = :old.cobbler_id) and
        (:new.cobbler_xen_id = :old.cobbler_xen_id) and
        (:new.last_modified = :old.last_modified) or
        (:new.last_modified is null ) then
             :new.last_modified := sysdate;
     end if;

	:new.modified := sysdate;
end rhn_kstree_mod_trig;
/
show errors
  07070100000565000081B400000000000000000000000167AE1114000000CE000000000000000000000000000000000000006100000000susemanager-schema/upgrade/spacewalk-schema-1.0-to-spacewalk-schema-1.1/106-rhnServerNetwork.sql  alter table rhnServerNetwork modify (ipaddr varchar(16));
alter trigger rhn_servernetwork_mod_trig disable;
update rhnServerNetwork set ipaddr=trim(ipaddr);
alter trigger rhn_servernetwork_mod_trig enable;
  07070100000566000081B400000000000000000000000167AE111400000180000000000000000000000000000000000000005900000000susemanager-schema/upgrade/spacewalk-schema-1.0-to-spacewalk-schema-1.1/200-number12.sql  
alter table rhn_command modify ( recid number );
alter table rhn_command_parameter modify ( command_id number );
alter table rhn_command_target modify ( recid number );
alter table rhn_contact_groups modify ( recid number );
alter table rhn_contact_methods modify ( recid number );
alter table rhn_probe modify ( recid number );
alter table rhn_sat_cluster modify ( recid number );

07070100000567000081B400000000000000000000000167AE111400000261000000000000000000000000000000000000006100000000susemanager-schema/upgrade/spacewalk-schema-1.0-to-spacewalk-schema-1.1/300-concat_list_clob.sql  
create or replace function concat_list_clob(
        concat_string in varchar,
        cur in sys_refcursor,
        close_the_cursor in integer default 0
)
return clob
is
    ret clob;
    tmp varchar2(4000);
begin
    dbms_lob.createtemporary(ret, true); 
    loop
        fetch cur into tmp;
        exit when cur%notfound;
        if cur%rowcount > 1 then
            dbms_lob.writeappend(ret, length(concat_string), concat_string);
        end if;
        dbms_lob.writeappend(ret, length(tmp), tmp);
    end loop;
    if close_the_cursor > 0 then
        close cur;
    end if;
    return ret;
end;
/

   07070100000568000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000004800000000susemanager-schema/upgrade/spacewalk-schema-1.1-to-spacewalk-schema-1.2   07070100000569000081B400000000000000000000000167AE1114000000A1000000000000000000000000000000000000006B00000000susemanager-schema/upgrade/spacewalk-schema-1.1-to-spacewalk-schema-1.2/001-rhnServerChannelArchCompat.sql    insert into rhnServerChannelArchCompat (server_arch_id, channel_arch_id) values
(LOOKUP_SERVER_ARCH('ppc64-redhat-linux'), LOOKUP_CHANNEL_ARCH('channel-ppc'));

   0707010000056A000081B400000000000000000000000167AE11140000018E000000000000000000000000000000000000006400000000susemanager-schema/upgrade/spacewalk-schema-1.1-to-spacewalk-schema-1.2/002-rhnKickstartPackage.sql   -- first, delete duplicate kickstart_id, package_name_id pairs if any

delete
    from rhnKickstartPackage
   where rowid not in
       (select min(rowid)
          from rhnKickstartPackage
      group by kickstart_id, package_name_id);

commit;

ALTER TABLE rhnKickstartPackage
    ADD CONSTRAINT rhn_kspackage_name_uq UNIQUE (kickstart_id, package_name_id)
    USING INDEX TABLESPACE [[4m_tbs]];
  0707010000056B000081B400000000000000000000000167AE11140000006A000000000000000000000000000000000000006200000000susemanager-schema/upgrade/spacewalk-schema-1.1-to-spacewalk-schema-1.2/003-rhnErrataFileType.sql insert into rhnErrataFileType ( id, label )
       values ( rhn_erratafile_type_id_seq.nextval, 'OVAL' );
  0707010000056C000081B400000000000000000000000167AE11140000083B000000000000000000000000000000000000006400000000susemanager-schema/upgrade/spacewalk-schema-1.1-to-spacewalk-schema-1.2/003-rhnPackage_triggers.sql   
--
-- Copyright (c) 2008--2010 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--

create or replace trigger
rhn_package_mod_trig
before insert or update on rhnPackage
for each row
begin
	-- when we do a sat sync, we use last_modified to keep track
	-- of the upstream modification date.  So if we're setting
	-- it explicitly, don't override with sysdate.  But if we're
	-- not changing it, then this is a genuine update that needs
	-- tracking.
	--
	-- we're not using is_satellite() here instead, because we
	-- might want to use this to keep webdev in sync.
	if :new.last_modified = :old.last_modified then
		:new.last_modified := sysdate;
	end if;       
	:new.modified := sysdate;

        -- bz 619337 if we are updating the checksum, we need to
        -- update the last modified time on all the channels the package is in
        if :new.checksum_id != :old.checksum_id then
            update rhnChannel
              set last_modified = sysdate
              where id in (select channel_id
                              from rhnChannelPackage
                              where package_id = :new.id);
            insert into rhnRepoRegenQueue (id, CHANNEL_LABEL, REASON)
                   (select rhn_repo_regen_queue_id_seq.nextval, C.label, 'checksum modification'
                    from rhnChannel C inner join
                         rhnChannelPackage CP on CP.channel_id = C.id
                    where CP.package_id = :new.id);
            delete from rhnPackageRepodata where package_id = :new.id;
        end if;

end;
/
show errors
 0707010000056D000081B400000000000000000000000167AE111400000024000000000000000000000000000000000000006800000000susemanager-schema/upgrade/spacewalk-schema-1.1-to-spacewalk-schema-1.2/003-truncateCacheQueue-drop.sql   drop procedure  truncateCacheQueue;
0707010000056E000081B400000000000000000000000167AE111400000441000000000000000000000000000000000000005E00000000susemanager-schema/upgrade/spacewalk-schema-1.1-to-spacewalk-schema-1.2/010-rhnTaskoBunch.sql --
-- Copyright (c) 2010 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnTaskoBunch
(
    id          NUMBER NOT NULL
                    CONSTRAINT rhn_tasko_bunch_id_pk PRIMARY KEY,
    name        VARCHAR2(80) NOT NULL
                    CONSTRAINT tasko_bunch_name_uq UNIQUE,
    description VARCHAR2(200),
    org_bunch   VARCHAR2(1),
    created     DATE
                    DEFAULT (sysdate) NOT NULL,
    modified    DATE
                    DEFAULT (sysdate) NOT NULL
)
;

CREATE SEQUENCE rhn_tasko_bunch_id_seq;
   0707010000056F000081B400000000000000000000000167AE11140000041A000000000000000000000000000000000000005D00000000susemanager-schema/upgrade/spacewalk-schema-1.1-to-spacewalk-schema-1.2/011-rhnTaskoTask.sql  --
-- Copyright (c) 2010 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnTaskoTask
(
    id        NUMBER NOT NULL
                  CONSTRAINT rhn_tasko_task_id_pk PRIMARY KEY,
    name      VARCHAR2(80) NOT NULL
                  CONSTRAINT rhn_tasko_task_name_uq UNIQUE,
    class     VARCHAR2(60) NOT NULL,
    created   DATE
                  DEFAULT (sysdate) NOT NULL,
    modified  DATE
                  DEFAULT (sysdate) NOT NULL
)
;

CREATE SEQUENCE rhn_tasko_task_id_seq;
  07070100000570000081B400000000000000000000000167AE11140000056F000000000000000000000000000000000000006100000000susemanager-schema/upgrade/spacewalk-schema-1.1-to-spacewalk-schema-1.2/012-rhnTaskoTemplate.sql  --
-- Copyright (c) 2010 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnTaskoTemplate
(
    id          NUMBER NOT NULL
                    CONSTRAINT rhn_tasko_template_id_pk PRIMARY KEY,
    bunch_id    NUMBER NOT NULL
                    CONSTRAINT rhn_tasko_template_bunch_fk
                    REFERENCES rhnTaskoBunch (id),
    task_id     NUMBER NOT NULL
                    CONSTRAINT rhn_tasko_template_task_fk
                    REFERENCES rhnTaskoTask (id),
    ordering    NUMBER NOT NULL,
    start_if    VARCHAR2(10),
    created     DATE
                    DEFAULT (sysdate) NOT NULL,
    modified    DATE
                    DEFAULT (sysdate) NOT NULL
)
;

CREATE SEQUENCE rhn_tasko_template_id_seq;

ALTER TABLE rhnTaskoTemplate
    ADD CONSTRAINT tasko_template_ordering_uq UNIQUE (bunch_id, ordering);
 07070100000571000081B400000000000000000000000167AE111400000516000000000000000000000000000000000000006100000000susemanager-schema/upgrade/spacewalk-schema-1.1-to-spacewalk-schema-1.2/013-rhnTaskoSchedule.sql  --
-- Copyright (c) 2010 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnTaskoSchedule
(
    id              NUMBER NOT NULL
                        CONSTRAINT rhn_tasko_schedule_id_pk PRIMARY KEY,
    job_label       VARCHAR2(50) NOT NULL,
    bunch_id        NUMBER NOT NULL
                        CONSTRAINT rhn_tasko_schedule_bunch_fk
                        REFERENCES rhnTaskoBunch (id),
    org_id          NUMBER,
    active_from     DATE,
    active_till     DATE,
    cron_expr       VARCHAR2(20),
    data            BLOB,
    created         DATE
                        DEFAULT (sysdate) NOT NULL,
    modified        DATE
                        DEFAULT (sysdate) NOT NULL
)
;

CREATE SEQUENCE rhn_tasko_schedule_id_seq;
  07070100000572000081B400000000000000000000000167AE1114000005A4000000000000000000000000000000000000005C00000000susemanager-schema/upgrade/spacewalk-schema-1.1-to-spacewalk-schema-1.2/014-rhnTaskoRun.sql   --
-- Copyright (c) 2010 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnTaskoRun
(
    id              NUMBER NOT NULL
                        CONSTRAINT rhn_tasko_run_id_pk PRIMARY KEY,
    template_id     NUMBER NOT NULL
                        CONSTRAINT rhn_tasko_run_template_fk
                        REFERENCES rhnTaskoTemplate (id),
    schedule_id     NUMBER NOT NULL
                        CONSTRAINT rhn_tasko_run_schedule_fk
                        REFERENCES rhnTaskoSchedule (id),
    org_id          NUMBER,
    start_time      DATE,
    end_time        DATE,
    std_output_path VARCHAR2(100),
    std_error_path  VARCHAR2(100),
    status          VARCHAR2(10),
    created         DATE
                        DEFAULT (sysdate) NOT NULL,
    modified        DATE
                        DEFAULT (sysdate) NOT NULL
)
;

CREATE SEQUENCE rhn_tasko_run_id_seq;
07070100000573000081B400000000000000000000000167AE111400001071000000000000000000000000000000000000006300000000susemanager-schema/upgrade/spacewalk-schema-1.1-to-spacewalk-schema-1.2/020-rhnTaskoBunch_data.sql    --
-- Copyright (c) 2010 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


INSERT INTO rhnTaskoBunch (id, name, description, org_bunch)
             VALUES (rhn_tasko_bunch_id_seq.nextval, 'daily-status-bunch', 'Sends daily report', '');

INSERT INTO rhnTaskoBunch (id, name, description, org_bunch)
             VALUES (rhn_tasko_bunch_id_seq.nextval, 'sat-sync-bunch', 'Runs satellite-sync
Parameters:
- list parameter lists channels
- channel parameter specifies channel to be synced
- without parameter runs satellite-sync without parameters', 'Y');

INSERT INTO rhnTaskoBunch (id, name, description, org_bunch)
             VALUES (rhn_tasko_bunch_id_seq.nextval, 'clear-taskologs-bunch', 'Clears taskomatic run log history
Parameters:
- days parameter specifies age of logs to be kept
- without parameter default value will be used', '');

INSERT INTO rhnTaskoBunch (id, name, description, org_bunch)
             VALUES (rhn_tasko_bunch_id_seq.nextval, 'cobbler-sync-bunch', 'Applies any cobbler configuration changes', '');

INSERT INTO rhnTaskoBunch (id, name, description, org_bunch)
             VALUES (rhn_tasko_bunch_id_seq.nextval, 'compare-configs-bunch', 'Schedules a comparison of config files on all systems', '');

INSERT INTO rhnTaskoBunch (id, name, description, org_bunch)
             VALUES (rhn_tasko_bunch_id_seq.nextval, 'clean-alerts-bunch', 'Clears current monitoring alerts', '');

INSERT INTO rhnTaskoBunch (id, name, description, org_bunch)
             VALUES (rhn_tasko_bunch_id_seq.nextval, 'sync-probe-bunch', 'Calls the synch probe state proc', '');

INSERT INTO rhnTaskoBunch (id, name, description, org_bunch)
             VALUES (rhn_tasko_bunch_id_seq.nextval, 'session-cleanup-bunch', 'Deletes expired rows from the PXTSessions table to keep it from growing too large', '');

INSERT INTO rhnTaskoBunch (id, name, description, org_bunch)
             VALUES (rhn_tasko_bunch_id_seq.nextval, 'sandbox-cleanup-bunch', 'Clean up sandbox', '');

INSERT INTO rhnTaskoBunch (id, name, description, org_bunch)
             VALUES (rhn_tasko_bunch_id_seq.nextval, 'repo-sync-bunch', 'Used for syncing repos to a channel', '');

INSERT INTO rhnTaskoBunch (id, name, description, org_bunch)
             VALUES (rhn_tasko_bunch_id_seq.nextval, 'package-cleanup-bunch', 'Cleans up orphaned packages', '');

INSERT INTO rhnTaskoBunch (id, name, description, org_bunch)
             VALUES (rhn_tasko_bunch_id_seq.nextval, 'kickstartfile-sync-bunch', 'Syncs kickstart profiles that were generated using the wizard', '');

INSERT INTO rhnTaskoBunch (id, name, description, org_bunch)
             VALUES (rhn_tasko_bunch_id_seq.nextval, 'kickstart-cleanup-bunch', 'Cleans up stale Kickstarts', '');

INSERT INTO rhnTaskoBunch (id, name, description, org_bunch)
             VALUES (rhn_tasko_bunch_id_seq.nextval, 'errata-queue-bunch', 'Processes errata', '');

INSERT INTO rhnTaskoBunch (id, name, description, org_bunch)
             VALUES (rhn_tasko_bunch_id_seq.nextval, 'errata-cache-bunch', 'Performs errata cache recalc for a given server or channel', '');

INSERT INTO rhnTaskoBunch (id, name, description, org_bunch)
             VALUES (rhn_tasko_bunch_id_seq.nextval, 'channel-repodata-bunch', 'Generates channel repodata', '');

INSERT INTO rhnTaskoBunch (id, name, description, org_bunch)
             VALUES (rhn_tasko_bunch_id_seq.nextval, 'satcert-check-bunch', 'Checks whether satellite certificate has not expired', '');

INSERT INTO rhnTaskoBunch (id, name, description, org_bunch)
             VALUES (rhn_tasko_bunch_id_seq.nextval, 'cleanup-data-bunch', 'Cleans up orphaned and outdated data', null);

commit;
   07070100000574000081B400000000000000000000000167AE111400000F33000000000000000000000000000000000000006200000000susemanager-schema/upgrade/spacewalk-schema-1.1-to-spacewalk-schema-1.2/021-rhnTaskoTask_data.sql --
-- Copyright (c) 2010 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


INSERT INTO rhnTaskoTask (id, name, class)
         VALUES (rhn_tasko_task_id_seq.nextval, 'repo-sync', 'com.redhat.rhn.taskomatic.task.RepoSyncTask');

INSERT INTO rhnTaskoTask (id, name, class)
         VALUES (rhn_tasko_task_id_seq.nextval, 'satellite-sync', 'com.redhat.rhn.taskomatic.task.SatSyncTask');

INSERT INTO rhnTaskoTask (id, name, class)
         VALUES (rhn_tasko_task_id_seq.nextval, 'kickstartfile-sync', 'com.redhat.rhn.taskomatic.task.KickstartFileSyncTask');

INSERT INTO rhnTaskoTask (id, name, class)
         VALUES (rhn_tasko_task_id_seq.nextval, 'kickstart-cleanup', 'com.redhat.rhn.taskomatic.task.KickstartCleanup');

INSERT INTO rhnTaskoTask (id, name, class)
         VALUES (rhn_tasko_task_id_seq.nextval, 'errata-cache', 'com.redhat.rhn.taskomatic.task.ErrataCacheTask');

INSERT INTO rhnTaskoTask (id, name, class)
         VALUES (rhn_tasko_task_id_seq.nextval, 'errata-queue', 'com.redhat.rhn.taskomatic.task.ErrataQueue');

INSERT INTO rhnTaskoTask (id, name, class)
         VALUES (rhn_tasko_task_id_seq.nextval, 'errata-mailer', 'com.redhat.rhn.taskomatic.task.ErrataMailer');

INSERT INTO rhnTaskoTask (id, name, class)
         VALUES (rhn_tasko_task_id_seq.nextval, 'sandbox-cleanup', 'com.redhat.rhn.taskomatic.task.SandboxCleanup');

INSERT INTO rhnTaskoTask (id, name, class)
         VALUES (rhn_tasko_task_id_seq.nextval, 'session-cleanup', 'com.redhat.rhn.taskomatic.task.SessionCleanup');

INSERT INTO rhnTaskoTask (id, name, class)
         VALUES (rhn_tasko_task_id_seq.nextval, 'channel-repodata', 'com.redhat.rhn.taskomatic.task.ChannelRepodata');

INSERT INTO rhnTaskoTask (id, name, class)
         VALUES (rhn_tasko_task_id_seq.nextval, 'package-cleanup', 'com.redhat.rhn.taskomatic.task.PackageCleanup');

INSERT INTO rhnTaskoTask (id, name, class)
         VALUES (rhn_tasko_task_id_seq.nextval, 'cobbler-sync', 'com.redhat.rhn.taskomatic.task.CobblerSyncTask');

INSERT INTO rhnTaskoTask (id, name, class)
         VALUES (rhn_tasko_task_id_seq.nextval, 'daily-summary', 'com.redhat.rhn.taskomatic.task.DailySummary');

INSERT INTO rhnTaskoTask (id, name, class)
         VALUES (rhn_tasko_task_id_seq.nextval, 'summary-population', 'com.redhat.rhn.taskomatic.task.SummaryPopulation');

INSERT INTO rhnTaskoTask (id, name, class)
         VALUES (rhn_tasko_task_id_seq.nextval, 'compare-config-files', 'com.redhat.rhn.taskomatic.task.CompareConfigFilesTask');

INSERT INTO rhnTaskoTask (id, name, class)
         VALUES (rhn_tasko_task_id_seq.nextval, 'clean-current-alerts', 'com.redhat.rhn.taskomatic.task.CleanCurrentAlerts');

INSERT INTO rhnTaskoTask (id, name, class)
         VALUES (rhn_tasko_task_id_seq.nextval, 'sync-probe-state', 'com.redhat.rhn.taskomatic.task.SynchProbeState');

INSERT INTO rhnTaskoTask (id, name, class)
         VALUES (rhn_tasko_task_id_seq.nextval, 'sat-cert-check', 'com.redhat.rhn.taskomatic.task.SatelliteCertificateCheck');

INSERT INTO rhnTaskoTask (id, name, class)
         VALUES (rhn_tasko_task_id_seq.nextval, 'clear-log-history', 'com.redhat.rhn.taskomatic.task.ClearLogHistory');

INSERT INTO rhnTaskoTask (id, name, class)
         VALUES (rhn_tasko_task_id_seq.nextval, 'cleanup-timeseries-data', 'com.redhat.rhn.taskomatic.task.TimeSeriesCleanUp');

commit;
 07070100000575000081B400000000000000000000000167AE111400001D39000000000000000000000000000000000000006600000000susemanager-schema/upgrade/spacewalk-schema-1.1-to-spacewalk-schema-1.2/022-rhnTaskoTemplate_data.sql --
-- Copyright (c) 2010 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


INSERT INTO rhnTaskoTemplate (id, bunch_id, task_id, ordering, start_if)
             VALUES (rhn_tasko_template_id_seq.nextval,
                        (SELECT id FROM rhnTaskoBunch WHERE name='daily-status-bunch'),
                        (SELECT id FROM rhnTaskoTask WHERE name='summary-population'),
                        0,
                        '');

INSERT INTO rhnTaskoTemplate (id, bunch_id, task_id, ordering, start_if)
             VALUES (rhn_tasko_template_id_seq.nextval,
                         (SELECT id FROM rhnTaskoBunch WHERE name='daily-status-bunch'),
                         (SELECT id FROM rhnTaskoTask WHERE name='daily-summary'),
                         1,
                         'FINISHED');

INSERT INTO rhnTaskoTemplate (id, bunch_id, task_id, ordering, start_if)
             VALUES (rhn_tasko_template_id_seq.nextval,
                        (SELECT id FROM rhnTaskoBunch WHERE name='sat-sync-bunch'),
                        (SELECT id FROM rhnTaskoTask WHERE name='satellite-sync'),
                        0,
                        '');

INSERT INTO rhnTaskoTemplate (id, bunch_id, task_id, ordering, start_if)
             VALUES (rhn_tasko_template_id_seq.nextval,
                        (SELECT id FROM rhnTaskoBunch WHERE name='clear-taskologs-bunch'),
                        (SELECT id FROM rhnTaskoTask WHERE name='clear-log-history'),
                        0,
                        '');

INSERT INTO rhnTaskoTemplate (id, bunch_id, task_id, ordering, start_if)
             VALUES (rhn_tasko_template_id_seq.nextval,
                        (SELECT id FROM rhnTaskoBunch WHERE name='cobbler-sync-bunch'),
                        (SELECT id FROM rhnTaskoTask WHERE name='cobbler-sync'),
                        0,
                        '');

INSERT INTO rhnTaskoTemplate (id, bunch_id, task_id, ordering, start_if)
             VALUES (rhn_tasko_template_id_seq.nextval,
                        (SELECT id FROM rhnTaskoBunch WHERE name='compare-configs-bunch'),
                        (SELECT id FROM rhnTaskoTask WHERE name='compare-config-files'),
                        0,
                        '');

INSERT INTO rhnTaskoTemplate (id, bunch_id, task_id, ordering, start_if)
             VALUES (rhn_tasko_template_id_seq.nextval,
                        (SELECT id FROM rhnTaskoBunch WHERE name='clean-alerts-bunch'),
                        (SELECT id FROM rhnTaskoTask WHERE name='clean-current-alerts'),
                        0,
                        '');

INSERT INTO rhnTaskoTemplate (id, bunch_id, task_id, ordering, start_if)
             VALUES (rhn_tasko_template_id_seq.nextval,
                        (SELECT id FROM rhnTaskoBunch WHERE name='sync-probe-bunch'),
                        (SELECT id FROM rhnTaskoTask WHERE name='sync-probe-state'),
                        0,
                        '');

INSERT INTO rhnTaskoTemplate (id, bunch_id, task_id, ordering, start_if)
             VALUES (rhn_tasko_template_id_seq.nextval,
                        (SELECT id FROM rhnTaskoBunch WHERE name='session-cleanup-bunch'),
                        (SELECT id FROM rhnTaskoTask WHERE name='session-cleanup'),
                        0,
                        '');

INSERT INTO rhnTaskoTemplate (id, bunch_id, task_id, ordering, start_if)
             VALUES (rhn_tasko_template_id_seq.nextval,
                        (SELECT id FROM rhnTaskoBunch WHERE name='sandbox-cleanup-bunch'),
                        (SELECT id FROM rhnTaskoTask WHERE name='sandbox-cleanup'),
                        0,
                        '');

INSERT INTO rhnTaskoTemplate (id, bunch_id, task_id, ordering, start_if)
             VALUES (rhn_tasko_template_id_seq.nextval,
                        (SELECT id FROM rhnTaskoBunch WHERE name='repo-sync-bunch'),
                        (SELECT id FROM rhnTaskoTask WHERE name='repo-sync'),
                        0,
                        '');

INSERT INTO rhnTaskoTemplate (id, bunch_id, task_id, ordering, start_if)
             VALUES (rhn_tasko_template_id_seq.nextval,
                        (SELECT id FROM rhnTaskoBunch WHERE name='package-cleanup-bunch'),
                        (SELECT id FROM rhnTaskoTask WHERE name='package-cleanup'),
                        0,
                        '');

INSERT INTO rhnTaskoTemplate (id, bunch_id, task_id, ordering, start_if)
             VALUES (rhn_tasko_template_id_seq.nextval,
                        (SELECT id FROM rhnTaskoBunch WHERE name='kickstartfile-sync-bunch'),
                        (SELECT id FROM rhnTaskoTask WHERE name='kickstartfile-sync'),
                        0,
                        '');

INSERT INTO rhnTaskoTemplate (id, bunch_id, task_id, ordering, start_if)
             VALUES (rhn_tasko_template_id_seq.nextval,
                        (SELECT id FROM rhnTaskoBunch WHERE name='kickstart-cleanup-bunch'),
                        (SELECT id FROM rhnTaskoTask WHERE name='kickstart-cleanup'),
                        0,
                        '');

INSERT INTO rhnTaskoTemplate (id, bunch_id, task_id, ordering, start_if)
             VALUES (rhn_tasko_template_id_seq.nextval,
                        (SELECT id FROM rhnTaskoBunch WHERE name='errata-queue-bunch'),
                        (SELECT id FROM rhnTaskoTask WHERE name='errata-queue'),
                        0,
                        '');

INSERT INTO rhnTaskoTemplate (id, bunch_id, task_id, ordering, start_if)
             VALUES (rhn_tasko_template_id_seq.nextval,
                        (SELECT id FROM rhnTaskoBunch WHERE name='errata-queue-bunch'),
                        (SELECT id FROM rhnTaskoTask WHERE name='errata-mailer'),
                        1,
                        '');

INSERT INTO rhnTaskoTemplate (id, bunch_id, task_id, ordering, start_if)
             VALUES (rhn_tasko_template_id_seq.nextval,
                        (SELECT id FROM rhnTaskoBunch WHERE name='channel-repodata-bunch'),
                        (SELECT id FROM rhnTaskoTask WHERE name='channel-repodata'),
                        0,
                        '');

INSERT INTO rhnTaskoTemplate (id, bunch_id, task_id, ordering, start_if)
             VALUES (rhn_tasko_template_id_seq.nextval,
                        (SELECT id FROM rhnTaskoBunch WHERE name='satcert-check-bunch'),
                        (SELECT id FROM rhnTaskoTask WHERE name='sat-cert-check'),
                        0,
                        '');

INSERT INTO rhnTaskoTemplate (id, bunch_id, task_id, ordering, start_if)
             VALUES (rhn_tasko_template_id_seq.nextval,
                        (SELECT id FROM rhnTaskoBunch WHERE name='cleanup-data-bunch'),
                        (SELECT id FROM rhnTaskoTask WHERE name='cleanup-timeseries-data'),
                        0,
                        null);

commit;
   07070100000576000081B400000000000000000000000167AE11140000146D000000000000000000000000000000000000006600000000susemanager-schema/upgrade/spacewalk-schema-1.1-to-spacewalk-schema-1.2/023-rhnTaskoSchedule_data.sql --
-- Copyright (c) 2010 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

-- Top of every minute
INSERT INTO rhnTaskoSchedule (id, job_label, bunch_id, active_from, cron_expr)
    VALUES(rhn_tasko_schedule_id_seq.nextval, 'sync-probe-default',
        (SELECT id FROM rhnTaskoBunch WHERE name='sync-probe-bunch'),
        sysdate, '0 * * * * ?');

INSERT INTO rhnTaskoSchedule (id, job_label, bunch_id, active_from, cron_expr)
    VALUES(rhn_tasko_schedule_id_seq.nextval, 'errata-queue-default',
        (SELECT id FROM rhnTaskoBunch WHERE name='errata-queue-bunch'),
        sysdate, '0 * * * * ?');

INSERT INTO rhnTaskoSchedule (id, job_label, bunch_id, active_from, cron_expr)
    VALUES(rhn_tasko_schedule_id_seq.nextval, 'cobbler-sync-default',
        (SELECT id FROM rhnTaskoBunch WHERE name='cobbler-sync-bunch'),
        sysdate, '0 * * * * ?');

INSERT INTO rhnTaskoSchedule (id, job_label, bunch_id, active_from, cron_expr)
    VALUES(rhn_tasko_schedule_id_seq.nextval, 'channel-repodata-default',
        (SELECT id FROM rhnTaskoBunch WHERE name='channel-repodata-bunch'),
        sysdate, '0 * * * * ?');

INSERT INTO rhnTaskoSchedule (id, job_label, bunch_id, active_from, cron_expr)
    VALUES(rhn_tasko_schedule_id_seq.nextval, 'repo-sync-default',
        (SELECT id FROM rhnTaskoBunch WHERE name='repo-sync-bunch'),
        sysdate, '0 * * * * ?');

-- Every 10 minutes

INSERT INTO rhnTaskoSchedule (id, job_label, bunch_id, active_from, cron_expr)
    VALUES(rhn_tasko_schedule_id_seq.nextval, 'package-cleanup-default',
        (SELECT id FROM rhnTaskoBunch WHERE name='package-cleanup-bunch'),
        sysdate, '0 0/10 * * * ?');

INSERT INTO rhnTaskoSchedule (id, job_label, bunch_id, active_from, cron_expr)
    VALUES(rhn_tasko_schedule_id_seq.nextval, 'kickstart-cleanup-default',
        (SELECT id FROM rhnTaskoBunch WHERE name='kickstart-cleanup-bunch'),
        sysdate, '0 0/10 * * * ?');

INSERT INTO rhnTaskoSchedule (id, job_label, bunch_id, active_from, cron_expr)
    VALUES(rhn_tasko_schedule_id_seq.nextval, 'errata-cache-default',
        (SELECT id FROM rhnTaskoBunch WHERE name='errata-cache-bunch'),
        sysdate, '0 0/10 * * * ?');

INSERT INTO rhnTaskoSchedule (id, job_label, bunch_id, active_from, cron_expr)
    VALUES(rhn_tasko_schedule_id_seq.nextval, 'kickstartfile-sync-default',
        (SELECT id FROM rhnTaskoBunch WHERE name='kickstartfile-sync-bunch'),
        sysdate, '0 0/10 * * * ?');

-- Every 15 minutes

INSERT INTO rhnTaskoSchedule (id, job_label, bunch_id, active_from, cron_expr)
    VALUES(rhn_tasko_schedule_id_seq.nextval, 'session-cleanup-default',
        (SELECT id FROM rhnTaskoBunch WHERE name='session-cleanup-bunch'),
        sysdate, '0 0/15 * * * ?');

-- Once a day at 4:05:00 AM (beware of 2AM cronjobs)

INSERT INTO rhnTaskoSchedule (id, job_label, bunch_id, active_from, cron_expr)
    VALUES(rhn_tasko_schedule_id_seq.nextval, 'sandbox-cleanup-default',
        (SELECT id FROM rhnTaskoBunch WHERE name='sandbox-cleanup-bunch'),
        sysdate, '0 5 4 ? * *');

-- Once a day at 4:35:00 AM (beware of 2AM cronjobs)

INSERT INTO rhnTaskoSchedule (id, job_label, bunch_id, active_from, cron_expr)
    VALUES(rhn_tasko_schedule_id_seq.nextval, 'clean-alerts-default',
        (SELECT id FROM rhnTaskoBunch WHERE name='clean-alerts-bunch'),
        sysdate, '0 35 4 ? * *');

-- Once a day at 11:00 PM

INSERT INTO rhnTaskoSchedule (id, job_label, bunch_id, active_from, cron_expr)
    VALUES(rhn_tasko_schedule_id_seq.nextval, 'daily-status-default',
        (SELECT id FROM rhnTaskoBunch WHERE name='daily-status-bunch'),
        sysdate, '0 0 23 ? * *');

INSERT INTO rhnTaskoSchedule (id, job_label, bunch_id, active_from, cron_expr)
    VALUES(rhn_tasko_schedule_id_seq.nextval, 'compare-configs-default',
        (SELECT id FROM rhnTaskoBunch WHERE name='compare-configs-bunch'),
        sysdate, '0 0 23 ? * *');

INSERT INTO rhnTaskoSchedule (id, job_label, bunch_id, active_from, cron_expr)
    VALUES(rhn_tasko_schedule_id_seq.nextval, 'satcert-check-default',
        (SELECT id FROM rhnTaskoBunch WHERE name='satcert-check-bunch'),
        sysdate, '0 0 23 ? * *');

INSERT INTO rhnTaskoSchedule (id, job_label, bunch_id, active_from, cron_expr)
    VALUES(rhn_tasko_schedule_id_seq.nextval, 'clear-taskologs-default',
        (SELECT id FROM rhnTaskoBunch WHERE name='clear-taskologs-bunch'),
        sysdate, '0 0 23 ? * *');

INSERT INTO rhnTaskoSchedule (id, job_label, bunch_id, active_from, cron_expr)
    VALUES(rhn_tasko_schedule_id_seq.nextval, 'cleanup-data-default',
        (SELECT id FROM rhnTaskoBunch WHERE name='cleanup-data-bunch'),
        sysdate, '0 0 23 ? * *');
   07070100000577000081B400000000000000000000000167AE111400000052000000000000000000000000000000000000006300000000susemanager-schema/upgrade/spacewalk-schema-1.1-to-spacewalk-schema-1.2/024-rhnTaskoBunch_data.sql    UPDATE rhnTaskoBunch set org_bunch = 'Y' WHERE name = 'repo-sync-bunch';

commit;
  07070100000578000081B400000000000000000000000167AE1114000000D1000000000000000000000000000000000000005C00000000susemanager-schema/upgrade/spacewalk-schema-1.1-to-spacewalk-schema-1.2/025-rhnTaskoRun.sql   ALTER TABLE rhnTaskoRun DROP CONSTRAINT rhn_tasko_run_schedule_fk;
ALTER TABLE rhnTaskoRun ADD CONSTRAINT rhn_tasko_run_schedule_fk FOREIGN KEY (schedule_id) REFERENCES rhnTaskoSchedule(id) ON DELETE CASCADE;
   07070100000579000081B400000000000000000000000167AE11140000004C000000000000000000000000000000000000006600000000susemanager-schema/upgrade/spacewalk-schema-1.1-to-spacewalk-schema-1.2/026-rhnTaskoSchedule_data.sql DELETE FROM rhnTaskoSchedule WHERE job_label='repo-sync-default';

commit;

0707010000057A000081B400000000000000000000000167AE111400000162000000000000000000000000000000000000006600000000susemanager-schema/upgrade/spacewalk-schema-1.1-to-spacewalk-schema-1.2/027-rhnTaskoTemplate_data.sql INSERT INTO rhnTaskoTemplate (id, bunch_id, task_id, ordering, start_if)
             VALUES (rhn_tasko_template_id_seq.nextval,
                        (SELECT id FROM rhnTaskoBunch WHERE name='errata-cache-bunch'),
                        (SELECT id FROM rhnTaskoTask WHERE name='errata-cache'),
                        0,
                        '');
  0707010000057B000081B400000000000000000000000167AE1114000000CB000000000000000000000000000000000000006600000000susemanager-schema/upgrade/spacewalk-schema-1.1-to-spacewalk-schema-1.2/028-rhnTaskoTemplate_data.sql UPDATE rhnTaskoTemplate
SET bunch_id = (SELECT id FROM rhnTaskoBunch WHERE name='errata-cache-bunch'),
    start_if = 'FINISHED'
WHERE task_id = (SELECT id FROM rhnTaskoTask WHERE name='errata-mailer');
 0707010000057C000081B400000000000000000000000167AE1114000014FC000000000000000000000000000000000000005500000000susemanager-schema/upgrade/spacewalk-schema-1.1-to-spacewalk-schema-1.2/030-qrtz.sql  --
-- A hint submitted by a user: Oracle DB MUST be created as "shared" and the
-- job_queue_processes parameter  must be greater than 2, otherwise a DB lock
-- will happen.   However, these settings are pretty much standard after any
-- Oracle install, so most users need not worry about this.
--
-- Many other users (including the primary author of Quartz) have had success
-- runing in dedicated mode, so only consider the above as a hint ;-)
--

CREATE TABLE qrtz_job_details
  (
    JOB_NAME  VARCHAR2(200) NOT NULL,
    JOB_GROUP VARCHAR2(200) NOT NULL,
    DESCRIPTION VARCHAR2(250) NULL,
    JOB_CLASS_NAME   VARCHAR2(250) NOT NULL,
    IS_DURABLE VARCHAR2(1) NOT NULL,
    IS_VOLATILE VARCHAR2(1) NOT NULL,
    IS_STATEFUL VARCHAR2(1) NOT NULL,
    REQUESTS_RECOVERY VARCHAR2(1) NOT NULL,
    JOB_DATA BLOB NULL,
    PRIMARY KEY (JOB_NAME,JOB_GROUP)
);
CREATE TABLE qrtz_job_listeners
  (
    JOB_NAME  VARCHAR2(200) NOT NULL,
    JOB_GROUP VARCHAR2(200) NOT NULL,
    JOB_LISTENER VARCHAR2(200) NOT NULL,
    PRIMARY KEY (JOB_NAME,JOB_GROUP,JOB_LISTENER),
    FOREIGN KEY (JOB_NAME,JOB_GROUP)
	REFERENCES QRTZ_JOB_DETAILS(JOB_NAME,JOB_GROUP)
);
CREATE TABLE qrtz_triggers
  (
    TRIGGER_NAME VARCHAR2(200) NOT NULL,
    TRIGGER_GROUP VARCHAR2(200) NOT NULL,
    JOB_NAME  VARCHAR2(200) NOT NULL,
    JOB_GROUP VARCHAR2(200) NOT NULL,
    IS_VOLATILE VARCHAR2(1) NOT NULL,
    DESCRIPTION VARCHAR2(250) NULL,
    NEXT_FIRE_TIME NUMBER(13) NULL,
    PREV_FIRE_TIME NUMBER(13) NULL,
    PRIORITY NUMBER(13) NULL,
    TRIGGER_STATE VARCHAR2(16) NOT NULL,
    TRIGGER_TYPE VARCHAR2(8) NOT NULL,
    START_TIME NUMBER(13) NOT NULL,
    END_TIME NUMBER(13) NULL,
    CALENDAR_NAME VARCHAR2(200) NULL,
    MISFIRE_INSTR NUMBER(2) NULL,
    JOB_DATA BLOB NULL,
    PRIMARY KEY (TRIGGER_NAME,TRIGGER_GROUP),
    FOREIGN KEY (JOB_NAME,JOB_GROUP)
	REFERENCES QRTZ_JOB_DETAILS(JOB_NAME,JOB_GROUP)
);
CREATE TABLE qrtz_simple_triggers
  (
    TRIGGER_NAME VARCHAR2(200) NOT NULL,
    TRIGGER_GROUP VARCHAR2(200) NOT NULL,
    REPEAT_COUNT NUMBER(7) NOT NULL,
    REPEAT_INTERVAL NUMBER(12) NOT NULL,
    TIMES_TRIGGERED NUMBER(10) NOT NULL,
    PRIMARY KEY (TRIGGER_NAME,TRIGGER_GROUP),
    FOREIGN KEY (TRIGGER_NAME,TRIGGER_GROUP)
	REFERENCES QRTZ_TRIGGERS(TRIGGER_NAME,TRIGGER_GROUP)
);
CREATE TABLE qrtz_cron_triggers
  (
    TRIGGER_NAME VARCHAR2(200) NOT NULL,
    TRIGGER_GROUP VARCHAR2(200) NOT NULL,
    CRON_EXPRESSION VARCHAR2(120) NOT NULL,
    TIME_ZONE_ID VARCHAR2(80),
    PRIMARY KEY (TRIGGER_NAME,TRIGGER_GROUP),
    FOREIGN KEY (TRIGGER_NAME,TRIGGER_GROUP)
	REFERENCES QRTZ_TRIGGERS(TRIGGER_NAME,TRIGGER_GROUP)
);
CREATE TABLE qrtz_blob_triggers
  (
    TRIGGER_NAME VARCHAR2(200) NOT NULL,
    TRIGGER_GROUP VARCHAR2(200) NOT NULL,
    BLOB_DATA BLOB NULL,
    PRIMARY KEY (TRIGGER_NAME,TRIGGER_GROUP),
    FOREIGN KEY (TRIGGER_NAME,TRIGGER_GROUP)
        REFERENCES QRTZ_TRIGGERS(TRIGGER_NAME,TRIGGER_GROUP)
);
CREATE TABLE qrtz_trigger_listeners
  (
    TRIGGER_NAME  VARCHAR2(200) NOT NULL,
    TRIGGER_GROUP VARCHAR2(200) NOT NULL,
    TRIGGER_LISTENER VARCHAR2(200) NOT NULL,
    PRIMARY KEY (TRIGGER_NAME,TRIGGER_GROUP,TRIGGER_LISTENER),
    FOREIGN KEY (TRIGGER_NAME,TRIGGER_GROUP)
	REFERENCES QRTZ_TRIGGERS(TRIGGER_NAME,TRIGGER_GROUP)
);
CREATE TABLE qrtz_calendars
  (
    CALENDAR_NAME  VARCHAR2(200) NOT NULL,
    CALENDAR BLOB NOT NULL,
    PRIMARY KEY (CALENDAR_NAME)
);
CREATE TABLE qrtz_paused_trigger_grps
  (
    TRIGGER_GROUP  VARCHAR2(200) NOT NULL,
    PRIMARY KEY (TRIGGER_GROUP)
);
CREATE TABLE qrtz_fired_triggers
  (
    ENTRY_ID VARCHAR2(95) NOT NULL,
    TRIGGER_NAME VARCHAR2(200) NOT NULL,
    TRIGGER_GROUP VARCHAR2(200) NOT NULL,
    IS_VOLATILE VARCHAR2(1) NOT NULL,
    INSTANCE_NAME VARCHAR2(200) NOT NULL,
    FIRED_TIME NUMBER(13) NOT NULL,
    PRIORITY NUMBER(13) NOT NULL,
    STATE VARCHAR2(16) NOT NULL,
    JOB_NAME VARCHAR2(200) NULL,
    JOB_GROUP VARCHAR2(200) NULL,
    IS_STATEFUL VARCHAR2(1) NULL,
    REQUESTS_RECOVERY VARCHAR2(1) NULL,
    PRIMARY KEY (ENTRY_ID)
);
CREATE TABLE qrtz_scheduler_state
  (
    INSTANCE_NAME VARCHAR2(200) NOT NULL,
    LAST_CHECKIN_TIME NUMBER(13) NOT NULL,
    CHECKIN_INTERVAL NUMBER(13) NOT NULL,
    PRIMARY KEY (INSTANCE_NAME)
);
CREATE TABLE qrtz_locks
  (
    LOCK_NAME  VARCHAR2(40) NOT NULL,
    PRIMARY KEY (LOCK_NAME)
);

create index idx_qrtz_j_req_recovery on qrtz_job_details(REQUESTS_RECOVERY);
create index idx_qrtz_t_next_fire_time on qrtz_triggers(NEXT_FIRE_TIME);
create index idx_qrtz_t_state on qrtz_triggers(TRIGGER_STATE);
create index idx_qrtz_t_nft_st on qrtz_triggers(NEXT_FIRE_TIME,TRIGGER_STATE);
create index idx_qrtz_t_volatile on qrtz_triggers(IS_VOLATILE);
create index idx_qrtz_ft_trig_name on qrtz_fired_triggers(TRIGGER_NAME);
create index idx_qrtz_ft_trig_group on qrtz_fired_triggers(TRIGGER_GROUP);
create index idx_qrtz_ft_trig_nm_gp on qrtz_fired_triggers(TRIGGER_NAME,TRIGGER_GROUP);
create index idx_qrtz_ft_trig_volatile on qrtz_fired_triggers(IS_VOLATILE);
create index idx_qrtz_ft_trig_inst_name on qrtz_fired_triggers(INSTANCE_NAME);
create index idx_qrtz_ft_job_name on qrtz_fired_triggers(JOB_NAME);
create index idx_qrtz_ft_job_group on qrtz_fired_triggers(JOB_GROUP);
create index idx_qrtz_ft_job_stateful on qrtz_fired_triggers(IS_STATEFUL);
create index idx_qrtz_ft_job_req_recovery on qrtz_fired_triggers(REQUESTS_RECOVERY);
0707010000057D000081B400000000000000000000000167AE1114000002B2000000000000000000000000000000000000005A00000000susemanager-schema/upgrade/spacewalk-schema-1.1-to-spacewalk-schema-1.2/031-qrtz_data.sql --
-- A hint submitted by a user: Oracle DB MUST be created as "shared" and the
-- job_queue_processes parameter  must be greater than 2, otherwise a DB lock
-- will happen.   However, these settings are pretty much standard after any
-- Oracle install, so most users need not worry about this.
--
-- Many other users (including the primary author of Quartz) have had success
-- runing in dedicated mode, so only consider the above as a hint ;-)
--

INSERT INTO qrtz_locks values('TRIGGER_ACCESS');
INSERT INTO qrtz_locks values('JOB_ACCESS');
INSERT INTO qrtz_locks values('CALENDAR_ACCESS');
INSERT INTO qrtz_locks values('STATE_ACCESS');
INSERT INTO qrtz_locks values('MISFIRE_ACCESS');
  0707010000057E000081B400000000000000000000000167AE11140000001D000000000000000000000000000000000000006200000000susemanager-schema/upgrade/spacewalk-schema-1.1-to-spacewalk-schema-1.2/040-queue_errata-drop.sql drop procedure queue_errata;
   0707010000057F000081B400000000000000000000000167AE11140000029D000000000000000000000000000000000000005F00000000susemanager-schema/upgrade/spacewalk-schema-1.1-to-spacewalk-schema-1.2/040-update-ks-data.sql    --
-- Copyright (c) 2010 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

alter table rhnKsData add partition_data blob;
   07070100000580000081B400000000000000000000000167AE11140000001E000000000000000000000000000000000000006700000000susemanager-schema/upgrade/spacewalk-schema-1.1-to-spacewalk-schema-1.2/041-rhnSNPErrataQueue-drop.sql    drop table rhnSNPErrataQueue;
  07070100000581000081B400000000000000000000000167AE11140000096A000000000000000000000000000000000000006C00000000susemanager-schema/upgrade/spacewalk-schema-1.1-to-spacewalk-schema-1.2/041-update_kickstart_partitions.sql   declare
  lob_data blob;

  function gen_part_line(cname in varchar2, arg in varchar2)
  return varchar2
  is
      ret varchar2(4000);
  begin
      ret := case cname
                  when 'partitions' then 'part'
                  when 'raids' then 'raid'
                  when 'volgroups' then 'volgroup'
                  when 'logvols' then 'logvol'
                  when 'include' then '%include'
                  when 'custom_partition' then NULL
             end;
      if arg like 'swap%'
         and arg not like 'swap %'
         and arg not like 'swap.%' then
          ret := ret || ' swap' || substr(arg, instr(arg,' '));
      else
          ret := ret || ' ' || arg;
      end if;
      return trim(ret);
  end gen_part_line;

begin
    for kickstart in (
        select distinct kc.kickstart_id
          from rhnKickstartCommand kc
         inner join rhnKickstartCommandName kcn
            on kcn.id = kc.ks_command_name_id
         where kcn.name in ('partitions', 'raids', 'volgroups', 'logvols', 'include', 'custom_partition')
         order by kc.kickstart_id
    ) loop

        update rhnKSData
           set partition_data = empty_blob()
         where id = kickstart.kickstart_id
        returning partition_data into lob_data;

        for command in (
                select kcn.name, kc.arguments
                  from rhnKickstartCommand kc
                 inner join rhnKickstartCommandName kcn
                    on kcn.id = kc.ks_command_name_id
                 where kcn.name in ('partitions', 'raids', 'volgroups', 'logvols', 'include', 'custom_partition')
                   and kc.kickstart_id = kickstart.kickstart_id
                 order by kcn.sort_order, kc.arguments
        ) loop
           if length(lob_data) > 0 then
               dbms_lob.append(lob_data, utl_raw.cast_to_raw(chr(10)));
           end if;
           dbms_lob.append(lob_data, utl_raw.cast_to_raw(gen_part_line(command.name, command.arguments)));
        end loop;

    end loop;

    delete from rhnKickstartCommand
     where ks_command_name_id in (
                select id
                  from rhnKickstartCommandName
                 where name in ('partitions','raids', 'volgroups','logvols','include','custom_partition'));

    delete from rhnKickstartCommandName
     where name in ('partitions', 'raids', 'volgroups', 'logvols', 'include', 'custom_partition');

end;
/
  07070100000582000081B400000000000000000000000167AE11140000001E000000000000000000000000000000000000006700000000susemanager-schema/upgrade/spacewalk-schema-1.1-to-spacewalk-schema-1.2/042-rhnSNPServerQueue-drop.sql    drop table rhnSNPServerQueue;
  07070100000583000081B400000000000000000000000167AE111400000369000000000000000000000000000000000000006C00000000susemanager-schema/upgrade/spacewalk-schema-1.1-to-spacewalk-schema-1.2/051-rhnChannelNewestPackageView.sql   create or replace view
rhnChannelNewestPackageView
as
SELECT m.channel_id          as channel_id,
       p.name_id             as name_id,
       p.evr_id              as evr_id,
       m.package_arch_id     as package_arch_id,
       p.id                  as package_id
FROM
    (select max(pe.evr) AS max_evr,
         cp.channel_id,
         p.name_id,
         p.package_arch_id
        from rhnPackageEVR       pe,
         rhnPackage          p,
         rhnChannelPackage   cp
        where p.evr_id = pe.id
         and cp.package_id = p.id
        group by cp.channel_id, p.name_id, p.package_arch_id) m,
    rhnPackageEVR       pe,
    rhnPackage          p,
    rhnChannelPackage   chp
WHERE m.max_evr = pe.evr
AND m.name_id = p.name_id
AND m.package_arch_id = p.package_arch_id
AND p.evr_id = pe.id
AND chp.package_id = p.id
AND chp.channel_id = m.channel_id
;
   07070100000584000081B400000000000000000000000167AE11140000046A000000000000000000000000000000000000006100000000susemanager-schema/upgrade/spacewalk-schema-1.1-to-spacewalk-schema-1.2/052-rhnKSData-nobase.sql  --
-- Copyright (c) 2010--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

alter trigger rhn_ks_mod_trig disable;

alter table rhnKsData add (
    no_base         CHAR(1)
                        DEFAULT ('N') NOT NULL
                        CONSTRAINT rhn_ks_nobase_ck
                            CHECK (no_base in ( 'Y' , 'N' )),
    ignore_missing  CHAR(1)
                        DEFAULT ('N') NOT NULL
                        CONSTRAINT rhn_ks_ignore_missing_ck
                            CHECK (ignore_missing in ( 'Y' , 'N' ))
);

alter trigger rhn_ks_mod_trig enable;
  07070100000585000081B400000000000000000000000167AE1114000005F8000000000000000000000000000000000000006100000000susemanager-schema/upgrade/spacewalk-schema-1.1-to-spacewalk-schema-1.2/053-rhnContectSource.sql  DROP INDEX rhn_cs_uq;


BEGIN
FOR i IN
    (SELECT cs.id, keep.min_id
        FROM rhnContentSource cs,
        (SELECT org_id, type_id, source_url, min(id) min_id
            FROM rhnContentSource
            GROUP BY org_id, type_id, source_url
            HAVING count(*) > 1) keep
        WHERE cs.org_id = keep.org_id
        AND cs.type_id = keep.type_id
        AND cs.source_url = keep.source_url
        AND cs.id > keep.min_id)
LOOP
-- remap duplicate repo referencies in rhnChannelContentSource to the lowest one
    DELETE FROM rhnChannelContentSource
        WHERE source_id = i.id
        AND EXISTS
            (SELECT 1 FROM rhnChannelContentSource
                WHERE source_id = i.min_id);
    UPDATE rhnChannelContentSource
        SET source_id = i.min_id
        WHERE source_id = i.id;
-- delete repo duplicates
    DELETE FROM rhnContentSource
        WHERE id = i.id;
END LOOP;
END;
/

-- rename label duplicates
UPDATE rhnContentSource cs
    SET label = cs.label || cs.id
    WHERE cs.id IN
    (SELECT id FROM rhnContentSource cs,
        (SELECT org_id, label, min(id) min_id
            FROM rhnContentSource
            GROUP BY org_id, label
            HAVING count(*) > 1) keep
    WHERE cs.org_id = keep.org_id
    AND cs.label = keep.label
    AND cs.id > keep.min_id);


CREATE UNIQUE INDEX rhn_cs_label_uq
    ON rhnContentSource(org_id, label)
    tablespace [[64k_tbs]];
CREATE UNIQUE INDEX rhn_cs_repo_uq
    ON rhnContentSource(org_id, type_id, source_url)
    tablespace [[64k_tbs]];
07070100000586000081B400000000000000000000000167AE11140000008A000000000000000000000000000000000000006100000000susemanager-schema/upgrade/spacewalk-schema-1.1-to-spacewalk-schema-1.2/054-rhnTimezone_data.sql  INSERT INTO rhnTimezone (id, olson_name, display_name)
VALUES (rhn_timezone_id_seq.nextval,
        'America/Regina', 'Canada (Regina)');
  07070100000587000081B400000000000000000000000167AE1114000000FE000000000000000000000000000000000000006100000000susemanager-schema/upgrade/spacewalk-schema-1.1-to-spacewalk-schema-1.2/055-rhnTimezone_data.sql  UPDATE rhnTimezone SET display_name = 'New Zealand (Wallis)'
    WHERE olson_name = 'Pacific/Wallis';

INSERT INTO rhnTimezone (id, olson_name, display_name)
  VALUES (rhn_timezone_id_seq.nextval,
          'Pacific/Auckland', 'New Zealand (Auckland)');
  07070100000588000081B400000000000000000000000167AE11140000053E000000000000000000000000000000000000006C00000000susemanager-schema/upgrade/spacewalk-schema-1.1-to-spacewalk-schema-1.2/056-rhnUserReceiveNotifications.sql   --
-- Copyright (c) 2010 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--
--
--
--

create or replace view rhnUserReceiveNotifications
as
    select wc.org_id, usp.user_id, usp.server_id
    from rhnUserServerPerms usp
    left join rhnWebContactDisabled wcd
        on usp.user_id = wcd.id
    join web_contact wc
        on usp.user_id = wc.id
    join rhnUserInfo ui
        on usp.user_id = ui.user_id
        and ui.email_notify = 1
    join web_user_personal_info upi
        on usp.user_id = upi.web_user_id
        and upi.email is not null
    left join rhnUserServerPrefs uspr
        on uspr.server_id = usp.server_id
        and usp.user_id = uspr.user_id
        and uspr.name = 'receive_notifications'
        and value='0'
    where uspr.server_id is null
    and wcd.id is null;
  07070100000589000081B400000000000000000000000167AE111400002B2A000000000000000000000000000000000000005E00000000susemanager-schema/upgrade/spacewalk-schema-1.1-to-spacewalk-schema-1.2/057-delete_server.sql --
-- Copyright (c) 2008--2010 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
-- This deletes a server.  All codepaths which delete servers should hit this
-- or delete_server_bulk()

create or replace
procedure delete_server (
	server_id_in in number
) is
	cursor servergroups is
		select	server_id, server_group_id
		from	rhnServerGroupMembers sgm
		where	sgm.server_id = server_id_in;
	cursor configchannels is
		select	cc.id
		from	rhnConfigChannel cc,
			rhnConfigChannelType cct,
			rhnServerConfigChannel scc
		where	1=1
			and scc.server_id = server_id_in
			and scc.config_channel_id = cc.id
			-- these config channel types are reserved
			-- for use by a single server, so we don't
			-- need to check for other servers subscribed
			and cct.label in
				('local_override','server_import')
			and cct.id = cc.confchan_type_id;
        type filelistsid_t is table of rhnServerPreserveFileList.file_list_id%type;
        filelistsid_c filelistsid_t;

        type probesid_t is table of rhn_check_probe.probe_id%type;
        probesid_c probesid_t;

    is_virt number := 0;
begin
	rhn_channel.delete_server_channels(server_id_in);
	-- rhn_channel.clear_subscriptions(server_id_in);

        -- filelists
	select	spfl.file_list_id id bulk collect into filelistsid_c
	  from	rhnServerPreserveFileList spfl
	 where	spfl.server_id = server_id_in
			and not exists (
				select	1
				from	rhnServerPreserveFileList
				where	file_list_id = spfl.file_list_id
					and server_id != server_id_in
				union
				select	1
				from	rhnKickstartPreserveFileList
				where	file_list_id = spfl.file_list_id
			);
        if filelistsid_c.first is not null then
            forall i in filelistsid_c.first..filelistsid_c.last
                delete from rhnFileList where id = filelistsid_c(i);
        end if;

	for configchannel in configchannels loop
		rhn_config.delete_channel(configchannel.id);
	end loop;

      select count(1) into is_virt
        from rhnServerEntitlementView
       where server_id = server_id_in
         and label in ('virtualization_host', 'virtualization_host_platform')
         and rownum <= 1;

	for sgm in servergroups loop
		rhn_server.delete_from_servergroup(
			sgm.server_id, sgm.server_group_id);
	end loop;

    if is_virt = 1 then
        rhn_entitlements.repoll_virt_guest_entitlements(server_id_in);
    end if;

	-- we're handling this instead of letting an "on delete
	-- set null" do it so that we don't run the risk
	-- of setting off the triggers and killing us with a
	-- mutating table

	-- this is merge of two single updates:
        --  update ... set old_server_id = null where old_server_id = server_id_in;
        --  update ... set new_server_id = null where new_server_id = server_id_in;
        -- so we scan rhnKickstartSession table only once
	update rhnKickstartSession
		set old_server_id = case when old_server_id = server_id_in then null else old_server_id end,
		    new_server_id = case when new_server_id = server_id_in then null else new_server_id end
		where old_server_id = server_id_in 
		   or new_server_id = server_id_in;

	rhn_channel.clear_subscriptions(server_id_in,1);

    	-- A little complicated here, but the goal is to
	-- delete records from rhnVirtualInstace only if we don't
	-- care about them anymore.  We don't care about records
	-- in rhnVirtualInstance if we are deleting the host
	-- system and the virtual system is already null, or
	-- vice-versa.  We *do* care about them if either the
	-- host or virtual system is still registered because we
	-- still want them to show up in the UI.
    -- If there's a newer row in rhnVirtualInstance with the same
    -- uuid, this guest must have been re-registered, so we can clean
    -- this data up.
				
        delete from rhnVirtualInstance vi
	      where (host_system_id = server_id_in and virtual_system_id is null)
                 or (virtual_system_id = server_id_in and host_system_id is null)
                 or (vi.virtual_system_id = server_id_in and vi.modified < (select max(vi2.modified)
                    from rhnVirtualInstance vi2 where vi2.uuid = vi.uuid));
						
        -- this is merge of two single updates:
        --  update ... set host_system_id = null where host_system_id = server_id_in;
        --  update ... set virtual_system_id = null where virtual_system_id = server_id_in;
        -- so we scan rhnVirtualInstance table only once
        update rhnVirtualInstance
	   set host_system_id = case when host_system_id = server_id_in then null else host_system_id end,
	       virtual_system_id = case when virtual_system_id = server_id_in then null else virtual_system_id end
	 where host_system_id = server_id_in
	    or virtual_system_id = server_id_in;
		
        -- this is merge of two single updates:
        --  update ... set old_host_system_id = null when old_host_system_id = server_id_in;
        --  update ... set new_host_system_id = null when new_host_system_id = server_id_in;
        -- so we scan rhnVirtualInstanceEventLog table only once
	update rhnVirtualInstanceEventLog
	   set old_host_system_id = case when old_host_system_id = server_id_in then null else old_host_system_id end,
               new_host_system_id = case when new_host_system_id = server_id_in then null else new_host_system_id end
         where old_host_system_id = server_id_in
            or new_host_system_id = server_id_in;
		 
	-- We're deleting everything with a foreign key to rhnServer
	-- here, now.  I'm hoping this will help aleviate our deadlock
	-- problem.

	delete from rhnActionConfigChannel where server_id = server_id_in;
	delete from rhnActionConfigRevision where server_id = server_id_in;
	delete from rhnActionPackageRemovalFailure where server_id = server_id_in;
	delete from rhnClientCapability where server_id = server_id_in;
	delete from rhnCpu where server_id = server_id_in;
	-- there's still a cascade here, because the constraint keeps the
	-- table locked for too long to rebuild it.  Ugh...
	delete from rhnDevice where server_id = server_id_in;
	delete from rhnProxyInfo where server_id = server_id_in;
	delete from rhnRam where server_id = server_id_in;
	delete from rhnRegToken where server_id = server_id_in;
	delete from rhnSatelliteInfo where server_id = server_id_in;
	-- this cascades to rhnActionConfigChannel and rhnActionConfigFileName
	delete from rhnServerAction where server_id = server_id_in;
	delete from rhnServerActionPackageResult where server_id = server_id_in;
	delete from rhnServerActionScriptResult where server_id = server_id_in;
	delete from rhnServerActionVerifyResult where server_id = server_id_in;
	delete from rhnServerActionVerifyMissing where server_id = server_id_in;
	-- counts are handled above.  this should be a delete_ function.
	delete from rhnServerChannel where server_id = server_id_in;
	delete from rhnServerConfigChannel where server_id = server_id_in;
	delete from rhnServerCustomDataValue where server_id = server_id_in;
	delete from rhnServerDMI where server_id = server_id_in;
	delete from rhnServerEvent where server_id = server_id_in;
	delete from rhnServerHistory where server_id = server_id_in;
	delete from rhnServerInfo where server_id = server_id_in;
	delete from rhnServerInstallInfo where server_id = server_id_in;
	delete from rhnServerLocation where server_id = server_id_in;
	delete from rhnServerLock where server_id = server_id_in;
	delete from rhnServerNeededCache where server_id = server_id_in;
	delete from rhnServerNetwork where server_id = server_id_in;
	delete from rhnServerNotes where server_id = server_id_in;
	-- I'm not removing the foreign key from rhnServerPackage; that'll
	-- take forever.  Do the delete anyway.
	delete from rhnServerPackage where server_id = server_id_in;
	delete from rhnServerTokenRegs where server_id = server_id_in;
	delete from rhnSnapshotTag where server_id = server_id_in;
	-- this cascades to:
	--   rhnSnapshotChannel, rhnSnapshotConfigChannel, rhnSnapshotPackage, 
	--   rhnSnapshotConfigRevision, rhnSnapshotServerGroup, 
	--   rhnSnapshotTag.
	-- We may want to consider delete_snapshot() at some point, but
	--   I don't think we need to yet.
	delete from rhnSnapshot where server_id = server_id_in;
	delete from rhnUserServerPrefs where server_id = server_id_in;
	-- hrm, this one's interesting... we _probably_ should delete
	-- everything for the parent server_id when we delete the proxy,
	-- but we don't currently.
	delete from rhnServerPath where server_id_in in (server_id, proxy_server_id);
	delete from rhnUserServerPerms where server_id = server_id_in;

	delete from rhnServerNetInterface where server_id = server_id_in;
	delete from rhn_server_monitoring_info where recid = server_id_in;

	delete from rhnAppInstallSession where server_id = server_id_in;
	delete from rhnServerUuid where server_id = server_id_in;
    -- We delete all the probes running directly against this system
    -- and any probes that were using this Server as a Proxy Scout.
     SELECT CP.probe_id bulk collect into probesid_c
       FROM rhn_check_probe CP  
      WHERE CP.host_id = server_id_in
         OR CP.sat_cluster_id in
    (SELECT SN.sat_cluster_id
       FROM rhn_sat_node SN
      WHERE SN.server_id = server_id_in);

    if probesid_c.first is not null then
        FORALL i IN probesid_c.first..probesid_c.last
            DELETE FROM rhn_probe_state PS WHERE PS.probe_id = probesid_c(i);
        FORALL i IN probesid_c.first..probesid_c.last
            DELETE FROM rhn_probe P  WHERE P.recid = probesid_c(i);
        FORALL i IN probesid_c.first..probesid_c.last
            DELETE /*+index(time_series time_series_probe_id_idx)*/
            FROM time_series
            WHERE substr(o_id, instr(o_id, '-') + 1,
                (instr(o_id, '-', instr(o_id, '-') + 1) - instr(o_id, '-'))	- 1) = probesid_c(i);
    end if;

	delete from rhn_check_probe where host_id = server_id_in;
	delete from rhn_host_probe where host_id = server_id_in;

    delete from rhn_sat_cluster where recid in
      ( select sat_cluster_id from rhn_sat_node where server_id = server_id_in );

	delete from rhn_sat_node where server_id = server_id_in;
	
	-- now get rhnServer itself.
	delete
	from	rhnServer
		where id = server_id_in;

	delete
	from	rhnSet
	where	1=1
		and user_id in (
			select	wc.id
			from	rhnServer rs,
				web_contact wc
			where	rs.id = server_id_in
				and rs.org_id = wc.org_id
		)
		and label = 'system_list'
		and element = server_id_in;
end delete_server;
/
show errors;
  0707010000058A000081B400000000000000000000000167AE11140000050E000000000000000000000000000000000000006C00000000susemanager-schema/upgrade/spacewalk-schema-1.1-to-spacewalk-schema-1.2/060-rhnPackageUpgradeArchCompat.sql   --
-- Copyright (c) 2010 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnPackageUpgradeArchCompat
(
    package_arch_id   NUMBER NOT NULL
                         CONSTRAINT rhn_puac_paid_fk
                             REFERENCES rhnPackageArch (id),
    package_upgrade_arch_id NUMBER NOT NULL
                         CONSTRAINT rhn_puac_pauid_fk
                             REFERENCES rhnPackageArch (id),
    created          DATE
                         DEFAULT (sysdate) NOT NULL,
    modified         DATE
                         DEFAULT (sysdate) NOT NULL
)
ENABLE ROW MOVEMENT
;

CREATE INDEX rhn_puac_pa_pua
    ON rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id)
    TABLESPACE [[64k_tbs]];
  0707010000058B000081B400000000000000000000000167AE11140000622F000000000000000000000000000000000000007100000000susemanager-schema/upgrade/spacewalk-schema-1.1-to-spacewalk-schema-1.2/061-rhnPackageUpgradeArchCompat-data.sql  --
-- Copyright (c) 2010 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--
--
--

insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('noarch'), LOOKUP_PACKAGE_ARCH('noarch'), sysdate, sysdate);

insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('i386'), LOOKUP_PACKAGE_ARCH('noarch'), sysdate, sysdate);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('i386'), LOOKUP_PACKAGE_ARCH('i386'), sysdate, sysdate);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('noarch'), LOOKUP_PACKAGE_ARCH('i386'), sysdate, sysdate);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('i486'), LOOKUP_PACKAGE_ARCH('noarch'), sysdate, sysdate);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('i486'), LOOKUP_PACKAGE_ARCH('i486'), sysdate, sysdate);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('noarch'), LOOKUP_PACKAGE_ARCH('i486'), sysdate, sysdate);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('i586'), LOOKUP_PACKAGE_ARCH('noarch'), sysdate, sysdate);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('i586'), LOOKUP_PACKAGE_ARCH('i586'), sysdate, sysdate);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('noarch'), LOOKUP_PACKAGE_ARCH('i586'), sysdate, sysdate);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('i686'), LOOKUP_PACKAGE_ARCH('noarch'), sysdate, sysdate);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('i686'), LOOKUP_PACKAGE_ARCH('i686'), sysdate, sysdate);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('noarch'), LOOKUP_PACKAGE_ARCH('i686'), sysdate, sysdate);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('alpha'), LOOKUP_PACKAGE_ARCH('noarch'), sysdate, sysdate);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('alpha'), LOOKUP_PACKAGE_ARCH('alpha'), sysdate, sysdate);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('noarch'), LOOKUP_PACKAGE_ARCH('alpha'), sysdate, sysdate);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('alphaev6'), LOOKUP_PACKAGE_ARCH('noarch'), sysdate, sysdate);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('alphaev6'), LOOKUP_PACKAGE_ARCH('alphaev6'), sysdate, sysdate);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('noarch'), LOOKUP_PACKAGE_ARCH('alphaev6'), sysdate, sysdate);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('ia64'), LOOKUP_PACKAGE_ARCH('noarch'), sysdate, sysdate);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('ia64'), LOOKUP_PACKAGE_ARCH('ia64'), sysdate, sysdate);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('noarch'), LOOKUP_PACKAGE_ARCH('ia64'), sysdate, sysdate);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('sparc'), LOOKUP_PACKAGE_ARCH('noarch'), sysdate, sysdate);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('sparc'), LOOKUP_PACKAGE_ARCH('sparc'), sysdate, sysdate);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('noarch'), LOOKUP_PACKAGE_ARCH('sparc'), sysdate, sysdate);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('sparcv9'), LOOKUP_PACKAGE_ARCH('noarch'), sysdate, sysdate);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('sparcv9'), LOOKUP_PACKAGE_ARCH('sparcv9'), sysdate, sysdate);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('noarch'), LOOKUP_PACKAGE_ARCH('sparcv9'), sysdate, sysdate);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('sparc64'), LOOKUP_PACKAGE_ARCH('noarch'), sysdate, sysdate);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('sparc64'), LOOKUP_PACKAGE_ARCH('sparc64'), sysdate, sysdate);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('noarch'), LOOKUP_PACKAGE_ARCH('sparc64'), sysdate, sysdate);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('s390'), LOOKUP_PACKAGE_ARCH('noarch'), sysdate, sysdate);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('s390'), LOOKUP_PACKAGE_ARCH('s390'), sysdate, sysdate);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('noarch'), LOOKUP_PACKAGE_ARCH('s390'), sysdate, sysdate);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('athlon'), LOOKUP_PACKAGE_ARCH('noarch'), sysdate, sysdate);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('athlon'), LOOKUP_PACKAGE_ARCH('athlon'), sysdate, sysdate);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('noarch'), LOOKUP_PACKAGE_ARCH('athlon'), sysdate, sysdate);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('s390x'), LOOKUP_PACKAGE_ARCH('noarch'), sysdate, sysdate);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('s390x'), LOOKUP_PACKAGE_ARCH('s390x'), sysdate, sysdate);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('noarch'), LOOKUP_PACKAGE_ARCH('s390x'), sysdate, sysdate);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('ppc'), LOOKUP_PACKAGE_ARCH('noarch'), sysdate, sysdate);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('ppc'), LOOKUP_PACKAGE_ARCH('ppc'), sysdate, sysdate);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('noarch'), LOOKUP_PACKAGE_ARCH('ppc'), sysdate, sysdate);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('ppc64'), LOOKUP_PACKAGE_ARCH('noarch'), sysdate, sysdate);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('ppc64'), LOOKUP_PACKAGE_ARCH('ppc64'), sysdate, sysdate);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('noarch'), LOOKUP_PACKAGE_ARCH('ppc64'), sysdate, sysdate);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('pSeries'), LOOKUP_PACKAGE_ARCH('noarch'), sysdate, sysdate);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('pSeries'), LOOKUP_PACKAGE_ARCH('pSeries'), sysdate, sysdate);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('noarch'), LOOKUP_PACKAGE_ARCH('pSeries'), sysdate, sysdate);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('iSeries'), LOOKUP_PACKAGE_ARCH('noarch'), sysdate, sysdate);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('iSeries'), LOOKUP_PACKAGE_ARCH('iSeries'), sysdate, sysdate);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('noarch'), LOOKUP_PACKAGE_ARCH('iSeries'), sysdate, sysdate);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('x86_64'), LOOKUP_PACKAGE_ARCH('noarch'), sysdate, sysdate);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('x86_64'), LOOKUP_PACKAGE_ARCH('x86_64'), sysdate, sysdate);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('noarch'), LOOKUP_PACKAGE_ARCH('x86_64'), sysdate, sysdate);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('ppc64iseries'), LOOKUP_PACKAGE_ARCH('noarch'), sysdate, sysdate);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('ppc64iseries'), LOOKUP_PACKAGE_ARCH('ppc64iseries'), sysdate, sysdate);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('noarch'), LOOKUP_PACKAGE_ARCH('ppc64iseries'), sysdate, sysdate);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('ppc64pseries'), LOOKUP_PACKAGE_ARCH('noarch'), sysdate, sysdate);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('ppc64pseries'), LOOKUP_PACKAGE_ARCH('ppc64pseries'), sysdate, sysdate);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('noarch'), LOOKUP_PACKAGE_ARCH('ppc64pseries'), sysdate, sysdate);

insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('sparc-solaris'), LOOKUP_PACKAGE_ARCH('noarch-solaris'), sysdate, sysdate);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('sparc-solaris'), LOOKUP_PACKAGE_ARCH('sparc-solaris'), sysdate, sysdate);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('noarch-solaris'), LOOKUP_PACKAGE_ARCH('sparc-solaris'), sysdate, sysdate);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('sparc.sun4u-solaris'), LOOKUP_PACKAGE_ARCH('noarch-solaris'), sysdate, sysdate);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('sparc.sun4u-solaris'), LOOKUP_PACKAGE_ARCH('sparc.sun4u-solaris'), sysdate, sysdate);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('noarch-solaris'), LOOKUP_PACKAGE_ARCH('sparc.sun4u-solaris'), sysdate, sysdate);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('sparc.sun4v-solaris'), LOOKUP_PACKAGE_ARCH('noarch-solaris'), sysdate, sysdate);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('sparc.sun4v-solaris'), LOOKUP_PACKAGE_ARCH('sparc.sun4v-solaris'), sysdate, sysdate);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('noarch-solaris'), LOOKUP_PACKAGE_ARCH('sparc.sun4v-solaris'), sysdate, sysdate);

insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('tar'), LOOKUP_PACKAGE_ARCH('tar'), sysdate, sysdate);

insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('ia32e'), LOOKUP_PACKAGE_ARCH('noarch'), sysdate, sysdate);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('ia32e'), LOOKUP_PACKAGE_ARCH('ia32e'), sysdate, sysdate);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('noarch'), LOOKUP_PACKAGE_ARCH('ia32e'), sysdate, sysdate);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('amd64'), LOOKUP_PACKAGE_ARCH('noarch'), sysdate, sysdate);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('amd64'), LOOKUP_PACKAGE_ARCH('amd64'), sysdate, sysdate);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('noarch'), LOOKUP_PACKAGE_ARCH('amd64'), sysdate, sysdate);

insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('i386-solaris'), LOOKUP_PACKAGE_ARCH('noarch-solaris'), sysdate, sysdate);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('i386-solaris'), LOOKUP_PACKAGE_ARCH('i386-solaris'), sysdate, sysdate);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('noarch-solaris'), LOOKUP_PACKAGE_ARCH('i386-solaris'), sysdate, sysdate);

insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('sparc-solaris-patch'), LOOKUP_PACKAGE_ARCH('noarch-solaris-patch'), sysdate, sysdate);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('sparc-solaris-patch'), LOOKUP_PACKAGE_ARCH('sparc-solaris-patch'), sysdate, sysdate);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('noarch-solaris-patch'), LOOKUP_PACKAGE_ARCH('sparc-solaris-patch'), sysdate, sysdate);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('i386-solaris-patch'), LOOKUP_PACKAGE_ARCH('noarch-solaris-patch'), sysdate, sysdate);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('i386-solaris-patch'), LOOKUP_PACKAGE_ARCH('i386-solaris-patch'), sysdate, sysdate);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('noarch-solaris-patch'), LOOKUP_PACKAGE_ARCH('i386-solaris-patch'), sysdate, sysdate);

insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('sparc-solaris-patch-cluster'), LOOKUP_PACKAGE_ARCH('noarch-solaris-patch-cluster'), sysdate, sysdate);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('sparc-solaris-patch-cluster'), LOOKUP_PACKAGE_ARCH('sparc-solaris-patch-cluster'), sysdate, sysdate);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('noarch-solaris-patch-cluster'), LOOKUP_PACKAGE_ARCH('sparc-solaris-patch-cluster'), sysdate, sysdate);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('i386-solaris-patch-cluster'), LOOKUP_PACKAGE_ARCH('noarch-solaris-patch-cluster'), sysdate, sysdate);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('i386-solaris-patch-cluster'), LOOKUP_PACKAGE_ARCH('i386-solaris-patch-cluster'), sysdate, sysdate);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('noarch-solaris-patch-cluster'), LOOKUP_PACKAGE_ARCH('i386-solaris-patch-cluster'), sysdate, sysdate);

insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('noarch-solaris'), LOOKUP_PACKAGE_ARCH('noarch-solaris'), sysdate, sysdate);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('noarch-solaris-patch'), LOOKUP_PACKAGE_ARCH('noarch-solaris-patch'), sysdate, sysdate);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('noarch-solaris-patch-cluster'), LOOKUP_PACKAGE_ARCH('noarch-solaris-patch-cluster'), sysdate, sysdate);

insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('all-deb'), LOOKUP_PACKAGE_ARCH('all-deb'), sysdate, sysdate);

insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('i386-deb'), LOOKUP_PACKAGE_ARCH('all-deb'), sysdate, sysdate);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('i386-deb'), LOOKUP_PACKAGE_ARCH('i386-deb'), sysdate, sysdate);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('all-deb'), LOOKUP_PACKAGE_ARCH('i386-deb'), sysdate, sysdate);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('alpha-deb'), LOOKUP_PACKAGE_ARCH('all-deb'), sysdate, sysdate);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('alpha-deb'), LOOKUP_PACKAGE_ARCH('alpha-deb'), sysdate, sysdate);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('all-deb'), LOOKUP_PACKAGE_ARCH('alpha-deb'), sysdate, sysdate);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('ia64-deb'), LOOKUP_PACKAGE_ARCH('all-deb'), sysdate, sysdate);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('ia64-deb'), LOOKUP_PACKAGE_ARCH('ia64-deb'), sysdate, sysdate);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('all-deb'), LOOKUP_PACKAGE_ARCH('ia64-deb'), sysdate, sysdate);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('sparc-deb'), LOOKUP_PACKAGE_ARCH('all-deb'), sysdate, sysdate);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('sparc-deb'), LOOKUP_PACKAGE_ARCH('sparc-deb'), sysdate, sysdate);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('all-deb'), LOOKUP_PACKAGE_ARCH('sparc-deb'), sysdate, sysdate);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('src-deb'), LOOKUP_PACKAGE_ARCH('src-deb'), sysdate, sysdate);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('s390-deb'), LOOKUP_PACKAGE_ARCH('all-deb'), sysdate, sysdate);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('s390-deb'), LOOKUP_PACKAGE_ARCH('s390-deb'), sysdate, sysdate);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('all-deb'), LOOKUP_PACKAGE_ARCH('s390-deb'), sysdate, sysdate);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('powerpc-deb'), LOOKUP_PACKAGE_ARCH('all-deb'), sysdate, sysdate);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('powerpc-deb'), LOOKUP_PACKAGE_ARCH('powerpc-deb'), sysdate, sysdate);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('all-deb'), LOOKUP_PACKAGE_ARCH('powerpc-deb'), sysdate, sysdate);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('arm-deb'), LOOKUP_PACKAGE_ARCH('all-deb'), sysdate, sysdate);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('arm-deb'), LOOKUP_PACKAGE_ARCH('arm-deb'), sysdate, sysdate);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('all-deb'), LOOKUP_PACKAGE_ARCH('arm-deb'), sysdate, sysdate);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('mips-deb'), LOOKUP_PACKAGE_ARCH('all-deb'), sysdate, sysdate);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('mips-deb'), LOOKUP_PACKAGE_ARCH('mips-deb'), sysdate, sysdate);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('all-deb'), LOOKUP_PACKAGE_ARCH('mips-deb'), sysdate, sysdate);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('amd64-deb'), LOOKUP_PACKAGE_ARCH('all-deb'), sysdate, sysdate);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('amd64-deb'), LOOKUP_PACKAGE_ARCH('amd64-deb'), sysdate, sysdate);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('all-deb'), LOOKUP_PACKAGE_ARCH('amd64-deb'), sysdate, sysdate);

 0707010000058C000081B400000000000000000000000167AE111400000E7A000000000000000000000000000000000000006400000000susemanager-schema/upgrade/spacewalk-schema-1.1-to-spacewalk-schema-1.2/062-rhnServerNeededView.sql   --
-- Copyright (c) 2010 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--


-- A view that displays packages which can be updated on selected client.
-- This is an uncached version of rhnServerNeededCache.

create or replace view
rhnServerNeededView
(
    org_id,
    server_id,
    errata_id,
    package_id,
    package_name_id,
    channel_id
)
as
select s.org_id,
       s.id as server_id,
       pce.errata_id,
       pkg.id as package_id,
       neededpkg.name_id as package_name_id,
       scp.min_channel_id as channel_id
  from (select sc.server_id, np.name_id, np.package_arch_id, max(np.evr) max_evr
          from (-- list of newest packages in channels with EVR
                select np_np.*, np_pe.evr
                  from rhnChannelNewestPackage np_np
                  join rhnPackageEVR np_pe
                    on np_pe.id = np_np.evr_id) np
          join (-- list of packages on the server with EVR
                select sp_sp.server_id, sp_sp.name_id, sp_sp.package_arch_id, max(sp_pe.evr) as max_evr
                  from rhnServerPackage sp_sp
                  join rhnPackageEVR sp_pe
                    on sp_pe.id = sp_sp.evr_id
                 group by sp_sp.server_id, sp_sp.name_id, sp_sp.package_arch_id) sp
            on -- at first - we want only newer (=higher EVR) packages than there are on the server
               sp.name_id = np.name_id and sp.max_evr < np.evr
          join -- secondly - packages must be upgrade compatible
               rhnPackageUpgradeArchCompat puac
            on puac.package_arch_id = sp.package_arch_id and puac.package_upgrade_arch_id = np.package_arch_id
          join -- thirdly - packages must be in channel where server is subscribed to
               rhnServerChannel sc
            on sc.server_id = sp.server_id and sc.channel_id = np.channel_id
        group by sc.server_id, np.name_id, np.package_arch_id
        ) neededpkg
  join -- lookup org_id by server
       rhnServer s
    on neededpkg.server_id = s.id
  join (--lookup package_id by max_evr, name and package_arch
        select p.*, p_evr.evr
               --
               , p_evr.release, p_evr.version, p_evr.epoch
          from rhnPackage p
          join rhnPackageEVR p_evr
            on p_evr.id = p.evr_id) pkg
    on pkg.evr = neededpkg.max_evr
   and pkg.name_id = neededpkg.name_id
   and pkg.package_arch_id = neededpkg.package_arch_id
  join (-- lookup channel_id - we want only one id eve if package is in more channels
        -- so pick lowest one
        select cp.package_id, csc.server_id, min(cp.channel_id) as min_channel_id
          from rhnChannelPackage cp
          join rhnServerChannel csc
            on csc.channel_id = cp.channel_id
         group by cp.package_id, csc.server_id) scp
    on scp.package_id = pkg.id and scp.server_id = neededpkg.server_id
  left join (-- lookup errata id (can be NULL)
             select ep.package_id, ce.errata_id, ce.channel_id
               from rhnErrataPackage ep
               join rhnChannelErrata ce
                 on ce.errata_id = ep.errata_id) pce
    on pce.package_id = pkg.id and pce.channel_id = scp.min_channel_id
;
  0707010000058D000081B400000000000000000000000167AE1114000018D3000000000000000000000000000000000000005C00000000susemanager-schema/upgrade/spacewalk-schema-1.1-to-spacewalk-schema-1.2/063-rhn_channel.sql   --
-- Copyright (c) 2008--2010 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--

CREATE OR REPLACE
PACKAGE rhn_channel
IS
	version varchar2(100) := '';

    CURSOR server_base_subscriptions(server_id_in NUMBER) IS
    	   SELECT C.id
	     FROM rhnChannel C, rhnServerChannel SC
	    WHERE C.id = SC.channel_id
	      AND SC.server_id = server_id_in
	      AND C.parent_channel IS NULL;
	      
    CURSOR check_server_subscription(server_id_in NUMBER, channel_id_in NUMBER) IS 
           SELECT channel_id 
	     FROM rhnServerChannel 
	    WHERE server_id = server_id_in 
	      AND channel_id = channel_id_in;

    CURSOR check_server_parent_membership(server_id_in NUMBER, channel_id_in NUMBER) IS
    	   SELECT C.id
	     FROM rhnChannel C, rhnServerChannel SC
	    WHERE C.parent_channel = channel_id_in
	      AND C.id = SC.channel_id
	      AND SC.server_id = server_id_in;
	    
    CURSOR channel_family_perm_cursor(channel_family_id_in NUMBER, org_id_in NUMBER) IS
           SELECT *
	     FROM rhnOrgChannelFamilyPermissions
	    WHERE channel_family_id = channel_family_id_in
	      AND org_id = org_id_in;


    PROCEDURE unsubscribe_server(server_id_in IN NUMBER, channel_id_in NUMBER, immediate_in NUMBER := 1, unsubscribe_children_in number := 0,
                                 deleting_server in number := 0,
                                 update_family_countsYN IN NUMBER := 1);
    PROCEDURE subscribe_server(server_id_in IN NUMBER, channel_id_in NUMBER, immediate_in NUMBER := 1, user_id_in number := null, recalcfamily_in number := 1);
    
    PROCEDURE convert_to_fve(server_id_in IN NUMBER, channel_family_id_val IN NUMBER);

    FUNCTION can_convert_to_fve(server_id_in IN NUMBER, channel_family_id_val IN NUMBER)  RETURN NUMBER;
	
    function can_server_consume_virt_channl(
        server_id_in IN NUMBER,
        family_id_in in number)
    return number;
    FUNCTION can_server_consume_fve( server_id_in IN NUMBER) RETURN NUMBER;

    FUNCTION guess_server_base(server_id_in IN NUMBER) RETURN NUMBER;

    FUNCTION base_channel_for_release_arch(release_in in varchar2, 
	server_arch_in in varchar2, org_id_in in number := -1, 
	user_id_in in number := null) RETURN number;

    FUNCTION base_channel_rel_archid(release_in in varchar2, 
	server_arch_id_in in number, org_id_in in number := -1, 
	user_id_in in number := null) RETURN number;

    FUNCTION channel_priority(channel_id_in in number) RETURN number;
    
    PROCEDURE clear_subscriptions(server_id_in IN NUMBER, deleting_server in number := 0,
                                update_family_countsYN IN NUMBER := 1);
    
    FUNCTION available_family_subscriptions(channel_family_id_in IN NUMBER, org_id_in IN NUMBER) RETURN NUMBER;

    FUNCTION available_fve_family_subs(channel_family_id_in IN NUMBER, org_id_in IN NUMBER) RETURN NUMBER;

    FUNCTION channel_family_current_members(channel_family_id_in IN NUMBER, org_id_in IN NUMBER) return number;

    FUNCTION cfam_curr_fve_members(channel_family_id_in IN NUMBER, org_id_in IN NUMBER) return number;

    PROCEDURE update_family_counts(channel_family_id_in IN NUMBER, org_id_in IN NUMBER);
    PROCEDURE update_group_family_counts(group_label_in IN VARCHAR2, org_id_in IN NUMBER);
    FUNCTION family_for_channel(channel_id_in IN NUMBER) RETURN NUMBER;

    FUNCTION available_chan_subscriptions(channel_id_in IN NUMBER, org_id_in IN NUMBER) RETURN NUMBER;

    FUNCTION available_fve_chan_subs(channel_id_in IN NUMBER, org_id_in IN NUMBER) RETURN NUMBER;

    PROCEDURE unsubscribe_server_from_family(server_id_in in number, channel_family_id_in in number);

    PROCEDURE delete_server_channels(server_id_in in number);

    PROCEDURE refresh_newest_package(channel_id_in in number, caller_in in varchar2 := '(unknown)');

    FUNCTION get_org_id(channel_id_in in number) return number;
    PRAGMA RESTRICT_REFERENCES(get_org_id, WNDS, RNPS, WNPS);

    function get_org_access(channel_id_in in number, org_id_in in number) return number;
    PRAGMA RESTRICT_REFERENCES(get_org_access, WNDS, RNPS, WNPS);
    
    function get_cfam_org_access(cfam_id_in in number, org_id_in in number) return number;

    function user_role_check_debug(channel_id_in in number, user_id_in in number, role_in in varchar2, reason_out out varchar2)
    	RETURN NUMBER;
    PRAGMA RESTRICT_REFERENCES(user_role_check_debug, WNDS, RNPS, WNPS);

    function user_role_check(channel_id_in in number, user_id_in in number, role_in in varchar2)
    	RETURN NUMBER;
    PRAGMA RESTRICT_REFERENCES(user_role_check, WNDS, RNPS, WNPS);
    
    function loose_user_role_check(channel_id_in in number, user_id_in in number, role_in in varchar2)
    	RETURN NUMBER;
    PRAGMA RESTRICT_REFERENCES(loose_user_role_check, WNDS, RNPS, WNPS);

    function direct_user_role_check(channel_id_in in number, user_id_in in number, role_in in varchar2)
    	RETURN NUMBER;
    PRAGMA RESTRICT_REFERENCES(direct_user_role_check, WNDS, RNPS, WNPS);

    function shared_user_role_check(channel_id in number, user_id in number, role in varchar2)
    	RETURN NUMBER;
    PRAGMA RESTRICT_REFERENCES(shared_user_role_check, WNDS, RNPS, WNPS);

    function org_channel_setting(channel_id_in in number, org_id_in in number, setting_in in varchar2)
    	RETURN NUMBER;

    PROCEDURE update_channel ( channel_id_in in number, invalidate_ss in number := 0, 
                               date_to_use in date := sysdate );

    PROCEDURE  update_channels_by_package ( package_id_in in number, date_to_use in date := sysdate );

     PROCEDURE update_channels_by_errata ( errata_id_in number, date_to_use in date := sysdate );


    PRAGMA RESTRICT_REFERENCES(org_channel_setting, WNDS, RNPS, WNPS);

    PROCEDURE update_needed_cache(channel_id_in in number);


END rhn_channel;
/
SHOW ERRORS
 0707010000058E000081B400000000000000000000000167AE111400000C8E000000000000000000000000000000000000005B00000000susemanager-schema/upgrade/spacewalk-schema-1.1-to-spacewalk-schema-1.2/064-rhn_server.sql    --
-- Copyright (c) 2008--2010 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--

create or replace
package rhn_server
is

    -- i.e., "can this box do management stuff?" and yes if provisioning box
    function system_service_level(
    	server_id_in in number,
	service_level_in in varchar2
    ) return number;	    

    function can_change_base_channel(
    	server_id_in in number
    ) return number;
    
    procedure set_custom_value(
    	server_id_in in number,
	user_id_in in number,
	key_label_in varchar2,
     	value_in in varchar2
    );
    
    function bulk_set_custom_value(
    	key_label_in in varchar2,
	value_in in varchar2,
	set_label_in in varchar2,
	set_uid_in in number
    ) return integer;
    
    procedure snapshot_server(
    	server_id_in in number,
	reason_in in varchar2
    );
    
    procedure bulk_snapshot(
    	reason_in in varchar2,
    	set_label_in in varchar2,
	set_uid_in in number
    );
    
    procedure tag_delete(
    	server_id_in in number,
	tag_id_in in number
    );

    procedure tag_snapshot(
    	snapshot_id_in in number,
	org_id_in in number,
    	tagname_in in varchar2
    );
    
    procedure bulk_snapshot_tag(
    	org_id_in in number,
    	tagname_in varchar2,
	set_label_in in varchar2,
	set_uid_in in number
    );

    procedure remove_action(
	server_id_in in number,
	action_id_in in number
    );
    
    function check_user_access(server_id_in in number, user_id_in in number) return number;


    function can_server_consume_virt_slot(server_id_in in number,
                                              group_type_in in
                                              rhnServerGroupType.label%TYPE)
    return number;                                              

    procedure insert_into_servergroup (
	server_id_in in number,
	server_group_id_in in number
    );

    function insert_into_servergroup_maybe (
	server_id_in in number,
	server_group_id_in in number
    ) return number;

	procedure insert_set_into_servergroup (
	server_group_id_in in number,
	user_id_in in number,
	set_label_in in varchar2
	);

    procedure delete_from_servergroup (
	server_id_in in number,
	server_group_id_in in number
    );

	procedure delete_set_from_servergroup (
	server_group_id_in in number,
	user_id_in in number,
	set_label_in in varchar2
	);

	procedure clear_servergroup (
	server_group_id_in in number
	);

	procedure delete_from_org_servergroups (
	server_id_in in number
	);
	
	function get_ip_address (
		server_id_in in number
	) return varchar2;

        procedure update_needed_cache(
                server_id_in in number
        );

end rhn_server;
/
SHOW ERRORS
  0707010000058F000081B400000000000000000000000167AE11140000ACB4000000000000000000000000000000000000006100000000susemanager-schema/upgrade/spacewalk-schema-1.1-to-spacewalk-schema-1.2/065-rhn_channel-body.sql  --
-- Copyright (c) 2008--2010 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--

CREATE OR REPLACE
PACKAGE BODY rhn_channel
IS
        body_version varchar2(100) := '';

    -- Cursor that fetches all the possible base channels for a
    -- (server_arch_id, release, org_id) combination
        cursor  base_channel_cursor(
                release_in in varchar2,
                server_arch_id_in in number,
                org_id_in in number
        ) return rhnChannel%ROWTYPE is
                select distinct c.*
                from    rhnDistChannelMap                       dcm,
                                rhnServerChannelArchCompat      scac,
                                rhnChannel                                      c,
                                rhnChannelPermissions           cp
                where   cp.org_id = org_id_in
                        and cp.channel_id = c.id
                        and c.parent_channel is null
                        and c.id = dcm.channel_id
                        and c.channel_arch_id = dcm.channel_arch_id
                        and dcm.release = release_in
                        and scac.server_arch_id = server_arch_id_in
                        and scac.channel_arch_id = c.channel_arch_id;

    procedure obtain_read_lock(channel_family_id_in in number, org_id_in in number)
    is
        read_lock date;

    begin
        select created into read_lock
          from rhnPrivateChannelFamily
         where channel_family_id = channel_family_id_in and org_id = org_id_in
           for update;
    end obtain_read_lock;

    PROCEDURE subscribe_server(server_id_in IN NUMBER, channel_id_in NUMBER, immediate_in NUMBER := 1, user_id_in in number := null, recalcfamily_in number := 1)
    IS
        channel_parent_val      rhnChannel.parent_channel%TYPE;
        parent_subscribed       BOOLEAN;
        server_has_base_chan    BOOLEAN;
        server_already_in_chan  BOOLEAN;
        channel_family_id_val   NUMBER;
        server_org_id_val       NUMBER;
        available_subscriptions NUMBER;
        available_fve_subs      NUMBER;
        consenting_user         NUMBER;
        allowed                 number := 0;
        is_fve                  CHAR(1) := 'N';
    BEGIN
        if user_id_in is not null then
            allowed := rhn_channel.user_role_check(channel_id_in, user_id_in, 'subscribe');
        else
            allowed := 1;
        end if;

        if allowed = 0 then
            rhn_exception.raise_exception('no_subscribe_permissions');
        end if;


        SELECT parent_channel INTO channel_parent_val FROM rhnChannel WHERE id = channel_id_in;

        IF channel_parent_val IS NOT NULL
        THEN    
            -- child channel; if attempting to cross-subscribe a child to the wrong base, silently ignore
            parent_subscribed := FALSE;    

            FOR check_subscription IN check_server_subscription(server_id_in, channel_parent_val)
            LOOP
                parent_subscribed := TRUE;
            END LOOP check_subscription;
        
            IF NOT parent_subscribed
            THEN
                RETURN;
            END IF;
        ELSE
            -- base channel
            server_has_base_chan := FALSE;
            FOR base IN server_base_subscriptions(server_id_in)
            LOOP
                server_has_base_chan := TRUE;
            END LOOP base;
            
            IF server_has_base_chan
            THEN
                rhn_exception.raise_exception('channel_server_one_base');
            END IF;
        END IF;
    
        FOR check_subscription IN check_server_subscription(server_id_in, channel_id_in)
        LOOP
            server_already_in_chan := TRUE;
        END LOOP check_subscription;
    
        IF server_already_in_chan
        THEN
            RETURN;
        END IF;
        
        channel_family_id_val := rhn_channel.family_for_channel(channel_id_in);
        IF channel_family_id_val IS NULL
        THEN
            rhn_exception.raise_exception('channel_subscribe_no_family');
        END IF;

        --
        -- Use the org_id of the server only if the org_id of the channel = NULL.
        -- This is required for subscribing to shared channels.
        --
        SELECT NVL(org_id, (SELECT org_id FROM rhnServer WHERE id = server_id_in))
          INTO server_org_id_val
          FROM rhnChannel
         WHERE id = channel_id_in;
         
        begin
            obtain_read_lock(channel_family_id_val, server_org_id_val);
        exception
            when no_data_found then
                rhn_exception.raise_exception('channel_family_no_subscriptions');
        end;

        available_subscriptions := rhn_channel.available_family_subscriptions(channel_family_id_val, server_org_id_val);
        available_fve_subs := rhn_channel.available_fve_family_subs(channel_family_id_val, server_org_id_val);

        IF available_subscriptions IS NULL OR
            available_subscriptions > 0 or
            can_server_consume_virt_channl(server_id_in, channel_family_id_val) = 1 OR
            (available_fve_subs > 0 AND can_server_consume_fve(server_id_in) = 1)
        THEN
            if can_server_consume_virt_channl(server_id_in, channel_family_id_val) = 0 AND available_fve_subs > 0 AND can_server_consume_fve(server_id_in) = 1 THEN
                is_fve := 'Y';
            END IF;
            insert into rhnServerHistory (id,server_id,summary,details) (
                select  rhn_event_id_seq.nextval,
                        server_id_in,
                        'subscribed to channel ' || SUBSTR(c.label, 0, 106),
                        c.label
                from    rhnChannel c
                where   c.id = channel_id_in
            );
            UPDATE rhnServer SET channels_changed = sysdate WHERE id = server_id_in;
            INSERT INTO rhnServerChannel (server_id, channel_id, is_fve) VALUES (server_id_in, channel_id_in, is_fve);
			IF recalcfamily_in > 0
			THEN
                rhn_channel.update_family_counts(channel_family_id_val, server_org_id_val);
			END IF;
            queue_server(server_id_in, immediate_in);
        ELSE
            rhn_exception.raise_exception('channel_family_no_subscriptions');
        END IF;
            
    END subscribe_server;



    FUNCTION can_convert_to_fve(server_id_in IN NUMBER, channel_family_id_val IN NUMBER)
    RETURN NUMBER
    IS
        CURSOR fve_convertible_entries IS
        select 1  from
            rhnServerFveCapable cap
          where cap.server_id = server_id_in
                AND cap.channel_family_id = channel_family_id_val;
    BEGIN
        FOR entry IN fve_convertible_entries LOOP
            return 1;
        END LOOP;
        RETURN 0;
    END can_convert_to_fve;



    -- Converts server channel_family to use a flex entitlement
    PROCEDURE convert_to_fve(server_id_in IN NUMBER, channel_family_id_val IN NUMBER)
    IS
        available_fve_subs      NUMBER;
        server_org_id_val       NUMBER;        
    BEGIN

        --
        -- Use the org_id of the server only if the org_id of the channel = NULL.
        -- This is required for subscribing to shared channels.
        --
        SELECT org_id
          INTO server_org_id_val
          FROM rhnServer
         WHERE id = server_id_in;
         
        begin
            obtain_read_lock(channel_family_id_val, server_org_id_val);
        exception
            when no_data_found then
                rhn_exception.raise_exception('channel_family_no_subscriptions');
        end;
        IF (can_convert_to_fve(server_id_in, channel_family_id_val ) = 0) 
            THEN
                rhn_exception.raise_exception('server_cannot_convert_to_flex');
        END IF;

        available_fve_subs := rhn_channel.available_fve_family_subs(channel_family_id_val, server_org_id_val);

        IF (available_fve_subs > 0)
        THEN
        
            insert into rhnServerHistory (id,server_id,summary,details) (
                select  rhn_event_id_seq.nextval,
                        server_id_in,
                        'converted to flex entitlement' || SUBSTR(cf.label, 0, 99),
                        cf.label
                from    rhnChannelFamily cf
                where   cf.id = channel_family_id_val
            );

            UPDATE rhnServerChannel sc set sc.is_fve = 'Y' 
                           where sc.server_id = server_id_in and  
                                 sc.channel_id in 
                                    (select cfm.channel_id from rhnChannelFamilyMembers cfm
                                                where cfm.CHANNEL_FAMILY_ID = channel_family_id_val);
            
            rhn_channel.update_family_counts(channel_family_id_val, server_org_id_val);
        ELSE
            rhn_exception.raise_exception('not_enough_flex_entitlements');
        END IF;
            
    END convert_to_fve;    
    
    function can_server_consume_virt_channl(
        server_id_in in number,
        family_id_in in number )
    return number
    is

        cursor server_virt_families is
            select vi.virtual_system_id, cfvsl.channel_family_id
            from
                rhnChannelFamilyVirtSubLevel cfvsl,
                rhnSGTypeVirtSubLevel sgtvsl,
                rhnVirtualInstance vi
            where
                vi.virtual_system_id = server_id_in 
                and sgtvsl.virt_sub_level_id = cfvsl.virt_sub_level_id
                and cfvsl.channel_family_id = family_id_in
                and exists (
                    select 1
                    from rhnServerEntitlementView sev
                    where vi.host_system_id = sev.server_id
                    and sev.server_group_type_id = sgtvsl.server_group_type_id );
    begin

        for server_virt_family in server_virt_families loop
            return 1;
        end loop;

        return 0;

    end;

    FUNCTION can_server_consume_fve(server_id_in IN NUMBER)
    RETURN NUMBER
    IS
        CURSOR vi_entries IS
            SELECT 1
              FROM rhnVirtualInstance vi
             WHERE vi.virtual_system_id = server_id_in
             and not exists(select server_id from rhnServerChannel sc where 
                            sc.server_id = vi.virtual_system_id 
                            and  sc.is_fve='Y');
        vi_count NUMBER;

    BEGIN
        FOR vi_entry IN VI_ENTRIES LOOP
            return 1;
        END LOOP;
        RETURN 0;
    END;

    function guess_server_base(
        server_id_in in number
    ) RETURN number is
        cursor server_cursor is
            select s.server_arch_id, s.release, s.org_id
              from rhnServer s
             where s.id = server_id_in;
    begin
        for s in server_cursor loop
            for channel in base_channel_cursor(s.release,
                s.server_arch_id, s.org_id) 
            loop
                return channel.id;
            end loop base_channel_cursor;
        end loop server_cursor;
        -- Server not found, or no base channel applies to it
        return null;
    end;

    -- Private function
    function normalize_server_arch(server_arch_in in varchar2)
    return varchar2
    deterministic
    is
        suffix VARCHAR2(128) := '-redhat-linux';
        suffix_len NUMBER := length(suffix);
    begin
        if server_arch_in is NULL then
            return NULL;
        end if;
        if instr(server_arch_in, '-') > 0
        then
            -- Suffix already present
            return server_arch_in;
        end if;
        return server_arch_in || suffix;
    end normalize_server_arch;

    --
    --
    -- Raises: 
    --   server_arch_not_found
    --   no_subscribe_permissions
    function base_channel_for_release_arch(
        release_in in varchar2,
        server_arch_in in varchar2,
        org_id_in in number := -1,
        user_id_in in number := null
    ) return number is
        server_arch varchar2(256) := normalize_server_arch(server_arch_in);
        server_arch_id number;
    begin
        -- Look up the server arch
        begin
            select id
              into server_arch_id
              from rhnServerArch
             where label = server_arch;
        exception
            when no_data_found then
                rhn_exception.raise_exception('server_arch_not_found');
        end;
        return base_channel_rel_archid(release_in, server_arch_id,
            org_id_in, user_id_in);
    end base_channel_for_release_arch;

    function base_channel_rel_archid(
        release_in in varchar2,
        server_arch_id_in in number,
        org_id_in in number := -1,
        user_id_in in number := null
    ) return number is
        denied_channel_id number := null;
        valid_org_id number := org_id_in;
        valid_user_id number := user_id_in;
        channel_subscribable number;
    begin
        if org_id_in = -1 and user_id_in is not null then
            -- Get the org id from the user id
            begin
                select org_id
                  into valid_org_id
                  from web_contact
                 where id = user_id_in;
            exception
                when no_data_found then
                    -- User doesn't exist
                    -- XXX Only list public stuff for now
                    valid_user_id := null;
                    valid_org_id := -1;
            end;
        end if;

        for c in base_channel_cursor(release_in, server_arch_id_in, valid_org_id)
        loop
            -- This row is a possible match
            if valid_user_id is null then
                -- User ID not specified, so no user to channel permissions to
                -- check
                return c.id;
            end if;

            -- Check user to channel permissions
            select loose_user_role_check(c.id, user_id_in, 'subscribe')
              into channel_subscribable
              from dual;

            if channel_subscribable = 1 then
                return c.id;
            end if;
                
            -- Base channel exists, but is not subscribable; keep trying
            denied_channel_id := c.id;
        end loop base_channel_fetch;
        
        if denied_channel_id is not null then
            rhn_exception.raise_exception('no_subscribe_permissions');
        end if;
        -- No base channel applies
        return NULL;
    end base_channel_rel_archid;

    PROCEDURE clear_subscriptions(server_id_in IN NUMBER, deleting_server IN NUMBER := 0,
                                update_family_countsYN IN NUMBER := 1)
    IS
        cursor server_channels(server_id_in in number) is
                select  s.org_id, sc.channel_id, cfm.channel_family_id
                from    rhnServer s,
                        rhnServerChannel sc,
                        rhnChannelFamilyMembers cfm
                where   s.id = server_id_in
                        and s.id = sc.server_id
                        and sc.channel_id = cfm.channel_id
                order by cfm.channel_family_id;
        last_channel_family_id rhnChannelFamilyMembers.channel_family_id%type := -1;
        last_channel_org_id    rhnServer.org_id%type := -1;
    BEGIN
        for channel in server_channels(server_id_in)
        loop
                unsubscribe_server(server_id_in, channel.channel_id, 1, 1, deleting_server, 0);
                if update_family_countsYN > 0
                    and channel.channel_family_id != last_channel_family_id then
                    -- update family counts only once
                    -- after all channels with same family has been fetched
                    if last_channel_family_id != -1 then
                        update_family_counts(last_channel_family_id, last_channel_org_id);
                    end if;
                    last_channel_family_id := channel.channel_family_id;
                    last_channel_org_id    := channel.org_id;
                end if;
        end loop channel;
        if update_family_countsYN > 0 and last_channel_family_id != -1 then
            -- update the last family fetched
            update_family_counts(last_channel_family_id, last_channel_org_id);
        end if;
    END clear_subscriptions;

    PROCEDURE unsubscribe_server(server_id_in IN NUMBER, channel_id_in NUMBER, immediate_in NUMBER := 1, unsubscribe_children_in number := 0,
                                 deleting_server IN NUMBER := 0,
                                 update_family_countsYN IN NUMBER := 1)
    IS
        channel_family_id_val   NUMBER;
        server_org_id_val       NUMBER;
        available_subscriptions NUMBER; 
        server_already_in_chan  BOOLEAN;
        cursor  channel_family_is_proxy(channel_family_id_in in number) is
                select  1
                from    rhnChannelFamily
                where   id = channel_family_id_in
                    and label = 'rhn-proxy';
        cursor  channel_family_is_satellite(channel_family_id_in in number) is
                select  1
                from    rhnChannelFamily
                where   id = channel_family_id_in
                    and label = 'rhn-satellite';
        -- this is *EXACTLY* like check_server_parent_membership, but if we recurse
        -- with the package-level one, we get a "cursor already open", so we need a
        -- copy on our call stack instead.  GROAN.
        cursor local_chk_server_parent_memb (
                        server_id_in number,
                        channel_id_in number ) is
                select  c.id
                from    rhnChannel                      c,
                                rhnServerChannel        sc
                where   1=1
                        and c.parent_channel = channel_id_in
                        and c.id = sc.channel_id
                        and sc.server_id = server_id_in;
    BEGIN
        FOR child IN local_chk_server_parent_memb(server_id_in, channel_id_in)
        LOOP
            if unsubscribe_children_in = 1 then
                unsubscribe_server(server_id_in => server_id_in,
                                                                channel_id_in => child.id,
                                                                immediate_in => immediate_in,
                                                                unsubscribe_children_in => unsubscribe_children_in,
                        deleting_server => deleting_server,
                        update_family_countsYN => update_family_countsYN);
            else
                rhn_exception.raise_exception('channel_unsubscribe_child_exists');
            end if;
        END LOOP child;
        
        server_already_in_chan := FALSE;
    
        FOR check_subscription IN check_server_subscription(server_id_in, channel_id_in)
        LOOP
            server_already_in_chan := TRUE;
        END LOOP check_subscription;
    
        IF NOT server_already_in_chan
        THEN
            RETURN;
        END IF;
        
   if deleting_server = 0 then 

      insert into rhnServerHistory (id,server_id,summary,details) (
          select  rhn_event_id_seq.nextval,
                server_id_in,
             'unsubscribed from channel ' || SUBSTR(c.label, 0, 106),
             c.label
          from    rhnChannel c
          where   c.id = channel_id_in
      );

        UPDATE rhnServer SET channels_changed = sysdate WHERE id = server_id_in;
   end if;
        
   DELETE FROM rhnServerChannel WHERE server_id = server_id_in AND channel_id = channel_id_in;

   if deleting_server = 0 then 
        queue_server(server_id_in, immediate_in);
   end if;

        channel_family_id_val := rhn_channel.family_for_channel(channel_id_in);
        IF channel_family_id_val IS NULL
        THEN
            rhn_exception.raise_exception('channel_unsubscribe_no_family');
        END IF;

        for ignore in channel_family_is_satellite(channel_family_id_val) loop
                delete from rhnSatelliteInfo where server_id = server_id_in;
        end loop;

        for ignore in channel_family_is_proxy(channel_family_id_val) loop
                delete from rhnProxyInfo where server_id = server_id_in;
        end loop;
        SELECT org_id INTO server_org_id_val
          FROM rhnServer
         WHERE id = server_id_in;
         
        if update_family_countsYN = 1 then
            rhn_channel.update_family_counts(channel_family_id_val, server_org_id_val);
        end if;
    END unsubscribe_server;


    FUNCTION family_for_channel(channel_id_in IN NUMBER)
    RETURN NUMBER
    IS
        channel_family_id_val NUMBER;
    BEGIN
        SELECT channel_family_id INTO channel_family_id_val
          FROM rhnChannelFamilyMembers
         WHERE channel_id = channel_id_in;
         
        RETURN channel_family_id_val;
    EXCEPTION
        WHEN NO_DATA_FOUND
        THEN
            RETURN NULL;
    END family_for_channel;

    FUNCTION available_family_subscriptions(channel_family_id_in IN NUMBER, org_id_in IN NUMBER)
    RETURN NUMBER
    IS
        cfp channel_family_perm_cursor%ROWTYPE;
        current_members_val NUMBER;
        max_members_val     NUMBER;
        found               NUMBER;
    BEGIN
        IF NOT channel_family_perm_cursor%ISOPEN
        THEN
            OPEN channel_family_perm_cursor(channel_family_id_in, org_id_in);
        END IF;

        FETCH channel_family_perm_cursor INTO cfp;
        
        WHILE channel_family_perm_cursor%FOUND
        LOOP
            found := 1;
            
            current_members_val := cfp.current_members;
            max_members_val := cfp.max_members;
            
            FETCH channel_family_perm_cursor INTO cfp;
        END LOOP;

        IF channel_family_perm_cursor%ISOPEN
        THEN
            CLOSE channel_family_perm_cursor;
        END IF;

        -- not found: either the channel fam doesn't have an entry in cfp, or the org doesn't have access to it.
        -- either way, there are no available subscriptions
        
        IF found IS NULL
        THEN
            RETURN 0;
        END IF;

        -- null max members?  in that case, pass it on; NULL means infinite                     
        IF max_members_val IS NULL
        THEN
            RETURN NULL;
        END IF;

        -- otherwise, return the delta  
        RETURN max_members_val - current_members_val;                   
    END available_family_subscriptions;

    FUNCTION available_fve_family_subs(channel_family_id_in IN NUMBER, org_id_in IN NUMBER)
    RETURN NUMBER
    IS
        cfp channel_family_perm_cursor%ROWTYPE;
        fve_current_members_val NUMBER;
        fve_max_members_val     NUMBER;
        found               NUMBER;

    BEGIN
        IF NOT channel_family_perm_cursor%ISOPEN THEN
            OPEN channel_family_perm_cursor(channel_family_id_in, org_id_in);
        END IF;

        FETCH channel_family_perm_cursor INTO cfp;

        WHILE channel_family_perm_cursor%FOUND LOOP
            found := 1;
            fve_current_members_val := cfp.fve_current_members;
            fve_max_members_val := cfp.fve_max_members;
            FETCH channel_family_perm_cursor INTO cfp;
        END LOOP;

        IF channel_family_perm_cursor%ISOPEN THEN
            CLOSE channel_family_perm_cursor;
        END IF;

        IF found IS NULL THEN
            RETURN 0;
        END IF;

        IF fve_max_members_val IS NULL THEN
            RETURN NULL;
        END IF;

        RETURN fve_max_members_val - fve_current_members_val;

    END available_fve_family_subs;

    
    -- *******************************************************************
    -- FUNCTION: channel_family_current_members
    -- Calculates and returns the actual count of systems consuming
    --   physical channel subscriptions.
    -- Called by: update_family_counts 
    --            rhn_entitlements.repoll_virt_guest_entitlements
    -- *******************************************************************
    function channel_family_current_members(channel_family_id_in IN NUMBER,
                                            org_id_in IN NUMBER)
    return number
    is
        current_members_count number := 0;
    begin
        select  count(distinct server_id)
        into    current_members_count
          from  rhnChannelFamilyServerPhysical cfsp
         where  cfsp.channel_family_id = channel_family_id_in
           and  cfsp.customer_id = org_id_in;
        return current_members_count;
    end;        


    function cfam_curr_fve_members(
        channel_family_id_in IN NUMBER,
        org_id_in IN NUMBER)
    return number
    is
        current_members_count number := 0;

    begin
        select count(sc.server_id)
          into current_members_count
          from rhnServerChannel sc,
               rhnChannelFamilyMembers cfm,
               rhnServer s
         where s.org_id = org_id_in
           and s.id = sc.server_id
           and cfm.channel_family_id = channel_family_id_in
           and cfm.channel_id = sc.channel_id
           and exists (
                select 1
                  from rhnChannelFamilyServerFve cfsp
                 where cfsp.CHANNEL_FAMILY_ID = channel_family_id_in
                   and cfsp.server_id = s.id
                );

        return current_members_count;
    end;
    PROCEDURE update_family_counts(channel_family_id_in IN NUMBER, 
                                   org_id_in IN NUMBER)
    IS
    BEGIN
        update rhnPrivateChannelFamily
           set current_members = ( channel_family_current_members(channel_family_id_in, org_id_in)),
               fve_current_members = ( cfam_curr_fve_members(channel_family_id_in, org_id_in))
         where org_id = org_id_in
           and channel_family_id = channel_family_id_in;
    END update_family_counts;
    
    PROCEDURE update_group_family_counts(group_label_in IN VARCHAR2,
                                   org_id_in IN NUMBER)
    IS
    BEGIN
        FOR i IN (
                SELECT DISTINCT CFM.channel_family_id, SG.org_id
                 FROM rhnChannelFamilyMembers CFM
                 JOIN rhnServerChannel SC
                   ON SC.channel_id = CFM.channel_id
                 JOIN rhnServerGroupMembers SGM
                   ON SC.server_id = SGM.server_id
                 JOIN rhnServerGroup SG
                   ON SGM.server_group_id = SG.id
                 JOIN rhnServerGroupType SGT
                   ON SG.group_type = SGT.id
                WHERE SGT.label = group_label_in
                  AND SG.org_id = org_id_in
                  AND SGT.is_base = 'Y'
        ) LOOP
            rhn_channel.update_family_counts(i.channel_family_id, i.org_id);
        END LOOP;
    END update_group_family_counts;

    FUNCTION available_chan_subscriptions(channel_id_in IN NUMBER, 
                                          org_id_in IN NUMBER)
    RETURN NUMBER
    IS
            channel_family_id_val NUMBER;
    BEGIN
        SELECT channel_family_id INTO channel_family_id_val
            FROM rhnChannelFamilyMembers
            WHERE channel_id = channel_id_in;
         
            RETURN rhn_channel.available_family_subscriptions(
                           channel_family_id_val, org_id_in);
    END available_chan_subscriptions;

	FUNCTION available_fve_chan_subs(channel_id_in IN NUMBER,
                                          org_id_in IN NUMBER)
    RETURN NUMBER
    IS
        channel_family_id_val NUMBER;

    BEGIN
        SELECT channel_family_id INTO channel_family_id_val
          FROM rhnChannelFamilyMembers
         WHERE channel_id = channel_id_in;

        RETURN rhn_channel.available_fve_family_subs( channel_family_id_val, org_id_in);
    END available_fve_chan_subs;

    procedure unsubscribe_server_from_family(server_id_in in number, 
                                             channel_family_id_in in number)
    is
    begin
        delete
        from    rhnServerChannel rsc
        where   rsc.server_id = server_id_in
            and channel_id in (
                select  rcfm.channel_id
                from    rhnChannelFamilyMembers rcfm
                where   rcfm.channel_family_id = channel_family_id_in);
    end;

    function get_org_id(channel_id_in in number)
    return number
    is
        org_id_out number;
    begin
        select org_id into org_id_out
            from rhnChannel
            where id = channel_id_in;
         
            return org_id_out;
    end get_org_id;
    
    function get_cfam_org_access(cfam_id_in in number, org_id_in in number)
    return number
    is
        cursor  families is
                        select  1
                        from    rhnOrgChannelFamilyPermissions cfp
                        where   cfp.org_id = org_id_in;
    begin
                -- the idea: if we get past this query, 
        -- the user has the role, else catch the exception and return 0
                for family in families loop
                return 1;
                end loop;
                return 0;
    end;

    function get_org_access(channel_id_in in number, org_id_in in number)
    return number
    is
        throwaway number;
    begin
        -- the idea: if we get past this query, 
        -- the org has access to the channel, else catch the exception and return 0
        select distinct 1 into throwaway
          from rhnChannelFamilyMembers CFM,
               rhnOrgChannelFamilyPermissions CFP
         where cfp.org_id = org_id_in
           and CFM.channel_family_id = CFP.channel_family_id
           and CFM.channel_id = channel_id_in
           and (CFP.max_members > 0 or CFP.max_members is null or CFP.org_id = 1);
           
        return 1;
        exception
            when no_data_found
            then
            return 0;
    end;
    
    -- check if a user has a given role, or if such a role is inferrable
    function user_role_check_debug(channel_id_in in number, 
                                   user_id_in in number, 
                                   role_in in varchar2, 
                                   reason_out out varchar2)
    return number
    is
        org_id number;
    begin
        org_id := rhn_user.get_org_id(user_id_in);

        -- channel might be shared
        if role_in = 'subscribe' and
           rhn_channel.shared_user_role_check(channel_id_in, user_id_in, role_in) = 1 then
            return 1;
        end if;
        
        if role_in = 'manage' and 
           NVL(rhn_channel.get_org_id(channel_id_in), -1) <> org_id then
                reason_out := 'channel_not_owned';
               return 0;
            end if;
        
        if role_in = 'subscribe' and 
           rhn_channel.get_org_access(channel_id_in, org_id) = 0 then
                reason_out := 'channel_not_available';
                return 0;
            end if;
        
        -- channel admins have all roles
        if rhn_user.check_role_implied(user_id_in, 'channel_admin') = 1 then
            reason_out := 'channel_admin';
            return 1;
            end if;

        -- the subscribe permission is inferred 
    -- UNLESS the not_globally_subscribable flag is set 
        if role_in = 'subscribe'
        then
            if rhn_channel.org_channel_setting(channel_id_in, 
                       org_id,
                       'not_globally_subscribable') = 0 then
                reason_out := 'globally_subscribable';
                    return 1;
            end if;
        end if;
        
        -- all other roles (manage right now) are explicitly granted    
        reason_out := 'direct_permission';
        return rhn_channel.direct_user_role_check(channel_id_in, 
                                              user_id_in, role_in);
    end;
    
    -- same as above, but with no OUT param; useful in views, etc
    function user_role_check(channel_id_in in number, user_id_in in number, role_in in varchar2)
    return number
    is
        throwaway varchar2(256);
    begin
        return rhn_channel.user_role_check_debug(channel_id_in, user_id_in, role_in, throwaway);
    end;

    --
    -- For multiorg phase II, this function simply checks to see if the user's
    -- has a trust relationship that includes this channel by id.
    --
    function shared_user_role_check(channel_id in number, user_id in number, role in varchar2)
    return number
    is
      n number;
      oid number;
    begin
      oid := rhn_user.get_org_id(user_id);
      select 1 into n
      from rhnSharedChannelView s
      where s.id = channel_id and s.org_trust_id = oid;
      return 1;
      exception
        when no_data_found then
          return 0;
    end;

    -- same as above, but returns 1 if user_id_in is null
    -- This is useful in queries where user_id is not specified
    function loose_user_role_check(channel_id_in in number, user_id_in in number, role_in in varchar2)
    return number
    is
    begin
        if user_id_in is null then
            return 1;
        end if;
        return user_role_check(channel_id_in, user_id_in, role_in);
    end loose_user_role_check;
    
    -- directly checks the table, no inferred permissions
    function direct_user_role_check(channel_id_in in number, user_id_in in number, role_in in varchar2)
    return number
    is
        throwaway number;
    begin
        -- the idea: if we get past this query, the user has the role, else catch the exception and return 0
        select 1 into throwaway
          from rhnChannelPermissionRole CPR,
               rhnChannelPermission CP
         where CP.user_id = user_id_in
           and CP.channel_id = channel_id_in
           and CPR.label = role_in
           and CP.role_id = CPR.id;
           
        return 1;
    exception
        when no_data_found
            then
            return 0;
    end;
    
    -- check if an org has a certain setting
    function org_channel_setting(channel_id_in in number, org_id_in in number, setting_in in varchar2)
    return number
    is
        throwaway number;
    begin
        -- the idea: if we get past this query, the org has the setting, else catch the exception and return 0
        select 1 into throwaway
          from rhnOrgChannelSettingsType OCST,
               rhnOrgChannelSettings OCS
         where OCS.org_id = org_id_in
           and OCS.channel_id = channel_id_in
           and OCST.label = setting_in
           and OCS.setting_id = OCST.id;
           
        return 1;
    exception
        when no_data_found
            then
            return 0;
    end;
    
    FUNCTION channel_priority(channel_id_in IN number) 
    RETURN number
    IS
         channel_name varchar2(256);
         priority number;
         end_of_life_val date;
         org_id_val number;
    BEGIN

        select name, end_of_life, org_id
        into channel_name, end_of_life_val, org_id_val
        from rhnChannel
        where id = channel_id_in;

        if end_of_life_val is not null then
          return -400;
        end if;

        if channel_name like 'Red Hat Enterprise Linux%' or channel_name like 'RHEL%' then
          priority := 1000;
          if channel_name not like '%Beta%' then
            priority := priority + 1000;
          end if;

          priority := priority +
            case
              when channel_name like '%v. 5%' then 600
              when channel_name like '%v. 4%' then 500
              when channel_name like '%v. 3%' then 400
              when channel_name like '%v. 2%' then 300
              when channel_name like '%v. 1%' then 200
              else 0
            end;

          priority := priority +
            case
              when channel_name like 'Red Hat Enterprise Linux (v. 5%' then 60
              when (channel_name like '%AS%' and channel_name not like '%Extras%') then 50
              when (channel_name like '%ES%' and channel_name not like '%Extras%') then 40
              when (channel_name like '%WS%' and channel_name not like '%Extras%') then 30
              when (channel_name like '%Desktop%' and channel_name not like '%Extras%') then 20
              when channel_name like '%Extras%' then 10
              else 0
            end; 

          priority := priority +
            case
              when channel_name like '%)' then 5
              else 0
            end;

          priority := priority +
            case
              when channel_name like '%32-bit x86%' then 4
              when channel_name like '%64-bit Intel Itanium%' then 3
              when channel_name like '%64-bit AMD64/Intel EM64T%' then 2
              else 0
            end;
        elsif channel_name like 'Red Hat Desktop%' then
            priority := 900;

            if channel_name not like '%Beta%' then
               priority := priority + 50;
            end if;
 
          priority := priority +
            case
              when channel_name like '%v. 4%' then 40
              when channel_name like '%v. 3%' then 30
              when channel_name like '%v. 2%' then 20
              when channel_name like '%v. 1%' then 10
              else 0
            end;
            
          priority := priority +
            case
              when channel_name like '%32-bit x86%' then 4
              when channel_name like '%64-bit Intel Itanium%' then 3
              when channel_name like '%64-bit AMD64/Intel EM64T%' then 2
              else 0
            end;
         
        elsif org_id_val is not null then
          priority := 600;
        else
          priority := 500;
        end if;
      
      return -priority;

    end channel_priority;

    -- right now this only does the accounting changes; the cascade
    -- actually does the rhnServerChannel delete.
    procedure delete_server_channels(server_id_in in number)
    is
    begin
        update  rhnPrivateChannelFamily
        set     current_members = current_members -1
        where   org_id in (
                        select  org_id
                        from    rhnServer
                        where   id = server_id_in
                )
                and channel_family_id in (
                        select  rcfm.channel_family_id
                        from    rhnChannelFamilyMembers rcfm,
                                rhnServerChannel rsc
                        where   rsc.server_id = server_id_in
                                and rsc.channel_id = rcfm.channel_id
                and not exists (
                    select 1
                    from
                        rhnChannelFamilyVirtSubLevel cfvsl,
                        rhnSGTypeVirtSubLevel sgtvsl,
                        rhnServerEntitlementView sev,
                        rhnVirtualInstance vi
                    where
                        -- system is a virtual instance
                        vi.virtual_system_id = server_id_in
                        and vi.host_system_id = sev.server_id
                        -- system's host has a virt ent
                        and sev.label in ('virtualization_host',
                                          'virtualization_host_platform')
                        and sev.server_group_type_id = 
                            sgtvsl.server_group_type_id
                        -- the host's virt ent grants a cf virt sub level
                        and sgtvsl.virt_sub_level_id = cfvsl.virt_sub_level_id
                        -- the cf is in that virt sub level
                        and cfvsl.channel_family_id = rcfm.channel_family_id
                    )
                );
    end;

        -- this could certainly be optimized to do updates if needs be
        procedure refresh_newest_package(channel_id_in in number, caller_in in varchar2 := '(unknown)')
        is
        begin
                delete from rhnChannelNewestPackage where channel_id = channel_id_in;
                insert into rhnChannelNewestPackage
                        ( channel_id, name_id, evr_id, package_id, package_arch_id ) 
                        (       select  channel_id,
                                                name_id, evr_id,
                                                package_id, package_arch_id
                                from    rhnChannelNewestPackageView
                                where   channel_id = channel_id_in
                        );
                insert into rhnChannelNewestPackageAudit (channel_id, caller)
                    values (channel_id_in, caller_in);
                update rhnChannel 
                    set last_modified = greatest(sysdate, last_modified + 1/86400)
                    where id = channel_id_in; 
        end;

   procedure update_channel ( channel_id_in in number, invalidate_ss in number := 0, 
                              date_to_use in date := sysdate )
   is

   channel_last_modified date;
   last_modified_value date;

   cursor snapshots is
   select  snapshot_id id
   from    rhnSnapshotChannel
   where   channel_id = channel_id_in;

   begin

      select last_modified
      into channel_last_modified
      from rhnChannel
      where id = channel_id_in;
  
      last_modified_value := date_to_use;

      if last_modified_value <= channel_last_modified then
          last_modified_value := last_modified_value + 1/86400;
      end if;

      update rhnChannel set last_modified = last_modified_value
      where id = channel_id_in;

      if invalidate_ss = 1 then 
        for snapshot in snapshots loop
            update rhnSnapshot
            set invalid = lookup_snapshot_invalid_reason('channel_modified')
            where id = snapshot.id;
        end loop;
      end if;

   end update_channel;

   procedure update_channels_by_package ( package_id_in in number, date_to_use in date := sysdate )
   is

   cursor channels is
   select channel_id
   from rhnChannelPackage
   where package_id = package_id_in
   order by channel_id;

   begin
      for channel in channels loop
         -- we want to invalidate the snapshot assocated with the channel when we
         -- do this b/c we know we've added or removed or packages
         rhn_channel.update_channel ( channel.channel_id, 1, date_to_use );
      end loop;
   end update_channels_by_package;

   
   procedure update_channels_by_errata ( errata_id_in number, date_to_use in date := sysdate )
   is

   cursor channels is
   select channel_id
   from rhnChannelErrata
   where errata_id = errata_id_in
   order by channel_id;

   begin
      for channel in channels loop
         -- we won't invalidate snapshots, b/c just changing the errata associated with
         -- a channel shouldn't invalidate snapshots
         rhn_channel.update_channel ( channel.channel_id, 0, date_to_use );
      end loop;
   end update_channels_by_errata;

   procedure update_needed_cache(channel_id_in in number)
   is
       pragma autonomous_transaction;
                -- update of needed cache ican be commited on a per server basis
                -- b/c failure of update for a server means nothing for the other servers
   begin
      -- we intentionaly do a loop here instead of one huge select
      -- b/c we want to break update into smaller transaction to unblock other sessions
      -- querying rhnServerNeededCache
      for server in (
                select sc.server_id as id
                  from rhnServerChannel sc
                 where sc.channel_id = channel_id_in
      ) loop
         rhn_server.update_needed_cache(server.id);
         commit;
      end loop;
   end update_needed_cache;

END rhn_channel;
/
SHOW ERRORS
07070100000590000081B400000000000000000000000167AE1114000055C9000000000000000000000000000000000000006000000000susemanager-schema/upgrade/spacewalk-schema-1.1-to-spacewalk-schema-1.2/066-rhn_server-body.sql   --
-- Copyright (c) 2008--2010 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--

create or replace
package body rhn_server
is
    function system_service_level(
    	server_id_in in number,
	service_level_in in varchar2
    ) return number is

    cursor ents is 
      select label from rhnServerEntitlementView
      where server_id = server_id_in;

    retval number := 0;

    begin
         for ent in ents loop
            retval := rhn_entitlements.entitlement_grants_service (ent.label, service_level_in);
            if retval = 1 then
               return retval;
            end if;
         end loop;

         return retval;

    end system_service_level;

        
    function can_change_base_channel(server_id_in IN NUMBER)
    return number
    is
    	throwaway number;
    begin
    	-- the idea: if we get past this query, the server is
	-- neither sat nor proxy, so base channel is changeable
	
	select 1 into throwaway
	  from rhnServer S
	 where S.id = server_id_in
	   and not exists (select 1 from rhnSatelliteInfo SI where SI.server_id = S.id)
	   and not exists (select 1 from rhnProxyInfo PI where PI.server_id = S.id);
	   
	return 1;
    exception
    	when no_data_found
	    then
	    return 0;
    end can_change_base_channel;
	        
    procedure set_custom_value(
    	server_id_in in number,
	user_id_in in number,
	key_label_in in varchar2,
	value_in in varchar2
    ) is
    	key_id_val number;
    begin
    	select CDK.id into key_id_val
	  from rhnCustomDataKey CDK,
	       rhnServer S
	 where S.id = server_id_in
	   and S.org_id = CDK.org_id
	   and CDK.label = key_label_in;
	   
	begin
	    insert into rhnServerCustomDataValue (server_id, key_id, value, created_by, last_modified_by)
	    values (server_id_in, key_id_val, value_in, user_id_in, user_id_in);
	exception
	    when DUP_VAL_ON_INDEX
	    	then
		update rhnServerCustomDataValue
		   set value = value_in,
		       last_modified_by = user_id_in
		 where server_id = server_id_in
		   and key_id = key_id_val;		   
	end;
	
    end set_custom_value;
    
    function bulk_set_custom_value(
    	key_label_in in varchar2,
	value_in in varchar2,
	set_label_in in varchar2,
	set_uid_in in number
    )
    return integer
    is
    i integer := 0;
    begin
        i := 0;
    	for server in rhn_set.set_iterator(set_label_in, set_uid_in)
	loop
	    if rhn_server.system_service_level(server.element, 'provisioning') = 1 then
	    	rhn_server.set_custom_value(server.element, set_uid_in, key_label_in, value_in);
            i := i + 1;
	    end if;
	end loop server;
    return i;
    end bulk_set_custom_value;

    procedure bulk_snapshot_tag(
    	org_id_in in number,
        tagname_in in varchar2,
	set_label_in in varchar2,
	set_uid_in in number
    ) is
    	snapshot_id number;
    begin
    	for server in rhn_set.set_iterator(set_label_in, set_uid_in)
	loop
	    if rhn_server.system_service_level(server.element, 'provisioning') = 1 then
	    	begin
	    	    select max(id) into snapshot_id
	    	    from rhnSnapshot
	    	    where server_id = server.element;
	    	exception
	    	    when NO_DATA_FOUND then
		    	rhn_server.snapshot_server(server.element, 'tagging system:  ' || tagname_in);
			
			select max(id) into snapshot_id
			from rhnSnapshot
			where server_id = server.element;
		end;
		 
		-- now have a snapshot_id to work with...
		begin
		    rhn_server.tag_snapshot(snapshot_id, org_id_in, tagname_in);
		exception
		    when DUP_VAL_ON_INDEX
		    	then
			-- do nothing, be forgiving...
			null;
		end;
	    end if;
	end loop server;    
    end bulk_snapshot_tag;

    procedure tag_delete(
    	server_id_in in number,
	tag_id_in in number
    ) is
    	cursor snapshots is
		select	snapshot_id
		from	rhnSnapshotTag
		where	tag_id = tag_id_in;
	tag_id_tmp number;
    begin
    	select	id into tag_id_tmp
	from	rhnTag
	where	id = tag_id_in
	for update;

	delete
		from	rhnSnapshotTag
		where	server_id = server_id_in
			and tag_id = tag_id_in;
	for snapshot in snapshots loop
		return;
	end loop;
	delete
		from rhnTag
		where id = tag_id_in;
    end tag_delete;

    procedure tag_snapshot(
        snapshot_id_in in number,
	org_id_in in number,
	tagname_in in varchar2
    ) is
    begin
    	insert into rhnSnapshotTag (snapshot_id, server_id, tag_id)
	select snapshot_id_in, server_id, lookup_tag(org_id_in, tagname_in)
	from rhnSnapshot
	where id = snapshot_id_in;
    end tag_snapshot;

    procedure bulk_snapshot(
    	reason_in in varchar2,
	set_label_in in varchar2,
	set_uid_in in number
    ) is
    begin
    	for server in rhn_set.set_iterator(set_label_in, set_uid_in)
	loop
    	    if rhn_server.system_service_level(server.element, 'provisioning') = 1 then
	    	rhn_server.snapshot_server(server.element, reason_in);
	    end if;
	end loop server;
    end bulk_snapshot;

    procedure snapshot_server(
    	server_id_in in number,
	reason_in in varchar2
    ) is
    	snapshot_id number;
	cursor revisions is
		select distinct
			cr.id
		from	rhnConfigRevision	cr,
			rhnConfigFileName	cfn,
			rhnConfigFile		cf,
			rhnConfigChannel	cc,
			rhnServerConfigChannel	scc
		where	1=1
			and scc.server_id = server_id_in
			and scc.config_channel_id = cc.id
			and cc.id = cf.config_channel_id
			and cf.id = cr.config_file_id
			and cr.id = cf.latest_config_revision_id
			and cf.config_file_name_id = cfn.id
			and cf.id = lookup_first_matching_cf(scc.server_id, cfn.path);
	locked integer;
    begin
    	select rhn_snapshot_id_seq.nextval into snapshot_id from dual;

	insert into rhnSnapshot (id, org_id, server_id, reason) (
		select	snapshot_id,
			s.org_id,
			server_id_in,
			reason_in
		from	rhnServer s
		where	s.id = server_id_in
	);
	insert into rhnSnapshotChannel (snapshot_id, channel_id) (
		select	snapshot_id, sc.channel_id
		from	rhnServerChannel sc
		where	sc.server_id = server_id_in
	);
	insert into rhnSnapshotServerGroup (snapshot_id, server_group_id) (
		select	snapshot_id, sgm.server_group_id
		from	rhnServerGroupMembers sgm
		where	sgm.server_id = server_id_in
	);
        locked := 0;
        while true loop
            begin
                insert into rhnPackageNEVRA (id, name_id, evr_id, package_arch_id)
                select rhn_pkgnevra_id_seq.nextval, sp.name_id, sp.evr_id, sp.package_arch_id
                from rhnServerPackage sp
                where sp.server_id = server_id_in
                        and not exists
                        (select 1
                                from rhnPackageNEVRA nevra
                                where nevra.name_id = sp.name_id
                                        and nevra.evr_id = sp.evr_id
                                        and (nevra.package_arch_id = sp.package_arch_id
                                            or (nevra.package_arch_id is null
                                                and sp.package_arch_id is null)));
                exit;
            exception when dup_val_on_index then
                if locked = 1 then
                    raise;
                else
                    lock table rhnPackageNEVRA in exclusive mode;
                    locked := 1;
                end if;
            end;
        end loop;
	insert into rhnSnapshotPackage (snapshot_id, nevra_id) (
                select distinct snapshot_id, nevra.id
                from    rhnServerPackage sp, rhnPackageNEVRA nevra
                where   sp.server_id = server_id_in
                        and nevra.name_id = sp.name_id
                        and nevra.evr_id = sp.evr_id
                        and (nevra.package_arch_id = sp.package_arch_id
                            or (nevra.package_arch_id is null
                                and sp.package_arch_id is null))
	);

	insert into rhnSnapshotConfigChannel ( snapshot_id, config_channel_id ) (
		select	snapshot_id, scc.config_channel_id
		from	rhnServerConfigChannel scc
		where	server_id = server_id_in
	);

	for revision in revisions loop
		insert into rhnSnapshotConfigRevision (
				snapshot_id, config_revision_id
			) values (
				snapshot_id, revision.id
			);
	end loop;
    end snapshot_server;

    procedure remove_action(
    	server_id_in in number,
	action_id_in in number
    ) is
    	-- this really wants "nulls last", but 8.1.7.3.0 sucks ass.
	-- instead, we make a local table that holds our
	-- list of ids with null prereqs.  There's surely a better way
	-- (an array instead of a table maybe?  who knows...)
	-- but I've got code to do this handy that I can look at ;)
    	cursor chained_actions is
		select	id, prerequisite
		from	rhnAction
		start with id = action_id_in
		connect by prior id = prerequisite
		order by prerequisite desc;
	cursor sessions is
		select	s.id
		from	rhnKickstartSession s
		where	server_id_in in (s.old_server_id, s.new_server_id)
			and s.action_id = action_id_in
			and not exists (
				select	1
				from	rhnKickstartSessionState ss
				where	ss.id = s.state_id
					and ss.label in ('failed','complete')
			);
	type chain_end_type is table of number index by binary_integer;
	chain_ends chain_end_type;
	i number;
	prereq number := 1;
    begin
	select	prerequisite
	into	prereq
	from	rhnAction
	where	id = action_id_in;

	if prereq is not null then
		rhn_exception.raise_exception('action_is_child');
	end if;

	i := 0;
	for action in chained_actions loop
		if action.prerequisite is null then
			chain_ends(i) := action.id;
			i := i + 1;
		else
			delete from rhnServerAction
				where server_id = server_id_in
				and action_id = action.id;
		end if;
	end loop;
	i := chain_ends.first;
	while i is not null loop
		delete from rhnServerAction
			where server_id = server_id_in
			and action_id = chain_ends(i);
		i := chain_ends.next(i);
	end loop;
	for s in sessions loop
		update rhnKickstartSession
			set 	state_id = (
					select	id
					from	rhnKickstartSessionState
					where	label = 'failed'
				),
				action_id = null
			where	id = s.id;
		set_ks_session_history_message(s.id, 'failed', 'Kickstart cancelled due to action removal');
	end loop;
    end remove_action;
   
    function check_user_access(server_id_in in number, user_id_in in number)
    return number
    is
    	has_access number;
    begin
    	-- first check; if this returns no rows, then the server/user are in different orgs, and we bail
        select 1 into has_access
	  from rhnServer S,
	       web_contact wc
	 where wc.org_id = s.org_id
	   and s.id = server_id_in
	   and wc.id = user_id_in;

	-- okay, so they're in the same org.  if we have an org admin, they get a free pass
    	if rhn_user.check_role(user_id_in, 'org_admin') = 1
	then
	    return 1;
	end if;
		   
    	select 1 into has_access
	  from rhnServerGroupMembers SGM,
	       rhnUserServerGroupPerms USG
	 where SGM.server_group_id = USG.server_group_id
	   and SGM.server_id = server_id_in
	   and USG.user_id = user_id_in
	   and rownum = 1;
	   
	return 1;
    exception
    	when no_data_found
	    then
	    return 0;
    end check_user_access;

    -- *******************************************************************
    -- FUNCTION: can_server_consume_virt_slot
    -- Returns 1 if the server id is eligible to consume a virtual slot,
    --   else returns 0.
    -- Called by: insert_into_servergroup, delete_from_servergroup
    -- *******************************************************************
    function can_server_consume_virt_slot(server_id_in in number,
                                           group_type_in in
                                           rhnServerGroupType.label%TYPE)
    return number                                           
    is

        cursor server_virt_slots is
            select vi.VIRTUAL_SYSTEM_ID
            from
                rhnVirtualInstance vi
            where
                -- server id is a virtual instance
                vi.VIRTUAL_SYSTEM_ID = server_id_in
                -- server id's host is virt entitled
                and exists ( select 1
                     from rhnServerEntitlementView sev
                 where vi.HOST_SYSTEM_ID = sev.server_id
                 and sev.label in ('virtualization_host',
                                   'virtualization_host_platform') )
                -- server id's host also has the ent we want
                and exists ( select 1
                     from rhnServerEntitlementView sev2
                 where vi.HOST_SYSTEM_ID = sev2.server_id
                 and sev2.label = group_type_in );

    begin
        for server_virt_slot in server_virt_slots loop
            return 1;
        end loop;
        return 0;
    end can_server_consume_virt_slot;


    procedure insert_into_servergroup (
		server_id_in in number,
		server_group_id_in in number
    ) is
		used_slots number;
		max_slots number;
		org_id number;
		mgmt_available number;
		mgmt_upgrade number;
		mgmt_sgid number;
		prov_available number;
		prov_upgrade number;
		prov_sgid number;
		group_label rhnServerGroupType.label%TYPE;
		group_type number;
	begin
		-- frist, group_type = null, because it's easy...

		-- this will rowlock the servergroup we're trying to change;
		-- we probably need to lock the other one, but I think the chances
		-- of it being a real issue are very small for now...
		select	sg.group_type, sg.org_id, sg.current_members, sg.max_members
		into	group_type, org_id, used_slots, max_slots
		from	rhnServerGroup sg
		where	sg.id = server_group_id_in
		for update of sg.current_members;

		if group_type is null then
			if used_slots >= max_slots then
				rhn_exception.raise_exception('servergroup_max_members');
			end if;

			insert into rhnServerGroupMembers(
					server_id, server_group_id
				) values (
					server_id_in, server_group_id_in
				);
			update rhnServerGroup
				set current_members = current_members + 1
				where id = server_group_id_in;

			rhn_cache.update_perms_for_server_group(server_group_id_in);
			return;
		end if;

		-- now for group_type != null
		-- 
		select	label
		into	group_label
		from	rhnServerGroupType	sgt
		where	sgt.id = group_type;

		-- the naive easy path that gets hit most often and has to be quickest.
		if group_label in ('sw_mgr_entitled',
                           'enterprise_entitled',
                           'monitoring_entitled',
                           'provisioning_entitled',
                           'virtualization_host',
                           'virtualization_host_platform') then
			if used_slots >= max_slots and 
               (can_server_consume_virt_slot(server_id_in, group_label) != 1) 
               then
				rhn_exception.raise_exception('servergroup_max_members');
			end if;

			insert into rhnServerGroupMembers(
					server_id, server_group_id
				) values (
					server_id_in, server_group_id_in
				);

            -- Only update current members if the system in consuming a 
            -- physical slot.
            if can_server_consume_virt_slot(server_id_in, group_label) = 0 then
                update rhnServerGroup
                set current_members = current_members + 1
                where id = server_group_id_in;
            end if;                

			return;
		end if;
	end;

	function insert_into_servergroup_maybe (
		server_id_in in number,
		server_group_id_in in number
	) return number is 
		retval number := 0;
		cursor servergroups is
			select	s.id	server_id,
					sg.id	server_group_id
			from	rhnServerGroup	sg,
					rhnServer		s
			where	s.id = server_id_in
				and sg.id = server_group_id_in
				and s.org_id = sg.org_id
				and not exists (
					select	1
					from	rhnServerGroupMembers sgm
					where	sgm.server_id = s.id
						and sgm.server_group_id = sg.id
				);
	begin
		for sgm in servergroups loop
			rhn_server.insert_into_servergroup(sgm.server_id, sgm.server_group_id);
			retval := retval + 1;
		end loop;
		return retval;
	end insert_into_servergroup_maybe;

	procedure insert_set_into_servergroup (
		server_group_id_in in number,
		user_id_in in number,
		set_label_in in varchar2
	) is
		cursor servers is
			select	st.element	id
			from	rhnSet		st
			where	st.user_id = user_id_in
				and st.label = set_label_in
				and exists (
					select	1
					from	rhnUserManagedServerGroups umsg
					where	umsg.server_group_id = server_group_id_in
						and umsg.user_id = user_id_in
					)
				and not exists (
					select	1
					from	rhnServerGroupMembers sgm
					where	sgm.server_id = st.element
						and sgm.server_group_id = server_group_id_in
				);
	begin
		for s in servers loop
			rhn_server.insert_into_servergroup(s.id, server_group_id_in);
		end loop;
	end insert_set_into_servergroup;
		
    procedure delete_from_servergroup (
    	server_id_in in number,
		server_group_id_in in number
    ) is
        cursor server_virt_groups is
            select 1
            from rhnServerEntitlementVirtual sev
            where sev.server_id = server_id_in
            and sev.server_group_id = server_group_id_in;

		oid number;
		mgmt_sgid number;
		label rhnServerGroupType.label%TYPE;
		group_type number;
	begin
		begin
			select	sg.group_type, sg.org_id
			into	group_type,	oid
			from	rhnServerGroupMembers	sgm,
					rhnServerGroup			sg
			where	sg.id = server_group_id_in
				and sg.id = sgm.server_group_id
				and sgm.server_id = server_id_in
			for update of sg.current_members;
		exception
			when no_data_found then
				rhn_exception.raise_exception('server_not_in_group');
		end;

		-- do group_type is null first
		if group_type is null then
			delete from rhnServerGroupMembers
				where server_group_id = server_group_id_in
				and	server_id = server_id_in;
			update rhnServerGroup
				set current_members = current_members - 1
				where id = server_group_id_in;
			rhn_cache.update_perms_for_server_group(server_group_id_in);
			return;
		end if;

		select	sgt.label
		into	label
		from	rhnServerGroupType sgt
		where	sgt.id = group_type;

		if label in ('sw_mgr_entitled',
                     'enterprise_entitled', 
                     'provisioning_entitled', 
                     'monitoring_entitled',
                     'virtualization_host',
                     'virtualization_host_platform') then

            -- Only update current members if the system is consuming
            -- a physical slot.
            for server_virt_group in server_virt_groups loop                
                delete from rhnServerGroupMembers
                where server_group_id = server_group_id_in
                and	server_id = server_id_in;
                return;
            end loop;                

            delete from rhnServerGroupMembers
            where server_group_id = server_group_id_in
            and	server_id = server_id_in;

            update rhnServerGroup
            set current_members = current_members - 1
            where id = server_group_id_in;
 
		end if;
	end;

	procedure delete_set_from_servergroup (
		server_group_id_in in number,
		user_id_in in number,
		set_label_in in varchar2
	) is
		cursor servergroups is
			select	sgm.server_id, sgm.server_group_id
			from	rhnSet st,
					rhnServerGroupMembers sgm
			where	sgm.server_group_id = server_group_id_in
				and st.user_id = user_id_in
				and st.label = set_label_in
				and sgm.server_id = st.element
				and exists (
					select	1
					from	rhnUserManagedServerGroups usgp
					where	usgp.server_group_id = server_group_id_in
						and usgp.user_id = user_id_in
				);
	begin
		for sgm in servergroups loop
			rhn_server.delete_from_servergroup(sgm.server_id, server_group_id_in);
		end loop;
	end delete_set_from_servergroup;

	procedure clear_servergroup (
		server_group_id_in in number
	) is
		cursor servers is
			select	sgm.server_id	id
			from	rhnServerGroupMembers sgm
			where	sgm.server_group_id = server_group_id_in;
	begin
		for s in servers loop
			rhn_server.delete_from_servergroup(s.id, server_group_id_in);
		end loop;
	end clear_servergroup;

	procedure delete_from_org_servergroups (
		server_id_in in number
	) is
		cursor servergroups is
			select	sgm.server_group_id id
			from	rhnServerGroup sg,
					rhnServerGroupMembers sgm
			where	sgm.server_id = server_id_in
				and sgm.server_group_id = sg.id
				and sg.group_type is null;
	begin
		for sg in servergroups loop
			rhn_server.delete_from_servergroup(server_id_in, sg.id);
		end loop;
	end delete_from_org_servergroups;

	function get_ip_address (
		server_id_in in number
	) return varchar2 is
		cursor interfaces is
			select	name, ip_addr
			from	rhnServerNetInterface
			where	server_id = server_id_in
				and ip_addr != '127.0.0.1';
		cursor addresses is
			select	ipaddr ip_addr
			from	rhnServerNetwork
			where	server_id = server_id_in
				and ipaddr != '127.0.0.1';
	begin
		for addr in addresses loop
			return addr.ip_addr;
		end loop;
		for iface in interfaces loop
			return iface.ip_addr;
		end loop;
		return NULL;
	end get_ip_address;

        procedure update_needed_cache(server_id_in in number)
        is
        begin
            delete from rhnServerNeededCache
             where server_id = server_id_in;
            insert into rhnServerNeededCache
                   (server_id, errata_id, package_id)
                   (select distinct server_id, errata_id, package_id
                      from rhnServerNeededView
                     where server_id = server_id_in);
        end update_needed_cache;

end rhn_server;
/
SHOW ERRORS
   07070100000591000081B400000000000000000000000167AE1114000002AF000000000000000000000000000000000000007400000000susemanager-schema/upgrade/spacewalk-schema-1.1-to-spacewalk-schema-1.2/070-rhnPackage-rhn_package_compat_check.sql   
set serveroutput on

begin
	for i in (
		select constraint_name, constraint_type, search_condition
		from ( select 'RHN_PACKAGE_COMPAT_CHECK' x from dual ) d, user_constraints
		where d.x = constraint_name (+)
		) loop
		if i.constraint_name is null or not (i.constraint_type = 'C' and i.search_condition = 'compat in ( 1 , 0 )') then
			if i.constraint_name is not null then
				execute immediate 'alter table RHNPACKAGE drop constraint RHN_PACKAGE_COMPAT_CHECK';
			end if;
			execute immediate 'alter table RHNPACKAGE add constraint RHN_PACKAGE_COMPAT_CHECK check (compat in ( 1 , 0 ))';
			dbms_output.put_line('(Re)creating RHN_PACKAGE_COMPAT_CHECK');
		end if;
	end loop;
end;
/

 07070100000592000081B400000000000000000000000167AE1114000002D0000000000000000000000000000000000000007900000000susemanager-schema/upgrade/spacewalk-schema-1.1-to-spacewalk-schema-1.2/071-rhn_contact_groups-rhn_cntgp_rotate_f_ck.sql  
set serveroutput on

begin
	for i in (
		select constraint_name, constraint_type, search_condition
		from ( select 'RHN_CNTGP_ROTATE_F_CK' x from dual ) d, user_constraints
		where d.x = constraint_name (+)
		) loop
		if i.constraint_name is null or not (i.constraint_type = 'C' and i.search_condition = 'rotate_first in (''0'',''1'')') then
			if i.constraint_name is not null then
				execute immediate 'alter table RHN_CONTACT_GROUPS drop constraint RHN_CNTGP_ROTATE_F_CK';
			end if;
			execute immediate 'alter table RHN_CONTACT_GROUPS add constraint RHN_CNTGP_ROTATE_F_CK check (rotate_first in (''0'',''1'')) novalidate';
			dbms_output.put_line('Recreating RHN_CNTGP_ROTATE_F_CK');
		end if;
	end loop;
end;
/

07070100000593000081B400000000000000000000000167AE1114000002A6000000000000000000000000000000000000006900000000susemanager-schema/upgrade/spacewalk-schema-1.1-to-spacewalk-schema-1.2/072-rhnKSData-rhn_ks_type_ck.sql  
set serveroutput on

begin
	for i in (
		select constraint_name, constraint_type, search_condition
		from ( select 'RHN_KS_TYPE_CK' x from dual ) d, user_constraints
		where d.x = constraint_name (+)
		) loop
		if i.constraint_name is null or not (i.constraint_type = 'C' and i.search_condition = 'ks_type in (''wizard'',''raw'')') then
			if i.constraint_name is not null then
				execute immediate 'alter table RHNKSDATA drop constraint RHN_KS_TYPE_CK';
			end if;
			execute immediate 'alter table RHNKSDATA add constraint RHN_KS_TYPE_CK check (ks_type in (''wizard'',''raw'')) novalidate';
			dbms_output.put_line('Recreating RHN_KS_TYPE_CK');
		end if;
	end loop;
end;
/

  07070100000594000081B400000000000000000000000167AE111400000246000000000000000000000000000000000000007D00000000susemanager-schema/upgrade/spacewalk-schema-1.1-to-spacewalk-schema-1.2/073-rhnKickstartScript-rhn_ksscript_rawscript_ck.sql  
set serveroutput on

begin
	for i in (
		select constraint_name, constraint_type, search_condition
		from user_constraints
		where table_name = 'RHNKICKSTARTSCRIPT'
		) loop
		if i.constraint_type = 'C' and i.search_condition like 'raw_script in%' then
			execute immediate 'alter table RHNKICKSTARTSCRIPT drop constraint ' || i.constraint_name;
		end if;
	end loop;
	execute immediate 'alter table RHNKICKSTARTSCRIPT add constraint RHN_KSSCRIPT_RAWSCRIPT_CK check (raw_script in (''Y'',''N'')) novalidate';
	dbms_output.put_line('(Re)creating RHN_KSSCRIPT_RAWSCRIPT_CK');
end;
/

  07070100000595000081B400000000000000000000000167AE11140000DED8000000000000000000000000000000000000006800000000susemanager-schema/upgrade/spacewalk-schema-1.1-to-spacewalk-schema-1.2/079-check_constraint_syntax.sql   
set serveroutput on


begin
	for i in (
		select constraint_name, constraint_type, search_condition
		from ( select 'RHN_ACTION_ARCHIVED_CK' x from dual ) d, user_constraints
		where d.x = constraint_name (+)
		) loop
		if i.constraint_name is null or not (i.constraint_type = 'C' and i.search_condition = 'archived in (0, 1)') then
			if i.constraint_name is not null then
				execute immediate 'alter table RHNACTION drop constraint RHN_ACTION_ARCHIVED_CK';
			end if;
			execute immediate 'alter table RHNACTION add constraint RHN_ACTION_ARCHIVED_CK check (archived in (0, 1)) novalidate';
			dbms_output.put_line('Recreating RHN_ACTION_ARCHIVED_CK');
		end if;
	end loop;
end;
/

begin
	for i in (
		select constraint_name, constraint_type, search_condition
		from ( select 'RHN_ACTIONCD_FILE_IC_CK' x from dual ) d, user_constraints
		where d.x = constraint_name (+)
		) loop
		if i.constraint_name is null or not (i.constraint_type = 'C' and i.search_condition = 'import_contents in (''Y'',''N'')') then
			if i.constraint_name is not null then
				execute immediate 'alter table RHNACTIONCONFIGDATE drop constraint RHN_ACTIONCD_FILE_IC_CK';
			end if;
			execute immediate 'alter table RHNACTIONCONFIGDATE add constraint RHN_ACTIONCD_FILE_IC_CK check (import_contents in (''Y'',''N'')) novalidate';
			dbms_output.put_line('Recreating RHN_ACTIONCD_FILE_IC_CK');
		end if;
	end loop;
end;
/

begin
	for i in (
		select constraint_name, constraint_type, search_condition
		from ( select 'RHN_ACTIONCD_FILE_FT_CK' x from dual ) d, user_constraints
		where d.x = constraint_name (+)
		) loop
		if i.constraint_name is null or not (i.constraint_type = 'C' and i.search_condition = 'file_type in (''W'',''B'')') then
			if i.constraint_name is not null then
				execute immediate 'alter table RHNACTIONCONFIGDATEFILE drop constraint RHN_ACTIONCD_FILE_FT_CK';
			end if;
			execute immediate 'alter table RHNACTIONCONFIGDATEFILE add constraint RHN_ACTIONCD_FILE_FT_CK check (file_type in (''W'',''B'')) novalidate';
			dbms_output.put_line('Recreating RHN_ACTIONCD_FILE_FT_CK');
		end if;
	end loop;
end;
/

begin
	for i in (
		select constraint_name, constraint_type, search_condition
		from ( select 'RHN_ACTIONDC_REST_CK' x from dual ) d, user_constraints
		where d.x = constraint_name (+)
		) loop
		if i.constraint_name is null or not (i.constraint_type = 'C' and i.search_condition = 'restart in (''Y'',''N'')') then
			if i.constraint_name is not null then
				execute immediate 'alter table RHNACTIONDAEMONCONFIG drop constraint RHN_ACTIONDC_REST_CK';
			end if;
			execute immediate 'alter table RHNACTIONDAEMONCONFIG add constraint RHN_ACTIONDC_REST_CK check (restart in (''Y'',''N'')) novalidate';
			dbms_output.put_line('Recreating RHN_ACTIONDC_REST_CK');
		end if;
	end loop;
end;
/

begin
	for i in (
		select constraint_name, constraint_type, search_condition
		from ( select 'RHN_ACT_P_PARAM_CK' x from dual ) d, user_constraints
		where d.x = constraint_name (+)
		) loop
		if i.constraint_name is null or not (i.constraint_type = 'C' and i.search_condition = 'parameter IN (''upgrade'', ''install'', ''remove'', ''downgrade'')') then
			if i.constraint_name is not null then
				execute immediate 'alter table RHNACTIONPACKAGE drop constraint RHN_ACT_P_PARAM_CK';
			end if;
			execute immediate 'alter table RHNACTIONPACKAGE add constraint RHN_ACT_P_PARAM_CK check (parameter IN (''upgrade'', ''install'', ''remove'', ''downgrade'')) novalidate';
			dbms_output.put_line('Recreating RHN_ACT_P_PARAM_CK');
		end if;
	end loop;
end;
/

begin
	for i in (
		select constraint_name, constraint_type, search_condition
		from ( select 'RHN_ACTION_TYPE_TRIGSNAP_CK' x from dual ) d, user_constraints
		where d.x = constraint_name (+)
		) loop
		if i.constraint_name is null or not (i.constraint_type = 'C' and i.search_condition = 'trigger_snapshot in (''Y'',''N'')') then
			if i.constraint_name is not null then
				execute immediate 'alter table RHNACTIONTYPE drop constraint RHN_ACTION_TYPE_TRIGSNAP_CK';
			end if;
			execute immediate 'alter table RHNACTIONTYPE add constraint RHN_ACTION_TYPE_TRIGSNAP_CK check (trigger_snapshot in (''Y'',''N'')) novalidate';
			dbms_output.put_line('Recreating RHN_ACTION_TYPE_TRIGSNAP_CK');
		end if;
	end loop;
end;
/

begin
	for i in (
		select constraint_name, constraint_type, search_condition
		from ( select 'RHN_ACTION_TYPE_UNLCK_CK' x from dual ) d, user_constraints
		where d.x = constraint_name (+)
		) loop
		if i.constraint_name is null or not (i.constraint_type = 'C' and i.search_condition = 'unlocked_only in (''Y'',''N'')') then
			if i.constraint_name is not null then
				execute immediate 'alter table RHNACTIONTYPE drop constraint RHN_ACTION_TYPE_UNLCK_CK';
			end if;
			execute immediate 'alter table RHNACTIONTYPE add constraint RHN_ACTION_TYPE_UNLCK_CK check (unlocked_only in (''Y'',''N'')) novalidate';
			dbms_output.put_line('Recreating RHN_ACTION_TYPE_UNLCK_CK');
		end if;
	end loop;
end;
/

begin
	for i in (
		select constraint_name, constraint_type, search_condition
		from ( select 'RHN_ALLOW_TRUST_CHANNELFLG_CK' x from dual ) d, user_constraints
		where d.x = constraint_name (+)
		) loop
		if i.constraint_name is null or not (i.constraint_type = 'C' and i.search_condition = 'channel_flag in (''N'',''Y'')') then
			if i.constraint_name is not null then
				execute immediate 'alter table RHNALLOWTRUST drop constraint RHN_ALLOW_TRUST_CHANNELFLG_CK';
			end if;
			execute immediate 'alter table RHNALLOWTRUST add constraint RHN_ALLOW_TRUST_CHANNELFLG_CK check (channel_flag in (''N'',''Y'')) novalidate';
			dbms_output.put_line('Recreating RHN_ALLOW_TRUST_CHANNELFLG_CK');
		end if;
	end loop;
end;
/

begin
	for i in (
		select constraint_name, constraint_type, search_condition
		from ( select 'RHN_ALLOW_TRUST_MIGRFLG_CK' x from dual ) d, user_constraints
		where d.x = constraint_name (+)
		) loop
		if i.constraint_name is null or not (i.constraint_type = 'C' and i.search_condition = 'migration_flag in (''N'',''Y'')') then
			if i.constraint_name is not null then
				execute immediate 'alter table RHNALLOWTRUST drop constraint RHN_ALLOW_TRUST_MIGRFLG_CK';
			end if;
			execute immediate 'alter table RHNALLOWTRUST add constraint RHN_ALLOW_TRUST_MIGRFLG_CK check (migration_flag in (''N'',''Y'')) novalidate';
			dbms_output.put_line('Recreating RHN_ALLOW_TRUST_MIGRFLG_CK');
		end if;
	end loop;
end;
/

begin
	for i in (
		select constraint_name, constraint_type, search_condition
		from ( select 'RHN_CHANNEL_RU_CK' x from dual ) d, user_constraints
		where d.x = constraint_name (+)
		) loop
		if i.constraint_name is null or not (i.constraint_type = 'C' and i.search_condition = 'receiving_updates in (''Y'', ''N'')') then
			if i.constraint_name is not null then
				execute immediate 'alter table RHNCHANNEL drop constraint RHN_CHANNEL_RU_CK';
			end if;
			execute immediate 'alter table RHNCHANNEL add constraint RHN_CHANNEL_RU_CK check (receiving_updates in (''Y'', ''N'')) novalidate';
			dbms_output.put_line('Recreating RHN_CHANNEL_RU_CK');
		end if;
	end loop;
end;
/

begin
	for i in (
		select constraint_name, constraint_type, search_condition
		from ( select 'RHN_CHANNELPROD_BETA_CK' x from dual ) d, user_constraints
		where d.x = constraint_name (+)
		) loop
		if i.constraint_name is null or not (i.constraint_type = 'C' and i.search_condition = 'beta in (''Y'', ''N'')') then
			if i.constraint_name is not null then
				execute immediate 'alter table RHNCHANNELPRODUCT drop constraint RHN_CHANNELPROD_BETA_CK';
			end if;
			execute immediate 'alter table RHNCHANNELPRODUCT add constraint RHN_CHANNELPROD_BETA_CK check (beta in (''Y'', ''N'')) novalidate';
			dbms_output.put_line('Recreating RHN_CHANNELPROD_BETA_CK');
		end if;
	end loop;
end;
/

begin
	for i in (
		select constraint_name, constraint_type, search_condition
		from ( select 'RHN_CONFCONTENT_ISBIN_CK' x from dual ) d, user_constraints
		where d.x = constraint_name (+)
		) loop
		if i.constraint_name is null or not (i.constraint_type = 'C' and i.search_condition = 'is_binary in (''Y'',''N'')') then
			if i.constraint_name is not null then
				execute immediate 'alter table RHNCONFIGCONTENT drop constraint RHN_CONFCONTENT_ISBIN_CK';
			end if;
			execute immediate 'alter table RHNCONFIGCONTENT add constraint RHN_CONFCONTENT_ISBIN_CK check (is_binary in (''Y'',''N'')) novalidate';
			dbms_output.put_line('Recreating RHN_CONFCONTENT_ISBIN_CK');
		end if;
	end loop;
end;
/

begin
	for i in (
		select constraint_name, constraint_type, search_condition
		from ( select 'RHN_ERRATA_ADV_TYPE_CK' x from dual ) d, user_constraints
		where d.x = constraint_name (+)
		) loop
		if i.constraint_name is null or not (i.constraint_type = 'C' and i.search_condition = 'advisory_type in (''Bug Fix Advisory'',
				                            ''Product Enhancement Advisory'',
							    ''Security Advisory'')') then
			if i.constraint_name is not null then
				execute immediate 'alter table RHNERRATA drop constraint RHN_ERRATA_ADV_TYPE_CK';
			end if;
			execute immediate 'alter table RHNERRATA add constraint RHN_ERRATA_ADV_TYPE_CK check (advisory_type in (''Bug Fix Advisory'',
				                            ''Product Enhancement Advisory'',
							    ''Security Advisory'')) novalidate';
			dbms_output.put_line('Recreating RHN_ERRATA_ADV_TYPE_CK');
		end if;
	end loop;
end;
/

begin
	for i in (
		select constraint_name, constraint_type, search_condition
		from ( select 'RHN_ERRATA_LM_CK' x from dual ) d, user_constraints
		where d.x = constraint_name (+)
		) loop
		if i.constraint_name is null or not (i.constraint_type = 'C' and i.search_condition = 'locally_modified in (''Y'',''N'')') then
			if i.constraint_name is not null then
				execute immediate 'alter table RHNERRATA drop constraint RHN_ERRATA_LM_CK';
			end if;
			execute immediate 'alter table RHNERRATA add constraint RHN_ERRATA_LM_CK check (locally_modified in (''Y'',''N'')) novalidate';
			dbms_output.put_line('Recreating RHN_ERRATA_LM_CK');
		end if;
	end loop;
end;
/

begin
	for i in (
		select constraint_name, constraint_type, search_condition
		from ( select 'RHN_ERRATATMP_ADV_TYPE_CK' x from dual ) d, user_constraints
		where d.x = constraint_name (+)
		) loop
		if i.constraint_name is null or not (i.constraint_type = 'C' and i.search_condition = 'advisory_type in (''Bug Fix Advisory'',
				                            ''Product Enhancement Advisory'',
							    ''Security Advisory'')') then
			if i.constraint_name is not null then
				execute immediate 'alter table RHNERRATATMP drop constraint RHN_ERRATATMP_ADV_TYPE_CK';
			end if;
			execute immediate 'alter table RHNERRATATMP add constraint RHN_ERRATATMP_ADV_TYPE_CK check (advisory_type in (''Bug Fix Advisory'',
				                            ''Product Enhancement Advisory'',
							    ''Security Advisory'')) novalidate';
			dbms_output.put_line('Recreating RHN_ERRATATMP_ADV_TYPE_CK');
		end if;
	end loop;
end;
/

begin
	for i in (
		select constraint_name, constraint_type, search_condition
		from ( select 'RHN_ERRATATMP_LM_CK' x from dual ) d, user_constraints
		where d.x = constraint_name (+)
		) loop
		if i.constraint_name is null or not (i.constraint_type = 'C' and i.search_condition = 'locally_modified in (''Y'',''N'')') then
			if i.constraint_name is not null then
				execute immediate 'alter table RHNERRATATMP drop constraint RHN_ERRATATMP_LM_CK';
			end if;
			execute immediate 'alter table RHNERRATATMP add constraint RHN_ERRATATMP_LM_CK check (locally_modified in (''Y'',''N'')) novalidate';
			dbms_output.put_line('Recreating RHN_ERRATATMP_LM_CK');
		end if;
	end loop;
end;
/

begin
	for i in (
		select constraint_name, constraint_type, search_condition
		from ( select 'RHN_KSCOMMANDNAME_REQRD_CK' x from dual ) d, user_constraints
		where d.x = constraint_name (+)
		) loop
		if i.constraint_name is null or not (i.constraint_type = 'C' and i.search_condition = ' required in (''Y'', ''N'') ') then
			if i.constraint_name is not null then
				execute immediate 'alter table RHNKICKSTARTCOMMANDNAME drop constraint RHN_KSCOMMANDNAME_REQRD_CK';
			end if;
			execute immediate 'alter table RHNKICKSTARTCOMMANDNAME add constraint RHN_KSCOMMANDNAME_REQRD_CK check ( required in (''Y'', ''N'') ) novalidate';
			dbms_output.put_line('Recreating RHN_KSCOMMANDNAME_REQRD_CK');
		end if;
	end loop;
end;
/

begin
	for i in (
		select constraint_name, constraint_type, search_condition
		from ( select 'RHN_KSCOMMANDNAME_USES_ARGS_CK' x from dual ) d, user_constraints
		where d.x = constraint_name (+)
		) loop
		if i.constraint_name is null or not (i.constraint_type = 'C' and i.search_condition = 'uses_arguments in (''Y'',''N'')') then
			if i.constraint_name is not null then
				execute immediate 'alter table RHNKICKSTARTCOMMANDNAME drop constraint RHN_KSCOMMANDNAME_USES_ARGS_CK';
			end if;
			execute immediate 'alter table RHNKICKSTARTCOMMANDNAME add constraint RHN_KSCOMMANDNAME_USES_ARGS_CK check (uses_arguments in (''Y'',''N'')) novalidate';
			dbms_output.put_line('Recreating RHN_KSCOMMANDNAME_USES_ARGS_CK');
		end if;
	end loop;
end;
/

begin
	for i in (
		select constraint_name, constraint_type, search_condition
		from ( select 'RHN_KSD_CMF_CK' x from dual ) d, user_constraints
		where d.x = constraint_name (+)
		) loop
		if i.constraint_name is null or not (i.constraint_type = 'C' and i.search_condition = 'cfg_management_flag in (''Y'',''N'')') then
			if i.constraint_name is not null then
				execute immediate 'alter table RHNKICKSTARTDEFAULTS drop constraint RHN_KSD_CMF_CK';
			end if;
			execute immediate 'alter table RHNKICKSTARTDEFAULTS add constraint RHN_KSD_CMF_CK check (cfg_management_flag in (''Y'',''N'')) novalidate';
			dbms_output.put_line('Recreating RHN_KSD_CMF_CK');
		end if;
	end loop;
end;
/

begin
	for i in (
		select constraint_name, constraint_type, search_condition
		from ( select 'RHN_KSD_RMF_CK' x from dual ) d, user_constraints
		where d.x = constraint_name (+)
		) loop
		if i.constraint_name is null or not (i.constraint_type = 'C' and i.search_condition = 'remote_command_flag in (''Y'',''N'')') then
			if i.constraint_name is not null then
				execute immediate 'alter table RHNKICKSTARTDEFAULTS drop constraint RHN_KSD_RMF_CK';
			end if;
			execute immediate 'alter table RHNKICKSTARTDEFAULTS add constraint RHN_KSD_RMF_CK check (remote_command_flag in (''Y'',''N'')) novalidate';
			dbms_output.put_line('Recreating RHN_KSD_RMF_CK');
		end if;
	end loop;
end;
/

begin
	for i in (
		select constraint_name, constraint_type, search_condition
		from ( select 'RHN_KSSCRIPT_CHROOT_CK' x from dual ) d, user_constraints
		where d.x = constraint_name (+)
		) loop
		if i.constraint_name is null or not (i.constraint_type = 'C' and i.search_condition = 'chroot in (''Y'',''N'')') then
			if i.constraint_name is not null then
				execute immediate 'alter table RHNKICKSTARTSCRIPT drop constraint RHN_KSSCRIPT_CHROOT_CK';
			end if;
			execute immediate 'alter table RHNKICKSTARTSCRIPT add constraint RHN_KSSCRIPT_CHROOT_CK check (chroot in (''Y'',''N'')) novalidate';
			dbms_output.put_line('Recreating RHN_KSSCRIPT_CHROOT_CK');
		end if;
	end loop;
end;
/

begin
	for i in (
		select constraint_name, constraint_type, search_condition
		from ( select 'RHN_KSSCRIPT_ST_CK' x from dual ) d, user_constraints
		where d.x = constraint_name (+)
		) loop
		if i.constraint_name is null or not (i.constraint_type = 'C' and i.search_condition = 'script_type in (''pre'',''post'')') then
			if i.constraint_name is not null then
				execute immediate 'alter table RHNKICKSTARTSCRIPT drop constraint RHN_KSSCRIPT_ST_CK';
			end if;
			execute immediate 'alter table RHNKICKSTARTSCRIPT add constraint RHN_KSSCRIPT_ST_CK check (script_type in (''pre'',''post'')) novalidate';
			dbms_output.put_line('Recreating RHN_KSSCRIPT_ST_CK');
		end if;
	end loop;
end;
/

begin
	for i in (
		select constraint_name, constraint_type, search_condition
		from ( select 'RHN_KS_ACTIVE_CK' x from dual ) d, user_constraints
		where d.x = constraint_name (+)
		) loop
		if i.constraint_name is null or not (i.constraint_type = 'C' and i.search_condition = 'active in (''Y'',''N'')') then
			if i.constraint_name is not null then
				execute immediate 'alter table RHNKSDATA drop constraint RHN_KS_ACTIVE_CK';
			end if;
			execute immediate 'alter table RHNKSDATA add constraint RHN_KS_ACTIVE_CK check (active in (''Y'',''N'')) novalidate';
			dbms_output.put_line('Recreating RHN_KS_ACTIVE_CK');
		end if;
	end loop;
end;
/

begin
	for i in (
		select constraint_name, constraint_type, search_condition
		from ( select 'RHN_KS_DEFAULT_CK' x from dual ) d, user_constraints
		where d.x = constraint_name (+)
		) loop
		if i.constraint_name is null or not (i.constraint_type = 'C' and i.search_condition = 'is_org_default in (''Y'',''N'')') then
			if i.constraint_name is not null then
				execute immediate 'alter table RHNKSDATA drop constraint RHN_KS_DEFAULT_CK';
			end if;
			execute immediate 'alter table RHNKSDATA add constraint RHN_KS_DEFAULT_CK check (is_org_default in (''Y'',''N'')) novalidate';
			dbms_output.put_line('Recreating RHN_KS_DEFAULT_CK');
		end if;
	end loop;
end;
/

begin
	for i in (
		select constraint_name, constraint_type, search_condition
		from ( select 'RHN_KS_CFG_SAVE_CK' x from dual ) d, user_constraints
		where d.x = constraint_name (+)
		) loop
		if i.constraint_name is null or not (i.constraint_type = 'C' and i.search_condition = 'kscfg in (''Y'',''N'')') then
			if i.constraint_name is not null then
				execute immediate 'alter table RHNKSDATA drop constraint RHN_KS_CFG_SAVE_CK';
			end if;
			execute immediate 'alter table RHNKSDATA add constraint RHN_KS_CFG_SAVE_CK check (kscfg in (''Y'',''N'')) novalidate';
			dbms_output.put_line('Recreating RHN_KS_CFG_SAVE_CK');
		end if;
	end loop;
end;
/

begin
	for i in (
		select constraint_name, constraint_type, search_condition
		from ( select 'RHN_KS_NONCHROOT_POST_CK' x from dual ) d, user_constraints
		where d.x = constraint_name (+)
		) loop
		if i.constraint_name is null or not (i.constraint_type = 'C' and i.search_condition = 'nonchrootpost in (''Y'',''N'')') then
			if i.constraint_name is not null then
				execute immediate 'alter table RHNKSDATA drop constraint RHN_KS_NONCHROOT_POST_CK';
			end if;
			execute immediate 'alter table RHNKSDATA add constraint RHN_KS_NONCHROOT_POST_CK check (nonchrootpost in (''Y'',''N'')) novalidate';
			dbms_output.put_line('Recreating RHN_KS_NONCHROOT_POST_CK');
		end if;
	end loop;
end;
/

begin
	for i in (
		select constraint_name, constraint_type, search_condition
		from ( select 'RHN_KS_POST_LOG_CK' x from dual ) d, user_constraints
		where d.x = constraint_name (+)
		) loop
		if i.constraint_name is null or not (i.constraint_type = 'C' and i.search_condition = 'postLog in (''Y'',''N'')') then
			if i.constraint_name is not null then
				execute immediate 'alter table RHNKSDATA drop constraint RHN_KS_POST_LOG_CK';
			end if;
			execute immediate 'alter table RHNKSDATA add constraint RHN_KS_POST_LOG_CK check (postLog in (''Y'',''N'')) novalidate';
			dbms_output.put_line('Recreating RHN_KS_POST_LOG_CK');
		end if;
	end loop;
end;
/

begin
	for i in (
		select constraint_name, constraint_type, search_condition
		from ( select 'RHN_KS_PRE_LOG_CK' x from dual ) d, user_constraints
		where d.x = constraint_name (+)
		) loop
		if i.constraint_name is null or not (i.constraint_type = 'C' and i.search_condition = 'preLog in (''Y'',''N'')') then
			if i.constraint_name is not null then
				execute immediate 'alter table RHNKSDATA drop constraint RHN_KS_PRE_LOG_CK';
			end if;
			execute immediate 'alter table RHNKSDATA add constraint RHN_KS_PRE_LOG_CK check (preLog in (''Y'',''N'')) novalidate';
			dbms_output.put_line('Recreating RHN_KS_PRE_LOG_CK');
		end if;
	end loop;
end;
/

begin
	for i in (
		select constraint_name, constraint_type, search_condition
		from ( select 'RHN_KS_VERBOSE_UP2DATE_CK' x from dual ) d, user_constraints
		where d.x = constraint_name (+)
		) loop
		if i.constraint_name is null or not (i.constraint_type = 'C' and i.search_condition = 'verboseup2date in (''Y'',''N'')') then
			if i.constraint_name is not null then
				execute immediate 'alter table RHNKSDATA drop constraint RHN_KS_VERBOSE_UP2DATE_CK';
			end if;
			execute immediate 'alter table RHNKSDATA add constraint RHN_KS_VERBOSE_UP2DATE_CK check (verboseup2date in (''Y'',''N'')) novalidate';
			dbms_output.put_line('Recreating RHN_KS_VERBOSE_UP2DATE_CK');
		end if;
	end loop;
end;
/

begin
	for i in (
		select constraint_name, constraint_type, search_condition
		from ( select 'RHN_REG_TOKEN_DEPLOYCONFS_CK' x from dual ) d, user_constraints
		where d.x = constraint_name (+)
		) loop
		if i.constraint_name is null or not (i.constraint_type = 'C' and i.search_condition = 'deploy_configs in (''Y'',''N'')') then
			if i.constraint_name is not null then
				execute immediate 'alter table RHNREGTOKEN drop constraint RHN_REG_TOKEN_DEPLOYCONFS_CK';
			end if;
			execute immediate 'alter table RHNREGTOKEN add constraint RHN_REG_TOKEN_DEPLOYCONFS_CK check (deploy_configs in (''Y'',''N'')) novalidate';
			dbms_output.put_line('Recreating RHN_REG_TOKEN_DEPLOYCONFS_CK');
		end if;
	end loop;
end;
/

begin
	for i in (
		select constraint_name, constraint_type, search_condition
		from ( select 'RHN_SAVEDSEARCH_SSET_CK' x from dual ) d, user_constraints
		where d.x = constraint_name (+)
		) loop
		if i.constraint_name is null or not (i.constraint_type = 'C' and i.search_condition = ' search_set in (''all'',''system_list'')') then
			if i.constraint_name is not null then
				execute immediate 'alter table RHNSAVEDSEARCH drop constraint RHN_SAVEDSEARCH_SSET_CK';
			end if;
			execute immediate 'alter table RHNSAVEDSEARCH add constraint RHN_SAVEDSEARCH_SSET_CK check ( search_set in (''all'',''system_list'')) novalidate';
			dbms_output.put_line('Recreating RHN_SAVEDSEARCH_SSET_CK');
		end if;
	end loop;
end;
/

begin
	for i in (
		select constraint_name, constraint_type, search_condition
		from ( select 'RHN_SAVEDSEARCH_INVERT_CK' x from dual ) d, user_constraints
		where d.x = constraint_name (+)
		) loop
		if i.constraint_name is null or not (i.constraint_type = 'C' and i.search_condition = 'invert in (''Y'',''N'')') then
			if i.constraint_name is not null then
				execute immediate 'alter table RHNSAVEDSEARCH drop constraint RHN_SAVEDSEARCH_INVERT_CK';
			end if;
			execute immediate 'alter table RHNSAVEDSEARCH add constraint RHN_SAVEDSEARCH_INVERT_CK check (invert in (''Y'',''N'')) novalidate';
			dbms_output.put_line('Recreating RHN_SAVEDSEARCH_INVERT_CK');
		end if;
	end loop;
end;
/

begin
	for i in (
		select constraint_name, constraint_type, search_condition
		from ( select 'RHN_SERVER_DELIVER_CK' x from dual ) d, user_constraints
		where d.x = constraint_name (+)
		) loop
		if i.constraint_name is null or not (i.constraint_type = 'C' and i.search_condition = 'auto_deliver in (''Y'', ''N'')') then
			if i.constraint_name is not null then
				execute immediate 'alter table RHNSERVER drop constraint RHN_SERVER_DELIVER_CK';
			end if;
			execute immediate 'alter table RHNSERVER add constraint RHN_SERVER_DELIVER_CK check (auto_deliver in (''Y'', ''N'')) novalidate';
			dbms_output.put_line('Recreating RHN_SERVER_DELIVER_CK');
		end if;
	end loop;
end;
/

begin
	for i in (
		select constraint_name, constraint_type, search_condition
		from ( select 'RHN_SERVER_UPDATE_CK' x from dual ) d, user_constraints
		where d.x = constraint_name (+)
		) loop
		if i.constraint_name is null or not (i.constraint_type = 'C' and i.search_condition = 'auto_update in (''Y'', ''N'')') then
			if i.constraint_name is not null then
				execute immediate 'alter table RHNSERVER drop constraint RHN_SERVER_UPDATE_CK';
			end if;
			execute immediate 'alter table RHNSERVER add constraint RHN_SERVER_UPDATE_CK check (auto_update in (''Y'', ''N'')) novalidate';
			dbms_output.put_line('Recreating RHN_SERVER_UPDATE_CK');
		end if;
	end loop;
end;
/

begin
	for i in (
		select constraint_name, constraint_type, search_condition
		from ( select 'RHN_SACTIONVR_ATTR_CK' x from dual ) d, user_constraints
		where d.x = constraint_name (+)
		) loop
		if i.constraint_name is null or not (i.constraint_type = 'C' and i.search_condition = 'attribute in (''c'',''d'',''g'',''l'',''r'')') then
			if i.constraint_name is not null then
				execute immediate 'alter table RHNSERVERACTIONVERIFYRESULT drop constraint RHN_SACTIONVR_ATTR_CK';
			end if;
			execute immediate 'alter table RHNSERVERACTIONVERIFYRESULT add constraint RHN_SACTIONVR_ATTR_CK check (attribute in (''c'',''d'',''g'',''l'',''r'')) novalidate';
			dbms_output.put_line('Recreating RHN_SACTIONVR_ATTR_CK');
		end if;
	end loop;
end;
/

begin
	for i in (
		select constraint_name, constraint_type, search_condition
		from ( select 'RHN_SACTIONVR_DEVNUM_CK' x from dual ) d, user_constraints
		where d.x = constraint_name (+)
		) loop
		if i.constraint_name is null or not (i.constraint_type = 'C' and i.search_condition = 'devnum_differs in (''Y'',''N'',''?'')') then
			if i.constraint_name is not null then
				execute immediate 'alter table RHNSERVERACTIONVERIFYRESULT drop constraint RHN_SACTIONVR_DEVNUM_CK';
			end if;
			execute immediate 'alter table RHNSERVERACTIONVERIFYRESULT add constraint RHN_SACTIONVR_DEVNUM_CK check (devnum_differs in (''Y'',''N'',''?'')) novalidate';
			dbms_output.put_line('Recreating RHN_SACTIONVR_DEVNUM_CK');
		end if;
	end loop;
end;
/

begin
	for i in (
		select constraint_name, constraint_type, search_condition
		from ( select 'RHN_SACTIONVR_GID_CK' x from dual ) d, user_constraints
		where d.x = constraint_name (+)
		) loop
		if i.constraint_name is null or not (i.constraint_type = 'C' and i.search_condition = 'gid_differs in (''Y'',''N'',''?'')') then
			if i.constraint_name is not null then
				execute immediate 'alter table RHNSERVERACTIONVERIFYRESULT drop constraint RHN_SACTIONVR_GID_CK';
			end if;
			execute immediate 'alter table RHNSERVERACTIONVERIFYRESULT add constraint RHN_SACTIONVR_GID_CK check (gid_differs in (''Y'',''N'',''?'')) novalidate';
			dbms_output.put_line('Recreating RHN_SACTIONVR_GID_CK');
		end if;
	end loop;
end;
/

begin
	for i in (
		select constraint_name, constraint_type, search_condition
		from ( select 'RHN_SACTIONVR_MODE_CK' x from dual ) d, user_constraints
		where d.x = constraint_name (+)
		) loop
		if i.constraint_name is null or not (i.constraint_type = 'C' and i.search_condition = 'mode_differs in (''Y'',''N'',''?'')') then
			if i.constraint_name is not null then
				execute immediate 'alter table RHNSERVERACTIONVERIFYRESULT drop constraint RHN_SACTIONVR_MODE_CK';
			end if;
			execute immediate 'alter table RHNSERVERACTIONVERIFYRESULT add constraint RHN_SACTIONVR_MODE_CK check (mode_differs in (''Y'',''N'',''?'')) novalidate';
			dbms_output.put_line('Recreating RHN_SACTIONVR_MODE_CK');
		end if;
	end loop;
end;
/

begin
	for i in (
		select constraint_name, constraint_type, search_condition
		from ( select 'RHN_SACTIONVR_MTIME_CK' x from dual ) d, user_constraints
		where d.x = constraint_name (+)
		) loop
		if i.constraint_name is null or not (i.constraint_type = 'C' and i.search_condition = 'mtime_differs in (''Y'',''N'',''?'')') then
			if i.constraint_name is not null then
				execute immediate 'alter table RHNSERVERACTIONVERIFYRESULT drop constraint RHN_SACTIONVR_MTIME_CK';
			end if;
			execute immediate 'alter table RHNSERVERACTIONVERIFYRESULT add constraint RHN_SACTIONVR_MTIME_CK check (mtime_differs in (''Y'',''N'',''?'')) novalidate';
			dbms_output.put_line('Recreating RHN_SACTIONVR_MTIME_CK');
		end if;
	end loop;
end;
/

begin
	for i in (
		select constraint_name, constraint_type, search_condition
		from ( select 'RHN_SACTIONVR_READLINK_CK' x from dual ) d, user_constraints
		where d.x = constraint_name (+)
		) loop
		if i.constraint_name is null or not (i.constraint_type = 'C' and i.search_condition = 'readlink_differs in (''Y'',''N'',''?'')') then
			if i.constraint_name is not null then
				execute immediate 'alter table RHNSERVERACTIONVERIFYRESULT drop constraint RHN_SACTIONVR_READLINK_CK';
			end if;
			execute immediate 'alter table RHNSERVERACTIONVERIFYRESULT add constraint RHN_SACTIONVR_READLINK_CK check (readlink_differs in (''Y'',''N'',''?'')) novalidate';
			dbms_output.put_line('Recreating RHN_SACTIONVR_READLINK_CK');
		end if;
	end loop;
end;
/

begin
	for i in (
		select constraint_name, constraint_type, search_condition
		from ( select 'RHN_SACTIONVR_SIZE_CK' x from dual ) d, user_constraints
		where d.x = constraint_name (+)
		) loop
		if i.constraint_name is null or not (i.constraint_type = 'C' and i.search_condition = 'size_differs in (''Y'',''N'',''?'')') then
			if i.constraint_name is not null then
				execute immediate 'alter table RHNSERVERACTIONVERIFYRESULT drop constraint RHN_SACTIONVR_SIZE_CK';
			end if;
			execute immediate 'alter table RHNSERVERACTIONVERIFYRESULT add constraint RHN_SACTIONVR_SIZE_CK check (size_differs in (''Y'',''N'',''?'')) novalidate';
			dbms_output.put_line('Recreating RHN_SACTIONVR_SIZE_CK');
		end if;
	end loop;
end;
/

begin
	for i in (
		select constraint_name, constraint_type, search_condition
		from ( select 'RHN_SACTIONVR_UID_CK' x from dual ) d, user_constraints
		where d.x = constraint_name (+)
		) loop
		if i.constraint_name is null or not (i.constraint_type = 'C' and i.search_condition = 'uid_differs in (''Y'',''N'',''?'')') then
			if i.constraint_name is not null then
				execute immediate 'alter table RHNSERVERACTIONVERIFYRESULT drop constraint RHN_SACTIONVR_UID_CK';
			end if;
			execute immediate 'alter table RHNSERVERACTIONVERIFYRESULT add constraint RHN_SACTIONVR_UID_CK check (uid_differs in (''Y'',''N'',''?'')) novalidate';
			dbms_output.put_line('Recreating RHN_SACTIONVR_UID_CK');
		end if;
	end loop;
end;
/

begin
	for i in (
		select constraint_name, constraint_type, search_condition
		from ( select 'RHN_SERVERGROUPTYPE_ISBASE_CK' x from dual ) d, user_constraints
		where d.x = constraint_name (+)
		) loop
		if i.constraint_name is null or not (i.constraint_type = 'C' and i.search_condition = 'is_base in (''Y'',''N'')') then
			if i.constraint_name is not null then
				execute immediate 'alter table RHNSERVERGROUPTYPE drop constraint RHN_SERVERGROUPTYPE_ISBASE_CK';
			end if;
			execute immediate 'alter table RHNSERVERGROUPTYPE add constraint RHN_SERVERGROUPTYPE_ISBASE_CK check (is_base in (''Y'',''N'')) novalidate';
			dbms_output.put_line('Recreating RHN_SERVERGROUPTYPE_ISBASE_CK');
		end if;
	end loop;
end;
/

begin
	for i in (
		select constraint_name, constraint_type, search_condition
		from ( select 'RHN_SERVERGROUPTYPE_PERM_CK' x from dual ) d, user_constraints
		where d.x = constraint_name (+)
		) loop
		if i.constraint_name is null or not (i.constraint_type = 'C' and i.search_condition = 'permanent in (''Y'',''N'')') then
			if i.constraint_name is not null then
				execute immediate 'alter table RHNSERVERGROUPTYPE drop constraint RHN_SERVERGROUPTYPE_PERM_CK';
			end if;
			execute immediate 'alter table RHNSERVERGROUPTYPE add constraint RHN_SERVERGROUPTYPE_PERM_CK check (permanent in (''Y'',''N'')) novalidate';
			dbms_output.put_line('Recreating RHN_SERVERGROUPTYPE_PERM_CK');
		end if;
	end loop;
end;
/

begin
	for i in (
		select constraint_name, constraint_type, search_condition
		from ( select 'RHN_SOLARIS_PKG_IO_CK' x from dual ) d, user_constraints
		where d.x = constraint_name (+)
		) loop
		if i.constraint_name is null or not (i.constraint_type = 'C' and i.search_condition = ' intonly in (''Y'',''N'')') then
			if i.constraint_name is not null then
				execute immediate 'alter table RHNSOLARISPACKAGE drop constraint RHN_SOLARIS_PKG_IO_CK';
			end if;
			execute immediate 'alter table RHNSOLARISPACKAGE add constraint RHN_SOLARIS_PKG_IO_CK check ( intonly in (''Y'',''N'')) novalidate';
			dbms_output.put_line('Recreating RHN_SOLARIS_PKG_IO_CK');
		end if;
	end loop;
end;
/

begin
	for i in (
		select constraint_name, constraint_type, search_condition
		from ( select 'RHN_TU_ENABLED_CK' x from dual ) d, user_constraints
		where d.x = constraint_name (+)
		) loop
		if i.constraint_name is null or not (i.constraint_type = 'C' and i.search_condition = 'enabled in (''Y'',''N'')') then
			if i.constraint_name is not null then
				execute immediate 'alter table RHNTINYURL drop constraint RHN_TU_ENABLED_CK';
			end if;
			execute immediate 'alter table RHNTINYURL add constraint RHN_TU_ENABLED_CK check (enabled in (''Y'',''N'')) novalidate';
			dbms_output.put_line('Recreating RHN_TU_ENABLED_CK');
		end if;
	end loop;
end;
/

begin
	for i in (
		select constraint_name, constraint_type, search_condition
		from ( select 'RHN_USER_INFO_ES_CK' x from dual ) d, user_constraints
		where d.x = constraint_name (+)
		) loop
		if i.constraint_name is null or not (i.constraint_type = 'C' and i.search_condition = 'agreed_to_es_terms is null or agreed_to_es_terms in (''Y'',''N'')') then
			if i.constraint_name is not null then
				execute immediate 'alter table RHNUSERINFO drop constraint RHN_USER_INFO_ES_CK';
			end if;
			execute immediate 'alter table RHNUSERINFO add constraint RHN_USER_INFO_ES_CK check (agreed_to_es_terms is null or agreed_to_es_terms in (''Y'',''N'')) novalidate';
			dbms_output.put_line('Recreating RHN_USER_INFO_ES_CK');
		end if;
	end loop;
end;
/

begin
	for i in (
		select constraint_name, constraint_type, search_condition
		from ( select 'RHN_USER_INFO_AGREED_CK' x from dual ) d, user_constraints
		where d.x = constraint_name (+)
		) loop
		if i.constraint_name is null or not (i.constraint_type = 'C' and i.search_condition = 'agreed_to_terms in (''Y'',''N'')') then
			if i.constraint_name is not null then
				execute immediate 'alter table RHNUSERINFO drop constraint RHN_USER_INFO_AGREED_CK';
			end if;
			execute immediate 'alter table RHNUSERINFO add constraint RHN_USER_INFO_AGREED_CK check (agreed_to_terms in (''Y'',''N'')) novalidate';
			dbms_output.put_line('Recreating RHN_USER_INFO_AGREED_CK');
		end if;
	end loop;
end;
/

begin
	for i in (
		select constraint_name, constraint_type, search_condition
		from ( select 'RHN_USER_INFO_WS_CK' x from dual ) d, user_constraints
		where d.x = constraint_name (+)
		) loop
		if i.constraint_name is null or not (i.constraint_type = 'C' and i.search_condition = 'agreed_to_ws_terms is null or agreed_to_ws_terms in (''Y'',''N'')') then
			if i.constraint_name is not null then
				execute immediate 'alter table RHNUSERINFO drop constraint RHN_USER_INFO_WS_CK';
			end if;
			execute immediate 'alter table RHNUSERINFO add constraint RHN_USER_INFO_WS_CK check (agreed_to_ws_terms is null or agreed_to_ws_terms in (''Y'',''N'')) novalidate';
			dbms_output.put_line('Recreating RHN_USER_INFO_WS_CK');
		end if;
	end loop;
end;
/

begin
	for i in (
		select constraint_name, constraint_type, search_condition
		from ( select 'RHN_USER_INFO_SEA_CK' x from dual ) d, user_constraints
		where d.x = constraint_name (+)
		) loop
		if i.constraint_name is null or not (i.constraint_type = 'C' and i.search_condition = 'show_applied_errata in (''Y'',''N'')') then
			if i.constraint_name is not null then
				execute immediate 'alter table RHNUSERINFO drop constraint RHN_USER_INFO_SEA_CK';
			end if;
			execute immediate 'alter table RHNUSERINFO add constraint RHN_USER_INFO_SEA_CK check (show_applied_errata in (''Y'',''N'')) novalidate';
			dbms_output.put_line('Recreating RHN_USER_INFO_SEA_CK');
		end if;
	end loop;
end;
/

begin
	for i in (
		select constraint_name, constraint_type, search_condition
		from ( select 'RHN_USER_INFO_SSGL_CK' x from dual ) d, user_constraints
		where d.x = constraint_name (+)
		) loop
		if i.constraint_name is null or not (i.constraint_type = 'C' and i.search_condition = 'show_system_group_list in (''Y'',''N'')') then
			if i.constraint_name is not null then
				execute immediate 'alter table RHNUSERINFO drop constraint RHN_USER_INFO_SSGL_CK';
			end if;
			execute immediate 'alter table RHNUSERINFO add constraint RHN_USER_INFO_SSGL_CK check (show_system_group_list in (''Y'',''N'')) novalidate';
			dbms_output.put_line('Recreating RHN_USER_INFO_SSGL_CK');
		end if;
	end loop;
end;
/

begin
	for i in (
		select constraint_name, constraint_type, search_condition
		from ( select 'RHN_USER_INFO_PAM_CK' x from dual ) d, user_constraints
		where d.x = constraint_name (+)
		) loop
		if i.constraint_name is null or not (i.constraint_type = 'C' and i.search_condition = 'use_pam_authentication in (''Y'',''N'')') then
			if i.constraint_name is not null then
				execute immediate 'alter table RHNUSERINFO drop constraint RHN_USER_INFO_PAM_CK';
			end if;
			execute immediate 'alter table RHNUSERINFO add constraint RHN_USER_INFO_PAM_CK check (use_pam_authentication in (''Y'',''N'')) novalidate';
			dbms_output.put_line('Recreating RHN_USER_INFO_PAM_CK');
		end if;
	end loop;
end;
/

begin
	for i in (
		select constraint_name, constraint_type, search_condition
		from ( select 'CHKPB_PROBE_TYPE_CK' x from dual ) d, user_constraints
		where d.x = constraint_name (+)
		) loop
		if i.constraint_name is null or not (i.constraint_type = 'C' and i.search_condition = 'probe_type=''check''') then
			if i.constraint_name is not null then
				execute immediate 'alter table RHN_CHECK_PROBE drop constraint CHKPB_PROBE_TYPE_CK';
			end if;
			execute immediate 'alter table RHN_CHECK_PROBE add constraint CHKPB_PROBE_TYPE_CK check (probe_type=''check'') novalidate';
			dbms_output.put_line('Recreating CHKPB_PROBE_TYPE_CK');
		end if;
	end loop;
end;
/

begin
	for i in (
		select constraint_name, constraint_type, search_condition
		from ( select 'RHN_CKSPB_PROBE_TYPE_CK' x from dual ) d, user_constraints
		where d.x = constraint_name (+)
		) loop
		if i.constraint_name is null or not (i.constraint_type = 'C' and i.search_condition = ' probe_type = ''suite'' ') then
			if i.constraint_name is not null then
				execute immediate 'alter table RHN_CHECK_SUITE_PROBE drop constraint RHN_CKSPB_PROBE_TYPE_CK';
			end if;
			execute immediate 'alter table RHN_CHECK_SUITE_PROBE add constraint RHN_CKSPB_PROBE_TYPE_CK check ( probe_type = ''suite'' ) novalidate';
			dbms_output.put_line('Recreating RHN_CKSPB_PROBE_TYPE_CK');
		end if;
	end loop;
end;
/

begin
	for i in (
		select constraint_name, constraint_type, search_condition
		from ( select 'RHN_COPTR_PARAM_TYPE_CK' x from dual ) d, user_constraints
		where d.x = constraint_name (+)
		) loop
		if i.constraint_name is null or not (i.constraint_type = 'C' and i.search_condition = 'param_type=''threshold''') then
			if i.constraint_name is not null then
				execute immediate 'alter table RHN_COMMAND_PARAM_THRESHOLD drop constraint RHN_COPTR_PARAM_TYPE_CK';
			end if;
			execute immediate 'alter table RHN_COMMAND_PARAM_THRESHOLD add constraint RHN_COPTR_PARAM_TYPE_CK check (param_type=''threshold'') novalidate';
			dbms_output.put_line('Recreating RHN_COPTR_PARAM_TYPE_CK');
		end if;
	end loop;
end;
/

begin
	for i in (
		select constraint_name, constraint_type, search_condition
		from ( select 'CMDTG_TARGET_TYPE_CK' x from dual ) d, user_constraints
		where d.x = constraint_name (+)
		) loop
		if i.constraint_name is null or not (i.constraint_type = 'C' and i.search_condition = 'target_type in (''cluster'',''node'')') then
			if i.constraint_name is not null then
				execute immediate 'alter table RHN_COMMAND_TARGET drop constraint CMDTG_TARGET_TYPE_CK';
			end if;
			execute immediate 'alter table RHN_COMMAND_TARGET add constraint CMDTG_TARGET_TYPE_CK check (target_type in (''cluster'',''node'')) novalidate';
			dbms_output.put_line('Recreating CMDTG_TARGET_TYPE_CK');
		end if;
	end loop;
end;
/

begin
	for i in (
		select constraint_name, constraint_type, search_condition
		from ( select 'RHN_CNTGP_ACK_WAIT_CK' x from dual ) d, user_constraints
		where d.x = constraint_name (+)
		) loop
		if i.constraint_name is null or not (i.constraint_type = 'C' and i.search_condition = ' ack_wait < 20160 ') then
			if i.constraint_name is not null then
				execute immediate 'alter table RHN_CONTACT_GROUPS drop constraint RHN_CNTGP_ACK_WAIT_CK';
			end if;
			execute immediate 'alter table RHN_CONTACT_GROUPS add constraint RHN_CNTGP_ACK_WAIT_CK check ( ack_wait < 20160 ) novalidate';
			dbms_output.put_line('Recreating RHN_CNTGP_ACK_WAIT_CK');
		end if;
	end loop;
end;
/

begin
	for i in (
		select constraint_name, constraint_type, search_condition
		from ( select 'RHN_HSTPB_PROBE_TYPE_CK' x from dual ) d, user_constraints
		where d.x = constraint_name (+)
		) loop
		if i.constraint_name is null or not (i.constraint_type = 'C' and i.search_condition = ' probe_type=''host'' ') then
			if i.constraint_name is not null then
				execute immediate 'alter table RHN_HOST_PROBE drop constraint RHN_HSTPB_PROBE_TYPE_CK';
			end if;
			execute immediate 'alter table RHN_HOST_PROBE add constraint RHN_HSTPB_PROBE_TYPE_CK check ( probe_type=''host'' ) novalidate';
			dbms_output.put_line('Recreating RHN_HSTPB_PROBE_TYPE_CK');
		end if;
	end loop;
end;
/

begin
	for i in (
		select constraint_name, constraint_type, search_condition
		from ( select 'RHN_RDRCT_REC_DTYPE_VALID' x from dual ) d, user_constraints
		where d.x = constraint_name (+)
		) loop
		if i.constraint_name is null or not (i.constraint_type = 'C' and i.search_condition = ' recurring_dur_type in (12,11,5,3,1) ') then
			if i.constraint_name is not null then
				execute immediate 'alter table RHN_REDIRECTS drop constraint RHN_RDRCT_REC_DTYPE_VALID';
			end if;
			execute immediate 'alter table RHN_REDIRECTS add constraint RHN_RDRCT_REC_DTYPE_VALID check ( recurring_dur_type in (12,11,5,3,1) ) novalidate';
			dbms_output.put_line('Recreating RHN_RDRCT_REC_DTYPE_VALID');
		end if;
	end loop;
end;
/

begin
	for i in (
		select constraint_name, constraint_type, search_condition
		from ( select 'RHN_RDRCT_RECUR_VALID' x from dual ) d, user_constraints
		where d.x = constraint_name (+)
		) loop
		if i.constraint_name is null or not (i.constraint_type = 'C' and i.search_condition = 'recurring in (0, 1)') then
			if i.constraint_name is not null then
				execute immediate 'alter table RHN_REDIRECTS drop constraint RHN_RDRCT_RECUR_VALID';
			end if;
			execute immediate 'alter table RHN_REDIRECTS add constraint RHN_RDRCT_RECUR_VALID check (recurring in (0, 1)) novalidate';
			dbms_output.put_line('Recreating RHN_RDRCT_RECUR_VALID');
		end if;
	end loop;
end;
/

begin
	for i in (
		select constraint_name, constraint_type, search_condition
		from ( select 'RHN_RDRCT_RECUR_FREQ_VALID' x from dual ) d, user_constraints
		where d.x = constraint_name (+)
		) loop
		if i.constraint_name is null or not (i.constraint_type = 'C' and i.search_condition = 'recurring_frequency in (2,3,6)') then
			if i.constraint_name is not null then
				execute immediate 'alter table RHN_REDIRECTS drop constraint RHN_RDRCT_RECUR_FREQ_VALID';
			end if;
			execute immediate 'alter table RHN_REDIRECTS add constraint RHN_RDRCT_RECUR_FREQ_VALID check (recurring_frequency in (2,3,6)) novalidate';
			dbms_output.put_line('Recreating RHN_RDRCT_RECUR_FREQ_VALID');
		end if;
	end loop;
end;
/

begin
	for i in (
		select constraint_name, constraint_type, search_condition
		from ( select 'RHN_RDRCT_START_LTE_EXPIR' x from dual ) d, user_constraints
		where d.x = constraint_name (+)
		) loop
		if i.constraint_name is null or not (i.constraint_type = 'C' and i.search_condition = 'start_date <= expiration ') then
			if i.constraint_name is not null then
				execute immediate 'alter table RHN_REDIRECTS drop constraint RHN_RDRCT_START_LTE_EXPIR';
			end if;
			execute immediate 'alter table RHN_REDIRECTS add constraint RHN_RDRCT_START_LTE_EXPIR check (start_date <= expiration ) novalidate';
			dbms_output.put_line('Recreating RHN_RDRCT_START_LTE_EXPIR');
		end if;
	end loop;
end;
/

begin
	for i in (
		select constraint_name, constraint_type, search_condition
		from ( select 'RHN_SATCL_DEPLOYED_CK' x from dual ) d, user_constraints
		where d.x = constraint_name (+)
		) loop
		if i.constraint_name is null or not (i.constraint_type = 'C' and i.search_condition = 'deployed in (''0'',''1'')') then
			if i.constraint_name is not null then
				execute immediate 'alter table RHN_SAT_CLUSTER drop constraint RHN_SATCL_DEPLOYED_CK';
			end if;
			execute immediate 'alter table RHN_SAT_CLUSTER add constraint RHN_SATCL_DEPLOYED_CK check (deployed in (''0'',''1'')) novalidate';
			dbms_output.put_line('Recreating RHN_SATCL_DEPLOYED_CK');
		end if;
	end loop;
end;
/

begin
	for i in (
		select constraint_name, constraint_type, search_condition
		from ( select 'RHN_SATCL_TARGET_TYPE_CK' x from dual ) d, user_constraints
		where d.x = constraint_name (+)
		) loop
		if i.constraint_name is null or not (i.constraint_type = 'C' and i.search_condition = 'target_type in (''cluster'')') then
			if i.constraint_name is not null then
				execute immediate 'alter table RHN_SAT_CLUSTER drop constraint RHN_SATCL_TARGET_TYPE_CK';
			end if;
			execute immediate 'alter table RHN_SAT_CLUSTER add constraint RHN_SATCL_TARGET_TYPE_CK check (target_type in (''cluster'')) novalidate';
			dbms_output.put_line('Recreating RHN_SATCL_TARGET_TYPE_CK');
		end if;
	end loop;
end;
/

begin
	for i in (
		select constraint_name, constraint_type, search_condition
		from ( select 'RHN_SCLPB_PROBE_TYPE_CK' x from dual ) d, user_constraints
		where d.x = constraint_name (+)
		) loop
		if i.constraint_name is null or not (i.constraint_type = 'C' and i.search_condition = 'probe_type=''satcluster''') then
			if i.constraint_name is not null then
				execute immediate 'alter table RHN_SAT_CLUSTER_PROBE drop constraint RHN_SCLPB_PROBE_TYPE_CK';
			end if;
			execute immediate 'alter table RHN_SAT_CLUSTER_PROBE add constraint RHN_SCLPB_PROBE_TYPE_CK check (probe_type=''satcluster'') novalidate';
			dbms_output.put_line('Recreating RHN_SCLPB_PROBE_TYPE_CK');
		end if;
	end loop;
end;
/

begin
	for i in (
		select constraint_name, constraint_type, search_condition
		from ( select 'RHN_SATND_TARGET_TYPE_CK' x from dual ) d, user_constraints
		where d.x = constraint_name (+)
		) loop
		if i.constraint_name is null or not (i.constraint_type = 'C' and i.search_condition = 'target_type in (''node'')') then
			if i.constraint_name is not null then
				execute immediate 'alter table RHN_SAT_NODE drop constraint RHN_SATND_TARGET_TYPE_CK';
			end if;
			execute immediate 'alter table RHN_SAT_NODE add constraint RHN_SATND_TARGET_TYPE_CK check (target_type in (''node'')) novalidate';
			dbms_output.put_line('Recreating RHN_SATND_TARGET_TYPE_CK');
		end if;
	end loop;
end;
/

begin
	for i in (
		select constraint_name, constraint_type, search_condition
		from ( select 'RHN_SNDPB_PROBE_TYPE_CK' x from dual ) d, user_constraints
		where d.x = constraint_name (+)
		) loop
		if i.constraint_name is null or not (i.constraint_type = 'C' and i.search_condition = 'probe_type=''satnode''') then
			if i.constraint_name is not null then
				execute immediate 'alter table RHN_SAT_NODE_PROBE drop constraint RHN_SNDPB_PROBE_TYPE_CK';
			end if;
			execute immediate 'alter table RHN_SAT_NODE_PROBE add constraint RHN_SNDPB_PROBE_TYPE_CK check (probe_type=''satnode'') novalidate';
			dbms_output.put_line('Recreating RHN_SNDPB_PROBE_TYPE_CK');
		end if;
	end loop;
end;
/

begin
	for i in (
		select constraint_name, constraint_type, search_condition
		from ( select 'RHN_STRAT_ACK_COMP_CK' x from dual ) d, user_constraints
		where d.x = constraint_name (+)
		) loop
		if i.constraint_name is null or not (i.constraint_type = 'C' and i.search_condition = 'ack_completed in ( ''All'', ''One'',''No'' )') then
			if i.constraint_name is not null then
				execute immediate 'alter table RHN_STRATEGIES drop constraint RHN_STRAT_ACK_COMP_CK';
			end if;
			execute immediate 'alter table RHN_STRATEGIES add constraint RHN_STRAT_ACK_COMP_CK check (ack_completed in ( ''All'', ''One'',''No'' )) novalidate';
			dbms_output.put_line('Recreating RHN_STRAT_ACK_COMP_CK');
		end if;
	end loop;
end;
/

begin
	for i in (
		select constraint_name, constraint_type, search_condition
		from ( select 'RHN_STRAT_CONT_STRAT_CK' x from dual ) d, user_constraints
		where d.x = constraint_name (+)
		) loop
		if i.constraint_name is null or not (i.constraint_type = 'C' and i.search_condition = 'contact_strategy in (''Broadcast'',''Escalate'')') then
			if i.constraint_name is not null then
				execute immediate 'alter table RHN_STRATEGIES drop constraint RHN_STRAT_CONT_STRAT_CK';
			end if;
			execute immediate 'alter table RHN_STRATEGIES add constraint RHN_STRAT_CONT_STRAT_CK check (contact_strategy in (''Broadcast'',''Escalate'')) novalidate';
			dbms_output.put_line('Recreating RHN_STRAT_CONT_STRAT_CK');
		end if;
	end loop;
end;
/

begin
	for i in (
		select constraint_name, constraint_type, search_condition
		from ( select 'RHN_URLPB_MULTI_STEP_CK' x from dual ) d, user_constraints
		where d.x = constraint_name (+)
		) loop
		if i.constraint_name is null or not (i.constraint_type = 'C' and i.search_condition = 'multi_step in (''0'',''1'')') then
			if i.constraint_name is not null then
				execute immediate 'alter table RHN_URL_PROBE drop constraint RHN_URLPB_MULTI_STEP_CK';
			end if;
			execute immediate 'alter table RHN_URL_PROBE add constraint RHN_URLPB_MULTI_STEP_CK check (multi_step in (''0'',''1'')) novalidate';
			dbms_output.put_line('Recreating RHN_URLPB_MULTI_STEP_CK');
		end if;
	end loop;
end;
/

begin
	for i in (
		select constraint_name, constraint_type, search_condition
		from ( select 'RHN_URLPB_PROBE_TYPE_CK' x from dual ) d, user_constraints
		where d.x = constraint_name (+)
		) loop
		if i.constraint_name is null or not (i.constraint_type = 'C' and i.search_condition = 'probe_type=''url''') then
			if i.constraint_name is not null then
				execute immediate 'alter table RHN_URL_PROBE drop constraint RHN_URLPB_PROBE_TYPE_CK';
			end if;
			execute immediate 'alter table RHN_URL_PROBE add constraint RHN_URLPB_PROBE_TYPE_CK check (probe_type=''url'') novalidate';
			dbms_output.put_line('Recreating RHN_URLPB_PROBE_TYPE_CK');
		end if;
	end loop;
end;
/

begin
	for i in (
		select constraint_name, constraint_type, search_condition
		from ( select 'RHN_URLPB_RUN_ON_SCOUTS_CK' x from dual ) d, user_constraints
		where d.x = constraint_name (+)
		) loop
		if i.constraint_name is null or not (i.constraint_type = 'C' and i.search_condition = 'run_on_scouts in (''0'',''1'')') then
			if i.constraint_name is not null then
				execute immediate 'alter table RHN_URL_PROBE drop constraint RHN_URLPB_RUN_ON_SCOUTS_CK';
			end if;
			execute immediate 'alter table RHN_URL_PROBE add constraint RHN_URLPB_RUN_ON_SCOUTS_CK check (run_on_scouts in (''0'',''1'')) novalidate';
			dbms_output.put_line('Recreating RHN_URLPB_RUN_ON_SCOUTS_CK');
		end if;
	end loop;
end;
/

begin
	for i in (
		select constraint_name, constraint_type, search_condition
		from ( select 'RHN_URLPS_COOKIE_SEC_CK' x from dual ) d, user_constraints
		where d.x = constraint_name (+)
		) loop
		if i.constraint_name is null or not (i.constraint_type = 'C' and i.search_condition = 'cookie_secure in (''0'',''1'')') then
			if i.constraint_name is not null then
				execute immediate 'alter table RHN_URL_PROBE_STEP drop constraint RHN_URLPS_COOKIE_SEC_CK';
			end if;
			execute immediate 'alter table RHN_URL_PROBE_STEP add constraint RHN_URLPS_COOKIE_SEC_CK check (cookie_secure in (''0'',''1'')) novalidate';
			dbms_output.put_line('Recreating RHN_URLPS_COOKIE_SEC_CK');
		end if;
	end loop;
end;
/

begin
	for i in (
		select constraint_name, constraint_type, search_condition
		from ( select 'RHN_URLPS_LOAD_SUB_CK' x from dual ) d, user_constraints
		where d.x = constraint_name (+)
		) loop
		if i.constraint_name is null or not (i.constraint_type = 'C' and i.search_condition = 'load_subsidiary in (''0'',''1'')') then
			if i.constraint_name is not null then
				execute immediate 'alter table RHN_URL_PROBE_STEP drop constraint RHN_URLPS_LOAD_SUB_CK';
			end if;
			execute immediate 'alter table RHN_URL_PROBE_STEP add constraint RHN_URLPS_LOAD_SUB_CK check (load_subsidiary in (''0'',''1'')) novalidate';
			dbms_output.put_line('Recreating RHN_URLPS_LOAD_SUB_CK');
		end if;
	end loop;
end;
/

begin
	for i in (
		select constraint_name, constraint_type, search_condition
		from ( select 'RHN_URLPS_VER_LINKS_CK' x from dual ) d, user_constraints
		where d.x = constraint_name (+)
		) loop
		if i.constraint_name is null or not (i.constraint_type = 'C' and i.search_condition = 'verify_links in (''0'',''1'')') then
			if i.constraint_name is not null then
				execute immediate 'alter table RHN_URL_PROBE_STEP drop constraint RHN_URLPS_VER_LINKS_CK';
			end if;
			execute immediate 'alter table RHN_URL_PROBE_STEP add constraint RHN_URLPS_VER_LINKS_CK check (verify_links in (''0'',''1'')) novalidate';
			dbms_output.put_line('Recreating RHN_URLPS_VER_LINKS_CK');
		end if;
	end loop;
end;
/

begin
	for i in (
		select constraint_name, constraint_type, search_condition
		from ( select 'WEB_CONTACT_IGNORE_CK' x from dual ) d, user_constraints
		where d.x = constraint_name (+)
		) loop
		if i.constraint_name is null or not (i.constraint_type = 'C' and i.search_condition = 'ignore_flag in (''N'',''Y'')') then
			if i.constraint_name is not null then
				execute immediate 'alter table WEB_CONTACT drop constraint WEB_CONTACT_IGNORE_CK';
			end if;
			execute immediate 'alter table WEB_CONTACT add constraint WEB_CONTACT_IGNORE_CK check (ignore_flag in (''N'',''Y'')) novalidate';
			dbms_output.put_line('Recreating WEB_CONTACT_IGNORE_CK');
		end if;
	end loop;
end;
/

begin
	for i in (
		select constraint_name, constraint_type, search_condition
		from ( select 'WUCP_CALL_CK' x from dual ) d, user_constraints
		where d.x = constraint_name (+)
		) loop
		if i.constraint_name is null or not (i.constraint_type = 'C' and i.search_condition = 'call in (''Y'',''N'')') then
			if i.constraint_name is not null then
				execute immediate 'alter table WEB_USER_CONTACT_PERMISSION drop constraint WUCP_CALL_CK';
			end if;
			execute immediate 'alter table WEB_USER_CONTACT_PERMISSION add constraint WUCP_CALL_CK check (call in (''Y'',''N'')) novalidate';
			dbms_output.put_line('Recreating WUCP_CALL_CK');
		end if;
	end loop;
end;
/

begin
	for i in (
		select constraint_name, constraint_type, search_condition
		from ( select 'WUCP_EMAIL_CK' x from dual ) d, user_constraints
		where d.x = constraint_name (+)
		) loop
		if i.constraint_name is null or not (i.constraint_type = 'C' and i.search_condition = 'email in (''Y'',''N'')') then
			if i.constraint_name is not null then
				execute immediate 'alter table WEB_USER_CONTACT_PERMISSION drop constraint WUCP_EMAIL_CK';
			end if;
			execute immediate 'alter table WEB_USER_CONTACT_PERMISSION add constraint WUCP_EMAIL_CK check (email in (''Y'',''N'')) novalidate';
			dbms_output.put_line('Recreating WUCP_EMAIL_CK');
		end if;
	end loop;
end;
/

begin
	for i in (
		select constraint_name, constraint_type, search_condition
		from ( select 'WUCP_FAX_CK' x from dual ) d, user_constraints
		where d.x = constraint_name (+)
		) loop
		if i.constraint_name is null or not (i.constraint_type = 'C' and i.search_condition = 'fax in (''Y'',''N'')') then
			if i.constraint_name is not null then
				execute immediate 'alter table WEB_USER_CONTACT_PERMISSION drop constraint WUCP_FAX_CK';
			end if;
			execute immediate 'alter table WEB_USER_CONTACT_PERMISSION add constraint WUCP_FAX_CK check (fax in (''Y'',''N'')) novalidate';
			dbms_output.put_line('Recreating WUCP_FAX_CK');
		end if;
	end loop;
end;
/

begin
	for i in (
		select constraint_name, constraint_type, search_condition
		from ( select 'WUCP_MAIL_CK' x from dual ) d, user_constraints
		where d.x = constraint_name (+)
		) loop
		if i.constraint_name is null or not (i.constraint_type = 'C' and i.search_condition = 'mail in (''Y'',''N'')') then
			if i.constraint_name is not null then
				execute immediate 'alter table WEB_USER_CONTACT_PERMISSION drop constraint WUCP_MAIL_CK';
			end if;
			execute immediate 'alter table WEB_USER_CONTACT_PERMISSION add constraint WUCP_MAIL_CK check (mail in (''Y'',''N'')) novalidate';
			dbms_output.put_line('Recreating WUCP_MAIL_CK');
		end if;
	end loop;
end;
/

begin
	for i in (
		select constraint_name, constraint_type, search_condition
		from ( select 'WUSI_IPB_CK' x from dual ) d, user_constraints
		where d.x = constraint_name (+)
		) loop
		if i.constraint_name is null or not (i.constraint_type = 'C' and i.search_condition = 'is_po_box in (''1'',''0'')') then
			if i.constraint_name is not null then
				execute immediate 'alter table WEB_USER_SITE_INFO drop constraint WUSI_IPB_CK';
			end if;
			execute immediate 'alter table WEB_USER_SITE_INFO add constraint WUSI_IPB_CK check (is_po_box in (''1'',''0'')) novalidate';
			dbms_output.put_line('Recreating WUSI_IPB_CK');
		end if;
	end loop;
end;
/
07070100000596000081B400000000000000000000000167AE11140000001B000000000000000000000000000000000000006A00000000susemanager-schema/upgrade/spacewalk-schema-1.1-to-spacewalk-schema-1.2/080-rhnUserMessage-drop-table.sql drop table rhnUserMessage;
 07070100000597000081B400000000000000000000000167AE111400000045000000000000000000000000000000000000007000000000susemanager-schema/upgrade/spacewalk-schema-1.1-to-spacewalk-schema-1.2/081-rhnUserMessageStatus-drop-table.sql   drop table rhnUserMessageStatus;
drop sequence rhn_um_status_id_seq;
   07070100000598000081B400000000000000000000000167AE11140000001F000000000000000000000000000000000000006E00000000susemanager-schema/upgrade/spacewalk-schema-1.1-to-spacewalk-schema-1.2/082-rhnUserMessageType-drop-table.sql drop table rhnUserMessageType;
 07070100000599000081B400000000000000000000000167AE111400002284000000000000000000000000000000000000005C00000000susemanager-schema/upgrade/spacewalk-schema-1.1-to-spacewalk-schema-1.2/083-rhn_org.pkb.sql   --
-- Copyright (c) 2008--2010 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--

CREATE OR REPLACE
PACKAGE BODY rhn_org
IS
    body_version varchar2(100) := '';

    FUNCTION find_server_group_by_type(org_id_in NUMBER, group_label_in VARCHAR2) 
    RETURN NUMBER
    IS
    server_group       server_group_by_label%ROWTYPE;
    BEGIN
        OPEN server_group_by_label(org_id_in, group_label_in);
    FETCH server_group_by_label INTO server_group;
    CLOSE server_group_by_label;

    RETURN server_group.id;
    END find_server_group_by_type;
    
    procedure delete_org (
        org_id_in in number
    )
    is
        cursor users is
        select id
        from web_contact
        where org_id = org_id_in;

    cursor servers(org_id_in in number) is
        select    id
        from    rhnServer
        where    org_id = org_id_in;

        cursor config_channels is
        select id
        from rhnConfigChannel
        where org_id = org_id_in;

    cursor custom_channels is
        select    id
        from    rhnChannel
        where    org_id = org_id_in;

    cursor errata is
        select    id
        from    rhnErrata
        where    org_id = org_id_in;

    begin

        if org_id_in = 1 then
            rhn_exception.raise_exception('cannot_delete_base_org');
        end if;

        -- Delete all users.
        for u in users loop
            rhn_org.delete_user(u.id, 1);
        end loop;

        -- Delete all servers.
        for s in servers(org_id_in) loop
            delete_server(s.id);
        end loop;

        -- Delete all config channels.
        for c in config_channels loop
            rhn_config.delete_channel(c.id);
        end loop;

        -- Delete all custom channels.
        for cc in custom_channels loop
          delete from rhnServerChannel where channel_id = cc.id;
          delete from rhnServerProfilePackage where server_profile_id in (
            select id from rhnServerProfile where base_channel = cc.id
          );
          delete from rhnServerProfile where base_channel = cc.id;
        end loop;

        -- Delete all errata packages 
        for e in errata loop
            delete from rhnErrataPackage where errata_id = e.id;
        end loop;

        -- Give the org's entitlements back to the main org.
        rhn_entitlements.remove_org_entitlements(org_id_in);

        -- Clean up tables where we don't have a cascading delete.
        delete from rhnChannel where org_id = org_id_in;
        delete from rhnDailySummaryQueue where org_id = org_id_in;
        delete from rhnOrgQuota where org_id = org_id_in;
        delete from rhnFileList where org_id = org_id_in;
        delete from rhnServerGroup where org_id = org_id_in;
        delete from rhn_check_suites where customer_id = org_id_in;
        delete from rhn_command_target where customer_id = org_id_in;
        delete from rhn_contact_groups where customer_id = org_id_in;
        delete from rhn_notification_formats where customer_id = org_id_in;
        delete from rhn_probe where customer_id = org_id_in;
        delete from rhn_redirects where customer_id = org_id_in;
        delete from rhn_sat_cluster where customer_id = org_id_in;
        delete from rhn_schedules where customer_id = org_id_in;

        -- Delete the org.
        delete from web_customer where id = org_id_in;

    end delete_org;

    procedure delete_user(user_id_in in number, deleting_org in number := 0) is
        cursor servergroups_needing_admins is
            select    usgp.server_group_id    server_group_id
            from    rhnUserServerGroupPerms    usgp
            where    1=1
                and usgp.user_id = user_id_in
                and not exists (
                    select    1
                    from    rhnUserServerGroupPerms    sq_usgp
                    where    1=1
                        and sq_usgp.server_group_id = usgp.server_group_id
                        and    sq_usgp.user_id != user_id_in
                );
        users            number;
        our_org_id        number;
        other_users        number;
        other_org_admin    number;
        other_user_id  number;
        is_admin       number;
    begin
        select    wc.org_id
        into    our_org_id
        from    web_contact wc
        where    id = user_id_in;

        -- find any other users
        begin
            select    id, 1
            into    other_user_id, other_users
            from    web_contact
            where    1=1
                and org_id = our_org_id
                and id != user_id_in
                and rownum = 1;
        exception
            when no_data_found then
                other_users := 0;
        end;

        -- now do org admin stuff
        if other_users != 0 then
            -- is user admin?
            select  count(1)
             into   is_admin
            from    rhnUserGroupType    ugt,
                    rhnUserGroup        ug,
                    rhnUserGroupMembers    ugm
            where    ugm.user_id = user_id_in
                and ugm.user_group_id = ug.id
                and ug.group_type = ugt.id
                and ugt.label = 'org_admin';
            if is_admin > 0 then
                begin
                    select    new_ugm.user_id
                    into    other_org_admin
                    from    rhnUserGroupMembers    new_ugm,
                            rhnUserGroupType    ugt,
                            rhnUserGroup        ug,
                            rhnUserGroupMembers    ugm
                    where    ugm.user_id = user_id_in
                        and ugm.user_group_id = ug.id
                        and ug.group_type = ugt.id
                        and ugt.label = 'org_admin'
                        and ug.id = new_ugm.user_group_id
                        and new_ugm.user_id != user_id_in
                        and rownum = 1;
                exception
                    when no_data_found then
                        -- If we're deleting the org, we don't want to raise
                        -- the exception.
                        if deleting_org = 0 then
                            rhn_exception.raise_exception('cannot_delete_user');
                        end if;
                end;

                for sg in servergroups_needing_admins loop
                    rhn_user.add_servergroup_perm(other_org_admin,
                        sg.server_group_id);
                end loop;
            end if;
        end if;

        -- and now things for every user
        delete from rhn_command_queue_sessions where contact_id = user_id_in;
        delete from rhn_contact_groups
        where recid in (
            select contact_group_id
            from rhn_contact_group_members
            where member_contact_method_id in (
                select recid from rhn_contact_methods
                where contact_id = user_id_in
                )
            )
            and not exists (
                select 1
                from rhn_contact_group_members, rhn_contact_methods
                where rhn_contact_groups.recid = rhn_contact_group_members.contact_group_id
                    and rhn_contact_group_members.member_contact_method_id = rhn_contact_methods.recid
                    and rhn_contact_methods.contact_id <> user_id_in
            );
        delete from rhn_contact_methods where contact_id = user_id_in;
        delete from rhn_redirects where contact_id = user_id_in;
        delete from rhnUserServerPerms where user_id = user_id_in;
        delete from rhnAppInstallSession where user_id = user_id_in;
        update rhnConfigRevision
           set changed_by_id = NULL
         where changed_by_id = user_id_in;
        if other_users != 0 then
            update        rhnRegToken
                set        user_id = nvl(other_org_admin, other_user_id)
                where    org_id = our_org_id
                    and user_id = user_id_in;
        end if;

        begin
            delete from web_contact where id = user_id_in;
        exception
            when others then
                rhn_exception.raise_exception('cannot_delete_user');
        end;
        return;
    end delete_user;

END rhn_org;
/
SHOW ERRORS

0707010000059A000081B400000000000000000000000167AE111400000393000000000000000000000000000000000000006A00000000susemanager-schema/upgrade/spacewalk-schema-1.1-to-spacewalk-schema-1.2/090-rhnRepoRegenQueue-trigger.sql 
--
-- Copyright (c) 2008--2010 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--

create or replace trigger rhn_repo_regen_queue_mod_trig
before insert or update on rhnRepoRegenQueue
for each row
begin
    if :new.id is null then
        select rhn_repo_regen_queue_id_seq.nextval into :new.id from dual;
    end if;
    :new.modified := sysdate;
end;
/
show errors
 0707010000059B000081B400000000000000000000000167AE111400001064000000000000000000000000000000000000006100000000susemanager-schema/upgrade/spacewalk-schema-1.1-to-spacewalk-schema-1.2/091-rhn_entitlements.sql  --
-- Copyright (c) 2008--2010 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--

create or replace
package rhn_entitlements
is
	body_version varchar2(100) := '';

   type ents_array is varray(10) of rhnServerGroupType.label%TYPE;

    procedure remove_org_entitlements (
        org_id_in number
    );

    function entitlement_grants_service (
	    entitlement_in in varchar2,
		service_level_in in varchar2
	) return number;

	function lookup_entitlement_group (
		org_id_in in number,
		type_label_in in varchar2 := 'sw_mgr_entitled'
	) return number;

	function create_entitlement_group (
		org_id_in in number,
		type_label_in in varchar2 := 'sw_mgr_entitled'
	) return number;

   function can_entitle_server ( 
      server_id_in   in number, 
      type_label_in  in varchar2
   )
   return number;

   function can_switch_base ( 
      server_id_in   in    integer, 
      type_label_in  in    varchar2
   )
   return number;

	procedure entitle_server (
		server_id_in in number,
		type_label_in in varchar2 := 'sw_mgr_entitled'
	);

	procedure remove_server_entitlement (
		server_id_in in number,
		type_label_in in varchar2 := 'sw_mgr_entitled',
        repoll_virt_guests in number := 1
	);

	procedure unentitle_server (
		server_id_in in number
	);

    procedure repoll_virt_guest_entitlements(
        server_id_in in number
    );

	function get_server_entitlement (
		server_id_in in number
	) return ents_array;

	procedure modify_org_service (
		org_id_in in number,
		service_label_in in varchar2,
		enable_in in char
	);

    procedure set_customer_enterprise (
		customer_id_in in number
	);

	procedure set_customer_provisioning (
		customer_id_in in number
	);

	procedure set_customer_nonlinux (
		customer_id_in in number
	);

    procedure unset_customer_enterprise (
		customer_id_in in number
	);

	procedure unset_customer_provisioning (
		customer_id_in in number
	);

	procedure unset_customer_nonlinux (
		customer_id_in in number
	);

    procedure assign_system_entitlement(
        group_label_in in varchar2,
        from_org_id_in in number,
        to_org_id_in in number,
        quantity_in in number
    );

    procedure assign_channel_entitlement(
        channel_family_label_in in varchar2,
        from_org_id_in in number,
        to_org_id_in in number,
        quantity_in in number,
        flex_in in number
    );

    procedure activate_system_entitlement(
        org_id_in in number,
        group_label_in in varchar2,
        quantity_in in number
    );

    procedure activate_channel_entitlement(
        org_id_in in number,
        channel_family_label_in in varchar2,
        quantity_in in number,
        flex_in in number
    );

    procedure set_group_count (
		customer_id_in in number,	-- customer_id
		type_in in char,			-- 'U' or 'S'
		group_type_in in number,	-- rhn[User|Server]GroupType.id
		quantity_in in number,		-- quantity
                update_family_countsYN in number := 1 -- call update_family_counts inside
    );

    procedure set_family_count (
		customer_id_in in number,		-- customer_id
		channel_family_id_in in number,	-- 246
		quantity_in in number,			-- 3
                flex_in in number
    );

    -- this makes NO checks that the quantity is within max,
    -- so we should NEVER run this unless we KNOW that we won't be
    -- violating the max
    procedure entitle_last_modified_servers (
		customer_id_in in number,	-- customer_id
		type_label_in in varchar2,	-- 'enterprise_entitled'
		quantity_in in number		-- 3
    );

	procedure subscribe_newest_servers (
		customer_id_in in number
	);
end rhn_entitlements;
/
show errors

0707010000059C000081B400000000000000000000000167AE1114000110AC000000000000000000000000000000000000006600000000susemanager-schema/upgrade/spacewalk-schema-1.1-to-spacewalk-schema-1.2/092-rhn_entitlements-body.sql --
-- Copyright (c) 2008--2010 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--

create or replace
package body rhn_entitlements
is
    body_version varchar2(100) := '';

   function find_compatible_sg (
      server_id_in    in   number,
      type_label_in   in   varchar2
   ) return number is

      cursor servergroups is
         select sg.id            id
           from rhnServerGroupType             sgt,
                rhnServerGroup                 sg,
                rhnServer                     s,
                rhnServerServerGroupArchCompat ssgac
          where s.id = server_id_in
            and s.org_id = sg.org_id
            and sgt.label = type_label_in
            and sg.group_type = sgt.id
            and ssgac.server_group_type = sgt.id
            and ssgac.server_arch_id = s.server_arch_id
            and not exists ( 
                     select 1
                      from rhnServerGroupMembers sgm
                     where sgm.server_group_id = sg.id 
                       and sgm.server_id = s.id);

         
   begin
      for servergroup in servergroups loop
         return servergroup.id;
      end loop;

      --no servergroup found
      return null;
   end find_compatible_sg;


    -- *******************************************************************
    -- PROCEDURE: remove_org_entitlements
    --
    -- Removes both system entitlements and channel subscriptions
    -- that are currently assigned to an org and re-assigns to the
    -- master org (org_id = 1).
    --
    -- When we call this we expect everything to already be unentitled
    -- which shoul be handled by delete_org.
    --
    -- Called by: delete_org
    -- *******************************************************************
    procedure remove_org_entitlements(
        org_id_in in number
    )
    is

        cursor system_ents is
        select sg.id, sg.max_members, sg.group_type
        from rhnServerGroup sg
        where group_type is not null
          and org_id = org_id_in;

        cursor channel_subs is
        select pcf.channel_family_id, pcf.max_members
        from rhnChannelFamily cf,
             rhnPrivateChannelFamily pcf
        where pcf.org_id = org_id_in
          and pcf.channel_family_id = cf.id
          and cf.org_id is null;

    begin

        for system_ent in system_ents loop
            update rhnServerGroup
            set max_members = max_members + system_ent.max_members
            where org_id = 1
              and group_type = system_ent.group_type;
        end loop;

        update rhnServerGroup
        set max_members = 0
        where org_id = org_id_in;

        for channel_sub in channel_subs loop
            update rhnPrivateChannelFamily
            set max_members = max_members + channel_sub.max_members
            where org_id = 1
              and channel_family_id = channel_sub.channel_family_id;
        end loop;
        
        update rhnPrivateChannelFamily
        set max_members = 0
        where org_id = org_id_in;

    end remove_org_entitlements;
 
    function entitlement_grants_service (
        entitlement_in in varchar2,
        service_level_in in varchar2
    ) return number    is
    begin
        if service_level_in = 'provisioning' then
            if entitlement_in = 'provisioning_entitled' then
                return 1;
            else
                return 0;
            end if;
        elsif service_level_in = 'management' then
            if entitlement_in = 'enterprise_entitled' then
                return 1;
            else
                return 0;
            end if;
        elsif service_level_in = 'monitoring' then
            if entitlement_in = 'monitoring_entitled' then
                return 1;
            end if;
        elsif service_level_in = 'updates' then
            return 1;
        else
            return 0;
        end if;
    end entitlement_grants_service;

    function lookup_entitlement_group (
        org_id_in in number,
        type_label_in in varchar2 := 'sw_mgr_entitled'
    ) return number is
        cursor server_groups is
            select    sg.id                server_group_id
            from    rhnServerGroup        sg,
                    rhnServerGroupType    sgt
            where    sgt.label = type_label_in
                and sgt.id = sg.group_type
                and sg.org_id = org_id_in;
    begin
        for sg in server_groups loop
            return sg.server_group_id;
        end loop;
        return rhn_entitlements.create_entitlement_group(
                org_id_in,
                type_label_in
            );
    end lookup_entitlement_group;

    function create_entitlement_group (
        org_id_in in number,
        type_label_in in varchar2 := 'sw_mgr_entitled'
    ) return number is
        sg_id_val number;
    begin
        select    rhn_server_group_id_seq.nextval
        into    sg_id_val
        from    dual;

        insert into rhnServerGroup (
                id, name, description, max_members, current_members,
                group_type, org_id
            ) (
                select    sg_id_val, sgt.label, sgt.label,
                        0, 0, sgt.id, org_id_in
                from    rhnServerGroupType sgt
                where    sgt.label = type_label_in
            );

        return sg_id_val;
    end create_entitlement_group;

   function can_entitle_server ( 
        server_id_in in number, 
        type_label_in in varchar2 ) 
   return number is
      cursor addon_servergroups (base_label_in in varchar2, 
                                 addon_label_in in varchar2) is
         select
            addon_id
         from
            rhnSGTypeBaseAddonCompat
         where base_id = lookup_sg_type (base_label_in)
           and addon_id = lookup_sg_type (addon_label_in);

      previous_ent        rhn_entitlements.ents_array;
      is_base_in          char   := 'N';
      is_base_current     char   := 'N';
      i                   number := 0;
      sgid                number := 0;

   begin

      previous_ent := rhn_entitlements.ents_array();
      previous_ent := rhn_entitlements.get_server_entitlement(server_id_in);

      select distinct is_base
      into is_base_in
      from rhnServerGroupType
      where label = type_label_in;

      if previous_ent.count = 0 then
         sgid := find_compatible_sg (server_id_in, type_label_in);
         if (is_base_in = 'Y' and sgid is not null) then
            -- rhn_server.insert_into_servergroup (server_id_in, sgid);
            return 1;
         else
            -- rhn_exception.raise_exception ('invalid_base_entitlement');
            return 0;
         end if;

      -- there are previous ents, first make sure we're not trying to entitle a base ent
      elsif is_base_in = 'Y' then
         -- rhn_exception.raise_exception ('invalid_addon_entitlement');
         return 0;

      -- it must be an addon, so proceed with the entitlement
      else

         -- find the servers base ent
         is_base_current := 'N';
         i := 0;
         while is_base_current = 'N' and i <= previous_ent.count
         loop
            i := i + 1;
            select is_base
            into is_base_current
            from rhnServerGroupType
            where label = previous_ent(i);
         end loop;

         -- never found a base ent, that would be strange
         if is_base_current  = 'N' then
            -- rhn_exception.raise_exception ('invalid_base_entitlement');
            return 0;
         end if;

         -- this for loop verifies the validity of the addon path
         for addon_servergroup in addon_servergroups  (previous_ent(i), type_label_in) loop
            -- find an appropriate sgid for the addon and entitle the server
            sgid := find_compatible_sg (server_id_in, type_label_in);
            if sgid is not null then
               -- rhn_server.insert_into_servergroup (server_id_in, sgid);
               return 1;
            else
               -- rhn_exception.raise_exception ('invalid_addon_entitlement');
               return 0;
            end if;
         end loop;

      end if;

      return 0;

   end can_entitle_server;

   function can_switch_base (
      server_id_in   in    integer,
      type_label_in  in    varchar2
   ) return number is

      type_label_in_is_base   char(1);
      sgid                    number;

   begin

      begin
         select is_base into type_label_in_is_base
         from rhnServerGroupType
         where label = type_label_in;
      exception
         when no_data_found then
            rhn_exception.raise_exception ( 'invalid_entitlement' );
      end;

      if type_label_in_is_base = 'N' then
         rhn_exception.raise_exception ( 'invalid_entitlement' );
      else
         sgid := find_compatible_sg ( server_id_in, type_label_in );
         if sgid is not null then
            return 1;
         else
            return 0;
         end if;
      end if;

   end can_switch_base;


    procedure entitle_server (
        server_id_in in number,
        type_label_in in varchar2 := 'sw_mgr_entitled'
    ) is
      sgid  number := 0;
      is_virt number := 0;

    begin

          begin
          select 1 into is_virt
            from rhnServerEntitlementView
           where server_id = server_id_in
             and label in ('virtualization_host', 'virtualization_host_platform');
      exception
            when no_data_found then
              is_virt := 0;
          end;
      
      if is_virt = 0 and (type_label_in = 'virtualization_host' or
                          type_label_in = 'virtualization_host_platform') then

        is_virt := 1;
      end if;



      if rhn_entitlements.can_entitle_server(server_id_in, 
                                             type_label_in) = 1 then
         sgid := find_compatible_sg (server_id_in, type_label_in);
         if sgid is not null then
            insert into rhnServerHistory ( id, server_id, summary, details )
            values ( rhn_event_id_seq.nextval, server_id_in,
                     'added system entitlement ',
                      case type_label_in
                       when 'enterprise_entitled' then 'Management'
                       when 'sw_mgr_entitled' then 'Update'
                       when 'provisioning_entitled' then 'Provisioning'
                       when 'monitoring_entitled' then 'Monitoring'  
                       when 'virtualization_host' then 'Virtualization'
                       when 'virtualization_host_platform' then 
                            'Virtualization Platform' end  );

            rhn_server.insert_into_servergroup (server_id_in, sgid);

            if is_virt = 1 then
              rhn_entitlements.repoll_virt_guest_entitlements(server_id_in);
            end if;

         else
            rhn_exception.raise_exception ('no_available_server_group');
         end if;
      else
         rhn_exception.raise_exception ('invalid_entitlement');
      end if;
   end entitle_server;

    procedure remove_server_entitlement (
        server_id_in in number,
        type_label_in in varchar2 := 'sw_mgr_entitled',
        repoll_virt_guests in number := 1
    ) is
        group_id number;
      type_is_base char;
      is_virt number := 0;
    begin
      begin


      -- would be nice if there were a virt attribute of entitlement types, not have to specify 2 different ones...
        begin
          select 1 into is_virt
            from rhnServerEntitlementView
           where server_id = server_id_in
             and label in ('virtualization_host', 'virtualization_host_platform');
        exception
          when no_data_found then
            is_virt := 0;
        end;

        select    sg.id, sgt.is_base
          into    group_id, type_is_base
          from    rhnServerGroupType sgt,
               rhnServerGroup sg,
                  rhnServerGroupMembers sgm,
                  rhnServer s
          where    s.id = server_id_in
              and s.id = sgm.server_id
              and sgm.server_group_id = sg.id
              and sg.org_id = s.org_id
              and sgt.label = type_label_in
              and sgt.id = sg.group_type;

      if ( type_is_base = 'Y' ) then
         -- unentitle_server should handle everything, don't really need to do anything else special here
         unentitle_server ( server_id_in );
      else

         insert into rhnServerHistory ( id, server_id, summary, details )
         values ( rhn_event_id_seq.nextval, server_id_in,
                  'removed system entitlement ',
                   case type_label_in
                    when 'enterprise_entitled' then 'Management'
                    when 'sw_mgr_entitled' then 'Update'
                    when 'provisioning_entitled' then 'Provisioning'
                    when 'monitoring_entitled' then 'Monitoring'
                    when 'virtualization_host' then 'Virtualization'
                    when 'virtualization_host_platform' then 
                         'Virtualization Platforrm' end  );

         rhn_server.delete_from_servergroup(server_id_in, group_id);

         -- special case: clean up related monitornig data
         if type_label_in = 'monitoring_entitled' then
           DELETE
             FROM state_change
            WHERE o_id IN (SELECT probe_id
                             FROM rhn_check_probe
                            WHERE host_id = server_id_in);
           DELETE /*+index(time_series time_series_probe_id_idx)*/
             FROM time_series
            WHERE SUBSTR(o_id, INSTR(o_id, '-') + 1, 
                        (INSTR(o_id, '-', INSTR(o_id, '-') + 1) - INSTR(o_id, '-')) - 1)
              IN (SELECT to_char(probe_id)
                    FROM rhn_check_probe
                   WHERE host_id = server_id_in);
           DELETE
             FROM rhn_probe
            WHERE recid IN (SELECT probe_id
                              FROM rhn_check_probe
                             WHERE host_id = server_id_in);
         end if;

         if is_virt = 1 and repoll_virt_guests = 1 then
           rhn_entitlements.repoll_virt_guest_entitlements(server_id_in);
         end if;
      end if;

          exception
          when no_data_found then
                  rhn_exception.raise_exception('invalid_server_group_member');
      end;

     end remove_server_entitlement;


   procedure unentitle_server (server_id_in in number) is

      cursor servergroups is
         select distinct sgt.label, sg.id server_group_id
         from  rhnServerGroupType sgt,
               rhnServerGroup sg,
               rhnServer s,
               rhnServerGroupMembers sgm
         where s.id = server_id_in
            and s.org_id = sg.org_id
            and sg.group_type = sgt.id
            and sgm.server_group_id = sg.id
            and sgm.server_id = s.id;
            
     is_virt number := 0;

   begin

      begin
        select 1 into is_virt
          from rhnServerEntitlementView
         where server_id = server_id_in
           and label in ('virtualization_host', 'virtualization_host_platform');
      exception
        when no_data_found then
          is_virt := 0;
      end;

      for servergroup in servergroups loop

         insert into rhnServerHistory ( id, server_id, summary, details )
         values ( rhn_event_id_seq.nextval, server_id_in,
                  'removed system entitlement ',
                   case servergroup.label
                    when 'enterprise_entitled' then 'Management'
                    when 'sw_mgr_entitled' then 'Update'
                    when 'provisioning_entitled' then 'Provisioning'
                    when 'monitoring_entitled' then 'Monitoring'
                    when 'virtualization_host' then 'Virtualization'
                    when 'virtualization_host_platform' then 
                         'Virtualization Platform' end  );
  
         rhn_server.delete_from_servergroup(server_id_in, 
                                            servergroup.server_group_id );
      end loop;

      if is_virt = 1 then
        rhn_entitlements.repoll_virt_guest_entitlements(server_id_in);
      end if;

   end unentitle_server;


    -- *******************************************************************
    -- PROCEDURE: repoll_virt_guest_entitlements
    --
    --   Whenever we add/remove a virtualization_host* entitlement from 
    --   a host, we can call this procedure to update what type of slots
    --   the guests are consuming.  
    -- 
    --   If you're removing the entitlement, it's 
    --   possible the guests will become unentitled if you don't have enough
    --   physical slots to cover them.
    --
    --   If you're adding the entitlement, you end up freeing up physical
    --   slots for other systems.
    --
    -- *******************************************************************
    procedure repoll_virt_guest_entitlements(server_id_in in number)
    is

        -- All channel families associated with the guests of server_id_in
        cursor families is 
            select distinct cfs.channel_family_id
            from
                rhnChannelFamilyServers cfs,
                rhnVirtualInstance vi
            where
                vi.host_system_id = server_id_in
                and vi.virtual_system_id = cfs.server_id;
        
        -- All of server group types associated with the guests of
        -- server_id_in
        cursor group_types is
            select distinct sg.group_type, sgt.label
            from
                rhnServerGroupType sgt,
                rhnServerGroup sg,
                rhnServerGroupMembers sgm,
                rhnVirtualInstance vi
            where
                vi.host_system_id = server_id_in
                and vi.virtual_system_id = sgm.server_id
                and sgm.server_group_id = sg.id
                and sg.group_type = sgt.id;

        -- Virtual servers from a certain family belonging to a speicifc
        -- host that are consuming physical channel slots over the limit.
        cursor virt_servers_cfam(family_id_in in number, quantity_in in number)  is
            select virtual_system_id
            from (
                select rownum, vi.virtual_system_id
                from
                    rhnChannelFamilyMembers cfm,
                    rhnServerChannel sc,
                    rhnVirtualInstance vi
                where
                    vi.host_system_id = server_id_in
                    and vi.virtual_system_id = sc.server_id
                    and sc.channel_id = cfm.channel_id
                    and cfm.channel_family_id = family_id_in
                order by sc.modified desc
                )
            where rownum <= quantity_in;

        -- Virtual servers from a certain family belonging to a speicifc
        -- host that are consuming physical system slots over the limit.
        cursor virt_servers_sgt(group_type_in in number, quantity_in in number)  is
            select virtual_system_id
            from (
                select rownum, vi.virtual_system_id
                from
                    rhnServerGroup sg,
                    rhnServerGroupMembers sgm,
                    rhnVirtualInstance vi
                where
                    vi.host_system_id = server_id_in
                    and vi.virtual_system_id = sgm.server_id
                    and sgm.server_group_id = sg.id
                    and sg.group_type = group_type_in
                order by sgm.modified desc
                )
            where rownum <= quantity_in;
        -- Get the orgs of Virtual guests
        -- Since they may belong to different orgs
        cursor virt_guest_orgs  is
                select  distinct (s.org_id)
                from rhnServer s
                    inner join  rhnVirtualInstance vi on vi.virtual_system_id = s.id
                where
                    vi.host_system_id = server_id_in 
                    and s.org_id <> (select s1.org_id from rhnServer s1 where s1.id = vi.host_system_id) ;


        org_id_val number;
        max_members_val number;
        max_flex_val number;
        current_members_calc number;
        sg_id number;
        is_virt number := 0;
    begin
        begin
          select 1 into is_virt
                from rhnServerEntitlementView
           where server_id = server_id_in
                 and label in ('virtualization_host', 'virtualization_host_platform');
           exception
                when no_data_found then
                  is_virt := 0;
        end;

        select org_id
        into org_id_val
        from rhnServer
        where id = server_id_in;

        -- deal w/ channel entitlements first ...
        for family in families loop
            if is_virt = 0 then
            -- if the host_server does not have virt
            --- find all possible flex slots
            -- and set each of the flex eligible guests to Y
                UPDATE rhnServerChannel sc set sc.is_fve = 'Y'
                where sc.server_id in (
                       select virtual_system_id from (
                            select rownum, vi.virtual_system_id,  sfc.max_members - sfc.current_members as free_slots
                            from rhnServerFveCapable sfc
                                inner join rhnVirtualInstance vi on vi.virtual_system_id = sfc.server_id
                            where vi.host_system_id = server_id_in
                                  and sfc.channel_family_id = family.channel_family_id
                              order by vi.modified desc
                          )
                        where rownum <=  free_slots
                );
            else
            -- if the host_server has virt
            -- set all its flex guests to N
                UPDATE rhnServerChannel sc set sc.is_fve = 'N'
                where 
                    sc.channel_id in (select cfm.channel_id from rhnChannelFamilyMembers cfm
                                      where cfm.CHANNEL_FAMILY_ID = family.channel_family_id)
                    and sc.is_fve = 'Y'
                    and sc.server_id in  
                            (select vi.virtual_system_id  from rhnVirtualInstance vi 
                                    where vi.host_system_id = server_id_in);
            end if;
        
            -- get the current (physical) members of the family
            current_members_calc := 
                rhn_channel.channel_family_current_members(family.channel_family_id,
                                                           org_id_val); -- fixed transposed args

            -- get the max members of the family
            select max_members
            into max_members_val
            from rhnPrivateChannelFamily
            where channel_family_id = family.channel_family_id
            and org_id = org_id_val;

            select fve_max_members
            into max_flex_val
            from rhnPrivateChannelFamily
            where channel_family_id = family.channel_family_id
            and org_id = org_id_val;

            if current_members_calc > max_members_val then
                -- A virtualization_host* ent must have been removed, so we'll
                -- unsubscribe guests from the host first.

                -- hm, i don't think max_members - current_members_calc yielding a negative number
                -- will work w/ rownum, swaping 'em in the body of this if...
                for virt_server in virt_servers_cfam(family.channel_family_id,
                                current_members_calc - max_members_val) loop 

                    rhn_channel.unsubscribe_server_from_family(
                                virt_server.virtual_system_id,
                                family.channel_family_id);
                end loop;                               

                -- if we're still over the limit, which would be odd,
                -- just prune the group to max_members
                --
                -- er... wouldn't we actually have to refresh the values of
                -- current_members_calc and max_members_val to actually ever
                -- *skip this??
                if current_members_calc > max_members_val then
                    -- argh, transposed again?!
                    set_family_count(org_id_val,
                                     family.channel_family_id,
                                     max_members_val, max_flex_val);
                    --TODO calculate this correctly
                end if; 

           end if;

            -- update current_members for the family.  This will set the value
            -- to reflect adding/removing the entitlement.
            --
            -- what's the difference of doing this vs the unavoidable set_family_count above?
            rhn_channel.update_family_counts(family.channel_family_id,
                                             org_id_val);

            -- It is possible that the guests belong  to a different org than the host
            -- so we are going to update the family counts in the guests orgs also
            for org in virt_guest_orgs loop
                    rhn_channel.update_family_counts(family.channel_family_id,
                                             org.org_id);
            end loop;
        end loop;

        for a_group_type in group_types loop
          -- get the current *physical* members of the system entitlement type for the org...
          -- 
          -- unlike channel families, it appears the standard rhnServerGroup.max_members represents
          -- *physical* slots, vs physical+virt ... boy that's confusing...

          select max_members, id
            into max_members_val, sg_id
            from rhnServerGroup
            where group_type = a_group_type.group_type
            and org_id = org_id_val;


      select count(sep.server_id) into current_members_calc
            from rhnServerEntitlementPhysical sep
           where sep.server_group_id = sg_id
             and sep.server_group_type_id = a_group_type.group_type;
          
          if current_members_calc > max_members_val then
            -- A virtualization_host* ent must have been removed, and we're over the limit, so unsubscribe guests
            for virt_server in virt_servers_sgt(a_group_type.group_type,
                                                current_members_calc - max_members_val) loop
              rhn_entitlements.remove_server_entitlement(virt_server.virtual_system_id, a_group_type.label);

              -- decrement current_members_calc, we'll use it to reset current_members for the group at the end...
              current_members_calc := current_members_calc - 1;
            end loop;

          end if;

          update rhnServerGroup set current_members = current_members_calc
           where org_id = org_id_val
             and group_type = a_group_type.group_type;

          -- I think that's all the house-keeping we have to do...
        end loop;

    end repoll_virt_guest_entitlements;


    function get_server_entitlement (
        server_id_in in number
    ) return ents_array is

        cursor server_groups is
            select    sgt.label
            from    rhnServerGroupType        sgt,
                    rhnServerGroup            sg,
                    rhnServerGroupMembers    sgm
            where    1=1
                and sgm.server_id = server_id_in
                and sg.id = sgm.server_group_id
                and sgt.id = sg.group_type
                and sgt.label in (
                    'sw_mgr_entitled','enterprise_entitled',
                    'provisioning_entitled', 'nonlinux_entitled',
                    'monitoring_entitled', 'virtualization_host',
                                        'virtualization_host_platform'
                    );

         ent_array ents_array;

    begin
      
      ent_array := ents_array();

        for sg in server_groups loop
         ent_array.extend;
         ent_array(ent_array.count) := sg.label;
        end loop;

        return ent_array;

    end get_server_entitlement;


    -- this desperately needs to be table driven.
    procedure modify_org_service (
        org_id_in in number,
        service_label_in in varchar2,
        enable_in in char
    ) is
        type roles_v is varray(10) of rhnUserGroupType.label%TYPE;
        roles_to_process roles_v;
        cursor roles(role_label_in in varchar2) is
            select    label, id
            from    rhnUserGroupType
            where    label = role_label_in;
        cursor org_roles(role_label_in in varchar2) is
            select    1
            from    rhnUserGroup ug,
                    rhnUserGroupType ugt
            where    ugt.label = role_label_in
                and ug.org_id = org_id_in
                and ugt.id = ug.group_type;

        type ents_v is varray(10) of rhnOrgEntitlementType.label%TYPE;
        ents_to_process ents_v;
        cursor ents(ent_label_in in varchar2) is
            select    label, id
            from    rhnOrgEntitlementType
            where    label = ent_label_in;
        cursor org_ents(ent_label_in in varchar2) is
            select    1
            from    rhnOrgEntitlements oe,
                    rhnOrgEntitlementType oet
            where    oet.label = ent_label_in
                and oe.org_id = org_id_in
                and oet.id = oe.entitlement_id;
        create_row char(1);
    begin
        ents_to_process := ents_v();
        roles_to_process := roles_v();
        -- a bit kludgy, but only for 3.4 really.  Certainly no
        -- worse than the old code...
        if service_label_in = 'enterprise' or
           service_label_in = 'management' then
            ents_to_process.extend;
            ents_to_process(ents_to_process.count) := 'sw_mgr_enterprise';

            roles_to_process.extend;
            roles_to_process(roles_to_process.count) := 'org_admin';

            roles_to_process.extend;
            roles_to_process(roles_to_process.count) := 'system_group_admin';

            roles_to_process.extend;
            roles_to_process(roles_to_process.count) := 'activation_key_admin';

            roles_to_process.extend;
            roles_to_process(roles_to_process.count) := 'org_applicant';
        elsif service_label_in = 'provisioning' then
            ents_to_process.extend;
            ents_to_process(ents_to_process.count) := 'rhn_provisioning';

            roles_to_process.extend;
            roles_to_process(roles_to_process.count) := 'system_group_admin';

            roles_to_process.extend;
            roles_to_process(roles_to_process.count) := 'activation_key_admin';

            roles_to_process.extend;
            roles_to_process(roles_to_process.count) := 'config_admin';
            -- another nasty special case...
            if enable_in = 'Y' then
                ents_to_process.extend;
                ents_to_process(ents_to_process.count) := 'sw_mgr_enterprise';
            end if;
        elsif service_label_in = 'monitoring' then
            ents_to_process.extend;
            ents_to_process(ents_to_process.count) := 'rhn_monitor';

            roles_to_process.extend;
            roles_to_process(roles_to_process.count) := 'monitoring_admin';
        elsif service_label_in = 'virtualization' then
            ents_to_process.extend;
            ents_to_process(ents_to_process.count) := 'rhn_virtualization';

            roles_to_process.extend;
            roles_to_process(roles_to_process.count) := 'config_admin';
        elsif service_label_in = 'virtualization_platform' then
            ents_to_process.extend;
            ents_to_process(ents_to_process.count) := 'rhn_virtualization_platform';
            roles_to_process.extend;
            roles_to_process(roles_to_process.count) := 'config_admin';
    elsif service_label_in = 'nonlinux' then
            ents_to_process.extend;
            ents_to_process(ents_to_process.count) := 'rhn_nonlinux';
            roles_to_process.extend;
            roles_to_process(roles_to_process.count) := 'config_admin';
        end if;

        if enable_in = 'Y' then
            for i in 1..ents_to_process.count loop
                for ent in ents(ents_to_process(i)) loop
                    create_row := 'Y';
                    for oe in org_ents(ent.label) loop
                        create_row := 'N';
                    end loop;
                    if create_row = 'Y' then
                        insert into rhnOrgEntitlements(org_id, entitlement_id)
                            values (org_id_in, ent.id);
                    end if;
                end loop;
            end loop;
            for i in 1..roles_to_process.count loop
                for role in roles(roles_to_process(i)) loop
                    create_row := 'Y';
                    for o_r in org_roles(role.label) loop
                        create_row := 'N';
                    end loop;
                    if create_row = 'Y' then
                        insert into rhnUserGroup(
                                id, name, description, current_members,
                                group_type, org_id
                            ) (
                                select    rhn_user_group_id_seq.nextval,
                                        ugt.name || 's',
                                        ugt.name || 's for Org ' ||
                                            o.name || ' ('|| o.id ||')',
                                        0, ugt.id, o.id
                                from    rhnUserGroupType ugt,
                                        web_customer o
                                where    o.id = org_id_in
                                    and ugt.id = role.id
                            );
                    end if;
                end loop;
            end loop;
        else
            for i in 1..ents_to_process.count loop
                for ent in ents(ents_to_process(i)) loop
                    delete from rhnOrgEntitlements
                     where org_id = org_id_in
                       and entitlement_id = ent.id;
                end loop;
            end loop;
        end if;
    end modify_org_service;

    procedure set_customer_enterprise (
        customer_id_in in number
    ) is
    begin
        modify_org_service(customer_id_in, 'enterprise', 'Y');
    end set_customer_enterprise;

    procedure set_customer_provisioning (
        customer_id_in in number
    ) is
    begin
        modify_org_service(customer_id_in, 'provisioning', 'Y');
    end set_customer_provisioning;

    procedure set_customer_monitoring (
        customer_id_in in number
    ) is
    begin
        modify_org_service(customer_id_in, 'monitoring', 'Y');
    end set_customer_monitoring;

    procedure set_customer_nonlinux (
        customer_id_in in number
    ) is
    begin
        modify_org_service(customer_id_in, 'nonlinux', 'Y');
    end set_customer_nonlinux;

    procedure unset_customer_enterprise (
        customer_id_in in number
    ) is
    begin
        modify_org_service(customer_id_in, 'enterprise', 'N');
    end unset_customer_enterprise;

    procedure unset_customer_provisioning (
        customer_id_in in number
    ) is
    begin
        modify_org_service(customer_id_in, 'provisioning', 'N');
    end unset_customer_provisioning;

    procedure unset_customer_monitoring (
        customer_id_in in number
    ) is
    begin
        modify_org_service(customer_id_in, 'monitoring', 'N');
    end unset_customer_monitoring;

    procedure unset_customer_nonlinux (
        customer_id_in in number
    ) is
    begin
        modify_org_service(customer_id_in, 'nonlinux', 'N');
    end unset_customer_nonlinux;

    -- *******************************************************************
    -- PROCEDURE: prune_group
    -- Unsubscribes servers consuming physical slots that over the org's
    --   limit.
    -- Called by: set_group_count, repoll_virt_guest_entitlements
    -- *******************************************************************
    procedure prune_group (
        group_id_in in number,
        type_in in char,
        quantity_in in number,
                update_family_countsYN in number := 1
    ) is
        cursor usergroups is
            select    user_id, user_group_id, ugt.label
            from    rhnUserGroupType    ugt,
                    rhnUserGroup        ug,
                    rhnUserGroupMembers    ugm
            where    1=1
                and ugm.user_group_id = group_id_in
                and ugm.user_id in (
                    select    user_id
                    from    (
                        select    rownum row_number,
                                user_id,
                                time
                        from    (
                            select    user_id,
                                    modified time
                            from    rhnUserGroupMembers
                            where    user_group_id = group_id_in
                            order by time asc
                        )
                    )
                    where    row_number > quantity_in
                )
                and ugm.user_group_id = ug.id
                and ug.group_type = ugt.id;
        cursor servergroups is
           select  server_id, server_group_id, sgt.id as group_type_id, sgt.label
            from    rhnServerGroupType              sgt,
                            rhnServerGroup                  sg,
                            rhnServerGroupMembers   sgm
            where   1=1
                    and sgm.server_group_id = group_id_in
                    and sgm.server_id in (
                            select  server_id
                            from    (
                                    select  rownum row_number,
                                                    server_id,
                                                    time
                                    from    (
                                            select  sep.server_id,
                                                    sep.modified time
                                            from
                                                rhnServerEntitlementPhysical sep
                                            where
                                                sep.server_group_id = group_id_in
                                            order by time asc
                                    )
                            )
                            where   row_number > quantity_in
                    )
                    and sgm.server_group_id = sg.id
                    and sg.group_type = sgt.id;
      type_is_base char;
    begin
        if type_in = 'U' then
            update        rhnUserGroup
                set        max_members = quantity_in
                where    id = group_id_in;

            for ug in usergroups loop
                rhn_user.remove_from_usergroup(ug.user_id, ug.user_group_id);
            end loop;
        elsif type_in = 'S' then
            update        rhnServerGroup
                set        max_members = quantity_in
                where    id = group_id_in;

            for sg in servergroups loop
                remove_server_entitlement(sg.server_id, sg.label);
            
            select is_base 
            into type_is_base
            from rhnServerGroupType sgt
            where sgt.id = sg.group_type_id;
 
            -- if we're removing a base ent, then be sure to
            -- remove the server's channel subscriptions.
            if ( type_is_base = 'Y' ) then
                   rhn_channel.clear_subscriptions(sg.server_id,
                                        update_family_countsYN => update_family_countsYN);
            end if;

            end loop;
        end if;
    end prune_group;

    -- *******************************************************************
    -- PROCEDURE: assign_system_entitlement
    --
    -- Moves system entitlements from from_org_id_in to to_org_id_in.
    -- Can raise not_enough_entitlements_in_base_org if from_org_id_in
    -- does not have enough entitlements to cover the move.
    -- Takes care of unentitling systems if necessary by calling 
    -- set_group_count
    -- *******************************************************************
    procedure assign_system_entitlement(
        group_label_in in varchar2,
        from_org_id_in in number,
        to_org_id_in in number,
        quantity_in in number
    )
    is
        prev_ent_count number;
    to_org_prev_ent_count number;
        new_ent_count number;
    new_quantity number;
        group_type number;
    begin

        begin
            select max_members
            into prev_ent_count
            from rhnServerGroupType sgt,
                 rhnServerGroup sg
            where sg.org_id = from_org_id_in
              and sg.group_type = sgt.id
              and sgt.label = group_label_in;
        exception
            when NO_DATA_FOUND then
                rhn_exception.raise_exception(
                              'not_enough_entitlements_in_base_org');
        end;

        begin
            select max_members
            into to_org_prev_ent_count
            from rhnServerGroupType sgt,
                 rhnServerGroup sg
            where sg.org_id = to_org_id_in
              and sg.group_type = sgt.id
              and sgt.label = group_label_in;
        exception
            when NO_DATA_FOUND then
                to_org_prev_ent_count := 0;
        end;

        begin
            select id
            into group_type
            from rhnServerGroupType
            where label = group_label_in;
        exception
            when NO_DATA_FOUND then
                rhn_exception.raise_exception(
                              'invalid_server_group');
        end;

        new_ent_count := prev_ent_count - quantity_in;

        if prev_ent_count > new_ent_count then
            new_quantity := to_org_prev_ent_count + quantity_in;
        end if;

        if new_ent_count < 0 then
            rhn_exception.raise_exception(
                          'not_enough_entitlements_in_base_org');
        end if;


        rhn_entitlements.set_group_count(from_org_id_in,
                                         'S',
                                         group_type,
                                         new_ent_count);

        rhn_entitlements.set_group_count(to_org_id_in,
                                         'S',
                                         group_type,
                                         new_quantity);
        
        -- Create or delete the entries in rhnOrgEntitlementType
        if group_label_in = 'enterprise_entitled' then 
            if new_quantity > 0 then
                set_customer_enterprise(to_org_id_in);
            else
                unset_customer_enterprise(to_org_id_in);
            end if;
        end if;

        if group_label_in = 'provisioning_entitled' then
            if new_quantity > 0 then
                set_customer_provisioning(to_org_id_in);
            else
                unset_customer_provisioning(to_org_id_in);
            end if;
        end if;

        if group_label_in = 'monitoring_entitled' then
            if new_quantity > 0 then
                set_customer_monitoring(to_org_id_in);
            else
                unset_customer_monitoring(to_org_id_in);
            end if;
        end if;

    end assign_system_entitlement;

    -- *******************************************************************
    -- PROCEDURE: assign_channel_entitlement
    --
    -- Moves channel entitlements from from_org_id_in to to_org_id_in.
    -- Can raise not_enough_entitlements_in_base_org if from_org_id_in
    -- does not have enough entitlements to cover the move.
    -- Takes care of unentitling systems if necessary by calling 
    -- set_family_count
    -- *******************************************************************
    procedure assign_channel_entitlement(
        channel_family_label_in in varchar2,
        from_org_id_in in number,
        to_org_id_in in number,
        quantity_in in number,
        flex_in in number
    )
    is
        from_org_prev_ent_count number;
        from_org_prev_ent_count_flex number;
        new_ent_count number;
        new_ent_count_flex number;
        to_org_prev_ent_count number;
        to_org_prev_ent_count_flex number;
        new_quantity number;
        new_flex number;
        cfam_id       number;
    begin

        begin
            select max_members
            into from_org_prev_ent_count
            from rhnChannelFamily cf,
                 rhnPrivateChannelFamily pcf
            where pcf.org_id = from_org_id_in
              and pcf.channel_family_id = cf.id
              and cf.label = channel_family_label_in;
        exception
            when NO_DATA_FOUND then
                rhn_exception.raise_exception(
                              'not_enough_entitlements_in_base_org');
        end;

        begin
            select max_members
            into to_org_prev_ent_count
            from rhnChannelFamily cf,
                 rhnPrivateChannelFamily pcf
            where pcf.org_id = to_org_id_in
              and pcf.channel_family_id = cf.id
              and cf.label = channel_family_label_in;
        exception
            when NO_DATA_FOUND then
                to_org_prev_ent_count := 0;
        end;

        begin
            select fve_max_members
            into from_org_prev_ent_count_flex
            from rhnChannelFamily cf,
                 rhnPrivateChannelFamily pcf
            where pcf.org_id = from_org_id_in
              and pcf.channel_family_id = cf.id
              and cf.label = channel_family_label_in;
        exception
            when NO_DATA_FOUND then
                rhn_exception.raise_exception(
                              'not_enough_flex_entitlements_in_base_org');
        end;

        begin
            select fve_max_members
            into to_org_prev_ent_count_flex
            from rhnChannelFamily cf,
                 rhnPrivateChannelFamily pcf
            where pcf.org_id = to_org_id_in
              and pcf.channel_family_id = cf.id
              and cf.label = channel_family_label_in;
        exception
            when NO_DATA_FOUND then
                to_org_prev_ent_count_flex := 0;
        end;

        begin
            select id
            into cfam_id
            from rhnChannelFamily
            where label = channel_family_label_in;
        exception
            when NO_DATA_FOUND then
                rhn_exception.raise_exception(
                              'invalid_channel_family');
        end;

        new_ent_count := from_org_prev_ent_count - quantity_in;
        new_ent_count_flex := from_org_prev_ent_count_flex - flex_in;

        if from_org_prev_ent_count >= new_ent_count then
            new_quantity := to_org_prev_ent_count + quantity_in;
       end if;

       if from_org_prev_ent_count_flex >= new_ent_count_flex then
            new_flex := to_org_prev_ent_count_flex + flex_in;
       end if;


        if new_ent_count < 0 then
            rhn_exception.raise_exception(
                          'not_enough_entitlements_in_base_org');
        end if;

        if new_ent_count_flex < 0 then
            rhn_exception.raise_exception(
                          'not_enough_flex_entitlements_in_base_org');
        end if;



        rhn_entitlements.set_family_count(from_org_id_in, cfam_id,
                                           new_ent_count, new_ent_count_flex);

        rhn_entitlements.set_family_count(to_org_id_in,
                                          cfam_id,
                                          new_quantity, new_flex);

    end assign_channel_entitlement;

    -- *******************************************************************
    -- PROCEDURE: activate_system_entitlement
    --
    -- Sets the values in rhnServerGroup for a given rhnServerGroupType.
    -- 
    -- Calls: set_group_count to update, prune, or create the group.
    -- Called by: the code that activates a satellite cert. 
    --
    -- Raises not_enough_entitlements_in_base_org if all entitlements
    -- in the org are used so the free entitlements would not cover
    -- the difference when descreasing the number of entitlements.
    -- *******************************************************************
    procedure activate_system_entitlement(
        org_id_in in number,
        group_label_in in varchar2,
        quantity_in in number
    )
    is
        prev_ent_count number; 
        prev_ent_count_sum number; 
        group_type number;
    begin

        -- Fetch the current entitlement count for the org
        -- into prev_ent_count
        begin
            select current_members
            into prev_ent_count
            from rhnServerGroupType sgt,
                 rhnServerGroup sg
            where sg.group_type = sgt.id
              and sgt.label = group_label_in
              and sg.org_id = org_id_in;
        exception
            when NO_DATA_FOUND then
                prev_ent_count := 0;
        end;

        begin
            select id
            into group_type
            from rhnServerGroupType
            where label = group_label_in;
        exception
            when NO_DATA_FOUND then
                rhn_exception.raise_exception(
                              'invalid_server_group');
        end;

        -- If we're setting the total entitlemnt count to a lower value,
        -- and that value is less than the allocated count in this org,
        -- we need to raise an exception.
        if quantity_in < prev_ent_count then
            rhn_exception.raise_exception(
                          'not_enough_entitlements_in_base_org');
        else
            -- don't update family counts after every server
            -- will do bulk update afterwards
            rhn_entitlements.set_group_count(org_id_in,
                                             'S',
                                             group_type,
                                             quantity_in,
                                             update_family_countsYN => 0);
            -- bulk update family counts
            rhn_channel.update_group_family_counts(group_label_in, org_id_in);
        end if;


    end activate_system_entitlement;

    -- *******************************************************************
    -- PROCEDURE: activate_channel_entitlement
    --
    -- Calls: set_family_count to update, prune, or create the family
    --        permission bucket.
    -- Called by: the code that activates a satellite cert. 
    --
    -- Raises not_enough_entitlements_in_base_org if there are not enough
    -- entitlements in the org to cover the difference when you are
    -- descreasing the number of entitlements.
    --
    -- The backend code in Python is expected to do whatever arithmetics
    -- is needed.
    -- *******************************************************************
    procedure activate_channel_entitlement(
        org_id_in in number,
        channel_family_label_in in varchar2,
        quantity_in in number,
        flex_in in number

    )
    is
        prev_ent_count number; 
        prev_flex_count number;
        prev_ent_count_sum number; 
        cfam_id number;
        reduce_quantity number;
        total_flex_capable number;
        cursor to_convert_reg (channel_family_id_val in number, org_id_in in number, quantity in number) 
                is
                     select SC.server_id
                     from rhnServerChannel SC inner join
                          rhnServer S on S.id = SC.server_id
                     where
                         is_fve = 'Y'
                         and S.org_id = org_id_in 
                         and SC.channel_id in
                         (select cfm.channel_id from rhnChannelFamilyMembers cfm
                             where cfm.CHANNEL_FAMILY_ID = channel_family_id_val)
                          and rownum <= quantity;
         cursor to_convert_flex (channel_family_id_val in number, org_id_in in number, quantity in number)
                 is
                   select server_id
                   from rhnServerFveCapable
                       where SERVER_ORG_ID = org_id_in and
                             channel_family_id = cfam_id;

    begin

        -- Fetch the current entitlement count for the org
        -- into prev_ent_count
        begin
            select current_members
            into prev_ent_count
            from rhnChannelFamily cf,
                 rhnPrivateChannelFamily pcf
            where pcf.org_id = org_id_in
              and pcf.channel_family_id = cf.id
              and cf.label = channel_family_label_in;
        exception
            when NO_DATA_FOUND then
                prev_ent_count := 0;
        end;

        begin
            select pcf.fve_current_members
            into prev_flex_count
            from rhnChannelFamily cf,
                 rhnPrivateChannelFamily pcf
            where pcf.org_id = org_id_in
              and pcf.channel_family_id = cf.id
              and cf.label = channel_family_label_in;
        exception
            when NO_DATA_FOUND then
                prev_flex_count := 0;
        end;


        begin
            select id
            into cfam_id
            from rhnChannelFamily
            where label = channel_family_label_in;
        exception
            when NO_DATA_FOUND then
                rhn_exception.raise_exception(
                              'invalid_channel_family');
        end;                              

        -- if there are too few flex entitlements
        if flex_in < prev_flex_count then
            -- and if the extra we need is less than or equal to our extra regular entitlements
            if prev_flex_count - flex_in <= quantity_in - prev_ent_count then
                   reduce_quantity := prev_flex_count - flex_in;
                   -- We need to convert some systems from flex guest to regular
                   for system in to_convert_reg(cfam_id, org_id_in, reduce_quantity) loop
                      --rhn_channel.convert_to_regular(system.server_id, cfam_id);
                      UPDATE rhnServerChannel sc set sc.is_fve = 'N'
                           where sc.server_id = system.server_id;
                   end loop;

                   --reset previous counts 
                   prev_ent_count := prev_ent_count + reduce_quantity;
                   prev_flex_count := prev_flex_count - reduce_quantity; 
            else
                rhn_exception.raise_exception(
                          'not_enough_flex_entitlements_in_base_org');
            end if;
        end if;

        -- if there are too few regular entitlements, and extra flex entitlements
        if quantity_in < prev_ent_count and prev_flex_count < flex_in then
                -- how many flex-capable systems (that aren't using flex) do we have
                select count(*)
                   into total_flex_capable 
                   from rhnServerFveCapable
                       where SERVER_ORG_ID = org_id_in and
                             channel_family_id = cfam_id;
                -- if we have enough flex capable machines that is at least 
                --   as many as what we are over on 
                if total_flex_capable >= prev_ent_count - quantity_in then
                    reduce_quantity := prev_ent_count - quantity_in;
                    for system in to_convert_flex(cfam_id, org_id_in, reduce_quantity) loop 
--                          rhn_channel.convert_to_fve(system.server_id, cfam_id);
                        UPDATE rhnServerChannel sc set sc.is_fve = 'Y'
                           where sc.server_id = system.server_id;
                    end loop;
                    prev_ent_count := prev_ent_count - reduce_quantity;
                    prev_flex_count := prev_flex_count + reduce_quantity;
                end if; 
        end if;




        -- If we're setting the total entitlemnt count to a lower value,
        -- and that value is less than the count in that one org,
        -- we need to raise an exception.
        if quantity_in < prev_ent_count then
            rhn_exception.raise_exception(
                          'not_enough_entitlements_in_base_org');
        else
            -- even if we've manually converted systems to/from flex above
            -- set_family_count should call update_family_counts, to reset
            -- current used slots
            rhn_entitlements.set_family_count(org_id_in, cfam_id,
                                              quantity_in, flex_in);
        end if;

    end activate_channel_entitlement;


    procedure set_group_count (
        customer_id_in in number,
        type_in in char,
        group_type_in in number,
        quantity_in in number,
                update_family_countsYN in number := 1
    ) is
        group_id number;
        quantity number;
    begin
        quantity := quantity_in;
        if quantity is not null and quantity < 0 then
            quantity := 0;
        end if;

        if type_in = 'U' then
            select    rug.id
            into    group_id
            from    rhnUserGroup rug
            where    1=1
                and rug.org_id = customer_id_in
                and rug.group_type = group_type_in;
        elsif type_in = 'S' then
            select    rsg.id
            into    group_id
            from    rhnServerGroup rsg
            where    1=1
                and rsg.org_id = customer_id_in
                and rsg.group_type = group_type_in;
        end if;

        rhn_entitlements.prune_group(
            group_id,
            type_in,
            quantity,
                        update_family_countsYN
        );
    exception
        when no_data_found then
            if type_in = 'U' then
                insert into rhnUserGroup (
                        id, name, description, max_members, current_members,
                        group_type, org_id, created, modified
                    ) (
                        select    rhn_user_group_id_seq.nextval, name, name,
                                quantity, 0, id, customer_id_in,
                                sysdate, sysdate
                        from    rhnUserGroupType
                        where    id = group_type_in
                );
            elsif type_in = 'S' then
                insert into rhnServerGroup (
                        id, name, description, max_members, current_members,
                        group_type, org_id, created, modified
                    ) (
                        select    rhn_server_group_id_seq.nextval, name, name,
                                quantity, 0, id, customer_id_in,
                                sysdate, sysdate
                        from    rhnServerGroupType
                        where    id = group_type_in
                );
            end if;
    end set_group_count;

    -- *******************************************************************
    -- PROCEDURE: prune_family
    -- Unsubscribes servers consuming physical slots from the channel family 
    --   that are over the org's limit.
    -- Called by: set_family_count
    -- *******************************************************************
    procedure prune_family (
        customer_id_in in number,
        channel_family_id_in in number,
        quantity_in in number,
        flex_in in number
    ) is
       is_fve_in char;
       tmp_quantity number;

        cursor serverchannels is
            select    sc.server_id,
                    sc.channel_id
            from    rhnServerChannel sc,
                    rhnChannelFamilyMembers cfm
            where    1=1
                and cfm.channel_family_id = channel_family_id_in
                and cfm.channel_id = sc.channel_id
                and server_id in (
                    select    server_id
                      from    (
                        select server_id, time, rownum row_number
                        from    (
                            select rs.id  server_id, rcfm.modified time
                            from    rhnServerChannel         rsc,
                                    rhnChannelFamilyMembers  rcfm,
                                    rhnServer                rs
                            where    1=1
                                and rs.org_id = customer_id_in
                                and rs.id = rsc.server_id
                                and rsc.channel_id = rcfm.channel_id
                                and rcfm.channel_family_id =  channel_family_id_in
                                and rsc.is_fve = is_fve_in
                                -- we only want to grab servers consuming
                                -- physical slots.
                                and exists (
                                    select 1
                                    from rhnChannelFamilyServerPhysical cfsp
                                    where cfsp.server_id = rs.id
                                    and cfsp.channel_family_id = 
                                        channel_family_id_in
                                    )
                            order by time asc
                        )
                    )
                    where row_number > tmp_quantity
                );
    begin
        -- if we get a null customer_id, this is completely bogus.
        if customer_id_in is null then
            return;
        end if;

        tmp_quantity := quantity_in;
        is_fve_in := 'N';

        for sc in serverchannels loop
            rhn_channel.unsubscribe_server(sc.server_id, sc.channel_id, 1, 1,
                                                       update_family_countsYN => 0);

        tmp_quantity := flex_in;
        is_fve_in := 'Y';
        for sc in serverchannels loop
            rhn_channel.unsubscribe_server(sc.server_id, sc.channel_id, 1, 1,
                                                        update_family_countsYN => 0);
        end loop;



        end loop;
                rhn_channel.update_family_counts(channel_family_id_in, customer_id_in);
    end prune_family;

    procedure set_family_count (
        customer_id_in in number,
        channel_family_id_in in number,
        quantity_in in number,
        flex_in in number
    ) is
        cursor privperms is
            select    1
            from    rhnPrivateChannelFamily
            where    org_id = customer_id_in
                and channel_family_id = channel_family_id_in;
        cursor pubperms is
            select    o.id org_id
            from    web_customer o,
                    rhnPublicChannelFamily pcf
            where    pcf.channel_family_id = channel_family_id_in;
        quantity number;
        done number := 0;
        flex number;
    begin
        quantity := quantity_in;
        if quantity is not null and quantity < 0 then
            quantity := 0;
        end if;
        flex := flex_in;
        if flex is not null and flex < 0 then
            flex := 0;
        end if;


        if customer_id_in is not null then
            for perm in privperms loop
                rhn_entitlements.prune_family(customer_id_in, channel_family_id_in,
                    quantity, flex);

               update rhnPrivateChannelFamily
                    set max_members = quantity
                    where org_id = customer_id_in
                        and channel_family_id = channel_family_id_in;

               update rhnPrivateChannelFamily
                    set fve_max_members = flex
                    where org_id = customer_id_in
                        and channel_family_id = channel_family_id_in;

                return;
            end loop;

            insert into rhnPrivateChannelFamily (
                    channel_family_id, org_id, max_members, current_members, fve_max_members, fve_current_members
                ) values (
                    channel_family_id_in, customer_id_in, quantity, 0, flex, 0 );
            return;
        end if;

        for perm in pubperms loop
            if quantity = 0 then
                rhn_entitlements.prune_family(
                    perm.org_id,
                    channel_family_id_in,
                    quantity,
                    flex
                );
                if done = 0 then
                    delete from rhnPublicChannelFamily
                        where channel_family_id = channel_family_id_in;
                end if;
            end if;
            done := 1;
        end loop;
        -- if done's not 1, then we don't have any entitlements
        if done != 1 then
            insert into rhnPublicChannelFamily (
                    channel_family_id
                ) values (
                    channel_family_id_in
                );
        end if;
    end set_family_count;

    -- this expects quantity_in to be the number of available slots, not the
    -- max_members of the server group.  If you give it too many, it'll fail
    -- and raise servergroup_max_members.
    -- We should NEVER run this unless we're SURE that we won't
    -- be violating the max.
    procedure entitle_last_modified_servers (
        customer_id_in in number,
        type_label_in in varchar2,
        quantity_in in number
    ) is
        -- find the servers that aren't currently in slots
        cursor servers(cid_in in number, quant_in in number) is
            select    server_id
            from    (
                        select    rownum row_number,
                                server_id
                        from    (
                                    select    rs.id server_iD
                                    from    rhnServer rs
                                    where    1=1
                                        and rs.org_id = cid_in
                                        and not exists (
                                            select    1
                                            from    rhnServerGroup sg,
                                                    rhnServerGroupMembers rsgm
                                            where    rsgm.server_id = rs.id
                                                and rsgm.server_group_id = sg.id
                                                and sg.group_type is not null
                                        )
                                        and not exists (
                                            select 1
                                            from rhnVirtualInstance vi
                                            where vi.virtual_system_id =
                                                  rs.id
                                        )                                                                           order by modified desc
                                )
                    )
            where    row_number <= quant_in;
    begin
        for server in servers(customer_id_in, quantity_in) loop
            rhn_entitlements.entitle_server(server.server_id, type_label_in);
        end loop;
    end entitle_last_modified_servers;

    procedure subscribe_newest_servers (
        customer_id_in in number
    ) is
        -- find servers without base channels
        cursor servers(cid_in in number) is
            select    s.id
            from    rhnServer            s
            where    1=1
                and s.org_id = cid_in
                and not exists (
                        select 1
                        from    rhnChannel            c,
                                rhnServerChannel    sc
                        where    sc.server_id = s.id
                            and sc.channel_id = c.id
                            and c.parent_channel is null
                    )
                and not exists (
                        select 1
                        from rhnVirtualInstance vi
                        where vi.virtual_system_id = s.id
                    )                        
            order by s.modified desc;
        channel_id number;
    begin
        for server in servers(customer_id_in) loop
            channel_id := rhn_channel.guess_server_base(server.id);
            if channel_id is not null then
                begin
                    rhn_channel.subscribe_server(server.id, channel_id);
                    commit;
                -- exception is really channel_family_no_subscriptions
                exception
                    when others then
                        null;
                end;
            end if;
        end loop;
    end subscribe_newest_servers;
end rhn_entitlements;
/
show errors

0707010000059D000081B400000000000000000000000167AE1114000003E7000000000000000000000000000000000000005E00000000susemanager-schema/upgrade/spacewalk-schema-1.1-to-spacewalk-schema-1.2/093-rhn_exception.sql --
-- Copyright (c) 2008--2010 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--

CREATE OR REPLACE
PACKAGE rhn_exception
IS
    PROCEDURE raise_exception(exception_label_in IN VARCHAR2);
    procedure raise_exception_val(
	exception_label_in in varchar2,
        val_in in number
    );
    PROCEDURE lookup_exception(exception_label_in IN VARCHAR2, exception_id_out OUT NUMBER, exception_message_out OUT VARCHAR2);
END rhn_exception;
/
SHOW ERRORS

 0707010000059E000081B400000000000000000000000167AE111400000941000000000000000000000000000000000000006300000000susemanager-schema/upgrade/spacewalk-schema-1.1-to-spacewalk-schema-1.2/094-rhn_exception-body.sql    --
-- Copyright (c) 2008--2010 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--

CREATE OR REPLACE
PACKAGE BODY rhn_exception
IS

    PROCEDURE lookup_exception(exception_label_in IN VARCHAR2, exception_id_out OUT NUMBER, exception_message_out OUT VARCHAR2)
    IS
        return_string     VARCHAR2(2000);
    BEGIN
        FOR exc IN (
            SELECT id, label, message
              FROM rhnException
             WHERE label = exception_label_in
        )
        LOOP
            exception_id_out := exc.id;
            exception_message_out := '(' || exc.label || ')' || ' - ' || exc.message;
        END LOOP exception_details;

        IF exception_message_out IS NULL
        THEN
            RAISE NO_DATA_FOUND;
        END IF;

    END lookup_exception;
    
    PROCEDURE raise_exception(exception_label_in IN VARCHAR2)
    IS
        exception_id        NUMBER;
        exception_message   VARCHAR2(2000);
    BEGIN
        lookup_exception(exception_label_in, exception_id, exception_message);
        RAISE_APPLICATION_ERROR(exception_id, exception_message);    
    EXCEPTION
        WHEN NO_DATA_FOUND
        THEN
        RAISE_APPLICATION_ERROR(-20001, 'Unable to lookup exception with label (' || exception_label_in || ')');    
    END raise_exception;

    procedure raise_exception_val(
	exception_label_in in varchar2,
	val_in in number
    ) is
	exception_id        NUMBER;
	exception_message   VARCHAR2(2000);
    begin
	lookup_exception(exception_label_in, exception_id, exception_message);
	RAISE_APPLICATION_ERROR(exception_id, exception_message || ' (' || val_in || ')');
    exception
	when no_data_found then
	RAISE_APPLICATION_ERROR(-20001, 'Unable to lookup exception with label (' || exception_label_in || ')');
    end raise_exception_val;
    
END rhn_exception;
/
SHOW ERRORS

   0707010000059F000081B400000000000000000000000167AE1114000002ED000000000000000000000000000000000000006F00000000susemanager-schema/upgrade/spacewalk-schema-1.1-to-spacewalk-schema-1.2/100-rhnActionType-proxy.deactivate.sql    --
-- Copyright (c) 2010 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--

update rhnActionType set name = 'Deactivate Proxy' where label = 'proxy.deactivate' and name <> 'Deactivate Proxy';
commit;

   070701000005A0000081B400000000000000000000000167AE111400000313000000000000000000000000000000000000006600000000susemanager-schema/upgrade/spacewalk-schema-1.1-to-spacewalk-schema-1.2/101-rhnKSInstallType_data.sql --
-- Copyright (c) 2010 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

 insert into rhnKSInstallType (id, label, name)
         values (rhn_ksinstalltype_id_seq.nextval,
                'rhel_6','Red Hat Enterprise Linux 6'
        );

 070701000005A1000081B400000000000000000000000167AE1114000171F7000000000000000000000000000000000000006A00000000susemanager-schema/upgrade/spacewalk-schema-1.1-to-spacewalk-schema-1.2/102-rhnKickstartTimeZone_data.sql --
-- Copyright (c) 2010--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--


-- RHEL 6  timezones

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Europe/Andorra',
	    	'Europe/Andorra',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Asia/Dubai',
	    	'Asia/Dubai',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Asia/Kabul',
	    	'Asia/Kabul',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'America/Antigua',
	    	'America/Antigua',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'America/Anguilla',
	    	'America/Anguilla',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Europe/Tirane',
	    	'Europe/Tirane',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Asia/Yerevan',
	    	'Asia/Yerevan',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'America/Curacao',
	    	'America/Curacao',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Africa/Luanda',
	    	'Africa/Luanda',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Antarctica/McMurdo',
	    	'Antarctica/McMurdo',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Antarctica/South_Pole',
	    	'Antarctica/South_Pole',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Antarctica/Palmer',
	    	'Antarctica/Palmer',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Antarctica/Mawson',
	    	'Antarctica/Mawson',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Antarctica/Davis',
	    	'Antarctica/Davis',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Antarctica/Casey',
	    	'Antarctica/Casey',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Antarctica/Vostok',
	    	'Antarctica/Vostok',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Antarctica/DumontDUrville',
	    	'Antarctica/DumontDUrville',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Antarctica/Syowa',
	    	'Antarctica/Syowa',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'America/Buenos_Aires',
	    	'America/Buenos_Aires',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'America/Cordoba',
	    	'America/Cordoba',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'America/Jujuy',
	    	'America/Jujuy',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'America/Catamarca',
	    	'America/Catamarca',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'America/Mendoza',
	    	'America/Mendoza',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Pacific/Pago_Pago',
	    	'Pacific/Pago_Pago',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Europe/Vienna',
	    	'Europe/Vienna',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Australia/Lord_Howe',
	    	'Australia/Lord_Howe',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Australia/Hobart',
	    	'Australia/Hobart',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Australia/Melbourne',
	    	'Australia/Melbourne',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Australia/Sydney',
	    	'Australia/Sydney',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Australia/Broken_Hill',
	    	'Australia/Broken_Hill',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Australia/Brisbane',
	    	'Australia/Brisbane',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Australia/Lindeman',
	    	'Australia/Lindeman',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Australia/Adelaide',
	    	'Australia/Adelaide',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Australia/Darwin',
	    	'Australia/Darwin',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Australia/Perth',
	    	'Australia/Perth',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'America/Aruba',
	    	'America/Aruba',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Asia/Baku',
	    	'Asia/Baku',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Europe/Sarajevo',
	    	'Europe/Sarajevo',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'America/Barbados',
	    	'America/Barbados',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Asia/Dhaka',
	    	'Asia/Dhaka',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Europe/Brussels',
	    	'Europe/Brussels',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Africa/Ouagadougou',
	    	'Africa/Ouagadougou',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Europe/Sofia',
	    	'Europe/Sofia',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Asia/Bahrain',
	    	'Asia/Bahrain',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Africa/Bujumbura',
	    	'Africa/Bujumbura',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Africa/Porto-Novo',
	    	'Africa/Porto-Novo',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Atlantic/Bermuda',
	    	'Atlantic/Bermuda',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Asia/Brunei',
	    	'Asia/Brunei',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'America/La_Paz',
	    	'America/La_Paz',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'America/Noronha',
	    	'America/Noronha',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'America/Belem',
	    	'America/Belem',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'America/Fortaleza',
	    	'America/Fortaleza',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'America/Recife',
	    	'America/Recife',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'America/Araguaina',
	    	'America/Araguaina',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'America/Maceio',
	    	'America/Maceio',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'America/Sao_Paulo',
	    	'America/Sao_Paulo',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'America/Cuiaba',
	    	'America/Cuiaba',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'America/Porto_Velho',
	    	'America/Porto_Velho',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'America/Boa_Vista',
	    	'America/Boa_Vista',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'America/Manaus',
	    	'America/Manaus',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'America/Eirunepe',
	    	'America/Eirunepe',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'America/Rio_Branco',
	    	'America/Rio_Branco',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'America/Nassau',
	    	'America/Nassau',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Asia/Thimphu',
	    	'Asia/Thimphu',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Africa/Gaborone',
	    	'Africa/Gaborone',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Europe/Minsk',
	    	'Europe/Minsk',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'America/Belize',
	    	'America/Belize',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'America/St_Johns',
	    	'America/St_Johns',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'America/Halifax',
	    	'America/Halifax',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'America/Glace_Bay',
	    	'America/Glace_Bay',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'America/Goose_Bay',
	    	'America/Goose_Bay',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'America/Montreal',
	    	'America/Montreal',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'America/Nipigon',
	    	'America/Nipigon',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'America/Thunder_Bay',
	    	'America/Thunder_Bay',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'America/Pangnirtung',
	    	'America/Pangnirtung',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'America/Iqaluit',
	    	'America/Iqaluit',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'America/Rankin_Inlet',
	    	'America/Rankin_Inlet',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'America/Winnipeg',
	    	'America/Winnipeg',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'America/Rainy_River',
	    	'America/Rainy_River',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'America/Cambridge_Bay',
	    	'America/Cambridge_Bay',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'America/Regina',
	    	'America/Regina',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'America/Swift_Current',
	    	'America/Swift_Current',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'America/Edmonton',
	    	'America/Edmonton',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'America/Yellowknife',
	    	'America/Yellowknife',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'America/Inuvik',
	    	'America/Inuvik',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'America/Dawson_Creek',
	    	'America/Dawson_Creek',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'America/Vancouver',
	    	'America/Vancouver',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'America/Whitehorse',
	    	'America/Whitehorse',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'America/Dawson',
	    	'America/Dawson',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Indian/Cocos',
	    	'Indian/Cocos',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Africa/Kinshasa',
	    	'Africa/Kinshasa',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Africa/Lubumbashi',
	    	'Africa/Lubumbashi',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Africa/Bangui',
	    	'Africa/Bangui',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Africa/Brazzaville',
	    	'Africa/Brazzaville',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Europe/Zurich',
	    	'Europe/Zurich',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Africa/Abidjan',
	    	'Africa/Abidjan',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Pacific/Rarotonga',
	    	'Pacific/Rarotonga',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'America/Santiago',
	    	'America/Santiago',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Pacific/Easter',
	    	'Pacific/Easter',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Africa/Douala',
	    	'Africa/Douala',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Asia/Shanghai',
	    	'Asia/Shanghai',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Asia/Harbin',
	    	'Asia/Harbin',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Asia/Chongqing',
	    	'Asia/Chongqing',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Asia/Urumqi',
	    	'Asia/Urumqi',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Asia/Kashgar',
	    	'Asia/Kashgar',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'America/Bogota',
	    	'America/Bogota',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'America/Costa_Rica',
	    	'America/Costa_Rica',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'America/Havana',
	    	'America/Havana',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Atlantic/Cape_Verde',
	    	'Atlantic/Cape_Verde',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Indian/Christmas',
	    	'Indian/Christmas',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Asia/Nicosia',
	    	'Asia/Nicosia',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Europe/Prague',
	    	'Europe/Prague',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Europe/Berlin',
	    	'Europe/Berlin',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Africa/Djibouti',
	    	'Africa/Djibouti',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Europe/Copenhagen',
	    	'Europe/Copenhagen',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'America/Dominica',
	    	'America/Dominica',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'America/Santo_Domingo',
	    	'America/Santo_Domingo',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Africa/Algiers',
	    	'Africa/Algiers',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'America/Guayaquil',
	    	'America/Guayaquil',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Pacific/Galapagos',
	    	'Pacific/Galapagos',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Europe/Tallinn',
	    	'Europe/Tallinn',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Africa/Cairo',
	    	'Africa/Cairo',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Africa/El_Aaiun',
	    	'Africa/El_Aaiun',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Africa/Asmera',
	    	'Africa/Asmera',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Europe/Madrid',
	    	'Europe/Madrid',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Africa/Ceuta',
	    	'Africa/Ceuta',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Atlantic/Canary',
	    	'Atlantic/Canary',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Africa/Addis_Ababa',
	    	'Africa/Addis_Ababa',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Europe/Helsinki',
	    	'Europe/Helsinki',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Pacific/Fiji',
	    	'Pacific/Fiji',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Atlantic/Stanley',
	    	'Atlantic/Stanley',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Pacific/Yap',
	    	'Pacific/Yap',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Pacific/Truk',
	    	'Pacific/Truk',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Pacific/Ponape',
	    	'Pacific/Ponape',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Pacific/Kosrae',
	    	'Pacific/Kosrae',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Atlantic/Faeroe',
	    	'Atlantic/Faeroe',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Europe/Paris',
	    	'Europe/Paris',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Africa/Libreville',
	    	'Africa/Libreville',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Europe/London',
	    	'Europe/London',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Europe/Belfast',
	    	'Europe/Belfast',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'America/Grenada',
	    	'America/Grenada',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Asia/Tbilisi',
	    	'Asia/Tbilisi',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'America/Cayenne',
	    	'America/Cayenne',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Africa/Accra',
	    	'Africa/Accra',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Europe/Gibraltar',
	    	'Europe/Gibraltar',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'America/Godthab',
	    	'America/Godthab',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'America/Danmarkshavn',
	    	'America/Danmarkshavn',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'America/Scoresbysund',
	    	'America/Scoresbysund',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'America/Thule',
	    	'America/Thule',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Africa/Banjul',
	    	'Africa/Banjul',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Africa/Conakry',
	    	'Africa/Conakry',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'America/Guadeloupe',
	    	'America/Guadeloupe',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Africa/Malabo',
	    	'Africa/Malabo',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Europe/Athens',
	    	'Europe/Athens',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Atlantic/South_Georgia',
	    	'Atlantic/South_Georgia',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'America/Guatemala',
	    	'America/Guatemala',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Pacific/Guam',
	    	'Pacific/Guam',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Africa/Bissau',
	    	'Africa/Bissau',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'America/Guyana',
	    	'America/Guyana',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Asia/Hong_Kong',
	    	'Asia/Hong_Kong',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'America/Tegucigalpa',
	    	'America/Tegucigalpa',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Europe/Zagreb',
	    	'Europe/Zagreb',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'America/Port-au-Prince',
	    	'America/Port-au-Prince',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Europe/Budapest',
	    	'Europe/Budapest',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Asia/Jakarta',
	    	'Asia/Jakarta',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Asia/Pontianak',
	    	'Asia/Pontianak',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Asia/Makassar',
	    	'Asia/Makassar',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Asia/Jayapura',
	    	'Asia/Jayapura',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Europe/Dublin',
	    	'Europe/Dublin',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Asia/Jerusalem',
	    	'Asia/Jerusalem',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Asia/Calcutta',
	    	'Asia/Calcutta',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Indian/Chagos',
	    	'Indian/Chagos',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Asia/Baghdad',
	    	'Asia/Baghdad',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Asia/Tehran',
	    	'Asia/Tehran',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Atlantic/Reykjavik',
	    	'Atlantic/Reykjavik',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Europe/Rome',
	    	'Europe/Rome',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'America/Jamaica',
	    	'America/Jamaica',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Asia/Amman',
	    	'Asia/Amman',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Asia/Tokyo',
	    	'Asia/Tokyo',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Africa/Nairobi',
	    	'Africa/Nairobi',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Asia/Bishkek',
	    	'Asia/Bishkek',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Asia/Phnom_Penh',
	    	'Asia/Phnom_Penh',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Pacific/Tarawa',
	    	'Pacific/Tarawa',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Pacific/Enderbury',
	    	'Pacific/Enderbury',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Pacific/Kiritimati',
	    	'Pacific/Kiritimati',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Indian/Comoro',
	    	'Indian/Comoro',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'America/St_Kitts',
	    	'America/St_Kitts',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Asia/Pyongyang',
	    	'Asia/Pyongyang',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Asia/Seoul',
	    	'Asia/Seoul',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Asia/Kuwait',
	    	'Asia/Kuwait',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'America/Cayman',
	    	'America/Cayman',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Asia/Almaty',
	    	'Asia/Almaty',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Asia/Qyzylorda',
	    	'Asia/Qyzylorda',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Asia/Aqtobe',
	    	'Asia/Aqtobe',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Asia/Aqtau',
	    	'Asia/Aqtau',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Asia/Oral',
	    	'Asia/Oral',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Asia/Vientiane',
	    	'Asia/Vientiane',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Asia/Beirut',
	    	'Asia/Beirut',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'America/St_Lucia',
	    	'America/St_Lucia',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Europe/Vaduz',
	    	'Europe/Vaduz',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Asia/Colombo',
	    	'Asia/Colombo',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Africa/Monrovia',
	    	'Africa/Monrovia',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Africa/Maseru',
	    	'Africa/Maseru',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Europe/Vilnius',
	    	'Europe/Vilnius',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Europe/Luxembourg',
	    	'Europe/Luxembourg',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Europe/Riga',
	    	'Europe/Riga',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Africa/Tripoli',
	    	'Africa/Tripoli',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Africa/Casablanca',
	    	'Africa/Casablanca',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Europe/Monaco',
	    	'Europe/Monaco',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Europe/Chisinau',
	    	'Europe/Chisinau',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Indian/Antananarivo',
	    	'Indian/Antananarivo',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Pacific/Majuro',
	    	'Pacific/Majuro',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Pacific/Kwajalein',
	    	'Pacific/Kwajalein',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Europe/Skopje',
	    	'Europe/Skopje',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Africa/Bamako',
	    	'Africa/Bamako',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Africa/Timbuktu',
	    	'Africa/Timbuktu',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Asia/Rangoon',
	    	'Asia/Rangoon',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Asia/Ulaanbaatar',
	    	'Asia/Ulaanbaatar',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Asia/Hovd',
	    	'Asia/Hovd',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Asia/Choibalsan',
	    	'Asia/Choibalsan',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Asia/Macau',
	    	'Asia/Macau',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Pacific/Saipan',
	    	'Pacific/Saipan',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'America/Martinique',
	    	'America/Martinique',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Africa/Nouakchott',
	    	'Africa/Nouakchott',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'America/Montserrat',
	    	'America/Montserrat',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Europe/Malta',
	    	'Europe/Malta',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Indian/Mauritius',
	    	'Indian/Mauritius',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Indian/Maldives',
	    	'Indian/Maldives',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Africa/Blantyre',
	    	'Africa/Blantyre',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'America/Mexico_City',
	    	'America/Mexico_City',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'America/Cancun',
	    	'America/Cancun',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'America/Merida',
	    	'America/Merida',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'America/Monterrey',
	    	'America/Monterrey',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'America/Mazatlan',
	    	'America/Mazatlan',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'America/Chihuahua',
	    	'America/Chihuahua',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'America/Hermosillo',
	    	'America/Hermosillo',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'America/Tijuana',
	    	'America/Tijuana',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Asia/Kuala_Lumpur',
	    	'Asia/Kuala_Lumpur',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Asia/Kuching',
	    	'Asia/Kuching',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Africa/Maputo',
	    	'Africa/Maputo',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Africa/Windhoek',
	    	'Africa/Windhoek',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Pacific/Noumea',
	    	'Pacific/Noumea',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Africa/Niamey',
	    	'Africa/Niamey',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Pacific/Norfolk',
	    	'Pacific/Norfolk',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Africa/Lagos',
	    	'Africa/Lagos',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'America/Managua',
	    	'America/Managua',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Europe/Amsterdam',
	    	'Europe/Amsterdam',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Europe/Oslo',
	    	'Europe/Oslo',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Asia/Katmandu',
	    	'Asia/Katmandu',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Pacific/Nauru',
	    	'Pacific/Nauru',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Pacific/Niue',
	    	'Pacific/Niue',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Pacific/Auckland',
	    	'Pacific/Auckland',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Pacific/Chatham',
	    	'Pacific/Chatham',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Asia/Muscat',
	    	'Asia/Muscat',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'America/Panama',
	    	'America/Panama',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'America/Lima',
	    	'America/Lima',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Pacific/Tahiti',
	    	'Pacific/Tahiti',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Pacific/Marquesas',
	    	'Pacific/Marquesas',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Pacific/Gambier',
	    	'Pacific/Gambier',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Pacific/Port_Moresby',
	    	'Pacific/Port_Moresby',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Asia/Manila',
	    	'Asia/Manila',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Asia/Karachi',
	    	'Asia/Karachi',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Europe/Warsaw',
	    	'Europe/Warsaw',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'America/Miquelon',
	    	'America/Miquelon',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Pacific/Pitcairn',
	    	'Pacific/Pitcairn',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'America/Puerto_Rico',
	    	'America/Puerto_Rico',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Asia/Gaza',
	    	'Asia/Gaza',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Europe/Lisbon',
	    	'Europe/Lisbon',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Atlantic/Madeira',
	    	'Atlantic/Madeira',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Atlantic/Azores',
	    	'Atlantic/Azores',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Pacific/Palau',
	    	'Pacific/Palau',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'America/Asuncion',
	    	'America/Asuncion',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Asia/Qatar',
	    	'Asia/Qatar',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Indian/Reunion',
	    	'Indian/Reunion',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Europe/Bucharest',
	    	'Europe/Bucharest',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Europe/Kaliningrad',
	    	'Europe/Kaliningrad',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Europe/Moscow',
	    	'Europe/Moscow',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Europe/Samara',
	    	'Europe/Samara',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Asia/Yekaterinburg',
	    	'Asia/Yekaterinburg',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Asia/Omsk',
	    	'Asia/Omsk',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Asia/Novosibirsk',
	    	'Asia/Novosibirsk',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Asia/Krasnoyarsk',
	    	'Asia/Krasnoyarsk',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Asia/Irkutsk',
	    	'Asia/Irkutsk',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Asia/Yakutsk',
	    	'Asia/Yakutsk',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Asia/Vladivostok',
	    	'Asia/Vladivostok',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Asia/Sakhalin',
	    	'Asia/Sakhalin',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Asia/Magadan',
	    	'Asia/Magadan',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Asia/Kamchatka',
	    	'Asia/Kamchatka',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Asia/Anadyr',
	    	'Asia/Anadyr',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Africa/Kigali',
	    	'Africa/Kigali',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Asia/Riyadh',
	    	'Asia/Riyadh',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Pacific/Guadalcanal',
	    	'Pacific/Guadalcanal',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Indian/Mahe',
	    	'Indian/Mahe',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Africa/Khartoum',
	    	'Africa/Khartoum',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Europe/Stockholm',
	    	'Europe/Stockholm',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Asia/Singapore',
	    	'Asia/Singapore',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Atlantic/St_Helena',
	    	'Atlantic/St_Helena',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Europe/Ljubljana',
	    	'Europe/Ljubljana',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Arctic/Longyearbyen',
	    	'Arctic/Longyearbyen',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Atlantic/Jan_Mayen',
	    	'Atlantic/Jan_Mayen',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Europe/Bratislava',
	    	'Europe/Bratislava',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Africa/Freetown',
	    	'Africa/Freetown',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Europe/San_Marino',
	    	'Europe/San_Marino',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Africa/Dakar',
	    	'Africa/Dakar',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Africa/Mogadishu',
	    	'Africa/Mogadishu',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'America/Paramaribo',
	    	'America/Paramaribo',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Africa/Sao_Tome',
	    	'Africa/Sao_Tome',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'America/El_Salvador',
	    	'America/El_Salvador',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Asia/Damascus',
	    	'Asia/Damascus',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Africa/Mbabane',
	    	'Africa/Mbabane',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'America/Grand_Turk',
	    	'America/Grand_Turk',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Africa/Ndjamena',
	    	'Africa/Ndjamena',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Indian/Kerguelen',
	    	'Indian/Kerguelen',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Africa/Lome',
	    	'Africa/Lome',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Asia/Bangkok',
	    	'Asia/Bangkok',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Asia/Dushanbe',
	    	'Asia/Dushanbe',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Pacific/Fakaofo',
	    	'Pacific/Fakaofo',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Asia/Ashgabat',
	    	'Asia/Ashgabat',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Africa/Tunis',
	    	'Africa/Tunis',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Pacific/Tongatapu',
	    	'Pacific/Tongatapu',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Asia/Dili',
	    	'Asia/Dili',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Europe/Istanbul',
	    	'Europe/Istanbul',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'America/Port_of_Spain',
	    	'America/Port_of_Spain',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Pacific/Funafuti',
	    	'Pacific/Funafuti',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Asia/Taipei',
	    	'Asia/Taipei',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Africa/Dar_es_Salaam',
	    	'Africa/Dar_es_Salaam',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Europe/Kiev',
	    	'Europe/Kiev',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Europe/Uzhgorod',
	    	'Europe/Uzhgorod',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Europe/Zaporozhye',
	    	'Europe/Zaporozhye',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Europe/Simferopol',
	    	'Europe/Simferopol',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Africa/Kampala',
	    	'Africa/Kampala',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Pacific/Johnston',
	    	'Pacific/Johnston',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Pacific/Midway',
	    	'Pacific/Midway',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Pacific/Wake',
	    	'Pacific/Wake',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'America/New_York',
	    	'America/New_York',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'America/Detroit',
	    	'America/Detroit',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'America/Louisville',
	    	'America/Louisville',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'America/Kentucky/Monticello',
	    	'America/Kentucky/Monticello',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'America/Indianapolis',
	    	'America/Indianapolis',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'America/Indiana/Marengo',
	    	'America/Indiana/Marengo',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'America/Indiana/Knox',
	    	'America/Indiana/Knox',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'America/Indiana/Vevay',
	    	'America/Indiana/Vevay',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'America/Chicago',
	    	'America/Chicago',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'America/Menominee',
	    	'America/Menominee',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'America/North_Dakota/Center',
	    	'America/North_Dakota/Center',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'America/Denver',
	    	'America/Denver',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'America/Boise',
	    	'America/Boise',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'America/Shiprock',
	    	'America/Shiprock',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'America/Phoenix',
	    	'America/Phoenix',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'America/Los_Angeles',
	    	'America/Los_Angeles',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'America/Anchorage',
	    	'America/Anchorage',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'America/Juneau',
	    	'America/Juneau',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'America/Yakutat',
	    	'America/Yakutat',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'America/Nome',
	    	'America/Nome',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'America/Adak',
	    	'America/Adak',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Pacific/Honolulu',
	    	'Pacific/Honolulu',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'America/Montevideo',
	    	'America/Montevideo',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Asia/Samarkand',
	    	'Asia/Samarkand',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Asia/Tashkent',
	    	'Asia/Tashkent',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Europe/Vatican',
	    	'Europe/Vatican',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'America/St_Vincent',
	    	'America/St_Vincent',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'America/Caracas',
	    	'America/Caracas',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'America/Tortola',
	    	'America/Tortola',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'America/St_Thomas',
	    	'America/St_Thomas',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Asia/Saigon',
	    	'Asia/Saigon',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Pacific/Efate',
	    	'Pacific/Efate',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Pacific/Wallis',
	    	'Pacific/Wallis',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Pacific/Apia',
	    	'Pacific/Apia',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Asia/Aden',
	    	'Asia/Aden',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Indian/Mayotte',
	    	'Indian/Mayotte',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Europe/Belgrade',
	    	'Europe/Belgrade',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Africa/Johannesburg',
	    	'Africa/Johannesburg',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Africa/Lusaka',
	    	'Africa/Lusaka',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'Africa/Harare',
	    	'Africa/Harare',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (rhn_ks_timezone_id_seq.nextval,
	    	'America/Toronto',
	    	'America/Toronto',
    	    	(SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_6')
        );


 070701000005A2000081B400000000000000000000000167AE111400001018000000000000000000000000000000000000007000000000susemanager-schema/upgrade/spacewalk-schema-1.1-to-spacewalk-schema-1.2/103-rhnPackageChangeLog-refactoring.sql   --
-- Copyright (c) 2010--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnPackageChangeLogData
(
    id          NUMBER NOT NULL
                    CONSTRAINT rhn_pkg_cld_id_pk PRIMARY KEY
                    USING INDEX TABLESPACE [[64k_tbs]],
    name        VARCHAR2(128) NOT NULL,
    text        VARCHAR2(3000) NOT NULL,
    time        DATE NOT NULL,
    created     DATE
                    DEFAULT (sysdate) NOT NULL
)
ENABLE ROW MOVEMENT
;

CREATE INDEX rhn_pkg_cld_nt_idx
    ON rhnPackageChangeLogData (name, time)
    NOLOGGING
    TABLESPACE [[32m_tbs]];

CREATE SEQUENCE rhn_pkg_cld_id_seq;

CREATE TABLE rhnPackageChangeLogRec
(
    id          NUMBER NOT NULL
                    CONSTRAINT rhn_pkg_clr_id_pk PRIMARY KEY
                    USING INDEX TABLESPACE [[64k_tbs]],
    package_id  NUMBER NOT NULL
                    CONSTRAINT rhn_pkg_clr_pid_fk
                        REFERENCES rhnPackage (id)
                        ON DELETE CASCADE,
    changelog_data_id  NUMBER NOT NULL
                    CONSTRAINT rhn_pkg_clr_cld_fk
                        REFERENCES rhnPackageChangeLogData (id),
    created     DATE
                    DEFAULT (sysdate) NOT NULL,
    modified    DATE
                    DEFAULT (sysdate) NOT NULL
)
ENABLE ROW MOVEMENT
;

CREATE UNIQUE INDEX rhn_pkg_clr_pid_cld_uq
    ON rhnPackageChangeLogRec (package_id, changelog_data_id)
    NOLOGGING
    TABLESPACE [[32m_tbs]];

CREATE INDEX rhn_pkg_clr_cld_uq
    ON rhnPackageChangeLogRec (changelog_data_id)
    NOLOGGING
    TABLESPACE [[32m_tbs]];

-- Split rhnPackageChangelog data into the two tables.

insert /*+append*/ into rhnPackageChangeLogData (id, name, text, time, created)
select min(id), name, text, time, min(created)
from rhnPackageChangelog
group by name, text, time;

commit;

declare
	max_id integer;
	i integer;
begin
	select max(id), min(id) into max_id, i from rhnPackageChangeLog;
	while i <= max_id loop
		insert /*+append*/ into rhnPackageChangelogRec (id, package_id, changelog_data_id, created, modified)
		select rhnPackageChangeLog.id, rhnPackageChangeLog.package_id, rhnPackageChangeLogData.id, rhnPackageChangeLog.created, rhnPackageChangeLog.modified
		from rhnPackageChangeLog, rhnPackageChangeLogData
		where rhnPackageChangeLog.name = rhnPackageChangeLogData.name
			and rhnPackageChangeLog.text = rhnPackageChangeLogData.text
			and rhnPackageChangeLog.time = rhnPackageChangeLogData.time
			and rhnPackageChangeLog.id >= i
			and rhnPackageChangeLog.id < i + 10000;
		commit;
		i := i + 10000;
	end loop;
end;
/

drop table rhnPackageChangelog;

-- Bump up the nextval of rhn_pkg_cld_id_seq to be above
-- the current max valu in rhnPackageChangeLogData.
begin
	for rec in (
		select id - rhn_pkg_cld_id_seq.nextval id from ( select nvl(max(id), 0) id from rhnPackageChangeLogData )
		) loop
		execute immediate 'alter sequence rhn_pkg_cld_id_seq increment by ' || greatest(rec.id, 1);
	end loop;
	for rec in (
		select rhn_pkg_cld_id_seq.nextval from dual
		) loop
		null;
	end loop;
	execute immediate 'alter sequence rhn_pkg_cld_id_seq increment by 1';
end;
/


create view rhnPackageChangeLog
as
select rhnPackageChangeLogRec.id,
	rhnPackageChangeLogRec.package_id,
	rhnPackageChangeLogRec.changelog_data_id,
	rhnPackageChangeLogData.name,
	rhnPackageChangeLogData.text,
	rhnPackageChangeLogData.time,
	rhnPackageChangeLogRec.created,
	rhnPackageChangeLogRec.modified
from rhnPackageChangeLogRec, rhnPackageChangeLogData
where rhnPackageChangeLogRec.changelog_data_id = rhnPackageChangeLogData.id;

070701000005A3000081B400000000000000000000000167AE111400000326000000000000000000000000000000000000006F00000000susemanager-schema/upgrade/spacewalk-schema-1.1-to-spacewalk-schema-1.2/104-rhnPackageChangeLogRec-trigger.sql    --
-- Copyright (c) 2008--2010 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

create or replace trigger
rhn_package_clog_rec_mod_trig
before insert or update on rhnPackageChangeLogRec
for each row
begin
        :new.modified := sysdate;
end;
/
show errors
  070701000005A4000081B400000000000000000000000167AE111400000437000000000000000000000000000000000000006200000000susemanager-schema/upgrade/spacewalk-schema-1.1-to-spacewalk-schema-1.2/105-date_diff_in_days.sql --
-- Copyright (c) 2008--2010 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--
--
-- Diffs two dates (date2 - date1) and returns number of dates in the result.
-- Can return fraction digits if dates has different time.
-- Basically this is equivalent of (date2 - date1) but we need to use this
-- function instead of the minus operator because of PostgreSQL compatibility.
--

create or replace function date_diff_in_days(ts1 in date, ts2 in date)
return number is
begin
    return ts2 - ts1;
end date_diff_in_days;
/
show errors

 070701000005A5000081B400000000000000000000000167AE111400000129000000000000000000000000000000000000006F00000000susemanager-schema/upgrade/spacewalk-schema-1.1-to-spacewalk-schema-1.2/200-rhnActionConfigChannel-indexes.sql    CREATE INDEX rhn_actioncc_sid_idx
    ON rhnActionConfigChannel (server_id)
    TABLESPACE [[4m_tbs]];

CREATE INDEX rhn_act_cc_ccid_idx
    ON rhnActionConfigChannel (config_channel_id)
    TABLESPACE [[4m_tbs]];

DROP INDEX rhn_actioncc_sid_aid_ccid_idx;
DROP INDEX rhn_act_cc_ccid_aid_sid_idx;
   070701000005A6000081B400000000000000000000000167AE111400000093000000000000000000000000000000000000007000000000susemanager-schema/upgrade/spacewalk-schema-1.1-to-spacewalk-schema-1.2/201-rhnActionConfigFileName-indexes.sql   CREATE INDEX rhn_actioncf_name_sid_idx
    ON rhnActionConfigFileName (server_id)
    TABLESPACE [[2m_tbs]];

DROP INDEX rhn_actioncf_name_sac_uq;
 070701000005A7000081B400000000000000000000000167AE11140000008E000000000000000000000000000000000000007000000000susemanager-schema/upgrade/spacewalk-schema-1.1-to-spacewalk-schema-1.2/202-rhnActionConfigRevision-indexes.sql   CREATE INDEX rhn_actioncr_sid_idx
    ON rhnActionConfigRevision (server_id)
    TABLESPACE [[2m_tbs]];

DROP INDEX rhn_actioncr_sid_aid_idx;
  070701000005A8000081B400000000000000000000000167AE111400000088000000000000000000000000000000000000006E00000000susemanager-schema/upgrade/spacewalk-schema-1.1-to-spacewalk-schema-1.2/203-rhnActionErrataUpdate-indexes.sql CREATE INDEX rhn_act_eu_eid_idx
    ON rhnActionErrataUpdate (errata_id)
    TABLESPACE [[8m_tbs]];

DROP INDEX rhn_act_eu_eid_aid_idx;
070701000005A9000081B400000000000000000000000167AE111400000025000000000000000000000000000000000000006300000000susemanager-schema/upgrade/spacewalk-schema-1.1-to-spacewalk-schema-1.2/204-rhnChannel-indexes.sql    
drop index rhn_channel_url_id_idx;

   070701000005AA000081B400000000000000000000000167AE11140000002D000000000000000000000000000000000000006900000000susemanager-schema/upgrade/spacewalk-schema-1.1-to-spacewalk-schema-1.2/205-rhnChannelCloned-indexes.sql  
drop index rhn_channelclone_tcid_fcid_idx;

   070701000005AB000081B400000000000000000000000167AE11140000001F000000000000000000000000000000000000007000000000susemanager-schema/upgrade/spacewalk-schema-1.1-to-spacewalk-schema-1.2/206-rhnChannelFamilyMembers-indexes.sql   
drop index rhn_cf_member_uq;

 070701000005AC000081B400000000000000000000000167AE111400000020000000000000000000000000000000000000006D00000000susemanager-schema/upgrade/spacewalk-schema-1.1-to-spacewalk-schema-1.2/207-rhnContentSourceType-indexes.sql  
drop index rhn_ccst_id_l_idx;

070701000005AD000081B400000000000000000000000167AE11140000002C000000000000000000000000000000000000006800000000susemanager-schema/upgrade/spacewalk-schema-1.1-to-spacewalk-schema-1.2/208-rhnErrataCloned-indexes.sql   
drop index rhn_errataclone_teid_feid_idx;

070701000005AE000081B400000000000000000000000167AE11140000002B000000000000000000000000000000000000006B00000000susemanager-schema/upgrade/spacewalk-schema-1.1-to-spacewalk-schema-1.2/209-rhnErrataClonedTmp-indexes.sql    
drop index rhn_eclonedtmp_teid_feid_idx;

 070701000005AF000081B400000000000000000000000167AE111400000E73000000000000000000000000000000000000006300000000susemanager-schema/upgrade/spacewalk-schema-1.1-to-spacewalk-schema-1.2/210-rhnPackage-indexes.sql    alter table RHNCHANNELNEWESTPACKAGE disable constraint RHN_CNP_PID_FK;
alter table RHNCHANNELPACKAGE disable constraint RHN_CP_PID_FK;
alter table RHNERRATAFILEPACKAGE disable constraint RHN_EFILEP_PID_FK;
alter table RHNERRATAFILEPACKAGETMP disable constraint RHN_EFILEPTMP_PID_FK;
alter table RHNERRATAPACKAGE disable constraint RHN_ERR_PKG_PID_FK;
alter table RHNERRATAPACKAGETMP disable constraint RHN_ERR_PKGTMP_PID_FK;
alter table RHNPACKAGECHANGELOGREC disable constraint RHN_PKG_CLR_PID_FK;
alter table RHNPACKAGECONFLICTS disable constraint RHN_PKG_CONFLICTS_PACKAGE_FK;
alter table RHNPACKAGEFILE disable constraint RHN_PACKAGE_FILE_PID_FK;
alter table RHNPACKAGEKEYASSOCIATION disable constraint RHN_PKEYA_PID_FK;
alter table RHNPACKAGEOBSOLETES disable constraint RHN_PKG_OBSOLETES_PACKAGE_FK;
alter table RHNPACKAGEPROVIDES disable constraint RHN_PKG_PROVIDES_PACKAGE_FK;
alter table RHNPACKAGEREPODATA disable constraint RHN_PKEY_RD_PID_FK;
alter table RHNPACKAGEREQUIRES disable constraint RHN_PKG_REQUIRES_PACKAGE_FK;
alter table RHNSERVERNEEDEDCACHE disable constraint RHN_SNCP_PID_FK;
alter table RHNSOLARISPACKAGE disable constraint RHN_SOLARIS_PKG_PID_FK;
alter table RHNSOLARISPATCH disable constraint RHN_SOLARIS_P_FK;
alter table RHNSOLARISPATCHSET disable constraint RHN_SOLARIS_PS_PID_FK;
alter table RHNSOLARISPATCHEDPACKAGE disable constraint RHN_SOLARIS_PATCHEDP_PID_FK;
alter table RHNSOLARISPATCHPACKAGES disable constraint RHN_SOLARIS_PP_FK;
alter table RHNSOLARISPATCHSETMEMBERS disable constraint RHN_SOLARIS_PSM_PID_FK;
alter table RHNSOLARISPATCHSETMEMBERS disable constraint RHN_SOLARIS_PSM_PSID_FK;

alter table rhnpackage disable constraint RHN_PACKAGE_ID_PK;
drop index rhn_package_id_nid_paid_idx;
drop index rhn_package_path_idx;
alter table rhnpackage enable novalidate constraint RHN_PACKAGE_ID_PK;

alter table RHNCHANNELNEWESTPACKAGE enable novalidate constraint RHN_CNP_PID_FK;
alter table RHNCHANNELPACKAGE enable novalidate constraint RHN_CP_PID_FK;
alter table RHNERRATAFILEPACKAGE enable novalidate constraint RHN_EFILEP_PID_FK;
alter table RHNERRATAFILEPACKAGETMP enable novalidate constraint RHN_EFILEPTMP_PID_FK;
alter table RHNERRATAPACKAGE enable novalidate constraint RHN_ERR_PKG_PID_FK;
alter table RHNERRATAPACKAGETMP enable novalidate constraint RHN_ERR_PKGTMP_PID_FK;
alter table RHNPACKAGECHANGELOGREC enable novalidate constraint RHN_PKG_CLR_PID_FK;
alter table RHNPACKAGECONFLICTS enable novalidate constraint RHN_PKG_CONFLICTS_PACKAGE_FK;
alter table RHNPACKAGEFILE enable novalidate constraint RHN_PACKAGE_FILE_PID_FK;
alter table RHNPACKAGEKEYASSOCIATION enable novalidate constraint RHN_PKEYA_PID_FK;
alter table RHNPACKAGEOBSOLETES enable novalidate constraint RHN_PKG_OBSOLETES_PACKAGE_FK;
alter table RHNPACKAGEPROVIDES enable novalidate constraint RHN_PKG_PROVIDES_PACKAGE_FK;
alter table RHNPACKAGEREPODATA enable novalidate constraint RHN_PKEY_RD_PID_FK;
alter table RHNPACKAGEREQUIRES enable novalidate constraint RHN_PKG_REQUIRES_PACKAGE_FK;
alter table RHNSERVERNEEDEDCACHE enable novalidate constraint RHN_SNCP_PID_FK;
alter table RHNSOLARISPACKAGE enable novalidate constraint RHN_SOLARIS_PKG_PID_FK;
alter table RHNSOLARISPATCH enable novalidate constraint RHN_SOLARIS_P_FK;
alter table RHNSOLARISPATCHSET enable novalidate constraint RHN_SOLARIS_PS_PID_FK;
alter table RHNSOLARISPATCHEDPACKAGE enable novalidate constraint RHN_SOLARIS_PATCHEDP_PID_FK;
alter table RHNSOLARISPATCHPACKAGES enable novalidate constraint RHN_SOLARIS_PP_FK;
alter table RHNSOLARISPATCHSETMEMBERS enable novalidate constraint RHN_SOLARIS_PSM_PID_FK;
alter table RHNSOLARISPATCHSETMEMBERS enable novalidate constraint RHN_SOLARIS_PSM_PSID_FK;
 070701000005B0000081B400000000000000000000000167AE111400000021000000000000000000000000000000000000006C00000000susemanager-schema/upgrade/spacewalk-schema-1.1-to-spacewalk-schema-1.2/211-rhnRegTokenPackages-indexes.sql   
drop index rhn_reg_tok_pkg_uq;

   070701000005B1000081B400000000000000000000000167AE111400000025000000000000000000000000000000000000006700000000susemanager-schema/upgrade/spacewalk-schema-1.1-to-spacewalk-schema-1.2/212-rhnServerGroup-indexes.sql    
drop index rhn_sg_id_oid_name_idx;

   070701000005B2000081B400000000000000000000000167AE111400000029000000000000000000000000000000000000006D00000000susemanager-schema/upgrade/spacewalk-schema-1.1-to-spacewalk-schema-1.2/213-rhnServerInstallInfo-indexes.sql  
drop index rhn_s_inst_info_sid_im_idx;

   070701000005B3000081B400000000000000000000000167AE111400000021000000000000000000000000000000000000006500000000susemanager-schema/upgrade/spacewalk-schema-1.1-to-spacewalk-schema-1.2/214-rhnUserGroup-indexes.sql  
drop index rhn_ug_id_name_org;

   070701000005B4000081B400000000000000000000000167AE11140000002A000000000000000000000000000000000000006700000000susemanager-schema/upgrade/spacewalk-schema-1.1-to-spacewalk-schema-1.2/215-rhnVersionInfo-indexes.sql    
drop index rhn_vinfo_label_eid_nid_idx;

  070701000005B5000081B400000000000000000000000167AE111400000029000000000000000000000000000000000000006800000000susemanager-schema/upgrade/spacewalk-schema-1.1-to-spacewalk-schema-1.2/216-rhn_check_probe-indexes.sql   
drop index rhn_chkpb_pid_ptype_uq_idx;

   070701000005B6000081B400000000000000000000000167AE11140000007D000000000000000000000000000000000000006E00000000susemanager-schema/upgrade/spacewalk-schema-1.1-to-spacewalk-schema-1.2/217-rhn_command_parameter-indexes.sql 
alter table rhn_command_parameter drop constraint rhn_cparm_id_p_name_p_type_uq;
drop index rhn_cparm_id_p_name_p_type_uq;

   070701000005B7000081B400000000000000000000000167AE111400000076000000000000000000000000000000000000006B00000000susemanager-schema/upgrade/spacewalk-schema-1.1-to-spacewalk-schema-1.2/218-rhn_deployed_probe-indexes.sql    
alter table rhn_deployed_probe drop constraint dprob_recid_probe_type_uq;
drop index rhn_dprob_recid_probe_type_uq;

  070701000005B8000081B400000000000000000000000167AE111400000027000000000000000000000000000000000000006700000000susemanager-schema/upgrade/spacewalk-schema-1.1-to-spacewalk-schema-1.2/219-rhn_host_probe-indexes.sql    
drop index rhn_hstpb_pbid_ptype_idx;

 070701000005B9000081B400000000000000000000000167AE111400000026000000000000000000000000000000000000006E00000000susemanager-schema/upgrade/spacewalk-schema-1.1-to-spacewalk-schema-1.2/220-rhn_sat_cluster_probe-indexes.sql 
drop index rhn_sclpb_pid_ptype_idx;

  070701000005BA000081B400000000000000000000000167AE1114000000B7000000000000000000000000000000000000006B00000000susemanager-schema/upgrade/spacewalk-schema-1.1-to-spacewalk-schema-1.2/221-rhn_sat_node_probe-indexes.sql    
alter table rhn_sat_node_probe disable constraint rhn_sndpb_probe_id_pk;
drop index rhn_sndpb_pid_ptype_idx;
alter table rhn_sat_node_probe enable constraint rhn_sndpb_probe_id_pk;

 070701000005BB000081B400000000000000000000000167AE11140000002A000000000000000000000000000000000000006600000000susemanager-schema/upgrade/spacewalk-schema-1.1-to-spacewalk-schema-1.2/222-rhn_url_probe-indexes.sql 
drop index rhn_url_probe_pid_ptype_idx;

  070701000005BC000081B400000000000000000000000167AE111400001709000000000000000000000000000000000000006400000000susemanager-schema/upgrade/spacewalk-schema-1.1-to-spacewalk-schema-1.2/223-web_contact-indexes.sql   alter table WEB_USER_SITE_INFO disable constraint WUSI_WUID_FK;
alter table WEB_USER_PERSONAL_INFO disable constraint PERSONAL_INFO_WEB_USER_ID_FK;
alter table WEB_USER_CONTACT_PERMISSION disable constraint CONTPERM_WBUSERID_FK;
alter table PXTSESSIONS disable constraint PXTSESSIONS_USER;
alter table RHNWEBCONTACTCHANGELOG disable constraint RHN_WCON_CL_WCON_ID_FK;
alter table RHNSAVEDSEARCH disable constraint RHN_SAVEDSEARCH_WCID_FK;
alter table RHNWEBCONTACTCHANGELOG disable constraint RHN_WCON_CL_WCON_FROM_ID_FK;
alter table RHNUSERSERVERPREFS disable constraint RHN_USERSERVERPREFS_UID_FK;
alter table RHNUSERSERVERPERMS disable constraint RHN_USPERMS_UID_FK;
alter table RHNUSERSERVERGROUPPERMS disable constraint RHN_USGP_USER_FK;
alter table RHNUSERINFOPANE disable constraint RHN_USR_INFO_PANE_UID_FK;
alter table RHNUSERINFO disable constraint RHN_USER_INFO_USER_FK;
alter table RHNUSERGROUPMEMBERS disable constraint RHN_UGMEMBERS_UID_FK;
alter table RHNUSERDEFAULTSYSTEMGROUPS disable constraint RHN_UDSG_UID_FK;
alter table RHNSSMOPERATION disable constraint RHN_SSMOP_USER_FK;
alter table RHNSET disable constraint RHN_SET_USER_FK;
alter table RHNREGTOKEN disable constraint RHN_REG_TOKEN_UID_FK;
alter table RHNGRAILCOMPONENTCHOICES disable constraint RHN_GRAIL_COMP_CH_USER_FK;
alter table RHNFILEDOWNLOAD disable constraint RHN_FILEDL_UID_FK;
alter table RHNEMAILADDRESSLOG disable constraint RHN_EADDRESSLOG_UID_FK;
alter table RHNEMAILADDRESS disable constraint RHN_EADDRESS_UID_FK;
alter table RHNCHANNELPERMISSION disable constraint RHN_CPERM_UID_FK;
alter table RHNAPPINSTALLSESSION disable constraint RHN_APPINST_SESSION_UID_FK;
alter table RHNKICKSTARTSESSION disable constraint RHN_KS_SESSION_SCHED_FK;
alter table RHNACTION disable constraint RHN_ACTION_SCHEDULER_FK;
alter table RHNSERVERLOCK disable constraint RHN_SERVER_LOCK_LID_FK;
alter table RHNSERVERCUSTOMDATAVALUE disable constraint RHN_SCDV_LMB_FK;
alter table RHNCUSTOMDATAKEY disable constraint RHN_CDATAKEY_LMB_FK;
alter table RHNSERVER disable constraint RHN_SERVER_CREATOR_FK;
alter table RHNSERVERNOTES disable constraint RHN_SERVERNOTES_CREATOR_FK;
alter table RHNSERVERGROUPNOTES disable constraint RHN_SERVERGRP_NOTE_CREATOR_FK;
alter table RHNSERVERCUSTOMDATAVALUE disable constraint RHN_SCDV_CB_FK;
alter table RHNCUSTOMDATAKEY disable constraint RHN_CDATAKEY_CB_FK;
alter table RHN_REDIRECTS disable constraint RHN_RDRCT_CNTCT_CONTACT_ID_FK;
alter table RHN_CONTACT_METHODS disable constraint RHN_CMETH_CONTACT_ID_FK;
alter table RHN_COMMAND_QUEUE_SESSIONS disable constraint RHN_CQSES_CNTCT_CONTACT_IDFK;
alter table RHNCONFIGREVISION disable constraint RHN_CONFREVISION_CID_FK;

alter table web_contact disable constraint WEB_CONTACT_PK;
drop index web_contact_id_oid_cust_luc;
alter table web_contact enable constraint WEB_CONTACT_PK;

alter table WEB_USER_SITE_INFO enable novalidate constraint WUSI_WUID_FK;
alter table WEB_USER_PERSONAL_INFO enable novalidate constraint PERSONAL_INFO_WEB_USER_ID_FK;
alter table WEB_USER_CONTACT_PERMISSION enable novalidate constraint CONTPERM_WBUSERID_FK;
alter table PXTSESSIONS enable novalidate constraint PXTSESSIONS_USER;
alter table RHNWEBCONTACTCHANGELOG enable novalidate constraint RHN_WCON_CL_WCON_ID_FK;
alter table RHNSAVEDSEARCH enable novalidate constraint RHN_SAVEDSEARCH_WCID_FK;
alter table RHNWEBCONTACTCHANGELOG enable novalidate constraint RHN_WCON_CL_WCON_FROM_ID_FK;
alter table RHNUSERSERVERPREFS enable novalidate constraint RHN_USERSERVERPREFS_UID_FK;
alter table RHNUSERSERVERPERMS enable novalidate constraint RHN_USPERMS_UID_FK;
alter table RHNUSERSERVERGROUPPERMS enable novalidate constraint RHN_USGP_USER_FK;
alter table RHNUSERINFOPANE enable novalidate constraint RHN_USR_INFO_PANE_UID_FK;
alter table RHNUSERINFO enable novalidate constraint RHN_USER_INFO_USER_FK;
alter table RHNUSERGROUPMEMBERS enable novalidate constraint RHN_UGMEMBERS_UID_FK;
alter table RHNUSERDEFAULTSYSTEMGROUPS enable novalidate constraint RHN_UDSG_UID_FK;
alter table RHNSSMOPERATION enable novalidate constraint RHN_SSMOP_USER_FK;
alter table RHNSET enable novalidate constraint RHN_SET_USER_FK;
alter table RHNREGTOKEN enable novalidate constraint RHN_REG_TOKEN_UID_FK;
alter table RHNGRAILCOMPONENTCHOICES enable novalidate constraint RHN_GRAIL_COMP_CH_USER_FK;
alter table RHNFILEDOWNLOAD enable novalidate constraint RHN_FILEDL_UID_FK;
alter table RHNEMAILADDRESSLOG enable novalidate constraint RHN_EADDRESSLOG_UID_FK;
alter table RHNEMAILADDRESS enable novalidate constraint RHN_EADDRESS_UID_FK;
alter table RHNCHANNELPERMISSION enable novalidate constraint RHN_CPERM_UID_FK;
alter table RHNAPPINSTALLSESSION enable novalidate constraint RHN_APPINST_SESSION_UID_FK;
alter table RHNKICKSTARTSESSION enable novalidate constraint RHN_KS_SESSION_SCHED_FK;
alter table RHNACTION enable novalidate constraint RHN_ACTION_SCHEDULER_FK;
alter table RHNSERVERLOCK enable novalidate constraint RHN_SERVER_LOCK_LID_FK;
alter table RHNSERVERCUSTOMDATAVALUE enable novalidate constraint RHN_SCDV_LMB_FK;
alter table RHNCUSTOMDATAKEY enable novalidate constraint RHN_CDATAKEY_LMB_FK;
alter table RHNSERVER enable novalidate constraint RHN_SERVER_CREATOR_FK;
alter table RHNSERVERNOTES enable novalidate constraint RHN_SERVERNOTES_CREATOR_FK;
alter table RHNSERVERGROUPNOTES enable novalidate constraint RHN_SERVERGRP_NOTE_CREATOR_FK;
alter table RHNSERVERCUSTOMDATAVALUE enable novalidate constraint RHN_SCDV_CB_FK;
alter table RHNCUSTOMDATAKEY enable novalidate constraint RHN_CDATAKEY_CB_FK;
alter table RHN_REDIRECTS enable novalidate constraint RHN_RDRCT_CNTCT_CONTACT_ID_FK;
alter table RHN_CONTACT_METHODS enable novalidate constraint RHN_CMETH_CONTACT_ID_FK;
alter table RHN_COMMAND_QUEUE_SESSIONS enable novalidate constraint RHN_CQSES_CNTCT_CONTACT_IDFK;
alter table RHNCONFIGREVISION enable novalidate constraint RHN_CONFREVISION_CID_FK;
   070701000005BD000081B400000000000000000000000167AE111400000433000000000000000000000000000000000000006700000000susemanager-schema/upgrade/spacewalk-schema-1.1-to-spacewalk-schema-1.2/224-rhnChannelArch-indexes.sql    alter table rhnChannel disable constraint rhn_channel_caid_fk;
alter table rhnChannelPackageArchCompat disable constraint rhn_cp_ac_caid_fk;
alter table rhnDistChannelMap disable constraint rhn_dcm_caid_fk;
alter table rhnReleaseChannelMap disable constraint rhn_rcm_caid_fk;
alter table rhnServerChannelArchCompat disable constraint rhn_sc_ac_caid_fk;
alter table rhnChannelArch disable constraint rhn_carch_id_pk;
drop index rhn_carch_id_l_n_idx;
alter table rhnChannelArch enable constraint rhn_carch_id_pk;
alter table rhnChannel enable constraint rhn_channel_caid_fk;
alter table rhnChannelPackageArchCompat enable constraint rhn_cp_ac_caid_fk;
alter table rhnDistChannelMap enable constraint rhn_dcm_caid_fk;
alter table rhnReleaseChannelMap enable constraint rhn_rcm_caid_fk;
alter table rhnServerChannelArchCompat enable constraint rhn_sc_ac_caid_fk;

alter table rhnChannelArch drop CONSTRAINT rhn_carch_label_uq;
drop index rhn_carch_l_id_n_idx;
ALTER TABLE rhnChannelArch
    ADD CONSTRAINT rhn_carch_label_uq UNIQUE (label)
    USING INDEX TABLESPACE [[2m_tbs]];
 070701000005BE000081B400000000000000000000000167AE11140000001F000000000000000000000000000000000000006C00000000susemanager-schema/upgrade/spacewalk-schema-1.1-to-spacewalk-schema-1.2/225-rhnChannelDownloads-indexes.sql   drop index rhn_cd_did_cid_idx;
 070701000005BF000081B400000000000000000000000167AE11140000007C000000000000000000000000000000000000006900000000susemanager-schema/upgrade/spacewalk-schema-1.1-to-spacewalk-schema-1.2/226-rhnChannelErrata-indexes.sql  CREATE INDEX rhn_ce_eid_idx
    ON rhnChannelErrata (errata_id)
    TABLESPACE [[64k_tbs]];

DROP INDEX rhn_ce_eid_cid_idx;
070701000005C0000081B400000000000000000000000167AE11140000045E000000000000000000000000000000000000005A00000000susemanager-schema/upgrade/spacewalk-schema-1.1-to-spacewalk-schema-1.2/501-rhn_cache.sql --
-- Copyright (c) 2008--2010 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--

create or replace package
rhn_cache
is
	version varchar2(100) := '';

	-- this searches out all users who get perms...
	procedure update_perms_for_server(
		server_id_in in number
	);

	procedure update_perms_for_user(
		user_id_in in number
	);

	procedure update_perms_for_server_group(
		server_group_id_in in number
	);
end rhn_cache;
/
show errors

--
--
-- Revision 1.1  2004/07/02 19:14:32  pjones
-- 125937 -- tools to manipulate rhnUserServerPerms when appropriate.
--

  070701000005C1000081B400000000000000000000000167AE11140000009B000000000000000000000000000000000000007500000000susemanager-schema/upgrade/spacewalk-schema-1.1-to-spacewalk-schema-1.2/227-rhnChannelFamilyVirtSubLevel-indexes.sql  CREATE INDEX rhn_cfvsl_vslid_idx
    ON rhnChannelFamilyVirtSubLevel (virt_sub_level_id)
    TABLESPACE [[64k_tbs]];

DROP INDEX rhn_cfvsl_vslid_cfid_idx;
 070701000005C2000081B400000000000000000000000167AE1114000000D1000000000000000000000000000000000000007000000000susemanager-schema/upgrade/spacewalk-schema-1.1-to-spacewalk-schema-1.2/228-rhnChannelNewestPackage-indexes.sql   alter table rhnChannelNewestPackage disable constraint rhn_cnp_cid_nid_uq;
drop index rhn_cnp_cnep_idx;
alter table rhnChannelNewestPackage enable constraint rhn_cnp_cid_nid_uq;

drop index rhn_cnp_necp_idx;

   070701000005C3000081B400000000000000000000000167AE111400000087000000000000000000000000000000000000006A00000000susemanager-schema/upgrade/spacewalk-schema-1.1-to-spacewalk-schema-1.2/229-rhnChannelPackage-indexes.sql CREATE INDEX rhn_cp_pid_idx
    ON rhnChannelPackage (package_id)
    TABLESPACE [[64k_tbs]]
    NOLOGGING;

DROP INDEX rhn_cp_pc_idx;
 070701000005C4000081B400000000000000000000000167AE111400000020000000000000000000000000000000000000007400000000susemanager-schema/upgrade/spacewalk-schema-1.1-to-spacewalk-schema-1.2/230-rhnChannelPackageArchCompat-indexes.sql   drop index rhn_cp_ac_paid_caid;
070701000005C5000081B400000000000000000000000167AE1114000000D7000000000000000000000000000000000000006300000000susemanager-schema/upgrade/spacewalk-schema-1.1-to-spacewalk-schema-1.2/231-rhnCpuArch-indexes.sql    ALTER TABLE rhnCpuArch DROP CONSTRAINT rhn_cpuarch_label_uq;
DROP INDEX rhn_cpuarch_l_id_n_idx;

ALTER TABLE rhnCpuArch
    ADD CONSTRAINT rhn_cpuarch_label_uq UNIQUE (label)
    USING INDEX TABLESPACE [[2m_tbs]];

 070701000005C6000081B400000000000000000000000167AE111400000080000000000000000000000000000000000000006E00000000susemanager-schema/upgrade/spacewalk-schema-1.1-to-spacewalk-schema-1.2/232-rhnCryptoKeyKickstart-indexes.sql CREATE INDEX rhn_ckey_ks_idx
    ON rhnCryptoKeyKickstart (ksdata_id)
    TABLESPACE [[4m_tbs]];

DROP INDEX rhn_ckey_ks__ckuq;
070701000005C7000081B400000000000000000000000167AE111400000023000000000000000000000000000000000000006800000000susemanager-schema/upgrade/spacewalk-schema-1.1-to-spacewalk-schema-1.2/233-rhnEmailAddress-indexes.sql   drop index rhn_eaddress_niusa_idx;
 070701000005C8000081B400000000000000000000000167AE1114000000EE000000000000000000000000000000000000006D00000000susemanager-schema/upgrade/spacewalk-schema-1.1-to-spacewalk-schema-1.2/234-rhnEmailAddressState-indexes.sql  ALTER TABLE rhnEmailAddressState DROP CONSTRAINT rhn_eastate_label_uq;
DROP INDEX rhn_eastate_label_id_idx;

ALTER TABLE rhnEmailAddressState
    ADD CONSTRAINT rhn_eastate_label_uq UNIQUE (label)
    USING INDEX TABLESPACE [[64k_tbs]];

  070701000005C9000081B400000000000000000000000167AE11140000008D000000000000000000000000000000000000006500000000susemanager-schema/upgrade/spacewalk-schema-1.1-to-spacewalk-schema-1.2/235-rhnErrataCVE-indexes.sql  CREATE INDEX rhn_err_cve_cid_idx
    ON rhnErrataCVE (cve_id)
    TABLESPACE [[64k_tbs]]
    NOLOGGING;

DROP INDEX rhn_err_cve_cid_eid_idx;
   070701000005CA000081B400000000000000000000000167AE11140000008A000000000000000000000000000000000000006D00000000susemanager-schema/upgrade/spacewalk-schema-1.1-to-spacewalk-schema-1.2/236-rhnErrataFileChannel-indexes.sql  CREATE INDEX rhn_efilec_cid_idx
    ON rhnErrataFileChannel (channel_id)
    TABLESPACE [[64k_tbs]];

DROP INDEX rhn_efilec_cid_efid_idx;
  070701000005CB000081B400000000000000000000000167AE111400000136000000000000000000000000000000000000007000000000susemanager-schema/upgrade/spacewalk-schema-1.1-to-spacewalk-schema-1.2/237-rhnErrataFileChannelTmp-indexes.sql   CREATE INDEX rhn_efilectmp_cid_idx
    ON rhnErrataFileChannelTmp (channel_id)
    TABLESPACE [[64k_tbs]];

alter table rhnErrataFileChannelTmp disable constraint RHN_EFILECTMP_EFID_CID_UQ;
DROP INDEX rhn_efilectmp_cid_efid_idx;
alter table rhnErrataFileChannelTmp enable constraint RHN_EFILECTMP_EFID_CID_UQ;
  070701000005CC000081B400000000000000000000000167AE1114000000EA000000000000000000000000000000000000006700000000susemanager-schema/upgrade/spacewalk-schema-1.1-to-spacewalk-schema-1.2/238-rhnChannelComps-unique.sql    
delete from rhnChannelComps
where id not in (
	select max(id)
	from rhnChannelComps
	group by channel_id
);

alter table rhnChannelComps
	add constraint rhn_channelcomps_cid_uq unique(channel_id)
	using index tablespace [[2m_tbs]];

  070701000005CD000081B400000000000000000000000167AE111400000155000000000000000000000000000000000000007300000000susemanager-schema/upgrade/spacewalk-schema-1.1-to-spacewalk-schema-1.2/239-rhnErrataNotificationQueue-indexes.sql    ALTER TABLE rhnErrataNotificationQueue
    disable CONSTRAINT rhn_enqueue_eoid_uq;
drop index rhn_enqueue_eid_idx;
ALTER TABLE rhnErrataNotificationQueue
    enable CONSTRAINT rhn_enqueue_eoid_uq;

CREATE INDEX rhn_enqueue_na_idx
    ON rhnErrataNotificationQueue (next_action)
     TABLESPACE [[8m_tbs]];
drop index rhn_enqueue_na_eid_idx;
   070701000005CE000081B400000000000000000000000167AE111400000094000000000000000000000000000000000000006900000000susemanager-schema/upgrade/spacewalk-schema-1.1-to-spacewalk-schema-1.2/240-rhnErrataPackage-indexes.sql  CREATE INDEX rhn_err_pkg_pid_idx
    ON rhnErrataPackage (package_id)
    TABLESPACE [[64k_tbs]]
    NOLOGGING;
drop index rhn_err_pkg_pid_eid_idx;
070701000005CF000081B400000000000000000000000167AE11140000009D000000000000000000000000000000000000006C00000000susemanager-schema/upgrade/spacewalk-schema-1.1-to-spacewalk-schema-1.2/241-rhnErrataPackageTmp-indexes.sql   CREATE INDEX rhn_err_pkgtmp_pid_idx
    ON rhnErrataPackageTmp (package_id)
    TABLESPACE [[64k_tbs]]
    NOLOGGING;
drop index rhn_err_pkgtmp_pid_eid_idx;
   070701000005D0000081B400000000000000000000000167AE1114000000A0000000000000000000000000000000000000007500000000susemanager-schema/upgrade/spacewalk-schema-1.1-to-spacewalk-schema-1.2/242-rhnKickstartPreserveFileList-indexes.sql  CREATE INDEX rhn_kspreservefl_flid_idx
    ON rhnKickstartPreserveFileList (file_list_id)
    TABLESPACE [[8m_tbs]];
drop index rhn_kspreservefl_flid_ksid_idx;
070701000005D1000081B400000000000000000000000167AE1114000000AC000000000000000000000000000000000000006700000000susemanager-schema/upgrade/spacewalk-schema-1.1-to-spacewalk-schema-1.2/243-rhnPackageArch-indexes.sql    ALTER TABLE rhnPackageArch
    disable CONSTRAINT rhn_parch_label_uq;
drop index rhn_parch_l_id_n_idx;
ALTER TABLE rhnPackageArch
    enable CONSTRAINT rhn_parch_label_uq;
070701000005D2000081B400000000000000000000000167AE11140000009F000000000000000000000000000000000000006700000000susemanager-schema/upgrade/spacewalk-schema-1.1-to-spacewalk-schema-1.2/244-rhnPackageFile-indexes.sql    CREATE INDEX rhn_package_file_cid_idx
    ON rhnPackageFile (capability_id)
    TABLESPACE [[32m_tbs]]
    NOLOGGING;
drop index rhn_package_file_cid_pid_idx;
 070701000005D3000081B400000000000000000000000167AE1114000000A1000000000000000000000000000000000000007000000000susemanager-schema/upgrade/spacewalk-schema-1.1-to-spacewalk-schema-1.2/245-rhnPrivateChannelFamily-indexes.sql   CREATE INDEX rhn_cfperm_cfid_idx
    ON rhnPrivateChannelFamily (channel_family_id)
    TABLESPACE [[2m_tbs]]
    NOLOGGING;
drop index rhn_cfperm_cfid_oid_idx;
   070701000005D4000081B400000000000000000000000167AE11140000008E000000000000000000000000000000000000006E00000000susemanager-schema/upgrade/spacewalk-schema-1.1-to-spacewalk-schema-1.2/246-rhnSGTypeVirtSubLevel-indexes.sql CREATE INDEX rhn_sgtvsl_vslid
    ON rhnSGTypeVirtSubLevel (virt_sub_level_id)
    TABLESPACE [[64k_tbs]];
drop index rhn_sgtvsl_vslid_sgtid;
  070701000005D5000081B400000000000000000000000167AE111400000093000000000000000000000000000000000000006800000000susemanager-schema/upgrade/spacewalk-schema-1.1-to-spacewalk-schema-1.2/248-rhnServerAction-indexes.sql   CREATE INDEX rhn_ser_act_aid_idx
    ON rhnServerAction (action_id)
    TABLESPACE [[8m_tbs]]
    NOLOGGING;
drop index rhn_ser_act_aid_sid_s_idx;
 070701000005D6000081B400000000000000000000000167AE1114000000AA000000000000000000000000000000000000006600000000susemanager-schema/upgrade/spacewalk-schema-1.1-to-spacewalk-schema-1.2/249-rhnServerArch-indexes.sql ALTER TABLE rhnServerArch
    disable CONSTRAINT rhn_sarch_label_uq;
drop index rhn_sarch_l_id_n_idx;
ALTER TABLE rhnServerArch
    enable CONSTRAINT rhn_sarch_label_uq;
  070701000005D7000081B400000000000000000000000167AE111400000089000000000000000000000000000000000000006900000000susemanager-schema/upgrade/spacewalk-schema-1.1-to-spacewalk-schema-1.2/250-rhnServerChannel-indexes.sql  CREATE INDEX rhn_sc_cid_idx
    ON rhnServerChannel (channel_id)
    TABLESPACE [[8m_tbs]]
    NOLOGGING;
drop index rhn_sc_cid_sid_idx;
   070701000005D8000081B400000000000000000000000167AE11140000008C000000000000000000000000000000000000007300000000susemanager-schema/upgrade/spacewalk-schema-1.1-to-spacewalk-schema-1.2/251-rhnServerChannelArchCompat-indexes.sql    CREATE INDEX rhn_sc_ac_caid
    ON rhnServerChannelArchCompat (channel_arch_id)
    TABLESPACE [[64k_tbs]];
drop index rhn_sc_ac_paid_caid;
070701000005D9000081B400000000000000000000000167AE111400000069000000000000000000000000000000000000007100000000susemanager-schema/upgrade/spacewalk-schema-1.1-to-spacewalk-schema-1.2/252-rhnServerCustomDataValue-indexes.sql  CREATE INDEX rhn_scdv_kid_idx
    ON rhnServerCustomDataValue (key_id);
drop index rhn_scdv_kid_sid_idx;
   070701000005DA000081B400000000000000000000000167AE111400000046000000000000000000000000000000000000006700000000susemanager-schema/upgrade/spacewalk-schema-1.1-to-spacewalk-schema-1.2/253-rhnServerGroup-indexes.sql    drop index rhn_sg_oid_id_name_idx;
drop index rhn_sg_oid_type_id_idx;
  070701000005DB000081B400000000000000000000000167AE1114000000A3000000000000000000000000000000000000006E00000000susemanager-schema/upgrade/spacewalk-schema-1.1-to-spacewalk-schema-1.2/254-rhnServerGroupMembers-indexes.sql CREATE INDEX rhn_sgmembers_sgid_idx
    ON rhnServerGroupMembers (server_group_id)
    TABLESPACE [[4m_tbs]]
    NOLOGGING;
drop index rhn_sgmembers_sgid_sid_idx;
 070701000005DC000081B400000000000000000000000167AE11140000001C000000000000000000000000000000000000006D00000000susemanager-schema/upgrade/spacewalk-schema-1.1-to-spacewalk-schema-1.2/255-rhnServerNeededCache-indexes.sql  drop index rhn_snc_sid_idx;
070701000005DD000081B400000000000000000000000167AE111400000096000000000000000000000000000000000000007300000000susemanager-schema/upgrade/spacewalk-schema-1.1-to-spacewalk-schema-1.2/256-rhnServerPackageArchCompat-indexes.sql    CREATE INDEX rhn_sp_ac_paid_pref
    ON rhnServerPackageArchCompat (package_arch_id)
    TABLESPACE [[64k_tbs]];
drop index rhn_sp_ac_paid_said_pref;
  070701000005DE000081B400000000000000000000000167AE111400000097000000000000000000000000000000000000007200000000susemanager-schema/upgrade/spacewalk-schema-1.1-to-spacewalk-schema-1.2/257-rhnServerPreserveFileList-indexes.sql CREATE INDEX rhn_serverpfl_flid_idx
    ON rhnServerPreserveFileList (file_list_id)
    TABLESPACE [[4m_tbs]];
drop index rhn_serverpfl_flid_ksid_idx;
 070701000005DF000081B400000000000000000000000167AE1114000000A8000000000000000000000000000000000000007700000000susemanager-schema/upgrade/spacewalk-schema-1.1-to-spacewalk-schema-1.2/258-rhnServerServerGroupArchCompat-indexes.sql    CREATE INDEX rhn_ssg_ac_sgt_idx
    ON rhnServerServerGroupArchCompat (server_group_type)
    TABLESPACE [[64k_tbs]]
    NOLOGGING;
drop index rhn_ssg_ac_sgt_said_idx;
070701000005E0000081B400000000000000000000000167AE11140000009F000000000000000000000000000000000000006B00000000susemanager-schema/upgrade/spacewalk-schema-1.1-to-spacewalk-schema-1.2/259-rhnServerTokenRegs-indexes.sql    CREATE INDEX RHN_SRVR_TKN_RGS_SID_IDX
    ON rhnServerTokenRegs (server_id)
    TABLESPACE [[64k_tbs]]
    NOLOGGING;
drop index RHN_SRVR_TKN_RGS_SID_TID_IDX;
 070701000005E1000081B400000000000000000000000167AE11140000009A000000000000000000000000000000000000007100000000susemanager-schema/upgrade/spacewalk-schema-1.1-to-spacewalk-schema-1.2/260-rhnSnapshotConfigChannel-indexes.sql  CREATE INDEX rhn_snpsht_cc_ccid_idx
    ON rhnSnapshotConfigChannel (config_channel_id)
    TABLESPACE [[4m_tbs]];
drop index rhn_snpsht_cc_ccid_sid_idx;
  070701000005E2000081B400000000000000000000000167AE111400000092000000000000000000000000000000000000007200000000susemanager-schema/upgrade/spacewalk-schema-1.1-to-spacewalk-schema-1.2/261-rhnSnapshotConfigRevision-indexes.sql CREATE INDEX rhn_sscr_crid_idx
    ON rhnSnapshotConfigRevision (config_revision_id)
    TABLESPACE [[2m_tbs]];
drop index rhn_sscr_crid_sid_idx;
  070701000005E3000081B400000000000000000000000167AE111400000088000000000000000000000000000000000000006700000000susemanager-schema/upgrade/spacewalk-schema-1.1-to-spacewalk-schema-1.2/262-rhnSnapshotTag-indexes.sql    drop index rhn_ss_tag_tid_ssid_idx;

CREATE INDEX rhn_ss_tag_tid_idx
    ON rhnSnapshotTag (tag_id);
drop index rhn_ss_tag_tid_sid_idx;
070701000005E4000081B400000000000000000000000167AE111400000080000000000000000000000000000000000000007000000000susemanager-schema/upgrade/spacewalk-schema-1.1-to-spacewalk-schema-1.2/263-rhnSolarisPatchPackages-indexes.sql   CREATE INDEX rhn_solaris_pp_pnid_idx
    ON rhnSolarisPatchPackages (package_nevra_id);
drop index rhn_solaris_pp_pnid_pid_idx;
070701000005E5000081B400000000000000000000000167AE11140000009A000000000000000000000000000000000000007200000000susemanager-schema/upgrade/spacewalk-schema-1.1-to-spacewalk-schema-1.2/264-rhnSolarisPatchSetMembers-indexes.sql CREATE INDEX rhn_solaris_psm_psid_idx
    ON rhnSolarisPatchSetMembers (patch_set_id)
    TABLESPACE [[4m_tbs]];
drop index rhn_solaris_psm_psid_pid_idx;
  070701000005E6000081B400000000000000000000000167AE111400000090000000000000000000000000000000000000007300000000susemanager-schema/upgrade/spacewalk-schema-1.1-to-spacewalk-schema-1.2/265-rhnUserDefaultSystemGroups-indexes.sql    CREATE INDEX rhn_udsg_sgid_idx
    ON rhnUserDefaultSystemGroups (system_group_id)
    TABLESPACE [[2m_tbs]];
drop index rhn_udsg_sgid_uid_idx;
070701000005E7000081B400000000000000000000000167AE1114000000E8000000000000000000000000000000000000006500000000susemanager-schema/upgrade/spacewalk-schema-1.1-to-spacewalk-schema-1.2/266-rhnUserGroup-indexes.sql  drop index rhn_ug_org_id_name_idx;

ALTER TABLE rhnUserGroup
 disable CONSTRAINT rhn_ug_oid_gt_uq;
drop index rhn_ug_org_id_gtype_idx;
ALTER TABLE rhnUserGroup
 enable CONSTRAINT rhn_ug_oid_gt_uq
 USING INDEX TABLESPACE [[8m_tbs]];
070701000005E8000081B400000000000000000000000167AE11140000009F000000000000000000000000000000000000006C00000000susemanager-schema/upgrade/spacewalk-schema-1.1-to-spacewalk-schema-1.2/267-rhnUserGroupMembers-indexes.sql   CREATE INDEX rhn_ugmembers_ugid_idx
    ON rhnUserGroupMembers (user_group_id)
    TABLESPACE [[8m_tbs]]
    NOLOGGING;
drop index rhn_ugmembers_ugid_uid_idx;
 070701000005E9000081B400000000000000000000000167AE111400000097000000000000000000000000000000000000007000000000susemanager-schema/upgrade/spacewalk-schema-1.1-to-spacewalk-schema-1.2/268-rhnUserServerGroupPerms-indexes.sql   CREATE INDEX rhn_usgp_sg_idx
    ON rhnUserServerGroupPerms (server_group_id)
    TABLESPACE [[4m_tbs]]
    NOLOGGING;
drop index rhn_usgp_sg_u_p_idx;
 070701000005EA000081B400000000000000000000000167AE1114000000BD000000000000000000000000000000000000006B00000000susemanager-schema/upgrade/spacewalk-schema-1.1-to-spacewalk-schema-1.2/269-rhnUserServerPrefs-indexes.sql    drop index rhn_usprefs_n_sid_uid_idx;

CREATE INDEX rhn_usprefs_sid_idx
    ON rhnUserServerPrefs (server_id)
    TABLESPACE [[2m_tbs]]
    NOLOGGING;
drop index rhn_usprefs_sid_uid_n_idx;
   070701000005EB000081B400000000000000000000000167AE111400000088000000000000000000000000000000000000006B00000000susemanager-schema/upgrade/spacewalk-schema-1.1-to-spacewalk-schema-1.2/270-rhnVirtualInstance-indexes.sql    CREATE INDEX rhn_vi_vsid_idx
    ON rhnVirtualInstance (virtual_system_id)
    TABLESPACE [[64k_tbs]];
drop index rhn_vi_vsid_hsid_idx;
070701000005EC000081B400000000000000000000000167AE11140000002D000000000000000000000000000000000000006800000000susemanager-schema/upgrade/spacewalk-schema-1.1-to-spacewalk-schema-1.2/271-rhnPackageNEVRA-indexes.sql   
drop index rhn_pkgnevra_nid_evrid_id_idx ;

   070701000005ED000081B400000000000000000000000167AE11140000002E000000000000000000000000000000000000006900000000susemanager-schema/upgrade/spacewalk-schema-1.1-to-spacewalk-schema-1.2/272-rhnServerProfile-indexes.sql  
drop index rhn_server_profile_o_id_bc_idx ;

  070701000005EE000081B400000000000000000000000167AE111400000023000000000000000000000000000000000000006B00000000susemanager-schema/upgrade/spacewalk-schema-1.1-to-spacewalk-schema-1.2/273-rhnSnapshotPackage-indexes.sql    
drop index rhn_snapshotpkg_sid ;

 070701000005EF000081B400000000000000000000000167AE111400000028000000000000000000000000000000000000006F00000000susemanager-schema/upgrade/spacewalk-schema-1.1-to-spacewalk-schema-1.2/274-rhnSatelliteChannelFamily-drop.sql    
drop table rhnSatelliteChannelFamily;

070701000005F0000081B400000000000000000000000167AE111400000046000000000000000000000000000000000000006C00000000susemanager-schema/upgrade/spacewalk-schema-1.1-to-spacewalk-schema-1.2/400-rhn_schedule_days_norm-drop.sql   
drop synonym schedule_days_norm;
drop table rhn_schedule_days_norm;

  070701000005F1000081B400000000000000000000000167AE111400000056000000000000000000000000000000000000007400000000susemanager-schema/upgrade/spacewalk-schema-1.1-to-spacewalk-schema-1.2/401-rhn_command_queue_instances_bk-drop.sql   
drop synonym command_queue_instances_bk;
drop table rhn_command_queue_instances_bk;

  070701000005F2000081B400000000000000000000000167AE11140000004E000000000000000000000000000000000000007000000000susemanager-schema/upgrade/spacewalk-schema-1.1-to-spacewalk-schema-1.2/402-rhn_command_queue_execs_bk-drop.sql   
drop synonym command_queue_execs_bk;
drop table rhn_command_queue_execs_bk;

  070701000005F3000081B400000000000000000000000167AE11140000004A000000000000000000000000000000000000007000000000susemanager-schema/upgrade/spacewalk-schema-1.1-to-spacewalk-schema-1.2/403-rhn_command_queue_execs_bk-drop.sql   
drop synonym command_center_state;
drop table rhn_command_center_state;

  070701000005F4000081B400000000000000000000000167AE11140000001D000000000000000000000000000000000000006400000000susemanager-schema/upgrade/spacewalk-schema-1.1-to-spacewalk-schema-1.2/404-rhnTextMessage-drop.sql   
drop table rhnTextMessage;

   070701000005F5000081B400000000000000000000000167AE111400000020000000000000000000000000000000000000006700000000susemanager-schema/upgrade/spacewalk-schema-1.1-to-spacewalk-schema-1.2/405-rhnEntitlementLog-drop.sql    
drop table rhnEntitlementLog;

070701000005F6000081B400000000000000000000000167AE11140000001C000000000000000000000000000000000000006300000000susemanager-schema/upgrade/spacewalk-schema-1.1-to-spacewalk-schema-1.2/406-rhnAllowTrust-drop.sql    
drop table rhnAllowTrust;

070701000005F7000081B400000000000000000000000167AE11140000001E000000000000000000000000000000000000006700000000susemanager-schema/upgrade/spacewalk-schema-1.1-to-spacewalk-schema-1.2/407-rhnBeehivePathMap-drop.sql    drop table rhnBeehivePathMap;
  070701000005F8000081B400000000000000000000000167AE111400000023000000000000000000000000000000000000006B00000000susemanager-schema/upgrade/spacewalk-schema-1.1-to-spacewalk-schema-1.2/408-rhnActionTransactions-drop.sql    
drop table rhnActionTransactions;
 070701000005F9000081B400000000000000000000000167AE111400000022000000000000000000000000000000000000006B00000000susemanager-schema/upgrade/spacewalk-schema-1.1-to-spacewalk-schema-1.2/409-rhnTransactionElement-drop.sql    drop table rhnTransactionElement;
  070701000005FA000081B400000000000000000000000167AE111400000041000000000000000000000000000000000000006400000000susemanager-schema/upgrade/spacewalk-schema-1.1-to-spacewalk-schema-1.2/410-rhnTransaction-drop.sql   drop table rhnTransaction;
drop sequence rhn_transaction_id_seq;
   070701000005FB000081B400000000000000000000000167AE111400000027000000000000000000000000000000000000006E00000000susemanager-schema/upgrade/spacewalk-schema-1.1-to-spacewalk-schema-1.2/411-rhn_interface_monitoring-drop.sql 
drop table rhn_interface_monitoring;

 070701000005FC000081B400000000000000000000000167AE111400000651000000000000000000000000000000000000005800000000susemanager-schema/upgrade/spacewalk-schema-1.1-to-spacewalk-schema-1.2/502-rhn_org.sql   --
-- Copyright (c) 2008--2010 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--

CREATE OR REPLACE
PACKAGE rhn_org
IS
	version varchar2(100) := '';

    CURSOR server_group_by_label(org_id_in NUMBER, group_label_in VARCHAR2) IS
    	   SELECT SG.*
	     FROM rhnServerGroupType SGT,
	     	  rhnServerGroup SG
	    WHERE SG.group_type = SGT.id
	      AND SGT.label = group_label_in
	      AND SG.org_id = org_id_in;
	    
    FUNCTION find_server_group_by_type(org_id_in NUMBER, 
                                       group_label_in VARCHAR2) 
    RETURN NUMBER;

    procedure delete_org(org_id_in in number);
    procedure delete_user(user_id_in in number, deleting_org in number := 0);

END rhn_org;
/
SHOW ERRORS

--
-- Revision 1.7  2004/07/13 22:46:04  pjones
-- bugzilla: 125938 -- nothing uses update_errata_cache() any more, remove it
--
-- Revision 1.6  2004/02/10 15:05:01  pjones
-- bugzilla: none -- add version tag here
--
-- Revision 1.5  2003/02/18 16:35:45  pjones
-- delete_user
--
-- Revision 1.4  2002/05/10 22:08:23  pjones
-- id/log
--
   070701000005FD000081B400000000000000000000000167AE1114000006D0000000000000000000000000000000000000005900000000susemanager-schema/upgrade/spacewalk-schema-1.1-to-spacewalk-schema-1.2/503-rhn_user.sql  --
-- Copyright (c) 2008--2010 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--

create or replace
package rhn_user
is
	version varchar2(100) := '';

    function check_role(user_id_in in number, role_in in varchar2) return number;
    PRAGMA RESTRICT_REFERENCES(check_role, WNDS, RNPS, WNPS);

    function check_role_implied(user_id_in in number, role_in in varchar2) return number;
    PRAGMA RESTRICT_REFERENCES(check_role_implied, WNDS, RNPS, WNPS);

    function get_org_id(user_id_in in number) return number;
    PRAGMA RESTRICT_REFERENCES(get_org_id, WNDS, RNPS, WNPS);
    
	function find_mailable_address(user_id_in in number) return varchar2;

	procedure add_servergroup_perm(
		user_id_in in number,
		server_group_id_in in number
	);

	procedure remove_servergroup_perm(
		user_id_in in number,
		server_group_id_in in number
	);

	procedure add_to_usergroup(
		user_id_in in number,
		user_group_id_in in number
	);

	procedure add_users_to_usergroups(
		user_id_in in number
	);

	procedure remove_from_usergroup(
		user_id_in in number,
		user_group_id_in in number
	);

	procedure remove_users_from_servergroups(
		user_id_in in number
	);
end rhn_user;
/
SHOW ERRORS
070701000005FE000081B400000000000000000000000167AE111400002120000000000000000000000000000000000000005E00000000susemanager-schema/upgrade/spacewalk-schema-1.1-to-spacewalk-schema-1.2/504-rhn_user-body.sql --
-- Copyright (c) 2008--2010 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--

create or replace
package body rhn_user
is
	body_version varchar2(100) := '';
	
    function check_role(user_id_in in number, role_in in varchar2)
    return number
    is
    	throwaway number;
    begin
    	-- the idea: if we get past this query, the org has the setting, else catch the exception and return 0
	select 1 into throwaway
	  from rhnUserGroupType UGT,
	       rhnUserGroup UG,
	       rhnUserGroupMembers UGM
	 where UGM.user_id = user_id_in
	   and UGM.user_group_id = UG.id
	   and UG.group_type = UGT.id
	   and UGT.label = role_in;
	   
	return 1;
    exception
    	when no_data_found
	    then
	    return 0;
    end check_role;
    
    function check_role_implied(user_id_in in number, role_in in varchar2)
    return number
    is
    	throwaway number;
    begin
    	-- if the user directly has the role, they win
    	if rhn_user.check_role(user_id_in, role_in) = 1
	then
	    return 1;
    	end if;

	-- config_admin and channel_admin are automatically implied for org admins	
	if role_in = 'config_admin' and rhn_user.check_role(user_id_in, 'org_admin') = 1
	then
	    return 1;
	end if;

	if role_in = 'channel_admin' and rhn_user.check_role(user_id_in, 'org_admin') = 1
	then
	    return 1;
	end if;

	return 0;	
    end check_role_implied;
    
    function get_org_id(user_id_in in number)
    return number
    is
    	org_id_out number;
    begin
    	select org_id into org_id_out
	  from web_contact
	 where id = user_id_in;
	 
	return org_id_out;
    end get_org_id;

	-- paid users often don't have verified email addresses, so
	-- try to find an address that is useful to us.
	function find_mailable_address(user_id_in in number)
	return varchar2 is
		PRAGMA AUTONOMOUS_TRANSACTION;
		-- this would be so much prettier if we just had an order built
		-- into rhnEmailAddressState
		cursor addrs is
			select	ea.state_id, ea.address
			from	rhnEmailAddressState eas,
					rhnEmailAddress ea
			where	ea.user_id = user_id_in
				and eas.label = 'verified'
				and ea.state_id = eas.id
			union all
			select	ea.state_id, ea.address
			from	rhnEmailAddressState eas,
					rhnEmailAddress ea
			where	ea.user_id = user_id_in
				and eas.label = 'unverified'
				and ea.state_id = eas.id
			union all
			select	ea.state_id, ea.address
			from	rhnEmailAddressState eas,
					rhnEmailAddress ea
			where	ea.user_id = user_id_in
				and eas.label = 'pending'
				and ea.state_id = eas.id
			union all
			select	ea.state_id, ea.address
			from	rhnEmailAddressState eas,
					rhnEmailAddress ea
			where	ea.user_id = user_id_in
				and eas.label = 'pending_warned'
				and ea.state_id = eas.id
			union all
			select	ea.state_id, ea.address
			from	rhnEmailAddressState eas,
					rhnEmailAddress ea
			where	ea.user_id = user_id_in
				and eas.label = 'needs_verifying'
				and ea.state_id = eas.id
			union all
			select	-1 state_id,
					email address
			from	web_user_personal_info
			where	web_user_id = user_id_in;
		retval rhnEmailAddress.address%TYPE;
	begin
		for addr in addrs loop
			retval := addr.address;
			if addr.address is null then
				update web_user_contact_permission
					set email = 'N'
					where web_user_id = user_id_in;
				commit;
				return null;
			end if;
			if addr.state_id = -1 then
				insert into rhnEmailAddress (
						id, address,
						user_id, state_id
					) (
						select	rhn_eaddress_id_seq.nextval, addr.address,
								user_id_in, eas.id
						from	rhnEmailAddressState eas
						where	eas.label = 'unverified'
					);
			end if;
			commit;
			return retval;
		end loop;
		return null;
	end;

	procedure add_servergroup_perm(
		user_id_in in number,
		server_group_id_in in number
	) is
		cursor	orgs_match is
			select	1
			from	rhnServerGroup sg,
					web_contact u
			where	u.id = user_id_in
				and sg.id = server_group_id_in
				and sg.org_id = u.org_id;
	begin
		for okay in orgs_match loop
			insert into rhnUserServerGroupPerms(user_id, server_group_id)
				values (user_id_in, server_group_id_in);
			rhn_cache.update_perms_for_user(user_id_in);
			return;
		end loop;
		rhn_exception.raise_exception('usgp_different_orgs');
	exception when dup_val_on_index then
		rhn_exception.raise_exception('usgp_already_allowed');
	end add_servergroup_perm;

	procedure remove_servergroup_perm(
		user_id_in in number,
		server_group_id_in in number
	) is
		cursor perms is
			select	1
			from	rhnUserServerGroupPerms
			where	user_id = user_id_in
				and server_group_id = server_group_id_in;
	begin
		for perm in perms loop
			delete from rhnUserServerGroupPerms
				where	user_id = user_id_in
					and server_group_id = server_group_id_in;
			rhn_cache.update_perms_for_user(user_id_in);
			return;
		end loop;
		rhn_exception.raise_exception('usgp_not_allowed');
	end remove_servergroup_perm;

	procedure add_to_usergroup(
		user_id_in in number,
		user_group_id_in in number
	) is
		cursor perm_granting_usergroups is
			select	user_group_id_in
			from	rhnUserGroup		ug,
					rhnUserGroupType	ugt
			where	ugt.label in ('org_admin') -- and server_group_admin ?
				and ug.id = user_group_id_in
				and ug.group_type = ugt.id;
	begin
		insert into rhnUserGroupMembers(user_id, user_group_id)
			values (user_id_in, user_group_id_in);

		for ug in perm_granting_usergroups loop
			rhn_cache.update_perms_for_user(user_id_in);
			return;
		end loop;
	end add_to_usergroup;

	procedure add_users_to_usergroups(
		user_id_in in number
	) is
		cursor ugms is
			select	element user_id,
					element_two user_group_id
			from	rhnSet
			where	user_id = user_id_in
				and label = 'user_group_list';
	begin
		for ugm in ugms loop
			rhn_user.add_to_usergroup(ugm.user_id, ugm.user_group_id);
		end loop;
	end add_users_to_usergroups;

	procedure remove_from_usergroup(
		user_id_in in number,
		user_group_id_in in number
	) is
		cursor perm_granting_usergroups is
			select	label
			from	rhnUserGroupType	ugt,
					rhnUserGroupMembers	ugm,
					rhnUserGroup		ug
			where	1=1
				and ug.id = user_group_id_in
				and ugm.user_group_id = user_group_id_in
				and ug.group_type = ugt.id
				and ugm.user_id = user_id_in;
	begin
		-- we only do anything if you're really in the group, because
		-- testing is significantly cheaper than rebuilding the user's
		-- cache for no reason.
		for ug in perm_granting_usergroups loop
			delete from rhnUserGroupMembers
				where	user_id = user_id_in
					and user_group_id = user_group_id_in;
			if ug.label in ('org_admin') then
				rhn_cache.update_perms_for_user(user_id_in);
			end if;
		end loop;
	end remove_from_usergroup;

	procedure remove_users_from_servergroups(
		user_id_in in number
	) is
		cursor ugms is
			select	element user_id,
					element_two user_group_id
			from	rhnSet
			where	user_id = user_id_in
				and label = 'user_group_list';
	begin
		for ugm in ugms loop
			rhn_user.remove_from_usergroup(ugm.user_id, ugm.user_group_id);
		end loop;
	end remove_users_from_servergroups;
end rhn_user;
/
SHOW ERRORS

-- select rhn_user.get_org_id(502474) from dual;
-- 1271287
-- select rhn_user.check_role(502474, 'org_admin') from dual;
-- 1
-- select rhn_user.check_role(502474, 'org_admin_nope') from dual;
-- 0, but should later raise an exception

--
--
-- Revision 1.8  2004/07/12 19:35:51  pjones
-- bugzilla: 125937 -- we _always_ delete, but only rebuild cache on org_admin.
--
-- Revision 1.7  2004/07/02 22:29:36  pjones
-- bugzilla: none -- typos and spelling errors.
--
-- Revision 1.6  2004/07/02 19:16:54  pjones
-- bugzilla: 125937 -- tools to manipulate rhnServerGroupMembers and
-- rhnUserGroupMembers
--
-- Revision 1.5  2004/03/31 21:09:47  pjones
-- bugzilla: none -- if the user truly doesn't have any email address, compensate.
--
-- Revision 1.4  2004/02/12 20:53:30  pjones
-- bugzilla: 108212 -- s/get_email_address/find_mailable_address/ and make it
-- do the same as web's version
--
070701000005FF000081B400000000000000000000000167AE111400000807000000000000000000000000000000000000006400000000susemanager-schema/upgrade/spacewalk-schema-1.1-to-spacewalk-schema-1.2/505-rhnServerFveCapable.sql   --
-- Copyright (c) 2008--2010 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--
-- A view to list systems that fve capable but that are not actually using
--    and fve entitlement
create or replace view 
rhnServerFveCapable (
 server_id,
 server_org_id,
 channel_family_id,
 current_members,
 max_members,
 channel_family_name
)
as
select  S.id as server_id,
        S.org_id as server_org_id,
        cf.id as channel_family_id,
        pcf.FVE_CURRENT_MEMBERS as current_members,
        pcf.FVE_MAX_MEMBERS as max_members,
        cf.name as channel_family_name
from
     RhnVirtualInstance vi
     inner join rhnServer s on vi.virtual_system_id = s.id
     inner join rhnServerChannel sc on sc.server_id = s.id
     inner join rhnChannelFamilyMembers cfm on cfm.channel_id = sc.channel_id
     inner join rhnChannelFamily cf on cf.id = cfm.channel_family_id
     inner join rhnPrivateChannelFamily pcf on pcf.channel_family_id  = cf.id and pcf.org_id = s.org_id
where sc.is_fve = 'N'
     AND (vi.host_system_id is null OR
     exists (
          select sg.id 
            from rhnServerGroupMembers sgm
                 inner join rhnServerGroup sg on sgm.server_group_id = sg.id
                 inner join rhnServerGroupType sgt on sgt.id = sg.group_type
                 inner join rhnServer s2 on s2.id = sgm.server_id
             where
                 s2.id = vi.host_system_id
                 and sgt.label not in ('virtualization_host' ,'virtualization_host_platform') )
      );

 07070100000600000081B400000000000000000000000167AE111400000022000000000000000000000000000000000000006B00000000susemanager-schema/upgrade/spacewalk-schema-1.1-to-spacewalk-schema-1.2/506-rhnActionPackageOrder-drop.sql    drop table rhnActionPackageOrder;
  07070100000601000081B400000000000000000000000167AE11140000001D000000000000000000000000000000000000006600000000susemanager-schema/upgrade/spacewalk-schema-1.1-to-spacewalk-schema-1.2/507-rhnChannelParent-drop.sql drop table rhnChannelParent;
   07070100000602000081B400000000000000000000000167AE11140000001F000000000000000000000000000000000000006800000000susemanager-schema/upgrade/spacewalk-schema-1.1-to-spacewalk-schema-1.2/508-rhnEmailAddressLog-drop.sql   drop table rhnEmailAddressLog;
 07070100000603000081B400000000000000000000000167AE111400000025000000000000000000000000000000000000006E00000000susemanager-schema/upgrade/spacewalk-schema-1.1-to-spacewalk-schema-1.2/509-rhnGrailComponentChoices-drop.sql drop table rhnGrailComponentChoices;
   07070100000604000081B400000000000000000000000167AE111400000047000000000000000000000000000000000000006800000000susemanager-schema/upgrade/spacewalk-schema-1.1-to-spacewalk-schema-1.2/510-rhnGrailComponents-drop.sql   drop table rhnGrailComponents;
drop sequence rhn_grail_components_seq;
 07070100000605000081B400000000000000000000000167AE11140000003A000000000000000000000000000000000000006000000000susemanager-schema/upgrade/spacewalk-schema-1.1-to-spacewalk-schema-1.2/511-rhnMonitor-drop.sql   drop table rhnMonitor;
drop sequence rhn_monitor_bid_seq;
  07070100000606000081B400000000000000000000000167AE11140000001F000000000000000000000000000000000000006800000000susemanager-schema/upgrade/spacewalk-schema-1.1-to-spacewalk-schema-1.2/512-rhnPackageSenseMap-drop.sql   drop table rhnPackageSenseMap;
 07070100000607000081B400000000000000000000000167AE11140000001E000000000000000000000000000000000000006700000000susemanager-schema/upgrade/spacewalk-schema-1.1-to-spacewalk-schema-1.2/513-rhnPathChannelMap-drop.sql    drop table rhnPathChannelMap;
  07070100000608000081B400000000000000000000000167AE11140000001E000000000000000000000000000000000000006700000000susemanager-schema/upgrade/spacewalk-schema-1.1-to-spacewalk-schema-1.2/514-rhnProductChannel-drop.sql    drop table rhnProductChannel;
  07070100000609000081B400000000000000000000000167AE111400000042000000000000000000000000000000000000006900000000susemanager-schema/upgrade/spacewalk-schema-1.1-to-spacewalk-schema-1.2/515-rhnRelationshipType-drop.sql  drop table rhnRelationshipType;
drop sequence rhn_reltype_id_seq;
  0707010000060A000081B400000000000000000000000167AE111400000041000000000000000000000000000000000000006400000000susemanager-schema/upgrade/spacewalk-schema-1.1-to-spacewalk-schema-1.2/516-rhnSavedSearch-drop.sql   drop table rhnSavedSearch;
drop sequence rhn_savedsearch_id_seq;
   0707010000060B000081B400000000000000000000000167AE11140000001F000000000000000000000000000000000000006800000000susemanager-schema/upgrade/spacewalk-schema-1.1-to-spacewalk-schema-1.2/517-rhnServerCacheInfo-drop.sql   drop table rhnServerCacheInfo;
 0707010000060C000081B400000000000000000000000167AE11140000004F000000000000000000000000000000000000006B00000000susemanager-schema/upgrade/spacewalk-schema-1.1-to-spacewalk-schema-1.2/518-rhnMonitorGranularity-drop.sql    drop table rhnMonitorGranularity;
drop sequence rhn_monitorgranularity_id_seq;
 0707010000060D000081B400000000000000000000000167AE111400000039000000000000000000000000000000000000006000000000susemanager-schema/upgrade/spacewalk-schema-1.1-to-spacewalk-schema-1.2/519-rhnProduct-drop.sql   drop table rhnProduct;
drop sequence rhn_product_id_seq;
   0707010000060E000081B400000000000000000000000167AE11140000001C000000000000000000000000000000000000006500000000susemanager-schema/upgrade/spacewalk-schema-1.1-to-spacewalk-schema-1.2/520-rhnPackageSense-drop.sql  drop table rhnPackageSense;
0707010000060F000081B400000000000000000000000167AE111400000040000000000000000000000000000000000000006800000000susemanager-schema/upgrade/spacewalk-schema-1.1-to-spacewalk-schema-1.2/521-rhnSavedSearchType-drop.sql   drop table rhnSavedSearchType;
drop sequence rhn_sstype_id_seq;
07070100000610000081B400000000000000000000000167AE11140000003F000000000000000000000000000000000000006400000000susemanager-schema/upgrade/spacewalk-schema-1.1-to-spacewalk-schema-1.2/522-rhnProductLine-drop.sql   drop table rhnProductLine;
drop sequence rhn_prod_line_id_seq;
 07070100000611000081B400000000000000000000000167AE11140000001D000000000000000000000000000000000000006600000000susemanager-schema/upgrade/spacewalk-schema-1.1-to-spacewalk-schema-1.2/523-rhnServerMessage-drop.sql drop table rhnServerMessage;
   07070100000612000081B400000000000000000000000167AE111400000033000000000000000000000000000000000000006000000000susemanager-schema/upgrade/spacewalk-schema-1.1-to-spacewalk-schema-1.2/524-rhnMessage-drop.sql   drop table rhnMessage;
drop sequence rhn_m_id_seq;
 07070100000613000081B400000000000000000000000167AE111400000044000000000000000000000000000000000000006800000000susemanager-schema/upgrade/spacewalk-schema-1.1-to-spacewalk-schema-1.2/525-rhnMessagePriority-drop.sql   drop table rhnMessagePriority;
drop sequence rhn_m_priority_id_seq;
07070100000614000081B400000000000000000000000167AE111400000038000000000000000000000000000000000000006400000000susemanager-schema/upgrade/spacewalk-schema-1.1-to-spacewalk-schema-1.2/526-rhnMessageType-drop.sql   drop table rhnMessageType;
drop sequence rhn_mt_id_seq;
07070100000615000081B400000000000000000000000167AE111400000024000000000000000000000000000000000000006D00000000susemanager-schema/upgrade/spacewalk-schema-1.1-to-spacewalk-schema-1.2/527-rhnSatelliteServerGroup-drop.sql  drop table rhnSatelliteServerGroup;
07070100000616000081B400000000000000000000000167AE111400000042000000000000000000000000000000000000006B00000000susemanager-schema/upgrade/spacewalk-schema-1.1-to-spacewalk-schema-1.2/528-rhn_host_check_suites-drop.sql    drop synonym host_check_suites;
drop table rhn_host_check_suites;
  07070100000617000081B400000000000000000000000167AE1114000000C2000000000000000000000000000000000000006B00000000susemanager-schema/upgrade/spacewalk-schema-1.1-to-spacewalk-schema-1.2/530-rhnErrataNotificationQueue.sql    ALTER TABLE rhnErrataNotificationQueue DROP CONSTRAINT rhn_enqueue_eoid_uq;
ALTER TABLE rhnErrataNotificationQueue
    ADD CONSTRAINT rhn_enqueue_eoid_uq UNIQUE (errata_id, channel_id, org_id);
  07070100000618000081B400000000000000000000000167AE111400000020000000000000000000000000000000000000006A00000000susemanager-schema/upgrade/spacewalk-schema-1.1-to-spacewalk-schema-1.2/531-rhnPrivateErrataMail-drop.sql drop view rhnPrivateErrataMail;
07070100000619000081B400000000000000000000000167AE111400000025000000000000000000000000000000000000006F00000000susemanager-schema/upgrade/spacewalk-schema-1.1-to-spacewalk-schema-1.2/532-rhnChannelPackageOverview-drop.sql    drop view rhnChannelPackageOverview;
   0707010000061A000081B400000000000000000000000167AE111400000021000000000000000000000000000000000000006B00000000susemanager-schema/upgrade/spacewalk-schema-1.1-to-spacewalk-schema-1.2/533-rhnOrgPackageOverview-drop.sql    drop view rhnOrgPackageOverview;
   0707010000061B000081B400000000000000000000000167AE111400000021000000000000000000000000000000000000006B00000000susemanager-schema/upgrade/spacewalk-schema-1.1-to-spacewalk-schema-1.2/534-rhnUserAppletOverview-drop.sql    drop view rhnUserAppletOverview;
   0707010000061C000081B400000000000000000000000167AE111400000022000000000000000000000000000000000000006C00000000susemanager-schema/upgrade/spacewalk-schema-1.1-to-spacewalk-schema-1.2/535-rhnUserGroupMembership-drop.sql   drop view rhnUserGroupMembership;
  0707010000061D000081B400000000000000000000000167AE11140000003C000000000000000000000000000000000000006700000000susemanager-schema/upgrade/spacewalk-schema-1.1-to-spacewalk-schema-1.2/540-rhnPaidErrataTempCache.sql    DROP index rhnpec_u_idx;
DROP TABLE rhnPaidErrataTempCache;
0707010000061E000081B400000000000000000000000167AE111400000680000000000000000000000000000000000000005E00000000susemanager-schema/upgrade/spacewalk-schema-1.1-to-spacewalk-schema-1.2/541-delete_errata.sql --
-- Copyright (c) 2008--2010 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--
--
--
--

create or replace procedure
delete_errata (
	errata_id_in in number
) is
begin
	delete from rhnServerNeededCache where errata_id = errata_id_in;
	delete from rhnErrataFile where errata_id = errata_id_in;
	delete from rhnErrataPackage where errata_id = errata_id_in;
	delete from rhnErrata where id = errata_id_in;
	delete from rhnErrataTmp where id = errata_id_in;
end delete_errata;
/
show errors

--
-- Revision 1.4  2004/12/04 21:24:51  cturner
-- bugzilla: 141768, and another one.  pre-delete from rhnErrataPackage to prevent trigger madness
--
-- Revision 1.3  2004/12/04 21:14:25  cturner
-- bugzilla: 141768, pre-delete from rhnErrataFile to prevent trigger madness
--
-- Revision 1.2  2004/09/13 20:56:44  pjones
-- bugzilla: 117597 --
-- 1) make the constraints look like they do in prod.
-- 2) remove the sat-only errata_id index
-- 3) remove duplicate server_id based index.
-- 4) make a new index that starts with errata
--
-- Revision 1.1  2003/08/15 20:45:44  pjones
-- bugzilla: 102263
--
-- delete_errata()
--
0707010000061F000081B400000000000000000000000167AE111400000498000000000000000000000000000000000000006300000000susemanager-schema/upgrade/spacewalk-schema-1.1-to-spacewalk-schema-1.2/542-lookup_config_info.sql    create or replace function
lookup_config_info (
    username_in     in varchar2,
    groupname_in    in varchar2,
    filemode_in     in number,
    selinux_ctx_in  in varchar2,
    symlink_target_id in number
) return number
deterministic
is
    pragma autonomous_transaction;
    v_id    number;
    cursor lookup_cursor is
        select id
          from rhnConfigInfo
         where 1=1
           and nvl(username, ' ') = nvl(username_in, ' ')
           and nvl(groupname,' ') = nvl(groupname_in, ' ')
           and nvl(filemode, -1) = nvl(filemode_in, -1)
           and nvl(selinux_ctx, ' ') = nvl(selinux_ctx_in, ' ')
           and nvl(symlink_target_filename_id, -1) = nvl(symlink_target_id, -1)
        ;
begin
    for r in lookup_cursor loop
        return r.id;
    end loop;
    -- If we got here, we don't have the id
    select rhn_confinfo_id_seq.nextval
      into v_id
      from dual;
    insert into rhnConfigInfo (id, username, groupname, filemode, selinux_ctx, symlink_target_filename_id)
    values (v_id, username_in, groupname_in, filemode_in, selinux_ctx_in, symlink_target_id);
    commit;
    return v_id;
end lookup_config_info;
/
show errors
07070100000620000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000004900000000susemanager-schema/upgrade/spacewalk-schema-1.10-to-spacewalk-schema-2.0  07070100000621000081B400000000000000000000000167AE11140000007A000000000000000000000000000000000000005000000000susemanager-schema/upgrade/spacewalk-schema-1.10-to-spacewalk-schema-2.0/README   -- Schema upgrade scripts.
-- leave this directory empty, all upgrades from 1.9 to 2.0 are covered by 1.9 to 1.10 upgrade
  07070100000622000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000004800000000susemanager-schema/upgrade/spacewalk-schema-1.2-to-spacewalk-schema-1.3   07070100000623000081B400000000000000000000000167AE1114000000C0000000000000000000000000000000000000006200000000susemanager-schema/upgrade/spacewalk-schema-1.2-to-spacewalk-schema-1.3/001-rhnTaskoTask_data.sql INSERT INTO rhnTaskoTask (id, name, class)
             VALUES (sequence_nextval('rhn_tasko_task_id_seq'), 'cleanup-packagechangelog-data', 'com.redhat.rhn.taskomatic.task.ChangeLogCleanUp');
07070100000624000081B400000000000000000000000167AE111400000138000000000000000000000000000000000000006600000000susemanager-schema/upgrade/spacewalk-schema-1.2-to-spacewalk-schema-1.3/002-rhnTaskoTemplate_data.sql INSERT INTO rhnTaskoTemplate (id, bunch_id, task_id, ordering, start_if)
    VALUES (sequence_nextval('rhn_tasko_template_id_seq'),
        (SELECT id FROM rhnTaskoBunch WHERE name='cleanup-data-bunch'),
        (SELECT id FROM rhnTaskoTask WHERE name='cleanup-packagechangelog-data'),
        1,
        null);
07070100000625000081B400000000000000000000000167AE11140000001C000000000000000000000000000000000000005F00000000susemanager-schema/upgrade/spacewalk-schema-1.2-to-spacewalk-schema-1.3/003-rhnDaemonState.sql    DROP TABLE rhnDaemonState;

07070100000626000081B400000000000000000000000167AE1114000002E7000000000000000000000000000000000000006100000000susemanager-schema/upgrade/spacewalk-schema-1.2-to-spacewalk-schema-1.3/004-rhn_channel-body.sql  --
-- Copyright (c) 2011--2012 Red Hat, Inc.

--update pg_setting
update pg_settings set setting = 'rhn_channel,' || setting where name = 'search_path';

    create or replace function can_server_consume_fve(server_id_in in numeric) returns numeric
    as $$
    declare
        vi_entries cursor for
            SELECT 1
              FROM rhnVirtualInstance vi
             WHERE vi.virtual_system_id = server_id_in;
        vi_count numeric;

    begin
        FOR vi_entry IN VI_ENTRIES LOOP
            return 1;
        END LOOP;
        RETURN 0;
    end$$ language plpgsql;

-- restore the original setting
update pg_settings set setting = overlay( setting placing '' from 1 for (length('rhn_channel')+1) ) where name = 'search_path';
 07070100000627000081B400000000000000000000000167AE111400000023000000000000000000000000000000000000006100000000susemanager-schema/upgrade/spacewalk-schema-1.2-to-spacewalk-schema-1.3/005-rhn_package-drop.sql  
drop schema rhn_package cascade;

 07070100000628000081B400000000000000000000000167AE1114000001C3000000000000000000000000000000000000005800000000susemanager-schema/upgrade/spacewalk-schema-1.2-to-spacewalk-schema-1.3/006-rhn_org.sql   --
-- Copyright (c) 2011--2012 Red Hat, Inc.

-- setup search_path so that these functions are created in appropriate schema.
update pg_settings set setting = 'rhn_org,' || setting where name = 'search_path';

drop function find_server_group_by_type(org_id_in NUMERIC, group_label_in VARCHAR);

-- restore the original setting
update pg_settings set setting = overlay( setting placing '' from 1 for (length('rhn_org')+1) ) where name = 'search_path';
 07070100000629000081B400000000000000000000000167AE1114000014DF000000000000000000000000000000000000005D00000000susemanager-schema/upgrade/spacewalk-schema-1.2-to-spacewalk-schema-1.3/007-rhn_org-body.sql  --
-- Copyright (c) 2011--2012 Red Hat, Inc.

-- setup search_path so that these functions are created in appropriate schema.
update pg_settings set setting = 'rhn_org,' || setting where name = 'search_path';

create or replace function delete_user(user_id_in in numeric, deleting_org in numeric default 0) returns void 
    as
    $$
    declare
    servergroups_needing_admins cursor for
            select    usgp.server_group_id    server_group_id
            from    rhnUserServerGroupPerms    usgp
            where    1=1
                and usgp.user_id = user_id_in
                and not exists (
                    select    1
                    from    rhnUserServerGroupPerms    sq_usgp
                    where    1=1
                        and sq_usgp.server_group_id = usgp.server_group_id
                        and    sq_usgp.user_id != user_id_in
                );
        users            numeric;
        our_org_id        numeric;
        other_users        numeric;
        other_org_admin    numeric;
        other_user_id  numeric;
        is_admin       numeric;
    begin
        select    wc.org_id
        into    our_org_id
        from    web_contact wc
        where    id = user_id_in;

        -- find any other users
        begin
            select    id, 1
            into    other_user_id, other_users
            from    web_contact
            where    1=1
                and org_id = our_org_id
                and id != user_id_in
                limit 1;
        exception
            when no_data_found then
                other_users := 0;
        end;

        -- now do org admin stuff
        if other_users != 0 then
            -- is user admin?
            select  count(1)
             into   is_admin
            from    rhnUserGroupType    ugt,
                    rhnUserGroup        ug,
                    rhnUserGroupMembers    ugm
            where    ugm.user_id = user_id_in
                and ugm.user_group_id = ug.id
                and ug.group_type = ugt.id
                and ugt.label = 'org_admin';
            if is_admin > 0 then
                begin
                    select    new_ugm.user_id
                    into    other_org_admin
                    from    rhnUserGroupMembers    new_ugm,
                            rhnUserGroupType    ugt,
                            rhnUserGroup        ug,
                            rhnUserGroupMembers    ugm
                    where    ugm.user_id = user_id_in
                        and ugm.user_group_id = ug.id
                        and ug.group_type = ugt.id
                        and ugt.label = 'org_admin'
                        and ug.id = new_ugm.user_group_id
                        and new_ugm.user_id != user_id_in
                        limit 1;
                exception
                    when no_data_found then
                        -- If we're deleting the org, we don't want to raise
                        -- the exception.
                        if deleting_org = 0 then
                           perform rhn_exception.raise_exception('cannot_delete_user');
                        end if;
                end;

                for sg in servergroups_needing_admins loop
                   perform rhn_user.add_servergroup_perm(other_org_admin,
                        sg.server_group_id);
                end loop;
            end if;
        end if;

        -- and now things for every user
        delete from rhn_command_queue_sessions where contact_id = user_id_in;
        delete from rhn_contact_groups
        where recid in (
            select contact_group_id
            from rhn_contact_group_members
            where member_contact_method_id in (
                select recid from rhn_contact_methods
                where contact_id = user_id_in
                )
            )
            and not exists (
                select 1
                from rhn_contact_group_members, rhn_contact_methods
                where rhn_contact_groups.recid = rhn_contact_group_members.contact_group_id
                    and rhn_contact_group_members.member_contact_method_id = rhn_contact_methods.recid
                    and rhn_contact_methods.contact_id <> user_id_in
            );
        delete from rhn_contact_methods where contact_id = user_id_in;
        delete from rhn_redirects where contact_id = user_id_in;
        delete from rhnUserServerPerms where user_id = user_id_in;
        delete from rhnAppInstallSession where user_id = user_id_in;
        update rhnConfigRevision
           set changed_by_id = NULL
         where changed_by_id = user_id_in;
        if other_users != 0 then
            update        rhnRegToken
                set        user_id = coalesce(other_org_admin, other_user_id)
                where    org_id = our_org_id
                    and user_id = user_id_in;
        end if;

        begin
            delete from web_contact where id = user_id_in;
        exception
            when others then
               perform rhn_exception.raise_exception('cannot_delete_user');
        end;
        return;

        end;
        $$
        language plpgsql;

-- restore the original setting
update pg_settings set setting = overlay( setting placing '' from 1 for (length('rhn_org')+1) ) where name = 'search_path';
 0707010000062A000081B400000000000000000000000167AE111400000448000000000000000000000000000000000000005900000000susemanager-schema/upgrade/spacewalk-schema-1.2-to-spacewalk-schema-1.3/011-rpm-body.sql  
--update pg_setting
update pg_settings set setting = 'rpm,' || setting where name = 'search_path';

   create or replace FUNCTION vercmp(
        e1 VARCHAR, v1 VARCHAR, r1 VARCHAR, 
        e2 VARCHAR, v2 VARCHAR, r2 VARCHAR)
    RETURNS INTEGER as $$
    declare
        rc INTEGER;
          ep1 INTEGER;
          ep2 INTEGER;
          BEGIN
            if e1 is null or e1 = '' then
              ep1 := 0;
            else
              ep1 := e1::integer;
            end if;
            if e2 is null or e2 = '' then
              ep2 := 0;
            else
              ep2 := e2::integer;
            end if;
            -- Epochs are non-null; compare them
            if ep1 < ep2 then return -1; end if;
            if ep1 > ep2 then return 1; end if;
            rc := rpm.rpmstrcmp(v1, v2);
            if rc != 0 then return rc; end if;
           return rpm.rpmstrcmp(r1, r2);
         END;
         $$ language 'plpgsql';

-- restore the original setting
update pg_settings set setting = overlay( setting placing '' from 1 for (length('rpm')+1) ) where name = 'search_path';
0707010000062B000081B400000000000000000000000167AE1114000001F4000000000000000000000000000000000000005900000000susemanager-schema/upgrade/spacewalk-schema-1.2-to-spacewalk-schema-1.3/012-rhn_user.sql  --
-- Copyright (c) 2011--2012 Red Hat, Inc.

-- setup search_path so that these functions are created in appropriate schema.
update pg_settings set setting = 'rhn_user,' || setting where name = 'search_path';

drop function add_users_to_usergroups(user_id_in in numeric);
drop function remove_users_from_servergroups(user_id_in in numeric);

-- restore the original setting
update pg_settings set setting = overlay( setting placing '' from 1 for (length('rhn_user')+1) ) where name = 'search_path';
0707010000062C000081B400000000000000000000000167AE11140000091A000000000000000000000000000000000000006400000000susemanager-schema/upgrade/spacewalk-schema-1.2-to-spacewalk-schema-1.3/014-rhn_entitlement_pkb.sql   --
-- Copyright (c) 2011 Red Hat, Inc.

-- setup search_path so that these functions are created in appropriate schema.
update pg_settings set setting = 'rhn_entitlements,' || setting where name = 'search_path';

    create or replace function set_customer_enterprise (
        customer_id_in in numeric
    ) returns void
as $$
    begin
        perform rhn_entitlements.modify_org_service(customer_id_in, 'enterprise', 'Y');
    end$$
language plpgsql;

    create or replace function set_customer_provisioning (
        customer_id_in in numeric
    ) returns void
as $$
    begin
        perform rhn_entitlements.modify_org_service(customer_id_in, 'provisioning', 'Y');
    end$$
language plpgsql;

    create or replace function set_customer_monitoring (
        customer_id_in in numeric
    ) returns void
as $$
    begin
        perform rhn_entitlements.modify_org_service(customer_id_in, 'monitoring', 'Y');
    end$$
language plpgsql;

    create or replace function set_customer_nonlinux (
        customer_id_in in numeric
    ) returns void
as $$
    begin
        perform rhn_entitlements.modify_org_service(customer_id_in, 'nonlinux', 'Y');
    end$$
language plpgsql;

    create or replace function unset_customer_enterprise (
        customer_id_in in numeric
    ) returns void
as $$
    begin
        perform rhn_entitlements.modify_org_service(customer_id_in, 'enterprise', 'N');
    end$$
language plpgsql;

    create or replace function unset_customer_provisioning (
        customer_id_in in numeric
    ) returns void
as $$
    begin
        perform rhn_entitlements.modify_org_service(customer_id_in, 'provisioning', 'N');
    end$$
language plpgsql;

    create or replace function unset_customer_monitoring (
        customer_id_in in numeric
    ) returns void
as $$
    begin
        perform rhn_entitlements.modify_org_service(customer_id_in, 'monitoring', 'N');
    end$$
language plpgsql;

    create or replace function unset_customer_nonlinux (
        customer_id_in in numeric
    ) returns void
as $$
    begin
        perform rhn_entitlements.modify_org_service(customer_id_in, 'nonlinux', 'N');
    end$$
language plpgsql;

-- restore the original setting
update pg_settings set setting = overlay( setting placing '' from 1 for (length('rhn_entitlements')+1) ) where name = 'search_path';
  0707010000062D000081B400000000000000000000000167AE111400000807000000000000000000000000000000000000006400000000susemanager-schema/upgrade/spacewalk-schema-1.2-to-spacewalk-schema-1.3/015-rhnServerFveCapable.sql   --
-- Copyright (c) 2008--2011 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--
-- A view to list systems that fve capable but that are not actually using
--    and fve entitlement
create or replace view 
rhnServerFveCapable (
 server_id,
 server_org_id,
 channel_family_id,
 current_members,
 max_members,
 channel_family_name
)
as
select  S.id as server_id,
        S.org_id as server_org_id,
        cf.id as channel_family_id,
        pcf.FVE_CURRENT_MEMBERS as current_members,
        pcf.FVE_MAX_MEMBERS as max_members,
        cf.name as channel_family_name
from
     RhnVirtualInstance vi
     inner join rhnServer s on vi.virtual_system_id = s.id
     inner join rhnServerChannel sc on sc.server_id = s.id
     inner join rhnChannelFamilyMembers cfm on cfm.channel_id = sc.channel_id
     inner join rhnChannelFamily cf on cf.id = cfm.channel_family_id
     inner join rhnPrivateChannelFamily pcf on pcf.channel_family_id  = cf.id and pcf.org_id = s.org_id
where sc.is_fve = 'N'
     AND (vi.host_system_id is null OR
     not exists (
          select sg.id 
            from rhnServerGroupMembers sgm
                 inner join rhnServerGroup sg on sgm.server_group_id = sg.id
                 inner join rhnServerGroupType sgt on sgt.id = sg.group_type
                 inner join rhnServer s2 on s2.id = sgm.server_id
             where
                 s2.id = vi.host_system_id
                 and sgt.label in ('virtualization_host' ,'virtualization_host_platform') )
      );

 0707010000062E000081B400000000000000000000000167AE111400000CDD000000000000000000000000000000000000006B00000000susemanager-schema/upgrade/spacewalk-schema-1.2-to-spacewalk-schema-1.3/016-rhnpackage-build_time-type.sql    
-- The drop is needed to avoid
-- ERROR:  cannot alter type of a column used by a view or rule
-- DETAIL:  rule _RETURN on view rhnserverneededview depends on column "build_time"
-- in the alter table command.

drop view rhnserverneededview;

alter table rhnpackage alter build_time type timestamp without time zone ;

-- recreating the view
create or replace view
rhnServerNeededView
(
    org_id,
    server_id,
    errata_id,
    package_id,
    package_name_id,
    channel_id
)
as
select s.org_id,
       s.id as server_id,
       pce.errata_id,
       pkg.id as package_id,
       neededpkg.name_id as package_name_id,
       scp.min_channel_id as channel_id
  from (select sc.server_id, np.name_id, np.package_arch_id, max(np.evr) max_evr
          from (-- list of newest packages in channels with EVR
                select np_np.*, np_pe.evr
                  from rhnChannelNewestPackage np_np
                  join rhnPackageEVR np_pe
                    on np_pe.id = np_np.evr_id) np
          join (-- list of packages on the server with EVR
                select sp_sp.server_id, sp_sp.name_id, sp_sp.package_arch_id, max(sp_pe.evr) as max_evr
                  from rhnServerPackage sp_sp
                  join rhnPackageEVR sp_pe
                    on sp_pe.id = sp_sp.evr_id
                 group by sp_sp.server_id, sp_sp.name_id, sp_sp.package_arch_id) sp
            on -- at first - we want only newer (=higher EVR) packages than there are on the server
               sp.name_id = np.name_id and sp.max_evr < np.evr
          join -- secondly - packages must be upgrade compatible
               rhnPackageUpgradeArchCompat puac
            on puac.package_arch_id = sp.package_arch_id and puac.package_upgrade_arch_id = np.package_arch_id
          join -- thirdly - packages must be in channel where server is subscribed to
               rhnServerChannel sc
            on sc.server_id = sp.server_id and sc.channel_id = np.channel_id
        group by sc.server_id, np.name_id, np.package_arch_id
        ) neededpkg
  join -- lookup org_id by server
       rhnServer s
    on neededpkg.server_id = s.id
  join (--lookup package_id by max_evr, name and package_arch
        select p.*, p_evr.evr
               --
               , p_evr.release, p_evr.version, p_evr.epoch
          from rhnPackage p
          join rhnPackageEVR p_evr
            on p_evr.id = p.evr_id) pkg
    on pkg.evr = neededpkg.max_evr
   and pkg.name_id = neededpkg.name_id
   and pkg.package_arch_id = neededpkg.package_arch_id
  join (-- lookup channel_id - we want only one id eve if package is in more channels
        -- so pick lowest one
        select cp.package_id, csc.server_id, min(cp.channel_id) as min_channel_id
          from rhnChannelPackage cp
          join rhnServerChannel csc
            on csc.channel_id = cp.channel_id
         group by cp.package_id, csc.server_id) scp
    on scp.package_id = pkg.id and scp.server_id = neededpkg.server_id
  left join (-- lookup errata id (can be NULL)
             select ep.package_id, ce.errata_id, ce.channel_id
               from rhnErrataPackage ep
               join rhnChannelErrata ce
                 on ce.errata_id = ep.errata_id) pce
    on pce.package_id = pkg.id and pce.channel_id = scp.min_channel_id
;
   0707010000062F000081B400000000000000000000000167AE1114000008D3000000000000000000000000000000000000006300000000susemanager-schema/upgrade/spacewalk-schema-1.2-to-spacewalk-schema-1.3/017-rhnPackageKey-data.sql    -- Fedora 13
insert into rhnPackageKey (id, key_id, key_type_id, provider_id) (
       select sequence_nextval('rhn_pkey_id_seq'),
              '7edc6ad6e8e40fde',
              lookup_package_key_type('gpg'),
              lookup_package_provider('Fedora')
         from dual
        where not exists (
              select 1
                from rhnPackageKey
               where key_id = '7edc6ad6e8e40fde'
                 and key_type_id = lookup_package_key_type('gpg')
                 and provider_id = lookup_package_provider('Fedora')
        )
);

-- Fedora 14
insert into rhnPackageKey (id, key_id, key_type_id, provider_id) (
       select sequence_nextval('rhn_pkey_id_seq'),
              '421caddb97a1071f',
              lookup_package_key_type('gpg'),
              lookup_package_provider('Fedora')
         from dual
        where not exists (
              select 1
                from rhnPackageKey
               where key_id = '421caddb97a1071f'
                 and key_type_id = lookup_package_key_type('gpg')
                 and provider_id = lookup_package_provider('Fedora')
        )
);
 
-- Spacewalk
insert into rhnPackageKey (id, key_id, key_type_id, provider_id) (
       select sequence_nextval('rhn_pkey_id_seq'),
              'ed635379b3892132',
              lookup_package_key_type('gpg'),
              lookup_package_provider('Spacewalk')
         from dual
        where not exists (
              select 1
                from rhnPackageKey
               where key_id = 'ed635379b3892132'
                 and key_type_id = lookup_package_key_type('gpg')
                 and provider_id = lookup_package_provider('Spacewalk')
        )
);

-- RHEL 6
insert into rhnPackageKey (id, key_id, key_type_id, provider_id) (
       select sequence_nextval('rhn_pkey_id_seq'),
              '199e2f91fd431d51',
              lookup_package_key_type('gpg'),
              lookup_package_provider('Red Hat Inc.')
         from dual
        where not exists (
              select 1
                from rhnPackageKey
               where key_id = '199e2f91fd431d51'
                 and key_type_id = lookup_package_key_type('gpg')
                 and provider_id = lookup_package_provider('Red Hat Inc.')
        )
);
 07070100000630000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000004A00000000susemanager-schema/upgrade/spacewalk-schema-1.2-to-susemanager-schema-1.2 07070100000631000081B400000000000000000000000167AE111400000529000000000000000000000000000000000000006700000000susemanager-schema/upgrade/spacewalk-schema-1.2-to-susemanager-schema-1.2/001-rhnPackageRecommends.sql    --
-- Copyright (c) 2010 Novell
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
--


CREATE TABLE rhnPackageRecommends
(
    package_id     NUMBER NOT NULL
                       CONSTRAINT rhn_pkg_rec_package_fk
                           REFERENCES rhnPackage (id)
                           ON DELETE CASCADE,
    capability_id  NUMBER NOT NULL
                       CONSTRAINT rhn_pkg_rec_capability_fk
                           REFERENCES rhnPackageCapability (id),
    sense          NUMBER
                       DEFAULT (0) NOT NULL,
    created        DATE
                       DEFAULT (sysdate) NOT NULL,
    modified       DATE
                       DEFAULT (sysdate) NOT NULL
)
ENABLE ROW MOVEMENT
;

CREATE UNIQUE INDEX rhn_pkg_rec_pid_cid_s_uq
    ON rhnPackageRecommends (package_id, capability_id, sense)
    TABLESPACE [[4m_tbs]];

CREATE INDEX rhn_pkg_rec_cid_idx
    ON rhnPackageRecommends (capability_id)
    NOLOGGING
    TABLESPACE [[4m_tbs]];

   07070100000632000081B400000000000000000000000167AE111400000527000000000000000000000000000000000000006500000000susemanager-schema/upgrade/spacewalk-schema-1.2-to-susemanager-schema-1.2/002-rhnPackageSuggests.sql  --
-- Copyright (c) 2010 Novell
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
--


CREATE TABLE rhnPackageSuggests
(
    package_id     NUMBER NOT NULL
                       CONSTRAINT rhn_pkg_sugg_package_fk
                           REFERENCES rhnPackage (id)
                           ON DELETE CASCADE,
    capability_id  NUMBER NOT NULL
                       CONSTRAINT rhn_pkg_sugg_capability_fk
                           REFERENCES rhnPackageCapability (id),
    sense          NUMBER
                       DEFAULT (0) NOT NULL,
    created        DATE
                       DEFAULT (sysdate) NOT NULL,
    modified       DATE
                       DEFAULT (sysdate) NOT NULL
)
ENABLE ROW MOVEMENT
;

CREATE UNIQUE INDEX rhn_pkg_sugg_pid_cid_s_uq
    ON rhnPackageSuggests (package_id, capability_id, sense)
    TABLESPACE [[4m_tbs]];

CREATE INDEX rhn_pkg_sugg_cid_idx
    ON rhnPackageSuggests (capability_id)
    NOLOGGING
    TABLESPACE [[4m_tbs]];

 07070100000633000081B400000000000000000000000167AE111400000530000000000000000000000000000000000000006800000000susemanager-schema/upgrade/spacewalk-schema-1.2-to-susemanager-schema-1.2/003-rhnPackageSupplements.sql   --
-- Copyright (c) 2010 Novell
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
--


CREATE TABLE rhnPackageSupplements
(
    package_id     NUMBER NOT NULL
                       CONSTRAINT rhn_pkg_supp_package_fk
                           REFERENCES rhnPackage (id)
                           ON DELETE CASCADE,
    capability_id  NUMBER NOT NULL
                       CONSTRAINT rhn_pkg_supp_capability_fk
                           REFERENCES rhnPackageCapability (id),
    sense          NUMBER
                       DEFAULT (0) NOT NULL,
    created        DATE
                       DEFAULT (sysdate) NOT NULL,
    modified       DATE
                       DEFAULT (sysdate) NOT NULL
)
ENABLE ROW MOVEMENT
;

CREATE UNIQUE INDEX rhn_pkg_supp_pid_cid_s_uq
    ON rhnPackageSupplements (package_id, capability_id, sense)
    TABLESPACE [[4m_tbs]];

CREATE INDEX rhn_pkg_supp_cid_idx
    ON rhnPackageSupplements (capability_id)
    NOLOGGING
    TABLESPACE [[4m_tbs]];

07070100000634000081B400000000000000000000000167AE111400000261000000000000000000000000000000000000006800000000susemanager-schema/upgrade/spacewalk-schema-1.2-to-susemanager-schema-1.2/006-rhnPackageSupplements.sql   
--
-- Copyright (c) 2010 Novell, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
--

create or replace trigger
rhn_pkg_supp_mod_trig
before insert or update on rhnPackageSupplements
for each row
begin
        :new.modified := sysdate;
end;
/
show errors
   07070100000635000081B400000000000000000000000167AE11140000026B000000000000000000000000000000000000005C00000000susemanager-schema/upgrade/spacewalk-schema-1.2-to-susemanager-schema-1.2/007-rhnErrata.sql   
--
-- Copyright (c) 2010 Novell, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
--

ALTER TABLE rhnErrata MODIFY advisory_name varchar2(100);
ALTER TABLE rhnErrata MODIFY advisory varchar2(100);
ALTER TABLE rhnErrata ADD    errata_from varchar2(127);
show errors
 07070100000636000081B400000000000000000000000167AE111400000274000000000000000000000000000000000000005F00000000susemanager-schema/upgrade/spacewalk-schema-1.2-to-susemanager-schema-1.2/008-rhnErrataTmp.sql    
--
-- Copyright (c) 2010 Novell, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
--

ALTER TABLE rhnErrataTmp MODIFY advisory_name varchar2(100);
ALTER TABLE rhnErrataTmp MODIFY advisory varchar2(100);
ALTER TABLE rhnErrataTmp ADD    errata_from varchar2(127);
show errors
07070100000637000081B400000000000000000000000167AE1114000001FA000000000000000000000000000000000000006300000000susemanager-schema/upgrade/spacewalk-schema-1.2-to-susemanager-schema-1.2/009-rhnErrataBuglist.sql    
--
-- Copyright (c) 2010 Novell, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
--

ALTER TABLE rhnErrataBuglist add(href VARCHAR2(255));
show errors
  07070100000638000081B400000000000000000000000167AE11140000022E000000000000000000000000000000000000006E00000000susemanager-schema/upgrade/spacewalk-schema-1.2-to-susemanager-schema-1.2/010-change-rhn_config_parameter.sql --
-- Copyright (c) 2010 Novell
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
--

update rhn_config_parameter set value='/var/lib/nocpulse/tsdb/bdb' where group_name = 'TSDBLocalQueue' and name = 'bdb_dir';

  07070100000639000081B400000000000000000000000167AE11140000003B000000000000000000000000000000000000006600000000susemanager-schema/upgrade/spacewalk-schema-1.2-to-susemanager-schema-1.2/011-rhnErrataBuglistTmp.sql 
alter table rhnErrataBuglistTmp add(href varchar2(255));

 0707010000063A000081B400000000000000000000000167AE1114000000D7000000000000000000000000000000000000006600000000susemanager-schema/upgrade/spacewalk-schema-1.2-to-susemanager-schema-1.2/060-add-metadata_signed.sql 
alter table rhnContentSource
add metadata_signed char(1) default('Y')
                constraint rhn_cs_ms_nn not null
                constraint rhn_cs_ms_ck
                check (metadata_signed in ('Y','N'));

 0707010000063B000081B400000000000000000000000167AE11140000006E000000000000000000000000000000000000006300000000susemanager-schema/upgrade/spacewalk-schema-1.2-to-susemanager-schema-1.2/070-rhnKsInstallType.sql    insert into rhnKSInstallType (id,label,name) VALUES (rhn_ksinstalltype_id_seq.nextval, 'suse', 'SUSE Linux');
  0707010000063C000081B400000000000000000000000167AE111400000445000000000000000000000000000000000000005F00000000susemanager-schema/upgrade/spacewalk-schema-1.2-to-susemanager-schema-1.2/075-suseOSTarget.sql    --
-- Copyright (c) 2011 Novell
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
--


create table
suseOSTarget
(
    id            number        not null PRIMARY KEY,
    os            varchar2(200) not null
                  CONSTRAINT suseostarget_os_uq UNIQUE,
    target        varchar2(100) not null,
    channel_arch_id  NUMBER
                  CONSTRAINT suse_ostarget_caid_fk
                  REFERENCES rhnChannelArch (id),
    created     date default(sysdate) not null,
    modified    date default(sysdate) not null
);

CREATE SEQUENCE suse_ostarget_id_seq START WITH 100;

create or replace trigger
suseostarget_mod_trig
before insert or update on suseOSTarget
for each row
begin
    :new.modified := sysdate;
end;
/
show errors

   0707010000063D000081B400000000000000000000000167AE11140000021F000000000000000000000000000000000000006000000000susemanager-schema/upgrade/spacewalk-schema-1.2-to-susemanager-schema-1.2/080-suseDelServer.sql   --
-- Copyright (c) 2010 Novell
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
--

create table
suseDelServer
(
    guid        varchar2(256),
    created     date default(sysdate) not null
);

 0707010000063E000081B400000000000000000000000167AE1114000005BA000000000000000000000000000000000000005D00000000susemanager-schema/upgrade/spacewalk-schema-1.2-to-susemanager-schema-1.2/085-suseServer.sql  --
-- Copyright (c) 2010 Novell
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
--

create table
suseServer
(
    rhn_server_id     number
                      CONSTRAINT suseserver_rhns_id_fk
                      REFERENCES rhnServer (id)
                      ON DELETE CASCADE
                      PRIMARY KEY,
    guid              varchar2(256)
                      CONSTRAINT suseserver_guid_uq UNIQUE,
    secret            varchar2(256),
    ostarget_id       number
                      CONSTRAINT suseostarget_id_fk
                      REFERENCES suseOSTarget (id),
    ncc_sync_required CHAR(1) DEFAULT ('N') NOT NULL,
    ncc_reg_error     CHAR(1) DEFAULT ('N') NOT NULL,
    created     date default(sysdate) not null,
    modified    date default(sysdate) not null
);

create or replace trigger
suseserver_mod_trig
before insert or update on suseServer
for each row
begin
    :new.modified := sysdate;
end;
/
show errors

create or replace trigger
suse_server_del_trig
before delete on suseServer
for each row
begin
    insert into suseDelServer ( guid ) values ( :old.guid );
end;
/
show errors

  0707010000063F000081B400000000000000000000000167AE111400000474000000000000000000000000000000000000006700000000susemanager-schema/upgrade/spacewalk-schema-1.2-to-susemanager-schema-1.2/090-suseInstalledProduct.sql    --
-- Copyright (c) 2010 Novell
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
--

create table
suseInstalledProduct
(
    id            number        not null PRIMARY KEY,
    name          varchar2(256) not null,
    version       varchar2(256),
    arch_type_id  NUMBER
                  CONSTRAINT suse_installed_product_aid_fk
                  REFERENCES rhnPackageArch (id),
    release       varchar2(256),
    is_baseproduct CHAR(1) DEFAULT ('N') NOT NULL,
    created     date default(sysdate) not null,
    modified    date default(sysdate) not null
);

CREATE SEQUENCE suse_inst_pr_id_seq START WITH 100;

create or replace trigger
suseinstalledproduct_mod_trig
before insert or update on suseInstalledProduct
for each row
begin
    :new.modified := sysdate;
end;
/
show errors

07070100000640000081B400000000000000000000000167AE1114000004C8000000000000000000000000000000000000005F00000000susemanager-schema/upgrade/spacewalk-schema-1.2-to-susemanager-schema-1.2/100-suseProducts.sql    --
-- Copyright (c) 2010 Novell
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
--

create table
suseProducts
(
    id            number        not null PRIMARY KEY,
    name          varchar2(256) not null,
    version       varchar2(256),
    friendly_name varchar2(256),
    arch_type_id  NUMBER
                  CONSTRAINT suse_products_aid_fk
                  REFERENCES rhnPackageArch (id),
    release           varchar2(256),
    channel_family_id varchar2(256),
    product_list      CHAR(1) DEFAULT ('N') NOT NULL,
    product_id        NUMBER NOT NULL,
    created     date default(sysdate) not null,
    modified    date default(sysdate) not null
);

CREATE SEQUENCE suse_products_id_seq START WITH 100;

create or replace trigger
suseproducts_mod_trig
before insert or update on suseProducts
for each row
begin
    :new.modified := sysdate;
end;
/
show errors

07070100000641000081B400000000000000000000000167AE111400000408000000000000000000000000000000000000006500000000susemanager-schema/upgrade/spacewalk-schema-1.2-to-susemanager-schema-1.2/105-suseProductChannel.sql  --
-- Copyright (c) 2010 Novell
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
--

create table
suseProductChannel
(
    product_id number        not null
                             CONSTRAINT spc_pid_fk
                             REFERENCES suseProducts (id),
    channel_id number        not null
                             CONSTRAINT spc_rhn_cid_fk
                             REFERENCES rhnChannel (id),
    created     date default(sysdate) not null,
    modified    date default(sysdate) not null
);

create or replace trigger
suseproductchannel_mod_trig
before insert or update on suseProductChannel
for each row
begin
    :new.modified := sysdate;
end;
/
show errors

07070100000642000081B400000000000000000000000167AE11140000048B000000000000000000000000000000000000006D00000000susemanager-schema/upgrade/spacewalk-schema-1.2-to-susemanager-schema-1.2/110-suseServerInstalledProduct.sql  --
-- Copyright (c) 2010 Novell
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
--


create table
suseServerInstalledProduct
(
    rhn_server_id     number
                      CONSTRAINT suseserver_ip_rhns_id_fk
                      REFERENCES rhnServer (id)
                      ON DELETE CASCADE
                      not null,
    suse_installed_product_id   number
                                CONSTRAINT ssip_sip_id_fk
                                REFERENCES suseInstalledProduct (id)
                                not null,
    created     date default(sysdate) not null,
    modified    date default(sysdate) not null
);

create or replace trigger
susesrvinstprod_mod_trig
before insert or update on suseServerInstalledProduct
for each row
begin
    :new.modified := sysdate;
end;
/
show errors

 07070100000643000081B400000000000000000000000167AE111400000232000000000000000000000000000000000000006A00000000susemanager-schema/upgrade/spacewalk-schema-1.2-to-susemanager-schema-1.2/120-add-VirtualInstanceType.sql --
-- Copyright (c) 2010 Novell
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
--

insert into rhnVirtualInstanceType (id, name, label)
    values (sequence_nextval('rhn_vit_id_seq'), 'VirtualBox', 'virtualbox');
  07070100000644000081B400000000000000000000000167AE111400000566000000000000000000000000000000000000006800000000susemanager-schema/upgrade/spacewalk-schema-1.2-to-susemanager-schema-1.2/130-add-ncc-register-task.sql   --
-- Copyright (c) 2010 Novell
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
--

INSERT INTO rhnTaskoTask (id, name, class)
     VALUES (sequence_nextval('rhn_tasko_task_id_seq'), 'mgr-register', 'com.redhat.rhn.taskomatic.task.NccRegisterTask');

INSERT INTO rhnTaskoBunch (id, name, description, org_bunch)
     VALUES (sequence_nextval('rhn_tasko_bunch_id_seq'), 'mgr-register-bunch', 'Runs mgr-register', 'Y');

INSERT INTO rhnTaskoSchedule (id, job_label, bunch_id, active_from, cron_expr)
     VALUES(sequence_nextval('rhn_tasko_schedule_id_seq'), 'mgr-register-default',
            (SELECT id FROM rhnTaskoBunch WHERE name='mgr-register-bunch'),
            current_timestamp, '0 0/15 * * * ?');

INSERT INTO rhnTaskoTemplate (id, bunch_id, task_id, ordering, start_if)
     VALUES (sequence_nextval('rhn_tasko_template_id_seq'),
             (SELECT id FROM rhnTaskoBunch WHERE name='mgr-register-bunch'),
             (SELECT id FROM rhnTaskoTask WHERE name='mgr-register'),
             0,
             null);

commit;

  07070100000645000081B400000000000000000000000167AE111400000849000000000000000000000000000000000000007000000000susemanager-schema/upgrade/spacewalk-schema-1.2-to-susemanager-schema-1.2/140-add-package-keys-and-provider.sql   --
-- Copyright (c) 2010 Novell
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
--

update rhnPackageProvider set name = 'SUSE LINUX Products GmbH' where name = 'Suse';

insert into rhnPackageProvider (id, name) values
(sequence_nextval('rhn_package_provider_id_seq'), 'Novell Inc.' );

commit;

insert into rhnPackageKey (id, key_id, key_type_id, provider_id) values
(sequence_nextval('rhn_pkey_id_seq'), 'e3a5c360307e3d54', lookup_package_key_type('gpg'), lookup_package_provider('SUSE LINUX Products GmbH'));

insert into rhnPackageKey (id, key_id, key_type_id, provider_id) values
(sequence_nextval('rhn_pkey_id_seq'), '6c74ce73b37b98a9', lookup_package_key_type('gpg'), lookup_package_provider('SUSE LINUX Products GmbH'));

insert into rhnPackageKey (id, key_id, key_type_id, provider_id) values
(sequence_nextval('rhn_pkey_id_seq'), '2afe16421d061a62', lookup_package_key_type('gpg'), lookup_package_provider('Novell Inc.'));

insert into rhnPackageKey (id, key_id, key_type_id, provider_id) values
(sequence_nextval('rhn_pkey_id_seq'), '14c28bc97e2e3b05', lookup_package_key_type('gpg'), lookup_package_provider('Novell Inc.'));

insert into rhnPackageKey (id, key_id, key_type_id, provider_id) values
(sequence_nextval('rhn_pkey_id_seq'), '478a32e8a1912208', lookup_package_key_type('gpg'), lookup_package_provider('Novell Inc.'));

insert into rhnPackageKey (id, key_id, key_type_id, provider_id) values
(sequence_nextval('rhn_pkey_id_seq'), '73d25d630dfb3188', lookup_package_key_type('gpg'), lookup_package_provider('Novell Inc.'));

insert into rhnPackageKey (id, key_id, key_type_id, provider_id) values
(sequence_nextval('rhn_pkey_id_seq'), '8055f0400182b964', lookup_package_key_type('gpg'), lookup_package_provider('SUSE LINUX Products GmbH'));

commit;


   07070100000646000081B400000000000000000000000167AE111400000539000000000000000000000000000000000000006400000000susemanager-schema/upgrade/spacewalk-schema-1.2-to-susemanager-schema-1.2/151-suseOSTarget-Data.sql   --
-- Copyright (c) 2011 Novell
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
--

insert into suseOSTarget (id, os, target, channel_arch_id) values
(sequence_nextval('suse_ostarget_id_seq'), 'sle-11-i586', 'sle-11-i586', LOOKUP_CHANNEL_ARCH('channel-ia32'))

insert into suseOSTarget (id, os, target, channel_arch_id) values
(sequence_nextval('suse_ostarget_id_seq'), 'sle-11-ia64', 'sle-11-ia64', LOOKUP_CHANNEL_ARCH('channel-ia64'))

insert into suseOSTarget (id, os, target, channel_arch_id) values
(sequence_nextval('suse_ostarget_id_seq'), 'sle-11-ppc64', 'sle-11-ppc64', LOOKUP_CHANNEL_ARCH('channel-ppc'))

insert into suseOSTarget (id, os, target, channel_arch_id) values
(sequence_nextval('suse_ostarget_id_seq'), 'sle-11-s390x', 'sle-11-s390x', LOOKUP_CHANNEL_ARCH('channel-s390x'))

insert into suseOSTarget (id, os, target, channel_arch_id) values
(sequence_nextval('suse_ostarget_id_seq'), 'sle-11-x86_64', 'sle-11-x86_64', LOOKUP_CHANNEL_ARCH('channel-x86_64'))

commit;


   07070100000647000081B400000000000000000000000167AE111400000344000000000000000000000000000000000000006400000000susemanager-schema/upgrade/spacewalk-schema-1.2-to-susemanager-schema-1.2/160-rhntemplatestring.sql   --
-- Copyright (c) 2010 Novell
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
--

update rhntemplatestring set value = '--the SUSE Manager Team', description = 'Footer for SUSE Manager e-mail'  where label = 'email_footer';
update rhntemplatestring set value = 'Account Information:
Your SUSE Manager login:         <login />
Your SUSE Manager email address: <email-address />', description = 'Account info lines for SUSE Manager e-mail' where label = 'email_account_info';


commit;


07070100000648000081B400000000000000000000000167AE111400001946000000000000000000000000000000000000006200000000susemanager-schema/upgrade/spacewalk-schema-1.2-to-susemanager-schema-1.2/299-rhn_channel-pks.sql --
-- Copyright (c) 2008--2010 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--

CREATE OR REPLACE
PACKAGE rhn_channel
IS
	version varchar2(100) := '';

    CURSOR server_base_subscriptions(server_id_in NUMBER) IS
    	   SELECT C.id
	     FROM rhnChannel C, rhnServerChannel SC
	    WHERE C.id = SC.channel_id
	      AND SC.server_id = server_id_in
	      AND C.parent_channel IS NULL;
	      
    CURSOR check_server_subscription(server_id_in NUMBER, channel_id_in NUMBER) IS 
           SELECT channel_id 
	     FROM rhnServerChannel 
	    WHERE server_id = server_id_in 
	      AND channel_id = channel_id_in;

    CURSOR check_server_parent_membership(server_id_in NUMBER, channel_id_in NUMBER) IS
    	   SELECT C.id
	     FROM rhnChannel C, rhnServerChannel SC
	    WHERE C.parent_channel = channel_id_in
	      AND C.id = SC.channel_id
	      AND SC.server_id = server_id_in;
	    
    CURSOR channel_family_perm_cursor(channel_family_id_in NUMBER, org_id_in NUMBER) IS
           SELECT *
	     FROM rhnOrgChannelFamilyPermissions
	    WHERE channel_family_id = channel_family_id_in
	      AND org_id = org_id_in;


    PROCEDURE unsubscribe_server(server_id_in IN NUMBER, channel_id_in NUMBER, immediate_in NUMBER := 1, unsubscribe_children_in number := 0,
                                 deleting_server in number := 0,
                                 update_family_countsYN IN NUMBER := 1);
    PROCEDURE subscribe_server(server_id_in IN NUMBER, channel_id_in NUMBER, immediate_in NUMBER := 1, user_id_in number := null, recalcfamily_in number := 1);
    
    PROCEDURE convert_to_fve(server_id_in IN NUMBER, channel_family_id_val IN NUMBER);

    FUNCTION can_convert_to_fve(server_id_in IN NUMBER, channel_family_id_val IN NUMBER)  RETURN NUMBER;
	
    function can_server_consume_virt_channl(
        server_id_in IN NUMBER,
        family_id_in in number)
    return number;
    FUNCTION can_server_consume_fve( server_id_in IN NUMBER) RETURN NUMBER;

    FUNCTION guess_server_base(server_id_in IN NUMBER) RETURN NUMBER;

    FUNCTION base_channel_for_release_arch(release_in in varchar2, 
	server_arch_in in varchar2, org_id_in in number := -1, 
	user_id_in in number := null) RETURN number;

    FUNCTION base_channel_rel_archid(release_in in varchar2, 
	server_arch_id_in in number, org_id_in in number := -1, 
	user_id_in in number := null) RETURN number;

    FUNCTION channel_priority(channel_id_in in number) RETURN number;
    
    PROCEDURE clear_subscriptions(server_id_in IN NUMBER, deleting_server in number := 0,
                                update_family_countsYN IN NUMBER := 1);
    
    FUNCTION available_family_subscriptions(channel_family_id_in IN NUMBER, org_id_in IN NUMBER) RETURN NUMBER;

    FUNCTION available_fve_family_subs(channel_family_id_in IN NUMBER, org_id_in IN NUMBER) RETURN NUMBER;

    FUNCTION channel_family_current_members(channel_family_id_in IN NUMBER, org_id_in IN NUMBER) return number;

    FUNCTION cfam_curr_fve_members(channel_family_id_in IN NUMBER, org_id_in IN NUMBER) return number;

    PROCEDURE update_family_counts(channel_family_id_in IN NUMBER, org_id_in IN NUMBER);
    PROCEDURE update_group_family_counts(group_label_in IN VARCHAR2, org_id_in IN NUMBER);
    FUNCTION family_for_channel(channel_id_in IN NUMBER) RETURN NUMBER;

    FUNCTION available_chan_subscriptions(channel_id_in IN NUMBER, org_id_in IN NUMBER) RETURN NUMBER;

    FUNCTION available_fve_chan_subs(channel_id_in IN NUMBER, org_id_in IN NUMBER) RETURN NUMBER;

    PROCEDURE unsubscribe_server_from_family(server_id_in in number, channel_family_id_in in number);

    PROCEDURE delete_server_channels(server_id_in in number);

    PROCEDURE refresh_newest_package(channel_id_in in number, caller_in in varchar2 := '(unknown)');

    FUNCTION get_org_id(channel_id_in in number) return number;
    PRAGMA RESTRICT_REFERENCES(get_org_id, WNDS, RNPS, WNPS);

    function get_org_access(channel_id_in in number, org_id_in in number) return number;
    PRAGMA RESTRICT_REFERENCES(get_org_access, WNDS, RNPS, WNPS);
    
    function get_cfam_org_access(cfam_id_in in number, org_id_in in number) return number;

    function user_role_check_debug(channel_id_in in number, user_id_in in number, role_in in varchar2, reason_out out varchar2)
    	RETURN NUMBER;
    PRAGMA RESTRICT_REFERENCES(user_role_check_debug, WNDS, RNPS, WNPS);

    function user_role_check(channel_id_in in number, user_id_in in number, role_in in varchar2)
    	RETURN NUMBER;
    PRAGMA RESTRICT_REFERENCES(user_role_check, WNDS, RNPS, WNPS);
    
    function loose_user_role_check(channel_id_in in number, user_id_in in number, role_in in varchar2)
    	RETURN NUMBER;
    PRAGMA RESTRICT_REFERENCES(loose_user_role_check, WNDS, RNPS, WNPS);

    function direct_user_role_check(channel_id_in in number, user_id_in in number, role_in in varchar2)
    	RETURN NUMBER;
    PRAGMA RESTRICT_REFERENCES(direct_user_role_check, WNDS, RNPS, WNPS);

    function shared_user_role_check(channel_id in number, user_id in number, role in varchar2)
    	RETURN NUMBER;
    PRAGMA RESTRICT_REFERENCES(shared_user_role_check, WNDS, RNPS, WNPS);

    function org_channel_setting(channel_id_in in number, org_id_in in number, setting_in in varchar2)
    	RETURN NUMBER;

    PROCEDURE update_channel ( channel_id_in in number, invalidate_ss in number := 0, 
                               date_to_use in date := sysdate );

    PROCEDURE  update_channels_by_package ( package_id_in in number, date_to_use in date := sysdate );

     PROCEDURE update_channels_by_errata ( errata_id_in number, date_to_use in date := sysdate );


    PRAGMA RESTRICT_REFERENCES(org_channel_setting, WNDS, RNPS, WNPS);

    PROCEDURE update_needed_cache(channel_id_in in number);

    FUNCTION server_has_family_subscription(server_id_in IN NUMBER, channel_family_id_in IN NUMBER) RETURN NUMBER;

END rhn_channel;
/
SHOW ERRORS
  07070100000649000081B400000000000000000000000167AE11140000AD7F000000000000000000000000000000000000006300000000susemanager-schema/upgrade/spacewalk-schema-1.2-to-susemanager-schema-1.2/300-rhn_channel-body.sql    --
-- Copyright (c) 2008--2010 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

CREATE OR REPLACE
PACKAGE BODY rhn_channel
IS
        body_version varchar2(100) := '';

    -- Cursor that fetches all the possible base channels for a
    -- (server_arch_id, release, org_id) combination
        cursor  base_channel_cursor(
                release_in in varchar2,
                server_arch_id_in in number,
                org_id_in in number
        ) return rhnChannel%ROWTYPE is
                select distinct c.*
                from    rhnDistChannelMap                       dcm,
                                rhnServerChannelArchCompat      scac,
                                rhnChannel                                      c,
                                rhnChannelPermissions           cp
                where   cp.org_id = org_id_in
                        and cp.channel_id = c.id
                        and c.parent_channel is null
                        and c.id = dcm.channel_id
                        and c.channel_arch_id = dcm.channel_arch_id
                        and dcm.release = release_in
                        and scac.server_arch_id = server_arch_id_in
                        and scac.channel_arch_id = c.channel_arch_id;

    procedure obtain_read_lock(channel_family_id_in in number, org_id_in in number)
    is
        read_lock date;

    begin
        select created into read_lock
          from rhnPrivateChannelFamily
         where channel_family_id = channel_family_id_in and org_id = org_id_in
           for update;
    end obtain_read_lock;

    PROCEDURE subscribe_server(server_id_in IN NUMBER, channel_id_in NUMBER, immediate_in NUMBER := 1, user_id_in in number := null, recalcfamily_in number := 1)
    IS
        channel_parent_val      rhnChannel.parent_channel%TYPE;
        parent_subscribed       BOOLEAN;
        server_has_base_chan    BOOLEAN;
        server_already_in_chan  BOOLEAN;
        channel_family_id_val   NUMBER;
        server_org_id_val       NUMBER;
        available_subscriptions NUMBER;
        available_fve_subs      NUMBER;
        has_family_subscription NUMBER;
        consenting_user         NUMBER;
        allowed                 number := 0;
        is_fve                  CHAR(1) := 'N';
    BEGIN
        if user_id_in is not null then
            allowed := rhn_channel.user_role_check(channel_id_in, user_id_in, 'subscribe');
        else
            allowed := 1;
        end if;

        if allowed = 0 then
            rhn_exception.raise_exception('no_subscribe_permissions');
        end if;


        SELECT parent_channel INTO channel_parent_val FROM rhnChannel WHERE id = channel_id_in;

        IF channel_parent_val IS NOT NULL
        THEN
            -- child channel; if attempting to cross-subscribe a child to the wrong base, silently ignore
            parent_subscribed := FALSE;

            FOR check_subscription IN check_server_subscription(server_id_in, channel_parent_val)
            LOOP
                parent_subscribed := TRUE;
            END LOOP check_subscription;

            IF NOT parent_subscribed
            THEN
                RETURN;
            END IF;
        ELSE
            -- base channel
            server_has_base_chan := FALSE;
            FOR base IN server_base_subscriptions(server_id_in)
            LOOP
                server_has_base_chan := TRUE;
            END LOOP base;

            IF server_has_base_chan
            THEN
                rhn_exception.raise_exception('channel_server_one_base');
            END IF;
        END IF;

        FOR check_subscription IN check_server_subscription(server_id_in, channel_id_in)
        LOOP
            server_already_in_chan := TRUE;
        END LOOP check_subscription;

        IF server_already_in_chan
        THEN
            RETURN;
        END IF;

        channel_family_id_val := rhn_channel.family_for_channel(channel_id_in);
        IF channel_family_id_val IS NULL
        THEN
            rhn_exception.raise_exception('channel_subscribe_no_family');
        END IF;

        --
        -- Use the org_id of the server only if the org_id of the channel = NULL.
        -- This is required for subscribing to shared channels.
        --
        SELECT NVL(org_id, (SELECT org_id FROM rhnServer WHERE id = server_id_in))
          INTO server_org_id_val
          FROM rhnChannel
         WHERE id = channel_id_in;

        begin
            obtain_read_lock(channel_family_id_val, server_org_id_val);
        exception
            when no_data_found then
                rhn_exception.raise_exception('channel_family_no_subscriptions');
        end;

        available_subscriptions := rhn_channel.available_family_subscriptions(channel_family_id_val, server_org_id_val);
        available_fve_subs := rhn_channel.available_fve_family_subs(channel_family_id_val, server_org_id_val);
        has_family_subscription := rhn_channel.server_has_family_subscription(server_id_in, channel_family_id_val);

        IF available_subscriptions IS NULL OR
            available_subscriptions > 0 or
            can_server_consume_virt_channl(server_id_in, channel_family_id_val) = 1 OR
            (available_fve_subs > 0 AND can_server_consume_fve(server_id_in) = 1) OR
            has_family_subscription > 0
        THEN
            if can_server_consume_virt_channl(server_id_in, channel_family_id_val) = 0 AND available_fve_subs > 0 AND can_server_consume_fve(server_id_in) = 1 THEN
                is_fve := 'Y';
            END IF;
            insert into rhnServerHistory (id,server_id,summary,details) (
                select  rhn_event_id_seq.nextval,
                        server_id_in,
                        'subscribed to channel ' || SUBSTR(c.label, 0, 106),
                        c.label
                from    rhnChannel c
                where   c.id = channel_id_in
            );
            UPDATE rhnServer SET channels_changed = sysdate WHERE id = server_id_in;
            INSERT INTO rhnServerChannel (server_id, channel_id, is_fve) VALUES (server_id_in, channel_id_in, is_fve);
			IF recalcfamily_in > 0
			THEN
                rhn_channel.update_family_counts(channel_family_id_val, server_org_id_val);
			END IF;
            queue_server(server_id_in, immediate_in);
        ELSE
            rhn_exception.raise_exception('channel_family_no_subscriptions');
        END IF;

    END subscribe_server;



    FUNCTION can_convert_to_fve(server_id_in IN NUMBER, channel_family_id_val IN NUMBER)
    RETURN NUMBER
    IS
        CURSOR fve_convertible_entries IS
        select 1  from
            rhnServerFveCapable cap
          where cap.server_id = server_id_in
                AND cap.channel_family_id = channel_family_id_val;
    BEGIN
        FOR entry IN fve_convertible_entries LOOP
            return 1;
        END LOOP;
        RETURN 0;
    END can_convert_to_fve;



    -- Converts server channel_family to use a flex entitlement
    PROCEDURE convert_to_fve(server_id_in IN NUMBER, channel_family_id_val IN NUMBER)
    IS
        available_fve_subs      NUMBER;
        server_org_id_val       NUMBER;
    BEGIN

        --
        -- Use the org_id of the server only if the org_id of the channel = NULL.
        -- This is required for subscribing to shared channels.
        --
        SELECT org_id
          INTO server_org_id_val
          FROM rhnServer
         WHERE id = server_id_in;

        begin
            obtain_read_lock(channel_family_id_val, server_org_id_val);
        exception
            when no_data_found then
                rhn_exception.raise_exception('channel_family_no_subscriptions');
        end;
        IF (can_convert_to_fve(server_id_in, channel_family_id_val ) = 0)
            THEN
                rhn_exception.raise_exception('server_cannot_convert_to_flex');
        END IF;

        available_fve_subs := rhn_channel.available_fve_family_subs(channel_family_id_val, server_org_id_val);

        IF (available_fve_subs > 0)
        THEN

            insert into rhnServerHistory (id,server_id,summary,details) (
                select  rhn_event_id_seq.nextval,
                        server_id_in,
                        'converted to flex entitlement' || SUBSTR(cf.label, 0, 99),
                        cf.label
                from    rhnChannelFamily cf
                where   cf.id = channel_family_id_val
            );

            UPDATE rhnServerChannel sc set sc.is_fve = 'Y'
                           where sc.server_id = server_id_in and
                                 sc.channel_id in
                                    (select cfm.channel_id from rhnChannelFamilyMembers cfm
                                                where cfm.CHANNEL_FAMILY_ID = channel_family_id_val);

            rhn_channel.update_family_counts(channel_family_id_val, server_org_id_val);
        ELSE
            rhn_exception.raise_exception('not_enough_flex_entitlements');
        END IF;

    END convert_to_fve;

    function can_server_consume_virt_channl(
        server_id_in in number,
        family_id_in in number )
    return number
    is

        cursor server_virt_families is
            select vi.virtual_system_id, cfvsl.channel_family_id
            from
                rhnChannelFamilyVirtSubLevel cfvsl,
                rhnSGTypeVirtSubLevel sgtvsl,
                rhnVirtualInstance vi
            where
                vi.virtual_system_id = server_id_in
                and sgtvsl.virt_sub_level_id = cfvsl.virt_sub_level_id
                and cfvsl.channel_family_id = family_id_in
                and exists (
                    select 1
                    from rhnServerEntitlementView sev
                    where vi.host_system_id = sev.server_id
                    and sev.server_group_type_id = sgtvsl.server_group_type_id );
    begin

        for server_virt_family in server_virt_families loop
            return 1;
        end loop;

        return 0;

    end;

    FUNCTION can_server_consume_fve(server_id_in IN NUMBER)
    RETURN NUMBER
    IS
        CURSOR vi_entries IS
            SELECT 1
              FROM rhnVirtualInstance vi
             WHERE vi.virtual_system_id = server_id_in;
        vi_count NUMBER;

    BEGIN
        FOR vi_entry IN VI_ENTRIES LOOP
            return 1;
        END LOOP;
        RETURN 0;
    END;

    function guess_server_base(
        server_id_in in number
    ) RETURN number is
        cursor server_cursor is
            select s.server_arch_id, s.release, s.org_id
              from rhnServer s
             where s.id = server_id_in;
    begin
        for s in server_cursor loop
            for channel in base_channel_cursor(s.release,
                s.server_arch_id, s.org_id)
            loop
                return channel.id;
            end loop base_channel_cursor;
        end loop server_cursor;
        -- Server not found, or no base channel applies to it
        return null;
    end;

    -- Private function
    function normalize_server_arch(server_arch_in in varchar2)
    return varchar2
    deterministic
    is
        suffix VARCHAR2(128) := '-redhat-linux';
        suffix_len NUMBER := length(suffix);
    begin
        if server_arch_in is NULL then
            return NULL;
        end if;
        if instr(server_arch_in, '-') > 0
        then
            -- Suffix already present
            return server_arch_in;
        end if;
        return server_arch_in || suffix;
    end normalize_server_arch;

    --
    --
    -- Raises:
    --   server_arch_not_found
    --   no_subscribe_permissions
    function base_channel_for_release_arch(
        release_in in varchar2,
        server_arch_in in varchar2,
        org_id_in in number := -1,
        user_id_in in number := null
    ) return number is
        server_arch varchar2(256) := normalize_server_arch(server_arch_in);
        server_arch_id number;
    begin
        -- Look up the server arch
        begin
            select id
              into server_arch_id
              from rhnServerArch
             where label = server_arch;
        exception
            when no_data_found then
                rhn_exception.raise_exception('server_arch_not_found');
        end;
        return base_channel_rel_archid(release_in, server_arch_id,
            org_id_in, user_id_in);
    end base_channel_for_release_arch;

    function base_channel_rel_archid(
        release_in in varchar2,
        server_arch_id_in in number,
        org_id_in in number := -1,
        user_id_in in number := null
    ) return number is
        denied_channel_id number := null;
        valid_org_id number := org_id_in;
        valid_user_id number := user_id_in;
        channel_subscribable number;
    begin
        if org_id_in = -1 and user_id_in is not null then
            -- Get the org id from the user id
            begin
                select org_id
                  into valid_org_id
                  from web_contact
                 where id = user_id_in;
            exception
                when no_data_found then
                    -- User doesn't exist
                    -- XXX Only list public stuff for now
                    valid_user_id := null;
                    valid_org_id := -1;
            end;
        end if;

        for c in base_channel_cursor(release_in, server_arch_id_in, valid_org_id)
        loop
            -- This row is a possible match
            if valid_user_id is null then
                -- User ID not specified, so no user to channel permissions to
                -- check
                return c.id;
            end if;

            -- Check user to channel permissions
            select loose_user_role_check(c.id, user_id_in, 'subscribe')
              into channel_subscribable
              from dual;

            if channel_subscribable = 1 then
                return c.id;
            end if;

            -- Base channel exists, but is not subscribable; keep trying
            denied_channel_id := c.id;
        end loop base_channel_fetch;

        if denied_channel_id is not null then
            rhn_exception.raise_exception('no_subscribe_permissions');
        end if;
        -- No base channel applies
        return NULL;
    end base_channel_rel_archid;

    PROCEDURE clear_subscriptions(server_id_in IN NUMBER, deleting_server IN NUMBER := 0,
                                update_family_countsYN IN NUMBER := 1)
    IS
        cursor server_channels(server_id_in in number) is
                select  s.org_id, sc.channel_id, cfm.channel_family_id
                from    rhnServer s,
                        rhnServerChannel sc,
                        rhnChannelFamilyMembers cfm
                where   s.id = server_id_in
                        and s.id = sc.server_id
                        and sc.channel_id = cfm.channel_id
                order by cfm.channel_family_id;
        last_channel_family_id rhnChannelFamilyMembers.channel_family_id%type := -1;
        last_channel_org_id    rhnServer.org_id%type := -1;
    BEGIN
        for channel in server_channels(server_id_in)
        loop
                unsubscribe_server(server_id_in, channel.channel_id, 1, 1, deleting_server, 0);
                if update_family_countsYN > 0
                    and channel.channel_family_id != last_channel_family_id then
                    -- update family counts only once
                    -- after all channels with same family has been fetched
                    if last_channel_family_id != -1 then
                        update_family_counts(last_channel_family_id, last_channel_org_id);
                    end if;
                    last_channel_family_id := channel.channel_family_id;
                    last_channel_org_id    := channel.org_id;
                end if;
        end loop channel;
        if update_family_countsYN > 0 and last_channel_family_id != -1 then
            -- update the last family fetched
            update_family_counts(last_channel_family_id, last_channel_org_id);
        end if;
    END clear_subscriptions;

    PROCEDURE unsubscribe_server(server_id_in IN NUMBER, channel_id_in NUMBER, immediate_in NUMBER := 1, unsubscribe_children_in number := 0,
                                 deleting_server IN NUMBER := 0,
                                 update_family_countsYN IN NUMBER := 1)
    IS
        channel_family_id_val   NUMBER;
        server_org_id_val       NUMBER;
        available_subscriptions NUMBER;
        server_already_in_chan  BOOLEAN;
        cursor  channel_family_is_proxy(channel_family_id_in in number) is
                select  1
                from    rhnChannelFamily
                where   id = channel_family_id_in
                    and label = 'rhn-proxy';
        cursor  channel_family_is_satellite(channel_family_id_in in number) is
                select  1
                from    rhnChannelFamily
                where   id = channel_family_id_in
                    and label = 'rhn-satellite';
        -- this is *EXACTLY* like check_server_parent_membership, but if we recurse
        -- with the package-level one, we get a "cursor already open", so we need a
        -- copy on our call stack instead.  GROAN.
        cursor local_chk_server_parent_memb (
                        server_id_in number,
                        channel_id_in number ) is
                select  c.id
                from    rhnChannel                      c,
                                rhnServerChannel        sc
                where   1=1
                        and c.parent_channel = channel_id_in
                        and c.id = sc.channel_id
                        and sc.server_id = server_id_in;
    BEGIN
        FOR child IN local_chk_server_parent_memb(server_id_in, channel_id_in)
        LOOP
            if unsubscribe_children_in = 1 then
                unsubscribe_server(server_id_in => server_id_in,
                                                                channel_id_in => child.id,
                                                                immediate_in => immediate_in,
                                                                unsubscribe_children_in => unsubscribe_children_in,
                        deleting_server => deleting_server,
                        update_family_countsYN => update_family_countsYN);
            else
                rhn_exception.raise_exception('channel_unsubscribe_child_exists');
            end if;
        END LOOP child;

        server_already_in_chan := FALSE;

        FOR check_subscription IN check_server_subscription(server_id_in, channel_id_in)
        LOOP
            server_already_in_chan := TRUE;
        END LOOP check_subscription;

        IF NOT server_already_in_chan
        THEN
            RETURN;
        END IF;

   if deleting_server = 0 then

      insert into rhnServerHistory (id,server_id,summary,details) (
          select  rhn_event_id_seq.nextval,
                server_id_in,
             'unsubscribed from channel ' || SUBSTR(c.label, 0, 106),
             c.label
          from    rhnChannel c
          where   c.id = channel_id_in
      );

        UPDATE rhnServer SET channels_changed = sysdate WHERE id = server_id_in;
   end if;

   DELETE FROM rhnServerChannel WHERE server_id = server_id_in AND channel_id = channel_id_in;

   if deleting_server = 0 then
        queue_server(server_id_in, immediate_in);
   end if;

        channel_family_id_val := rhn_channel.family_for_channel(channel_id_in);
        IF channel_family_id_val IS NULL
        THEN
            rhn_exception.raise_exception('channel_unsubscribe_no_family');
        END IF;

        for ignore in channel_family_is_satellite(channel_family_id_val) loop
                delete from rhnSatelliteInfo where server_id = server_id_in;
        end loop;

        for ignore in channel_family_is_proxy(channel_family_id_val) loop
                delete from rhnProxyInfo where server_id = server_id_in;
        end loop;
        SELECT org_id INTO server_org_id_val
          FROM rhnServer
         WHERE id = server_id_in;

        if update_family_countsYN = 1 then
            rhn_channel.update_family_counts(channel_family_id_val, server_org_id_val);
        end if;
    END unsubscribe_server;


    FUNCTION family_for_channel(channel_id_in IN NUMBER)
    RETURN NUMBER
    IS
        channel_family_id_val NUMBER;
    BEGIN
        SELECT channel_family_id INTO channel_family_id_val
          FROM rhnChannelFamilyMembers
         WHERE channel_id = channel_id_in;

        RETURN channel_family_id_val;
    EXCEPTION
        WHEN NO_DATA_FOUND
        THEN
            RETURN NULL;
    END family_for_channel;

    FUNCTION available_family_subscriptions(channel_family_id_in IN NUMBER, org_id_in IN NUMBER)
    RETURN NUMBER
    IS
        cfp channel_family_perm_cursor%ROWTYPE;
        current_members_val NUMBER;
        max_members_val     NUMBER;
        found               NUMBER;
    BEGIN
        IF NOT channel_family_perm_cursor%ISOPEN
        THEN
            OPEN channel_family_perm_cursor(channel_family_id_in, org_id_in);
        END IF;

        FETCH channel_family_perm_cursor INTO cfp;

        WHILE channel_family_perm_cursor%FOUND
        LOOP
            found := 1;

            current_members_val := cfp.current_members;
            max_members_val := cfp.max_members;

            FETCH channel_family_perm_cursor INTO cfp;
        END LOOP;

        IF channel_family_perm_cursor%ISOPEN
        THEN
            CLOSE channel_family_perm_cursor;
        END IF;

        -- not found: either the channel fam doesn't have an entry in cfp, or the org doesn't have access to it.
        -- either way, there are no available subscriptions

        IF found IS NULL
        THEN
            RETURN 0;
        END IF;

        -- null max members?  in that case, pass it on; NULL means infinite
        IF max_members_val IS NULL
        THEN
            RETURN NULL;
        END IF;

        -- otherwise, return the delta
        RETURN max_members_val - current_members_val;
    END available_family_subscriptions;

    FUNCTION available_fve_family_subs(channel_family_id_in IN NUMBER, org_id_in IN NUMBER)
    RETURN NUMBER
    IS
        cfp channel_family_perm_cursor%ROWTYPE;
        fve_current_members_val NUMBER;
        fve_max_members_val     NUMBER;
        found               NUMBER;

    BEGIN
        IF NOT channel_family_perm_cursor%ISOPEN THEN
            OPEN channel_family_perm_cursor(channel_family_id_in, org_id_in);
        END IF;

        FETCH channel_family_perm_cursor INTO cfp;

        WHILE channel_family_perm_cursor%FOUND LOOP
            found := 1;
            fve_current_members_val := cfp.fve_current_members;
            fve_max_members_val := cfp.fve_max_members;
            FETCH channel_family_perm_cursor INTO cfp;
        END LOOP;

        IF channel_family_perm_cursor%ISOPEN THEN
            CLOSE channel_family_perm_cursor;
        END IF;

        IF found IS NULL THEN
            RETURN 0;
        END IF;

        IF fve_max_members_val IS NULL THEN
            RETURN NULL;
        END IF;

        RETURN fve_max_members_val - fve_current_members_val;

    END available_fve_family_subs;


    -- *******************************************************************
    -- FUNCTION: channel_family_current_members
    -- Calculates and returns the actual count of systems consuming
    --   physical channel subscriptions.
    -- Called by: update_family_counts
    --            rhn_entitlements.repoll_virt_guest_entitlements
    -- *******************************************************************
    function channel_family_current_members(channel_family_id_in IN NUMBER,
                                            org_id_in IN NUMBER)
    return number
    is
        current_members_count number := 0;
    begin
        select  count(distinct server_id)
        into    current_members_count
          from  rhnChannelFamilyServerPhysical cfsp
         where  cfsp.channel_family_id = channel_family_id_in
           and  cfsp.customer_id = org_id_in;
        return current_members_count;
    end;


    function cfam_curr_fve_members(
        channel_family_id_in IN NUMBER,
        org_id_in IN NUMBER)
    return number
    is
        current_members_count number := 0;

    begin
        select count(sc.server_id)
          into current_members_count
          from rhnServerChannel sc,
               rhnChannelFamilyMembers cfm,
               rhnServer s
         where s.org_id = org_id_in
           and s.id = sc.server_id
           and cfm.channel_family_id = channel_family_id_in
           and cfm.channel_id = sc.channel_id
           and exists (
                select 1
                  from rhnChannelFamilyServerFve cfsp
                 where cfsp.CHANNEL_FAMILY_ID = channel_family_id_in
                   and cfsp.server_id = s.id
                );

        return current_members_count;
    end;
    PROCEDURE update_family_counts(channel_family_id_in IN NUMBER,
                                   org_id_in IN NUMBER)
    IS
    BEGIN
        update rhnPrivateChannelFamily
           set current_members = ( channel_family_current_members(channel_family_id_in, org_id_in)),
               fve_current_members = ( cfam_curr_fve_members(channel_family_id_in, org_id_in))
         where org_id = org_id_in
           and channel_family_id = channel_family_id_in;
    END update_family_counts;

    PROCEDURE update_group_family_counts(group_label_in IN VARCHAR2,
                                   org_id_in IN NUMBER)
    IS
    BEGIN
        FOR i IN (
                SELECT DISTINCT CFM.channel_family_id, SG.org_id
                 FROM rhnChannelFamilyMembers CFM
                 JOIN rhnServerChannel SC
                   ON SC.channel_id = CFM.channel_id
                 JOIN rhnServerGroupMembers SGM
                   ON SC.server_id = SGM.server_id
                 JOIN rhnServerGroup SG
                   ON SGM.server_group_id = SG.id
                 JOIN rhnServerGroupType SGT
                   ON SG.group_type = SGT.id
                WHERE SGT.label = group_label_in
                  AND SG.org_id = org_id_in
                  AND SGT.is_base = 'Y'
        ) LOOP
            rhn_channel.update_family_counts(i.channel_family_id, i.org_id);
        END LOOP;
    END update_group_family_counts;

    FUNCTION available_chan_subscriptions(channel_id_in IN NUMBER,
                                          org_id_in IN NUMBER)
    RETURN NUMBER
    IS
            channel_family_id_val NUMBER;
    BEGIN
        SELECT channel_family_id INTO channel_family_id_val
            FROM rhnChannelFamilyMembers
            WHERE channel_id = channel_id_in;

            RETURN rhn_channel.available_family_subscriptions(
                           channel_family_id_val, org_id_in);
    END available_chan_subscriptions;

	FUNCTION available_fve_chan_subs(channel_id_in IN NUMBER,
                                          org_id_in IN NUMBER)
    RETURN NUMBER
    IS
        channel_family_id_val NUMBER;

    BEGIN
        SELECT channel_family_id INTO channel_family_id_val
          FROM rhnChannelFamilyMembers
         WHERE channel_id = channel_id_in;

        RETURN rhn_channel.available_fve_family_subs( channel_family_id_val, org_id_in);
    END available_fve_chan_subs;

    procedure unsubscribe_server_from_family(server_id_in in number,
                                             channel_family_id_in in number)
    is
    begin
        delete
        from    rhnServerChannel rsc
        where   rsc.server_id = server_id_in
            and channel_id in (
                select  rcfm.channel_id
                from    rhnChannelFamilyMembers rcfm
                where   rcfm.channel_family_id = channel_family_id_in);
    end;

    function get_org_id(channel_id_in in number)
    return number
    is
        org_id_out number;
    begin
        select org_id into org_id_out
            from rhnChannel
            where id = channel_id_in;

            return org_id_out;
    end get_org_id;

    function get_cfam_org_access(cfam_id_in in number, org_id_in in number)
    return number
    is
        cursor  families is
                        select  1
                        from    rhnOrgChannelFamilyPermissions cfp
                        where   cfp.org_id = org_id_in;
    begin
                -- the idea: if we get past this query,
        -- the user has the role, else catch the exception and return 0
                for family in families loop
                return 1;
                end loop;
                return 0;
    end;

    function get_org_access(channel_id_in in number, org_id_in in number)
    return number
    is
        throwaway number;
    begin
        -- the idea: if we get past this query,
        -- the org has access to the channel, else catch the exception and return 0
        select distinct 1 into throwaway
          from rhnChannelFamilyMembers CFM,
               rhnOrgChannelFamilyPermissions CFP
         where cfp.org_id = org_id_in
           and CFM.channel_family_id = CFP.channel_family_id
           and CFM.channel_id = channel_id_in
           and (CFP.max_members > 0 or CFP.max_members is null or CFP.org_id = 1);

        return 1;
        exception
            when no_data_found
            then
            return 0;
    end;

    -- check if a user has a given role, or if such a role is inferrable
    function user_role_check_debug(channel_id_in in number,
                                   user_id_in in number,
                                   role_in in varchar2,
                                   reason_out out varchar2)
    return number
    is
        org_id number;
    begin
        org_id := rhn_user.get_org_id(user_id_in);

        -- channel might be shared
        if role_in = 'subscribe' and
           rhn_channel.shared_user_role_check(channel_id_in, user_id_in, role_in) = 1 then
            return 1;
        end if;

        if role_in = 'manage' and
           NVL(rhn_channel.get_org_id(channel_id_in), -1) <> org_id then
                reason_out := 'channel_not_owned';
               return 0;
            end if;

        if role_in = 'subscribe' and
           rhn_channel.get_org_access(channel_id_in, org_id) = 0 then
                reason_out := 'channel_not_available';
                return 0;
            end if;

        -- channel admins have all roles
        if rhn_user.check_role_implied(user_id_in, 'channel_admin') = 1 then
            reason_out := 'channel_admin';
            return 1;
            end if;

        -- the subscribe permission is inferred
    -- UNLESS the not_globally_subscribable flag is set
        if role_in = 'subscribe'
        then
            if rhn_channel.org_channel_setting(channel_id_in,
                       org_id,
                       'not_globally_subscribable') = 0 then
                reason_out := 'globally_subscribable';
                    return 1;
            end if;
        end if;

        -- all other roles (manage right now) are explicitly granted
        reason_out := 'direct_permission';
        return rhn_channel.direct_user_role_check(channel_id_in,
                                              user_id_in, role_in);
    end;

    -- same as above, but with no OUT param; useful in views, etc
    function user_role_check(channel_id_in in number, user_id_in in number, role_in in varchar2)
    return number
    is
        throwaway varchar2(256);
    begin
        return rhn_channel.user_role_check_debug(channel_id_in, user_id_in, role_in, throwaway);
    end;

    --
    -- For multiorg phase II, this function simply checks to see if the user's
    -- has a trust relationship that includes this channel by id.
    --
    function shared_user_role_check(channel_id in number, user_id in number, role in varchar2)
    return number
    is
      n number;
      oid number;
    begin
      oid := rhn_user.get_org_id(user_id);
      select 1 into n
      from rhnSharedChannelView s
      where s.id = channel_id and s.org_trust_id = oid;
      return 1;
      exception
        when no_data_found then
          return 0;
    end;

    -- same as above, but returns 1 if user_id_in is null
    -- This is useful in queries where user_id is not specified
    function loose_user_role_check(channel_id_in in number, user_id_in in number, role_in in varchar2)
    return number
    is
    begin
        if user_id_in is null then
            return 1;
        end if;
        return user_role_check(channel_id_in, user_id_in, role_in);
    end loose_user_role_check;

    -- directly checks the table, no inferred permissions
    function direct_user_role_check(channel_id_in in number, user_id_in in number, role_in in varchar2)
    return number
    is
        throwaway number;
    begin
        -- the idea: if we get past this query, the user has the role, else catch the exception and return 0
        select 1 into throwaway
          from rhnChannelPermissionRole CPR,
               rhnChannelPermission CP
         where CP.user_id = user_id_in
           and CP.channel_id = channel_id_in
           and CPR.label = role_in
           and CP.role_id = CPR.id;

        return 1;
    exception
        when no_data_found
            then
            return 0;
    end;

    -- check if an org has a certain setting
    function org_channel_setting(channel_id_in in number, org_id_in in number, setting_in in varchar2)
    return number
    is
        throwaway number;
    begin
        -- the idea: if we get past this query, the org has the setting, else catch the exception and return 0
        select 1 into throwaway
          from rhnOrgChannelSettingsType OCST,
               rhnOrgChannelSettings OCS
         where OCS.org_id = org_id_in
           and OCS.channel_id = channel_id_in
           and OCST.label = setting_in
           and OCS.setting_id = OCST.id;

        return 1;
    exception
        when no_data_found
            then
            return 0;
    end;

    FUNCTION channel_priority(channel_id_in IN number)
    RETURN number
    IS
         channel_name varchar2(256);
         priority number;
         end_of_life_val date;
         org_id_val number;
    BEGIN

        select name, end_of_life, org_id
        into channel_name, end_of_life_val, org_id_val
        from rhnChannel
        where id = channel_id_in;

        if end_of_life_val is not null then
          return -400;
        end if;

        if channel_name like 'Red Hat Enterprise Linux%' or channel_name like 'RHEL%' then
          priority := 1000;
          if channel_name not like '%Beta%' then
            priority := priority + 1000;
          end if;

          priority := priority +
            case
              when channel_name like '%v. 5%' then 600
              when channel_name like '%v. 4%' then 500
              when channel_name like '%v. 3%' then 400
              when channel_name like '%v. 2%' then 300
              when channel_name like '%v. 1%' then 200
              else 0
            end;

          priority := priority +
            case
              when channel_name like 'Red Hat Enterprise Linux (v. 5%' then 60
              when (channel_name like '%AS%' and channel_name not like '%Extras%') then 50
              when (channel_name like '%ES%' and channel_name not like '%Extras%') then 40
              when (channel_name like '%WS%' and channel_name not like '%Extras%') then 30
              when (channel_name like '%Desktop%' and channel_name not like '%Extras%') then 20
              when channel_name like '%Extras%' then 10
              else 0
            end;

          priority := priority +
            case
              when channel_name like '%)' then 5
              else 0
            end;

          priority := priority +
            case
              when channel_name like '%32-bit x86%' then 4
              when channel_name like '%64-bit Intel Itanium%' then 3
              when channel_name like '%64-bit AMD64/Intel EM64T%' then 2
              else 0
            end;
        elsif channel_name like 'Red Hat Desktop%' then
            priority := 900;

            if channel_name not like '%Beta%' then
               priority := priority + 50;
            end if;

          priority := priority +
            case
              when channel_name like '%v. 4%' then 40
              when channel_name like '%v. 3%' then 30
              when channel_name like '%v. 2%' then 20
              when channel_name like '%v. 1%' then 10
              else 0
            end;

          priority := priority +
            case
              when channel_name like '%32-bit x86%' then 4
              when channel_name like '%64-bit Intel Itanium%' then 3
              when channel_name like '%64-bit AMD64/Intel EM64T%' then 2
              else 0
            end;

        elsif org_id_val is not null then
          priority := 600;
        else
          priority := 500;
        end if;

      return -priority;

    end channel_priority;

    -- right now this only does the accounting changes; the cascade
    -- actually does the rhnServerChannel delete.
    procedure delete_server_channels(server_id_in in number)
    is
    begin
        update  rhnPrivateChannelFamily
        set     current_members = current_members -1
        where   org_id in (
                        select  org_id
                        from    rhnServer
                        where   id = server_id_in
                )
                and channel_family_id in (
                        select  rcfm.channel_family_id
                        from    rhnChannelFamilyMembers rcfm,
                                rhnServerChannel rsc
                        where   rsc.server_id = server_id_in
                                and rsc.channel_id = rcfm.channel_id
                and not exists (
                    select 1
                    from
                        rhnChannelFamilyVirtSubLevel cfvsl,
                        rhnSGTypeVirtSubLevel sgtvsl,
                        rhnServerEntitlementView sev,
                        rhnVirtualInstance vi
                    where
                        -- system is a virtual instance
                        vi.virtual_system_id = server_id_in
                        and vi.host_system_id = sev.server_id
                        -- system's host has a virt ent
                        and sev.label in ('virtualization_host',
                                          'virtualization_host_platform')
                        and sev.server_group_type_id =
                            sgtvsl.server_group_type_id
                        -- the host's virt ent grants a cf virt sub level
                        and sgtvsl.virt_sub_level_id = cfvsl.virt_sub_level_id
                        -- the cf is in that virt sub level
                        and cfvsl.channel_family_id = rcfm.channel_family_id
                    )
                );
    end;

        -- this could certainly be optimized to do updates if needs be
        procedure refresh_newest_package(channel_id_in in number, caller_in in varchar2 := '(unknown)')
        is
        begin
                delete from rhnChannelNewestPackage where channel_id = channel_id_in;
                insert into rhnChannelNewestPackage
                        ( channel_id, name_id, evr_id, package_id, package_arch_id )
                        (       select  channel_id,
                                                name_id, evr_id,
                                                package_id, package_arch_id
                                from    rhnChannelNewestPackageView
                                where   channel_id = channel_id_in
                        );
                insert into rhnChannelNewestPackageAudit (channel_id, caller)
                    values (channel_id_in, caller_in);
                update rhnChannel
                    set last_modified = greatest(sysdate, last_modified + 1/86400)
                    where id = channel_id_in;
        end;

   procedure update_channel ( channel_id_in in number, invalidate_ss in number := 0,
                              date_to_use in date := sysdate )
   is

   channel_last_modified date;
   last_modified_value date;

   cursor snapshots is
   select  snapshot_id id
   from    rhnSnapshotChannel
   where   channel_id = channel_id_in;

   begin

      select last_modified
      into channel_last_modified
      from rhnChannel
      where id = channel_id_in;

      last_modified_value := date_to_use;

      if last_modified_value <= channel_last_modified then
          last_modified_value := last_modified_value + 1/86400;
      end if;

      update rhnChannel set last_modified = last_modified_value
      where id = channel_id_in;

      if invalidate_ss = 1 then
        for snapshot in snapshots loop
            update rhnSnapshot
            set invalid = lookup_snapshot_invalid_reason('channel_modified')
            where id = snapshot.id;
        end loop;
      end if;

   end update_channel;

   procedure update_channels_by_package ( package_id_in in number, date_to_use in date := sysdate )
   is

   cursor channels is
   select channel_id
   from rhnChannelPackage
   where package_id = package_id_in
   order by channel_id;

   begin
      for channel in channels loop
         -- we want to invalidate the snapshot assocated with the channel when we
         -- do this b/c we know we've added or removed or packages
         rhn_channel.update_channel ( channel.channel_id, 1, date_to_use );
      end loop;
   end update_channels_by_package;


   procedure update_channels_by_errata ( errata_id_in number, date_to_use in date := sysdate )
   is

   cursor channels is
   select channel_id
   from rhnChannelErrata
   where errata_id = errata_id_in
   order by channel_id;

   begin
      for channel in channels loop
         -- we won't invalidate snapshots, b/c just changing the errata associated with
         -- a channel shouldn't invalidate snapshots
         rhn_channel.update_channel ( channel.channel_id, 0, date_to_use );
      end loop;
   end update_channels_by_errata;

   procedure update_needed_cache(channel_id_in in number)
   is
       pragma autonomous_transaction;
                -- update of needed cache ican be commited on a per server basis
                -- b/c failure of update for a server means nothing for the other servers
   begin
      -- we intentionaly do a loop here instead of one huge select
      -- b/c we want to break update into smaller transaction to unblock other sessions
      -- querying rhnServerNeededCache
      for server in (
                select sc.server_id as id
                  from rhnServerChannel sc
                 where sc.channel_id = channel_id_in
      ) loop
         rhn_server.update_needed_cache(server.id);
         commit;
      end loop;
   end update_needed_cache;

   -- return true if the given server has a subs to a channel of channel_family_id_in
   FUNCTION server_has_family_subscription(server_id_in IN NUMBER, channel_family_id_in IN NUMBER)
   RETURN NUMBER
   IS
      CURSOR fam_entries IS
         SELECT DISTINCT cfm.channel_family_id
           FROM rhnchannelfamilymembers cfm
           JOIN rhnserverchannel sc on sc.channel_id = cfm.channel_id
          WHERE sc.server_id =  server_id_in
            AND cfm.channel_family_id = channel_family_id_in;
      fam_count NUMBER;
   BEGIN
      FOR fam_entry IN fam_entries LOOP
         RETURN 1;
      END LOOP;
      RETURN 0;
   END server_has_family_subscription;

END rhn_channel;
/
SHOW ERRORS
 0707010000064A000081B400000000000000000000000167AE1114000112F3000000000000000000000000000000000000006600000000susemanager-schema/upgrade/spacewalk-schema-1.2-to-susemanager-schema-1.2/301-rhn_entitlement_pkb.sql --
-- Copyright (c) 2008--2011 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--

create or replace
package body rhn_entitlements
is
    body_version varchar2(100) := '';

   function find_compatible_sg (
      server_id_in    in   number,
      type_label_in   in   varchar2
   ) return number is

      cursor servergroups is
         select sg.id            id
           from rhnServerGroupType             sgt,
                rhnServerGroup                 sg,
                rhnServer                     s,
                rhnServerServerGroupArchCompat ssgac
          where s.id = server_id_in
            and s.org_id = sg.org_id
            and sgt.label = type_label_in
            and sg.group_type = sgt.id
            and ssgac.server_group_type = sgt.id
            and ssgac.server_arch_id = s.server_arch_id
            and not exists ( 
                     select 1
                      from rhnServerGroupMembers sgm
                     where sgm.server_group_id = sg.id 
                       and sgm.server_id = s.id);

         
   begin
      for servergroup in servergroups loop
         return servergroup.id;
      end loop;

      --no servergroup found
      return null;
   end find_compatible_sg;


    -- *******************************************************************
    -- PROCEDURE: remove_org_entitlements
    --
    -- Removes both system entitlements and channel subscriptions
    -- that are currently assigned to an org and re-assigns to the
    -- master org (org_id = 1).
    --
    -- When we call this we expect everything to already be unentitled
    -- which shoul be handled by delete_org.
    --
    -- Called by: delete_org
    -- *******************************************************************
    procedure remove_org_entitlements(
        org_id_in in number
    )
    is

        cursor system_ents is
        select sg.id, sg.max_members, sg.group_type
        from rhnServerGroup sg
        where group_type is not null
          and org_id = org_id_in;

        cursor channel_subs is
        select pcf.channel_family_id, pcf.max_members
        from rhnChannelFamily cf,
             rhnPrivateChannelFamily pcf
        where pcf.org_id = org_id_in
          and pcf.channel_family_id = cf.id
          and cf.org_id is null;

    begin

        for system_ent in system_ents loop
            update rhnServerGroup
            set max_members = max_members + system_ent.max_members
            where org_id = 1
              and group_type = system_ent.group_type;
        end loop;

        update rhnServerGroup
        set max_members = 0
        where org_id = org_id_in;

        for channel_sub in channel_subs loop
            update rhnPrivateChannelFamily
            set max_members = max_members + channel_sub.max_members
            where org_id = 1
              and channel_family_id = channel_sub.channel_family_id;
        end loop;
        
        update rhnPrivateChannelFamily
        set max_members = 0
        where org_id = org_id_in;

    end remove_org_entitlements;
 
    function entitlement_grants_service (
        entitlement_in in varchar2,
        service_level_in in varchar2
    ) return number    is
    begin
        if service_level_in = 'provisioning' then
            if entitlement_in = 'provisioning_entitled' then
                return 1;
            else
                return 0;
            end if;
        elsif service_level_in = 'management' then
            if entitlement_in = 'enterprise_entitled' then
                return 1;
            else
                return 0;
            end if;
        elsif service_level_in = 'monitoring' then
            if entitlement_in = 'monitoring_entitled' then
                return 1;
            end if;
        elsif service_level_in = 'updates' then
            return 1;
        else
            return 0;
        end if;
    end entitlement_grants_service;

    function lookup_entitlement_group (
        org_id_in in number,
        type_label_in in varchar2 := 'sw_mgr_entitled'
    ) return number is
        cursor server_groups is
            select    sg.id                server_group_id
            from    rhnServerGroup        sg,
                    rhnServerGroupType    sgt
            where    sgt.label = type_label_in
                and sgt.id = sg.group_type
                and sg.org_id = org_id_in;
    begin
        for sg in server_groups loop
            return sg.server_group_id;
        end loop;
        return rhn_entitlements.create_entitlement_group(
                org_id_in,
                type_label_in
            );
    end lookup_entitlement_group;

    function create_entitlement_group (
        org_id_in in number,
        type_label_in in varchar2 := 'sw_mgr_entitled'
    ) return number is
        sg_id_val number;
    begin
        select    rhn_server_group_id_seq.nextval
        into    sg_id_val
        from    dual;

        insert into rhnServerGroup (
                id, name, description, max_members, current_members,
                group_type, org_id
            ) (
                select    sg_id_val, sgt.label, sgt.label,
                        0, 0, sgt.id, org_id_in
                from    rhnServerGroupType sgt
                where    sgt.label = type_label_in
            );

        return sg_id_val;
    end create_entitlement_group;

   function can_entitle_server ( 
        server_id_in in number, 
        type_label_in in varchar2 ) 
   return number is
      cursor addon_servergroups (base_label_in in varchar2, 
                                 addon_label_in in varchar2) is
         select
            addon_id
         from
            rhnSGTypeBaseAddonCompat
         where base_id = lookup_sg_type (base_label_in)
           and addon_id = lookup_sg_type (addon_label_in);

      previous_ent        rhn_entitlements.ents_array;
      is_base_in          char   := 'N';
      is_base_current     char   := 'N';
      i                   number := 0;
      sgid                number := 0;

   begin

      previous_ent := rhn_entitlements.ents_array();
      previous_ent := rhn_entitlements.get_server_entitlement(server_id_in);

      select distinct is_base
      into is_base_in
      from rhnServerGroupType
      where label = type_label_in;

      if previous_ent.count = 0 then
         sgid := find_compatible_sg (server_id_in, type_label_in);
         if (is_base_in = 'Y' and sgid is not null) then
            -- rhn_server.insert_into_servergroup (server_id_in, sgid);
            return 1;
         else
            -- rhn_exception.raise_exception ('invalid_base_entitlement');
            return 0;
         end if;

      -- there are previous ents, first make sure we're not trying to entitle a base ent
      elsif is_base_in = 'Y' then
         -- rhn_exception.raise_exception ('invalid_addon_entitlement');
         return 0;

      -- it must be an addon, so proceed with the entitlement
      else

         -- find the servers base ent
         is_base_current := 'N';
         i := 0;
         while is_base_current = 'N' and i <= previous_ent.count
         loop
            i := i + 1;
            select is_base
            into is_base_current
            from rhnServerGroupType
            where label = previous_ent(i);
         end loop;

         -- never found a base ent, that would be strange
         if is_base_current  = 'N' then
            -- rhn_exception.raise_exception ('invalid_base_entitlement');
            return 0;
         end if;

         -- this for loop verifies the validity of the addon path
         for addon_servergroup in addon_servergroups  (previous_ent(i), type_label_in) loop
            -- find an appropriate sgid for the addon and entitle the server
            sgid := find_compatible_sg (server_id_in, type_label_in);
            if sgid is not null then
               -- rhn_server.insert_into_servergroup (server_id_in, sgid);
               return 1;
            else
               -- rhn_exception.raise_exception ('invalid_addon_entitlement');
               return 0;
            end if;
         end loop;

      end if;

      return 0;

   end can_entitle_server;

   function can_switch_base (
      server_id_in   in    integer,
      type_label_in  in    varchar2
   ) return number is

      type_label_in_is_base   char(1);
      sgid                    number;

   begin

      begin
         select is_base into type_label_in_is_base
         from rhnServerGroupType
         where label = type_label_in;
      exception
         when no_data_found then
            rhn_exception.raise_exception ( 'invalid_entitlement' );
      end;

      if type_label_in_is_base = 'N' then
         rhn_exception.raise_exception ( 'invalid_entitlement' );
      else
         sgid := find_compatible_sg ( server_id_in, type_label_in );
         if sgid is not null then
            return 1;
         else
            return 0;
         end if;
      end if;

   end can_switch_base;


    procedure entitle_server (
        server_id_in in number,
        type_label_in in varchar2 := 'sw_mgr_entitled'
    ) is
      sgid  number := 0;
      is_virt number := 0;

    begin

          begin
          select 1 into is_virt
            from rhnServerEntitlementView
           where server_id = server_id_in
             and label in ('virtualization_host', 'virtualization_host_platform');
      exception
            when no_data_found then
              is_virt := 0;
          end;
      
      if is_virt = 0 and (type_label_in = 'virtualization_host' or
                          type_label_in = 'virtualization_host_platform') then

        is_virt := 1;
      end if;



      if rhn_entitlements.can_entitle_server(server_id_in, 
                                             type_label_in) = 1 then
         sgid := find_compatible_sg (server_id_in, type_label_in);
         if sgid is not null then
            insert into rhnServerHistory ( id, server_id, summary, details )
            values ( rhn_event_id_seq.nextval, server_id_in,
                     'added system entitlement ',
                      case type_label_in
                       when 'enterprise_entitled' then 'Management'
                       when 'sw_mgr_entitled' then 'Update'
                       when 'provisioning_entitled' then 'Provisioning'
                       when 'monitoring_entitled' then 'Monitoring'  
                       when 'virtualization_host' then 'Virtualization'
                       when 'virtualization_host_platform' then 
                            'Virtualization Platform' end  );

            rhn_server.insert_into_servergroup (server_id_in, sgid);

            if is_virt = 1 then
              rhn_entitlements.repoll_virt_guest_entitlements(server_id_in);
            end if;

         else
            rhn_exception.raise_exception ('no_available_server_group');
         end if;
      else
         rhn_exception.raise_exception ('invalid_entitlement');
      end if;
   end entitle_server;

    procedure remove_server_entitlement (
        server_id_in in number,
        type_label_in in varchar2 := 'sw_mgr_entitled',
        repoll_virt_guests in number := 1
    ) is
        group_id number;
      type_is_base char;
      is_virt number := 0;
    begin
      begin


      -- would be nice if there were a virt attribute of entitlement types, not have to specify 2 different ones...
        begin
          select 1 into is_virt
            from rhnServerEntitlementView
           where server_id = server_id_in
             and label in ('virtualization_host', 'virtualization_host_platform');
        exception
          when no_data_found then
            is_virt := 0;
        end;

        select    sg.id, sgt.is_base
          into    group_id, type_is_base
          from    rhnServerGroupType sgt,
               rhnServerGroup sg,
                  rhnServerGroupMembers sgm,
                  rhnServer s
          where    s.id = server_id_in
              and s.id = sgm.server_id
              and sgm.server_group_id = sg.id
              and sg.org_id = s.org_id
              and sgt.label = type_label_in
              and sgt.id = sg.group_type;

      if ( type_is_base = 'Y' ) then
         -- unentitle_server should handle everything, don't really need to do anything else special here
         unentitle_server ( server_id_in );
      else

         insert into rhnServerHistory ( id, server_id, summary, details )
         values ( rhn_event_id_seq.nextval, server_id_in,
                  'removed system entitlement ',
                   case type_label_in
                    when 'enterprise_entitled' then 'Management'
                    when 'sw_mgr_entitled' then 'Update'
                    when 'provisioning_entitled' then 'Provisioning'
                    when 'monitoring_entitled' then 'Monitoring'
                    when 'virtualization_host' then 'Virtualization'
                    when 'virtualization_host_platform' then 
                         'Virtualization Platforrm' end  );

         rhn_server.delete_from_servergroup(server_id_in, group_id);

         -- special case: clean up related monitornig data
         if type_label_in = 'monitoring_entitled' then
           DELETE
             FROM state_change
            WHERE o_id IN (SELECT probe_id
                             FROM rhn_check_probe
                            WHERE host_id = server_id_in);
           DELETE /*+index(time_series time_series_probe_id_idx)*/
             FROM time_series
            WHERE SUBSTR(o_id, INSTR(o_id, '-') + 1, 
                        (INSTR(o_id, '-', INSTR(o_id, '-') + 1) - INSTR(o_id, '-')) - 1)
              IN (SELECT to_char(probe_id)
                    FROM rhn_check_probe
                   WHERE host_id = server_id_in);
           DELETE
             FROM rhn_probe
            WHERE recid IN (SELECT probe_id
                              FROM rhn_check_probe
                             WHERE host_id = server_id_in);
         end if;

         if is_virt = 1 and repoll_virt_guests = 1 then
           rhn_entitlements.repoll_virt_guest_entitlements(server_id_in);
         end if;
      end if;

          exception
          when no_data_found then
                  rhn_exception.raise_exception('invalid_server_group_member');
      end;

     end remove_server_entitlement;


   procedure unentitle_server (server_id_in in number) is

      cursor servergroups is
         select distinct sgt.label, sg.id server_group_id
         from  rhnServerGroupType sgt,
               rhnServerGroup sg,
               rhnServer s,
               rhnServerGroupMembers sgm
         where s.id = server_id_in
            and s.org_id = sg.org_id
            and sg.group_type = sgt.id
            and sgm.server_group_id = sg.id
            and sgm.server_id = s.id;
            
     is_virt number := 0;

   begin

      begin
        select 1 into is_virt
          from rhnServerEntitlementView
         where server_id = server_id_in
           and label in ('virtualization_host', 'virtualization_host_platform');
      exception
        when no_data_found then
          is_virt := 0;
      end;

      for servergroup in servergroups loop

         insert into rhnServerHistory ( id, server_id, summary, details )
         values ( rhn_event_id_seq.nextval, server_id_in,
                  'removed system entitlement ',
                   case servergroup.label
                    when 'enterprise_entitled' then 'Management'
                    when 'sw_mgr_entitled' then 'Update'
                    when 'provisioning_entitled' then 'Provisioning'
                    when 'monitoring_entitled' then 'Monitoring'
                    when 'virtualization_host' then 'Virtualization'
                    when 'virtualization_host_platform' then 
                         'Virtualization Platform' end  );
  
         rhn_server.delete_from_servergroup(server_id_in, 
                                            servergroup.server_group_id );
      end loop;

      if is_virt = 1 then
        rhn_entitlements.repoll_virt_guest_entitlements(server_id_in);
      end if;

   end unentitle_server;


    -- *******************************************************************
    -- PROCEDURE: repoll_virt_guest_entitlements
    --
    --   Whenever we add/remove a virtualization_host* entitlement from 
    --   a host, we can call this procedure to update what type of slots
    --   the guests are consuming.  
    -- 
    --   If you're removing the entitlement, it's 
    --   possible the guests will become unentitled if you don't have enough
    --   physical slots to cover them.
    --
    --   If you're adding the entitlement, you end up freeing up physical
    --   slots for other systems.
    --
    -- *******************************************************************
    procedure repoll_virt_guest_entitlements(server_id_in in number)
    is

        -- All channel families associated with the guests of server_id_in
        cursor families is 
            select distinct cfs.channel_family_id
            from
                rhnChannelFamilyServers cfs,
                rhnVirtualInstance vi
            where
                vi.host_system_id = server_id_in
                and vi.virtual_system_id = cfs.server_id;
        
        -- All of server group types associated with the guests of
        -- server_id_in
        cursor group_types is
            select distinct sg.group_type, sgt.label
            from
                rhnServerGroupType sgt,
                rhnServerGroup sg,
                rhnServerGroupMembers sgm,
                rhnVirtualInstance vi
            where
                vi.host_system_id = server_id_in
                and vi.virtual_system_id = sgm.server_id
                and sgm.server_group_id = sg.id
                and sg.group_type = sgt.id;

        -- Virtual servers from a certain family belonging to a speicifc
        -- host that are consuming physical channel slots over the limit.
        cursor virt_servers_cfam(family_id_in in number, quantity_in in number)  is
            select virtual_system_id
            from (
                select rownum, vi.virtual_system_id
                from
                    rhnChannelFamilyMembers cfm,
                    rhnServerChannel sc,
                    rhnVirtualInstance vi
                where
                    vi.host_system_id = server_id_in
                    and vi.virtual_system_id = sc.server_id
                    and sc.channel_id = cfm.channel_id
                    and cfm.channel_family_id = family_id_in
                order by sc.modified desc
                )
            where rownum <= quantity_in;

        -- Virtual servers from a certain family belonging to a speicifc
        -- host that are consuming physical system slots over the limit.
        cursor virt_servers_sgt(group_type_in in number, quantity_in in number)  is
            select virtual_system_id
            from (
                select rownum, vi.virtual_system_id
                from
                    rhnServerGroup sg,
                    rhnServerGroupMembers sgm,
                    rhnVirtualInstance vi
                where
                    vi.host_system_id = server_id_in
                    and vi.virtual_system_id = sgm.server_id
                    and sgm.server_group_id = sg.id
                    and sg.group_type = group_type_in
                order by sgm.modified desc
                )
            where rownum <= quantity_in;
        -- Get the orgs of Virtual guests
        -- Since they may belong to different orgs
        cursor virt_guest_orgs  is
                select  distinct (s.org_id)
                from rhnServer s
                    inner join  rhnVirtualInstance vi on vi.virtual_system_id = s.id
                where
                    vi.host_system_id = server_id_in 
                    and s.org_id <> (select s1.org_id from rhnServer s1 where s1.id = vi.host_system_id) ;


        org_id_val number;
        max_members_val number;
        max_flex_val number;
        current_members_calc number;
        sg_id number;
        is_virt number := 0;
    begin
        begin
          select 1 into is_virt
                from rhnServerEntitlementView
           where server_id = server_id_in
                 and label in ('virtualization_host', 'virtualization_host_platform');
           exception
                when no_data_found then
                  is_virt := 0;
        end;

        select org_id
        into org_id_val
        from rhnServer
        where id = server_id_in;

        -- deal w/ channel entitlements first ...
        for family in families loop
            if is_virt = 0 then
            -- if the host_server does not have virt
            --- find all possible flex slots
            -- and set each of the flex eligible guests to Y
                UPDATE rhnServerChannel sc set sc.is_fve = 'Y'
                where sc.server_id in (
                       select virtual_system_id from (
                            select rownum, vi.virtual_system_id,  sfc.max_members - sfc.current_members as free_slots
                            from rhnServerFveCapable sfc
                                inner join rhnVirtualInstance vi on vi.virtual_system_id = sfc.server_id
                            where vi.host_system_id = server_id_in
                                  and sfc.channel_family_id = family.channel_family_id
                              order by vi.modified desc
                          )
                        where rownum <=  free_slots
                );
            else
            -- if the host_server has virt
            -- set all its flex guests to N
                UPDATE rhnServerChannel sc set sc.is_fve = 'N'
                where 
                    sc.channel_id in (select cfm.channel_id from rhnChannelFamilyMembers cfm
                                      where cfm.CHANNEL_FAMILY_ID = family.channel_family_id)
                    and sc.is_fve = 'Y'
                    and sc.server_id in  
                            (select vi.virtual_system_id  from rhnVirtualInstance vi 
                                    where vi.host_system_id = server_id_in);
            end if;
        
            -- get the current (physical) members of the family
            current_members_calc := 
                rhn_channel.channel_family_current_members(family.channel_family_id,
                                                           org_id_val); -- fixed transposed args

            -- get the max members of the family
            select max_members
            into max_members_val
            from rhnPrivateChannelFamily
            where channel_family_id = family.channel_family_id
            and org_id = org_id_val;

            select fve_max_members
            into max_flex_val
            from rhnPrivateChannelFamily
            where channel_family_id = family.channel_family_id
            and org_id = org_id_val;

            if current_members_calc > max_members_val then
                -- A virtualization_host* ent must have been removed, so we'll
                -- unsubscribe guests from the host first.

                -- hm, i don't think max_members - current_members_calc yielding a negative number
                -- will work w/ rownum, swaping 'em in the body of this if...
                for virt_server in virt_servers_cfam(family.channel_family_id,
                                current_members_calc - max_members_val) loop 

                    rhn_channel.unsubscribe_server_from_family(
                                virt_server.virtual_system_id,
                                family.channel_family_id);
                end loop;                               

                -- if we're still over the limit, which would be odd,
                -- just prune the group to max_members
                --
                -- er... wouldn't we actually have to refresh the values of
                -- current_members_calc and max_members_val to actually ever
                -- *skip this??
                if current_members_calc > max_members_val then
                    -- argh, transposed again?!
                    set_family_count(org_id_val,
                                     family.channel_family_id,
                                     max_members_val, max_flex_val);
                    --TODO calculate this correctly
                end if; 

           end if;

            -- update current_members for the family.  This will set the value
            -- to reflect adding/removing the entitlement.
            --
            -- what's the difference of doing this vs the unavoidable set_family_count above?
            rhn_channel.update_family_counts(family.channel_family_id,
                                             org_id_val);

            -- It is possible that the guests belong  to a different org than the host
            -- so we are going to update the family counts in the guests orgs also
            for org in virt_guest_orgs loop
                    rhn_channel.update_family_counts(family.channel_family_id,
                                             org.org_id);
            end loop;
        end loop;

        for a_group_type in group_types loop
          -- get the current *physical* members of the system entitlement type for the org...
          -- 
          -- unlike channel families, it appears the standard rhnServerGroup.max_members represents
          -- *physical* slots, vs physical+virt ... boy that's confusing...

          select max_members, id
            into max_members_val, sg_id
            from rhnServerGroup
            where group_type = a_group_type.group_type
            and org_id = org_id_val;


      select count(sep.server_id) into current_members_calc
            from rhnServerEntitlementPhysical sep
           where sep.server_group_id = sg_id
             and sep.server_group_type_id = a_group_type.group_type;
          
          if current_members_calc > max_members_val then
            -- A virtualization_host* ent must have been removed, and we're over the limit, so unsubscribe guests
            for virt_server in virt_servers_sgt(a_group_type.group_type,
                                                current_members_calc - max_members_val) loop
              rhn_entitlements.remove_server_entitlement(virt_server.virtual_system_id, a_group_type.label);

              -- decrement current_members_calc, we'll use it to reset current_members for the group at the end...
              current_members_calc := current_members_calc - 1;
            end loop;

          end if;

          update rhnServerGroup set current_members = current_members_calc
           where org_id = org_id_val
             and group_type = a_group_type.group_type;

          -- I think that's all the house-keeping we have to do...
        end loop;

    end repoll_virt_guest_entitlements;


    function get_server_entitlement (
        server_id_in in number
    ) return ents_array is

        cursor server_groups is
            select    sgt.label
            from    rhnServerGroupType        sgt,
                    rhnServerGroup            sg,
                    rhnServerGroupMembers    sgm
            where    1=1
                and sgm.server_id = server_id_in
                and sg.id = sgm.server_group_id
                and sgt.id = sg.group_type
                and sgt.label in (
                    'sw_mgr_entitled','enterprise_entitled',
                    'provisioning_entitled', 'nonlinux_entitled',
                    'monitoring_entitled', 'virtualization_host',
                                        'virtualization_host_platform'
                    );

         ent_array ents_array;

    begin
      
      ent_array := ents_array();

        for sg in server_groups loop
         ent_array.extend;
         ent_array(ent_array.count) := sg.label;
        end loop;

        return ent_array;

    end get_server_entitlement;


    -- this desperately needs to be table driven.
    procedure modify_org_service (
        org_id_in in number,
        service_label_in in varchar2,
        enable_in in char
    ) is
        type roles_v is varray(10) of rhnUserGroupType.label%TYPE;
        roles_to_process roles_v;
        cursor roles(role_label_in in varchar2) is
            select    label, id
            from    rhnUserGroupType
            where    label = role_label_in;
        cursor org_roles(role_label_in in varchar2) is
            select    1
            from    rhnUserGroup ug,
                    rhnUserGroupType ugt
            where    ugt.label = role_label_in
                and ug.org_id = org_id_in
                and ugt.id = ug.group_type;

        type ents_v is varray(10) of rhnOrgEntitlementType.label%TYPE;
        ents_to_process ents_v;
        cursor ents(ent_label_in in varchar2) is
            select    label, id
            from    rhnOrgEntitlementType
            where    label = ent_label_in;
        cursor org_ents(ent_label_in in varchar2) is
            select    1
            from    rhnOrgEntitlements oe,
                    rhnOrgEntitlementType oet
            where    oet.label = ent_label_in
                and oe.org_id = org_id_in
                and oet.id = oe.entitlement_id;
        create_row char(1);
    begin
        ents_to_process := ents_v();
        roles_to_process := roles_v();
        -- a bit kludgy, but only for 3.4 really.  Certainly no
        -- worse than the old code...
        if service_label_in = 'enterprise' or
           service_label_in = 'management' then
            ents_to_process.extend;
            ents_to_process(ents_to_process.count) := 'sw_mgr_enterprise';

            roles_to_process.extend;
            roles_to_process(roles_to_process.count) := 'org_admin';

            roles_to_process.extend;
            roles_to_process(roles_to_process.count) := 'system_group_admin';

            roles_to_process.extend;
            roles_to_process(roles_to_process.count) := 'activation_key_admin';

            roles_to_process.extend;
            roles_to_process(roles_to_process.count) := 'org_applicant';
        elsif service_label_in = 'provisioning' then
            ents_to_process.extend;
            ents_to_process(ents_to_process.count) := 'rhn_provisioning';

            roles_to_process.extend;
            roles_to_process(roles_to_process.count) := 'system_group_admin';

            roles_to_process.extend;
            roles_to_process(roles_to_process.count) := 'activation_key_admin';

            roles_to_process.extend;
            roles_to_process(roles_to_process.count) := 'config_admin';
            -- another nasty special case...
            if enable_in = 'Y' then
                ents_to_process.extend;
                ents_to_process(ents_to_process.count) := 'sw_mgr_enterprise';
            end if;
        elsif service_label_in = 'monitoring' then
            ents_to_process.extend;
            ents_to_process(ents_to_process.count) := 'rhn_monitor';

            roles_to_process.extend;
            roles_to_process(roles_to_process.count) := 'monitoring_admin';
        elsif service_label_in = 'virtualization' then
            ents_to_process.extend;
            ents_to_process(ents_to_process.count) := 'rhn_virtualization';

            roles_to_process.extend;
            roles_to_process(roles_to_process.count) := 'config_admin';
        elsif service_label_in = 'virtualization_platform' then
            ents_to_process.extend;
            ents_to_process(ents_to_process.count) := 'rhn_virtualization_platform';
            roles_to_process.extend;
            roles_to_process(roles_to_process.count) := 'config_admin';
    elsif service_label_in = 'nonlinux' then
            ents_to_process.extend;
            ents_to_process(ents_to_process.count) := 'rhn_nonlinux';
            roles_to_process.extend;
            roles_to_process(roles_to_process.count) := 'config_admin';
        end if;

        if enable_in = 'Y' then
            for i in 1..ents_to_process.count loop
                for ent in ents(ents_to_process(i)) loop
                    create_row := 'Y';
                    for oe in org_ents(ent.label) loop
                        create_row := 'N';
                    end loop;
                    if create_row = 'Y' then
                        insert into rhnOrgEntitlements(org_id, entitlement_id)
                            values (org_id_in, ent.id);
                    end if;
                end loop;
            end loop;
            for i in 1..roles_to_process.count loop
                for role in roles(roles_to_process(i)) loop
                    create_row := 'Y';
                    for o_r in org_roles(role.label) loop
                        create_row := 'N';
                    end loop;
                    if create_row = 'Y' then
                        insert into rhnUserGroup(
                                id, name, description, current_members,
                                group_type, org_id
                            ) (
                                select    rhn_user_group_id_seq.nextval,
                                        ugt.name || 's',
                                        ugt.name || 's for Org ' ||
                                            o.name || ' ('|| o.id ||')',
                                        0, ugt.id, o.id
                                from    rhnUserGroupType ugt,
                                        web_customer o
                                where    o.id = org_id_in
                                    and ugt.id = role.id
                            );
                    end if;
                end loop;
            end loop;
        else
            for i in 1..ents_to_process.count loop
                for ent in ents(ents_to_process(i)) loop
                    delete from rhnOrgEntitlements
                     where org_id = org_id_in
                       and entitlement_id = ent.id;
                end loop;
            end loop;
        end if;
    end modify_org_service;

    procedure set_customer_enterprise (
        customer_id_in in number
    ) is
    begin
        modify_org_service(customer_id_in, 'enterprise', 'Y');
    end set_customer_enterprise;

    procedure set_customer_provisioning (
        customer_id_in in number
    ) is
    begin
        modify_org_service(customer_id_in, 'provisioning', 'Y');
    end set_customer_provisioning;

    procedure set_customer_monitoring (
        customer_id_in in number
    ) is
    begin
        modify_org_service(customer_id_in, 'monitoring', 'Y');
    end set_customer_monitoring;

    procedure set_customer_nonlinux (
        customer_id_in in number
    ) is
    begin
        modify_org_service(customer_id_in, 'nonlinux', 'Y');
    end set_customer_nonlinux;

    procedure unset_customer_enterprise (
        customer_id_in in number
    ) is
    begin
        modify_org_service(customer_id_in, 'enterprise', 'N');
    end unset_customer_enterprise;

    procedure unset_customer_provisioning (
        customer_id_in in number
    ) is
    begin
        modify_org_service(customer_id_in, 'provisioning', 'N');
    end unset_customer_provisioning;

    procedure unset_customer_monitoring (
        customer_id_in in number
    ) is
    begin
        modify_org_service(customer_id_in, 'monitoring', 'N');
    end unset_customer_monitoring;

    procedure unset_customer_nonlinux (
        customer_id_in in number
    ) is
    begin
        modify_org_service(customer_id_in, 'nonlinux', 'N');
    end unset_customer_nonlinux;

    -- *******************************************************************
    -- PROCEDURE: prune_group
    -- Unsubscribes servers consuming physical slots that over the org's
    --   limit.
    -- Called by: set_group_count, repoll_virt_guest_entitlements
    -- *******************************************************************
    procedure prune_group (
        group_id_in in number,
        type_in in char,
        quantity_in in number,
                update_family_countsYN in number := 1
    ) is
        cursor usergroups is
            select    user_id, user_group_id, ugt.label
            from    rhnUserGroupType    ugt,
                    rhnUserGroup        ug,
                    rhnUserGroupMembers    ugm
            where    1=1
                and ugm.user_group_id = group_id_in
                and ugm.user_id in (
                    select    user_id
                    from    (
                        select    rownum row_number,
                                user_id,
                                time
                        from    (
                            select    user_id,
                                    modified time
                            from    rhnUserGroupMembers
                            where    user_group_id = group_id_in
                            order by time asc
                        )
                    )
                    where    row_number > quantity_in
                )
                and ugm.user_group_id = ug.id
                and ug.group_type = ugt.id;
        cursor servergroups is
           select  server_id, server_group_id, sgt.id as group_type_id, sgt.label
            from    rhnServerGroupType              sgt,
                            rhnServerGroup                  sg,
                            rhnServerGroupMembers   sgm
            where   1=1
                    and sgm.server_group_id = group_id_in
                    and sgm.server_id in (
                            select  server_id
                            from    (
                                    select  rownum row_number,
                                                    server_id,
                                                    time
                                    from    (
                                            select  sep.server_id,
                                                    sep.modified time
                                            from
                                                rhnServerEntitlementPhysical sep
                                            where
                                                sep.server_group_id = group_id_in
                                            order by time asc
                                    )
                            )
                            where   row_number > quantity_in
                    )
                    and sgm.server_group_id = sg.id
                    and sg.group_type = sgt.id;
      type_is_base char;
    begin
        if type_in = 'U' then
            update        rhnUserGroup
                set        max_members = quantity_in
                where    id = group_id_in;

            for ug in usergroups loop
                rhn_user.remove_from_usergroup(ug.user_id, ug.user_group_id);
            end loop;
        elsif type_in = 'S' then
            update        rhnServerGroup
                set        max_members = quantity_in
                where    id = group_id_in;

            for sg in servergroups loop
                remove_server_entitlement(sg.server_id, sg.label);
            
            select is_base 
            into type_is_base
            from rhnServerGroupType sgt
            where sgt.id = sg.group_type_id;
 
            -- if we're removing a base ent, then be sure to
            -- remove the server's channel subscriptions.
            if ( type_is_base = 'Y' ) then
                   rhn_channel.clear_subscriptions(sg.server_id,
                                        update_family_countsYN => update_family_countsYN);
            end if;

            end loop;
        end if;
    end prune_group;

    -- *******************************************************************
    -- PROCEDURE: assign_system_entitlement
    --
    -- Moves system entitlements from from_org_id_in to to_org_id_in.
    -- Can raise not_enough_entitlements_in_base_org if from_org_id_in
    -- does not have enough entitlements to cover the move.
    -- Takes care of unentitling systems if necessary by calling 
    -- set_group_count
    -- *******************************************************************
    procedure assign_system_entitlement(
        group_label_in in varchar2,
        from_org_id_in in number,
        to_org_id_in in number,
        quantity_in in number
    )
    is
        prev_ent_count number;
    to_org_prev_ent_count number;
        new_ent_count number;
    new_quantity number;
        group_type number;
    begin

        begin
            select max_members
            into prev_ent_count
            from rhnServerGroupType sgt,
                 rhnServerGroup sg
            where sg.org_id = from_org_id_in
              and sg.group_type = sgt.id
              and sgt.label = group_label_in;
        exception
            when NO_DATA_FOUND then
                rhn_exception.raise_exception(
                              'not_enough_entitlements_in_base_org');
        end;

        begin
            select max_members
            into to_org_prev_ent_count
            from rhnServerGroupType sgt,
                 rhnServerGroup sg
            where sg.org_id = to_org_id_in
              and sg.group_type = sgt.id
              and sgt.label = group_label_in;
        exception
            when NO_DATA_FOUND then
                to_org_prev_ent_count := 0;
        end;

        begin
            select id
            into group_type
            from rhnServerGroupType
            where label = group_label_in;
        exception
            when NO_DATA_FOUND then
                rhn_exception.raise_exception(
                              'invalid_server_group');
        end;

        new_ent_count := prev_ent_count - quantity_in;

        if prev_ent_count > new_ent_count then
            new_quantity := to_org_prev_ent_count + quantity_in;
        end if;

        if new_ent_count < 0 then
            rhn_exception.raise_exception(
                          'not_enough_entitlements_in_base_org');
        end if;


        rhn_entitlements.set_group_count(from_org_id_in,
                                         'S',
                                         group_type,
                                         new_ent_count);

        rhn_entitlements.set_group_count(to_org_id_in,
                                         'S',
                                         group_type,
                                         new_quantity);
        
        -- Create or delete the entries in rhnOrgEntitlementType
        if group_label_in = 'enterprise_entitled' then 
            if new_quantity > 0 then
                set_customer_enterprise(to_org_id_in);
            else
                unset_customer_enterprise(to_org_id_in);
            end if;
        end if;

        if group_label_in = 'provisioning_entitled' then
            if new_quantity > 0 then
                set_customer_provisioning(to_org_id_in);
            else
                unset_customer_provisioning(to_org_id_in);
            end if;
        end if;

        if group_label_in = 'monitoring_entitled' then
            if new_quantity > 0 then
                set_customer_monitoring(to_org_id_in);
            else
                unset_customer_monitoring(to_org_id_in);
            end if;
        end if;

    end assign_system_entitlement;

    -- *******************************************************************
    -- PROCEDURE: assign_channel_entitlement
    --
    -- Moves channel entitlements from from_org_id_in to to_org_id_in.
    -- Can raise not_enough_entitlements_in_base_org if from_org_id_in
    -- does not have enough entitlements to cover the move.
    -- Takes care of unentitling systems if necessary by calling 
    -- set_family_count
    -- *******************************************************************
    procedure assign_channel_entitlement(
        channel_family_label_in in varchar2,
        from_org_id_in in number,
        to_org_id_in in number,
        quantity_in in number,
        flex_in in number
    )
    is
        from_org_prev_ent_count number;
        from_org_prev_ent_count_flex number;
        new_ent_count number;
        new_ent_count_flex number;
        to_org_prev_ent_count number;
        to_org_prev_ent_count_flex number;
        new_quantity number;
        new_flex number;
        cfam_id       number;
    begin

        begin
            select max_members
            into from_org_prev_ent_count
            from rhnChannelFamily cf,
                 rhnPrivateChannelFamily pcf
            where pcf.org_id = from_org_id_in
              and pcf.channel_family_id = cf.id
              and cf.label = channel_family_label_in;
        exception
            when NO_DATA_FOUND then
                rhn_exception.raise_exception(
                              'not_enough_entitlements_in_base_org');
        end;

        begin
            select max_members
            into to_org_prev_ent_count
            from rhnChannelFamily cf,
                 rhnPrivateChannelFamily pcf
            where pcf.org_id = to_org_id_in
              and pcf.channel_family_id = cf.id
              and cf.label = channel_family_label_in;
        exception
            when NO_DATA_FOUND then
                to_org_prev_ent_count := 0;
        end;

        begin
            select fve_max_members
            into from_org_prev_ent_count_flex
            from rhnChannelFamily cf,
                 rhnPrivateChannelFamily pcf
            where pcf.org_id = from_org_id_in
              and pcf.channel_family_id = cf.id
              and cf.label = channel_family_label_in;
        exception
            when NO_DATA_FOUND then
                rhn_exception.raise_exception(
                              'not_enough_flex_entitlements_in_base_org');
        end;

        begin
            select fve_max_members
            into to_org_prev_ent_count_flex
            from rhnChannelFamily cf,
                 rhnPrivateChannelFamily pcf
            where pcf.org_id = to_org_id_in
              and pcf.channel_family_id = cf.id
              and cf.label = channel_family_label_in;
        exception
            when NO_DATA_FOUND then
                to_org_prev_ent_count_flex := 0;
        end;

        begin
            select id
            into cfam_id
            from rhnChannelFamily
            where label = channel_family_label_in;
        exception
            when NO_DATA_FOUND then
                rhn_exception.raise_exception(
                              'invalid_channel_family');
        end;

        new_ent_count := from_org_prev_ent_count - quantity_in;
        new_ent_count_flex := from_org_prev_ent_count_flex - flex_in;

        if from_org_prev_ent_count >= new_ent_count then
            new_quantity := to_org_prev_ent_count + quantity_in;
       end if;

       if from_org_prev_ent_count_flex >= new_ent_count_flex then
            new_flex := to_org_prev_ent_count_flex + flex_in;
       end if;


        if new_ent_count < 0 then
            rhn_exception.raise_exception(
                          'not_enough_entitlements_in_base_org');
        end if;

        if new_ent_count_flex < 0 then
            rhn_exception.raise_exception(
                          'not_enough_flex_entitlements_in_base_org');
        end if;



        rhn_entitlements.set_family_count(from_org_id_in, cfam_id,
                                           new_ent_count, new_ent_count_flex);

        rhn_entitlements.set_family_count(to_org_id_in,
                                          cfam_id,
                                          new_quantity, new_flex);

    end assign_channel_entitlement;

    -- *******************************************************************
    -- PROCEDURE: activate_system_entitlement
    --
    -- Sets the values in rhnServerGroup for a given rhnServerGroupType.
    -- 
    -- Calls: set_group_count to update, prune, or create the group.
    -- Called by: the code that activates a satellite cert. 
    --
    -- Raises not_enough_entitlements_in_base_org if all entitlements
    -- in the org are used so the free entitlements would not cover
    -- the difference when descreasing the number of entitlements.
    -- *******************************************************************
    procedure activate_system_entitlement(
        org_id_in in number,
        group_label_in in varchar2,
        quantity_in in number
    )
    is
        prev_ent_count number; 
        prev_ent_count_sum number; 
        group_type number;
    begin

        -- Fetch the current entitlement count for the org
        -- into prev_ent_count
        begin
            select current_members
            into prev_ent_count
            from rhnServerGroupType sgt,
                 rhnServerGroup sg
            where sg.group_type = sgt.id
              and sgt.label = group_label_in
              and sg.org_id = org_id_in;
        exception
            when NO_DATA_FOUND then
                prev_ent_count := 0;
        end;

        begin
            select id
            into group_type
            from rhnServerGroupType
            where label = group_label_in;
        exception
            when NO_DATA_FOUND then
                rhn_exception.raise_exception(
                              'invalid_server_group');
        end;

        -- If we're setting the total entitlemnt count to a lower value,
        -- and that value is less than the allocated count in this org,
        -- we need to raise an exception.
        if quantity_in < prev_ent_count then
            rhn_exception.raise_exception(
                          'not_enough_entitlements_in_base_org');
        else
            -- don't update family counts after every server
            -- will do bulk update afterwards
            rhn_entitlements.set_group_count(org_id_in,
                                             'S',
                                             group_type,
                                             quantity_in,
                                             update_family_countsYN => 0);
            -- bulk update family counts
            rhn_channel.update_group_family_counts(group_label_in, org_id_in);
        end if;


    end activate_system_entitlement;

    -- *******************************************************************
    -- PROCEDURE: activate_channel_entitlement
    --
    -- Calls: set_family_count to update, prune, or create the family
    --        permission bucket.
    -- Called by: the code that activates a satellite cert. 
    --
    -- Raises not_enough_entitlements_in_base_org if there are not enough
    -- entitlements in the org to cover the difference when you are
    -- descreasing the number of entitlements.
    --
    -- The backend code in Python is expected to do whatever arithmetics
    -- is needed.
    -- *******************************************************************
    procedure activate_channel_entitlement(
        org_id_in in number,
        channel_family_label_in in varchar2,
        quantity_in in number,
        flex_in in number

    )
    is
        prev_ent_count number; 
        prev_flex_count number;
        prev_ent_count_sum number; 
        cfam_id number;
        reduce_quantity number;
        total_flex_capable number;
        cursor to_convert_reg (channel_family_id_val in number, org_id_in in number, quantity in number) 
                is
                     select SC.server_id
                     from rhnServerChannel SC inner join
                          rhnServer S on S.id = SC.server_id
                     where
                         is_fve = 'Y'
                         and S.org_id = org_id_in 
                         and SC.channel_id in
                         (select cfm.channel_id from rhnChannelFamilyMembers cfm
                             where cfm.CHANNEL_FAMILY_ID = channel_family_id_val)
                          and rownum <= quantity;
         cursor to_convert_flex (channel_family_id_val in number, org_id_in in number, quantity in number)
                 is
                   select server_id
                   from rhnServerFveCapable
                       where SERVER_ORG_ID = org_id_in and
                             channel_family_id = cfam_id and
                             rownum <= quantity;

    begin

        -- Fetch the current entitlement count for the org
        -- into prev_ent_count
        begin
            select current_members
            into prev_ent_count
            from rhnChannelFamily cf,
                 rhnPrivateChannelFamily pcf
            where pcf.org_id = org_id_in
              and pcf.channel_family_id = cf.id
              and cf.label = channel_family_label_in;
        exception
            when NO_DATA_FOUND then
                prev_ent_count := 0;
        end;

        begin
            select pcf.fve_current_members
            into prev_flex_count
            from rhnChannelFamily cf,
                 rhnPrivateChannelFamily pcf
            where pcf.org_id = org_id_in
              and pcf.channel_family_id = cf.id
              and cf.label = channel_family_label_in;
        exception
            when NO_DATA_FOUND then
                prev_flex_count := 0;
        end;


        begin
            select id
            into cfam_id
            from rhnChannelFamily
            where label = channel_family_label_in;
        exception
            when NO_DATA_FOUND then
                rhn_exception.raise_exception(
                              'invalid_channel_family');
        end;                              

        -- if there are too few flex entitlements
        if flex_in < prev_flex_count then
            -- and if the extra we need is less than or equal to our extra regular entitlements
            if prev_flex_count - flex_in <= quantity_in - prev_ent_count then
                   reduce_quantity := prev_flex_count - flex_in;
                   -- We need to convert some systems from flex guest to regular
                   for system in to_convert_reg(cfam_id, org_id_in, reduce_quantity) loop
                      --rhn_channel.convert_to_regular(system.server_id, cfam_id);
                      UPDATE rhnServerChannel sc set sc.is_fve = 'N'
                           where sc.server_id = system.server_id
                                 and sc.channel_id in (select cfm.channel_id
                                                          from rhnChannelFamilyMembers cfm
                                                          where cfm.channel_family_id = cfam_id);
                   end loop;

                   --reset previous counts 
                   prev_ent_count := prev_ent_count + reduce_quantity;
                   prev_flex_count := prev_flex_count - reduce_quantity; 
            else
                rhn_exception.raise_exception(
                          'not_enough_flex_entitlements_in_base_org');
            end if;
        end if;

        -- if there are too few regular entitlements, and extra flex entitlements
        if quantity_in < prev_ent_count and prev_flex_count < flex_in then
                -- how many flex-capable systems (that aren't using flex) do we have
                select count(*)
                   into total_flex_capable 
                   from rhnServerFveCapable
                       where SERVER_ORG_ID = org_id_in and
                             channel_family_id = cfam_id;
                -- if we have enough flex capable machines that is at least 
                --   as many as what we are over on 
                if total_flex_capable >= prev_ent_count - quantity_in then
                    reduce_quantity := prev_ent_count - quantity_in;
                    for system in to_convert_flex(cfam_id, org_id_in, reduce_quantity) loop 
--                          rhn_channel.convert_to_fve(system.server_id, cfam_id);
                        UPDATE rhnServerChannel sc set sc.is_fve = 'Y'
                           where sc.server_id = system.server_id 
                                 and sc.channel_id in (select cfm.channel_id
                                                          from rhnChannelFamilyMembers cfm
                                                          where cfm.channel_family_id = cfam_id);
                    end loop;
                    prev_ent_count := prev_ent_count - reduce_quantity;
                    prev_flex_count := prev_flex_count + reduce_quantity;
                end if; 
        end if;




        -- If we're setting the total entitlemnt count to a lower value,
        -- and that value is less than the count in that one org,
        -- we need to raise an exception.
        if quantity_in < prev_ent_count then
            rhn_exception.raise_exception(
                          'not_enough_entitlements_in_base_org');
        else
            -- even if we've manually converted systems to/from flex above
            -- set_family_count should call update_family_counts, to reset
            -- current used slots
            rhn_entitlements.set_family_count(org_id_in, cfam_id,
                                              quantity_in, flex_in);
        end if;

    end activate_channel_entitlement;


    procedure set_group_count (
        customer_id_in in number,
        type_in in char,
        group_type_in in number,
        quantity_in in number,
                update_family_countsYN in number := 1
    ) is
        group_id number;
        quantity number;
    begin
        quantity := quantity_in;
        if quantity is not null and quantity < 0 then
            quantity := 0;
        end if;

        if type_in = 'U' then
            select    rug.id
            into    group_id
            from    rhnUserGroup rug
            where    1=1
                and rug.org_id = customer_id_in
                and rug.group_type = group_type_in;
        elsif type_in = 'S' then
            select    rsg.id
            into    group_id
            from    rhnServerGroup rsg
            where    1=1
                and rsg.org_id = customer_id_in
                and rsg.group_type = group_type_in;
        end if;

        rhn_entitlements.prune_group(
            group_id,
            type_in,
            quantity,
                        update_family_countsYN
        );
    exception
        when no_data_found then
            if type_in = 'U' then
                insert into rhnUserGroup (
                        id, name, description, max_members, current_members,
                        group_type, org_id, created, modified
                    ) (
                        select    rhn_user_group_id_seq.nextval, name, name,
                                quantity, 0, id, customer_id_in,
                                sysdate, sysdate
                        from    rhnUserGroupType
                        where    id = group_type_in
                );
            elsif type_in = 'S' then
                insert into rhnServerGroup (
                        id, name, description, max_members, current_members,
                        group_type, org_id, created, modified
                    ) (
                        select    rhn_server_group_id_seq.nextval, name, name,
                                quantity, 0, id, customer_id_in,
                                sysdate, sysdate
                        from    rhnServerGroupType
                        where    id = group_type_in
                );
            end if;
    end set_group_count;

    -- *******************************************************************
    -- PROCEDURE: prune_family
    -- Unsubscribes servers consuming physical slots from the channel family 
    --   that are over the org's limit.
    -- Called by: set_family_count
    -- *******************************************************************
    procedure prune_family (
        customer_id_in in number,
        channel_family_id_in in number,
        quantity_in in number,
        flex_in in number
    ) is
       is_fve_in char;
       tmp_quantity number;

        cursor serverchannels is
            select    sc.server_id,
                    sc.channel_id
            from    rhnServerChannel sc,
                    rhnChannelFamilyMembers cfm
            where    1=1
                and cfm.channel_family_id = channel_family_id_in
                and cfm.channel_id = sc.channel_id
                and server_id in (
                    select    server_id
                      from    (
                        select server_id, time, rownum row_number
                        from    (
                            select rs.id  server_id, rcfm.modified time
                            from    rhnServerChannel         rsc,
                                    rhnChannelFamilyMembers  rcfm,
                                    rhnServer                rs
                            where    1=1
                                and rs.org_id = customer_id_in
                                and rs.id = rsc.server_id
                                and rsc.channel_id = rcfm.channel_id
                                and rcfm.channel_family_id =  channel_family_id_in
                                and rsc.is_fve = is_fve_in
                                -- we only want to grab servers consuming
                                -- physical slots.
                                and exists (
                                    select 1
                                    from rhnChannelFamilyServerPhysical cfsp
                                    where cfsp.server_id = rs.id
                                    and cfsp.channel_family_id = 
                                        channel_family_id_in
                                    )
                            order by time asc
                        )
                    )
                    where row_number > tmp_quantity
                );
    begin
        -- if we get a null customer_id, this is completely bogus.
        if customer_id_in is null then
            return;
        end if;

        tmp_quantity := quantity_in;
        is_fve_in := 'N';

        for sc in serverchannels loop
            rhn_channel.unsubscribe_server(sc.server_id, sc.channel_id, 1, 1,
                                                       update_family_countsYN => 0);

        tmp_quantity := flex_in;
        is_fve_in := 'Y';
        for sc in serverchannels loop
            rhn_channel.unsubscribe_server(sc.server_id, sc.channel_id, 1, 1,
                                                        update_family_countsYN => 0);
        end loop;



        end loop;
                rhn_channel.update_family_counts(channel_family_id_in, customer_id_in);
    end prune_family;

    procedure set_family_count (
        customer_id_in in number,
        channel_family_id_in in number,
        quantity_in in number,
        flex_in in number
    ) is
        cursor privperms is
            select    1
            from    rhnPrivateChannelFamily
            where    org_id = customer_id_in
                and channel_family_id = channel_family_id_in;
        cursor pubperms is
            select    o.id org_id
            from    web_customer o,
                    rhnPublicChannelFamily pcf
            where    pcf.channel_family_id = channel_family_id_in;
        quantity number;
        done number := 0;
        flex number;
    begin
        quantity := quantity_in;
        if quantity is not null and quantity < 0 then
            quantity := 0;
        end if;
        flex := flex_in;
        if flex is not null and flex < 0 then
            flex := 0;
        end if;


        if customer_id_in is not null then
            for perm in privperms loop
                rhn_entitlements.prune_family(customer_id_in, channel_family_id_in,
                    quantity, flex);

               update rhnPrivateChannelFamily
                    set max_members = quantity
                    where org_id = customer_id_in
                        and channel_family_id = channel_family_id_in;

               update rhnPrivateChannelFamily
                    set fve_max_members = flex
                    where org_id = customer_id_in
                        and channel_family_id = channel_family_id_in;

                return;
            end loop;

            insert into rhnPrivateChannelFamily (
                    channel_family_id, org_id, max_members, current_members, fve_max_members, fve_current_members
                ) values (
                    channel_family_id_in, customer_id_in, quantity, 0, flex, 0 );
            return;
        end if;

        for perm in pubperms loop
            if quantity = 0 then
                rhn_entitlements.prune_family(
                    perm.org_id,
                    channel_family_id_in,
                    quantity,
                    flex
                );
                if done = 0 then
                    delete from rhnPublicChannelFamily
                        where channel_family_id = channel_family_id_in;
                end if;
            end if;
            done := 1;
        end loop;
        -- if done's not 1, then we don't have any entitlements
        if done != 1 then
            insert into rhnPublicChannelFamily (
                    channel_family_id
                ) values (
                    channel_family_id_in
                );
        end if;
    end set_family_count;

    -- this expects quantity_in to be the number of available slots, not the
    -- max_members of the server group.  If you give it too many, it'll fail
    -- and raise servergroup_max_members.
    -- We should NEVER run this unless we're SURE that we won't
    -- be violating the max.
    procedure entitle_last_modified_servers (
        customer_id_in in number,
        type_label_in in varchar2,
        quantity_in in number
    ) is
        -- find the servers that aren't currently in slots
        cursor servers(cid_in in number, quant_in in number) is
            select    server_id
            from    (
                        select    rownum row_number,
                                server_id
                        from    (
                                    select    rs.id server_iD
                                    from    rhnServer rs
                                    where    1=1
                                        and rs.org_id = cid_in
                                        and not exists (
                                            select    1
                                            from    rhnServerGroup sg,
                                                    rhnServerGroupMembers rsgm
                                            where    rsgm.server_id = rs.id
                                                and rsgm.server_group_id = sg.id
                                                and sg.group_type is not null
                                        )
                                        and not exists (
                                            select 1
                                            from rhnVirtualInstance vi
                                            where vi.virtual_system_id =
                                                  rs.id
                                        )                                                                           order by modified desc
                                )
                    )
            where    row_number <= quant_in;
    begin
        for server in servers(customer_id_in, quantity_in) loop
            rhn_entitlements.entitle_server(server.server_id, type_label_in);
        end loop;
    end entitle_last_modified_servers;

    procedure subscribe_newest_servers (
        customer_id_in in number
    ) is
        -- find servers without base channels
        cursor servers(cid_in in number) is
            select    s.id
            from    rhnServer            s
            where    1=1
                and s.org_id = cid_in
                and not exists (
                        select 1
                        from    rhnChannel            c,
                                rhnServerChannel    sc
                        where    sc.server_id = s.id
                            and sc.channel_id = c.id
                            and c.parent_channel is null
                    )
                and not exists (
                        select 1
                        from rhnVirtualInstance vi
                        where vi.virtual_system_id = s.id
                    )                        
            order by s.modified desc;
        channel_id number;
    begin
        for server in servers(customer_id_in) loop
            channel_id := rhn_channel.guess_server_base(server.id);
            if channel_id is not null then
                begin
                    rhn_channel.subscribe_server(server.id, channel_id);
                    commit;
                -- exception is really channel_family_no_subscriptions
                exception
                    when others then
                        null;
                end;
            end if;
        end loop;
    end subscribe_newest_servers;
end rhn_entitlements;
/
show errors

 0707010000064B000081B400000000000000000000000167AE111400000807000000000000000000000000000000000000006600000000susemanager-schema/upgrade/spacewalk-schema-1.2-to-susemanager-schema-1.2/302-rhnServerFveCapable.sql --
-- Copyright (c) 2008--2011 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--
-- A view to list systems that fve capable but that are not actually using
--    and fve entitlement
create or replace view 
rhnServerFveCapable (
 server_id,
 server_org_id,
 channel_family_id,
 current_members,
 max_members,
 channel_family_name
)
as
select  S.id as server_id,
        S.org_id as server_org_id,
        cf.id as channel_family_id,
        pcf.FVE_CURRENT_MEMBERS as current_members,
        pcf.FVE_MAX_MEMBERS as max_members,
        cf.name as channel_family_name
from
     RhnVirtualInstance vi
     inner join rhnServer s on vi.virtual_system_id = s.id
     inner join rhnServerChannel sc on sc.server_id = s.id
     inner join rhnChannelFamilyMembers cfm on cfm.channel_id = sc.channel_id
     inner join rhnChannelFamily cf on cf.id = cfm.channel_family_id
     inner join rhnPrivateChannelFamily pcf on pcf.channel_family_id  = cf.id and pcf.org_id = s.org_id
where sc.is_fve = 'N'
     AND (vi.host_system_id is null OR
     not exists (
          select sg.id 
            from rhnServerGroupMembers sgm
                 inner join rhnServerGroup sg on sgm.server_group_id = sg.id
                 inner join rhnServerGroupType sgt on sgt.id = sg.group_type
                 inner join rhnServer s2 on s2.id = sgm.server_id
             where
                 s2.id = vi.host_system_id
                 and sgt.label in ('virtualization_host' ,'virtualization_host_platform') )
      );

 0707010000064C000081B400000000000000000000000167AE111400000213000000000000000000000000000000000000006600000000susemanager-schema/upgrade/spacewalk-schema-1.2-to-susemanager-schema-1.2/303-suseRoleSUSEManager.sql --
-- Copyright (c) 2011 Novell
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
--

update rhnUserGroupType set name = 'SUSE Manager Administrator' where label = 'satellite_admin' ;

 0707010000064D000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000004800000000susemanager-schema/upgrade/spacewalk-schema-1.3-to-spacewalk-schema-1.4   0707010000064E000081B400000000000000000000000167AE1114000002BB000000000000000000000000000000000000007E00000000susemanager-schema/upgrade/spacewalk-schema-1.3-to-spacewalk-schema-1.4/001-rhnUserGroupMembers-rhn_ugm_applicant_fix_fun.sql 
create or replace function rhn_ugm_applicant_fix_fun() returns trigger
as
$$
declare
        group_type_val    NUMERIC;
        group_label_val   rhnUserGroupType.label%TYPE;
begin
        SELECT group_type INTO group_type_val
          FROM rhnUserGroup
         WHERE id = old.user_group_id;

        IF group_type_val IS NOT NULL
        THEN
            SELECT label INTO group_label_val
              FROM rhnUserGroupType
             WHERE id = group_type_val;

            IF group_label_val = 'org_applicant'
            THEN
                UPDATE web_contact SET password = old_password WHERE id = old.user_id;
            END IF;
        END IF;
	return new;
end;
$$ LANGUAGE PLPGSQL;

 0707010000064F000081B400000000000000000000000167AE111400000080000000000000000000000000000000000000006D00000000susemanager-schema/upgrade/spacewalk-schema-1.3-to-spacewalk-schema-1.4/002-rhnActionErrataUpdate-unique.sql  
drop index rhn_act_eu_aid_eid_idx;
create unique index rhn_act_eu_aid_eid_uq on rhnActionErrataUpdate (action_id, errata_id);

07070100000650000081B400000000000000000000000167AE111400000026000000000000000000000000000000000000006F00000000susemanager-schema/upgrade/spacewalk-schema-1.3-to-spacewalk-schema-1.4/003-web_customer_notification_drop.sql    drop table web_customer_notification;
  07070100000651000081B400000000000000000000000167AE11140000001F000000000000000000000000000000000000006800000000susemanager-schema/upgrade/spacewalk-schema-1.3-to-spacewalk-schema-1.4/004-rhn_sat_node_probe_drop.sql   drop table rhn_sat_node_probe;
 07070100000652000081B400000000000000000000000167AE111400000022000000000000000000000000000000000000006800000000susemanager-schema/upgrade/spacewalk-schema-1.3-to-spacewalk-schema-1.4/005-web_cust_notif_seq_drop.sql   drop sequence web_cust_notif_seq;
  07070100000653000081B400000000000000000000000167AE111400000459000000000000000000000000000000000000007300000000susemanager-schema/upgrade/spacewalk-schema-1.3-to-spacewalk-schema-1.4/007-rhn_ks_session_history_trigger_fun.sql    
create or replace function rhn_ks_session_history_trigger_fun() returns trigger
as
$$
begin
        if tg_op ='INSERT' then
                insert into rhnKickstartSessionHistory (
                                id, kickstart_session_id, action_id, state_id
                        ) values (
                                nextval('rhn_ks_sessionhist_id_seq'),
                                new.id,
                                new.action_id,
                                new.state_id
                        );
        end if;
        if tg_op ='UPDATE' then
          if new.state_id is distinct from old.state_id then
                insert into rhnKickstartSessionHistory (
                                id, kickstart_session_id, action_id, state_id
                        ) values (
                                nextval('rhn_ks_sessionhist_id_seq'),
                                new.id,
                                new.action_id,
                                new.state_id
                        );
          end if;
        end if;
        return new;
end;
$$ language plpgsql;

   07070100000654000081B400000000000000000000000167AE111400000040000000000000000000000000000000000000006200000000susemanager-schema/upgrade/spacewalk-schema-1.3-to-spacewalk-schema-1.4/008-rhnVirtualization.sql 
CREATE INDEX rhn_vi_uuid_idx
    ON rhnVirtualInstance (uuid);
07070100000655000081B400000000000000000000000167AE111400000022000000000000000000000000000000000000006600000000susemanager-schema/upgrade/spacewalk-schema-1.3-to-spacewalk-schema-1.4/009-rhnBlacklistObsoletes.sql drop table rhnBlacklistObsoletes;
  07070100000656000081B400000000000000000000000167AE111400000276000000000000000000000000000000000000006400000000susemanager-schema/upgrade/spacewalk-schema-1.3-to-spacewalk-schema-1.4/011-get_hw_info_as_clob.sql   
create or replace function get_hw_info_as_clob(
	sid in rhnserver.id%TYPE,
	separator in varchar
)
returns text
as
$$
declare
	ret text;
	rec record;
begin
	for rec in (
		select m
		from (
			select 1 n, sum(nrcpu) || ' CPUs' m
			from rhncpu where rhncpu.server_id = sid
			union all
			select 2, name||' '||coalesce(ip_addr,'')||'/'||coalesce(netmask,'')||' '||hw_addr val
			from rhnservernetinterface
			where rhnservernetinterface.server_id = sid
			) X
		order by n, m
		) loop
		if ret is null then
			ret := rec.m;
		else
			ret := ret || separator || rec.m;
		end if;
	end loop;
	return ret;
end;
$$ language plpgsql;

  07070100000657000081B400000000000000000000000167AE1114000001D2000000000000000000000000000000000000007000000000susemanager-schema/upgrade/spacewalk-schema-1.3-to-spacewalk-schema-1.4/012-rhn_errata_package_mod_trig_fun.sql   
create or replace function rhn_errata_package_mod_trig_fun() returns trigger
as
$$
begin
        if tg_op='INSERT' or tg_op='UPDATE' then
                new.modified := current_timestamp;
	        return new;
        end if;
        if tg_op='DELETE' then
                update rhnErrata
                set last_modified = current_timestamp
                where rhnErrata.id in ( old.errata_id );
	        return old;
        end if;
end;
$$ language plpgsql;

  07070100000658000081B400000000000000000000000167AE1114000002C5000000000000000000000000000000000000006000000000susemanager-schema/upgrade/spacewalk-schema-1.3-to-spacewalk-schema-1.4/013-rhn_sg_del_trig.sql   
create or replace function rhn_sg_del_trig_fun() returns trigger
as
$$
declare
        snapshot_curs_id	numeric;
begin
	for snapshot_curs_id in
                select  snapshot_id
                from    rhnSnapshotServerGroup
                where   server_group_id = old.id
                order by snapshot_id
	loop
		update rhnSnapshot
                        set invalid = lookup_snapshot_invalid_reason('sg_removed')
                        where id = snapshot_curs_id;
                delete from rhnSnapshotServerGroup
                        where snapshot_id = snapshot_curs_id
                                and server_group_id = old.id;
		
	end loop;

	return old;
 end;
 $$
 language plpgsql;

   07070100000659000081B400000000000000000000000167AE1114000032B6000000000000000000000000000000000000005A00000000susemanager-schema/upgrade/spacewalk-schema-1.3-to-spacewalk-schema-1.4/016-rhnErrata.sql --
-- Copyright (c) 2010 Novell, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
--
drop view IF EXISTS rhnVisServerGroupOverviewLite;
drop view IF EXISTS rhnServerOverview;
drop view IF EXISTS rhnServerErrataTypeView;
drop view IF EXISTS rhnServerGroupOVLiteHelper;
drop view IF EXISTS rhnServerOutdatedPackages;
drop view IF EXISTS rhnServerGroupOverview;
drop view IF EXISTS rhnServerNeededPackageView;
drop view IF EXISTS rhnVisServerGroupOverview;

ALTER TABLE rhnErrata ALTER advisory_name type varchar(100);
ALTER TABLE rhnErrata ALTER advisory type varchar(100);
ALTER TABLE rhnErrata ADD    errata_from varchar(127);

CREATE OR REPLACE VIEW rhnServerErrataTypeView
(
	server_id,
	errata_id,
	errata_type
)
AS
SELECT
	SNEC.server_id,
	SNEC.errata_id,
	E.advisory_type
FROM    rhnErrata E,
		rhnServerNeededErrataCache SNEC
WHERE   E.id = SNEC.errata_id
GROUP BY SNEC.server_id, SNEC.errata_id, E.advisory_type
;

create or replace view
rhnServerGroupOVLiteHelper as
select	sgm.server_group_id						as server_group_id,
		e.advisory_type							as advisory_type
from	rhnErrata								e,
		rhnServerNeededPackageCache				snpc,
		rhnServerGroupMembers					sgm
where   sgm.server_id = snpc.server_id
	and snpc.errata_id = e.id
;

CREATE OR REPLACE VIEW
rhnServerOutdatedPackages
(
    server_id,
    package_name_id,
    package_evr_id,
    package_nvre,
    errata_id,
    errata_advisory
)
AS
SELECT DISTINCT SNPC.server_id,
       P.name_id,
       P.evr_id,
       PN.name || '-' || evr_t_as_vre_simple( PE.evr ),
       E.id,
       E.advisory
  FROM rhnPackageName PN,
       rhnPackageEVR PE,
       rhnPackage P,
       rhnServerNeededPackageCache SNPC
         left outer join
        rhnErrata E
          on SNPC.errata_id = E.id
 WHERE SNPC.package_id = P.id
   AND P.name_id = PN.id
   AND P.evr_id = PE.id;

CREATE OR REPLACE VIEW rhnServerGroupOverview (
         ORG_ID, SECURITY_ERRATA, BUG_ERRATA, ENHANCEMENT_ERRATA, GROUP_ID, GROUP_NAME, GROUP_ADMINS, SERVER_COUNT, NOTE_COUNT, MODIFIED, MAX_MEMBERS
)
AS
  SELECT SG.org_id,
         (SELECT COUNT(distinct E.id)
            FROM rhnErrata E,
                 rhnServerNeededPackageCache SNPC,
                 rhnServerGroupMembers SGM
           WHERE E.advisory_type = 'Security Advisory'
                 and snpc.errata_id = e.id
                 and snpc.server_id = sgm.server_id
                 and sgm.server_group_id = sg.id
                 AND EXISTS ( SELECT 1
                              FROM rhnServerFeaturesView SFV
                              WHERE SFV.server_id = SGM.server_id
                                    AND SFV.label = 'ftr_system_grouping')),
         (SELECT COUNT(distinct E.id)
            FROM rhnErrata E,
                 rhnServerNeededPackageCache SNPC,
                 rhnServerGroupMembers SGM
           WHERE E.advisory_type = 'Bug Fix Advisory'
                 and snpc.errata_id = e.id
                 and snpc.server_id = sgm.server_id
                 and sgm.server_group_id = sg.id
                 AND EXISTS ( SELECT 1
                              FROM rhnServerFeaturesView SFV
                              WHERE SFV.server_id = SGM.server_id
                                    AND SFV.label = 'ftr_system_grouping')),
         (SELECT COUNT(distinct E.id)
            FROM rhnErrata E,
                 rhnServerNeededPackageCache SNPC,
                 rhnServerGroupMembers SGM
           WHERE E.advisory_type = 'Product Enhancement Advisory'
                 and snpc.errata_id = e.id
                 and snpc.server_id = sgm.server_id
                 and sgm.server_group_id = sg.id
                 AND EXISTS ( SELECT 1
                              FROM rhnServerFeaturesView SFV
                              WHERE SFV.server_id = SGM.server_id
                                    AND SFV.label = 'ftr_system_grouping')),
         SG.id, SG.name,
         (SELECT COUNT(*) FROM rhnUserManagedServerGroups UMSG WHERE UMSG.server_group_id = SG.id),
         (SELECT COUNT(*) FROM rhnServerGroupMembers SGM WHERE SGM.server_group_id = SG.id
                 AND EXISTS ( SELECT 1
                              FROM rhnServerFeaturesView SFV
                              WHERE SFV.server_id = SGM.server_id
                                    AND SFV.label = 'ftr_system_grouping')),
         cast(0 as bigint), CURRENT_TIMESTAMP, MAX_MEMBERS
    FROM rhnServerGroup SG;

CREATE OR REPLACE VIEW
rhnServerNeededPackageView
(
    org_id,
    server_id,
    errata_id,
    package_id,
    package_name_id
)
AS
SELECT   S.org_id,
         S.id,
	  (SELECT EP.errata_id
	     FROM rhnErrataPackage EP,
	          rhnChannelErrata CE,
		  rhnServerChannel SC
	    WHERE SC.server_id = S.id
	      AND SC.channel_id = CE.channel_id
	      AND CE.errata_id = EP.errata_id
	      AND EP.package_id = P.id
	    LIMIT 1),
	 P.id,
	 P.name_id
FROM
	 rhnPackage P,
	 rhnServerPackageArchCompat SPAC,
	 rhnPackageEVR P_EVR,
	 rhnPackageEVR SP_EVR,
	 rhnServerPackage SP,
	 rhnChannelPackage CP,
	 rhnServerChannel SC,
         rhnServer S
WHERE
		 SC.server_id = S.id
  AND  	 SC.channel_id = CP.channel_id
  AND    CP.package_id = P.id
  AND    p.package_arch_id = spac.package_arch_id
  AND    spac.server_arch_id = s.server_arch_id
  AND    SP_EVR.id = SP.evr_id
  AND    P_EVR.id = P.evr_id
  AND    SP.server_id = S.id
  AND    SP.name_id = P.name_id
  AND    SP.evr_id != P.evr_id
  AND    SP_EVR.evr < P_EVR.evr
  AND    SP_EVR.evr = (SELECT MAX(PE.evr) FROM rhnServerPackage SP2, rhnPackageEvr PE WHERE PE.id = SP2.evr_id AND SP2.server_id = SP.server_id AND SP2.name_id = SP.name_id)
;

CREATE OR REPLACE VIEW rhnVisServerGroupOverview (
         ORG_ID, SECURITY_ERRATA, BUG_ERRATA, ENHANCEMENT_ERRATA, GROUP_ID, GROUP_NAME, GROUP_ADMINS, SERVER_COUNT, NOTE_COUNT, MODIFIED, MAX_MEMBERS
)
AS
  SELECT SG.org_id,
         (SELECT COUNT(E.id)
	    FROM rhnErrata E
	   WHERE E.advisory_type = 'Security Advisory'
	     AND EXISTS (SELECT 1 FROM rhnServerNeededPackageCache SNEC, rhnServerGroupMembers SGM
	                         WHERE SGM.server_id = SNEC.server_id
				   AND SNEC.errata_id = E.id
				   AND SGM.server_group_id = SG.id)),
         (SELECT COUNT(E.id)
	    FROM rhnErrata E
	   WHERE E.advisory_type = 'Bug Fix Advisory'
	     AND EXISTS (SELECT 1 FROM rhnServerNeededPackageCache SNEC, rhnServerGroupMembers SGM
	                         WHERE SGM.server_id = SNEC.server_id
				   AND SNEC.errata_id = E.id
				   AND SGM.server_group_id = SG.id)),
         (SELECT COUNT(E.id)
	    FROM rhnErrata E
	   WHERE E.advisory_type = 'Product Enhancement Advisory'
	     AND EXISTS (SELECT 1 FROM rhnServerNeededPackageCache SNEC, rhnServerGroupMembers SGM
	                         WHERE SGM.server_id = SNEC.server_id
				   AND SNEC.errata_id = E.id
				   AND SGM.server_group_id = SG.id)),
	 SG.id, SG.name,
	 (SELECT COUNT(*) FROM rhnUserManagedServerGroups UMSG WHERE UMSG.server_group_id = SG.id),
	 (SELECT COUNT(*) FROM rhnServerGroupMembers SGM WHERE SGM.server_group_id = SG.id),
	 cast(0 as bigint), current_timestamp, MAX_MEMBERS
    FROM rhnVisibleServerGroup SG;

create or replace view
rhnServerOverview
(
    org_id,
    server_id,
    server_name,
    note_count,
    modified,
    server_admins,
    group_count,
    channel_id,
    channel_labels,
    history_count,
    security_errata,
    bug_errata,
    enhancement_errata,
    outdated_packages,
    config_files_with_differences,
    last_checkin_days_ago,
    last_checkin,
    pending_updates,
    os,
    release,
    server_arch_name,
    locked
)
as
select
    s.org_id, s.id, s.name, 0, s.modified,
    ( select count(user_id) from rhnUserServerPerms ap
      where server_id = s.id ),
    ( select count(server_group_id) from rhnVisibleServerGroupMembers
      where server_id = s.id ),
    ( select C.id
        from rhnChannel C,
         rhnServerChannel SC
       where SC.server_id = S.id
         and SC.channel_id = C.id
     and C.parent_channel IS NULL),
    coalesce(( select C.name
        from rhnChannel C,
         rhnServerChannel SC
       where SC.server_id = S.id
         and SC.channel_id = C.id
     and C.parent_channel IS NULL), '(none)'),
    ( select count(id) from rhnServerHistory
      where
            server_id = S.id),
    ( select count(*) from rhnServerErrataTypeView setv
      where
            setv.server_id = s.id
        and setv.errata_type = 'Security Advisory'),
    ( select count(*) from rhnServerErrataTypeView setv
      where
            setv.server_id = s.id
        and setv.errata_type = 'Bug Fix Advisory'),
    ( select count(*) from rhnServerErrataTypeView setv
      where
            setv.server_id = s.id
        and setv.errata_type = 'Product Enhancement Advisory'),
    ( select count(distinct p.name_id) from rhnPackage p, rhnServerNeededPackageCache snpc
      where
             snpc.server_id = S.id
     and p.id = snpc.package_id
     ),
    ( select count(*)
        from rhnActionConfigRevision ACR
             INNER JOIN rhnActionConfigRevisionResult ACRR on ACR.id = ACRR.action_config_revision_id
       where ACR.server_id = S.id
         and ACR.action_id = (
              select MAX(rA.id)
                from rhnAction rA
                     INNER JOIN rhnServerAction rSA on rSA.action_id = rA.id
                     INNER JOIN rhnActionStatus rAS on rAS.id = rSA.status
                     INNER JOIN rhnActionType rAT on rAT.id = rA.action_type
               where rSA.server_id = S.id
                 and rAS.name in ('Completed', 'Failed')
                 and rAT.label = 'configfiles.diff'
         )
         and ACR.failure_id is null
         and ACRR.result is not null
        ),
    ( select date_diff_in_days(checkin, current_timestamp) from rhnServerInfo where server_id = S.id ),
    ( select TO_CHAR(checkin, 'YYYY-MM-DD HH24:MI:SS') from rhnServerInfo where server_id = S.id ),
    ( select count(1)·
        from rhnServerAction
       where server_id = S.id
         and status in (0, 1)),
    os,
    release,
    ( select name from rhnServerArch where id = s.server_arch_id),
    coalesce((select 1 from rhnServerLock SL WHERE SL.server_id = S.id), 0)
from
    rhnServer S
;

create or replace view
rhnVisServerGroupOverviewLite as
select  sg.org_id                                       as org_id,
                case when exists (
                        select  1
                        from    rhnServerGroupOVLiteHelper
                        where   server_group_id = sg.id
                                and advisory_type = 'Security Advisory'
                        )
                        then 1
                        else 0
                        end                                             as security_errata,
                case when exists (
                        select  1
                        from    rhnServerGroupOVLiteHelper
                        where   server_group_id = sg.id
                                and advisory_type = 'Bug Fix Advisory'
                        )
                        then 1
                        else 0
                        end                                             as bug_errata,
                case when exists (
                        select  1
                        from    rhnServerGroupOVLiteHelper
                        where   server_group_id = sg.id
                                and advisory_type = 'Product Enhancement Advisory'
                        )
                        then 1
                        else 0
                        end                                             as enhancement_errata,
                sg.id                                           as group_id,
                sg.name                                         as group_name,
                (       select  count(*)
                        from    rhnUserManagedServerGroups      umsg
                        where   umsg.server_group_id = sg.id
                )                                                       as group_admins,
                (       select  count(*)
                        from    rhnServerGroupMembers           sgm
                        where   sgm.server_group_id = sg.id
                )                                                       as server_count,
                0                                                       as note_count,
                current_timestamp                                       as modified,
                max_members                                     as max_members
from    rhnVisibleServerGroup           sg
;
  0707010000065A000081B400000000000000000000000167AE11140000026A000000000000000000000000000000000000005D00000000susemanager-schema/upgrade/spacewalk-schema-1.3-to-spacewalk-schema-1.4/017-rhnErrataTmp.sql  --
-- Copyright (c) 2010 Novell, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
--
ALTER TABLE rhnErrataTmp ALTER advisory_name type varchar(100);
ALTER TABLE rhnErrataTmp ALTER advisory type varchar(100);
ALTER TABLE rhnErrataTmp ADD    errata_from varchar(127);
  0707010000065B000081B400000000000000000000000167AE1114000001E9000000000000000000000000000000000000006100000000susemanager-schema/upgrade/spacewalk-schema-1.3-to-spacewalk-schema-1.4/018-rhnErrataBuglist.sql  --
-- Copyright (c) 2010 Novell, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
--
ALTER TABLE rhnErrataBuglist add href VARCHAR(255);
   0707010000065C000081B400000000000000000000000167AE111400000039000000000000000000000000000000000000006400000000susemanager-schema/upgrade/spacewalk-schema-1.3-to-spacewalk-schema-1.4/019-rhnErrataBuglistTmp.sql   
alter table rhnErrataBuglistTmp add href varchar(255);

   0707010000065D000081B400000000000000000000000167AE11140000007A000000000000000000000000000000000000006100000000susemanager-schema/upgrade/spacewalk-schema-1.3-to-spacewalk-schema-1.4/021-rhnKsInstallType.sql  insert into rhnKSInstallType (id,label,name) VALUES (sequence_nextval('rhn_ksinstalltype_id_seq'), 'suse', 'SUSE Linux');
  0707010000065E000081B400000000000000000000000167AE11140000FC06000000000000000000000000000000000000006100000000susemanager-schema/upgrade/spacewalk-schema-1.3-to-spacewalk-schema-1.4/022-rhn_entitlements.sql  
-- Note: this file is not a full equivalent of the Oracle sources.
-- Neither the flex stuff nor the update_family_countsYN was fully migrated.
-- Migrated functions or code paths:
--
-- can_entitle_server
-- entitle_server
-- code path of simple rhn-satellite-activate
--
--
-- Copyright (c) 2008--2011 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

-- create schema rhn_entitlements;

-- setup search_path so that these functions are created in appropriate schema.
update pg_settings set setting = 'rhn_entitlements,' || setting where name = 'search_path';

   create or replace function find_compatible_sg (
      server_id_in in numeric,
      type_label_in in varchar
   )
   returns numeric
as $$
    declare
      servergroups cursor for
         select sg.id
           from rhnServerGroupType             sgt,
                rhnServerGroup                 sg,
                rhnServer                     s,
                rhnServerServerGroupArchCompat ssgac
          where s.id = server_id_in
            and s.org_id = sg.org_id
            and sgt.label = type_label_in
            and sg.group_type = sgt.id
            and ssgac.server_group_type = sgt.id
            and ssgac.server_arch_id = s.server_arch_id
            and not exists (
                     select 1
                      from rhnServerGroupMembers sgm
                     where sgm.server_group_id = sg.id
                       and sgm.server_id = s.id);


   begin
      for servergroup in servergroups loop
         return servergroup.id;
      end loop;

      --no servergroup found
      return NULL;
   end$$
language plpgsql;

    -- *******************************************************************
    -- PROCEDURE: remove_org_entitlements
    --
    -- Removes both system entitlements and channel subscriptions
    -- that are currently assigned to an org and re-assigns to the
    -- master org (org_id = 1).
    --
    -- When we call this we expect everything to already be unentitled
    -- which shoul be handled by delete_org.
    --
    -- Called by: delete_org
    -- *******************************************************************
    create or replace function remove_org_entitlements (
        org_id_in numeric
    ) returns void
as $$
    declare
        system_ents cursor for
        select sg.id, sg.max_members, sg.group_type
        from rhnServerGroup sg
        where group_type is not null
          and org_id = org_id_in;

        channel_subs cursor for
        select pcf.channel_family_id, pcf.max_members
        from rhnChannelFamily cf,
             rhnPrivateChannelFamily pcf
        where pcf.org_id = org_id_in
          and pcf.channel_family_id = cf.id
          and cf.org_id is null;

    begin

        for system_ent in system_ents loop
            update rhnServerGroup
            set max_members = max_members + system_ent.max_members
            where org_id = 1
              and group_type = system_ent.group_type;
        end loop;

        update rhnServerGroup
        set max_members = 0
        where org_id = org_id_in;

        for channel_sub in channel_subs loop
            update rhnPrivateChannelFamily
            set max_members = max_members + channel_sub.max_members
            where org_id = 1
              and channel_family_id = channel_sub.channel_family_id;
        end loop;

        update rhnPrivateChannelFamily
        set max_members = 0
        where org_id = org_id_in;

    end$$
language plpgsql;

    create or replace function entitlement_grants_service (
        entitlement_in in varchar,
        service_level_in in varchar
    ) returns numeric
as $$
    begin
        if service_level_in = 'provisioning' then
            if entitlement_in = 'provisioning_entitled' then
                return 1;
            else
                return 0;
            end if;
        elsif service_level_in = 'management' then
            if entitlement_in = 'enterprise_entitled' then
                return 1;
            else
                return 0;
            end if;
        elsif service_level_in = 'monitoring' then
            if entitlement_in = 'monitoring_entitled' then
                return 1;
            end if;
        elsif service_level_in = 'updates' then
            return 1;
        else
            return 0;
        end if;
    end$$
language plpgsql;

    create or replace function lookup_entitlement_group (
        org_id_in in numeric,
        type_label_in in varchar default 'sw_mgr_entitled'
    ) returns numeric
as $$
    declare
        server_groups cursor for
            select  sg.id               server_group_id
            from    rhnServerGroup      sg,
                    rhnServerGroupType  sgt
            where   sgt.label = type_label_in
                and sgt.id = sg.group_type
                and sg.org_id = org_id_in;
    begin
        for sg in server_groups loop
            return sg.server_group_id;
        end loop;
        return rhn_entitlements.create_entitlement_group(
                org_id_in,
                type_label_in
            );
    end$$
language plpgsql;

    create or replace function create_entitlement_group (
        org_id_in in numeric,
        type_label_in in varchar default 'sw_mgr_entitled'
    ) returns numeric
as $$
    declare
        sg_id_val numeric;
    begin
        select  nextval('rhn_server_group_id_seq')
        into    sg_id_val;

        insert into rhnServerGroup (
                id, name, description, max_members, current_members,
                group_type, org_id
            ) (
                select  sg_id_val, sgt.label, sgt.label,
                        0, 0, sgt.id, org_id_in
                from    rhnServerGroupType sgt
                where   sgt.label = type_label_in
            );

        return sg_id_val;
    end$$
language plpgsql;

   create or replace function can_entitle_server (
      server_id_in   in numeric,
      type_label_in  in varchar
   )
   returns numeric
as $$
    declare
      addon_servergroups cursor (base_label_in varchar,
                                 addon_label_in varchar) for
         select
            addon_id
         from
            rhnSGTypeBaseAddonCompat
         where base_id = lookup_sg_type (base_label_in)
           and addon_id = lookup_sg_type (addon_label_in);

      previous_ent        varchar[];
      is_base_in          char   := 'N';
      is_base_current     char   := 'N';
      i                   numeric := 0;
      sgid                numeric := 0;

   begin

      previous_ent := rhn_entitlements.get_server_entitlement(server_id_in);

      select distinct is_base
      into is_base_in
      from rhnServerGroupType
      where label = type_label_in;

      if array_upper(previous_ent, 1) is null or array_upper(previous_ent, 1) = 0 then
         if is_base_in = 'Y' then
            sgid := rhn_entitlements.find_compatible_sg (server_id_in, type_label_in);
            if sgid is not null then
              -- rhn_server.insert_into_servergroup (server_id_in, sgid);
              return 1;
            else
              -- rhn_exception.raise_exception ('invalid_base_entitlement');
              return 0;
            end if;
         else
            -- rhn_exception.raise_exception ('invalid_base_entitlement');
            return 0;
         end if;

      -- there are previous ents, first make sure we're not trying to entitle a base ent
      elsif is_base_in = 'Y' then
         -- rhn_exception.raise_exception ('invalid_addon_entitlement');
         return 0;

      -- it must be an addon, so proceed with the entitlement
      else

         -- find the servers base ent
         is_base_current := 'N';
         i := 0;
         while is_base_current = 'N' and i < array_upper(previous_ent, 1)
         loop
            i := i + 1;
            select is_base
            into is_base_current
            from rhnServerGroupType
            where label = previous_ent[i];
         end loop;

         -- never found a base ent, that would be strange
         if is_base_current  = 'N' then
            -- rhn_exception.raise_exception ('invalid_base_entitlement');
            return 0;
         end if;

         -- this for loop verifies the validity of the addon path
         for addon_servergroup in addon_servergroups  (previous_ent[i], type_label_in) loop
            -- find an appropriate sgid for the addon and entitle the server
            sgid := rhn_entitlements.find_compatible_sg (server_id_in, type_label_in);
            if sgid is not null then
               -- rhn_server.insert_into_servergroup (server_id_in, sgid);
               return 1;
            else
               -- rhn_exception.raise_exception ('invalid_addon_entitlement');
               return 0;
            end if;
         end loop;

      end if;

      return 0;

   end$$
language plpgsql;

   create or replace function can_switch_base (
      server_id_in   in    integer,
      type_label_in  in    varchar
   )
   returns numeric
as $$
   declare
      type_label_in_is_base   char(1);
      sgid                    numeric;

   begin

       select is_base into type_label_in_is_base
       from rhnServerGroupType
       where label = type_label_in;

       if not found then
          perform rhn_exception.raise_exception ( 'invalid_entitlement' );
       end if;

      if type_label_in_is_base = 'N' then
         perform rhn_exception.raise_exception ( 'invalid_entitlement' );
      else
         sgid := rhn_entitlements.find_compatible_sg ( server_id_in,
                                                       type_label_in );
         if sgid is not null then
           return 1;
         else
           return 0;
         end if;
      end if;

   end$$
language plpgsql;

    create or replace function entitle_server (
        server_id_in in numeric,
        type_label_in in varchar default 'sw_mgr_entitled'
    ) returns void
as $$
    declare
      sgid  numeric := 0;
      is_virt numeric := 0;

    begin

      select 1 into is_virt
        from rhnServerEntitlementView
        where server_id = server_id_in
          and label in ('virtualization_host', 'virtualization_host_platform');

      if not found then
          is_virt := 0;
      end if;

      if is_virt = 0 and (type_label_in = 'virtualization_host' or
                          type_label_in = 'virtualization_host_platform') then

        is_virt := 1;
      end if;

      if rhn_entitlements.can_entitle_server(server_id_in,
                                             type_label_in) = 1 then
         sgid := rhn_entitlements.find_compatible_sg (server_id_in,
                                                      type_label_in);
         if sgid is not null then
            insert into rhnServerHistory ( id, server_id, summary, details )
            values ( nextval('rhn_event_id_seq'), server_id_in,
                     'added system entitlement ',
                      case type_label_in
                       when 'enterprise_entitled' then 'Management'
                       when 'sw_mgr_entitled' then 'Update'
                       when 'provisioning_entitled' then 'Provisioning'
                       when 'monitoring_entitled' then 'Monitoring'
                       when 'virtualization_host' then 'Virtualization'
                       when 'virtualization_host_platform' then
                            'Virtualization Platform' end  );

            perform rhn_server.insert_into_servergroup (server_id_in, sgid);

            if is_virt = 1 then
              perform rhn_entitlements.repoll_virt_guest_entitlements(server_id_in);
            end if;

         else
            perform rhn_exception.raise_exception ('no_available_server_group');
         end if;
      else
         perform rhn_exception.raise_exception ('invalid_entitlement');
      end if;
   end$$
language plpgsql;

    create or replace function remove_server_entitlement (
        server_id_in in numeric,
        type_label_in in varchar default 'sw_mgr_entitled',
        repoll_virt_guests in numeric default 1
    ) returns void
as $$
    declare
      group_id numeric;
      type_is_base char;
      is_virt numeric := 0;
    begin
      -- would be nice if there were a virt attribute of entitlement types, not have to specify 2 different ones...
        select 1 into is_virt
          from rhnServerEntitlementView
          where server_id = server_id_in
            and label in ('virtualization_host', 'virtualization_host_platform');
        if not found then
            is_virt := 0;
        end if;

        select  sg.id, sgt.is_base
        into group_id, type_is_base
        from    rhnServerGroupType sgt,
            rhnServerGroup sg,
                rhnServerGroupMembers sgm,
                rhnServer s
        where   s.id = server_id_in
            and s.id = sgm.server_id
            and sgm.server_group_id = sg.id
            and sg.org_id = s.org_id
            and sgt.label = type_label_in
            and sgt.id = sg.group_type;

        if not found then
          perform rhn_exception.raise_exception('invalid_server_group_member');
        end if;

      if ( type_is_base = 'Y' ) then
         -- unentitle_server should handle everything, don't really need to do anything else special here
         perform rhn_entitlements.unentitle_server ( server_id_in );
      else

         insert into rhnServerHistory ( id, server_id, summary, details )
         values ( nextval('rhn_event_id_seq'), server_id_in,
                  'removed system entitlement ',
                   case type_label_in
                    when 'enterprise_entitled' then 'Management'
                    when 'sw_mgr_entitled' then 'Update'
                    when 'provisioning_entitled' then 'Provisioning'
                    when 'monitoring_entitled' then 'Monitoring'
                    when 'virtualization_host' then 'Virtualization'
                    when 'virtualization_host_platform' then
                         'Virtualization Platforrm' end  );

         perform rhn_server.delete_from_servergroup(server_id_in, group_id);

         -- special case: clean up related monitoring data
         if type_label_in = 'monitoring_entitled' then
           DELETE
             FROM state_change
            WHERE o_id IN (SELECT probe_id::varchar
                             FROM rhn_check_probe
                            WHERE host_id = server_id_in);
           DELETE
             FROM time_series
            WHERE substring(o_id FROM position('-' IN o_id) + 1
                            FOR position('-' IN substring(o_id FROM position('-' IN o_id) + 1)) - 1)
              IN (SELECT probe_id::text
                    FROM rhn_check_probe
                   WHERE host_id = server_id_in);
           DELETE
             FROM rhn_probe
            WHERE recid IN (SELECT probe_id
                              FROM rhn_check_probe
                             WHERE host_id = server_id_in);
         end if;

         if is_virt = 1 and repoll_virt_guests = 1 then
           perform rhn_entitlements.repoll_virt_guest_entitlements(server_id_in);
         end if;
      end if;

    end$$
language plpgsql;

    create or replace function unentitle_server (
        server_id_in in numeric
    ) returns void
as $$
    declare
      servergroups cursor for
         select distinct sgt.label, sg.id server_group_id
         from  rhnServerGroupType sgt,
               rhnServerGroup sg,
               rhnServer s,
               rhnServerGroupMembers sgm
         where s.id = server_id_in
            and s.org_id = sg.org_id
            and sg.group_type = sgt.id
            and sgm.server_group_id = sg.id
            and sgm.server_id = s.id;

     is_virt numeric := 0;

   begin

      select 1 into is_virt
        from rhnServerEntitlementView
        where server_id = server_id_in
         and label in ('virtualization_host', 'virtualization_host_platform');

      if not found then
          is_virt := 0;
      end if;

      for servergroup in servergroups loop

         insert into rhnServerHistory ( id, server_id, summary, details )
         values ( nextval('rhn_event_id_seq'), server_id_in,
                  'removed system entitlement ',
                   case servergroup.label
                    when 'enterprise_entitled' then 'Management'
                    when 'sw_mgr_entitled' then 'Update'
                    when 'provisioning_entitled' then 'Provisioning'
                    when 'monitoring_entitled' then 'Monitoring'
                    when 'virtualization_host' then 'Virtualization'
                    when 'virtualization_host_platform' then
                         'Virtualization Platform' end  );

         perform rhn_server.delete_from_servergroup(server_id_in,
                                            servergroup.server_group_id );
      end loop;

      if is_virt = 1 then
        perform rhn_entitlements.repoll_virt_guest_entitlements(server_id_in);
      end if;

   end$$
language plpgsql;


    -- *******************************************************************
    -- PROCEDURE: repoll_virt_guest_entitlements
    --
    --   Whenever we add/remove a virtualization_host* entitlement from
    --   a host, we can call this procedure to update what type of slots
    --   the guests are consuming.
    --
    --   If you're removing the entitlement, it's
    --   possible the guests will become unentitled if you don't have enough
    --   physical slots to cover them.
    --
    --   If you're adding the entitlement, you end up freeing up physical
    --   slots for other systems.
    --
    -- *******************************************************************
    create or replace function repoll_virt_guest_entitlements(
        server_id_in in numeric
    ) returns void
as $$
    declare
        -- All channel families associated with the guests of server_id_in
        families cursor for
            select distinct cfs.channel_family_id
            from
                rhnChannelFamilyServers cfs,
                rhnVirtualInstance vi
            where
                vi.host_system_id = server_id_in
                and vi.virtual_system_id = cfs.server_id;

        -- All of server group types associated with the guests of
        -- server_id_in
        group_types cursor for
            select distinct sg.group_type, sgt.label
            from
                rhnServerGroupType sgt,
                rhnServerGroup sg,
                rhnServerGroupMembers sgm,
                rhnVirtualInstance vi
            where
                vi.host_system_id = server_id_in
                and vi.virtual_system_id = sgm.server_id
                and sgm.server_group_id = sg.id
                and sg.group_type = sgt.id;

        -- Virtual servers from a certain family belonging to a specific
        -- host that are consuming physical channel slots over the limit.
        virt_servers_cfam cursor(family_id_in numeric, quantity_in numeric) for
                select vi.virtual_system_id
                from
                    rhnChannelFamilyMembers cfm,
                    rhnServerChannel sc,
                    rhnVirtualInstance vi
                where
                    vi.host_system_id = server_id_in
                    and vi.virtual_system_id = sc.server_id
                    and sc.channel_id = cfm.channel_id
                    and cfm.channel_family_id = family_id_in
                order by sc.modified desc
                limit quantity_in;

        -- Virtual servers from a certain family belonging to a specific
        -- host that are consuming physical system slots over the limit.
        virt_servers_sgt cursor(group_type_in numeric, quantity_in numeric) for
                select vi.virtual_system_id
                from
                    rhnServerGroup sg,
                    rhnServerGroupMembers sgm,
                    rhnVirtualInstance vi
                where
                    vi.host_system_id = server_id_in
                    and vi.virtual_system_id = sgm.server_id
                    and sgm.server_group_id = sg.id
                    and sg.group_type = group_type_in
                order by sgm.modified desc
                limit quantity_in;

        org_id_val numeric;
        max_members_val numeric;
        current_members_calc numeric;
        sg_id numeric;

    begin

        select org_id
        into org_id_val
        from rhnServer
        where id = server_id_in;

        -- deal w/ channel entitlements first ...
        for family in families loop
            -- get the current (physical) members of the family
            current_members_calc :=
                rhn_channel.channel_family_current_members(family.channel_family_id,
                                                           org_id_val); -- fixed transposed args

            -- get the max members of the family
            select max_members
            into max_members_val
            from rhnPrivateChannelFamily
            where channel_family_id = family.channel_family_id
            and org_id = org_id_val;

            if current_members_calc > max_members_val then
                -- A virtualization_host* ent must have been removed, so we'll
                -- unsubscribe guests from the host first.

                -- hm, i don't think max_members - current_members_calc yielding a negative number
                -- will work w/ rownum, swaping 'em in the body of this if...
                for virt_server in virt_servers_cfam(family.channel_family_id,
                                current_members_calc - max_members_val) loop

                    perform rhn_channel.unsubscribe_server_from_family(
                                virt_server.virtual_system_id,
                                family.channel_family_id);
                end loop;

                -- if we're still over the limit, which would be odd,
                -- just prune the group to max_members
                --
                -- er... wouldn't we actually have to refresh the values of
                -- current_members_calc and max_members_val to actually ever
                -- *skip this??
                if current_members_calc > max_members_val then
                    -- argh, transposed again?!
                    perform rhn_entitlements.set_family_count(org_id_val,
                                     family.channel_family_id,
                                     max_members_val);
                end if;

           end if;

            -- update current_members for the family.  This will set the value
            -- to reflect adding/removing the entitlement.
            --
            -- what's the difference of doing this vs the unavoidable set_family_count above?
            perform rhn_channel.update_family_counts(family.channel_family_id,
                                             org_id_val);
        end loop;

        for a_group_type in group_types loop
          -- get the current *physical* members of the system entitlement type for the org...
          --
          -- unlike channel families, it appears the standard rhnServerGroup.max_members represents
          -- *physical* slots, vs physical+virt ... boy that's confusing...

          select max_members, id
            into max_members_val, sg_id
            from rhnServerGroup
            where group_type = a_group_type.group_type
            and org_id = org_id_val;


      select count(sep.server_id) into current_members_calc
            from rhnServerEntitlementPhysical sep
           where sep.server_group_id = sg_id
             and sep.server_group_type_id = a_group_type.group_type;

          if current_members_calc > max_members_val then
            -- A virtualization_host* ent must have been removed, and we're over the limit, so unsubscribe guests
            for virt_server in virt_servers_sgt(a_group_type.group_type,
                                                current_members_calc - max_members_val) loop
              perform rhn_entitlements.remove_server_entitlement(virt_server.virtual_system_id, a_group_type.label);

              -- decrement current_members_calc, we'll use it to reset current_members for the group at the end...
              current_members_calc := current_members_calc - 1;
            end loop;

          end if;

          update rhnServerGroup set current_members = current_members_calc
           where org_id = org_id_val
             and group_type = a_group_type.group_type;

          -- I think that's all the house-keeping we have to do...
        end loop;

    end$$
language plpgsql;

    create or replace function get_server_entitlement (
        server_id_in in numeric
    ) returns varchar[]
as $$
    declare
        server_groups cursor for
            select  sgt.label
            from    rhnServerGroupType      sgt,
                    rhnServerGroup          sg,
                    rhnServerGroupMembers   sgm
            where   1=1
                and sgm.server_id = server_id_in
                and sg.id = sgm.server_group_id
                and sgt.id = sg.group_type
                and sgt.label in (
                    'sw_mgr_entitled','enterprise_entitled',
                    'provisioning_entitled', 'nonlinux_entitled',
                    'monitoring_entitled', 'virtualization_host',
                                        'virtualization_host_platform'
                    );

         ent_array varchar[];

    begin

      ent_array := '{}';

      for sg in server_groups loop
         ent_array := ent_array || sg.label;
      end loop;

      return ent_array;

    end$$
language plpgsql;

    -- this desperately needs to be table driven.
    create or replace function modify_org_service (
        org_id_in in numeric,
        service_label_in in varchar,
        enable_in in char
    ) returns void
as $$
    declare
        roles_to_process varchar[];
        roles cursor(role_label_in varchar) for
            select  label, id
            from    rhnUserGroupType
            where   label = role_label_in;
        org_roles cursor(role_label_in varchar) for
            select  1
            from    rhnUserGroup ug,
                    rhnUserGroupType ugt
            where   ugt.label = role_label_in
                and ug.org_id = org_id_in
                and ugt.id = ug.group_type;

        ents_to_process varchar[];
        ents cursor(ent_label_in varchar) for
            select  label, id
            from    rhnOrgEntitlementType
            where   label = ent_label_in;
        org_ents cursor(ent_label_in varchar) for
            select  1
            from    rhnOrgEntitlements oe,
                    rhnOrgEntitlementType oet
            where   oet.label = ent_label_in
                and oe.org_id = org_id_in
                and oet.id = oe.entitlement_id;
        create_row char(1);
    begin
        ents_to_process := '{}';
        roles_to_process := '{}';
        -- a bit kludgy, but only for 3.4 really.  Certainly no
        -- worse than the old code...
        if service_label_in = 'enterprise' or
           service_label_in = 'management' then
            ents_to_process := array_append(ents_to_process, 'sw_mgr_enterprise');

            roles_to_process := array_append(roles_to_process, 'org_admin');

            roles_to_process := array_append(roles_to_process, 'system_group_admin');

            roles_to_process := array_append(roles_to_process, 'activation_key_admin');

            roles_to_process := array_append(roles_to_process, 'org_applicant');
        elsif service_label_in = 'provisioning' then
            ents_to_process := array_append(ents_to_process, 'rhn_provisioning');

            roles_to_process := array_append(roles_to_process, 'system_group_admin');

            roles_to_process := array_append(roles_to_process, 'activation_key_admin');

            roles_to_process := array_append(roles_to_process, 'config_admin');
            -- another nasty special case...
            if enable_in = 'Y' then
                ents_to_process := array_append(ents_to_process, 'sw_mgr_enterprise');
            end if;
        elsif service_label_in = 'monitoring' then
            ents_to_process := array_append(ents_to_process, 'rhn_monitor');

            roles_to_process := array_append(roles_to_process, 'monitoring_admin');
        elsif service_label_in = 'virtualization' then
            ents_to_process := array_append(ents_to_process, 'rhn_virtualization');

            roles_to_process := array_append(roles_to_process, 'config_admin');
        elsif service_label_in = 'virtualization_platform' then
            ents_to_process := array_append(ents_to_process, 'rhn_virtualization_platform');
            roles_to_process := array_append(roles_to_process, 'config_admin');
    elsif service_label_in = 'nonlinux' then
            ents_to_process := array_append(ents_to_process, 'rhn_nonlinux');
            roles_to_process := array_append(roles_to_process, 'config_admin');
        end if;

        if enable_in = 'Y' then
            for i in 1..array_upper(ents_to_process, 1) loop
                for ent in ents(ents_to_process[i]) loop
                    create_row := 'Y';
                    for oe in org_ents(ent.label) loop
                        create_row := 'N';
                    end loop;
                    if create_row = 'Y' then
                        insert into rhnOrgEntitlements(org_id, entitlement_id)
                            values (org_id_in, ent.id);
                    end if;
                end loop;
            end loop;
            for i in 1..array_upper(roles_to_process, 1) loop
                for role in roles(roles_to_process[i]) loop
                    create_row := 'Y';
                    for o_r in org_roles(role.label) loop
                        create_row := 'N';
                    end loop;
                    if create_row = 'Y' then
                        insert into rhnUserGroup(
                                id, name, description, current_members,
                                group_type, org_id
                            ) (
                                select  nextval('rhn_user_group_id_seq'),
                                        ugt.name || 's',
                                        ugt.name || 's for Org ' ||
                                            o.name || ' ('|| o.id ||')',
                                        0, ugt.id, o.id
                                from    rhnUserGroupType ugt,
                                        web_customer o
                                where   o.id = org_id_in
                                    and ugt.id = role.id
                            );
                    end if;
                end loop;
            end loop;
        else
            for i in 1..coalesce(array_upper(ents_to_process, 1), 0) loop
                for ent in ents(ents_to_process[i]) loop
                    delete from rhnOrgEntitlements
                     where org_id = org_id_in
                       and entitlement_id = ent.id;
                end loop;
            end loop;
        end if;
    end$$
language plpgsql;

    create or replace function set_customer_enterprise (
        customer_id_in in numeric
    ) returns void
as $$
    begin
        perform rhn_entitlements.modify_org_service(customer_id_in, 'enterprise', 'Y');
    end$$
language plpgsql;

    create or replace function set_customer_provisioning (
        customer_id_in in numeric
    ) returns void
as $$
    begin
        perform rhn_entitlements.modify_org_service(customer_id_in, 'provisioning', 'Y');
    end$$
language plpgsql;

    create or replace function set_customer_monitoring (
        customer_id_in in numeric
    ) returns void
as $$
    begin
        perform rhn_entitlements.modify_org_service(customer_id_in, 'monitoring', 'Y');
    end$$
language plpgsql;

    create or replace function set_customer_nonlinux (
        customer_id_in in numeric
    ) returns void
as $$
    begin
        perform rhn_entitlements.modify_org_service(customer_id_in, 'nonlinux', 'Y');
    end$$
language plpgsql;

    create or replace function unset_customer_enterprise (
        customer_id_in in numeric
    ) returns void
as $$
    begin
        perform rhn_entitlements.modify_org_service(customer_id_in, 'enterprise', 'N');
    end$$
language plpgsql;

    create or replace function unset_customer_provisioning (
        customer_id_in in numeric
    ) returns void
as $$
    begin
        perform rhn_entitlements.modify_org_service(customer_id_in, 'provisioning', 'N');
    end$$
language plpgsql;

    create or replace function unset_customer_monitoring (
        customer_id_in in numeric
    ) returns void
as $$
    begin
        perform rhn_entitlements.modify_org_service(customer_id_in, 'monitoring', 'N');
    end$$
language plpgsql;

    create or replace function unset_customer_nonlinux (
        customer_id_in in numeric
    ) returns void
as $$
    begin
        perform rhn_entitlements.modify_org_service(customer_id_in, 'nonlinux', 'N');
    end$$
language plpgsql;

    -- *******************************************************************
    -- PROCEDURE: prune_group
    -- Unsubscribes servers consuming physical slots that over the org's
    --   limit.
    -- Called by: set_group_count, repoll_virt_guest_entitlements
    -- *******************************************************************
    create or replace function prune_group (
        group_id_in in numeric,
        type_in in char,
        quantity_in in numeric,
        update_family_countsYN in numeric default 1
    ) returns void
as $$
    declare
        ugrecord record;
        sgrecord record;
      type_is_base char;
    begin
        if type_in = 'U' then
            update      rhnUserGroup
                set     max_members = quantity_in
                where   id = group_id_in;

            for ugrecord in (
		    select  user_id, user_group_id, ugt.label
		    from    rhnUserGroupType    ugt,
			    rhnUserGroup        ug,
			    rhnUserGroupMembers ugm
		    where   1=1
			and ugm.user_group_id = group_id_in
			and ugm.user_id in (
				    select  user_id
				    from    rhnUserGroupMembers
				    where   user_group_id = group_id_in
				    order by modified asc
				    offset quantity_in
				)
			and ugm.user_group_id = ug.id
			and ug.group_type = ugt.id
	    ) loop
                perform rhn_user.remove_from_usergroup(ugrecord.user_id, ugrecord.user_group_id);
            end loop;
        elsif type_in = 'S' then
            update      rhnServerGroup
                set     max_members = quantity_in
                where   id = group_id_in;

            for sgrecord in (
		   select  server_id, server_group_id, sgt.id as group_type_id, sgt.label
		    from    rhnServerGroupType              sgt,
				    rhnServerGroup                  sg,
				    rhnServerGroupMembers   sgm
		    where   1=1
			    and sgm.server_group_id = group_id_in
			    and sgm.server_id in (
				    select  sep.server_id
				    from
					rhnServerEntitlementPhysical sep
				    where
					sep.server_group_id = group_id_in
				    order by sep.modified asc
				    offset quantity_in
				)
			    and sgm.server_group_id = sg.id
			    and sg.group_type = sgt.id
	    ) loop
                perform rhn_entitlements.remove_server_entitlement(sgrecord.server_id, sgrecord.label);

            select is_base
            into type_is_base
            from rhnServerGroupType sgt
            where sgt.id = sgrecord.group_type_id;

            -- if we're removing a base ent, then be sure to
            -- remove the server's channel subscriptions.
            if ( type_is_base = 'Y' ) then
                   perform rhn_channel.clear_subscriptions(sgrecord.server_id, update_family_countsYN);
            end if;

            end loop;
        end if;
    end$$
language plpgsql;

    -- *******************************************************************
    -- PROCEDURE: assign_system_entitlement
    --
    -- Moves system entitlements from from_org_id_in to to_org_id_in.
    -- Can raise not_enough_entitlements_in_base_org if from_org_id_in
    -- does not have enough entitlements to cover the move.
    -- Takes care of unentitling systems if necessary by calling
    -- set_group_count
    -- *******************************************************************
    create or replace function assign_system_entitlement(
        group_label_in in varchar,
        from_org_id_in in numeric,
        to_org_id_in in numeric,
        quantity_in in numeric
    ) returns void
as $$
    declare
        prev_ent_count numeric;
    to_org_prev_ent_count numeric;
        new_ent_count numeric;
    new_quantity numeric;
        group_type numeric;
    begin

            select max_members
            into prev_ent_count
            from rhnServerGroupType sgt,
                 rhnServerGroup sg
            where sg.org_id = from_org_id_in
              and sg.group_type = sgt.id
              and sgt.label = group_label_in;

            if not found then
                perform rhn_exception.raise_exception(
                              'not_enough_entitlements_in_base_org');
            end if;

            select max_members
            into to_org_prev_ent_count
            from rhnServerGroupType sgt,
                 rhnServerGroup sg
            where sg.org_id = to_org_id_in
              and sg.group_type = sgt.id
              and sgt.label = group_label_in;

            if not found then
                to_org_prev_ent_count := 0;
            end if;

            select id
            into group_type
            from rhnServerGroupType
            where label = group_label_in;

            if not found then
                perform rhn_exception.raise_exception(
                              'invalid_server_group');
            end if;

        new_ent_count := prev_ent_count - quantity_in;

        if prev_ent_count > new_ent_count then
            new_quantity := to_org_prev_ent_count + quantity_in;
        end if;

        if new_ent_count < 0 then
            perform rhn_exception.raise_exception(
                          'not_enough_entitlements_in_base_org');
        end if;


        perform rhn_entitlements.set_group_count(from_org_id_in,
                                         'S',
                                         group_type,
                                         new_ent_count);

        perform rhn_entitlements.set_group_count(to_org_id_in,
                                         'S',
                                         group_type,
                                         new_quantity);

        -- Create or delete the entries in rhnOrgEntitlementType
        if group_label_in = 'enterprise_entitled' then
            if new_quantity > 0 then
                perform rhn_entitlements.set_customer_enterprise(to_org_id_in);
            else
                perform rhn_entitlements.unset_customer_enterprise(to_org_id_in);
            end if;
        end if;

        if group_label_in = 'provisioning_entitled' then
            if new_quantity > 0 then
                perform rhn_entitlements.set_customer_provisioning(to_org_id_in);
            else
                perform rhn_entitlements.unset_customer_provisioning(to_org_id_in);
            end if;
        end if;

        if group_label_in = 'monitoring_entitled' then
            if new_quantity > 0 then
                perform rhn_entitlements.set_customer_monitoring(to_org_id_in);
            else
                perform rhn_entitlements.unset_customer_monitoring(to_org_id_in);
            end if;
        end if;

    end$$
language plpgsql;

    -- *******************************************************************
    -- PROCEDURE: assign_channel_entitlement
    --
    -- Moves channel entitlements from from_org_id_in to to_org_id_in.
    -- Can raise not_enough_entitlements_in_base_org if from_org_id_in
    -- does not have enough entitlements to cover the move.
    -- Takes care of unentitling systems if necessary by calling
    -- set_family_count
    -- *******************************************************************
    create or replace function assign_channel_entitlement(
        channel_family_label_in in varchar,
        from_org_id_in in numeric,
        to_org_id_in in numeric,
        quantity_in in numeric
    ) returns void
as $$
    declare
        prev_ent_count numeric;
        new_ent_count numeric;
    to_org_prev_ent_count numeric;
    new_quantity numeric;
        cfam_id       numeric;
    begin

            select max_members
            into prev_ent_count
            from rhnChannelFamily cf,
                 rhnPrivateChannelFamily pcf
            where pcf.org_id = from_org_id_in
              and pcf.channel_family_id = cf.id
              and cf.label = channel_family_label_in;

            if not found then
                perform rhn_exception.raise_exception(
                              'not_enough_entitlements_in_base_org');
            end if;

            select max_members
            into to_org_prev_ent_count
            from rhnChannelFamily cf,
                 rhnPrivateChannelFamily pcf
            where pcf.org_id = to_org_id_in
              and pcf.channel_family_id = cf.id
              and cf.label = channel_family_label_in;

            if not found then
                to_org_prev_ent_count := 0;
            end if;

            select id
            into cfam_id
            from rhnChannelFamily
            where label = channel_family_label_in;

            if not found then
                perform rhn_exception.raise_exception(
                              'invalid_channel_family');
            end if;

        new_ent_count := prev_ent_count - quantity_in;

    if prev_ent_count > new_ent_count then
            new_quantity := to_org_prev_ent_count + quantity_in;
    end if;


        if new_ent_count < 0 then
            perform rhn_exception.raise_exception(
                          'not_enough_entitlements_in_base_org');
        end if;

        perform rhn_entitlements.set_family_count(from_org_id_in,
                                          cfam_id,
                                          new_ent_count);

        perform rhn_entitlements.set_family_count(to_org_id_in,
                                          cfam_id,
                                          new_quantity);

    end$$
language plpgsql;

    -- *******************************************************************
    -- PROCEDURE: activate_system_entitlement
    --
    -- Sets the values in rhnServerGroup for a given rhnServerGroupType.
    --
    -- Calls: set_group_count to update, prune, or create the group.
    -- Called by: the code that activates a satellite cert.
    --
    -- Raises not_enough_entitlements_in_base_org if all entitlements
    -- in the org are used so the free entitlements would not cover
    -- the difference when descreasing the number of entitlements.
    -- *******************************************************************
    create or replace function activate_system_entitlement(
        org_id_in in numeric,
        group_label_in in varchar,
        quantity_in in numeric
    ) returns void
as $$
    declare
        prev_ent_count numeric;
        prev_ent_count_sum numeric;
        group_type numeric;
    begin

        -- Fetch the current entitlement count for the org
        -- into prev_ent_count

            select current_members
            into prev_ent_count
            from rhnServerGroupType sgt,
                 rhnServerGroup sg
            where sg.group_type = sgt.id
              and sgt.label = group_label_in
              and sg.org_id = org_id_in;

            if not found then
                prev_ent_count := 0;
            end if;

            select id
            into group_type
            from rhnServerGroupType
            where label = group_label_in;

            if not found then
                perform rhn_exception.raise_exception(
                              'invalid_server_group');
            end if;

        -- If we're setting the total entitlemnt count to a lower value,
        -- and that value is less than the allocated count in this org,
        -- we need to raise an exception.
        if quantity_in < prev_ent_count then
            perform rhn_exception.raise_exception(
                          'not_enough_entitlements_in_base_org');
        else
            perform rhn_entitlements.set_group_count(org_id_in,
                                             'S',
                                             group_type,
                                             quantity_in);
        end if;

    end$$
language plpgsql;

    -- *******************************************************************
    -- PROCEDURE: activate_channel_entitlement
    --
    -- Calls: set_family_count to update, prune, or create the family
    --        permission bucket.
    -- Called by: the code that activates a satellite cert.
    --
    -- Raises not_enough_entitlements_in_base_org if there are not enough
    -- entitlements in the org to cover the difference when you are
    -- descreasing the number of entitlements.
    --
    -- The backend code in Python is expected to do whatever arithmetics
    -- is needed.
    -- *******************************************************************
    create or replace function activate_channel_entitlement(
        org_id_in in numeric,
        channel_family_label_in in varchar,
        quantity_in in numeric,
        flex_in in numeric
    ) returns void
as $$
    declare
        prev_ent_count numeric;
        prev_flex_count numeric;
        prev_ent_count_sum numeric;
        cfam_id numeric;
        reduce_quantity numeric;
        total_flex_capable numeric;
        to_convert_reg cursor (channel_family_id_val numeric, org_id_in numeric, quantity numeric) for
                     select SC.server_id
                     from rhnServerChannel SC inner join
                          rhnServer S on S.id = SC.server_id
                     where
                         is_fve = 'Y'
                         and S.org_id = org_id_in
                         and SC.channel_id in
                         (select cfm.channel_id from rhnChannelFamilyMembers cfm
                             where cfm.CHANNEL_FAMILY_ID = channel_family_id_val)
                         limit quantity;
         to_convert_flex cursor (channel_family_id_val numeric, org_id_in numeric, quantity numeric) for
                   select server_id
                   from rhnServerFveCapable
                       where SERVER_ORG_ID = org_id_in and
                             channel_family_id = cfam_id;

    begin

        -- Fetch the current entitlement count for the org
        -- into prev_ent_count
            select current_members
            into prev_ent_count
            from rhnChannelFamily cf,
                 rhnPrivateChannelFamily pcf
            where pcf.org_id = org_id_in
              and pcf.channel_family_id = cf.id
              and cf.label = channel_family_label_in;

            if not found then
                prev_ent_count := 0;
            end if;

            select pcf.fve_current_members
            into prev_flex_count
            from rhnChannelFamily cf,
                 rhnPrivateChannelFamily pcf
            where pcf.org_id = org_id_in
              and pcf.channel_family_id = cf.id
              and cf.label = channel_family_label_in;

            if not found then
                prev_flex_count := 0;
            end if;

            select id
            into cfam_id
            from rhnChannelFamily
            where label = channel_family_label_in;

            if not found then
                perform rhn_exception.raise_exception(
                              'invalid_channel_family');
            end if;

        -- if there are too few flex entitlements
        if flex_in < prev_flex_count then
            -- and if the extra we need is less than or equal to our extra regular entitlements
            if prev_flex_count - flex_in <= quantity_in - prev_ent_count then
                   reduce_quantity := prev_flex_count - flex_in;
                   -- We need to convert some systems from flex guest to regular
                   for system in to_convert_reg(cfam_id, org_id_in, reduce_quantity) loop
                      --rhn_channel.convert_to_regular(system.server_id, cfam_id);
                      UPDATE rhnServerChannel sc set sc.is_fve = 'N'
                           where sc.server_id = system.server_id;
                   end loop;

                   --reset previous counts
                   prev_ent_count := prev_ent_count + reduce_quantity;
                   prev_flex_count := prev_flex_count - reduce_quantity;
            else
                perform rhn_exception.raise_exception(
                          'not_enough_flex_entitlements_in_base_org');
            end if;
        end if;

        -- if there are too few regular entitlements, and extra flex entitlements
        if quantity_in < prev_ent_count and prev_flex_count < flex_in then
                -- how many flex-capable systems (that aren't using flex) do we have
                select count(*)
                   into total_flex_capable
                   from rhnServerFveCapable
                       where SERVER_ORG_ID = org_id_in and
                             channel_family_id = cfam_id;
                -- if we have enough flex capable machines that is at least
                --   as many as what we are over on
                if total_flex_capable >= prev_ent_count - quantity_in then
                    reduce_quantity := prev_ent_count - quantity_in;
                    for system in to_convert_flex(cfam_id, org_id_in, reduce_quantity) loop
--                          rhn_channel.convert_to_fve(system.server_id, cfam_id);
                        UPDATE rhnServerChannel sc set sc.is_fve = 'Y'
                           where sc.server_id = system.server_id;
                    end loop;
                    prev_ent_count := prev_ent_count - reduce_quantity;
                    prev_flex_count := prev_flex_count + reduce_quantity;
                end if;
        end if;

        -- If we're setting the total entitlemnt count to a lower value,
        -- and that value is less than the count in that one org,
        -- we need to raise an exception.
        if quantity_in < prev_ent_count then
            perform rhn_exception.raise_exception(
                          'not_enough_entitlements_in_base_org');
        else
            -- even if we've manually converted systems to/from flex above
            -- set_family_count should call update_family_counts, to reset
            -- current used slots
            perform rhn_entitlements.set_family_count(org_id_in, cfam_id,
                                              quantity_in, flex_in);
        end if;

    end$$
language plpgsql;

    create or replace function set_group_count (
        customer_id_in in numeric,  -- customer_id
        type_in in char,            -- 'U' or 'S'
        group_type_in in numeric,   -- rhn[User|Server]GroupType.id
        quantity_in in numeric,      -- quantity
                update_family_countsYN in numeric default 1
    ) returns void
as $$
    declare
        group_id numeric;
        quantity numeric;
        wasfound boolean;
    begin
        quantity := quantity_in;
        if quantity is not null and quantity < 0 then
            quantity := 0;
        end if;

        if type_in = 'U' then
            select  rug.id
            into    group_id
            from    rhnUserGroup rug
            where   1=1
                and rug.org_id = customer_id_in
                and rug.group_type = group_type_in;
        elsif type_in = 'S' then
            select  rsg.id
            into    group_id
            from    rhnServerGroup rsg
            where   1=1
                and rsg.org_id = customer_id_in
                and rsg.group_type = group_type_in;
        end if;

        -- preserve the not found status across the rhn_entitlements.prune_group invocation
        wasfound := true;
        if not found then
            wasfound := false;
        end if;

        perform rhn_entitlements.prune_group(
            group_id,
            type_in,
            quantity,
                        update_family_countsYN
        );

        if not wasfound then
            if type_in = 'U' then
                insert into rhnUserGroup (
                        id, name, description, max_members, current_members,
                        group_type, org_id, created, modified
                    ) (
                        select  nextval('rhn_user_group_id_seq'), name, name,
                                quantity, 0, id, customer_id_in,
                                current_timestamp, current_timestamp
                        from    rhnUserGroupType
                        where    id = group_type_in
                );
            elsif type_in = 'S' then
                insert into rhnServerGroup (
                        id, name, description, max_members, current_members,
                        group_type, org_id, created, modified
                    ) (
                        select  nextval('rhn_server_group_id_seq'), name, name,
                                quantity, 0, id, customer_id_in,
                                current_timestamp, current_timestamp
                        from    rhnServerGroupType
                        where   id = group_type_in
                );
            end if;
        end if;

    end$$
language plpgsql;

    -- *******************************************************************
    -- PROCEDURE: prune_family
    -- Unsubscribes servers consuming physical slots from the channel family
    --   that are over the org's limit.
    -- Called by: set_family_count
    -- *******************************************************************
    create or replace function prune_family (
        customer_id_in in numeric,
        channel_family_id_in in numeric,
        quantity_in in numeric,
        flex_in in numeric
    ) returns void
as $$
    declare
       is_fve_in char;
       tmp_quantity numeric;

        serverchannels cursor for
            select  sc.server_id,
                    sc.channel_id
            from    rhnServerChannel sc,
                    rhnChannelFamilyMembers cfm
            where   1=1
                and cfm.channel_family_id = channel_family_id_in
                and cfm.channel_id = sc.channel_id
                and server_id in (
                            select  rs.id as server_id
                            from
                                    rhnServerChannel        rsc,
                                    rhnChannelFamilyMembers rcfm,
                                    rhnServer               rs
                            where   1=1
                                and rs.org_id = customer_id_in
                                and rs.id = rsc.server_id
                                and rsc.channel_id = rcfm.channel_id
                                and rcfm.channel_family_id =
                                    channel_family_id_in
                                -- we only want to grab servers consuming
                                -- physical slots.
                                and exists (
                                    select 1
                                    from rhnChannelFamilyServerPhysical cfsp
                                    where cfsp.server_id = rs.id
                                    and cfsp.channel_family_id =
                                        channel_family_id_in
                                    )
                            order by rcfm.modified asc
                            offset quantity_in
                        );
    begin
        -- if we get a null customer_id, this is completely bogus.
        if customer_id_in is null then
            return;
        end if;

        tmp_quantity := quantity_in;
        is_fve_in := 'N';

        for sc in serverchannels loop
            perform rhn_channel.unsubscribe_server(sc.server_id, sc.channel_id, 1, 1);

        tmp_quantity := flex_in;
        is_fve_in := 'Y';
        for sc in serverchannels loop
            perform rhn_channel.unsubscribe_server(sc.server_id, sc.channel_id, 1, 1);
        end loop;
        end loop;
                perform rhn_channel.update_family_counts(channel_family_id_in, customer_id_in);
    end$$
language plpgsql;

    create or replace function set_family_count (
        customer_id_in in numeric,      -- customer_id
        channel_family_id_in in numeric,    -- 246
        quantity_in in numeric,          -- 3
        flex_in in numeric
    ) returns void
as $$
    declare
        privperms cursor for
            select  1
            from    rhnPrivateChannelFamily
            where   org_id = customer_id_in
                and channel_family_id = channel_family_id_in;
        pubperms cursor for
            select  o.id org_id
            from    web_customer o,
                    rhnPublicChannelFamily pcf
            where   pcf.channel_family_id = channel_family_id_in;
        quantity numeric;
        done numeric := 0;
        flex numeric;
    begin
        quantity := quantity_in;
        if quantity is not null and quantity < 0 then
            quantity := 0;
        end if;
        flex := flex_in;
        if flex is not null and flex < 0 then
            flex := 0;
        end if;

        if customer_id_in is not null then
            for perm in privperms loop
                perform rhn_entitlements.prune_family(
                    customer_id_in,
                    channel_family_id_in,
                    quantity,
                    flex
                );

                if quantity is null and flex is null then
                    delete from rhnPrivateChannelFamily
                        where org_id = customer_id_in
                            and channel_family_id = channel_family_id_in;
                 else
                    update rhnPrivateChannelFamily
                        set max_members = quantity
                        where org_id = customer_id_in
                            and channel_family_id = channel_family_id_in;

                   update rhnPrivateChannelFamily
                        set fve_max_members = flex
                        where org_id = customer_id_in
                            and channel_family_id = channel_family_id_in;
                end if;
                return;
            end loop;

            insert into rhnPrivateChannelFamily (
                    channel_family_id, org_id, max_members, current_members, fve_max_members, fve_current_members
                ) values (
                    channel_family_id_in, customer_id_in, quantity, 0, flex, 0 );
            return;
        end if;

        for perm in pubperms loop
            if quantity = 0 then
                perform rhn_entitlements.prune_family(
                    perm.org_id,
                    channel_family_id_in,
                    quantity,
                    flex
                );
                if done = 0 then
                    delete from rhnPublicChannelFamily
                        where channel_family_id = channel_family_id_in;
                end if;
            end if;
            done := 1;
        end loop;
        -- if done's not 1, then we don't have any entitlements
        if done != 1 then
            insert into rhnPublicChannelFamily (
                    channel_family_id
                ) values (
                    channel_family_id_in
                );
        end if;
    end$$
language plpgsql;

    -- this expects quantity_in to be the number of available slots, not the
    -- max_members of the server group.  If you give it too many, it'll fail
    -- and raise servergroup_max_members.
    -- We should NEVER run this unless we're SURE that we won't
    -- be violating the max.
    create or replace function entitle_last_modified_servers (
        customer_id_in in numeric,  -- customer_id
        type_label_in in varchar,   -- 'enterprise_entitled'
        quantity_in in numeric      -- 3
    ) returns void
as $$
    declare
        -- find the servers that aren't currently in slots
        servers cursor(cid_in numeric, quant_in numeric) for
                                    select  rs.id as server_id
                                    from    rhnServer rs
                                    where   1=1
                                        and rs.org_id = cid_in
                                        and not exists (
                                            select  1
                                            from    rhnServerGroup sg,
                                                    rhnServerGroupMembers rsgm
                                            where   rsgm.server_id = rs.id
                                                and rsgm.server_group_id = sg.id
                                                and sg.group_type is not null
                                        )
                                        and not exists (
                                            select 1
                                            from rhnVirtualInstance vi
                                            where vi.virtual_system_id =
                                                  rs.id
                                        )
                                    order by modified desc
                                    limit quant_in;
    begin
        for server in servers(customer_id_in, quantity_in) loop
            perform rhn_entitlements.entitle_server(server.server_id, type_label_in);
        end loop;
    end$$
language plpgsql;

    create or replace function subscribe_newest_servers (
        customer_id_in in numeric
    ) returns void
as $$
    declare
        -- find servers without base channels
        servers cursor(cid_in numeric) for
            select  s.id
            from    rhnServer           s
            where   1=1
                and s.org_id = cid_in
                and not exists (
                        select 1
                        from    rhnChannel          c,
                                rhnServerChannel    sc
                        where   sc.server_id = s.id
                            and sc.channel_id = c.id
                            and c.parent_channel is null
                    )
                and not exists (
                        select 1
                        from rhnVirtualInstance vi
                        where vi.virtual_system_id = s.id
                    )
            order by s.modified desc;
        channel_id numeric;
    begin
        for server in servers(customer_id_in) loop
            channel_id := rhn_channel.guess_server_base(server.id);
            if channel_id is not null then
                begin
                    perform rhn_channel.subscribe_server(server.id, channel_id);
                -- exception is really channel_family_no_subscriptions
                exception
                    when others then
                        null;
                end;
            end if;
        end loop;
    end$$
language plpgsql;


-- restore the original setting
update pg_settings set setting = overlay( setting placing '' from 1 for (length('rhn_entitlements')+1) ) where name = 'search_path';
  0707010000065F000081B400000000000000000000000167AE111400001C6A000000000000000000000000000000000000005F00000000susemanager-schema/upgrade/spacewalk-schema-1.3-to-spacewalk-schema-1.4/023-rhn_config.pkb.sql    --
-- Copyright (c) 2008--2011 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--
--
--
--

-- setup search_path so that these functions are created in appropriate schema.
update pg_settings set setting = 'rhn_config,' || setting where name = 'search_path';


	-- just a stub for now
create or replace function prune_org_configs (
		org_id_in in numeric,
		total_in in numeric
	)
returns void
as $$
begin
end;
$$ LANGUAGE 'plpgsql';


	create or replace function insert_revision (
		revision_in in numeric,
		config_file_id_in in numeric,
		config_content_id_in in numeric,
		config_info_id_in in numeric,
		config_file_type_id_in in numeric default 1
	) returns numeric as $$
               declare
		retval numeric;
		 affected_orgs cursor is
			select cc.org_id as id from rhnConfigChannel cc,
					rhnConfigFile cf
			where cf.id = config_file_id_in
				and cf.config_channel_id = cc.id;
	begin

		insert into rhnConfigRevision(id, revision, config_file_id,
				config_content_id, config_info_id, config_file_type_id
			) values (
				nextval('rhn_confrevision_id_seq'), revision_in, config_file_id_in,
				config_content_id_in, config_info_id_in, config_file_type_id_in
			)
			returning id into retval;

		for org in affected_orgs loop
                        perform rhn_quota.update_org_quota(org.id);
                end loop;

		return retval;
	end$$ language 'plpgsql';

	create or replace function delete_revision (
		config_revision_id_in in numeric,
		org_id_in in numeric default -1
	) returns void as $$
	declare
		cfid numeric;
		ccid numeric;
		oid numeric;
		latest_crid numeric;
		others numeric := 0;
		snapshots cursor is
			select scr.snapshot_id as id
			from rhnSnapshot s,
					rhnSnapshotConfigRevision scr
			where scr.config_revision_id = config_revision_id_in
					and scr.snapshot_id = s.id
					and s.invalid is null;
		 other_revisions cursor (config_content_id_in numeric) is
			select 1
			from rhnConfigRevision
			where config_content_id = config_content_id_in;
	begin
                for snapshot in snapshots loop
                    update rhnSnapshot
                        set invalid = lookup_snapshot_invalid_reason('cr_removed')
                        where id = snapshot.id;
                end loop;

		if org_id_in < 0 then
			select cr.config_content_id, cc.org_id
			into ccid, oid
			from rhnConfigChannel cc,
					rhnConfigFile cf,
					rhnConfigRevision cr
			where cr.id = config_revision_id_in
				and cr.config_file_id = cf.id
				and cf.config_channel_id = cc.id;
		else
			select	cr.config_content_id, org_id_in
			into	ccid, oid
			from	rhnConfigRevision cr
			where	cr.id = config_revision_id_in;
		end if;

		-- right now this will set rhnActionConfigFileName.config_revision_id
		-- to null, and will remove an entry from rhnActionConfigRevision.
		-- might we want to prune and/or kill the action in some way?  maybe
		-- mark it failed or something?
		delete from rhnConfigRevision where id = config_revision_id_in;

		-- now prune away content if there aren't any other revisions pointing
		-- at it
		for other_revision in other_revisions(ccid) loop
			others := 1;
			exit;
		end loop;
		if others = 0 then
			delete from rhnConfigContent where id = ccid;
		end if;

		-- now make sure rhnConfigFile points at a valid revision;
		-- if there isn't one, we're deleting it, _unless_ org_id_in is
		-- >= 0, in which case we're in the delete trigger anyway
		if org_id_in < 0 then
			select	cf.latest_config_revision_id,
					cf.id
			into latest_crid,
					cfid
			from rhnConfigFile cf,
					rhnConfigRevision cr
			where cr.id = config_revision_id_in
				and cr.config_file_id = cf.id;

			if latest_crid = config_revision_id_in then
				latest_crid := rhn_config.get_latest_revision(cfid);
				if latest_crid is not null then
					update rhnConfigFile set latest_config_revision_id = latest_crid
						where id = cfid;
				else
					delete from rhnConfigFile where id = cfid;
				end if;
			end if;

		end if;
		perform rhn_quota.update_org_quota(oid);

	end ;
$$ LANGUAGE 'plpgsql';

	create or replace function get_latest_revision (
		config_file_id_in in numeric
		)
		returns numeric as $$
		declare
		revision1 record;
		begin
		for revision1 in
			select cr.id
			from rhnConfigRevision cr
			where cr.config_file_id = config_file_id_in
			order by revision desc
		loop
			return revision1.id;
		end loop;
		return null;
end;
$$ LANGUAGE 'plpgsql';

	create or replace function insert_file (
		config_channel_id_in in numeric,
		name_in in varchar
	) returns numeric as $$
		declare
		retval numeric;
	begin
		select nextval('rhn_conffile_id_seq')
		into retval;

		insert into rhnConfigFile(id, config_channel_id, config_file_name_id,
				state_id
			) (
				select retval,
						config_channel_id_in,
						lookup_config_filename(name_in),
						id
				from rhnConfigFileState
				where label = 'alive'
			);

		return retval;
	end;
$$ LANGUAGE 'plpgsql';

	create or replace function delete_file (
		config_file_id_in in numeric
	) returns void as $$
declare
org_id numeric;
revision record;

	begin
		for revision in
		select cr.id, cc.org_id
			from rhnConfigChannel cc,
					rhnConfigRevision cr,
					rhnConfigFile cf
			where cf.id = config_file_id_in
				and cf.config_channel_id = cc.id
				and cr.config_file_id = cf.id

                loop
			perform rhn_config.delete_revision(revision.id, revision.org_id);
			org_id := revision.org_id;
		end loop;
		perform rhn_quota.update_org_quota(org_id);
		delete from rhnConfigFile where id = config_file_id_in;
	end;
$$ LANGUAGE 'plpgsql';

	create or replace function insert_channel (
		org_id_in in numeric,
		type_in in varchar,
		name_in in varchar,
		label_in in varchar,
		description_in in varchar
	) returns numeric as $$
declare
		retval numeric;
	begin
		select nextval ('rhn_confchan_id_seq')
		into retval;

		insert into rhnConfigChannel(id, org_id, confchan_type_id,
				name, label, description
			) (
				select	retval,
						org_id_in,
						cct.id,
						name_in,
						label_in,
						description_in
				from rhnConfigChannelType cct
				where label = type_in
			);
		return retval;
	end;
$$ LANGUAGE 'plpgsql';

	create or replace function delete_channel (
		config_channel_id_in in numeric
	) returns void as $$
declare
	config_file record;
	begin
		for config_file in
		select id
			from rhnConfigFile
			where config_channel_id = config_channel_id_in
                loop
                    perform rhn_config.delete_file(config_file.id);
		end loop;
		delete from rhnConfigChannel where id = config_channel_id_in;

end;
$$ LANGUAGE 'plpgsql';

update pg_settings set setting = overlay( setting placing '' from 1 for (length('rhn_config')+1) ) where name = 'search_path';
  07070100000660000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000004800000000susemanager-schema/upgrade/spacewalk-schema-1.4-to-spacewalk-schema-1.5   07070100000661000081B400000000000000000000000167AE111400000508000000000000000000000000000000000000006C00000000susemanager-schema/upgrade/spacewalk-schema-1.4-to-spacewalk-schema-1.5/010-rhnPackageRecommends-create.sql   --
-- Copyright (c) 2010 Novell
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
--


CREATE TABLE rhnPackageRecommends
(
    package_id     NUMERIC NOT NULL
                       CONSTRAINT rhn_pkg_rec_package_fk
                           REFERENCES rhnPackage (id)
                           ON DELETE CASCADE,
    capability_id  NUMERIC NOT NULL
                       CONSTRAINT rhn_pkg_rec_capability_fk
                           REFERENCES rhnPackageCapability (id),
    sense          NUMERIC
                       DEFAULT (0) NOT NULL,
    created        TIMESTAMPTZ
                       DEFAULT (CURRENT_TIMESTAMP) NOT NULL,
    modified       TIMESTAMPTZ
                       DEFAULT (CURRENT_TIMESTAMP) NOT NULL
)

;

CREATE UNIQUE INDEX rhn_pkg_rec_pid_cid_s_uq
    ON rhnPackageRecommends (package_id, capability_id, sense)
    ;

CREATE INDEX rhn_pkg_rec_cid_idx
    ON rhnPackageRecommends (capability_id)
    
    ;

07070100000662000081B400000000000000000000000167AE111400000506000000000000000000000000000000000000006A00000000susemanager-schema/upgrade/spacewalk-schema-1.4-to-spacewalk-schema-1.5/011-rhnPackageSuggests-create.sql --
-- Copyright (c) 2010 Novell
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
--


CREATE TABLE rhnPackageSuggests
(
    package_id     NUMERIC NOT NULL
                       CONSTRAINT rhn_pkg_sugg_package_fk
                           REFERENCES rhnPackage (id)
                           ON DELETE CASCADE,
    capability_id  NUMERIC NOT NULL
                       CONSTRAINT rhn_pkg_sugg_capability_fk
                           REFERENCES rhnPackageCapability (id),
    sense          NUMERIC
                       DEFAULT (0) NOT NULL,
    created        TIMESTAMPTZ
                       DEFAULT (CURRENT_TIMESTAMP) NOT NULL,
    modified       TIMESTAMPTZ
                       DEFAULT (CURRENT_TIMESTAMP) NOT NULL
)

;

CREATE UNIQUE INDEX rhn_pkg_sugg_pid_cid_s_uq
    ON rhnPackageSuggests (package_id, capability_id, sense)
    ;

CREATE INDEX rhn_pkg_sugg_cid_idx
    ON rhnPackageSuggests (capability_id)
    
    ;

  07070100000663000081B400000000000000000000000167AE11140000050F000000000000000000000000000000000000006D00000000susemanager-schema/upgrade/spacewalk-schema-1.4-to-spacewalk-schema-1.5/012-rhnPackageSupplements-create.sql  --
-- Copyright (c) 2010 Novell
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
--


CREATE TABLE rhnPackageSupplements
(
    package_id     NUMERIC NOT NULL
                       CONSTRAINT rhn_pkg_supp_package_fk
                           REFERENCES rhnPackage (id)
                           ON DELETE CASCADE,
    capability_id  NUMERIC NOT NULL
                       CONSTRAINT rhn_pkg_supp_capability_fk
                           REFERENCES rhnPackageCapability (id),
    sense          NUMERIC
                       DEFAULT (0) NOT NULL,
    created        TIMESTAMPTZ
                       DEFAULT (CURRENT_TIMESTAMP) NOT NULL,
    modified       TIMESTAMPTZ
                       DEFAULT (CURRENT_TIMESTAMP) NOT NULL
)

;

CREATE UNIQUE INDEX rhn_pkg_supp_pid_cid_s_uq
    ON rhnPackageSupplements (package_id, capability_id, sense)
    ;

CREATE INDEX rhn_pkg_supp_cid_idx
    ON rhnPackageSupplements (capability_id)
    
    ;

 07070100000664000081B400000000000000000000000167AE1114000002E5000000000000000000000000000000000000006D00000000susemanager-schema/upgrade/spacewalk-schema-1.4-to-spacewalk-schema-1.5/013-rhnPackageRecommends-trigger.sql  --
-- Copyright (c) 2010 Novell, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
--

create or replace function rhn_pkg_rec_mod_trig_fun() returns trigger as
$$
begin
	new.modified := current_timestamp;

	return new;
end;
$$ language plpgsql;

create trigger
rhn_pkg_rec_mod_trig
before insert or update on rhnPackageRecommends
for each row
execute procedure rhn_pkg_rec_mod_trig_fun();

   07070100000665000081B400000000000000000000000167AE1114000002E6000000000000000000000000000000000000006B00000000susemanager-schema/upgrade/spacewalk-schema-1.4-to-spacewalk-schema-1.5/014-rhnPackageSuggests-trigger.sql    --
-- Copyright (c) 2010 Novell, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
--

create or replace function rhn_pkg_sugg_mod_trig_fun() returns trigger as
$$
begin
	new.modified := current_timestamp;

	return new;
end;
$$ language plpgsql;

create trigger
rhn_pkg_sugg_mod_trig
before insert or update on rhnPackageSuggests
for each row
execute procedure rhn_pkg_sugg_mod_trig_fun();

  07070100000666000081B400000000000000000000000167AE1114000002E9000000000000000000000000000000000000006E00000000susemanager-schema/upgrade/spacewalk-schema-1.4-to-spacewalk-schema-1.5/015-rhnPackageSupplements-trigger.sql --
-- Copyright (c) 2010 Novell, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
--

create or replace function rhn_pkg_supp_mod_trig_fun() returns trigger as
$$
begin
	new.modified := current_timestamp;

	return new;
end;
$$ language plpgsql;

create trigger
rhn_pkg_supp_mod_trig
before insert or update on rhnPackageSupplements
for each row
execute procedure rhn_pkg_supp_mod_trig_fun();

   07070100000667000081B400000000000000000000000167AE11140000032D000000000000000000000000000000000000006000000000susemanager-schema/upgrade/spacewalk-schema-1.4-to-spacewalk-schema-1.5/016-rhn_channel.pkb.sql   
--update pg_setting
update pg_settings set setting = 'rhn_channel,' || setting where name = 'search_path';

    CREATE OR REPLACE FUNCTION available_fve_chan_subs(channel_id_in IN NUMERIC,
                                          org_id_in IN NUMERIC)
    RETURNS NUMERIC
    AS $$
    declare
            channel_family_id_val NUMERIC;
    BEGIN
        SELECT channel_family_id INTO STRICT channel_family_id_val
            FROM rhnChannelFamilyMembers
            WHERE channel_id = channel_id_in;

            RETURN rhn_channel.available_fve_family_subs(
                           channel_family_id_val, org_id_in);
    END$$ language plpgsql;

-- restore the original setting
update pg_settings set setting = overlay( setting placing '' from 1 for (length('rhn_channel')+1) ) where name = 'search_path';
   07070100000668000081B400000000000000000000000167AE111400002AE0000000000000000000000000000000000000005B00000000susemanager-schema/upgrade/spacewalk-schema-1.4-to-spacewalk-schema-1.5/017-rhn_server.sql    
create or replace
function delete_server (
        server_id_in in numeric
) returns void 
as
$$
declare
         servergroups cursor for
                select  server_id, server_group_id
                from    rhnServerGroupMembers sgm
                where   sgm.server_id = server_id_in;

         configchannels cursor for
                select  cc.id
                from    rhnConfigChannel cc,
                        rhnConfigChannelType cct,
                        rhnServerConfigChannel scc
                where   1=1
                        and scc.server_id = server_id_in
                        and scc.config_channel_id = cc.id
                        -- these config channel types are reserved
                        -- for use by a single server, so we don't
                        -- need to check for other servers subscribed
                        and cct.label in
                                ('local_override','server_import')
                        and cct.id = cc.confchan_type_id;

    is_virt boolean;
begin
        perform rhn_channel.delete_server_channels(server_id_in);
        -- rhn_channel.clear_subscriptions(server_id_in);

        -- filelists
        delete from rhnFileList where id in (
	select	spfl.file_list_id
	  from	rhnServerPreserveFileList spfl
	 where	spfl.server_id = server_id_in
			and not exists (
				select	1
				from	rhnServerPreserveFileList
				where	file_list_id = spfl.file_list_id
					and server_id != server_id_in
				union all
				select	1
				from	rhnKickstartPreserveFileList
				where	file_list_id = spfl.file_list_id
			)
        );

	for configchannel in configchannels loop
		perform rhn_config.delete_channel(configchannel.id);
	end loop;

      is_virt := exists (
       select 1
        from rhnServerEntitlementView
       where server_id = server_id_in
         and label in ('virtualization_host', 'virtualization_host_platform')
      );

	for sgm in servergroups loop
		perform rhn_server.delete_from_servergroup(
			sgm.server_id, sgm.server_group_id);
	end loop;

    if is_virt then
        perform rhn_entitlements.repoll_virt_guest_entitlements(server_id_in);
    end if;

        -- we're handling this instead of letting an "on delete
        -- set null" do it so that we don't run the risk
        -- of setting off the triggers and killing us with a
        -- mutating table

        -- this is merge of two single updates:
        --  update ... set old_server_id = null where old_server_id = server_id_in;
        --  update ... set new_server_id = null where new_server_id = server_id_in;
        -- so we scan rhnKickstartSession table only once
        update rhnKickstartSession
                set old_server_id = case when old_server_id = server_id_in then null else old_server_id end,
                    new_server_id = case when new_server_id = server_id_in then null else new_server_id end
                where old_server_id = server_id_in
                   or new_server_id = server_id_in;

        perform rhn_channel.clear_subscriptions(server_id_in,1);

        -- A little complicated here, but the goal is to
        -- delete records from rhnVirtualInstace only if we don't
        -- care about them anymore.  We don't care about records
        -- in rhnVirtualInstance if we are deleting the host
        -- system and the virtual system is already null, or
        -- vice-versa.  We *do* care about them if either the
        -- host or virtual system is still registered because we
        -- still want them to show up in the UI.
    -- If there's a newer row in rhnVirtualInstance with the same
    -- uuid, this guest must have been re-registered, so we can clean
    -- this data up.

        delete from rhnVirtualInstance vi
              where (host_system_id = server_id_in and virtual_system_id is null)
                 or (virtual_system_id = server_id_in and host_system_id is null)
                 or (vi.virtual_system_id = server_id_in and vi.modified < (select max(vi2.modified)
                    from rhnVirtualInstance vi2 where vi2.uuid = vi.uuid));

        -- this is merge of two single updates:
        --  update ... set host_system_id = null where host_system_id = server_id_in;
        --  update ... set virtual_system_id = null where virtual_system_id = server_id_in;
        -- so we scan rhnVirtualInstance table only once
        update rhnVirtualInstance
           set host_system_id = case when host_system_id = server_id_in then null else host_system_id end,
               virtual_system_id = case when virtual_system_id = server_id_in then null else virtual_system_id end
         where host_system_id = server_id_in
            or virtual_system_id = server_id_in;

        -- this is merge of two single updates:
        --  update ... set old_host_system_id = null when old_host_system_id = server_id_in;
        --  update ... set new_host_system_id = null when new_host_system_id = server_id_in;
        -- so we scan rhnVirtualInstanceEventLog table only once
        update rhnVirtualInstanceEventLog
           set old_host_system_id = case when old_host_system_id = server_id_in then null else old_host_system_id end,
               new_host_system_id = case when new_host_system_id = server_id_in then null else new_host_system_id end
         where old_host_system_id = server_id_in
            or new_host_system_id = server_id_in;

        -- We're deleting everything with a foreign key to rhnServer
        -- here, now.  I'm hoping this will help aleviate our deadlock
        -- problem.

        delete from rhnActionConfigChannel where server_id = server_id_in;
        delete from rhnActionConfigRevision where server_id = server_id_in;
        delete from rhnActionPackageRemovalFailure where server_id = server_id_in;
        delete from rhnClientCapability where server_id = server_id_in;
        delete from rhnCpu where server_id = server_id_in;
        -- there's still a cascade here, because the constraint keeps the
        -- table locked for too long to rebuild it.  Ugh...
        delete from rhnDevice where server_id = server_id_in;
        delete from rhnProxyInfo where server_id = server_id_in;
        delete from rhnRam where server_id = server_id_in;
        delete from rhnRegToken where server_id = server_id_in;
        delete from rhnSatelliteInfo where server_id = server_id_in;
        -- this cascades to rhnActionConfigChannel and rhnActionConfigFileName
        delete from rhnServerAction where server_id = server_id_in;
        delete from rhnServerActionPackageResult where server_id = server_id_in;
        delete from rhnServerActionScriptResult where server_id = server_id_in;
        delete from rhnServerActionVerifyResult where server_id = server_id_in;
        delete from rhnServerActionVerifyMissing where server_id = server_id_in;
        -- counts are handled above.  this should be a delete_ function.
        delete from rhnServerChannel where server_id = server_id_in;
        delete from rhnServerConfigChannel where server_id = server_id_in;
        delete from rhnServerCustomDataValue where server_id = server_id_in;
        delete from rhnServerDMI where server_id = server_id_in;
        delete from rhnServerEvent where server_id = server_id_in;
        delete from rhnServerHistory where server_id = server_id_in;
        delete from rhnServerInfo where server_id = server_id_in;
        delete from rhnServerInstallInfo where server_id = server_id_in;
        delete from rhnServerLocation where server_id = server_id_in;
        delete from rhnServerLock where server_id = server_id_in;
        delete from rhnServerNeededCache where server_id = server_id_in;
        delete from rhnServerNetwork where server_id = server_id_in;
        delete from rhnServerNotes where server_id = server_id_in;
        -- I'm not removing the foreign key from rhnServerPackage; that'll
        -- take forever.  Do the delete anyway.
        delete from rhnServerPackage where server_id = server_id_in;
        delete from rhnServerTokenRegs where server_id = server_id_in;
        delete from rhnSnapshotTag where server_id = server_id_in;
        -- this cascades to:
        --   rhnSnapshotChannel, rhnSnapshotConfigChannel, rhnSnapshotPackage,
        --   rhnSnapshotConfigRevision, rhnSnapshotServerGroup,
        --   rhnSnapshotTag.
        -- We may want to consider delete_snapshot() at some point, but
        --   I don't think we need to yet.
        delete from rhnSnapshot where server_id = server_id_in;
        delete from rhnUserServerPrefs where server_id = server_id_in;
        -- hrm, this one's interesting... we _probably_ should delete
        -- everything for the parent server_id when we delete the proxy,
        -- but we don't currently.
        delete from rhnServerPath where server_id_in in (server_id, proxy_server_id);
        delete from rhnUserServerPerms where server_id = server_id_in;

        delete from rhnServerNetInterface where server_id = server_id_in;
        delete from rhn_server_monitoring_info where recid = server_id_in;

        delete from rhnAppInstallSession where server_id = server_id_in;
        delete from rhnServerUuid where server_id = server_id_in;

    -- We delete all the probes running directly against this system
    -- and any probes that were using this Server as a Proxy Scout.
    DELETE FROM rhn_probe_state PS WHERE PS.probe_id IN (
     SELECT CP.probe_id
       FROM rhn_check_probe CP  
      WHERE CP.host_id = server_id_in
         OR CP.sat_cluster_id in
    (SELECT SN.sat_cluster_id
       FROM rhn_sat_node SN
      WHERE SN.server_id = server_id_in)
    );

    DELETE FROM rhn_probe P  WHERE P.recid IN (
     SELECT CP.probe_id
       FROM rhn_check_probe CP  
      WHERE CP.host_id = server_id_in
         OR CP.sat_cluster_id in
    (SELECT SN.sat_cluster_id
       FROM rhn_sat_node SN
      WHERE SN.server_id = server_id_in)
    );

    -- delete from time_series TODO

        delete from rhn_check_probe where host_id = server_id_in;
        delete from rhn_host_probe where host_id = server_id_in;

    delete from rhn_sat_cluster where recid in
      ( select sat_cluster_id from rhn_sat_node where server_id = server_id_in );

        delete from rhn_sat_node where server_id = server_id_in;

        delete from rhnPushClient where server_id = server_id_in;

        -- now get rhnServer itself.
        delete
        from    rhnServer
                where id = server_id_in;

        delete
        from    rhnSet
        where   1=1
                and user_id in (
                        select  wc.id
                        from    rhnServer rs,
                                web_contact wc
                        where   rs.id = server_id_in
                                and rs.org_id = wc.org_id
                )
                and label = 'system_list'
                and element = server_id_in;
end;
$$
language plpgsql;

07070100000669000081B400000000000000000000000167AE1114000000A0000000000000000000000000000000000000007800000000susemanager-schema/upgrade/spacewalk-schema-1.4-to-spacewalk-schema-1.5/020-rhnKickstartCommandName-iscsi-iscsiname.sql   
update rhnKickstartCommandName set sort_order = 40 where name = 'iscsiname';
update rhnKickstartCommandName set sort_order = 41 where name = 'iscsi';
commit;

0707010000066A000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000004800000000susemanager-schema/upgrade/spacewalk-schema-1.5-to-spacewalk-schema-1.6   0707010000066B000081B400000000000000000000000167AE111400000514000000000000000000000000000000000000006400000000susemanager-schema/upgrade/spacewalk-schema-1.5-to-spacewalk-schema-1.6/002-rhnServerNeededView.sql   CREATE OR REPLACE VIEW
rhnServerNeededView
(
    org_id,
    server_id,
    errata_id,
    package_id,
    package_name_id,
    channel_id
)
AS
SELECT s.org_id,
       sp.server_id,
       x.errata_id,
       up.id,
       up.name_id,
       x.channel_id
    FROM rhnServer s
        join (SELECT sp_sp.server_id, sp_sp.name_id, sp_sp.package_arch_id, max(sp_pe.evr) AS max_evr
                FROM rhnServerPackage sp_sp
                    join rhnPackageEvr sp_pe ON sp_pe.id = sp_sp.evr_id
                    GROUP BY sp_sp.server_id, sp_sp.name_id, sp_sp.package_arch_id) sp ON sp.server_id = s.id
        join rhnPackage up ON up.name_id = sp.name_id
        join rhnPackageEvr upe ON upe.id = up.evr_id AND sp.max_evr < upe.evr
        join rhnPackageUpgradeArchCompat puac ON puac.package_arch_id = sp.package_arch_id AND puac.package_upgrade_arch_id = up.package_arch_id
        join rhnServerChannel sc ON sc.server_id = sp.server_id
        join rhnChannelPackage cp ON cp.package_id = up.id AND cp.channel_id = sc.channel_id
        left join
        (SELECT ep.errata_id, cp.channel_id, ep.package_id
         FROM rhnChannelErrata cp
             join rhnErrataPackage ep ON ep.errata_id = cp.errata_id) x
            ON x.channel_id = sc.channel_id AND x.package_id = cp.package_id
;
0707010000066C000081B400000000000000000000000167AE111400001152000000000000000000000000000000000000006B00000000susemanager-schema/upgrade/spacewalk-schema-1.5-to-spacewalk-schema-1.6/003-assign_channel_entitlement.sql    
-- setup search_path so that these functions are created in appropriate schema.
update pg_settings set setting = 'rhn_entitlements,' || setting where name = 'search_path';

create or replace function assign_channel_entitlement(
        channel_family_label_in in varchar,
        from_org_id_in in numeric,
        to_org_id_in in numeric,
        quantity_in in numeric,
        flex_in in numeric
    ) returns void
as $$
    declare
        from_org_prev_ent_count numeric;
        from_org_prev_ent_count_flex numeric;
        new_ent_count numeric;
        new_ent_count_flex numeric;
        to_org_prev_ent_count numeric;
        to_org_prev_ent_count_flex numeric;
        new_quantity numeric;
        new_flex numeric;
        cfam_id       numeric;
    begin

            select max_members
            into from_org_prev_ent_count
            from rhnChannelFamily cf,
                 rhnPrivateChannelFamily pcf
            where pcf.org_id = from_org_id_in
              and pcf.channel_family_id = cf.id
              and cf.label = channel_family_label_in;

            if not found then
                perform rhn_exception.raise_exception(
                              'not_enough_entitlements_in_base_org');
            end if;

            select max_members
            into to_org_prev_ent_count
            from rhnChannelFamily cf,
                 rhnPrivateChannelFamily pcf
            where pcf.org_id = to_org_id_in
              and pcf.channel_family_id = cf.id
              and cf.label = channel_family_label_in;

            if not found then
                to_org_prev_ent_count := 0;
            end if;

            select fve_max_members
            into from_org_prev_ent_count_flex
            from rhnChannelFamily cf,
                rhnPrivateChannelFamily pcf
            where pcf.org_id = from_org_id_in
              and pcf.channel_family_id = cf.id
              and cf.label = channel_family_label_in;

            if not found then
                perform rhn_exception.raise_exception(
                              'not_enough_flex_entitlements_in_base_org');
            end if;

            select fve_max_members
            into to_org_prev_ent_count_flex
            from rhnChannelFamily cf,
                 rhnPrivateChannelFamily pcf
            where pcf.org_id = to_org_id_in
              and pcf.channel_family_id = cf.id
              and cf.label = channel_family_label_in;

            if not found then
                to_org_prev_ent_count_flex := 0;
            end if;

            select id
            into cfam_id
            from rhnChannelFamily
            where label = channel_family_label_in;

            if not found then
                perform rhn_exception.raise_exception(
                              'invalid_channel_family');
            end if;

        new_ent_count := from_org_prev_ent_count - quantity_in;
        new_ent_count_flex := from_org_prev_ent_count_flex - flex_in;

        if from_org_prev_ent_count > new_ent_count then
            new_quantity := to_org_prev_ent_count + quantity_in;
        end if;

        if from_org_prev_ent_count_flex >= new_ent_count_flex then
            new_flex := to_org_prev_ent_count_flex + flex_in;
        end if;

        if new_ent_count < 0 then
            perform rhn_exception.raise_exception(
                          'not_enough_entitlements_in_base_org');
        end if;

        if new_ent_count_flex < 0 then
            perform rhn_exception.raise_exception(
                          'not_enough_flex_entitlements_in_base_org');
        end if;



        perform rhn_entitlements.set_family_count(from_org_id_in,
                                          cfam_id,
                                          new_ent_count,
                                          new_ent_count_flex);

        perform rhn_entitlements.set_family_count(to_org_id_in,
                                          cfam_id,
                                          new_quantity,
                                          new_flex);

    end$$
language plpgsql;

drop function assign_channel_entitlement(
    channel_family_label_in varchar,
    from_org_id_in numeric,
    to_org_id_in numeric,
    quantity_in numeric
    );

-- restore the original setting
update pg_settings set setting = overlay( setting placing '' from 1 for (length('rhn_entitlements')+1) ) where name = 'search_path';
  0707010000066D000081B400000000000000000000000167AE11140000016D000000000000000000000000000000000000006000000000susemanager-schema/upgrade/spacewalk-schema-1.5-to-spacewalk-schema-1.6/004-all_tab_columns.sql   
create or replace view all_tab_columns
as
select
        table_name              as table_name,
        column_name             as column_name,
        ordinal_position        as column_id,
        data_type               as data_type,
        numeric_precision       as data_precision,
        substr(is_nullable,1,1) as nullable
from information_schema.columns;
   0707010000066E000081B400000000000000000000000167AE1114000001DE000000000000000000000000000000000000006100000000susemanager-schema/upgrade/spacewalk-schema-1.5-to-spacewalk-schema-1.6/005-all_primary_keys.sql  
create or replace view all_primary_keys as
select
        ts.table_name              as table_name,
        ts.constraint_name         as constraint_name,
        ccu.column_name            as column_name
  from information_schema.table_constraints ts
  join information_schema.constraint_column_usage ccu
    on ts.table_name = ccu.table_name
   and ts.table_schema = ccu.table_schema
   and ts.constraint_name = ccu.constraint_name
 where ts.constraint_type = 'PRIMARY KEY';
  0707010000066F000081B400000000000000000000000167AE11140000002A000000000000000000000000000000000000006D00000000susemanager-schema/upgrade/spacewalk-schema-1.5-to-spacewalk-schema-1.6/024-rhn_service_probe_origins-pk.sql  
drop index rhn_srvpo_serv_orig_pr_id_uq;
  07070100000670000081B400000000000000000000000167AE111400000055000000000000000000000000000000000000007000000000susemanager-schema/upgrade/spacewalk-schema-1.5-to-spacewalk-schema-1.6/027-rhn_command_queue_execs-numeric.sql   
alter table rhn_command_queue_execs alter column execution_time type numeric(10,6);
   07070100000671000081B400000000000000000000000167AE11140000037C000000000000000000000000000000000000006400000000susemanager-schema/upgrade/spacewalk-schema-1.5-to-spacewalk-schema-1.6/028-rhn_satellite_state.sql   
alter table rhn_satellite_state alter column pct_ok          type numeric(10,2);
alter table rhn_satellite_state alter column pct_warning     type numeric(10,2);
alter table rhn_satellite_state alter column pct_critical    type numeric(10,2);
alter table rhn_satellite_state alter column pct_unknown     type numeric(10,2);
alter table rhn_satellite_state alter column pct_pending     type numeric(10,2);
alter table rhn_satellite_state alter column max_exec_time   type numeric(10,2);
alter table rhn_satellite_state alter column min_exec_time   type numeric(10,2);
alter table rhn_satellite_state alter column avg_exec_time   type numeric(10,2);
alter table rhn_satellite_state alter column max_latency     type numeric(10,2);
alter table rhn_satellite_state alter column min_latency     type numeric(10,2);
alter table rhn_satellite_state alter column avg_latency     type numeric(10,2);
07070100000672000081B400000000000000000000000167AE111400000269000000000000000000000000000000000000006300000000susemanager-schema/upgrade/spacewalk-schema-1.5-to-spacewalk-schema-1.6/029-rhn_url_probe_step.sql    
alter table rhn_url_probe_step alter column connect_warn type numeric(10,3);
alter table rhn_url_probe_step alter column connect_crit type numeric(10,3);
alter table rhn_url_probe_step alter column latency_warn type numeric(10,3);
alter table rhn_url_probe_step alter column latency_crit type numeric(10,3);
alter table rhn_url_probe_step alter column dns_warn     type numeric(10,3);
alter table rhn_url_probe_step alter column dns_crit     type numeric(10,3);
alter table rhn_url_probe_step alter column total_warn   type numeric(10,3);
alter table rhn_url_probe_step alter column total_crit   type numeric(10,3);
   07070100000673000081B400000000000000000000000167AE111400000047000000000000000000000000000000000000006F00000000susemanager-schema/upgrade/spacewalk-schema-1.5-to-spacewalk-schema-1.6/030-rhnVirtualInstance.sql-numeric.sql    alter table rhnVirtualInstance alter column confirmed type numeric(1);
 07070100000674000081B400000000000000000000000167AE1114000000D1000000000000000000000000000000000000006C00000000susemanager-schema/upgrade/spacewalk-schema-1.5-to-spacewalk-schema-1.6/031-rhn_check_probe.sql-numeric.sql   alter table rhn_check_probe alter column probe_id type numeric(12);
alter table rhn_check_probe alter column host_id type numeric(12);
alter table rhn_check_probe alter column sat_cluster_id type numeric(12);
   07070100000675000081B400000000000000000000000167AE11140000008A000000000000000000000000000000000000006D00000000susemanager-schema/upgrade/spacewalk-schema-1.5-to-spacewalk-schema-1.6/032-rhn_check_suites.sql-numeric.sql  alter table rhn_check_suites alter column recid type numeric(12);
alter table rhn_check_suites alter column customer_id type numeric(12);
  07070100000676000081B400000000000000000000000167AE11140000009A000000000000000000000000000000000000007200000000susemanager-schema/upgrade/spacewalk-schema-1.5-to-spacewalk-schema-1.6/033-rhn_check_suite_probe.sql-numeric.sql alter table rhn_check_suite_probe alter column probe_id type numeric(12);
alter table rhn_check_suite_probe alter column check_suite_id type numeric(12);
  07070100000677000081B400000000000000000000000167AE111400000052000000000000000000000000000000000000007800000000susemanager-schema/upgrade/spacewalk-schema-1.5-to-spacewalk-schema-1.6/034-rhn_command_param_threshold.sql-numeric.sql   alter table rhn_command_param_threshold alter column command_id type numeric(12);
  07070100000678000081B400000000000000000000000167AE11140000004C000000000000000000000000000000000000007700000000susemanager-schema/upgrade/spacewalk-schema-1.5-to-spacewalk-schema-1.6/035-rhn_command_queue_commands.sql-numeric.sql    alter table rhn_command_queue_commands alter column recid type numeric(12);
07070100000679000081B400000000000000000000000167AE1114000000ED000000000000000000000000000000000000007800000000susemanager-schema/upgrade/spacewalk-schema-1.5-to-spacewalk-schema-1.6/036-rhn_command_queue_instances.sql-numeric.sql   alter table rhn_command_queue_instances alter column recid type numeric(12);
alter table rhn_command_queue_instances alter column command_id type numeric(12);
alter table rhn_command_queue_instances alter column timeout type numeric(5);
   0707010000067A000081B400000000000000000000000167AE1114000000EC000000000000000000000000000000000000007400000000susemanager-schema/upgrade/spacewalk-schema-1.5-to-spacewalk-schema-1.6/037-rhn_command_queue_execs.sql-numeric.sql   alter table rhn_command_queue_execs alter column instance_id type numeric(12);
alter table rhn_command_queue_execs alter column netsaint_id type numeric(12);
alter table rhn_command_queue_execs alter column exit_status type numeric(5);
0707010000067B000081B400000000000000000000000167AE111400000097000000000000000000000000000000000000007500000000susemanager-schema/upgrade/spacewalk-schema-1.5-to-spacewalk-schema-1.6/038-rhn_command_queue_params.sql-numeric.sql  alter table rhn_command_queue_params alter column instance_id type numeric(12);
alter table rhn_command_queue_params alter column ord type numeric(3);
 0707010000067C000081B400000000000000000000000167AE111400000051000000000000000000000000000000000000007700000000susemanager-schema/upgrade/spacewalk-schema-1.5-to-spacewalk-schema-1.6/039-rhn_command_queue_sessions.sql-numeric.sql    alter table rhn_command_queue_sessions alter column contact_id type numeric(12);
   0707010000067D000081B400000000000000000000000167AE11140000004A000000000000000000000000000000000000006F00000000susemanager-schema/upgrade/spacewalk-schema-1.5-to-spacewalk-schema-1.6/040-rhn_command_target.sql-numeric.sql    alter table rhn_command_target alter column customer_id type numeric(12);
  0707010000067E000081B400000000000000000000000167AE111400000040000000000000000000000000000000000000006B00000000susemanager-schema/upgrade/spacewalk-schema-1.5-to-spacewalk-schema-1.6/041-rhn_strategies.sql-numeric.sql    alter table rhn_strategies alter column recid type numeric(12);
0707010000067F000081B400000000000000000000000167AE11140000025C000000000000000000000000000000000000006F00000000susemanager-schema/upgrade/spacewalk-schema-1.5-to-spacewalk-schema-1.6/043-rhn_current_alerts.sql-numeric.sql    alter table rhn_current_alerts alter column recid type numeric(12);
alter table rhn_current_alerts alter column original_server type numeric(12);
alter table rhn_current_alerts alter column current_server type numeric(12);
alter table rhn_current_alerts alter column escalation_level type numeric(2);
alter table rhn_current_alerts alter column host_probe_id type numeric(12);
alter table rhn_current_alerts alter column service_probe_id type numeric(12);
alter table rhn_current_alerts alter column customer_id type numeric(12);
alter table rhn_current_alerts alter column netsaint_id type numeric(12);
07070100000680000081B400000000000000000000000167AE1114000000A5000000000000000000000000000000000000007800000000susemanager-schema/upgrade/spacewalk-schema-1.5-to-spacewalk-schema-1.6/044-rhn_current_state_summaries.sql-numeric.sql   alter table rhn_current_state_summaries alter column customer_id type numeric(12);
alter table rhn_current_state_summaries alter column state_count type numeric(9);
   07070100000681000081B400000000000000000000000167AE111400000356000000000000000000000000000000000000006F00000000susemanager-schema/upgrade/spacewalk-schema-1.5-to-spacewalk-schema-1.6/045-rhn_deployed_probe.sql-numeric.sql    alter table rhn_deployed_probe alter column recid type numeric(12);
alter table rhn_deployed_probe alter column customer_id type numeric(12);
alter table rhn_deployed_probe alter column command_id type numeric(16);
alter table rhn_deployed_probe alter column contact_group_id type numeric(12);
alter table rhn_deployed_probe alter column os_id type numeric(12);
alter table rhn_deployed_probe alter column notification_interval_minutes type numeric(16);
alter table rhn_deployed_probe alter column check_interval_minutes type numeric(16);
alter table rhn_deployed_probe alter column retry_interval_minutes type numeric(16);
alter table rhn_deployed_probe alter column max_attempts type numeric(16);
alter table rhn_deployed_probe alter column sat_cluster_id type numeric(12);
alter table rhn_deployed_probe alter column parent_probe_id type numeric(12);
  07070100000682000081B400000000000000000000000167AE1114000000CE000000000000000000000000000000000000006B00000000susemanager-schema/upgrade/spacewalk-schema-1.5-to-spacewalk-schema-1.6/046-rhn_host_probe.sql-numeric.sql    alter table rhn_host_probe alter column probe_id type numeric(12);
alter table rhn_host_probe alter column host_id type numeric(12);
alter table rhn_host_probe alter column sat_cluster_id type numeric(12);
  07070100000683000081B400000000000000000000000167AE111400000095000000000000000000000000000000000000006D00000000susemanager-schema/upgrade/spacewalk-schema-1.5-to-spacewalk-schema-1.6/047-rhn_method_types.sql-numeric.sql  alter table rhn_method_types alter column recid type numeric(12);
alter table rhn_method_types alter column notification_format_id type numeric(12);
   07070100000684000081B400000000000000000000000167AE111400000109000000000000000000000000000000000000007600000000susemanager-schema/upgrade/spacewalk-schema-1.5-to-spacewalk-schema-1.6/048-rhn_multi_scout_threshold.sql-numeric.sql alter table rhn_multi_scout_threshold alter column probe_id type numeric(12);
alter table rhn_multi_scout_threshold alter column scout_warning_threshold type numeric(12);
alter table rhn_multi_scout_threshold alter column scout_critical_threshold type numeric(12);
   07070100000685000081B400000000000000000000000167AE111400000145000000000000000000000000000000000000007500000000susemanager-schema/upgrade/spacewalk-schema-1.5-to-spacewalk-schema-1.6/049-rhn_notification_formats.sql-numeric.sql  alter table rhn_notification_formats alter column recid type numeric(12);
alter table rhn_notification_formats alter column customer_id type numeric(12);
alter table rhn_notification_formats alter column max_subject_length type numeric(12);
alter table rhn_notification_formats alter column max_body_length type numeric(12);
   07070100000686000081B400000000000000000000000167AE111400000042000000000000000000000000000000000000006D00000000susemanager-schema/upgrade/spacewalk-schema-1.5-to-spacewalk-schema-1.6/050-rhn_notifservers.sql-numeric.sql  alter table rhn_notifservers alter column recid type numeric(12);
  07070100000687000081B400000000000000000000000167AE111400000038000000000000000000000000000000000000006300000000susemanager-schema/upgrade/spacewalk-schema-1.5-to-spacewalk-schema-1.6/051-rhn_os.sql-numeric.sql    alter table rhn_os alter column recid type numeric(12);
07070100000688000081B400000000000000000000000167AE111400000092000000000000000000000000000000000000007100000000susemanager-schema/upgrade/spacewalk-schema-1.5-to-spacewalk-schema-1.6/052-rhn_os_commands_xref.sql-numeric.sql  alter table rhn_os_commands_xref alter column os_id type numeric(12);
alter table rhn_os_commands_xref alter column commands_id type numeric(12);
  07070100000689000081B400000000000000000000000167AE111400000041000000000000000000000000000000000000006C00000000susemanager-schema/upgrade/spacewalk-schema-1.5-to-spacewalk-schema-1.6/053-rhn_pager_types.sql-numeric.sql   alter table rhn_pager_types alter column recid type numeric(12);
   0707010000068A000081B400000000000000000000000167AE111400000094000000000000000000000000000000000000007200000000susemanager-schema/upgrade/spacewalk-schema-1.5-to-spacewalk-schema-1.6/054-rhn_physical_location.sql-numeric.sql alter table rhn_physical_location alter column recid type numeric(12);
alter table rhn_physical_location alter column customer_id type numeric(12);
0707010000068B000081B400000000000000000000000167AE1114000001F4000000000000000000000000000000000000006600000000susemanager-schema/upgrade/spacewalk-schema-1.5-to-spacewalk-schema-1.6/055-rhn_probe.sql-numeric.sql alter table rhn_probe alter column customer_id type numeric(12);
alter table rhn_probe alter column command_id type numeric(16);
alter table rhn_probe alter column contact_group_id type numeric(12);
alter table rhn_probe alter column notification_interval_minutes type numeric(16);
alter table rhn_probe alter column check_interval_minutes type numeric(16);
alter table rhn_probe alter column retry_interval_minutes type numeric(16);
alter table rhn_probe alter column max_attempts type numeric(16);
0707010000068C000081B400000000000000000000000167AE111400000088000000000000000000000000000000000000006C00000000susemanager-schema/upgrade/spacewalk-schema-1.5-to-spacewalk-schema-1.6/056-rhn_probe_state.sql-numeric.sql   alter table rhn_probe_state alter column probe_id type numeric(12);
alter table rhn_probe_state alter column scout_id type numeric(12);
0707010000068D000081B400000000000000000000000167AE1114000001F0000000000000000000000000000000000000006A00000000susemanager-schema/upgrade/spacewalk-schema-1.5-to-spacewalk-schema-1.6/057-rhn_redirects.sql-numeric.sql alter table rhn_redirects alter column recid type numeric(12);
alter table rhn_redirects alter column customer_id type numeric(12);
alter table rhn_redirects alter column contact_id type numeric(12);
alter table rhn_redirects alter column recurring type numeric(12);
alter table rhn_redirects alter column recurring_frequency type numeric(12);
alter table rhn_redirects alter column recurring_duration type numeric(12);
alter table rhn_redirects alter column recurring_dur_type type numeric(12);
0707010000068E000081B400000000000000000000000167AE111400000052000000000000000000000000000000000000007700000000susemanager-schema/upgrade/spacewalk-schema-1.5-to-spacewalk-schema-1.6/058-rhn_redirect_email_targets.sql-numeric.sql    alter table rhn_redirect_email_targets alter column redirect_id type numeric(12);
  0707010000068F000081B400000000000000000000000167AE1114000000A9000000000000000000000000000000000000007700000000susemanager-schema/upgrade/spacewalk-schema-1.5-to-spacewalk-schema-1.6/059-rhn_redirect_group_targets.sql-numeric.sql    alter table rhn_redirect_group_targets alter column redirect_id type numeric(12);
alter table rhn_redirect_group_targets alter column contact_group_id type numeric(12);
   07070100000690000081B400000000000000000000000167AE1114000000AC000000000000000000000000000000000000007800000000susemanager-schema/upgrade/spacewalk-schema-1.5-to-spacewalk-schema-1.6/060-rhn_redirect_method_targets.sql-numeric.sql   alter table rhn_redirect_method_targets alter column redirect_id type numeric(12);
alter table rhn_redirect_method_targets alter column contact_method_id type numeric(12);
07070100000691000081B400000000000000000000000167AE111400000094000000000000000000000000000000000000007200000000susemanager-schema/upgrade/spacewalk-schema-1.5-to-spacewalk-schema-1.6/061-rhn_redirect_criteria.sql-numeric.sql alter table rhn_redirect_criteria alter column recid type numeric(12);
alter table rhn_redirect_criteria alter column redirect_id type numeric(12);
07070100000692000081B400000000000000000000000167AE111400000097000000000000000000000000000000000000006C00000000susemanager-schema/upgrade/spacewalk-schema-1.5-to-spacewalk-schema-1.6/062-rhn_sat_cluster.sql-numeric.sql   alter table rhn_sat_cluster alter column customer_id type numeric(12);
alter table rhn_sat_cluster alter column physical_location_id type numeric(12);
 07070100000693000081B400000000000000000000000167AE11140000009A000000000000000000000000000000000000007200000000susemanager-schema/upgrade/spacewalk-schema-1.5-to-spacewalk-schema-1.6/063-rhn_sat_cluster_probe.sql-numeric.sql alter table rhn_sat_cluster_probe alter column probe_id type numeric(12);
alter table rhn_sat_cluster_probe alter column sat_cluster_id type numeric(12);
  07070100000694000081B400000000000000000000000167AE1114000001A3000000000000000000000000000000000000006900000000susemanager-schema/upgrade/spacewalk-schema-1.5-to-spacewalk-schema-1.6/064-rhn_sat_node.sql-numeric.sql  alter table rhn_sat_node alter column recid type numeric(12);
alter table rhn_sat_node alter column max_concurrent_checks type numeric(4);
alter table rhn_sat_node alter column sat_cluster_id type numeric(12);
alter table rhn_sat_node alter column sched_log_level type numeric(4);
alter table rhn_sat_node alter column sput_log_level type numeric(4);
alter table rhn_sat_node alter column dq_log_level type numeric(4);
 07070100000695000081B400000000000000000000000167AE11140000013A000000000000000000000000000000000000007000000000susemanager-schema/upgrade/spacewalk-schema-1.5-to-spacewalk-schema-1.6/065-rhn_satellite_state.sql-numeric.sql   alter table rhn_satellite_state alter column satellite_id type numeric(12);
alter table rhn_satellite_state alter column probe_count type numeric(10);
alter table rhn_satellite_state alter column recent_state_changes type numeric(10);
alter table rhn_satellite_state alter column imminent_probes type numeric(10);
  07070100000696000081B400000000000000000000000167AE111400000044000000000000000000000000000000000000006F00000000susemanager-schema/upgrade/spacewalk-schema-1.5-to-spacewalk-schema-1.6/066-rhn_schedule_types.sql-numeric.sql    alter table rhn_schedule_types alter column recid type numeric(12);
07070100000697000081B400000000000000000000000167AE1114000000CE000000000000000000000000000000000000006A00000000susemanager-schema/upgrade/spacewalk-schema-1.5-to-spacewalk-schema-1.6/067-rhn_schedules.sql-numeric.sql alter table rhn_schedules alter column recid type numeric(12);
alter table rhn_schedules alter column schedule_type_id type numeric(12);
alter table rhn_schedules alter column customer_id type numeric(12);
  07070100000698000081B400000000000000000000000167AE111400000123000000000000000000000000000000000000006F00000000susemanager-schema/upgrade/spacewalk-schema-1.5-to-spacewalk-schema-1.6/068-rhn_schedule_weeks.sql-numeric.sql    alter table rhn_schedule_weeks alter column recid type numeric(12);
alter table rhn_schedule_weeks alter column schedule_id type numeric(12);
alter table rhn_schedule_weeks alter column component_schedule_id type numeric(12);
alter table rhn_schedule_weeks alter column ord type numeric(3);
 07070100000699000081B400000000000000000000000167AE1114000000CC000000000000000000000000000000000000006E00000000susemanager-schema/upgrade/spacewalk-schema-1.5-to-spacewalk-schema-1.6/069-rhn_schedule_days.sql-numeric.sql alter table rhn_schedule_days alter column recid type numeric(12);
alter table rhn_schedule_days alter column schedule_id type numeric(12);
alter table rhn_schedule_days alter column ord type numeric(3);
0707010000069A000081B400000000000000000000000167AE111400000098000000000000000000000000000000000000007700000000susemanager-schema/upgrade/spacewalk-schema-1.5-to-spacewalk-schema-1.6/070-rhn_server_monitoring_info.sql-numeric.sql    alter table rhn_server_monitoring_info alter column recid type numeric(12);
alter table rhn_server_monitoring_info alter column os_id type numeric(12);
0707010000069B000081B400000000000000000000000167AE1114000000AB000000000000000000000000000000000000007600000000susemanager-schema/upgrade/spacewalk-schema-1.5-to-spacewalk-schema-1.6/071-rhn_service_probe_origins.sql-numeric.sql alter table rhn_service_probe_origins alter column service_probe_id type numeric(12);
alter table rhn_service_probe_origins alter column origin_probe_id type numeric(12);
 0707010000069C000081B400000000000000000000000167AE111400000222000000000000000000000000000000000000006B00000000susemanager-schema/upgrade/spacewalk-schema-1.5-to-spacewalk-schema-1.6/072-rhn_snmp_alert.sql-numeric.sql    alter table rhn_snmp_alert alter column recid type numeric(12);
alter table rhn_snmp_alert alter column sender_cluster_id type numeric(12);
alter table rhn_snmp_alert alter column dest_port type numeric(5);
alter table rhn_snmp_alert alter column notif_type type numeric(5);
alter table rhn_snmp_alert alter column probe_id type numeric(12);
alter table rhn_snmp_alert alter column severity type numeric(5);
alter table rhn_snmp_alert alter column command_id type numeric(12);
alter table rhn_snmp_alert alter column probe_class type numeric(5);
  0707010000069D000081B400000000000000000000000167AE11140000012F000000000000000000000000000000000000006F00000000susemanager-schema/upgrade/spacewalk-schema-1.5-to-spacewalk-schema-1.6/073-rhn_contact_groups.sql-numeric.sql    alter table rhn_contact_groups alter column customer_id type numeric(12);
alter table rhn_contact_groups alter column strategy_id type numeric(12);
alter table rhn_contact_groups alter column ack_wait type numeric(4);
alter table rhn_contact_groups alter column notification_format_id type numeric(12);
 0707010000069E000081B400000000000000000000000167AE111400000045000000000000000000000000000000000000006F00000000susemanager-schema/upgrade/spacewalk-schema-1.5-to-spacewalk-schema-1.6/074-rhn_threshold_type.sql-numeric.sql    alter table rhn_threshold_type alter column ordinal type numeric(3);
   0707010000069F000081B400000000000000000000000167AE111400000096000000000000000000000000000000000000007000000000susemanager-schema/upgrade/spacewalk-schema-1.5-to-spacewalk-schema-1.6/075-rhn_time_zone_names.sql-numeric.sql   alter table rhn_time_zone_names alter column recid type numeric(12);
alter table rhn_time_zone_names alter column gmt_offset_minutes type numeric(4);
  070701000006A0000081B400000000000000000000000167AE11140000012D000000000000000000000000000000000000006A00000000susemanager-schema/upgrade/spacewalk-schema-1.5-to-spacewalk-schema-1.6/076-rhn_url_probe.sql-numeric.sql alter table rhn_url_probe alter column probe_id type numeric(12);
alter table rhn_url_probe alter column sat_cluster_id type numeric(12);
alter table rhn_url_probe alter column scout_warning_threshold type numeric(12);
alter table rhn_url_probe alter column scout_critical_threshold type numeric(12);
   070701000006A1000081B400000000000000000000000167AE111400000294000000000000000000000000000000000000006F00000000susemanager-schema/upgrade/spacewalk-schema-1.5-to-spacewalk-schema-1.6/077-rhn_url_probe_step.sql-numeric.sql    alter table rhn_url_probe_step alter column recid type numeric(12);
alter table rhn_url_probe_step alter column url_probe_id type numeric(12);
alter table rhn_url_probe_step alter column step_number type numeric(3);
alter table rhn_url_probe_step alter column trans_warn type numeric(12);
alter table rhn_url_probe_step alter column trans_crit type numeric(12);
alter table rhn_url_probe_step alter column through_warn type numeric(12);
alter table rhn_url_probe_step alter column through_crit type numeric(12);
alter table rhn_url_probe_step alter column cookie_port type numeric(5);
alter table rhn_url_probe_step alter column cookie_maxage type numeric(9);
070701000006A2000081B400000000000000000000000167AE11140000027A000000000000000000000000000000000000007000000000susemanager-schema/upgrade/spacewalk-schema-1.5-to-spacewalk-schema-1.6/078-rhn_contact_methods.sql-numeric.sql   alter table rhn_contact_methods alter column contact_id type numeric(12);
alter table rhn_contact_methods alter column schedule_id type numeric(12);
alter table rhn_contact_methods alter column method_type_id type numeric(12);
alter table rhn_contact_methods alter column pager_type_id type numeric(12);
alter table rhn_contact_methods alter column pager_max_message_length type numeric(6);
alter table rhn_contact_methods alter column snmp_port type numeric(5);
alter table rhn_contact_methods alter column notification_format_id type numeric(12);
alter table rhn_contact_methods alter column sender_sat_cluster_id type numeric(12);
  070701000006A3000081B400000000000000000000000167AE1114000004B1000000000000000000000000000000000000006400000000susemanager-schema/upgrade/spacewalk-schema-1.5-to-spacewalk-schema-1.6/080-rhn_prepare_install.sql   
create or replace function
rhn_prepare_install
(
    username            in rhn_command_queue_instances.last_update_user%type,
    command_instance_id in out rhn_command_queue_instances.recid%type,
    install_command     in rhn_command_queue_instances.command_id%type
)
as $$
declare
    /* ignore this command if it has not been run after five minutes */
    stale_after_minutes numeric := 10;

    /* should take no more than five minutes to run the install */
    max_execution_time_seconds numeric := 10 * 60;

begin
    select nextval('rhn_command_q_inst_recid_seq')
    into command_instance_id;
    

    insert into rhn_command_queue_instances (
        recid,
        command_id,
        notes,
        expiration_date,
        notify_email,
        timeout,
        date_submitted,
        last_update_user,
        last_update_date
    )
    values (
        command_instance_id,
        install_command,
        null, /* no notes */
        current_timestamp + stale_after_minutes * '1 minute'::interval,
        null, /* no notification email */
        max_execution_time_seconds,
        current_timestamp,
        username,
        current_timestamp
    );
end; $$
language plpgsql;
   070701000006A4000081B400000000000000000000000167AE111400000221000000000000000000000000000000000000005E00000000susemanager-schema/upgrade/spacewalk-schema-1.5-to-spacewalk-schema-1.6/081-rhn_redirects.sql 
ALTER TABLE rhn_redirects drop CONSTRAINT RHN_RDRCT_RECUR_VALID;
ALTER TABLE rhn_redirects
    ADD CONSTRAINT RHN_RDRCT_RECUR_VALID
    CHECK (recurring in (0, 1));

ALTER TABLE rhn_redirects drop CONSTRAINT RHN_RDRCT_RECUR_FREQ_VALID;
ALTER TABLE rhn_redirects
    ADD CONSTRAINT RHN_RDRCT_RECUR_FREQ_VALID
    CHECK (recurring_frequency in (2,3,6));

ALTER TABLE rhn_redirects drop CONSTRAINT RHN_RDRCT_REC_DTYPE_VALID;
ALTER TABLE rhn_redirects
    ADD CONSTRAINT RHN_RDRCT_REC_DTYPE_VALID
    CHECK ( recurring_dur_type in (12,11,5,3,1) );
   070701000006A5000081B400000000000000000000000167AE111400000076000000000000000000000000000000000000006800000000susemanager-schema/upgrade/spacewalk-schema-1.5-to-spacewalk-schema-1.6/082-rhnPackageProvider-data.sql   insert into rhnPackageProvider (id, name) values
(sequence_nextval('rhn_package_provider_id_seq'), 'EPEL' );

commit;
  070701000006A6000081B400000000000000000000000167AE1114000009E9000000000000000000000000000000000000006300000000susemanager-schema/upgrade/spacewalk-schema-1.5-to-spacewalk-schema-1.6/083-rhnPackageKey-data.sql    -- Fedora 15
update rhnPackageKey set provider_id = lookup_package_provider('Fedora')
 where key_id = 'b4ebf579069c8460';
insert into rhnPackageKey (id, key_id, key_type_id, provider_id)
    (select sequence_nextval('rhn_pkey_id_seq'), 'b4ebf579069c8460', lookup_package_key_type('gpg'), lookup_package_provider('Fedora') from dual
      where 1 not in (select 1 from rhnPackageKey where key_id = 'b4ebf579069c8460'));

-- CentOS 6
update rhnPackageKey set provider_id = lookup_package_provider('CentOS')
 where key_id = '0946fca2c105b9de';
insert into rhnPackageKey (id, key_id, key_type_id, provider_id)
    (select sequence_nextval('rhn_pkey_id_seq'), '0946fca2c105b9de', lookup_package_key_type('gpg'), lookup_package_provider('CentOS') from dual
    where 1 not in (select 1 from rhnPackageKey where key_id = '0946fca2c105b9de'));

-- Scientific Linux 6
update rhnPackageKey set provider_id = lookup_package_provider('Scientific Linux')
 where key_id = '915d75e09b1fd350';
insert into rhnPackageKey (id, key_id, key_type_id, provider_id)
    (select sequence_nextval('rhn_pkey_id_seq'), '915d75e09b1fd350', lookup_package_key_type('gpg'), lookup_package_provider('Scientific Linux') from dual
    where 1 not in (select 1 from rhnPackageKey where key_id = '915d75e09b1fd350'));
update rhnPackageKey set provider_id = lookup_package_provider('Scientific Linux')
 where key_id = 'b0b4183f192a7d7d';
insert into rhnPackageKey (id, key_id, key_type_id, provider_id)
    (select sequence_nextval('rhn_pkey_id_seq'), 'b0b4183f192a7d7d', lookup_package_key_type('gpg'), lookup_package_provider('Scientific Linux') from dual
    where 1 not in (select 1 from rhnPackageKey where key_id = 'b0b4183f192a7d7d'));

-- EPEL 5
update rhnPackageKey set provider_id = lookup_package_provider('EPEL')
 where key_id = '119cc036217521f6';
insert into rhnPackageKey (id, key_id, key_type_id, provider_id)
    (select sequence_nextval('rhn_pkey_id_seq'), '119cc036217521f6', lookup_package_key_type('gpg'), lookup_package_provider('EPEL') from dual
    where 1 not in (select 1 from rhnPackageKey where key_id = '119cc036217521f6'));
-- EPEL 6
update rhnPackageKey set provider_id = lookup_package_provider('EPEL')
 where key_id = '3b49df2a0608b895';
insert into rhnPackageKey (id, key_id, key_type_id, provider_id)
    (select sequence_nextval('rhn_pkey_id_seq'), '3b49df2a0608b895', lookup_package_key_type('gpg'), lookup_package_provider('EPEL') from dual
    where 1 not in (select 1 from rhnPackageKey where key_id = '3b49df2a0608b895'));

commit;
   070701000006A7000081B400000000000000000000000167AE1114000002E4000000000000000000000000000000000000005F00000000susemanager-schema/upgrade/spacewalk-schema-1.5-to-spacewalk-schema-1.6/085-rhn_server.pkb.sql    
--update pg_setting
update pg_settings set setting = 'rhn_server,' || setting where name = 'search_path';

    create or replace function update_needed_cache(
        server_id_in in numeric
	) returns void as $$
    begin
        delete from rhnServerNeededCache
         where server_id = server_id_in;
        insert into rhnServerNeededCache
               (server_id, errata_id, package_id)
               (select distinct server_id, errata_id, package_id
                  from rhnServerNeededView
                 where server_id = server_id_in);
	end$$ language plpgsql;

-- restore the original setting
update pg_settings set setting = overlay( setting placing '' from 1 for (length('rhn_server')+1) ) where name = 'search_path';
070701000006A8000081B400000000000000000000000167AE111400010D9D000000000000000000000000000000000000006100000000susemanager-schema/upgrade/spacewalk-schema-1.5-to-spacewalk-schema-1.6/090-rhn_entitlements.sql  
-- create schema rhn_entitlements;

-- setup search_path so that these functions are created in appropriate schema.
update pg_settings set setting = 'rhn_entitlements,' || setting where name = 'search_path';

   create or replace function find_compatible_sg (
      server_id_in in numeric,
      type_label_in in varchar
   )
   returns numeric
as $$
    declare
      servergroups cursor for
         select sg.id
           from rhnServerGroupType             sgt,
                rhnServerGroup                 sg,
                rhnServer                     s,
                rhnServerServerGroupArchCompat ssgac
          where s.id = server_id_in
            and s.org_id = sg.org_id
            and sgt.label = type_label_in
            and sg.group_type = sgt.id
            and ssgac.server_group_type = sgt.id
            and ssgac.server_arch_id = s.server_arch_id
            and not exists (
                     select 1
                      from rhnServerGroupMembers sgm
                     where sgm.server_group_id = sg.id
                       and sgm.server_id = s.id);


   begin
      for servergroup in servergroups loop
         return servergroup.id;
      end loop;

      --no servergroup found
      return NULL;
   end$$
language plpgsql;

    -- *******************************************************************
    -- PROCEDURE: remove_org_entitlements
    --
    -- Removes both system entitlements and channel subscriptions
    -- that are currently assigned to an org and re-assigns to the
    -- master org (org_id = 1).
    --
    -- When we call this we expect everything to already be unentitled
    -- which shoul be handled by delete_org.
    --
    -- Called by: delete_org
    -- *******************************************************************
    create or replace function remove_org_entitlements (
        org_id_in numeric
    ) returns void
as $$
    declare
        system_ents cursor for
        select sg.id, sg.max_members, sg.group_type
        from rhnServerGroup sg
        where group_type is not null
          and org_id = org_id_in;

        channel_subs cursor for
        select pcf.channel_family_id, pcf.max_members
        from rhnChannelFamily cf,
             rhnPrivateChannelFamily pcf
        where pcf.org_id = org_id_in
          and pcf.channel_family_id = cf.id
          and cf.org_id is null;

    begin

        for system_ent in system_ents loop
            update rhnServerGroup
            set max_members = max_members + system_ent.max_members
            where org_id = 1
              and group_type = system_ent.group_type;
        end loop;

        update rhnServerGroup
        set max_members = 0
        where org_id = org_id_in;

        for channel_sub in channel_subs loop
            update rhnPrivateChannelFamily
            set max_members = max_members + channel_sub.max_members
            where org_id = 1
              and channel_family_id = channel_sub.channel_family_id;
        end loop;

        update rhnPrivateChannelFamily
        set max_members = 0
        where org_id = org_id_in;

    end$$
language plpgsql;

    create or replace function entitlement_grants_service (
        entitlement_in in varchar,
        service_level_in in varchar
    ) returns numeric
as $$
    begin
        if service_level_in = 'provisioning' then
            if entitlement_in = 'provisioning_entitled' then
                return 1;
            else
                return 0;
            end if;
        elsif service_level_in = 'management' then
            if entitlement_in = 'enterprise_entitled' then
                return 1;
            else
                return 0;
            end if;
        elsif service_level_in = 'monitoring' then
            if entitlement_in = 'monitoring_entitled' then
                return 1;
            end if;
        elsif service_level_in = 'updates' then
            return 1;
        else
            return 0;
        end if;
    end$$
language plpgsql;

    create or replace function lookup_entitlement_group (
        org_id_in in numeric,
        type_label_in in varchar default 'sw_mgr_entitled'
    ) returns numeric
as $$
    declare
        server_groups cursor for
            select  sg.id               server_group_id
            from    rhnServerGroup      sg,
                    rhnServerGroupType  sgt
            where   sgt.label = type_label_in
                and sgt.id = sg.group_type
                and sg.org_id = org_id_in;
    begin
        for sg in server_groups loop
            return sg.server_group_id;
        end loop;
        return rhn_entitlements.create_entitlement_group(
                org_id_in,
                type_label_in
            );
    end$$
language plpgsql;

    create or replace function create_entitlement_group (
        org_id_in in numeric,
        type_label_in in varchar default 'sw_mgr_entitled'
    ) returns numeric
as $$
    declare
        sg_id_val numeric;
    begin
        select  nextval('rhn_server_group_id_seq')
        into    sg_id_val;

        insert into rhnServerGroup (
                id, name, description, max_members, current_members,
                group_type, org_id
            ) (
                select  sg_id_val, sgt.label, sgt.label,
                        0, 0, sgt.id, org_id_in
                from    rhnServerGroupType sgt
                where   sgt.label = type_label_in
            );

        return sg_id_val;
    end$$
language plpgsql;

   create or replace function can_entitle_server (
      server_id_in   in numeric,
      type_label_in  in varchar
   )
   returns numeric
as $$
    declare
      addon_servergroups cursor (base_label_in varchar,
                                 addon_label_in varchar) for
         select
            addon_id
         from
            rhnSGTypeBaseAddonCompat
         where base_id = lookup_sg_type (base_label_in)
           and addon_id = lookup_sg_type (addon_label_in);

      previous_ent        varchar[];
      is_base_in          char   := 'N';
      is_base_current     char   := 'N';
      i                   numeric := 0;
      sgid                numeric := 0;

   begin

      previous_ent := rhn_entitlements.get_server_entitlement(server_id_in);

      select distinct is_base
      into is_base_in
      from rhnServerGroupType
      where label = type_label_in;

      if array_upper(previous_ent, 1) is null or array_upper(previous_ent, 1) = 0 then
         if is_base_in = 'Y' then
            sgid := rhn_entitlements.find_compatible_sg (server_id_in, type_label_in);
            if sgid is not null then
              -- rhn_server.insert_into_servergroup (server_id_in, sgid);
              return 1;
            else
              -- rhn_exception.raise_exception ('invalid_base_entitlement');
              return 0;
            end if;
         else
            -- rhn_exception.raise_exception ('invalid_base_entitlement');
            return 0;
         end if;

      -- there are previous ents, first make sure we're not trying to entitle a base ent
      elsif is_base_in = 'Y' then
         -- rhn_exception.raise_exception ('invalid_addon_entitlement');
         return 0;

      -- it must be an addon, so proceed with the entitlement
      else

         -- find the servers base ent
         is_base_current := 'N';
         i := 0;
         while is_base_current = 'N' and i < array_upper(previous_ent, 1)
         loop
            i := i + 1;
            select is_base
            into is_base_current
            from rhnServerGroupType
            where label = previous_ent[i];
         end loop;

         -- never found a base ent, that would be strange
         if is_base_current  = 'N' then
            -- rhn_exception.raise_exception ('invalid_base_entitlement');
            return 0;
         end if;

         -- this for loop verifies the validity of the addon path
         for addon_servergroup in addon_servergroups  (previous_ent[i], type_label_in) loop
            -- find an appropriate sgid for the addon and entitle the server
            sgid := rhn_entitlements.find_compatible_sg (server_id_in, type_label_in);
            if sgid is not null then
               -- rhn_server.insert_into_servergroup (server_id_in, sgid);
               return 1;
            else
               -- rhn_exception.raise_exception ('invalid_addon_entitlement');
               return 0;
            end if;
         end loop;

      end if;

      return 0;

   end$$
language plpgsql;

   create or replace function can_switch_base (
      server_id_in   in    integer,
      type_label_in  in    varchar
   )
   returns numeric
as $$
   declare
      type_label_in_is_base   char(1);
      sgid                    numeric;

   begin

       select is_base into type_label_in_is_base
       from rhnServerGroupType
       where label = type_label_in;

       if not found then
          perform rhn_exception.raise_exception ( 'invalid_entitlement' );
       end if;

      if type_label_in_is_base = 'N' then
         perform rhn_exception.raise_exception ( 'invalid_entitlement' );
      else
         sgid := rhn_entitlements.find_compatible_sg ( server_id_in,
                                                       type_label_in );
         if sgid is not null then
           return 1;
         else
           return 0;
         end if;
      end if;

   end$$
language plpgsql;

    create or replace function entitle_server (
        server_id_in in numeric,
        type_label_in in varchar default 'sw_mgr_entitled'
    ) returns void
as $$
    declare
      sgid  numeric := 0;
      is_virt numeric := 0;

    begin

      select 1 into is_virt
        from rhnServerEntitlementView
        where server_id = server_id_in
          and label in ('virtualization_host', 'virtualization_host_platform');

      if not found then
          is_virt := 0;
      end if;

      if is_virt = 0 and (type_label_in = 'virtualization_host' or
                          type_label_in = 'virtualization_host_platform') then

        is_virt := 1;
      end if;

      if rhn_entitlements.can_entitle_server(server_id_in,
                                             type_label_in) = 1 then
         sgid := rhn_entitlements.find_compatible_sg (server_id_in,
                                                      type_label_in);
         if sgid is not null then
            insert into rhnServerHistory ( id, server_id, summary, details )
            values ( nextval('rhn_event_id_seq'), server_id_in,
                     'added system entitlement ',
                      case type_label_in
                       when 'enterprise_entitled' then 'Management'
                       when 'sw_mgr_entitled' then 'Update'
                       when 'provisioning_entitled' then 'Provisioning'
                       when 'monitoring_entitled' then 'Monitoring'
                       when 'virtualization_host' then 'Virtualization'
                       when 'virtualization_host_platform' then
                            'Virtualization Platform' end  );

            perform rhn_server.insert_into_servergroup (server_id_in, sgid);

            if is_virt = 1 then
              perform rhn_entitlements.repoll_virt_guest_entitlements(server_id_in);
            end if;

         else
            perform rhn_exception.raise_exception ('no_available_server_group');
         end if;
      else
         perform rhn_exception.raise_exception ('invalid_entitlement');
      end if;
   end$$
language plpgsql;

    create or replace function remove_server_entitlement (
        server_id_in in numeric,
        type_label_in in varchar default 'sw_mgr_entitled',
        repoll_virt_guests in numeric default 1
    ) returns void
as $$
    declare
      group_id numeric;
      type_is_base char;
      is_virt numeric := 0;
    begin
      -- would be nice if there were a virt attribute of entitlement types, not have to specify 2 different ones...
        select 1 into is_virt
          from rhnServerEntitlementView
          where server_id = server_id_in
            and label in ('virtualization_host', 'virtualization_host_platform');
        if not found then
            is_virt := 0;
        end if;

        select  sg.id, sgt.is_base
        into group_id, type_is_base
        from    rhnServerGroupType sgt,
            rhnServerGroup sg,
                rhnServerGroupMembers sgm,
                rhnServer s
        where   s.id = server_id_in
            and s.id = sgm.server_id
            and sgm.server_group_id = sg.id
            and sg.org_id = s.org_id
            and sgt.label = type_label_in
            and sgt.id = sg.group_type;

        if not found then
          perform rhn_exception.raise_exception('invalid_server_group_member');
        end if;

      if ( type_is_base = 'Y' ) then
         -- unentitle_server should handle everything, don't really need to do anything else special here
         perform rhn_entitlements.unentitle_server ( server_id_in );
      else

         insert into rhnServerHistory ( id, server_id, summary, details )
         values ( nextval('rhn_event_id_seq'), server_id_in,
                  'removed system entitlement ',
                   case type_label_in
                    when 'enterprise_entitled' then 'Management'
                    when 'sw_mgr_entitled' then 'Update'
                    when 'provisioning_entitled' then 'Provisioning'
                    when 'monitoring_entitled' then 'Monitoring'
                    when 'virtualization_host' then 'Virtualization'
                    when 'virtualization_host_platform' then
                         'Virtualization Platforrm' end  );

         perform rhn_server.delete_from_servergroup(server_id_in, group_id);

         -- special case: clean up related monitoring data
         if type_label_in = 'monitoring_entitled' then
           DELETE
             FROM state_change
            WHERE o_id IN (SELECT probe_id::varchar
                             FROM rhn_check_probe
                            WHERE host_id = server_id_in);
           DELETE
             FROM time_series
            WHERE substring(o_id FROM position('-' IN o_id) + 1
                            FOR position('-' IN substring(o_id FROM position('-' IN o_id) + 1)) - 1)
              IN (SELECT probe_id::text
                    FROM rhn_check_probe
                   WHERE host_id = server_id_in);
           DELETE
             FROM rhn_probe
            WHERE recid IN (SELECT probe_id
                              FROM rhn_check_probe
                             WHERE host_id = server_id_in);
         end if;

         if is_virt = 1 and repoll_virt_guests = 1 then
           perform rhn_entitlements.repoll_virt_guest_entitlements(server_id_in);
         end if;
      end if;

    end$$
language plpgsql;

    create or replace function unentitle_server (
        server_id_in in numeric
    ) returns void
as $$
    declare
      servergroups cursor for
         select distinct sgt.label, sg.id server_group_id
         from  rhnServerGroupType sgt,
               rhnServerGroup sg,
               rhnServer s,
               rhnServerGroupMembers sgm
         where s.id = server_id_in
            and s.org_id = sg.org_id
            and sg.group_type = sgt.id
            and sgm.server_group_id = sg.id
            and sgm.server_id = s.id;

     is_virt numeric := 0;

   begin

      select 1 into is_virt
        from rhnServerEntitlementView
        where server_id = server_id_in
         and label in ('virtualization_host', 'virtualization_host_platform');

      if not found then
          is_virt := 0;
      end if;

      for servergroup in servergroups loop

         insert into rhnServerHistory ( id, server_id, summary, details )
         values ( nextval('rhn_event_id_seq'), server_id_in,
                  'removed system entitlement ',
                   case servergroup.label
                    when 'enterprise_entitled' then 'Management'
                    when 'sw_mgr_entitled' then 'Update'
                    when 'provisioning_entitled' then 'Provisioning'
                    when 'monitoring_entitled' then 'Monitoring'
                    when 'virtualization_host' then 'Virtualization'
                    when 'virtualization_host_platform' then
                         'Virtualization Platform' end  );

         perform rhn_server.delete_from_servergroup(server_id_in,
                                            servergroup.server_group_id );
      end loop;

      if is_virt = 1 then
        perform rhn_entitlements.repoll_virt_guest_entitlements(server_id_in);
      end if;

   end$$
language plpgsql;


    -- *******************************************************************
    -- PROCEDURE: repoll_virt_guest_entitlements
    --
    --   Whenever we add/remove a virtualization_host* entitlement from
    --   a host, we can call this procedure to update what type of slots
    --   the guests are consuming.
    --
    --   If you're removing the entitlement, it's
    --   possible the guests will become unentitled if you don't have enough
    --   physical slots to cover them.
    --
    --   If you're adding the entitlement, you end up freeing up physical
    --   slots for other systems.
    --
    -- *******************************************************************
    create or replace function repoll_virt_guest_entitlements(
        server_id_in in numeric
    ) returns void
as $$
    declare
        -- All channel families associated with the guests of server_id_in
        families cursor for
            select distinct cfs.channel_family_id
            from
                rhnChannelFamilyServers cfs,
                rhnVirtualInstance vi
            where
                vi.host_system_id = server_id_in
                and vi.virtual_system_id = cfs.server_id;

        -- All of server group types associated with the guests of
        -- server_id_in
        group_types cursor for
            select distinct sg.group_type, sgt.label
            from
                rhnServerGroupType sgt,
                rhnServerGroup sg,
                rhnServerGroupMembers sgm,
                rhnVirtualInstance vi
            where
                vi.host_system_id = server_id_in
                and vi.virtual_system_id = sgm.server_id
                and sgm.server_group_id = sg.id
                and sg.group_type = sgt.id;

        -- Virtual servers from a certain family belonging to a specific
        -- host that are consuming physical channel slots over the limit.
        virt_servers_cfam cursor(family_id_in numeric, quantity_in numeric) for
                select vi.virtual_system_id
                from
                    rhnChannelFamilyMembers cfm,
                    rhnServerChannel sc,
                    rhnVirtualInstance vi
                where
                    vi.host_system_id = server_id_in
                    and vi.virtual_system_id = sc.server_id
                    and sc.channel_id = cfm.channel_id
                    and cfm.channel_family_id = family_id_in
                order by sc.modified desc
                limit quantity_in;

        -- Virtual servers from a certain family belonging to a specific
        -- host that are consuming physical system slots over the limit.
        virt_servers_sgt cursor(group_type_in numeric, quantity_in numeric) for
                select vi.virtual_system_id
                from
                    rhnServerGroup sg,
                    rhnServerGroupMembers sgm,
                    rhnVirtualInstance vi
                where
                    vi.host_system_id = server_id_in
                    and vi.virtual_system_id = sgm.server_id
                    and sgm.server_group_id = sg.id
                    and sg.group_type = group_type_in
                order by sgm.modified desc
                limit quantity_in;

        -- Get the orgs of Virtual guests
        -- Since they may belong to different orgs
        virt_guest_orgs cursor for
                select  distinct (s.org_id)
                from rhnServer s
                    inner join  rhnVirtualInstance vi on vi.virtual_system_id = s.id
                where
                    vi.host_system_id = server_id_in
                    and s.org_id <> (select s1.org_id from rhnServer s1 where s1.id = vi.host_system_id) ;

        org_id_val numeric;
        max_members_val numeric;
        max_flex_val numeric;
        current_members_calc numeric;
        sg_id numeric;
        is_virt numeric := 0;
    begin
          select 1 into is_virt
                from rhnServerEntitlementView
           where server_id = server_id_in
                 and label in ('virtualization_host', 'virtualization_host_platform');

      if not found then
          is_virt := 0;
      end if;

        select org_id
        into org_id_val
        from rhnServer
        where id = server_id_in;

        -- deal w/ channel entitlements first ...
        for family in families loop
            if is_virt = 0 then
            -- if the host_server does not have virt
            --- find all possible flex slots
            -- and set each of the flex eligible guests to Y
                UPDATE rhnServerChannel sc set is_fve = 'Y'
                where sc.server_id in (
                            select vi.virtual_system_id
                            from rhnServerFveCapable sfc
                                inner join rhnVirtualInstance vi on vi.virtual_system_id = sfc.server_id
                            where vi.host_system_id = server_id_in
                                  and sfc.channel_family_id = family.channel_family_id
                              order by vi.modified desc
                            limit free_slots
                );
            else
            -- if the host_server has virt
            -- set all its flex guests to N
                UPDATE rhnServerChannel sc set is_fve = 'N'
                where
                    sc.channel_id in (select cfm.channel_id from rhnChannelFamilyMembers cfm
                                      where cfm.CHANNEL_FAMILY_ID = family.channel_family_id)
                    and sc.is_fve = 'Y'
                    and sc.server_id in
                            (select vi.virtual_system_id  from rhnVirtualInstance vi
                                    where vi.host_system_id = server_id_in);
            end if;

            -- get the current (physical) members of the family
            current_members_calc :=
                rhn_channel.channel_family_current_members(family.channel_family_id,
                                                           org_id_val); -- fixed transposed args

            -- get the max members of the family
            select max_members
            into max_members_val
            from rhnPrivateChannelFamily
            where channel_family_id = family.channel_family_id
            and org_id = org_id_val;

            select fve_max_members
            into max_flex_val
            from rhnPrivateChannelFamily
            where channel_family_id = family.channel_family_id
            and org_id = org_id_val;

            if current_members_calc > max_members_val then
                -- A virtualization_host* ent must have been removed, so we'll
                -- unsubscribe guests from the host first.

                -- hm, i don't think max_members - current_members_calc yielding a negative number
                -- will work w/ rownum, swaping 'em in the body of this if...
                for virt_server in virt_servers_cfam(family.channel_family_id,
                                current_members_calc - max_members_val) loop

                    perform rhn_channel.unsubscribe_server_from_family(
                                virt_server.virtual_system_id,
                                family.channel_family_id);
                end loop;

                -- if we're still over the limit, which would be odd,
                -- just prune the group to max_members
                --
                -- er... wouldn't we actually have to refresh the values of
                -- current_members_calc and max_members_val to actually ever
                -- *skip this??
                if current_members_calc > max_members_val then
                    -- argh, transposed again?!
                    perform rhn_entitlements.set_family_count(org_id_val,
                                     family.channel_family_id,
                                     max_members_val, max_flex_val);
                    --TODO calculate this correctly
                end if;

           end if;

            -- update current_members for the family.  This will set the value
            -- to reflect adding/removing the entitlement.
            --
            -- what's the difference of doing this vs the unavoidable set_family_count above?
            perform rhn_channel.update_family_counts(family.channel_family_id,
                                             org_id_val);

            -- It is possible that the guests belong  to a different org than the host
            -- so we are going to update the family counts in the guests orgs also
            for org in virt_guest_orgs loop
                    perform rhn_channel.update_family_counts(family.channel_family_id,
                                             org.org_id);
            end loop;
        end loop;

        for a_group_type in group_types loop
          -- get the current *physical* members of the system entitlement type for the org...
          --
          -- unlike channel families, it appears the standard rhnServerGroup.max_members represents
          -- *physical* slots, vs physical+virt ... boy that's confusing...

          select max_members, id
            into max_members_val, sg_id
            from rhnServerGroup
            where group_type = a_group_type.group_type
            and org_id = org_id_val;


      select count(sep.server_id) into current_members_calc
            from rhnServerEntitlementPhysical sep
           where sep.server_group_id = sg_id
             and sep.server_group_type_id = a_group_type.group_type;

          if current_members_calc > max_members_val then
            -- A virtualization_host* ent must have been removed, and we're over the limit, so unsubscribe guests
            for virt_server in virt_servers_sgt(a_group_type.group_type,
                                                current_members_calc - max_members_val) loop
              perform rhn_entitlements.remove_server_entitlement(virt_server.virtual_system_id, a_group_type.label);

              -- decrement current_members_calc, we'll use it to reset current_members for the group at the end...
              current_members_calc := current_members_calc - 1;
            end loop;

          end if;

          update rhnServerGroup set current_members = current_members_calc
           where org_id = org_id_val
             and group_type = a_group_type.group_type;

          -- I think that's all the house-keeping we have to do...
        end loop;

    end$$
language plpgsql;

    create or replace function get_server_entitlement (
        server_id_in in numeric
    ) returns varchar[]
as $$
    declare
        server_groups cursor for
            select  sgt.label
            from    rhnServerGroupType      sgt,
                    rhnServerGroup          sg,
                    rhnServerGroupMembers   sgm
            where   1=1
                and sgm.server_id = server_id_in
                and sg.id = sgm.server_group_id
                and sgt.id = sg.group_type
                and sgt.label in (
                    'sw_mgr_entitled','enterprise_entitled',
                    'provisioning_entitled', 'nonlinux_entitled',
                    'monitoring_entitled', 'virtualization_host',
                                        'virtualization_host_platform'
                    );

         ent_array varchar[];

    begin

      ent_array := '{}';

      for sg in server_groups loop
         ent_array := ent_array || sg.label;
      end loop;

      return ent_array;

    end$$
language plpgsql;

    -- this desperately needs to be table driven.
    create or replace function modify_org_service (
        org_id_in in numeric,
        service_label_in in varchar,
        enable_in in char
    ) returns void
as $$
    declare
        roles_to_process varchar[];
        roles cursor(role_label_in varchar) for
            select  label, id
            from    rhnUserGroupType
            where   label = role_label_in;
        org_roles cursor(role_label_in varchar) for
            select  1
            from    rhnUserGroup ug,
                    rhnUserGroupType ugt
            where   ugt.label = role_label_in
                and ug.org_id = org_id_in
                and ugt.id = ug.group_type;

        ents_to_process varchar[];
        ents cursor(ent_label_in varchar) for
            select  label, id
            from    rhnOrgEntitlementType
            where   label = ent_label_in;
        org_ents cursor(ent_label_in varchar) for
            select  1
            from    rhnOrgEntitlements oe,
                    rhnOrgEntitlementType oet
            where   oet.label = ent_label_in
                and oe.org_id = org_id_in
                and oet.id = oe.entitlement_id;
        create_row char(1);
    begin
        ents_to_process := '{}';
        roles_to_process := '{}';
        -- a bit kludgy, but only for 3.4 really.  Certainly no
        -- worse than the old code...
        if service_label_in = 'enterprise' or
           service_label_in = 'management' then
            ents_to_process := array_append(ents_to_process, 'sw_mgr_enterprise');

            roles_to_process := array_append(roles_to_process, 'org_admin');

            roles_to_process := array_append(roles_to_process, 'system_group_admin');

            roles_to_process := array_append(roles_to_process, 'activation_key_admin');

            roles_to_process := array_append(roles_to_process, 'org_applicant');
        elsif service_label_in = 'provisioning' then
            ents_to_process := array_append(ents_to_process, 'rhn_provisioning');

            roles_to_process := array_append(roles_to_process, 'system_group_admin');

            roles_to_process := array_append(roles_to_process, 'activation_key_admin');

            roles_to_process := array_append(roles_to_process, 'config_admin');
            -- another nasty special case...
            if enable_in = 'Y' then
                ents_to_process := array_append(ents_to_process, 'sw_mgr_enterprise');
            end if;
        elsif service_label_in = 'monitoring' then
            ents_to_process := array_append(ents_to_process, 'rhn_monitor');

            roles_to_process := array_append(roles_to_process, 'monitoring_admin');
        elsif service_label_in = 'virtualization' then
            ents_to_process := array_append(ents_to_process, 'rhn_virtualization');

            roles_to_process := array_append(roles_to_process, 'config_admin');
        elsif service_label_in = 'virtualization_platform' then
            ents_to_process := array_append(ents_to_process, 'rhn_virtualization_platform');
            roles_to_process := array_append(roles_to_process, 'config_admin');
    elsif service_label_in = 'nonlinux' then
            ents_to_process := array_append(ents_to_process, 'rhn_nonlinux');
            roles_to_process := array_append(roles_to_process, 'config_admin');
        end if;

        if enable_in = 'Y' then
            for i in 1..array_upper(ents_to_process, 1) loop
                for ent in ents(ents_to_process[i]) loop
                    create_row := 'Y';
                    for oe in org_ents(ent.label) loop
                        create_row := 'N';
                    end loop;
                    if create_row = 'Y' then
                        insert into rhnOrgEntitlements(org_id, entitlement_id)
                            values (org_id_in, ent.id);
                    end if;
                end loop;
            end loop;
            for i in 1..array_upper(roles_to_process, 1) loop
                for role in roles(roles_to_process[i]) loop
                    create_row := 'Y';
                    for o_r in org_roles(role.label) loop
                        create_row := 'N';
                    end loop;
                    if create_row = 'Y' then
                        insert into rhnUserGroup(
                                id, name, description, current_members,
                                group_type, org_id
                            ) (
                                select  nextval('rhn_user_group_id_seq'),
                                        ugt.name || 's',
                                        ugt.name || 's for Org ' ||
                                            o.name || ' ('|| o.id ||')',
                                        0, ugt.id, o.id
                                from    rhnUserGroupType ugt,
                                        web_customer o
                                where   o.id = org_id_in
                                    and ugt.id = role.id
                            );
                    end if;
                end loop;
            end loop;
        else
            for i in 1..coalesce(array_upper(ents_to_process, 1), 0) loop
                for ent in ents(ents_to_process[i]) loop
                    delete from rhnOrgEntitlements
                     where org_id = org_id_in
                       and entitlement_id = ent.id;
                end loop;
            end loop;
        end if;
    end$$
language plpgsql;

    create or replace function set_customer_enterprise (
        customer_id_in in numeric
    ) returns void
as $$
    begin
        perform rhn_entitlements.modify_org_service(customer_id_in, 'enterprise', 'Y');
    end$$
language plpgsql;

    create or replace function set_customer_provisioning (
        customer_id_in in numeric
    ) returns void
as $$
    begin
        perform rhn_entitlements.modify_org_service(customer_id_in, 'provisioning', 'Y');
    end$$
language plpgsql;

    create or replace function set_customer_monitoring (
        customer_id_in in numeric
    ) returns void
as $$
    begin
        perform rhn_entitlements.modify_org_service(customer_id_in, 'monitoring', 'Y');
    end$$
language plpgsql;

    create or replace function set_customer_nonlinux (
        customer_id_in in numeric
    ) returns void
as $$
    begin
        perform rhn_entitlements.modify_org_service(customer_id_in, 'nonlinux', 'Y');
    end$$
language plpgsql;

    create or replace function unset_customer_enterprise (
        customer_id_in in numeric
    ) returns void
as $$
    begin
        perform rhn_entitlements.modify_org_service(customer_id_in, 'enterprise', 'N');
    end$$
language plpgsql;

    create or replace function unset_customer_provisioning (
        customer_id_in in numeric
    ) returns void
as $$
    begin
        perform rhn_entitlements.modify_org_service(customer_id_in, 'provisioning', 'N');
    end$$
language plpgsql;

    create or replace function unset_customer_monitoring (
        customer_id_in in numeric
    ) returns void
as $$
    begin
        perform rhn_entitlements.modify_org_service(customer_id_in, 'monitoring', 'N');
    end$$
language plpgsql;

    create or replace function unset_customer_nonlinux (
        customer_id_in in numeric
    ) returns void
as $$
    begin
        perform rhn_entitlements.modify_org_service(customer_id_in, 'nonlinux', 'N');
    end$$
language plpgsql;

    -- *******************************************************************
    -- PROCEDURE: prune_group
    -- Unsubscribes servers consuming physical slots that over the org's
    --   limit.
    -- Called by: set_group_count, repoll_virt_guest_entitlements
    -- *******************************************************************
    create or replace function prune_group (
        group_id_in in numeric,
        type_in in char,
        quantity_in in numeric,
        update_family_countsYN in numeric default 1
    ) returns void
as $$
    declare
        ugrecord record;
        sgrecord record;
      type_is_base char;
    begin
        if type_in = 'U' then
            update      rhnUserGroup
                set     max_members = quantity_in
                where   id = group_id_in;

            for ugrecord in (
		    select  user_id, user_group_id, ugt.label
		    from    rhnUserGroupType    ugt,
			    rhnUserGroup        ug,
			    rhnUserGroupMembers ugm
		    where   1=1
			and ugm.user_group_id = group_id_in
			and ugm.user_id in (
				    select  user_id
				    from    rhnUserGroupMembers
				    where   user_group_id = group_id_in
				    order by modified asc
				    offset quantity_in
				)
			and ugm.user_group_id = ug.id
			and ug.group_type = ugt.id
	    ) loop
                perform rhn_user.remove_from_usergroup(ugrecord.user_id, ugrecord.user_group_id);
            end loop;
        elsif type_in = 'S' then
            update      rhnServerGroup
                set     max_members = quantity_in
                where   id = group_id_in;

            for sgrecord in (
		   select  server_id, server_group_id, sgt.id as group_type_id, sgt.label
		    from    rhnServerGroupType              sgt,
				    rhnServerGroup                  sg,
				    rhnServerGroupMembers   sgm
		    where   1=1
			    and sgm.server_group_id = group_id_in
			    and sgm.server_id in (
				    select  sep.server_id
				    from
					rhnServerEntitlementPhysical sep
				    where
					sep.server_group_id = group_id_in
				    order by sep.modified asc
				    offset quantity_in
				)
			    and sgm.server_group_id = sg.id
			    and sg.group_type = sgt.id
	    ) loop
                perform rhn_entitlements.remove_server_entitlement(sgrecord.server_id, sgrecord.label);

            select is_base
            into type_is_base
            from rhnServerGroupType sgt
            where sgt.id = sgrecord.group_type_id;

            -- if we're removing a base ent, then be sure to
            -- remove the server's channel subscriptions.
            if ( type_is_base = 'Y' ) then
                   perform rhn_channel.clear_subscriptions(sgrecord.server_id, 0, update_family_countsYN);
            end if;

            end loop;
        end if;
    end$$
language plpgsql;

    -- *******************************************************************
    -- PROCEDURE: assign_system_entitlement
    --
    -- Moves system entitlements from from_org_id_in to to_org_id_in.
    -- Can raise not_enough_entitlements_in_base_org if from_org_id_in
    -- does not have enough entitlements to cover the move.
    -- Takes care of unentitling systems if necessary by calling
    -- set_group_count
    -- *******************************************************************
    create or replace function assign_system_entitlement(
        group_label_in in varchar,
        from_org_id_in in numeric,
        to_org_id_in in numeric,
        quantity_in in numeric
    ) returns void
as $$
    declare
        prev_ent_count numeric;
    to_org_prev_ent_count numeric;
        new_ent_count numeric;
    new_quantity numeric;
        group_type numeric;
    begin

            select max_members
            into prev_ent_count
            from rhnServerGroupType sgt,
                 rhnServerGroup sg
            where sg.org_id = from_org_id_in
              and sg.group_type = sgt.id
              and sgt.label = group_label_in;

            if not found then
                perform rhn_exception.raise_exception(
                              'not_enough_entitlements_in_base_org');
            end if;

            select max_members
            into to_org_prev_ent_count
            from rhnServerGroupType sgt,
                 rhnServerGroup sg
            where sg.org_id = to_org_id_in
              and sg.group_type = sgt.id
              and sgt.label = group_label_in;

            if not found then
                to_org_prev_ent_count := 0;
            end if;

            select id
            into group_type
            from rhnServerGroupType
            where label = group_label_in;

            if not found then
                perform rhn_exception.raise_exception(
                              'invalid_server_group');
            end if;

        new_ent_count := prev_ent_count - quantity_in;

        if prev_ent_count > new_ent_count then
            new_quantity := to_org_prev_ent_count + quantity_in;
        end if;

        if new_ent_count < 0 then
            perform rhn_exception.raise_exception(
                          'not_enough_entitlements_in_base_org');
        end if;


        perform rhn_entitlements.set_group_count(from_org_id_in,
                                         'S',
                                         group_type,
                                         new_ent_count);

        perform rhn_entitlements.set_group_count(to_org_id_in,
                                         'S',
                                         group_type,
                                         new_quantity);

        -- Create or delete the entries in rhnOrgEntitlementType
        if group_label_in = 'enterprise_entitled' then
            if new_quantity > 0 then
                perform rhn_entitlements.set_customer_enterprise(to_org_id_in);
            else
                perform rhn_entitlements.unset_customer_enterprise(to_org_id_in);
            end if;
        end if;

        if group_label_in = 'provisioning_entitled' then
            if new_quantity > 0 then
                perform rhn_entitlements.set_customer_provisioning(to_org_id_in);
            else
                perform rhn_entitlements.unset_customer_provisioning(to_org_id_in);
            end if;
        end if;

        if group_label_in = 'monitoring_entitled' then
            if new_quantity > 0 then
                perform rhn_entitlements.set_customer_monitoring(to_org_id_in);
            else
                perform rhn_entitlements.unset_customer_monitoring(to_org_id_in);
            end if;
        end if;

    end$$
language plpgsql;

    -- *******************************************************************
    -- PROCEDURE: assign_channel_entitlement
    --
    -- Moves channel entitlements from from_org_id_in to to_org_id_in.
    -- Can raise not_enough_entitlements_in_base_org if from_org_id_in
    -- does not have enough entitlements to cover the move.
    -- Takes care of unentitling systems if necessary by calling
    -- set_family_count
    -- *******************************************************************
    create or replace function assign_channel_entitlement(
        channel_family_label_in in varchar,
        from_org_id_in in numeric,
        to_org_id_in in numeric,
        quantity_in in numeric,
        flex_in in numeric
    ) returns void
as $$
    declare
        from_org_prev_ent_count numeric;
        from_org_prev_ent_count_flex numeric;
        new_ent_count numeric;
        new_ent_count_flex numeric;
        to_org_prev_ent_count numeric;
        to_org_prev_ent_count_flex numeric;
        new_quantity numeric;
        new_flex numeric;
        cfam_id       numeric;
    begin

            select max_members
            into from_org_prev_ent_count
            from rhnChannelFamily cf,
                 rhnPrivateChannelFamily pcf
            where pcf.org_id = from_org_id_in
              and pcf.channel_family_id = cf.id
              and cf.label = channel_family_label_in;

            if not found then
                perform rhn_exception.raise_exception(
                              'not_enough_entitlements_in_base_org');
            end if;

            select max_members
            into to_org_prev_ent_count
            from rhnChannelFamily cf,
                 rhnPrivateChannelFamily pcf
            where pcf.org_id = to_org_id_in
              and pcf.channel_family_id = cf.id
              and cf.label = channel_family_label_in;

            if not found then
                to_org_prev_ent_count := 0;
            end if;

            select fve_max_members
            into from_org_prev_ent_count_flex
            from rhnChannelFamily cf,
                rhnPrivateChannelFamily pcf
            where pcf.org_id = from_org_id_in
              and pcf.channel_family_id = cf.id
              and cf.label = channel_family_label_in;

            if not found then
                perform rhn_exception.raise_exception(
                              'not_enough_flex_entitlements_in_base_org');
            end if;

            select fve_max_members
            into to_org_prev_ent_count_flex
            from rhnChannelFamily cf,
                 rhnPrivateChannelFamily pcf
            where pcf.org_id = to_org_id_in
              and pcf.channel_family_id = cf.id
              and cf.label = channel_family_label_in;

            if not found then
                to_org_prev_ent_count_flex := 0;
            end if;

            select id
            into cfam_id
            from rhnChannelFamily
            where label = channel_family_label_in;

            if not found then
                perform rhn_exception.raise_exception(
                              'invalid_channel_family');
            end if;

        new_ent_count := from_org_prev_ent_count - quantity_in;
        new_ent_count_flex := from_org_prev_ent_count_flex - flex_in;

        if from_org_prev_ent_count >= new_ent_count then
            new_quantity := to_org_prev_ent_count + quantity_in;
        end if;

        if from_org_prev_ent_count_flex >= new_ent_count_flex then
            new_flex := to_org_prev_ent_count_flex + flex_in;
        end if;

        if new_ent_count < 0 then
            perform rhn_exception.raise_exception(
                          'not_enough_entitlements_in_base_org');
        end if;

        if new_ent_count_flex < 0 then
            perform rhn_exception.raise_exception(
                          'not_enough_flex_entitlements_in_base_org');
        end if;



        perform rhn_entitlements.set_family_count(from_org_id_in,
                                          cfam_id,
                                          new_ent_count,
                                          new_ent_count_flex);

        perform rhn_entitlements.set_family_count(to_org_id_in,
                                          cfam_id,
                                          new_quantity,
                                          new_flex);

    end$$
language plpgsql;

    -- *******************************************************************
    -- PROCEDURE: activate_system_entitlement
    --
    -- Sets the values in rhnServerGroup for a given rhnServerGroupType.
    --
    -- Calls: set_group_count to update, prune, or create the group.
    -- Called by: the code that activates a satellite cert.
    --
    -- Raises not_enough_entitlements_in_base_org if all entitlements
    -- in the org are used so the free entitlements would not cover
    -- the difference when descreasing the number of entitlements.
    -- *******************************************************************
    create or replace function activate_system_entitlement(
        org_id_in in numeric,
        group_label_in in varchar,
        quantity_in in numeric
    ) returns void
as $$
    declare
        prev_ent_count numeric;
        prev_ent_count_sum numeric;
        group_type numeric;
    begin

        -- Fetch the current entitlement count for the org
        -- into prev_ent_count

            select current_members
            into prev_ent_count
            from rhnServerGroupType sgt,
                 rhnServerGroup sg
            where sg.group_type = sgt.id
              and sgt.label = group_label_in
              and sg.org_id = org_id_in;

            if not found then
                prev_ent_count := 0;
            end if;

            select id
            into group_type
            from rhnServerGroupType
            where label = group_label_in;

            if not found then
                perform rhn_exception.raise_exception(
                              'invalid_server_group');
            end if;

        -- If we're setting the total entitlemnt count to a lower value,
        -- and that value is less than the allocated count in this org,
        -- we need to raise an exception.
        if quantity_in < prev_ent_count then
            perform rhn_exception.raise_exception(
                          'not_enough_entitlements_in_base_org');
        else
            -- don't update family counts after every server
            -- will do bulk update afterwards
            perform rhn_entitlements.set_group_count(org_id_in,
                                             'S',
                                             group_type,
                                             quantity_in,
                                             0);
            -- bulk update family counts
            perform rhn_channel.update_group_family_counts(group_label_in, org_id_in);
        end if;

    end$$
language plpgsql;

    -- *******************************************************************
    -- PROCEDURE: activate_channel_entitlement
    --
    -- Calls: set_family_count to update, prune, or create the family
    --        permission bucket.
    -- Called by: the code that activates a satellite cert.
    --
    -- Raises not_enough_entitlements_in_base_org if there are not enough
    -- entitlements in the org to cover the difference when you are
    -- descreasing the number of entitlements.
    --
    -- The backend code in Python is expected to do whatever arithmetics
    -- is needed.
    -- *******************************************************************
    create or replace function activate_channel_entitlement(
        org_id_in in numeric,
        channel_family_label_in in varchar,
        quantity_in in numeric,
        flex_in in numeric
    ) returns void
as $$
    declare
        prev_ent_count numeric;
        prev_flex_count numeric;
        prev_ent_count_sum numeric;
        cfam_id numeric;
        reduce_quantity numeric;
        total_flex_capable numeric;
        to_convert_reg cursor (channel_family_id_val numeric, org_id_in numeric, quantity numeric) for
                     select SC.server_id
                     from rhnServerChannel SC inner join
                          rhnServer S on S.id = SC.server_id
                     where
                         is_fve = 'Y'
                         and S.org_id = org_id_in
                         and SC.channel_id in
                         (select cfm.channel_id from rhnChannelFamilyMembers cfm
                             where cfm.CHANNEL_FAMILY_ID = channel_family_id_val)
                         limit quantity;
         to_convert_flex cursor (channel_family_id_val numeric, org_id_in numeric, quantity numeric) for
                   select server_id
                   from rhnServerFveCapable
                       where SERVER_ORG_ID = org_id_in and
                             channel_family_id = cfam_id
                       limit quantity;

    begin

        -- Fetch the current entitlement count for the org
        -- into prev_ent_count
            select current_members
            into prev_ent_count
            from rhnChannelFamily cf,
                 rhnPrivateChannelFamily pcf
            where pcf.org_id = org_id_in
              and pcf.channel_family_id = cf.id
              and cf.label = channel_family_label_in;

            if not found then
                prev_ent_count := 0;
            end if;

            select pcf.fve_current_members
            into prev_flex_count
            from rhnChannelFamily cf,
                 rhnPrivateChannelFamily pcf
            where pcf.org_id = org_id_in
              and pcf.channel_family_id = cf.id
              and cf.label = channel_family_label_in;

            if not found then
                prev_flex_count := 0;
            end if;

            select id
            into cfam_id
            from rhnChannelFamily
            where label = channel_family_label_in;

            if not found then
                perform rhn_exception.raise_exception(
                              'invalid_channel_family');
            end if;

        -- if there are too few flex entitlements
        if flex_in < prev_flex_count then
            -- and if the extra we need is less than or equal to our extra regular entitlements
            if prev_flex_count - flex_in <= quantity_in - prev_ent_count then
                   reduce_quantity := prev_flex_count - flex_in;
                   -- We need to convert some systems from flex guest to regular
                   for system in to_convert_reg(cfam_id, org_id_in, reduce_quantity) loop
                      --rhn_channel.convert_to_regular(system.server_id, cfam_id);
                      UPDATE rhnServerChannel sc set is_fve = 'N'
                           where sc.server_id = system.server_id
                                 and sc.channel_id in (select cfm.channel_id
                                                          from rhnChannelFamilyMembers cfm
                                                          where cfm.channel_family_id = cfam_id);
                   end loop;

                   --reset previous counts
                   prev_ent_count := prev_ent_count + reduce_quantity;
                   prev_flex_count := prev_flex_count - reduce_quantity;
            else
                perform rhn_exception.raise_exception(
                          'not_enough_flex_entitlements_in_base_org');
            end if;
        end if;

        -- if there are too few regular entitlements, and extra flex entitlements
        if quantity_in < prev_ent_count and prev_flex_count < flex_in then
                -- how many flex-capable systems (that aren't using flex) do we have
                select count(*)
                   into total_flex_capable
                   from rhnServerFveCapable
                       where SERVER_ORG_ID = org_id_in and
                             channel_family_id = cfam_id;
                -- if we have enough flex capable machines that is at least
                --   as many as what we are over on
                if total_flex_capable >= prev_ent_count - quantity_in then
                    reduce_quantity := prev_ent_count - quantity_in;
                    for system in to_convert_flex(cfam_id, org_id_in, reduce_quantity) loop
--                          rhn_channel.convert_to_fve(system.server_id, cfam_id);
                        UPDATE rhnServerChannel sc set is_fve = 'Y'
                           where sc.server_id = system.server_id
                                 and sc.channel_id in (select cfm.channel_id
                                                          from rhnChannelFamilyMembers cfm
                                                          where cfm.channel_family_id = cfam_id);
                    end loop;
                    prev_ent_count := prev_ent_count - reduce_quantity;
                    prev_flex_count := prev_flex_count + reduce_quantity;
                end if;
        end if;

        -- If we're setting the total entitlemnt count to a lower value,
        -- and that value is less than the count in that one org,
        -- we need to raise an exception.
        if quantity_in < prev_ent_count then
            perform rhn_exception.raise_exception(
                          'not_enough_entitlements_in_base_org');
        else
            -- even if we've manually converted systems to/from flex above
            -- set_family_count should call update_family_counts, to reset
            -- current used slots
            perform rhn_entitlements.set_family_count(org_id_in, cfam_id,
                                              quantity_in, flex_in);
        end if;

    end$$
language plpgsql;

    create or replace function set_group_count (
        customer_id_in in numeric,  -- customer_id
        type_in in char,            -- 'U' or 'S'
        group_type_in in numeric,   -- rhn[User|Server]GroupType.id
        quantity_in in numeric,      -- quantity
                update_family_countsYN in numeric default 1
    ) returns void
as $$
    declare
        group_id numeric;
        quantity numeric;
        wasfound boolean;
    begin
        quantity := quantity_in;
        if quantity is not null and quantity < 0 then
            quantity := 0;
        end if;

        if type_in = 'U' then
            select  rug.id
            into    group_id
            from    rhnUserGroup rug
            where   1=1
                and rug.org_id = customer_id_in
                and rug.group_type = group_type_in;
        elsif type_in = 'S' then
            select  rsg.id
            into    group_id
            from    rhnServerGroup rsg
            where   1=1
                and rsg.org_id = customer_id_in
                and rsg.group_type = group_type_in;
        end if;

        -- preserve the not found status across the rhn_entitlements.prune_group invocation
        wasfound := true;
        if not found then
            wasfound := false;
        end if;

        perform rhn_entitlements.prune_group(
            group_id,
            type_in,
            quantity,
                        update_family_countsYN
        );

        if not wasfound then
            if type_in = 'U' then
                insert into rhnUserGroup (
                        id, name, description, max_members, current_members,
                        group_type, org_id, created, modified
                    ) (
                        select  nextval('rhn_user_group_id_seq'), name, name,
                                quantity, 0, id, customer_id_in,
                                current_timestamp, current_timestamp
                        from    rhnUserGroupType
                        where    id = group_type_in
                );
            elsif type_in = 'S' then
                insert into rhnServerGroup (
                        id, name, description, max_members, current_members,
                        group_type, org_id, created, modified
                    ) (
                        select  nextval('rhn_server_group_id_seq'), name, name,
                                quantity, 0, id, customer_id_in,
                                current_timestamp, current_timestamp
                        from    rhnServerGroupType
                        where   id = group_type_in
                );
            end if;
        end if;

    end$$
language plpgsql;

    -- *******************************************************************
    -- PROCEDURE: prune_family
    -- Unsubscribes servers consuming physical slots from the channel family
    --   that are over the org's limit.
    -- Called by: set_family_count
    -- *******************************************************************
    create or replace function prune_family (
        customer_id_in in numeric,
        channel_family_id_in in numeric,
        quantity_in in numeric,
        flex_in in numeric
    ) returns void
as $$
    declare
       is_fve_in char;
       tmp_quantity numeric;

        serverchannels cursor for
            select  sc.server_id,
                    sc.channel_id
            from    rhnServerChannel sc,
                    rhnChannelFamilyMembers cfm
            where   1=1
                and cfm.channel_family_id = channel_family_id_in
                and cfm.channel_id = sc.channel_id
                and server_id in (
                            select  rs.id as server_id
                            from
                                    rhnServerChannel        rsc,
                                    rhnChannelFamilyMembers rcfm,
                                    rhnServer               rs
                            where   1=1
                                and rs.org_id = customer_id_in
                                and rs.id = rsc.server_id
                                and rsc.channel_id = rcfm.channel_id
                                and rcfm.channel_family_id =  channel_family_id_in
                                and rsc.is_fve = is_fve_in
                                -- we only want to grab servers consuming
                                -- physical slots.
                                and exists (
                                    select 1
                                    from rhnChannelFamilyServerPhysical cfsp
                                    where cfsp.server_id = rs.id
                                    and cfsp.channel_family_id =
                                        channel_family_id_in
                                    )
                            order by rcfm.modified asc
                            offset quantity_in
                        );
    begin
        -- if we get a null customer_id, this is completely bogus.
        if customer_id_in is null then
            return;
        end if;

        tmp_quantity := quantity_in;
        is_fve_in := 'N';

        for sc in serverchannels loop
            perform rhn_channel.unsubscribe_server(sc.server_id, sc.channel_id, 1, 1, 0, 0);

        tmp_quantity := flex_in;
        is_fve_in := 'Y';
        for sc in serverchannels loop
            perform rhn_channel.unsubscribe_server(sc.server_id, sc.channel_id, 1, 1, 0, 0);
        end loop;
        end loop;
                perform rhn_channel.update_family_counts(channel_family_id_in, customer_id_in);
    end$$
language plpgsql;

    create or replace function set_family_count (
        customer_id_in in numeric,      -- customer_id
        channel_family_id_in in numeric,    -- 246
        quantity_in in numeric,          -- 3
        flex_in in numeric
    ) returns void
as $$
    declare
        privperms cursor for
            select  1
            from    rhnPrivateChannelFamily
            where   org_id = customer_id_in
                and channel_family_id = channel_family_id_in;
        pubperms cursor for
            select  o.id org_id
            from    web_customer o,
                    rhnPublicChannelFamily pcf
            where   pcf.channel_family_id = channel_family_id_in;
        quantity numeric;
        done numeric := 0;
        flex numeric;
    begin
        quantity := quantity_in;
        if quantity is not null and quantity < 0 then
            quantity := 0;
        end if;
        flex := flex_in;
        if flex is not null and flex < 0 then
            flex := 0;
        end if;

        if customer_id_in is not null then
            for perm in privperms loop
                perform rhn_entitlements.prune_family(
                    customer_id_in,
                    channel_family_id_in,
                    quantity,
                    flex
                );

                if quantity is null and flex is null then
                    delete from rhnPrivateChannelFamily
                        where org_id = customer_id_in
                            and channel_family_id = channel_family_id_in;
                 else
                    update rhnPrivateChannelFamily
                        set max_members = quantity
                        where org_id = customer_id_in
                            and channel_family_id = channel_family_id_in;

                   update rhnPrivateChannelFamily
                        set fve_max_members = flex
                        where org_id = customer_id_in
                            and channel_family_id = channel_family_id_in;
                end if;
                return;
            end loop;

            insert into rhnPrivateChannelFamily (
                    channel_family_id, org_id, max_members, current_members, fve_max_members, fve_current_members
                ) values (
                    channel_family_id_in, customer_id_in, quantity, 0, flex, 0 );
            return;
        end if;

        for perm in pubperms loop
            if quantity = 0 then
                perform rhn_entitlements.prune_family(
                    perm.org_id,
                    channel_family_id_in,
                    quantity,
                    flex
                );
                if done = 0 then
                    delete from rhnPublicChannelFamily
                        where channel_family_id = channel_family_id_in;
                end if;
            end if;
            done := 1;
        end loop;
        -- if done's not 1, then we don't have any entitlements
        if done != 1 then
            insert into rhnPublicChannelFamily (
                    channel_family_id
                ) values (
                    channel_family_id_in
                );
        end if;
    end$$
language plpgsql;

    -- this expects quantity_in to be the number of available slots, not the
    -- max_members of the server group.  If you give it too many, it'll fail
    -- and raise servergroup_max_members.
    -- We should NEVER run this unless we're SURE that we won't
    -- be violating the max.
    create or replace function entitle_last_modified_servers (
        customer_id_in in numeric,  -- customer_id
        type_label_in in varchar,   -- 'enterprise_entitled'
        quantity_in in numeric      -- 3
    ) returns void
as $$
    declare
        -- find the servers that aren't currently in slots
        servers cursor(cid_in numeric, quant_in numeric) for
                                    select  rs.id as server_id
                                    from    rhnServer rs
                                    where   1=1
                                        and rs.org_id = cid_in
                                        and not exists (
                                            select  1
                                            from    rhnServerGroup sg,
                                                    rhnServerGroupMembers rsgm
                                            where   rsgm.server_id = rs.id
                                                and rsgm.server_group_id = sg.id
                                                and sg.group_type is not null
                                        )
                                        and not exists (
                                            select 1
                                            from rhnVirtualInstance vi
                                            where vi.virtual_system_id =
                                                  rs.id
                                        )
                                    order by modified desc
                                    limit quant_in;
    begin
        for server in servers(customer_id_in, quantity_in) loop
            perform rhn_entitlements.entitle_server(server.server_id, type_label_in);
        end loop;
    end$$
language plpgsql;

    create or replace function subscribe_newest_servers (
        customer_id_in in numeric
    ) returns void
as $$
    declare
        -- find servers without base channels
        servers cursor(cid_in numeric) for
            select  s.id
            from    rhnServer           s
            where   1=1
                and s.org_id = cid_in
                and not exists (
                        select 1
                        from    rhnChannel          c,
                                rhnServerChannel    sc
                        where   sc.server_id = s.id
                            and sc.channel_id = c.id
                            and c.parent_channel is null
                    )
                and not exists (
                        select 1
                        from rhnVirtualInstance vi
                        where vi.virtual_system_id = s.id
                    )
            order by s.modified desc;
        channel_id numeric;
    begin
        for server in servers(customer_id_in) loop
            channel_id := rhn_channel.guess_server_base(server.id);
            if channel_id is not null then
                begin
                    perform rhn_channel.subscribe_server(server.id, channel_id);
                -- exception is really channel_family_no_subscriptions
                exception
                    when others then
                        null;
                end;
            end if;
        end loop;
    end$$
language plpgsql;


-- restore the original setting
update pg_settings set setting = overlay( setting placing '' from 1 for (length('rhn_entitlements')+1) ) where name = 'search_path';
   070701000006A9000081B400000000000000000000000167AE11140000B243000000000000000000000000000000000000005C00000000susemanager-schema/upgrade/spacewalk-schema-1.5-to-spacewalk-schema-1.6/091-rhn_channel.sql   
--update pg_setting
update pg_settings set setting = 'rhn_channel,' || setting where name = 'search_path';

drop function get_license_path(channel_id_in in numeric);
drop function license_consent(channel_id_in in numeric, user_id_in in numeric, server_id_in in numeric);
drop function clear_subscriptions(server_id_in in numeric, deleting_server in numeric);

    create or replace function obtain_read_lock(channel_family_id_in in numeric, org_id_in in numeric)
    returns void as $$
    declare
        read_lock TIMESTAMPTZ;
    begin
        select created into read_lock
          from rhnPrivateChannelFamily
         where channel_family_id = channel_family_id_in and org_id = org_id_in
           for update;
    end$$ language plpgsql;

    -- this "emulates" cursor server_base_subscriptions defined in oracle/rhn_channel.pks
    create or replace function server_base_subscriptions(server_id_in NUMERIC)
    returns boolean as $$
    begin
      return exists(SELECT C.id FROM rhnChannel C, rhnServerChannel SC
		    WHERE C.id = SC.channel_id
		      AND SC.server_id = server_id_in
		      AND C.parent_channel IS NULL);
    end$$ language plpgsql;

    -- this "emulates" cursor server_base_subscriptions defined in oracle/rhn_channel.pks
    create or replace function check_server_subscription(server_id_in NUMERIC, channel_id_in NUMERIC)
    returns boolean as $$
    begin
      return exists(SELECT channel_id FROM rhnServerChannel WHERE server_id = server_id_in AND channel_id = channel_id_in);
    end$$ language plpgsql;


    CREATE OR REPLACE FUNCTION subscribe_server(server_id_in IN NUMERIC, channel_id_in NUMERIC, immediate_in NUMERIC default 1, user_id_in in numeric default null, recalcfamily_in NUMERIC default 1) returns void
    AS $$
    declare
        channel_parent_val      rhnChannel.parent_channel%TYPE;
        parent_subscribed       BOOLEAN;
        server_has_base_chan    BOOLEAN;
        server_already_in_chan  BOOLEAN;
        channel_family_id_val   NUMERIC;
        server_org_id_val       NUMERIC;
        available_subscriptions NUMERIC;
        available_fve_subs      numeric;
        consenting_user         NUMERIC;
        allowed                 numeric;
        is_fve_char             char(1) := 'N';
    BEGIN
        if user_id_in is not null then
            allowed := rhn_channel.user_role_check(channel_id_in, user_id_in, 'subscribe');
        else
            allowed := 1;
        end if;

        if allowed = 0 then
            perform rhn_exception.raise_exception('no_subscribe_permissions');
        end if;


        SELECT parent_channel INTO channel_parent_val FROM rhnChannel WHERE id = channel_id_in;

        IF channel_parent_val IS NOT NULL
        THEN
            -- child channel; if attempting to cross-subscribe a child to the wrong base, silently ignore
            parent_subscribed := rhn_channel.check_server_subscription(server_id_in, channel_parent_val);

            IF NOT parent_subscribed
            THEN
                RETURN;
            END IF;
        ELSE
            -- base channel
            server_has_base_chan := rhn_channel.server_base_subscriptions(server_id_in);

            IF server_has_base_chan
            THEN
                perform rhn_exception.raise_exception('channel_server_one_base');
            END IF;
        END IF;

        server_already_in_chan := rhn_channel.check_server_subscription(server_id_in, channel_id_in);

        IF server_already_in_chan
        THEN
            RETURN;
        END IF;

        channel_family_id_val := rhn_channel.family_for_channel(channel_id_in);
        IF channel_family_id_val IS NULL
        THEN
            perform rhn_exception.raise_exception('channel_subscribe_no_family');
        END IF;

        --
        -- Use the org_id of the server only if the org_id of the channel = NULL.
        -- This is required for subscribing to shared channels.
        --
        SELECT COALESCE(org_id, (SELECT org_id FROM rhnServer WHERE id = server_id_in))
          INTO server_org_id_val
          FROM rhnChannel
         WHERE id = channel_id_in;

        begin
            perform rhn_channel.obtain_read_lock(channel_family_id_val, server_org_id_val);
        exception
            when no_data_found then
                perform rhn_exception.raise_exception('channel_family_no_subscriptions');
        end;

        available_subscriptions := rhn_channel.available_family_subscriptions(channel_family_id_val, server_org_id_val);
        available_fve_subs := rhn_channel.available_fve_family_subs(channel_family_id_val, server_org_id_val);

        IF available_subscriptions IS NULL OR
           available_subscriptions > 0 or
           rhn_channel.can_server_consume_virt_channl(server_id_in, channel_family_id_val) = 1 OR
            (available_fve_subs > 0 AND rhn_channel.can_server_consume_fve(server_id_in) = 1)
        THEN
            if rhn_channel.can_server_consume_virt_channl(server_id_in, channel_family_id_val) = 0 AND available_fve_subs > 0 AND rhn_channel.can_server_consume_fve(server_id_in) = 1 THEN
                is_fve_char := 'Y';
            end if;

            insert into rhnServerHistory (id,server_id,summary,details) (
                select  nextval('rhn_event_id_seq'),
                        server_id_in,
                        'subscribed to channel ' || SUBSTR(c.label, 0, 106),
                        c.label
                from    rhnChannel c
                where   c.id = channel_id_in
            );
            UPDATE rhnServer SET channels_changed = current_timestamp WHERE id = server_id_in;
            INSERT INTO rhnServerChannel (server_id, channel_id, is_fve) VALUES (server_id_in, channel_id_in, is_fve_char);
			IF recalcfamily_in > 0
			THEN
                perform rhn_channel.update_family_counts(channel_family_id_val, server_org_id_val);
			END IF;
            perform queue_server(server_id_in, immediate_in);
        ELSE
            perform rhn_exception.raise_exception('channel_family_no_subscriptions');
        END IF;

    END$$ language plpgsql;



    create or replace function can_convert_to_fve(server_id_in IN NUMERIC, channel_family_id_val IN NUMERIC)
    RETURNS NUMERIC
    as $$
    declare
        fve_convertible_entries cursor for
        select 1  from
            rhnServerFveCapable cap
          where cap.server_id = server_id_in
                AND cap.channel_family_id = channel_family_id_val;
    BEGIN
        FOR entry IN fve_convertible_entries LOOP
            return 1;
        END LOOP;
        RETURN 0;
    END$$ language plpgsql;



    -- Converts server channel_family to use a flex entitlement
    create or replace function convert_to_fve(server_id_in IN NUMERIC, channel_family_id_val IN NUMERIC)
    returns void
    as $$
    declare
        available_fve_subs      NUMERIC;
        server_org_id_val       NUMERIC;
    BEGIN

        --
        -- Use the org_id of the server only if the org_id of the channel = NULL.
        -- This is required for subscribing to shared channels.
        --
        SELECT org_id
          INTO server_org_id_val
          FROM rhnServer
         WHERE id = server_id_in;


        perform obtain_read_lock(channel_family_id_val, server_org_id_val);
        if not found then
                perform rhn_exception.raise_exception('channel_family_no_subscriptions');
        end if;
        IF (can_convert_to_fve(server_id_in, channel_family_id_val ) = 0)
            THEN
                perform rhn_exception.raise_exception('server_cannot_convert_to_flex');
        END IF;

        available_fve_subs := rhn_channel.available_fve_family_subs(channel_family_id_val, server_org_id_val);

        IF (available_fve_subs > 0)
        THEN

            insert into rhnServerHistory (id,server_id,summary,details) (
                select  nextval('rhn_event_id_seq'),
                        server_id_in,
                        'converted to flex entitlement' || SUBSTR(cf.label, 0, 99),
                        cf.label
                from    rhnChannelFamily cf
                where   cf.id = channel_family_id_val
            );

            UPDATE rhnServerChannel sc set sc.is_fve = 'Y'
                           where sc.server_id = server_id_in and
                                 sc.channel_id in
                                    (select cfm.channel_id from rhnChannelFamilyMembers cfm
                                                where cfm.CHANNEL_FAMILY_ID = channel_family_id_val);

            perform rhn_channel.update_family_counts(channel_family_id_val, server_org_id_val);
        ELSE
            perform rhn_exception.raise_exception('not_enough_flex_entitlements');
        END IF;

    END$$ language plpgsql;

    create or replace function can_server_consume_virt_channl(
        server_id_in in numeric,
        family_id_in in numeric )
    returns numeric
    as $$
    begin
      if exists(
            select 1
            from
                rhnChannelFamilyVirtSubLevel cfvsl,
                rhnSGTypeVirtSubLevel sgtvsl,
                rhnVirtualInstance vi
            where
                vi.virtual_system_id = server_id_in
                and sgtvsl.virt_sub_level_id = cfvsl.virt_sub_level_id
                and cfvsl.channel_family_id = family_id_in
                and exists (
                    select 1
                    from rhnServerEntitlementView sev
                    where vi.host_system_id = sev.server_id
                    and sev.server_group_type_id = sgtvsl.server_group_type_id ))
      then
        return 1;
      else
        return 0;
      end if;
    end$$ language plpgsql;

    create or replace function can_server_consume_fve(server_id_in in numeric) returns numeric
    as $$
    declare
        vi_entries cursor for
            SELECT 1
              FROM rhnVirtualInstance vi
             WHERE vi.virtual_system_id = server_id_in;
        vi_count numeric;

    begin
        FOR vi_entry IN VI_ENTRIES LOOP
            return 1;
        END LOOP;
        RETURN 0;
    end$$ language plpgsql;

    create or replace function guess_server_base(
        server_id_in in numeric
    ) RETURNS numeric as $$
    declare
        server_cursor cursor for
            select s.server_arch_id, s.release, s.org_id
              from rhnServer s
             where s.id = server_id_in;
    -- Cursor that fetches all the possible base channels for a
    -- (server_arch_id, release, org_id) combination
        base_channel_cursor cursor(
                release_in varchar,
                server_arch_id_in numeric,
                org_id_in numeric
        ) for
                select distinct c.*
                from    rhnDistChannelMap                       dcm,
                                rhnServerChannelArchCompat      scac,
                                rhnChannel                                      c,
                                rhnChannelPermissions           cp
                where   cp.org_id = org_id_in
                        and cp.channel_id = c.id
                        and c.parent_channel is null
                        and c.id = dcm.channel_id
                        and c.channel_arch_id = dcm.channel_arch_id
                        and dcm.release = release_in
                        and scac.server_arch_id = server_arch_id_in
                        and scac.channel_arch_id = c.channel_arch_id;

    begin
        for s in server_cursor loop
            for channel in base_channel_cursor(s.release,
                s.server_arch_id, s.org_id)
            loop
                return channel.id;
            end loop;
        end loop;
        -- Server not found, or no base channel applies to it
        return null;
    end$$ language plpgsql;

    -- Private function
    create or replace function normalize_server_arch(server_arch_in in varchar)
    returns varchar
    as $$
    declare
        suffix VARCHAR(128) := '-redhat-linux';
    begin
        if server_arch_in is NULL then
            return NULL;
        end if;
        if position('-' IN server_arch_in) > 0
        then
            -- Suffix already present
            return server_arch_in;
        end if;
        return server_arch_in || suffix;
    end$$ language plpgsql;

    --
    -- Raises:
    --   server_arch_not_found
    --   no_subscribe_permissions
    create or replace function base_channel_for_release_arch(
        release_in in varchar,
        server_arch_in in varchar,
        org_id_in in numeric default -1,
        user_id_in in numeric default null
    ) returns numeric as $$
    declare
        server_arch varchar(256) := rhn_channel.normalize_server_arch(server_arch_in);
        server_arch_id numeric;
    begin
        -- Look up the server arch
            select id
              into server_arch_id
              from rhnServerArch
             where label = server_arch;
            if not found then
                perform rhn_exception.raise_exception('server_arch_not_found');
            end if;

        return rhn_channel.base_channel_rel_archid(release_in, server_arch_id,
            org_id_in, user_id_in);
    end$$ language plpgsql;

    create or replace function base_channel_rel_archid(
        release_in in varchar,
        server_arch_id_in in numeric,
        org_id_in in numeric default -1,
        user_id_in in numeric default null
    ) returns numeric as $$
    declare
        denied_channel_id numeric := null;
        valid_org_id numeric := org_id_in;
        valid_user_id numeric := user_id_in;
        channel_subscribable numeric;
    -- Cursor that fetches all the possible base channels for a
    -- (server_arch_id, release, org_id) combination
        base_channel_cursor cursor(
                release_in varchar,
                server_arch_id_in numeric,
                org_id_in numeric
        ) for
                select distinct c.*
                from    rhnDistChannelMap                       dcm,
                                rhnServerChannelArchCompat      scac,
                                rhnChannel                                      c,
                                rhnChannelPermissions           cp
                where   cp.org_id = org_id_in
                        and cp.channel_id = c.id
                        and c.parent_channel is null
                        and c.id = dcm.channel_id
                        and c.channel_arch_id = dcm.channel_arch_id
                        and dcm.release = release_in
                        and scac.server_arch_id = server_arch_id_in
                        and scac.channel_arch_id = c.channel_arch_id;

    begin
        if org_id_in = -1 and user_id_in is not null then
            -- Get the org id from the user id

                select org_id
                  into valid_org_id
                  from web_contact
                 where id = user_id_in;

                if not found then
                    -- User doesn't exist
                    -- XXX Only list public stuff for now
                    valid_user_id := null;
                    valid_org_id := -1;
                end if;
        end if;

        for c in base_channel_cursor(release_in, server_arch_id_in, valid_org_id)
        loop
            -- This row is a possible match
            if valid_user_id is null then
                -- User ID not specified, so no user to channel permissions to
                -- check
                return c.id;
            end if;

            -- Check user to channel permissions
            select rhn_channel.loose_user_role_check(c.id, user_id_in, 'subscribe')
              into channel_subscribable;

            if channel_subscribable = 1 then
                return c.id;
            end if;

            -- Base channel exists, but is not subscribable; keep trying
            denied_channel_id := c.id;
        end loop;

        if denied_channel_id is not null then
            perform rhn_exception.raise_exception('no_subscribe_permissions');
        end if;
        -- No base channel applies
        return NULL;
    end$$ language plpgsql;

    CREATE OR REPLACE FUNCTION clear_subscriptions(server_id_in IN NUMERIC, deleting_server IN NUMERIC default 0,
                                update_family_countsYN IN NUMERIC default 1 ) returns void
    AS $$
    declare
        server_channels cursor(server_id_in numeric) for
                select  s.org_id, sc.channel_id, cfm.channel_family_id
                from    rhnServer s,
                        rhnServerChannel sc,
                        rhnChannelFamilyMembers cfm
                where   s.id = server_id_in
                        and s.id = sc.server_id
                        and sc.channel_id = cfm.channel_id
                order by cfm.channel_family_id;
        last_channel_family_id rhnChannelFamilyMembers.channel_family_id%type := -1;
        last_channel_org_id    rhnServer.org_id%type := -1;
    BEGIN
        for channel in server_channels(server_id_in)
        loop
                perform rhn_channel.unsubscribe_server(server_id_in, channel.channel_id, 1, 1, deleting_server, 0);
                if update_family_countsYN > 0
                    and channel.channel_family_id != last_channel_family_id then
                    -- update family counts only once
                    -- after all channels with same family has been fetched
                    if last_channel_family_id != -1 then
                        perform rhn_channel.update_family_counts(channel.channel_family_id, channel.org_id);
                    end if;
                    last_channel_family_id := channel.channel_family_id;
                    last_channel_org_id    := channel.org_id;
                end if;
        end loop;
        if update_family_countsYN > 0 and last_channel_family_id != -1 then
            -- update the last family fetched
            perform rhn_channel.update_family_counts(last_channel_family_id, last_channel_org_id);
        end if;
    END$$ language plpgsql;

    CREATE OR REPLACE FUNCTION unsubscribe_server(server_id_in IN NUMERIC, channel_id_in NUMERIC, immediate_in NUMERIC default 1, unsubscribe_children_in numeric default 0,
                                 deleting_server in numeric default 0,
                                 update_family_countsYN in numeric default 1) returns void
    AS $$
    declare
        channel_family_id_val   NUMERIC;
        server_org_id_val       NUMERIC;
        available_subscriptions NUMERIC;
        server_already_in_chan  BOOLEAN;
        channel_family_is_proxy cursor(channel_family_id_in numeric) for
                select  1
                from    rhnChannelFamily
                where   id = channel_family_id_in
                    and label = 'rhn-proxy';
        channel_family_is_satellite cursor(channel_family_id_in numeric) for
                select  1
                from    rhnChannelFamily
                where   id = channel_family_id_in
                    and label = 'rhn-satellite';
        child record;
    BEGIN
        -- In PostgreSQL recursion with opened cursors is not allowed so we use
        -- FOR IN SELECT form which is ok.
        FOR child IN select  c.id
                from    rhnChannel                      c,
                                rhnServerChannel        sc
                where   1=1
                        and c.parent_channel = channel_id_in
                        and c.id = sc.channel_id
                        and sc.server_id = server_id_in
        LOOP
            if unsubscribe_children_in = 1 then
                perform rhn_channel.unsubscribe_server(server_id_in,
                                                       child.id,
                                                       immediate_in,
                                                       unsubscribe_children_in,
                                                       deleting_server,
                                                       update_family_countsYN);
            else
                perform rhn_exception.raise_exception('channel_unsubscribe_child_exists');
            end if;
        END LOOP;

        server_already_in_chan := rhn_channel.check_server_subscription(server_id_in, channel_id_in);

        IF NOT server_already_in_chan
        THEN
            RETURN;
        END IF;

   if deleting_server = 0 then

      insert into rhnServerHistory (id,server_id,summary,details) (
          select  nextval('rhn_event_id_seq'),
                server_id_in,
             'unsubscribed from channel ' || SUBSTR(c.label, 0, 106),
             c.label
          from    rhnChannel c
          where   c.id = channel_id_in
      );

        UPDATE rhnServer SET channels_changed = current_timestamp WHERE id = server_id_in;
   end if;

   DELETE FROM rhnServerChannel WHERE server_id = server_id_in AND channel_id = channel_id_in;

   if deleting_server = 0 then
        perform queue_server(server_id_in, immediate_in);
   end if;

        channel_family_id_val := rhn_channel.family_for_channel(channel_id_in);
        IF channel_family_id_val IS NULL
        THEN
            perform rhn_exception.raise_exception('channel_unsubscribe_no_family');
        END IF;

        for ignore in channel_family_is_satellite(channel_family_id_val) loop
                delete from rhnSatelliteInfo where server_id = server_id_in;
        end loop;

        for ignore in channel_family_is_proxy(channel_family_id_val) loop
                delete from rhnProxyInfo where server_id = server_id_in;
        end loop;
        SELECT org_id INTO server_org_id_val
          FROM rhnServer
         WHERE id = server_id_in;

        if update_family_countsYN = 1 then
           perform rhn_channel.update_family_counts(channel_family_id_val, server_org_id_val);
        end if;
    END$$ language plpgsql;

    CREATE OR REPLACE FUNCTION family_for_channel(channel_id_in IN NUMERIC)
    RETURNS NUMERIC
    AS $$
    declare
        channel_family_id_val NUMERIC;
    BEGIN
        SELECT channel_family_id INTO channel_family_id_val
          FROM rhnChannelFamilyMembers
         WHERE channel_id = channel_id_in;

        IF NOT FOUND THEN
          RETURN NULL;
        END IF;

        RETURN channel_family_id_val;
    END$$ language plpgsql;

    CREATE OR REPLACE FUNCTION available_family_subscriptions(channel_family_id_in IN NUMERIC, org_id_in IN NUMERIC)
    RETURNS NUMERIC
    AS $$
    declare
        cfp record;
        current_members_val NUMERIC;
        max_members_val     NUMERIC;
        found               NUMERIC;
    BEGIN
        for cfp in SELECT * FROM rhnOrgChannelFamilyPermissions
	    WHERE channel_family_id = channel_family_id_in
	      AND org_id = org_id_in
        LOOP
            found := 1;
            current_members_val := cfp.current_members;
            max_members_val := cfp.max_members;
        END LOOP;

        -- not found: either the channel fam doesn't have an entry in cfp, or the org doesn't have access to it.
        -- either way, there are no available subscriptions

        IF found IS NULL
        THEN
            RETURN 0;
        END IF;

        -- null max members?  in that case, pass it on; NULL means infinite
        IF max_members_val IS NULL
        THEN
            RETURN NULL;
        END IF;

        -- otherwise, return the delta
        RETURN max_members_val - current_members_val;
    END$$ language plpgsql;

    CREATE OR REPLACE FUNCTION available_fve_family_subs(channel_family_id_in IN NUMERIC, org_id_in IN NUMERIC)
    RETURNS NUMERIC
    AS $$
    declare
        cfp record;
        fve_current_members_val NUMERIC;
        fve_max_members_val     NUMERIC;
        found               NUMERIC;
    BEGIN
        for cfp in SELECT * FROM rhnOrgChannelFamilyPermissions
	    WHERE channel_family_id = channel_family_id_in
	      AND org_id = org_id_in
        LOOP
            found := 1;
            fve_current_members_val := cfp.fve_current_members;
            fve_max_members_val := cfp.fve_max_members;
        END LOOP;

        -- not found: either the channel fam doesn't have an entry in cfp, or the org doesn't have access to it.
        -- either way, there are no available subscriptions

        IF found IS NULL
        THEN
            RETURN 0;
        END IF;

        -- null max members?  in that case, pass it on; NULL means infinite
        IF fve_max_members_val IS NULL
        THEN
            RETURN NULL;
        END IF;

        -- otherwise, return the delta
        RETURN fve_max_members_val - fve_current_members_val;
    END$$ language plpgsql;

    -- *******************************************************************
    -- FUNCTION: channel_family_current_members
    -- Calculates and returns the actual count of systems consuming
    --   physical channel subscriptions.
    -- Called by: update_family_counts
    --            rhn_entitlements.repoll_virt_guest_entitlements
    -- *******************************************************************
    create or replace function channel_family_current_members(channel_family_id_in IN NUMERIC,
                                            org_id_in IN NUMERIC)
    returns numeric
    as $$
    declare
        current_members_count numeric := 0;
    begin
        select  count(distinct server_id)
        into    current_members_count
          from  rhnChannelFamilyServerPhysical cfsp
         where  cfsp.channel_family_id = channel_family_id_in
           and  cfsp.customer_id = org_id_in;
        return current_members_count;
    end$$ language plpgsql;


    create or replace function cfam_curr_fve_members(
        channel_family_id_in IN NUMERIC,
        org_id_in IN NUMERIC)
    returns numeric
    as $$
    declare
        current_members_count numeric := 0;

    begin
        select count(sc.server_id)
          into current_members_count
          from rhnServerChannel sc,
               rhnChannelFamilyMembers cfm,
               rhnServer s
         where s.org_id = org_id_in
           and s.id = sc.server_id
           and cfm.channel_family_id = channel_family_id_in
           and cfm.channel_id = sc.channel_id
           and exists (
                select 1
                  from rhnChannelFamilyServerFve cfsp
                 where cfsp.CHANNEL_FAMILY_ID = channel_family_id_in
                   and cfsp.server_id = s.id
                );

        return current_members_count;
    end$$ language plpgsql;
    CREATE OR REPLACE FUNCTION update_family_counts(channel_family_id_in IN NUMERIC,
                                   org_id_in IN NUMERIC) returns void
    AS $$
    BEGIN
        update rhnPrivateChannelFamily
           set current_members = rhn_channel.channel_family_current_members(channel_family_id_in, org_id_in),
               fve_current_members = rhn_channel.cfam_curr_fve_members(channel_family_id_in,org_id_in)
         where org_id = org_id_in
           and channel_family_id = channel_family_id_in;
    END$$ language plpgsql;

    create or replace function update_group_family_counts(group_label_in IN VARCHAR,
                                   org_id_in IN NUMERIC)
    returns void
    as $$
    declare
        i record;
    BEGIN
        FOR i IN (
                SELECT DISTINCT CFM.channel_family_id, SG.org_id
                 FROM rhnChannelFamilyMembers CFM
                 JOIN rhnServerChannel SC
                   ON SC.channel_id = CFM.channel_id
                 JOIN rhnServerGroupMembers SGM
                   ON SC.server_id = SGM.server_id
                 JOIN rhnServerGroup SG
                   ON SGM.server_group_id = SG.id
                 JOIN rhnServerGroupType SGT
                   ON SG.group_type = SGT.id
                WHERE SGT.label = group_label_in
                  AND SG.org_id = org_id_in
                  AND SGT.is_base = 'Y'
        ) LOOP
            perform rhn_channel.update_family_counts(i.channel_family_id, i.org_id);
        END LOOP;
    END$$ language plpgsql;

    CREATE OR REPLACE FUNCTION available_chan_subscriptions(channel_id_in IN NUMERIC,
                                          org_id_in IN NUMERIC)
    RETURNS NUMERIC
    AS $$
    declare
            channel_family_id_val NUMERIC;
    BEGIN
        SELECT channel_family_id INTO STRICT channel_family_id_val
            FROM rhnChannelFamilyMembers
            WHERE channel_id = channel_id_in;

            RETURN rhn_channel.available_family_subscriptions(
                           channel_family_id_val, org_id_in);
    END$$ language plpgsql;

    CREATE OR REPLACE FUNCTION available_fve_chan_subs(channel_id_in IN NUMERIC,
                                          org_id_in IN NUMERIC)
    RETURNS NUMERIC
    AS $$
    declare
            channel_family_id_val NUMERIC;
    BEGIN
        SELECT channel_family_id INTO STRICT channel_family_id_val
            FROM rhnChannelFamilyMembers
            WHERE channel_id = channel_id_in;

            RETURN rhn_channel.available_fve_family_subs(
                           channel_family_id_val, org_id_in);
    END$$ language plpgsql;

    create or replace function unsubscribe_server_from_family(server_id_in in numeric,
                                             channel_family_id_in in numeric)
    returns void
    as $$
    begin
        delete
        from    rhnServerChannel rsc
        where   rsc.server_id = server_id_in
            and channel_id in (
                select  rcfm.channel_id
                from    rhnChannelFamilyMembers rcfm
                where   rcfm.channel_family_id = channel_family_id_in);
    end$$ language plpgsql;

    create or replace function get_org_id(channel_id_in in numeric)
    returns numeric
    as $$
    declare
        org_id_out numeric;
    begin
        select org_id into strict org_id_out
            from rhnChannel
            where id = channel_id_in;

            return org_id_out;
    end$$ language plpgsql;

    create or replace function get_cfam_org_access(cfam_id_in in numeric, org_id_in in numeric)
    returns numeric
    as $$
    begin
      if exists(
                        select  1
                        from    rhnOrgChannelFamilyPermissions cfp
                        where   cfp.org_id = org_id_in
      ) then
                return 1;
      else
                return 0;
      end if;
    end$$ language plpgsql;

    create or replace function get_org_access(channel_id_in in numeric, org_id_in in numeric)
    returns integer
    as $$
    begin
        -- the idea: if we get past this query,
        -- the org has access to the channel, else not
        if exists(
        select 1
          from rhnChannelFamilyMembers CFM,
               rhnOrgChannelFamilyPermissions CFP
         where cfp.org_id = org_id_in
           and CFM.channel_family_id = CFP.channel_family_id
           and CFM.channel_id = channel_id_in
           and (CFP.max_members > 0 or CFP.max_members is null or CFP.org_id = 1) )
        then
          return 1;
        else
          return 0;
        end if;
    end$$ language plpgsql;

    -- check if a user has a given role, or if such a role is inferrable
    create or replace function user_role_check_debug(channel_id_in in numeric,
                                   user_id_in in numeric,
                                   role_in in varchar,
                                   status out numeric,
                                   reason_out out varchar)
    as $$
    declare
        org_id numeric;
    begin
        org_id := rhn_user.get_org_id(user_id_in);

        -- channel might be shared
        if role_in = 'subscribe' and
           rhn_channel.shared_user_role_check(channel_id_in, user_id_in, role_in) = 1 then
            status := 1;
            return;
        end if;

        if role_in = 'manage' and
           COALESCE(rhn_channel.get_org_id(channel_id_in), -1) <> org_id then
                reason_out := 'channel_not_owned';
               status := 0;
               return;
            end if;

        if role_in = 'subscribe' and
           rhn_channel.get_org_access(channel_id_in, org_id) = 0 then
                reason_out := 'channel_not_available';
                status := 0;
                return;
            end if;

        -- channel admins have all roles
        if rhn_user.check_role_implied(user_id_in, 'channel_admin') = 1 then
            reason_out := 'channel_admin';
            status := 1;
            return;
            end if;

        -- the subscribe permission is inferred
    -- UNLESS the not_globally_subscribable flag is set
        if role_in = 'subscribe'
        then
            if rhn_channel.org_channel_setting(channel_id_in,
                       org_id,
                       'not_globally_subscribable') = 0 then
                reason_out := 'globally_subscribable';
                status := 1;
                return;
            end if;
        end if;

        -- all other roles (manage right now) are explicitly granted
        reason_out := 'direct_permission';
        status := rhn_channel.direct_user_role_check(channel_id_in,
                                              user_id_in, role_in);
        return;
    end$$ language plpgsql;

    -- same as above, but with no OUT param; useful in views, etc
    create or replace function user_role_check(channel_id_in in numeric, user_id_in in numeric, role_in in varchar)
    returns numeric
    as $$
    declare
        throwaway record;
    begin
        throwaway := rhn_channel.user_role_check_debug(channel_id_in, user_id_in, role_in);
        return throwaway.status;
    end$$ language plpgsql;

    --
    -- For multiorg phase II, this function simply checks to see if the user's
    -- has a trust relationship that includes this channel by id.
    --
    create or replace function shared_user_role_check(channel_id in numeric, user_id in numeric, role in varchar)
    returns numeric
    as $$
    declare
      n numeric;
      oid numeric;
    begin
      oid := rhn_user.get_org_id(user_id);
      select 1 into n
      from rhnSharedChannelView s
      where s.id = channel_id and s.org_trust_id = oid;

      if not found then
        return 0;
      end if;

      return 1;
    end$$ language plpgsql;

    -- same as above, but returns 1 if user_id_in is null
    -- This is useful in queries where user_id is not specified
    create or replace function loose_user_role_check(channel_id_in in numeric, user_id_in in numeric, role_in in varchar)
    returns numeric
    as $$
    begin
        if user_id_in is null then
            return 1;
        end if;
        return rhn_channel.user_role_check(channel_id_in, user_id_in, role_in);
    end$$ language plpgsql;

    -- directly checks the table, no inferred permissions
    create or replace function direct_user_role_check(channel_id_in in numeric, user_id_in in numeric, role_in in varchar)
    returns numeric
    as $$
    declare
        throwaway numeric;
    begin
        -- the idea: if we get past this query, the user has the role, else no
        select 1 into throwaway
          from rhnChannelPermissionRole CPR,
               rhnChannelPermission CP
         where CP.user_id = user_id_in
           and CP.channel_id = channel_id_in
           and CPR.label = role_in
           and CP.role_id = CPR.id;

      if not found then
        return 0;
      end if;

      return 1;
    end$$ language plpgsql;

    -- check if an org has a certain setting
    create or replace function org_channel_setting(channel_id_in in numeric, org_id_in in numeric, setting_in in varchar)
    returns numeric
    as $$
    declare
        throwaway numeric;
    begin
        -- the idea: if we get past this query, the org has the setting
        select 1 into throwaway
          from rhnOrgChannelSettingsType OCST,
               rhnOrgChannelSettings OCS
         where OCS.org_id = org_id_in
           and OCS.channel_id = channel_id_in
           and OCST.label = setting_in
           and OCS.setting_id = OCST.id;

      if not found then
        return 0;
      end if;

      return 1;
    end$$ language plpgsql;

    CREATE OR REPLACE FUNCTION channel_priority(channel_id_in IN numeric)
    RETURNS numeric
    AS $$
    declare
         channel_name varchar(256);
         priority numeric;
         end_of_life_val timestamptz;
         org_id_val numeric;
    BEGIN

        select name, end_of_life, org_id
        into channel_name, end_of_life_val, org_id_val
        from rhnChannel
        where id = channel_id_in;

        if end_of_life_val is not null then
          return -400;
        end if;

        if channel_name like 'Red Hat Enterprise Linux%' or channel_name like 'RHEL%' then
          priority := 1000;
          if channel_name not like '%Beta%' then
            priority := priority + 1000;
          end if;

          priority := priority +
            case
              when channel_name like '%v. 5%' then 600
              when channel_name like '%v. 4%' then 500
              when channel_name like '%v. 3%' then 400
              when channel_name like '%v. 2%' then 300
              when channel_name like '%v. 1%' then 200
              else 0
            end;

          priority := priority +
            case
              when channel_name like 'Red Hat Enterprise Linux (v. 5%' then 60
              when (channel_name like '%AS%' and channel_name not like '%Extras%') then 50
              when (channel_name like '%ES%' and channel_name not like '%Extras%') then 40
              when (channel_name like '%WS%' and channel_name not like '%Extras%') then 30
              when (channel_name like '%Desktop%' and channel_name not like '%Extras%') then 20
              when channel_name like '%Extras%' then 10
              else 0
            end;

          priority := priority +
            case
              when channel_name like '%)' then 5
              else 0
            end;

          priority := priority +
            case
              when channel_name like '%32-bit x86%' then 4
              when channel_name like '%64-bit Intel Itanium%' then 3
              when channel_name like '%64-bit AMD64/Intel EM64T%' then 2
              else 0
            end;
        elsif channel_name like 'Red Hat Desktop%' then
            priority := 900;

            if channel_name not like '%Beta%' then
               priority := priority + 50;
            end if;

          priority := priority +
            case
              when channel_name like '%v. 4%' then 40
              when channel_name like '%v. 3%' then 30
              when channel_name like '%v. 2%' then 20
              when channel_name like '%v. 1%' then 10
              else 0
            end;

          priority := priority +
            case
              when channel_name like '%32-bit x86%' then 4
              when channel_name like '%64-bit Intel Itanium%' then 3
              when channel_name like '%64-bit AMD64/Intel EM64T%' then 2
              else 0
            end;

        elsif org_id_val is not null then
          priority := 600;
        else
          priority := 500;
        end if;

      return -priority;

    end$$ language plpgsql;

    -- right now this only does the accounting changes; the cascade
    -- actually does the rhnServerChannel delete.
    create or replace function delete_server_channels(server_id_in in numeric) returns void
    as $$
    begin
        update  rhnPrivateChannelFamily
        set     current_members = current_members -1
        where   org_id in (
                        select  org_id
                        from    rhnServer
                        where   id = server_id_in
                )
                and channel_family_id in (
                        select  rcfm.channel_family_id
                        from    rhnChannelFamilyMembers rcfm,
                                rhnServerChannel rsc
                        where   rsc.server_id = server_id_in
                                and rsc.channel_id = rcfm.channel_id
                and not exists (
                    select 1
                    from
                        rhnChannelFamilyVirtSubLevel cfvsl,
                        rhnSGTypeVirtSubLevel sgtvsl,
                        rhnServerEntitlementView sev,
                        rhnVirtualInstance vi
                    where
                        -- system is a virtual instance
                        vi.virtual_system_id = server_id_in
                        and vi.host_system_id = sev.server_id
                        -- system's host has a virt ent
                        and sev.label in ('virtualization_host',
                                          'virtualization_host_platform')
                        and sev.server_group_type_id =
                            sgtvsl.server_group_type_id
                        -- the host's virt ent grants a cf virt sub level
                        and sgtvsl.virt_sub_level_id = cfvsl.virt_sub_level_id
                        -- the cf is in that virt sub level
                        and cfvsl.channel_family_id = rcfm.channel_family_id
                    )
                );
    end$$ language plpgsql;

        -- this could certainly be optimized to do updates if needs be
        create or replace function refresh_newest_package(channel_id_in in numeric, caller_in in varchar default '(unknown)') returns void
        as $$
        begin
                delete from rhnChannelNewestPackage where channel_id = channel_id_in;
                insert into rhnChannelNewestPackage
                        ( channel_id, name_id, evr_id, package_id, package_arch_id )
                        (       select  channel_id,
                                                name_id, evr_id,
                                                package_id, package_arch_id
                                from    rhnChannelNewestPackageView
                                where   channel_id = channel_id_in
                        );
                insert into rhnChannelNewestPackageAudit (channel_id, caller)
                    values (channel_id_in, caller_in);
                update rhnChannel
                    set last_modified = greatest(current_timestamp, last_modified + interval '1 second')
                    where id = channel_id_in;
        end$$ language plpgsql;

   create or replace function update_channel ( channel_id_in in numeric, invalidate_ss in numeric default 0,
                              date_to_use in timestamptz default current_timestamp ) returns void
   as $$
   declare
   channel_last_modified timestamptz;
   last_modified_value timestamptz;

   snapshots cursor for
   select  snapshot_id id
   from    rhnSnapshotChannel
   where   channel_id = channel_id_in;

   begin

      select last_modified
      into channel_last_modified
      from rhnChannel
      where id = channel_id_in;

      last_modified_value := date_to_use;

      if last_modified_value <= channel_last_modified then
          last_modified_value := last_modified_value + interval '1 second';
      end if;

      update rhnChannel set last_modified = last_modified_value
      where id = channel_id_in;

      if invalidate_ss = 1 then
        for snapshot in snapshots loop
            update rhnSnapshot
            set invalid = lookup_snapshot_invalid_reason('channel_modified')
            where id = snapshot.id;
        end loop;
      end if;

   end$$ language plpgsql;

   create or replace function update_channels_by_package ( package_id_in in numeric, date_to_use in timestamptz default current_timestamp ) returns void
   as $$
   declare
   channels cursor for
   select channel_id
   from rhnChannelPackage
   where package_id = package_id_in
   order by channel_id;

   begin
      for channel in channels loop
         -- we want to invalidate the snapshot assocated with the channel when we
         -- do this b/c we know we've added or removed or packages
         perform rhn_channel.update_channel ( channel.channel_id, 1, date_to_use );
      end loop;
   end$$ language plpgsql;


   create or replace function update_channels_by_errata ( errata_id_in numeric, date_to_use in timestamptz default current_timestamp ) returns void
   as $$
   declare
   channels cursor for
   select channel_id
   from rhnChannelErrata
   where errata_id = errata_id_in
   order by channel_id;

   begin
      for channel in channels loop
         -- we won't invalidate snapshots, b/c just changing the errata associated with
         -- a channel shouldn't invalidate snapshots
         perform rhn_channel.update_channel ( channel.channel_id, 0, date_to_use );
      end loop;
   end$$ language plpgsql;

   create or replace function update_needed_cache(channel_id_in in numeric) returns void
   as $$
   declare
   server record;
   begin
      -- we intentionaly do a loop here instead of one huge select
      -- b/c we want to break update into smaller transaction to unblock other sessions
      -- querying rhnServerNeededCache
      for server in (
                select sc.server_id as id
                  from rhnServerChannel sc
                 where sc.channel_id = channel_id_in
      ) loop
         perform rhn_server.update_needed_cache(server.id);
      end loop;
   end$$ language plpgsql;

-- restore the original setting
update pg_settings set setting = overlay( setting placing '' from 1 for (length('rhn_channel')+1) ) where name = 'search_path';
 070701000006AA000081B400000000000000000000000167AE111400002AE4000000000000000000000000000000000000005E00000000susemanager-schema/upgrade/spacewalk-schema-1.5-to-spacewalk-schema-1.6/092-delete_server.sql 
create or replace
function delete_server (
        server_id_in in numeric
) returns void 
as
$$
declare
         servergroups cursor for
                select  server_id, server_group_id
                from    rhnServerGroupMembers sgm
                where   sgm.server_id = server_id_in;

         configchannels cursor for
                select  cc.id
                from    rhnConfigChannel cc,
                        rhnConfigChannelType cct,
                        rhnServerConfigChannel scc
                where   1=1
                        and scc.server_id = server_id_in
                        and scc.config_channel_id = cc.id
                        -- these config channel types are reserved
                        -- for use by a single server, so we don't
                        -- need to check for other servers subscribed
                        and cct.label in
                                ('local_override','server_import')
                        and cct.id = cc.confchan_type_id;

    is_virt boolean;
begin
        perform rhn_channel.delete_server_channels(server_id_in);
        -- rhn_channel.clear_subscriptions(server_id_in);

        -- filelists
        delete from rhnFileList where id in (
	select	spfl.file_list_id
	  from	rhnServerPreserveFileList spfl
	 where	spfl.server_id = server_id_in
			and not exists (
				select	1
				from	rhnServerPreserveFileList
				where	file_list_id = spfl.file_list_id
					and server_id != server_id_in
				union all
				select	1
				from	rhnKickstartPreserveFileList
				where	file_list_id = spfl.file_list_id
			)
        );

	for configchannel in configchannels loop
		perform rhn_config.delete_channel(configchannel.id);
	end loop;

      is_virt := exists (
       select 1
        from rhnServerEntitlementView
       where server_id = server_id_in
         and label in ('virtualization_host', 'virtualization_host_platform')
      );

	for sgm in servergroups loop
		perform rhn_server.delete_from_servergroup(
			sgm.server_id, sgm.server_group_id);
	end loop;

    if is_virt then
        perform rhn_entitlements.repoll_virt_guest_entitlements(server_id_in);
    end if;

        -- we're handling this instead of letting an "on delete
        -- set null" do it so that we don't run the risk
        -- of setting off the triggers and killing us with a
        -- mutating table

        -- this is merge of two single updates:
        --  update ... set old_server_id = null where old_server_id = server_id_in;
        --  update ... set new_server_id = null where new_server_id = server_id_in;
        -- so we scan rhnKickstartSession table only once
        update rhnKickstartSession
                set old_server_id = case when old_server_id = server_id_in then null else old_server_id end,
                    new_server_id = case when new_server_id = server_id_in then null else new_server_id end
                where old_server_id = server_id_in
                   or new_server_id = server_id_in;

        perform rhn_channel.clear_subscriptions(server_id_in, 1, 1);

        -- A little complicated here, but the goal is to
        -- delete records from rhnVirtualInstace only if we don't
        -- care about them anymore.  We don't care about records
        -- in rhnVirtualInstance if we are deleting the host
        -- system and the virtual system is already null, or
        -- vice-versa.  We *do* care about them if either the
        -- host or virtual system is still registered because we
        -- still want them to show up in the UI.
    -- If there's a newer row in rhnVirtualInstance with the same
    -- uuid, this guest must have been re-registered, so we can clean
    -- this data up.

        delete from rhnVirtualInstance vi
              where (host_system_id = server_id_in and virtual_system_id is null)
                 or (virtual_system_id = server_id_in and host_system_id is null)
                 or (vi.virtual_system_id = server_id_in and vi.modified < (select max(vi2.modified)
                    from rhnVirtualInstance vi2 where vi2.uuid = vi.uuid));

        -- this is merge of two single updates:
        --  update ... set host_system_id = null where host_system_id = server_id_in;
        --  update ... set virtual_system_id = null where virtual_system_id = server_id_in;
        -- so we scan rhnVirtualInstance table only once
        update rhnVirtualInstance
           set host_system_id = case when host_system_id = server_id_in then null else host_system_id end,
               virtual_system_id = case when virtual_system_id = server_id_in then null else virtual_system_id end
         where host_system_id = server_id_in
            or virtual_system_id = server_id_in;

        -- this is merge of two single updates:
        --  update ... set old_host_system_id = null when old_host_system_id = server_id_in;
        --  update ... set new_host_system_id = null when new_host_system_id = server_id_in;
        -- so we scan rhnVirtualInstanceEventLog table only once
        update rhnVirtualInstanceEventLog
           set old_host_system_id = case when old_host_system_id = server_id_in then null else old_host_system_id end,
               new_host_system_id = case when new_host_system_id = server_id_in then null else new_host_system_id end
         where old_host_system_id = server_id_in
            or new_host_system_id = server_id_in;

        -- We're deleting everything with a foreign key to rhnServer
        -- here, now.  I'm hoping this will help aleviate our deadlock
        -- problem.

        delete from rhnActionConfigChannel where server_id = server_id_in;
        delete from rhnActionConfigRevision where server_id = server_id_in;
        delete from rhnActionPackageRemovalFailure where server_id = server_id_in;
        delete from rhnClientCapability where server_id = server_id_in;
        delete from rhnCpu where server_id = server_id_in;
        -- there's still a cascade here, because the constraint keeps the
        -- table locked for too long to rebuild it.  Ugh...
        delete from rhnDevice where server_id = server_id_in;
        delete from rhnProxyInfo where server_id = server_id_in;
        delete from rhnRam where server_id = server_id_in;
        delete from rhnRegToken where server_id = server_id_in;
        delete from rhnSatelliteInfo where server_id = server_id_in;
        -- this cascades to rhnActionConfigChannel and rhnActionConfigFileName
        delete from rhnServerAction where server_id = server_id_in;
        delete from rhnServerActionPackageResult where server_id = server_id_in;
        delete from rhnServerActionScriptResult where server_id = server_id_in;
        delete from rhnServerActionVerifyResult where server_id = server_id_in;
        delete from rhnServerActionVerifyMissing where server_id = server_id_in;
        -- counts are handled above.  this should be a delete_ function.
        delete from rhnServerChannel where server_id = server_id_in;
        delete from rhnServerConfigChannel where server_id = server_id_in;
        delete from rhnServerCustomDataValue where server_id = server_id_in;
        delete from rhnServerDMI where server_id = server_id_in;
        delete from rhnServerEvent where server_id = server_id_in;
        delete from rhnServerHistory where server_id = server_id_in;
        delete from rhnServerInfo where server_id = server_id_in;
        delete from rhnServerInstallInfo where server_id = server_id_in;
        delete from rhnServerLocation where server_id = server_id_in;
        delete from rhnServerLock where server_id = server_id_in;
        delete from rhnServerNeededCache where server_id = server_id_in;
        delete from rhnServerNetwork where server_id = server_id_in;
        delete from rhnServerNotes where server_id = server_id_in;
        -- I'm not removing the foreign key from rhnServerPackage; that'll
        -- take forever.  Do the delete anyway.
        delete from rhnServerPackage where server_id = server_id_in;
        delete from rhnServerTokenRegs where server_id = server_id_in;
        delete from rhnSnapshotTag where server_id = server_id_in;
        -- this cascades to:
        --   rhnSnapshotChannel, rhnSnapshotConfigChannel, rhnSnapshotPackage,
        --   rhnSnapshotConfigRevision, rhnSnapshotServerGroup,
        --   rhnSnapshotTag.
        -- We may want to consider delete_snapshot() at some point, but
        --   I don't think we need to yet.
        delete from rhnSnapshot where server_id = server_id_in;
        delete from rhnUserServerPrefs where server_id = server_id_in;
        -- hrm, this one's interesting... we _probably_ should delete
        -- everything for the parent server_id when we delete the proxy,
        -- but we don't currently.
        delete from rhnServerPath where server_id_in in (server_id, proxy_server_id);
        delete from rhnUserServerPerms where server_id = server_id_in;

        delete from rhnServerNetInterface where server_id = server_id_in;
        delete from rhn_server_monitoring_info where recid = server_id_in;

        delete from rhnAppInstallSession where server_id = server_id_in;
        delete from rhnServerUuid where server_id = server_id_in;

    -- We delete all the probes running directly against this system
    -- and any probes that were using this Server as a Proxy Scout.
    DELETE FROM rhn_probe_state PS WHERE PS.probe_id IN (
     SELECT CP.probe_id
       FROM rhn_check_probe CP  
      WHERE CP.host_id = server_id_in
         OR CP.sat_cluster_id in
    (SELECT SN.sat_cluster_id
       FROM rhn_sat_node SN
      WHERE SN.server_id = server_id_in)
    );

    DELETE FROM rhn_probe P  WHERE P.recid IN (
     SELECT CP.probe_id
       FROM rhn_check_probe CP  
      WHERE CP.host_id = server_id_in
         OR CP.sat_cluster_id in
    (SELECT SN.sat_cluster_id
       FROM rhn_sat_node SN
      WHERE SN.server_id = server_id_in)
    );

    -- delete from time_series TODO

        delete from rhn_check_probe where host_id = server_id_in;
        delete from rhn_host_probe where host_id = server_id_in;

    delete from rhn_sat_cluster where recid in
      ( select sat_cluster_id from rhn_sat_node where server_id = server_id_in );

        delete from rhn_sat_node where server_id = server_id_in;

        delete from rhnPushClient where server_id = server_id_in;

        -- now get rhnServer itself.
        delete
        from    rhnServer
                where id = server_id_in;

        delete
        from    rhnSet
        where   1=1
                and user_id in (
                        select  wc.id
                        from    rhnServer rs,
                                web_contact wc
                        where   rs.id = server_id_in
                                and rs.org_id = wc.org_id
                )
                and label = 'system_list'
                and element = server_id_in;
end;
$$
language plpgsql;

070701000006AB000081B400000000000000000000000167AE11140000023D000000000000000000000000000000000000006400000000susemanager-schema/upgrade/spacewalk-schema-1.5-to-spacewalk-schema-1.6/095-rhn_host_monitoring.sql   drop view rhn_host_monitoring;
create or replace view rhn_host_monitoring
(
	recid,
	ip,
	name,
	description,
	customer_id,
	os_id,
	asset_id,
	last_update_user,
	last_update_date
) as
select  s.id            as recid,
	rhn_server.get_ip_address(s.id)	as ip,
        s.name          as name,
        s.description   as description,
        s.org_id        as customer_id,
        4               as os_id,
        to_number(null,null) as asset_id,
        cast(null as char)   as last_update_user,
        cast(null as TIMESTAMPTZ)   as last_update_date
from	rhnServer	s
;
   070701000006AC000081B400000000000000000000000167AE111400000036000000000000000000000000000000000000006400000000susemanager-schema/upgrade/spacewalk-schema-1.5-to-spacewalk-schema-1.6/096-add_rhnServerNetwor.sql   alter table rhnServerNetwork add ip6addr VARCHAR(45);
  070701000006AD000081B400000000000000000000000167AE1114000002CB000000000000000000000000000000000000006700000000susemanager-schema/upgrade/spacewalk-schema-1.5-to-spacewalk-schema-1.6/100-rhnContentSourceFilter.sql    
create table
rhnContentSourceFilter
(
        id		NUMERIC NOT NULL
			constraint rhn_csf_id_pk primary key,
        source_id		NUMERIC
			constraint rhn_csf_source_fk
                                references rhnContentSource (id),
        sort_order	NUMERIC NOT NULL,
        flag            VARCHAR(1) NOT NULL
                        check (flag in ('+','-')),
        filter          VARCHAR(4000) NOT NULL,
        created         TIMESTAMPTZ default(CURRENT_TIMESTAMP) NOT NULL,
        modified        TIMESTAMPTZ default(CURRENT_TIMESTAMP) NOT NULL
)

  ;


create sequence rhn_csf_id_seq start with 500;

CREATE UNIQUE INDEX rhn_csf_sid_so_uq
    ON rhnContentSourceFilter (source_id, sort_order)
    ;

 070701000006AE000081B400000000000000000000000167AE11140000003C000000000000000000000000000000000000007200000000susemanager-schema/upgrade/spacewalk-schema-1.5-to-spacewalk-schema-1.6/101-add_rhnKickstartScript_scriptname.sql alter table rhnKickstartScript add script_name VARCHAR(40);
070701000006AF000081B400000000000000000000000167AE111400000914000000000000000000000000000000000000006F00000000susemanager-schema/upgrade/spacewalk-schema-1.5-to-spacewalk-schema-1.6/102-set_ks_session_history_message.sql    --
-- Copyright (c) 2008--2011 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--

-- this seems like maybe it should have action_id as well?
-- maybe optional?

create or replace function
set_ks_session_history_message (
        kickstart_session_id_in in numeric,
        state_label_in in varchar,
        message_in in varchar
) returns void as
$$
declare
        states cursor is
                select  id
                from    rhnKickstartSessionState
                where   label = state_label_in;

                
		history_items cursor (state_id_in numeric) is
                select  id
                from    rhnKickstartSessionHistory
                where   kickstart_session_id = kickstart_session_id_in
                        and state_id = state_id_in
                order by time desc;

                id_states_curs numeric;
                id_history_items_curs numeric;
                
begin
	for id_states_curs in states
        loop
		for id_history_items_curs in history_items(id_states_curs.id)
                loop
                        update rhnKickstartSessionHistory
                                set message = message_in
                                where id = id_history_items_curs.id;
                        return;
                end loop;

                insert into rhnKickstartSessionHistory (
                                id, kickstart_session_id, state_id, message
                        ) values (
                                nextval('rhn_ks_sessionhist_id_seq'),
                                kickstart_session_id_in,
                                id_states_cursor,
                                message_in
                        );
                return;
        end loop;
end;
$$
language plpgsql;

070701000006B0000081B400000000000000000000000167AE1114000001E4000000000000000000000000000000000000006C00000000susemanager-schema/upgrade/spacewalk-schema-1.5-to-spacewalk-schema-1.6/105-alter_rhnServerNetInterface.sql   
alter table rhnServerNetInterface add id numeric;

create sequence rhn_srv_net_iface_id_seq;

alter table rhnServerNetInterface disable trigger rhn_srv_net_iface_mod_trig;
update rhnServerNetInterface set id = nextval('rhn_srv_net_iface_id_seq');
alter table rhnServerNetInterface enable trigger rhn_srv_net_iface_mod_trig;

alter table rhnServerNetInterface alter column id set not null;

alter table rhnServerNetInterface add constraint rhn_srv_net_iface_id_pk primary key ( id );
070701000006B1000081B400000000000000000000000167AE111400000538000000000000000000000000000000000000006900000000susemanager-schema/upgrade/spacewalk-schema-1.5-to-spacewalk-schema-1.6/110-add_rhnServerNetAddress4.sql  --
-- Copyright (c) 2011--2013 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnServerNetAddress4
(
    interface_id  NUMERIC NOT NULL
                   CONSTRAINT rhn_srv_net_iaddress4_iid_fk
                       REFERENCES rhnServerNetInterface (id)
                       ON DELETE CASCADE,
    address    VARCHAR(64),
    netmask    VARCHAR(64),
    broadcast  VARCHAR(64),
    created    TIMESTAMPTZ
                   DEFAULT (CURRENT_TIMESTAMP) NOT NULL,
    modified   TIMESTAMPTZ
                   DEFAULT (CURRENT_TIMESTAMP) NOT NULL
)

;

CREATE INDEX rhn_srv_net_addr4_iid_addr_idx
    ON rhnServerNetAddress4 (interface_id, address)
    ;

ALTER TABLE rhnServerNetAddress4
    ADD CONSTRAINT rhn_srv_net_addr4_iid_addr_uq UNIQUE (interface_id, address);
070701000006B2000081B400000000000000000000000167AE1114000000B7000000000000000000000000000000000000006E00000000susemanager-schema/upgrade/spacewalk-schema-1.5-to-spacewalk-schema-1.6/111-add_rhnServerNetAddress4_data.sql INSERT INTO rhnServerNetAddress4
    (interface_id, address, netmask, broadcast, created)
    SELECT id, ip_addr, netmask, broadcast, created
    FROM rhnServerNetInterface;

COMMIT;
 070701000006B3000081B400000000000000000000000167AE1114000000A7000000000000000000000000000000000000007300000000susemanager-schema/upgrade/spacewalk-schema-1.5-to-spacewalk-schema-1.6/115-drop_columns_rhnServerNetInterface.sql    ALTER TABLE rhnServerNetInterface DROP COLUMN ip_addr;
ALTER TABLE rhnServerNetInterface DROP COLUMN netmask;
ALTER TABLE rhnServerNetInterface DROP COLUMN broadcast;
 070701000006B4000081B400000000000000000000000167AE111400000544000000000000000000000000000000000000006900000000susemanager-schema/upgrade/spacewalk-schema-1.5-to-spacewalk-schema-1.6/120-add_rhnServerNetAddress6.sql  --
-- Copyright (c) 2011--2013 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnServerNetAddress6
(
    interface_id  NUMERIC NOT NULL
                   CONSTRAINT rhn_srv_net_iaddress6_iid_fk
                       REFERENCES rhnServerNetInterface (id)
                       ON DELETE CASCADE,
    address    VARCHAR(45),
    netmask    VARCHAR(49),
    scope      VARCHAR(64),
    created    TIMESTAMPTZ
                   DEFAULT (CURRENT_TIMESTAMP) NOT NULL,
    modified   TIMESTAMPTZ
                   DEFAULT (CURRENT_TIMESTAMP) NOT NULL
)

;

CREATE INDEX rhn_srv_net_ad6_iid_sc_ad_idx
    ON rhnServerNetAddress6 (interface_id, scope, address)
    ;

ALTER TABLE rhnServerNetAddress6
    ADD CONSTRAINT rhn_srv_net_ad6_iid_sc_ad_uq UNIQUE (interface_id, scope, address);
070701000006B5000081B400000000000000000000000167AE111400005ACF000000000000000000000000000000000000006A00000000susemanager-schema/upgrade/spacewalk-schema-1.5-to-spacewalk-schema-1.6/121-rhn_server-get_ip_address.sql --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.

--update pg_setting
update pg_settings set setting = 'rhn_server,' || setting where name = 'search_path';

    create or replace function system_service_level(
	server_id_in in numeric,
	service_level_in in varchar
    ) returns numeric as $$
    declare
    ents cursor is
      select label from rhnServerEntitlementView
      where server_id = server_id_in;

    retval numeric := 0;

    begin
         for ent in ents loop
            retval := rhn_entitlements.entitlement_grants_service (ent.label, service_level_in);
            if retval = 1 then
               return retval;
            end if;
         end loop;

         return retval;

    end$$ language plpgsql;


    create or replace function can_change_base_channel(server_id_in IN NUMERIC)
    returns numeric
    as $$
    declare
	throwaway numeric;
    begin
	-- the idea: if we get past this query, the server is
	-- neither sat nor proxy, so base channel is changeable

	select 1 into throwaway
	  from rhnServer S
	 where S.id = server_id_in
	   and not exists (select 1 from rhnSatelliteInfo SI where SI.server_id = S.id)
	   and not exists (select 1 from rhnProxyInfo PI where PI.server_id = S.id);

        if not found then
	    return 0;
        end if;

	return 1;
    end$$ language plpgsql;

    create or replace function set_custom_value(
	server_id_in in numeric,
	user_id_in in numeric,
	key_label_in in varchar,
	value_in in varchar
    ) returns void
    as $$
    declare
	key_id_val numeric;
    begin
	select CDK.id into strict key_id_val
	  from rhnCustomDataKey CDK,
	       rhnServer S
	 where S.id = server_id_in
	   and S.org_id = CDK.org_id
	   and CDK.label = key_label_in;

	begin
	    insert into rhnServerCustomDataValue (server_id, key_id, value, created_by, last_modified_by)
	    values (server_id_in, key_id_val, value_in, user_id_in, user_id_in);
	exception
	    when UNIQUE_VIOLATION
		then
		update rhnServerCustomDataValue
		   set value = value_in,
		       last_modified_by = user_id_in
		 where server_id = server_id_in
		   and key_id = key_id_val;
	end;

    end$$ language plpgsql;

    create or replace function bulk_set_custom_value(
	key_label_in in varchar,
	value_in in varchar,
	set_label_in in varchar,
	set_uid_in in numeric
    )
    returns integer
    as $$
    declare
        i integer;
        server record;
    begin
        i := 0;
	for server in
	   SELECT user_id, label, element, element_two
	     FROM rhnSet
	    WHERE label = set_label_in
	      AND user_id = set_uid_in
	loop
	    if rhn_server.system_service_level(server.element, 'provisioning') = 1 then
		perform rhn_server.set_custom_value(server.element, set_uid_in, key_label_in, value_in);
            i := i + 1;
	    end if;
	end loop;
    return i;
    end$$ language plpgsql;

    create or replace function bulk_snapshot_tag(
	org_id_in in numeric,
        tagname_in in varchar,
	set_label_in in varchar,
	set_uid_in in numeric
    ) returns void
    as $$
    declare
        server record;
	snapshot_id numeric;
    begin
	for server in
	   SELECT user_id, label, element, element_two
	     FROM rhnSet
	    WHERE label = set_label_in
	      AND user_id = set_uid_in
	loop
	    if rhn_server.system_service_level(server.element, 'provisioning') = 1 then
		    select max(id) into snapshot_id
		    from rhnSnapshot
		    where server_id = server.element;

		    if snapshot_id is null then
			perform rhn_server.snapshot_server(server.element, 'tagging system:  ' || tagname_in);

			select max(id) into snapshot_id
			from rhnSnapshot
			where server_id = server.element;
		    end if;

		-- now have a snapshot_id to work with...
		begin
		    perform rhn_server.tag_snapshot(snapshot_id, org_id_in, tagname_in);
		exception
		    when UNIQUE_VIOLATION
			then
			-- do nothing, be forgiving...
			null;
		end;
	    end if;
	end loop;
    end$$ language plpgsql;

    create or replace function tag_delete(
	server_id_in in numeric,
	tag_id_in in numeric
    ) returns void
    as $$
    declare
	snapshots cursor is
		select	snapshot_id
		from	rhnSnapshotTag
		where	tag_id = tag_id_in;
	tag_id_tmp numeric;
    begin
	select	id into tag_id_tmp
	from	rhnTag
	where	id = tag_id_in
	for update;

	delete
		from	rhnSnapshotTag
		where	server_id = server_id_in
			and tag_id = tag_id_in;
	for snapshot in snapshots loop
		return;
	end loop;
	delete
		from rhnTag
		where id = tag_id_in;
    end$$ language plpgsql;

    create or replace function tag_snapshot(
        snapshot_id_in in numeric,
	org_id_in in numeric,
	tagname_in in varchar
    ) returns void
    as $$
    begin
	insert into rhnSnapshotTag (snapshot_id, server_id, tag_id)
	select snapshot_id_in, server_id, lookup_tag(org_id_in, tagname_in)
	from rhnSnapshot
	where id = snapshot_id_in;
    end$$ language plpgsql;

    create or replace function bulk_snapshot(
	reason_in in varchar,
	set_label_in in varchar,
	set_uid_in in numeric
    ) returns void
    as $$
    declare
        server record;
    begin
	for server in
	   SELECT user_id, label, element, element_two
	     FROM rhnSet
	    WHERE label = set_label_in
	      AND user_id = set_uid_in
	loop
	    if rhn_server.system_service_level(server.element, 'provisioning') = 1 then
		perform rhn_server.snapshot_server(server.element, reason_in);
	    end if;
	end loop;
    end$$ language plpgsql;

    create or replace function snapshot_server(
	server_id_in in numeric,
	reason_in in varchar
    ) returns void
    as $$
    declare
	snapshot_id_v numeric;
	revisions cursor is
		select distinct
			cr.id
		from	rhnConfigRevision	cr,
			rhnConfigFileName	cfn,
			rhnConfigFile		cf,
			rhnConfigChannel	cc,
			rhnServerConfigChannel	scc
		where	1=1
			and scc.server_id = server_id_in
			and scc.config_channel_id = cc.id
			and cc.id = cf.config_channel_id
			and cf.id = cr.config_file_id
			and cr.id = cf.latest_config_revision_id
			and cf.config_file_name_id = cfn.id
			and cf.id = lookup_first_matching_cf(scc.server_id, cfn.path);
	locked integer;
    begin
	select nextval('rhn_snapshot_id_seq') into snapshot_id_v;

	insert into rhnSnapshot (id, org_id, server_id, reason) (
		select	snapshot_id_v,
			s.org_id,
			server_id_in,
			reason_in
		from	rhnServer s
		where	s.id = server_id_in
	);
	insert into rhnSnapshotChannel (snapshot_id, channel_id) (
		select	snapshot_id_v, sc.channel_id
		from	rhnServerChannel sc
		where	sc.server_id = server_id_in
	);
	insert into rhnSnapshotServerGroup (snapshot_id, server_group_id) (
		select	snapshot_id_v, sgm.server_group_id
		from	rhnServerGroupMembers sgm
		where	sgm.server_id = server_id_in
	);
        locked := 0;
        <<iloop>>
        while true loop
            begin
                insert into rhnPackageNEVRA (id, name_id, evr_id, package_arch_id)
                select nextval('rhn_pkgnevra_id_seq'), sp.name_id, sp.evr_id, sp.package_arch_id
                from rhnServerPackage sp
                where sp.server_id = server_id_in
                        and not exists
                        (select 1
                                from rhnPackageNEVRA nevra
                                where nevra.name_id = sp.name_id
                                        and nevra.evr_id = sp.evr_id
                                        and (nevra.package_arch_id = sp.package_arch_id
                                            or (nevra.package_arch_id is null
                                                and sp.package_arch_id is null)));
                exit iloop;
            exception when unique_violation then
                if locked = 1 then
                    raise;
                else
                    lock table rhnPackageNEVRA in exclusive mode;
                    locked := 1;
                end if;
            end;
        end loop;
	insert into rhnSnapshotPackage (snapshot_id, nevra_id) (
                select distinct snapshot_id_v, nevra.id
                from    rhnServerPackage sp, rhnPackageNEVRA nevra
                where   sp.server_id = server_id_in
                        and nevra.name_id = sp.name_id
                        and nevra.evr_id = sp.evr_id
                        and (nevra.package_arch_id = sp.package_arch_id
                            or (nevra.package_arch_id is null
                                and sp.package_arch_id is null))
	);

	insert into rhnSnapshotConfigChannel ( snapshot_id, config_channel_id ) (
		select	snapshot_id_v, scc.config_channel_id
		from	rhnServerConfigChannel scc
		where	server_id = server_id_in
	);

	for revision in revisions loop
		insert into rhnSnapshotConfigRevision (
				snapshot_id, config_revision_id
			) values (
				snapshot_id_v, revision.id
			);
	end loop;
    end$$ language plpgsql;

    create or replace function remove_action(
	server_id_in in numeric,
	action_id_in in numeric
    ) returns void
    as $$
    declare
	-- this really wants "nulls last", but 8.1.7.3.0 sucks ass.
	-- instead, we make a local table that holds our
	-- list of ids with null prereqs.  There's surely a better way
	-- (an array instead of a table maybe?  who knows...)
	-- but I've got code to do this handy that I can look at ;)
	chained_actions cursor is
                with recursive r(id, prerequisite) as (
			select	id, prerequisite
			from	rhnAction
			where id = action_id_in
		union all
			select	r1.id, r1.prerequisite
			from	rhnAction r1, r
			where r.id = r1.prerequisite
		)
		select * from r
		order by prerequisite desc;
	sessions cursor is
		select	s.id
		from	rhnKickstartSession s
		where	server_id_in in (s.old_server_id, s.new_server_id)
			and s.action_id = action_id_in
			and not exists (
				select	1
				from	rhnKickstartSessionState ss
				where	ss.id = s.state_id
					and ss.label in ('failed','complete')
			);
	chain_ends numeric[];
	i numeric;
	prereq numeric := 1;
    begin
	select	prerequisite
	into	prereq
	from	rhnAction
	where	id = action_id_in;

	if prereq is not null then
		perform rhn_exception.raise_exception('action_is_child');
	end if;

        chain_ends := '{}';
	i := 1;
	for action in chained_actions loop
		if action.prerequisite is null then
			chain_ends[i] := action.id;
			i := i + 1;
		else
			delete from rhnServerAction
				where server_id = server_id_in
				and action_id = action.id;
		end if;
	end loop;

	delete from rhnServerAction
		where server_id = server_id_in
		and action_id = any(chain_ends);

	for s in sessions loop
		update rhnKickstartSession
			set 	state_id = (
					select	id
					from	rhnKickstartSessionState
					where	label = 'failed'
				),
				action_id = null
			where	id = s.id;
		perform set_ks_session_history_message(s.id, 'failed', 'Kickstart cancelled due to action removal');
	end loop;
    end$$ language plpgsql;

    create or replace function check_user_access(server_id_in in numeric, user_id_in in numeric)
    returns numeric
    as $$
    declare
	has_access numeric;
    begin
	-- first check; if this returns no rows, then the server/user are in different orgs, and we bail
        select 1 into has_access
	  from rhnServer S,
	       web_contact wc
	 where wc.org_id = s.org_id
	   and s.id = server_id_in
	   and wc.id = user_id_in;

        if not found then
          return 0;
        end if;

	-- okay, so they're in the same org.  if we have an org admin, they get a free pass
	if rhn_user.check_role(user_id_in, 'org_admin') = 1
	then
	    return 1;
	end if;

	select 1 into has_access
	  from rhnServerGroupMembers SGM,
	       rhnUserServerGroupPerms USG
	 where SGM.server_group_id = USG.server_group_id
	   and SGM.server_id = server_id_in
	   and USG.user_id = user_id_in;

        if not found then
          return 0;
        end if;

	return 1;
    end$$ language plpgsql;

    -- *******************************************************************
    -- FUNCTION: can_server_consume_virt_slot
    -- Returns 1 if the server id is eligible to consume a virtual slot,
    --   else returns 0.
    -- Called by: insert_into_servergroup, delete_from_servergroup
    -- *******************************************************************
    create or replace function can_server_consume_virt_slot(server_id_in in numeric,
                                           group_type_in in varchar)
    returns numeric
    as $$
    declare
        server_virt_slots cursor is
            select vi.VIRTUAL_SYSTEM_ID
            from
                rhnVirtualInstance vi
            where
                -- server id is a virtual instance
                vi.VIRTUAL_SYSTEM_ID = server_id_in
                -- server id's host is virt entitled
                and exists ( select 1
                     from rhnServerEntitlementView sev
                 where vi.HOST_SYSTEM_ID = sev.server_id
                 and sev.label in ('virtualization_host',
                                   'virtualization_host_platform') )
                -- server id's host also has the ent we want
                and exists ( select 1
                     from rhnServerEntitlementView sev2
                 where vi.HOST_SYSTEM_ID = sev2.server_id
                 and sev2.label = group_type_in );

    begin
        for server_virt_slot in server_virt_slots loop
            return 1;
        end loop;
        return 0;
    end$$ language plpgsql;


    create or replace function insert_into_servergroup (
		server_id_in in numeric,
		server_group_id_in in numeric
    ) returns void
    as $$
    declare
		used_slots numeric;
		max_slots numeric;
		org_id numeric;
		mgmt_available numeric;
		mgmt_upgrade numeric;
		mgmt_sgid numeric;
		prov_available numeric;
		prov_upgrade numeric;
		prov_sgid numeric;
		group_label varchar;
		group_type numeric;
	begin
		-- first, group_type = null, because it's easy...

		-- this will rowlock the servergroup we're trying to change;
		-- we probably need to lock the other one, but I think the chances
		-- of it being a real issue are very small for now...
		select	sg.group_type, sg.org_id, sg.current_members, sg.max_members
		into	group_type, org_id, used_slots, max_slots
		from	rhnServerGroup sg
		where	sg.id = server_group_id_in
		for update of sg;

		if group_type is null then
			if used_slots >= max_slots then
				perform rhn_exception.raise_exception('servergroup_max_members');
			end if;

			insert into rhnServerGroupMembers(
					server_id, server_group_id
				) values (
					server_id_in, server_group_id_in
				);
			update rhnServerGroup
				set current_members = current_members + 1
				where id = server_group_id_in;

			perform rhn_cache.update_perms_for_server_group(server_group_id_in);
			return;
		end if;

		-- now for group_type != null
		--
		select	label
		into	group_label
		from	rhnServerGroupType	sgt
		where	sgt.id = group_type;

		-- the naive easy path that gets hit most often and has to be quickest.
		if group_label in ('sw_mgr_entitled',
                           'enterprise_entitled',
                           'monitoring_entitled',
                           'provisioning_entitled',
                           'virtualization_host',
                           'virtualization_host_platform') then
			if used_slots >= max_slots and
               (rhn_server.can_server_consume_virt_slot(server_id_in, group_label) != 1)
               then
				perform rhn_exception.raise_exception('servergroup_max_members');
			end if;

			insert into rhnServerGroupMembers(
					server_id, server_group_id
				) values (
					server_id_in, server_group_id_in
				);

            -- Only update current members if the system in consuming a
            -- physical slot.
            if rhn_server.can_server_consume_virt_slot(server_id_in, group_label) = 0 then
                update rhnServerGroup
                set current_members = current_members + 1
                where id = server_group_id_in;
            end if;

			return;
		end if;
	end$$ language plpgsql;

	create or replace function insert_into_servergroup_maybe (
		server_id_in in numeric,
		server_group_id_in in numeric
	) returns numeric as $$
    declare
		retval numeric := 0;
		servergroups cursor is
			select	s.id	server_id,
					sg.id	server_group_id
			from	rhnServerGroup	sg,
					rhnServer		s
			where	s.id = server_id_in
				and sg.id = server_group_id_in
				and s.org_id = sg.org_id
				and not exists (
					select	1
					from	rhnServerGroupMembers sgm
					where	sgm.server_id = s.id
						and sgm.server_group_id = sg.id
				);
	begin
		for sgm in servergroups loop
			perform rhn_server.insert_into_servergroup(sgm.server_id, sgm.server_group_id);
			retval := retval + 1;
		end loop;
		return retval;
	end$$ language plpgsql;

	create or replace function insert_set_into_servergroup (
		server_group_id_in in numeric,
		user_id_in in numeric,
		set_label_in in varchar
	) returns void
        as $$
    declare
		servers cursor is
			select	st.element	id
			from	rhnSet		st
			where	st.user_id = user_id_in
				and st.label = set_label_in
				and exists (
					select	1
					from	rhnUserManagedServerGroups umsg
					where	umsg.server_group_id = server_group_id_in
						and umsg.user_id = user_id_in
					)
				and not exists (
					select	1
					from	rhnServerGroupMembers sgm
					where	sgm.server_id = st.element
						and sgm.server_group_id = server_group_id_in
				);
	begin
		for s in servers loop
			perform rhn_server.insert_into_servergroup(s.id, server_group_id_in);
		end loop;
	end$$ language plpgsql;

    create or replace function delete_from_servergroup (
	server_id_in in numeric,
		server_group_id_in in numeric
    ) returns void
    as $$
    declare
        server_virt_groups cursor is
            select 1
            from rhnServerEntitlementVirtual sev
            where sev.server_id = server_id_in
            and sev.server_group_id = server_group_id_in;

		oid numeric;
		mgmt_sgid numeric;
		label varchar;
		group_type numeric;
	begin
			select	sg.group_type, sg.org_id
			into	group_type,	oid
			from	rhnServerGroupMembers	sgm,
					rhnServerGroup			sg
			where	sg.id = server_group_id_in
				and sg.id = sgm.server_group_id
				and sgm.server_id = server_id_in
			for update of sg;

			if not found then
				perform rhn_exception.raise_exception('server_not_in_group');
			end if;

		-- do group_type is null first
		if group_type is null then
			delete from rhnServerGroupMembers
				where server_group_id = server_group_id_in
				and	server_id = server_id_in;
			update rhnServerGroup
				set current_members = current_members - 1
				where id = server_group_id_in;
			perform rhn_cache.update_perms_for_server_group(server_group_id_in);
			return;
		end if;

		select	sgt.label
		into	label
		from	rhnServerGroupType sgt
		where	sgt.id = group_type;

		if label in ('sw_mgr_entitled',
                     'enterprise_entitled',
                     'provisioning_entitled',
                     'monitoring_entitled',
                     'virtualization_host',
                     'virtualization_host_platform') then

            -- Only update current members if the system is consuming
            -- a physical slot.
            for server_virt_group in server_virt_groups loop
                delete from rhnServerGroupMembers
                where server_group_id = server_group_id_in
                and	server_id = server_id_in;
                return;
            end loop;

            delete from rhnServerGroupMembers
            where server_group_id = server_group_id_in
            and	server_id = server_id_in;

            update rhnServerGroup
            set current_members = current_members - 1
            where id = server_group_id_in;

		end if;
	end$$ language plpgsql;

	create or replace function delete_set_from_servergroup (
		server_group_id_in in numeric,
		user_id_in in numeric,
		set_label_in in varchar
	) returns void
        as $$
        declare
		servergroups cursor is
			select	sgm.server_id, sgm.server_group_id
			from	rhnSet st,
					rhnServerGroupMembers sgm
			where	sgm.server_group_id = server_group_id_in
				and st.user_id = user_id_in
				and st.label = set_label_in
				and sgm.server_id = st.element
				and exists (
					select	1
					from	rhnUserManagedServerGroups usgp
					where	usgp.server_group_id = server_group_id_in
						and usgp.user_id = user_id_in
				);
	begin
		for sgm in servergroups loop
			perform rhn_server.delete_from_servergroup(sgm.server_id, server_group_id_in);
		end loop;
	end$$ language plpgsql;

	create or replace function clear_servergroup (
		server_group_id_in in numeric
	) returns void
        as $$
        declare
		servers cursor is
			select	sgm.server_id	id
			from	rhnServerGroupMembers sgm
			where	sgm.server_group_id = server_group_id_in;
	begin
		for s in servers loop
			perform rhn_server.delete_from_servergroup(s.id, server_group_id_in);
		end loop;
	end$$ language plpgsql;

	create or replace function delete_from_org_servergroups (
		server_id_in in numeric
	) returns void
        as $$
        declare
		servergroups cursor is
			select	sgm.server_group_id id
			from	rhnServerGroup sg,
					rhnServerGroupMembers sgm
			where	sgm.server_id = server_id_in
				and sgm.server_group_id = sg.id
				and sg.group_type is null;
	begin
		for sg in servergroups loop
			perform rhn_server.delete_from_servergroup(server_id_in, sg.id);
		end loop;
	end$$ language plpgsql;

	create or replace function get_ip_address (
		server_id_in in numeric
	) returns varchar as $$
        declare
		interfaces cursor is
			select	ni.name as name, na4.address as address
			from	rhnServerNetInterface ni,
			        rhnServerNetAddress4 na4
			where	server_id = server_id_in
                and ni.id = na4.interface_id
				and na4.address != '127.0.0.1';
		addresses cursor is
			select	ipaddr ip_addr
			from	rhnServerNetwork
			where	server_id = server_id_in
				and ipaddr != '127.0.0.1';
	begin
		for addr in addresses loop
			return addr.ip_addr;
		end loop;
		for iface in interfaces loop
			return iface.address;
		end loop;
		return NULL;
	end$$ language plpgsql;

    create or replace function update_needed_cache(
        server_id_in in numeric
	) returns void as $$
    begin
        delete from rhnServerNeededCache
         where server_id = server_id_in;
        insert into rhnServerNeededCache
               (server_id, errata_id, package_id)
               (select distinct server_id, errata_id, package_id
                  from rhnServerNeededView
                 where server_id = server_id_in);
	end$$ language plpgsql;

-- restore the original setting
update pg_settings set setting = overlay( setting placing '' from 1 for (length('rhn_server')+1) ) where name = 'search_path';
 070701000006B6000081B400000000000000000000000167AE1114000002B7000000000000000000000000000000000000006400000000susemanager-schema/upgrade/spacewalk-schema-1.5-to-spacewalk-schema-1.6/122-get_hw_info_as_clob.sql   
create or replace function get_hw_info_as_clob(
	sid in rhnserver.id%TYPE,
	separator in varchar
)
returns text
as
$$
declare
	ret text;
	rec record;
begin
	for rec in (
		select m
		from (
			select 1 n, sum(nrcpu) || ' CPUs' m
			from rhncpu where rhncpu.server_id = sid
			union all
			select 2, ni.name||' '||coalesce(na4.address,'')||'/'||coalesce(na4.netmask,'')||' '||ni.hw_addr val
			from rhnservernetinterface ni,
			     rhnServerNetAddress4 na4
			where ni.server_id = sid
			  and ni.id = na4.interface_id
			) X
		order by n, m
		) loop
		if ret is null then
			ret := rec.m;
		else
			ret := ret || separator || rec.m;
		end if;
	end loop;
	return ret;
end;
$$ language plpgsql;
 070701000006B7000081B400000000000000000000000167AE1114000001F1000000000000000000000000000000000000006E00000000susemanager-schema/upgrade/spacewalk-schema-1.5-to-spacewalk-schema-1.6/123-trigger-rhnServerNetInterface.sql create or replace function rhn_srv_net_iface_mod_trig_fun() returns trigger as
$$
begin
    if new.id is null then
        new.id := nextval('rhn_srv_net_iface_id_seq');
    end if;
    new.modified := current_timestamp;
    return new;
end;
$$ language plpgsql;

drop trigger if exists rhn_srv_net_iface_mod_trig on rhnServerNetInterface;

create trigger
rhn_srv_net_iface_mod_trig
before insert or update on rhnServerNetInterface
for each row
execute procedure rhn_srv_net_iface_mod_trig_fun();
   070701000006B8000081B400000000000000000000000167AE111400000038000000000000000000000000000000000000006200000000susemanager-schema/upgrade/spacewalk-schema-1.5-to-spacewalk-schema-1.6/124-rhnPushDispatcher.sql alter table rhnPushDispatcher add password VARCHAR(32);
070701000006B9000081B400000000000000000000000167AE111400000141000000000000000000000000000000000000006300000000susemanager-schema/upgrade/spacewalk-schema-1.5-to-spacewalk-schema-1.6/125-alter-index-rhnRam.sql    
delete from rhnram X
	where server_id in (select server_id from rhnram group by server_id having count(server_id)>1)
	 and id<(select max(id) from rhnram Y where X.server_id=Y.server_id group by server_id having count(server_id)>1);

drop index rhn_ram_sid_idx;

create unique index rhn_ram_sid_uq on rhnRam(server_id);
   070701000006BA000081B400000000000000000000000167AE111400000152000000000000000000000000000000000000006300000000susemanager-schema/upgrade/spacewalk-schema-1.5-to-spacewalk-schema-1.6/126-alter-index-rhnCpu.sql    
delete from rhncpu X
	where server_id in (select server_id from rhncpu group by server_id having count(server_id)>1)
	 and id<(select max(id) from rhncpu Y where X.server_id=Y.server_id group by server_id having count(server_id)>1);

DROP INDEX rhn_cpu_server_id_idx;

CREATE UNIQUE INDEX rhn_cpu_server_id_uq
    ON rhnCpu (server_id);
  070701000006BB000081B400000000000000000000000167AE111400000178000000000000000000000000000000000000006900000000susemanager-schema/upgrade/spacewalk-schema-1.5-to-spacewalk-schema-1.6/127-alter-index-rhnServerDmi.sql  
delete from rhnServerDMI X
       where server_id in (select server_id from rhnServerDMI group by server_id having count(server_id)>1)
        and id<(select max(id) from rhnServerDMI Y where X.server_id=Y.server_id group by server_id having count(server_id)>1);

DROP INDEX rhn_server_dmi_sid_idx;

CREATE UNIQUE INDEX rhn_server_dmi_sid_uq
    ON rhnServerDMI (server_id);
070701000006BC000081B400000000000000000000000167AE11140000078E000000000000000000000000000000000000006400000000susemanager-schema/upgrade/spacewalk-schema-1.5-to-spacewalk-schema-1.6/130-rhn_prepare_install.sql   --
-- Copyright (c) 2008--2011 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--

--monitoring stored procedure

create or replace function
rhn_prepare_install
(
    username            in rhn_command_queue_instances.last_update_user%type,
    install_command     in rhn_command_queue_instances.command_id%type
)
returns rhn_command_queue_instances.recid%type
as $$
declare
    /* ignore this command if it has not been run after five minutes */
    stale_after_minutes numeric := 10;

    /* should take no more than five minutes to run the install */
    max_execution_time_seconds numeric := 10 * 60;

    command_instance_id rhn_command_queue_instances.recid%type;
begin
    select nextval('rhn_command_q_inst_recid_seq')
    into command_instance_id;
    

    insert into rhn_command_queue_instances (
        recid,
        command_id,
        notes,
        expiration_date,
        notify_email,
        timeout,
        date_submitted,
        last_update_user,
        last_update_date
    )
    values (
        command_instance_id,
        install_command,
        null, /* no notes */
        current_timestamp + stale_after_minutes * '1 minute'::interval,
        null, /* no notification email */
        max_execution_time_seconds,
        current_timestamp,
        username,
        current_timestamp
    );

    return command_instance_id;
end; $$
language plpgsql;
  070701000006BD000081B400000000000000000000000167AE11140000075B000000000000000000000000000000000000006B00000000susemanager-schema/upgrade/spacewalk-schema-1.5-to-spacewalk-schema-1.6/131-rhn_install_org_satellites.sql    --
-- Copyright (c) 2008--2011 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--

--monitoring stored procedure


create or replace function
rhn_install_org_satellites
(
    for_customer_id in web_customer.id%type,
    sat_cluster_id in rhn_sat_cluster.recid%type,
    username in rhn_command_queue_instances.last_update_user%type
) returns void 
as
$$ 
declare

-- the cursor is defined such that the following behavior occurs based on the sat_cluster_id param:
--   null results in all of a customer's scout being configured.
--   an id for a scout belonging to the cust results in just that scout being configured
--   an id for a scout not belonging to the cust results in no action.

    satellite_cursor cursor for
        select recid from rhn_sat_cluster
        where customer_id = for_customer_id
        and recid not in (
            select netsaint_id from rhn_ll_netsaint
        )
        except
        select recid from rhn_sat_cluster
        where customer_id = for_customer_id
        and recid not in (sat_cluster_id);

    command_instance_id rhn_command_queue_instances.recid%type;

begin
    command_instance_id := rhn_prepare_install(username, 1);

    for satellite in satellite_cursor loop
        perform rhn_install_satellite(command_instance_id, satellite.recid);
    end loop;
end 
$$
language plpgsql;

 070701000006BE000081B400000000000000000000000167AE1114000003BF000000000000000000000000000000000000007200000000susemanager-schema/upgrade/spacewalk-schema-1.5-to-spacewalk-schema-1.6/132-rhnServerNetwork-update-rhn_probe.sql 
create or replace function rhn_servnet_ipaddr_mon_trig_fun() returns trigger as
$$
declare
	updateit boolean = false;
begin
	if tg_op ='INSERT' then
		updateit = true;
	elsif tg_op ='UPDATE' then
		if old.ipaddr is null and new.ipaddr is not null
			or old.ipaddr is not null and new.ipaddr is null
			or old.ipaddr <> new.ipaddr
			or old.ip6addr is null and new.ip6addr is not null
			or old.ip6addr is not null and new.ip6addr is null
			or old.ip6addr <> new.ip6addr then
			updateit = true;
		end if;
	end if;
	if updateit then
		update rhn_probe
		set last_update_user = 'IP change',
			last_update_date = current_timestamp
		where (recid, probe_type) in (
			select probe_id, probe_type
			from rhn_check_probe
			where host_id = new.server_id
		);
	end if;
	return new;
end;
$$ language plpgsql;

create trigger
rhn_servnet_ipaddr_mon_trig
after insert or update on rhnServerNetwork
for each row
execute procedure rhn_servnet_ipaddr_mon_trig_fun();

 070701000006BF000081B400000000000000000000000167AE111400000068000000000000000000000000000000000000006500000000susemanager-schema/upgrade/spacewalk-schema-1.5-to-spacewalk-schema-1.6/133-rhn_tasko_run_id_seq.sql  SELECT PG_CATALOG.SETVAL('rhn_tasko_run_id_seq', (SELECT nextval('rhn_tasko_template_id_seq')), false);
070701000006C0000081B400000000000000000000000167AE11140000001B000000000000000000000000000000000000004F00000000susemanager-schema/upgrade/spacewalk-schema-1.5-to-spacewalk-schema-1.6/README    -- Schema upgrade scripts.
 070701000006C1000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000004800000000susemanager-schema/upgrade/spacewalk-schema-1.6-to-spacewalk-schema-1.7   070701000006C2000081B400000000000000000000000167AE11140000004A000000000000000000000000000000000000007000000000susemanager-schema/upgrade/spacewalk-schema-1.6-to-spacewalk-schema-1.7/001-rhnServerAction-result_msg-size.sql   alter table rhnServerAction modify ( result_msg VARCHAR(1024) );

commit;
  070701000006C3000081B400000000000000000000000167AE111400000394000000000000000000000000000000000000006500000000susemanager-schema/upgrade/spacewalk-schema-1.6-to-spacewalk-schema-1.7/001-rhn_entitlements.pks.sql  
-- setup search_path so that these functions are created in appropriate schema.
update pg_settings set setting = 'rhn_entitlements,' || setting where name = 'search_path';

    drop function set_group_count (
               customer_id_in in numeric,      -- customer_id
               type_in in char,                        -- 'U' or 'S'
               group_type_in in numeric,       -- rhn[User|Server]GroupType.id
               quantity_in in numeric,         -- quantity
               update_family_countsYN in numeric     -- call update_family_counts inside
    );

    drop function prune_group (
         group_id_in in numeric,
         type_in in char,
         quantity_in in numeric,
         update_family_countsYN in numeric
    );

-- restore the original setting
update pg_settings set setting = overlay( setting placing '' from 1 for (length('rhn_entitlements')+1) ) where name = 'search_path';
070701000006C4000081B400000000000000000000000167AE11140000281A000000000000000000000000000000000000006500000000susemanager-schema/upgrade/spacewalk-schema-1.6-to-spacewalk-schema-1.7/002-rhn_entitlements.pkb.sql  
-- setup search_path so that these functions are created in appropriate schema.
update pg_settings set setting = 'rhn_entitlements,' || setting where name = 'search_path';

    -- *******************************************************************
    -- PROCEDURE: prune_group
    -- Unsubscribes servers consuming physical slots that over the org's
    --   limit.
    -- Called by: set_server_group_count, repoll_virt_guest_entitlements
    -- *******************************************************************
    create or replace function prune_group (
        group_id_in in numeric,
        quantity_in in numeric,
        update_family_countsYN in numeric default 1
    ) returns void
as $$
    declare
        sgrecord record;
      type_is_base char;
    begin
            update      rhnServerGroup
                set     max_members = quantity_in
                where   id = group_id_in;

            for sgrecord in (
		   select  server_id, server_group_id, sgt.id as group_type_id, sgt.label
		    from    rhnServerGroupType              sgt,
				    rhnServerGroup                  sg,
				    rhnServerGroupMembers   sgm
		    where   1=1
			    and sgm.server_group_id = group_id_in
			    and sgm.server_id in (
				    select  sep.server_id
				    from
					rhnServerEntitlementPhysical sep
				    where
					sep.server_group_id = group_id_in
				    order by sep.modified asc
				    offset quantity_in
				)
			    and sgm.server_group_id = sg.id
			    and sg.group_type = sgt.id
	    ) loop
                perform rhn_entitlements.remove_server_entitlement(sgrecord.server_id, sgrecord.label);
            
            select is_base 
            into type_is_base
            from rhnServerGroupType sgt
            where sgt.id = sgrecord.group_type_id;

            -- if we're removing a base ent, then be sure to
            -- remove the server's channel subscriptions.
            if ( type_is_base = 'Y' ) then
                   perform rhn_channel.clear_subscriptions(sgrecord.server_id, 0, update_family_countsYN);
            end if;

            end loop;
    end$$
language plpgsql;

    -- *******************************************************************
    -- PROCEDURE: assign_system_entitlement
    --
    -- Moves system entitlements from from_org_id_in to to_org_id_in.
    -- Can raise not_enough_entitlements_in_base_org if from_org_id_in
    -- does not have enough entitlements to cover the move.
    -- Takes care of unentitling systems if necessary by calling 
    -- set_server_group_count
    -- *******************************************************************
    create or replace function assign_system_entitlement(
        group_label_in in varchar,
        from_org_id_in in numeric,
        to_org_id_in in numeric,
        quantity_in in numeric
    ) returns void
as $$
    declare
        prev_ent_count numeric;
    to_org_prev_ent_count numeric;
        new_ent_count numeric;
    new_quantity numeric;
        group_type numeric;
    begin

            select max_members
            into prev_ent_count
            from rhnServerGroupType sgt,
                 rhnServerGroup sg
            where sg.org_id = from_org_id_in
              and sg.group_type = sgt.id
              and sgt.label = group_label_in;

            if not found then
                perform rhn_exception.raise_exception(
                              'not_enough_entitlements_in_base_org');
            end if;

            select max_members
            into to_org_prev_ent_count
            from rhnServerGroupType sgt,
                 rhnServerGroup sg
            where sg.org_id = to_org_id_in
              and sg.group_type = sgt.id
              and sgt.label = group_label_in;

            if not found then
                to_org_prev_ent_count := 0;
            end if;
    
            select id
            into group_type
            from rhnServerGroupType
            where label = group_label_in;

            if not found then
                perform rhn_exception.raise_exception(
                              'invalid_server_group');
            end if;

        new_ent_count := prev_ent_count - quantity_in;
    
        if prev_ent_count > new_ent_count then
            new_quantity := to_org_prev_ent_count + quantity_in;
        end if;
    
        if new_ent_count < 0 then
            perform rhn_exception.raise_exception(
                          'not_enough_entitlements_in_base_org');
        end if;


        perform rhn_entitlements.set_server_group_count(from_org_id_in,
                                         group_type,
                                         new_ent_count);

        perform rhn_entitlements.set_server_group_count(to_org_id_in,
                                         group_type,
                                         new_quantity);
        
        -- Create or delete the entries in rhnOrgEntitlementType
        if group_label_in = 'enterprise_entitled' then 
            if new_quantity > 0 then
                perform rhn_entitlements.set_customer_enterprise(to_org_id_in);
            else
                perform rhn_entitlements.unset_customer_enterprise(to_org_id_in);
            end if;
        end if;

        if group_label_in = 'provisioning_entitled' then
            if new_quantity > 0 then
                perform rhn_entitlements.set_customer_provisioning(to_org_id_in);
            else
                perform rhn_entitlements.unset_customer_provisioning(to_org_id_in);
            end if;
        end if;

        if group_label_in = 'monitoring_entitled' then
            if new_quantity > 0 then
                perform rhn_entitlements.set_customer_monitoring(to_org_id_in);
            else
                perform rhn_entitlements.unset_customer_monitoring(to_org_id_in);
            end if;
        end if;

    end$$
language plpgsql;

    -- *******************************************************************
    -- PROCEDURE: activate_system_entitlement
    --
    -- Sets the values in rhnServerGroup for a given rhnServerGroupType.
    -- 
    -- Calls: set_server_group_count to update, prune, or create the group.
    -- Called by: the code that activates a satellite cert. 
    --
    -- Raises not_enough_entitlements_in_base_org if all entitlements
    -- in the org are used so the free entitlements would not cover
    -- the difference when descreasing the number of entitlements.
    -- *******************************************************************
    create or replace function activate_system_entitlement(
        org_id_in in numeric,
        group_label_in in varchar,
        quantity_in in numeric
    ) returns void
as $$
    declare
        prev_ent_count numeric; 
        prev_ent_count_sum numeric; 
        group_type numeric;
    begin

        -- Fetch the current entitlement count for the org
        -- into prev_ent_count

            select current_members
            into prev_ent_count
            from rhnServerGroupType sgt,
                 rhnServerGroup sg
            where sg.group_type = sgt.id
              and sgt.label = group_label_in
              and sg.org_id = org_id_in;

            if not found then
                prev_ent_count := 0;
            end if;

            select id
            into group_type
            from rhnServerGroupType
            where label = group_label_in;

            if not found then
                perform rhn_exception.raise_exception(
                              'invalid_server_group');
            end if;

        -- If we're setting the total entitlemnt count to a lower value,
        -- and that value is less than the allocated count in this org,
        -- we need to raise an exception.
        if quantity_in < prev_ent_count then
            perform rhn_exception.raise_exception(
                          'not_enough_entitlements_in_base_org');
        else
            -- don't update family counts after every server
            -- will do bulk update afterwards
            perform rhn_entitlements.set_server_group_count(org_id_in,
                                             group_type,
                                             quantity_in,
                                             0);
            -- bulk update family counts
            perform rhn_channel.update_group_family_counts(group_label_in, org_id_in);
        end if;

    end$$
language plpgsql;


    create or replace function set_server_group_count (
        customer_id_in in numeric,  -- customer_id
        group_type_in in numeric,   -- rhn[User|Server]GroupType.id
        quantity_in in numeric,      -- quantity
                update_family_countsYN in numeric default 1
    ) returns void
as $$
    declare
        group_id numeric;
        quantity numeric;
        wasfound boolean;
    begin
        quantity := quantity_in;
        if quantity is not null and quantity < 0 then
            quantity := 0;
        end if;

        select  rsg.id
        into    group_id
        from    rhnServerGroup rsg
        where   1=1
            and rsg.org_id = customer_id_in
            and rsg.group_type = group_type_in;

        -- preserve the not found status across the rhn_entitlements.prune_group invocation
        wasfound := true;
        if not found then
            wasfound := false;
        end if;

        perform rhn_entitlements.prune_group(
            group_id,
            quantity,
                        update_family_countsYN
        );

        if not wasfound then
            insert into rhnServerGroup (
                    id, name, description, max_members, current_members,
                    group_type, org_id, created, modified
                ) (
                    select  nextval('rhn_server_group_id_seq'), name, name,
                            quantity, 0, id, customer_id_in,
                            current_timestamp, current_timestamp
                    from    rhnServerGroupType
                    where   id = group_type_in
            );
        end if;

    end$$
language plpgsql;

-- restore the original setting
update pg_settings set setting = overlay( setting placing '' from 1 for (length('rhn_entitlements')+1) ) where name = 'search_path';
  070701000006C5000081B400000000000000000000000167AE11140000040C000000000000000000000000000000000000006000000000susemanager-schema/upgrade/spacewalk-schema-1.6-to-spacewalk-schema-1.7/003-rhn_channel.pkb.sql   
--update pg_setting
update pg_settings set setting = 'rhn_channel,' || setting where name = 'search_path';


    create or replace function get_org_access(channel_id_in in numeric, org_id_in in numeric)
    returns integer
    as $$
    begin
        -- the idea: if we get past this query,
        -- the org has access to the channel, else not
        if exists(
        select 1
          from rhnChannelFamilyMembers CFM,
               rhnOrgChannelFamilyPermissions CFP
         where cfp.org_id = org_id_in
           and CFM.channel_family_id = CFP.channel_family_id
           and CFM.channel_id = channel_id_in
           and (CFP.max_members > 0 or CFP.max_members is null or CFP.fve_max_members > 0 or CFP.fve_max_members is null or CFP.org_id = 1) )
        then
          return 1;
        else
          return 0;
        end if;
    end$$ language plpgsql;


-- restore the original setting
update pg_settings set setting = overlay( setting placing '' from 1 for (length('rhn_channel')+1) ) where name = 'search_path';
070701000006C6000081B400000000000000000000000167AE1114000004FC000000000000000000000000000000000000006E00000000susemanager-schema/upgrade/spacewalk-schema-1.6-to-spacewalk-schema-1.7/004-update_perms_for_server_group.sql 
-- setup search_path so that these functions are created in appropriate schema.
update pg_settings set setting = 'rhn_cache,' || setting where name = 'search_path';

	-- this means a server got added or removed, so we
	-- can't key off of a server anywhere.
create or replace function update_perms_for_server_group(
                server_group_id_in in numeric
        ) returns void 
as
$$
declare
       users cursor for
			-- org admins aren't affected, so don't test for them
			select	usgp.user_id id
			from	rhnUserServerGroupPerms usgp
			where	usgp.server_group_id = server_group_id_in
				and not exists (
					select	1
					from	rhnUserGroup ug,
							rhnUserGroupMembers ugm,
							rhnServerGroup sg,
							rhnUserGroupType ugt
					where	ugt.label = 'org_admin'
                                                and ugt.id = ug.group_type
						and sg.id = server_group_id_in
						and ugm.user_id = usgp.user_id
						and ug.org_id = sg.org_id
						and ugm.user_group_id = ug.id
					);
begin
	for u in users loop
		perform rhn_cache.update_perms_for_user(u.id);
	end loop;
end;
$$ language plpgsql;

-- restore the original setting
update pg_settings set setting = overlay( setting placing '' from 1 for (length('rhn_cache')+1) ) where name = 'search_path';
070701000006C7000081B400000000000000000000000167AE111400000756000000000000000000000000000000000000006000000000susemanager-schema/upgrade/spacewalk-schema-1.6-to-spacewalk-schema-1.7/006-rhn_channel-pkb.sql   

--update pg_setting
update pg_settings set setting = 'rhn_channel,' || setting where name = 'search_path';

    drop function refresh_newest_package(channel_id_in in numeric,
                                      caller_in in varchar);

    -- this could certainly be optimized to do updates if needs be
    create or replace function refresh_newest_package(channel_id_in in numeric,
                                      caller_in in varchar default '(unknown)',
                                      package_name_id_in in numeric default null)
    returns void
    as $$
    -- procedure refreshes rows for name_id = package_name_id_in or
    -- all rows if package_name_id_in is null
    begin
        delete from rhnChannelNewestPackage
              where channel_id = channel_id_in
                and (package_name_id_in is null
                     or name_id = package_name_id_in);
        insert into rhnChannelNewestPackage
                (channel_id, name_id, evr_id, package_id, package_arch_id)
                (select channel_id,
                        name_id, evr_id,
                        package_id, package_arch_id
                   from rhnChannelNewestPackageView
                  where channel_id = channel_id_in
                    and (package_name_id_in is null
                         or name_id = package_name_id_in)
                );
        insert into rhnChannelNewestPackageAudit (channel_id, caller)
             values (channel_id_in, caller_in);
        update rhnChannel
           set last_modified = greatest(current_timestamp,
                                        last_modified + interval '1 second')
         where id = channel_id_in;
    end$$ language plpgsql;


-- restore the original setting
update pg_settings set setting = overlay( setting placing '' from 1 for (length('rhn_channel')+1) ) where name = 'search_path';
  070701000006C8000081B400000000000000000000000167AE111400000EFC000000000000000000000000000000000000006500000000susemanager-schema/upgrade/spacewalk-schema-1.6-to-spacewalk-schema-1.7/007-rhnPackageGroup-trim.sql  
-- relink reference to group with trailing \n to correct one
update rhnpackage set package_group = (select n.id
                                         from rhnpackagegroup n
                                         join rhnpackagegroup o
                                           on substr(o.name, 1, length(o.name)-1) = n.name
                                          and o.id <> n.id
                                        where o.id = package_group)
                where package_group in (select o.id
                                          from rhnpackagegroup n
                                          join rhnpackagegroup o
                                            on substr(o.name, 1, length(o.name)-1) = n.name
                                           and o.id <> n.id);

update rhnpackagesource set package_group = (select n.id
                                         from rhnpackagegroup n
                                         join rhnpackagegroup o
                                           on substr(o.name, 1, length(o.name)-1) = n.name
                                          and o.id <> n.id
                                        where o.id = package_group)
                where package_group in (select o.id
                                          from rhnpackagegroup n
                                          join rhnpackagegroup o
                                            on substr(o.name, 1, length(o.name)-1) = n.name
                                           and o.id <> n.id);

-- delete unused groups
delete from rhnpackagegroup pg
      where not exists (select 1 from rhnpackage p where p.package_group = pg.id)
        and not exists (select 1 from rhnpackagesource p where p.package_group = pg.id)
        -- don't remove 'NoGroup'
        and id > 1;

-- remove trailing \n
update rhnpackagegroup set name = substr(name, 1, length(name)-1)
                     where name like '%' || chr(10);

-- relink reference to group with trailing space to correct one (without space)
update rhnpackage set package_group = (select n.id
                                         from rhnpackagegroup n
                                         join rhnpackagegroup o
                                           on trim(o.name) = n.name
                                          and o.id <> n.id
                                        where o.id = package_group)
                where package_group in (select o.id
                                          from rhnpackagegroup n
                                          join rhnpackagegroup o
                                            on trim(o.name) = n.name
                                           and o.id <> n.id);

update rhnPackageSource set package_group = (select n.id
                                         from rhnPackageGroup n
                                         join rhnPackageGroup o
                                           on trim(o.name) = n.name
                                          and o.id <> n.id
                                        where o.id = package_group)
                where package_group in (select o.id
                                          from rhnPackageGroup n
                                          join rhnPackageGroup o
                                            on trim(o.name) = n.name
                                           and o.id <> n.id);

-- delete unused groups
delete from rhnpackagegroup pg
      where not exists (select 1 from rhnpackage p where p.package_group = pg.id)
        and not exists (select 1 from rhnpackagesource p where p.package_group = pg.id)
        -- don't remove 'NoGroup'
        and id > 1;

-- remove trailing spaces from rest of packages
update rhnpackagegroup set name = trim(name)
                     where name like '% ';
070701000006C9000081B400000000000000000000000167AE1114000001EE000000000000000000000000000000000000006600000000susemanager-schema/upgrade/spacewalk-schema-1.6-to-spacewalk-schema-1.7/008-rhn_install_satellite.sql 
drop function if exists rhn_install_satellite(command_instance_id smallint, satellite_id numeric);

create or replace function
rhn_install_satellite
(
    command_instance_id in rhn_command_queue_instances.recid%type,
    satellite_id in rhn_sat_cluster.recid%type
)
returns void
as $$

begin
    insert into rhn_command_queue_execs (
           instance_id,
           netsaint_id,
           target_type)
    values (command_instance_id, satellite_id, 'cluster');
end; $$ language plpgsql;

  070701000006CA000081B400000000000000000000000167AE111400000607000000000000000000000000000000000000006400000000susemanager-schema/upgrade/spacewalk-schema-1.6-to-spacewalk-schema-1.7/009-rhn_prepare_install.sql   
create or replace function
rhn_prepare_install
(
    username            in rhn_command_queue_instances.last_update_user%type,
    install_command     in rhn_command_queue_instances.command_id%type
)
returns rhn_command_queue_instances.recid%type
as $$
declare
    /* ignore this command if it has not been run after five minutes */
    stale_after_minutes numeric := 10;

    /* should take no more than five minutes to run the install */
    max_execution_time_seconds numeric := 10 * 60;

    command_instance_id rhn_command_queue_instances.recid%type;
begin
    select nextval('rhn_command_q_inst_recid_seq')
    into command_instance_id;
    

    insert into rhn_command_queue_instances (
        recid,
        command_id,
        notes,
        expiration_date,
        notify_email,
        timeout,
        date_submitted,
        last_update_user,
        last_update_date
    )
    values (
        command_instance_id,
        install_command,
        null, /* no notes */
        current_timestamp + stale_after_minutes * '1 minute'::interval,
        null, /* no notification email */
        max_execution_time_seconds,
        current_timestamp,
        username,
        current_timestamp
    );

    return command_instance_id;
end; $$
language plpgsql;

drop function if exists rhn_prepare_install(username character varying, INOUT command_instance_id smallint, install_command smallint);
drop function if exists rhn_prepare_install(username character varying, INOUT command_instance_id numeric, install_command numeric);
 070701000006CB000081B400000000000000000000000167AE111400000034000000000000000000000000000000000000006D00000000susemanager-schema/upgrade/spacewalk-schema-1.6-to-spacewalk-schema-1.7/010-rhn_bl_obs_mod_trig_fun-drop.sql  
drop function if exists rhn_bl_obs_mod_trig_fun();
070701000006CC000081B400000000000000000000000167AE1114000003A4000000000000000000000000000000000000006400000000susemanager-schema/upgrade/spacewalk-schema-1.6-to-spacewalk-schema-1.7/011-rhn_contact_methods.sql   create or replace function rhn_cmeth_val_trig_fun() returns trigger as
$$
begin
    if new.method_type_id = 1 then

    --- pager fields pager_email,pager_split_long_messages should be not null
        if (new.pager_email   is null     or new.pager_split_long_messages  is null ) then
            raise exception 'missing or invalid data for contact_methods table'; --missing_data;
        end if;
    end if;

    if new.method_type_id = 2 then

    --- the all email fields but email_reply_to should be not null
        if new.email_address is null then
            raise exception 'missing or invalid data for contact_methods table';  --missing_data;
        end if;
    end if;

    return new;
end;
$$ language plpgsql;


drop trigger if exists rhn_cmeth_val_trig on rhn_contact_methods;

create trigger
rhn_cmeth_val_trig
before insert or update on rhn_contact_methods
for each row
execute procedure rhn_cmeth_val_trig_fun();
070701000006CD000081B400000000000000000000000167AE111400000A94000000000000000000000000000000000000005F00000000susemanager-schema/upgrade/spacewalk-schema-1.6-to-spacewalk-schema-1.7/012-rhn_server.pkb.sql    
--update pg_setting
update pg_settings set setting = 'rhn_server,' || setting where name = 'search_path';

    create or replace function bulk_set_custom_value(
    	key_label_in in varchar,
	value_in in varchar,
	set_label_in in varchar,
	set_uid_in in numeric
    )
    returns integer
    as $$
    declare
        i integer;
        server record;
    begin
        i := 0;
        for server in (
           SELECT user_id, label, element, element_two
	     FROM rhnSet
	    WHERE label = set_label_in
	      AND user_id = set_uid_in
	) loop
	    if rhn_server.system_service_level(server.element, 'provisioning') = 1 then
	    	perform rhn_server.set_custom_value(server.element, set_uid_in, key_label_in, value_in);
            i := i + 1;
	    end if;
	end loop;
    return i;
    end$$ language plpgsql;

    create or replace function bulk_snapshot_tag(
    	org_id_in in numeric,
        tagname_in in varchar,
	set_label_in in varchar,
	set_uid_in in numeric
    ) returns void
    as $$
    declare
        server record;
    	snapshot_id numeric;
    begin
        for server in (
           SELECT user_id, label, element, element_two
	     FROM rhnSet
	    WHERE label = set_label_in
	      AND user_id = set_uid_in
	    ) loop
	    if rhn_server.system_service_level(server.element, 'provisioning') = 1 then
	    	    select max(id) into snapshot_id
	    	    from rhnSnapshot
	    	    where server_id = server.element;

	    	    if snapshot_id is null then
		    	perform rhn_server.snapshot_server(server.element, 'tagging system:  ' || tagname_in);
			
			select max(id) into snapshot_id
			from rhnSnapshot
			where server_id = server.element;
		    end if;
		 
		-- now have a snapshot_id to work with...
		begin
		    perform rhn_server.tag_snapshot(snapshot_id, org_id_in, tagname_in);
		exception
		    when UNIQUE_VIOLATION
		    	then
			-- do nothing, be forgiving...
			null;
		end;
	    end if;
	end loop;    
    end$$ language plpgsql;

    create or replace function bulk_snapshot(
    	reason_in in varchar,
	set_label_in in varchar,
	set_uid_in in numeric
    ) returns void
    as $$
    declare
        server record;
    begin
        for server in (
           SELECT user_id, label, element, element_two
	     FROM rhnSet
	    WHERE label = set_label_in
	      AND user_id = set_uid_in
	    ) loop
    	    if rhn_server.system_service_level(server.element, 'provisioning') = 1 then
	    	perform rhn_server.snapshot_server(server.element, reason_in);
	    end if;
	end loop;
    end$$ language plpgsql;

-- restore the original setting
update pg_settings set setting = overlay( setting placing '' from 1 for (length('rhn_server')+1) ) where name = 'search_path';

070701000006CE000081B400000000000000000000000167AE1114000001E6000000000000000000000000000000000000005E00000000susemanager-schema/upgrade/spacewalk-schema-1.6-to-spacewalk-schema-1.7/014-rhn_quota.pks.sql 
-- setup search_path so that these functions are created in appropriate schema.
update pg_settings set setting = 'rhn_quota,' || setting where name = 'search_path';

drop function get_org_for_config_content ( config_content_id_in in numeric );

drop function set_org_quota_total ( org_id_in in numeric, total_in in numeric );

-- restore the original setting
update pg_settings set setting = overlay( setting placing '' from 1 for (length('rhn_quota')+1) ) where name = 'search_path';
  070701000006CF000081B400000000000000000000000167AE111400000566000000000000000000000000000000000000005D00000000susemanager-schema/upgrade/spacewalk-schema-1.6-to-spacewalk-schema-1.7/018-rhn_user.pkb.sql  --
-- Copyright (c) 2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--

-- create schema rhn_user;

-- setup search_path so that these functions are created in appropriate schema.
update pg_settings set setting = 'rhn_user,' || setting where name = 'search_path';

create function role_names (user_id_in in numeric)
	returns varchar
	as
$$
	declare
		rec record;
		tmp varchar(4000);
	begin
		for rec in (
			select type_name
			from rhnUserTypeBase
			where user_id = user_id_in
			order by type_id
			) loop
			if tmp is null then
				tmp := rec.type_name;
			else
				tmp := tmp || ', ' || rec.type_name;
			end if;
		end loop;
		return tmp;
	end;
$$ language plpgsql;

-- restore the original setting
update pg_settings set setting = overlay( setting placing '' from 1 for (length('rhn_user')+1) ) where name = 'search_path';
  070701000006D0000081B400000000000000000000000167AE11140000056F000000000000000000000000000000000000006600000000susemanager-schema/upgrade/spacewalk-schema-1.6-to-spacewalk-schema-1.7/019-rhnUsersInOrgOverview.sql --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
drop view rhnUsersInOrgOverview;
create view rhnUsersInOrgOverview as
select    
	u.org_id					as org_id,
	u.id						as user_id,
	u.login						as user_login,
	pi.first_names					as user_first_name,
	pi.last_name					as user_last_name,
	u.modified					as user_modified,
    	(	select	count(server_id)
		from	rhnUserServerPerms sp
		where	sp.user_id = u.id)
							as server_count,
	(	select	count(server_group_id)
		from	rhnUserManagedServerGroups umsg
		where	umsg.user_id = u.id and exists (
			select	1
			from	rhnVisibleServerGroup sg
			where	sg.id = umsg.server_group_id))
							as server_group_count,
	coalesce(rhn_user.role_names(u.id), '(normal user)') as role_names
from	web_user_personal_info pi, 
	web_contact u 
where
	u.id = pi.web_user_id;

 070701000006D1000081B400000000000000000000000167AE111400000022000000000000000000000000000000000000006A00000000susemanager-schema/upgrade/spacewalk-schema-1.6-to-spacewalk-schema-1.7/020-rhnUserTypeCommaView-drop.sql 
drop view rhnUserTypeCommaView;

  070701000006D2000081B400000000000000000000000167AE111400000E64000000000000000000000000000000000000006A00000000susemanager-schema/upgrade/spacewalk-schema-1.6-to-spacewalk-schema-1.7/024-time-series-revamp-tables.sql --
-- Copyright (c) 2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

create table time_series_purge
(
    id        numeric not null
                  constraint time_series_purge_pk primary key,
    probe_id  numeric
                  constraint time_series_purge_pid_fk
                  references rhn_probe(recid),
    deleted   numeric,
    created   timestamptz default (current_timestamp) not null,
    modified  timestamptz default (current_timestamp) not null
);

alter table time_series_purge
        add constraint time_series_purge
      check (id = probe_id);

create index time_series_purge_id_del_idx
    on time_series_purge(id, deleted);

-- populate time_series_purge with values from rhn_probe
insert into time_series_purge (id, probe_id, deleted) (select rp.recid, rp.recid, 0 from rhn_probe rp);
commit;

create table time_series_data
(
    org_id      numeric not null,
    probe_id    numeric not null
                    constraint time_series_data_pid_fk references
                    time_series_purge(id),
    probe_desc  varchar(64),
    entry_time  numeric not null,
    data        varchar(1024)
);

create index time_series_data_pid_time_idx on time_series_data(probe_id, entry_time);

-- triggers
create or replace function rhn_probe_insert_trigger_fun() returns trigger as
$$
begin
    insert into time_series_purge (id, probe_id, deleted) values (new.recid, new.recid, 0);
    return new;
end;
$$ language plpgsql;

create trigger rhn_probe_insert_trigger after insert on rhn_probe
for each row
execute procedure rhn_probe_insert_trigger_fun();

create or replace function rhn_probe_delete_trigger_fun() returns trigger as
$$
begin
    update time_series_purge
       set probe_id = null
     where id = old.recid;

    update time_series_purge
       set deleted = 1
     where id = old.recid;

    return old;
end;
$$ language plpgsql;

create trigger rhn_probe_delete_trigger before delete on rhn_probe
for each row
execute procedure rhn_probe_delete_trigger_fun();

create or replace function time_series_purge_mod_trig_fun() returns trigger as
$$
begin
    new.modified := current_timestamp;
    return new;
end;
$$ language plpgsql;

create trigger time_series_purge_mod_trig before insert or update on time_series_purge
for each row
execute procedure time_series_purge_mod_trig_fun();

-- migration from time_series to time_series_data
insert into time_series_data (org_id, probe_id, probe_desc, entry_time, data) (
    select t_ts.*
      from (
            select split_part(ts.o_id, '-', 1) :: numeric,
                   split_part(ts.o_id, '-', 2) :: numeric as probe_id,
                   split_part(ts.o_id, '-', 3),
                   ts.entry_time,
                   ts.data
              from time_series ts
           ) t_ts, rhn_probe rp
     where t_ts.probe_id :: numeric = rp.recid
);

drop table time_series;

-- compatibility time_series view
create or replace view time_series as (
    select tsd.org_id || '-' || tsd.probe_id || '-' || tsd.probe_desc as o_id,
           tsd.entry_time as entry_time,
           tsd.data as data
      from time_series_data tsd
    );
070701000006D3000081B400000000000000000000000167AE111400013027000000000000000000000000000000000000006900000000susemanager-schema/upgrade/spacewalk-schema-1.6-to-spacewalk-schema-1.7/025-time-series-revamp-plsql.sql  --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.

-- create schema rhn_entitlements;

-- setup search_path so that these functions are created in appropriate schema.
update pg_settings set setting = 'rhn_entitlements,' || setting where name = 'search_path';

   create or replace function find_compatible_sg (
      server_id_in in numeric,
      type_label_in in varchar
   )
   returns numeric
as $$
    declare
      servergroups cursor for
         select sg.id
           from rhnServerGroupType             sgt,
                rhnServerGroup                 sg,
                rhnServer                     s,
                rhnServerServerGroupArchCompat ssgac
          where s.id = server_id_in
            and s.org_id = sg.org_id
            and sgt.label = type_label_in
            and sg.group_type = sgt.id
            and ssgac.server_group_type = sgt.id
            and ssgac.server_arch_id = s.server_arch_id
            and not exists (
                     select 1
                      from rhnServerGroupMembers sgm
                     where sgm.server_group_id = sg.id
                       and sgm.server_id = s.id);


   begin
      for servergroup in servergroups loop
         return servergroup.id;
      end loop;

      --no servergroup found
      return NULL;
   end$$
language plpgsql;

    -- *******************************************************************
    -- PROCEDURE: remove_org_entitlements
    --
    -- Removes both system entitlements and channel subscriptions
    -- that are currently assigned to an org and re-assigns to the
    -- master org (org_id = 1).
    --
    -- When we call this we expect everything to already be unentitled
    -- which shoul be handled by delete_org.
    --
    -- Called by: delete_org
    -- *******************************************************************
    create or replace function remove_org_entitlements (
        org_id_in numeric
    ) returns void
as $$
    declare
        system_ents cursor for
        select sg.id, sg.max_members, sg.group_type
        from rhnServerGroup sg
        where group_type is not null
          and org_id = org_id_in;

        channel_subs cursor for
        select pcf.channel_family_id, pcf.max_members
        from rhnChannelFamily cf,
             rhnPrivateChannelFamily pcf
        where pcf.org_id = org_id_in
          and pcf.channel_family_id = cf.id
          and cf.org_id is null;

    begin

        for system_ent in system_ents loop
            update rhnServerGroup
            set max_members = max_members + system_ent.max_members
            where org_id = 1
              and group_type = system_ent.group_type;
        end loop;

        update rhnServerGroup
        set max_members = 0
        where org_id = org_id_in;

        for channel_sub in channel_subs loop
            update rhnPrivateChannelFamily
            set max_members = max_members + channel_sub.max_members
            where org_id = 1
              and channel_family_id = channel_sub.channel_family_id;
        end loop;

        update rhnPrivateChannelFamily
        set max_members = 0
        where org_id = org_id_in;

    end$$
language plpgsql;

    create or replace function entitlement_grants_service (
        entitlement_in in varchar,
        service_level_in in varchar
    ) returns numeric
as $$
    begin
        if service_level_in = 'provisioning' then
            if entitlement_in = 'provisioning_entitled' then
                return 1;
            else
                return 0;
            end if;
        elsif service_level_in = 'management' then
            if entitlement_in = 'enterprise_entitled' then
                return 1;
            else
                return 0;
            end if;
        elsif service_level_in = 'monitoring' then
            if entitlement_in = 'monitoring_entitled' then
                return 1;
            end if;
        elsif service_level_in = 'updates' then
            return 1;
        else
            return 0;
        end if;
    end$$
language plpgsql;

    create or replace function lookup_entitlement_group (
        org_id_in in numeric,
        type_label_in in varchar default 'sw_mgr_entitled'
    ) returns numeric
as $$
    declare
        server_groups cursor for
            select  sg.id               server_group_id
            from    rhnServerGroup      sg,
                    rhnServerGroupType  sgt
            where   sgt.label = type_label_in
                and sgt.id = sg.group_type
                and sg.org_id = org_id_in;
    begin
        for sg in server_groups loop
            return sg.server_group_id;
        end loop;
        return rhn_entitlements.create_entitlement_group(
                org_id_in,
                type_label_in
            );
    end$$
language plpgsql;

    create or replace function create_entitlement_group (
        org_id_in in numeric,
        type_label_in in varchar default 'sw_mgr_entitled'
    ) returns numeric
as $$
    declare
        sg_id_val numeric;
    begin
        select  nextval('rhn_server_group_id_seq')
        into    sg_id_val;

        insert into rhnServerGroup (
                id, name, description, max_members, current_members,
                group_type, org_id
            ) (
                select  sg_id_val, sgt.label, sgt.label,
                        0, 0, sgt.id, org_id_in
                from    rhnServerGroupType sgt
                where   sgt.label = type_label_in
            );

        return sg_id_val;
    end$$
language plpgsql;

   create or replace function can_entitle_server (
      server_id_in   in numeric,
      type_label_in  in varchar
   )
   returns numeric
as $$
    declare
      addon_servergroups cursor (base_label_in varchar,
                                 addon_label_in varchar) for
         select
            addon_id
         from
            rhnSGTypeBaseAddonCompat
         where base_id = lookup_sg_type (base_label_in)
           and addon_id = lookup_sg_type (addon_label_in);

      previous_ent        varchar[];
      is_base_in          char   := 'N';
      is_base_current     char   := 'N';
      i                   numeric := 0;
      sgid                numeric := 0;

   begin

      previous_ent := rhn_entitlements.get_server_entitlement(server_id_in);

      select distinct is_base
      into is_base_in
      from rhnServerGroupType
      where label = type_label_in;

      if array_upper(previous_ent, 1) is null or array_upper(previous_ent, 1) = 0 then
         if is_base_in = 'Y' then
            sgid := rhn_entitlements.find_compatible_sg (server_id_in, type_label_in);
            if sgid is not null then
              -- rhn_server.insert_into_servergroup (server_id_in, sgid);
              return 1;
            else
              -- rhn_exception.raise_exception ('invalid_base_entitlement');
              return 0;
            end if;
         else
            -- rhn_exception.raise_exception ('invalid_base_entitlement');
            return 0;
         end if;

      -- there are previous ents, first make sure we're not trying to entitle a base ent
      elsif is_base_in = 'Y' then
         -- rhn_exception.raise_exception ('invalid_addon_entitlement');
         return 0;

      -- it must be an addon, so proceed with the entitlement
      else

         -- find the servers base ent
         is_base_current := 'N';
         i := 0;
         while is_base_current = 'N' and i < array_upper(previous_ent, 1)
         loop
            i := i + 1;
            select is_base
            into is_base_current
            from rhnServerGroupType
            where label = previous_ent[i];
         end loop;

         -- never found a base ent, that would be strange
         if is_base_current  = 'N' then
            -- rhn_exception.raise_exception ('invalid_base_entitlement');
            return 0;
         end if;

         -- this for loop verifies the validity of the addon path
         for addon_servergroup in addon_servergroups  (previous_ent[i], type_label_in) loop
            -- find an appropriate sgid for the addon and entitle the server
            sgid := rhn_entitlements.find_compatible_sg (server_id_in, type_label_in);
            if sgid is not null then
               -- rhn_server.insert_into_servergroup (server_id_in, sgid);
               return 1;
            else
               -- rhn_exception.raise_exception ('invalid_addon_entitlement');
               return 0;
            end if;
         end loop;

      end if;

      return 0;

   end$$
language plpgsql;

   create or replace function can_switch_base (
      server_id_in   in    integer,
      type_label_in  in    varchar
   )
   returns numeric
as $$
   declare
      type_label_in_is_base   char(1);
      sgid                    numeric;

   begin

       select is_base into type_label_in_is_base
       from rhnServerGroupType
       where label = type_label_in;

       if not found then
          perform rhn_exception.raise_exception ( 'invalid_entitlement' );
       end if;

      if type_label_in_is_base = 'N' then
         perform rhn_exception.raise_exception ( 'invalid_entitlement' );
      else
         sgid := rhn_entitlements.find_compatible_sg ( server_id_in,
                                                       type_label_in );
         if sgid is not null then
           return 1;
         else
           return 0;
         end if;
      end if;

   end$$
language plpgsql;

    create or replace function entitle_server (
        server_id_in in numeric,
        type_label_in in varchar default 'sw_mgr_entitled'
    ) returns void
as $$
    declare
      sgid  numeric := 0;
      is_virt numeric := 0;

    begin

      select 1 into is_virt
        from rhnServerEntitlementView
        where server_id = server_id_in
          and label in ('virtualization_host', 'virtualization_host_platform');

      if not found then
          is_virt := 0;
      end if;

      if is_virt = 0 and (type_label_in = 'virtualization_host' or
                          type_label_in = 'virtualization_host_platform') then

        is_virt := 1;
      end if;

      if rhn_entitlements.can_entitle_server(server_id_in,
                                             type_label_in) = 1 then
         sgid := rhn_entitlements.find_compatible_sg (server_id_in,
                                                      type_label_in);
         if sgid is not null then
            insert into rhnServerHistory ( id, server_id, summary, details )
            values ( nextval('rhn_event_id_seq'), server_id_in,
                     'added system entitlement ',
                      case type_label_in
                       when 'enterprise_entitled' then 'Management'
                       when 'sw_mgr_entitled' then 'Update'
                       when 'provisioning_entitled' then 'Provisioning'
                       when 'monitoring_entitled' then 'Monitoring'
                       when 'virtualization_host' then 'Virtualization'
                       when 'virtualization_host_platform' then
                            'Virtualization Platform' end  );

            perform rhn_server.insert_into_servergroup (server_id_in, sgid);

            if is_virt = 1 then
              perform rhn_entitlements.repoll_virt_guest_entitlements(server_id_in);
            end if;

         else
            perform rhn_exception.raise_exception ('no_available_server_group');
         end if;
      else
         perform rhn_exception.raise_exception ('invalid_entitlement');
      end if;
   end$$
language plpgsql;

    create or replace function remove_server_entitlement (
        server_id_in in numeric,
        type_label_in in varchar default 'sw_mgr_entitled',
        repoll_virt_guests in numeric default 1
    ) returns void
as $$
    declare
      group_id numeric;
      type_is_base char;
      is_virt numeric := 0;
    begin
      -- would be nice if there were a virt attribute of entitlement types, not have to specify 2 different ones...
        select 1 into is_virt
          from rhnServerEntitlementView
          where server_id = server_id_in
            and label in ('virtualization_host', 'virtualization_host_platform');
        if not found then
            is_virt := 0;
        end if;

        select  sg.id, sgt.is_base
        into group_id, type_is_base
        from    rhnServerGroupType sgt,
            rhnServerGroup sg,
                rhnServerGroupMembers sgm,
                rhnServer s
        where   s.id = server_id_in
            and s.id = sgm.server_id
            and sgm.server_group_id = sg.id
            and sg.org_id = s.org_id
            and sgt.label = type_label_in
            and sgt.id = sg.group_type;

        if not found then
          perform rhn_exception.raise_exception('invalid_server_group_member');
        end if;

      if ( type_is_base = 'Y' ) then
         -- unentitle_server should handle everything, don't really need to do anything else special here
         perform rhn_entitlements.unentitle_server ( server_id_in );
      else

         insert into rhnServerHistory ( id, server_id, summary, details )
         values ( nextval('rhn_event_id_seq'), server_id_in,
                  'removed system entitlement ',
                   case type_label_in
                    when 'enterprise_entitled' then 'Management'
                    when 'sw_mgr_entitled' then 'Update'
                    when 'provisioning_entitled' then 'Provisioning'
                    when 'monitoring_entitled' then 'Monitoring'
                    when 'virtualization_host' then 'Virtualization'
                    when 'virtualization_host_platform' then
                         'Virtualization Platforrm' end  );

         perform rhn_server.delete_from_servergroup(server_id_in, group_id);

         if type_label_in = 'monitoring_entitled' then
           DELETE
             FROM rhn_probe
            WHERE recid IN (SELECT probe_id
                              FROM rhn_check_probe
                             WHERE host_id = server_id_in);
         end if;

         if is_virt = 1 and repoll_virt_guests = 1 then
           perform rhn_entitlements.repoll_virt_guest_entitlements(server_id_in);
         end if;
      end if;

    end$$
language plpgsql;

    create or replace function unentitle_server (
        server_id_in in numeric
    ) returns void
as $$
    declare
      servergroups cursor for
         select distinct sgt.label, sg.id server_group_id
         from  rhnServerGroupType sgt,
               rhnServerGroup sg,
               rhnServer s,
               rhnServerGroupMembers sgm
         where s.id = server_id_in
            and s.org_id = sg.org_id
            and sg.group_type = sgt.id
            and sgm.server_group_id = sg.id
            and sgm.server_id = s.id;

     is_virt numeric := 0;

   begin

      select 1 into is_virt
        from rhnServerEntitlementView
        where server_id = server_id_in
         and label in ('virtualization_host', 'virtualization_host_platform');

      if not found then
          is_virt := 0;
      end if;

      for servergroup in servergroups loop

         insert into rhnServerHistory ( id, server_id, summary, details )
         values ( nextval('rhn_event_id_seq'), server_id_in,
                  'removed system entitlement ',
                   case servergroup.label
                    when 'enterprise_entitled' then 'Management'
                    when 'sw_mgr_entitled' then 'Update'
                    when 'provisioning_entitled' then 'Provisioning'
                    when 'monitoring_entitled' then 'Monitoring'
                    when 'virtualization_host' then 'Virtualization'
                    when 'virtualization_host_platform' then
                         'Virtualization Platform' end  );

         perform rhn_server.delete_from_servergroup(server_id_in,
                                            servergroup.server_group_id );
      end loop;

      if is_virt = 1 then
        perform rhn_entitlements.repoll_virt_guest_entitlements(server_id_in);
      end if;

   end$$
language plpgsql;


    -- *******************************************************************
    -- PROCEDURE: repoll_virt_guest_entitlements
    --
    --   Whenever we add/remove a virtualization_host* entitlement from
    --   a host, we can call this procedure to update what type of slots
    --   the guests are consuming.
    --
    --   If you're removing the entitlement, it's
    --   possible the guests will become unentitled if you don't have enough
    --   physical slots to cover them.
    --
    --   If you're adding the entitlement, you end up freeing up physical
    --   slots for other systems.
    --
    -- *******************************************************************
    create or replace function repoll_virt_guest_entitlements(
        server_id_in in numeric
    ) returns void
as $$
    declare
        -- All channel families associated with the guests of server_id_in
        families cursor for
            select distinct cfs.channel_family_id
            from
                rhnChannelFamilyServers cfs,
                rhnVirtualInstance vi
            where
                vi.host_system_id = server_id_in
                and vi.virtual_system_id = cfs.server_id;

        -- All of server group types associated with the guests of
        -- server_id_in
        group_types cursor for
            select distinct sg.group_type, sgt.label
            from
                rhnServerGroupType sgt,
                rhnServerGroup sg,
                rhnServerGroupMembers sgm,
                rhnVirtualInstance vi
            where
                vi.host_system_id = server_id_in
                and vi.virtual_system_id = sgm.server_id
                and sgm.server_group_id = sg.id
                and sg.group_type = sgt.id;

        -- Virtual servers from a certain family belonging to a specific
        -- host that are consuming physical channel slots over the limit.
        virt_servers_cfam cursor(family_id_in numeric, quantity_in numeric) for
                select vi.virtual_system_id
                from
                    rhnChannelFamilyMembers cfm,
                    rhnServerChannel sc,
                    rhnVirtualInstance vi
                where
                    vi.host_system_id = server_id_in
                    and vi.virtual_system_id = sc.server_id
                    and sc.channel_id = cfm.channel_id
                    and cfm.channel_family_id = family_id_in
                order by sc.modified desc
                limit quantity_in;

        -- Virtual servers from a certain family belonging to a specific
        -- host that are consuming physical system slots over the limit.
        virt_servers_sgt cursor(group_type_in numeric, quantity_in numeric) for
                select vi.virtual_system_id
                from
                    rhnServerGroup sg,
                    rhnServerGroupMembers sgm,
                    rhnVirtualInstance vi
                where
                    vi.host_system_id = server_id_in
                    and vi.virtual_system_id = sgm.server_id
                    and sgm.server_group_id = sg.id
                    and sg.group_type = group_type_in
                order by sgm.modified desc
                limit quantity_in;

        -- Get the orgs of Virtual guests
        -- Since they may belong to different orgs
        virt_guest_orgs cursor for
                select  distinct (s.org_id)
                from rhnServer s
                    inner join  rhnVirtualInstance vi on vi.virtual_system_id = s.id
                where
                    vi.host_system_id = server_id_in
                    and s.org_id <> (select s1.org_id from rhnServer s1 where s1.id = vi.host_system_id) ;

        org_id_val numeric;
        max_members_val numeric;
        max_flex_val numeric;
        current_members_calc numeric;
        sg_id numeric;
        is_virt numeric := 0;
    begin
          select 1 into is_virt
                from rhnServerEntitlementView
           where server_id = server_id_in
                 and label in ('virtualization_host', 'virtualization_host_platform');

      if not found then
          is_virt := 0;
      end if;

        select org_id
        into org_id_val
        from rhnServer
        where id = server_id_in;

        -- deal w/ channel entitlements first ...
        for family in families loop
            if is_virt = 0 then
            -- if the host_server does not have virt
            --- find all possible flex slots
            -- and set each of the flex eligible guests to Y
                UPDATE rhnServerChannel sc set is_fve = 'Y'
                where sc.server_id in (
                            select vi.virtual_system_id
                            from rhnServerFveCapable sfc
                                inner join rhnVirtualInstance vi on vi.virtual_system_id = sfc.server_id
                            where vi.host_system_id = server_id_in
                                  and sfc.channel_family_id = family.channel_family_id
                              order by vi.modified desc
                            limit free_slots
                );
            else
            -- if the host_server has virt
            -- set all its flex guests to N
                UPDATE rhnServerChannel sc set is_fve = 'N'
                where
                    sc.channel_id in (select cfm.channel_id from rhnChannelFamilyMembers cfm
                                      where cfm.CHANNEL_FAMILY_ID = family.channel_family_id)
                    and sc.is_fve = 'Y'
                    and sc.server_id in
                            (select vi.virtual_system_id  from rhnVirtualInstance vi
                                    where vi.host_system_id = server_id_in);
            end if;

            -- get the current (physical) members of the family
            current_members_calc :=
                rhn_channel.channel_family_current_members(family.channel_family_id,
                                                           org_id_val); -- fixed transposed args

            -- get the max members of the family
            select max_members
            into max_members_val
            from rhnPrivateChannelFamily
            where channel_family_id = family.channel_family_id
            and org_id = org_id_val;

            select fve_max_members
            into max_flex_val
            from rhnPrivateChannelFamily
            where channel_family_id = family.channel_family_id
            and org_id = org_id_val;

            if current_members_calc > max_members_val then
                -- A virtualization_host* ent must have been removed, so we'll
                -- unsubscribe guests from the host first.

                -- hm, i don't think max_members - current_members_calc yielding a negative number
                -- will work w/ rownum, swaping 'em in the body of this if...
                for virt_server in virt_servers_cfam(family.channel_family_id,
                                current_members_calc - max_members_val) loop

                    perform rhn_channel.unsubscribe_server_from_family(
                                virt_server.virtual_system_id,
                                family.channel_family_id);
                end loop;

                -- if we're still over the limit, which would be odd,
                -- just prune the group to max_members
                --
                -- er... wouldn't we actually have to refresh the values of
                -- current_members_calc and max_members_val to actually ever
                -- *skip this??
                if current_members_calc > max_members_val then
                    -- argh, transposed again?!
                    perform rhn_entitlements.set_family_count(org_id_val,
                                     family.channel_family_id,
                                     max_members_val, max_flex_val);
                    --TODO calculate this correctly
                end if;

           end if;

            -- update current_members for the family.  This will set the value
            -- to reflect adding/removing the entitlement.
            --
            -- what's the difference of doing this vs the unavoidable set_family_count above?
            perform rhn_channel.update_family_counts(family.channel_family_id,
                                             org_id_val);

            -- It is possible that the guests belong  to a different org than the host
            -- so we are going to update the family counts in the guests orgs also
            for org in virt_guest_orgs loop
                    perform rhn_channel.update_family_counts(family.channel_family_id,
                                             org.org_id);
            end loop;
        end loop;

        for a_group_type in group_types loop
          -- get the current *physical* members of the system entitlement type for the org...
          --
          -- unlike channel families, it appears the standard rhnServerGroup.max_members represents
          -- *physical* slots, vs physical+virt ... boy that's confusing...

          select max_members, id
            into max_members_val, sg_id
            from rhnServerGroup
            where group_type = a_group_type.group_type
            and org_id = org_id_val;


      select count(sep.server_id) into current_members_calc
            from rhnServerEntitlementPhysical sep
           where sep.server_group_id = sg_id
             and sep.server_group_type_id = a_group_type.group_type;

          if current_members_calc > max_members_val then
            -- A virtualization_host* ent must have been removed, and we're over the limit, so unsubscribe guests
            for virt_server in virt_servers_sgt(a_group_type.group_type,
                                                current_members_calc - max_members_val) loop
              perform rhn_entitlements.remove_server_entitlement(virt_server.virtual_system_id, a_group_type.label);

              -- decrement current_members_calc, we'll use it to reset current_members for the group at the end...
              current_members_calc := current_members_calc - 1;
            end loop;

          end if;

          update rhnServerGroup set current_members = current_members_calc
           where org_id = org_id_val
             and group_type = a_group_type.group_type;

          -- I think that's all the house-keeping we have to do...
        end loop;

    end$$
language plpgsql;

    create or replace function get_server_entitlement (
        server_id_in in numeric
    ) returns varchar[]
as $$
    declare
        server_groups cursor for
            select  sgt.label
            from    rhnServerGroupType      sgt,
                    rhnServerGroup          sg,
                    rhnServerGroupMembers   sgm
            where   1=1
                and sgm.server_id = server_id_in
                and sg.id = sgm.server_group_id
                and sgt.id = sg.group_type
                and sgt.label in (
                    'sw_mgr_entitled','enterprise_entitled',
                    'provisioning_entitled', 'nonlinux_entitled',
                    'monitoring_entitled', 'virtualization_host',
                                        'virtualization_host_platform'
                    );

         ent_array varchar[];

    begin

      ent_array := '{}';

      for sg in server_groups loop
         ent_array := ent_array || sg.label;
      end loop;

      return ent_array;

    end$$
language plpgsql;

    -- this desperately needs to be table driven.
    create or replace function modify_org_service (
        org_id_in in numeric,
        service_label_in in varchar,
        enable_in in char
    ) returns void
as $$
    declare
        roles_to_process varchar[];
        roles cursor(role_label_in varchar) for
            select  label, id
            from    rhnUserGroupType
            where   label = role_label_in;
        org_roles cursor(role_label_in varchar) for
            select  1
            from    rhnUserGroup ug,
                    rhnUserGroupType ugt
            where   ugt.label = role_label_in
                and ug.org_id = org_id_in
                and ugt.id = ug.group_type;

        ents_to_process varchar[];
        ents cursor(ent_label_in varchar) for
            select  label, id
            from    rhnOrgEntitlementType
            where   label = ent_label_in;
        org_ents cursor(ent_label_in varchar) for
            select  1
            from    rhnOrgEntitlements oe,
                    rhnOrgEntitlementType oet
            where   oet.label = ent_label_in
                and oe.org_id = org_id_in
                and oet.id = oe.entitlement_id;
        create_row char(1);
    begin
        ents_to_process := '{}';
        roles_to_process := '{}';
        -- a bit kludgy, but only for 3.4 really.  Certainly no
        -- worse than the old code...
        if service_label_in = 'enterprise' or
           service_label_in = 'management' then
            ents_to_process := array_append(ents_to_process, 'sw_mgr_enterprise');

            roles_to_process := array_append(roles_to_process, 'org_admin');

            roles_to_process := array_append(roles_to_process, 'system_group_admin');

            roles_to_process := array_append(roles_to_process, 'activation_key_admin');

            roles_to_process := array_append(roles_to_process, 'org_applicant');
        elsif service_label_in = 'provisioning' then
            ents_to_process := array_append(ents_to_process, 'rhn_provisioning');

            roles_to_process := array_append(roles_to_process, 'system_group_admin');

            roles_to_process := array_append(roles_to_process, 'activation_key_admin');

            roles_to_process := array_append(roles_to_process, 'config_admin');
            -- another nasty special case...
            if enable_in = 'Y' then
                ents_to_process := array_append(ents_to_process, 'sw_mgr_enterprise');
            end if;
        elsif service_label_in = 'monitoring' then
            ents_to_process := array_append(ents_to_process, 'rhn_monitor');

            roles_to_process := array_append(roles_to_process, 'monitoring_admin');
        elsif service_label_in = 'virtualization' then
            ents_to_process := array_append(ents_to_process, 'rhn_virtualization');

            roles_to_process := array_append(roles_to_process, 'config_admin');
        elsif service_label_in = 'virtualization_platform' then
            ents_to_process := array_append(ents_to_process, 'rhn_virtualization_platform');
            roles_to_process := array_append(roles_to_process, 'config_admin');
    elsif service_label_in = 'nonlinux' then
            ents_to_process := array_append(ents_to_process, 'rhn_nonlinux');
            roles_to_process := array_append(roles_to_process, 'config_admin');
        end if;

        if enable_in = 'Y' then
            for i in 1..array_upper(ents_to_process, 1) loop
                for ent in ents(ents_to_process[i]) loop
                    create_row := 'Y';
                    for oe in org_ents(ent.label) loop
                        create_row := 'N';
                    end loop;
                    if create_row = 'Y' then
                        insert into rhnOrgEntitlements(org_id, entitlement_id)
                            values (org_id_in, ent.id);
                    end if;
                end loop;
            end loop;
            for i in 1..array_upper(roles_to_process, 1) loop
                for role in roles(roles_to_process[i]) loop
                    create_row := 'Y';
                    for o_r in org_roles(role.label) loop
                        create_row := 'N';
                    end loop;
                    if create_row = 'Y' then
                        insert into rhnUserGroup(
                                id, name, description, current_members,
                                group_type, org_id
                            ) (
                                select  nextval('rhn_user_group_id_seq'),
                                        ugt.name || 's',
                                        ugt.name || 's for Org ' ||
                                            o.name || ' ('|| o.id ||')',
                                        0, ugt.id, o.id
                                from    rhnUserGroupType ugt,
                                        web_customer o
                                where   o.id = org_id_in
                                    and ugt.id = role.id
                            );
                    end if;
                end loop;
            end loop;
        else
            for i in 1..coalesce(array_upper(ents_to_process, 1), 0) loop
                for ent in ents(ents_to_process[i]) loop
                    delete from rhnOrgEntitlements
                     where org_id = org_id_in
                       and entitlement_id = ent.id;
                end loop;
            end loop;
        end if;
    end$$
language plpgsql;

    create or replace function set_customer_enterprise (
        customer_id_in in numeric
    ) returns void
as $$
    begin
        perform rhn_entitlements.modify_org_service(customer_id_in, 'enterprise', 'Y');
    end$$
language plpgsql;

    create or replace function set_customer_provisioning (
        customer_id_in in numeric
    ) returns void
as $$
    begin
        perform rhn_entitlements.modify_org_service(customer_id_in, 'provisioning', 'Y');
    end$$
language plpgsql;

    create or replace function set_customer_monitoring (
        customer_id_in in numeric
    ) returns void
as $$
    begin
        perform rhn_entitlements.modify_org_service(customer_id_in, 'monitoring', 'Y');
    end$$
language plpgsql;

    create or replace function set_customer_nonlinux (
        customer_id_in in numeric
    ) returns void
as $$
    begin
        perform rhn_entitlements.modify_org_service(customer_id_in, 'nonlinux', 'Y');
    end$$
language plpgsql;

    create or replace function unset_customer_enterprise (
        customer_id_in in numeric
    ) returns void
as $$
    begin
        perform rhn_entitlements.modify_org_service(customer_id_in, 'enterprise', 'N');
    end$$
language plpgsql;

    create or replace function unset_customer_provisioning (
        customer_id_in in numeric
    ) returns void
as $$
    begin
        perform rhn_entitlements.modify_org_service(customer_id_in, 'provisioning', 'N');
    end$$
language plpgsql;

    create or replace function unset_customer_monitoring (
        customer_id_in in numeric
    ) returns void
as $$
    begin
        perform rhn_entitlements.modify_org_service(customer_id_in, 'monitoring', 'N');
    end$$
language plpgsql;

    create or replace function unset_customer_nonlinux (
        customer_id_in in numeric
    ) returns void
as $$
    begin
        perform rhn_entitlements.modify_org_service(customer_id_in, 'nonlinux', 'N');
    end$$
language plpgsql;

    -- *******************************************************************
    -- PROCEDURE: prune_group
    -- Unsubscribes servers consuming physical slots that over the org's
    --   limit.
    -- Called by: set_server_group_count, repoll_virt_guest_entitlements
    -- *******************************************************************
    create or replace function prune_group (
        group_id_in in numeric,
        quantity_in in numeric,
        update_family_countsYN in numeric default 1
    ) returns void
as $$
    declare
        sgrecord record;
      type_is_base char;
    begin
            update      rhnServerGroup
                set     max_members = quantity_in
                where   id = group_id_in;

            for sgrecord in (
		   select  server_id, server_group_id, sgt.id as group_type_id, sgt.label
		    from    rhnServerGroupType              sgt,
				    rhnServerGroup                  sg,
				    rhnServerGroupMembers   sgm
		    where   1=1
			    and sgm.server_group_id = group_id_in
			    and sgm.server_id in (
				    select  sep.server_id
				    from
					rhnServerEntitlementPhysical sep
				    where
					sep.server_group_id = group_id_in
				    order by sep.modified asc
				    offset quantity_in
				)
			    and sgm.server_group_id = sg.id
			    and sg.group_type = sgt.id
	    ) loop
                perform rhn_entitlements.remove_server_entitlement(sgrecord.server_id, sgrecord.label);

            select is_base
            into type_is_base
            from rhnServerGroupType sgt
            where sgt.id = sgrecord.group_type_id;

            -- if we're removing a base ent, then be sure to
            -- remove the server's channel subscriptions.
            if ( type_is_base = 'Y' ) then
                   perform rhn_channel.clear_subscriptions(sgrecord.server_id, 0, update_family_countsYN);
            end if;

            end loop;
    end$$
language plpgsql;

    -- *******************************************************************
    -- PROCEDURE: assign_system_entitlement
    --
    -- Moves system entitlements from from_org_id_in to to_org_id_in.
    -- Can raise not_enough_entitlements_in_base_org if from_org_id_in
    -- does not have enough entitlements to cover the move.
    -- Takes care of unentitling systems if necessary by calling
    -- set_server_group_count
    -- *******************************************************************
    create or replace function assign_system_entitlement(
        group_label_in in varchar,
        from_org_id_in in numeric,
        to_org_id_in in numeric,
        quantity_in in numeric
    ) returns void
as $$
    declare
        prev_ent_count numeric;
    to_org_prev_ent_count numeric;
        new_ent_count numeric;
    new_quantity numeric;
        group_type numeric;
    begin

            select max_members
            into prev_ent_count
            from rhnServerGroupType sgt,
                 rhnServerGroup sg
            where sg.org_id = from_org_id_in
              and sg.group_type = sgt.id
              and sgt.label = group_label_in;

            if not found then
                perform rhn_exception.raise_exception(
                              'not_enough_entitlements_in_base_org');
            end if;

            select max_members
            into to_org_prev_ent_count
            from rhnServerGroupType sgt,
                 rhnServerGroup sg
            where sg.org_id = to_org_id_in
              and sg.group_type = sgt.id
              and sgt.label = group_label_in;

            if not found then
                to_org_prev_ent_count := 0;
            end if;

            select id
            into group_type
            from rhnServerGroupType
            where label = group_label_in;

            if not found then
                perform rhn_exception.raise_exception(
                              'invalid_server_group');
            end if;

        new_ent_count := prev_ent_count - quantity_in;

        if prev_ent_count > new_ent_count then
            new_quantity := to_org_prev_ent_count + quantity_in;
        end if;

        if new_ent_count < 0 then
            perform rhn_exception.raise_exception(
                          'not_enough_entitlements_in_base_org');
        end if;


        perform rhn_entitlements.set_server_group_count(from_org_id_in,
                                         group_type,
                                         new_ent_count);

        perform rhn_entitlements.set_server_group_count(to_org_id_in,
                                         group_type,
                                         new_quantity);

        -- Create or delete the entries in rhnOrgEntitlementType
        if group_label_in = 'enterprise_entitled' then
            if new_quantity > 0 then
                perform rhn_entitlements.set_customer_enterprise(to_org_id_in);
            else
                perform rhn_entitlements.unset_customer_enterprise(to_org_id_in);
            end if;
        end if;

        if group_label_in = 'provisioning_entitled' then
            if new_quantity > 0 then
                perform rhn_entitlements.set_customer_provisioning(to_org_id_in);
            else
                perform rhn_entitlements.unset_customer_provisioning(to_org_id_in);
            end if;
        end if;

        if group_label_in = 'monitoring_entitled' then
            if new_quantity > 0 then
                perform rhn_entitlements.set_customer_monitoring(to_org_id_in);
            else
                perform rhn_entitlements.unset_customer_monitoring(to_org_id_in);
            end if;
        end if;

    end$$
language plpgsql;

    -- *******************************************************************
    -- PROCEDURE: assign_channel_entitlement
    --
    -- Moves channel entitlements from from_org_id_in to to_org_id_in.
    -- Can raise not_enough_entitlements_in_base_org if from_org_id_in
    -- does not have enough entitlements to cover the move.
    -- Takes care of unentitling systems if necessary by calling
    -- set_family_count
    -- *******************************************************************
    create or replace function assign_channel_entitlement(
        channel_family_label_in in varchar,
        from_org_id_in in numeric,
        to_org_id_in in numeric,
        quantity_in in numeric,
        flex_in in numeric
    ) returns void
as $$
    declare
        from_org_prev_ent_count numeric;
        from_org_prev_ent_count_flex numeric;
        new_ent_count numeric;
        new_ent_count_flex numeric;
        to_org_prev_ent_count numeric;
        to_org_prev_ent_count_flex numeric;
        new_quantity numeric;
        new_flex numeric;
        cfam_id       numeric;
    begin

            select max_members
            into from_org_prev_ent_count
            from rhnChannelFamily cf,
                 rhnPrivateChannelFamily pcf
            where pcf.org_id = from_org_id_in
              and pcf.channel_family_id = cf.id
              and cf.label = channel_family_label_in;

            if not found then
                perform rhn_exception.raise_exception(
                              'not_enough_entitlements_in_base_org');
            end if;

            select max_members
            into to_org_prev_ent_count
            from rhnChannelFamily cf,
                 rhnPrivateChannelFamily pcf
            where pcf.org_id = to_org_id_in
              and pcf.channel_family_id = cf.id
              and cf.label = channel_family_label_in;

            if not found then
                to_org_prev_ent_count := 0;
            end if;

            select fve_max_members
            into from_org_prev_ent_count_flex
            from rhnChannelFamily cf,
                rhnPrivateChannelFamily pcf
            where pcf.org_id = from_org_id_in
              and pcf.channel_family_id = cf.id
              and cf.label = channel_family_label_in;

            if not found then
                perform rhn_exception.raise_exception(
                              'not_enough_flex_entitlements_in_base_org');
            end if;

            select fve_max_members
            into to_org_prev_ent_count_flex
            from rhnChannelFamily cf,
                 rhnPrivateChannelFamily pcf
            where pcf.org_id = to_org_id_in
              and pcf.channel_family_id = cf.id
              and cf.label = channel_family_label_in;

            if not found then
                to_org_prev_ent_count_flex := 0;
            end if;

            select id
            into cfam_id
            from rhnChannelFamily
            where label = channel_family_label_in;

            if not found then
                perform rhn_exception.raise_exception(
                              'invalid_channel_family');
            end if;

        new_ent_count := from_org_prev_ent_count - quantity_in;
        new_ent_count_flex := from_org_prev_ent_count_flex - flex_in;

        if from_org_prev_ent_count >= new_ent_count then
            new_quantity := to_org_prev_ent_count + quantity_in;
        end if;

        if from_org_prev_ent_count_flex >= new_ent_count_flex then
            new_flex := to_org_prev_ent_count_flex + flex_in;
        end if;

        if new_ent_count < 0 then
            perform rhn_exception.raise_exception(
                          'not_enough_entitlements_in_base_org');
        end if;

        if new_ent_count_flex < 0 then
            perform rhn_exception.raise_exception(
                          'not_enough_flex_entitlements_in_base_org');
        end if;



        perform rhn_entitlements.set_family_count(from_org_id_in,
                                          cfam_id,
                                          new_ent_count,
                                          new_ent_count_flex);

        perform rhn_entitlements.set_family_count(to_org_id_in,
                                          cfam_id,
                                          new_quantity,
                                          new_flex);

    end$$
language plpgsql;

    -- *******************************************************************
    -- PROCEDURE: activate_system_entitlement
    --
    -- Sets the values in rhnServerGroup for a given rhnServerGroupType.
    --
    -- Calls: set_server_group_count to update, prune, or create the group.
    -- Called by: the code that activates a satellite cert.
    --
    -- Raises not_enough_entitlements_in_base_org if all entitlements
    -- in the org are used so the free entitlements would not cover
    -- the difference when descreasing the number of entitlements.
    -- *******************************************************************
    create or replace function activate_system_entitlement(
        org_id_in in numeric,
        group_label_in in varchar,
        quantity_in in numeric
    ) returns void
as $$
    declare
        prev_ent_count numeric;
        prev_ent_count_sum numeric;
        group_type numeric;
    begin

        -- Fetch the current entitlement count for the org
        -- into prev_ent_count

            select current_members
            into prev_ent_count
            from rhnServerGroupType sgt,
                 rhnServerGroup sg
            where sg.group_type = sgt.id
              and sgt.label = group_label_in
              and sg.org_id = org_id_in;

            if not found then
                prev_ent_count := 0;
            end if;

            select id
            into group_type
            from rhnServerGroupType
            where label = group_label_in;

            if not found then
                perform rhn_exception.raise_exception(
                              'invalid_server_group');
            end if;

        -- If we're setting the total entitlemnt count to a lower value,
        -- and that value is less than the allocated count in this org,
        -- we need to raise an exception.
        if quantity_in < prev_ent_count then
            perform rhn_exception.raise_exception(
                          'not_enough_entitlements_in_base_org');
        else
            -- don't update family counts after every server
            -- will do bulk update afterwards
            perform rhn_entitlements.set_server_group_count(org_id_in,
                                             group_type,
                                             quantity_in,
                                             0);
            -- bulk update family counts
            perform rhn_channel.update_group_family_counts(group_label_in, org_id_in);
        end if;

    end$$
language plpgsql;

    -- *******************************************************************
    -- PROCEDURE: activate_channel_entitlement
    --
    -- Calls: set_family_count to update, prune, or create the family
    --        permission bucket.
    -- Called by: the code that activates a satellite cert.
    --
    -- Raises not_enough_entitlements_in_base_org if there are not enough
    -- entitlements in the org to cover the difference when you are
    -- descreasing the number of entitlements.
    --
    -- The backend code in Python is expected to do whatever arithmetics
    -- is needed.
    -- *******************************************************************
    create or replace function activate_channel_entitlement(
        org_id_in in numeric,
        channel_family_label_in in varchar,
        quantity_in in numeric,
        flex_in in numeric
    ) returns void
as $$
    declare
        prev_ent_count numeric;
        prev_flex_count numeric;
        prev_ent_count_sum numeric;
        cfam_id numeric;
        reduce_quantity numeric;
        total_flex_capable numeric;
        to_convert_reg cursor (channel_family_id_val numeric, org_id_in numeric, quantity numeric) for
                     select SC.server_id
                     from rhnServerChannel SC inner join
                          rhnServer S on S.id = SC.server_id
                     where
                         is_fve = 'Y'
                         and S.org_id = org_id_in
                         and SC.channel_id in
                         (select cfm.channel_id from rhnChannelFamilyMembers cfm
                             where cfm.CHANNEL_FAMILY_ID = channel_family_id_val)
                         limit quantity;
         to_convert_flex cursor (channel_family_id_val numeric, org_id_in numeric, quantity numeric) for
                   select server_id
                   from rhnServerFveCapable
                       where SERVER_ORG_ID = org_id_in and
                             channel_family_id = cfam_id
                       limit quantity;

    begin

        -- Fetch the current entitlement count for the org
        -- into prev_ent_count
            select current_members
            into prev_ent_count
            from rhnChannelFamily cf,
                 rhnPrivateChannelFamily pcf
            where pcf.org_id = org_id_in
              and pcf.channel_family_id = cf.id
              and cf.label = channel_family_label_in;

            if not found then
                prev_ent_count := 0;
            end if;

            select pcf.fve_current_members
            into prev_flex_count
            from rhnChannelFamily cf,
                 rhnPrivateChannelFamily pcf
            where pcf.org_id = org_id_in
              and pcf.channel_family_id = cf.id
              and cf.label = channel_family_label_in;

            if not found then
                prev_flex_count := 0;
            end if;

            select id
            into cfam_id
            from rhnChannelFamily
            where label = channel_family_label_in;

            if not found then
                perform rhn_exception.raise_exception(
                              'invalid_channel_family');
            end if;

        -- if there are too few flex entitlements
        if flex_in < prev_flex_count then
            -- and if the extra we need is less than or equal to our extra regular entitlements
            if prev_flex_count - flex_in <= quantity_in - prev_ent_count then
                   reduce_quantity := prev_flex_count - flex_in;
                   -- We need to convert some systems from flex guest to regular
                   for system in to_convert_reg(cfam_id, org_id_in, reduce_quantity) loop
                      --rhn_channel.convert_to_regular(system.server_id, cfam_id);
                      UPDATE rhnServerChannel sc set is_fve = 'N'
                           where sc.server_id = system.server_id
                                 and sc.channel_id in (select cfm.channel_id
                                                          from rhnChannelFamilyMembers cfm
                                                          where cfm.channel_family_id = cfam_id);
                   end loop;

                   --reset previous counts
                   prev_ent_count := prev_ent_count + reduce_quantity;
                   prev_flex_count := prev_flex_count - reduce_quantity;
            else
                perform rhn_exception.raise_exception(
                          'not_enough_flex_entitlements_in_base_org');
            end if;
        end if;

        -- if there are too few regular entitlements, and extra flex entitlements
        if quantity_in < prev_ent_count and prev_flex_count < flex_in then
                -- how many flex-capable systems (that aren't using flex) do we have
                select count(*)
                   into total_flex_capable
                   from rhnServerFveCapable
                       where SERVER_ORG_ID = org_id_in and
                             channel_family_id = cfam_id;
                -- if we have enough flex capable machines that is at least
                --   as many as what we are over on
                if total_flex_capable >= prev_ent_count - quantity_in then
                    reduce_quantity := prev_ent_count - quantity_in;
                    for system in to_convert_flex(cfam_id, org_id_in, reduce_quantity) loop
--                          rhn_channel.convert_to_fve(system.server_id, cfam_id);
                        UPDATE rhnServerChannel sc set is_fve = 'Y'
                           where sc.server_id = system.server_id
                                 and sc.channel_id in (select cfm.channel_id
                                                          from rhnChannelFamilyMembers cfm
                                                          where cfm.channel_family_id = cfam_id);
                    end loop;
                    prev_ent_count := prev_ent_count - reduce_quantity;
                    prev_flex_count := prev_flex_count + reduce_quantity;
                end if;
        end if;

        -- If we're setting the total entitlemnt count to a lower value,
        -- and that value is less than the count in that one org,
        -- we need to raise an exception.
        if quantity_in < prev_ent_count then
            perform rhn_exception.raise_exception(
                          'not_enough_entitlements_in_base_org');
        else
            -- even if we've manually converted systems to/from flex above
            -- set_family_count should call update_family_counts, to reset
            -- current used slots
            perform rhn_entitlements.set_family_count(org_id_in, cfam_id,
                                              quantity_in, flex_in);
        end if;

    end$$
language plpgsql;

    create or replace function set_server_group_count (
        customer_id_in in numeric,  -- customer_id
        group_type_in in numeric,   -- rhn[User|Server]GroupType.id
        quantity_in in numeric,      -- quantity
                update_family_countsYN in numeric default 1
    ) returns void
as $$
    declare
        group_id numeric;
        quantity numeric;
        wasfound boolean;
    begin
        quantity := quantity_in;
        if quantity is not null and quantity < 0 then
            quantity := 0;
        end if;

        select  rsg.id
        into    group_id
        from    rhnServerGroup rsg
        where   1=1
            and rsg.org_id = customer_id_in
            and rsg.group_type = group_type_in;

        -- preserve the not found status across the rhn_entitlements.prune_group invocation
        wasfound := true;
        if not found then
            wasfound := false;
        end if;

        perform rhn_entitlements.prune_group(
            group_id,
            quantity,
                        update_family_countsYN
        );

        if not wasfound then
            insert into rhnServerGroup (
                    id, name, description, max_members, current_members,
                    group_type, org_id, created, modified
                ) (
                    select  nextval('rhn_server_group_id_seq'), name, name,
                            quantity, 0, id, customer_id_in,
                            current_timestamp, current_timestamp
                    from    rhnServerGroupType
                    where   id = group_type_in
            );
        end if;

    end$$
language plpgsql;

    -- *******************************************************************
    -- PROCEDURE: prune_family
    -- Unsubscribes servers consuming physical slots from the channel family
    --   that are over the org's limit.
    -- Called by: set_family_count
    -- *******************************************************************
    create or replace function prune_family (
        customer_id_in in numeric,
        channel_family_id_in in numeric,
        quantity_in in numeric,
        flex_in in numeric
    ) returns void
as $$
    declare
       is_fve_in char;
       tmp_quantity numeric;

        serverchannels cursor for
            select  sc.server_id,
                    sc.channel_id
            from    rhnServerChannel sc,
                    rhnChannelFamilyMembers cfm
            where   1=1
                and cfm.channel_family_id = channel_family_id_in
                and cfm.channel_id = sc.channel_id
                and server_id in (
                            select  rs.id as server_id
                            from
                                    rhnServerChannel        rsc,
                                    rhnChannelFamilyMembers rcfm,
                                    rhnServer               rs
                            where   1=1
                                and rs.org_id = customer_id_in
                                and rs.id = rsc.server_id
                                and rsc.channel_id = rcfm.channel_id
                                and rcfm.channel_family_id =  channel_family_id_in
                                and rsc.is_fve = is_fve_in
                                -- we only want to grab servers consuming
                                -- physical slots.
                                and exists (
                                    select 1
                                    from rhnChannelFamilyServerPhysical cfsp
                                    where cfsp.server_id = rs.id
                                    and cfsp.channel_family_id =
                                        channel_family_id_in
                                    )
                            order by rcfm.modified asc
                            offset quantity_in
                        );
    begin
        -- if we get a null customer_id, this is completely bogus.
        if customer_id_in is null then
            return;
        end if;

        tmp_quantity := quantity_in;
        is_fve_in := 'N';

        for sc in serverchannels loop
            perform rhn_channel.unsubscribe_server(sc.server_id, sc.channel_id, 1, 1, 0, 0);

        tmp_quantity := flex_in;
        is_fve_in := 'Y';
        for sc in serverchannels loop
            perform rhn_channel.unsubscribe_server(sc.server_id, sc.channel_id, 1, 1, 0, 0);
        end loop;
        end loop;
                perform rhn_channel.update_family_counts(channel_family_id_in, customer_id_in);
    end$$
language plpgsql;

    create or replace function set_family_count (
        customer_id_in in numeric,      -- customer_id
        channel_family_id_in in numeric,    -- 246
        quantity_in in numeric,          -- 3
        flex_in in numeric
    ) returns void
as $$
    declare
        privperms cursor for
            select  1
            from    rhnPrivateChannelFamily
            where   org_id = customer_id_in
                and channel_family_id = channel_family_id_in;
        pubperms cursor for
            select  o.id org_id
            from    web_customer o,
                    rhnPublicChannelFamily pcf
            where   pcf.channel_family_id = channel_family_id_in;
        quantity numeric;
        done numeric := 0;
        flex numeric;
    begin
        quantity := quantity_in;
        if quantity is not null and quantity < 0 then
            quantity := 0;
        end if;
        flex := flex_in;
        if flex is not null and flex < 0 then
            flex := 0;
        end if;

        if customer_id_in is not null then
            for perm in privperms loop
                perform rhn_entitlements.prune_family(
                    customer_id_in,
                    channel_family_id_in,
                    quantity,
                    flex
                );

                if quantity is null and flex is null then
                    delete from rhnPrivateChannelFamily
                        where org_id = customer_id_in
                            and channel_family_id = channel_family_id_in;
                 else
                    update rhnPrivateChannelFamily
                        set max_members = quantity
                        where org_id = customer_id_in
                            and channel_family_id = channel_family_id_in;

                   update rhnPrivateChannelFamily
                        set fve_max_members = flex
                        where org_id = customer_id_in
                            and channel_family_id = channel_family_id_in;
                end if;
                return;
            end loop;

            insert into rhnPrivateChannelFamily (
                    channel_family_id, org_id, max_members, current_members, fve_max_members, fve_current_members
                ) values (
                    channel_family_id_in, customer_id_in, quantity, 0, flex, 0 );
            return;
        end if;

        for perm in pubperms loop
            if quantity = 0 then
                perform rhn_entitlements.prune_family(
                    perm.org_id,
                    channel_family_id_in,
                    quantity,
                    flex
                );
                if done = 0 then
                    delete from rhnPublicChannelFamily
                        where channel_family_id = channel_family_id_in;
                end if;
            end if;
            done := 1;
        end loop;
        -- if done's not 1, then we don't have any entitlements
        if done != 1 then
            insert into rhnPublicChannelFamily (
                    channel_family_id
                ) values (
                    channel_family_id_in
                );
        end if;
    end$$
language plpgsql;

    -- this expects quantity_in to be the number of available slots, not the
    -- max_members of the server group.  If you give it too many, it'll fail
    -- and raise servergroup_max_members.
    -- We should NEVER run this unless we're SURE that we won't
    -- be violating the max.
    create or replace function entitle_last_modified_servers (
        customer_id_in in numeric,  -- customer_id
        type_label_in in varchar,   -- 'enterprise_entitled'
        quantity_in in numeric      -- 3
    ) returns void
as $$
    declare
        -- find the servers that aren't currently in slots
        servers cursor(cid_in numeric, quant_in numeric) for
                                    select  rs.id as server_id
                                    from    rhnServer rs
                                    where   1=1
                                        and rs.org_id = cid_in
                                        and not exists (
                                            select  1
                                            from    rhnServerGroup sg,
                                                    rhnServerGroupMembers rsgm
                                            where   rsgm.server_id = rs.id
                                                and rsgm.server_group_id = sg.id
                                                and sg.group_type is not null
                                        )
                                        and not exists (
                                            select 1
                                            from rhnVirtualInstance vi
                                            where vi.virtual_system_id =
                                                  rs.id
                                        )
                                    order by modified desc
                                    limit quant_in;
    begin
        for server in servers(customer_id_in, quantity_in) loop
            perform rhn_entitlements.entitle_server(server.server_id, type_label_in);
        end loop;
    end$$
language plpgsql;

    create or replace function subscribe_newest_servers (
        customer_id_in in numeric
    ) returns void
as $$
    declare
        -- find servers without base channels
        servers cursor(cid_in numeric) for
            select  s.id
            from    rhnServer           s
            where   1=1
                and s.org_id = cid_in
                and not exists (
                        select 1
                        from    rhnChannel          c,
                                rhnServerChannel    sc
                        where   sc.server_id = s.id
                            and sc.channel_id = c.id
                            and c.parent_channel is null
                    )
                and not exists (
                        select 1
                        from rhnVirtualInstance vi
                        where vi.virtual_system_id = s.id
                    )
            order by s.modified desc;
        channel_id numeric;
    begin
        for server in servers(customer_id_in) loop
            channel_id := rhn_channel.guess_server_base(server.id);
            if channel_id is not null then
                begin
                    perform rhn_channel.subscribe_server(server.id, channel_id);
                -- exception is really channel_family_no_subscriptions
                exception
                    when others then
                        null;
                end;
            end if;
        end loop;
    end$$
language plpgsql;


-- restore the original setting
update pg_settings set setting = overlay( setting placing '' from 1 for (length('rhn_entitlements')+1) ) where name = 'search_path';


create or replace
function delete_server (
        server_id_in in numeric
) returns void
as
$$
declare
         servergroups cursor for
                select  server_id, server_group_id
                from    rhnServerGroupMembers sgm
                where   sgm.server_id = server_id_in;

         configchannels cursor for
                select  cc.id
                from    rhnConfigChannel cc,
                        rhnConfigChannelType cct,
                        rhnServerConfigChannel scc
                where   1=1
                        and scc.server_id = server_id_in
                        and scc.config_channel_id = cc.id
                        -- these config channel types are reserved
                        -- for use by a single server, so we don't
                        -- need to check for other servers subscribed
                        and cct.label in
                                ('local_override','server_import')
                        and cct.id = cc.confchan_type_id;

    is_virt boolean;
begin
        perform rhn_channel.delete_server_channels(server_id_in);
        -- rhn_channel.clear_subscriptions(server_id_in);

        -- filelists
        delete from rhnFileList where id in (
	select	spfl.file_list_id
	  from	rhnServerPreserveFileList spfl
	 where	spfl.server_id = server_id_in
			and not exists (
				select	1
				from	rhnServerPreserveFileList
				where	file_list_id = spfl.file_list_id
					and server_id != server_id_in
				union all
				select	1
				from	rhnKickstartPreserveFileList
				where	file_list_id = spfl.file_list_id
			)
        );

	for configchannel in configchannels loop
		perform rhn_config.delete_channel(configchannel.id);
	end loop;

      is_virt := exists (
       select 1
        from rhnServerEntitlementView
       where server_id = server_id_in
         and label in ('virtualization_host', 'virtualization_host_platform')
      );

	for sgm in servergroups loop
		perform rhn_server.delete_from_servergroup(
			sgm.server_id, sgm.server_group_id);
	end loop;

    if is_virt then
        perform rhn_entitlements.repoll_virt_guest_entitlements(server_id_in);
    end if;

        -- we're handling this instead of letting an "on delete
        -- set null" do it so that we don't run the risk
        -- of setting off the triggers and killing us with a
        -- mutating table

        -- this is merge of two single updates:
        --  update ... set old_server_id = null where old_server_id = server_id_in;
        --  update ... set new_server_id = null where new_server_id = server_id_in;
        -- so we scan rhnKickstartSession table only once
        update rhnKickstartSession
                set old_server_id = case when old_server_id = server_id_in then null else old_server_id end,
                    new_server_id = case when new_server_id = server_id_in then null else new_server_id end
                where old_server_id = server_id_in
                   or new_server_id = server_id_in;

        perform rhn_channel.clear_subscriptions(server_id_in, 1, 1);

        -- A little complicated here, but the goal is to
        -- delete records from rhnVirtualInstace only if we don't
        -- care about them anymore.  We don't care about records
        -- in rhnVirtualInstance if we are deleting the host
        -- system and the virtual system is already null, or
        -- vice-versa.  We *do* care about them if either the
        -- host or virtual system is still registered because we
        -- still want them to show up in the UI.
    -- If there's a newer row in rhnVirtualInstance with the same
    -- uuid, this guest must have been re-registered, so we can clean
    -- this data up.

        delete from rhnVirtualInstance vi
              where (host_system_id = server_id_in and virtual_system_id is null)
                 or (virtual_system_id = server_id_in and host_system_id is null)
                 or (vi.virtual_system_id = server_id_in and vi.modified < (select max(vi2.modified)
                    from rhnVirtualInstance vi2 where vi2.uuid = vi.uuid));

        -- this is merge of two single updates:
        --  update ... set host_system_id = null where host_system_id = server_id_in;
        --  update ... set virtual_system_id = null where virtual_system_id = server_id_in;
        -- so we scan rhnVirtualInstance table only once
        update rhnVirtualInstance
           set host_system_id = case when host_system_id = server_id_in then null else host_system_id end,
               virtual_system_id = case when virtual_system_id = server_id_in then null else virtual_system_id end
         where host_system_id = server_id_in
            or virtual_system_id = server_id_in;

        -- this is merge of two single updates:
        --  update ... set old_host_system_id = null when old_host_system_id = server_id_in;
        --  update ... set new_host_system_id = null when new_host_system_id = server_id_in;
        -- so we scan rhnVirtualInstanceEventLog table only once
        update rhnVirtualInstanceEventLog
           set old_host_system_id = case when old_host_system_id = server_id_in then null else old_host_system_id end,
               new_host_system_id = case when new_host_system_id = server_id_in then null else new_host_system_id end
         where old_host_system_id = server_id_in
            or new_host_system_id = server_id_in;

        -- We're deleting everything with a foreign key to rhnServer
        -- here, now.  I'm hoping this will help aleviate our deadlock
        -- problem.

        delete from rhnActionConfigChannel where server_id = server_id_in;
        delete from rhnActionConfigRevision where server_id = server_id_in;
        delete from rhnActionPackageRemovalFailure where server_id = server_id_in;
        delete from rhnClientCapability where server_id = server_id_in;
        delete from rhnCpu where server_id = server_id_in;
        -- there's still a cascade here, because the constraint keeps the
        -- table locked for too long to rebuild it.  Ugh...
        delete from rhnDevice where server_id = server_id_in;
        delete from rhnProxyInfo where server_id = server_id_in;
        delete from rhnRam where server_id = server_id_in;
        delete from rhnRegToken where server_id = server_id_in;
        delete from rhnSatelliteInfo where server_id = server_id_in;
        -- this cascades to rhnActionConfigChannel and rhnActionConfigFileName
        delete from rhnServerAction where server_id = server_id_in;
        delete from rhnServerActionPackageResult where server_id = server_id_in;
        delete from rhnServerActionScriptResult where server_id = server_id_in;
        delete from rhnServerActionVerifyResult where server_id = server_id_in;
        delete from rhnServerActionVerifyMissing where server_id = server_id_in;
        -- counts are handled above.  this should be a delete_ function.
        delete from rhnServerChannel where server_id = server_id_in;
        delete from rhnServerConfigChannel where server_id = server_id_in;
        delete from rhnServerCustomDataValue where server_id = server_id_in;
        delete from rhnServerDMI where server_id = server_id_in;
        delete from rhnServerEvent where server_id = server_id_in;
        delete from rhnServerHistory where server_id = server_id_in;
        delete from rhnServerInfo where server_id = server_id_in;
        delete from rhnServerInstallInfo where server_id = server_id_in;
        delete from rhnServerLocation where server_id = server_id_in;
        delete from rhnServerLock where server_id = server_id_in;
        delete from rhnServerNeededCache where server_id = server_id_in;
        delete from rhnServerNetwork where server_id = server_id_in;
        delete from rhnServerNotes where server_id = server_id_in;
        -- I'm not removing the foreign key from rhnServerPackage; that'll
        -- take forever.  Do the delete anyway.
        delete from rhnServerPackage where server_id = server_id_in;
        delete from rhnServerTokenRegs where server_id = server_id_in;
        delete from rhnSnapshotTag where server_id = server_id_in;
        -- this cascades to:
        --   rhnSnapshotChannel, rhnSnapshotConfigChannel, rhnSnapshotPackage,
        --   rhnSnapshotConfigRevision, rhnSnapshotServerGroup,
        --   rhnSnapshotTag.
        -- We may want to consider delete_snapshot() at some point, but
        --   I don't think we need to yet.
        delete from rhnSnapshot where server_id = server_id_in;
        delete from rhnUserServerPrefs where server_id = server_id_in;
        -- hrm, this one's interesting... we _probably_ should delete
        -- everything for the parent server_id when we delete the proxy,
        -- but we don't currently.
        delete from rhnServerPath where server_id_in in (server_id, proxy_server_id);
        delete from rhnUserServerPerms where server_id = server_id_in;

        delete from rhnServerNetInterface where server_id = server_id_in;
        delete from rhn_server_monitoring_info where recid = server_id_in;

        delete from rhnServerUuid where server_id = server_id_in;

    -- We delete all the probes running directly against this system
    -- and any probes that were using this Server as a Proxy Scout.
    DELETE FROM rhn_probe_state PS WHERE PS.probe_id IN (
     SELECT CP.probe_id
       FROM rhn_check_probe CP
      WHERE CP.host_id = server_id_in
         OR CP.sat_cluster_id in
    (SELECT SN.sat_cluster_id
       FROM rhn_sat_node SN
      WHERE SN.server_id = server_id_in)
    );

    DELETE FROM rhn_probe P  WHERE P.recid IN (
     SELECT CP.probe_id
       FROM rhn_check_probe CP
      WHERE CP.host_id = server_id_in
         OR CP.sat_cluster_id in
    (SELECT SN.sat_cluster_id
       FROM rhn_sat_node SN
      WHERE SN.server_id = server_id_in)
    );

        delete from rhn_check_probe where host_id = server_id_in;
        delete from rhn_host_probe where host_id = server_id_in;

    delete from rhn_sat_cluster where recid in
      ( select sat_cluster_id from rhn_sat_node where server_id = server_id_in );

        delete from rhn_sat_node where server_id = server_id_in;

        delete from rhnPushClient where server_id = server_id_in;

        -- now get rhnServer itself.
        delete
        from    rhnServer
                where id = server_id_in;

        delete
        from    rhnSet
        where   1=1
                and user_id in (
                        select  wc.id
                        from    rhnServer rs,
                                web_contact wc
                        where   rs.id = server_id_in
                                and rs.org_id = wc.org_id
                )
                and label = 'system_list'
                and element = server_id_in;
end;
$$
language plpgsql;
 070701000006D4000081B400000000000000000000000167AE111400000E84000000000000000000000000000000000000006200000000susemanager-schema/upgrade/spacewalk-schema-1.6-to-spacewalk-schema-1.7/026-rhnServerOverview.sql --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
drop view rhnServerOverview;
create view
rhnServerOverview
(
    org_id, 
    server_id, 
    server_name, 
    modified, 
    server_admins, 
    group_count, 
    channel_id,
    channel_labels, 
    history_count, 
    security_errata, 
    bug_errata, 
    enhancement_errata,
    outdated_packages,
	config_files_with_differences,
    last_checkin_days_ago,
    last_checkin,
    pending_updates,
    os,
    release,
    server_arch_name,
    locked
)
as
select
    s.org_id, s.id, s.name, s.modified,
    ( select count(user_id) from rhnUserServerPerms ap 
      where server_id = s.id ), 
    ( select count(server_group_id) from rhnVisibleServerGroupMembers
      where server_id = s.id ),
    ( select C.id
        from rhnChannel C,
	     rhnServerChannel SC
       where SC.server_id = S.id
         and SC.channel_id = C.id
	 and C.parent_channel IS NULL),
    coalesce(( select C.name
        from rhnChannel C,
	     rhnServerChannel SC
       where SC.server_id = S.id
         and SC.channel_id = C.id
	 and C.parent_channel IS NULL), '(none)'),
    ( select count(id) from rhnServerHistory
      where
            server_id = S.id),
    ( select count(*) from rhnServerErrataTypeView setv 
      where
            setv.server_id = s.id
        and setv.errata_type = 'Security Advisory'), 
    ( select count(*) from rhnServerErrataTypeView setv 
      where 
            setv.server_id = s.id
        and setv.errata_type = 'Bug Fix Advisory'),
    ( select count(*) from rhnServerErrataTypeView setv 
      where 
            setv.server_id = s.id
        and setv.errata_type = 'Product Enhancement Advisory'),
    ( select count(distinct p.name_id) from rhnPackage p, rhnServerNeededPackageCache snpc
      where
             snpc.server_id = S.id
	 and p.id = snpc.package_id
	 ),
    ( select count(*)
        from rhnActionConfigRevision ACR
             INNER JOIN rhnActionConfigRevisionResult ACRR on ACR.id = ACRR.action_config_revision_id
       where ACR.server_id = S.id
         and ACR.action_id = (
              select MAX(rA.id)
                from rhnAction rA
                     INNER JOIN rhnServerAction rSA on rSA.action_id = rA.id
                     INNER JOIN rhnActionStatus rAS on rAS.id = rSA.status
                     INNER JOIN rhnActionType rAT on rAT.id = rA.action_type
               where rSA.server_id = S.id
                 and rAS.name in ('Completed', 'Failed')
                 and rAT.label = 'configfiles.diff'
         )
         and ACR.failure_id is null
         and ACRR.result is not null
        ),
    ( select date_diff_in_days(checkin, current_timestamp) from rhnServerInfo where server_id = S.id ),
    ( select TO_CHAR(checkin, 'YYYY-MM-DD HH24:MI:SS') from rhnServerInfo where server_id = S.id ),
    ( select count(1) 
        from rhnServerAction
       where server_id = S.id
         and status in (0, 1)),
    os,
    release,
    ( select name from rhnServerArch where id = s.server_arch_id),
    coalesce((select 1 from rhnServerLock SL WHERE SL.server_id = S.id), 0)
from 
    rhnServer S
;
070701000006D5000081B400000000000000000000000167AE111400000113000000000000000000000000000000000000006800000000susemanager-schema/upgrade/spacewalk-schema-1.6-to-spacewalk-schema-1.7/027-monitoring-data-cleanup.sql   -- delete orphaned data from state_change
delete from state_change sc where sc.o_id not in (select rp.recid || '' from rhn_probe rp);

-- delete orphaned data from rhn_probe_state
delete from rhn_probe_state rps where rps.probe_id not in (select rp.recid from rhn_probe rp);
 070701000006D6000081B400000000000000000000000167AE1114000005E9000000000000000000000000000000000000006200000000susemanager-schema/upgrade/spacewalk-schema-1.6-to-spacewalk-schema-1.7/028-rhnActionOverview.sql --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
CREATE OR REPLACE VIEW
rhnActionOverview
(
	org_id,
	action_id,
	type_id,
	type_name,
	name,
    	scheduler,
	scheduler_login,
	earliest_action,
	total_count,
	successful_count,
	failed_count,
	in_progress_count,
	archived
)
AS
SELECT    A.org_id,
	  A.id,
	  AT.id,
	  AT.name,
	  A.name,
	  A.scheduler,
	  U.login,
	  A.earliest_action,
	  (SELECT COUNT(*) FROM rhnServerAction WHERE action_id = A.id),
	  (SELECT COUNT(*) FROM rhnServerAction WHERE action_id = A.id AND status = 2), -- XXX: don''t hard code status here :)
	  (SELECT COUNT(*) FROM rhnServerAction WHERE action_id = A.id AND status = 3),
	  (SELECT COUNT(*) FROM rhnServerAction WHERE action_id = A.id AND status NOT IN (2, 3)),
	  A.archived
FROM
	  rhnActionType AT,
	  rhnAction A
		left outer join
          web_contact U
		on A.scheduler = U.id
WHERE A.action_type = AT.id
ORDER BY  A.earliest_action;

   070701000006D7000081B400000000000000000000000167AE111400000434000000000000000000000000000000000000006800000000susemanager-schema/upgrade/spacewalk-schema-1.6-to-spacewalk-schema-1.7/029-rhnChannelFamilyServers.sql   --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--

create or replace view rhnChannelFamilyServers as
	select	rs.org_id			as customer_id,
		rcfm.channel_family_id		as channel_family_id,
		rsc.server_id			as server_id,
		rsc.created			as created,
		rsc.modified			as modified
	from	rhnChannelFamilyMembers		rcfm,
		rhnChannelFamily		rcf,
		rhnServerChannel		rsc,
		rhnServer			rs
	where
		rcfm.channel_id = rsc.channel_id
		and rcfm.channel_family_id = rcf.id
		and rsc.server_id = rs.id;

070701000006D8000081B400000000000000000000000167AE1114000004B7000000000000000000000000000000000000006600000000susemanager-schema/upgrade/spacewalk-schema-1.6-to-spacewalk-schema-1.7/030-rhnChannelPermissions.sql --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--

create or replace view
rhnChannelPermissions
(
    org_id, channel_id
)
as
select distinct org_id, channel_id
 from ( select privcf.org_id,
               cfm.channel_id
        from   rhnChannelFamilyMembers cfm,
               rhnPrivateChannelFamily privcf
        where  privcf.channel_family_id = cfm.channel_family_id
       union all
       select  u.org_id, cfm.channel_id
       from    web_contact u,
               rhnChannelFamilyMembers cfm,
               rhnPublicChannelFamily pubcf
       where   pubcf.channel_family_id = cfm.channel_family_id
) S;

 070701000006D9000081B400000000000000000000000167AE111400000665000000000000000000000000000000000000006300000000susemanager-schema/upgrade/spacewalk-schema-1.6-to-spacewalk-schema-1.7/031-rhnChannelTreeView.sql    --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--

CREATE OR REPLACE VIEW rhnChannelTreeView
(
        id,
        depth,
	name,
        padded_name,
	channel_arch_id,
        last_modified,
        label,
	parent_or_self_label,
	parent_or_self_id,
	end_of_life
)
AS
select * from (
	select	c.id			as id,
		1			as depth,
		c.name			as name,
		'  ' || c.name		as padded_name,
		c.channel_arch_id	as channel_arch_id,
		c.last_modified		as last_modified,
		c.label			as label,
		c.label			as parent_or_self_label,
		c.id			as parent_or_self_id,
		c.end_of_life		as end_of_life
	from	rhnChannel		c
	where	c.parent_channel is null
	union
	select	c.id			as id,
		2			as depth,
		c.name			as name,
		'' || c.name		as padded_name,
		c.channel_arch_id 	as channel_arch_id,
		c.last_modified		as last_modified,
		c.label			as label,
		pc.label		as parent_or_self_label,
		pc.id			as parent_or_self_id,
		c.end_of_life		as end_of_life
	from	rhnChannel		pc,
		rhnChannel		c
	where	c.parent_channel = pc.id
) S order by parent_or_self_label, parent_or_self_id;

   070701000006DA000081B400000000000000000000000167AE111400000473000000000000000000000000000000000000006F00000000susemanager-schema/upgrade/spacewalk-schema-1.6-to-spacewalk-schema-1.7/032-rhnOrgChannelFamilyPermissions.sql    --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--

create or replace view rhnOrgChannelFamilyPermissions as
	select	pcf.channel_family_id,
		u.org_id as org_id,
		to_number(null, null) as max_members,
		0 as current_members,
		to_number(null, null) as fve_max_members,
		0 as fve_current_members,
		pcf.created,
		pcf.modified
	from	rhnPublicChannelFamily pcf,
		web_contact u
	union
	select	channel_family_id,
		org_id,
		max_members,
		current_members,
		fve_max_members,
		fve_current_members,
		created,
		modified
	from	rhnPrivateChannelFamily;

 070701000006DB000081B400000000000000000000000167AE1114000007CD000000000000000000000000000000000000006600000000susemanager-schema/upgrade/spacewalk-schema-1.6-to-spacewalk-schema-1.7/033-rhnOrgChannelTreeView.sql --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--

CREATE OR REPLACE VIEW rhnOrgChannelTreeView
(
	org_id,
        id,
        depth,
	name,
        padded_name,
	channel_arch_id,
        last_modified,
        label,
	parent_or_self_label,
	parent_or_self_id,
	end_of_life
)
AS
select * from (
	select	cfp.org_id		as org_id,
		c.id			as id,
		1			as depth,
		c.name			as name,
		'  ' || c.name		as padded_name,
		c.channel_arch_id	as channel_arch_id,
		c.last_modified		as last_modified,
		c.label			as label,
		c.label			as parent_or_self_label,
		c.id			as parent_or_self_id,
		c.end_of_life		as end_of_life
	from	rhnChannel		c,
		rhnChannelFamilyMembers cfm,
		rhnOrgChannelFamilyPermissions cfp
	where	cfp.channel_family_id = cfm.channel_family_id
		and cfm.channel_id = c.id
		and c.parent_channel is null
	union
	select	cfp.org_id		as org_id,
		c.id			as id,
		2			as depth,
		c.name			as name,
		'' || c.name		as padded_name,
		c.channel_arch_id 	as channel_arch_id,
		c.last_modified		as last_modified,
		c.label			as label,
		pc.label		as parent_or_self_label,
		pc.id			as parent_or_self_id,
		c.end_of_life		as end_of_life
	from	rhnChannel		pc,
		rhnChannel		c,
		rhnChannelFamilyMembers	cfm,
		rhnOrgChannelFamilyPermissions cfp
	where	cfp.channel_family_id = cfm.channel_family_id
		and cfm.channel_id = c.id
		and c.parent_channel = pc.id
) s order by parent_or_self_label, parent_or_self_id;

   070701000006DC000081B400000000000000000000000167AE11140000043A000000000000000000000000000000000000006900000000susemanager-schema/upgrade/spacewalk-schema-1.6-to-spacewalk-schema-1.7/034-rhnServerGroupMembership.sql  --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--


CREATE OR REPLACE VIEW rhnServerGroupMembership (
         ORG_ID, SERVER_ID, GROUP_ID, GROUP_NAME, GROUP_TYPE, CURRENT_MEMBERS, MAX_MEMBERS
)
AS
SELECT   SG.org_id, SGM.server_id, SG.id, SG.name, SGT.label, SG.current_members, SG.max_members
  FROM
	 rhnServerGroupMembers SGM
             right join
    	 rhnServerGroup SG on (SG.id = SGM.server_group_id)
             left join
         rhnServerGroupType SGT on (SG.group_type = SGT.id)
;

  070701000006DD000081B400000000000000000000000167AE1114000003FF000000000000000000000000000000000000006B00000000susemanager-schema/upgrade/spacewalk-schema-1.6-to-spacewalk-schema-1.7/035-rhnServerGroupOVLiteHelper.sql    --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--
-- this is a helper for rhnServerGroupOverviewLite and it's Vis brother.

create or replace view
rhnServerGroupOVLiteHelper as
select	sgm.server_group_id						as server_group_id,
		e.advisory_type							as advisory_type
from	rhnErrata								e,
		rhnServerNeededPackageCache				snpc,
		rhnServerGroupMembers					sgm
where   sgm.server_id = snpc.server_id
	and snpc.errata_id = e.id
;

 070701000006DE000081B400000000000000000000000167AE111400000631000000000000000000000000000000000000006900000000susemanager-schema/upgrade/spacewalk-schema-1.6-to-spacewalk-schema-1.7/036-rhnSharedChannelTreeView.sql  --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--

CREATE OR REPLACE VIEW RHNSHAREDCHANNELTREEVIEW
(
  ORG_ID,
  ID,
  DEPTH,
  NAME,
  PADDED_NAME,
  CHANNEL_ARCH_ID,
  LAST_MODIFIED,
  LABEL,
  PARENT_OR_SELF_LABEL,
  PARENT_OR_SELF_ID,
  END_OF_LIFE
)
AS
SELECT * FROM (
  SELECT
    C.ORG_TRUST_ID AS ORG_ID,
    C.ID,
    1 AS DEPTH,
    C.NAME,
    '  '||C.NAME AS PADDED_NAME,
    C.CHANNEL_ARCH_ID,
    C.LAST_MODIFIED,
    C.LABEL,
    C.LABEL AS PARENT_OR_SELF_LABEL,
    C.ID AS PARENT_OR_SELF_ID,
    C.END_OF_LIFE
  FROM RHNSHAREDCHANNELVIEW C
  WHERE C.PARENT_CHANNEL IS NULL
  UNION
  SELECT
    C.ORG_TRUST_ID AS ORG_ID,
    C.ID,
    2 AS DEPTH,
    c.name,
    ''||C.NAME AS PADDED_NAME,
    C.CHANNEL_ARCH_ID,
    C.LAST_MODIFIED,
    C.LABEL,
    PC.LABEL AS PARENT_OR_SELF_LABEL,
    PC.ID AS PARENT_OR_SELF_ID,
    C.END_OF_LIFE
  FROM RHNCHANNEL PC,
       RHNSHAREDCHANNELVIEW C
  WHERE C.PARENT_CHANNEL = PC.ID
) SHARRED
ORDER BY PARENT_OR_SELF_LABEL, PARENT_OR_SELF_ID;

   070701000006DF000081B400000000000000000000000167AE111400000427000000000000000000000000000000000000006500000000susemanager-schema/upgrade/spacewalk-schema-1.6-to-spacewalk-schema-1.7/037-rhnSharedChannelView.sql  CREATE OR REPLACE VIEW RHNSHAREDCHANNELVIEW
AS
SELECT 
   CH.ID,
   CH.PARENT_CHANNEL,
   CH.ORG_ID,
   CH.CHANNEL_ARCH_ID,
   CH.LABEL,
   CH.BASEDIR,
   CH.NAME,
   CH.SUMMARY,
   CH.DESCRIPTION,
   CH.PRODUCT_NAME_ID,
   CH.GPG_KEY_URL,
   CH.GPG_KEY_ID,
   CH.GPG_KEY_FP,
   CH.END_OF_LIFE,
   CH.RECEIVING_UPDATES,
   CH.LAST_MODIFIED,
   CH.CHANNEL_PRODUCT_ID,
   CH.CREATED,
   CH.MODIFIED,
   CH.CHANNEL_ACCESS,
   TR.ORG_TRUST_ID
FROM RHNCHANNEL CH,
     RHNTRUSTEDORGS TR
WHERE CH.ORG_ID = TR.ORG_ID AND
      CH.CHANNEL_ACCESS = 'public'
UNION
SELECT
   CH.ID,
   CH.PARENT_CHANNEL,
   CH.ORG_ID,
   CH.CHANNEL_ARCH_ID,
   CH.LABEL,
   CH.BASEDIR,
   CH.NAME,
   CH.SUMMARY,
   CH.DESCRIPTION,
   CH.PRODUCT_NAME_ID,
   CH.GPG_KEY_URL,
   CH.GPG_KEY_ID,
   CH.GPG_KEY_FP,
   CH.END_OF_LIFE,
   CH.RECEIVING_UPDATES,
   CH.LAST_MODIFIED,
   CH.CHANNEL_PRODUCT_ID,
   CH.CREATED,
   CH.MODIFIED,
   CH.CHANNEL_ACCESS,
   TR.ORG_TRUST_ID
FROM RHNCHANNEL CH,
     RHNCHANNELTRUST TR
WHERE CH.ID = TR.CHANNEL_ID AND
      CH.CHANNEL_ACCESS = 'protected'
;

 070701000006E0000081B400000000000000000000000167AE111400000787000000000000000000000000000000000000006600000000susemanager-schema/upgrade/spacewalk-schema-1.6-to-spacewalk-schema-1.7/038-rhnUserActionOverview.sql --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--
-- rhnActionOverview, but on a per-user basis.

-- invoke as:
--
-- select	*
-- from		rhnUserActionOverview
-- where	org_id = :oid
--		and user_id = :uid;
--

create or replace view rhnUserActionOverview as
select	ao.org_id                                       as org_id,
	usp.user_id                                     as user_id,
    	ao.action_id                                    as id,
	ao.type_name                                    as type_name,
        ao.scheduler                                    as scheduler,
	ao.earliest_action                              as earliest_action,
	coalesce( ao.name, ao.type_name )		as action_name,
	sa.status					as action_status_id,
	astat.name                                      as action_status,
	count(sa.action_id)				as tally,
	ao.archived                                     as archived
from	rhnActionStatus            astat,
    	rhnUserServerPerms         usp,
	rhnServerAction            sa,
	rhnActionOverview	   ao
where	ao.action_id = sa.action_id
  and   sa.server_id = usp.server_id
  and   sa.status = astat.id
group by ao.org_id,
	 usp.user_id,
	 ao.action_id,
	 ao.type_name,
	 ao.scheduler,
	 ao.earliest_action,
	 coalesce( ao.name, ao.type_name ),
	 sa.status,
	 astat.name,
	 ao.archived
order by earliest_action;

 070701000006E1000081B400000000000000000000000167AE1114000005DE000000000000000000000000000000000000005F00000000susemanager-schema/upgrade/spacewalk-schema-1.6-to-spacewalk-schema-1.7/039-rhnUserChannel.sql    --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--

create or replace view rhnUserChannel
as
select
   cfp.user_id,
   cfp.org_id,
   cfm.channel_id,
   'manage' as role
from rhnChannelFamilyMembers cfm,
      rhnUserChannelFamilyPerms cfp
where
   cfp.channel_family_id = cfm.channel_family_id and
   rhn_channel.user_role_check(cfm.channel_id, cfp.user_id, 'manage') = 1
union all
select
   cfp.user_id,
   cfp.org_id,
   cfm.channel_id,
   'subscribe' as role
from rhnChannelFamilyMembers cfm,
      rhnUserChannelFamilyPerms cfp
where
   cfp.channel_family_id = cfm.channel_family_id and
   rhn_channel.user_role_check(cfm.channel_id, cfp.user_id, 'subscribe') = 1
union all
select
   w.id as user_id,
   w.org_id,
   s.id as channel_id,
   'subscribe' as role
from rhnSharedChannelView s,
      web_contact w
where
   w.org_id = s.org_trust_id and
   rhn_channel.user_role_check(s.id, w.id, 'subscribe') = 1;

  070701000006E2000081B400000000000000000000000167AE111400000804000000000000000000000000000000000000006700000000susemanager-schema/upgrade/spacewalk-schema-1.6-to-spacewalk-schema-1.7/040-rhnUserChannelTreeView.sql    --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--

CREATE OR REPLACE VIEW rhnUserChannelTreeView
(
	user_id,
	org_id,
        id,
        depth,
	name,
        padded_name,
	channel_arch_id,
        last_modified,
        label,
	parent_or_self_label,
	parent_or_self_id,
	end_of_life
)
AS
select * from (
	select	cfp.user_id		as user_id,
		cfp.org_id		as org_id,
		c.id			as id,
		1			as depth,
		c.name			as name,
		'  ' || c.name		as padded_name,
		c.channel_arch_id	as channel_arch_id,
		c.last_modified		as last_modified,
		c.label			as label,
		c.label			as parent_or_self_label,
		c.id			as parent_or_self_id,
		c.end_of_life		as end_of_life
	from	rhnChannel		c,
		rhnChannelFamilyMembers cfm,
		rhnUserChannelFamilyPerms cfp
	where	cfp.channel_family_id = cfm.channel_family_id
		and cfm.channel_id = c.id
		and c.parent_channel is null
	union
	select	cfp.user_id		as user_id,
		cfp.org_id		as org_id,
		c.id			as id,
		2			as depth,
		c.name			as name,
		'' || c.name		as padded_name,
		c.channel_arch_id 	as channel_arch_id,
		c.last_modified		as last_modified,
		c.label			as label,
		pc.label		as parent_or_self_label,
		pc.id			as parent_or_self_id,
		c.end_of_life		as end_of_life
	from	rhnChannel		pc,
		rhnChannel		c,
		rhnChannelFamilyMembers	cfm,
		rhnUserChannelFamilyPerms cfp
	where	cfp.channel_family_id = cfm.channel_family_id
		and cfm.channel_id = c.id
		and c.parent_channel = pc.id
) S order by parent_or_self_label, parent_or_self_id;

070701000006E3000081B400000000000000000000000167AE111400000446000000000000000000000000000000000000006C00000000susemanager-schema/upgrade/spacewalk-schema-1.6-to-spacewalk-schema-1.7/041-rhnVisServerGroupMembership.sql   --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
CREATE OR REPLACE VIEW rhnVisServerGroupMembership (
         ORG_ID, SERVER_ID, GROUP_ID, GROUP_NAME, GROUP_TYPE, CURRENT_MEMBERS, MAX_MEMBERS
)
AS
SELECT   SG.org_id, SGM.server_id, SG.id, SG.name, SGT.label, SG.current_members, SG.max_members
  FROM
	 rhnServerGroupMembers SGM
            right outer join
    	 rhnVisibleServerGroup SG on (SG.id = SGM.server_group_id)
            left outer join
         rhnServerGroupType SGT on (SG.group_type = SGT.id)
;

  070701000006E4000081B400000000000000000000000167AE111400000517000000000000000000000000000000000000006600000000susemanager-schema/upgrade/spacewalk-schema-1.6-to-spacewalk-schema-1.7/042-rhnWebContactDisabled.sql --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--
create or replace view
rhnWebContactDisabled
as
select
   wcon.id,
   wcon.org_id,
   wcon.login,
   wcon.login_uc,
   wcon.password,
   wcon.old_password,
   wcon.oracle_contact_id,
   wcon.created,
   wcon.modified,
   wcon.ignore_flag
from
   rhnWebContactChangeLog   wccl,
   rhnWebContactChangeState wccs,
   web_contact              wcon
where wccl.change_state_id = wccs.id
   and wccs.label = 'disabled'
   and wccl.web_contact_id = wcon.id
   and wccl.date_completed =
              (select max(wccl_exists.date_completed)
                 from rhnWebContactChangeLog   wccl_exists
                where wccl.web_contact_id = wccl_exists.web_contact_id);

 070701000006E5000081B400000000000000000000000167AE111400000468000000000000000000000000000000000000006700000000susemanager-schema/upgrade/spacewalk-schema-1.6-to-spacewalk-schema-1.7/043-rhn_contact_monitoring.sql    --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--
--

create or replace view rhn_contact_monitoring as
select	u.id			as recid,
	u.org_id		as customer_id,
	wupi.last_name		as contact_last_name,
	wupi.first_names	as contact_first_name,
	rhn_user.find_mailable_address(u.id)
				as email_address,
	u.login			as username,
	u.password		as password,
	1			as schedule_id,
	'GMT'			as preferred_time_zone
from 
	web_user_personal_info wupi,
	web_contact u
where	u.id = wupi.web_user_id
	--  and some logic here to check org id for entitlements?
;

070701000006E6000081B400000000000000000000000167AE111400000082000000000000000000000000000000000000006400000000susemanager-schema/upgrade/spacewalk-schema-1.6-to-spacewalk-schema-1.7/044-rhnHistoryView-drop.sql   
drop view rhnhistoryview;
drop view rhnhistoryview_errata;
drop view rhnhistoryview_packages;
drop view rhnhistoryview_refresh;

  070701000006E7000081B400000000000000000000000167AE1114000000B1000000000000000000000000000000000000008600000000susemanager-schema/upgrade/spacewalk-schema-1.6-to-spacewalk-schema-1.7/045-rhnHistoryView_erratalist-rhnHistoryView_pkglist.drop.sql 
drop function rhnHistoryView_erratalist(action_id numeric, separator character varying);
drop function rhnHistoryView_pkglist(action_id numeric, separator character varying);

   070701000006E8000081B400000000000000000000000167AE111400000C93000000000000000000000000000000000000006700000000susemanager-schema/upgrade/spacewalk-schema-1.6-to-spacewalk-schema-1.7/046-rhnServerGroupOverview.sql    --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
drop VIEW rhnServerGroupOverview;
CREATE VIEW rhnServerGroupOverview (
         ORG_ID, SECURITY_ERRATA, BUG_ERRATA, ENHANCEMENT_ERRATA, GROUP_ID, GROUP_NAME, GROUP_ADMINS, SERVER_COUNT, MODIFIED, MAX_MEMBERS
)
AS
  SELECT SG.org_id,
         (SELECT COUNT(distinct E.id)
            FROM rhnErrata E,
                 rhnServerNeededPackageCache SNPC,
                 rhnServerGroupMembers SGM
           WHERE E.advisory_type = 'Security Advisory'
                 and snpc.errata_id = e.id
                 and snpc.server_id = sgm.server_id
                 and sgm.server_group_id = sg.id
                 AND EXISTS ( SELECT 1
                              FROM rhnServerFeaturesView SFV
                              WHERE SFV.server_id = SGM.server_id
                                    AND SFV.label = 'ftr_system_grouping')),
         (SELECT COUNT(distinct E.id)
            FROM rhnErrata E,
                 rhnServerNeededPackageCache SNPC,
                 rhnServerGroupMembers SGM
           WHERE E.advisory_type = 'Bug Fix Advisory'
                 and snpc.errata_id = e.id
                 and snpc.server_id = sgm.server_id
                 and sgm.server_group_id = sg.id
                 AND EXISTS ( SELECT 1
                              FROM rhnServerFeaturesView SFV
                              WHERE SFV.server_id = SGM.server_id
                                    AND SFV.label = 'ftr_system_grouping')),
         (SELECT COUNT(distinct E.id)
            FROM rhnErrata E,
                 rhnServerNeededPackageCache SNPC,
                 rhnServerGroupMembers SGM
           WHERE E.advisory_type = 'Product Enhancement Advisory'
                 and snpc.errata_id = e.id
                 and snpc.server_id = sgm.server_id
                 and sgm.server_group_id = sg.id
                 AND EXISTS ( SELECT 1
                              FROM rhnServerFeaturesView SFV
                              WHERE SFV.server_id = SGM.server_id
                                    AND SFV.label = 'ftr_system_grouping')),
         SG.id, SG.name,
         (SELECT COUNT(*) FROM rhnUserManagedServerGroups UMSG WHERE UMSG.server_group_id = SG.id),
         (SELECT COUNT(*) FROM rhnServerGroupMembers SGM WHERE SGM.server_group_id = SG.id
                 AND EXISTS ( SELECT 1
                              FROM rhnServerFeaturesView SFV
                              WHERE SFV.server_id = SGM.server_id
                                    AND SFV.label = 'ftr_system_grouping')),
         CURRENT_TIMESTAMP, MAX_MEMBERS
    FROM rhnServerGroup SG;

 070701000006E9000081B400000000000000000000000167AE111400000027000000000000000000000000000000000000006F00000000susemanager-schema/upgrade/spacewalk-schema-1.6-to-spacewalk-schema-1.7/047-rhnVisServerGroupOverview-drop.sql    
drop view rhnVisServerGroupOverview;

 070701000006EA000081B400000000000000000000000167AE111400000737000000000000000000000000000000000000006E00000000susemanager-schema/upgrade/spacewalk-schema-1.6-to-spacewalk-schema-1.7/048-rhnVisServerGroupOverviewLite.sql --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--
-- This is much more readable with tabsize as 4.  You've been warned ;)

drop view rhnVisServerGroupOverviewLite;
create view
rhnVisServerGroupOverviewLite as
select	sg.org_id					as org_id,
		case when exists (
			select	1
			from	rhnServerGroupOVLiteHelper
			where	server_group_id = sg.id
				and advisory_type = 'Security Advisory'
			)
			then 1
			else 0
			end						as security_errata,
		case when exists (
			select	1
			from	rhnServerGroupOVLiteHelper
			where	server_group_id = sg.id
				and advisory_type = 'Bug Fix Advisory'
			)
			then 1
			else 0
			end						as bug_errata,
		case when exists (
			select	1
			from	rhnServerGroupOVLiteHelper
			where	server_group_id = sg.id
				and advisory_type = 'Product Enhancement Advisory'
			)
			then 1
			else 0
			end						as enhancement_errata,
		sg.id						as group_id,
		sg.name						as group_name,
		(	select	count(*)
			from	rhnUserManagedServerGroups	umsg
			where	umsg.server_group_id = sg.id
		)							as group_admins,
		(	select	count(*)
			from	rhnServerGroupMembers		sgm
			where	sgm.server_group_id = sg.id
		)							as server_count,
		current_timestamp					as modified,
		max_members					as max_members
from	rhnVisibleServerGroup		sg
;

 070701000006EB000081B400000000000000000000000167AE111400000028000000000000000000000000000000000000006B00000000susemanager-schema/upgrade/spacewalk-schema-1.6-to-spacewalk-schema-1.7/049-rhnServerNeededPackageView.sql    
drop view rhnServerNeededPackageView;

070701000006EC000081B400000000000000000000000167AE111400000461000000000000000000000000000000000000006A00000000susemanager-schema/upgrade/spacewalk-schema-1.6-to-spacewalk-schema-1.7/050-rhnUserChannelFamilyPerms.sql --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--

create or replace view rhnUserChannelFamilyPerms as
	select	pcf.channel_family_id,
		u.org_id as org_id,
		u.id as user_id,
		to_number(null, null) as max_members,
		0 as current_members,
		pcf.created,
		pcf.modified
	from	rhnPublicChannelFamily pcf,
		web_contact u
	union
	select	pcf.channel_family_id,
		u.org_id,
		u.id as user_id,
		pcf.max_members,
		pcf.current_members,
		pcf.created,
		pcf.modified
	from	rhnPrivateChannelFamily pcf,
		web_contact u
	where	u.org_id = pcf.org_id;

   070701000006ED000081B400000000000000000000000167AE1114000003ED000000000000000000000000000000000000006500000000susemanager-schema/upgrade/spacewalk-schema-1.6-to-spacewalk-schema-1.7/051-rhnWebContactEnabled.sql  --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--

create or replace view
rhnWebContactEnabled
as
select
   wcon.id,
   wcon.org_id,
   wcon.login,
   wcon.login_uc,
   wcon.password,
   wcon.old_password,
   wcon.oracle_contact_id,
   wcon.created,
   wcon.modified,
   wcon.ignore_flag
from
   web_contact wcon
where not exists (
     select 1 from rhnWebContactDisabled
     where wcon.id = rhnWebContactDisabled.id
   );

   070701000006EE000081B400000000000000000000000167AE1114000003B6000000000000000000000000000000000000006800000000susemanager-schema/upgrade/spacewalk-schema-1.6-to-spacewalk-schema-1.7/052-rhn_customer_monitoring.sql   --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--

drop view rhn_customer_monitoring;
create view rhn_customer_monitoring as
select	org.id			as recid,
	org.name		as description,
	1			as schedule_id,	--24 x 7
	0			as def_ack_wait,
	1			as def_strategy,	--Broadcast, No Ack
	'GMT' || ''		as preferred_time_zone,
	0			as auto_update	--Windows only
from
	web_customer org
;

  070701000006EF000081B400000000000000000000000167AE11140000003B000000000000000000000000000000000000006500000000susemanager-schema/upgrade/spacewalk-schema-1.6-to-spacewalk-schema-1.7/053-new_user_postop-drop.sql  
drop function new_user_postop ( user_id_in IN numeric );

 070701000006F0000081B400000000000000000000000167AE111400000032000000000000000000000000000000000000006000000000susemanager-schema/upgrade/spacewalk-schema-1.6-to-spacewalk-schema-1.7/053-rhn_sat_cluster.sql   ALTER TABLE rhn_sat_cluster ADD vip6 VARCHAR(45);
  070701000006F1000081B400000000000000000000000167AE11140000002E000000000000000000000000000000000000005D00000000susemanager-schema/upgrade/spacewalk-schema-1.6-to-spacewalk-schema-1.7/054-rhn_sat_node.sql  ALTER TABLE rhn_sat_node ADD ip6 VARCHAR(45);
  070701000006F2000081B400000000000000000000000167AE111400000021000000000000000000000000000000000000006800000000susemanager-schema/upgrade/spacewalk-schema-1.6-to-spacewalk-schema-1.7/054-valid_countries_tl-drop.sql   
drop table valid_countries_tl;

   070701000006F3000081B400000000000000000000000167AE111400000015000000000000000000000000000000000000005D00000000susemanager-schema/upgrade/spacewalk-schema-1.6-to-spacewalk-schema-1.7/055-rhnUser-drop.sql  
drop view rhnUser;

   070701000006F4000081B400000000000000000000000167AE11140000004F000000000000000000000000000000000000006E00000000susemanager-schema/upgrade/spacewalk-schema-1.6-to-spacewalk-schema-1.7/060-rhnAppInstallSessionData-drop.sql 
drop table rhnAppInstallSessionData;
drop sequence rhn_appinst_sdata_id_seq;

 070701000006F5000081B400000000000000000000000167AE111400000032000000000000000000000000000000000000007400000000susemanager-schema/upgrade/spacewalk-schema-1.6-to-spacewalk-schema-1.7/061-rhn_appinst_sdata_mod_trig_fun-drop.sql   
drop function rhn_appinst_sdata_mod_trig_fun();

  070701000006F6000081B400000000000000000000000167AE1114000016FF000000000000000000000000000000000000005C00000000susemanager-schema/upgrade/spacewalk-schema-1.6-to-spacewalk-schema-1.7/062-rhn_org.pkb.sql   --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--

-- create schema rhn_org;

-- setup search_path so that these functions are created in appropriate schema.
update pg_settings set setting = 'rhn_org,' || setting where name = 'search_path';


create or replace function delete_user(user_id_in in numeric, deleting_org in numeric default 0) returns void 
    as
    $$
    declare
    servergroups_needing_admins cursor for
            select    usgp.server_group_id    server_group_id
            from    rhnUserServerGroupPerms    usgp
            where    1=1
                and usgp.user_id = user_id_in
                and not exists (
                    select    1
                    from    rhnUserServerGroupPerms    sq_usgp
                    where    1=1
                        and sq_usgp.server_group_id = usgp.server_group_id
                        and    sq_usgp.user_id != user_id_in
                );
        users            numeric;
        our_org_id        numeric;
        other_users        numeric;
        other_org_admin    numeric;
        other_user_id  numeric;
        is_admin       numeric;
    begin
        select    wc.org_id
        into    our_org_id
        from    web_contact wc
        where    id = user_id_in;

        -- find any other users
        begin
            select    id, 1
            into    other_user_id, other_users
            from    web_contact
            where    1=1
                and org_id = our_org_id
                and id != user_id_in
                limit 1;
        exception
            when no_data_found then
                other_users := 0;
        end;

        -- now do org admin stuff
        if other_users != 0 then
            -- is user admin?
            select  count(1)
             into   is_admin
            from    rhnUserGroupType    ugt,
                    rhnUserGroup        ug,
                    rhnUserGroupMembers    ugm
            where    ugm.user_id = user_id_in
                and ugm.user_group_id = ug.id
                and ug.group_type = ugt.id
                and ugt.label = 'org_admin';
            if is_admin > 0 then
                begin
                    select    new_ugm.user_id
                    into    other_org_admin
                    from    rhnUserGroupMembers    new_ugm,
                            rhnUserGroupType    ugt,
                            rhnUserGroup        ug,
                            rhnUserGroupMembers    ugm
                    where    ugm.user_id = user_id_in
                        and ugm.user_group_id = ug.id
                        and ug.group_type = ugt.id
                        and ugt.label = 'org_admin'
                        and ug.id = new_ugm.user_group_id
                        and new_ugm.user_id != user_id_in
                        limit 1;
                exception
                    when no_data_found then
                        -- If we're deleting the org, we don't want to raise
                        -- the exception.
                        if deleting_org = 0 then
                           perform rhn_exception.raise_exception('cannot_delete_user');
                        end if;
                end;

                for sg in servergroups_needing_admins loop
                   perform rhn_user.add_servergroup_perm(other_org_admin,
                        sg.server_group_id);
                end loop;
            end if;
        end if;

        -- and now things for every user
        delete from rhn_command_queue_sessions where contact_id = user_id_in;
        delete from rhn_contact_groups
        where recid in (
            select contact_group_id
            from rhn_contact_group_members
            where member_contact_method_id in (
                select recid from rhn_contact_methods
                where contact_id = user_id_in
                )
            )
            and not exists (
                select 1
                from rhn_contact_group_members, rhn_contact_methods
                where rhn_contact_groups.recid = rhn_contact_group_members.contact_group_id
                    and rhn_contact_group_members.member_contact_method_id = rhn_contact_methods.recid
                    and rhn_contact_methods.contact_id <> user_id_in
            );
        delete from rhn_contact_methods where contact_id = user_id_in;
        delete from rhn_redirects where contact_id = user_id_in;
        delete from rhnUserServerPerms where user_id = user_id_in;
        update rhnConfigRevision
           set changed_by_id = NULL
         where changed_by_id = user_id_in;
        if other_users != 0 then
            update        rhnRegToken
                set        user_id = coalesce(other_org_admin, other_user_id)
                where    org_id = our_org_id
                    and user_id = user_id_in;
        end if;

        begin
            delete from web_contact where id = user_id_in;
        exception
            when others then
               perform rhn_exception.raise_exception('cannot_delete_user');
        end;
        return;

        end;
        $$
        language plpgsql;


-- restore the original setting
update pg_settings set setting = overlay( setting placing '' from 1 for (length('rhn_org')+1) ) where name = 'search_path';
 070701000006F7000081B400000000000000000000000167AE11140000004D000000000000000000000000000000000000006A00000000susemanager-schema/upgrade/spacewalk-schema-1.6-to-spacewalk-schema-1.7/063-rhnAppInstallSession-drop.sql 
drop table rhnAppInstallSession;
drop sequence rhn_appinst_session_id_seq;

   070701000006F8000081B400000000000000000000000167AE111400000034000000000000000000000000000000000000007600000000susemanager-schema/upgrade/spacewalk-schema-1.6-to-spacewalk-schema-1.7/064-rhn_appinst_session_mod_trig_fun-drop.sql 
drop function rhn_appinst_session_mod_trig_fun();

070701000006F9000081B400000000000000000000000167AE11140000004F000000000000000000000000000000000000006B00000000susemanager-schema/upgrade/spacewalk-schema-1.6-to-spacewalk-schema-1.7/065-rhnAppInstallInstance-drop.sql    
drop table rhnAppInstallInstance;
drop sequence rhn_appinst_instance_id_seq;

 070701000006FA000081B400000000000000000000000167AE111400000034000000000000000000000000000000000000007600000000susemanager-schema/upgrade/spacewalk-schema-1.6-to-spacewalk-schema-1.7/066-rhn_appinst_istance_mod_trig_fun-drop.sql 
drop function rhn_appinst_istance_mod_trig_fun();

070701000006FB000081B400000000000000000000000167AE111400000625000000000000000000000000000000000000006900000000susemanager-schema/upgrade/spacewalk-schema-1.6-to-spacewalk-schema-1.7/067-rhnChannelCloned-trigger.sql  --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--

create or replace function rhn_channel_cloned_comps_trig_fun() returns trigger
as
$$
begin
	new.modified := current_timestamp;

	if tg_op = 'INSERT' then
		-- if there are not comps in the cloned channel by now,
		-- we shall clone comps from the original channel
		insert into rhnChannelComps
			( id, channel_id, relative_filename,
				last_modified, created, modified )
		select nextval('rhn_channelcomps_id_seq'), new.id, relative_filename,
				current_timestamp, current_timestamp, current_timestamp
		from rhnChannelComps
		where channel_id = new.original_id
			and not exists (
				select 1
				from rhnChannelComps x
				where x.channel_id = new.id
			);
	end if;
        return new;
end;
$$
language plpgsql;


drop trigger rhn_channel_cloned_comps_trig on rhnChannelCloned;;

create trigger
rhn_channel_cloned_comps_trig
before insert or update on rhnChannelCloned
for each row
execute procedure rhn_channel_cloned_comps_trig_fun();
   070701000006FC000081B400000000000000000000000167AE111400000374000000000000000000000000000000000000006A00000000susemanager-schema/upgrade/spacewalk-schema-1.6-to-spacewalk-schema-1.7/068-rhnChannelPackage-trigger.sql --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
-- triggers for rhnChannelPackage

drop trigger rhn_channel_package_mod_trig on rhnChannelCloned;

create trigger
rhn_channel_package_mod_trig
before insert or update on rhnChannelPackage
for each row
execute procedure rhn_channel_package_mod_trig_fun();
070701000006FD000081B400000000000000000000000167AE1114000000D1000000000000000000000000000000000000007300000000susemanager-schema/upgrade/spacewalk-schema-1.6-to-spacewalk-schema-1.7/069-rhnErrataNotificationQueue-trigger.sql    
drop trigger rhn_enqueue_mod_trig on rhnErrataKeywordTmp;

create trigger
rhn_enqueue_mod_trig
before insert or update on rhnErrataNotificationQueue
for each row
execute procedure rhn_enqueue_mod_trig_fun();
   070701000006FE000081B400000000000000000000000167AE1114000000D1000000000000000000000000000000000000006A00000000susemanager-schema/upgrade/spacewalk-schema-1.6-to-spacewalk-schema-1.7/070-rhnConfigFileType-trigger.sql 
drop trigger rhn_conffiletype_mod_trig on rhnConfigFile;

create trigger
rhn_conffiletype_mod_trig
before insert or update on rhnConfigFileType
for each row
execute procedure rhn_conffiletype_mod_trig_fun();
   070701000006FF000081B400000000000000000000000167AE11140000016C000000000000000000000000000000000000006B00000000susemanager-schema/upgrade/spacewalk-schema-1.6-to-spacewalk-schema-1.7/071-rhnKickstartScript-trigger.sql    
create or replace function rhn_ksscript_mod_trig_fun() returns trigger as
$$
begin
	new.modified := current_timestamp;
	return new;
end;
$$ language plpgsql;

drop trigger rhn_ksscript_mod_trig on rhnKickstartSession;

create trigger
rhn_ksscript_mod_trig
before insert or update on rhnKickstartScript
for each row
execute procedure rhn_ksscript_mod_trig_fun();

07070100000700000081B400000000000000000000000167AE1114000002B0000000000000000000000000000000000000006C00000000susemanager-schema/upgrade/spacewalk-schema-1.6-to-spacewalk-schema-1.7/073-clean-current-alerts-delete.sql   
delete from rhnTaskoRun
where template_id in (
	select id from rhnTaskoTemplate
	where task_id in (
		select id from rhnTaskoTask
		where class = 'com.redhat.rhn.taskomatic.task.CleanCurrentAlerts'
	)
);

delete from rhnTaskoTemplate
where task_id in (
	select id from rhnTaskoTask
	where class = 'com.redhat.rhn.taskomatic.task.CleanCurrentAlerts'
);

delete from rhnTaskoTask
where class = 'com.redhat.rhn.taskomatic.task.CleanCurrentAlerts';

delete from rhnTaskoSchedule
where bunch_id in (
	select id from rhnTaskoBunch
	where id not in (
		select bunch_id from rhnTaskoTemplate
	)
);

delete from rhnTaskoBunch
where id not in (
	select bunch_id from rhnTaskoTemplate
);

commit;

07070100000701000081B400000000000000000000000167AE11140000004D000000000000000000000000000000000000006800000000susemanager-schema/upgrade/spacewalk-schema-1.6-to-spacewalk-schema-1.7/074-rhn_current_alerts-drop.sql   
drop table rhn_current_alerts;
drop sequence rhn_current_alerts_recid_seq;

   07070100000702000081B400000000000000000000000167AE1114000003A6000000000000000000000000000000000000006800000000susemanager-schema/upgrade/spacewalk-schema-1.6-to-spacewalk-schema-1.7/075-rhnChecksumType-trigger.sql   --
-- Copyright (c) 2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

create or replace function rhn_checksumtype_mod_trig_fun() returns trigger as
$$
begin
	new.modified := current_timestamp;
	return new;
end;
$$ language plpgsql;

create trigger
rhn_checksumtype_mod_trig
before insert or update on rhnChecksumType
for each row
execute procedure rhn_checksumtype_mod_trig_fun();

  07070100000703000081B400000000000000000000000167AE111400000413000000000000000000000000000000000000005F00000000susemanager-schema/upgrade/spacewalk-schema-1.6-to-spacewalk-schema-1.7/076-pg_dblink_exec.sql    -- oracle equivalent source none
--
-- Copyright (c) 2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.

create or replace function pg_dblink_exec(in_sql in varchar) returns void as
$$
begin
    perform dblink_connect('at_conn', 'dbname=' || current_database());
    begin
        perform dblink_exec('at_conn', in_sql, true);
    exception when others then
        perform dblink_disconnect('at_conn');
        raise;
    end;
    perform dblink_disconnect('at_conn');
end;
$$
language plpgsql;
 07070100000704000081B400000000000000000000000167AE1114000006FC000000000000000000000000000000000000006000000000susemanager-schema/upgrade/spacewalk-schema-1.6-to-spacewalk-schema-1.7/077-lookup-checksum.sql   --
-- Copyright (c) 2010 - 2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

create or replace function
lookup_checksum(checksum_type_in in varchar, checksum_in in varchar)
returns numeric
as
$$
declare
    checksum_id     numeric;
begin
    if checksum_in is null then
        return null;
    end if;

    select c.id
      into checksum_id
      from rhnChecksumView c
     where c.checksum = checksum_in and
           c.checksum_type = checksum_type_in;

    if not found then
        checksum_id := nextval('rhnchecksum_seq');
        begin
            perform pg_dblink_exec(
                'insert into rhnChecksum (id, checksum_type_id, checksum) values (' ||
                checksum_id || ', (select id from rhnChecksumType where label = ' ||
                coalesce(quote_literal(checksum_type_in), 'NULL') || '), ' ||
                coalesce(quote_literal(checksum_in), 'NULL') || ')');
        exception when unique_violation then
            select c.id
              into strict checksum_id
              from rhnChecksumView c
             where c.checksum = checksum_in and
                   c.checksum_type = checksum_type_in;
        end;
    end if;

    return checksum_id;
end;
$$
language plpgsql immutable;
07070100000705000081B400000000000000000000000167AE1114000005A5000000000000000000000000000000000000006900000000susemanager-schema/upgrade/spacewalk-schema-1.6-to-spacewalk-schema-1.7/078-lookup_client_capability.sql  --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.

create or replace function
lookup_client_capability(name_in in varchar)
returns numeric
as $$
declare
    cap_name_id     numeric;
begin
    select id
      into cap_name_id
      from rhnclientcapabilityname
     where name = name_in;

    if not found then
        cap_name_id := nextval('rhn_client_capname_id_seq');
        begin
            perform pg_dblink_exec(
                'insert into rhnClientCapabilityName(id, name) values (' ||
                cap_name_id  || ' ,' ||
                coalesce(quote_literal(name_in), 'NULL') || ')');
        exception when unique_violation then
            select id
              into strict cap_name_id
              from rhnclientcapabilityname
            where name = name_in;
        end;
    end if;

    return cap_name_id;
end;
$$ language plpgsql immutable;
   07070100000706000081B400000000000000000000000167AE111400000568000000000000000000000000000000000000006700000000susemanager-schema/upgrade/spacewalk-schema-1.6-to-spacewalk-schema-1.7/079-lookup_config_filename.sql    --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.

create or replace function
lookup_config_filename(name_in in varchar)
returns numeric as
$$
declare
    name_id     numeric;
begin
    select id
      into name_id
      from rhnconfigfilename
     where path = name_in;

    if not found then
        name_id := nextval('rhn_cfname_id_seq');
        begin
            perform pg_dblink_exec(
                'insert into rhnConfigFileName (id, path) values (' ||
                name_id || ', ' ||
                coalesce(quote_literal(name_in), 'NULL') || ')');
        exception when unique_violation then
            select id
              into strict name_id
              from rhnconfigfilename
             where path = name_in;
        end;
    end if;

    return name_id;
end; $$
language plpgsql;
07070100000707000081B400000000000000000000000167AE111400000064000000000000000000000000000000000000006300000000susemanager-schema/upgrade/spacewalk-schema-1.6-to-spacewalk-schema-1.7/080-rhnActionType_data.sql    
insert into rhnActionType
    values (50, 'scap.xccdf_eval', 'OpenSCAP xccdf scanning', 'N', 'Y');
07070100000708000081B400000000000000000000000167AE11140000027C000000000000000000000000000000000000005E00000000susemanager-schema/upgrade/spacewalk-schema-1.6-to-spacewalk-schema-1.7/081-rhnActionScap.sql 
CREATE TABLE rhnActionScap
(
    id               NUMERIC NOT NULL
                         CONSTRAINT rhn_act_scap_id_pk PRIMARY KEY
                         ,
    action_id        NUMERIC NOT NULL
                         CONSTRAINT rhn_act_scap_act_fk
                             REFERENCES rhnAction (id)
                             ON DELETE CASCADE,
    path             VARCHAR(2048) NOT NULL,
    parameters       BYTEA
)


;

CREATE UNIQUE INDEX rhn_act_scap_aid_idx
    ON rhnActionScap (action_id)
    
    ;

CREATE INDEX rhn_act_scap_path_idx
    ON rhnActionScap (path)
    
    ;

CREATE SEQUENCE rhn_act_scap_id_seq;
07070100000709000081B400000000000000000000000167AE11140000018F000000000000000000000000000000000000006200000000susemanager-schema/upgrade/spacewalk-schema-1.6-to-spacewalk-schema-1.7/082-rhnXccdfBenchmark.sql 
CREATE TABLE rhnXccdfBenchmark
(
    id            NUMERIC NOT NULL
                      CONSTRAINT rhn_xccdf_benchmark_id_pk PRIMARY KEY
                      ,
    identifier    VARCHAR(120) NOT NULL,
    version       VARCHAR(80) NOT NULL
)

;

CREATE UNIQUE INDEX rhn_xccdf_benchmark_iv_uq
    ON rhnXccdfBenchmark (identifier, version)
    
    ;

CREATE SEQUENCE rhn_xccdf_benchmark_id_seq;
 0707010000070A000081B400000000000000000000000167AE111400000184000000000000000000000000000000000000006000000000susemanager-schema/upgrade/spacewalk-schema-1.6-to-spacewalk-schema-1.7/083-rhnXccdfProfile.sql   
CREATE TABLE rhnXccdfProfile
(
    id            NUMERIC NOT NULL
                      CONSTRAINT rhn_xccdf_profile_id_pk PRIMARY KEY
                      ,
    identifier    VARCHAR(120) NOT NULL,
    title         VARCHAR(120) NOT NULL
)

;

CREATE UNIQUE INDEX rhn_xccdf_profile_it_uq
    ON rhnXccdfProfile (identifier, title)
    
    ;

CREATE SEQUENCE rhn_xccdf_profile_id_seq;
0707010000070B000081B400000000000000000000000167AE111400000149000000000000000000000000000000000000006400000000susemanager-schema/upgrade/spacewalk-schema-1.6-to-spacewalk-schema-1.7/084-rhnXccdfIdentsystem.sql   
CREATE TABLE rhnXccdfIdentsystem
(
    id      NUMERIC NOT NULL
                CONSTRAINT rhn_xccdf_identsytem_id_pk PRIMARY KEY
                ,
    system  VARCHAR(80) NOT NULL
)

;

CREATE UNIQUE INDEX rhn_xccdf_identsystem_id_uq
    ON rhnXccdfIdentsystem (system)
    
    ;

CREATE SEQUENCE rhn_xccdf_identsytem_id_seq;
   0707010000070C000081B400000000000000000000000167AE111400000206000000000000000000000000000000000000005E00000000susemanager-schema/upgrade/spacewalk-schema-1.6-to-spacewalk-schema-1.7/085-rhnXccdfIdent.sql 
CREATE TABLE rhnXccdfIdent
(
    id              NUMERIC NOT NULL
                        CONSTRAINT rhn_xccdf_ident_id_pk PRIMARY KEY
                        ,
    identsystem_id  NUMERIC NOT NULL
                        CONSTRAINT rhn_xccdf_ident_system_fk
                            REFERENCES rhnXccdfIdentsystem (id),
    identifier      VARCHAR (20) NOT NULL
)

;

CREATE UNIQUE INDEX rhn_xccdf_ident_isi_uq
    ON rhnXccdfIdent (identsystem_id, identifier)
    
    ;

CREATE SEQUENCE rhn_xccdf_ident_id_seq;
  0707010000070D000081B400000000000000000000000167AE111400000498000000000000000000000000000000000000006300000000susemanager-schema/upgrade/spacewalk-schema-1.6-to-spacewalk-schema-1.7/086-rhnXccdfTestresult.sql    
CREATE TABLE rhnXccdfTestresult
(
    id             NUMERIC NOT NULL
                       CONSTRAINT rhn_xccdf_tresult_id_pk PRIMARY KEY
                       ,
    server_id      NUMERIC NOT NULL
                       CONSTRAINT rhn_xccdf_tresult_srvr_fk
                           REFERENCES rhnServer (id)
                           ON DELETE CASCADE,
    action_scap_id NUMERIC NOT NULL
                       CONSTRAINT rhn_xccdf_tresult_act_fk
                           REFERENCES rhnActionScap (id)
                           ON DELETE CASCADE,
    benchmark_id   NUMERIC NOT NULL
                       CONSTRAINT rhn_xccdf_tresult_bench_fk
                           REFERENCES rhnXccdfBenchmark (id),
    profile_id     NUMERIC NOT NULL
                       CONSTRAINT rhn_xccdf_tresult_profile_fk
                           REFERENCES rhnXccdfProfile (id),
    identifier     VARCHAR(120) NOT NULL,
    start_time     TIMESTAMPTZ,
    end_time       TIMESTAMPTZ NOT NULL,
    errors         BYTEA
)


;

CREATE UNIQUE INDEX rhn_xccdf_tresult_sa_uq
    ON rhnXccdfTestresult (server_id, action_scap_id)
    
    ;

CREATE SEQUENCE rhn_xccdf_tresult_id_seq;
0707010000070E000081B400000000000000000000000167AE111400000185000000000000000000000000000000000000006700000000susemanager-schema/upgrade/spacewalk-schema-1.6-to-spacewalk-schema-1.7/087-rhnXccdfRuleresultType.sql    
CREATE TABLE rhnXccdfRuleresultType
(
    id            NUMERIC NOT NULL
                      CONSTRAINT rhn_xccdf_rresult_t_id_pk PRIMARY KEY
                      ,
    abbreviation  CHAR(1) NOT NULL,
    label         VARCHAR(16) NOT NULL,
    description   VARCHAR(120) NOT NULL
)

;

CREATE UNIQUE INDEX rhn_xccdf_rresult_t_label_uq
    ON rhnXccdfRuleresultType (label)
    
    ;
   0707010000070F000081B400000000000000000000000167AE1114000004FB000000000000000000000000000000000000006C00000000susemanager-schema/upgrade/spacewalk-schema-1.6-to-spacewalk-schema-1.7/088-rhnXccdfRuleresultType_data.sql   
insert into rhnXccdfRuleresultType values (1, 'P', 'pass',
    'The target system satisfied all the conditions of the xccdf:Rule.');
insert into rhnXccdfRuleresultType values (2, 'F', 'fail',
    'The target system did not satisfy all the conditions of the xccdf:Rule');
insert into rhnXccdfRuleresultType values (3, 'E', 'error',
    'The checking engine could not complete the evaluation, therefore the status of compliance is uncertain.');
insert into rhnXccdfRuleresultType values (4, 'U', 'unknown',
    'The testing tool encountered some problem and the result is unknown.');
insert into rhnXccdfRuleresultType values (5, 'N', 'notapplicable',
    'The xccdf:Rule was not applicable to the target.');
insert into rhnXccdfRuleresultType values (6, 'K', 'notchecked',
    'The xccdf:Rule was not evaluated by the checking engine; xccdf:check was either unspecified or unsupported.');
insert into rhnXccdfRuleresultType values (7, 'S', 'notselected',
    'The xccdf:Rule was not selected in the profile.');
insert into rhnXccdfRuleresultType values (8, 'I', 'informational',
    'The xccdf:Rule was not checked; it is not a compliance category.');
insert into rhnXccdfRuleresultType values (9, 'X', 'fixed',
    'The xccdf:Rule had failed, but was then fixed by tool.');
 07070100000710000081B400000000000000000000000167AE111400000299000000000000000000000000000000000000006300000000susemanager-schema/upgrade/spacewalk-schema-1.6-to-spacewalk-schema-1.7/089-rhnXccdfRuleresult.sql    
CREATE TABLE rhnXccdfRuleresult
(
    testresult_id NUMERIC NOT NULL
                      CONSTRAINT rhn_xccdf_rresult_tresult_fk
                          REFERENCES rhnXccdfTestresult (id)
                          ON DELETE CASCADE,
    ident_id      NUMERIC NOT NULL
                      CONSTRAINT rhn_xccdf_rresult_ident_fk
                          REFERENCES rhnXccdfIdent (id),
    result_id     NUMERIC NOT NULL
                      CONSTRAINT rhn_xccdf_rresult_result_fk
                          REFERENCES rhnXccdfRuleresultType (id)
)

;

CREATE UNIQUE INDEX rhn_xccdf_rresult_tri_uq
    ON rhnXccdfRuleresult (testresult_id, ident_id)
    
    ;
   07070100000711000081B400000000000000000000000167AE111400000261000000000000000000000000000000000000006700000000susemanager-schema/upgrade/spacewalk-schema-1.6-to-spacewalk-schema-1.7/090-lookup_xccdf_benchmark.sql    
CREATE OR REPLACE FUNCTION
lookup_xccdf_benchmark(identifier_in IN VARCHAR, version_in IN VARCHAR)
RETURNS NUMERIC
AS
$$
DECLARE
    benchmark_id NUMERIC;
BEGIN
    SELECT id
        INTO benchmark_id
        FROM rhnXccdfBenchmark
        WHERE identifier = identifier_in
            AND version = version_in;

    IF NOT FOUND THEN
        INSERT INTO rhnXccdfBenchmark (id, identifier, version)
            VALUES (nextval('rhn_xccdf_benchmark_id_seq'),
                identifier_in, version_in)
            RETURNING id INTO benchmark_id;
    END IF;

    RETURN benchmark_id;
END;
$$ LANGUAGE PLPGSQL;
   07070100000712000081B400000000000000000000000167AE111400000247000000000000000000000000000000000000006500000000susemanager-schema/upgrade/spacewalk-schema-1.6-to-spacewalk-schema-1.7/091-lookup_xccdf_profile.sql  
CREATE OR REPLACE FUNCTION
lookup_xccdf_profile(identifier_in IN VARCHAR, title_in IN VARCHAR)
RETURNS NUMERIC
AS
$$
DECLARE
    profile_id NUMERIC;
BEGIN
    SELECT id
        INTO profile_id
        FROM rhnXccdfProfile
        WHERE identifier = identifier_in
            AND title = title_in;

    IF NOT FOUND THEN
        INSERT INTO rhnXccdfProfile (id, identifier, title)
            VALUES (nextval('rhn_xccdf_profile_id_seq'),
                identifier_in, title_in)
            RETURNING id INTO profile_id;
    END IF;

    RETURN profile_id;
END;
$$ LANGUAGE PLPGSQL;
 07070100000713000081B400000000000000000000000167AE1114000003A8000000000000000000000000000000000000006300000000susemanager-schema/upgrade/spacewalk-schema-1.6-to-spacewalk-schema-1.7/092-lookup_xccdf_ident.sql    
CREATE OR REPLACE FUNCTION
lookup_xccdf_ident(system_in IN VARCHAR, identifier_in IN VARCHAR)
RETURNS NUMERIC
AS
$$
DECLARE
    xccdf_ident_id NUMERIC;
    ident_sys_id NUMERIC;
BEGIN
    SELECT id
        INTO ident_sys_id
        FROM rhnXccdfIdentsystem
        WHERE system = system_in;
    IF NOT FOUND THEN
        INSERT INTO rhnXccdfIdentsystem (id, system)
            VALUES (nextval('rhn_xccdf_identsytem_id_seq'), system_in)
            RETURNING id INTO ident_sys_id;
    END IF;

    SELECT id
        INTO xccdf_ident_id
        FROM rhnXccdfIdent
        WHERE identsystem_id = ident_sys_id
            AND identifier = identifier_in;
    IF NOT FOUND THEN
        INSERT INTO rhnXccdfIdent (id, identsystem_id, identifier)
            VALUES (nextval('rhn_xccdf_ident_id_seq'), ident_sys_id, identifier_in)
            RETURNING id INTO xccdf_ident_id;
    END IF;
    RETURN xccdf_ident_id;
END;
$$ LANGUAGE PLPGSQL;
07070100000714000081B400000000000000000000000167AE111400000991000000000000000000000000000000000000006300000000susemanager-schema/upgrade/spacewalk-schema-1.6-to-spacewalk-schema-1.7/093-lookup_config_info.sql    --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

create or replace function
lookup_config_info
(
    username_in     in varchar,
    groupname_in    in varchar,
    filemode_in     in numeric,
    selinux_ctx_in  in varchar,
    symlink_target_id in numeric
)
returns numeric
as
$$
declare
    r numeric;
    v_id    numeric;
    lookup_cursor cursor  for
        select id
          from rhnConfigInfo
         where 1=1
           and (username = username_in or (username is null and username_in is null))
           and (groupname = groupname_in or (groupname is null and groupname_in is null))
           and (filemode = filemode_in or (filemode is null and filemode_in is null))
           and (selinux_ctx = selinux_ctx_in or
               (selinux_ctx is null and selinux_ctx_in is null))
           and (symlink_target_filename_id = symlink_target_id or
               (symlink_target_filename_id is null and symlink_target_id is null))
        ;
begin
    for r in lookup_cursor loop
        return r.id;
    end loop;
    -- If we got here, we don't have the id
    v_id := nextval('rhn_confinfo_id_seq');
    begin
        perform pg_dblink_exec(
            'insert into rhnConfigInfo ' ||
            '(id, username, groupname, filemode, selinux_ctx, symlink_target_filename_id)' ||
            'values (' || v_id || ', ' ||
            coalesce(quote_literal(username_in), 'NULL') || ', ' ||
            coalesce(quote_literal(groupname_in), 'NULL') || ', ' ||
            coalesce(quote_literal( filemode_in), 'NULL') || ', ' ||
            coalesce(quote_literal(selinux_ctx_in), 'NULL') || ', ' ||
            coalesce(quote_literal(symlink_target_id), 'NULL') || ')');
    exception when unique_violation then
        for r in lookup_cursor loop
            return r.id;
        end loop;
    end;
    return v_id;
end;
$$ language plpgsql immutable;
   07070100000715000081B400000000000000000000000167AE111400000532000000000000000000000000000000000000005B00000000susemanager-schema/upgrade/spacewalk-schema-1.6-to-spacewalk-schema-1.7/094-lookup_cve.sql    --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.

create or replace function
lookup_cve(name_in in varchar)
returns numeric
as $$
declare
    name_id     numeric;
begin
    select id
      into name_id
      from rhnCVE
     where name = name_in;

    if not found then
        name_id := nextval('rhn_cve_id_seq');
        begin
            perform pg_dblink_exec(
                'insert into rhnCVE (id, name) values (' || name_id || ', ' ||
                coalesce(quote_literal(name_in), 'NULL') || ')');
        exception when unique_violation then
            select id
              into strict name_id
              from rhnCVE
             where name = name_in;
        end;
    end if;

    return name_id;
end; $$ language plpgsql immutable;
  07070100000716000081B400000000000000000000000167AE1114000007A7000000000000000000000000000000000000005B00000000susemanager-schema/upgrade/spacewalk-schema-1.6-to-spacewalk-schema-1.7/096-lookup_evr.sql    --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.

create or replace function
lookup_evr(e_in in varchar, v_in in varchar, r_in in varchar)
returns numeric
as
$$
declare
    evr_id  numeric;
begin
    select id
      into evr_id
      from rhnPackageEVR
     where ((epoch is null and e_in is null) or (epoch = e_in)) and
           version = v_in and
           release = r_in;

    if not found then
        evr_id := nextval('rhn_pkg_evr_seq');
        begin
            perform pg_dblink_exec(
                'insert into rhnPackageEVR(id, epoch, version, release, evr) values (' ||
                evr_id || ', ' ||
                coalesce(quote_literal(e_in), 'NULL') || ', ' ||
                coalesce(quote_literal(v_in), 'NULL') || ', ' ||
                coalesce(quote_literal(r_in), 'NULL') || ', ' ||
                evr_t(coalesce(quote_literal(e_in), 'NULL'),
                      coalesce(quote_literal(v_in), 'NULL'),
                      coalesce(quote_literal(r_in), 'NULL')) || ')'
            );
        exception when unique_violation then
            select id
              into strict evr_id
              from rhnPackageEVR
             where ((epoch is null and e_in is null) or (epoch = e_in)) and
                   version = v_in and
                   release = r_in;
        end;
    end if;

    return evr_id;
end;
$$ language plpgsql immutable;
 07070100000717000081B400000000000000000000000167AE111400000839000000000000000000000000000000000000006A00000000susemanager-schema/upgrade/spacewalk-schema-1.6-to-spacewalk-schema-1.7/097-lookup_package_capability.sql --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.

create or replace function lookup_package_capability(name_in in varchar, version_in in varchar default null)
returns numeric
as
$$
declare
    name_id numeric;
begin
    if version_in is null then
        select id
          into name_id
          from rhnpackagecapability
         where name = name_in and
               version is null;
    else
        select id
          into name_id
          from rhnpackagecapability
         where name = name_in and
               version = version_in;
    end if;

    if not found then
        name_id = nextval('rhn_pkg_capability_id_seq');
        begin
            perform pg_dblink_exec(
                'insert into rhnPackageCapability(id, name, version) values (' ||
                name_id || ', ' ||
                coalesce(quote_literal(name_in), 'NULL') || ', ' ||
                coalesce(quote_literal(version_in), 'NULL') || ')');
        exception when unique_violation then
            if version_in is null then
                select id
                  into strict name_id
                  from rhnpackagecapability
                 where name = name_in and
                       version is null;
            else
                select id
                  into strict name_id
                  from rhnpackagecapability
                 where name = name_in and
                       version = version_in;
            end if;
        end;
    end if;

    return name_id;
end;
$$
language plpgsql immutable;
   07070100000718000081B400000000000000000000000167AE111400000555000000000000000000000000000000000000006500000000susemanager-schema/upgrade/spacewalk-schema-1.6-to-spacewalk-schema-1.7/098-lookup_package_delta.sql  --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.

create or replace function lookup_package_delta(n_in in varchar)
returns numeric
as
$$
declare
    name_id     numeric;
begin
    select id
      into name_id
      from rhnPackageDelta
     where label = n_in;

    if not found then
        name_id := nextval('rhn_packagedelta_id_seq');
        begin
            perform pg_dblink_exec(
                'insert into rhnPackageDelta(id, label) values (' ||
                name_id || ', ' || coalesce(quote_literal(n_in), 'NULL'), ')' );
        exception when unique_violation then
            select id
              into strict name_id
              from rhnpackagedelta
             where label = n_in;
        end;
    end if;

    return name_id;
end;
$$ language plpgsql immutable;
   07070100000719000081B400000000000000000000000167AE1114000005CA000000000000000000000000000000000000006400000000susemanager-schema/upgrade/spacewalk-schema-1.6-to-spacewalk-schema-1.7/099-lookup_package_name.sql   --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 

create or replace function
lookup_package_name(name_in in varchar, ignore_null in numeric default 0)
returns numeric
as
$$
declare
    name_id     numeric;
begin
    if ignore_null = 1 and name_in is null then
        return null;
    end if;

    select id
      into name_id
      from rhnPackageName
     where name = name_in;

    if not found then
        name_id := nextval('rhn_pkg_name_seq');
        begin
            perform pg_dblink_exec(
                'insert into rhnPackageName(id, name) values (' || name_id || ', ' ||
                coalesce(quote_literal(name_in), 'NULL') || ')');
        exception when unique_violation then
            select id
              into strict name_id
              from rhnPackageName
             where name = name_in;
        end;
    end if;

    return name_id;
end;
$$ language plpgsql immutable;
  0707010000071A000081B400000000000000000000000167AE11140000063C000000000000000000000000000000000000006500000000susemanager-schema/upgrade/spacewalk-schema-1.6-to-spacewalk-schema-1.7/100-lookup_package_nevra.sql  
create or replace function
lookup_package_nevra(
        name_id_in in numeric,
        evr_id_in in numeric,
        package_arch_id_in in numeric,
        ignore_null_name in numeric default 0
) returns numeric
as
$$
declare
    nevra_id numeric;
begin
    if ignore_null_name = 1 and name_id_in is null then
        return null;
    end if;

    select id
      into nevra_id
      from rhnPackageNEVRA
     where name_id = name_id_in and
           evr_id = evr_id_in and
           (package_arch_id = package_arch_id_in or
            (package_arch_id is null and package_arch_id_in is null));

    if not found then
        nevra_id := nextval('rhn_pkgnevra_id_seq');
        begin
            perform pg_dblink_exec(
                'insert into rhnPackageNEVRA(id, name_id, evr_id, package_arch_id) values (' ||
                    nevra_id || ', ' ||
                    coalesce(quote_literal(name_id_in), 'NULL') || ', ' ||
                    coalesce(quote_literal(evr_id_in), 'NULL') || ', ' ||
                    coalesce(quote_literal(package_arch_id_in), 'NULL') || ')');
                nevra_id := currval('rhn_pkgnevra_id_seq');
        exception when unique_violation then
            select id
              into strict nevra_id
              from rhnPackageNEVRA
             where name_id = name_id_in and
                   evr_id = evr_id_in and
                   (package_arch_id = package_arch_id_in or
                    (package_arch_id is null and package_arch_id_in is null));
        end;
    end if;

    return nevra_id;
end;
$$ language plpgsql immutable;
0707010000071B000081B400000000000000000000000167AE1114000002EB000000000000000000000000000000000000006300000000susemanager-schema/upgrade/spacewalk-schema-1.6-to-spacewalk-schema-1.7/102-lookup_source_name.sql    
create or replace function
lookup_source_name(name_in in varchar)
returns numeric
as
$$
declare
    source_id   numeric;
begin
    select id
      into source_id
      from rhnSourceRPM
     where name = name_in;

    if not found then
        source_id := nextval('rhn_sourcerpm_id_seq');
        begin
            perform pg_dblink_exec(
                'insert into rhnSourceRPM(id, name) values (' ||
                source_id || ', ' || coalesce(quote_literal(name_in), 'NULL') || ')');
        exception when unique_violation then
            select id
              into strict source_id
              from rhnSourceRPM
             where name = name_in;
        end;
    end if;

    return source_id;
end;
$$
language plpgsql immutable;
 0707010000071C000081B400000000000000000000000167AE1114000005F5000000000000000000000000000000000000005B00000000susemanager-schema/upgrade/spacewalk-schema-1.6-to-spacewalk-schema-1.7/103-lookup_tag.sql    --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 

create or replace function
lookup_tag(org_id_in in numeric, name_in in varchar)
returns numeric
as $$
declare
    tag_id  numeric;
begin
    select id
      into tag_id
      from rhnTag
     where org_id = org_id_in and
           name_id = lookup_tag_name(name_in);

    if not found then
        tag_id := nextval('rhn_tag_id_seq');
        begin
            perform pg_dblink_exec(
                'insert into rhnTag(id, org_id, name_id) values (' ||
                tag_id || ', ' || org_id_in || ', ' ||
                coalesce(quote_literal(lookup_tag_name(name_in), 'NULL')) || ')');
        exception when unique_violation then
            select id
              into strict tag_id
              from rhnTag
             where org_id = org_id_in and
                   name_id = lookup_tag_name(name_in);
        end;
    end if;

    return tag_id;
end; $$
language plpgsql immutable;
   0707010000071D000081B400000000000000000000000167AE1114000002D2000000000000000000000000000000000000006000000000susemanager-schema/upgrade/spacewalk-schema-1.6-to-spacewalk-schema-1.7/104-lookup_tag_name.sql   
create or replace function
lookup_tag_name(name_in in varchar)
returns numeric
as
$$
declare
    name_id numeric;
begin
    select id
      into name_id
      from rhnTagName
     where name = name_in;

    if not found then
        name_id := nextval('rhn_tagname_id_seq');
        begin
            perform pg_dblink_exec(
                'insert into rhnTagName(id, name) values (' ||
                name_id || ', ' || coalesce(quote_literal(name_in), 'NULL') || ')');
        exception when unique_violation then
            select id
              into strict name_id
              from rhnTagName
             where name = name_in;
        end;
    end if;

    return name_id;
end;
$$ language plpgsql immutable;
  0707010000071E000081B400000000000000000000000167AE111400000704000000000000000000000000000000000000006B00000000susemanager-schema/upgrade/spacewalk-schema-1.6-to-spacewalk-schema-1.7/105-lookup_transaction_package.sql    
create or replace function
lookup_transaction_package(
    o_in in varchar,
    n_in in varchar,
    e_in in varchar,
    v_in in varchar,
    r_in in varchar,
    a_in in varchar)
returns numeric
as
$$
declare
    o_id        numeric;
    n_id        numeric;
    e_id        numeric;
    p_arch_id   numeric;
    tp_id       numeric;
begin
    select id
      into o_id
      from rhnTransactionOperation
     where label = o_in;

    if not found then
        perform rhn_exception.raise_exception('invalid_transaction_operation');
    end if;

    n_id := lookup_package_name(n_in);
    e_id := lookup_evr(e_in, v_in, r_in);
    p_arch_id := null;

    if a_in is not null then
        p_arch_id := lookup_package_arch(a_in);
    end if;

    select id
      into tp_id
      from rhnTransactionPackage
     where operation = o_id and
           name_id = n_id and
           evr_id = e_id and
           (package_arch_id = p_arch_id or (p_arch_id is null and package_arch_id is null));

    if not found then
        tp_id := nextval('rhn_transpack_id_seq');
        begin
            perform pg_dblink_exec(
                'insert into rhnTransactionPackage (id, operation, name_id, evr_id, package_arch_id)' ||
                ' values (' || tp_id || ', ' || o_id || ', ' || n_id || ', ' || e_id ||
                ', ' || ', ' || p_arch_id  || ')');
        exception when unique_violation then
            select id
              into strict tp_id
              from rhnTransactionPackage
             where operation = o_id and
                   name_id = n_id and
                   evr_id = e_id and
                   (package_arch_id = p_arch_id or (p_arch_id is null and package_arch_id is null));
        end;
    end if;

    return tp_id;
end;
$$
language plpgsql immutable;
0707010000071F000081B400000000000000000000000167AE1114000000B0000000000000000000000000000000000000006600000000susemanager-schema/upgrade/spacewalk-schema-1.6-to-spacewalk-schema-1.7/105-rhnUserGroupType_data.sql DELETE FROM rhnUserGroupType WHERE label = 'coma_admin';
DELETE FROM rhnUserGroupType WHERE label = 'coma_author';
DELETE FROM rhnUserGroupType WHERE label = 'coma_publisher';
07070100000720000081B400000000000000000000000167AE1114000003E8000000000000000000000000000000000000006700000000susemanager-schema/upgrade/spacewalk-schema-1.6-to-spacewalk-schema-1.7/106-lookup_xccdf_benchmark.sql    
create or replace function
lookup_xccdf_benchmark(identifier_in in varchar, version_in in varchar)
returns numeric
as
$$
declare
    benchmark_id numeric;
begin
    select id
      into benchmark_id
      from rhnXccdfBenchmark
     where identifier = identifier_in and version = version_in;

    if not found then
        benchmark_id := nextval('rhn_xccdf_benchmark_id_seq');
        begin
            perform pg_dblink_exec(
                'insert into rhnXccdfBenchmark (id, identifier, version) values (' ||
                benchmark_id || ', ' ||
                coalesce(quote_literal(identifier_in), 'NULL') || ', ' ||
                coalesce(quote_literal(version_in), 'NULL') || ')');
        exception when unique_violation then
            select id
              into strict benchmark_id
              from rhnXccdfBenchmark
             where identifier = identifier_in and version = version_in;
        end;
    end if;

    return benchmark_id;
end;
$$ language plpgsql immutable;
07070100000721000081B400000000000000000000000167AE111400000637000000000000000000000000000000000000006300000000susemanager-schema/upgrade/spacewalk-schema-1.6-to-spacewalk-schema-1.7/107-lookup_xccdf_ident.sql    
create or replace function
lookup_xccdf_ident(system_in in varchar, identifier_in in varchar)
returns numeric
as
$$
declare
    xccdf_ident_id numeric;
    ident_sys_id numeric;
begin
    select id
      into ident_sys_id
      from rhnXccdfIdentSystem
     where system = system_in;
    if not found then
        ident_sys_id := nextval('rhn_xccdf_identsytem_id_seq');
        begin
            perform pg_dblink_exec(
                'insert into rhnXccdfIdentSystem (id, system) values (' ||
                ident_sys_id || ', ' || coalesce(quote_literal(system_in)) || ')');
        exception when unique_violation then
            select id
              into strict ident_sys_id
              from rhnXccdfIdentSystem
             where system = system_in;
        end;
    end if;

    select id
      into xccdf_ident_id
      from rhnXccdfIdent
     where identsystem_id = ident_sys_id and identifier = identifier_in;
    if not found then
        xccdf_ident_id := nextval('rhn_xccdf_ident_id_seq');
        begin
            perform pg_dblink_exec(
                'insert into rhnXccdfIdent (id, identsystem_id, identifier) values (' ||
                xccdf_ident_id || ', ' || ident_sys_id || ', ' ||
                coalesce(quote_literal( identifier_in)) || ')');
        exception when unique_violation then
            select id
              into strict xccdf_ident_id
              from rhnXccdfIdent
             where identsystem_id = ident_sys_id and identifier = identifier_in;
        end;
    end if;
    return xccdf_ident_id;
end;
$$ language plpgsql immutable;
 07070100000722000081B400000000000000000000000167AE1114000003B4000000000000000000000000000000000000006500000000susemanager-schema/upgrade/spacewalk-schema-1.6-to-spacewalk-schema-1.7/108-lookup_xccdf_profile.sql  
create or replace function
lookup_xccdf_profile(identifier_in in varchar, title_in in varchar)
returns numeric
as
$$
declare
    profile_id numeric;
begin
    select id
      into profile_id
      from rhnXccdfProfile
     where identifier = identifier_in and title = title_in;

    if not found then
        profile_id := nextval('rhn_xccdf_profile_id_seq');
        begin
            perform pg_dblink_exec(
                'insert into rhnXccdfProfile (id, identifier, title) values (' ||
                profile_id || ', ' ||
                coalesce(quote_literal(identifier_in), 'NULL') || ', ' ||
                coalesce(quote_literal(title_in), 'NULL') || ')' );
        exception when unique_violation then
            select id
              into profile_id
              from rhnXccdfProfile
             where identifier = identifier_in and title = title_in;
        end;
    end if;

    return profile_id;
end;
$$ language plpgsql;
07070100000723000081B400000000000000000000000167AE11140000012D000000000000000000000000000000000000005700000000susemanager-schema/upgrade/spacewalk-schema-1.6-to-spacewalk-schema-1.7/109-dblink.sql    
create temporary table store_searchpath as select setting from pg_settings where name = 'search_path';

\i /usr/share/pgsql/contrib/dblink.sql

update pg_settings set setting = (select setting from store_searchpath) where name = 'search_path';
drop table store_searchpath;

create extension dblink;

   07070100000724000081B400000000000000000000000167AE1114000001F9000000000000000000000000000000000000006300000000susemanager-schema/upgrade/spacewalk-schema-1.6-to-spacewalk-schema-1.7/110-create_pxt_session.sql    
create or replace function
create_pxt_session(p_web_user_id in numeric, p_expires in numeric, p_value in varchar)
returns numeric as $$
declare
	l_id numeric;
begin
    l_id := nextval( 'pxt_id_seq' );

    perform pg_dblink_exec(
        'insert into PXTSessions (id, value, expires, web_user_id) values (' ||
        l_id || ', ' || ', ' || coalesce(quote_literal(p_value), 'NULL') ||
        ', ' || ', ' || p_expires || ', ' || p_web_user_id || '); commit');

	return l_id;
end;
$$ language plpgsql;
   07070100000725000081B400000000000000000000000167AE1114000006A6000000000000000000000000000000000000006300000000susemanager-schema/upgrade/spacewalk-schema-1.6-to-spacewalk-schema-1.7/111-rhnPackageKey-data.sql    --
-- Copyright (c) 2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

-- Fedora 16, 17, 18
update rhnPackageKey set provider_id = lookup_package_provider('Fedora')
where key_id in ('067f00b6a82ba4b7', '50e94c991aca3465', '0983129322b3b81a');

-- Fedora 16
insert into rhnPackageKey (id, key_id, key_type_id, provider_id)
select sequence_nextval('rhn_pkey_id_seq'), '067f00b6a82ba4b7', lookup_package_key_type('gpg'), lookup_package_provider('Fedora')
from dual
where not exists ( select 1 from rhnPackageKey where key_id = '067f00b6a82ba4b7' );
-- Fedora 17
insert into rhnPackageKey (id, key_id, key_type_id, provider_id)
select sequence_nextval('rhn_pkey_id_seq'), '50e94c991aca3465', lookup_package_key_type('gpg'), lookup_package_provider('Fedora')
from dual
where not exists ( select 1 from rhnPackageKey where key_id = '50e94c991aca3465' );
-- Fedora 18
insert into rhnPackageKey (id, key_id, key_type_id, provider_id)
select sequence_nextval('rhn_pkey_id_seq'), '0983129322b3b81a', lookup_package_key_type('gpg'), lookup_package_provider('Fedora')
from dual
where not exists ( select 1 from rhnPackageKey where key_id = '0983129322b3b81a' );

  07070100000726000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000004800000000susemanager-schema/upgrade/spacewalk-schema-1.7-to-spacewalk-schema-1.8   07070100000727000081B400000000000000000000000167AE1114000001BC000000000000000000000000000000000000006700000000susemanager-schema/upgrade/spacewalk-schema-1.7-to-spacewalk-schema-1.8/002-rhn_contact_monitoring.sql    drop view rhn_contact_monitoring;
create or replace view rhn_contact_monitoring as
select	u.id			as recid,
	u.org_id		as customer_id,
	wupi.last_name		as contact_last_name,
	wupi.first_names	as contact_first_name,
	wupi.email          as email_address,
	u.login			as username,
	u.password		as password,
	1			as schedule_id,
	'GMT' || ''			as preferred_time_zone
from
	web_user_personal_info wupi,
	web_contact u
where	u.id = wupi.web_user_id
;
07070100000728000081B400000000000000000000000167AE111400000180000000000000000000000000000000000000005D00000000susemanager-schema/upgrade/spacewalk-schema-1.7-to-spacewalk-schema-1.8/003-rhn_user.pks.sql  
-- setup search_path so that these functions are created in appropriate schema.
update pg_settings set setting = 'rhn_user,' || setting where name = 'search_path';

drop function find_mailable_address(user_id_in in numeric);

-- restore the original setting
update pg_settings set setting = overlay( setting placing '' from 1 for (length('rhn_user')+1) ) where name = 'search_path';
07070100000729000081B400000000000000000000000167AE111400000083000000000000000000000000000000000000006500000000susemanager-schema/upgrade/spacewalk-schema-1.7-to-spacewalk-schema-1.8/005-rhnEmailAddress_drop.sql  drop table rhnEmailAddress;
drop sequence rhn_eaddress_id_seq;

drop table rhnEmailAddressState;
drop sequence rhn_eastate_id_seq;
 0707010000072A000081B400000000000000000000000167AE1114000001E9000000000000000000000000000000000000006300000000susemanager-schema/upgrade/spacewalk-schema-1.7-to-spacewalk-schema-1.8/007-create_pxt_session.sql    
create or replace function
create_pxt_session(p_web_user_id in numeric, p_expires in numeric, p_value in varchar)
returns numeric as $$
declare
	l_id numeric;
begin
    l_id := nextval( 'pxt_id_seq' );

    perform pg_dblink_exec(
        'insert into PXTSessions (id, value, expires, web_user_id) values (' ||
        l_id || ', ' || coalesce(quote_literal(p_value), 'NULL') ||
        ', ' || p_expires || ', ' || p_web_user_id || '); commit');

	return l_id;
end;
$$ language plpgsql;
   0707010000072B000081B400000000000000000000000167AE111400000057000000000000000000000000000000000000007800000000susemanager-schema/upgrade/spacewalk-schema-1.7-to-spacewalk-schema-1.8/008-rhnEmailAddress_triggers_functions_drop.sql   
drop function rhn_eastate_mod_trig_fun();
drop function rhn_eaddress_mod_trig_fun();

 0707010000072C000081B400000000000000000000000167AE1114000000E0000000000000000000000000000000000000006600000000susemanager-schema/upgrade/spacewalk-schema-1.7-to-spacewalk-schema-1.8/010-rhn_config-tableowner.sql delete from rhn_config_parameter where group_name='cf_db' and name='tableowner';
delete from rhn_config_parameter where group_name='cs_db' and name='tableowner';
delete from rhn_config_macro where name='RHN_DB_TABLE_OWNER';
0707010000072D000081B400000000000000000000000167AE11140000016D000000000000000000000000000000000000006700000000susemanager-schema/upgrade/spacewalk-schema-1.7-to-spacewalk-schema-1.8/011-rhn-config-rhn_db_name.sql    delete from rhn_config_macro where name='CFDB_NAME';
delete from rhn_config_macro where name='CSDB_NAME';
delete from rhn_config_macro where name='RHN_DB_NAME';
delete from rhn_config_macro where name='SCDB_NAME';

delete from rhn_config_parameter where group_name='cf_db' and name='name';
delete from rhn_config_parameter where group_name='cs_db' and name='name';
   0707010000072E000081B400000000000000000000000167AE1114000002DC000000000000000000000000000000000000006900000000susemanager-schema/upgrade/spacewalk-schema-1.7-to-spacewalk-schema-1.8/012-rhn-config-rhn_db_passwd.sql  delete from rhn_config_macro where name='CFDB_NOTIF_PASSWD';
delete from rhn_config_macro where name='CFDB_PASSWD';
delete from rhn_config_macro where name='RHN_DB_PASSWD';
delete from rhn_config_macro where name='CSDB_PASSWD';

delete from rhn_config_parameter where group_name='cf_db' and name='password';
delete from rhn_config_parameter where group_name='cf_db' and name='portal_password';
delete from rhn_config_parameter where group_name='cf_db' and name='proxy_password';
delete from rhn_config_parameter where group_name='cf_db' and name='ui_password';
delete from rhn_config_parameter where group_name='cf_db' and name='notification_password';
delete from rhn_config_parameter where group_name='cs_db' and name='password';
0707010000072F000081B400000000000000000000000167AE111400000233000000000000000000000000000000000000006B00000000susemanager-schema/upgrade/spacewalk-schema-1.7-to-spacewalk-schema-1.8/013-rhn-config-rhn_db_username.sql    delete from rhn_config_macro where name='RHN_DB_USERNAME';

delete from rhn_config_parameter where group_name='cf_db' and name='notification_username';
delete from rhn_config_parameter where group_name='cf_db' and name='portal_username';
delete from rhn_config_parameter where group_name='cf_db' and name='proxy_username';
delete from rhn_config_parameter where group_name='cf_db' and name='ui_username';
delete from rhn_config_parameter where group_name='cf_db' and name='username';
delete from rhn_config_parameter where group_name='cs_db' and name='username';
 07070100000730000081B400000000000000000000000167AE111400000337000000000000000000000000000000000000006000000000susemanager-schema/upgrade/spacewalk-schema-1.7-to-spacewalk-schema-1.8/014-rhnChecksumView.sql   --
-- Copyright (c) 2009--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--

create or replace view rhnChecksumView 
as
select c.id,
       ct.label checksum_type,
       c.checksum
  from rhnChecksum c
  left join rhnChecksumType ct
    on c.checksum_type_id = ct.id;

 07070100000731000081B400000000000000000000000167AE11140000037F000000000000000000000000000000000000005B00000000susemanager-schema/upgrade/spacewalk-schema-1.7-to-spacewalk-schema-1.8/015-lookup_tag.sql    
create or replace function
lookup_tag(org_id_in in numeric, name_in in varchar)
returns numeric
as $$
declare
    tag_id  numeric;
    tag_name_id numeric;
begin
    tag_name_id := lookup_tag_name(name_in);

    select id
      into tag_id
      from rhnTag
     where org_id = org_id_in and
           name_id = tag_name_id;

    if not found then
        tag_id := nextval('rhn_tag_id_seq');
        begin
            perform pg_dblink_exec(
                'insert into rhnTag(id, org_id, name_id) values (' ||
                tag_id || ', ' || org_id_in || ', ' || tag_name_id || ')');
        exception when unique_violation then
            select id
              into strict tag_id
              from rhnTag
             where org_id = org_id_in and
                   name_id = lookup_tag_name(name_in);
        end;
    end if;

    return tag_id;
end; $$
language plpgsql immutable;
 07070100000732000081B400000000000000000000000167AE111400000046000000000000000000000000000000000000005E00000000susemanager-schema/upgrade/spacewalk-schema-1.7-to-spacewalk-schema-1.8/016-rhnXccdfIdent.sql 
ALTER TABLE rhnXccdfIdent ALTER COLUMN identifier TYPE VARCHAR(100);
  07070100000733000081B400000000000000000000000167AE11140000013F000000000000000000000000000000000000006300000000susemanager-schema/upgrade/spacewalk-schema-1.7-to-spacewalk-schema-1.8/017-rhnXccdfRuleresult.sql    
ALTER TABLE rhnXccdfRuleresult ADD id NUMERIC;

CREATE SEQUENCE rhn_xccdf_rresult_id_seq;

UPDATE rhnXccdfRuleresult SET id = nextval('rhn_xccdf_rresult_id_seq');

ALTER TABLE rhnXccdfRuleresult ALTER COLUMN id SET NOT NULL;

ALTER TABLE rhnXccdfRuleresult
    ADD CONSTRAINT rhn_xccdf_rresult_id_pk PRIMARY KEY (id);
 07070100000734000081B400000000000000000000000167AE1114000001EB000000000000000000000000000000000000006500000000susemanager-schema/upgrade/spacewalk-schema-1.7-to-spacewalk-schema-1.8/018-rhnXccdfRuleIdentMap.sql  
CREATE TABLE rhnXccdfRuleIdentMap
(
    rresult_id    NUMERIC NOT NULL
                      CONSTRAINT rhn_xccdf_rim_rresult_fk
                          REFERENCES rhnXccdfRuleresult (id)
                          ON DELETE CASCADE,
    ident_id      NUMERIC NOT NULL
                      CONSTRAINT rhn_xccdf_rim_ident_fk
                          REFERENCES rhnXccdfIdent (id)
)

;

CREATE UNIQUE INDEX rhn_xccdf_rim_ri_uq
    ON rhnXccdfRuleIdentMap (rresult_id, ident_id)
    
    ;
 07070100000735000081B400000000000000000000000167AE11140000008B000000000000000000000000000000000000006A00000000susemanager-schema/upgrade/spacewalk-schema-1.7-to-spacewalk-schema-1.8/019-rhnXccdfRuleIdentMap_data.sql 
INSERT INTO rhnXccdfRuleIdentMap
    (rresult_id, ident_id)
    SELECT xrr.id, xrr.ident_id
        FROM rhnXccdfRuleresult xrr;

COMMIT;
 07070100000736000081B400000000000000000000000167AE111400000036000000000000000000000000000000000000006300000000susemanager-schema/upgrade/spacewalk-schema-1.7-to-spacewalk-schema-1.8/020-rhnXccdfRuleresult.sql    
ALTER TABLE rhnXccdfRuleresult DROP COLUMN ident_id;
  07070100000737000081B400000000000000000000000167AE11140000096C000000000000000000000000000000000000006B00000000susemanager-schema/upgrade/spacewalk-schema-1.7-to-spacewalk-schema-1.8/021-lookup_transaction_package.sql    --
-- Copyright (c) 2008--2015 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.

create or replace function
lookup_transaction_package(
    o_in in varchar,
    n_in in varchar,
    e_in in varchar,
    v_in in varchar,
    r_in in varchar,
    a_in in varchar)
returns numeric
as
$$
declare
    o_id        numeric;
    n_id        numeric;
    e_id        numeric;
    p_arch_id   numeric;
    tp_id       numeric;
begin
    select id
      into o_id
      from rhnTransactionOperation
     where label = o_in;

    if not found then
        perform rhn_exception.raise_exception('invalid_transaction_operation');
    end if;

    n_id := lookup_package_name(n_in);
    e_id := lookup_evr(e_in, v_in, r_in);
    p_arch_id := null;

    if a_in is not null then
        p_arch_id := lookup_package_arch(a_in);
    end if;

    select id
      into tp_id
      from rhnTransactionPackage
     where operation = o_id and
           name_id = n_id and
           evr_id = e_id and
           (package_arch_id = p_arch_id or (p_arch_id is null and package_arch_id is null));

    if not found then
        tp_id := nextval('rhn_transpack_id_seq');
        begin
            perform pg_dblink_exec(
                'insert into rhnTransactionPackage (id, operation, name_id, evr_id, package_arch_id)' ||
                ' values (' || tp_id || ', ' || o_id || ', ' || n_id || ', ' || e_id ||
                ', ' || p_arch_id  || ')');
        exception when unique_violation then
            select id
              into strict tp_id
              from rhnTransactionPackage
             where operation = o_id and
                   name_id = n_id and
                   evr_id = e_id and
                   (package_arch_id = p_arch_id or (p_arch_id is null and package_arch_id is null));
        end;
    end if;

    return tp_id;
end;
$$
language plpgsql immutable;
07070100000738000081B400000000000000000000000167AE111400000059000000000000000000000000000000000000006B00000000susemanager-schema/upgrade/spacewalk-schema-1.7-to-spacewalk-schema-1.8/021-rhn_command-check_log_size.sql    
update rhn_command set description = 'Log Size Growth' where name = 'check_log_size' ;

   07070100000739000081B400000000000000000000000167AE111400000095000000000000000000000000000000000000007300000000susemanager-schema/upgrade/spacewalk-schema-1.7-to-spacewalk-schema-1.8/022-rhnPackageUpgradeArchCompat-unique.sql    
drop index rhn_puac_pa_pua;
create unique index rhn_puac_pa_pua_uq
     on rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id);

   0707010000073A000081B400000000000000000000000167AE111400000B78000000000000000000000000000000000000006F00000000susemanager-schema/upgrade/spacewalk-schema-1.7-to-spacewalk-schema-1.8/023-rhn_schedule_days-to_timestamp.sql    
update rhn_schedule_days
set start_1 = to_timestamp('2000-09-08 12:00:02 AM','YYYY-MM-DD HH:MI:SS AM')
where schedule_id = ( select recid from rhn_schedules where customer_id is null and description = '24x7' )
and ord = 0
	and end_1 = to_timestamp('2000-09-09 12:00:00 AM','YYYY-MM-DD HH:MI:SS AM')
	and start_2 is null and end_2 is null
	and start_3 is null and end_3 is null
	and start_4 is null and end_4 is null;

update rhn_schedule_days
set start_1 = to_timestamp('2000-09-08 12:00:09 AM','YYYY-MM-DD HH:MI:SS AM')
where schedule_id = ( select recid from rhn_schedules where customer_id is null and description = '24x7' )
and ord = 1
	and end_1 = to_timestamp('2000-09-09 12:00:00 AM','YYYY-MM-DD HH:MI:SS AM')
	and start_2 is null and end_2 is null
	and start_3 is null and end_3 is null
	and start_4 is null and end_4 is null;

update rhn_schedule_days
set start_1 = to_timestamp('2000-09-08 12:00:14 AM','YYYY-MM-DD HH:MI:SS AM')
where schedule_id = ( select recid from rhn_schedules where customer_id is null and description = '24x7' )
and ord = 2
	and end_1 = to_timestamp('2000-09-09 12:00:00 AM','YYYY-MM-DD HH:MI:SS AM')
	and start_2 is null and end_2 is null
	and start_3 is null and end_3 is null
	and start_4 is null and end_4 is null;

update rhn_schedule_days
set start_1 = to_timestamp('2000-09-08 12:00:20 AM','YYYY-MM-DD HH:MI:SS AM')
where schedule_id = ( select recid from rhn_schedules where customer_id is null and description = '24x7' )
and ord = 3
	and end_1 = to_timestamp('2000-09-09 12:00:00 AM','YYYY-MM-DD HH:MI:SS AM')
	and start_2 is null and end_2 is null
	and start_3 is null and end_3 is null
	and start_4 is null and end_4 is null;

update rhn_schedule_days
set start_1 = to_timestamp('2000-09-08 12:00:25 AM','YYYY-MM-DD HH:MI:SS AM')
where schedule_id = ( select recid from rhn_schedules where customer_id is null and description = '24x7' )
and ord = 4
	and end_1 = to_timestamp('2000-09-09 12:00:00 AM','YYYY-MM-DD HH:MI:SS AM')
	and start_2 is null and end_2 is null
	and start_3 is null and end_3 is null
	and start_4 is null and end_4 is null;

update rhn_schedule_days
set start_1 = to_timestamp('2000-09-08 12:00:31 AM','YYYY-MM-DD HH:MI:SS AM')
where schedule_id = ( select recid from rhn_schedules where customer_id is null and description = '24x7' )
and ord = 5
	and end_1 = to_timestamp('2000-09-09 12:00:00 AM','YYYY-MM-DD HH:MI:SS AM')
	and start_2 is null and end_2 is null
	and start_3 is null and end_3 is null
	and start_4 is null and end_4 is null;

update rhn_schedule_days
set start_1 = to_timestamp('2000-09-08 12:00:36 AM','YYYY-MM-DD HH:MI:SS AM')
where schedule_id = ( select recid from rhn_schedules where customer_id is null and description = '24x7' )
and ord = 6
	and end_1 = to_timestamp('2000-09-09 12:00:00 AM','YYYY-MM-DD HH:MI:SS AM')
	and start_2 is null and end_2 is null
	and start_3 is null and end_3 is null
	and start_4 is null and end_4 is null;

commit;

0707010000073B000081B400000000000000000000000167AE1114000000D1000000000000000000000000000000000000006600000000susemanager-schema/upgrade/spacewalk-schema-1.7-to-spacewalk-schema-1.8/031-no_operation_trig_fun.sql -- oracle equivalent source none

create function no_operation_trig_fun()
returns trigger as
$$
begin
	raise exception 'Permission denied: % is not allowed on %', TG_OP, TG_RELNAME;
end;
$$ language plpgsql;

   0707010000073C000081B400000000000000000000000167AE111400000080000000000000000000000000000000000000006600000000susemanager-schema/upgrade/spacewalk-schema-1.7-to-spacewalk-schema-1.8/032-rhnPackageEvr-trigger.sql 
create trigger
rhn_pack_evr_no_updel_trig
before update or delete on rhnPackageEvr
execute procedure no_operation_trig_fun();

0707010000073D000081B400000000000000000000000167AE111400002BD4000000000000000000000000000000000000006500000000susemanager-schema/upgrade/spacewalk-schema-1.7-to-spacewalk-schema-1.8/033-rhn_entitlements.pkb.sql  
-- setup search_path so that these functions are created in appropriate schema.
update pg_settings set setting = 'rhn_entitlements,' || setting where name = 'search_path';


    -- *******************************************************************
    -- PROCEDURE: repoll_virt_guest_entitlements
    --
    --   Whenever we add/remove a virtualization_host* entitlement from 
    --   a host, we can call this procedure to update what type of slots
    --   the guests are consuming.  
    -- 
    --   If you're removing the entitlement, it's 
    --   possible the guests will become unentitled if you don't have enough
    --   physical slots to cover them.
    --
    --   If you're adding the entitlement, you end up freeing up physical
    --   slots for other systems.
    --
    -- *******************************************************************
    create or replace function repoll_virt_guest_entitlements(
        server_id_in in numeric
    ) returns void
as $$
    declare
        -- All channel families associated with the guests of server_id_in
        families cursor for 
            select distinct cfs.channel_family_id
            from
                rhnChannelFamilyServers cfs,
                rhnVirtualInstance vi
            where
                vi.host_system_id = server_id_in
                and vi.virtual_system_id = cfs.server_id;
        
        -- All of server group types associated with the guests of
        -- server_id_in
        group_types cursor for
            select distinct sg.group_type, sgt.label
            from
                rhnServerGroupType sgt,
                rhnServerGroup sg,
                rhnServerGroupMembers sgm,
                rhnVirtualInstance vi
            where
                vi.host_system_id = server_id_in
                and vi.virtual_system_id = sgm.server_id
                and sgm.server_group_id = sg.id
                and sg.group_type = sgt.id;

        -- Virtual servers from a certain family belonging to a specific
        -- host that are consuming physical channel slots over the limit.
        virt_servers_cfam cursor(family_id_in numeric, quantity_in numeric) for
                select vi.virtual_system_id
                from
                    rhnChannelFamilyMembers cfm,
                    rhnServerChannel sc,
                    rhnVirtualInstance vi
                where
                    vi.host_system_id = server_id_in
                    and vi.virtual_system_id = sc.server_id
                    and sc.channel_id = cfm.channel_id
                    and cfm.channel_family_id = family_id_in
                order by sc.modified desc
                limit quantity_in;                

        -- Virtual servers from a certain family belonging to a specific
        -- host that are consuming physical system slots over the limit.
        virt_servers_sgt cursor(group_type_in numeric, quantity_in numeric) for
                select vi.virtual_system_id
                from
                    rhnServerGroup sg,
                    rhnServerGroupMembers sgm,
                    rhnVirtualInstance vi
                where
                    vi.host_system_id = server_id_in
                    and vi.virtual_system_id = sgm.server_id
                    and sgm.server_group_id = sg.id
                    and sg.group_type = group_type_in
                order by sgm.modified desc
                limit quantity_in;                
        
        -- Get the orgs of Virtual guests
        -- Since they may belong to different orgs
        virt_guest_orgs cursor for
                select  distinct (s.org_id)
                from rhnServer s
                    inner join  rhnVirtualInstance vi on vi.virtual_system_id = s.id
                where
                    vi.host_system_id = server_id_in
                    and s.org_id <> (select s1.org_id from rhnServer s1 where s1.id = vi.host_system_id) ;

        org_id_val numeric;
        max_members_val numeric;
        max_flex_val numeric;
        current_members_calc numeric;
        sg_id numeric;
        is_virt numeric := 0;
        free_slots numeric := 0;
    begin
          select 1 into is_virt
                from rhnServerEntitlementView
           where server_id = server_id_in
                 and label in ('virtualization_host', 'virtualization_host_platform');

      if not found then
          is_virt := 0;
      end if;

        select org_id
        into org_id_val
        from rhnServer
        where id = server_id_in;

        -- deal w/ channel entitlements first ...
        for family in families loop
            if is_virt = 0 then
            -- if the host_server does not have virt
            --- find all possible flex slots
            -- and set each of the flex eligible guests to Y
                select sfc.max_members - sfc.current_members
                  into free_slots
                  from rhnServerFveCapable sfc
                 where sfc.channel_family_id = family.channel_family_id;
                UPDATE rhnServerChannel sc set is_fve = 'Y'
                where sc.server_id in (
                            select vi.virtual_system_id
                            from rhnServerFveCapable sfc
                                inner join rhnVirtualInstance vi on vi.virtual_system_id = sfc.server_id
                            where vi.host_system_id = server_id_in
                                  and sfc.channel_family_id = family.channel_family_id
                              order by vi.modified desc
                            limit free_slots
                );
            else
            -- if the host_server has virt
            -- set all its flex guests to N
                UPDATE rhnServerChannel sc set is_fve = 'N'
                where
                    sc.channel_id in (select cfm.channel_id from rhnChannelFamilyMembers cfm
                                      where cfm.CHANNEL_FAMILY_ID = family.channel_family_id)
                    and sc.is_fve = 'Y'
                    and sc.server_id in
                            (select vi.virtual_system_id  from rhnVirtualInstance vi
                                    where vi.host_system_id = server_id_in);
            end if;

            -- get the current (physical) members of the family
            current_members_calc := 
                rhn_channel.channel_family_current_members(family.channel_family_id,
                                                           org_id_val); -- fixed transposed args

            -- get the max members of the family
            select max_members
            into max_members_val
            from rhnPrivateChannelFamily
            where channel_family_id = family.channel_family_id
            and org_id = org_id_val;

            select fve_max_members
            into max_flex_val
            from rhnPrivateChannelFamily
            where channel_family_id = family.channel_family_id
            and org_id = org_id_val;

            if current_members_calc > max_members_val then
                -- A virtualization_host* ent must have been removed, so we'll
                -- unsubscribe guests from the host first.

                -- hm, i don't think max_members - current_members_calc yielding a negative number
                -- will work w/ rownum, swaping 'em in the body of this if...
                for virt_server in virt_servers_cfam(family.channel_family_id,
                                current_members_calc - max_members_val) loop 

                    perform rhn_channel.unsubscribe_server_from_family(
                                virt_server.virtual_system_id,
                                family.channel_family_id);
                end loop;                               

                -- if we're still over the limit, which would be odd,
                -- just prune the group to max_members
                --
                -- er... wouldn't we actually have to refresh the values of
                -- current_members_calc and max_members_val to actually ever
                -- *skip this??
                if current_members_calc > max_members_val then
                    -- argh, transposed again?!
                    perform rhn_entitlements.set_family_count(org_id_val,
                                     family.channel_family_id,
                                     max_members_val, max_flex_val);
                    --TODO calculate this correctly
                end if; 

           end if;

            -- update current_members for the family.  This will set the value
            -- to reflect adding/removing the entitlement.
            --
            -- what's the difference of doing this vs the unavoidable set_family_count above?
            perform rhn_channel.update_family_counts(family.channel_family_id,
                                             org_id_val);

            -- It is possible that the guests belong  to a different org than the host
            -- so we are going to update the family counts in the guests orgs also
            for org in virt_guest_orgs loop
                    perform rhn_channel.update_family_counts(family.channel_family_id,
                                             org.org_id);
            end loop;
        end loop;

        for a_group_type in group_types loop
          -- get the current *physical* members of the system entitlement type for the org...
          -- 
          -- unlike channel families, it appears the standard rhnServerGroup.max_members represents
          -- *physical* slots, vs physical+virt ... boy that's confusing...

          select max_members, id
            into max_members_val, sg_id
            from rhnServerGroup
            where group_type = a_group_type.group_type
            and org_id = org_id_val;


      select count(sep.server_id) into current_members_calc
            from rhnServerEntitlementPhysical sep
           where sep.server_group_id = sg_id
             and sep.server_group_type_id = a_group_type.group_type;
          
          if current_members_calc > max_members_val then
            -- A virtualization_host* ent must have been removed, and we're over the limit, so unsubscribe guests
            for virt_server in virt_servers_sgt(a_group_type.group_type,
                                                current_members_calc - max_members_val) loop
              perform rhn_entitlements.remove_server_entitlement(virt_server.virtual_system_id, a_group_type.label);

              -- decrement current_members_calc, we'll use it to reset current_members for the group at the end...
              current_members_calc := current_members_calc - 1;
            end loop;

          end if;

          update rhnServerGroup set current_members = current_members_calc
           where org_id = org_id_val
             and group_type = a_group_type.group_type;

          -- I think that's all the house-keeping we have to do...
        end loop;

    end$$
language plpgsql;


-- restore the original setting
update pg_settings set setting = overlay( setting placing '' from 1 for (length('rhn_entitlements')+1) ) where name = 'search_path';
0707010000073E000081B400000000000000000000000167AE111400000054000000000000000000000000000000000000005F00000000susemanager-schema/upgrade/spacewalk-schema-1.7-to-spacewalk-schema-1.8/034-rhnChannelArch.sql    ALTER TABLE rhnChannelArch
    ADD CONSTRAINT rhn_carch_name_uq UNIQUE (name)
    ;
0707010000073F000081B400000000000000000000000167AE111400000F8A000000000000000000000000000000000000005C00000000susemanager-schema/upgrade/spacewalk-schema-1.7-to-spacewalk-schema-1.8/035-rhn_org.pkb.sql   --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--

-- create schema rhn_org;

-- setup search_path so that these functions are created in appropriate schema.
update pg_settings set setting = 'rhn_org,' || setting where name = 'search_path';


create or replace function delete_org (
        org_id_in in numeric
    ) returns void
    as
    $$
    declare
        users cursor for
        select id
        from web_contact
        where org_id = org_id_in;

        servers cursor (org_id_in numeric) for
        select  id
        from    rhnServer
        where   org_id = org_id_in;

        config_channels cursor for
        select id
        from rhnConfigChannel
        where org_id = org_id_in;

        custom_channels cursor for
        select  id
        from    rhnChannel
        where   org_id = org_id_in;

        errata cursor for
        select  id
        from    rhnErrata
        where   org_id = org_id_in;

    begin

        if org_id_in = 1 then
            perform rhn_exception.raise_exception('cannot_delete_base_org');
        end if;

        -- Delete all users.
        for u in users loop
            perform rhn_org.delete_user(u.id, 1);
        end loop;

        -- Delete all servers.
        for s in servers(org_id_in) loop
            perform delete_server(s.id);
        end loop;

        -- Delete all config channels.
        for c in config_channels loop
            perform rhn_config.delete_channel(c.id);
        end loop;

        -- Delete all custom channels.
        for cc in custom_channels loop
          delete from rhnServerChannel where channel_id = cc.id;
          delete from rhnServerProfilePackage where server_profile_id in (
            select id from rhnServerProfile where base_channel = cc.id
          );
          delete from rhnServerProfile where base_channel = cc.id;
        end loop;

        -- Delete all errata packages 
        for e in errata loop
            delete from rhnErrataPackage where errata_id = e.id;
        end loop;

        -- Give the org's entitlements back to the main org.
        perform rhn_entitlements.remove_org_entitlements(org_id_in);

        -- Clean up tables where we don't have a cascading delete.
        delete from rhnChannel where org_id = org_id_in;
        delete from rhnDailySummaryQueue where org_id = org_id_in;
        delete from rhnOrgQuota where org_id = org_id_in;
        delete from rhnFileList where org_id = org_id_in;
        delete from rhnServerGroup where org_id = org_id_in;
        delete from rhn_check_suites where customer_id = org_id_in;
        delete from rhn_command_target where customer_id = org_id_in;
        delete from rhn_contact_groups where customer_id = org_id_in;
        delete from rhn_notification_formats where customer_id = org_id_in;
        delete from rhn_probe where customer_id = org_id_in;
        delete from rhn_redirects where customer_id = org_id_in;
        delete from rhn_sat_cluster where customer_id = org_id_in;
        delete from rhn_schedules where customer_id = org_id_in;
        delete from rhnContentSource where org_id = org_id_in;

        -- Delete the org.
        delete from web_customer where id = org_id_in;

    end;
    $$
    language plpgsql;

-- restore the original setting
update pg_settings set setting = overlay( setting placing '' from 1 for (length('rhn_org')+1) ) where name = 'search_path';

  07070100000740000081B400000000000000000000000167AE11140000113B000000000000000000000000000000000000006200000000susemanager-schema/upgrade/spacewalk-schema-1.7-to-spacewalk-schema-1.8/036-support-for-armv7.sql insert into rhnChannelArch (id, label, name, arch_type_id) select
sequence_nextval('rhn_channel_arch_id_seq'), 'channel-armhfp', 'ARM hard. FP', lookup_arch_type('rpm') from dual
where not exists (select 1 from rhnChannelArch where label = 'channel-armhfp');

insert into rhnPackageArch (id, label, name, arch_type_id) select
sequence_nextval('rhn_package_arch_id_seq'), 'armv7hnl', 'ARMv7hnl', lookup_arch_type('rpm') from dual
where not exists (select 1 from rhnPackageArch where label = 'armv7hnl');
insert into rhnPackageArch (id, label, name, arch_type_id) select
sequence_nextval('rhn_package_arch_id_seq'), 'armv7hl', 'ARMv7hl', lookup_arch_type('rpm') from dual
where not exists (select 1 from rhnPackageArch where label = 'armv7hl');

insert into rhnChannelPackageArchCompat (channel_arch_id, package_arch_id) select
LOOKUP_CHANNEL_ARCH('channel-armhfp'), LOOKUP_PACKAGE_ARCH('armv7hnl') from dual
where not exists (select 1 from rhnChannelPackageArchCompat where channel_arch_id = LOOKUP_CHANNEL_ARCH('channel-armhfp') and package_arch_id = LOOKUP_PACKAGE_ARCH('armv7hnl'));
insert into rhnChannelPackageArchCompat (channel_arch_id, package_arch_id) select
LOOKUP_CHANNEL_ARCH('channel-armhfp'), LOOKUP_PACKAGE_ARCH('armv7hl') from dual
where not exists (select 1 from rhnChannelPackageArchCompat where channel_arch_id = LOOKUP_CHANNEL_ARCH('channel-armhfp') and package_arch_id = LOOKUP_PACKAGE_ARCH('armv7hnl'));
insert into rhnChannelPackageArchCompat (channel_arch_id, package_arch_id) select
LOOKUP_CHANNEL_ARCH('channel-armhfp'), LOOKUP_PACKAGE_ARCH('noarch') from dual
where not exists (select 1 from rhnChannelPackageArchCompat where channel_arch_id = LOOKUP_CHANNEL_ARCH('channel-armhfp') and package_arch_id = LOOKUP_PACKAGE_ARCH('noarch'));

insert into rhnServerArch (id, label, name, arch_type_id) select
sequence_nextval('rhn_server_arch_id_seq'), 'armv7l-redhat-linux', 'armv7l', lookup_arch_type('rpm') from dual
where not exists (select 1 from rhnServerArch where label = 'armv7l-redhat-linux');

insert into rhnServerChannelArchCompat (server_arch_id, channel_arch_id) select
LOOKUP_SERVER_ARCH('armv7l-redhat-linux'), LOOKUP_CHANNEL_ARCH('channel-armhfp') from dual
where not exists (select 1 from rhnServerChannelArchCompat where server_arch_id = LOOKUP_SERVER_ARCH('armv7l-redhat-linux') and channel_arch_id = LOOKUP_CHANNEL_ARCH('channel-armhfp'));


insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type) select
LOOKUP_SERVER_ARCH('armv7l-redhat-linux'), LOOKUP_SG_TYPE('sw_mgr_entitled') from dual
where not exists (select 1 from rhnServerServerGroupArchCompat where server_arch_id = LOOKUP_SERVER_ARCH('armv7l-redhat-linux') and server_group_type = LOOKUP_SG_TYPE('sw_mgr_entitled'));
insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type) select
LOOKUP_SERVER_ARCH('armv7l-redhat-linux'), LOOKUP_SG_TYPE('enterprise_entitled') from dual
where not exists (select 1 from rhnServerServerGroupArchCompat where server_arch_id = LOOKUP_SERVER_ARCH('armv7l-redhat-linux') and server_group_type = LOOKUP_SG_TYPE('enterprise_entitled'));
insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type) select
LOOKUP_SERVER_ARCH('armv7l-redhat-linux'), LOOKUP_SG_TYPE('provisioning_entitled') from dual
where not exists (select 1 from rhnServerServerGroupArchCompat where server_arch_id = LOOKUP_SERVER_ARCH('armv7l-redhat-linux') and server_group_type = LOOKUP_SG_TYPE('provisioning_entitled'));
insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type) select
LOOKUP_SERVER_ARCH('armv7l-redhat-linux'), LOOKUP_SG_TYPE('monitoring_entitled') from dual
where not exists (select 1 from rhnServerServerGroupArchCompat where server_arch_id = LOOKUP_SERVER_ARCH('armv7l-redhat-linux') and server_group_type = LOOKUP_SG_TYPE('monitoring_entitled'));
insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type) select
LOOKUP_SERVER_ARCH('armv7l-redhat-linux'), LOOKUP_SG_TYPE('virtualization_host') from dual
where not exists (select 1 from rhnServerServerGroupArchCompat where server_arch_id = LOOKUP_SERVER_ARCH('armv7l-redhat-linux') and server_group_type = LOOKUP_SG_TYPE('virtualization_host'));

insert into rhnCpuArch (id, label, name) select
sequence_nextval('rhn_cpu_arch_id_seq'), 'armv7l', 'ARMv7l' from dual
where not exists (select 1 from rhnCpuArch where label = 'armv7l');
 07070100000741000081B400000000000000000000000167AE111400000B53000000000000000000000000000000000000006A00000000susemanager-schema/upgrade/spacewalk-schema-1.7-to-spacewalk-schema-1.8/037-support-for-armv5-channel.sql insert into rhnChannelArch (id, label, name, arch_type_id) values
        (sequence_nextval('rhn_channel_arch_id_seq'), 'channel-arm', 'ARM soft. FP', lookup_arch_type('rpm'));

insert into rhnPackageArch (id, label, name, arch_type_id) values
(sequence_nextval('rhn_package_arch_id_seq'), 'armv7l', 'ARMv7l', lookup_arch_type('rpm'));
insert into rhnPackageArch (id, label, name, arch_type_id) values
(sequence_nextval('rhn_package_arch_id_seq'), 'armv6l', 'ARMv6l', lookup_arch_type('rpm'));
insert into rhnPackageArch (id, label, name, arch_type_id) values
(sequence_nextval('rhn_package_arch_id_seq'), 'armv5tel', 'ARMv5tel', lookup_arch_type('rpm'));

insert into rhnChannelPackageArchCompat (channel_arch_id, package_arch_id)
        values (LOOKUP_CHANNEL_ARCH('channel-arm'), LOOKUP_PACKAGE_ARCH('armv7l'));
insert into rhnChannelPackageArchCompat (channel_arch_id, package_arch_id)
        values (LOOKUP_CHANNEL_ARCH('channel-arm'), LOOKUP_PACKAGE_ARCH('armv6l'));
insert into rhnChannelPackageArchCompat (channel_arch_id, package_arch_id)
        values (LOOKUP_CHANNEL_ARCH('channel-arm'), LOOKUP_PACKAGE_ARCH('armv5tel'));
insert into rhnChannelPackageArchCompat (channel_arch_id, package_arch_id)
		values (LOOKUP_CHANNEL_ARCH('channel-arm'), LOOKUP_PACKAGE_ARCH('noarch'));

insert into rhnServerArch (id, label, name, arch_type_id) values
(sequence_nextval('rhn_server_arch_id_seq'), 'armv5tejl-redhat-linux', 'armv5tejl', lookup_arch_type('rpm'));

insert into rhnServerChannelArchCompat (server_arch_id, channel_arch_id) values
        (LOOKUP_SERVER_ARCH('armv7l-redhat-linux'), LOOKUP_CHANNEL_ARCH('channel-arm'));
insert into rhnServerChannelArchCompat (server_arch_id, channel_arch_id) values
        (LOOKUP_SERVER_ARCH('armv5tejl-redhat-linux'), LOOKUP_CHANNEL_ARCH('channel-arm'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
        values (lookup_server_arch('armv5tejl-redhat-linux'),
            lookup_sg_type('sw_mgr_entitled'));
insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
        values (lookup_server_arch('armv5tejl-redhat-linux'),
            lookup_sg_type('enterprise_entitled'));
insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
        values (lookup_server_arch('armv5tejl-redhat-linux'),
            lookup_sg_type('provisioning_entitled'));
insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
        values (lookup_server_arch('armv5tejl-redhat-linux'),
            lookup_sg_type('monitoring_entitled'));
insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
        values (lookup_server_arch('armv5tejl-redhat-linux'),
            lookup_sg_type('virtualization_host'));

insert into rhnCpuArch (id, label, name) values
(sequence_nextval('rhn_cpu_arch_id_seq'), 'armv5tejl', 'ARMv5tejl');
 07070100000742000081B400000000000000000000000167AE1114000004F4000000000000000000000000000000000000007200000000susemanager-schema/upgrade/spacewalk-schema-1.7-to-spacewalk-schema-1.8/038-rhn_notification_formats-newlines.sql -- oracle equivalent source none

update rhn_notification_formats
set body_format = 'This is a Spacewalk Monitoring Satellite event notification.\n\nTime:      ^[timestamp:"%a %b %d, %H:%M:%S %Z"]\nState:     ^[probe state]\nHost:      ^[hostname] (^[host IP])\nCheck:     ^[probe description]\nMessage:   ^[probe output]\nRun from:  ^[satellite description]\n\nTo acknowledge, reply to this message with this subject line:\n     ACK ^[alert id]\n\nTo immediately escalate, reply to this message with this subject line:\n     NACK ^[alert id]'
where customer_id is null
	and description = 'New Default (2.15)';

update rhn_notification_formats
set body_format = 'This is Spacewalk Monitoring Satellite notification ^[alert id].\n\nTime:      ^[timestamp:"%a %b %d, %H:%M:%S %Z"]\nState:     ^[probe state]\nHost:      ^[hostname] (^[host IP])\nCheck:     ^[probe description]\nMessage:   ^[probe output]\nRun from:  ^[satellite description]',
	reply_format = '\n\nTo acknowledge, reply to this message within ^[ack wait] minutes with this subject line:\n     ACK ^[alert id]\n\nTo immediately escalate, reply to this message within ^[ack wait] minutes with this subject line:\n     NACK ^[alert id]'
where customer_id is null
	and description = 'New Default (2.18)';

07070100000743000081B400000000000000000000000167AE111400000020000000000000000000000000000000000000006400000000susemanager-schema/upgrade/spacewalk-schema-1.7-to-spacewalk-schema-1.8/040-rhn_time_zone_names.sql   DROP TABLE rhn_time_zone_names;
07070100000744000081B400000000000000000000000167AE1114000000CD000000000000000000000000000000000000006500000000susemanager-schema/upgrade/spacewalk-schema-1.7-to-spacewalk-schema-1.8/041-rhnKickstartableTree.sql  ALTER TABLE rhnKickstartableTree DROP CONSTRAINT rhn_kstree_cid_fk;
ALTER TABLE rhnKickstartableTree ADD CONSTRAINT rhn_kstree_cid_fk FOREIGN KEY (channel_id) REFERENCES rhnChannel (id) ON DELETE CASCADE;
   07070100000745000081B400000000000000000000000167AE111400001052000000000000000000000000000000000000005F00000000susemanager-schema/upgrade/spacewalk-schema-1.7-to-spacewalk-schema-1.8/042-rhn_config.pkb.sql    
-- setup search_path so that these functions are created in appropriate schema.
update pg_settings set setting = 'rhn_config,' || setting where name = 'search_path';


	create or replace function insert_revision (
		revision_in in numeric,
		config_file_id_in in numeric,
		config_content_id_in in numeric,
		config_info_id_in in numeric,
		config_file_type_id_in in numeric default 1
	) returns numeric as $$
               declare
		retval numeric;

	begin
      
		insert into rhnConfigRevision(id, revision, config_file_id,
				config_content_id, config_info_id, config_file_type_id
			) values (
				nextval('rhn_confrevision_id_seq'), revision_in, config_file_id_in,
				config_content_id_in, config_info_id_in, config_file_type_id_in
			)
			returning id into retval;

		return retval;
	end$$ language 'plpgsql';

	create or replace function delete_revision (
		config_revision_id_in in numeric,
		org_id_in in numeric default -1
	) returns void as $$
	declare
		cfid numeric;
		ccid numeric;
		oid numeric;
		latest_crid numeric;
		others numeric := 0;
		snapshots cursor is
			select scr.snapshot_id as id
			from rhnSnapshot s,
					rhnSnapshotConfigRevision scr
			where scr.config_revision_id = config_revision_id_in
					and scr.snapshot_id = s.id
					and s.invalid is null;
		 other_revisions cursor (config_content_id_in numeric) is
			select 1
			from rhnConfigRevision
			where config_content_id = config_content_id_in;
	begin
                for snapshot in snapshots loop
                    update rhnSnapshot
                        set invalid = lookup_snapshot_invalid_reason('cr_removed')
                        where id = snapshot.id;
                end loop;

		if org_id_in < 0 then
			select cr.config_content_id, cc.org_id
			into ccid, oid
			from rhnConfigChannel cc,
					rhnConfigFile cf,
					rhnConfigRevision cr
			where cr.id = config_revision_id_in
				and cr.config_file_id = cf.id
				and cf.config_channel_id = cc.id;
		else
			select	cr.config_content_id, org_id_in
			into	ccid, oid
			from	rhnConfigRevision cr
			where	cr.id = config_revision_id_in;
		end if;

		-- right now this will set rhnActionConfigFileName.config_revision_id
		-- to null, and will remove an entry from rhnActionConfigRevision.
		-- might we want to prune and/or kill the action in some way?  maybe
		-- mark it failed or something?
		delete from rhnConfigRevision where id = config_revision_id_in;

		-- now prune away content if there aren't any other revisions pointing
		-- at it
		for other_revision in other_revisions(ccid) loop
			others := 1;
			exit;
		end loop;
		if others = 0 then
			delete from rhnConfigContent where id = ccid;
		end if;

		-- now make sure rhnConfigFile points at a valid revision;
		-- if there isn't one, we're deleting it, _unless_ org_id_in is
		-- >= 0, in which case we're in the delete trigger anyway
		if org_id_in < 0 then
			select	cf.latest_config_revision_id,
					cf.id
			into latest_crid,
					cfid
			from rhnConfigFile cf,
					rhnConfigRevision cr
			where cr.id = config_revision_id_in
				and cr.config_file_id = cf.id;

			if latest_crid = config_revision_id_in then
				latest_crid := rhn_config.get_latest_revision(cfid);
				if latest_crid is not null then
					update rhnConfigFile set latest_config_revision_id = latest_crid
						where id = cfid;
				else
					delete from rhnConfigFile where id = cfid;
				end if;
			end if;

		end if;

	end ;
$$ LANGUAGE 'plpgsql';

	create or replace function delete_file (
		config_file_id_in in numeric
	) returns void as $$
declare
org_id numeric;
revision record;
			
	begin
		for revision in 
		select cr.id, cc.org_id
			from rhnConfigChannel cc,
					rhnConfigRevision cr,
					rhnConfigFile cf
			where cf.id = config_file_id_in
				and cf.config_channel_id = cc.id
				and cr.config_file_id = cf.id
		
                loop
			perform rhn_config.delete_revision(revision.id, revision.org_id);
			org_id := revision.org_id;
		end loop;
		delete from rhnConfigFile where id = config_file_id_in;
	end;
$$ LANGUAGE 'plpgsql';

update pg_settings set setting = overlay( setting placing '' from 1 for (length('rhn_config')+1) ) where name = 'search_path';
  07070100000746000081B400000000000000000000000167AE111400000020000000000000000000000000000000000000005A00000000susemanager-schema/upgrade/spacewalk-schema-1.7-to-spacewalk-schema-1.8/043-rhn_quota.sql 
DROP SCHEMA rhn_quota CASCADE;
07070100000747000081B400000000000000000000000167AE111400000CC0000000000000000000000000000000000000005C00000000susemanager-schema/upgrade/spacewalk-schema-1.7-to-spacewalk-schema-1.8/044-rhn_org.pkb.sql   
-- setup search_path so that these functions are created in appropriate schema.
update pg_settings set setting = 'rhn_org,' || setting where name = 'search_path';


create or replace function delete_org (
        org_id_in in numeric
    ) returns void
    as
    $$
    declare
        users cursor for
        select id
        from web_contact
        where org_id = org_id_in;

        servers cursor (org_id_in numeric) for
        select  id
        from    rhnServer
        where   org_id = org_id_in;

        config_channels cursor for
        select id
        from rhnConfigChannel
        where org_id = org_id_in;

        custom_channels cursor for
        select  id
        from    rhnChannel
        where   org_id = org_id_in;

        errata cursor for
        select  id
        from    rhnErrata
        where   org_id = org_id_in;

    begin

        if org_id_in = 1 then
            perform rhn_exception.raise_exception('cannot_delete_base_org');
        end if;

        -- Delete all users.
        for u in users loop
            perform rhn_org.delete_user(u.id, 1);
        end loop;

        -- Delete all servers.
        for s in servers(org_id_in) loop
            perform delete_server(s.id);
        end loop;

        -- Delete all config channels.
        for c in config_channels loop
            perform rhn_config.delete_channel(c.id);
        end loop;

        -- Delete all custom channels.
        for cc in custom_channels loop
          delete from rhnServerChannel where channel_id = cc.id;
          delete from rhnServerProfilePackage where server_profile_id in (
            select id from rhnServerProfile where base_channel = cc.id
          );
          delete from rhnServerProfile where base_channel = cc.id;
        end loop;

        -- Delete all errata packages 
        for e in errata loop
            delete from rhnErrataPackage where errata_id = e.id;
        end loop;

        -- Give the org's entitlements back to the main org.
        perform rhn_entitlements.remove_org_entitlements(org_id_in);

        -- Clean up tables where we don't have a cascading delete.
        delete from rhnChannel where org_id = org_id_in;
        delete from rhnDailySummaryQueue where org_id = org_id_in;
        delete from rhnFileList where org_id = org_id_in;
        delete from rhnServerGroup where org_id = org_id_in;
        delete from rhn_check_suites where customer_id = org_id_in;
        delete from rhn_command_target where customer_id = org_id_in;
        delete from rhn_contact_groups where customer_id = org_id_in;
        delete from rhn_notification_formats where customer_id = org_id_in;
        delete from rhn_probe where customer_id = org_id_in;
        delete from rhn_redirects where customer_id = org_id_in;
        delete from rhn_sat_cluster where customer_id = org_id_in;
        delete from rhn_schedules where customer_id = org_id_in;
        delete from rhnContentSource where org_id = org_id_in;

        -- Delete the org.
        delete from web_customer where id = org_id_in;

    end;
    $$
    language plpgsql;


-- restore the original setting
update pg_settings set setting = overlay( setting placing '' from 1 for (length('rhn_org')+1) ) where name = 'search_path';
07070100000748000081B400000000000000000000000167AE111400000BA5000000000000000000000000000000000000006100000000susemanager-schema/upgrade/spacewalk-schema-1.7-to-spacewalk-schema-1.8/045-create_first_org.sql  
create or replace function
create_first_org
(
	name_in in varchar,
	password_in in varchar
)
returns void as
$$
declare
	ug_type			numeric;
	group_val		numeric;
begin
	insert into web_customer (
		id, name
	) values (
		1, name_in
	);

	select nextval( 'rhn_user_group_id_seq' ) into group_val from dual;

	select	id
	into	ug_type
	from	rhnUserGroupType
	where	label = 'org_admin';

	insert into rhnUserGroup (
		id, name,
		description,
		max_members, group_type, org_id
	) values (
		group_val, 'Organization Administrators',
		'Organization Administrators for Org ' || name_in || ' (1)',
		NULL, ug_type, 1
	);

	select nextval('rhn_user_group_id_seq') into group_val from dual;

	select	id
	into	ug_type
	from	rhnUserGroupType
	where	label = 'org_applicant';

	insert into rhnUserGroup (
		id, name,
		description,
		max_members, group_type, org_id
	) values (
		group_val, 'Organization Applicants',
		'Organization Applicants for Org ' || name_in || ' (1)',
		NULL, ug_type, 1
	);

	select nextval('rhn_user_group_id_seq') into group_val from dual;

	select	id
	into	ug_type
	from	rhnUserGroupType
	where	label = 'system_group_admin';

	insert into rhnUserGroup (
		id, name,
		description,
		max_members, group_type, org_id
	) values (
		group_val, 'System Group Administrators',
		'System Group Administrators for Org ' || name_in || ' (1)',
		NULL, ug_type, 1
	);


	select nextval('rhn_user_group_id_seq') into group_val from dual;

	select	id
	into	ug_type
	from	rhnUserGroupType
	where	label = 'activation_key_admin';

	insert into rhnUserGroup (
		id, name,
		description,
		max_members, group_type, org_id
	) values (
		group_val, 'Activation Key Administrators',
		'Activation Key Administrators for Org ' || name_in || ' (1)',
		NULL, ug_type, 1
	);

	-- config admin is special; it gets created in
	-- rhn_entitlements.set_customer_provisioning instead.

	select nextval('rhn_user_group_id_seq') into group_val from dual;

	select	id
	into	ug_type
	from	rhnUserGroupType
	where	label = 'channel_admin';

	insert into rhnUserGroup (
		id, name,
		description,
		max_members, group_type, org_id
	) values (
		group_val, 'Channel Administrators',
		'Channel Administrators for Org ' || name_in || ' (1)',
		NULL, ug_type, 1
	);

	select nextval('rhn_user_group_id_seq') into group_val from dual;

	select	id
	into	ug_type
	from	rhnUserGroupType
	where	label = 'satellite_admin';

	insert into rhnUserGroup (
		id, name,
		description,
		max_members, group_type, org_id
	) values (
		group_val, 'Satellite Administrators',
		'Satellite Administrators for Org ' || name_in || ' (1)',
		NULL, ug_type, 1
	);


	-- there aren't any users yet, so we don't need to update
	-- rhnUserServerPerms
        insert into rhnServerGroup 
		( id, name, description, max_members, group_type, org_id )
		select nextval('rhn_server_group_id_seq'), sgt.name, sgt.name, 
			0, sgt.id, 1
		from rhnServerGroupType sgt
		where sgt.label = 'sw_mgr_entitled';
		
end
$$ language plpgsql;

   07070100000749000081B400000000000000000000000167AE1114000000D0000000000000000000000000000000000000006500000000susemanager-schema/upgrade/spacewalk-schema-1.7-to-spacewalk-schema-1.8/046-rhnOrgQuota-triggers.sql  
DROP TRIGGER rhn_confrevision_acct_trig ON rhnConfigRevision;
DROP FUNCTION rhn_confrevision_acct_trig_fun();

DROP TRIGGER rhn_orgquota_mod_trig ON rhnOrgQuota;
DROP FUNCTION rhn_orgquote_mod_trig_fun();


0707010000074A000081B400000000000000000000000167AE111400000039000000000000000000000000000000000000005C00000000susemanager-schema/upgrade/spacewalk-schema-1.7-to-spacewalk-schema-1.8/047-rhnOrgQuota.sql   DROP INDEX rhn_orgquota_oid_uq;
DROP TABLE rhnOrgQuota;

   0707010000074B000081B400000000000000000000000167AE111400000033000000000000000000000000000000000000006E00000000susemanager-schema/upgrade/spacewalk-schema-1.7-to-spacewalk-schema-1.8/048-add_rhnPackage_installed_size.sql alter table rhnPackage add installed_size NUMERIC;
 0707010000074C000081B400000000000000000000000167AE111400000C71000000000000000000000000000000000000006C00000000susemanager-schema/upgrade/spacewalk-schema-1.7-to-spacewalk-schema-1.8/049-rhnPackageUpgradeArchCompat.sql   insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('noarch'), LOOKUP_PACKAGE_ARCH('armv7l'), current_timestamp, current_timestamp);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('armv7l'), LOOKUP_PACKAGE_ARCH('armv7l'), current_timestamp, current_timestamp);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('armv7l'), LOOKUP_PACKAGE_ARCH('noarch'), current_timestamp, current_timestamp);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('noarch'), LOOKUP_PACKAGE_ARCH('armv6l'), current_timestamp, current_timestamp);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('armv6l'), LOOKUP_PACKAGE_ARCH('armv6l'), current_timestamp, current_timestamp);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('armv6l'), LOOKUP_PACKAGE_ARCH('noarch'), current_timestamp, current_timestamp);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('noarch'), LOOKUP_PACKAGE_ARCH('armv5tel'), current_timestamp, current_timestamp);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('armv5tel'), LOOKUP_PACKAGE_ARCH('armv5tel'), current_timestamp, current_timestamp);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('armv5tel'), LOOKUP_PACKAGE_ARCH('noarch'), current_timestamp, current_timestamp);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('noarch'), LOOKUP_PACKAGE_ARCH('armv7hl'), current_timestamp, current_timestamp);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('armv7hl'), LOOKUP_PACKAGE_ARCH('armv7hl'), current_timestamp, current_timestamp);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('armv7hl'), LOOKUP_PACKAGE_ARCH('noarch'), current_timestamp, current_timestamp);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('noarch'), LOOKUP_PACKAGE_ARCH('armv7hnl'), current_timestamp, current_timestamp);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('armv7hnl'), LOOKUP_PACKAGE_ARCH('armv7hnl'), current_timestamp, current_timestamp);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('armv7hnl'), LOOKUP_PACKAGE_ARCH('noarch'), current_timestamp, current_timestamp);
   0707010000074D000081B400000000000000000000000167AE111400000577000000000000000000000000000000000000006B00000000susemanager-schema/upgrade/spacewalk-schema-1.7-to-spacewalk-schema-1.8/050-rhnServerPackageArchCompat.sql    insert into rhnServerPackageArchCompat
(server_arch_id, package_arch_id, preference) values
(LOOKUP_SERVER_ARCH('armv7l-redhat-linux'), LOOKUP_PACKAGE_ARCH('armv7hnl'), 0);

insert into rhnServerPackageArchCompat
(server_arch_id, package_arch_id, preference) values
(LOOKUP_SERVER_ARCH('armv7l-redhat-linux'), LOOKUP_PACKAGE_ARCH('armv7hl'), 10);

insert into rhnServerPackageArchCompat
(server_arch_id, package_arch_id, preference) values
(LOOKUP_SERVER_ARCH('armv7l-redhat-linux'), LOOKUP_PACKAGE_ARCH('armv7l'), 20);

insert into rhnServerPackageArchCompat
(server_arch_id, package_arch_id, preference) values
(LOOKUP_SERVER_ARCH('armv7l-redhat-linux'), LOOKUP_PACKAGE_ARCH('armv6l'), 30);

insert into rhnServerPackageArchCompat
(server_arch_id, package_arch_id, preference) values
(LOOKUP_SERVER_ARCH('armv7l-redhat-linux'), LOOKUP_PACKAGE_ARCH('armv5tel'), 40);

insert into rhnServerPackageArchCompat
(server_arch_id, package_arch_id, preference) values
(LOOKUP_SERVER_ARCH('armv7l-redhat-linux'), LOOKUP_PACKAGE_ARCH('noarch'), 1000);


insert into rhnServerPackageArchCompat
(server_arch_id, package_arch_id, preference) values
(LOOKUP_SERVER_ARCH('armv5tejl-redhat-linux'), LOOKUP_PACKAGE_ARCH('armv5tel'), 0);

insert into rhnServerPackageArchCompat
(server_arch_id, package_arch_id, preference) values
(LOOKUP_SERVER_ARCH('armv5tejl-redhat-linux'), LOOKUP_PACKAGE_ARCH('noarch'), 1000);
 0707010000074E000081B400000000000000000000000167AE111400000029000000000000000000000000000000000000007000000000susemanager-schema/upgrade/spacewalk-schema-1.7-to-spacewalk-schema-1.8/050-rhn_versioninfo_nid_eid_uq-drop.sql   
drop index rhn_versioninfo_nid_eid_uq;

   0707010000074F000081B400000000000000000000000167AE111400001335000000000000000000000000000000000000006000000000susemanager-schema/upgrade/spacewalk-schema-1.7-to-spacewalk-schema-1.8/051-rhn_channel.pkb.sql   --
--update pg_setting
update pg_settings set setting = 'rhn_channel,' || setting where name = 'search_path';

    -- Converts server channel_family to use a flex entitlement
    create or replace function convert_to_fve(server_id_in IN NUMERIC, channel_family_id_val IN NUMERIC)
    returns void
    as $$
    declare
        available_fve_subs      NUMERIC;
        server_org_id_val       NUMERIC;
    BEGIN

        --
        -- Use the org_id of the server only if the org_id of the channel = NULL.
        -- This is required for subscribing to shared channels.
        --
        SELECT org_id
          INTO server_org_id_val
          FROM rhnServer
         WHERE id = server_id_in;


        perform rhn_channel.obtain_read_lock(channel_family_id_val, server_org_id_val);
        if not found then
                perform rhn_exception.raise_exception('channel_family_no_subscriptions');
        end if;
        IF (rhn_channel.can_convert_to_fve(server_id_in, channel_family_id_val ) = 0)
            THEN
                perform rhn_exception.raise_exception('server_cannot_convert_to_flex');
        END IF;

        available_fve_subs := rhn_channel.available_fve_family_subs(channel_family_id_val, server_org_id_val);

        IF (available_fve_subs > 0)
        THEN

            insert into rhnServerHistory (id,server_id,summary,details) (
                select  nextval('rhn_event_id_seq'),
                        server_id_in,
                        'converted to flex entitlement' || SUBSTR(cf.label, 0, 99),
                        cf.label
                from    rhnChannelFamily cf
                where   cf.id = channel_family_id_val
            );

            UPDATE rhnServerChannel sc set is_fve = 'Y'
                           where sc.server_id = server_id_in and
                                 sc.channel_id in
                                    (select cfm.channel_id from rhnChannelFamilyMembers cfm
                                                where cfm.CHANNEL_FAMILY_ID = channel_family_id_val);

            perform rhn_channel.update_family_counts(channel_family_id_val, server_org_id_val);
        ELSE
            perform rhn_exception.raise_exception('not_enough_flex_entitlements');
        END IF;

    END$$ language plpgsql;

    drop function user_role_check_debug(channel_id_in in numeric,
                                   user_id_in in numeric,
                                   role_in in varchar,
                                   status out numeric,
                                   reason_out out varchar);

    create or replace function user_role_check_debug(channel_id_in in numeric,
                                   user_id_in in numeric,
                                   role_in in varchar)
    returns varchar
    as $$
    declare
        org_id numeric;
    begin
        org_id := rhn_user.get_org_id(user_id_in);

        -- channel might be shared
        if role_in = 'subscribe' and
           rhn_channel.shared_user_role_check(channel_id_in, user_id_in, role_in) = 1 then
            return NULL;
        end if;

        if role_in = 'manage' and
           COALESCE(rhn_channel.get_org_id(channel_id_in), -1) <> org_id then
               return 'channel_not_owned';
        end if;

        if role_in = 'subscribe' and
           rhn_channel.get_org_access(channel_id_in, org_id) = 0 then
                return 'channel_not_available';
        end if;

        -- channel admins have all roles
        if rhn_user.check_role_implied(user_id_in, 'channel_admin') = 1 then
            return NULL;
        end if;

        -- the subscribe permission is inferred
        -- UNLESS the not_globally_subscribable flag is set
        if role_in = 'subscribe'
        then
            if rhn_channel.org_channel_setting(channel_id_in,
                       org_id,
                       'not_globally_subscribable') = 0 then
                return NULL;
            end if;
        end if;

        -- all other roles (manage right now) are explicitly granted
        if rhn_channel.direct_user_role_check(channel_id_in,
                                              user_id_in, role_in) = 1 then
            return NULL;
        end if;
        return 'direct_permission';
    end$$ language plpgsql;

    -- same as above, but with 1/0 output; useful in views, etc
    create or replace function user_role_check(channel_id_in in numeric, user_id_in in numeric, role_in in varchar)
    returns numeric
    as $$
    begin
        if rhn_channel.user_role_check_debug(channel_id_in,
                                             user_id_in, role_in) is NULL then
            return 1;
        else
            return 0;
        end if;
    end$$ language plpgsql;

-- restore the original setting
update pg_settings set setting = overlay( setting placing '' from 1 for (length('rhn_channel')+1) ) where name = 'search_path';
   07070100000750000081B400000000000000000000000167AE11140000084D000000000000000000000000000000000000005700000000susemanager-schema/upgrade/spacewalk-schema-1.7-to-spacewalk-schema-1.8/055-armv6l.sql    insert into rhnCpuArch (id, label, name) values
(sequence_nextval('rhn_cpu_arch_id_seq'), 'armv6l', 'ARMv6l');

insert into rhnServerArch (id, label, name, arch_type_id) values
(sequence_nextval('rhn_server_arch_id_seq'), 'armv6l-redhat-linux', 'armv6l', lookup_arch_type('rpm'));

insert into rhnServerChannelArchCompat (server_arch_id, channel_arch_id) values
(LOOKUP_SERVER_ARCH('armv6l-redhat-linux'), LOOKUP_CHANNEL_ARCH('channel-arm'));

insert into rhnServerPackageArchCompat
(server_arch_id, package_arch_id, preference) values
(LOOKUP_SERVER_ARCH('armv6l-redhat-linux'), LOOKUP_PACKAGE_ARCH('armv6l'), 0);

insert into rhnServerPackageArchCompat
(server_arch_id, package_arch_id, preference) values
(LOOKUP_SERVER_ARCH('armv6l-redhat-linux'), LOOKUP_PACKAGE_ARCH('armv5tel'), 10);

insert into rhnServerPackageArchCompat
(server_arch_id, package_arch_id, preference) values
(LOOKUP_SERVER_ARCH('armv6l-redhat-linux'), LOOKUP_PACKAGE_ARCH('noarch'), 1000);

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
        values (lookup_server_arch('armv6l-redhat-linux'),
            lookup_sg_type('sw_mgr_entitled'));
insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
        values (lookup_server_arch('armv6l-redhat-linux'),
            lookup_sg_type('enterprise_entitled'));
insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
        values (lookup_server_arch('armv6l-redhat-linux'),
            lookup_sg_type('provisioning_entitled'));
insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
        values (lookup_server_arch('armv6l-redhat-linux'),
            lookup_sg_type('monitoring_entitled'));
insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
        values (lookup_server_arch('armv6l-redhat-linux'),
            lookup_sg_type('virtualization_host'));
insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
        values (lookup_server_arch('armv6l-redhat-linux'),
            lookup_sg_type('virtualization_host_platform'));
   07070100000751000081B400000000000000000000000167AE111400000022000000000000000000000000000000000000006B00000000susemanager-schema/upgrade/spacewalk-schema-1.7-to-spacewalk-schema-1.8/056-rhnRedHatCanonVersion-drop.sql    drop table rhnRedHatCanonVersion;
  07070100000752000081B400000000000000000000000167AE1114000004CB000000000000000000000000000000000000006C00000000susemanager-schema/upgrade/spacewalk-schema-1.7-to-spacewalk-schema-1.8/100-rhnActionImageDeploy_create.sql   --
-- Copyright (c) 2012 Novell
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

CREATE TABLE rhnActionImageDeploy
(
    id            NUMERIC NOT NULL
                  CONSTRAINT rhn_aid_id_pk PRIMARY KEY
                  ,
    action_id     NUMERIC NOT NULL
                      CONSTRAINT rhn_act_idp_act_fk
                      REFERENCES rhnAction (id)
                      ON DELETE CASCADE,
    vcpus         NUMERIC NOT NULL,
    mem_kb        NUMERIC NOT NULL,
    bridge_device VARCHAR(32),
    download_url  VARCHAR(256) NOT NULL,
    proxy_server  VARCHAR(64),
    proxy_user    VARCHAR(32),
    proxy_pass    VARCHAR(64)
)

;

CREATE SEQUENCE rhn_action_image_deploy_id_seq;
 07070100000753000081B400000000000000000000000167AE1114000002D7000000000000000000000000000000000000007200000000susemanager-schema/upgrade/spacewalk-schema-1.7-to-spacewalk-schema-1.8/101-rhnActionType_image-deploy_insert.sql --
-- Copyright (c) 2012 Novell
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

insert into rhnActionType values (500, 'image.deploy', 'Deploy an image to a virtual host.', 'N', 'N');
commit;
 07070100000754000081B400000000000000000000000167AE1114000004C3000000000000000000000000000000000000006B00000000susemanager-schema/upgrade/spacewalk-schema-1.7-to-spacewalk-schema-1.8/102-suseCredentialsType_create.sql    --
-- Copyright (c) 2012 Novell
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

CREATE TABLE suseCredentialsType
(
    id        NUMERIC NOT NULL
                  CONSTRAINT suse_credtype_id_pk PRIMARY KEY
                  ,
    label     VARCHAR(64) NOT NULL,
    name      VARCHAR(128) NOT NULL,
    created   TIMESTAMPTZ
                  DEFAULT (CURRENT_TIMESTAMP) NOT NULL,
    modified  TIMESTAMPTZ
                  DEFAULT (CURRENT_TIMESTAMP) NOT NULL
)

;

CREATE INDEX suse_credtype_label_id_idx
    ON suseCredentialsType (label, id)
    ;

CREATE SEQUENCE suse_credtype_id_seq;

ALTER TABLE suseCredentialsType
    ADD CONSTRAINT suse_credtype_label_uq UNIQUE (label);
 07070100000755000081B400000000000000000000000167AE1114000002F2000000000000000000000000000000000000006B00000000susemanager-schema/upgrade/spacewalk-schema-1.7-to-spacewalk-schema-1.8/103-suseCredentialsType_insert.sql    --
-- Copyright (c) 2012 Novell
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

insert into suseCredentialsType (id, label, name) values
	(sequence_nextval('suse_credtype_id_seq'), 'susestudio', 'SUSE Studio');
commit;
  07070100000756000081B400000000000000000000000167AE11140000051B000000000000000000000000000000000000006700000000susemanager-schema/upgrade/spacewalk-schema-1.7-to-spacewalk-schema-1.8/104-suseCredentials_create.sql    --
-- Copyright (c) 2012 Novell
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

CREATE TABLE suseCredentials
(
    id       NUMERIC NOT NULL
                 CONSTRAINT suse_credentials_pk PRIMARY KEY,
    user_id  NUMERIC NOT NULL
                 CONSTRAINT suse_credentials_user_fk
                 REFERENCES web_contact (id)
                 ON DELETE CASCADE,
    type_id  NUMERIC NOT NULL
                 CONSTRAINT suse_credentials_type_fk
                 REFERENCES suseCredentialsType (id),
    url      VARCHAR(256),
    username VARCHAR(64) NOT NULL,
    password VARCHAR(64) NOT NULL,
    created  TIMESTAMPTZ DEFAULT (CURRENT_TIMESTAMP) NOT NULL,
    modified TIMESTAMPTZ DEFAULT (CURRENT_TIMESTAMP) NOT NULL
)

;

CREATE SEQUENCE suse_credentials_id_seq;
 07070100000757000081B400000000000000000000000167AE111400000060000000000000000000000000000000000000006900000000susemanager-schema/upgrade/spacewalk-schema-1.7-to-spacewalk-schema-1.8/105-rhnXccdfRuleresult-index.sql  CREATE INDEX rhn_xccdf_rresult_tresult_idx
    ON rhnXccdfRuleresult (testresult_id)
    
    ;
07070100000758000081B400000000000000000000000167AE111400000057000000000000000000000000000000000000006B00000000susemanager-schema/upgrade/spacewalk-schema-1.7-to-spacewalk-schema-1.8/106-rhnXccdfRuleIdentMap-index.sql    CREATE INDEX rhn_xccdf_rim_ident_idx
    ON rhnXccdfRuleIdentMap (ident_id)
    
    ;
 07070100000759000081B400000000000000000000000167AE11140000004C000000000000000000000000000000000000006900000000susemanager-schema/upgrade/spacewalk-schema-1.7-to-spacewalk-schema-1.8/107-rhnServerGroupNotes-drop.sql  
drop table rhnServerGroupNotes;

drop sequence rhn_servergrp_note_id_seq;

0707010000075A000081B400000000000000000000000167AE111400000035000000000000000000000000000000000000007700000000susemanager-schema/upgrade/spacewalk-schema-1.7-to-spacewalk-schema-1.8/108-rhn_servergroup_note_mod_trig_fun-drop.sql    
drop function rhn_servergroup_note_mod_trig_fun();

   0707010000075B000081B400000000000000000000000167AE111400000041000000000000000000000000000000000000007F00000000susemanager-schema/upgrade/spacewalk-schema-1.7-to-spacewalk-schema-1.8/109-rhnactionkickstartguest_mac_address_column_add.sql    alter table rhnactionkickstartguest add mac_address VARCHAR(17);
   0707010000075C000081B400000000000000000000000167AE11140000077F000000000000000000000000000000000000005B00000000susemanager-schema/upgrade/spacewalk-schema-1.7-to-spacewalk-schema-1.8/110-lookup_evr.sql    --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.

create or replace function
lookup_evr(e_in in varchar, v_in in varchar, r_in in varchar)
returns numeric
as
$$
declare
    evr_id  numeric;
begin
    select id
      into evr_id
      from rhnPackageEVR
     where ((epoch is null and e_in is null) or (epoch = e_in)) and
           version = v_in and
           release = r_in;
            
    if not found then
        evr_id := nextval('rhn_pkg_evr_seq');
        declare
            e_text varchar = coalesce(quote_literal(e_in), 'NULL');
            v_text varchar = coalesce(quote_literal(v_in), 'NULL');
            r_text varchar = coalesce(quote_literal(r_in), 'NULL');
        begin
            perform pg_dblink_exec(
                'insert into rhnPackageEVR(id, epoch, version, release, evr) values (' ||
                evr_id || ', ' || e_text || ', ' || v_text || ', ' || r_text
		|| ', evr_t(' || e_text || ', ' || v_text || ', ' || r_text || '))'
            );
        exception when unique_violation then
            select id
              into strict evr_id
              from rhnPackageEVR
             where ((epoch is null and e_in is null) or (epoch = e_in)) and
                   version = v_in and
                   release = r_in;
        end;
    end if;

    return evr_id;
end;
$$ language plpgsql immutable;
 0707010000075D000081B400000000000000000000000167AE111400000426000000000000000000000000000000000000006300000000susemanager-schema/upgrade/spacewalk-schema-1.7-to-spacewalk-schema-1.8/111-rhnAbrtInfo_create.sql    --
-- Copyright (c) 2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

CREATE TABLE rhnAbrtInfo
(
    id             NUMERIC NOT NULL
                        CONSTRAINT rhn_abrt_info_pk PRIMARY KEY,
    server_id      NUMERIC NOT NULL
                       CONSTRAINT rhn_abrt_info_srvr_fk
                           REFERENCES rhnServer (id)
                           ON DELETE CASCADE,
    num_crashes    NUMERIC NOT NULL,
    created        TIMESTAMPTZ NOT NULL
)

;

CREATE SEQUENCE rhn_abrt_info_id_seq;
  0707010000075E000081B400000000000000000000000167AE111400000462000000000000000000000000000000000000005F00000000susemanager-schema/upgrade/spacewalk-schema-1.7-to-spacewalk-schema-1.8/112-pg_dblink_exec.sql    -- oracle equivalent source none
--
-- Copyright (c) 2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.

create or replace function pg_dblink_exec(in_sql in varchar) returns void as
$$
begin
    if in_sql is null then
	raise 'pg_dblink_exec in_sql is null';
    end if;
    perform dblink_connect('at_conn', 'dbname=' || current_database());
    begin
        perform dblink_exec('at_conn', in_sql, true);
    exception when others then
        perform dblink_disconnect('at_conn');
        raise;
    end;
    perform dblink_disconnect('at_conn');
end;
$$
language plpgsql;
  0707010000075F000081B400000000000000000000000167AE1114000009AC000000000000000000000000000000000000006B00000000susemanager-schema/upgrade/spacewalk-schema-1.7-to-spacewalk-schema-1.8/113-lookup_transaction_package.sql    --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 

create or replace function
lookup_transaction_package(
    o_in in varchar,
    n_in in varchar,
    e_in in varchar,
    v_in in varchar,
    r_in in varchar,
    a_in in varchar)
returns numeric
as
$$
declare
    o_id        numeric;
    n_id        numeric;
    e_id        numeric;
    p_arch_id   numeric;
    tp_id       numeric;
begin
    select id
      into o_id
      from rhnTransactionOperation
     where label = o_in;

    if not found then
        perform rhn_exception.raise_exception('invalid_transaction_operation');
    end if;

    n_id := lookup_package_name(n_in);
    e_id := lookup_evr(e_in, v_in, r_in);
    p_arch_id := null;

    if a_in is not null then
        p_arch_id := lookup_package_arch(a_in);
    end if;

    select id
      into tp_id
      from rhnTransactionPackage
     where operation = o_id and
           name_id = n_id and
           evr_id = e_id and
           (package_arch_id = p_arch_id or (p_arch_id is null and package_arch_id is null));

    if not found then
        tp_id := nextval('rhn_transpack_id_seq');
        begin
            perform pg_dblink_exec(
                'insert into rhnTransactionPackage (id, operation, name_id, evr_id, package_arch_id)' ||
                ' values (' || tp_id || ', ' || o_id || ', ' || n_id || ', ' || e_id ||
                ', ' || ( case when p_arch_id is null then 'NULL' else p_arch_id::varchar end )  || ')');
        exception when unique_violation then
            select id
              into strict tp_id
              from rhnTransactionPackage
             where operation = o_id and
                   name_id = n_id and
                   evr_id = e_id and
                   (package_arch_id = p_arch_id or (p_arch_id is null and package_arch_id is null));
        end;
    end if;

    return tp_id;
end;
$$
language plpgsql immutable;
07070100000760000081B400000000000000000000000167AE111400000158000000000000000000000000000000000000006F00000000susemanager-schema/upgrade/spacewalk-schema-1.7-to-spacewalk-schema-1.8/114-rhnUserGroupType_rhn_superuser.sql    DELETE FROM rhnUserGroupMembers WHERE user_group_id IN (SELECT g.id from rhnUserGroup g JOIN rhnUserGroupType gt ON g.group_type = gt.id WHERE gt.label = 'rhn_superuser');

DELETE FROM rhnUserGroup WHERE group_type IN (SELECT id FROM rhnUserGroupType WHERE label = 'rhn_superuser');

DELETE FROM rhnUserGroupType WHERE label = 'rhn_superuser';
07070100000761000081B400000000000000000000000167AE111400000152000000000000000000000000000000000000006D00000000susemanager-schema/upgrade/spacewalk-schema-1.7-to-spacewalk-schema-1.8/115-rhnUserGroupType_rhn_support.sql  DELETE FROM rhnUserGroupMembers WHERE user_group_id IN (SELECT g.id from rhnUserGroup g JOIN rhnUserGroupType gt ON g.group_type = gt.id WHERE gt.label = 'rhn_support');

DELETE FROM rhnUserGroup WHERE group_type IN (SELECT id FROM rhnUserGroupType WHERE label = 'rhn_support');

DELETE FROM rhnUserGroupType WHERE label = 'rhn_support';
  07070100000762000081B400000000000000000000000167AE11140000014F000000000000000000000000000000000000006C00000000susemanager-schema/upgrade/spacewalk-schema-1.7-to-spacewalk-schema-1.8/116-rhnUserGroupType_cert_admin.sql   DELETE FROM rhnUserGroupMembers WHERE user_group_id IN (SELECT g.id from rhnUserGroup g JOIN rhnUserGroupType gt ON g.group_type = gt.id WHERE gt.label = 'cert_admin');

DELETE FROM rhnUserGroup WHERE group_type IN (SELECT id FROM rhnUserGroupType WHERE label = 'cert_admin');

DELETE FROM rhnUserGroupType WHERE label = 'cert_admin';
 07070100000763000081B400000000000000000000000167AE11140000003C000000000000000000000000000000000000006200000000susemanager-schema/upgrade/spacewalk-schema-1.7-to-spacewalk-schema-1.8/117-is_user_applicant.sql --

DROP FUNCTION is_user_applicant(user_id_in IN numeric);
07070100000764000081B400000000000000000000000167AE111400000CEC000000000000000000000000000000000000006100000000susemanager-schema/upgrade/spacewalk-schema-1.7-to-spacewalk-schema-1.8/118-create_first_org.sql  --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--
--
-- This creates an org with ID of 1, and errors if there already is one
--

create or replace function
create_first_org
(
	name_in in varchar,
	password_in in varchar
)
returns void as
$$
declare
	ug_type			numeric;
	group_val		numeric;
begin
	insert into web_customer (
		id, name
	) values (
		1, name_in
	);

	select nextval( 'rhn_user_group_id_seq' ) into group_val from dual;

	select	id
	into	ug_type
	from	rhnUserGroupType
	where	label = 'org_admin';

	insert into rhnUserGroup (
		id, name,
		description,
		max_members, group_type, org_id
	) values (
		group_val, 'Organization Administrators',
		'Organization Administrators for Org ' || name_in || ' (1)',
		NULL, ug_type, 1
	);

	select nextval('rhn_user_group_id_seq') into group_val from dual;

	select	id
	into	ug_type
	from	rhnUserGroupType
	where	label = 'system_group_admin';

	insert into rhnUserGroup (
		id, name,
		description,
		max_members, group_type, org_id
	) values (
		group_val, 'System Group Administrators',
		'System Group Administrators for Org ' || name_in || ' (1)',
		NULL, ug_type, 1
	);


	select nextval('rhn_user_group_id_seq') into group_val from dual;

	select	id
	into	ug_type
	from	rhnUserGroupType
	where	label = 'activation_key_admin';

	insert into rhnUserGroup (
		id, name,
		description,
		max_members, group_type, org_id
	) values (
		group_val, 'Activation Key Administrators',
		'Activation Key Administrators for Org ' || name_in || ' (1)',
		NULL, ug_type, 1
	);

	-- config admin is special; it gets created in
	-- rhn_entitlements.set_customer_provisioning instead.

	select nextval('rhn_user_group_id_seq') into group_val from dual;

	select	id
	into	ug_type
	from	rhnUserGroupType
	where	label = 'channel_admin';

	insert into rhnUserGroup (
		id, name,
		description,
		max_members, group_type, org_id
	) values (
		group_val, 'Channel Administrators',
		'Channel Administrators for Org ' || name_in || ' (1)',
		NULL, ug_type, 1
	);

	select nextval('rhn_user_group_id_seq') into group_val from dual;

	select	id
	into	ug_type
	from	rhnUserGroupType
	where	label = 'satellite_admin';

	insert into rhnUserGroup (
		id, name,
		description,
		max_members, group_type, org_id
	) values (
		group_val, 'Satellite Administrators',
		'Satellite Administrators for Org ' || name_in || ' (1)',
		NULL, ug_type, 1
	);


	-- there aren't any users yet, so we don't need to update
	-- rhnUserServerPerms
        insert into rhnServerGroup
		( id, name, description, max_members, group_type, org_id )
		select nextval('rhn_server_group_id_seq'), sgt.name, sgt.name,
			0, sgt.id, 1
		from rhnServerGroupType sgt
		where sgt.label = 'sw_mgr_entitled';

end
$$ language plpgsql;
07070100000765000081B400000000000000000000000167AE111400000F47000000000000000000000000000000000000005F00000000susemanager-schema/upgrade/spacewalk-schema-1.7-to-spacewalk-schema-1.8/119-create_new_org.sql    --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

create or replace function create_new_org
(
        name_in      in varchar,
        password_in  in varchar
        --org_id_out   out NUMERIC
) returns numeric
as
$$
declare
        ug_type                 numeric;
        group_val               numeric;
        new_org_id              numeric;
        org_id_out		numeric;
begin

        select nextval('web_customer_id_seq') into new_org_id;

        insert into web_customer (
                id, name
        ) values (
                new_org_id, name_in
        );

        select nextval('rhn_user_group_id_seq') into group_val;

        select  id
        into    ug_type
        from    rhnUserGroupType
        where   label = 'org_admin';

        insert into rhnUserGroup (
                id, name,
                description,
                max_members, group_type, org_id
        ) values (
                group_val, 'Organization Administrators',
                'Organization Administrators for Org ' || name_in,
                NULL, ug_type, new_org_id
        );

        select nextval('rhn_user_group_id_seq') into group_val;

        select  id
        into    ug_type
        from    rhnUserGroupType
        where   label = 'system_group_admin';

        insert into rhnUserGroup (
                id, name,
                description,
                max_members, group_type, org_id
        ) values (
                group_val, 'System Group Administrators',
                'System Group Administrators for Org ' || name_in,
                NULL, ug_type, new_org_id
        );


        select nextval('rhn_user_group_id_seq') into group_val;

        select  id
        into    ug_type
        from    rhnUserGroupType
        where   label = 'activation_key_admin';

        insert into rhnUserGroup (
                id, name,
                description,
                max_members, group_type, org_id
        ) values (
                group_val, 'Activation Key Administrators',
                'Activation Key Administrators for Org ' || name_in,
                NULL, ug_type, new_org_id
        );

        -- config admin is special; it gets created in
        -- rhn_entitlements.set_customer_provisioning instead.

        select nextval('rhn_user_group_id_seq') into group_val;

        select  id
        into    ug_type
        from    rhnUserGroupType
        where   label = 'channel_admin';

        insert into rhnUserGroup (
                id, name,
                description,
                max_members, group_type, org_id
        ) values (
                group_val, 'Channel Administrators',
                'Channel Administrators for Org ' || name_in,
                NULL, ug_type, new_org_id
        );

        -- there aren't any users yet, so we don't need to update
        -- rhnUserServerPerms
        insert into rhnServerGroup
                ( id, name, description, max_members, group_type, org_id )
                select nextval('rhn_server_group_id_seq'), sgt.name, sgt.name,
                        0, sgt.id, new_org_id
                from rhnServerGroupType sgt
                where sgt.label = 'sw_mgr_entitled';

        org_id_out := new_org_id;

	-- Returning the value of OUT parameter
        return org_id_out;

end;
$$
language plpgsql;
 07070100000766000081B400000000000000000000000167AE1114000016BA000000000000000000000000000000000000006500000000susemanager-schema/upgrade/spacewalk-schema-1.7-to-spacewalk-schema-1.8/120-rhn_entitlements.pkb.sql  --
-- setup search_path so that these functions are created in appropriate schema.
update pg_settings set setting = 'rhn_entitlements,' || setting where name = 'search_path';

    -- this desperately needs to be table driven.
    create or replace function modify_org_service (
        org_id_in in numeric,
        service_label_in in varchar,
        enable_in in char
    ) returns void
as $$
    declare
        roles_to_process varchar[];
        roles cursor(role_label_in varchar) for
            select  label, id
            from    rhnUserGroupType
            where   label = role_label_in;
        org_roles cursor(role_label_in varchar) for
            select  1
            from    rhnUserGroup ug,
                    rhnUserGroupType ugt
            where   ugt.label = role_label_in
                and ug.org_id = org_id_in
                and ugt.id = ug.group_type;

        ents_to_process varchar[];
        ents cursor(ent_label_in varchar) for
            select  label, id
            from    rhnOrgEntitlementType
            where   label = ent_label_in;
        org_ents cursor(ent_label_in varchar) for
            select  1
            from    rhnOrgEntitlements oe,
                    rhnOrgEntitlementType oet
            where   oet.label = ent_label_in
                and oe.org_id = org_id_in
                and oet.id = oe.entitlement_id;
        create_row char(1);
    begin
        ents_to_process := '{}';
        roles_to_process := '{}';
        -- a bit kludgy, but only for 3.4 really.  Certainly no
        -- worse than the old code...
        if service_label_in = 'enterprise' or
           service_label_in = 'management' then
            ents_to_process := array_append(ents_to_process, 'sw_mgr_enterprise');

            roles_to_process := array_append(roles_to_process, 'org_admin');

            roles_to_process := array_append(roles_to_process, 'system_group_admin');

            roles_to_process := array_append(roles_to_process, 'activation_key_admin');
        elsif service_label_in = 'provisioning' then
            ents_to_process := array_append(ents_to_process, 'rhn_provisioning');

            roles_to_process := array_append(roles_to_process, 'system_group_admin');

            roles_to_process := array_append(roles_to_process, 'activation_key_admin');

            roles_to_process := array_append(roles_to_process, 'config_admin');
            -- another nasty special case...
            if enable_in = 'Y' then
                ents_to_process := array_append(ents_to_process, 'sw_mgr_enterprise');
            end if;
        elsif service_label_in = 'monitoring' then
            ents_to_process := array_append(ents_to_process, 'rhn_monitor');

            roles_to_process := array_append(roles_to_process, 'monitoring_admin');
        elsif service_label_in = 'virtualization' then
            ents_to_process := array_append(ents_to_process, 'rhn_virtualization');

            roles_to_process := array_append(roles_to_process, 'config_admin');
        elsif service_label_in = 'virtualization_platform' then
            ents_to_process := array_append(ents_to_process, 'rhn_virtualization_platform');
            roles_to_process := array_append(roles_to_process, 'config_admin');
    elsif service_label_in = 'nonlinux' then
            ents_to_process := array_append(ents_to_process, 'rhn_nonlinux');
            roles_to_process := array_append(roles_to_process, 'config_admin');
        end if;

        if enable_in = 'Y' then
            for i in 1..array_upper(ents_to_process, 1) loop
                for ent in ents(ents_to_process[i]) loop
                    create_row := 'Y';
                    for oe in org_ents(ent.label) loop
                        create_row := 'N';
                    end loop;
                    if create_row = 'Y' then
                        insert into rhnOrgEntitlements(org_id, entitlement_id)
                            values (org_id_in, ent.id);
                    end if;
                end loop;
            end loop;
            for i in 1..array_upper(roles_to_process, 1) loop
                for role in roles(roles_to_process[i]) loop
                    create_row := 'Y';
                    for o_r in org_roles(role.label) loop
                        create_row := 'N';
                    end loop;
                    if create_row = 'Y' then
                        insert into rhnUserGroup(
                                id, name, description, current_members,
                                group_type, org_id
                            ) (
                                select  nextval('rhn_user_group_id_seq'),
                                        ugt.name || 's',
                                        ugt.name || 's for Org ' ||
                                            o.name || ' ('|| o.id ||')',
                                        0, ugt.id, o.id
                                from    rhnUserGroupType ugt,
                                        web_customer o
                                where   o.id = org_id_in
                                    and ugt.id = role.id
                            );
                    end if;
                end loop;
            end loop;
        else
            for i in 1..coalesce(array_upper(ents_to_process, 1), 0) loop
                for ent in ents(ents_to_process[i]) loop
                    delete from rhnOrgEntitlements
                     where org_id = org_id_in
                       and entitlement_id = ent.id;
                end loop;
            end loop;
        end if;
    end$$
language plpgsql;

-- restore the original setting
update pg_settings set setting = overlay( setting placing '' from 1 for (length('rhn_entitlements')+1) ) where name = 'search_path';
  07070100000767000081B400000000000000000000000167AE11140000006B000000000000000000000000000000000000006C00000000susemanager-schema/upgrade/spacewalk-schema-1.7-to-spacewalk-schema-1.8/121-rhnUserGroupMembers-trigger.sql   --

DROP TRIGGER rhn_ugm_applicant_fix ON rhnUserGroupMembers;

DROP FUNCTION rhn_ugm_applicant_fix_fun();
 07070100000768000081B400000000000000000000000167AE111400000158000000000000000000000000000000000000006F00000000susemanager-schema/upgrade/spacewalk-schema-1.7-to-spacewalk-schema-1.8/122-rhnUserGroupType_org_applicant.sql    DELETE FROM rhnUserGroupMembers WHERE user_group_id IN (SELECT g.id from rhnUserGroup g JOIN rhnUserGroupType gt ON g.group_type = gt.id WHERE gt.label = 'org_applicant');

DELETE FROM rhnUserGroup WHERE group_type IN (SELECT id FROM rhnUserGroupType WHERE label = 'org_applicant');

DELETE FROM rhnUserGroupType WHERE label = 'org_applicant';
07070100000769000081B400000000000000000000000167AE1114000007C5000000000000000000000000000000000000006C00000000susemanager-schema/upgrade/spacewalk-schema-1.7-to-spacewalk-schema-1.8/123-rhnChannelNewestPackageView.sql   --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--
--
--
--
-- this is much more readable with ts=4, enjoy!

create or replace view
rhnChannelNewestPackageView
as
SELECT channel_id,
       name_id,
       evr_id,
       package_arch_id,
       max(package_id) as package_id
FROM (
       SELECT m.channel_id          as channel_id,
              p.name_id             as name_id,
              p.evr_id              as evr_id,
              m.package_arch_id     as package_arch_id,
              p.id                  as package_id
         FROM
              (select max(pe.evr) AS max_evr,
                      cp.channel_id,
                      p.name_id,
                      p.package_arch_id
                 from rhnPackageEVR       pe,
                      rhnPackage          p,
                      rhnChannelPackage   cp
                where p.evr_id = pe.id
                  and cp.package_id = p.id
                group by cp.channel_id, p.name_id, p.package_arch_id) m,
              rhnPackageEVR       pe,
              rhnPackage          p,
              rhnChannelPackage   chp
        WHERE m.max_evr = pe.evr
          AND m.name_id = p.name_id
          AND m.package_arch_id = p.package_arch_id
          AND p.evr_id = pe.id
          AND chp.package_id = p.id
          AND chp.channel_id = m.channel_id
) latest_packages
group by channel_id, name_id, evr_id, package_arch_id
;
   0707010000076A000081B400000000000000000000000167AE111400000486000000000000000000000000000000000000006300000000susemanager-schema/upgrade/spacewalk-schema-1.7-to-spacewalk-schema-1.8/124-create_pxt_session.sql    --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--
--
--
--

create or replace function
create_pxt_session(p_web_user_id in numeric, p_expires in numeric, p_value in varchar)
returns numeric as $$
declare
	l_id numeric;
begin
    l_id := nextval( 'pxt_id_seq' );

    perform pg_dblink_exec(
        'insert into PXTSessions (id, value, expires, web_user_id) values (' ||
        l_id || ', ' || coalesce(quote_literal(p_value), 'NULL') ||
        ', ' || p_expires || ', ' || coalesce(quote_literal(p_web_user_id), 'NULL') || '); commit');

	return l_id;
end;
$$ language plpgsql;
  0707010000076B000081B400000000000000000000000167AE111400000290000000000000000000000000000000000000007100000000susemanager-schema/upgrade/spacewalk-schema-1.7-to-spacewalk-schema-1.8/125-rhn_channel-obtain_read_lock.pkb.sql  
--update pg_setting
update pg_settings set setting = 'rhn_channel,' || setting where name = 'search_path';

    create or replace function obtain_read_lock(channel_family_id_in in numeric, org_id_in in numeric)
    returns void as $$
    declare
        read_lock timestamptz;
    begin
        select created into read_lock
          from rhnPrivateChannelFamily
         where channel_family_id = channel_family_id_in and org_id = org_id_in
           for update;
    end$$ language plpgsql;

-- restore the original setting
update pg_settings set setting = overlay( setting placing '' from 1 for (length('rhn_channel')+1) ) where name = 'search_path';
0707010000076C000081B400000000000000000000000167AE11140000005E000000000000000000000000000000000000007200000000susemanager-schema/upgrade/spacewalk-schema-1.7-to-spacewalk-schema-1.8/126-rhn_command-command_class-default.sql 
alter table rhn_command
alter command_class set default '/var/lib/nocpulse/libexec/plugin';

  0707010000076D000081B400000000000000000000000167AE111400000045000000000000000000000000000000000000006D00000000susemanager-schema/upgrade/spacewalk-schema-1.7-to-spacewalk-schema-1.8/127-rhnPackageCapability-version.sql  
alter table rhnPackageCapability alter version type varchar(512) ;

   0707010000076E000081B400000000000000000000000167AE1114000000D6000000000000000000000000000000000000006200000000susemanager-schema/upgrade/spacewalk-schema-1.7-to-spacewalk-schema-1.8/131-rhnPackage-common.sql 
alter table rhnpackage alter compat type numeric(1) ;

alter table rhnpackage drop constraint rhn_package_compat_check;
alter table rhnpackage add constraint rhn_package_compat_check CHECK (compat in ( 1 , 0 ));

  0707010000076F000081B400000000000000000000000167AE111400000283000000000000000000000000000000000000007500000000susemanager-schema/upgrade/spacewalk-schema-1.7-to-spacewalk-schema-1.8/133-rhn_host_monitoring-last_update_date.sql  
drop view rhn_host_monitoring;
create view rhn_host_monitoring
(
        recid,
        ip,
        name,
        description,
        customer_id,
        os_id,
        asset_id,
        last_update_user,
        last_update_date
) as
select  s.id            as recid,
        rhn_server.get_ip_address(s.id) as ip,
        s.name          as name,
        s.description   as description,
        s.org_id        as customer_id,
        4               as os_id,
        to_number(null,null) as asset_id,
        cast(null as char)   as last_update_user,
        cast(null as TIMESTAMPTZ)   as last_update_date
from    rhnServer       s
;

 07070100000770000081B400000000000000000000000167AE111400000036000000000000000000000000000000000000006200000000susemanager-schema/upgrade/spacewalk-schema-1.7-to-spacewalk-schema-1.8/136-date_diff_in_days.sql 
drop function date_diff_in_days(TIMESTAMPTZ, date);

  07070100000771000081B400000000000000000000000167AE11140000070D000000000000000000000000000000000000006F00000000susemanager-schema/upgrade/spacewalk-schema-1.7-to-spacewalk-schema-1.8/138-rhn_prepare_install-timestamps.sql    --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--

--monitoring stored procedure

create or replace function
rhn_prepare_install
(
    username            in rhn_command_queue_instances.last_update_user%type,
    install_command     in rhn_command_queue_instances.command_id%type
)
returns rhn_command_queue_instances.recid%type
as $$
declare
    command_instance_id rhn_command_queue_instances.recid%type;
begin
    select nextval('rhn_command_q_inst_recid_seq')
    into command_instance_id;
    

    insert into rhn_command_queue_instances (
        recid,
        command_id,
        notes,
        expiration_date,
        notify_email,
        timeout,
        date_submitted,
        last_update_user,
        last_update_date
    )
    values (
        command_instance_id,
        install_command,
        null, /* no notes */
        /* ignore this command if it has not been run after ten minutes */
        current_timestamp + '10 minute'::interval,
        null, /* no notification email */
        /* should take no more than five minutes to run the install */
        600,
        current_timestamp,
        username,
        current_timestamp
    );

    return command_instance_id;
end; $$
language plpgsql;
   07070100000772000081B400000000000000000000000167AE111400000508000000000000000000000000000000000000006200000000susemanager-schema/upgrade/spacewalk-schema-1.7-to-spacewalk-schema-1.8/142-suse-package-keys.sql 
update rhnPackageKey set provider_id = lookup_package_provider('Suse')
 where key_id = 'e3a5c360307e3d54';
update rhnPackageKey set provider_id = lookup_package_provider('Suse')
 where key_id = '6c74ce73b37b98a9';
update rhnPackageKey set provider_id = lookup_package_provider('Suse')
 where key_id = '8055f0400182b964';


insert into rhnPackageKey (id, key_id, key_type_id, provider_id)
    (select sequence_nextval('rhn_pkey_id_seq'), 'e3a5c360307e3d54', lookup_package_key_type('gpg'), lookup_package_provider('Suse') from dual
     where not exists (select 1 from rhnPackageKey where key_id = 'e3a5c360307e3d54'));
insert into rhnPackageKey (id, key_id, key_type_id, provider_id)
    (select sequence_nextval('rhn_pkey_id_seq'), '6c74ce73b37b98a9', lookup_package_key_type('gpg'), lookup_package_provider('Suse') from dual
     where not exists (select 1 from rhnPackageKey where key_id = '6c74ce73b37b98a9'));
insert into rhnPackageKey (id, key_id, key_type_id, provider_id)
    (select sequence_nextval('rhn_pkey_id_seq'), '8055f0400182b964', lookup_package_key_type('gpg'), lookup_package_provider('Suse') from dual
     where not exists (select 1 from rhnPackageKey where key_id = '8055f0400182b964'));


update rhnPackageProvider set name = 'SUSE' where name = 'Suse';

commit;
07070100000773000081B400000000000000000000000167AE111400000705000000000000000000000000000000000000006400000000susemanager-schema/upgrade/spacewalk-schema-1.7-to-spacewalk-schema-1.8/143-novell-package-keys.sql   
insert into rhnPackageProvider (id, name) values
(sequence_nextval('rhn_package_provider_id_seq'), 'Novell Inc.' );

update rhnPackageKey set provider_id = lookup_package_provider('Novell Inc.')
 where key_id = '2afe16421d061a62';
update rhnPackageKey set provider_id = lookup_package_provider('Novell Inc.')
 where key_id = '14c28bc97e2e3b05';
update rhnPackageKey set provider_id = lookup_package_provider('Novell Inc.')
 where key_id = '478a32e8a1912208';
update rhnPackageKey set provider_id = lookup_package_provider('Novell Inc.')
 where key_id = '73d25d630dfb3188';

insert into rhnPackageKey (id, key_id, key_type_id, provider_id)
    (select sequence_nextval('rhn_pkey_id_seq'), '2afe16421d061a62', lookup_package_key_type('gpg'), lookup_package_provider('Novell Inc.') from dual
     where not exists (select 1 from rhnPackageKey where key_id = '2afe16421d061a62'));
insert into rhnPackageKey (id, key_id, key_type_id, provider_id)
    (select sequence_nextval('rhn_pkey_id_seq'), '14c28bc97e2e3b05', lookup_package_key_type('gpg'), lookup_package_provider('Novell Inc.') from dual
     where not exists (select 1 from rhnPackageKey where key_id = '14c28bc97e2e3b05'));
insert into rhnPackageKey (id, key_id, key_type_id, provider_id)
    (select sequence_nextval('rhn_pkey_id_seq'), '478a32e8a1912208', lookup_package_key_type('gpg'), lookup_package_provider('Novell Inc.') from dual
     where not exists (select 1 from rhnPackageKey where key_id = '478a32e8a1912208'));
insert into rhnPackageKey (id, key_id, key_type_id, provider_id)
    (select sequence_nextval('rhn_pkey_id_seq'), '73d25d630dfb3188', lookup_package_key_type('gpg'), lookup_package_provider('Novell Inc.') from dual
     where not exists (select 1 from rhnPackageKey where key_id = '73d25d630dfb3188'));


commit;
   07070100000774000081B400000000000000000000000167AE111400000190000000000000000000000000000000000000006100000000susemanager-schema/upgrade/spacewalk-schema-1.7-to-spacewalk-schema-1.8/144-rhnTimezone-data.sql  insert into rhnTimezone (id, olson_name, display_name) (
    select sequence_nextval('rhn_timezone_id_seq'),
           'Africa/Johannesburg',
           'South Africa (Johannesburg)'
      from dual
     where not exists (
           select 1
             from rhnTimezone
            where olson_name = 'Africa/Johannesburg'
              and display_name = 'South Africa (Johannesburg)'
     )
);
07070100000775000081B400000000000000000000000167AE111400000342000000000000000000000000000000000000006200000000susemanager-schema/upgrade/spacewalk-schema-1.7-to-spacewalk-schema-1.8/145-rhnDistChannelMap.sql 
ALTER TABLE rhnDistChannelMap ADD org_id NUMERIC;
ALTER TABLE rhnDistChannelMap ADD CONSTRAINT rhn_dcm_oid_fk FOREIGN KEY (org_id) REFERENCES web_customer (id) ON DELETE CASCADE;
DROP INDEX if exists rhn_dcm_os_release_caid_idx;
ALTER TABLE rhnDistChannelMap DROP CONSTRAINT rhn_dcm_os_release_caid_uq;

delete
 from rhnDistChannelMap
where channel_id in (
      select id
        from rhnChannel
       where parent_channel is not null);

ALTER TABLE rhnDistChannelMap ADD CONSTRAINT rhn_dcm_release_caid_oid_uq UNIQUE (release, channel_arch_id, org_id);

ALTER TABLE rhnDistChannelMap ADD id NUMERIC;
CREATE SEQUENCE rhn_dcm_id_seq;
UPDATE rhnDistChannelMap SET id = nextval('rhn_dcm_id_seq');
ALTER TABLE rhnDistChannelMap ALTER COLUMN id SET NOT NULL;
ALTER TABLE rhnDistChannelMap ADD CONSTRAINT rhn_dcm_id_pk PRIMARY KEY (id);
  07070100000776000081B400000000000000000000000167AE1114000001A8000000000000000000000000000000000000006600000000susemanager-schema/upgrade/spacewalk-schema-1.7-to-spacewalk-schema-1.8/145-spacewalk-package-key.sql 
update rhnPackageKey set provider_id = lookup_package_provider('Spacewalk')
 where key_id = '0e646f68863a853d';

insert into rhnPackageKey (id, key_id, key_type_id, provider_id)
    (select sequence_nextval('rhn_pkey_id_seq'), '0e646f68863a853d', lookup_package_key_type('gpg'), lookup_package_provider('Spacewalk') from dual
     where not exists (select 1 from rhnPackageKey where key_id = '0e646f68863a853d'));

commit;
07070100000777000081B400000000000000000000000167AE11140000006B000000000000000000000000000000000000006700000000susemanager-schema/upgrade/spacewalk-schema-1.7-to-spacewalk-schema-1.8/146-rhnDistChannelMap-data.sql    UPDATE rhnDistChannelMap dcm SET org_id = (SELECT c.org_id FROM rhnChannel c where c.id = dcm.channel_id);
 07070100000778000081B400000000000000000000000167AE11140000072C000000000000000000000000000000000000006500000000susemanager-schema/upgrade/spacewalk-schema-1.7-to-spacewalk-schema-1.8/147-rhnOrgDistChannelMap.sql  --
-- Copyright (c) 2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--
--
--
CREATE OR REPLACE VIEW
rhnOrgDistChannelMap
(
    id,
    for_org_id,
    org_id,
    os,
    release,
    channel_arch_id,
    channel_id
)
AS
SELECT CASE WHEN dcm_o.org_id IS NOT NULL THEN dcm_o.id ELSE dcm_n.id END id,
        o.id as for_org_id,
        dcm_o.org_id,
        CASE WHEN dcm_o.org_id IS NOT NULL THEN dcm_o.os ELSE dcm_n.os END os,
        CASE WHEN dcm_o.org_id IS NOT NULL THEN dcm_o.release ELSE dcm_n.release END as release,
        CASE WHEN dcm_o.org_id IS NOT NULL THEN dcm_o.channel_arch_id ELSE dcm_n.channel_arch_id END as channel_arch_id,
        CASE WHEN dcm_o.org_id IS NOT NULL THEN dcm_o.channel_id ELSE dcm_n.channel_id END as channel_id
FROM web_customer o
    JOIN (SELECT DISTINCT release, channel_arch_id from rhnDistChannelMap) dcm ON 1 = 1
    LEFT JOIN rhnDistChannelMap dcm_n ON dcm_n.org_id IS NULL
        AND dcm_n.release = dcm.release
        AND dcm_n.channel_arch_id = dcm.channel_arch_id
    LEFT JOIN rhnDistChannelMap dcm_o ON dcm_o.org_id = o.id
        AND dcm_o.release = dcm.release
        AND dcm_o.channel_arch_id = dcm.channel_arch_id
WHERE (dcm_o.channel_id IS NOT NULL OR dcm_n.channel_id IS NOT NULL)
ORDER BY org_id, release, channel_arch_id;
07070100000779000081B400000000000000000000000167AE11140000017D000000000000000000000000000000000000006A00000000susemanager-schema/upgrade/spacewalk-schema-1.7-to-spacewalk-schema-1.8/148-rhnDistChannelMap-trigger.sql 
create or replace function rhn_dist_channel_map_mod_trig_fun() returns trigger as
$$
begin
    if new.id is null then
        new.id := nextval('rhn_rhn_dcm_id_seq');
    end if;
    return new;
end;
$$ language plpgsql;

create trigger
rhn_dist_channel_map_mod_trig
before insert or update on rhnDistChannelMap
for each row
execute procedure rhn_dist_channel_map_mod_trig_fun();
   0707010000077A000081B400000000000000000000000167AE11140000126E000000000000000000000000000000000000006000000000susemanager-schema/upgrade/spacewalk-schema-1.7-to-spacewalk-schema-1.8/149-rhn_channel.pkb.sql   
--update pg_setting
update pg_settings set setting = 'rhn_channel,' || setting where name = 'search_path';

    create or replace function guess_server_base(
        server_id_in in numeric
    ) RETURNS numeric as $$
    declare
        server_cursor cursor for
            select s.server_arch_id, s.release, s.org_id
              from rhnServer s
             where s.id = server_id_in;
    -- Cursor that fetches all the possible base channels for a
    -- (server_arch_id, release, org_id) combination
        base_channel_cursor cursor(
                release_in varchar,
                server_arch_id_in numeric,
                org_id_in numeric
        ) for
                select distinct c.*
                from    rhnOrgDistChannelMap                       odcm,
                                rhnServerChannelArchCompat      scac,
                                rhnChannel                                      c
                where   c.parent_channel is null
                        and c.id = odcm.channel_id
                        and c.channel_arch_id = odcm.channel_arch_id
                        and odcm.release = release_in
                        and odcm.for_org_id = org_id_in
                        and scac.server_arch_id = server_arch_id_in
                        and scac.channel_arch_id = c.channel_arch_id;

    begin
        for s in server_cursor loop
            for channel in base_channel_cursor(s.release,
                s.server_arch_id, s.org_id)
            loop
                return channel.id;
            end loop;
        end loop;
        -- Server not found, or no base channel applies to it
        return null;
    end$$ language plpgsql;

    create or replace function base_channel_rel_archid(
        release_in in varchar,
        server_arch_id_in in numeric,
        org_id_in in numeric default -1,
        user_id_in in numeric default null
    ) returns numeric as $$
    declare
        denied_channel_id numeric := null;
        valid_org_id numeric := org_id_in;
        valid_user_id numeric := user_id_in;
        channel_subscribable numeric;
    -- Cursor that fetches all the possible base channels for a
    -- (server_arch_id, release, org_id) combination
        base_channel_cursor cursor(
                release_in varchar,
                server_arch_id_in numeric,
                org_id_in numeric
        ) for
                select distinct c.*
                from    rhnOrgDistChannelMap                       odcm,
                                rhnServerChannelArchCompat      scac,
                                rhnChannel                                      c
                where   c.parent_channel is null
                        and c.id = odcm.channel_id
                        and c.channel_arch_id = odcm.channel_arch_id
                        and odcm.release = release_in
                        and odcm.for_org_id = org_id_in
                        and scac.server_arch_id = server_arch_id_in
                        and scac.channel_arch_id = c.channel_arch_id;

    begin
        if org_id_in = -1 and user_id_in is not null then
            -- Get the org id from the user id

                select org_id
                  into valid_org_id
                  from web_contact
                 where id = user_id_in;

                if not found then
                    -- User doesn't exist
                    -- XXX Only list public stuff for now
                    valid_user_id := null;
                    valid_org_id := -1;
                end if;
        end if;

        for c in base_channel_cursor(release_in, server_arch_id_in, valid_org_id)
        loop
            -- This row is a possible match
            if valid_user_id is null then
                -- User ID not specified, so no user to channel permissions to
                -- check
                return c.id;
            end if;

            -- Check user to channel permissions
            select rhn_channel.loose_user_role_check(c.id, user_id_in, 'subscribe')
              into channel_subscribable;

            if channel_subscribable = 1 then
                return c.id;
            end if;

            -- Base channel exists, but is not subscribable; keep trying
            denied_channel_id := c.id;
        end loop;

        if denied_channel_id is not null then
            perform rhn_exception.raise_exception('no_subscribe_permissions');
        end if;
        -- No base channel applies
        return NULL;
    end$$ language plpgsql;

-- restore the original setting
update pg_settings set setting = overlay( setting placing '' from 1 for (length('rhn_channel')+1) ) where name = 'search_path';
  0707010000077B000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000004800000000susemanager-schema/upgrade/spacewalk-schema-1.8-to-spacewalk-schema-1.9   0707010000077C000081B400000000000000000000000167AE1114000000DB000000000000000000000000000000000000006A00000000susemanager-schema/upgrade/spacewalk-schema-1.8-to-spacewalk-schema-1.9/001-rhnDistChannelMap-trigger.sql 
create or replace function rhn_dist_channel_map_mod_trig_fun() returns trigger as
$$
begin
    if new.id is null then
        new.id := nextval('rhn_dcm_id_seq');
    end if;
    return new;
end;
$$ language plpgsql;

 0707010000077D000081B400000000000000000000000167AE1114000000AE000000000000000000000000000000000000006100000000susemanager-schema/upgrade/spacewalk-schema-1.8-to-spacewalk-schema-1.9/002-rhnKSInstallType.sql  insert into rhnKSInstallType (id, label, name)
        values (sequence_nextval('rhn_ksinstalltype_id_seq'),
                'rhel_7','Red Hat Enterprise Linux 7'
        );
  0707010000077E000081B400000000000000000000000167AE11140001D64D000000000000000000000000000000000000006500000000susemanager-schema/upgrade/spacewalk-schema-1.8-to-spacewalk-schema-1.9/003-rhnKickstartTimezome.sql  insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Abidjan',
                'Africa/Abidjan',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Accra',
                'Africa/Accra',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Addis_Ababa',
                'Africa/Addis_Ababa',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Algiers',
                'Africa/Algiers',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Asmara',
                'Africa/Asmara',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Bamako',
                'Africa/Bamako',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Bangui',
                'Africa/Bangui',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Banjul',
                'Africa/Banjul',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Bissau',
                'Africa/Bissau',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Blantyre',
                'Africa/Blantyre',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Brazzaville',
                'Africa/Brazzaville',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Bujumbura',
                'Africa/Bujumbura',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Cairo',
                'Africa/Cairo',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Casablanca',
                'Africa/Casablanca',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Ceuta',
                'Africa/Ceuta',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Conakry',
                'Africa/Conakry',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Dakar',
                'Africa/Dakar',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Dar_es_Salaam',
                'Africa/Dar_es_Salaam',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Djibouti',
                'Africa/Djibouti',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Douala',
                'Africa/Douala',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/El_Aaiun',
                'Africa/El_Aaiun',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Freetown',
                'Africa/Freetown',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Gaborone',
                'Africa/Gaborone',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Harare',
                'Africa/Harare',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Johannesburg',
                'Africa/Johannesburg',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Juba',
                'Africa/Juba',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Kampala',
                'Africa/Kampala',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Khartoum',
                'Africa/Khartoum',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Kigali',
                'Africa/Kigali',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Kinshasa',
                'Africa/Kinshasa',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Lagos',
                'Africa/Lagos',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Libreville',
                'Africa/Libreville',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Lome',
                'Africa/Lome',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Luanda',
                'Africa/Luanda',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Lubumbashi',
                'Africa/Lubumbashi',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Lusaka',
                'Africa/Lusaka',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Malabo',
                'Africa/Malabo',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Maputo',
                'Africa/Maputo',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Maseru',
                'Africa/Maseru',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Mbabane',
                'Africa/Mbabane',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Mogadishu',
                'Africa/Mogadishu',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Monrovia',
                'Africa/Monrovia',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Nairobi',
                'Africa/Nairobi',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Ndjamena',
                'Africa/Ndjamena',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Niamey',
                'Africa/Niamey',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Nouakchott',
                'Africa/Nouakchott',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Ouagadougou',
                'Africa/Ouagadougou',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Porto-Novo',
                'Africa/Porto-Novo',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Sao_Tome',
                'Africa/Sao_Tome',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Tripoli',
                'Africa/Tripoli',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Tunis',
                'Africa/Tunis',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Windhoek',
                'Africa/Windhoek',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Adak',
                'America/Adak',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Anchorage',
                'America/Anchorage',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Anguilla',
                'America/Anguilla',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Antigua',
                'America/Antigua',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Araguaina',
                'America/Araguaina',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Argentina/Buenos_Aires',
                'America/Argentina/Buenos_Aires',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Argentina/Catamarca',
                'America/Argentina/Catamarca',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Argentina/Cordoba',
                'America/Argentina/Cordoba',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Argentina/Jujuy',
                'America/Argentina/Jujuy',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Argentina/La_Rioja',
                'America/Argentina/La_Rioja',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Argentina/Mendoza',
                'America/Argentina/Mendoza',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Argentina/Rio_Gallegos',
                'America/Argentina/Rio_Gallegos',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Argentina/Salta',
                'America/Argentina/Salta',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Argentina/San_Juan',
                'America/Argentina/San_Juan',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Argentina/San_Luis',
                'America/Argentina/San_Luis',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Argentina/Tucuman',
                'America/Argentina/Tucuman',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Argentina/Ushuaia',
                'America/Argentina/Ushuaia',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Aruba',
                'America/Aruba',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Asuncion',
                'America/Asuncion',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Atikokan',
                'America/Atikokan',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Bahia',
                'America/Bahia',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Bahia_Banderas',
                'America/Bahia_Banderas',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Barbados',
                'America/Barbados',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Belem',
                'America/Belem',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Belize',
                'America/Belize',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Blanc-Sablon',
                'America/Blanc-Sablon',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Boa_Vista',
                'America/Boa_Vista',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Bogota',
                'America/Bogota',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Boise',
                'America/Boise',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Cambridge_Bay',
                'America/Cambridge_Bay',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Campo_Grande',
                'America/Campo_Grande',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Cancun',
                'America/Cancun',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Caracas',
                'America/Caracas',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Cayenne',
                'America/Cayenne',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Cayman',
                'America/Cayman',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Chicago',
                'America/Chicago',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Chihuahua',
                'America/Chihuahua',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Costa_Rica',
                'America/Costa_Rica',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Creston',
                'America/Creston',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Cuiaba',
                'America/Cuiaba',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Curacao',
                'America/Curacao',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Danmarkshavn',
                'America/Danmarkshavn',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Dawson',
                'America/Dawson',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Dawson_Creek',
                'America/Dawson_Creek',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Denver',
                'America/Denver',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Detroit',
                'America/Detroit',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Dominica',
                'America/Dominica',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Edmonton',
                'America/Edmonton',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Eirunepe',
                'America/Eirunepe',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/El_Salvador',
                'America/El_Salvador',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Fortaleza',
                'America/Fortaleza',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Glace_Bay',
                'America/Glace_Bay',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Godthab',
                'America/Godthab',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Goose_Bay',
                'America/Goose_Bay',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Grand_Turk',
                'America/Grand_Turk',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Grenada',
                'America/Grenada',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Guadeloupe',
                'America/Guadeloupe',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Guatemala',
                'America/Guatemala',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Guayaquil',
                'America/Guayaquil',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Guyana',
                'America/Guyana',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Halifax',
                'America/Halifax',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Havana',
                'America/Havana',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Hermosillo',
                'America/Hermosillo',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Indiana/Indianapolis',
                'America/Indiana/Indianapolis',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Indiana/Knox',
                'America/Indiana/Knox',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Indiana/Marengo',
                'America/Indiana/Marengo',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Indiana/Petersburg',
                'America/Indiana/Petersburg',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Indiana/Tell_City',
                'America/Indiana/Tell_City',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Indiana/Vevay',
                'America/Indiana/Vevay',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Indiana/Vincennes',
                'America/Indiana/Vincennes',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Indiana/Winamac',
                'America/Indiana/Winamac',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Inuvik',
                'America/Inuvik',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Iqaluit',
                'America/Iqaluit',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Jamaica',
                'America/Jamaica',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Juneau',
                'America/Juneau',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Kentucky/Louisville',
                'America/Kentucky/Louisville',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Kentucky/Monticello',
                'America/Kentucky/Monticello',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Kralendijk',
                'America/Kralendijk',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/La_Paz',
                'America/La_Paz',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Lima',
                'America/Lima',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Los_Angeles',
                'America/Los_Angeles',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Lower_Princes',
                'America/Lower_Princes',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Maceio',
                'America/Maceio',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Managua',
                'America/Managua',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Manaus',
                'America/Manaus',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Marigot',
                'America/Marigot',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Martinique',
                'America/Martinique',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Matamoros',
                'America/Matamoros',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Mazatlan',
                'America/Mazatlan',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Menominee',
                'America/Menominee',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Merida',
                'America/Merida',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Metlakatla',
                'America/Metlakatla',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Mexico_City',
                'America/Mexico_City',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Miquelon',
                'America/Miquelon',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Moncton',
                'America/Moncton',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Monterrey',
                'America/Monterrey',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Montevideo',
                'America/Montevideo',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Montreal',
                'America/Montreal',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Montserrat',
                'America/Montserrat',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Nassau',
                'America/Nassau',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/New_York',
                'America/New_York',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Nipigon',
                'America/Nipigon',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Nome',
                'America/Nome',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Noronha',
                'America/Noronha',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/North_Dakota/Beulah',
                'America/North_Dakota/Beulah',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/North_Dakota/Center',
                'America/North_Dakota/Center',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/North_Dakota/New_Salem',
                'America/North_Dakota/New_Salem',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Ojinaga',
                'America/Ojinaga',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Panama',
                'America/Panama',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Pangnirtung',
                'America/Pangnirtung',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Paramaribo',
                'America/Paramaribo',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Phoenix',
                'America/Phoenix',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Port_of_Spain',
                'America/Port_of_Spain',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Port-au-Prince',
                'America/Port-au-Prince',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Porto_Velho',
                'America/Porto_Velho',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Puerto_Rico',
                'America/Puerto_Rico',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Rainy_River',
                'America/Rainy_River',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Rankin_Inlet',
                'America/Rankin_Inlet',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Recife',
                'America/Recife',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Regina',
                'America/Regina',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Resolute',
                'America/Resolute',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Rio_Branco',
                'America/Rio_Branco',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Santa_Isabel',
                'America/Santa_Isabel',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Santarem',
                'America/Santarem',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Santiago',
                'America/Santiago',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Santo_Domingo',
                'America/Santo_Domingo',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Sao_Paulo',
                'America/Sao_Paulo',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Scoresbysund',
                'America/Scoresbysund',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Shiprock',
                'America/Shiprock',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Sitka',
                'America/Sitka',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/St_Barthelemy',
                'America/St_Barthelemy',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/St_Johns',
                'America/St_Johns',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/St_Kitts',
                'America/St_Kitts',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/St_Lucia',
                'America/St_Lucia',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/St_Thomas',
                'America/St_Thomas',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/St_Vincent',
                'America/St_Vincent',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Swift_Current',
                'America/Swift_Current',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Tegucigalpa',
                'America/Tegucigalpa',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Thule',
                'America/Thule',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Thunder_Bay',
                'America/Thunder_Bay',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Tijuana',
                'America/Tijuana',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Toronto',
                'America/Toronto',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Tortola',
                'America/Tortola',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Vancouver',
                'America/Vancouver',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Whitehorse',
                'America/Whitehorse',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Winnipeg',
                'America/Winnipeg',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Yakutat',
                'America/Yakutat',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Yellowknife',
                'America/Yellowknife',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Antarctica/Casey',
                'Antarctica/Casey',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Antarctica/Davis',
                'Antarctica/Davis',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Antarctica/DumontDUrville',
                'Antarctica/DumontDUrville',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Antarctica/Macquarie',
                'Antarctica/Macquarie',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Antarctica/Mawson',
                'Antarctica/Mawson',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Antarctica/McMurdo',
                'Antarctica/McMurdo',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Antarctica/Palmer',
                'Antarctica/Palmer',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Antarctica/Rothera',
                'Antarctica/Rothera',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Antarctica/South_Pole',
                'Antarctica/South_Pole',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Antarctica/Syowa',
                'Antarctica/Syowa',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Antarctica/Vostok',
                'Antarctica/Vostok',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Arctic/Longyearbyen',
                'Arctic/Longyearbyen',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Aden',
                'Asia/Aden',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Almaty',
                'Asia/Almaty',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Amman',
                'Asia/Amman',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Anadyr',
                'Asia/Anadyr',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Aqtau',
                'Asia/Aqtau',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Aqtobe',
                'Asia/Aqtobe',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Ashgabat',
                'Asia/Ashgabat',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Baghdad',
                'Asia/Baghdad',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Bahrain',
                'Asia/Bahrain',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Baku',
                'Asia/Baku',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Bangkok',
                'Asia/Bangkok',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Beirut',
                'Asia/Beirut',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Bishkek',
                'Asia/Bishkek',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Brunei',
                'Asia/Brunei',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Choibalsan',
                'Asia/Choibalsan',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Chongqing',
                'Asia/Chongqing',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Colombo',
                'Asia/Colombo',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Damascus',
                'Asia/Damascus',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Dhaka',
                'Asia/Dhaka',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Dili',
                'Asia/Dili',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Dubai',
                'Asia/Dubai',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Dushanbe',
                'Asia/Dushanbe',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Gaza',
                'Asia/Gaza',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Harbin',
                'Asia/Harbin',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Hebron',
                'Asia/Hebron',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Ho_Chi_Minh',
                'Asia/Ho_Chi_Minh',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Hong_Kong',
                'Asia/Hong_Kong',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Hovd',
                'Asia/Hovd',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Irkutsk',
                'Asia/Irkutsk',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Jakarta',
                'Asia/Jakarta',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Jayapura',
                'Asia/Jayapura',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Jerusalem',
                'Asia/Jerusalem',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Kabul',
                'Asia/Kabul',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Kamchatka',
                'Asia/Kamchatka',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Karachi',
                'Asia/Karachi',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Kashgar',
                'Asia/Kashgar',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Kathmandu',
                'Asia/Kathmandu',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Kolkata',
                'Asia/Kolkata',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Krasnoyarsk',
                'Asia/Krasnoyarsk',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Kuala_Lumpur',
                'Asia/Kuala_Lumpur',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Kuching',
                'Asia/Kuching',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Kuwait',
                'Asia/Kuwait',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Macau',
                'Asia/Macau',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Magadan',
                'Asia/Magadan',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Makassar',
                'Asia/Makassar',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Manila',
                'Asia/Manila',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Muscat',
                'Asia/Muscat',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Nicosia',
                'Asia/Nicosia',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Novokuznetsk',
                'Asia/Novokuznetsk',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Novosibirsk',
                'Asia/Novosibirsk',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Omsk',
                'Asia/Omsk',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Oral',
                'Asia/Oral',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Phnom_Penh',
                'Asia/Phnom_Penh',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Pontianak',
                'Asia/Pontianak',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Pyongyang',
                'Asia/Pyongyang',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Qatar',
                'Asia/Qatar',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Qyzylorda',
                'Asia/Qyzylorda',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Rangoon',
                'Asia/Rangoon',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Riyadh',
                'Asia/Riyadh',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Sakhalin',
                'Asia/Sakhalin',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Samarkand',
                'Asia/Samarkand',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Seoul',
                'Asia/Seoul',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Shanghai',
                'Asia/Shanghai',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Singapore',
                'Asia/Singapore',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Taipei',
                'Asia/Taipei',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Tashkent',
                'Asia/Tashkent',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Tbilisi',
                'Asia/Tbilisi',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Tehran',
                'Asia/Tehran',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Thimphu',
                'Asia/Thimphu',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Tokyo',
                'Asia/Tokyo',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Ulaanbaatar',
                'Asia/Ulaanbaatar',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Urumqi',
                'Asia/Urumqi',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Vientiane',
                'Asia/Vientiane',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Vladivostok',
                'Asia/Vladivostok',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Yakutsk',
                'Asia/Yakutsk',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Yekaterinburg',
                'Asia/Yekaterinburg',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Yerevan',
                'Asia/Yerevan',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Atlantic/Azores',
                'Atlantic/Azores',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Atlantic/Bermuda',
                'Atlantic/Bermuda',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Atlantic/Canary',
                'Atlantic/Canary',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Atlantic/Cape_Verde',
                'Atlantic/Cape_Verde',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Atlantic/Faroe',
                'Atlantic/Faroe',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Atlantic/Madeira',
                'Atlantic/Madeira',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Atlantic/Reykjavik',
                'Atlantic/Reykjavik',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Atlantic/South_Georgia',
                'Atlantic/South_Georgia',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Atlantic/St_Helena',
                'Atlantic/St_Helena',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Atlantic/Stanley',
                'Atlantic/Stanley',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Australia/Adelaide',
                'Australia/Adelaide',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Australia/Brisbane',
                'Australia/Brisbane',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Australia/Broken_Hill',
                'Australia/Broken_Hill',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Australia/Currie',
                'Australia/Currie',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Australia/Darwin',
                'Australia/Darwin',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Australia/Eucla',
                'Australia/Eucla',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Australia/Hobart',
                'Australia/Hobart',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Australia/Lindeman',
                'Australia/Lindeman',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Australia/Lord_Howe',
                'Australia/Lord_Howe',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Australia/Melbourne',
                'Australia/Melbourne',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Australia/Perth',
                'Australia/Perth',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Australia/Sydney',
                'Australia/Sydney',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Amsterdam',
                'Europe/Amsterdam',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Andorra',
                'Europe/Andorra',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Athens',
                'Europe/Athens',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Belgrade',
                'Europe/Belgrade',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Berlin',
                'Europe/Berlin',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Bratislava',
                'Europe/Bratislava',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Brussels',
                'Europe/Brussels',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Bucharest',
                'Europe/Bucharest',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Budapest',
                'Europe/Budapest',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Chisinau',
                'Europe/Chisinau',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Copenhagen',
                'Europe/Copenhagen',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Dublin',
                'Europe/Dublin',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Gibraltar',
                'Europe/Gibraltar',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Guernsey',
                'Europe/Guernsey',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Helsinki',
                'Europe/Helsinki',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Isle_of_Man',
                'Europe/Isle_of_Man',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Istanbul',
                'Europe/Istanbul',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Jersey',
                'Europe/Jersey',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Kaliningrad',
                'Europe/Kaliningrad',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Kiev',
                'Europe/Kiev',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Lisbon',
                'Europe/Lisbon',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Ljubljana',
                'Europe/Ljubljana',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/London',
                'Europe/London',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Luxembourg',
                'Europe/Luxembourg',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Madrid',
                'Europe/Madrid',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Malta',
                'Europe/Malta',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Mariehamn',
                'Europe/Mariehamn',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Minsk',
                'Europe/Minsk',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Monaco',
                'Europe/Monaco',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Moscow',
                'Europe/Moscow',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Oslo',
                'Europe/Oslo',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Paris',
                'Europe/Paris',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Podgorica',
                'Europe/Podgorica',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Prague',
                'Europe/Prague',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Riga',
                'Europe/Riga',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Rome',
                'Europe/Rome',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Samara',
                'Europe/Samara',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/San_Marino',
                'Europe/San_Marino',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Sarajevo',
                'Europe/Sarajevo',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Simferopol',
                'Europe/Simferopol',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Skopje',
                'Europe/Skopje',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Sofia',
                'Europe/Sofia',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Stockholm',
                'Europe/Stockholm',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Tallinn',
                'Europe/Tallinn',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Tirane',
                'Europe/Tirane',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Uzhgorod',
                'Europe/Uzhgorod',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Vaduz',
                'Europe/Vaduz',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Vatican',
                'Europe/Vatican',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Vienna',
                'Europe/Vienna',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Vilnius',
                'Europe/Vilnius',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Volgograd',
                'Europe/Volgograd',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Warsaw',
                'Europe/Warsaw',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Zagreb',
                'Europe/Zagreb',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Zaporozhye',
                'Europe/Zaporozhye',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Zurich',
                'Europe/Zurich',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Indian/Antananarivo',
                'Indian/Antananarivo',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Indian/Chagos',
                'Indian/Chagos',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Indian/Christmas',
                'Indian/Christmas',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Indian/Cocos',
                'Indian/Cocos',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Indian/Comoro',
                'Indian/Comoro',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Indian/Kerguelen',
                'Indian/Kerguelen',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Indian/Mahe',
                'Indian/Mahe',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Indian/Maldives',
                'Indian/Maldives',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Indian/Mauritius',
                'Indian/Mauritius',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Indian/Mayotte',
                'Indian/Mayotte',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Indian/Reunion',
                'Indian/Reunion',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Apia',
                'Pacific/Apia',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Auckland',
                'Pacific/Auckland',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Chatham',
                'Pacific/Chatham',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Chuuk',
                'Pacific/Chuuk',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Easter',
                'Pacific/Easter',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Efate',
                'Pacific/Efate',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Enderbury',
                'Pacific/Enderbury',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Fakaofo',
                'Pacific/Fakaofo',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Fiji',
                'Pacific/Fiji',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Funafuti',
                'Pacific/Funafuti',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Galapagos',
                'Pacific/Galapagos',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Gambier',
                'Pacific/Gambier',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Guadalcanal',
                'Pacific/Guadalcanal',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Guam',
                'Pacific/Guam',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Honolulu',
                'Pacific/Honolulu',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Johnston',
                'Pacific/Johnston',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Kiritimati',
                'Pacific/Kiritimati',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Kosrae',
                'Pacific/Kosrae',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Kwajalein',
                'Pacific/Kwajalein',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Majuro',
                'Pacific/Majuro',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Marquesas',
                'Pacific/Marquesas',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Midway',
                'Pacific/Midway',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Nauru',
                'Pacific/Nauru',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Niue',
                'Pacific/Niue',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Norfolk',
                'Pacific/Norfolk',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Noumea',
                'Pacific/Noumea',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Pago_Pago',
                'Pacific/Pago_Pago',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Palau',
                'Pacific/Palau',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Pitcairn',
                'Pacific/Pitcairn',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Pohnpei',
                'Pacific/Pohnpei',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Port_Moresby',
                'Pacific/Port_Moresby',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Rarotonga',
                'Pacific/Rarotonga',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Saipan',
                'Pacific/Saipan',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Tahiti',
                'Pacific/Tahiti',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Tarawa',
                'Pacific/Tarawa',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Tongatapu',
                'Pacific/Tongatapu',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Wake',
                'Pacific/Wake',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Wallis',
                'Pacific/Wallis',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

   0707010000077F000081B400000000000000000000000167AE111400000201000000000000000000000000000000000000005C00000000susemanager-schema/upgrade/spacewalk-schema-1.8-to-spacewalk-schema-1.9/004-rhnTimezone.sql   update rhnTimezone
   set display_name = 'Australia (Eastern Daylight)'
 where olson_name = 'Australia/Sydney';

insert into rhnTimezone (id, olson_name, display_name) (
    select sequence_nextval('rhn_timezone_id_seq'),
           'Australia/Brisbane',
           'Australia (Eastern Standard)'
      from dual
     where not exists (
           select 1
             from rhnTimezone
            where olson_name = 'Australia/Brisbane'
              and display_name = 'Australia (Eastern Standard)'
     )
);
   07070100000780000081B400000000000000000000000167AE111400000088000000000000000000000000000000000000005C00000000susemanager-schema/upgrade/spacewalk-schema-1.8-to-spacewalk-schema-1.9/005-rhnTimezone.sql   update rhnTimezone
   set olson_name = 'Australia/Perth'
 where olson_name = 'Asia/Hong_Kong' and display_name = 'Australia (Western)';
07070100000781000081B400000000000000000000000167AE11140000007A000000000000000000000000000000000000006200000000susemanager-schema/upgrade/spacewalk-schema-1.8-to-spacewalk-schema-1.9/006-rhnDownloads-drop.sql 
drop table rhnChannelDownloads;
drop table rhnDownloads;
drop table rhnDownloadType;
drop sequence rhn_download_id_seq;

  07070100000782000081B400000000000000000000000167AE111400000C69000000000000000000000000000000000000006200000000susemanager-schema/upgrade/spacewalk-schema-1.8-to-spacewalk-schema-1.9/006-rhnServerOverview.sql drop view rhnServerOverview;
create or replace view
rhnServerOverview
(
    org_id, 
    server_id, 
    server_name, 
    modified, 
    server_admins, 
    group_count, 
    channel_id,
    channel_labels, 
    history_count, 
    security_errata, 
    bug_errata, 
    enhancement_errata,
    outdated_packages,
	config_files_with_differences,
    crash_count,
    last_checkin_days_ago,
    last_checkin,
    pending_updates,
    os,
    release,
    server_arch_name,
    locked
)
as
select
    s.org_id, s.id, s.name, s.modified,
    ( select count(user_id) from rhnUserServerPerms ap 
      where server_id = s.id ), 
    ( select count(server_group_id) from rhnVisibleServerGroupMembers
      where server_id = s.id ),
    ( select C.id
        from rhnChannel C,
	     rhnServerChannel SC
       where SC.server_id = S.id
         and SC.channel_id = C.id
	 and C.parent_channel IS NULL),
    coalesce(( select C.name
        from rhnChannel C,
	     rhnServerChannel SC
       where SC.server_id = S.id
         and SC.channel_id = C.id
	 and C.parent_channel IS NULL), '(none)'),
    ( select count(id) from rhnServerHistory
      where
            server_id = S.id),
    ( select count(*) from rhnServerErrataTypeView setv 
      where
            setv.server_id = s.id
        and setv.errata_type = 'Security Advisory'), 
    ( select count(*) from rhnServerErrataTypeView setv 
      where 
            setv.server_id = s.id
        and setv.errata_type = 'Bug Fix Advisory'),
    ( select count(*) from rhnServerErrataTypeView setv 
      where 
            setv.server_id = s.id
        and setv.errata_type = 'Product Enhancement Advisory'),
    ( select count(distinct p.name_id) from rhnPackage p, rhnServerNeededPackageCache snpc
      where
             snpc.server_id = S.id
	 and p.id = snpc.package_id
	 ),
    ( select count(*)
        from rhnActionConfigRevision ACR
             INNER JOIN rhnActionConfigRevisionResult ACRR on ACR.id = ACRR.action_config_revision_id
       where ACR.server_id = S.id
         and ACR.action_id = (
              select MAX(rA.id)
                from rhnAction rA
                     INNER JOIN rhnServerAction rSA on rSA.action_id = rA.id
                     INNER JOIN rhnActionStatus rAS on rAS.id = rSA.status
                     INNER JOIN rhnActionType rAT on rAT.id = rA.action_type
               where rSA.server_id = S.id
                 and rAS.name in ('Completed', 'Failed')
                 and rAT.label = 'configfiles.diff'
         )
         and ACR.failure_id is null
         and ACRR.result is not null
        ),
    ( select num_crashes from rhnAbrtInfo where server_id = S.id ),
    ( select date_diff_in_days(checkin, current_timestamp) from rhnServerInfo where server_id = S.id ),
    ( select TO_CHAR(checkin, 'YYYY-MM-DD HH24:MI:SS') from rhnServerInfo where server_id = S.id ),
    ( select count(1) 
        from rhnServerAction
       where server_id = S.id
         and status in (0, 1)),
    os,
    release,
    ( select name from rhnServerArch where id = s.server_arch_id),
    coalesce((select 1 from rhnServerLock SL WHERE SL.server_id = S.id), 0)
from 
    rhnServer S
;
   07070100000783000081B400000000000000000000000167AE11140000002D000000000000000000000000000000000000006F00000000susemanager-schema/upgrade/spacewalk-schema-1.8-to-spacewalk-schema-1.9/007-rhn_download_mod_trig_fun-drop.sql    
drop function rhn_download_mod_trig_fun();

   07070100000784000081B400000000000000000000000167AE111400000320000000000000000000000000000000000000006400000000susemanager-schema/upgrade/spacewalk-schema-1.8-to-spacewalk-schema-1.9/008-rhnContentSourceSsl.sql   
create table
rhnContentSourceSsl
(
	id NUMERIC not null
		constraint rhn_csssl_id_pk primary key,
	content_source_id NUMERIC not null
		constraint rhn_csssl_csid_uq unique
		constraint rhn_csssl_csid_fk references rhnContentSource(id) on delete cascade,
	ssl_ca_cert_id NUMERIC not null
		constraint rhn_csssl_cacertid_fk references rhnCryptoKey(id),
	ssl_client_cert_id NUMERIC
		constraint rhn_csssl_clcertid_fk references rhnCryptoKey(id),
	ssl_client_key_id NUMERIC
		constraint rhn_csssl_clkeyid_fk references rhnCryptoKey(id),
	constraint rhn_csssl_client_chk check(ssl_client_key_id is null or ssl_client_cert_id is not null),
	created TIMESTAMPTZ default(current_timestamp) not null,
	modified TIMESTAMPTZ default(current_timestamp) not null
)

;

create sequence rhn_contentsourcessl_seq;

07070100000785000081B400000000000000000000000167AE111400000146000000000000000000000000000000000000007000000000susemanager-schema/upgrade/spacewalk-schema-1.8-to-spacewalk-schema-1.9/009-rhn_content_source_ssl_mod_trig.sql   
create or replace function rhn_cont_source_ssl_mod_trig_fun() returns trigger as
$$
begin
	new.modified := current_timestamp;
	return new;
end;
$$ language plpgsql;


create trigger
rhn_cont_source_ssl_mod_trig
before insert or update on rhnContentSourceSsl
for each row
execute procedure rhn_cont_source_ssl_mod_trig_fun();
  07070100000786000081B400000000000000000000000167AE111400000741000000000000000000000000000000000000006000000000susemanager-schema/upgrade/spacewalk-schema-1.8-to-spacewalk-schema-1.9/011-rhn_channel.pkb.sql   --
-- Copyright (c) 2008--2013 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--

-- create schema rhn_channel;

--update pg_setting
update pg_settings set setting = 'rhn_channel,' || setting where name = 'search_path';

    create or replace function set_comps(channel_id_in in numeric, path_in in varchar, timestamp_in in varchar) returns void
    as $$
    declare
    row record;
    begin
        for row in (
            select relative_filename, last_modified
            from rhnChannelComps
            where channel_id = channel_id_in
            ) loop
            if row.relative_filename = path_in
                and row.last_modified = to_date(timestamp_in, 'YYYYMMDDHH24MISS') then
                return;
            end if;
        end loop;
        delete from rhnChannelComps
        where channel_id = channel_id_in;
        insert into rhnChannelComps (id, channel_id, relative_filename, last_modified, created, modified)
        values (sequence_nextval('rhn_channelcomps_id_seq'), channel_id_in, path_in, to_date(timestamp_in, 'YYYYMMDDHH24MISS'), current_timestamp, current_timestamp);
    end$$ language plpgsql;

-- restore the original setting
update pg_settings set setting = overlay( setting placing '' from 1 for (length('rhn_channel')+1) ) where name = 'search_path';
   07070100000787000081B400000000000000000000000167AE111400000166000000000000000000000000000000000000006E00000000susemanager-schema/upgrade/spacewalk-schema-1.8-to-spacewalk-schema-1.9/012-epoch_seconds_to_timestamp_tz.sql --
-- Take seconds since epoch (January 1, 1970 UTC) and convert it
-- to time-zone'd timestamp. Mainly as compatibility with Oracle
-- which does not have the single-parameter to_timestamp.
--

create function epoch_seconds_to_timestamp_tz(secs in numeric)
returns timestamp with time zone
as
$$
begin
	return to_timestamp(secs);
end;
$$ language plpgsql;

  07070100000788000081B400000000000000000000000167AE111400000852000000000000000000000000000000000000005F00000000susemanager-schema/upgrade/spacewalk-schema-1.8-to-spacewalk-schema-1.9/013-rhnServerCrash.sql    --
-- Copyright (c) 2013 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

create table rhnServerCrash
(
    id              NUMERIC not null
                    constraint rhn_server_crash_id_pk primary key,
    server_id       NUMERIC not null
                    constraint rhn_server_crash_sid_fk
                        references rhnServer(id)
                        on delete cascade,
    crash           VARCHAR(512) not null,
    path            VARCHAR(1024) not null,
    count           NUMERIC not null,
    analyzer        VARCHAR(128),
    architecture    VARCHAR(16),
    cmdline         VARCHAR(2048),
    component       VARCHAR(256),
    executable      VARCHAR(512),
    kernel          VARCHAR(128),
    reason          VARCHAR(512),
    username        VARCHAR(256),
    package_name_id NUMERIC
                    constraint rhn_server_crash_pname_id_fk
                        references rhnPackageName(id),
    package_evr_id  NUMERIC
                    constraint rhn_server_crash_evr_id_fk
                        references rhnPackageEVR(id),
    package_arch_id NUMERIC
                    constraint rhn_server_crash_arch_id_fk
                        references rhnPackageArch(id),
    storage_path    VARCHAR(1024),
    created         TIMESTAMPTZ
                        default (current_timestamp) not null,
    modified        TIMESTAMPTZ
                        default (current_timestamp) not null
)

;

create sequence rhn_server_crash_id_seq start with 1;

create unique index rhn_scr_sid_crash
    on rhnServerCrash (server_id, crash)
    ;
  07070100000789000081B400000000000000000000000167AE1114000003B2000000000000000000000000000000000000006800000000susemanager-schema/upgrade/spacewalk-schema-1.8-to-spacewalk-schema-1.9/014-rhnServerCrash-triggers.sql   --
-- Copyright (c) 2013 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

create or replace function rhn_server_crash_mod_trig_fun() returns trigger as
$$
begin
        new.modified := current_timestamp;
        return new;
end;
$$ language plpgsql;

create trigger
rhn_server_crash_mod_trig
before insert or update on rhnServerCrash
for each row
execute procedure rhn_server_crash_mod_trig_fun();
  0707010000078A000081B400000000000000000000000167AE111400000608000000000000000000000000000000000000006300000000susemanager-schema/upgrade/spacewalk-schema-1.8-to-spacewalk-schema-1.9/015-rhnServerCrashFile.sql    --
-- Copyright (c) 2013 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

create table rhnServerCrashFile
(
    id          NUMERIC not null
                constraint rhn_server_crash_file_id_pk primary key,
    crash_id    NUMERIC not null
                constraint rhn_server_crash_file_cis_fk
                    references rhnServerCrash(id)
                    on delete cascade,
    filename    VARCHAR(512) not null,
    path        VARCHAR(1024) not null,
    filesize    NUMERIC not null,
    is_uploaded char(1)
                default ('N') not null
                constraint rhn_server_crash_file_upl_ck
                check (is_uploaded in ('Y', 'N')),
    created     TIMESTAMPTZ
                    default (current_timestamp) not null,
    modified    TIMESTAMPTZ
                    default (current_timestamp) not null
)

;

create sequence rhn_server_crash_file_id_seq start with 1;

create unique index rhn_scrf_cid_fn
    on rhnServerCrashFile (crash_id, filename)
    ;
0707010000078B000081B400000000000000000000000167AE11140000059B000000000000000000000000000000000000006200000000susemanager-schema/upgrade/spacewalk-schema-1.8-to-spacewalk-schema-1.9/016-insert_crash_file.sql --
-- Copyright (c) 2013 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

create or replace function
insert_crash_file(
    crash_id_in in numeric,
    filename_in in varchar,
    path_in in varchar,
    filesize_in in numeric)
returns numeric
as
$$
declare
    crash_file_id numeric;
begin
    crash_file_id := nextval('rhn_server_crash_file_id_seq');
    insert into rhnServerCrashFile (id, crash_id, filename, path, filesize)
    values (crash_file_id, crash_id_in, filename_in, path_in, filesize_in);

    return crash_file_id;
exception when unique_violation then
    select id
      into crash_file_id
      from rhnServerCrashFile
     where crash_id = crash_id_in and
           filename = filename_in;

    update rhnServerCrashFile
       set path = path_in,
           filesize = filesize_in
     where id = crash_file_id;

    return crash_file_id;
end;
$$ language plpgsql;
 0707010000078C000081B400000000000000000000000167AE1114000003C5000000000000000000000000000000000000006C00000000susemanager-schema/upgrade/spacewalk-schema-1.8-to-spacewalk-schema-1.9/017-rhnServerCrashFile-triggers.sql   --
-- Copyright (c) 2013 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

create or replace function rhn_server_crash_file_mod_trig_fun() returns trigger as
$$
begin
        new.modified := current_timestamp;
        return new;
end;
$$ language plpgsql;

create trigger
rhn_server_crash_file_mod_trig
before insert or update on rhnServerCrashFile
for each row
execute procedure rhn_server_crash_file_mod_trig_fun();
   0707010000078D000081B400000000000000000000000167AE111400000341000000000000000000000000000000000000006400000000susemanager-schema/upgrade/spacewalk-schema-1.8-to-spacewalk-schema-1.9/018-rhnServerCrashCount.sql   --
-- Copyright (c) 2013 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

create or replace view rhnServerCrashCount
as
select server_id,
       count(id) as unique_count,
       sum(count) as total_count,
       max(modified) as last_report
  from rhnServerCrash
 group by server_id;
   0707010000078E000081B400000000000000000000000167AE1114000000A8000000000000000000000000000000000000005D00000000susemanager-schema/upgrade/spacewalk-schema-1.8-to-spacewalk-schema-1.9/019-web_customer.sql  alter table web_customer
  add crash_file_sizelimit
      NUMERIC default(2048) not null
      constraint web_customer_sizelimit_chk check (crash_file_sizelimit >= 0);
0707010000078F000081B400000000000000000000000167AE111400000F43000000000000000000000000000000000000006200000000susemanager-schema/upgrade/spacewalk-schema-1.8-to-spacewalk-schema-1.9/020-rhnServerOverview.sql --
-- Copyright (c) 2008--2013 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--
--
--

drop view rhnServerOverview;

create or replace view
rhnServerOverview
(
    org_id,
    server_id,
    server_name,
    modified,
    server_admins,
    group_count,
    channel_id,
    channel_labels,
    history_count,
    security_errata,
    bug_errata,
    enhancement_errata,
    outdated_packages,
	config_files_with_differences,
    unique_crash_count,
    total_crash_count,
    last_checkin_days_ago,
    last_checkin,
    pending_updates,
    os,
    release,
    server_arch_name,
    locked
)
as
select
    s.org_id, s.id, s.name, s.modified,
    ( select count(user_id) from rhnUserServerPerms ap
      where server_id = s.id ),
    ( select count(server_group_id) from rhnVisibleServerGroupMembers
      where server_id = s.id ),
    ( select C.id
        from rhnChannel C,
	     rhnServerChannel SC
       where SC.server_id = S.id
         and SC.channel_id = C.id
	 and C.parent_channel IS NULL),
    coalesce(( select C.name
        from rhnChannel C,
	     rhnServerChannel SC
       where SC.server_id = S.id
         and SC.channel_id = C.id
	 and C.parent_channel IS NULL), '(none)'),
    ( select count(id) from rhnServerHistory
      where
            server_id = S.id),
    ( select count(*) from rhnServerErrataTypeView setv
      where
            setv.server_id = s.id
        and setv.errata_type = 'Security Advisory'),
    ( select count(*) from rhnServerErrataTypeView setv
      where
            setv.server_id = s.id
        and setv.errata_type = 'Bug Fix Advisory'),
    ( select count(*) from rhnServerErrataTypeView setv
      where
            setv.server_id = s.id
        and setv.errata_type = 'Product Enhancement Advisory'),
    ( select count(distinct p.name_id) from rhnPackage p, rhnServerNeededPackageCache snpc
      where
             snpc.server_id = S.id
	 and p.id = snpc.package_id
	 ),
    ( select count(*)
        from rhnActionConfigRevision ACR
             INNER JOIN rhnActionConfigRevisionResult ACRR on ACR.id = ACRR.action_config_revision_id
       where ACR.server_id = S.id
         and ACR.action_id = (
              select MAX(rA.id)
                from rhnAction rA
                     INNER JOIN rhnServerAction rSA on rSA.action_id = rA.id
                     INNER JOIN rhnActionStatus rAS on rAS.id = rSA.status
                     INNER JOIN rhnActionType rAT on rAT.id = rA.action_type
               where rSA.server_id = S.id
                 and rAS.name in ('Completed', 'Failed')
                 and rAT.label = 'configfiles.diff'
         )
         and ACR.failure_id is null
         and ACRR.result is not null
        ),
    ( select unique_count from rhnServerCrashCount where server_id = S.id ),
    ( select total_count from rhnServerCrashCount where server_id = S.id ),
    ( select date_diff_in_days(checkin, current_timestamp) from rhnServerInfo where server_id = S.id ),
    ( select TO_CHAR(checkin, 'YYYY-MM-DD HH24:MI:SS') from rhnServerInfo where server_id = S.id ),
    ( select count(1)
        from rhnServerAction
       where server_id = S.id
         and status in (0, 1)),
    os,
    release,
    ( select name from rhnServerArch where id = s.server_arch_id),
    coalesce((select 1 from rhnServerLock SL WHERE SL.server_id = S.id), 0)
from
    rhnServer S
;
 07070100000790000081B400000000000000000000000167AE11140000003C000000000000000000000000000000000000005C00000000susemanager-schema/upgrade/spacewalk-schema-1.8-to-spacewalk-schema-1.9/021-rhnAbrtInfo.sql   drop table rhnAbrtInfo;
drop sequence rhn_abrt_info_id_seq;
07070100000791000081B400000000000000000000000167AE1114000000BE000000000000000000000000000000000000006600000000susemanager-schema/upgrade/spacewalk-schema-1.8-to-spacewalk-schema-1.9/022-rhnServerNetInterface.sql 
ALTER TABLE rhnServerNetInterface ADD COLUMN is_primary VARCHAR(1);

CREATE UNIQUE INDEX rhn_srv_net_iface_prim_iface
  ON rhnServerNetInterface
  (server_id) where is_primary is not null;
  07070100000792000081B400000000000000000000000167AE1114000000B7000000000000000000000000000000000000005A00000000susemanager-schema/upgrade/spacewalk-schema-1.8-to-spacewalk-schema-1.9/023-rhnKsData.sql alter table rhnksdata add update_type VARCHAR(7) default ('none') not null;
alter table rhnksdata add constraint rhn_ks_update_type check (update_type in ('all', 'red_hat', 'none'));
 07070100000793000081B400000000000000000000000167AE11140000001B000000000000000000000000000000000000004F00000000susemanager-schema/upgrade/spacewalk-schema-1.8-to-spacewalk-schema-1.9/README    -- Schema upgrade scripts.
 07070100000794000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000004900000000susemanager-schema/upgrade/spacewalk-schema-1.9-to-spacewalk-schema-1.10  07070100000795000081B400000000000000000000000167AE111400000163000000000000000000000000000000000000006D00000000susemanager-schema/upgrade/spacewalk-schema-1.9-to-spacewalk-schema-1.10/001-rhnContentSourceSsl-trigger.sql  
create or replace function rhn_csssl_ins_trig_fun() returns trigger as
$$
begin
    if new.id is null then
        new.id := sequence_nextval('rhn_contentsourcessl_seq');
    end if;
    return new;
end;
$$ language plpgsql;

create trigger
rhn_csssl_ins_trig
before insert on rhnContentSourceSsl
for each row
execute procedure rhn_csssl_ins_trig_fun();
 07070100000796000081B400000000000000000000000167AE1114000008A9000000000000000000000000000000000000006500000000susemanager-schema/upgrade/spacewalk-schema-1.9-to-spacewalk-schema-1.10/002-rhnOrgConfiguration.sql  --
-- Copyright (c) 2013 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

create table rhnOrgConfiguration
(
    org_id                     NUMERIC not null
                                   constraint rhn_org_conf_org_id_fk
                                   references web_customer(id)
                                   on delete cascade,
    staging_content_enabled    char(1)
                                   default ('N') not null
                                   constraint rhn_org_conf_stage_content_chk
                                   check (staging_content_enabled in ('Y', 'N')),
    crash_reporting_enabled    char(1)
                                   default ('Y') not null
                                   constraint rhn_org_conf_crash_report_chk
                                   check (crash_reporting_enabled in ('Y', 'N')),
    crashfile_upload_enabled   char(1)
                                   default ('Y') not null
                                   constraint rhn_org_conf_crash_upload_chk
                                   check (crashfile_upload_enabled in ('Y', 'N')),
    crash_file_sizelimit       NUMERIC
                                   default(2048) not null
                                   constraint rhn_org_conf_sizelimit_chk
                                   check (crash_file_sizelimit >= 0),
    created                    TIMESTAMPTZ
                                   default (current_timestamp) not null,
    modified                   TIMESTAMPTZ
                                   default (current_timestamp) not null
)

;

create unique index rhn_org_conf_org_id
    on rhnOrgConfiguration (org_id)
    ;
   07070100000797000081B400000000000000000000000167AE1114000003AB000000000000000000000000000000000000006D00000000susemanager-schema/upgrade/spacewalk-schema-1.9-to-spacewalk-schema-1.10/003-rhnOrgConfiguration-trigger.sql  --
-- Copyright (c) 2013 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

create or replace function rhn_org_conf_mod_trig_fun() returns trigger as
$$
begin
        new.modified := current_timestamp;
        return new;
end;
$$ language plpgsql;

create trigger
rhn_org_conf_mod_trig
before insert or update on rhnOrgConfiguration
for each row
execute procedure rhn_org_conf_mod_trig_fun();
 07070100000798000081B400000000000000000000000167AE11140000039F000000000000000000000000000000000000006A00000000susemanager-schema/upgrade/spacewalk-schema-1.9-to-spacewalk-schema-1.10/004-rhnOrgConfiguration-data.sql --
-- Copyright (c) 2013 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

insert into rhnOrgConfiguration (
    org_id,
    staging_content_enabled,
    crash_reporting_enabled,
    crashfile_upload_enabled,
    crash_file_sizelimit )
(
    select id,
           staging_content_enabled,
           'Y',
           'Y',
           crash_file_sizelimit
      from web_customer
);
 07070100000799000081B400000000000000000000000167AE1114000002E7000000000000000000000000000000000000005E00000000susemanager-schema/upgrade/spacewalk-schema-1.9-to-spacewalk-schema-1.10/005-web_customer.sql --
-- Copyright (c) 2013 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

alter table web_customer drop column staging_content_enabled;
alter table web_customer drop column crash_file_sizelimit;
 0707010000079A000081B400000000000000000000000167AE1114000003BB000000000000000000000000000000000000006700000000susemanager-schema/upgrade/spacewalk-schema-1.9-to-spacewalk-schema-1.10/006-web_customer-triggers.sql    --
-- Copyright (c) 2013 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

create or replace function web_customer_insert_trig_fun() returns trigger
as
$$
begin
        insert into rhnOrgConfiguration (org_id) values (new.id);

        return new;
end;
$$
language plpgsql;


create trigger
web_customer_insert_trig
after insert on web_customer
for each row
execute procedure web_customer_insert_trig_fun();
 0707010000079B000081B400000000000000000000000167AE111400000644000000000000000000000000000000000000006400000000susemanager-schema/upgrade/spacewalk-schema-1.9-to-spacewalk-schema-1.10/007-rhnServerCrashNote.sql   --
-- Copyright (c) 2013 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnServerCrashNote
(
    id         NUMERIC NOT NULL
                   CONSTRAINT rhn_server_crash_note_id_pk PRIMARY KEY
                   ,
    creator    NUMERIC
                   CONSTRAINT rhn_srv_crash_note_creator_fk
                       REFERENCES web_contact (id)
                       ON DELETE SET NULL,
    crash_id  NUMERIC NOT NULL
                   CONSTRAINT rhn_srv_crash_note_sid_fk
                       REFERENCES rhnServerCrash (id)
                       ON DELETE CASCADE,
    subject    VARCHAR(80) NOT NULL,
    note       VARCHAR(4000),
    created    TIMESTAMPTZ
                   DEFAULT (current_timestamp) NOT NULL,
    modified   TIMESTAMPTZ
                   DEFAULT (current_timestamp) NOT NULL
)

;

CREATE INDEX rhn_srv_crash_note_sid_idx
    ON rhnServerCrashNote (crash_id)
    
    ;

CREATE INDEX rhn_srv_crash_note_creator_idx
    ON rhnServerCrashNote (creator)
    
    ;

CREATE SEQUENCE rhn_srv_crash_note_id_seq;
0707010000079C000081B400000000000000000000000167AE111400000154000000000000000000000000000000000000006C00000000susemanager-schema/upgrade/spacewalk-schema-1.9-to-spacewalk-schema-1.10/008-rhnServerCrashNote-trigger.sql   
create or replace function rhn_server_crash_note_mod_trig_fun() returns trigger as
$$
begin
    new.modified := current_timestamp;
    return new;
end;
$$ language plpgsql;

create trigger rhn_server_crash_note_mod_trig
before insert or update on rhnServerCrashNote
for each row
    execute procedure rhn_server_crash_note_mod_trig_fun();
0707010000079D000081B400000000000000000000000167AE111400000032000000000000000000000000000000000000006000000000susemanager-schema/upgrade/spacewalk-schema-1.9-to-spacewalk-schema-1.10/009-rhnServerCrash.sql   alter table rhnServerCrash add uuid VARCHAR(256);
  0707010000079E000081B400000000000000000000000167AE111400000029000000000000000000000000000000000000006500000000susemanager-schema/upgrade/spacewalk-schema-1.9-to-spacewalk-schema-1.10/010-add_rhncpu_nrsocket.sql  ALTER TABLE rhnCpu ADD nrsocket NUMERIC;
   0707010000079F000081B400000000000000000000000167AE11140000074B000000000000000000000000000000000000006100000000susemanager-schema/upgrade/spacewalk-schema-1.9-to-spacewalk-schema-1.10/011-rhn_channel.pkb.sql  --
-- Copyright (c) 2008--2013 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--

-- create schema rhn_channel;

--update pg_setting
update pg_settings set setting = 'rhn_channel,' || setting where name = 'search_path';

    create or replace function set_comps(channel_id_in in numeric, path_in in varchar, timestamp_in in varchar) returns void
    as $$
    declare
    row record;
    begin
        for row in (
            select relative_filename, last_modified
            from rhnChannelComps
            where channel_id = channel_id_in
            ) loop
            if row.relative_filename = path_in
                and row.last_modified = to_timestamp(timestamp_in, 'YYYYMMDDHH24MISS') then
                return;
            end if;
        end loop;
        delete from rhnChannelComps
        where channel_id = channel_id_in;
        insert into rhnChannelComps (id, channel_id, relative_filename, last_modified, created, modified)
        values (sequence_nextval('rhn_channelcomps_id_seq'), channel_id_in, path_in, to_timestamp(timestamp_in, 'YYYYMMDDHH24MISS'), current_timestamp, current_timestamp);
    end$$ language plpgsql;

-- restore the original setting
update pg_settings set setting = overlay( setting placing '' from 1 for (length('rhn_channel')+1) ) where name = 'search_path';
 070701000007A0000081B400000000000000000000000167AE11140000003E000000000000000000000000000000000000006800000000susemanager-schema/upgrade/spacewalk-schema-1.9-to-spacewalk-schema-1.10/012-rhnErrataFile-filename.sql   
ALTER TABLE rhnErrataFile ALTER filename TYPE VARCHAR(4000);
  070701000007A1000081B400000000000000000000000167AE1114000002FF000000000000000000000000000000000000006500000000susemanager-schema/upgrade/spacewalk-schema-1.9-to-spacewalk-schema-1.10/013-get_hw_info_as_clob.sql  
create or replace function get_hw_info_as_clob(
	sid in rhnserver.id%TYPE,
	separator in varchar
)
returns text
as
$$
declare
	ret text;
	rec record;
begin
	for rec in (
		select m
		from (
			select 1 n, sum(nrcpu) || ' CPUs ' || coalesce(to_char(sum(nrsocket), 'FM999'), 'unknown') || ' Sockets' m
			from rhncpu where rhncpu.server_id = sid
			union all
			select 2, ni.name||' '||coalesce(na4.address,'')||'/'||coalesce(na4.netmask,'')||' '||ni.hw_addr val
			from rhnservernetinterface ni,
			     rhnServerNetAddress4 na4
			where ni.server_id = sid
			  and ni.id = na4.interface_id
			) X
		order by n, m
		) loop
		if ret is null then
			ret := rec.m;
		else
			ret := ret || separator || rec.m;
		end if;
	end loop;
	return ret;
end;
$$ language plpgsql;

 070701000007A2000081B400000000000000000000000167AE11140000047C000000000000000000000000000000000000006000000000susemanager-schema/upgrade/spacewalk-schema-1.9-to-spacewalk-schema-1.10/014-pg_dblink_exec.sql   --
-- Copyright (c) 2012 - 2013 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.

create or replace function pg_dblink_exec(in_sql in varchar) returns void as
$$
begin
    if in_sql is null then
	raise 'pg_dblink_exec in_sql is null';
    end if;
    perform dblink_connect('at_conn', 'dbname=' || current_database() || ' port=' || coalesce(inet_server_port(), '5432'));
    begin
        perform dblink_exec('at_conn', in_sql, true);
    exception when others then
        perform dblink_disconnect('at_conn');
        raise;
    end;
    perform dblink_disconnect('at_conn');
end;
$$
language plpgsql;
070701000007A3000081B400000000000000000000000167AE1114000000A7000000000000000000000000000000000000007000000000susemanager-schema/upgrade/spacewalk-schema-1.9-to-spacewalk-schema-1.10/015-rhnKickstartScript-erroronfail.sql   ALTER TABLE rhnkickstartscript ADD error_on_fail CHAR(1)
    DEFAULT ('N') not NULL CONSTRAINT rhn_ksscript_erroronfail_ck
        CHECK (error_on_fail in ('Y','N'));
 070701000007A4000081B400000000000000000000000167AE111400000572000000000000000000000000000000000000006600000000susemanager-schema/upgrade/spacewalk-schema-1.9-to-spacewalk-schema-1.10/016-lookup_package_group.sql --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 

create or replace function
lookup_package_group(name_in in varchar)
returns numeric
as
$$
declare
    package_id   numeric;
begin
    select id
      into package_id
      from rhnPackageGroup
     where name = name_in;

    if not found then
        package_id := nextval('rhn_package_group_id_seq');
        begin
            perform pg_dblink_exec(
                'insert into rhnPackageGroup(id, name) values (' ||
                package_id || ', ' || coalesce(quote_literal(name_in), 'NULL') || ')');
        exception when unique_violation then
            select id
              into strict package_id
              from rhnPackageGroup
             where name = name_in;
        end;
    end if;

    return package_id;
end;
$$
language plpgsql immutable;
  070701000007A5000081B400000000000000000000000167AE111400000041000000000000000000000000000000000000006B00000000susemanager-schema/upgrade/spacewalk-schema-1.9-to-spacewalk-schema-1.10/017-rhnErrataFileTmp-filename.sql    
ALTER TABLE rhnErrataFileTmp ALTER filename TYPE VARCHAR(4000);
   070701000007A6000081B400000000000000000000000167AE1114000001BA000000000000000000000000000000000000006100000000susemanager-schema/upgrade/spacewalk-schema-1.9-to-spacewalk-schema-1.10/018-all_tab_columns.sql  
drop view all_tab_columns;

create or replace view all_tab_columns
as
select
        table_name              as table_name,
        column_name             as column_name,
        ordinal_position        as column_id,
        data_type               as data_type,
        numeric_precision       as data_precision,
        character_maximum_length as data_length,
        substr(is_nullable,1,1) as nullable
from information_schema.columns;
  070701000007A7000081B400000000000000000000000167AE111400000171000000000000000000000000000000000000006A00000000susemanager-schema/upgrade/spacewalk-schema-1.9-to-spacewalk-schema-1.10/019-rhnOrgConfiguration-scap.sql alter table rhnOrgConfiguration
  add scapfile_upload_enabled
      char(1) default ('N') not null
      constraint rhn_org_conf_scap_upload_chk check (scapfile_upload_enabled in ('Y', 'N'));
alter table rhnOrgConfiguration
  add scap_file_sizelimit
      NUMERIC default(2097152) not null
      constraint rhn_org_conf_scap_szlmt_chk check (scap_file_sizelimit >= 0);
   070701000007A8000081B400000000000000000000000167AE111400000038000000000000000000000000000000000000006400000000susemanager-schema/upgrade/spacewalk-schema-1.9-to-spacewalk-schema-1.10/019-rhnTaskoRun-status.sql   
ALTER TABLE rhnTaskoRun ALTER status TYPE VARCHAR(12);
070701000007A9000081B400000000000000000000000167AE111400000052000000000000000000000000000000000000006900000000susemanager-schema/upgrade/spacewalk-schema-1.9-to-spacewalk-schema-1.10/020-rhnConfigRevision-index.sql  
create index rhn_confrevision_ccid_idx on rhnConfigRevision (config_content_id);
  070701000007AA000081B400000000000000000000000167AE11140000182B000000000000000000000000000000000000006000000000susemanager-schema/upgrade/spacewalk-schema-1.9-to-spacewalk-schema-1.10/021-rhn_config.pkb.sql   --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--

-- setup search_path so that these functions are created in appropriate schema.
update pg_settings set setting = 'rhn_config,' || setting where name = 'search_path';


	-- just a stub for now
create or replace function prune_org_configs (
		org_id_in in numeric,
		total_in in numeric
	)
returns void
as $$	
begin
end;
$$ LANGUAGE 'plpgsql';


	create or replace function insert_revision (
		revision_in in numeric,
		config_file_id_in in numeric,
		config_content_id_in in numeric,
		config_info_id_in in numeric,
		config_file_type_id_in in numeric default 1
	) returns numeric as $$
               declare
		retval numeric;

	begin
      
		insert into rhnConfigRevision(id, revision, config_file_id,
				config_content_id, config_info_id, config_file_type_id
			) values (
				nextval('rhn_confrevision_id_seq'), revision_in, config_file_id_in,
				config_content_id_in, config_info_id_in, config_file_type_id_in
			)
			returning id into retval;

		return retval;
	end$$ language 'plpgsql';

	create or replace function delete_revision (
		config_revision_id_in in numeric,
		org_id_in in numeric default -1
	) returns void as $$
	declare
		cfid numeric;
		ccid numeric;
		latest_crid numeric;
		others numeric := 0;
	begin
		select	cr.config_content_id
		into	ccid
		from	rhnConfigRevision cr
		where	cr.id = config_revision_id_in;

		-- right now this will set rhnActionConfigFileName.config_revision_id
		-- to null, and will remove an entry from rhnActionConfigRevision.
		-- might we want to prune and/or kill the action in some way?  maybe
		-- mark it failed or something?
                -- this delete also triggers rhn_confrevision_del_trig() which
                -- a) updates rhnSnapshot.invalid to 'cr_removed'
                -- and b) deletes snapshots from rhnSnapshotConfigRevision
		delete from rhnConfigRevision where id = config_revision_id_in;

		-- now prune away content if there aren't any other revisions pointing
		-- at it
		select count(*)
                  into others
                  from rhnConfigRevision
                 where config_content_id = ccid;
		if others = 0 then
			delete from rhnConfigContent where id = ccid;
		end if;

		-- now make sure rhnConfigFile points at a valid revision;
		-- if there isn't one, we're deleting it, _unless_ org_id_in is
		-- >= 0, in which case we're in the delete trigger anyway
		if org_id_in < 0 then
			select	cf.latest_config_revision_id,
					cf.id
			into latest_crid,
					cfid
			from rhnConfigFile cf,
					rhnConfigRevision cr
			where cr.id = config_revision_id_in
				and cr.config_file_id = cf.id;

			if latest_crid = config_revision_id_in then
				latest_crid := rhn_config.get_latest_revision(cfid);
				if latest_crid is not null then
					update rhnConfigFile set latest_config_revision_id = latest_crid
						where id = cfid;
				else
					delete from rhnConfigFile where id = cfid;
				end if;
			end if;

		end if;

	end ;
$$ LANGUAGE 'plpgsql';

	create or replace function get_latest_revision (
		config_file_id_in in numeric
		) 
		returns numeric as $$
		declare 
 		revision1 record;
		begin
		for revision1 in 
			select cr.id 
			from rhnConfigRevision cr
			where cr.config_file_id = config_file_id_in
			order by revision desc
		loop
			return revision1.id;
		end loop;
		return null;
end;
$$ LANGUAGE 'plpgsql';

	create or replace function insert_file (
		config_channel_id_in in numeric,
		name_in in varchar
	) returns numeric as $$
		declare
		retval numeric;
	begin
		select nextval('rhn_conffile_id_seq')
		into retval;

		insert into rhnConfigFile(id, config_channel_id, config_file_name_id, 
				state_id
			) (
				select retval,
						config_channel_id_in,
						lookup_config_filename(name_in),
						id
				from rhnConfigFileState
				where label = 'alive'
			);

		return retval;
	end;
$$ LANGUAGE 'plpgsql';

	create or replace function delete_file (
		config_file_id_in in numeric
	) returns void as $$
declare
revision record;
			
	begin
		for revision in 
		select cr.id, cc.org_id
			from rhnConfigChannel cc,
					rhnConfigRevision cr,
					rhnConfigFile cf
			where cf.id = config_file_id_in
				and cf.config_channel_id = cc.id
				and cr.config_file_id = cf.id
		
                loop
			perform rhn_config.delete_revision(revision.id, revision.org_id);
		end loop;
		delete from rhnConfigFile where id = config_file_id_in;
	end;
$$ LANGUAGE 'plpgsql';

	create or replace function insert_channel (
		org_id_in in numeric,
		type_in in varchar,
		name_in in varchar,
		label_in in varchar,
		description_in in varchar
	) returns numeric as $$
declare
		retval numeric;
	begin
		select nextval ('rhn_confchan_id_seq')
		into retval;

		insert into rhnConfigChannel(id, org_id, confchan_type_id,
				name, label, description
			) (
				select	retval,
						org_id_in,
						cct.id,
						name_in,
						label_in,
						description_in
				from rhnConfigChannelType cct
				where label = type_in
			);
		return retval;
	end;
$$ LANGUAGE 'plpgsql';

	create or replace function delete_channel (
		config_channel_id_in in numeric
	) returns void as $$
declare
	config_file record;		
	begin
		for config_file in 
		select id
			from rhnConfigFile
			where config_channel_id = config_channel_id_in
                loop
                    perform rhn_config.delete_file(config_file.id);
		end loop;
		delete from rhnConfigChannel where id = config_channel_id_in;

end;
$$ LANGUAGE 'plpgsql';

update pg_settings set setting = overlay( setting placing '' from 1 for (length('rhn_config')+1) ) where name = 'search_path';
 070701000007AB000081B400000000000000000000000167AE111400000230000000000000000000000000000000000000005D00000000susemanager-schema/upgrade/spacewalk-schema-1.9-to-spacewalk-schema-1.10/022-rhnISSSlave.sql  create table rhnISSSlave (
    id NUMERIC not null constraint rhn_isss_id_pk primary key,
    slave VARCHAR(512) not null constraint rhn_isss_name_uq unique,
    enabled char(1) default 'Y' not null
        constraint rhn_isss_enabled_yn check (enabled in ( 'Y', 'N' )),
    allow_all_orgs char(1) default 'Y' not null
        constraint rhn_isss_allorgs_yn check (allow_all_orgs in ( 'Y', 'N' )),
    created TIMESTAMPTZ default (current_timestamp) not null,
    modified TIMESTAMPTZ default (current_timestamp) not null
);

create sequence rhn_issslave_seq;
070701000007AC000081B400000000000000000000000167AE111400000132000000000000000000000000000000000000006100000000susemanager-schema/upgrade/spacewalk-schema-1.9-to-spacewalk-schema-1.10/023-rhnISSSlaveOrgs.sql  create table rhnISSSlaveOrgs (
    slave_id NUMERIC not null constraint rhn_isssorg_sid_fk references rhnISSSlave(id) on delete cascade,
    org_id NUMERIC not null constraint rhn_isssorg_oid_fk references web_customer(id) on delete cascade,
    created TIMESTAMPTZ default (current_timestamp) not null
);
  070701000007AD000081B400000000000000000000000167AE111400000110000000000000000000000000000000000000005E00000000susemanager-schema/upgrade/spacewalk-schema-1.9-to-spacewalk-schema-1.10/024-rhnISSMaster.sql create table rhnIssMaster (
    id NUMERIC not null constraint rhn_iss_master_id_pk primary key,
    label VARCHAR(256) not null constraint rhn_iss_master_label_uq unique,
    created TIMESTAMPTZ default (current_timestamp) not null
);

create sequence rhn_issmaster_seq;
070701000007AE000081B400000000000000000000000167AE1114000001FB000000000000000000000000000000000000006200000000susemanager-schema/upgrade/spacewalk-schema-1.9-to-spacewalk-schema-1.10/025-rhnISSMasterOrgs.sql create table rhnIssMasterOrgs (
    id NUMERIC not null constraint rhn_issmasterorgs_id_pk primary key,
    master_id NUMERIC not null
        constraint rhn_issmasterorgs_cid_fk references rhnIssMaster(id) on delete cascade,
    master_org_id NUMERIC not null,
    master_org_name VARCHAR(512) not null,
    local_org_id NUMERIC
        constraint rhn_issmasterorgs_lid_fk references web_customer(id),
    created TIMESTAMPTZ default (current_timestamp) not null
);

create sequence rhn_issmasterorgs_seq;
 070701000007AF000081B400000000000000000000000167AE1114000002C4000000000000000000000000000000000000006C00000000susemanager-schema/upgrade/spacewalk-schema-1.9-to-spacewalk-schema-1.10/026-rhnConfigRevision-triggers.sql   
create or replace function rhn_confrevision_del_trig_fun() returns trigger 
as
$$
declare
        cr_removed numeric := lookup_snapshot_invalid_reason('cr_removed');
begin
        update rhnSnapshot
           set invalid = cr_removed
         where id in (select snapshot_id
                        from rhnSnapshotConfigRevision
                       where config_revision_id = old.id);
        delete from rhnSnapshotConfigRevision
         where config_revision_id = old.id
           and snapshot_id in (select snapshot_id
                                 from rhnSnapshotConfigRevision
                                where config_revision_id = old.id);
        return old;
end;
$$ language plpgsql;
070701000007B0000081B400000000000000000000000167AE11140000008E000000000000000000000000000000000000006000000000susemanager-schema/upgrade/spacewalk-schema-1.9-to-spacewalk-schema-1.10/027-web_contact-ro.sql   alter table web_contact
    add read_only char(1) default('N') not null
        constraint web_contact_ro_ck check (read_only in ('Y', 'N'));
  070701000007B1000081B400000000000000000000000167AE111400000143000000000000000000000000000000000000006D00000000susemanager-schema/upgrade/spacewalk-schema-1.9-to-spacewalk-schema-1.10/028-satellite_sync_master_in_db.sql  
alter table rhnISSMaster add is_current_master char(1) default 'N' not null
    constraint rhn_issm_master_yn check (is_current_master in ('Y', 'N'));

alter table rhnISSMaster add ca_cert varchar(1024);

create unique index rhn_issm_only_one_default on rhnISSMaster
    (is_current_master) where is_current_master = 'Y';
 070701000007B2000081B400000000000000000000000167AE111400000030000000000000000000000000000000000000005B00000000susemanager-schema/upgrade/spacewalk-schema-1.9-to-spacewalk-schema-1.10/029-rhnServer.sql    ALTER TABLE rhnServer DROP COLUMN auto_deliver;
070701000007B3000081B400000000000000000000000167AE1114000000F0000000000000000000000000000000000000006100000000susemanager-schema/upgrade/spacewalk-schema-1.9-to-spacewalk-schema-1.10/030-web_contact_all.sql  CREATE TABLE web_contact_all
(
    id                 NUMERIC
                           CONSTRAINT web_contact_all_pk PRIMARY KEY
                           ,
    org_id             NUMERIC,
    login              VARCHAR(64) NOT NULL
)
;
070701000007B4000081B400000000000000000000000167AE111400000108000000000000000000000000000000000000006600000000susemanager-schema/upgrade/spacewalk-schema-1.9-to-spacewalk-schema-1.10/031-web_contact_all-data.sql INSERT INTO web_contact_all (id, org_id, login)
        VALUES (-1, null, 'SETUP');
INSERT INTO web_contact_all (id, org_id, login)
        VALUES (-2, null, 'CLIENT');
INSERT INTO web_contact_all (id, org_id, login)
    SELECT id, org_id, login FROM web_contact;
070701000007B5000081B400000000000000000000000167AE111400000144000000000000000000000000000000000000006600000000susemanager-schema/upgrade/spacewalk-schema-1.9-to-spacewalk-schema-1.10/032-web_contact-triggers.sql 
create or replace function web_contact_ins_trig_fun() returns trigger
as
$$
begin
        new.modified := current_timestamp;
        new.login_uc := UPPER(new.login);
        insert into web_contact_all (id, org_id, login)
            values (new.id, new.org_id, new.login);

        return new;
end;
$$
language plpgsql;

070701000007B6000081B400000000000000000000000167AE1114000000AE000000000000000000000000000000000000005500000000susemanager-schema/upgrade/spacewalk-schema-1.9-to-spacewalk-schema-1.10/033-log.sql  CREATE TABLE log
(
    id INTEGER NOT NULL PRIMARY KEY,
    stamp TIMESTAMP WITH TIME ZONE,
    user_id INTEGER REFERENCES web_contact_all(id)
)

;

CREATE SEQUENCE log_seq;
  070701000007B7000081B400000000000000000000000167AE11140000027E000000000000000000000000000000000000005D00000000susemanager-schema/upgrade/spacewalk-schema-1.9-to-spacewalk-schema-1.10/034-logging.pks.sql  --
-- Copyright (c) 2013 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

create schema ;
  070701000007B8000081B400000000000000000000000167AE111400001961000000000000000000000000000000000000005D00000000susemanager-schema/upgrade/spacewalk-schema-1.9-to-spacewalk-schema-1.10/035-logging.pkb.sql  --
-- Copyright (c) 2013 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

-- create schema ;

update pg_settings set setting = ',' || setting where name = 'search_path';

create or replace function clear_log_id()
returns void
as
$$
    global the_log_id
    set the_log_id 0
    global the_user_id
    set the_user_id 0
    global the_stamp
    set the_stamp ""
    return
$$ language pltclu set search_path from current;

create or replace function _set_log_auth(user_id in integer, stamp in varchar)
returns void
as
$$
    global the_user_id
    set the_user_id $1
    global the_stamp
    set the_stamp $2
$$ language pltclu set search_path from current;

create or replace function set_log_auth(user_id in integer)
returns void
as
$$
begin
    perform _set_log_auth(user_id, current_timestamp::varchar);
end
$$ language plpgsql set search_path from current;

create or replace function _get_log_auth()
returns integer
as
$$
    global the_user_id
    return $the_user_id
$$ language pltclu set search_path from current;

create or replace function _get_log_stamp()
returns varchar
as
$$
    global the_stamp
    return $the_stamp
$$ language pltclu set search_path from current;

create or replace function _get_log_id()
returns integer
as
$$
    global the_log_id
    return $the_log_id
$$ language pltclu set search_path from current;

create or replace function _set_log_id(log_id in integer)
returns void
as
$$
    global the_log_id
    set the_log_id $1
    return
$$ language pltclu set search_path from current;

create or replace function get_log_id()
returns integer
as
$$
declare
    the_log_id integer;
    the_user_id integer;
    the_stamp varchar;
begin
    the_log_id := _get_log_id();
    if the_log_id is not null and the_log_id > 0 then return the_log_id ; end if;
    the_log_id := nextval('log_seq');
    the_user_id := _get_log_auth();
    the_stamp := _get_log_stamp();
    insert into public.log (id, stamp, user_id)
    values (the_log_id,
        case when the_stamp = '' then current_timestamp else the_stamp::timestamp with time zone end,
        case when the_user_id = '0' then null else the_user_id::integer end);
    perform _set_log_id(the_log_id);
    return the_log_id;
end;
$$ language plpgsql set search_path from current;

create or replace function enable_(table_name_in in varchar)
returns void
as
$$
declare
    pk_column varchar;
    ddl_columns varchar;
    the_insert varchar;
    rec record;
begin
    select constraint_column_usage.column_name into strict pk_column
    from information_schema.table_constraints, information_schema.constraint_column_usage
    where constraint_column_usage.table_catalog = current_catalog
        and constraint_column_usage.table_schema = 'public'
        and constraint_column_usage.table_name = table_name_in
        and constraint_column_usage.constraint_catalog = current_catalog
        and constraint_column_usage.constraint_schema = 'public'
        and constraint_column_usage.table_catalog = table_constraints.constraint_catalog
        and constraint_column_usage.table_catalog = table_constraints.table_catalog
        and constraint_column_usage.table_schema = table_constraints.constraint_schema
        and constraint_column_usage.table_schema = table_constraints.table_schema
        and constraint_column_usage.constraint_catalog = table_constraints.constraint_catalog
        and constraint_column_usage.constraint_name = table_constraints.constraint_name
        and table_constraints.constraint_type = 'PRIMARY KEY';
    ddl_columns := '';
    for rec in (
        select column_name
        from information_schema.columns
        where table_catalog = current_catalog
            and table_schema = 'public'
            and table_name = table_name_in
            and column_name not in ( pk_column, 'created', 'modified' )
    ) loop
        ddl_columns := ddl_columns || ', ' || rec.column_name;
    end loop;

    execute 'create table public.' || table_name_in || '_log
        as select ' || pk_column || ', .get_log_id()::integer as log_id, ''A''::char as action' || ddl_columns
        || ' from ' || table_name_in;
    execute 'alter table public.' || table_name_in || '_log alter ' || pk_column || ' set not null';
    execute 'create index ' || table_name_in || '_log_idx on public.' || table_name_in || '_log(' || pk_column || ')';
    execute 'alter table public.' || table_name_in || '_log alter log_id set not null';
    execute 'alter table public.' || table_name_in || '_log add foreign key (log_id) references log(id)';
    execute 'alter table public.' || table_name_in || '_log alter action set not null';

    the_insert := 'insert into public.' || table_name_in || '_log (log_id, action, ' || pk_column || ddl_columns ||')
                values (log_id_v, substr(tg_op, 1, 1)' || replace(', ' || pk_column || ddl_columns, ', ', ', old.') || ');';
    execute 'create or replace function public.' || table_name_in || '_log_trig_fun() returns trigger as
        ''
        declare
            log_id_v integer;
        begin
            log_id_v := .get_log_id();
            if tg_op = ''''UPDATE'''' then
                if old.' || pk_column || ' <> new.' || pk_column || ' then raise exception ''''Cannot update column ' || table_name_in || '.' || pk_column || '.''''; end if;
            end if;
            if tg_op = ''''DELETE'''' then
                ' || the_insert || '
            else
                ' || replace(the_insert, 'old.', 'new.') || '
            end if;
            return new;
        end;
        ''
        language plpgsql;';

    execute 'create trigger ' || table_name_in || '_log_trig
        after insert or update or delete on public.' || table_name_in || '
        for each row
        execute procedure ' || table_name_in || '_log_trig_fun()';

end;
$$
language plpgsql;

update pg_settings set setting = overlay( setting placing '' from 1 for (length('')+1) ) where name = 'search_path';
   070701000007B9000081B400000000000000000000000167AE1114000002FC000000000000000000000000000000000000006000000000susemanager-schema/upgrade/spacewalk-schema-1.9-to-spacewalk-schema-1.10/036-enable_logging.sql   --
-- Copyright (c) 2013 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

select .clear_log_id();
select .enable_logging('web_contact');
select .enable_logging('rhnserver');
select .enable_logging('rhnservergroup');
070701000007BA000081B400000000000000000000000167AE111400000198000000000000000000000000000000000000005F00000000susemanager-schema/upgrade/spacewalk-schema-1.9-to-spacewalk-schema-1.10/037-rhnPackageKey.sql    update rhnPackageKey set provider_id = lookup_package_provider('Fedora')
 where key_id = '07477e65fb4b18e6';

insert into rhnPackageKey (id, key_id, key_type_id, provider_id)
    (select sequence_nextval('rhn_pkey_id_seq'), '07477e65fb4b18e6', lookup_package_key_type('gpg'), lookup_package_provider('Fedora') from dual
     where not exists (select 1 from rhnPackageKey where key_id = '07477e65fb4b18e6'));
070701000007BB000081B400000000000000000000000167AE11140000001B000000000000000000000000000000000000005000000000susemanager-schema/upgrade/spacewalk-schema-1.9-to-spacewalk-schema-1.10/README   -- Schema upgrade scripts.
 070701000007BC000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000004800000000susemanager-schema/upgrade/spacewalk-schema-2.0-to-spacewalk-schema-2.1   070701000007BD000081B400000000000000000000000167AE111400000054000000000000000000000000000000000000005400000000susemanager-schema/upgrade/spacewalk-schema-2.0-to-spacewalk-schema-2.1/001-log.sql   
ALTER TABLE log ALTER id TYPE numeric;
ALTER TABLE log ALTER user_id TYPE numeric;
070701000007BE000081B400000000000000000000000167AE1114000000A7000000000000000000000000000000000000005B00000000susemanager-schema/upgrade/spacewalk-schema-2.0-to-spacewalk-schema-2.1/002-log-tables.sql    
ALTER TABLE web_contact_log ALTER log_id TYPE numeric;
ALTER TABLE rhnServer_log ALTER log_id TYPE numeric;
ALTER TABLE rhnServerGroup_log ALTER log_id TYPE numeric;
 070701000007BF000081B400000000000000000000000167AE111400001F07000000000000000000000000000000000000005C00000000susemanager-schema/upgrade/spacewalk-schema-2.0-to-spacewalk-schema-2.1/004-logging.pkb.sql   --
-- Copyright (c) 2013 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

-- create schema ;

update pg_settings set setting = ',' || setting where name = 'search_path';

drop function clear_log_id();
drop function _set_log_auth(user_id in integer, stamp in varchar);
drop function set_log_auth(user_id in integer);
drop function _get_log_auth();
drop function _get_log_stamp();
drop function _get_log_id();
drop function _set_log_id(log_id in integer);
drop function get_log_id();
drop function enable_(table_name_in in varchar);

create or replace function clear_log_id()
returns void
as
$$
    global the_log_id
    set the_log_id 0
    global the_user_id
    set the_user_id 0
    global the_stamp
    set the_stamp ""
    return
$$ language pltclu set search_path from current;

create or replace function _set_log_auth(user_id in numeric, stamp in varchar)
returns void
as
$$
    global the_user_id
    set the_user_id $1
    global the_stamp
    set the_stamp $2
$$ language pltclu set search_path from current;

create or replace function set_log_auth(user_id in numeric)
returns void
as
$$
begin
    perform _set_log_auth(user_id, current_timestamp::varchar);
end
$$ language plpgsql set search_path from current;

create or replace function _get_log_auth()
returns numeric
as
$$
    global the_user_id
    return $the_user_id
$$ language pltclu set search_path from current;

create or replace function _get_log_stamp()
returns varchar
as
$$
    global the_stamp
    return $the_stamp
$$ language pltclu set search_path from current;

create or replace function _get_log_id()
returns numeric
as
$$
    global the_log_id
    return $the_log_id
$$ language pltclu set search_path from current;

create or replace function _set_log_id(log_id in numeric)
returns void
as
$$
    global the_log_id
    set the_log_id $1
    return
$$ language pltclu set search_path from current;

create or replace function get_log_id()
returns numeric
as
$$
declare
    the_log_id numeric;
    the_user_id numeric;
    the_stamp varchar;
begin
    the_log_id := _get_log_id();
    if the_log_id is not null and the_log_id > 0 then return the_log_id ; end if;
    the_log_id := nextval('log_seq');
    the_user_id := _get_log_auth();
    the_stamp := _get_log_stamp();
    insert into public.log (id, stamp, user_id)
    values (the_log_id,
        case when the_stamp = '' then current_timestamp else the_stamp::timestamp with time zone end,
        case when the_user_id = '0' then null else the_user_id::numeric end);
    perform _set_log_id(the_log_id);
    return the_log_id;
end;
$$ language plpgsql set search_path from current;

create or replace function _get_primary_key_column(table_name_in in varchar)
returns varchar
as
$$
declare
    pk_column varchar;
begin
    select constraint_column_usage.column_name into strict pk_column
    from information_schema.table_constraints, information_schema.constraint_column_usage
    where constraint_column_usage.table_catalog = current_catalog
        and constraint_column_usage.table_schema = 'public'
        and constraint_column_usage.table_name = lower(table_name_in)
        and constraint_column_usage.constraint_catalog = current_catalog
        and constraint_column_usage.constraint_schema = 'public'
        and constraint_column_usage.table_catalog = table_constraints.constraint_catalog
        and constraint_column_usage.table_catalog = table_constraints.table_catalog
        and constraint_column_usage.table_schema = table_constraints.constraint_schema
        and constraint_column_usage.table_schema = table_constraints.table_schema
        and constraint_column_usage.constraint_catalog = table_constraints.constraint_catalog
        and constraint_column_usage.constraint_name = table_constraints.constraint_name
        and table_constraints.constraint_type = 'PRIMARY KEY';
    return pk_column;
end;
$$
language plpgsql set search_path from current;

create or replace function _get_ddl_columns(table_name_in in varchar, pk_column_in in varchar)
returns varchar
as
$$
declare
    ddl_columns varchar;
    rec record;
begin
    ddl_columns := '';
    for rec in (
        select column_name
        from information_schema.columns
        where table_catalog = current_catalog
            and table_schema = 'public'
            and table_name = lower(table_name_in)
            and column_name not in (pk_column_in, 'created', 'modified' )
    ) loop
        ddl_columns := ddl_columns || ', ' || rec.column_name;
    end loop;
    return ddl_columns;
end;
$$
language plpgsql set search_path from current;


create or replace function recreate_trigger(table_name_in in varchar)
returns void
as
$$
declare
    pk_column varchar;
    ddl_columns varchar;
    the_insert varchar;
begin
    pk_column := _get_primary_key_column(table_name_in);
    ddl_columns := _get_ddl_columns(table_name_in, pk_column);
    the_insert := 'insert into public.' || table_name_in || '_log (log_id, action, ' || pk_column || ddl_columns ||')
                values (log_id_v, substr(tg_op, 1, 1)' || replace(', ' || pk_column || ddl_columns, ', ', ', old.') || ');';
    execute 'create or replace function public.' || table_name_in || '_log_trig_fun() returns trigger as
        ''
        declare
            log_id_v numeric;
        begin
            log_id_v := .get_log_id();
            if tg_op = ''''UPDATE'''' then
                if old.' || pk_column || ' <> new.' || pk_column || ' then raise exception ''''Cannot update column ' || table_name_in || '.' || pk_column || '.''''; end if;
            end if;
            if tg_op = ''''DELETE'''' then
                ' || the_insert || '
            else
                ' || replace(the_insert, 'old.', 'new.') || '
            end if;
            return new;
        end;
        ''
        language plpgsql;';

    execute 'drop trigger if exists ' || table_name_in || '_log_trig' || ' on ' || table_name_in;
    execute 'create trigger ' || table_name_in || '_log_trig
        after insert or update or delete on public.' || table_name_in || '
        for each row
        execute procedure ' || table_name_in || '_log_trig_fun()';

end;
$$
language plpgsql set search_path from current;

create or replace function enable_(table_name_in in varchar)
returns void
as
$$
declare
    pk_column varchar;
    ddl_columns varchar;
begin
    pk_column := _get_primary_key_column(table_name_in);
    ddl_columns := _get_ddl_columns(table_name_in, pk_column);

    execute 'create table public.' || table_name_in || '_log
        as select ' || pk_column || ', .get_log_id()::numeric as log_id, ''A''::char as action' || ddl_columns
        || ' from ' || table_name_in;
    execute 'alter table public.' || table_name_in || '_log alter ' || pk_column || ' set not null';
    execute 'create index ' || table_name_in || '_log_idx on public.' || table_name_in || '_log(' || pk_column || ')';
    execute 'alter table public.' || table_name_in || '_log alter log_id set not null';
    execute 'alter table public.' || table_name_in || '_log add foreign key (log_id) references log(id)';
    execute 'alter table public.' || table_name_in || '_log alter action set not null';
    perform recreate_trigger(table_name_in);
end;
$$
language plpgsql set search_path from current;

update pg_settings set setting = overlay( setting placing '' from 1 for (length('')+1) ) where name = 'search_path';
 070701000007C0000081B400000000000000000000000167AE11140000007D000000000000000000000000000000000000006A00000000susemanager-schema/upgrade/spacewalk-schema-2.0-to-spacewalk-schema-2.1/005-logging-recreate-triggers.sql 
select .recreate_trigger('web_contact');
select .recreate_trigger('rhnserver');
select .recreate_trigger('rhnservergroup');
   070701000007C1000081B400000000000000000000000167AE111400010654000000000000000000000000000000000000006500000000susemanager-schema/upgrade/spacewalk-schema-2.0-to-spacewalk-schema-2.1/010-rhn_entitlements.pkb.sql  --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

-- create schema rhn_entitlements;

-- setup search_path so that these functions are created in appropriate schema.
update pg_settings set setting = 'rhn_entitlements,' || setting where name = 'search_path';

   create or replace function find_compatible_sg (
      server_id_in in numeric,
      type_label_in in varchar
   )
   returns numeric
as $$
    declare
      servergroups cursor for
         select sg.id
           from rhnServerGroupType             sgt,
                rhnServerGroup                 sg,
                rhnServer                     s,
                rhnServerServerGroupArchCompat ssgac
          where s.id = server_id_in
            and s.org_id = sg.org_id
            and sgt.label = type_label_in
            and sg.group_type = sgt.id
            and ssgac.server_group_type = sgt.id
            and ssgac.server_arch_id = s.server_arch_id
            and not exists (
                     select 1
                      from rhnServerGroupMembers sgm
                     where sgm.server_group_id = sg.id
                       and sgm.server_id = s.id);


   begin
      for servergroup in servergroups loop
         return servergroup.id;
      end loop;

      --no servergroup found
      return NULL;
   end$$
language plpgsql;

    -- *******************************************************************
    -- PROCEDURE: remove_org_entitlements
    --
    -- Removes both system entitlements and channel subscriptions
    -- that are currently assigned to an org and re-assigns to the
    -- master org (org_id = 1).
    --
    -- When we call this we expect everything to already be unentitled
    -- which shoul be handled by delete_org.
    --
    -- Called by: delete_org
    -- *******************************************************************
    create or replace function remove_org_entitlements (
        org_id_in numeric
    ) returns void
as $$
    declare
        system_ents cursor for
        select sg.id, sg.max_members, sg.group_type
        from rhnServerGroup sg
        where group_type is not null
          and org_id = org_id_in;

        channel_subs cursor for
        select pcf.channel_family_id, pcf.max_members
        from rhnChannelFamily cf,
             rhnPrivateChannelFamily pcf
        where pcf.org_id = org_id_in
          and pcf.channel_family_id = cf.id
          and cf.org_id is null;

    begin

        for system_ent in system_ents loop
            update rhnServerGroup
            set max_members = max_members + system_ent.max_members
            where org_id = 1
              and group_type = system_ent.group_type;
        end loop;

        update rhnServerGroup
        set max_members = 0
        where org_id = org_id_in;

        for channel_sub in channel_subs loop
            update rhnPrivateChannelFamily
            set max_members = max_members + channel_sub.max_members
            where org_id = 1
              and channel_family_id = channel_sub.channel_family_id;
        end loop;

        update rhnPrivateChannelFamily
        set max_members = 0
        where org_id = org_id_in;

    end$$
language plpgsql;

    create or replace function entitlement_grants_service (
        entitlement_in in varchar,
        service_level_in in varchar
    ) returns numeric
as $$
    begin
        if service_level_in = 'provisioning' then
            if entitlement_in = 'provisioning_entitled' then
                return 1;
            else
                return 0;
            end if;
        elsif service_level_in = 'management' then
            if entitlement_in = 'enterprise_entitled' then
                return 1;
            else
                return 0;
            end if;
        elsif service_level_in = 'monitoring' then
            if entitlement_in = 'monitoring_entitled' then
                return 1;
            end if;
        elsif service_level_in = 'updates' then
            return 1;
        else
            return 0;
        end if;
    end$$
language plpgsql;

    create or replace function lookup_entitlement_group (
        org_id_in in numeric,
        type_label_in in varchar default 'sw_mgr_entitled'
    ) returns numeric
as $$
    declare
        server_groups cursor for
            select  sg.id               server_group_id
            from    rhnServerGroup      sg,
                    rhnServerGroupType  sgt
            where   sgt.label = type_label_in
                and sgt.id = sg.group_type
                and sg.org_id = org_id_in;
    begin
        for sg in server_groups loop
            return sg.server_group_id;
        end loop;
        return rhn_entitlements.create_entitlement_group(
                org_id_in,
                type_label_in
            );
    end$$
language plpgsql;

    create or replace function create_entitlement_group (
        org_id_in in numeric,
        type_label_in in varchar default 'sw_mgr_entitled'
    ) returns numeric
as $$
    declare
        sg_id_val numeric;
    begin
        select  nextval('rhn_server_group_id_seq')
        into    sg_id_val;

        insert into rhnServerGroup (
                id, name, description, max_members, current_members,
                group_type, org_id
            ) (
                select  sg_id_val, sgt.label, sgt.label,
                        0, 0, sgt.id, org_id_in
                from    rhnServerGroupType sgt
                where   sgt.label = type_label_in
            );

        return sg_id_val;
    end$$
language plpgsql;

   create or replace function can_entitle_server (
      server_id_in   in numeric,
      type_label_in  in varchar
   )
   returns numeric
as $$
    declare
      addon_servergroups cursor (base_label_in varchar,
                                 addon_label_in varchar) for
         select
            addon_id
         from
            rhnSGTypeBaseAddonCompat
         where base_id = lookup_sg_type (base_label_in)
           and addon_id = lookup_sg_type (addon_label_in);

      previous_ent        varchar[];
      is_base_in          char   := 'N';
      is_base_current     char   := 'N';
      i                   numeric := 0;
      sgid                numeric := 0;

   begin

      previous_ent := rhn_entitlements.get_server_entitlement(server_id_in);

      select distinct is_base
      into is_base_in
      from rhnServerGroupType
      where label = type_label_in;

      if array_upper(previous_ent, 1) is null or array_upper(previous_ent, 1) = 0 then
         if is_base_in = 'Y' then
            sgid := rhn_entitlements.find_compatible_sg (server_id_in, type_label_in);
            if sgid is not null then
              -- rhn_server.insert_into_servergroup (server_id_in, sgid);
              return 1;
            else
              -- rhn_exception.raise_exception ('invalid_base_entitlement');
              return 0;
            end if;
         else
            -- rhn_exception.raise_exception ('invalid_base_entitlement');
            return 0;
         end if;

      -- there are previous ents, first make sure we're not trying to entitle a base ent
      elsif is_base_in = 'Y' then
         -- rhn_exception.raise_exception ('invalid_addon_entitlement');
         return 0;

      -- it must be an addon, so proceed with the entitlement
      else

         -- find the servers base ent
         is_base_current := 'N';
         i := 0;
         while is_base_current = 'N' and i < array_upper(previous_ent, 1)
         loop
            i := i + 1;
            select is_base
            into is_base_current
            from rhnServerGroupType
            where label = previous_ent[i];
         end loop;

         -- never found a base ent, that would be strange
         if is_base_current  = 'N' then
            -- rhn_exception.raise_exception ('invalid_base_entitlement');
            return 0;
         end if;

         -- this for loop verifies the validity of the addon path
         for addon_servergroup in addon_servergroups  (previous_ent[i], type_label_in) loop
            -- find an appropriate sgid for the addon and entitle the server
            sgid := rhn_entitlements.find_compatible_sg (server_id_in, type_label_in);
            if sgid is not null then
               -- rhn_server.insert_into_servergroup (server_id_in, sgid);
               return 1;
            else
               -- rhn_exception.raise_exception ('invalid_addon_entitlement');
               return 0;
            end if;
         end loop;

      end if;

      return 0;

   end$$
language plpgsql;

   create or replace function can_switch_base (
      server_id_in   in    integer,
      type_label_in  in    varchar
   )
   returns numeric
as $$
   declare
      type_label_in_is_base   char(1);
      sgid                    numeric;

   begin

       select is_base into type_label_in_is_base
       from rhnServerGroupType
       where label = type_label_in;

       if not found then
          perform rhn_exception.raise_exception ( 'invalid_entitlement' );
       end if;

      if type_label_in_is_base = 'N' then
         perform rhn_exception.raise_exception ( 'invalid_entitlement' );
      else
         sgid := rhn_entitlements.find_compatible_sg ( server_id_in,
                                                       type_label_in );
         if sgid is not null then
           return 1;
         else
           return 0;
         end if;
      end if;

   end$$
language plpgsql;

    create or replace function entitle_server (
        server_id_in in numeric,
        type_label_in in varchar default 'sw_mgr_entitled'
    ) returns void
as $$
    declare
      sgid  numeric := 0;
      is_virt numeric := 0;

    begin

      select 1 into is_virt
        from rhnServerEntitlementView
        where server_id = server_id_in
          and label in ('virtualization_host', 'virtualization_host_platform');

      if not found then
          is_virt := 0;
      end if;

      if is_virt = 0 and (type_label_in = 'virtualization_host' or
                          type_label_in = 'virtualization_host_platform') then

        is_virt := 1;
      end if;

      if rhn_entitlements.can_entitle_server(server_id_in,
                                             type_label_in) = 1 then
         sgid := rhn_entitlements.find_compatible_sg (server_id_in,
                                                      type_label_in);
         if sgid is not null then
            insert into rhnServerHistory ( id, server_id, summary, details )
            values ( nextval('rhn_event_id_seq'), server_id_in,
                     'added system entitlement ',
                      case type_label_in
                       when 'enterprise_entitled' then 'Management'
                       when 'sw_mgr_entitled' then 'Update'
                       when 'provisioning_entitled' then 'Provisioning'
                       when 'monitoring_entitled' then 'Monitoring'
                       when 'virtualization_host' then 'Virtualization'
                       when 'virtualization_host_platform' then
                            'Virtualization Platform' end  );

            perform rhn_server.insert_into_servergroup (server_id_in, sgid);

            if is_virt = 1 then
              perform rhn_entitlements.repoll_virt_guest_entitlements(server_id_in);
            end if;

         else
            perform rhn_exception.raise_exception ('no_available_server_group');
         end if;
      else
         perform rhn_exception.raise_exception ('invalid_entitlement');
      end if;
   end$$
language plpgsql;

    create or replace function remove_server_entitlement (
        server_id_in in numeric,
        type_label_in in varchar default 'sw_mgr_entitled',
        repoll_virt_guests in numeric default 1
    ) returns void
as $$
    declare
      group_id numeric;
      type_is_base char;
      is_virt numeric := 0;
    begin
      -- would be nice if there were a virt attribute of entitlement types, not have to specify 2 different ones...
        select 1 into is_virt
          from rhnServerEntitlementView
          where server_id = server_id_in
            and label in ('virtualization_host', 'virtualization_host_platform');
        if not found then
            is_virt := 0;
        end if;

        select  sg.id, sgt.is_base
        into group_id, type_is_base
        from    rhnServerGroupType sgt,
            rhnServerGroup sg,
                rhnServerGroupMembers sgm,
                rhnServer s
        where   s.id = server_id_in
            and s.id = sgm.server_id
            and sgm.server_group_id = sg.id
            and sg.org_id = s.org_id
            and sgt.label = type_label_in
            and sgt.id = sg.group_type;

        if not found then
          perform rhn_exception.raise_exception('invalid_server_group_member');
        end if;

      if ( type_is_base = 'Y' ) then
         -- unentitle_server should handle everything, don't really need to do anything else special here
         perform rhn_entitlements.unentitle_server ( server_id_in );
      else

         insert into rhnServerHistory ( id, server_id, summary, details )
         values ( nextval('rhn_event_id_seq'), server_id_in,
                  'removed system entitlement ',
                   case type_label_in
                    when 'enterprise_entitled' then 'Management'
                    when 'sw_mgr_entitled' then 'Update'
                    when 'provisioning_entitled' then 'Provisioning'
                    when 'monitoring_entitled' then 'Monitoring'
                    when 'virtualization_host' then 'Virtualization'
                    when 'virtualization_host_platform' then
                         'Virtualization Platforrm' end  );

         perform rhn_server.delete_from_servergroup(server_id_in, group_id);

         if type_label_in = 'monitoring_entitled' then
           DELETE
             FROM rhn_probe
            WHERE recid IN (SELECT probe_id
                              FROM rhn_check_probe
                             WHERE host_id = server_id_in);
         end if;

         if is_virt = 1 and repoll_virt_guests = 1 then
           perform rhn_entitlements.repoll_virt_guest_entitlements(server_id_in);
         end if;
      end if;

    end$$
language plpgsql;

    create or replace function unentitle_server (
        server_id_in in numeric
    ) returns void
as $$
    declare
      servergroups cursor for
         select distinct sgt.label, sg.id server_group_id
         from  rhnServerGroupType sgt,
               rhnServerGroup sg,
               rhnServer s,
               rhnServerGroupMembers sgm
         where s.id = server_id_in
            and s.org_id = sg.org_id
            and sg.group_type = sgt.id
            and sgm.server_group_id = sg.id
            and sgm.server_id = s.id;

     is_virt numeric := 0;

   begin

      select 1 into is_virt
        from rhnServerEntitlementView
        where server_id = server_id_in
         and label in ('virtualization_host', 'virtualization_host_platform');

      if not found then
          is_virt := 0;
      end if;

      for servergroup in servergroups loop

         insert into rhnServerHistory ( id, server_id, summary, details )
         values ( nextval('rhn_event_id_seq'), server_id_in,
                  'removed system entitlement ',
                   case servergroup.label
                    when 'enterprise_entitled' then 'Management'
                    when 'sw_mgr_entitled' then 'Update'
                    when 'provisioning_entitled' then 'Provisioning'
                    when 'monitoring_entitled' then 'Monitoring'
                    when 'virtualization_host' then 'Virtualization'
                    when 'virtualization_host_platform' then
                         'Virtualization Platform' end  );

         perform rhn_server.delete_from_servergroup(server_id_in,
                                            servergroup.server_group_id );
      end loop;

      if is_virt = 1 then
        perform rhn_entitlements.repoll_virt_guest_entitlements(server_id_in);
      end if;

   end$$
language plpgsql;


    -- *******************************************************************
    -- PROCEDURE: repoll_virt_guest_entitlements
    --
    --   Whenever we add/remove a virtualization_host* entitlement from
    --   a host, we can call this procedure to update what type of slots
    --   the guests are consuming.
    --
    --   If you're removing the entitlement, it's
    --   possible the guests will become unentitled if you don't have enough
    --   physical slots to cover them.
    --
    --   If you're adding the entitlement, you end up freeing up physical
    --   slots for other systems.
    --
    -- *******************************************************************
    create or replace function repoll_virt_guest_entitlements(
        server_id_in in numeric
    ) returns void
as $$
    declare
        -- All channel families associated with the guests of server_id_in
        families cursor for
            select distinct cfs.channel_family_id
            from
                rhnChannelFamilyServers cfs,
                rhnVirtualInstance vi
            where
                vi.host_system_id = server_id_in
                and vi.virtual_system_id = cfs.server_id;

        -- All of server group types associated with the guests of
        -- server_id_in
        group_types cursor for
            select distinct sg.group_type, sgt.label
            from
                rhnServerGroupType sgt,
                rhnServerGroup sg,
                rhnServerGroupMembers sgm,
                rhnVirtualInstance vi
            where
                vi.host_system_id = server_id_in
                and vi.virtual_system_id = sgm.server_id
                and sgm.server_group_id = sg.id
                and sg.group_type = sgt.id;

        -- Virtual servers from a certain family belonging to a specific
        -- host that are consuming physical channel slots over the limit.
        virt_servers_cfam cursor(family_id_in numeric, quantity_in numeric) for
                select vi.virtual_system_id
                from
                    rhnChannelFamilyMembers cfm,
                    rhnServerChannel sc,
                    rhnVirtualInstance vi
                where
                    vi.host_system_id = server_id_in
                    and vi.virtual_system_id = sc.server_id
                    and sc.channel_id = cfm.channel_id
                    and cfm.channel_family_id = family_id_in
                order by sc.modified desc
                limit quantity_in;

        -- Virtual servers from a certain family belonging to a specific
        -- host that are consuming physical system slots over the limit.
        virt_servers_sgt cursor(group_type_in numeric, quantity_in numeric) for
                select vi.virtual_system_id
                from
                    rhnServerGroup sg,
                    rhnServerGroupMembers sgm,
                    rhnVirtualInstance vi
                where
                    vi.host_system_id = server_id_in
                    and vi.virtual_system_id = sgm.server_id
                    and sgm.server_group_id = sg.id
                    and sg.group_type = group_type_in
                order by sgm.modified desc
                limit quantity_in;

        -- Get the orgs of Virtual guests
        -- Since they may belong to different orgs
        virt_guest_orgs cursor for
                select  distinct (s.org_id)
                from rhnServer s
                    inner join  rhnVirtualInstance vi on vi.virtual_system_id = s.id
                where
                    vi.host_system_id = server_id_in
                    and s.org_id <> (select s1.org_id from rhnServer s1 where s1.id = vi.host_system_id) ;

        org_id_val numeric;
        max_members_val numeric;
        max_flex_val numeric;
        current_members_calc numeric;
        sg_id numeric;
        is_virt numeric := 0;
        free_slots numeric := 0;
    begin
          select 1 into is_virt
                from rhnServerEntitlementView
           where server_id = server_id_in
                 and label in ('virtualization_host', 'virtualization_host_platform');

      if not found then
          is_virt := 0;
      end if;

        select org_id
        into org_id_val
        from rhnServer
        where id = server_id_in;

        -- deal w/ channel entitlements first ...
        for family in families loop
            if is_virt = 0 then
            -- if the host_server does not have virt
            --- find all possible flex slots
            -- and set each of the flex eligible guests to Y
                select sfc.max_members - sfc.current_members
                  into free_slots
                  from rhnServerFveCapable sfc
                 where sfc.channel_family_id = family.channel_family_id;
                UPDATE rhnServerChannel sc set is_fve = 'Y'
                where sc.server_id in (
                            select vi.virtual_system_id
                            from rhnServerFveCapable sfc
                                inner join rhnVirtualInstance vi on vi.virtual_system_id = sfc.server_id
                            where vi.host_system_id = server_id_in
                                  and sfc.channel_family_id = family.channel_family_id
                              order by vi.modified desc
                            limit free_slots
                );
            else
            -- if the host_server has virt
            -- set all its flex guests to N
                UPDATE rhnServerChannel sc set is_fve = 'N'
                where
                    sc.channel_id in (select cfm.channel_id from rhnChannelFamilyMembers cfm
                                      where cfm.CHANNEL_FAMILY_ID = family.channel_family_id)
                    and sc.is_fve = 'Y'
                    and sc.server_id in
                            (select vi.virtual_system_id  from rhnVirtualInstance vi
                                    where vi.host_system_id = server_id_in);
            end if;

            -- get the current (physical) members of the family
            current_members_calc :=
                rhn_channel.channel_family_current_members(family.channel_family_id,
                                                           org_id_val); -- fixed transposed args

            -- get the max members of the family
            select max_members
            into max_members_val
            from rhnPrivateChannelFamily
            where channel_family_id = family.channel_family_id
            and org_id = org_id_val;

            select fve_max_members
            into max_flex_val
            from rhnPrivateChannelFamily
            where channel_family_id = family.channel_family_id
            and org_id = org_id_val;

            if current_members_calc > max_members_val then
                -- A virtualization_host* ent must have been removed, so we'll
                -- unsubscribe guests from the host first.

                -- hm, i don't think max_members - current_members_calc yielding a negative number
                -- will work w/ rownum, swaping 'em in the body of this if...
                for virt_server in virt_servers_cfam(family.channel_family_id,
                                current_members_calc - max_members_val) loop

                    perform rhn_channel.unsubscribe_server_from_family(
                                virt_server.virtual_system_id,
                                family.channel_family_id);
                end loop;

                -- if we're still over the limit, which would be odd,
                -- just prune the group to max_members
                --
                -- er... wouldn't we actually have to refresh the values of
                -- current_members_calc and max_members_val to actually ever
                -- *skip this??
                if current_members_calc > max_members_val then
                    -- argh, transposed again?!
                    perform rhn_entitlements.set_family_count(org_id_val,
                                     family.channel_family_id,
                                     max_members_val, max_flex_val);
                    --TODO calculate this correctly
                end if;

           end if;

            -- update current_members for the family.  This will set the value
            -- to reflect adding/removing the entitlement.
            --
            -- what's the difference of doing this vs the unavoidable set_family_count above?
            perform rhn_channel.update_family_counts(family.channel_family_id,
                                             org_id_val);

            -- It is possible that the guests belong  to a different org than the host
            -- so we are going to update the family counts in the guests orgs also
            for org in virt_guest_orgs loop
                    perform rhn_channel.update_family_counts(family.channel_family_id,
                                             org.org_id);
            end loop;
        end loop;

        for a_group_type in group_types loop
          -- get the current *physical* members of the system entitlement type for the org...
          --
          -- unlike channel families, it appears the standard rhnServerGroup.max_members represents
          -- *physical* slots, vs physical+virt ... boy that's confusing...

          select max_members, id
            into max_members_val, sg_id
            from rhnServerGroup
            where group_type = a_group_type.group_type
            and org_id = org_id_val;


      select count(sep.server_id) into current_members_calc
            from rhnServerEntitlementPhysical sep
           where sep.server_group_id = sg_id
             and sep.server_group_type_id = a_group_type.group_type;

          if current_members_calc > max_members_val then
            -- A virtualization_host* ent must have been removed, and we're over the limit, so unsubscribe guests
            for virt_server in virt_servers_sgt(a_group_type.group_type,
                                                current_members_calc - max_members_val) loop
              perform rhn_entitlements.remove_server_entitlement(virt_server.virtual_system_id, a_group_type.label);

              -- decrement current_members_calc, we'll use it to reset current_members for the group at the end...
              current_members_calc := current_members_calc - 1;
            end loop;

          end if;

          update rhnServerGroup set current_members = current_members_calc
           where org_id = org_id_val
             and group_type = a_group_type.group_type;

          -- I think that's all the house-keeping we have to do...
        end loop;

    end$$
language plpgsql;

    create or replace function get_server_entitlement (
        server_id_in in numeric
    ) returns varchar[]
as $$
    declare
        server_groups cursor for
            select  sgt.label
            from    rhnServerGroupType      sgt,
                    rhnServerGroup          sg,
                    rhnServerGroupMembers   sgm
            where   1=1
                and sgm.server_id = server_id_in
                and sg.id = sgm.server_group_id
                and sgt.id = sg.group_type
                and sgt.label in (
                    'sw_mgr_entitled','enterprise_entitled',
                    'provisioning_entitled', 'nonlinux_entitled',
                    'monitoring_entitled', 'virtualization_host',
                                        'virtualization_host_platform'
                    );

         ent_array varchar[];

    begin

      ent_array := '{}';

      for sg in server_groups loop
         ent_array := ent_array || sg.label;
      end loop;

      return ent_array;

    end$$
language plpgsql;

    -- this desperately needs to be table driven.
    create or replace function modify_org_service (
        org_id_in in numeric,
        service_label_in in varchar,
        enable_in in char
    ) returns void
as $$
    declare
        roles_to_process varchar[];
        roles cursor(role_label_in varchar) for
            select  label, id
            from    rhnUserGroupType
            where   label = role_label_in;
        org_roles cursor(role_label_in varchar) for
            select  1
            from    rhnUserGroup ug,
                    rhnUserGroupType ugt
            where   ugt.label = role_label_in
                and ug.org_id = org_id_in
                and ugt.id = ug.group_type;

        ents_to_process varchar[];
        ents cursor(ent_label_in varchar) for
            select  label, id
            from    rhnOrgEntitlementType
            where   label = ent_label_in;
        org_ents cursor(ent_label_in varchar) for
            select  1
            from    rhnOrgEntitlements oe,
                    rhnOrgEntitlementType oet
            where   oet.label = ent_label_in
                and oe.org_id = org_id_in
                and oet.id = oe.entitlement_id;
        create_row char(1);
    begin
        ents_to_process := '{}';
        roles_to_process := '{}';
        -- a bit kludgy, but only for 3.4 really.  Certainly no
        -- worse than the old code...
        if service_label_in = 'enterprise' or
           service_label_in = 'management' then
            ents_to_process := array_append(ents_to_process, 'sw_mgr_enterprise');

            roles_to_process := array_append(roles_to_process, 'org_admin');

            roles_to_process := array_append(roles_to_process, 'system_group_admin');

            roles_to_process := array_append(roles_to_process, 'activation_key_admin');
        elsif service_label_in = 'provisioning' then
            ents_to_process := array_append(ents_to_process, 'rhn_provisioning');

            roles_to_process := array_append(roles_to_process, 'system_group_admin');

            roles_to_process := array_append(roles_to_process, 'activation_key_admin');

            roles_to_process := array_append(roles_to_process, 'config_admin');
            -- another nasty special case...
            if enable_in = 'Y' then
                ents_to_process := array_append(ents_to_process, 'sw_mgr_enterprise');
            end if;
        elsif service_label_in = 'monitoring' then
            ents_to_process := array_append(ents_to_process, 'rhn_monitor');

            roles_to_process := array_append(roles_to_process, 'monitoring_admin');
        elsif service_label_in = 'virtualization' then
            ents_to_process := array_append(ents_to_process, 'rhn_virtualization');

            roles_to_process := array_append(roles_to_process, 'config_admin');
        elsif service_label_in = 'virtualization_platform' then
            ents_to_process := array_append(ents_to_process, 'rhn_virtualization_platform');
            roles_to_process := array_append(roles_to_process, 'config_admin');
    elsif service_label_in = 'nonlinux' then
            ents_to_process := array_append(ents_to_process, 'rhn_nonlinux');
            roles_to_process := array_append(roles_to_process, 'config_admin');
        end if;

        if enable_in = 'Y' then
            for i in 1..array_upper(ents_to_process, 1) loop
                for ent in ents(ents_to_process[i]) loop
                    create_row := 'Y';
                    for oe in org_ents(ent.label) loop
                        create_row := 'N';
                    end loop;
                    if create_row = 'Y' then
                        insert into rhnOrgEntitlements(org_id, entitlement_id)
                            values (org_id_in, ent.id);
                    end if;
                end loop;
            end loop;
            for i in 1..array_upper(roles_to_process, 1) loop
                for role in roles(roles_to_process[i]) loop
                    create_row := 'Y';
                    for o_r in org_roles(role.label) loop
                        create_row := 'N';
                    end loop;
                    if create_row = 'Y' then
                        insert into rhnUserGroup(
                                id, name, description, current_members,
                                group_type, org_id
                            ) (
                                select  nextval('rhn_user_group_id_seq'),
                                        ugt.name || 's',
                                        ugt.name || 's for Org ' ||
                                            o.name || ' ('|| o.id ||')',
                                        0, ugt.id, o.id
                                from    rhnUserGroupType ugt,
                                        web_customer o
                                where   o.id = org_id_in
                                    and ugt.id = role.id
                            );
                    end if;
                end loop;
            end loop;
        else
            for i in 1..coalesce(array_upper(ents_to_process, 1), 0) loop
                for ent in ents(ents_to_process[i]) loop
                    delete from rhnOrgEntitlements
                     where org_id = org_id_in
                       and entitlement_id = ent.id;
                end loop;
            end loop;
        end if;
    end$$
language plpgsql;

    create or replace function set_customer_enterprise (
        customer_id_in in numeric
    ) returns void
as $$
    begin
        perform rhn_entitlements.modify_org_service(customer_id_in, 'enterprise', 'Y');
    end$$
language plpgsql;

    create or replace function set_customer_provisioning (
        customer_id_in in numeric
    ) returns void
as $$
    begin
        perform rhn_entitlements.modify_org_service(customer_id_in, 'provisioning', 'Y');
    end$$
language plpgsql;

    create or replace function set_customer_monitoring (
        customer_id_in in numeric
    ) returns void
as $$
    begin
        perform rhn_entitlements.modify_org_service(customer_id_in, 'monitoring', 'Y');
    end$$
language plpgsql;

    create or replace function set_customer_nonlinux (
        customer_id_in in numeric
    ) returns void
as $$
    begin
        perform rhn_entitlements.modify_org_service(customer_id_in, 'nonlinux', 'Y');
    end$$
language plpgsql;

    create or replace function unset_customer_enterprise (
        customer_id_in in numeric
    ) returns void
as $$
    begin
        perform rhn_entitlements.modify_org_service(customer_id_in, 'enterprise', 'N');
    end$$
language plpgsql;

    create or replace function unset_customer_provisioning (
        customer_id_in in numeric
    ) returns void
as $$
    begin
        perform rhn_entitlements.modify_org_service(customer_id_in, 'provisioning', 'N');
    end$$
language plpgsql;

    create or replace function unset_customer_monitoring (
        customer_id_in in numeric
    ) returns void
as $$
    begin
        perform rhn_entitlements.modify_org_service(customer_id_in, 'monitoring', 'N');
    end$$
language plpgsql;

    create or replace function unset_customer_nonlinux (
        customer_id_in in numeric
    ) returns void
as $$
    begin
        perform rhn_entitlements.modify_org_service(customer_id_in, 'nonlinux', 'N');
    end$$
language plpgsql;

    -- *******************************************************************
    -- PROCEDURE: prune_group
    -- Unsubscribes servers consuming physical slots that over the org's
    --   limit.
    -- Called by: set_server_group_count, repoll_virt_guest_entitlements
    -- *******************************************************************
    create or replace function prune_group (
        group_id_in in numeric,
        quantity_in in numeric,
        update_family_countsYN in numeric default 1
    ) returns void
as $$
    declare
        sgrecord record;
      type_is_base char;
    begin
            update      rhnServerGroup
                set     max_members = quantity_in
                where   id = group_id_in;

            for sgrecord in (
		   select  server_id, server_group_id, sgt.id as group_type_id, sgt.label
		    from    rhnServerGroupType              sgt,
				    rhnServerGroup                  sg,
				    rhnServerGroupMembers   sgm
		    where   1=1
			    and sgm.server_group_id = group_id_in
			    and sgm.server_id in (
				    select  sep.server_id
				    from
					rhnServerEntitlementPhysical sep
				    where
					sep.server_group_id = group_id_in
				    order by sep.modified asc
				    offset quantity_in
				)
			    and sgm.server_group_id = sg.id
			    and sg.group_type = sgt.id
	    ) loop
                perform rhn_entitlements.remove_server_entitlement(sgrecord.server_id, sgrecord.label);

            select is_base
            into type_is_base
            from rhnServerGroupType sgt
            where sgt.id = sgrecord.group_type_id;

            -- if we're removing a base ent, then be sure to
            -- remove the server's channel subscriptions.
            if ( type_is_base = 'Y' ) then
                   perform rhn_channel.clear_subscriptions(sgrecord.server_id, 0, update_family_countsYN);
            end if;

            end loop;
    end$$
language plpgsql;

    -- *******************************************************************
    -- PROCEDURE: assign_system_entitlement
    --
    -- Moves system entitlements from from_org_id_in to to_org_id_in.
    -- Can raise not_enough_entitlements_in_base_org if from_org_id_in
    -- does not have enough entitlements to cover the move.
    -- Takes care of unentitling systems if necessary by calling
    -- set_server_group_count
    -- *******************************************************************
    create or replace function assign_system_entitlement(
        group_label_in in varchar,
        from_org_id_in in numeric,
        to_org_id_in in numeric,
        quantity_in in numeric
    ) returns void
as $$
    declare
        prev_ent_count numeric;
    to_org_prev_ent_count numeric;
        new_ent_count numeric;
    new_quantity numeric;
        group_type numeric;
    begin

            select max_members
            into prev_ent_count
            from rhnServerGroupType sgt,
                 rhnServerGroup sg
            where sg.org_id = from_org_id_in
              and sg.group_type = sgt.id
              and sgt.label = group_label_in;

            if not found then
                perform rhn_exception.raise_exception(
                              'not_enough_entitlements_in_base_org');
            end if;

            select max_members
            into to_org_prev_ent_count
            from rhnServerGroupType sgt,
                 rhnServerGroup sg
            where sg.org_id = to_org_id_in
              and sg.group_type = sgt.id
              and sgt.label = group_label_in;

            if not found then
                to_org_prev_ent_count := 0;
            end if;

            select id
            into group_type
            from rhnServerGroupType
            where label = group_label_in;

            if not found then
                perform rhn_exception.raise_exception(
                              'invalid_server_group');
            end if;

        new_ent_count := prev_ent_count - quantity_in;

        if prev_ent_count > new_ent_count then
            new_quantity := to_org_prev_ent_count + quantity_in;
        end if;

        if new_ent_count < 0 then
            perform rhn_exception.raise_exception(
                          'not_enough_entitlements_in_base_org');
        end if;


        perform rhn_entitlements.set_server_group_count(from_org_id_in,
                                         group_type,
                                         new_ent_count);

        perform rhn_entitlements.set_server_group_count(to_org_id_in,
                                         group_type,
                                         new_quantity);

        -- Create or delete the entries in rhnOrgEntitlementType
        if group_label_in = 'enterprise_entitled' then
            if new_quantity > 0 then
                perform rhn_entitlements.set_customer_enterprise(to_org_id_in);
            else
                perform rhn_entitlements.unset_customer_enterprise(to_org_id_in);
            end if;
        end if;

        if group_label_in = 'provisioning_entitled' then
            if new_quantity > 0 then
                perform rhn_entitlements.set_customer_provisioning(to_org_id_in);
            else
                perform rhn_entitlements.unset_customer_provisioning(to_org_id_in);
            end if;
        end if;

        if group_label_in = 'monitoring_entitled' then
            if new_quantity > 0 then
                perform rhn_entitlements.set_customer_monitoring(to_org_id_in);
            else
                perform rhn_entitlements.unset_customer_monitoring(to_org_id_in);
            end if;
        end if;

    end$$
language plpgsql;

    -- *******************************************************************
    -- PROCEDURE: assign_channel_entitlement
    --
    -- Moves channel entitlements from from_org_id_in to to_org_id_in.
    -- Can raise not_enough_entitlements_in_base_org if from_org_id_in
    -- does not have enough entitlements to cover the move.
    -- Takes care of unentitling systems if necessary by calling
    -- set_family_count
    -- *******************************************************************
    create or replace function assign_channel_entitlement(
        channel_family_label_in in varchar,
        from_org_id_in in numeric,
        to_org_id_in in numeric,
        quantity_in in numeric,
        flex_in in numeric
    ) returns void
as $$
    declare
        from_org_prev_ent_count numeric;
        from_org_prev_ent_count_flex numeric;
        new_ent_count numeric;
        new_ent_count_flex numeric;
        to_org_prev_ent_count numeric;
        to_org_prev_ent_count_flex numeric;
        new_quantity numeric;
        new_flex numeric;
        cfam_id       numeric;
    begin

            select max_members
            into from_org_prev_ent_count
            from rhnChannelFamily cf,
                 rhnPrivateChannelFamily pcf
            where pcf.org_id = from_org_id_in
              and pcf.channel_family_id = cf.id
              and cf.label = channel_family_label_in;

            if not found then
                perform rhn_exception.raise_exception(
                              'not_enough_entitlements_in_base_org');
            end if;

            select max_members
            into to_org_prev_ent_count
            from rhnChannelFamily cf,
                 rhnPrivateChannelFamily pcf
            where pcf.org_id = to_org_id_in
              and pcf.channel_family_id = cf.id
              and cf.label = channel_family_label_in;

            if not found then
                to_org_prev_ent_count := 0;
            end if;

            select fve_max_members
            into from_org_prev_ent_count_flex
            from rhnChannelFamily cf,
                rhnPrivateChannelFamily pcf
            where pcf.org_id = from_org_id_in
              and pcf.channel_family_id = cf.id
              and cf.label = channel_family_label_in;

            if not found then
                perform rhn_exception.raise_exception(
                              'not_enough_flex_entitlements_in_base_org');
            end if;

            select fve_max_members
            into to_org_prev_ent_count_flex
            from rhnChannelFamily cf,
                 rhnPrivateChannelFamily pcf
            where pcf.org_id = to_org_id_in
              and pcf.channel_family_id = cf.id
              and cf.label = channel_family_label_in;

            if not found then
                to_org_prev_ent_count_flex := 0;
            end if;

            select id
            into cfam_id
            from rhnChannelFamily
            where label = channel_family_label_in;

            if not found then
                perform rhn_exception.raise_exception(
                              'invalid_channel_family');
            end if;

        new_ent_count := from_org_prev_ent_count - quantity_in;
        new_ent_count_flex := from_org_prev_ent_count_flex - flex_in;

        if from_org_prev_ent_count >= new_ent_count then
            new_quantity := to_org_prev_ent_count + quantity_in;
        end if;

        if from_org_prev_ent_count_flex >= new_ent_count_flex then
            new_flex := to_org_prev_ent_count_flex + flex_in;
        end if;

        if new_ent_count < 0 then
            perform rhn_exception.raise_exception(
                          'not_enough_entitlements_in_base_org');
        end if;

        if new_ent_count_flex < 0 then
            perform rhn_exception.raise_exception(
                          'not_enough_flex_entitlements_in_base_org');
        end if;



        perform rhn_entitlements.set_family_count(from_org_id_in,
                                          cfam_id,
                                          new_ent_count,
                                          new_ent_count_flex);

        perform rhn_entitlements.set_family_count(to_org_id_in,
                                          cfam_id,
                                          new_quantity,
                                          new_flex);

    end$$
language plpgsql;

    -- *******************************************************************
    -- PROCEDURE: activate_system_entitlement
    --
    -- Sets the values in rhnServerGroup for a given rhnServerGroupType.
    --
    -- Calls: set_server_group_count to update, prune, or create the group.
    -- Called by: the code that activates a satellite cert.
    --
    -- Raises not_enough_entitlements_in_base_org if all entitlements
    -- in the org are used so the free entitlements would not cover
    -- the difference when descreasing the number of entitlements.
    -- *******************************************************************
    create or replace function activate_system_entitlement(
        org_id_in in numeric,
        group_label_in in varchar,
        quantity_in in numeric
    ) returns void
as $$
    declare
        prev_ent_count numeric;
        prev_ent_count_sum numeric;
        group_type numeric;
    begin

        -- Fetch the current entitlement count for the org
        -- into prev_ent_count

            select current_members
            into prev_ent_count
            from rhnServerGroupType sgt,
                 rhnServerGroup sg
            where sg.group_type = sgt.id
              and sgt.label = group_label_in
              and sg.org_id = org_id_in;

            if not found then
                prev_ent_count := 0;
            end if;

            select id
            into group_type
            from rhnServerGroupType
            where label = group_label_in;

            if not found then
                perform rhn_exception.raise_exception(
                              'invalid_server_group');
            end if;

        -- If we're setting the total entitlemnt count to a lower value,
        -- and that value is less than the allocated count in this org,
        -- we need to raise an exception.
        if quantity_in < prev_ent_count then
            perform rhn_exception.raise_exception(
                          'not_enough_entitlements_in_base_org');
        else
            -- don't update family counts after every server
            -- will do bulk update afterwards
            perform rhn_entitlements.set_server_group_count(org_id_in,
                                             group_type,
                                             quantity_in,
                                             0);
            -- bulk update family counts
            perform rhn_channel.update_group_family_counts(group_label_in, org_id_in);
        end if;

    end$$
language plpgsql;

    -- *******************************************************************
    -- PROCEDURE: activate_channel_entitlement
    --
    -- Calls: set_family_count to update, prune, or create the family
    --        permission bucket.
    -- Called by: the code that activates a satellite cert.
    --
    -- Raises not_enough_entitlements_in_base_org if there are not enough
    -- entitlements in the org to cover the difference when you are
    -- descreasing the number of entitlements.
    --
    -- The backend code in Python is expected to do whatever arithmetics
    -- is needed.
    -- *******************************************************************
    create or replace function activate_channel_entitlement(
        org_id_in in numeric,
        channel_family_label_in in varchar,
        quantity_in in numeric,
        flex_in in numeric
    ) returns void
as $$
    declare
        prev_ent_count numeric;
        prev_flex_count numeric;
        prev_ent_count_sum numeric;
        cfam_id numeric;
        reduce_quantity numeric;
        total_flex_capable numeric;
        to_convert_reg cursor (channel_family_id_val numeric, org_id_in numeric, quantity numeric) for
                     select SC.server_id
                     from rhnServerChannel SC inner join
                          rhnServer S on S.id = SC.server_id
                     where
                         is_fve = 'Y'
                         and S.org_id = org_id_in
                         and SC.channel_id in
                         (select cfm.channel_id from rhnChannelFamilyMembers cfm
                             where cfm.CHANNEL_FAMILY_ID = channel_family_id_val)
                         limit quantity;
         to_convert_flex cursor (channel_family_id_val numeric, org_id_in numeric, quantity numeric) for
                   select server_id
                   from rhnServerFveCapable
                       where SERVER_ORG_ID = org_id_in and
                             channel_family_id = cfam_id
                       limit quantity;

    begin

        -- Fetch the current entitlement count for the org
        -- into prev_ent_count
            select current_members
            into prev_ent_count
            from rhnChannelFamily cf,
                 rhnPrivateChannelFamily pcf
            where pcf.org_id = org_id_in
              and pcf.channel_family_id = cf.id
              and cf.label = channel_family_label_in;

            if not found then
                prev_ent_count := 0;
            end if;

            select pcf.fve_current_members
            into prev_flex_count
            from rhnChannelFamily cf,
                 rhnPrivateChannelFamily pcf
            where pcf.org_id = org_id_in
              and pcf.channel_family_id = cf.id
              and cf.label = channel_family_label_in;

            if not found then
                prev_flex_count := 0;
            end if;

            select id
            into cfam_id
            from rhnChannelFamily
            where label = channel_family_label_in;

            if not found then
                perform rhn_exception.raise_exception(
                              'invalid_channel_family');
            end if;

        -- if there are too few flex entitlements
        if flex_in < prev_flex_count then
            -- and if the extra we need is less than or equal to our extra regular entitlements
            if prev_flex_count - flex_in <= quantity_in - prev_ent_count then
                   reduce_quantity := prev_flex_count - flex_in;
                   -- We need to convert some systems from flex guest to regular
                   for system in to_convert_reg(cfam_id, org_id_in, reduce_quantity) loop
                      --rhn_channel.convert_to_regular(system.server_id, cfam_id);
                      UPDATE rhnServerChannel sc set is_fve = 'N'
                           where sc.server_id = system.server_id
                                 and sc.channel_id in (select cfm.channel_id
                                                          from rhnChannelFamilyMembers cfm
                                                          where cfm.channel_family_id = cfam_id);
                   end loop;

                   --reset previous counts
                   prev_ent_count := prev_ent_count + reduce_quantity;
                   prev_flex_count := prev_flex_count - reduce_quantity;
            else
                perform rhn_exception.raise_exception(
                          'not_enough_flex_entitlements_in_base_org');
            end if;
        end if;

        -- if there are too few regular entitlements, and extra flex entitlements
        if quantity_in < prev_ent_count and prev_flex_count < flex_in then
                -- how many flex-capable systems (that aren't using flex) do we have
                select count(*)
                   into total_flex_capable
                   from rhnServerFveCapable
                       where SERVER_ORG_ID = org_id_in and
                             channel_family_id = cfam_id;
                -- if we have enough flex capable machines that is at least
                --   as many as what we are over on
                if total_flex_capable >= prev_ent_count - quantity_in then
                    reduce_quantity := prev_ent_count - quantity_in;
                    for system in to_convert_flex(cfam_id, org_id_in, reduce_quantity) loop
--                          rhn_channel.convert_to_fve(system.server_id, cfam_id);
                        UPDATE rhnServerChannel sc set is_fve = 'Y'
                           where sc.server_id = system.server_id
                                 and sc.channel_id in (select cfm.channel_id
                                                          from rhnChannelFamilyMembers cfm
                                                          where cfm.channel_family_id = cfam_id);
                    end loop;
                    prev_ent_count := prev_ent_count - reduce_quantity;
                    prev_flex_count := prev_flex_count + reduce_quantity;
                end if;
        end if;

        -- If we're setting the total entitlemnt count to a lower value,
        -- and that value is less than the count in that one org,
        -- we need to raise an exception.
        if quantity_in < prev_ent_count then
            perform rhn_exception.raise_exception(
                          'not_enough_entitlements_in_base_org');
        else
            -- even if we've manually converted systems to/from flex above
            -- set_family_count should call update_family_counts, to reset
            -- current used slots
            perform rhn_entitlements.set_family_count(org_id_in, cfam_id,
                                              quantity_in, flex_in);
        end if;

    end$$
language plpgsql;

    create or replace function set_server_group_count (
        customer_id_in in numeric,  -- customer_id
        group_type_in in numeric,   -- rhn[User|Server]GroupType.id
        quantity_in in numeric,      -- quantity
                update_family_countsYN in numeric default 1
    ) returns void
as $$
    declare
        group_id numeric;
        quantity numeric;
        wasfound boolean;
    begin
        quantity := quantity_in;
        if quantity is not null and quantity < 0 then
            quantity := 0;
        end if;

        select  rsg.id
        into    group_id
        from    rhnServerGroup rsg
        where   1=1
            and rsg.org_id = customer_id_in
            and rsg.group_type = group_type_in;

        -- preserve the not found status across the rhn_entitlements.prune_group invocation
        wasfound := true;
        if not found then
            wasfound := false;
        end if;

        perform rhn_entitlements.prune_group(
            group_id,
            quantity,
                        update_family_countsYN
        );

        if not wasfound then
            insert into rhnServerGroup (
                    id, name, description, max_members, current_members,
                    group_type, org_id, created, modified
                ) (
                    select  nextval('rhn_server_group_id_seq'), name, name,
                            quantity, 0, id, customer_id_in,
                            current_timestamp, current_timestamp
                    from    rhnServerGroupType
                    where   id = group_type_in
            );
        end if;

    end$$
language plpgsql;

    -- *******************************************************************
    -- PROCEDURE: prune_family
    -- Unsubscribes servers consuming physical slots from the channel family
    --   that are over the org's limit.
    -- Called by: set_family_count
    -- *******************************************************************
    create or replace function prune_family (
        customer_id_in in numeric,
        channel_family_id_in in numeric,
        quantity_in in numeric,
        flex_in in numeric
    ) returns void
as $$
    declare
        serverchannels cursor(tmp_quantity numeric, is_fve_in char) for
            select  sc.server_id,
                    sc.channel_id
            from    rhnServerChannel sc,
                    rhnChannelFamilyMembers cfm
            where   1=1
                and cfm.channel_family_id = channel_family_id_in
                and cfm.channel_id = sc.channel_id
                and server_id in (
                            select  rs.id as server_id
                            from
                                    rhnServerChannel        rsc,
                                    rhnChannelFamilyMembers rcfm,
                                    rhnServer               rs
                            where   1=1
                                and rs.org_id = customer_id_in
                                and rs.id = rsc.server_id
                                and rsc.channel_id = rcfm.channel_id
                                and rcfm.channel_family_id =  channel_family_id_in
                                and rsc.is_fve = is_fve_in
                                -- we only want to grab servers consuming
                                -- physical slots.
                                and exists (
                                    select 1
                                    from rhnChannelFamilyServerPhysical cfsp
                                    where cfsp.server_id = rs.id
                                    and cfsp.channel_family_id =
                                        channel_family_id_in
                                    )
                            order by rcfm.modified asc
                            offset quantity_in
                        );
    begin
        -- if we get a null customer_id, this is completely bogus.
        if customer_id_in is null then
            return;
        end if;

        for sc in serverchannels(quantity_in, 'N') loop
            perform rhn_channel.unsubscribe_server(sc.server_id, sc.channel_id,
                                                   1, 1, 0, 0);
        end loop;

        for sc in serverchannels(flex_in, 'Y') loop
            perform rhn_channel.unsubscribe_server(sc.server_id, sc.channel_id,
                                                   1, 1, 0, 0);
        end loop;

        perform rhn_channel.update_family_counts(channel_family_id_in, customer_id_in);
    end$$
language plpgsql;

    create or replace function set_family_count (
        customer_id_in in numeric,      -- customer_id
        channel_family_id_in in numeric,    -- 246
        quantity_in in numeric,          -- 3
        flex_in in numeric
    ) returns void
as $$
    declare
        privperms cursor for
            select  1
            from    rhnPrivateChannelFamily
            where   org_id = customer_id_in
                and channel_family_id = channel_family_id_in;
        pubperms cursor for
            select  o.id org_id
            from    web_customer o,
                    rhnPublicChannelFamily pcf
            where   pcf.channel_family_id = channel_family_id_in;
        quantity numeric;
        done numeric := 0;
        flex numeric;
    begin
        quantity := quantity_in;
        if quantity is not null and quantity < 0 then
            quantity := 0;
        end if;
        flex := flex_in;
        if flex is not null and flex < 0 then
            flex := 0;
        end if;

        if customer_id_in is not null then
            for perm in privperms loop
                perform rhn_entitlements.prune_family(
                    customer_id_in,
                    channel_family_id_in,
                    quantity,
                    flex
                );

                if quantity is null and flex is null then
                    delete from rhnPrivateChannelFamily
                        where org_id = customer_id_in
                            and channel_family_id = channel_family_id_in;
                 else
                    update rhnPrivateChannelFamily
                        set max_members = quantity
                        where org_id = customer_id_in
                            and channel_family_id = channel_family_id_in;

                   update rhnPrivateChannelFamily
                        set fve_max_members = flex
                        where org_id = customer_id_in
                            and channel_family_id = channel_family_id_in;
                end if;
                return;
            end loop;

            insert into rhnPrivateChannelFamily (
                    channel_family_id, org_id, max_members, current_members, fve_max_members, fve_current_members
                ) values (
                    channel_family_id_in, customer_id_in, quantity, 0, flex, 0 );
            return;
        end if;

        for perm in pubperms loop
            if quantity = 0 then
                perform rhn_entitlements.prune_family(
                    perm.org_id,
                    channel_family_id_in,
                    quantity,
                    flex
                );
                if done = 0 then
                    delete from rhnPublicChannelFamily
                        where channel_family_id = channel_family_id_in;
                end if;
            end if;
            done := 1;
        end loop;
        -- if done's not 1, then we don't have any entitlements
        if done != 1 then
            insert into rhnPublicChannelFamily (
                    channel_family_id
                ) values (
                    channel_family_id_in
                );
        end if;
    end$$
language plpgsql;

    -- this expects quantity_in to be the number of available slots, not the
    -- max_members of the server group.  If you give it too many, it'll fail
    -- and raise servergroup_max_members.
    -- We should NEVER run this unless we're SURE that we won't
    -- be violating the max.
    create or replace function entitle_last_modified_servers (
        customer_id_in in numeric,  -- customer_id
        type_label_in in varchar,   -- 'enterprise_entitled'
        quantity_in in numeric      -- 3
    ) returns void
as $$
    declare
        -- find the servers that aren't currently in slots
        servers cursor(cid_in numeric, quant_in numeric) for
                                    select  rs.id as server_id
                                    from    rhnServer rs
                                    where   1=1
                                        and rs.org_id = cid_in
                                        and not exists (
                                            select  1
                                            from    rhnServerGroup sg,
                                                    rhnServerGroupMembers rsgm
                                            where   rsgm.server_id = rs.id
                                                and rsgm.server_group_id = sg.id
                                                and sg.group_type is not null
                                        )
                                        and not exists (
                                            select 1
                                            from rhnVirtualInstance vi
                                            where vi.virtual_system_id =
                                                  rs.id
                                        )
                                    order by modified desc
                                    limit quant_in;
    begin
        for server in servers(customer_id_in, quantity_in) loop
            perform rhn_entitlements.entitle_server(server.server_id, type_label_in);
        end loop;
    end$$
language plpgsql;

    create or replace function subscribe_newest_servers (
        customer_id_in in numeric
    ) returns void
as $$
    declare
        -- find servers without base channels
        servers cursor(cid_in numeric) for
            select  s.id
            from    rhnServer           s
            where   1=1
                and s.org_id = cid_in
                and not exists (
                        select 1
                        from    rhnChannel          c,
                                rhnServerChannel    sc
                        where   sc.server_id = s.id
                            and sc.channel_id = c.id
                            and c.parent_channel is null
                    )
                and not exists (
                        select 1
                        from rhnVirtualInstance vi
                        where vi.virtual_system_id = s.id
                    )
            order by s.modified desc;
        channel_id numeric;
    begin
        for server in servers(customer_id_in) loop
            channel_id := rhn_channel.guess_server_base(server.id);
            if channel_id is not null then
                begin
                    perform rhn_channel.subscribe_server(server.id, channel_id);
                -- exception is really channel_family_no_subscriptions
                exception
                    when others then
                        null;
                end;
            end if;
        end loop;
    end$$
language plpgsql;


-- restore the original setting
update pg_settings set setting = overlay( setting placing '' from 1 for (length('rhn_entitlements')+1) ) where name = 'search_path';
070701000007C2000081B400000000000000000000000167AE1114000000B2000000000000000000000000000000000000006C00000000susemanager-schema/upgrade/spacewalk-schema-2.0-to-spacewalk-schema-2.1/011-rhnOrgConfiguration-scapret.sql   alter table rhnOrgConfiguration
  add scap_retention_period_days
      NUMERIC default (90)
      constraint rhn_org_conf_scap_reten_chk check (scap_retention_period_days >= 0);
  070701000007C3000081B400000000000000000000000167AE11140000034D000000000000000000000000000000000000005400000000susemanager-schema/upgrade/spacewalk-schema-2.0-to-spacewalk-schema-2.1/013-log.sql   
CREATE OR REPLACE FUNCTION log_rename_constrains()
RETURNS VOID
LANGUAGE plpgsql
AS
$$
DECLARE
    pk_constraint_name varchar;
    fk_constraint_name varchar;
BEGIN
    SELECT constraint_name INTO pk_constraint_name
    FROM information_schema.table_constraints
    WHERE table_name = 'log'
    AND constraint_type = 'PRIMARY KEY';

    SELECT constraint_name INTO fk_constraint_name
    FROM information_schema.table_constraints
    WHERE table_name = 'log'
    AND constraint_type = 'FOREIGN KEY';

    EXECUTE 'ALTER INDEX ' || pk_constraint_name || ' RENAME TO log_id_pk';

    EXECUTE 'ALTER TABLE log DROP CONSTRAINT ' || fk_constraint_name;
    EXECUTE 'ALTER TABLE log ADD CONSTRAINT log_user_id_fk FOREIGN KEY (user_id) REFERENCES web_contact_all(id)';
END;
$$;

SELECT log_rename_constrains();

DROP FUNCTION log_rename_constrains();
   070701000007C4000081B400000000000000000000000167AE111400000269000000000000000000000000000000000000006900000000susemanager-schema/upgrade/spacewalk-schema-2.0-to-spacewalk-schema-2.1/014-add-column-csv-separator.sql  --
-- Copyright (c) 2013 SUSE
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--

-- Create new column for rhnUserInfo
ALTER TABLE rhnUserInfo ADD csv_separator CHAR(1) DEFAULT (',') NOT NULL
    CONSTRAINT rhn_user_info_csv_ck
        CHECK (csv_separator in (',',';'));
   070701000007C5000081B400000000000000000000000167AE111400000CCC000000000000000000000000000000000000006200000000susemanager-schema/upgrade/spacewalk-schema-2.0-to-spacewalk-schema-2.1/015-evr_t-max-replace.sql 
CREATE OR REPLACE VIEW
rhnServerNeededView
(
    org_id,
    server_id,
    errata_id,
    package_id,
    package_name_id,
    channel_id
)
AS
select 1.0, 1.0, 1.0, 1.0, 1.0, 1.0 from dual;

create or replace view
rhnChannelNewestPackageView
as
SELECT 1.0 as channel_id,
       1.0 as name_id,
       1.0 as evr_id,
       1.0 as package_arch_id,
       1.0 as package_id from dual;

-- this is the part we actually care about, messing with the views
-- is just a dance to get this to work
drop aggregate if exists max(evr_t);

create aggregate max (
  sfunc=evr_t_larger,
  basetype=evr_t,
  stype=evr_t
);

-- replace the views back to what they actually should be
CREATE OR REPLACE VIEW
rhnServerNeededView
(
    org_id,
    server_id,
    errata_id,
    package_id,
    package_name_id,
    channel_id
)
AS
SELECT s.org_id,
       sp.server_id,
       x.errata_id,
       up.id,
       up.name_id,
       x.channel_id
    FROM rhnServer s
        join (SELECT sp_sp.server_id, sp_sp.name_id, sp_sp.package_arch_id, max(sp_pe.evr) AS max_evr
                FROM rhnServerPackage sp_sp
                    join rhnPackageEvr sp_pe ON sp_pe.id = sp_sp.evr_id
                    GROUP BY sp_sp.server_id, sp_sp.name_id, sp_sp.package_arch_id) sp ON sp.server_id = s.id
        join rhnPackage up ON up.name_id = sp.name_id
        join rhnPackageEvr upe ON upe.id = up.evr_id AND sp.max_evr < upe.evr
        join rhnPackageUpgradeArchCompat puac ON puac.package_arch_id = sp.package_arch_id AND puac.package_upgrade_arch_id = up.package_arch_id
        join rhnServerChannel sc ON sc.server_id = sp.server_id
        join rhnChannelPackage cp ON cp.package_id = up.id AND cp.channel_id = sc.channel_id
        left join
        (SELECT ep.errata_id, cp.channel_id, ep.package_id
         FROM rhnChannelErrata cp
             join rhnErrataPackage ep ON ep.errata_id = cp.errata_id) x
            ON x.channel_id = sc.channel_id AND x.package_id = cp.package_id
;


create or replace view
rhnChannelNewestPackageView
as
SELECT channel_id,
       name_id,
       evr_id,
       package_arch_id,
       max(package_id) as package_id
FROM (
       SELECT m.channel_id          as channel_id,
              p.name_id             as name_id,
              p.evr_id              as evr_id,
              m.package_arch_id     as package_arch_id,
              p.id                  as package_id
         FROM
              (select max(pe.evr) AS max_evr,
                      cp.channel_id,
                      p.name_id,
                      p.package_arch_id
                 from rhnPackageEVR       pe,
                      rhnPackage          p,
                      rhnChannelPackage   cp
                where p.evr_id = pe.id
                  and cp.package_id = p.id
                group by cp.channel_id, p.name_id, p.package_arch_id) m,
              rhnPackageEVR       pe,
              rhnPackage          p,
              rhnChannelPackage   chp
        WHERE m.max_evr = pe.evr
          AND m.name_id = p.name_id
          AND m.package_arch_id = p.package_arch_id
          AND p.evr_id = pe.id
          AND chp.package_id = p.id
          AND chp.channel_id = m.channel_id
) latest_packages
group by channel_id, name_id, evr_id, package_arch_id
;

070701000007C6000081B400000000000000000000000167AE11140000025E000000000000000000000000000000000000005C00000000susemanager-schema/upgrade/spacewalk-schema-2.0-to-spacewalk-schema-2.1/017-queu_server.sql   
CREATE OR REPLACE FUNCTION
queue_server(server_id_in IN NUMERIC, immediate_in IN NUMERIC DEFAULT 1)
RETURNS VOID
AS
$$
DECLARE
    org_id_tmp NUMERIC;
BEGIN
    IF immediate_in > 0
    THEN
          PERFORM rhn_server.update_needed_cache(server_id_in);
    ELSE
          SELECT org_id INTO STRICT org_id_tmp
          FROM rhnServer WHERE id = server_id_in;

          INSERT
            INTO rhnTaskQueue
                 (org_id, task_name, task_data)
          VALUES (org_id_tmp,
                  'update_server_errata_cache',
                  server_id_in);
    END IF;
END;
$$ LANGUAGE plpgsql;
  070701000007C7000081B400000000000000000000000167AE11140000002A000000000000000000000000000000000000006400000000susemanager-schema/upgrade/spacewalk-schema-2.0-to-spacewalk-schema-2.1/018-rhnServerNeededView.sql   
DROP VIEW IF EXISTS rhnServerNeededView;
  070701000007C8000081B400000000000000000000000167AE1114000001A2000000000000000000000000000000000000005E00000000susemanager-schema/upgrade/spacewalk-schema-2.0-to-spacewalk-schema-2.1/019-rhnPackageKey.sql update rhnPackageKey set provider_id = lookup_package_provider('Oracle Inc.')
 where key_id = '72f97b74ec551f03';

insert into rhnPackageKey (id, key_id, key_type_id, provider_id)
    (select sequence_nextval('rhn_pkey_id_seq'), '72f97b74ec551f03', lookup_package_key_type('gpg'), lookup_package_provider('Oracle Inc.') from dual
     where not exists (select 1 from rhnPackageKey where key_id = '72f97b74ec551f03'));
  070701000007C9000081B400000000000000000000000167AE111400010785000000000000000000000000000000000000006500000000susemanager-schema/upgrade/spacewalk-schema-2.0-to-spacewalk-schema-2.1/020-rhn_entitlements.pkb.sql  --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--

-- create schema rhn_entitlements;

-- setup search_path so that these functions are created in appropriate schema.
update pg_settings set setting = 'rhn_entitlements,' || setting where name = 'search_path';

   create or replace function find_compatible_sg (
      server_id_in in numeric,
      type_label_in in varchar
   )
   returns numeric
as $$
    declare
      servergroups cursor for
         select sg.id
           from rhnServerGroupType             sgt,
                rhnServerGroup                 sg,
                rhnServer                     s,
                rhnServerServerGroupArchCompat ssgac
          where s.id = server_id_in
            and s.org_id = sg.org_id
            and sgt.label = type_label_in
            and sg.group_type = sgt.id
            and ssgac.server_group_type = sgt.id
            and ssgac.server_arch_id = s.server_arch_id
            and not exists ( 
                     select 1
                      from rhnServerGroupMembers sgm
                     where sgm.server_group_id = sg.id 
                       and sgm.server_id = s.id);

         
   begin
      for servergroup in servergroups loop
         return servergroup.id;
      end loop;

      --no servergroup found
      return NULL;
   end$$
language plpgsql;

    -- *******************************************************************
    -- PROCEDURE: remove_org_entitlements
    --
    -- Removes both system entitlements and channel subscriptions
    -- that are currently assigned to an org and re-assigns to the
    -- master org (org_id = 1).
    --
    -- When we call this we expect everything to already be unentitled
    -- which shoul be handled by delete_org.
    --
    -- Called by: delete_org
    -- *******************************************************************
    create or replace function remove_org_entitlements (
        org_id_in numeric
    ) returns void
as $$
    declare
        system_ents cursor for
        select sg.id, sg.max_members, sg.group_type
        from rhnServerGroup sg
        where group_type is not null
          and org_id = org_id_in;

        channel_subs cursor for
        select pcf.channel_family_id, pcf.max_members
        from rhnChannelFamily cf,
             rhnPrivateChannelFamily pcf
        where pcf.org_id = org_id_in
          and pcf.channel_family_id = cf.id
          and cf.org_id is null;

    begin

        for system_ent in system_ents loop
            update rhnServerGroup
            set max_members = max_members + system_ent.max_members
            where org_id = 1
              and group_type = system_ent.group_type;
        end loop;

        update rhnServerGroup
        set max_members = 0
        where org_id = org_id_in;

        for channel_sub in channel_subs loop
            update rhnPrivateChannelFamily
            set max_members = max_members + channel_sub.max_members
            where org_id = 1
              and channel_family_id = channel_sub.channel_family_id;
        end loop;
        
        update rhnPrivateChannelFamily
        set max_members = 0
        where org_id = org_id_in;

    end$$
language plpgsql;

    create or replace function entitlement_grants_service (
        entitlement_in in varchar,
        service_level_in in varchar
    ) returns numeric
as $$
    begin
        if service_level_in = 'provisioning' then
            if entitlement_in = 'provisioning_entitled' then
                return 1;
            else
                return 0;
            end if;
        elsif service_level_in = 'management' then
            if entitlement_in = 'enterprise_entitled' then
                return 1;
            else
                return 0;
            end if;
        elsif service_level_in = 'monitoring' then
            if entitlement_in = 'monitoring_entitled' then
                return 1;
            end if;
        elsif service_level_in = 'updates' then
            return 1;           
        else
            return 0;
        end if;
    end$$
language plpgsql;

    create or replace function lookup_entitlement_group (
        org_id_in in numeric,
        type_label_in in varchar default 'sw_mgr_entitled'
    ) returns numeric
as $$
    declare
        server_groups cursor for
            select  sg.id               server_group_id
            from    rhnServerGroup      sg,
                    rhnServerGroupType  sgt
            where   sgt.label = type_label_in
                and sgt.id = sg.group_type
                and sg.org_id = org_id_in;
    begin
        for sg in server_groups loop
            return sg.server_group_id;
        end loop;
        return rhn_entitlements.create_entitlement_group(
                org_id_in, 
                type_label_in
            );
    end$$
language plpgsql;

    create or replace function create_entitlement_group (
        org_id_in in numeric,
        type_label_in in varchar default 'sw_mgr_entitled'
    ) returns numeric
as $$
    declare
        sg_id_val numeric;
    begin
        select  nextval('rhn_server_group_id_seq')
        into    sg_id_val;

        insert into rhnServerGroup (
                id, name, description, max_members, current_members,
                group_type, org_id
            ) (
                select  sg_id_val, sgt.label, sgt.label,
                        0, 0, sgt.id, org_id_in
                from    rhnServerGroupType sgt
                where   sgt.label = type_label_in
            );

        return sg_id_val;
    end$$
language plpgsql;

   create or replace function can_entitle_server ( 
      server_id_in   in numeric, 
      type_label_in  in varchar
   )
   returns numeric
as $$
    declare
      addon_servergroups cursor (base_label_in varchar, 
                                 addon_label_in varchar) for
         select
            addon_id
         from
            rhnSGTypeBaseAddonCompat
         where base_id = lookup_sg_type (base_label_in)
           and addon_id = lookup_sg_type (addon_label_in);

      previous_ent        varchar[];
      is_base_in          char   := 'N';
      is_base_current     char   := 'N';
      i                   numeric := 0;
      sgid                numeric := 0;

   begin

      previous_ent := rhn_entitlements.get_server_entitlement(server_id_in);

      select distinct is_base
      into is_base_in
      from rhnServerGroupType
      where label = type_label_in;

      if array_upper(previous_ent, 1) is null or array_upper(previous_ent, 1) = 0 then
         if is_base_in = 'Y' then
            sgid := rhn_entitlements.find_compatible_sg (server_id_in, type_label_in);
            if sgid is not null then
              -- rhn_server.insert_into_servergroup (server_id_in, sgid);
              return 1;
            else
              -- rhn_exception.raise_exception ('invalid_base_entitlement');
              return 0;
            end if;
         else
            -- rhn_exception.raise_exception ('invalid_base_entitlement');
            return 0;
         end if;

      -- there are previous ents, first make sure we're not trying to entitle a base ent
      elsif is_base_in = 'Y' then
         -- rhn_exception.raise_exception ('invalid_addon_entitlement');
         return 0;

      -- it must be an addon, so proceed with the entitlement
      else

         -- find the servers base ent
         is_base_current := 'N';
         i := 0;
         while is_base_current = 'N' and i < array_upper(previous_ent, 1)
         loop
            i := i + 1;
            select is_base
            into is_base_current
            from rhnServerGroupType
            where label = previous_ent[i];
         end loop;

         -- never found a base ent, that would be strange
         if is_base_current  = 'N' then
            -- rhn_exception.raise_exception ('invalid_base_entitlement');
            return 0;
         end if;

         -- this for loop verifies the validity of the addon path
         for addon_servergroup in addon_servergroups  (previous_ent[i], type_label_in) loop
            -- find an appropriate sgid for the addon and entitle the server
            sgid := rhn_entitlements.find_compatible_sg (server_id_in, type_label_in);
            if sgid is not null then
               -- rhn_server.insert_into_servergroup (server_id_in, sgid);
               return 1;
            else
               -- rhn_exception.raise_exception ('invalid_addon_entitlement');
               return 0;
            end if;
         end loop;

      end if;

      return 0;

   end$$
language plpgsql;

   create or replace function can_switch_base ( 
      server_id_in   in    integer, 
      type_label_in  in    varchar
   )
   returns numeric
as $$
   declare
      type_label_in_is_base   char(1);
      sgid                    numeric;

   begin

       select is_base into type_label_in_is_base
       from rhnServerGroupType
       where label = type_label_in;

       if not found then
          perform rhn_exception.raise_exception ( 'invalid_entitlement' );
       end if;

      if type_label_in_is_base = 'N' then
         perform rhn_exception.raise_exception ( 'invalid_entitlement' );
      else
         sgid := rhn_entitlements.find_compatible_sg ( server_id_in,
                                                       type_label_in );
         if sgid is not null then
           return 1;
         else
           return 0;
         end if;
      end if;

   end$$
language plpgsql;

    create or replace function entitle_server (
        server_id_in in numeric,
        type_label_in in varchar default 'sw_mgr_entitled'
    ) returns void
as $$
    declare
      sgid  numeric := 0;
      is_virt numeric := 0;

    begin

      select 1 into is_virt
        from rhnServerEntitlementView
        where server_id = server_id_in
          and label in ('virtualization_host', 'virtualization_host_platform');

      if not found then
          is_virt := 0;
      end if;
      
      if is_virt = 0 and (type_label_in = 'virtualization_host' or
                          type_label_in = 'virtualization_host_platform') then

        is_virt := 1;
      end if;

      if rhn_entitlements.can_entitle_server(server_id_in, 
                                             type_label_in) = 1 then
         sgid := rhn_entitlements.find_compatible_sg (server_id_in,
                                                      type_label_in);
         if sgid is not null then
            insert into rhnServerHistory ( id, server_id, summary, details )
            values ( nextval('rhn_event_id_seq'), server_id_in,
                     'added system entitlement ',
                      case type_label_in
                       when 'enterprise_entitled' then 'Management'
                       when 'sw_mgr_entitled' then 'Update'
                       when 'provisioning_entitled' then 'Provisioning'
                       when 'monitoring_entitled' then 'Monitoring'  
                       when 'virtualization_host' then 'Virtualization'
                       when 'virtualization_host_platform' then 
                            'Virtualization Platform' end  );

            perform rhn_server.insert_into_servergroup (server_id_in, sgid);

            if is_virt = 1 then
              perform rhn_entitlements.repoll_virt_guest_entitlements(server_id_in);
            end if;

         else
            perform rhn_exception.raise_exception ('no_available_server_group');
         end if;
      else
         perform rhn_exception.raise_exception ('invalid_entitlement');
      end if;
   end$$
language plpgsql;

    create or replace function remove_server_entitlement (
        server_id_in in numeric,
        type_label_in in varchar default 'sw_mgr_entitled',
        repoll_virt_guests in numeric default 1
    ) returns void
as $$
    declare
      group_id numeric;
      type_is_base char;
      is_virt numeric := 0;
    begin
      -- would be nice if there were a virt attribute of entitlement types, not have to specify 2 different ones...
        select 1 into is_virt
          from rhnServerEntitlementView
          where server_id = server_id_in
            and label in ('virtualization_host', 'virtualization_host_platform');
        if not found then
            is_virt := 0;
        end if;

        select  sg.id, sgt.is_base
        into group_id, type_is_base
        from    rhnServerGroupType sgt,
            rhnServerGroup sg,
                rhnServerGroupMembers sgm,
                rhnServer s
        where   s.id = server_id_in
            and s.id = sgm.server_id
            and sgm.server_group_id = sg.id
            and sg.org_id = s.org_id
            and sgt.label = type_label_in
            and sgt.id = sg.group_type;

        if not found then
          perform rhn_exception.raise_exception('invalid_server_group_member');
        end if;

      if ( type_is_base = 'Y' ) then
         -- unentitle_server should handle everything, don't really need to do anything else special here
         perform rhn_entitlements.unentitle_server ( server_id_in );
      else

         insert into rhnServerHistory ( id, server_id, summary, details )
         values ( nextval('rhn_event_id_seq'), server_id_in,
                  'removed system entitlement ',
                   case type_label_in
                    when 'enterprise_entitled' then 'Management'
                    when 'sw_mgr_entitled' then 'Update'
                    when 'provisioning_entitled' then 'Provisioning'
                    when 'monitoring_entitled' then 'Monitoring'
                    when 'virtualization_host' then 'Virtualization'
                    when 'virtualization_host_platform' then 
                         'Virtualization Platforrm' end  );

         perform rhn_server.delete_from_servergroup(server_id_in, group_id);

         if type_label_in = 'monitoring_entitled' then
           DELETE
             FROM rhn_probe
            WHERE recid IN (SELECT probe_id
                              FROM rhn_check_probe
                             WHERE host_id = server_id_in);
         end if;

         if is_virt = 1 and repoll_virt_guests = 1 then
           perform rhn_entitlements.repoll_virt_guest_entitlements(server_id_in);
         end if;
      end if;

    end$$
language plpgsql;

    create or replace function unentitle_server (
        server_id_in in numeric
    ) returns void
as $$
    declare
      servergroups cursor for
         select distinct sgt.label, sg.id server_group_id
         from  rhnServerGroupType sgt,
               rhnServerGroup sg,
               rhnServer s,
               rhnServerGroupMembers sgm
         where s.id = server_id_in
            and s.org_id = sg.org_id
            and sg.group_type = sgt.id
            and sgm.server_group_id = sg.id
            and sgm.server_id = s.id;
            
     is_virt numeric := 0;

   begin

      select 1 into is_virt
        from rhnServerEntitlementView
        where server_id = server_id_in
         and label in ('virtualization_host', 'virtualization_host_platform');

      if not found then
          is_virt := 0;
      end if;

      for servergroup in servergroups loop

         insert into rhnServerHistory ( id, server_id, summary, details )
         values ( nextval('rhn_event_id_seq'), server_id_in,
                  'removed system entitlement ',
                   case servergroup.label
                    when 'enterprise_entitled' then 'Management'
                    when 'sw_mgr_entitled' then 'Update'
                    when 'provisioning_entitled' then 'Provisioning'
                    when 'monitoring_entitled' then 'Monitoring'
                    when 'virtualization_host' then 'Virtualization'
                    when 'virtualization_host_platform' then 
                         'Virtualization Platform' end  );
  
         perform rhn_server.delete_from_servergroup(server_id_in, 
                                            servergroup.server_group_id );
      end loop;

      if is_virt = 1 then
        perform rhn_entitlements.repoll_virt_guest_entitlements(server_id_in);
      end if;

   end$$
language plpgsql;


    -- *******************************************************************
    -- PROCEDURE: repoll_virt_guest_entitlements
    --
    --   Whenever we add/remove a virtualization_host* entitlement from 
    --   a host, we can call this procedure to update what type of slots
    --   the guests are consuming.  
    -- 
    --   If you're removing the entitlement, it's 
    --   possible the guests will become unentitled if you don't have enough
    --   physical slots to cover them.
    --
    --   If you're adding the entitlement, you end up freeing up physical
    --   slots for other systems.
    --
    -- *******************************************************************
    create or replace function repoll_virt_guest_entitlements(
        server_id_in in numeric
    ) returns void
as $$
    declare
        -- All channel families associated with the guests of server_id_in
        families cursor for 
            select distinct cfs.channel_family_id
            from
                rhnChannelFamilyServers cfs,
                rhnVirtualInstance vi
            where
                vi.host_system_id = server_id_in
                and vi.virtual_system_id = cfs.server_id;
        
        -- All of server group types associated with the guests of
        -- server_id_in
        group_types cursor for
            select distinct sg.group_type, sgt.label, sg.org_id
            from
                rhnServerGroupType sgt,
                rhnServerGroup sg,
                rhnServerGroupMembers sgm,
                rhnVirtualInstance vi
            where
                vi.host_system_id = server_id_in
                and vi.virtual_system_id = sgm.server_id
                and sgm.server_group_id = sg.id
                and sg.group_type = sgt.id;

        -- Virtual servers from a certain family belonging to a specific
        -- host that are consuming physical channel slots over the limit.
        virt_servers_cfam cursor(family_id_in numeric, quantity_in numeric) for
                select vi.virtual_system_id
                from
                    rhnChannelFamilyMembers cfm,
                    rhnServerChannel sc,
                    rhnVirtualInstance vi
                where
                    vi.host_system_id = server_id_in
                    and vi.virtual_system_id = sc.server_id
                    and sc.channel_id = cfm.channel_id
                    and cfm.channel_family_id = family_id_in
                order by sc.modified desc
                limit quantity_in;                

        -- Virtual servers from a certain family belonging to a specific
        -- host that are consuming physical system slots over the limit.
        virt_servers_sgt cursor(group_type_in numeric, quantity_in numeric) for
                select vi.virtual_system_id
                from
                    rhnServerGroup sg,
                    rhnServerGroupMembers sgm,
                    rhnVirtualInstance vi
                where
                    vi.host_system_id = server_id_in
                    and vi.virtual_system_id = sgm.server_id
                    and sgm.server_group_id = sg.id
                    and sg.group_type = group_type_in
                order by sgm.modified desc
                limit quantity_in;                
        
        -- Get the orgs of Virtual guests
        -- Since they may belong to different orgs
        virt_guest_orgs cursor for
                select  distinct (s.org_id)
                from rhnServer s
                    inner join  rhnVirtualInstance vi on vi.virtual_system_id = s.id
                where
                    vi.host_system_id = server_id_in
                    and s.org_id <> (select s1.org_id from rhnServer s1 where s1.id = vi.host_system_id) ;

        org_id_val numeric;
        max_members_val numeric;
        max_flex_val numeric;
        current_members_calc numeric;
        sg_id numeric;
        is_virt numeric := 0;
        free_slots numeric := 0;
    begin
          select 1 into is_virt
                from rhnServerEntitlementView
           where server_id = server_id_in
                 and label in ('virtualization_host', 'virtualization_host_platform');

      if not found then
          is_virt := 0;
      end if;

        select org_id
        into org_id_val
        from rhnServer
        where id = server_id_in;

        -- deal w/ channel entitlements first ...
        for family in families loop
            if is_virt = 0 then
            -- if the host_server does not have virt
            --- find all possible flex slots
            -- and set each of the flex eligible guests to Y
                select sfc.max_members - sfc.current_members
                  into free_slots
                  from rhnServerFveCapable sfc
                 where sfc.channel_family_id = family.channel_family_id;
                UPDATE rhnServerChannel sc set is_fve = 'Y'
                where sc.server_id in (
                            select vi.virtual_system_id
                            from rhnServerFveCapable sfc
                                inner join rhnVirtualInstance vi on vi.virtual_system_id = sfc.server_id
                            where vi.host_system_id = server_id_in
                                  and sfc.channel_family_id = family.channel_family_id
                              order by vi.modified desc
                            limit free_slots
                );
            else
            -- if the host_server has virt
            -- set all its flex guests to N
                UPDATE rhnServerChannel sc set is_fve = 'N'
                where
                    sc.channel_id in (select cfm.channel_id from rhnChannelFamilyMembers cfm
                                      where cfm.CHANNEL_FAMILY_ID = family.channel_family_id)
                    and sc.is_fve = 'Y'
                    and sc.server_id in
                            (select vi.virtual_system_id  from rhnVirtualInstance vi
                                    where vi.host_system_id = server_id_in);
            end if;

            -- get the current (physical) members of the family
            current_members_calc := 
                rhn_channel.channel_family_current_members(family.channel_family_id,
                                                           org_id_val); -- fixed transposed args

            -- get the max members of the family
            select max_members
            into max_members_val
            from rhnPrivateChannelFamily
            where channel_family_id = family.channel_family_id
            and org_id = org_id_val;

            select fve_max_members
            into max_flex_val
            from rhnPrivateChannelFamily
            where channel_family_id = family.channel_family_id
            and org_id = org_id_val;

            if current_members_calc > max_members_val then
                -- A virtualization_host* ent must have been removed, so we'll
                -- unsubscribe guests from the host first.

                -- hm, i don't think max_members - current_members_calc yielding a negative number
                -- will work w/ rownum, swaping 'em in the body of this if...
                for virt_server in virt_servers_cfam(family.channel_family_id,
                                current_members_calc - max_members_val) loop 

                    perform rhn_channel.unsubscribe_server_from_family(
                                virt_server.virtual_system_id,
                                family.channel_family_id);
                end loop;                               

                -- if we're still over the limit, which would be odd,
                -- just prune the group to max_members
                --
                -- er... wouldn't we actually have to refresh the values of
                -- current_members_calc and max_members_val to actually ever
                -- *skip this??
                if current_members_calc > max_members_val then
                    -- argh, transposed again?!
                    perform rhn_entitlements.set_family_count(org_id_val,
                                     family.channel_family_id,
                                     max_members_val, max_flex_val);
                    --TODO calculate this correctly
                end if; 

           end if;

            -- update current_members for the family.  This will set the value
            -- to reflect adding/removing the entitlement.
            --
            -- what's the difference of doing this vs the unavoidable set_family_count above?
            perform rhn_channel.update_family_counts(family.channel_family_id,
                                             org_id_val);

            -- It is possible that the guests belong  to a different org than the host
            -- so we are going to update the family counts in the guests orgs also
            for org in virt_guest_orgs loop
                    perform rhn_channel.update_family_counts(family.channel_family_id,
                                             org.org_id);
            end loop;
        end loop;

        for a_group_type in group_types loop
          -- get the current *physical* members of the system entitlement type for the org...
          -- 
          -- unlike channel families, it appears the standard rhnServerGroup.max_members represents
          -- *physical* slots, vs physical+virt ... boy that's confusing...

          select max_members, id
            into max_members_val, sg_id
            from rhnServerGroup
            where group_type = a_group_type.group_type
            and org_id = a_group_type.org_id;


      select count(sep.server_id) into current_members_calc
            from rhnServerEntitlementPhysical sep
           where sep.server_group_id = sg_id
             and sep.server_group_type_id = a_group_type.group_type;
          
          if current_members_calc > max_members_val then
            -- A virtualization_host* ent must have been removed, and we're over the limit, so unsubscribe guests
            for virt_server in virt_servers_sgt(a_group_type.group_type,
                                                current_members_calc - max_members_val) loop
              perform rhn_entitlements.remove_server_entitlement(virt_server.virtual_system_id, a_group_type.label);

              -- decrement current_members_calc, we'll use it to reset current_members for the group at the end...
              current_members_calc := current_members_calc - 1;
            end loop;

          end if;

          update rhnServerGroup set current_members = current_members_calc
           where org_id = a_group_type.org_id
             and group_type = a_group_type.group_type;

          -- I think that's all the house-keeping we have to do...
        end loop;

    end$$
language plpgsql;

    create or replace function get_server_entitlement (
        server_id_in in numeric
    ) returns varchar[]
as $$
    declare
        server_groups cursor for
            select  sgt.label
            from    rhnServerGroupType      sgt,
                    rhnServerGroup          sg,
                    rhnServerGroupMembers   sgm
            where   1=1
                and sgm.server_id = server_id_in
                and sg.id = sgm.server_group_id
                and sgt.id = sg.group_type
                and sgt.label in (
                    'sw_mgr_entitled','enterprise_entitled',
                    'provisioning_entitled', 'nonlinux_entitled',
                    'monitoring_entitled', 'virtualization_host',
                                        'virtualization_host_platform'
                    );

         ent_array varchar[];

    begin
      
      ent_array := '{}';

      for sg in server_groups loop
         ent_array := ent_array || sg.label;
      end loop;

      return ent_array;

    end$$
language plpgsql;

    -- this desperately needs to be table driven.
    create or replace function modify_org_service (
        org_id_in in numeric,
        service_label_in in varchar,
        enable_in in char
    ) returns void
as $$
    declare
        roles_to_process varchar[];
        roles cursor(role_label_in varchar) for
            select  label, id
            from    rhnUserGroupType
            where   label = role_label_in;
        org_roles cursor(role_label_in varchar) for
            select  1
            from    rhnUserGroup ug,
                    rhnUserGroupType ugt
            where   ugt.label = role_label_in
                and ug.org_id = org_id_in
                and ugt.id = ug.group_type;
                
        ents_to_process varchar[];
        ents cursor(ent_label_in varchar) for
            select  label, id
            from    rhnOrgEntitlementType
            where   label = ent_label_in;
        org_ents cursor(ent_label_in varchar) for
            select  1
            from    rhnOrgEntitlements oe,
                    rhnOrgEntitlementType oet
            where   oet.label = ent_label_in
                and oe.org_id = org_id_in
                and oet.id = oe.entitlement_id;
        create_row char(1);
    begin
        ents_to_process := '{}';
        roles_to_process := '{}';
        -- a bit kludgy, but only for 3.4 really.  Certainly no
        -- worse than the old code...
        if service_label_in = 'enterprise' or 
           service_label_in = 'management' then
            ents_to_process := array_append(ents_to_process, 'sw_mgr_enterprise');

            roles_to_process := array_append(roles_to_process, 'org_admin');

            roles_to_process := array_append(roles_to_process, 'system_group_admin');

            roles_to_process := array_append(roles_to_process, 'activation_key_admin');
        elsif service_label_in = 'provisioning' then
            ents_to_process := array_append(ents_to_process, 'rhn_provisioning');

            roles_to_process := array_append(roles_to_process, 'system_group_admin');

            roles_to_process := array_append(roles_to_process, 'activation_key_admin');

            roles_to_process := array_append(roles_to_process, 'config_admin');
            -- another nasty special case...
            if enable_in = 'Y' then
                ents_to_process := array_append(ents_to_process, 'sw_mgr_enterprise');
            end if;
        elsif service_label_in = 'monitoring' then
            ents_to_process := array_append(ents_to_process, 'rhn_monitor');

            roles_to_process := array_append(roles_to_process, 'monitoring_admin');
        elsif service_label_in = 'virtualization' then
            ents_to_process := array_append(ents_to_process, 'rhn_virtualization');

            roles_to_process := array_append(roles_to_process, 'config_admin');
        elsif service_label_in = 'virtualization_platform' then
            ents_to_process := array_append(ents_to_process, 'rhn_virtualization_platform');
            roles_to_process := array_append(roles_to_process, 'config_admin');
    elsif service_label_in = 'nonlinux' then
            ents_to_process := array_append(ents_to_process, 'rhn_nonlinux');
            roles_to_process := array_append(roles_to_process, 'config_admin');
        end if;

        if enable_in = 'Y' then
            for i in 1..array_upper(ents_to_process, 1) loop
                for ent in ents(ents_to_process[i]) loop
                    create_row := 'Y';
                    for oe in org_ents(ent.label) loop
                        create_row := 'N';
                    end loop;
                    if create_row = 'Y' then
                        insert into rhnOrgEntitlements(org_id, entitlement_id)
                            values (org_id_in, ent.id);
                    end if;
                end loop;
            end loop;
            for i in 1..array_upper(roles_to_process, 1) loop
                for role in roles(roles_to_process[i]) loop
                    create_row := 'Y';
                    for o_r in org_roles(role.label) loop
                        create_row := 'N';
                    end loop;
                    if create_row = 'Y' then
                        insert into rhnUserGroup(
                                id, name, description, current_members,
                                group_type, org_id
                            ) (
                                select  nextval('rhn_user_group_id_seq'),
                                        ugt.name || 's',
                                        ugt.name || 's for Org ' ||
                                            o.name || ' ('|| o.id ||')',
                                        0, ugt.id, o.id
                                from    rhnUserGroupType ugt,
                                        web_customer o
                                where   o.id = org_id_in
                                    and ugt.id = role.id
                            );
                    end if;
                end loop;
            end loop;
        else
            for i in 1..coalesce(array_upper(ents_to_process, 1), 0) loop
                for ent in ents(ents_to_process[i]) loop
                    delete from rhnOrgEntitlements
                     where org_id = org_id_in
                       and entitlement_id = ent.id;
                end loop;
            end loop;
        end if;
    end$$
language plpgsql;

    create or replace function set_customer_enterprise (
        customer_id_in in numeric
    ) returns void
as $$
    begin
        perform rhn_entitlements.modify_org_service(customer_id_in, 'enterprise', 'Y');
    end$$
language plpgsql;

    create or replace function set_customer_provisioning (
        customer_id_in in numeric
    ) returns void
as $$
    begin
        perform rhn_entitlements.modify_org_service(customer_id_in, 'provisioning', 'Y');
    end$$
language plpgsql;

    create or replace function set_customer_monitoring (
        customer_id_in in numeric
    ) returns void
as $$
    begin
        perform rhn_entitlements.modify_org_service(customer_id_in, 'monitoring', 'Y');
    end$$
language plpgsql;

    create or replace function set_customer_nonlinux (
        customer_id_in in numeric
    ) returns void
as $$
    begin
        perform rhn_entitlements.modify_org_service(customer_id_in, 'nonlinux', 'Y');
    end$$
language plpgsql;

    create or replace function unset_customer_enterprise (
        customer_id_in in numeric
    ) returns void
as $$
    begin
        perform rhn_entitlements.modify_org_service(customer_id_in, 'enterprise', 'N');
    end$$
language plpgsql;

    create or replace function unset_customer_provisioning (
        customer_id_in in numeric
    ) returns void
as $$
    begin
        perform rhn_entitlements.modify_org_service(customer_id_in, 'provisioning', 'N');
    end$$
language plpgsql;

    create or replace function unset_customer_monitoring (
        customer_id_in in numeric
    ) returns void
as $$
    begin
        perform rhn_entitlements.modify_org_service(customer_id_in, 'monitoring', 'N');
    end$$
language plpgsql;

    create or replace function unset_customer_nonlinux (
        customer_id_in in numeric
    ) returns void
as $$
    begin
        perform rhn_entitlements.modify_org_service(customer_id_in, 'nonlinux', 'N');
    end$$
language plpgsql;

    -- *******************************************************************
    -- PROCEDURE: prune_group
    -- Unsubscribes servers consuming physical slots that over the org's
    --   limit.
    -- Called by: set_server_group_count, repoll_virt_guest_entitlements
    -- *******************************************************************
    create or replace function prune_group (
        group_id_in in numeric,
        quantity_in in numeric,
        update_family_countsYN in numeric default 1
    ) returns void
as $$
    declare
        sgrecord record;
      type_is_base char;
    begin
            update      rhnServerGroup
                set     max_members = quantity_in
                where   id = group_id_in;

            for sgrecord in (
		   select  server_id, server_group_id, sgt.id as group_type_id, sgt.label
		    from    rhnServerGroupType              sgt,
				    rhnServerGroup                  sg,
				    rhnServerGroupMembers   sgm
		    where   1=1
			    and sgm.server_group_id = group_id_in
			    and sgm.server_id in (
				    select  sep.server_id
				    from
					rhnServerEntitlementPhysical sep
				    where
					sep.server_group_id = group_id_in
				    order by sep.modified asc
				    offset quantity_in
				)
			    and sgm.server_group_id = sg.id
			    and sg.group_type = sgt.id
	    ) loop
                perform rhn_entitlements.remove_server_entitlement(sgrecord.server_id, sgrecord.label);
            
            select is_base 
            into type_is_base
            from rhnServerGroupType sgt
            where sgt.id = sgrecord.group_type_id;

            -- if we're removing a base ent, then be sure to
            -- remove the server's channel subscriptions.
            if ( type_is_base = 'Y' ) then
                   perform rhn_channel.clear_subscriptions(sgrecord.server_id, 0, update_family_countsYN);
            end if;

            end loop;
    end$$
language plpgsql;

    -- *******************************************************************
    -- PROCEDURE: assign_system_entitlement
    --
    -- Moves system entitlements from from_org_id_in to to_org_id_in.
    -- Can raise not_enough_entitlements_in_base_org if from_org_id_in
    -- does not have enough entitlements to cover the move.
    -- Takes care of unentitling systems if necessary by calling 
    -- set_server_group_count
    -- *******************************************************************
    create or replace function assign_system_entitlement(
        group_label_in in varchar,
        from_org_id_in in numeric,
        to_org_id_in in numeric,
        quantity_in in numeric
    ) returns void
as $$
    declare
        prev_ent_count numeric;
    to_org_prev_ent_count numeric;
        new_ent_count numeric;
    new_quantity numeric;
        group_type numeric;
    begin

            select max_members
            into prev_ent_count
            from rhnServerGroupType sgt,
                 rhnServerGroup sg
            where sg.org_id = from_org_id_in
              and sg.group_type = sgt.id
              and sgt.label = group_label_in;

            if not found then
                perform rhn_exception.raise_exception(
                              'not_enough_entitlements_in_base_org');
            end if;

            select max_members
            into to_org_prev_ent_count
            from rhnServerGroupType sgt,
                 rhnServerGroup sg
            where sg.org_id = to_org_id_in
              and sg.group_type = sgt.id
              and sgt.label = group_label_in;

            if not found then
                to_org_prev_ent_count := 0;
            end if;
    
            select id
            into group_type
            from rhnServerGroupType
            where label = group_label_in;

            if not found then
                perform rhn_exception.raise_exception(
                              'invalid_server_group');
            end if;

        new_ent_count := prev_ent_count - quantity_in;
    
        if prev_ent_count > new_ent_count then
            new_quantity := to_org_prev_ent_count + quantity_in;
        end if;
    
        if new_ent_count < 0 then
            perform rhn_exception.raise_exception(
                          'not_enough_entitlements_in_base_org');
        end if;


        perform rhn_entitlements.set_server_group_count(from_org_id_in,
                                         group_type,
                                         new_ent_count);

        perform rhn_entitlements.set_server_group_count(to_org_id_in,
                                         group_type,
                                         new_quantity);
        
        -- Create or delete the entries in rhnOrgEntitlementType
        if group_label_in = 'enterprise_entitled' then 
            if new_quantity > 0 then
                perform rhn_entitlements.set_customer_enterprise(to_org_id_in);
            else
                perform rhn_entitlements.unset_customer_enterprise(to_org_id_in);
            end if;
        end if;

        if group_label_in = 'provisioning_entitled' then
            if new_quantity > 0 then
                perform rhn_entitlements.set_customer_provisioning(to_org_id_in);
            else
                perform rhn_entitlements.unset_customer_provisioning(to_org_id_in);
            end if;
        end if;

        if group_label_in = 'monitoring_entitled' then
            if new_quantity > 0 then
                perform rhn_entitlements.set_customer_monitoring(to_org_id_in);
            else
                perform rhn_entitlements.unset_customer_monitoring(to_org_id_in);
            end if;
        end if;

    end$$
language plpgsql;

    -- *******************************************************************
    -- PROCEDURE: assign_channel_entitlement
    --
    -- Moves channel entitlements from from_org_id_in to to_org_id_in.
    -- Can raise not_enough_entitlements_in_base_org if from_org_id_in
    -- does not have enough entitlements to cover the move.
    -- Takes care of unentitling systems if necessary by calling 
    -- set_family_count
    -- *******************************************************************
    create or replace function assign_channel_entitlement(
        channel_family_label_in in varchar,
        from_org_id_in in numeric,
        to_org_id_in in numeric,
        quantity_in in numeric,
        flex_in in numeric
    ) returns void
as $$
    declare
        from_org_prev_ent_count numeric;
        from_org_prev_ent_count_flex numeric;
        new_ent_count numeric;
        new_ent_count_flex numeric;
        to_org_prev_ent_count numeric;
        to_org_prev_ent_count_flex numeric;
        new_quantity numeric;
        new_flex numeric;
        cfam_id       numeric;
    begin

            select max_members
            into from_org_prev_ent_count
            from rhnChannelFamily cf,
                 rhnPrivateChannelFamily pcf
            where pcf.org_id = from_org_id_in
              and pcf.channel_family_id = cf.id
              and cf.label = channel_family_label_in;

            if not found then
                perform rhn_exception.raise_exception(
                              'not_enough_entitlements_in_base_org');
            end if;
    
            select max_members
            into to_org_prev_ent_count
            from rhnChannelFamily cf,
                 rhnPrivateChannelFamily pcf
            where pcf.org_id = to_org_id_in
              and pcf.channel_family_id = cf.id
              and cf.label = channel_family_label_in;

            if not found then
                to_org_prev_ent_count := 0;
            end if;

            select fve_max_members
            into from_org_prev_ent_count_flex
            from rhnChannelFamily cf,
                rhnPrivateChannelFamily pcf
            where pcf.org_id = from_org_id_in
              and pcf.channel_family_id = cf.id
              and cf.label = channel_family_label_in;

            if not found then
                perform rhn_exception.raise_exception(
                              'not_enough_flex_entitlements_in_base_org');
            end if;

            select fve_max_members
            into to_org_prev_ent_count_flex
            from rhnChannelFamily cf,
                 rhnPrivateChannelFamily pcf
            where pcf.org_id = to_org_id_in
              and pcf.channel_family_id = cf.id
              and cf.label = channel_family_label_in;

            if not found then
                to_org_prev_ent_count_flex := 0;
            end if;

            select id
            into cfam_id
            from rhnChannelFamily
            where label = channel_family_label_in;

            if not found then
                perform rhn_exception.raise_exception(
                              'invalid_channel_family');
            end if;

        new_ent_count := from_org_prev_ent_count - quantity_in;
        new_ent_count_flex := from_org_prev_ent_count_flex - flex_in;
    
        if from_org_prev_ent_count >= new_ent_count then
            new_quantity := to_org_prev_ent_count + quantity_in;
        end if;

        if from_org_prev_ent_count_flex >= new_ent_count_flex then
            new_flex := to_org_prev_ent_count_flex + flex_in;
        end if;

        if new_ent_count < 0 then
            perform rhn_exception.raise_exception(
                          'not_enough_entitlements_in_base_org');
        end if;

        if new_ent_count_flex < 0 then
            perform rhn_exception.raise_exception(
                          'not_enough_flex_entitlements_in_base_org');
        end if;



        perform rhn_entitlements.set_family_count(from_org_id_in,
                                          cfam_id,
                                          new_ent_count,
                                          new_ent_count_flex);

        perform rhn_entitlements.set_family_count(to_org_id_in,
                                          cfam_id,
                                          new_quantity,
                                          new_flex);

    end$$
language plpgsql;

    -- *******************************************************************
    -- PROCEDURE: activate_system_entitlement
    --
    -- Sets the values in rhnServerGroup for a given rhnServerGroupType.
    -- 
    -- Calls: set_server_group_count to update, prune, or create the group.
    -- Called by: the code that activates a satellite cert. 
    --
    -- Raises not_enough_entitlements_in_base_org if all entitlements
    -- in the org are used so the free entitlements would not cover
    -- the difference when descreasing the number of entitlements.
    -- *******************************************************************
    create or replace function activate_system_entitlement(
        org_id_in in numeric,
        group_label_in in varchar,
        quantity_in in numeric
    ) returns void
as $$
    declare
        prev_ent_count numeric; 
        prev_ent_count_sum numeric; 
        group_type numeric;
    begin

        -- Fetch the current entitlement count for the org
        -- into prev_ent_count

            select current_members
            into prev_ent_count
            from rhnServerGroupType sgt,
                 rhnServerGroup sg
            where sg.group_type = sgt.id
              and sgt.label = group_label_in
              and sg.org_id = org_id_in;

            if not found then
                prev_ent_count := 0;
            end if;

            select id
            into group_type
            from rhnServerGroupType
            where label = group_label_in;

            if not found then
                perform rhn_exception.raise_exception(
                              'invalid_server_group');
            end if;

        -- If we're setting the total entitlemnt count to a lower value,
        -- and that value is less than the allocated count in this org,
        -- we need to raise an exception.
        if quantity_in < prev_ent_count then
            perform rhn_exception.raise_exception(
                          'not_enough_entitlements_in_base_org');
        else
            -- don't update family counts after every server
            -- will do bulk update afterwards
            perform rhn_entitlements.set_server_group_count(org_id_in,
                                             group_type,
                                             quantity_in,
                                             0);
            -- bulk update family counts
            perform rhn_channel.update_group_family_counts(group_label_in, org_id_in);
        end if;

    end$$
language plpgsql;

    -- *******************************************************************
    -- PROCEDURE: activate_channel_entitlement
    --
    -- Calls: set_family_count to update, prune, or create the family
    --        permission bucket.
    -- Called by: the code that activates a satellite cert. 
    --
    -- Raises not_enough_entitlements_in_base_org if there are not enough
    -- entitlements in the org to cover the difference when you are
    -- descreasing the number of entitlements.
    --
    -- The backend code in Python is expected to do whatever arithmetics
    -- is needed.
    -- *******************************************************************
    create or replace function activate_channel_entitlement(
        org_id_in in numeric,
        channel_family_label_in in varchar,
        quantity_in in numeric,
        flex_in in numeric
    ) returns void
as $$
    declare
        prev_ent_count numeric; 
        prev_flex_count numeric;
        prev_ent_count_sum numeric; 
        cfam_id numeric;
        reduce_quantity numeric;
        total_flex_capable numeric;
        to_convert_reg cursor (channel_family_id_val numeric, org_id_in numeric, quantity numeric) for
                     select SC.server_id
                     from rhnServerChannel SC inner join
                          rhnServer S on S.id = SC.server_id
                     where
                         is_fve = 'Y'
                         and S.org_id = org_id_in
                         and SC.channel_id in
                         (select cfm.channel_id from rhnChannelFamilyMembers cfm
                             where cfm.CHANNEL_FAMILY_ID = channel_family_id_val)
                         limit quantity;
         to_convert_flex cursor (channel_family_id_val numeric, org_id_in numeric, quantity numeric) for
                   select server_id
                   from rhnServerFveCapable
                       where SERVER_ORG_ID = org_id_in and
                             channel_family_id = cfam_id
                       limit quantity;

    begin

        -- Fetch the current entitlement count for the org
        -- into prev_ent_count
            select current_members
            into prev_ent_count
            from rhnChannelFamily cf,
                 rhnPrivateChannelFamily pcf
            where pcf.org_id = org_id_in
              and pcf.channel_family_id = cf.id
              and cf.label = channel_family_label_in;

            if not found then
                prev_ent_count := 0;
            end if;

            select pcf.fve_current_members
            into prev_flex_count
            from rhnChannelFamily cf,
                 rhnPrivateChannelFamily pcf
            where pcf.org_id = org_id_in
              and pcf.channel_family_id = cf.id
              and cf.label = channel_family_label_in;

            if not found then
                prev_flex_count := 0;
            end if;

            select id
            into cfam_id
            from rhnChannelFamily
            where label = channel_family_label_in;

            if not found then
                perform rhn_exception.raise_exception(
                              'invalid_channel_family');
            end if;

        -- if there are too few flex entitlements
        if flex_in < prev_flex_count then
            -- and if the extra we need is less than or equal to our extra regular entitlements
            if prev_flex_count - flex_in <= quantity_in - prev_ent_count then
                   reduce_quantity := prev_flex_count - flex_in;
                   -- We need to convert some systems from flex guest to regular
                   for system in to_convert_reg(cfam_id, org_id_in, reduce_quantity) loop
                      --rhn_channel.convert_to_regular(system.server_id, cfam_id);
                      UPDATE rhnServerChannel sc set is_fve = 'N'
                           where sc.server_id = system.server_id
                                 and sc.channel_id in (select cfm.channel_id
                                                          from rhnChannelFamilyMembers cfm
                                                          where cfm.channel_family_id = cfam_id);
                   end loop;

                   --reset previous counts
                   prev_ent_count := prev_ent_count + reduce_quantity;
                   prev_flex_count := prev_flex_count - reduce_quantity;
            else
                perform rhn_exception.raise_exception(
                          'not_enough_flex_entitlements_in_base_org');
            end if;
        end if;

        -- if there are too few regular entitlements, and extra flex entitlements
        if quantity_in < prev_ent_count and prev_flex_count < flex_in then
                -- how many flex-capable systems (that aren't using flex) do we have
                select count(*)
                   into total_flex_capable
                   from rhnServerFveCapable
                       where SERVER_ORG_ID = org_id_in and
                             channel_family_id = cfam_id;
                -- if we have enough flex capable machines that is at least
                --   as many as what we are over on
                if total_flex_capable >= prev_ent_count - quantity_in then
                    reduce_quantity := prev_ent_count - quantity_in;
                    for system in to_convert_flex(cfam_id, org_id_in, reduce_quantity) loop
--                          rhn_channel.convert_to_fve(system.server_id, cfam_id);
                        UPDATE rhnServerChannel sc set is_fve = 'Y'
                           where sc.server_id = system.server_id
                                 and sc.channel_id in (select cfm.channel_id
                                                          from rhnChannelFamilyMembers cfm
                                                          where cfm.channel_family_id = cfam_id);
                    end loop;
                    prev_ent_count := prev_ent_count - reduce_quantity;
                    prev_flex_count := prev_flex_count + reduce_quantity;
                end if;
        end if;

        -- If we're setting the total entitlemnt count to a lower value,
        -- and that value is less than the count in that one org,
        -- we need to raise an exception.
        if quantity_in < prev_ent_count then
            perform rhn_exception.raise_exception(
                          'not_enough_entitlements_in_base_org');
        else
            -- even if we've manually converted systems to/from flex above
            -- set_family_count should call update_family_counts, to reset
            -- current used slots
            perform rhn_entitlements.set_family_count(org_id_in, cfam_id,
                                              quantity_in, flex_in);
        end if;

    end$$
language plpgsql;

    create or replace function set_server_group_count (
        customer_id_in in numeric,  -- customer_id
        group_type_in in numeric,   -- rhn[User|Server]GroupType.id
        quantity_in in numeric,      -- quantity
                update_family_countsYN in numeric default 1
    ) returns void
as $$
    declare
        group_id numeric;
        quantity numeric;
        wasfound boolean;
    begin
        quantity := quantity_in;
        if quantity is not null and quantity < 0 then
            quantity := 0;
        end if;

        select  rsg.id
        into    group_id
        from    rhnServerGroup rsg
        where   1=1
            and rsg.org_id = customer_id_in
            and rsg.group_type = group_type_in;

        -- preserve the not found status across the rhn_entitlements.prune_group invocation
        wasfound := true;
        if not found then
            wasfound := false;
        end if;

        perform rhn_entitlements.prune_group(
            group_id,
            quantity,
                        update_family_countsYN
        );

        if not wasfound then
            insert into rhnServerGroup (
                    id, name, description, max_members, current_members,
                    group_type, org_id, created, modified
                ) (
                    select  nextval('rhn_server_group_id_seq'), name, name,
                            quantity, 0, id, customer_id_in,
                            current_timestamp, current_timestamp
                    from    rhnServerGroupType
                    where   id = group_type_in
            );
        end if;

    end$$
language plpgsql;

    -- *******************************************************************
    -- PROCEDURE: prune_family
    -- Unsubscribes servers consuming physical slots from the channel family 
    --   that are over the org's limit.
    -- Called by: set_family_count
    -- *******************************************************************
    create or replace function prune_family (
        customer_id_in in numeric,
        channel_family_id_in in numeric,
        quantity_in in numeric,
        flex_in in numeric
    ) returns void
as $$
    declare
        serverchannels cursor(tmp_quantity numeric, is_fve_in char) for
            select  sc.server_id,
                    sc.channel_id
            from    rhnServerChannel sc,
                    rhnChannelFamilyMembers cfm
            where   1=1
                and cfm.channel_family_id = channel_family_id_in
                and cfm.channel_id = sc.channel_id
                and server_id in (
                            select  rs.id as server_id
                            from    
                                    rhnServerChannel        rsc,
                                    rhnChannelFamilyMembers rcfm,
                                    rhnServer               rs
                            where   1=1
                                and rs.org_id = customer_id_in
                                and rs.id = rsc.server_id
                                and rsc.channel_id = rcfm.channel_id
                                and rcfm.channel_family_id =  channel_family_id_in
                                and rsc.is_fve = is_fve_in
                                -- we only want to grab servers consuming
                                -- physical slots.
                                and exists (
                                    select 1
                                    from rhnChannelFamilyServerPhysical cfsp
                                    where cfsp.server_id = rs.id
                                    and cfsp.channel_family_id = 
                                        channel_family_id_in
                                    )
                            order by rcfm.modified asc
                            offset quantity_in
                        );
    begin
        -- if we get a null customer_id, this is completely bogus.
        if customer_id_in is null then
            return;
        end if;

        for sc in serverchannels(quantity_in, 'N') loop
            perform rhn_channel.unsubscribe_server(sc.server_id, sc.channel_id,
                                                   1, 1, 0, 0);
        end loop;

        for sc in serverchannels(flex_in, 'Y') loop
            perform rhn_channel.unsubscribe_server(sc.server_id, sc.channel_id,
                                                   1, 1, 0, 0);
        end loop;

        perform rhn_channel.update_family_counts(channel_family_id_in, customer_id_in);
    end$$
language plpgsql;
        
    create or replace function set_family_count (
        customer_id_in in numeric,      -- customer_id
        channel_family_id_in in numeric,    -- 246
        quantity_in in numeric,          -- 3
        flex_in in numeric
    ) returns void
as $$
    declare
        privperms cursor for
            select  1
            from    rhnPrivateChannelFamily
            where   org_id = customer_id_in
                and channel_family_id = channel_family_id_in;
        pubperms cursor for
            select  o.id org_id
            from    web_customer o,
                    rhnPublicChannelFamily pcf
            where   pcf.channel_family_id = channel_family_id_in;
        quantity numeric;
        done numeric := 0;
        flex numeric;
    begin
        quantity := quantity_in;
        if quantity is not null and quantity < 0 then
            quantity := 0;
        end if;
        flex := flex_in;
        if flex is not null and flex < 0 then
            flex := 0;
        end if;

        if customer_id_in is not null then
            for perm in privperms loop
                perform rhn_entitlements.prune_family(
                    customer_id_in,
                    channel_family_id_in,
                    quantity,
                    flex
                );

                if quantity is null and flex is null then
                    delete from rhnPrivateChannelFamily
                        where org_id = customer_id_in
                            and channel_family_id = channel_family_id_in;
                 else
                    update rhnPrivateChannelFamily
                        set max_members = quantity
                        where org_id = customer_id_in
                            and channel_family_id = channel_family_id_in;

                   update rhnPrivateChannelFamily
                        set fve_max_members = flex
                        where org_id = customer_id_in
                            and channel_family_id = channel_family_id_in;
                end if;
                return;
            end loop;

            insert into rhnPrivateChannelFamily (
                    channel_family_id, org_id, max_members, current_members, fve_max_members, fve_current_members
                ) values (
                    channel_family_id_in, customer_id_in, quantity, 0, flex, 0 );
            return;
        end if;

        for perm in pubperms loop
            if quantity = 0 then
                perform rhn_entitlements.prune_family(
                    perm.org_id,
                    channel_family_id_in,
                    quantity,
                    flex
                );
                if done = 0 then
                    delete from rhnPublicChannelFamily
                        where channel_family_id = channel_family_id_in;
                end if;
            end if;
            done := 1;
        end loop;
        -- if done's not 1, then we don't have any entitlements
        if done != 1 then
            insert into rhnPublicChannelFamily (
                    channel_family_id
                ) values (
                    channel_family_id_in
                );
        end if;
    end$$
language plpgsql;

    -- this expects quantity_in to be the number of available slots, not the
    -- max_members of the server group.  If you give it too many, it'll fail
    -- and raise servergroup_max_members.
    -- We should NEVER run this unless we're SURE that we won't
    -- be violating the max.
    create or replace function entitle_last_modified_servers (
        customer_id_in in numeric,  -- customer_id
        type_label_in in varchar,   -- 'enterprise_entitled'
        quantity_in in numeric      -- 3
    ) returns void
as $$
    declare
        -- find the servers that aren't currently in slots
        servers cursor(cid_in numeric, quant_in numeric) for
                                    select  rs.id as server_id
                                    from    rhnServer rs
                                    where   1=1
                                        and rs.org_id = cid_in
                                        and not exists (
                                            select  1
                                            from    rhnServerGroup sg,
                                                    rhnServerGroupMembers rsgm
                                            where   rsgm.server_id = rs.id
                                                and rsgm.server_group_id = sg.id
                                                and sg.group_type is not null
                                        )
                                        and not exists (
                                            select 1
                                            from rhnVirtualInstance vi
                                            where vi.virtual_system_id =
                                                  rs.id
                                        )
                                    order by modified desc
                                    limit quant_in;
    begin
        for server in servers(customer_id_in, quantity_in) loop
            perform rhn_entitlements.entitle_server(server.server_id, type_label_in);
        end loop;
    end$$
language plpgsql;

    create or replace function subscribe_newest_servers (
        customer_id_in in numeric
    ) returns void
as $$
    declare
        -- find servers without base channels
        servers cursor(cid_in numeric) for
            select  s.id
            from    rhnServer           s
            where   1=1
                and s.org_id = cid_in
                and not exists (
                        select 1
                        from    rhnChannel          c,
                                rhnServerChannel    sc
                        where   sc.server_id = s.id
                            and sc.channel_id = c.id
                            and c.parent_channel is null
                    )
                and not exists (
                        select 1
                        from rhnVirtualInstance vi
                        where vi.virtual_system_id = s.id
                    )                        
            order by s.modified desc;
        channel_id numeric;
    begin
        for server in servers(customer_id_in) loop
            channel_id := rhn_channel.guess_server_base(server.id);
            if channel_id is not null then
                begin
                    perform rhn_channel.subscribe_server(server.id, channel_id);
                -- exception is really channel_family_no_subscriptions
                exception
                    when others then
                        null;
                end;
            end if;
        end loop;
    end$$
language plpgsql;


-- restore the original setting
update pg_settings set setting = overlay( setting placing '' from 1 for (length('rhn_entitlements')+1) ) where name = 'search_path';
   070701000007CA000081B400000000000000000000000167AE111400000064000000000000000000000000000000000000006300000000susemanager-schema/upgrade/spacewalk-schema-2.0-to-spacewalk-schema-2.1/021-rhnKickstartScript.sql    update rhnkickstartscript set position = position * -1 where script_type = 'post' and chroot = 'N';
070701000007CB000081B400000000000000000000000167AE111400000500000000000000000000000000000000000000006300000000susemanager-schema/upgrade/spacewalk-schema-2.0-to-spacewalk-schema-2.1/030-rhnPackageEnhances.sql    --
-- Copyright (c) 2013 Novell
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
--

CREATE TABLE rhnPackageEnhances
(
    package_id     NUMERIC NOT NULL
                       CONSTRAINT rhn_pkg_enh_package_fk
                           REFERENCES rhnPackage (id)
                           ON DELETE CASCADE,
    capability_id  NUMERIC NOT NULL
                       CONSTRAINT rhn_pkg_enh_capability_fk
                           REFERENCES rhnPackageCapability (id),
    sense          NUMERIC
                       DEFAULT (0) NOT NULL,
    created        TIMESTAMPTZ
                       DEFAULT (current_timestamp) NOT NULL,
    modified       TIMESTAMPTZ
                       DEFAULT (current_timestamp) NOT NULL
)

;

CREATE UNIQUE INDEX rhn_pkg_enh_pid_cid_s_uq
    ON rhnPackageEnhances (package_id, capability_id, sense)
    ;

CREATE INDEX rhn_pkg_enh_cid_idx
    ON rhnPackageEnhances (capability_id)
    
    ;
070701000007CC000081B400000000000000000000000167AE1114000002E2000000000000000000000000000000000000006300000000susemanager-schema/upgrade/spacewalk-schema-2.0-to-spacewalk-schema-2.1/031-rhnPackageEnhances.sql    --
-- Copyright (c) 2013 Novell, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
--

create or replace function rhn_pkg_enh_mod_trig_fun() returns trigger as
$$
begin
	new.modified := current_timestamp;

	return new;
end;
$$ language plpgsql;

create trigger
rhn_pkg_enh_mod_trig
before insert or update on rhnPackageEnhances
for each row
execute procedure rhn_pkg_enh_mod_trig_fun();
  070701000007CD000081B400000000000000000000000167AE11140000014A000000000000000000000000000000000000006900000000susemanager-schema/upgrade/spacewalk-schema-2.0-to-spacewalk-schema-2.1/032-fix-supplements-enhances.sql  
insert into rhnPackageEnhances (package_id, capability_id, sense)
  select s.package_id, s.capability_id, s.sense
    from rhnPackageSupplements s
   where (s.sense::bigint & 134217728) != 134217728;
-- 134217728 == (1 << 27) STRONG FLAG in RPM

delete from rhnPackageSupplements
 where (sense::bigint & 134217728) != 134217728;
  070701000007CE000081B400000000000000000000000167AE1114000000F7000000000000000000000000000000000000006700000000susemanager-schema/upgrade/spacewalk-schema-2.0-to-spacewalk-schema-2.1/033-delete-cached-repodata.sql    delete from rhnPackageRepodata;

insert into rhnRepoRegenQueue (id, CHANNEL_LABEL, REASON, FORCE)
(select sequence_nextval('rhn_repo_regen_queue_id_seq'),
        C.label,
        'package summary modification',
        'Y'
   from rhnChannel C);
 070701000007CF000081B400000000000000000000000167AE111400000108000000000000000000000000000000000000007000000000susemanager-schema/upgrade/spacewalk-schema-2.0-to-spacewalk-schema-2.1/034-rhnServerNeededCache-channel_id.sql   

ALTER TABLE rhnServerNeededCache ADD
        channel_id NUMERIC
                CONSTRAINT rhn_sncp_cid_fk
                REFERENCES rhnChannel (id)
                ON DELETE CASCADE;

CREATE INDEX rhn_snc_cid_idx
    ON rhnServerNeededCache (channel_id)
    ;
070701000007D0000081B400000000000000000000000167AE111400000767000000000000000000000000000000000000005F00000000susemanager-schema/upgrade/spacewalk-schema-2.0-to-spacewalk-schema-2.1/035-rhn_server.pkb.sql    

update pg_settings set setting = 'rhn_server,' || setting where name = 'search_path';

    create or replace function update_needed_cache(
        server_id_in in numeric
	) returns void as $$
    begin
      delete from rhnServerNeededCache
        where server_id = server_id_in;
      insert into rhnServerNeededCache
             (server_id, errata_id, package_id, channel_id)
        (select distinct sp.server_id, x.errata_id, p.id, x.channel_id
           FROM (SELECT sp_sp.server_id, sp_sp.name_id,
		        sp_sp.package_arch_id, max(sp_pe.evr) AS max_evr
                   FROM rhnServerPackage sp_sp
                   join rhnPackageEvr sp_pe ON sp_pe.id = sp_sp.evr_id
                  GROUP BY sp_sp.server_id, sp_sp.name_id, sp_sp.package_arch_id) sp
           join rhnPackage p ON p.name_id = sp.name_id
           join rhnPackageEvr pe ON pe.id = p.evr_id AND sp.max_evr < pe.evr
           join rhnPackageUpgradeArchCompat puac
	            ON puac.package_arch_id = sp.package_arch_id
		    AND puac.package_upgrade_arch_id = p.package_arch_id
           join rhnServerChannel sc ON sc.server_id = sp.server_id
           join rhnChannelPackage cp ON cp.package_id = p.id
	            AND cp.channel_id = sc.channel_id
           left join (SELECT ep.errata_id, ce.channel_id, ep.package_id
                        FROM rhnChannelErrata ce
                        join rhnErrataPackage ep
			         ON ep.errata_id = ce.errata_id
			join rhnServerChannel sc_sc
			         ON sc_sc.channel_id = ce.channel_id
		       WHERE sc_sc.server_id = server_id_in) x
             ON x.channel_id = sc.channel_id AND x.package_id = cp.package_id
          where sp.server_id = server_id_in);
	end$$ language plpgsql;

-- restore the original setting
update pg_settings set setting = overlay( setting placing '' from 1 for (length('rhn_server')+1) ) where name = 'search_path';
 070701000007D1000081B400000000000000000000000167AE1114000019BA000000000000000000000000000000000000005800000000susemanager-schema/upgrade/spacewalk-schema-2.0-to-spacewalk-schema-2.1/036-armv6hl.sql   insert into rhnCpuArch (id, label, name) select
sequence_nextval('rhn_cpu_arch_id_seq'), 'armv6hl', 'ARMv6hl' from dual
where not exists (select 1 from rhnCpuArch where label = 'armv6hl');


insert into rhnPackageArch (id, label, name, arch_type_id) select
sequence_nextval('rhn_package_arch_id_seq'), 'armv6hl', 'ARMv6hl', lookup_arch_type('rpm') from dual
where not exists (select 1 from rhnPackageArch where label = 'armv6hl');


insert into rhnServerArch (id, label, name, arch_type_id) select
sequence_nextval('rhn_server_arch_id_seq'), 'armv6hl-redhat-linux', 'armv6hl', lookup_arch_type('rpm') from dual
where not exists (select 1 from rhnServerArch where label = 'armv6hl-redhat-linux');


insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) select
LOOKUP_PACKAGE_ARCH('noarch'), LOOKUP_PACKAGE_ARCH('armv6hl'), current_timestamp, current_timestamp from dual
where not exists (select 1 from rhnPackageUpgradeArchCompat where package_arch_id = LOOKUP_PACKAGE_ARCH('noarch') and package_upgrade_arch_id = LOOKUP_PACKAGE_ARCH('armv6hl'));

insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) select
LOOKUP_PACKAGE_ARCH('armv6hl'), LOOKUP_PACKAGE_ARCH('armv6hl'), current_timestamp, current_timestamp from dual
where not exists (select 1 from rhnPackageUpgradeArchCompat where package_arch_id = LOOKUP_PACKAGE_ARCH('armv6hl') and package_upgrade_arch_id = LOOKUP_PACKAGE_ARCH('armv6hl'));

insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) select
LOOKUP_PACKAGE_ARCH('armv6hl'), LOOKUP_PACKAGE_ARCH('noarch'), current_timestamp, current_timestamp from dual
where not exists (select 1 from rhnPackageUpgradeArchCompat where package_arch_id = LOOKUP_PACKAGE_ARCH('armv6hl') and package_upgrade_arch_id = LOOKUP_PACKAGE_ARCH('noarch'));


insert into rhnChannelPackageArchCompat (channel_arch_id, package_arch_id) select
LOOKUP_CHANNEL_ARCH('channel-arm'), LOOKUP_PACKAGE_ARCH('armv6hl') from dual
where not exists (select 1 from rhnChannelPackageArchCompat where channel_arch_id = LOOKUP_CHANNEL_ARCH('channel-arm') and package_arch_id = LOOKUP_PACKAGE_ARCH('armv6hl'));


insert into rhnServerChannelArchCompat (server_arch_id, channel_arch_id) select
LOOKUP_SERVER_ARCH('armv6hl-redhat-linux'), LOOKUP_CHANNEL_ARCH('channel-arm') from dual
where not exists (select 1 from rhnServerChannelArchCompat where server_arch_id = LOOKUP_SERVER_ARCH('armv6hl-redhat-linux') and channel_arch_id = LOOKUP_CHANNEL_ARCH('channel-arm'));

insert into rhnServerPackageArchCompat (server_arch_id, package_arch_id, preference) select
LOOKUP_SERVER_ARCH('armv7l-redhat-linux'), LOOKUP_PACKAGE_ARCH('armv6hl'), 25 from dual
where not exists (select 1 from rhnServerPackageArchCompat where server_arch_id = LOOKUP_SERVER_ARCH('armv7l-redhat-linux') and package_arch_id = LOOKUP_PACKAGE_ARCH('armv6hl'));

insert into rhnServerPackageArchCompat (server_arch_id, package_arch_id, preference) select
LOOKUP_SERVER_ARCH('armv6hl-redhat-linux'), LOOKUP_PACKAGE_ARCH('armv6hl'), 0 from dual
where not exists (select 1 from rhnServerPackageArchCompat where server_arch_id = LOOKUP_SERVER_ARCH('armv6hl-redhat-linux'));

insert into rhnServerPackageArchCompat (server_arch_id, package_arch_id, preference) select
LOOKUP_SERVER_ARCH('armv6hl-redhat-linux'), LOOKUP_PACKAGE_ARCH('armv6l'), 10 from dual
where not exists (select 1 from rhnServerPackageArchCompat where server_arch_id = LOOKUP_SERVER_ARCH('armv6hl-redhat-linux') and package_arch_id = LOOKUP_PACKAGE_ARCH('armv6l'));

insert into rhnServerPackageArchCompat (server_arch_id, package_arch_id, preference) select
LOOKUP_SERVER_ARCH('armv6hl-redhat-linux'), LOOKUP_PACKAGE_ARCH('armv5tel'), 20 from dual
where not exists (select 1 from rhnServerPackageArchCompat where server_arch_id = LOOKUP_SERVER_ARCH('armv6hl-redhat-linux') and package_arch_id = LOOKUP_PACKAGE_ARCH('armv5tel'));

insert into rhnServerPackageArchCompat (server_arch_id, package_arch_id, preference) select
LOOKUP_SERVER_ARCH('armv6hl-redhat-linux'), LOOKUP_PACKAGE_ARCH('noarch'), 1000 from dual
where not exists (select 1 from rhnServerPackageArchCompat where server_arch_id = LOOKUP_SERVER_ARCH('armv6hl-redhat-linux') and package_arch_id = LOOKUP_PACKAGE_ARCH('noarch'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type ) select
lookup_server_arch('armv6hl-redhat-linux'), lookup_sg_type('sw_mgr_entitled') from dual
where not exists (select 1 from rhnServerServerGroupArchCompat where server_arch_id = lookup_server_arch('armv6hl-redhat-linux') and server_group_type = lookup_sg_type('sw_mgr_entitled'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type ) select
lookup_server_arch('armv6hl-redhat-linux'), lookup_sg_type('enterprise_entitled') from dual
where not exists (select 1 from rhnServerServerGroupArchCompat where server_arch_id = lookup_server_arch('armv6hl-redhat-linux') and server_group_type = lookup_sg_type('enterprise_entitled'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type ) select
lookup_server_arch('armv6hl-redhat-linux'), lookup_sg_type('provisioning_entitled') from dual
where not exists (select 1 from rhnServerServerGroupArchCompat where server_arch_id = lookup_server_arch('armv6hl-redhat-linux') and server_group_type = lookup_sg_type('provisioning_entitled'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type ) select
lookup_server_arch('armv6hl-redhat-linux'), lookup_sg_type('monitoring_entitled') from dual
where not exists (select 1 from rhnServerServerGroupArchCompat where server_arch_id = lookup_server_arch('armv6hl-redhat-linux') and server_group_type = lookup_sg_type('monitoring_entitled'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type ) select
lookup_server_arch('armv6hl-redhat-linux'), lookup_sg_type('virtualization_host') from dual
where not exists (select 1 from rhnServerServerGroupArchCompat where server_arch_id = lookup_server_arch('armv6hl-redhat-linux') and server_group_type = lookup_sg_type('virtualization_host'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type ) select
lookup_server_arch('armv6hl-redhat-linux'), lookup_sg_type('virtualization_host_platform') from dual
where not exists (select 1 from rhnServerServerGroupArchCompat where server_arch_id = lookup_server_arch('armv6hl-redhat-linux') and server_group_type = lookup_sg_type('virtualization_host_platform'));
  070701000007D2000081B400000000000000000000000167AE11140000003C000000000000000000000000000000000000006700000000susemanager-schema/upgrade/spacewalk-schema-2.0-to-spacewalk-schema-2.1/040-inc-length-rhnCVE-name.sql    
ALTER TABLE rhnCVE
    ALTER COLUMN name TYPE varchar(20);
070701000007D3000081B400000000000000000000000167AE11140000046F000000000000000000000000000000000000006100000000susemanager-schema/upgrade/spacewalk-schema-2.0-to-spacewalk-schema-2.1/040-rhnConfiguration.sql  --
-- Copyright (c) 2014 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

CREATE TABLE rhnConfiguration
(
    key                     VARCHAR(64) NOT NULL
                                CONSTRAINT rhnConfig_key_pk PRIMARY KEY,
    description             VARCHAR(512) NOT NULL,
    value                   VARCHAR(512),
    default_value           VARCHAR(512),
    created                 TIMESTAMPTZ
                                DEFAULT (current_timestamp) NOT NULL,
    modified                TIMESTAMPTZ
                                DEFAULT (current_timestamp) NOT NULL
)

;
 070701000007D4000081B400000000000000000000000167AE11140000039C000000000000000000000000000000000000006900000000susemanager-schema/upgrade/spacewalk-schema-2.0-to-spacewalk-schema-2.1/041-rhnConfiguration-trigger.sql  --
-- Copyright (c) 2014 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

create or replace function rhn_conf_mod_trig_fun() returns trigger as
$$
begin
        new.modified := current_timestamp;
        return new;
end;
$$ language plpgsql;

create trigger
rhn_conf_mod_trig
before insert or update on rhnConfiguration
for each row
execute procedure rhn_conf_mod_trig_fun();
070701000007D5000081B400000000000000000000000167AE111400000163000000000000000000000000000000000000006600000000susemanager-schema/upgrade/spacewalk-schema-2.0-to-spacewalk-schema-2.1/042-rhnConfiguration-data.sql INSERT INTO rhnConfiguration (key, description) VALUES ('extauth_default_orgid', 'Organization id, where externally authenticated users will be created.');
INSERT INTO rhnConfiguration (key, description, default_value) VALUES ('extauth_use_orgunit', 'Use Org. Unit IPA setting as organization name to create externally authenticated users in.', 'false');
 070701000007D6000081B400000000000000000000000167AE111400000449000000000000000000000000000000000000006000000000susemanager-schema/upgrade/spacewalk-schema-2.0-to-spacewalk-schema-2.1/043-rhnUserExtGroup.sql   --
-- Copyright (c) 2014 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnUserExtGroup
(
    id        NUMERIC NOT NULL
                  CONSTRAINT rhn_userExtGroup_id_pk PRIMARY KEY
                  ,
    label     VARCHAR(512) NOT NULL,
    created   TIMESTAMPTZ
                  DEFAULT (current_timestamp) NOT NULL,
    modified  TIMESTAMPTZ
                  DEFAULT (current_timestamp) NOT NULL
)

;

CREATE UNIQUE INDEX rhn_userextgroup_label_uq
    ON rhnUserExtGroup (label)
    ;

CREATE SEQUENCE rhn_userextgroup_seq;
   070701000007D7000081B400000000000000000000000167AE1114000003AA000000000000000000000000000000000000006800000000susemanager-schema/upgrade/spacewalk-schema-2.0-to-spacewalk-schema-2.1/044-rhnUserExtGroup-trigger.sql   --
-- Copyright (c) 2014 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

create or replace function rhn_userextgr_mod_trig_fun() returns trigger as
$$
begin
        new.modified := current_timestamp;
        return new;
end;
$$ language plpgsql;

create trigger
rhn_userextgr_mod_trig
before insert or update on rhnUserExtGroup
for each row
execute procedure rhn_userextgr_mod_trig_fun();
  070701000007D8000081B400000000000000000000000167AE1114000005C2000000000000000000000000000000000000006700000000susemanager-schema/upgrade/spacewalk-schema-2.0-to-spacewalk-schema-2.1/045-rhnUserExtGroupMapping.sql    --
-- Copyright (c) 2014 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnUserExtGroupMapping
(
    id        NUMERIC NOT NULL
                  CONSTRAINT rhn_userExtGroupMap_id_pk PRIMARY KEY
                  ,
    ext_group_id        NUMERIC NOT NULL
                  constraint rhn_userextgroupmap_e_fk
                  references rhnUserExtGroup(id)
                  on delete cascade,
    int_group_type_id        NUMERIC NOT NULL
                  constraint rhn_userextgroupmap_i_fk
                  references rhnUserGroupType(id)
                  on delete cascade,
    created   TIMESTAMPTZ
                  DEFAULT (current_timestamp) NOT NULL,
    modified  TIMESTAMPTZ
                  DEFAULT (current_timestamp) NOT NULL
)

;

CREATE UNIQUE INDEX rhn_userextgroupmap_ei_uq
    ON rhnUserExtGroupMapping (ext_group_id, int_group_type_id)
    ;

CREATE SEQUENCE rhn_userextgroupmap_seq;
  070701000007D9000081B400000000000000000000000167AE111400000423000000000000000000000000000000000000006F00000000susemanager-schema/upgrade/spacewalk-schema-2.0-to-spacewalk-schema-2.1/046-rhnUserExtGroupMapping-trigger.sql    --
-- Copyright (c) 2014 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

create or replace function rhn_userextgrmap_mod_trig_fun() returns trigger as
$$
begin
        if new.id is null then
            new.id := nextval('rhn_userextgroupmap_seq');
        end if;
        new.modified := current_timestamp;
        return new;
end;
$$ language plpgsql;

create trigger
rhn_userextgrmap_mod_trig
before insert or update on rhnUserExtGroupMapping
for each row
execute procedure rhn_userextgrmap_mod_trig_fun();
 070701000007DA000081B400000000000000000000000167AE111400000198000000000000000000000000000000000000006200000000susemanager-schema/upgrade/spacewalk-schema-2.0-to-spacewalk-schema-2.1/047-rhnPackageKey-f20.sql update rhnPackageKey set provider_id = lookup_package_provider('Fedora')
 where key_id = '2eb161fa246110c1';

insert into rhnPackageKey (id, key_id, key_type_id, provider_id)
    (select sequence_nextval('rhn_pkey_id_seq'), '2eb161fa246110c1', lookup_package_key_type('gpg'), lookup_package_provider('Fedora') from dual
     where not exists (select 1 from rhnPackageKey where key_id = '2eb161fa246110c1'));
070701000007DB000081B400000000000000000000000167AE11140000B781000000000000000000000000000000000000006000000000susemanager-schema/upgrade/spacewalk-schema-2.0-to-spacewalk-schema-2.1/048-rhn_channel.pkb.sql   --
-- Copyright (c) 2008--2014 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--
--
--
--

-- create schema rhn_channel;

--update pg_setting
update pg_settings set setting = 'rhn_channel,' || setting where name = 'search_path';

    create or replace function obtain_read_lock(channel_family_id_in in numeric, org_id_in in numeric)
    returns void as $$
    declare
        read_lock timestamptz;
    begin
        select created into read_lock
          from rhnPrivateChannelFamily
         where channel_family_id = channel_family_id_in and org_id = org_id_in
           for update;
    end$$ language plpgsql;

    -- this "emulates" cursor server_base_subscriptions defined in oracle/rhn_channel.pks
    create or replace function server_base_subscriptions(server_id_in NUMERIC)
    returns boolean as $$
    begin
      return exists(SELECT C.id FROM rhnChannel C, rhnServerChannel SC
		    WHERE C.id = SC.channel_id
		      AND SC.server_id = server_id_in
		      AND C.parent_channel IS NULL);
    end$$ language plpgsql;

    -- this "emulates" cursor server_base_subscriptions defined in oracle/rhn_channel.pks
    create or replace function check_server_subscription(server_id_in NUMERIC, channel_id_in NUMERIC)
    returns boolean as $$
    begin
      return exists(SELECT channel_id FROM rhnServerChannel WHERE server_id = server_id_in AND channel_id = channel_id_in);
    end$$ language plpgsql;


    CREATE OR REPLACE FUNCTION subscribe_server(server_id_in IN NUMERIC, channel_id_in NUMERIC, immediate_in NUMERIC default 1, user_id_in in numeric default null, recalcfamily_in NUMERIC default 1) returns void
    AS $$
    declare
        channel_parent_val      rhnChannel.parent_channel%TYPE;
        parent_subscribed       BOOLEAN;
        server_has_base_chan    BOOLEAN;
        server_already_in_chan  BOOLEAN;
        channel_family_id_val   NUMERIC;
        server_org_id_val       NUMERIC;
        available_subscriptions NUMERIC;
        available_fve_subs      numeric;
        consenting_user         NUMERIC;
        allowed                 numeric;
        is_fve_char             char(1) := 'N';
    BEGIN
        if user_id_in is not null then
            allowed := rhn_channel.user_role_check(channel_id_in, user_id_in, 'subscribe');
        else
            allowed := 1;
        end if;

        if allowed = 0 then
            perform rhn_exception.raise_exception('no_subscribe_permissions');
        end if;


        SELECT parent_channel INTO channel_parent_val FROM rhnChannel WHERE id = channel_id_in;

        IF channel_parent_val IS NOT NULL
        THEN
            -- child channel; if attempting to cross-subscribe a child to the wrong base, silently ignore
            parent_subscribed := rhn_channel.check_server_subscription(server_id_in, channel_parent_val);

            IF NOT parent_subscribed
            THEN
                RETURN;
            END IF;
        ELSE
            -- base channel
            server_has_base_chan := rhn_channel.server_base_subscriptions(server_id_in);

            IF server_has_base_chan
            THEN
                perform rhn_exception.raise_exception('channel_server_one_base');
            END IF;
        END IF;

        server_already_in_chan := rhn_channel.check_server_subscription(server_id_in, channel_id_in);

        IF server_already_in_chan
        THEN
            RETURN;
        END IF;

        channel_family_id_val := rhn_channel.family_for_channel(channel_id_in);
        IF channel_family_id_val IS NULL
        THEN
            perform rhn_exception.raise_exception('channel_subscribe_no_family');
        END IF;

        --
        -- Use the org_id of the server only if the org_id of the channel = NULL.
        -- This is required for subscribing to shared channels.
        --
        SELECT COALESCE(org_id, (SELECT org_id FROM rhnServer WHERE id = server_id_in))
          INTO server_org_id_val
          FROM rhnChannel
         WHERE id = channel_id_in;

        begin
            perform rhn_channel.obtain_read_lock(channel_family_id_val, server_org_id_val);
        exception
            when no_data_found then
                perform rhn_exception.raise_exception('channel_family_no_subscriptions');
        end;

        available_subscriptions := rhn_channel.available_family_subscriptions(channel_family_id_val, server_org_id_val);
        available_fve_subs := rhn_channel.available_fve_family_subs(channel_family_id_val, server_org_id_val);

        IF available_subscriptions IS NULL OR
           available_subscriptions > 0 or
           rhn_channel.can_server_consume_virt_channl(server_id_in, channel_family_id_val) = 1 OR
            (available_fve_subs > 0 AND rhn_channel.can_server_consume_fve(server_id_in) = 1)
        THEN
            if rhn_channel.can_server_consume_virt_channl(server_id_in, channel_family_id_val) = 0 AND available_fve_subs > 0 AND rhn_channel.can_server_consume_fve(server_id_in) = 1 THEN
                is_fve_char := 'Y';
            end if;

            insert into rhnServerHistory (id,server_id,summary,details) (
                select  nextval('rhn_event_id_seq'),
                        server_id_in,
                        'subscribed to channel ' || SUBSTR(c.label, 0, 106),
                        c.label
                from    rhnChannel c
                where   c.id = channel_id_in
            );

            INSERT INTO rhnServerChannel (server_id, channel_id, is_fve) VALUES (server_id_in, channel_id_in, is_fve_char);
			IF recalcfamily_in > 0
			THEN
                perform rhn_channel.update_family_counts(channel_family_id_val, server_org_id_val);
			END IF;
            perform queue_server(server_id_in, immediate_in);

            update rhnServer
               set channels_changed = current_timestamp
             where id = server_id_in;
        ELSE
            perform rhn_exception.raise_exception('channel_family_no_subscriptions');
        END IF;

    END$$ language plpgsql;



    create or replace function can_convert_to_fve(server_id_in IN NUMERIC, channel_family_id_val IN NUMERIC)
    RETURNS NUMERIC
    as $$
    declare
        fve_convertible_entries cursor for
        select 1  from
            rhnServerFveCapable cap
          where cap.server_id = server_id_in
                AND cap.channel_family_id = channel_family_id_val;
    BEGIN
        FOR entry IN fve_convertible_entries LOOP
            return 1;
        END LOOP;
        RETURN 0;
    END$$ language plpgsql;



    -- Converts server channel_family to use a flex entitlement
    create or replace function convert_to_fve(server_id_in IN NUMERIC, channel_family_id_val IN NUMERIC)
    returns void
    as $$
    declare
        available_fve_subs      NUMERIC;
        server_org_id_val       NUMERIC;
    BEGIN

        --
        -- Use the org_id of the server only if the org_id of the channel = NULL.
        -- This is required for subscribing to shared channels.
        --
        SELECT org_id
          INTO server_org_id_val
          FROM rhnServer
         WHERE id = server_id_in;


        perform rhn_channel.obtain_read_lock(channel_family_id_val, server_org_id_val);
        if not found then
                perform rhn_exception.raise_exception('channel_family_no_subscriptions');
        end if;
        IF (rhn_channel.can_convert_to_fve(server_id_in, channel_family_id_val ) = 0)
            THEN
                perform rhn_exception.raise_exception('server_cannot_convert_to_flex');
        END IF;

        available_fve_subs := rhn_channel.available_fve_family_subs(channel_family_id_val, server_org_id_val);

        IF (available_fve_subs > 0)
        THEN

            insert into rhnServerHistory (id,server_id,summary,details) (
                select  nextval('rhn_event_id_seq'),
                        server_id_in,
                        'converted to flex entitlement' || SUBSTR(cf.label, 0, 99),
                        cf.label
                from    rhnChannelFamily cf
                where   cf.id = channel_family_id_val
            );

            UPDATE rhnServerChannel sc set is_fve = 'Y'
                           where sc.server_id = server_id_in and
                                 sc.channel_id in
                                    (select cfm.channel_id from rhnChannelFamilyMembers cfm
                                                where cfm.CHANNEL_FAMILY_ID = channel_family_id_val);

            perform rhn_channel.update_family_counts(channel_family_id_val, server_org_id_val);
        ELSE
            perform rhn_exception.raise_exception('not_enough_flex_entitlements');
        END IF;

    END$$ language plpgsql;

    create or replace function can_server_consume_virt_channl(
        server_id_in in numeric,
        family_id_in in numeric )
    returns numeric
    as $$
    begin
      if exists(
            select 1
            from
                rhnChannelFamilyVirtSubLevel cfvsl,
                rhnSGTypeVirtSubLevel sgtvsl,
                rhnVirtualInstance vi
            where
                vi.virtual_system_id = server_id_in
                and sgtvsl.virt_sub_level_id = cfvsl.virt_sub_level_id
                and cfvsl.channel_family_id = family_id_in
                and exists (
                    select 1
                    from rhnServerEntitlementView sev
                    where vi.host_system_id = sev.server_id
                    and sev.server_group_type_id = sgtvsl.server_group_type_id ))
      then
        return 1;
      else
        return 0;
      end if;
    end$$ language plpgsql;

    create or replace function can_server_consume_fve(server_id_in in numeric) returns numeric
    as $$
    declare
        vi_entries cursor for
            SELECT 1
              FROM rhnVirtualInstance vi
             WHERE vi.virtual_system_id = server_id_in;
        vi_count numeric;

    begin
        FOR vi_entry IN VI_ENTRIES LOOP
            return 1;
        END LOOP;
        RETURN 0;
    end$$ language plpgsql;

    create or replace function guess_server_base(
        server_id_in in numeric
    ) RETURNS numeric as $$
    declare
        server_cursor cursor for
            select s.server_arch_id, s.release, s.org_id
              from rhnServer s
             where s.id = server_id_in;
    -- Cursor that fetches all the possible base channels for a
    -- (server_arch_id, release, org_id) combination
        base_channel_cursor cursor(
                release_in varchar,
                server_arch_id_in numeric,
                org_id_in numeric
        ) for
                select distinct c.*
                from    rhnOrgDistChannelMap                       odcm,
                                rhnServerChannelArchCompat      scac,
                                rhnChannel                                      c
                where   c.parent_channel is null
                        and c.id = odcm.channel_id
                        and c.channel_arch_id = odcm.channel_arch_id
                        and odcm.release = release_in
                        and odcm.for_org_id = org_id_in
                        and scac.server_arch_id = server_arch_id_in
                        and scac.channel_arch_id = c.channel_arch_id;

    begin
        for s in server_cursor loop
            for channel in base_channel_cursor(s.release,
                s.server_arch_id, s.org_id)
            loop
                return channel.id;
            end loop;
        end loop;
        -- Server not found, or no base channel applies to it
        return null;
    end$$ language plpgsql;

    -- Private function
    create or replace function normalize_server_arch(server_arch_in in varchar)
    returns varchar
    as $$
    declare
        suffix VARCHAR(128) := '-redhat-linux';
    begin
        if server_arch_in is NULL then
            return NULL;
        end if;
        if position('-' IN server_arch_in) > 0
        then
            -- Suffix already present
            return server_arch_in;
        end if;
        return server_arch_in || suffix;
    end$$ language plpgsql;

    --
    -- Raises:
    --   server_arch_not_found
    --   no_subscribe_permissions
    create or replace function base_channel_for_release_arch(
        release_in in varchar,
        server_arch_in in varchar,
        org_id_in in numeric default -1,
        user_id_in in numeric default null
    ) returns numeric as $$
    declare
        server_arch varchar(256) := rhn_channel.normalize_server_arch(server_arch_in);
        server_arch_id numeric;
    begin
        -- Look up the server arch
            select id
              into server_arch_id
              from rhnServerArch
             where label = server_arch;
            if not found then
                perform rhn_exception.raise_exception('server_arch_not_found');
            end if;

        return rhn_channel.base_channel_rel_archid(release_in, server_arch_id,
            org_id_in, user_id_in);
    end$$ language plpgsql;

    create or replace function base_channel_rel_archid(
        release_in in varchar,
        server_arch_id_in in numeric,
        org_id_in in numeric default -1,
        user_id_in in numeric default null
    ) returns numeric as $$
    declare
        denied_channel_id numeric := null;
        valid_org_id numeric := org_id_in;
        valid_user_id numeric := user_id_in;
        channel_subscribable numeric;
    -- Cursor that fetches all the possible base channels for a
    -- (server_arch_id, release, org_id) combination
        base_channel_cursor cursor(
                release_in varchar,
                server_arch_id_in numeric,
                org_id_in numeric
        ) for
                select distinct c.*
                from    rhnOrgDistChannelMap                       odcm,
                                rhnServerChannelArchCompat      scac,
                                rhnChannel                                      c
                where   c.parent_channel is null
                        and c.id = odcm.channel_id
                        and c.channel_arch_id = odcm.channel_arch_id
                        and odcm.release = release_in
                        and odcm.for_org_id = org_id_in
                        and scac.server_arch_id = server_arch_id_in
                        and scac.channel_arch_id = c.channel_arch_id;

    begin
        if org_id_in = -1 and user_id_in is not null then
            -- Get the org id from the user id

                select org_id
                  into valid_org_id
                  from web_contact
                 where id = user_id_in;

                if not found then
                    -- User doesn't exist
                    -- XXX Only list public stuff for now
                    valid_user_id := null;
                    valid_org_id := -1;
                end if;
        end if;

        for c in base_channel_cursor(release_in, server_arch_id_in, valid_org_id)
        loop
            -- This row is a possible match
            if valid_user_id is null then
                -- User ID not specified, so no user to channel permissions to
                -- check
                return c.id;
            end if;

            -- Check user to channel permissions
            select rhn_channel.loose_user_role_check(c.id, user_id_in, 'subscribe')
              into channel_subscribable;

            if channel_subscribable = 1 then
                return c.id;
            end if;

            -- Base channel exists, but is not subscribable; keep trying
            denied_channel_id := c.id;
        end loop;

        if denied_channel_id is not null then
            perform rhn_exception.raise_exception('no_subscribe_permissions');
        end if;
        -- No base channel applies
        return NULL;
    end$$ language plpgsql;

    CREATE OR REPLACE FUNCTION clear_subscriptions(server_id_in IN NUMERIC, deleting_server IN NUMERIC default 0,
                                update_family_countsYN IN NUMERIC default 1 ) returns void
    AS $$
    declare
        server_channels cursor(server_id_in numeric) for
                select  s.org_id, sc.channel_id, cfm.channel_family_id
                from    rhnServer s,
                        rhnServerChannel sc,
                        rhnChannelFamilyMembers cfm
                where   s.id = server_id_in
                        and s.id = sc.server_id
                        and sc.channel_id = cfm.channel_id
                order by cfm.channel_family_id;
        last_channel_family_id rhnChannelFamilyMembers.channel_family_id%type := -1;
        last_channel_org_id    rhnServer.org_id%type := -1;
    BEGIN
        for channel in server_channels(server_id_in)
        loop
                perform rhn_channel.unsubscribe_server(server_id_in, channel.channel_id, 1, 1, deleting_server, 0);
                if update_family_countsYN > 0
                    and channel.channel_family_id != last_channel_family_id then
                    -- update family counts only once
                    -- after all channels with same family has been fetched
                    if last_channel_family_id != -1 then
                        perform rhn_channel.update_family_counts(channel.channel_family_id, channel.org_id);
                    end if;
                    last_channel_family_id := channel.channel_family_id;
                    last_channel_org_id    := channel.org_id;
                end if;
        end loop;
        if update_family_countsYN > 0 and last_channel_family_id != -1 then
            -- update the last family fetched
            perform rhn_channel.update_family_counts(last_channel_family_id, last_channel_org_id);
        end if;
    END$$ language plpgsql;

    CREATE OR REPLACE FUNCTION unsubscribe_server(server_id_in IN NUMERIC, channel_id_in NUMERIC, immediate_in NUMERIC default 1, unsubscribe_children_in numeric default 0,
                                 deleting_server in numeric default 0,
                                 update_family_countsYN in numeric default 1) returns void
    AS $$
    declare
        channel_family_id_val   NUMERIC;
        server_org_id_val       NUMERIC;
        available_subscriptions NUMERIC;
        server_already_in_chan  BOOLEAN;
        channel_family_is_proxy cursor(channel_family_id_in numeric) for
                select  1
                from    rhnChannelFamily
                where   id = channel_family_id_in
                    and label = 'rhn-proxy';
        channel_family_is_satellite cursor(channel_family_id_in numeric) for
                select  1
                from    rhnChannelFamily
                where   id = channel_family_id_in
                    and label = 'rhn-satellite';
        child record;
    BEGIN
        -- In PostgreSQL recursion with opened cursors is not allowed so we use
        -- FOR IN SELECT form which is ok.
        FOR child IN select  c.id
                from    rhnChannel                      c,
                                rhnServerChannel        sc
                where   1=1
                        and c.parent_channel = channel_id_in
                        and c.id = sc.channel_id
                        and sc.server_id = server_id_in
        LOOP
            if unsubscribe_children_in = 1 then
                perform rhn_channel.unsubscribe_server(server_id_in,
                                                       child.id,
                                                       immediate_in,
                                                       unsubscribe_children_in,
                                                       deleting_server,
                                                       update_family_countsYN);
            else
                perform rhn_exception.raise_exception('channel_unsubscribe_child_exists');
            end if;
        END LOOP;

        server_already_in_chan := rhn_channel.check_server_subscription(server_id_in, channel_id_in);

        IF NOT server_already_in_chan
        THEN
            RETURN;
        END IF;

   if deleting_server = 0 then
      insert into rhnServerHistory (id,server_id,summary,details) (
          select  nextval('rhn_event_id_seq'),
                server_id_in,
             'unsubscribed from channel ' || SUBSTR(c.label, 0, 106),
             c.label
          from    rhnChannel c
          where   c.id = channel_id_in
      );
   end if;

   DELETE FROM rhnServerChannel WHERE server_id = server_id_in AND channel_id = channel_id_in;

   if deleting_server = 0 then
        perform queue_server(server_id_in, immediate_in);

        update rhnServer
           set channels_changed = current_timestamp
         where id = server_id_in;
   end if;

        channel_family_id_val := rhn_channel.family_for_channel(channel_id_in);
        IF channel_family_id_val IS NULL
        THEN
            perform rhn_exception.raise_exception('channel_unsubscribe_no_family');
        END IF;

        for ignore in channel_family_is_satellite(channel_family_id_val) loop
                delete from rhnSatelliteInfo where server_id = server_id_in;
        end loop;

        for ignore in channel_family_is_proxy(channel_family_id_val) loop
                delete from rhnProxyInfo where server_id = server_id_in;
        end loop;
        SELECT org_id INTO server_org_id_val
          FROM rhnServer
         WHERE id = server_id_in;

        if update_family_countsYN = 1 then
           perform rhn_channel.update_family_counts(channel_family_id_val, server_org_id_val);
        end if;
    END$$ language plpgsql;

    CREATE OR REPLACE FUNCTION family_for_channel(channel_id_in IN NUMERIC)
    RETURNS NUMERIC
    AS $$
    declare
        channel_family_id_val NUMERIC;
    BEGIN
        SELECT channel_family_id INTO channel_family_id_val
          FROM rhnChannelFamilyMembers
         WHERE channel_id = channel_id_in;

        IF NOT FOUND THEN
          RETURN NULL;
        END IF;

        RETURN channel_family_id_val;
    END$$ language plpgsql;

    CREATE OR REPLACE FUNCTION available_family_subscriptions(channel_family_id_in IN NUMERIC, org_id_in IN NUMERIC)
    RETURNS NUMERIC
    AS $$
    declare
        cfp record;
        current_members_val NUMERIC;
        max_members_val     NUMERIC;
        found               NUMERIC;
    BEGIN
        for cfp in SELECT * FROM rhnOrgChannelFamilyPermissions
	    WHERE channel_family_id = channel_family_id_in
	      AND org_id = org_id_in
        LOOP
            found := 1;
            current_members_val := cfp.current_members;
            max_members_val := cfp.max_members;
        END LOOP;

        -- not found: either the channel fam doesn't have an entry in cfp, or the org doesn't have access to it.
        -- either way, there are no available subscriptions

        IF found IS NULL
        THEN
            RETURN 0;
        END IF;

        -- null max members?  in that case, pass it on; NULL means infinite
        IF max_members_val IS NULL
        THEN
            RETURN NULL;
        END IF;

        -- otherwise, return the delta
        RETURN max_members_val - current_members_val;
    END$$ language plpgsql;

    CREATE OR REPLACE FUNCTION available_fve_family_subs(channel_family_id_in IN NUMERIC, org_id_in IN NUMERIC)
    RETURNS NUMERIC
    AS $$
    declare
        cfp record;
        fve_current_members_val NUMERIC;
        fve_max_members_val     NUMERIC;
        found               NUMERIC;
    BEGIN
        for cfp in SELECT * FROM rhnOrgChannelFamilyPermissions
	    WHERE channel_family_id = channel_family_id_in
	      AND org_id = org_id_in
        LOOP
            found := 1;
            fve_current_members_val := cfp.fve_current_members;
            fve_max_members_val := cfp.fve_max_members;
        END LOOP;

        -- not found: either the channel fam doesn't have an entry in cfp, or the org doesn't have access to it.
        -- either way, there are no available subscriptions

        IF found IS NULL
        THEN
            RETURN 0;
        END IF;

        -- null max members?  in that case, pass it on; NULL means infinite
        IF fve_max_members_val IS NULL
        THEN
            RETURN NULL;
        END IF;

        -- otherwise, return the delta
        RETURN fve_max_members_val - fve_current_members_val;
    END$$ language plpgsql;

    -- *******************************************************************
    -- FUNCTION: channel_family_current_members
    -- Calculates and returns the actual count of systems consuming
    --   physical channel subscriptions.
    -- Called by: update_family_counts
    --            rhn_entitlements.repoll_virt_guest_entitlements
    -- *******************************************************************
    create or replace function channel_family_current_members(channel_family_id_in IN NUMERIC,
                                            org_id_in IN NUMERIC)
    returns numeric
    as $$
    declare
        current_members_count numeric := 0;
    begin
        select  count(distinct server_id)
        into    current_members_count
          from  rhnChannelFamilyServerPhysical cfsp
         where  cfsp.channel_family_id = channel_family_id_in
           and  cfsp.customer_id = org_id_in;
        return current_members_count;
    end$$ language plpgsql;


    create or replace function cfam_curr_fve_members(
        channel_family_id_in IN NUMERIC,
        org_id_in IN NUMERIC)
    returns numeric
    as $$
    declare
        current_members_count numeric := 0;

    begin
        select count(sc.server_id)
          into current_members_count
          from rhnServerChannel sc,
               rhnChannelFamilyMembers cfm,
               rhnServer s
         where s.org_id = org_id_in
           and s.id = sc.server_id
           and cfm.channel_family_id = channel_family_id_in
           and cfm.channel_id = sc.channel_id
           and exists (
                select 1
                  from rhnChannelFamilyServerFve cfsp
                 where cfsp.CHANNEL_FAMILY_ID = channel_family_id_in
                   and cfsp.server_id = s.id
                );

        return current_members_count;
    end$$ language plpgsql;
    CREATE OR REPLACE FUNCTION update_family_counts(channel_family_id_in IN NUMERIC,
                                   org_id_in IN NUMERIC) returns void
    AS $$
    BEGIN
        update rhnPrivateChannelFamily
           set current_members = rhn_channel.channel_family_current_members(channel_family_id_in, org_id_in),
               fve_current_members = rhn_channel.cfam_curr_fve_members(channel_family_id_in,org_id_in)
         where org_id = org_id_in
           and channel_family_id = channel_family_id_in;
    END$$ language plpgsql;

    create or replace function update_group_family_counts(group_label_in IN VARCHAR,
                                   org_id_in IN NUMERIC)
    returns void
    as $$
    declare
        i record;
    BEGIN
        FOR i IN (
                SELECT DISTINCT CFM.channel_family_id, SG.org_id
                 FROM rhnChannelFamilyMembers CFM
                 JOIN rhnServerChannel SC
                   ON SC.channel_id = CFM.channel_id
                 JOIN rhnServerGroupMembers SGM
                   ON SC.server_id = SGM.server_id
                 JOIN rhnServerGroup SG
                   ON SGM.server_group_id = SG.id
                 JOIN rhnServerGroupType SGT
                   ON SG.group_type = SGT.id
                WHERE SGT.label = group_label_in
                  AND SG.org_id = org_id_in
                  AND SGT.is_base = 'Y'
        ) LOOP
            perform rhn_channel.update_family_counts(i.channel_family_id, i.org_id);
        END LOOP;
    END$$ language plpgsql;

    CREATE OR REPLACE FUNCTION available_chan_subscriptions(channel_id_in IN NUMERIC,
                                          org_id_in IN NUMERIC)
    RETURNS NUMERIC
    AS $$
    declare
            channel_family_id_val NUMERIC;
    BEGIN
        SELECT channel_family_id INTO STRICT channel_family_id_val
            FROM rhnChannelFamilyMembers
            WHERE channel_id = channel_id_in;

            RETURN rhn_channel.available_family_subscriptions(
                           channel_family_id_val, org_id_in);
    END$$ language plpgsql;

    CREATE OR REPLACE FUNCTION available_fve_chan_subs(channel_id_in IN NUMERIC,
                                          org_id_in IN NUMERIC)
    RETURNS NUMERIC
    AS $$
    declare
            channel_family_id_val NUMERIC;
    BEGIN
        SELECT channel_family_id INTO STRICT channel_family_id_val
            FROM rhnChannelFamilyMembers
            WHERE channel_id = channel_id_in;

            RETURN rhn_channel.available_fve_family_subs(
                           channel_family_id_val, org_id_in);
    END$$ language plpgsql;

    create or replace function unsubscribe_server_from_family(server_id_in in numeric,
                                             channel_family_id_in in numeric)
    returns void
    as $$
    begin
        delete
        from    rhnServerChannel rsc
        where   rsc.server_id = server_id_in
            and channel_id in (
                select  rcfm.channel_id
                from    rhnChannelFamilyMembers rcfm
                where   rcfm.channel_family_id = channel_family_id_in);
    end$$ language plpgsql;

    create or replace function get_org_id(channel_id_in in numeric)
    returns numeric
    as $$
    declare
        org_id_out numeric;
    begin
        select org_id into strict org_id_out
            from rhnChannel
            where id = channel_id_in;

            return org_id_out;
    end$$ language plpgsql;

    create or replace function get_cfam_org_access(cfam_id_in in numeric, org_id_in in numeric)
    returns numeric
    as $$
    begin
      if exists(
                        select  1
                        from    rhnOrgChannelFamilyPermissions cfp
                        where   cfp.org_id = org_id_in
      ) then
                return 1;
      else
                return 0;
      end if;
    end$$ language plpgsql;

    create or replace function get_org_access(channel_id_in in numeric, org_id_in in numeric)
    returns integer
    as $$
    begin
        -- the idea: if we get past this query,
        -- the org has access to the channel, else not
        if exists(
        select 1
          from rhnChannelFamilyMembers CFM,
               rhnOrgChannelFamilyPermissions CFP
         where cfp.org_id = org_id_in
           and CFM.channel_family_id = CFP.channel_family_id
           and CFM.channel_id = channel_id_in
           and (CFP.max_members > 0 or CFP.max_members is null or CFP.fve_max_members > 0 or CFP.fve_max_members is null or CFP.org_id = 1) )
        then
          return 1;
        else
          return 0;
        end if;
    end$$ language plpgsql;

    -- check if a user has a given role, or if such a role is inferrable
    -- returns NULL if OK, error message otherwise
    create or replace function user_role_check_debug(channel_id_in in numeric,
                                   user_id_in in numeric,
                                   role_in in varchar)
    returns varchar
    as $$
    declare
        org_id numeric;
    begin
        org_id := rhn_user.get_org_id(user_id_in);

        -- channel might be shared
        if role_in = 'subscribe' and
           rhn_channel.shared_user_role_check(channel_id_in, user_id_in, role_in) = 1 then
            return NULL;
        end if;

        if role_in = 'manage' and
           COALESCE(rhn_channel.get_org_id(channel_id_in), -1) <> org_id then
               return 'channel_not_owned';
        end if;

        if role_in = 'subscribe' and
           rhn_channel.get_org_access(channel_id_in, org_id) = 0 then
                return 'channel_not_available';
        end if;

        -- channel admins have all roles
        if rhn_user.check_role_implied(user_id_in, 'channel_admin') = 1 then
            return NULL;
        end if;

        -- the subscribe permission is inferred
        -- UNLESS the not_globally_subscribable flag is set
        if role_in = 'subscribe'
        then
            if rhn_channel.org_channel_setting(channel_id_in,
                       org_id,
                       'not_globally_subscribable') = 0 then
                return NULL;
            end if;
        end if;

        -- all other roles (manage right now) are explicitly granted
        if rhn_channel.direct_user_role_check(channel_id_in,
                                              user_id_in, role_in) = 1 then
            return NULL;
        end if;
        return 'direct_permission';
    end$$ language plpgsql;

    -- same as above, but with 1/0 output; useful in views, etc
    create or replace function user_role_check(channel_id_in in numeric, user_id_in in numeric, role_in in varchar)
    returns numeric
    as $$
    begin
        if rhn_channel.user_role_check_debug(channel_id_in,
                                             user_id_in, role_in) is NULL then
            return 1;
        else
            return 0;
        end if;
    end$$ language plpgsql;

    --
    -- For multiorg phase II, this function simply checks to see if the user's
    -- has a trust relationship that includes this channel by id.
    --
    create or replace function shared_user_role_check(channel_id in numeric, user_id in numeric, role in varchar)
    returns numeric
    as $$
    declare
      n numeric;
      oid numeric;
    begin
      oid := rhn_user.get_org_id(user_id);
      select 1 into n
      from rhnSharedChannelView s
      where s.id = channel_id and s.org_trust_id = oid;

      if not found then
        return 0;
      end if;

      return 1;
    end$$ language plpgsql;

    -- same as above, but returns 1 if user_id_in is null
    -- This is useful in queries where user_id is not specified
    create or replace function loose_user_role_check(channel_id_in in numeric, user_id_in in numeric, role_in in varchar)
    returns numeric
    as $$
    begin
        if user_id_in is null then
            return 1;
        end if;
        return rhn_channel.user_role_check(channel_id_in, user_id_in, role_in);
    end$$ language plpgsql;

    -- directly checks the table, no inferred permissions
    create or replace function direct_user_role_check(channel_id_in in numeric, user_id_in in numeric, role_in in varchar)
    returns numeric
    as $$
    declare
        throwaway numeric;
    begin
        -- the idea: if we get past this query, the user has the role, else no
        select 1 into throwaway
          from rhnChannelPermissionRole CPR,
               rhnChannelPermission CP
         where CP.user_id = user_id_in
           and CP.channel_id = channel_id_in
           and CPR.label = role_in
           and CP.role_id = CPR.id;

      if not found then
        return 0;
      end if;

      return 1;
    end$$ language plpgsql;

    -- check if an org has a certain setting
    create or replace function org_channel_setting(channel_id_in in numeric, org_id_in in numeric, setting_in in varchar)
    returns numeric
    as $$
    declare
        throwaway numeric;
    begin
        -- the idea: if we get past this query, the org has the setting
        select 1 into throwaway
          from rhnOrgChannelSettingsType OCST,
               rhnOrgChannelSettings OCS
         where OCS.org_id = org_id_in
           and OCS.channel_id = channel_id_in
           and OCST.label = setting_in
           and OCS.setting_id = OCST.id;

      if not found then
        return 0;
      end if;

      return 1;
    end$$ language plpgsql;

    CREATE OR REPLACE FUNCTION channel_priority(channel_id_in IN numeric)
    RETURNS numeric
    AS $$
    declare
         channel_name varchar(256);
         priority numeric;
         end_of_life_val timestamptz;
         org_id_val numeric;
    BEGIN

        select name, end_of_life, org_id
        into channel_name, end_of_life_val, org_id_val
        from rhnChannel
        where id = channel_id_in;

        if end_of_life_val is not null then
          return -400;
        end if;

        if channel_name like 'Red Hat Enterprise Linux%' or channel_name like 'RHEL%' then
          priority := 1000;
          if channel_name not like '%Beta%' then
            priority := priority + 1000;
          end if;

          priority := priority +
            case
              when channel_name like '%v. 5%' then 600
              when channel_name like '%v. 4%' then 500
              when channel_name like '%v. 3%' then 400
              when channel_name like '%v. 2%' then 300
              when channel_name like '%v. 1%' then 200
              else 0
            end;

          priority := priority +
            case
              when channel_name like 'Red Hat Enterprise Linux (v. 5%' then 60
              when (channel_name like '%AS%' and channel_name not like '%Extras%') then 50
              when (channel_name like '%ES%' and channel_name not like '%Extras%') then 40
              when (channel_name like '%WS%' and channel_name not like '%Extras%') then 30
              when (channel_name like '%Desktop%' and channel_name not like '%Extras%') then 20
              when channel_name like '%Extras%' then 10
              else 0
            end;

          priority := priority +
            case
              when channel_name like '%)' then 5
              else 0
            end;

          priority := priority +
            case
              when channel_name like '%32-bit x86%' then 4
              when channel_name like '%64-bit Intel Itanium%' then 3
              when channel_name like '%64-bit AMD64/Intel EM64T%' then 2
              else 0
            end;
        elsif channel_name like 'Red Hat Desktop%' then
            priority := 900;

            if channel_name not like '%Beta%' then
               priority := priority + 50;
            end if;

          priority := priority +
            case
              when channel_name like '%v. 4%' then 40
              when channel_name like '%v. 3%' then 30
              when channel_name like '%v. 2%' then 20
              when channel_name like '%v. 1%' then 10
              else 0
            end;

          priority := priority +
            case
              when channel_name like '%32-bit x86%' then 4
              when channel_name like '%64-bit Intel Itanium%' then 3
              when channel_name like '%64-bit AMD64/Intel EM64T%' then 2
              else 0
            end;

        elsif org_id_val is not null then
          priority := 600;
        else
          priority := 500;
        end if;

      return -priority;

    end$$ language plpgsql;

    -- right now this only does the accounting changes; the cascade
    -- actually does the rhnServerChannel delete.
    create or replace function delete_server_channels(server_id_in in numeric) returns void
    as $$
    begin
        update  rhnPrivateChannelFamily
        set     current_members = current_members -1
        where   org_id in (
                        select  org_id
                        from    rhnServer
                        where   id = server_id_in
                )
                and channel_family_id in (
                        select  rcfm.channel_family_id
                        from    rhnChannelFamilyMembers rcfm,
                                rhnServerChannel rsc
                        where   rsc.server_id = server_id_in
                                and rsc.channel_id = rcfm.channel_id
                and not exists (
                    select 1
                    from
                        rhnChannelFamilyVirtSubLevel cfvsl,
                        rhnSGTypeVirtSubLevel sgtvsl,
                        rhnServerEntitlementView sev,
                        rhnVirtualInstance vi
                    where
                        -- system is a virtual instance
                        vi.virtual_system_id = server_id_in
                        and vi.host_system_id = sev.server_id
                        -- system's host has a virt ent
                        and sev.label in ('virtualization_host',
                                          'virtualization_host_platform')
                        and sev.server_group_type_id =
                            sgtvsl.server_group_type_id
                        -- the host's virt ent grants a cf virt sub level
                        and sgtvsl.virt_sub_level_id = cfvsl.virt_sub_level_id
                        -- the cf is in that virt sub level
                        and cfvsl.channel_family_id = rcfm.channel_family_id
                    )
                );
    end$$ language plpgsql;

    -- this could certainly be optimized to do updates if needs be
    create or replace function refresh_newest_package(channel_id_in in numeric,
                                      caller_in in varchar default '(unknown)',
                                      package_name_id_in in numeric default null)
    returns void
    as $$
    -- procedure refreshes rows for name_id = package_name_id_in or
    -- all rows if package_name_id_in is null
    begin
        delete from rhnChannelNewestPackage
              where channel_id = channel_id_in
                and (package_name_id_in is null
                     or name_id = package_name_id_in);
        insert into rhnChannelNewestPackage
                (channel_id, name_id, evr_id, package_id, package_arch_id)
                (select channel_id,
                        name_id, evr_id,
                        package_id, package_arch_id
                   from rhnChannelNewestPackageView
                  where channel_id = channel_id_in
                    and (package_name_id_in is null
                         or name_id = package_name_id_in)
                );
        insert into rhnChannelNewestPackageAudit (channel_id, caller)
             values (channel_id_in, caller_in);
        update rhnChannel
           set last_modified = greatest(current_timestamp,
                                        last_modified + interval '1 second')
         where id = channel_id_in;
    end$$ language plpgsql;

   create or replace function update_channel ( channel_id_in in numeric, invalidate_ss in numeric default 0,
                              date_to_use in timestamptz default current_timestamp ) returns void
   as $$
   declare
   channel_last_modified timestamptz;
   last_modified_value timestamptz;

   snapshots cursor for
   select  snapshot_id id
   from    rhnSnapshotChannel
   where   channel_id = channel_id_in;

   begin

      select last_modified
      into channel_last_modified
      from rhnChannel
      where id = channel_id_in;

      last_modified_value := date_to_use;

      if last_modified_value <= channel_last_modified then
          last_modified_value := last_modified_value + interval '1 second';
      end if;

      update rhnChannel set last_modified = last_modified_value
      where id = channel_id_in;

      if invalidate_ss = 1 then
        for snapshot in snapshots loop
            update rhnSnapshot
            set invalid = lookup_snapshot_invalid_reason('channel_modified')
            where id = snapshot.id;
        end loop;
      end if;

   end$$ language plpgsql;

   create or replace function update_channels_by_package ( package_id_in in numeric, date_to_use in timestamptz default current_timestamp ) returns void
   as $$
   declare
   channels cursor for
   select channel_id
   from rhnChannelPackage
   where package_id = package_id_in
   order by channel_id;

   begin
      for channel in channels loop
         -- we want to invalidate the snapshot assocated with the channel when we
         -- do this b/c we know we've added or removed or packages
         perform rhn_channel.update_channel ( channel.channel_id, 1, date_to_use );
      end loop;
   end$$ language plpgsql;


   create or replace function update_channels_by_errata ( errata_id_in numeric, date_to_use in timestamptz default current_timestamp ) returns void
   as $$
   declare
   channels cursor for
   select channel_id
   from rhnChannelErrata
   where errata_id = errata_id_in
   order by channel_id;

   begin
      for channel in channels loop
         -- we won't invalidate snapshots, b/c just changing the errata associated with
         -- a channel shouldn't invalidate snapshots
         perform rhn_channel.update_channel ( channel.channel_id, 0, date_to_use );
      end loop;
   end$$ language plpgsql;

   create or replace function update_needed_cache(channel_id_in in numeric) returns void
   as $$
   declare
   server record;
   begin
      -- we intentionaly do a loop here instead of one huge select
      -- b/c we want to break update into smaller transaction to unblock other sessions
      -- querying rhnServerNeededCache
      for server in (
                select sc.server_id as id
                  from rhnServerChannel sc
                 where sc.channel_id = channel_id_in
                 order by id asc
      ) loop
         perform rhn_server.update_needed_cache(server.id);
      end loop;
   end$$ language plpgsql;

    create or replace function set_comps(channel_id_in in numeric, path_in in varchar, timestamp_in in varchar) returns void
    as $$
    declare
    row record;
    begin
        for row in (
            select relative_filename, last_modified
            from rhnChannelComps
            where channel_id = channel_id_in
            ) loop
            if row.relative_filename = path_in
                and row.last_modified = to_timestamp(timestamp_in, 'YYYYMMDDHH24MISS') then
                return;
            end if;
        end loop;
        delete from rhnChannelComps
        where channel_id = channel_id_in;
        insert into rhnChannelComps (id, channel_id, relative_filename, last_modified, created, modified)
        values (sequence_nextval('rhn_channelcomps_id_seq'), channel_id_in, path_in, to_timestamp(timestamp_in, 'YYYYMMDDHH24MISS'), current_timestamp, current_timestamp);
    end$$ language plpgsql;

-- restore the original setting
update pg_settings set setting = overlay( setting placing '' from 1 for (length('rhn_channel')+1) ) where name = 'search_path';
   070701000007DC000081B400000000000000000000000167AE111400000162000000000000000000000000000000000000006100000000susemanager-schema/upgrade/spacewalk-schema-2.0-to-spacewalk-schema-2.1/050-rhnTimezone-data.sql  insert into rhnTimezone (id, olson_name, display_name) (
    select sequence_nextval('rhn_timezone_id_seq'),
           'Asia/Riyadh',
           'Saudi Arabia'
      from dual
     where not exists (
           select 1
             from rhnTimezone
            where olson_name = 'Asia/Riyadh'
              and display_name = 'Saudi Arabia'
     )
);
  070701000007DD000081B400000000000000000000000167AE11140000051F000000000000000000000000000000000000006A00000000susemanager-schema/upgrade/spacewalk-schema-2.0-to-spacewalk-schema-2.1/051-rhnServerOutdatedPackages.sql --
-- Copyright (c) 2008--2014 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--

DROP VIEW rhnServerOutdatedPackages;

CREATE OR REPLACE VIEW
rhnServerOutdatedPackages
(
    server_id,
    package_name_id,
    package_evr_id,    
    package_arch_id,
    package_nvre,
    errata_id,
    errata_advisory
)
AS
SELECT DISTINCT SNPC.server_id,
       P.name_id,
       P.evr_id,
       P.package_arch_id,
       PN.name || '-' || evr_t_as_vre_simple( PE.evr ),
       E.id,
       E.advisory
  FROM rhnPackageName PN,
       rhnPackageEVR PE,
       rhnPackage P,
       rhnServerNeededPackageCache SNPC
         left outer join
        rhnErrata E
          on SNPC.errata_id = E.id
 WHERE SNPC.package_id = P.id
   AND P.name_id = PN.id
   AND P.evr_id = PE.id;

 070701000007DE000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000004800000000susemanager-schema/upgrade/spacewalk-schema-2.1-to-spacewalk-schema-2.2   070701000007DF000081B400000000000000000000000167AE111400000132000000000000000000000000000000000000006400000000susemanager-schema/upgrade/spacewalk-schema-2.1-to-spacewalk-schema-2.2/001-rhnUserGroupMembers.sql   ALTER TABLE rhnUserGroupMembers ADD temporary CHAR(1) DEFAULT ('N') NOT NULL
    CONSTRAINT rhn_ugmembers_t_ck
        CHECK (temporary in ('Y', 'N'));

CREATE UNIQUE INDEX rhn_ugmembers_uid_ugid_temp_uq
    ON rhnUserGroupMembers (user_id, user_group_id, temporary);
DROP INDEX rhn_ugmembers_uid_ugid_uq;
  070701000007E0000081B400000000000000000000000167AE1114000000DF000000000000000000000000000000000000006600000000susemanager-schema/upgrade/spacewalk-schema-2.1-to-spacewalk-schema-2.2/002-rhnConfiguration-data.sql INSERT INTO rhnConfiguration (key, description, default_value) VALUES ('extauth_keep_temproles', 'Keep temporary user roles granted due to the external authentication setup for subsequent logins using password.', 'false');
 070701000007E1000081B400000000000000000000000167AE111400000041000000000000000000000000000000000000006100000000susemanager-schema/upgrade/spacewalk-schema-2.1-to-spacewalk-schema-2.2/003-rhnTaskoSchedule.sql  
ALTER TABLE rhnTaskoSchedule ALTER cron_expr TYPE VARCHAR(120);
   070701000007E2000081B400000000000000000000000167AE1114000014B7000000000000000000000000000000000000006900000000susemanager-schema/upgrade/spacewalk-schema-2.1-to-spacewalk-schema-2.2/004-web_contact-old_password.sql  
-- ## views

create or replace view
rhnUserReceiveNotifications
as
select
	0::numeric as org_id,
	0::numeric as user_id,
	0::numeric as server_id
from dual;

drop view rhnWebContactEnabled;
drop view rhnWebContactDisabled;

create or replace view
rhnWebContactDisabled
as
select
   wcon.id,
   wcon.org_id,
   wcon.login,
   wcon.login_uc,
   wcon.password,
   wcon.oracle_contact_id,
   wcon.created,
   wcon.modified,
   wcon.ignore_flag
from
   rhnWebContactChangeLog   wccl,
   rhnWebContactChangeState wccs,
   web_contact              wcon
where wccl.change_state_id = wccs.id
   and wccs.label = 'disabled'
   and wccl.web_contact_id = wcon.id
   and wccl.date_completed =
              (select max(wccl_exists.date_completed)
                 from rhnWebContactChangeLog   wccl_exists
                where wccl.web_contact_id = wccl_exists.web_contact_id);

create or replace view
rhnWebContactEnabled
as
select
   wcon.id,
   wcon.org_id,
   wcon.login,
   wcon.login_uc,
   wcon.password,
   wcon.oracle_contact_id,
   wcon.created,
   wcon.modified,
   wcon.ignore_flag
from
   web_contact wcon
where not exists (
     select 1 from rhnWebContactDisabled
     where wcon.id = rhnWebContactDisabled.id
   );

create or replace view rhnUserReceiveNotifications
as
    select wc.org_id, usp.user_id, usp.server_id
    from rhnUserServerPerms usp
    left join rhnWebContactDisabled wcd
        on usp.user_id = wcd.id
    join web_contact wc
        on usp.user_id = wc.id
    join rhnUserInfo ui
        on usp.user_id = ui.user_id
        and ui.email_notify = 1
    join web_user_personal_info upi
        on usp.user_id = upi.web_user_id
        and upi.email is not null
    left join rhnUserServerPrefs uspr
        on uspr.server_id = usp.server_id
        and usp.user_id = uspr.user_id
        and uspr.name = 'receive_notifications'
        and value='0'
    where uspr.server_id is null
    and wcd.id is null;

-- ## create_new_user

create or replace function
create_new_user
(
    org_id_in           in numeric,
    login_in            in varchar,
    password_in         in varchar,
    oracle_contact_id_in in varchar,
    prefix_in           in varchar,
    first_names_in      in varchar,
    last_name_in        in varchar,
    genqual_in          in varchar,
    parent_company_in   in varchar,
    company_in          in varchar,
    title_in            in varchar,
    phone_in            in varchar,
    fax_in              in varchar,
    email_in            in varchar,
    pin_in              in numeric,
    first_names_ol_in   in varchar,
    last_name_ol_in     in varchar,
    address1_in         in varchar,
    address2_in         in varchar,
    address3_in         in varchar,
    city_in             in varchar,
    state_in            in varchar,
    zip_in              in varchar,
    country_in          in varchar,
    alt_first_names_in  in varchar,
    alt_last_name_in    in varchar,
    contact_call_in     varchar,
    contact_mail_in     varchar,
    contact_email_in    varchar,
    contact_fax_in      varchar
)
returns numeric
AS
$$
declare
    user_id_tmp             numeric;


    -- Would be using the below variables instead of the last four parameters
    contact_call_in_tmp     varchar := 'N';
    contact_mail_in_tmp     varchar := 'N';
    contact_email_in_tmp    varchar := 'N';
    contact_fax_in_tmp      varchar := 'N';
begin
    select nextval('web_contact_id_seq') into user_id_tmp;

    insert into web_contact
        (id, org_id, login, login_uc, password, oracle_contact_id)
    values
        (user_id_tmp, org_id_in, login_in, upper(login_in), password_in, oracle_contact_id_in::numeric);

    insert into web_user_contact_permission
        (web_user_id, call, mail, email, fax)
    values
        (user_id_tmp, contact_call_in_tmp, contact_mail_in_tmp, contact_email_in_tmp, contact_fax_in_tmp);

    insert into web_user_personal_info
        (web_user_id, prefix, first_names, last_name, genqual,
        parent_company, company, title, phone, fax, email, pin,
        first_names_ol, last_name_ol)
    values
        (user_id_tmp, prefix_in, first_names_in, last_name_in, genqual_in,
        parent_company_in, company_in, title_in, phone_in, fax_in, email_in, pin_in :: numeric,
        first_names_ol_in, last_name_ol_in);

    if address1_in != '.' then
        insert into web_user_site_info
            (id, web_user_id, email,
            address1, address2, address3,
            city, state, zip, country, phone, fax, type,
            alt_first_names, alt_last_name)
        values
            (nextval('web_user_site_info_id_seq'), user_id_tmp, email_in,
            address1_in, address2_in, address3_in,
            city_in, state_in, zip_in, country_in, phone_in, fax_in, 'M',
            alt_first_names_in, alt_last_name_in);
    end if;

    insert into rhnUserInfo
        (user_id)
    values
        (user_id_tmp);

    return user_id_tmp;
end;
$$
language plpgsql;

-- ## web_contact triggers

create or replace function web_contact_upd_trig_fun() returns trigger
as
$$
begin
        new.modified := current_timestamp;
        new.login_uc := UPPER(new.login);

        return new;
end;
$$
language plpgsql;

-- ## drop web_contact.old_password

alter table web_contact drop column old_password;
 070701000007E3000081B400000000000000000000000167AE111400001516000000000000000000000000000000000000006400000000susemanager-schema/upgrade/spacewalk-schema-2.1-to-spacewalk-schema-2.2/005-support-for-aarch64.sql   insert into rhnChannelArch (id, label, name, arch_type_id) select
sequence_nextval('rhn_channel_arch_id_seq'), 'channel-aarch64', 'AArch64', lookup_arch_type('rpm') from dual
where not exists (select 1 from rhnChannelArch where label = 'channel-aarch64');

insert into rhnPackageArch (id, label, name, arch_type_id) select
sequence_nextval('rhn_package_arch_id_seq'), 'aarch64', 'AArch64', lookup_arch_type('rpm') from dual
where not exists (select 1 from rhnPackageArch where label ='aarch64');

insert into rhnChannelPackageArchCompat (channel_arch_id, package_arch_id) select
LOOKUP_CHANNEL_ARCH('channel-aarch64'), LOOKUP_PACKAGE_ARCH('aarch64') from dual
where not exists (select 1 from rhnChannelPackageArchCompat where channel_arch_id = LOOKUP_CHANNEL_ARCH('channel-aarch64') and package_arch_id = LOOKUP_PACKAGE_ARCH('aarch64'));
insert into rhnChannelPackageArchCompat (channel_arch_id, package_arch_id) select
LOOKUP_CHANNEL_ARCH('channel-aarch64'), LOOKUP_PACKAGE_ARCH('noarch') from dual
where not exists (select 1 from rhnChannelPackageArchCompat where channel_arch_id = LOOKUP_CHANNEL_ARCH('channel-aarch64') and package_arch_id = LOOKUP_PACKAGE_ARCH('noarch'));

insert into rhnServerArch (id, label, name, arch_type_id) select
sequence_nextval('rhn_server_arch_id_seq'), 'aarch64-redhat-linux', 'aarch64', lookup_arch_type('rpm') from dual
where not exists (select 1 from rhnServerArch where label = 'aarch64-redhat-linux');

insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) select
LOOKUP_PACKAGE_ARCH('noarch'), LOOKUP_PACKAGE_ARCH('aarch64'), current_timestamp, current_timestamp from dual
where not exists (select 1 from rhnPackageUpgradeArchCompat where package_arch_id = LOOKUP_PACKAGE_ARCH('noarch') and package_upgrade_arch_id = LOOKUP_PACKAGE_ARCH('aarch64'));
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) select
LOOKUP_PACKAGE_ARCH('aarch64'), LOOKUP_PACKAGE_ARCH('aarch64'), current_timestamp, current_timestamp from dual
where not exists (select 1 from rhnPackageUpgradeArchCompat where package_arch_id = LOOKUP_PACKAGE_ARCH('aarch64') and package_upgrade_arch_id = LOOKUP_PACKAGE_ARCH('aarch64'));
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) select
LOOKUP_PACKAGE_ARCH('aarch64'), LOOKUP_PACKAGE_ARCH('noarch'), current_timestamp, current_timestamp from dual
where not exists (select 1 from rhnPackageUpgradeArchCompat where package_arch_id = LOOKUP_PACKAGE_ARCH('aarch64') and package_upgrade_arch_id = LOOKUP_PACKAGE_ARCH('noarch'));

insert into rhnServerChannelArchCompat (server_arch_id, channel_arch_id) select
LOOKUP_SERVER_ARCH('aarch64-redhat-linux'), LOOKUP_CHANNEL_ARCH('channel-aarch64') from dual
where not exists (select 1 from rhnServerChannelArchCompat where server_arch_id = LOOKUP_SERVER_ARCH('aarch64-redhat-linux') and channel_arch_id = LOOKUP_CHANNEL_ARCH('channel-aarch64'));

insert into rhnServerPackageArchCompat (server_arch_id, package_arch_id, preference) select
LOOKUP_SERVER_ARCH('aarch64-redhat-linux'), LOOKUP_PACKAGE_ARCH('aarch64'), 0 from dual
where not exists (select 1 from rhnServerPackageArchCompat where server_arch_id = LOOKUP_SERVER_ARCH('aarch64-redhat-linux') and package_arch_id = LOOKUP_PACKAGE_ARCH('aarch64'));


insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type) select
LOOKUP_SERVER_ARCH('aarch64-redhat-linux'), LOOKUP_SG_TYPE('sw_mgr_entitled') from dual
where not exists (select 1 from rhnServerServerGroupArchCompat where server_arch_id = LOOKUP_SERVER_ARCH('aarch64-redhat-linux') and server_group_type = LOOKUP_SG_TYPE('sw_mgr_entitled'));
insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type) select
LOOKUP_SERVER_ARCH('aarch64-redhat-linux'), LOOKUP_SG_TYPE('enterprise_entitled') from dual
where not exists (select 1 from rhnServerServerGroupArchCompat where server_arch_id = LOOKUP_SERVER_ARCH('aarch64-redhat-linux') and server_group_type = LOOKUP_SG_TYPE('enterprise_entitled'));
insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type) select
LOOKUP_SERVER_ARCH('aarch64-redhat-linux'), LOOKUP_SG_TYPE('provisioning_entitled') from dual
where not exists (select 1 from rhnServerServerGroupArchCompat where server_arch_id = LOOKUP_SERVER_ARCH('aarch64-redhat-linux') and server_group_type = LOOKUP_SG_TYPE('provisioning_entitled'));
insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type) select
LOOKUP_SERVER_ARCH('aarch64-redhat-linux'), LOOKUP_SG_TYPE('monitoring_entitled') from dual
where not exists (select 1 from rhnServerServerGroupArchCompat where server_arch_id = LOOKUP_SERVER_ARCH('aarch64-redhat-linux') and server_group_type = LOOKUP_SG_TYPE('monitoring_entitled'));
insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type) select
LOOKUP_SERVER_ARCH('aarch64-redhat-linux'), LOOKUP_SG_TYPE('virtualization_host') from dual
where not exists (select 1 from rhnServerServerGroupArchCompat where server_arch_id = LOOKUP_SERVER_ARCH('aarch64-redhat-linux') and server_group_type = LOOKUP_SG_TYPE('virtualization_host'));

insert into rhnCpuArch (id, label, name) select
sequence_nextval('rhn_cpu_arch_id_seq'), 'aarch64', 'AArch64' from dual
where not exists (select 1 from rhnCpuArch where label = 'aarch64');
  070701000007E4000081B400000000000000000000000167AE111400000A06000000000000000000000000000000000000006500000000susemanager-schema/upgrade/spacewalk-schema-2.1-to-spacewalk-schema-2.2/006-web_contact-password.sql  
drop view rhnWebContactEnabled;
drop view rhnUserReceiveNotifications;
drop view rhnWebContactDisabled;
drop view rhn_contact_monitoring;

alter table web_contact alter password type varchar(110);

create or replace view
rhnWebContactDisabled
as
select
   wcon.id,
   wcon.org_id,
   wcon.login,
   wcon.login_uc,
   wcon.password,
   wcon.oracle_contact_id,
   wcon.created,
   wcon.modified,
   wcon.ignore_flag
from
   rhnWebContactChangeLog   wccl,
   rhnWebContactChangeState wccs,
   web_contact              wcon
where wccl.change_state_id = wccs.id
   and wccs.label = 'disabled'
   and wccl.web_contact_id = wcon.id
   and wccl.date_completed =
              (select max(wccl_exists.date_completed)
                 from rhnWebContactChangeLog   wccl_exists
                where wccl.web_contact_id = wccl_exists.web_contact_id);

create or replace view
rhnWebContactEnabled
as
select
   wcon.id,
   wcon.org_id,
   wcon.login,
   wcon.login_uc,
   wcon.password,
   wcon.oracle_contact_id,
   wcon.created,
   wcon.modified,
   wcon.ignore_flag
from
   web_contact wcon
where not exists (
     select 1 from rhnWebContactDisabled
     where wcon.id = rhnWebContactDisabled.id
   );

create or replace view rhnUserReceiveNotifications
as
    select wc.org_id, usp.user_id, usp.server_id
    from rhnUserServerPerms usp
    left join rhnWebContactDisabled wcd
        on usp.user_id = wcd.id
    join web_contact wc
        on usp.user_id = wc.id
    join rhnUserInfo ui
        on usp.user_id = ui.user_id
        and ui.email_notify = 1
    join web_user_personal_info upi
        on usp.user_id = upi.web_user_id
        and upi.email is not null
    left join rhnUserServerPrefs uspr
        on uspr.server_id = usp.server_id
        and usp.user_id = uspr.user_id
        and uspr.name = 'receive_notifications'
        and value='0'
    where uspr.server_id is null
    and wcd.id is null;

create or replace view rhn_contact_monitoring as
select  u.id                    as recid,
        u.org_id                as customer_id,
        wupi.last_name          as contact_last_name,
        wupi.first_names        as contact_first_name,
        wupi.email          as email_address,
        u.login                 as username,
        u.password              as password,
        1                       as schedule_id,
        'GMT' || ''                     as preferred_time_zone
from
        web_user_personal_info wupi,
        web_contact u
where   u.id = wupi.web_user_id
        --  and some logic here to check org id for entitlements?
;
  070701000007E5000081B400000000000000000000000167AE111400000125000000000000000000000000000000000000006000000000susemanager-schema/upgrade/spacewalk-schema-2.1-to-spacewalk-schema-2.2/007-rhnUserExtGroup.sql   ALTER TABLE rhnUserExtGroup ADD org_id NUMERIC DEFAULT NULL
    CONSTRAINT rhn_userExtGroup_oid_fk
        REFERENCES web_customer (id)
        ON DELETE CASCADE;

CREATE UNIQUE INDEX rhn_userextgroup_label_oid_uq
    ON rhnUserExtGroup (label, org_id) ;
DROP INDEX rhn_userextgroup_label_uq;
   070701000007E6000081B400000000000000000000000167AE1114000005B2000000000000000000000000000000000000006600000000susemanager-schema/upgrade/spacewalk-schema-2.1-to-spacewalk-schema-2.2/008-rhnOrgExtGroupMapping.sql --
-- Copyright (c) 2014 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnOrgExtGroupMapping
(
    id        NUMERIC NOT NULL
                  CONSTRAINT rhn_orgextgroupmap_id_pk PRIMARY KEY
                  ,
    ext_group_id       NUMERIC NOT NULL
                  constraint rhn_orgextgroupmap_eg_fk
                  references rhnUserExtGroup(id)
                  on delete cascade,
    server_group_id    NUMERIC NOT NULL
                  constraint rhn_orgextgroupmap_sg_fk
                  references rhnServerGroup(id)
                  on delete cascade,
    created   TIMESTAMPTZ
                  DEFAULT (current_timestamp) NOT NULL,
    modified  TIMESTAMPTZ
                  DEFAULT (current_timestamp) NOT NULL
)

;

CREATE UNIQUE INDEX rhn_orgextgroupmap_es_uq
    ON rhnOrgExtGroupMapping (ext_group_id, server_group_id)
    ;

CREATE SEQUENCE rhn_orgextgroupmap_seq;
  070701000007E7000081B400000000000000000000000167AE1114000000AC000000000000000000000000000000000000006400000000susemanager-schema/upgrade/spacewalk-schema-2.1-to-spacewalk-schema-2.2/009-rhnOrgConfiguration.sql   ALTER TABLE rhnOrgConfiguration ADD create_default_sg CHAR(1)
    default('N') not null
    constraint rhn_org_cong_deforg_chk
    check (create_default_sg in ('Y', 'N'));
070701000007E8000081B400000000000000000000000167AE1114000000A0000000000000000000000000000000000000006000000000susemanager-schema/upgrade/spacewalk-schema-2.1-to-spacewalk-schema-2.2/010-web_contact_log.sql   
alter table web_contact_log drop column old_password;

alter table web_contact_log alter password type varchar(110);

select .recreate_trigger('web_contact');
070701000007E9000081B400000000000000000000000167AE11140000042A000000000000000000000000000000000000006B00000000susemanager-schema/upgrade/spacewalk-schema-2.1-to-spacewalk-schema-2.2/011-rhnOrgExtGroupMapping-trig.sql    --
-- Copyright (c) 2014 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

create or replace function rhn_userorgextgrmap_mod_trig_fun() returns trigger as
$$
begin
        if new.id is null then
            new.id := nextval('rhn_orgextgroupmap_seq');
        end if;
        new.modified := current_timestamp;
        return new;
end;
$$ language plpgsql;

create trigger
rhn_userorgextgrmap_mod_trig
before insert or update on rhnOrgExtGroupMapping
for each row
execute procedure rhn_userorgextgrmap_mod_trig_fun();
  070701000007EA000081B400000000000000000000000167AE1114000002CC000000000000000000000000000000000000006100000000susemanager-schema/upgrade/spacewalk-schema-2.1-to-spacewalk-schema-2.2/012-rhnServer-secret.sql  
drop view rhnentitledservers;

alter table rhnServer alter column secret type varchar(64);

create or replace view
rhnEntitledServers
as
select distinct
    S.id,
    S.org_id,
    S.digital_server_id,
    S.server_arch_id,
    S.os,
    S.release,
    S.name,
    S.description,
    S.info,
    S.secret
from
    rhnServerGroup SG,
    rhnServerGroupType SGT,
    rhnServerGroupMembers SGM,
    rhnServer S
where
    S.id = SGM.server_id
and SG.id = SGM.server_group_id
and SGT.label IN ('sw_mgr_entitled', 'enterprise_entitled', 'provisioning_entitled')
and SG.group_type = SGT.id
and SG.org_id = S.org_id
;

alter table rhnServer_log alter column secret type varchar(64);

select .recreate_trigger('rhnserver');
070701000007EB000081B400000000000000000000000167AE1114000003DC000000000000000000000000000000000000005F00000000susemanager-schema/upgrade/spacewalk-schema-2.1-to-spacewalk-schema-2.2/013-rhnActionChain.sql    --
-- Copyright (c) 2014 SUSE
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
--

CREATE TABLE rhnActionChain
(
    id          NUMERIC        NOT NULL
                    CONSTRAINT rhn_action_chain_id_pk PRIMARY KEY,
    label       VARCHAR(256) NOT NULL,
    user_id     NUMERIC        NOT NULL
                    CONSTRAINT rhn_actionchain_uid_fk
                        REFERENCES web_contact (id)
                        ON DELETE CASCADE,
    created     TIMESTAMPTZ          DEFAULT(CURRENT_TIMESTAMP) NOT NULL,
    modified    TIMESTAMPTZ          DEFAULT(CURRENT_TIMESTAMP) NOT NULL
)

;

CREATE SEQUENCE rhn_actionchain_id_seq;
070701000007EC000081B400000000000000000000000167AE11140000048F000000000000000000000000000000000000006400000000susemanager-schema/upgrade/spacewalk-schema-2.1-to-spacewalk-schema-2.2/014-rhnActionChainEntry.sql   --
-- Copyright (c) 2014 SUSE
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
--

CREATE TABLE rhnActionChainEntry
(
    actionchain_id NUMERIC NOT NULL
        CONSTRAINT rhn_actchainent_acid_fk
            REFERENCES rhnActionChain (id)
            ON DELETE CASCADE,
    action_id      NUMERIC
        CONSTRAINT rhn_actchainent_aid_fk
            REFERENCES rhnAction (id)
            ON DELETE CASCADE,
    server_id      NUMERIC NOT NULL
        CONSTRAINT rhn_actchainent_sid_fk
            REFERENCES rhnServer(id)
            ON DELETE CASCADE,
    sort_order     NUMERIC NOT NULL,
    created        TIMESTAMPTZ DEFAULT(CURRENT_TIMESTAMP) NOT NULL,
    modified       TIMESTAMPTZ DEFAULT(CURRENT_TIMESTAMP) NOT NULL
)

;

CREATE UNIQUE INDEX rhn_actchainent_aid_uq
    ON rhnActionChainEntry(action_id)
    ;
 070701000007ED000081B400000000000000000000000167AE111400000312000000000000000000000000000000000000006700000000susemanager-schema/upgrade/spacewalk-schema-2.1-to-spacewalk-schema-2.2/015-rhnActionChain-trigger.sql    --
-- Copyright (c) 2014 SUSE
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
--
CREATE OR REPLACE FUNCTION rhn_actionchain_mod_trig_fun() RETURNS TRIGGER
    AS
    $$
    BEGIN
        new.modified := current_timestamp;
        RETURN new;
    END;
    $$
    LANGUAGE PLPGSQL;

CREATE TRIGGER rhn_actionchain_mod_trig
    BEFORE INSERT OR UPDATE ON rhnActionChain
    FOR EACH ROW
    EXECUTE PROCEDURE rhn_actionchain_mod_trig_fun();
  070701000007EE000081B400000000000000000000000167AE111400000317000000000000000000000000000000000000006C00000000susemanager-schema/upgrade/spacewalk-schema-2.1-to-spacewalk-schema-2.2/016-rhnActionChainEntry-trigger.sql   --
-- Copyright (c) 2014 SUSE
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
--
CREATE OR REPLACE FUNCTION rhn_actchainent_mod_trig_fun() RETURNS TRIGGER
    AS
    $$
    BEGIN
        new.modified := current_timestamp;
        RETURN new;
    END;
    $$
    LANGUAGE PLPGSQL;

CREATE TRIGGER rhn_actchainent_mod_trig
    BEFORE INSERT OR UPDATE ON rhnActionChainEntry
    FOR EACH ROW
    EXECUTE PROCEDURE rhn_actchainent_mod_trig_fun();
 070701000007EF000081B400000000000000000000000167AE1114000003FE000000000000000000000000000000000000006F00000000susemanager-schema/upgrade/spacewalk-schema-2.1-to-spacewalk-schema-2.2/017-add-reboot-action-cleanup-task.sql    INSERT INTO rhnTaskoBunch (id, name, description, org_bunch)
    VALUES (sequence_nextval('rhn_tasko_bunch_id_seq'), 'reboot-action-cleanup-bunch', 'invalidate reboot actions which never finish', null);

-- Every hour

INSERT INTO rhnTaskoSchedule (id, job_label, bunch_id, active_from, cron_expr)
    VALUES(sequence_nextval('rhn_tasko_schedule_id_seq'), 'reboot-action-cleanup-default',
        (SELECT id FROM rhnTaskoBunch WHERE name='reboot-action-cleanup-bunch'),
        current_timestamp, '0 0 * * * ?');

INSERT INTO rhnTaskoTask (id, name, class)
    VALUES (sequence_nextval('rhn_tasko_task_id_seq'), 'reboot-action-cleanup', 'com.redhat.rhn.taskomatic.task.RebootActionCleanup');

INSERT INTO rhnTaskoTemplate (id, bunch_id, task_id, ordering, start_if)
    VALUES (sequence_nextval('rhn_tasko_template_id_seq'),
            (SELECT id FROM rhnTaskoBunch WHERE name='reboot-action-cleanup-bunch'),
            (SELECT id FROM rhnTaskoTask WHERE name='reboot-action-cleanup'),
            0,
            null);
  070701000007F0000081B400000000000000000000000167AE111400000500000000000000000000000000000000000000006100000000susemanager-schema/upgrade/spacewalk-schema-2.1-to-spacewalk-schema-2.2/018-rhnPackageBreaks.sql  --
-- Copyright (c) 2010 Novell
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
--


CREATE TABLE rhnPackageBreaks
(
    package_id     NUMERIC NOT NULL
                       CONSTRAINT rhn_pkg_brks_package_fk
                           REFERENCES rhnPackage (id)
                           ON DELETE CASCADE,
    capability_id  NUMERIC NOT NULL
                       CONSTRAINT rhn_pkg_brks_capability_fk
                           REFERENCES rhnPackageCapability (id),
    sense          NUMERIC
                       DEFAULT (0) NOT NULL,
    created        TIMESTAMPTZ
                       DEFAULT (current_timestamp) NOT NULL,
    modified       TIMESTAMPTZ
                       DEFAULT (current_timestamp) NOT NULL
)

;

CREATE UNIQUE INDEX rhn_pkg_brks_pid_cid_s_uq
    ON rhnPackageBreaks (package_id, capability_id, sense)
    ;

CREATE INDEX rhn_pkg_brks_cid_idx
    ON rhnPackageBreaks (capability_id)
    
    ;

070701000007F1000081B400000000000000000000000167AE11140000050C000000000000000000000000000000000000006500000000susemanager-schema/upgrade/spacewalk-schema-2.1-to-spacewalk-schema-2.2/019-rhnPackagePredepends.sql  --
-- Copyright (c) 2010 Novell
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
--


CREATE TABLE rhnPackagePredepends
(
    package_id     NUMERIC NOT NULL
                       CONSTRAINT rhn_pkg_pdep_package_fk
                           REFERENCES rhnPackage (id)
                           ON DELETE CASCADE,
    capability_id  NUMERIC NOT NULL
                       CONSTRAINT rhn_pkg_pdep_capability_fk
                           REFERENCES rhnPackageCapability (id),
    sense          NUMERIC
                       DEFAULT (0) NOT NULL,
    created        TIMESTAMPTZ
                       DEFAULT (current_timestamp) NOT NULL,
    modified       TIMESTAMPTZ
                       DEFAULT (current_timestamp) NOT NULL
)

;

CREATE UNIQUE INDEX rhn_pkg_pdep_pid_cid_s_uq
    ON rhnPackagePredepends (package_id, capability_id, sense)
    ;

CREATE INDEX rhn_pkg_pdep_cid_idx
    ON rhnPackagePredepends (capability_id)
    
    ;

070701000007F2000081B400000000000000000000000167AE1114000002E4000000000000000000000000000000000000006900000000susemanager-schema/upgrade/spacewalk-schema-2.1-to-spacewalk-schema-2.2/020-rhnPackageBreaks-trigger.sql  --
-- Copyright (c) 2010 Novell, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
--

create or replace function rhn_pkg_brks_mod_trig_fun() returns trigger as
$$
begin
	new.modified := current_timestamp;

	return new;
end;
$$ language plpgsql;

create trigger
rhn_pkg_brks_mod_trig
before insert or update on rhnPackageBreaks
for each row
execute procedure rhn_pkg_brks_mod_trig_fun();

070701000007F3000081B400000000000000000000000167AE1114000002E8000000000000000000000000000000000000006D00000000susemanager-schema/upgrade/spacewalk-schema-2.1-to-spacewalk-schema-2.2/020-rhnPackagePredepends-trigger.sql  --
-- Copyright (c) 2010 Novell, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
--

create or replace function rhn_pkg_pdep_mod_trig_fun() returns trigger as
$$
begin
	new.modified := current_timestamp;

	return new;
end;
$$ language plpgsql;

create trigger
rhn_pkg_pdep_mod_trig
before insert or update on rhnPackagePredepends
for each row
execute procedure rhn_pkg_pdep_mod_trig_fun();

070701000007F4000081B400000000000000000000000167AE111400000071000000000000000000000000000000000000006900000000susemanager-schema/upgrade/spacewalk-schema-2.1-to-spacewalk-schema-2.2/021-rhnActionType-clientcert.sql  insert
  into rhnActionType
values (51, 'clientcert.update_client_cert', 'Update Client Certificate', 'N', 'Y');
   070701000007F5000081B400000000000000000000000167AE11140000004B000000000000000000000000000000000000007300000000susemanager-schema/upgrade/spacewalk-schema-2.1-to-spacewalk-schema-2.2/022-web_user_personal_info-userIdIndex.sql    CREATE INDEX wupi_user_id_idx
    ON web_user_personal_info (web_user_id);
 070701000007F6000081B400000000000000000000000167AE11140000004D000000000000000000000000000000000000007200000000susemanager-schema/upgrade/spacewalk-schema-2.1-to-spacewalk-schema-2.2/023-add-note-to-rhnssmoperationserver.sql ALTER TABLE rhnSsmOperationServer
  ADD note VARCHAR(256)
    DEFAULT NULL
;
   070701000007F7000081B400000000000000000000000167AE1114000004BF000000000000000000000000000000000000006D00000000susemanager-schema/upgrade/spacewalk-schema-2.1-to-spacewalk-schema-2.2/024-rhnKickstartableTree-trigger.sql  
create or replace function rhn_kstree_mod_trig_fun() returns trigger as
$$
begin
        if tg_op='UPDATE' then
                -- Basically if we're changing something other than cobbler_id,
                -- cobbler_xen_id, and last_modified - or if last_modified is
                -- explicity set to null. Gets complicated because we have
                -- to allow for the possibility of the ids being null
                if ((not old.cobbler_id is null and new.cobbler_id = old.cobbler_id)
                        or (old.cobbler_id is null and new.cobbler_id is null))
                    and ((not old.cobbler_xen_id is null and new.cobbler_xen_id = old.cobbler_xen_id)
                        or (old.cobbler_xen_id is null and new.cobbler_xen_id is null))
                    and new.last_modified = old.last_modified
                    or new.last_modified is null
                then
                    new.last_modified := current_timestamp;
                end if;
        elseif tg_op='INSERT' and new.last_modified is null then
                new.last_modified := current_timestamp;
        end if;

        new.modified := current_timestamp;

        return new;
end;
$$ language plpgsql;
 070701000007F8000081B400000000000000000000000167AE111400000114000000000000000000000000000000000000007900000000susemanager-schema/upgrade/spacewalk-schema-2.1-to-spacewalk-schema-2.2/025-rhnKickstartableTree-touch-last_modified.sql  -- Update last_modified on every kickstart tree.
-- This will force a re-sync to cobbler the next time
-- something on cobbler changes or taskomatic is restarted.
-- The re-sync will correct the cobbler arch.
update rhnKickstartableTree set last_modified = current_timestamp;
070701000007F9000081B400000000000000000000000167AE11140000098F000000000000000000000000000000000000006C00000000susemanager-schema/upgrade/spacewalk-schema-2.1-to-spacewalk-schema-2.2/026-support-for-armhf-on-debian.sql   
insert into rhnPackageArch (id, label, name, arch_type_id) values
        (sequence_nextval('rhn_package_arch_id_seq'), 'armhf-deb', 'armhf-deb', lookup_arch_type('deb'));

insert into rhnChannelPackageArchCompat (channel_arch_id, package_arch_id)
        values (LOOKUP_CHANNEL_ARCH('channel-arm-deb'), LOOKUP_PACKAGE_ARCH('armhf-deb'));

insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('armhf-deb'), LOOKUP_PACKAGE_ARCH('all-deb'), current_timestamp, current_timestamp);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('all-deb'), LOOKUP_PACKAGE_ARCH('armhf-deb'), current_timestamp, current_timestamp);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('armhf-deb'), LOOKUP_PACKAGE_ARCH('armhf-deb'), current_timestamp, current_timestamp);

insert into rhnServerArch (id, label, name, arch_type_id) values
(sequence_nextval('rhn_server_arch_id_seq'), 'armv6l-debian-linux', 'arm Debian', lookup_arch_type('deb'));

insert into rhnServerChannelArchCompat (server_arch_id, channel_arch_id) values
(LOOKUP_SERVER_ARCH('armv6l-debian-linux'), LOOKUP_CHANNEL_ARCH('channel-arm-deb'));

insert into rhnServerPackageArchCompat
(server_arch_id, package_arch_id, preference) values
(LOOKUP_SERVER_ARCH('armv6l-debian-linux'), LOOKUP_PACKAGE_ARCH('armhf-deb'), 0);
insert into rhnServerPackageArchCompat
(server_arch_id, package_arch_id, preference) values
(LOOKUP_SERVER_ARCH('armv6l-debian-linux'), LOOKUP_PACKAGE_ARCH('all-deb'), 1000);


insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
        values (lookup_server_arch('armv6l-debian-linux'),
            lookup_sg_type('sw_mgr_entitled'));
insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
        values (lookup_server_arch('armv6l-debian-linux'),
            lookup_sg_type('enterprise_entitled'));
insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
        values (lookup_server_arch('armv6l-debian-linux'),
            lookup_sg_type('provisioning_entitled'));
insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
        values (lookup_server_arch('armv6l-debian-linux'),
            lookup_sg_type('monitoring_entitled'));

 070701000007FA000081B400000000000000000000000167AE111400000198000000000000000000000000000000000000006700000000susemanager-schema/upgrade/spacewalk-schema-2.1-to-spacewalk-schema-2.2/027-rhnPackageKey-CentOS-7.sql    update rhnPackageKey set provider_id = lookup_package_provider('CentOS')
 where key_id = '24c6a8a7f4a80eb5';

insert into rhnPackageKey (id, key_id, key_type_id, provider_id)
    (select sequence_nextval('rhn_pkey_id_seq'), '24c6a8a7f4a80eb5', lookup_package_key_type('gpg'), lookup_package_provider('CentOS') from dual
     where not exists (select 1 from rhnPackageKey where key_id = '24c6a8a7f4a80eb5'));
070701000007FB000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000004800000000susemanager-schema/upgrade/spacewalk-schema-2.2-to-spacewalk-schema-2.3   070701000007FC000081B400000000000000000000000167AE11140000038D000000000000000000000000000000000000006A00000000susemanager-schema/upgrade/spacewalk-schema-2.2-to-spacewalk-schema-2.3/001-lookup_package_capability.sql 
-- Note: intentionally not thread-safe! You must aquire a write lock on the
-- rhnPackageCapability tabel if you are going to use this proc!
create or replace function lookup_package_capability_fast(name_in in varchar, version_in in varchar default null)
returns numeric
as
$$
declare
    name_id numeric;
begin
    if version_in is null then
        select id
          into name_id
          from rhnpackagecapability
         where name = name_in and
               version is null;
    else
        select id
          into name_id
          from rhnpackagecapability
         where name = name_in and
               version = version_in;
    end if;

    if not found then
        name_id = nextval('rhn_pkg_capability_id_seq');
        insert into rhnPackageCapability(id, name, version) values (
               name_id, name_in, version_in);
    end if;

    return name_id;
end;
$$
language plpgsql;
   070701000007FD000081B400000000000000000000000167AE1114000002E2000000000000000000000000000000000000006800000000susemanager-schema/upgrade/spacewalk-schema-2.2-to-spacewalk-schema-2.3/001-rhnPackageKey-Fedora-21.sql   update rhnPackageKey set provider_id = lookup_package_provider('Fedora')
 where key_id = '89ad4e8795a43f54' or key_id = '636dea19a0a7badb';

insert into rhnPackageKey (id, key_id, key_type_id, provider_id)
    (select sequence_nextval('rhn_pkey_id_seq'), '89ad4e8795a43f54', lookup_package_key_type('gpg'), lookup_package_provider('Fedora') from dual
     where not exists (select 1 from rhnPackageKey where key_id = '89ad4e8795a43f54'));

insert into rhnPackageKey (id, key_id, key_type_id, provider_id)
    (select sequence_nextval('rhn_pkey_id_seq'), '636dea19a0a7badb', lookup_package_key_type('gpg'), lookup_package_provider('Fedora') from dual
     where not exists (select 1 from rhnPackageKey where key_id = '636dea19a0a7badb'));
  070701000007FE000081B400000000000000000000000167AE11140000034C000000000000000000000000000000000000006000000000susemanager-schema/upgrade/spacewalk-schema-2.2-to-spacewalk-schema-2.3/002-lookup_checksum.sql   
-- NOTE: This is intentionally not thread safe! You must lock rhnChecksum
-- if you are going to use this procedure!
create or replace function
lookup_checksum_fast(checksum_type_in in varchar, checksum_in in varchar)
returns numeric
as
$$
declare
    checksum_id     numeric;
begin
    if checksum_in is null then
        return null;
    end if;

    select c.id
      into checksum_id
      from rhnChecksumView c
     where c.checksum = checksum_in and
           c.checksum_type = checksum_type_in;

    if not found then
        checksum_id := nextval('rhnchecksum_seq');
        insert into rhnChecksum (id, checksum_type_id, checksum) values (
            checksum_id,
            (select id from rhnChecksumType where label = checksum_type_in),
            checksum_in);
    end if;

    return checksum_id;
end;
$$
language plpgsql;
070701000007FF000081B400000000000000000000000167AE111400001684000000000000000000000000000000000000005C00000000susemanager-schema/upgrade/spacewalk-schema-2.2-to-spacewalk-schema-2.3/003-add-ppc64le.sql   insert into rhnChannelArch (id, label, name, arch_type_id) select
sequence_nextval('rhn_channel_arch_id_seq'), 'channel-ppc64le', 'PPC64LE', lookup_arch_type('rpm') from dual
where not exists (select 1 from rhnChannelArch where label = 'channel-ppc64le');

insert into rhnChannelPackageArchCompat (channel_arch_id, package_arch_id) select
LOOKUP_CHANNEL_ARCH('channel-ppc64le'), LOOKUP_PACKAGE_ARCH('noarch') from dual
where not exists (select 1 from rhnChannelPackageArchCompat where channel_arch_id = LOOKUP_CHANNEL_ARCH('channel-ppc64le') and package_arch_id = LOOKUP_PACKAGE_ARCH('noarch'));

insert into rhnCpuArch (id, label, name) select
sequence_nextval('rhn_cpu_arch_id_seq'), 'ppc64le', 'ppc64le' from dual
where not exists (select 1 from rhnCpuArch where label = 'ppc64le');

insert into rhnPackageArch (id, label, name, arch_type_id) select
sequence_nextval('rhn_package_arch_id_seq'), 'ppc64le', 'ppc64le', lookup_arch_type('rpm') from dual
where not exists (select 1 from rhnPackageArch where label = 'ppc64le');

insert into rhnChannelPackageArchCompat (channel_arch_id, package_arch_id) select
LOOKUP_CHANNEL_ARCH('channel-ppc64le'), LOOKUP_PACKAGE_ARCH('ppc64le') from dual
where not exists (select 1 from rhnChannelPackageArchCompat where channel_arch_id = LOOKUP_CHANNEL_ARCH('channel-ppc64le') and package_arch_id = LOOKUP_PACKAGE_ARCH('ppc64le'));

insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) select
LOOKUP_PACKAGE_ARCH('noarch'), LOOKUP_PACKAGE_ARCH('ppc64le'), current_timestamp, current_timestamp from dual
where not exists (select 1 from rhnPackageUpgradeArchCompat where package_arch_id = LOOKUP_PACKAGE_ARCH('noarch') and package_upgrade_arch_id = LOOKUP_PACKAGE_ARCH('ppc64le'));
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) select
LOOKUP_PACKAGE_ARCH('ppc64le'), LOOKUP_PACKAGE_ARCH('ppc64le'), current_timestamp, current_timestamp from dual
where not exists (select 1 from rhnPackageUpgradeArchCompat where package_arch_id = LOOKUP_PACKAGE_ARCH('noarch') and package_upgrade_arch_id = LOOKUP_PACKAGE_ARCH('ppc64le'));
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) select
LOOKUP_PACKAGE_ARCH('ppc64le'), LOOKUP_PACKAGE_ARCH('noarch'), current_timestamp, current_timestamp from dual
where not exists (select 1 from rhnPackageUpgradeArchCompat where package_arch_id = LOOKUP_PACKAGE_ARCH('ppc64le') and package_upgrade_arch_id = LOOKUP_PACKAGE_ARCH('noarch'));

insert into rhnServerArch (id, label, name, arch_type_id) select
sequence_nextval('rhn_server_arch_id_seq'), 'ppc64le-redhat-linux', 'ppc64le', lookup_arch_type('rpm') from dual
where not exists (select 1 from rhnServerArch where label = 'ppc64le-redhat-linux');

insert into rhnServerChannelArchCompat (server_arch_id, channel_arch_id) select
LOOKUP_SERVER_ARCH('ppc64le-redhat-linux'), LOOKUP_CHANNEL_ARCH('channel-ppc64le') from dual
where not exists (select 1 from rhnServerChannelArchCompat where server_arch_id = LOOKUP_SERVER_ARCH('ppc64le-redhat-linux') and channel_arch_id = LOOKUP_CHANNEL_ARCH('channel-ppc64le'));

insert into rhnServerPackageArchCompat (server_arch_id, package_arch_id, preference) select
LOOKUP_SERVER_ARCH('ppc64le-redhat-linux'), LOOKUP_PACKAGE_ARCH('ppc64le'), 0 from dual
where not exists (select 1 from rhnServerPackageArchCompat where server_arch_id = LOOKUP_SERVER_ARCH('ppc64le-redhat-linux') and package_arch_id = LOOKUP_PACKAGE_ARCH('ppc64le'));

insert into rhnServerPackageArchCompat (server_arch_id, package_arch_id, preference) select
LOOKUP_SERVER_ARCH('ppc64le-redhat-linux'), LOOKUP_PACKAGE_ARCH('noarch'), 1000 from dual
where not exists (select 1 from rhnServerPackageArchCompat where server_arch_id = LOOKUP_SERVER_ARCH('ppc64le-redhat-linux') and package_arch_id = LOOKUP_PACKAGE_ARCH('noarch'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type) select
LOOKUP_SERVER_ARCH('ppc64le-redhat-linux'), LOOKUP_SG_TYPE('sw_mgr_entitled') from dual
where not exists (select 1 from rhnServerServerGroupArchCompat where server_arch_id = LOOKUP_SERVER_ARCH('ppc64le-redhat-linux') and server_group_type = LOOKUP_SG_TYPE('sw_mgr_entitled'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type) select
lookup_server_arch('ppc64le-redhat-linux'), lookup_sg_type('enterprise_entitled') from dual
where not exists (select 1 from rhnServerServerGroupArchCompat where server_arch_id = LOOKUP_SERVER_ARCH('ppc64le-redhat-linux') and server_group_type = LOOKUP_SG_TYPE('enterprise_entitled'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type) select
lookup_server_arch('ppc64le-redhat-linux'), lookup_sg_type('provisioning_entitled') from dual
where not exists (select 1 from rhnServerServerGroupArchCompat where server_arch_id = LOOKUP_SERVER_ARCH('ppc64le-redhat-linux') and server_group_type = LOOKUP_SG_TYPE('provisioning_entitled'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type) select
lookup_server_arch('ppc64le-redhat-linux'), lookup_sg_type('monitoring_entitled') from dual
where not exists (select 1 from rhnServerServerGroupArchCompat where server_arch_id = LOOKUP_SERVER_ARCH('ppc64le-redhat-linux') and server_group_type = LOOKUP_SG_TYPE('monitoring_entitled'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type) select
lookup_server_arch('ppc64le-redhat-linux'), lookup_sg_type('virtualization_host') from dual
where not exists (select 1 from rhnServerServerGroupArchCompat where server_arch_id = LOOKUP_SERVER_ARCH('ppc64le-redhat-linux') and server_group_type = LOOKUP_SG_TYPE('virtualization_host'));
07070100000800000081B400000000000000000000000167AE11140000006A000000000000000000000000000000000000006A00000000susemanager-schema/upgrade/spacewalk-schema-2.2-to-spacewalk-schema-2.3/003-rhnServerGroupTypeFeature.sql delete from rhnServerGroupTypeFeature where server_group_type_id = lookup_sg_type('monitoring_entitled');
  07070100000801000081B400000000000000000000000167AE11140000047E000000000000000000000000000000000000007100000000susemanager-schema/upgrade/spacewalk-schema-2.2-to-spacewalk-schema-2.3/004-rhnConfigRevision-delete-trigger.sql  --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--


create or replace function rhn_confrevision_del_trig_fun() returns trigger 
as
$$
declare
        cr_removed numeric := lookup_snapshot_invalid_reason('cr_removed');
begin
        update rhnSnapshot as s
           set invalid = cr_removed
          from rhnSnapshotConfigRevision as scr
         where s.id = scr.snapshot_id
           and scr.config_revision_id = old.id;
        delete from rhnSnapshotConfigRevision
         where config_revision_id = old.id;
        return old;
end;
$$ language plpgsql;
  07070100000802000081B400000000000000000000000167AE111400000152000000000000000000000000000000000000006100000000susemanager-schema/upgrade/spacewalk-schema-2.2-to-spacewalk-schema-2.3/005-rhnTimezone-data.sql  insert into rhnTimezone (id, olson_name, display_name) (
    select sequence_nextval('rhn_timezone_id_seq'),
           'Asia/Seoul',
           'Korea'
      from dual
     where not exists (
           select 1
             from rhnTimezone
            where olson_name = 'Asia/Seoul'
              and display_name = 'Korea'
     )
);
  07070100000803000081B400000000000000000000000167AE111400000060000000000000000000000000000000000000007200000000susemanager-schema/upgrade/spacewalk-schema-2.2-to-spacewalk-schema-2.3/006-rhnTaskoSchedule-update-cron_expr.sql update rhnTaskoSchedule set cron_expr = '0 * * * * ?' where job_label = 'errata-cache-default';
07070100000804000081B400000000000000000000000167AE11140000B8CF000000000000000000000000000000000000006000000000susemanager-schema/upgrade/spacewalk-schema-2.2-to-spacewalk-schema-2.3/007-rhn_channel.pkb.sql   --
-- Copyright (c) 2008--2014 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--

-- create schema rhn_channel;

--update pg_setting
update pg_settings set setting = 'rhn_channel,' || setting where name = 'search_path';

    create or replace function obtain_read_lock(channel_family_id_in in numeric, org_id_in in numeric)
    returns void as $$
    declare
        read_lock timestamptz;
    begin
        select created into read_lock
          from rhnPrivateChannelFamily
         where channel_family_id = channel_family_id_in and org_id = org_id_in
           for update;
    end$$ language plpgsql;

    -- this "emulates" cursor server_base_subscriptions defined in oracle/rhn_channel.pks
    create or replace function server_base_subscriptions(server_id_in NUMERIC)
    returns boolean as $$
    begin
      return exists(SELECT C.id FROM rhnChannel C, rhnServerChannel SC
		    WHERE C.id = SC.channel_id
		      AND SC.server_id = server_id_in
		      AND C.parent_channel IS NULL);
    end$$ language plpgsql;

    -- this "emulates" cursor server_base_subscriptions defined in oracle/rhn_channel.pks
    create or replace function check_server_subscription(server_id_in NUMERIC, channel_id_in NUMERIC)
    returns boolean as $$
    begin
      return exists(SELECT channel_id FROM rhnServerChannel WHERE server_id = server_id_in AND channel_id = channel_id_in);
    end$$ language plpgsql;


    CREATE OR REPLACE FUNCTION subscribe_server(server_id_in IN NUMERIC, channel_id_in NUMERIC, immediate_in NUMERIC default 1, user_id_in in numeric default null, recalcfamily_in NUMERIC default 1) returns void
    AS $$
    declare
        channel_parent_val      rhnChannel.parent_channel%TYPE;
        parent_subscribed       BOOLEAN;
        server_has_base_chan    BOOLEAN;
        server_already_in_chan  BOOLEAN;
        channel_family_id_val   NUMERIC;
        server_org_id_val       NUMERIC;
        available_subscriptions NUMERIC;
        available_fve_subs      numeric;
        consenting_user         NUMERIC;
        allowed                 numeric;
        is_fve_char             char(1) := 'N';
    BEGIN
        if user_id_in is not null then
            allowed := rhn_channel.user_role_check(channel_id_in, user_id_in, 'subscribe');
        else
            allowed := 1;
        end if;

        if allowed = 0 then
            perform rhn_exception.raise_exception('no_subscribe_permissions');
        end if;


        SELECT parent_channel INTO channel_parent_val FROM rhnChannel WHERE id = channel_id_in;

        IF channel_parent_val IS NOT NULL
        THEN    
            -- child channel; if attempting to cross-subscribe a child to the wrong base, silently ignore
            parent_subscribed := rhn_channel.check_server_subscription(server_id_in, channel_parent_val);
        
            IF NOT parent_subscribed
            THEN
                RETURN;
            END IF;
        ELSE
            -- base channel
            server_has_base_chan := rhn_channel.server_base_subscriptions(server_id_in);
            
            IF server_has_base_chan
            THEN
                perform rhn_exception.raise_exception('channel_server_one_base');
            END IF;
        END IF;

        server_already_in_chan := rhn_channel.check_server_subscription(server_id_in, channel_id_in);
    
        IF server_already_in_chan
        THEN
            RETURN;
        END IF;
        
        channel_family_id_val := rhn_channel.family_for_channel(channel_id_in);
        IF channel_family_id_val IS NULL
        THEN
            perform rhn_exception.raise_exception('channel_subscribe_no_family');
        END IF;

        --
        -- Use the org_id of the server only if the org_id of the channel = NULL.
        -- This is required for subscribing to shared channels.
        --
        SELECT COALESCE(org_id, (SELECT org_id FROM rhnServer WHERE id = server_id_in))
          INTO server_org_id_val
          FROM rhnChannel
         WHERE id = channel_id_in;
         
        begin
            perform rhn_channel.obtain_read_lock(channel_family_id_val, server_org_id_val);
        exception
            when no_data_found then
                perform rhn_exception.raise_exception('channel_family_no_subscriptions');
        end;

        available_subscriptions := rhn_channel.available_family_subscriptions(channel_family_id_val, server_org_id_val);
        available_fve_subs := rhn_channel.available_fve_family_subs(channel_family_id_val, server_org_id_val);
        
        IF available_subscriptions IS NULL OR 
           available_subscriptions > 0 or
           rhn_channel.can_server_consume_virt_channl(server_id_in, channel_family_id_val) = 1 OR
            (available_fve_subs > 0 AND rhn_channel.can_server_consume_fve(server_id_in) = 1)
        THEN
            if rhn_channel.can_server_consume_virt_channl(server_id_in, channel_family_id_val) = 0 AND available_fve_subs > 0 AND rhn_channel.can_server_consume_fve(server_id_in) = 1 THEN
                is_fve_char := 'Y';
            end if;

            insert into rhnServerHistory (id,server_id,summary,details) (
                select  nextval('rhn_event_id_seq'),
                        server_id_in,
                        'subscribed to channel ' || SUBSTR(c.label, 0, 106),
                        c.label
                from    rhnChannel c
                where   c.id = channel_id_in
            );

            INSERT INTO rhnServerChannel (server_id, channel_id, is_fve) VALUES (server_id_in, channel_id_in, is_fve_char);
			IF recalcfamily_in > 0
			THEN
                perform rhn_channel.update_family_counts(channel_family_id_val, server_org_id_val);
			END IF;

            perform queue_server(server_id_in, immediate_in);

            update rhnServer
               set channels_changed = current_timestamp
             where id = server_id_in;
        ELSE
            perform rhn_exception.raise_exception('channel_family_no_subscriptions');
        END IF;
            
    END$$ language plpgsql;



    create or replace function can_convert_to_fve(server_id_in IN NUMERIC, channel_family_id_val IN NUMERIC)
    RETURNS NUMERIC
    as $$
    declare
        fve_convertible_entries cursor for
        select 1  from
            rhnServerFveCapable cap
          where cap.server_id = server_id_in
                AND cap.channel_family_id = channel_family_id_val;
    BEGIN
        FOR entry IN fve_convertible_entries LOOP
            return 1;
        END LOOP;
        RETURN 0;
    END$$ language plpgsql;



    -- Converts server channel_family to use a flex entitlement
    create or replace function convert_to_fve(server_id_in IN NUMERIC, channel_family_id_val IN NUMERIC)
    returns void
    as $$
    declare
        available_fve_subs      NUMERIC;
        server_org_id_val       NUMERIC;
    BEGIN

        --
        -- Use the org_id of the server only if the org_id of the channel = NULL.
        -- This is required for subscribing to shared channels.
        --
        SELECT org_id
          INTO server_org_id_val
          FROM rhnServer
         WHERE id = server_id_in;


        perform rhn_channel.obtain_read_lock(channel_family_id_val, server_org_id_val);
        if not found then
                perform rhn_exception.raise_exception('channel_family_no_subscriptions');
        end if;
        IF (rhn_channel.can_convert_to_fve(server_id_in, channel_family_id_val ) = 0)
            THEN
                perform rhn_exception.raise_exception('server_cannot_convert_to_flex');
        END IF;

        available_fve_subs := rhn_channel.available_fve_family_subs(channel_family_id_val, server_org_id_val);

        IF (available_fve_subs > 0)
        THEN

            insert into rhnServerHistory (id,server_id,summary,details) (
                select  nextval('rhn_event_id_seq'),
                        server_id_in,
                        'converted to flex entitlement' || SUBSTR(cf.label, 0, 99),
                        cf.label
                from    rhnChannelFamily cf
                where   cf.id = channel_family_id_val
            );

            UPDATE rhnServerChannel sc set is_fve = 'Y'
                           where sc.server_id = server_id_in and
                                 sc.channel_id in
                                    (select cfm.channel_id from rhnChannelFamilyMembers cfm
                                                where cfm.CHANNEL_FAMILY_ID = channel_family_id_val);

            perform rhn_channel.update_family_counts(channel_family_id_val, server_org_id_val);
        ELSE
            perform rhn_exception.raise_exception('not_enough_flex_entitlements');
        END IF;

    END$$ language plpgsql;
    
    create or replace function can_server_consume_virt_channl(
        server_id_in in numeric,
        family_id_in in numeric )
    returns numeric
    as $$
    begin
      if exists(
            select 1
            from
                rhnChannelFamilyVirtSubLevel cfvsl,
                rhnSGTypeVirtSubLevel sgtvsl,
                rhnVirtualInstance vi
            where
                vi.virtual_system_id = server_id_in 
                and sgtvsl.virt_sub_level_id = cfvsl.virt_sub_level_id
                and cfvsl.channel_family_id = family_id_in
                and exists (
                    select 1
                    from rhnServerEntitlementView sev
                    where vi.host_system_id = sev.server_id
                    and sev.server_group_type_id = sgtvsl.server_group_type_id ))
      then
        return 1;
      else
        return 0;
      end if;
    end$$ language plpgsql;

    create or replace function can_server_consume_fve(server_id_in in numeric) returns numeric
    as $$
    declare
        vi_entries cursor for
            SELECT 1
              FROM rhnVirtualInstance vi
             WHERE vi.virtual_system_id = server_id_in;
        vi_count numeric;

    begin
        FOR vi_entry IN VI_ENTRIES LOOP
            return 1;
        END LOOP;
        RETURN 0;
    end$$ language plpgsql;

    create or replace function guess_server_base(
        server_id_in in numeric
    ) RETURNS numeric as $$
    declare
        server_cursor cursor for
            select s.server_arch_id, s.release, s.org_id
              from rhnServer s
             where s.id = server_id_in;
    -- Cursor that fetches all the possible base channels for a
    -- (server_arch_id, release, org_id) combination
        base_channel_cursor cursor(
                release_in varchar,
                server_arch_id_in numeric,
                org_id_in numeric
        ) for
                select distinct c.*
                from    rhnOrgDistChannelMap                       odcm,
                                rhnServerChannelArchCompat      scac,
                                rhnChannel                                      c
                where   c.parent_channel is null
                        and c.id = odcm.channel_id
                        and c.channel_arch_id = odcm.channel_arch_id
                        and odcm.release = release_in
                        and odcm.for_org_id = org_id_in
                        and scac.server_arch_id = server_arch_id_in
                        and scac.channel_arch_id = c.channel_arch_id;

    begin
        for s in server_cursor loop
            for channel in base_channel_cursor(s.release,
                s.server_arch_id, s.org_id) 
            loop
                return channel.id;
            end loop;
        end loop;
        -- Server not found, or no base channel applies to it
        return null;
    end$$ language plpgsql;

    -- Private function
    create or replace function normalize_server_arch(server_arch_in in varchar)
    returns varchar
    as $$
    declare
        suffix VARCHAR(128) := '-redhat-linux';
    begin
        if server_arch_in is NULL then
            return NULL;
        end if;
        if position('-' IN server_arch_in) > 0
        then
            -- Suffix already present
            return server_arch_in;
        end if;
        return server_arch_in || suffix;
    end$$ language plpgsql;

    --
    -- Raises: 
    --   server_arch_not_found
    --   no_subscribe_permissions
    create or replace function base_channel_for_release_arch(
        release_in in varchar,
        server_arch_in in varchar,
        org_id_in in numeric default -1,
        user_id_in in numeric default null
    ) returns numeric as $$
    declare
        server_arch varchar(256) := rhn_channel.normalize_server_arch(server_arch_in);
        server_arch_id numeric;
    begin
        -- Look up the server arch
            select id
              into server_arch_id
              from rhnServerArch
             where label = server_arch;
            if not found then
                perform rhn_exception.raise_exception('server_arch_not_found');
            end if;

        return rhn_channel.base_channel_rel_archid(release_in, server_arch_id,
            org_id_in, user_id_in);
    end$$ language plpgsql;

    create or replace function base_channel_rel_archid(
        release_in in varchar,
        server_arch_id_in in numeric,
        org_id_in in numeric default -1,
        user_id_in in numeric default null
    ) returns numeric as $$
    declare
        denied_channel_id numeric := null;
        valid_org_id numeric := org_id_in;
        valid_user_id numeric := user_id_in;
        channel_subscribable numeric;
    -- Cursor that fetches all the possible base channels for a
    -- (server_arch_id, release, org_id) combination
        base_channel_cursor cursor(
                release_in varchar,
                server_arch_id_in numeric,
                org_id_in numeric
        ) for
                select distinct c.*
                from    rhnOrgDistChannelMap                       odcm,
                                rhnServerChannelArchCompat      scac,
                                rhnChannel                                      c
                where   c.parent_channel is null
                        and c.id = odcm.channel_id
                        and c.channel_arch_id = odcm.channel_arch_id
                        and odcm.release = release_in
                        and odcm.for_org_id = org_id_in
                        and scac.server_arch_id = server_arch_id_in
                        and scac.channel_arch_id = c.channel_arch_id;

    begin
        if org_id_in = -1 and user_id_in is not null then
            -- Get the org id from the user id

                select org_id
                  into valid_org_id
                  from web_contact
                 where id = user_id_in;

                if not found then
                    -- User doesn't exist
                    -- XXX Only list public stuff for now
                    valid_user_id := null;
                    valid_org_id := -1;
                end if;
        end if;

        for c in base_channel_cursor(release_in, server_arch_id_in, valid_org_id)
        loop
            -- This row is a possible match
            if valid_user_id is null then
                -- User ID not specified, so no user to channel permissions to
                -- check
                return c.id;
            end if;

            -- Check user to channel permissions
            select rhn_channel.loose_user_role_check(c.id, user_id_in, 'subscribe')
              into channel_subscribable;

            if channel_subscribable = 1 then
                return c.id;
            end if;
                
            -- Base channel exists, but is not subscribable; keep trying
            denied_channel_id := c.id;
        end loop;
        
        if denied_channel_id is not null then
            perform rhn_exception.raise_exception('no_subscribe_permissions');
        end if;
        -- No base channel applies
        return NULL;
    end$$ language plpgsql;

    CREATE OR REPLACE FUNCTION clear_subscriptions(server_id_in IN NUMERIC, deleting_server IN NUMERIC default 0,
                                update_family_countsYN IN NUMERIC default 1 ) returns void
    AS $$
    declare
        server_channels cursor(server_id_in numeric) for
                select  s.org_id, sc.channel_id, cfm.channel_family_id
                from    rhnServer s,
                        rhnServerChannel sc,
                        rhnChannelFamilyMembers cfm
                where   s.id = server_id_in
                        and s.id = sc.server_id
                        and sc.channel_id = cfm.channel_id
                order by cfm.channel_family_id;
        last_channel_family_id rhnChannelFamilyMembers.channel_family_id%type := -1;
        last_channel_org_id    rhnServer.org_id%type := -1;
    BEGIN
        for channel in server_channels(server_id_in)
        loop
                perform rhn_channel.unsubscribe_server(server_id_in, channel.channel_id, 1, 1, deleting_server, 0);
                if update_family_countsYN > 0
                    and channel.channel_family_id != last_channel_family_id then
                    -- update family counts only once
                    -- after all channels with same family has been fetched
                    if last_channel_family_id != -1 then
                        perform rhn_channel.update_family_counts(channel.channel_family_id, channel.org_id);
                    end if;
                    last_channel_family_id := channel.channel_family_id;
                    last_channel_org_id    := channel.org_id;
                end if;
        end loop;
        if update_family_countsYN > 0 and last_channel_family_id != -1 then
            -- update the last family fetched
            perform rhn_channel.update_family_counts(last_channel_family_id, last_channel_org_id);
        end if;
    END$$ language plpgsql;

    CREATE OR REPLACE FUNCTION unsubscribe_server(server_id_in IN NUMERIC, channel_id_in NUMERIC, immediate_in NUMERIC default 1, unsubscribe_children_in numeric default 0,
                                 deleting_server in numeric default 0,
                                 update_family_countsYN in numeric default 1) returns void
    AS $$
    declare
        channel_family_id_val   NUMERIC;
        server_org_id_val       NUMERIC;
        available_subscriptions NUMERIC; 
        server_already_in_chan  BOOLEAN;
        channel_family_is_proxy cursor(channel_family_id_in numeric) for
                select  1
                from    rhnChannelFamily
                where   id = channel_family_id_in
                    and label = 'rhn-proxy';
        channel_family_is_satellite cursor(channel_family_id_in numeric) for
                select  1
                from    rhnChannelFamily
                where   id = channel_family_id_in
                    and label = 'rhn-satellite';
        child record;
    BEGIN
        -- In PostgreSQL recursion with opened cursors is not allowed so we use
        -- FOR IN SELECT form which is ok.
        FOR child IN select  c.id
                from    rhnChannel                      c,
                                rhnServerChannel        sc
                where   1=1
                        and c.parent_channel = channel_id_in
                        and c.id = sc.channel_id
                        and sc.server_id = server_id_in
        LOOP
            if unsubscribe_children_in = 1 then
                perform rhn_channel.unsubscribe_server(server_id_in,
                                                       child.id,
                                                       immediate_in,
                                                       unsubscribe_children_in,
                                                       deleting_server,
                                                       update_family_countsYN);
            else
                perform rhn_exception.raise_exception('channel_unsubscribe_child_exists');
            end if;
        END LOOP;
        
        server_already_in_chan := rhn_channel.check_server_subscription(server_id_in, channel_id_in);
    
        IF NOT server_already_in_chan
        THEN
            RETURN;
        END IF;
        
   if deleting_server = 0 then 
      insert into rhnServerHistory (id,server_id,summary,details) (
          select  nextval('rhn_event_id_seq'),
                server_id_in,
             'unsubscribed from channel ' || SUBSTR(c.label, 0, 106),
             c.label
          from    rhnChannel c
          where   c.id = channel_id_in
      );
   end if;
        
   DELETE FROM rhnServerChannel WHERE server_id = server_id_in AND channel_id = channel_id_in;

   if deleting_server = 0 then 
        perform queue_server(server_id_in, immediate_in);

        update rhnServer
           set channels_changed = current_timestamp
         where id = server_id_in;
   end if;

        channel_family_id_val := rhn_channel.family_for_channel(channel_id_in);
        IF channel_family_id_val IS NULL
        THEN
            perform rhn_exception.raise_exception('channel_unsubscribe_no_family');
        END IF;

        for ignore in channel_family_is_satellite(channel_family_id_val) loop
                delete from rhnSatelliteInfo where server_id = server_id_in;
        end loop;

        for ignore in channel_family_is_proxy(channel_family_id_val) loop
                delete from rhnProxyInfo where server_id = server_id_in;
        end loop;
        SELECT org_id INTO server_org_id_val
          FROM rhnServer
         WHERE id = server_id_in;
         
        if update_family_countsYN = 1 then
           perform rhn_channel.update_family_counts(channel_family_id_val, server_org_id_val);
        end if;
    END$$ language plpgsql;

    CREATE OR REPLACE FUNCTION family_for_channel(channel_id_in IN NUMERIC)
    RETURNS NUMERIC
    AS $$
    declare
        channel_family_id_val NUMERIC;
    BEGIN
        SELECT channel_family_id INTO channel_family_id_val
          FROM rhnChannelFamilyMembers
         WHERE channel_id = channel_id_in;

        IF NOT FOUND THEN
          RETURN NULL;
        END IF;
         
        RETURN channel_family_id_val;
    END$$ language plpgsql;

    CREATE OR REPLACE FUNCTION available_family_subscriptions(channel_family_id_in IN NUMERIC, org_id_in IN NUMERIC)
    RETURNS NUMERIC
    AS $$
    declare
        cfp record;
        current_members_val NUMERIC;
        max_members_val     NUMERIC;
        found               NUMERIC;
    BEGIN
        for cfp in SELECT * FROM rhnOrgChannelFamilyPermissions
	    WHERE channel_family_id = channel_family_id_in
	      AND org_id = org_id_in
        LOOP
            found := 1;
            current_members_val := cfp.current_members;
            max_members_val := cfp.max_members;
        END LOOP;

        -- not found: either the channel fam doesn't have an entry in cfp, or the org doesn't have access to it.
        -- either way, there are no available subscriptions

        IF found IS NULL
        THEN
            RETURN 0;
        END IF;

        -- null max members?  in that case, pass it on; NULL means infinite
        IF max_members_val IS NULL
        THEN
            RETURN NULL;
        END IF;

        -- otherwise, return the delta
        RETURN max_members_val - current_members_val;
    END$$ language plpgsql;

    CREATE OR REPLACE FUNCTION available_fve_family_subs(channel_family_id_in IN NUMERIC, org_id_in IN NUMERIC)
    RETURNS NUMERIC
    AS $$
    declare
        cfp record;
        fve_current_members_val NUMERIC;
        fve_max_members_val     NUMERIC;
        found               NUMERIC;
    BEGIN
        for cfp in SELECT * FROM rhnOrgChannelFamilyPermissions
	    WHERE channel_family_id = channel_family_id_in
	      AND org_id = org_id_in
        LOOP
            found := 1;
            fve_current_members_val := cfp.fve_current_members;
            fve_max_members_val := cfp.fve_max_members;
        END LOOP;

        -- not found: either the channel fam doesn't have an entry in cfp, or the org doesn't have access to it.
        -- either way, there are no available subscriptions
        
        IF found IS NULL
        THEN
            RETURN 0;
        END IF;

        -- null max members?  in that case, pass it on; NULL means infinite                     
        IF fve_max_members_val IS NULL
        THEN
            RETURN NULL;
        END IF;

        -- otherwise, return the delta  
        RETURN fve_max_members_val - fve_current_members_val;
    END$$ language plpgsql;
    
    -- *******************************************************************
    -- FUNCTION: channel_family_current_members
    -- Calculates and returns the actual count of systems consuming
    --   physical channel subscriptions.
    -- Called by: update_family_counts 
    --            rhn_entitlements.repoll_virt_guest_entitlements
    -- *******************************************************************
    create or replace function channel_family_current_members(channel_family_id_in IN NUMERIC,
                                            org_id_in IN NUMERIC)
    returns numeric
    as $$
    declare
        current_members_count numeric := 0;
    begin
        select  count(distinct server_id)
        into    current_members_count
          from  rhnChannelFamilyServerPhysical cfsp
         where  cfsp.channel_family_id = channel_family_id_in
           and  cfsp.customer_id = org_id_in;
        return current_members_count;
    end$$ language plpgsql;


    create or replace function cfam_curr_fve_members(
        channel_family_id_in IN NUMERIC,
        org_id_in IN NUMERIC)
    returns numeric
    as $$
    declare
        current_members_count numeric := 0;

    begin
        select count(distinct sc.server_id)
          into current_members_count
          from rhnServerChannel sc,
               rhnChannelFamilyMembers cfm,
               rhnServer s
         where s.org_id = org_id_in
           and s.id = sc.server_id
           and cfm.channel_family_id = channel_family_id_in
           and cfm.channel_id = sc.channel_id
           and exists (
                select 1
                  from rhnChannelFamilyServerFve cfsp
                 where cfsp.CHANNEL_FAMILY_ID = channel_family_id_in
                   and cfsp.server_id = s.id
                );

        return current_members_count;
    end$$ language plpgsql;
    CREATE OR REPLACE FUNCTION update_family_counts(channel_family_id_in IN NUMERIC, 
                                   org_id_in IN NUMERIC) returns void
    AS $$
    BEGIN
        update rhnPrivateChannelFamily
           set current_members = rhn_channel.channel_family_current_members(channel_family_id_in, org_id_in),
               fve_current_members = rhn_channel.cfam_curr_fve_members(channel_family_id_in,org_id_in)
         where org_id = org_id_in
           and channel_family_id = channel_family_id_in;
    END$$ language plpgsql;
    
    create or replace function update_group_family_counts(group_label_in IN VARCHAR,
                                   org_id_in IN NUMERIC)
    returns void
    as $$
    declare
        i record;
    BEGIN
        FOR i IN (
                SELECT DISTINCT CFM.channel_family_id, SG.org_id
                 FROM rhnChannelFamilyMembers CFM
                 JOIN rhnServerChannel SC
                   ON SC.channel_id = CFM.channel_id
                 JOIN rhnServerGroupMembers SGM
                   ON SC.server_id = SGM.server_id
                 JOIN rhnServerGroup SG
                   ON SGM.server_group_id = SG.id
                 JOIN rhnServerGroupType SGT
                   ON SG.group_type = SGT.id
                WHERE SGT.label = group_label_in
                  AND SG.org_id = org_id_in
                  AND SGT.is_base = 'Y'
        ) LOOP
            perform rhn_channel.update_family_counts(i.channel_family_id, i.org_id);
        END LOOP;
    END$$ language plpgsql;

    CREATE OR REPLACE FUNCTION available_chan_subscriptions(channel_id_in IN NUMERIC, 
                                          org_id_in IN NUMERIC)
    RETURNS NUMERIC
    AS $$
    declare
            channel_family_id_val NUMERIC;
    BEGIN
        SELECT channel_family_id INTO STRICT channel_family_id_val
            FROM rhnChannelFamilyMembers
            WHERE channel_id = channel_id_in;
         
            RETURN rhn_channel.available_family_subscriptions(
                           channel_family_id_val, org_id_in);
    END$$ language plpgsql;

    CREATE OR REPLACE FUNCTION available_fve_chan_subs(channel_id_in IN NUMERIC,
                                          org_id_in IN NUMERIC)
    RETURNS NUMERIC
    AS $$
    declare
            channel_family_id_val NUMERIC;
    BEGIN
        SELECT channel_family_id INTO STRICT channel_family_id_val
            FROM rhnChannelFamilyMembers
            WHERE channel_id = channel_id_in;

            RETURN rhn_channel.available_fve_family_subs(
                           channel_family_id_val, org_id_in);
    END$$ language plpgsql;

    create or replace function unsubscribe_server_from_family(server_id_in in numeric, 
                                             channel_family_id_in in numeric)
    returns void
    as $$
    begin
        delete
        from    rhnServerChannel rsc
        where   rsc.server_id = server_id_in
            and channel_id in (
                select  rcfm.channel_id
                from    rhnChannelFamilyMembers rcfm
                where   rcfm.channel_family_id = channel_family_id_in);
    end$$ language plpgsql;

    create or replace function get_org_id(channel_id_in in numeric)
    returns numeric
    as $$
    declare
        org_id_out numeric;
    begin
        select org_id into strict org_id_out
            from rhnChannel
            where id = channel_id_in;
         
            return org_id_out;
    end$$ language plpgsql;
    
    create or replace function get_cfam_org_access(cfam_id_in in numeric, org_id_in in numeric)
    returns numeric
    as $$
    begin
      if exists(
                        select  1
                        from    rhnOrgChannelFamilyPermissions cfp
                        where   cfp.org_id = org_id_in
      ) then
                return 1;
      else
                return 0;
      end if;
    end$$ language plpgsql;

    create or replace function get_org_access(channel_id_in in numeric, org_id_in in numeric)
    returns integer
    as $$
    begin
        -- the idea: if we get past this query, 
        -- the org has access to the channel, else not
        if exists(
        select 1
          from rhnChannelFamilyMembers CFM,
               rhnOrgChannelFamilyPermissions CFP
         where cfp.org_id = org_id_in
           and CFM.channel_family_id = CFP.channel_family_id
           and CFM.channel_id = channel_id_in
           and (CFP.max_members > 0 or CFP.max_members is null or CFP.fve_max_members > 0 or CFP.fve_max_members is null or CFP.org_id = 1) )
        then
          return 1;
        else
          return 0;
        end if;
    end$$ language plpgsql;
    
    -- check if a user has a given role, or if such a role is inferrable
    -- returns NULL if OK, error message otherwise
    create or replace function user_role_check_debug(channel_id_in in numeric, 
                                   user_id_in in numeric, 
                                   role_in in varchar)
    returns varchar
    as $$
    declare
        org_id numeric;
    begin
        org_id := rhn_user.get_org_id(user_id_in);

        -- channel might be shared
        if role_in = 'subscribe' and
           rhn_channel.shared_user_role_check(channel_id_in, user_id_in, role_in) = 1 then
            return NULL;
        end if;
        
        if role_in = 'manage' and 
           COALESCE(rhn_channel.get_org_id(channel_id_in), -1) <> org_id then
               return 'channel_not_owned';
        end if;
        
        if role_in = 'subscribe' and 
           rhn_channel.get_org_access(channel_id_in, org_id) = 0 then
                return 'channel_not_available';
        end if;
        
        -- channel admins have all roles
        if rhn_user.check_role_implied(user_id_in, 'channel_admin') = 1 then
            return NULL;
        end if;

        -- the subscribe permission is inferred 
        -- UNLESS the not_globally_subscribable flag is set
        if role_in = 'subscribe'
        then
            if rhn_channel.org_channel_setting(channel_id_in, 
                       org_id,
                       'not_globally_subscribable') = 0 then
                return NULL;
            end if;
        end if;
        
        -- all other roles (manage right now) are explicitly granted    
        if rhn_channel.direct_user_role_check(channel_id_in,
                                              user_id_in, role_in) = 1 then
            return NULL;
        end if;
        return 'direct_permission';
    end$$ language plpgsql;
    
    -- same as above, but with 1/0 output; useful in views, etc
    create or replace function user_role_check(channel_id_in in numeric, user_id_in in numeric, role_in in varchar)
    returns numeric
    as $$
    begin
        if rhn_channel.user_role_check_debug(channel_id_in,
                                             user_id_in, role_in) is NULL then
            return 1;
        else
            return 0;
        end if;
    end$$ language plpgsql;

    --
    -- For multiorg phase II, this function simply checks to see if the user's
    -- has a trust relationship that includes this channel by id.
    --
    create or replace function shared_user_role_check(channel_id in numeric, user_id in numeric, role in varchar)
    returns numeric
    as $$
    declare
      n numeric;
      oid numeric;
    begin
      oid := rhn_user.get_org_id(user_id);
      select 1 into n
      from rhnSharedChannelView s
      where s.id = channel_id and s.org_trust_id = oid;

      if not found then
        return 0;
      end if;

      return 1;
    end$$ language plpgsql;

    -- same as above, but returns 1 if user_id_in is null
    -- This is useful in queries where user_id is not specified
    create or replace function loose_user_role_check(channel_id_in in numeric, user_id_in in numeric, role_in in varchar)
    returns numeric
    as $$
    begin
        if user_id_in is null then
            return 1;
        end if;
        return rhn_channel.user_role_check(channel_id_in, user_id_in, role_in);
    end$$ language plpgsql;
    
    -- directly checks the table, no inferred permissions
    create or replace function direct_user_role_check(channel_id_in in numeric, user_id_in in numeric, role_in in varchar)
    returns numeric
    as $$
    declare
        throwaway numeric;
    begin
        -- the idea: if we get past this query, the user has the role, else no
        select 1 into throwaway
          from rhnChannelPermissionRole CPR,
               rhnChannelPermission CP
         where CP.user_id = user_id_in
           and CP.channel_id = channel_id_in
           and CPR.label = role_in
           and CP.role_id = CPR.id;

      if not found then
        return 0;
      end if;
           
      return 1;
    end$$ language plpgsql;
    
    -- check if an org has a certain setting
    create or replace function org_channel_setting(channel_id_in in numeric, org_id_in in numeric, setting_in in varchar)
    returns numeric
    as $$
    declare
        throwaway numeric;
    begin
        -- the idea: if we get past this query, the org has the setting
        select 1 into throwaway
          from rhnOrgChannelSettingsType OCST,
               rhnOrgChannelSettings OCS
         where OCS.org_id = org_id_in
           and OCS.channel_id = channel_id_in
           and OCST.label = setting_in
           and OCS.setting_id = OCST.id;

      if not found then
        return 0;
      end if;

      return 1;
    end$$ language plpgsql;
    
    CREATE OR REPLACE FUNCTION channel_priority(channel_id_in IN numeric) 
    RETURNS numeric
    AS $$
    declare
         channel_name varchar(256);
         priority numeric;
         end_of_life_val timestamptz;
         org_id_val numeric;
    BEGIN

        select name, end_of_life, org_id
        into channel_name, end_of_life_val, org_id_val
        from rhnChannel
        where id = channel_id_in;

        if end_of_life_val is not null then
          return -400;
        end if;

        if channel_name like 'Red Hat Enterprise Linux%' or channel_name like 'RHEL%' then
          priority := 1000;
          if channel_name not like '%Beta%' then
            priority := priority + 1000;
          end if;

          priority := priority +
            case
              when channel_name like '%v. 5%' then 600
              when channel_name like '%v. 4%' then 500
              when channel_name like '%v. 3%' then 400
              when channel_name like '%v. 2%' then 300
              when channel_name like '%v. 1%' then 200
              else 0
            end;

          priority := priority +
            case
              when channel_name like 'Red Hat Enterprise Linux (v. 5%' then 60
              when (channel_name like '%AS%' and channel_name not like '%Extras%') then 50
              when (channel_name like '%ES%' and channel_name not like '%Extras%') then 40
              when (channel_name like '%WS%' and channel_name not like '%Extras%') then 30
              when (channel_name like '%Desktop%' and channel_name not like '%Extras%') then 20
              when channel_name like '%Extras%' then 10
              else 0
            end; 

          priority := priority +
            case
              when channel_name like '%)' then 5
              else 0
            end;

          priority := priority +
            case
              when channel_name like '%32-bit x86%' then 4
              when channel_name like '%64-bit Intel Itanium%' then 3
              when channel_name like '%64-bit AMD64/Intel EM64T%' then 2
              else 0
            end;
        elsif channel_name like 'Red Hat Desktop%' then
            priority := 900;

            if channel_name not like '%Beta%' then
               priority := priority + 50;
            end if;

          priority := priority +
            case
              when channel_name like '%v. 4%' then 40
              when channel_name like '%v. 3%' then 30
              when channel_name like '%v. 2%' then 20
              when channel_name like '%v. 1%' then 10
              else 0
            end;
            
          priority := priority +
            case
              when channel_name like '%32-bit x86%' then 4
              when channel_name like '%64-bit Intel Itanium%' then 3
              when channel_name like '%64-bit AMD64/Intel EM64T%' then 2
              else 0
            end;
         
        elsif org_id_val is not null then
          priority := 600;
        else
          priority := 500;
        end if;
      
      return -priority;

    end$$ language plpgsql;

    -- right now this only does the accounting changes; the cascade
    -- actually does the rhnServerChannel delete.
    create or replace function delete_server_channels(server_id_in in numeric) returns void
    as $$
    begin
        update  rhnPrivateChannelFamily
        set     current_members = current_members -1
        where   org_id in (
                        select  org_id
                        from    rhnServer
                        where   id = server_id_in
                )
                and channel_family_id in (
                        select  rcfm.channel_family_id
                        from    rhnChannelFamilyMembers rcfm,
                                rhnServerChannel rsc
                        where   rsc.server_id = server_id_in
                                and rsc.channel_id = rcfm.channel_id
                and not exists (
                    select 1
                    from
                        rhnChannelFamilyVirtSubLevel cfvsl,
                        rhnSGTypeVirtSubLevel sgtvsl,
                        rhnServerEntitlementView sev,
                        rhnVirtualInstance vi
                    where
                        -- system is a virtual instance
                        vi.virtual_system_id = server_id_in
                        and vi.host_system_id = sev.server_id
                        -- system's host has a virt ent
                        and sev.label in ('virtualization_host',
                                          'virtualization_host_platform')
                        and sev.server_group_type_id = 
                            sgtvsl.server_group_type_id
                        -- the host's virt ent grants a cf virt sub level
                        and sgtvsl.virt_sub_level_id = cfvsl.virt_sub_level_id
                        -- the cf is in that virt sub level
                        and cfvsl.channel_family_id = rcfm.channel_family_id
                    )
                );
    end$$ language plpgsql;

    -- this could certainly be optimized to do updates if needs be
    create or replace function refresh_newest_package(channel_id_in in numeric,
                                      caller_in in varchar default '(unknown)',
                                      package_name_id_in in numeric default null)
    returns void
    as $$
    -- procedure refreshes rows for name_id = package_name_id_in or
    -- all rows if package_name_id_in is null
    begin
        delete from rhnChannelNewestPackage
              where channel_id = channel_id_in
                and (package_name_id_in is null
                     or name_id = package_name_id_in);
        insert into rhnChannelNewestPackage
                (channel_id, name_id, evr_id, package_id, package_arch_id)
                (select channel_id,
                        name_id, evr_id,
                        package_id, package_arch_id
                   from rhnChannelNewestPackageView
                  where channel_id = channel_id_in
                    and (package_name_id_in is null
                         or name_id = package_name_id_in)
                );
        insert into rhnChannelNewestPackageAudit (channel_id, caller)
             values (channel_id_in, caller_in);
        update rhnChannel
           set last_modified = greatest(current_timestamp,
                                        last_modified + interval '1 second')
         where id = channel_id_in;
    end$$ language plpgsql;

   create or replace function update_channel ( channel_id_in in numeric, invalidate_ss in numeric default 0, 
                              date_to_use in timestamptz default current_timestamp ) returns void
   as $$
   declare
   channel_last_modified timestamptz;
   last_modified_value timestamptz;

   snapshots cursor for
   select  snapshot_id id
   from    rhnSnapshotChannel
   where   channel_id = channel_id_in;

   begin

      select last_modified
      into channel_last_modified
      from rhnChannel
      where id = channel_id_in;
  
      last_modified_value := date_to_use;

      if last_modified_value <= channel_last_modified then
          last_modified_value := last_modified_value + interval '1 second';
      end if;

      update rhnChannel set last_modified = last_modified_value
      where id = channel_id_in;

      if invalidate_ss = 1 then 
        for snapshot in snapshots loop
            update rhnSnapshot
            set invalid = lookup_snapshot_invalid_reason('channel_modified')
            where id = snapshot.id;
        end loop;
      end if;

   end$$ language plpgsql;

   create or replace function update_channels_by_package ( package_id_in in numeric, date_to_use in timestamptz default current_timestamp ) returns void
   as $$
   declare
   channels cursor for
   select channel_id
   from rhnChannelPackage
   where package_id = package_id_in
   order by channel_id;

   begin
      for channel in channels loop
         -- we want to invalidate the snapshot assocated with the channel when we
         -- do this b/c we know we've added or removed or packages
         perform rhn_channel.update_channel ( channel.channel_id, 1, date_to_use );
      end loop;
   end$$ language plpgsql;

   
   create or replace function update_channels_by_errata ( errata_id_in numeric, date_to_use in timestamptz default current_timestamp ) returns void
   as $$
   declare
   channels cursor for
   select channel_id
   from rhnChannelErrata
   where errata_id = errata_id_in
   order by channel_id;

   begin
      for channel in channels loop
         -- we won't invalidate snapshots, b/c just changing the errata associated with
         -- a channel shouldn't invalidate snapshots
         perform rhn_channel.update_channel ( channel.channel_id, 0, date_to_use );
      end loop;
   end$$ language plpgsql;

   create or replace function update_needed_cache(channel_id_in in numeric) returns void
   as $$
   declare
   server record;
   begin
      -- we intentionaly do a loop here instead of one huge select
      -- b/c we want to break update into smaller transaction to unblock other sessions
      -- querying rhnServerNeededCache
      for server in (
                select sc.server_id as id
                  from rhnServerChannel sc
                 where sc.channel_id = channel_id_in
                 order by id asc
      ) loop
         perform rhn_server.update_needed_cache(server.id);
      end loop;
   end$$ language plpgsql;

    create or replace function set_comps(channel_id_in in numeric, path_in in varchar, timestamp_in in varchar) returns void
    as $$
    declare
    row record;
    begin
        for row in (
            select relative_filename, last_modified
            from rhnChannelComps
            where channel_id = channel_id_in
            ) loop
            if row.relative_filename = path_in
                and row.last_modified = to_timestamp(timestamp_in, 'YYYYMMDDHH24MISS') then
                return;
            end if;
        end loop;
        delete from rhnChannelComps
        where channel_id = channel_id_in;
        insert into rhnChannelComps (id, channel_id, relative_filename, last_modified, created, modified)
        values (sequence_nextval('rhn_channelcomps_id_seq'), channel_id_in, path_in, to_timestamp(timestamp_in, 'YYYYMMDDHH24MISS'), current_timestamp, current_timestamp);
    end$$ language plpgsql;

-- restore the original setting
update pg_settings set setting = overlay( setting placing '' from 1 for (length('rhn_channel')+1) ) where name = 'search_path';
 07070100000805000081B400000000000000000000000167AE11140000007A000000000000000000000000000000000000006200000000susemanager-schema/upgrade/spacewalk-schema-2.2-to-spacewalk-schema-2.3/008-update_fve_counts.sql update rhnPrivateChannelFamily
   set fve_current_members = rhn_channel.cfam_curr_fve_members(channel_family_id,org_id);

  07070100000806000081B400000000000000000000000167AE111400001C48000000000000000000000000000000000000006A00000000susemanager-schema/upgrade/spacewalk-schema-2.2-to-spacewalk-schema-2.3/009-rhnChildChannelArchCompat.sql --
-- Copyright (c) 2014 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--

CREATE TABLE rhnChildChannelArchCompat
(
    parent_arch_id  NUMERIC NOT NULL
                         CONSTRAINT rhn_ccac_paid_fk
                             REFERENCES rhnChannelArch (id),
    child_arch_id  NUMERIC NOT NULL
                         CONSTRAINT rhn_ccac_caid_fk
                             REFERENCES rhnChannelArch (id),
    created          TIMESTAMPTZ
                         DEFAULT (current_timestamp) NOT NULL,
    modified         TIMESTAMPTZ
                         DEFAULT (current_timestamp) NOT NULL
)

;

CREATE INDEX rhn_ccac_paid_caid
    ON rhnChildChannelArchCompat (parent_arch_id, child_arch_id)
    ;

ALTER TABLE rhnChildChannelArchCompat
    ADD CONSTRAINT rhn_ccac_paid_caid_uq UNIQUE (parent_arch_id, child_arch_id);


insert into rhnChildChannelArchCompat (parent_arch_id, child_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-ia32'), LOOKUP_CHANNEL_ARCH('channel-ia32'));

insert into rhnChildChannelArchCompat (parent_arch_id, child_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-ia64'), LOOKUP_CHANNEL_ARCH('channel-ia32'));

insert into rhnChildChannelArchCompat (parent_arch_id, child_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-ia64'), LOOKUP_CHANNEL_ARCH('channel-ia64'));

insert into rhnChildChannelArchCompat (parent_arch_id, child_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-ia32-deb'), LOOKUP_CHANNEL_ARCH('channel-ia32-deb'));

insert into rhnChildChannelArchCompat (parent_arch_id, child_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-ia64-deb'), LOOKUP_CHANNEL_ARCH('channel-ia32-deb'));

insert into rhnChildChannelArchCompat (parent_arch_id, child_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-ia64-deb'), LOOKUP_CHANNEL_ARCH('channel-ia64-deb'));

insert into rhnChildChannelArchCompat (parent_arch_id, child_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-sparc'), LOOKUP_CHANNEL_ARCH('channel-sparc'));

insert into rhnChildChannelArchCompat (parent_arch_id, child_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-sparc'), LOOKUP_CHANNEL_ARCH('channel-sparc-sun-solaris'));

insert into rhnChildChannelArchCompat (parent_arch_id, child_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-sparc'), LOOKUP_CHANNEL_ARCH('channel-i386-sun-solaris'));

insert into rhnChildChannelArchCompat (parent_arch_id, child_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-sparc-deb'), LOOKUP_CHANNEL_ARCH('channel-sparc-deb'));

insert into rhnChildChannelArchCompat (parent_arch_id, child_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-alpha'), LOOKUP_CHANNEL_ARCH('channel-alpha'));

insert into rhnChildChannelArchCompat (parent_arch_id, child_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-alpha-deb'), LOOKUP_CHANNEL_ARCH('channel-alpha-deb'));

insert into rhnChildChannelArchCompat (parent_arch_id, child_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-s390'), LOOKUP_CHANNEL_ARCH('channel-s390'));

insert into rhnChildChannelArchCompat (parent_arch_id, child_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-s390-deb'), LOOKUP_CHANNEL_ARCH('channel-s390-deb'));

insert into rhnChildChannelArchCompat (parent_arch_id, child_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-s390x'), LOOKUP_CHANNEL_ARCH('channel-s390'));

insert into rhnChildChannelArchCompat (parent_arch_id, child_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-s390x'), LOOKUP_CHANNEL_ARCH('channel-s390x'));

insert into rhnChildChannelArchCompat (parent_arch_id, child_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-iSeries'), LOOKUP_CHANNEL_ARCH('channel-iSeries'));

insert into rhnChildChannelArchCompat (parent_arch_id, child_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-pSeries'), LOOKUP_CHANNEL_ARCH('channel-pSeries'));

insert into rhnChildChannelArchCompat (parent_arch_id, child_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-x86_64'), LOOKUP_CHANNEL_ARCH('channel-ia32'));

insert into rhnChildChannelArchCompat (parent_arch_id, child_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-x86_64'), LOOKUP_CHANNEL_ARCH('channel-x86_64'));

insert into rhnChildChannelArchCompat (parent_arch_id, child_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-amd64-deb'), LOOKUP_CHANNEL_ARCH('channel-ia32-deb'));

insert into rhnChildChannelArchCompat (parent_arch_id, child_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-amd64-deb'), LOOKUP_CHANNEL_ARCH('channel-amd64-deb'));

insert into rhnChildChannelArchCompat (parent_arch_id, child_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-ppc'), LOOKUP_CHANNEL_ARCH('channel-ppc'));

insert into rhnChildChannelArchCompat (parent_arch_id, child_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-powerpc-deb'), LOOKUP_CHANNEL_ARCH('channel-powerpc-deb'));

insert into rhnChildChannelArchCompat (parent_arch_id, child_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-arm'), LOOKUP_CHANNEL_ARCH('channel-arm'));

insert into rhnChildChannelArchCompat (parent_arch_id, child_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-armhfp'), LOOKUP_CHANNEL_ARCH('channel-armhfp'));

insert into rhnChildChannelArchCompat (parent_arch_id, child_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-arm-deb'), LOOKUP_CHANNEL_ARCH('channel-arm-deb'));

insert into rhnChildChannelArchCompat (parent_arch_id, child_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-mips-deb'), LOOKUP_CHANNEL_ARCH('channel-mips-deb'));

insert into rhnChildChannelArchCompat (parent_arch_id, child_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-sparc-sun-solaris'), LOOKUP_CHANNEL_ARCH('channel-sparc'));

insert into rhnChildChannelArchCompat (parent_arch_id, child_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-sparc-sun-solaris'), LOOKUP_CHANNEL_ARCH('channel-sparc-sun-solaris'));

insert into rhnChildChannelArchCompat (parent_arch_id, child_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-sparc-sun-solaris'), LOOKUP_CHANNEL_ARCH('channel-i386-sun-solaris'));

insert into rhnChildChannelArchCompat (parent_arch_id, child_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-i386-sun-solaris'), LOOKUP_CHANNEL_ARCH('channel-sparc'));

insert into rhnChildChannelArchCompat (parent_arch_id, child_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-i386-sun-solaris'), LOOKUP_CHANNEL_ARCH('channel-sparc-sun-solaris'));

insert into rhnChildChannelArchCompat (parent_arch_id, child_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-i386-sun-solaris'), LOOKUP_CHANNEL_ARCH('channel-i386-sun-solaris'));

insert into rhnChildChannelArchCompat (parent_arch_id, child_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-aarch64'), LOOKUP_CHANNEL_ARCH('channel-aarch64'));

insert into rhnChildChannelArchCompat (parent_arch_id, child_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-ppc64le'), LOOKUP_CHANNEL_ARCH('channel-ppc64le'));

commit;

07070100000807000081B400000000000000000000000167AE11140000014D000000000000000000000000000000000000006800000000susemanager-schema/upgrade/spacewalk-schema-2.2-to-spacewalk-schema-2.3/010-rhnDistChannelMap_index.sql   
alter table rhnDistChannelMap drop constraint rhn_dcm_release_caid_oid_uq;

create unique index rhn_dcm_rel_caid_oid_uq_idx
    on rhnDistChannelMap (release, channel_arch_id, org_id)
 where org_id is not null;

create unique index rhn_dcm_rel_caid_uq_idx
    on rhnDistChannelMap (release, channel_arch_id)
 where org_id is null;

   07070100000808000081B400000000000000000000000167AE1114000003CE000000000000000000000000000000000000006500000000susemanager-schema/upgrade/spacewalk-schema-2.2-to-spacewalk-schema-2.3/011-rhnWebContactEnabled.sql  --
-- Copyright (c) 2008--2014 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

create or replace view
rhnWebContactEnabled
as
select
   wcon.id,
   wcon.org_id,
   wcon.login,
   wcon.login_uc,
   wcon.password,
   wcon.oracle_contact_id,
   wcon.created,
   wcon.modified,
   wcon.ignore_flag,
   wcon.read_only
from
   web_contact wcon left join rhnWebContactDisabled wcond on wcond.id = wcon.id
   where wcond.id is null;
  07070100000809000081B400000000000000000000000167AE1114000000B0000000000000000000000000000000000000006B00000000susemanager-schema/upgrade/spacewalk-schema-2.2-to-spacewalk-schema-2.3/012-rhnServerPackageArchCompat.sql    insert into rhnServerPackageArchCompat
(server_arch_id, package_arch_id, preference) values
(LOOKUP_SERVER_ARCH('aarch64-redhat-linux'), LOOKUP_PACKAGE_ARCH('noarch'), 1000);

0707010000080A000081B400000000000000000000000167AE111400000047000000000000000000000000000000000000006600000000susemanager-schema/upgrade/spacewalk-schema-2.2-to-spacewalk-schema-2.3/013-rhnKSInstallType-data.sql UPDATE rhnKSInstallType SET label = 'fedora18' WHERE label = 'fedora';
 0707010000080B000081B400000000000000000000000167AE11140000004E000000000000000000000000000000000000007700000000susemanager-schema/upgrade/spacewalk-schema-2.2-to-spacewalk-schema-2.3/014-inc-length-rhnContentSource-source_url.sql    
ALTER TABLE rhnContentSource
    ALTER COLUMN source_url TYPE varchar(2048);
  0707010000080C000081B400000000000000000000000167AE11140000030C000000000000000000000000000000000000008E00000000susemanager-schema/upgrade/spacewalk-schema-2.2-to-spacewalk-schema-2.3/015-rhnServerServerGroupArchCompat-missing-virt-platform-mappings.sql insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type) select
LOOKUP_SERVER_ARCH('aarch64-redhat-linux'), LOOKUP_SG_TYPE('virtualization_host_platform') from dual
where not exists (select 1 from rhnServerServerGroupArchCompat where server_arch_id = LOOKUP_SERVER_ARCH('aarch64-redhat-linux') and server_group_type = LOOKUP_SG_TYPE('virtualization_host_platform'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type) select
LOOKUP_SERVER_ARCH('ppc64le-redhat-linux'), LOOKUP_SG_TYPE('virtualization_host_platform') from dual
where not exists (select 1 from rhnServerServerGroupArchCompat where server_arch_id = LOOKUP_SERVER_ARCH('ppc64le-redhat-linux') and server_group_type = LOOKUP_SG_TYPE('virtualization_host_platform'));

0707010000080D000081B400000000000000000000000167AE1114000028FE000000000000000000000000000000000000005E00000000susemanager-schema/upgrade/spacewalk-schema-2.2-to-spacewalk-schema-2.3/016-delete_server.sql --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
-- This deletes a server.  All codepaths which delete servers should hit this
-- or delete_server_bulk()

create or replace
function delete_server (
        server_id_in in numeric
) returns void 
as
$$
declare
         servergroups cursor for
                select  server_id, server_group_id
                from    rhnServerGroupMembers sgm
                where   sgm.server_id = server_id_in;

         configchannels cursor for
                select  cc.id
                from    rhnConfigChannel cc,
                        rhnConfigChannelType cct,
                        rhnServerConfigChannel scc
                where   1=1
                        and scc.server_id = server_id_in
                        and scc.config_channel_id = cc.id
                        -- these config channel types are reserved
                        -- for use by a single server, so we don't
                        -- need to check for other servers subscribed
                        and cct.label in
                                ('local_override','server_import')
                        and cct.id = cc.confchan_type_id;

    is_virt boolean;
begin
        perform rhn_channel.delete_server_channels(server_id_in);
        -- rhn_channel.clear_subscriptions(server_id_in);

        -- filelists
        delete from rhnFileList where id in (
	select	spfl.file_list_id
	  from	rhnServerPreserveFileList spfl
	 where	spfl.server_id = server_id_in
			and not exists (
				select	1
				from	rhnServerPreserveFileList
				where	file_list_id = spfl.file_list_id
					and server_id != server_id_in
				union all
				select	1
				from	rhnKickstartPreserveFileList
				where	file_list_id = spfl.file_list_id
			)
        );

	for configchannel in configchannels loop
		perform rhn_config.delete_channel(configchannel.id);
	end loop;

      is_virt := exists (
       select 1
        from rhnServerEntitlementView
       where server_id = server_id_in
         and label in ('virtualization_host', 'virtualization_host_platform')
      );

	for sgm in servergroups loop
		perform rhn_server.delete_from_servergroup(
			sgm.server_id, sgm.server_group_id);
	end loop;

    if is_virt then
        perform rhn_entitlements.repoll_virt_guest_entitlements(server_id_in);
    end if;

        -- we're handling this instead of letting an "on delete
        -- set null" do it so that we don't run the risk
        -- of setting off the triggers and killing us with a
        -- mutating table

        -- this is merge of two single updates:
        --  update ... set old_server_id = null where old_server_id = server_id_in;
        --  update ... set new_server_id = null where new_server_id = server_id_in;
        -- so we scan rhnKickstartSession table only once
        update rhnKickstartSession
                set old_server_id = case when old_server_id = server_id_in then null else old_server_id end,
                    new_server_id = case when new_server_id = server_id_in then null else new_server_id end
                where old_server_id = server_id_in
                   or new_server_id = server_id_in;

        perform rhn_channel.clear_subscriptions(server_id_in, 1, 1);

        -- A little complicated here, but the goal is to
        -- delete records from rhnVirtualInstace only if we don't
        -- care about them anymore.  We don't care about records
        -- in rhnVirtualInstance if we are deleting the host
        -- system and the virtual system is already null, or
        -- vice-versa.  We *do* care about them if either the
        -- host or virtual system is still registered because we
        -- still want them to show up in the UI.
    -- If there's a newer row in rhnVirtualInstance with the same
    -- uuid, this guest must have been re-registered, so we can clean
    -- this data up.

        delete from rhnVirtualInstance vi
              where (host_system_id = server_id_in and virtual_system_id is null)
                 or (virtual_system_id = server_id_in and host_system_id is null)
                 or (vi.virtual_system_id = server_id_in and vi.modified < (select max(vi2.modified)
                    from rhnVirtualInstance vi2 where vi2.uuid = vi.uuid));

        -- this is merge of two single updates:
        --  update ... set host_system_id = null where host_system_id = server_id_in;
        --  update ... set virtual_system_id = null where virtual_system_id = server_id_in;
        -- so we scan rhnVirtualInstance table only once
        update rhnVirtualInstance
           set host_system_id = case when host_system_id = server_id_in then null else host_system_id end,
               virtual_system_id = case when virtual_system_id = server_id_in then null else virtual_system_id end
         where host_system_id = server_id_in
            or virtual_system_id = server_id_in;

        -- this is merge of two single updates:
        --  update ... set old_host_system_id = null when old_host_system_id = server_id_in;
        --  update ... set new_host_system_id = null when new_host_system_id = server_id_in;
        -- so we scan rhnVirtualInstanceEventLog table only once
        update rhnVirtualInstanceEventLog
           set old_host_system_id = case when old_host_system_id = server_id_in then null else old_host_system_id end,
               new_host_system_id = case when new_host_system_id = server_id_in then null else new_host_system_id end
         where old_host_system_id = server_id_in
            or new_host_system_id = server_id_in;

        -- We're deleting everything with a foreign key to rhnServer
        -- here, now.  I'm hoping this will help aleviate our deadlock
        -- problem.

        delete from rhnActionConfigChannel where server_id = server_id_in;
        delete from rhnActionConfigRevision where server_id = server_id_in;
        delete from rhnActionPackageRemovalFailure where server_id = server_id_in;
        delete from rhnClientCapability where server_id = server_id_in;
        delete from rhnCpu where server_id = server_id_in;
        -- there's still a cascade here, because the constraint keeps the
        -- table locked for too long to rebuild it.  Ugh...
        delete from rhnDevice where server_id = server_id_in;
        delete from rhnProxyInfo where server_id = server_id_in;
        delete from rhnRam where server_id = server_id_in;
        delete from rhnRegToken where server_id = server_id_in;
        delete from rhnSatelliteInfo where server_id = server_id_in;
        -- this cascades to rhnActionConfigChannel and rhnActionConfigFileName
        delete from rhnServerAction where server_id = server_id_in;
        delete from rhnServerActionPackageResult where server_id = server_id_in;
        delete from rhnServerActionScriptResult where server_id = server_id_in;
        delete from rhnServerActionVerifyResult where server_id = server_id_in;
        delete from rhnServerActionVerifyMissing where server_id = server_id_in;
        -- counts are handled above.  this should be a delete_ function.
        delete from rhnServerChannel where server_id = server_id_in;
        delete from rhnServerConfigChannel where server_id = server_id_in;
        delete from rhnServerCustomDataValue where server_id = server_id_in;
        delete from rhnServerDMI where server_id = server_id_in;
        delete from rhnServerEvent where server_id = server_id_in;
        delete from rhnServerHistory where server_id = server_id_in;
        delete from rhnServerInfo where server_id = server_id_in;
        delete from rhnServerInstallInfo where server_id = server_id_in;
        delete from rhnServerLocation where server_id = server_id_in;
        delete from rhnServerLock where server_id = server_id_in;
        delete from rhnServerNeededCache where server_id = server_id_in;
        delete from rhnServerNetwork where server_id = server_id_in;
        delete from rhnServerNotes where server_id = server_id_in;
        -- I'm not removing the foreign key from rhnServerPackage; that'll
        -- take forever.  Do the delete anyway.
        delete from rhnServerPackage where server_id = server_id_in;
        delete from rhnServerTokenRegs where server_id = server_id_in;
        delete from rhnSnapshotTag where server_id = server_id_in;
        -- this cascades to:
        --   rhnSnapshotChannel, rhnSnapshotConfigChannel, rhnSnapshotPackage,
        --   rhnSnapshotConfigRevision, rhnSnapshotServerGroup,
        --   rhnSnapshotTag.
        -- We may want to consider delete_snapshot() at some point, but
        --   I don't think we need to yet.
        delete from rhnSnapshot where server_id = server_id_in;
        delete from rhnUserServerPrefs where server_id = server_id_in;
        -- hrm, this one's interesting... we _probably_ should delete
        -- everything for the parent server_id when we delete the proxy,
        -- but we don't currently.
        delete from rhnServerPath where server_id_in in (server_id, proxy_server_id);
        delete from rhnUserServerPerms where server_id = server_id_in;

        delete from rhnServerNetInterface where server_id = server_id_in;

        delete from rhnServerUuid where server_id = server_id_in;

        delete from rhnPushClient where server_id = server_id_in;

        -- now get rhnServer itself.
        delete
        from    rhnServer
                where id = server_id_in;

        delete
        from    rhnSet
        where   1=1
                and user_id in (
                        select  wc.id
                        from    rhnServer rs,
                                web_contact wc
                        where   rs.id = server_id_in
                                and rs.org_id = wc.org_id
                )
                and label = 'system_list'
                and element = server_id_in;
end;
$$
language plpgsql;

  0707010000080E000081B400000000000000000000000167AE111400000053000000000000000000000000000000000000005C00000000susemanager-schema/upgrade/spacewalk-schema-2.2-to-spacewalk-schema-2.3/016-rhnFeatures.sql   delete from rhnFeature where label = 'ftr_schedule_probe' or label = 'ftr_probes';
 0707010000080F000081B400000000000000000000000167AE1114000106BF000000000000000000000000000000000000006500000000susemanager-schema/upgrade/spacewalk-schema-2.2-to-spacewalk-schema-2.3/016-rhn_entitlements.pkb.sql  --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--

-- create schema rhn_entitlements;

-- setup search_path so that these functions are created in appropriate schema.
update pg_settings set setting = 'rhn_entitlements,' || setting where name = 'search_path';

   create or replace function find_compatible_sg (
      server_id_in in numeric,
      type_label_in in varchar
   )
   returns numeric
as $$
    declare
      servergroups cursor for
         select sg.id
           from rhnServerGroupType             sgt,
                rhnServerGroup                 sg,
                rhnServer                     s,
                rhnServerServerGroupArchCompat ssgac
          where s.id = server_id_in
            and s.org_id = sg.org_id
            and sgt.label = type_label_in
            and sg.group_type = sgt.id
            and ssgac.server_group_type = sgt.id
            and ssgac.server_arch_id = s.server_arch_id
            and not exists ( 
                     select 1
                      from rhnServerGroupMembers sgm
                     where sgm.server_group_id = sg.id 
                       and sgm.server_id = s.id);

         
   begin
      for servergroup in servergroups loop
         return servergroup.id;
      end loop;

      --no servergroup found
      return NULL;
   end$$
language plpgsql;

    -- *******************************************************************
    -- PROCEDURE: remove_org_entitlements
    --
    -- Removes both system entitlements and channel subscriptions
    -- that are currently assigned to an org and re-assigns to the
    -- master org (org_id = 1).
    --
    -- When we call this we expect everything to already be unentitled
    -- which shoul be handled by delete_org.
    --
    -- Called by: delete_org
    -- *******************************************************************
    create or replace function remove_org_entitlements (
        org_id_in numeric
    ) returns void
as $$
    declare
        system_ents cursor for
        select sg.id, sg.max_members, sg.group_type
        from rhnServerGroup sg
        where group_type is not null
          and org_id = org_id_in;

        channel_subs cursor for
        select pcf.channel_family_id, pcf.max_members
        from rhnChannelFamily cf,
             rhnPrivateChannelFamily pcf
        where pcf.org_id = org_id_in
          and pcf.channel_family_id = cf.id
          and cf.org_id is null;

    begin

        for system_ent in system_ents loop
            update rhnServerGroup
            set max_members = max_members + system_ent.max_members
            where org_id = 1
              and group_type = system_ent.group_type;
        end loop;

        update rhnServerGroup
        set max_members = 0
        where org_id = org_id_in;

        for channel_sub in channel_subs loop
            update rhnPrivateChannelFamily
            set max_members = max_members + channel_sub.max_members
            where org_id = 1
              and channel_family_id = channel_sub.channel_family_id;
        end loop;
        
        update rhnPrivateChannelFamily
        set max_members = 0
        where org_id = org_id_in;

    end$$
language plpgsql;

    create or replace function entitlement_grants_service (
        entitlement_in in varchar,
        service_level_in in varchar
    ) returns numeric
as $$
    begin
        if service_level_in = 'provisioning' then
            if entitlement_in = 'provisioning_entitled' then
                return 1;
            else
                return 0;
            end if;
        elsif service_level_in = 'management' then
            if entitlement_in = 'enterprise_entitled' then
                return 1;
            else
                return 0;
            end if;
        elsif service_level_in = 'monitoring' then
            if entitlement_in = 'monitoring_entitled' then
                return 1;
            end if;
        elsif service_level_in = 'updates' then
            return 1;           
        else
            return 0;
        end if;
    end$$
language plpgsql;

    create or replace function lookup_entitlement_group (
        org_id_in in numeric,
        type_label_in in varchar default 'sw_mgr_entitled'
    ) returns numeric
as $$
    declare
        server_groups cursor for
            select  sg.id               server_group_id
            from    rhnServerGroup      sg,
                    rhnServerGroupType  sgt
            where   sgt.label = type_label_in
                and sgt.id = sg.group_type
                and sg.org_id = org_id_in;
    begin
        for sg in server_groups loop
            return sg.server_group_id;
        end loop;
        return rhn_entitlements.create_entitlement_group(
                org_id_in, 
                type_label_in
            );
    end$$
language plpgsql;

    create or replace function create_entitlement_group (
        org_id_in in numeric,
        type_label_in in varchar default 'sw_mgr_entitled'
    ) returns numeric
as $$
    declare
        sg_id_val numeric;
    begin
        select  nextval('rhn_server_group_id_seq')
        into    sg_id_val;

        insert into rhnServerGroup (
                id, name, description, max_members, current_members,
                group_type, org_id
            ) (
                select  sg_id_val, sgt.label, sgt.label,
                        0, 0, sgt.id, org_id_in
                from    rhnServerGroupType sgt
                where   sgt.label = type_label_in
            );

        return sg_id_val;
    end$$
language plpgsql;

   create or replace function can_entitle_server ( 
      server_id_in   in numeric, 
      type_label_in  in varchar
   )
   returns numeric
as $$
    declare
      addon_servergroups cursor (base_label_in varchar, 
                                 addon_label_in varchar) for
         select
            addon_id
         from
            rhnSGTypeBaseAddonCompat
         where base_id = lookup_sg_type (base_label_in)
           and addon_id = lookup_sg_type (addon_label_in);

      previous_ent        varchar[];
      is_base_in          char   := 'N';
      is_base_current     char   := 'N';
      i                   numeric := 0;
      sgid                numeric := 0;

   begin

      previous_ent := rhn_entitlements.get_server_entitlement(server_id_in);

      select distinct is_base
      into is_base_in
      from rhnServerGroupType
      where label = type_label_in;

      if array_upper(previous_ent, 1) is null or array_upper(previous_ent, 1) = 0 then
         if is_base_in = 'Y' then
            sgid := rhn_entitlements.find_compatible_sg (server_id_in, type_label_in);
            if sgid is not null then
              -- rhn_server.insert_into_servergroup (server_id_in, sgid);
              return 1;
            else
              -- rhn_exception.raise_exception ('invalid_base_entitlement');
              return 0;
            end if;
         else
            -- rhn_exception.raise_exception ('invalid_base_entitlement');
            return 0;
         end if;

      -- there are previous ents, first make sure we're not trying to entitle a base ent
      elsif is_base_in = 'Y' then
         -- rhn_exception.raise_exception ('invalid_addon_entitlement');
         return 0;

      -- it must be an addon, so proceed with the entitlement
      else

         -- find the servers base ent
         is_base_current := 'N';
         i := 0;
         while is_base_current = 'N' and i < array_upper(previous_ent, 1)
         loop
            i := i + 1;
            select is_base
            into is_base_current
            from rhnServerGroupType
            where label = previous_ent[i];
         end loop;

         -- never found a base ent, that would be strange
         if is_base_current  = 'N' then
            -- rhn_exception.raise_exception ('invalid_base_entitlement');
            return 0;
         end if;

         -- this for loop verifies the validity of the addon path
         for addon_servergroup in addon_servergroups  (previous_ent[i], type_label_in) loop
            -- find an appropriate sgid for the addon and entitle the server
            sgid := rhn_entitlements.find_compatible_sg (server_id_in, type_label_in);
            if sgid is not null then
               -- rhn_server.insert_into_servergroup (server_id_in, sgid);
               return 1;
            else
               -- rhn_exception.raise_exception ('invalid_addon_entitlement');
               return 0;
            end if;
         end loop;

      end if;

      return 0;

   end$$
language plpgsql;

   create or replace function can_switch_base ( 
      server_id_in   in    integer, 
      type_label_in  in    varchar
   )
   returns numeric
as $$
   declare
      type_label_in_is_base   char(1);
      sgid                    numeric;

   begin

       select is_base into type_label_in_is_base
       from rhnServerGroupType
       where label = type_label_in;

       if not found then
          perform rhn_exception.raise_exception ( 'invalid_entitlement' );
       end if;

      if type_label_in_is_base = 'N' then
         perform rhn_exception.raise_exception ( 'invalid_entitlement' );
      else
         sgid := rhn_entitlements.find_compatible_sg ( server_id_in,
                                                       type_label_in );
         if sgid is not null then
           return 1;
         else
           return 0;
         end if;
      end if;

   end$$
language plpgsql;

    create or replace function entitle_server (
        server_id_in in numeric,
        type_label_in in varchar default 'sw_mgr_entitled'
    ) returns void
as $$
    declare
      sgid  numeric := 0;
      is_virt numeric := 0;

    begin

      select 1 into is_virt
        from rhnServerEntitlementView
        where server_id = server_id_in
          and label in ('virtualization_host', 'virtualization_host_platform');

      if not found then
          is_virt := 0;
      end if;
      
      if is_virt = 0 and (type_label_in = 'virtualization_host' or
                          type_label_in = 'virtualization_host_platform') then

        is_virt := 1;
      end if;

      if rhn_entitlements.can_entitle_server(server_id_in, 
                                             type_label_in) = 1 then
         sgid := rhn_entitlements.find_compatible_sg (server_id_in,
                                                      type_label_in);
         if sgid is not null then
            insert into rhnServerHistory ( id, server_id, summary, details )
            values ( nextval('rhn_event_id_seq'), server_id_in,
                     'added system entitlement ',
                      case type_label_in
                       when 'enterprise_entitled' then 'Management'
                       when 'sw_mgr_entitled' then 'Update'
                       when 'provisioning_entitled' then 'Provisioning'
                       when 'monitoring_entitled' then 'Monitoring'  
                       when 'virtualization_host' then 'Virtualization'
                       when 'virtualization_host_platform' then 
                            'Virtualization Platform' end  );

            perform rhn_server.insert_into_servergroup (server_id_in, sgid);

            if is_virt = 1 then
              perform rhn_entitlements.repoll_virt_guest_entitlements(server_id_in);
            end if;

         else
            perform rhn_exception.raise_exception ('no_available_server_group');
         end if;
      else
         perform rhn_exception.raise_exception ('invalid_entitlement');
      end if;
   end$$
language plpgsql;

    create or replace function remove_server_entitlement (
        server_id_in in numeric,
        type_label_in in varchar default 'sw_mgr_entitled',
        repoll_virt_guests in numeric default 1
    ) returns void
as $$
    declare
      group_id numeric;
      type_is_base char;
      is_virt numeric := 0;
    begin
      -- would be nice if there were a virt attribute of entitlement types, not have to specify 2 different ones...
        select 1 into is_virt
          from rhnServerEntitlementView
          where server_id = server_id_in
            and label in ('virtualization_host', 'virtualization_host_platform');
        if not found then
            is_virt := 0;
        end if;

        select  sg.id, sgt.is_base
        into group_id, type_is_base
        from    rhnServerGroupType sgt,
            rhnServerGroup sg,
                rhnServerGroupMembers sgm,
                rhnServer s
        where   s.id = server_id_in
            and s.id = sgm.server_id
            and sgm.server_group_id = sg.id
            and sg.org_id = s.org_id
            and sgt.label = type_label_in
            and sgt.id = sg.group_type;

        if not found then
          perform rhn_exception.raise_exception('invalid_server_group_member');
        end if;

      if ( type_is_base = 'Y' ) then
         -- unentitle_server should handle everything, don't really need to do anything else special here
         perform rhn_entitlements.unentitle_server ( server_id_in );
      else

         insert into rhnServerHistory ( id, server_id, summary, details )
         values ( nextval('rhn_event_id_seq'), server_id_in,
                  'removed system entitlement ',
                   case type_label_in
                    when 'enterprise_entitled' then 'Management'
                    when 'sw_mgr_entitled' then 'Update'
                    when 'provisioning_entitled' then 'Provisioning'
                    when 'monitoring_entitled' then 'Monitoring'
                    when 'virtualization_host' then 'Virtualization'
                    when 'virtualization_host_platform' then 
                         'Virtualization Platforrm' end  );

         perform rhn_server.delete_from_servergroup(server_id_in, group_id);

         if is_virt = 1 and repoll_virt_guests = 1 then
           perform rhn_entitlements.repoll_virt_guest_entitlements(server_id_in);
         end if;
      end if;

    end$$
language plpgsql;

    create or replace function unentitle_server (
        server_id_in in numeric
    ) returns void
as $$
    declare
      servergroups cursor for
         select distinct sgt.label, sg.id server_group_id
         from  rhnServerGroupType sgt,
               rhnServerGroup sg,
               rhnServer s,
               rhnServerGroupMembers sgm
         where s.id = server_id_in
            and s.org_id = sg.org_id
            and sg.group_type = sgt.id
            and sgm.server_group_id = sg.id
            and sgm.server_id = s.id;
            
     is_virt numeric := 0;

   begin

      select 1 into is_virt
        from rhnServerEntitlementView
        where server_id = server_id_in
         and label in ('virtualization_host', 'virtualization_host_platform');

      if not found then
          is_virt := 0;
      end if;

      for servergroup in servergroups loop

         insert into rhnServerHistory ( id, server_id, summary, details )
         values ( nextval('rhn_event_id_seq'), server_id_in,
                  'removed system entitlement ',
                   case servergroup.label
                    when 'enterprise_entitled' then 'Management'
                    when 'sw_mgr_entitled' then 'Update'
                    when 'provisioning_entitled' then 'Provisioning'
                    when 'monitoring_entitled' then 'Monitoring'
                    when 'virtualization_host' then 'Virtualization'
                    when 'virtualization_host_platform' then 
                         'Virtualization Platform' end  );
  
         perform rhn_server.delete_from_servergroup(server_id_in, 
                                            servergroup.server_group_id );
      end loop;

      if is_virt = 1 then
        perform rhn_entitlements.repoll_virt_guest_entitlements(server_id_in);
      end if;

   end$$
language plpgsql;


    -- *******************************************************************
    -- PROCEDURE: repoll_virt_guest_entitlements
    --
    --   Whenever we add/remove a virtualization_host* entitlement from 
    --   a host, we can call this procedure to update what type of slots
    --   the guests are consuming.  
    -- 
    --   If you're removing the entitlement, it's 
    --   possible the guests will become unentitled if you don't have enough
    --   physical slots to cover them.
    --
    --   If you're adding the entitlement, you end up freeing up physical
    --   slots for other systems.
    --
    -- *******************************************************************
    create or replace function repoll_virt_guest_entitlements(
        server_id_in in numeric
    ) returns void
as $$
    declare
        -- All channel families associated with the guests of server_id_in
        families cursor for 
            select distinct cfs.channel_family_id
            from
                rhnChannelFamilyServers cfs,
                rhnVirtualInstance vi
            where
                vi.host_system_id = server_id_in
                and vi.virtual_system_id = cfs.server_id;
        
        -- All of server group types associated with the guests of
        -- server_id_in
        group_types cursor for
            select distinct sg.group_type, sgt.label, sg.org_id
            from
                rhnServerGroupType sgt,
                rhnServerGroup sg,
                rhnServerGroupMembers sgm,
                rhnVirtualInstance vi
            where
                vi.host_system_id = server_id_in
                and vi.virtual_system_id = sgm.server_id
                and sgm.server_group_id = sg.id
                and sg.group_type = sgt.id;

        -- Virtual servers from a certain family belonging to a specific
        -- host that are consuming physical channel slots over the limit.
        virt_servers_cfam cursor(family_id_in numeric, quantity_in numeric) for
                select vi.virtual_system_id
                from
                    rhnChannelFamilyMembers cfm,
                    rhnServerChannel sc,
                    rhnVirtualInstance vi
                where
                    vi.host_system_id = server_id_in
                    and vi.virtual_system_id = sc.server_id
                    and sc.channel_id = cfm.channel_id
                    and cfm.channel_family_id = family_id_in
                order by sc.modified desc
                limit quantity_in;                

        -- Virtual servers from a certain family belonging to a specific
        -- host that are consuming physical system slots over the limit.
        virt_servers_sgt cursor(group_type_in numeric, quantity_in numeric) for
                select vi.virtual_system_id
                from
                    rhnServerGroup sg,
                    rhnServerGroupMembers sgm,
                    rhnVirtualInstance vi
                where
                    vi.host_system_id = server_id_in
                    and vi.virtual_system_id = sgm.server_id
                    and sgm.server_group_id = sg.id
                    and sg.group_type = group_type_in
                order by sgm.modified desc
                limit quantity_in;                
        
        -- Get the orgs of Virtual guests
        -- Since they may belong to different orgs
        virt_guest_orgs cursor for
                select  distinct (s.org_id)
                from rhnServer s
                    inner join  rhnVirtualInstance vi on vi.virtual_system_id = s.id
                where
                    vi.host_system_id = server_id_in
                    and s.org_id <> (select s1.org_id from rhnServer s1 where s1.id = vi.host_system_id) ;

        org_id_val numeric;
        max_members_val numeric;
        max_flex_val numeric;
        current_members_calc numeric;
        sg_id numeric;
        is_virt numeric := 0;
        free_slots numeric := 0;
    begin
          select 1 into is_virt
                from rhnServerEntitlementView
           where server_id = server_id_in
                 and label in ('virtualization_host', 'virtualization_host_platform');

      if not found then
          is_virt := 0;
      end if;

        select org_id
        into org_id_val
        from rhnServer
        where id = server_id_in;

        -- deal w/ channel entitlements first ...
        for family in families loop
            if is_virt = 0 then
            -- if the host_server does not have virt
            --- find all possible flex slots
            -- and set each of the flex eligible guests to Y
                select sfc.max_members - sfc.current_members
                  into free_slots
                  from rhnServerFveCapable sfc
                 where sfc.channel_family_id = family.channel_family_id;
                UPDATE rhnServerChannel sc set is_fve = 'Y'
                where sc.server_id in (
                            select vi.virtual_system_id
                            from rhnServerFveCapable sfc
                                inner join rhnVirtualInstance vi on vi.virtual_system_id = sfc.server_id
                            where vi.host_system_id = server_id_in
                                  and sfc.channel_family_id = family.channel_family_id
                              order by vi.modified desc
                            limit free_slots
                );
            else
            -- if the host_server has virt
            -- set all its flex guests to N
                UPDATE rhnServerChannel sc set is_fve = 'N'
                where
                    sc.channel_id in (select cfm.channel_id from rhnChannelFamilyMembers cfm
                                      where cfm.CHANNEL_FAMILY_ID = family.channel_family_id)
                    and sc.is_fve = 'Y'
                    and sc.server_id in
                            (select vi.virtual_system_id  from rhnVirtualInstance vi
                                    where vi.host_system_id = server_id_in);
            end if;

            -- get the current (physical) members of the family
            current_members_calc := 
                rhn_channel.channel_family_current_members(family.channel_family_id,
                                                           org_id_val); -- fixed transposed args

            -- get the max members of the family
            select max_members
            into max_members_val
            from rhnPrivateChannelFamily
            where channel_family_id = family.channel_family_id
            and org_id = org_id_val;

            select fve_max_members
            into max_flex_val
            from rhnPrivateChannelFamily
            where channel_family_id = family.channel_family_id
            and org_id = org_id_val;

            if current_members_calc > max_members_val then
                -- A virtualization_host* ent must have been removed, so we'll
                -- unsubscribe guests from the host first.

                -- hm, i don't think max_members - current_members_calc yielding a negative number
                -- will work w/ rownum, swaping 'em in the body of this if...
                for virt_server in virt_servers_cfam(family.channel_family_id,
                                current_members_calc - max_members_val) loop 

                    perform rhn_channel.unsubscribe_server_from_family(
                                virt_server.virtual_system_id,
                                family.channel_family_id);
                end loop;                               

                -- if we're still over the limit, which would be odd,
                -- just prune the group to max_members
                --
                -- er... wouldn't we actually have to refresh the values of
                -- current_members_calc and max_members_val to actually ever
                -- *skip this??
                if current_members_calc > max_members_val then
                    -- argh, transposed again?!
                    perform rhn_entitlements.set_family_count(org_id_val,
                                     family.channel_family_id,
                                     max_members_val, max_flex_val);
                    --TODO calculate this correctly
                end if; 

           end if;

            -- update current_members for the family.  This will set the value
            -- to reflect adding/removing the entitlement.
            --
            -- what's the difference of doing this vs the unavoidable set_family_count above?
            perform rhn_channel.update_family_counts(family.channel_family_id,
                                             org_id_val);

            -- It is possible that the guests belong  to a different org than the host
            -- so we are going to update the family counts in the guests orgs also
            for org in virt_guest_orgs loop
                    perform rhn_channel.update_family_counts(family.channel_family_id,
                                             org.org_id);
            end loop;
        end loop;

        for a_group_type in group_types loop
          -- get the current *physical* members of the system entitlement type for the org...
          -- 
          -- unlike channel families, it appears the standard rhnServerGroup.max_members represents
          -- *physical* slots, vs physical+virt ... boy that's confusing...

          select max_members, id
            into max_members_val, sg_id
            from rhnServerGroup
            where group_type = a_group_type.group_type
            and org_id = a_group_type.org_id;


      select count(sep.server_id) into current_members_calc
            from rhnServerEntitlementPhysical sep
           where sep.server_group_id = sg_id
             and sep.server_group_type_id = a_group_type.group_type;
          
          if current_members_calc > max_members_val then
            -- A virtualization_host* ent must have been removed, and we're over the limit, so unsubscribe guests
            for virt_server in virt_servers_sgt(a_group_type.group_type,
                                                current_members_calc - max_members_val) loop
              perform rhn_entitlements.remove_server_entitlement(virt_server.virtual_system_id, a_group_type.label);

              -- decrement current_members_calc, we'll use it to reset current_members for the group at the end...
              current_members_calc := current_members_calc - 1;
            end loop;

          end if;

          update rhnServerGroup set current_members = current_members_calc
           where org_id = a_group_type.org_id
             and group_type = a_group_type.group_type;

          -- I think that's all the house-keeping we have to do...
        end loop;

    end$$
language plpgsql;

    create or replace function get_server_entitlement (
        server_id_in in numeric
    ) returns varchar[]
as $$
    declare
        server_groups cursor for
            select  sgt.label
            from    rhnServerGroupType      sgt,
                    rhnServerGroup          sg,
                    rhnServerGroupMembers   sgm
            where   1=1
                and sgm.server_id = server_id_in
                and sg.id = sgm.server_group_id
                and sgt.id = sg.group_type
                and sgt.label in (
                    'sw_mgr_entitled','enterprise_entitled',
                    'provisioning_entitled', 'nonlinux_entitled',
                    'monitoring_entitled', 'virtualization_host',
                                        'virtualization_host_platform'
                    );

         ent_array varchar[];

    begin
      
      ent_array := '{}';

      for sg in server_groups loop
         ent_array := ent_array || sg.label;
      end loop;

      return ent_array;

    end$$
language plpgsql;

    -- this desperately needs to be table driven.
    create or replace function modify_org_service (
        org_id_in in numeric,
        service_label_in in varchar,
        enable_in in char
    ) returns void
as $$
    declare
        roles_to_process varchar[];
        roles cursor(role_label_in varchar) for
            select  label, id
            from    rhnUserGroupType
            where   label = role_label_in;
        org_roles cursor(role_label_in varchar) for
            select  1
            from    rhnUserGroup ug,
                    rhnUserGroupType ugt
            where   ugt.label = role_label_in
                and ug.org_id = org_id_in
                and ugt.id = ug.group_type;
                
        ents_to_process varchar[];
        ents cursor(ent_label_in varchar) for
            select  label, id
            from    rhnOrgEntitlementType
            where   label = ent_label_in;
        org_ents cursor(ent_label_in varchar) for
            select  1
            from    rhnOrgEntitlements oe,
                    rhnOrgEntitlementType oet
            where   oet.label = ent_label_in
                and oe.org_id = org_id_in
                and oet.id = oe.entitlement_id;
        create_row char(1);
    begin
        ents_to_process := '{}';
        roles_to_process := '{}';
        -- a bit kludgy, but only for 3.4 really.  Certainly no
        -- worse than the old code...
        if service_label_in = 'enterprise' or 
           service_label_in = 'management' then
            ents_to_process := array_append(ents_to_process, 'sw_mgr_enterprise');

            roles_to_process := array_append(roles_to_process, 'org_admin');

            roles_to_process := array_append(roles_to_process, 'system_group_admin');

            roles_to_process := array_append(roles_to_process, 'activation_key_admin');
        elsif service_label_in = 'provisioning' then
            ents_to_process := array_append(ents_to_process, 'rhn_provisioning');

            roles_to_process := array_append(roles_to_process, 'system_group_admin');

            roles_to_process := array_append(roles_to_process, 'activation_key_admin');

            roles_to_process := array_append(roles_to_process, 'config_admin');
            -- another nasty special case...
            if enable_in = 'Y' then
                ents_to_process := array_append(ents_to_process, 'sw_mgr_enterprise');
            end if;
        elsif service_label_in = 'monitoring' then
            ents_to_process := array_append(ents_to_process, 'rhn_monitor');

            roles_to_process := array_append(roles_to_process, 'monitoring_admin');
        elsif service_label_in = 'virtualization' then
            ents_to_process := array_append(ents_to_process, 'rhn_virtualization');

            roles_to_process := array_append(roles_to_process, 'config_admin');
        elsif service_label_in = 'virtualization_platform' then
            ents_to_process := array_append(ents_to_process, 'rhn_virtualization_platform');
            roles_to_process := array_append(roles_to_process, 'config_admin');
    elsif service_label_in = 'nonlinux' then
            ents_to_process := array_append(ents_to_process, 'rhn_nonlinux');
            roles_to_process := array_append(roles_to_process, 'config_admin');
        end if;

        if enable_in = 'Y' then
            for i in 1..array_upper(ents_to_process, 1) loop
                for ent in ents(ents_to_process[i]) loop
                    create_row := 'Y';
                    for oe in org_ents(ent.label) loop
                        create_row := 'N';
                    end loop;
                    if create_row = 'Y' then
                        insert into rhnOrgEntitlements(org_id, entitlement_id)
                            values (org_id_in, ent.id);
                    end if;
                end loop;
            end loop;
            for i in 1..array_upper(roles_to_process, 1) loop
                for role in roles(roles_to_process[i]) loop
                    create_row := 'Y';
                    for o_r in org_roles(role.label) loop
                        create_row := 'N';
                    end loop;
                    if create_row = 'Y' then
                        insert into rhnUserGroup(
                                id, name, description, current_members,
                                group_type, org_id
                            ) (
                                select  nextval('rhn_user_group_id_seq'),
                                        ugt.name || 's',
                                        ugt.name || 's for Org ' ||
                                            o.name || ' ('|| o.id ||')',
                                        0, ugt.id, o.id
                                from    rhnUserGroupType ugt,
                                        web_customer o
                                where   o.id = org_id_in
                                    and ugt.id = role.id
                            );
                    end if;
                end loop;
            end loop;
        else
            for i in 1..coalesce(array_upper(ents_to_process, 1), 0) loop
                for ent in ents(ents_to_process[i]) loop
                    delete from rhnOrgEntitlements
                     where org_id = org_id_in
                       and entitlement_id = ent.id;
                end loop;
            end loop;
        end if;
    end$$
language plpgsql;

    create or replace function set_customer_enterprise (
        customer_id_in in numeric
    ) returns void
as $$
    begin
        perform rhn_entitlements.modify_org_service(customer_id_in, 'enterprise', 'Y');
    end$$
language plpgsql;

    create or replace function set_customer_provisioning (
        customer_id_in in numeric
    ) returns void
as $$
    begin
        perform rhn_entitlements.modify_org_service(customer_id_in, 'provisioning', 'Y');
    end$$
language plpgsql;

    create or replace function set_customer_monitoring (
        customer_id_in in numeric
    ) returns void
as $$
    begin
        perform rhn_entitlements.modify_org_service(customer_id_in, 'monitoring', 'Y');
    end$$
language plpgsql;

    create or replace function set_customer_nonlinux (
        customer_id_in in numeric
    ) returns void
as $$
    begin
        perform rhn_entitlements.modify_org_service(customer_id_in, 'nonlinux', 'Y');
    end$$
language plpgsql;

    create or replace function unset_customer_enterprise (
        customer_id_in in numeric
    ) returns void
as $$
    begin
        perform rhn_entitlements.modify_org_service(customer_id_in, 'enterprise', 'N');
    end$$
language plpgsql;

    create or replace function unset_customer_provisioning (
        customer_id_in in numeric
    ) returns void
as $$
    begin
        perform rhn_entitlements.modify_org_service(customer_id_in, 'provisioning', 'N');
    end$$
language plpgsql;

    create or replace function unset_customer_monitoring (
        customer_id_in in numeric
    ) returns void
as $$
    begin
        perform rhn_entitlements.modify_org_service(customer_id_in, 'monitoring', 'N');
    end$$
language plpgsql;

    create or replace function unset_customer_nonlinux (
        customer_id_in in numeric
    ) returns void
as $$
    begin
        perform rhn_entitlements.modify_org_service(customer_id_in, 'nonlinux', 'N');
    end$$
language plpgsql;

    -- *******************************************************************
    -- PROCEDURE: prune_group
    -- Unsubscribes servers consuming physical slots that over the org's
    --   limit.
    -- Called by: set_server_group_count, repoll_virt_guest_entitlements
    -- *******************************************************************
    create or replace function prune_group (
        group_id_in in numeric,
        quantity_in in numeric,
        update_family_countsYN in numeric default 1
    ) returns void
as $$
    declare
        sgrecord record;
      type_is_base char;
    begin
            update      rhnServerGroup
                set     max_members = quantity_in
                where   id = group_id_in;

            for sgrecord in (
		   select  server_id, server_group_id, sgt.id as group_type_id, sgt.label
		    from    rhnServerGroupType              sgt,
				    rhnServerGroup                  sg,
				    rhnServerGroupMembers   sgm
		    where   1=1
			    and sgm.server_group_id = group_id_in
			    and sgm.server_id in (
				    select  sep.server_id
				    from
					rhnServerEntitlementPhysical sep
				    where
					sep.server_group_id = group_id_in
				    order by sep.modified asc
				    offset quantity_in
				)
			    and sgm.server_group_id = sg.id
			    and sg.group_type = sgt.id
	    ) loop
                perform rhn_entitlements.remove_server_entitlement(sgrecord.server_id, sgrecord.label);
            
            select is_base 
            into type_is_base
            from rhnServerGroupType sgt
            where sgt.id = sgrecord.group_type_id;

            -- if we're removing a base ent, then be sure to
            -- remove the server's channel subscriptions.
            if ( type_is_base = 'Y' ) then
                   perform rhn_channel.clear_subscriptions(sgrecord.server_id, 0, update_family_countsYN);
            end if;

            end loop;
    end$$
language plpgsql;

    -- *******************************************************************
    -- PROCEDURE: assign_system_entitlement
    --
    -- Moves system entitlements from from_org_id_in to to_org_id_in.
    -- Can raise not_enough_entitlements_in_base_org if from_org_id_in
    -- does not have enough entitlements to cover the move.
    -- Takes care of unentitling systems if necessary by calling 
    -- set_server_group_count
    -- *******************************************************************
    create or replace function assign_system_entitlement(
        group_label_in in varchar,
        from_org_id_in in numeric,
        to_org_id_in in numeric,
        quantity_in in numeric
    ) returns void
as $$
    declare
        prev_ent_count numeric;
    to_org_prev_ent_count numeric;
        new_ent_count numeric;
    new_quantity numeric;
        group_type numeric;
    begin

            select max_members
            into prev_ent_count
            from rhnServerGroupType sgt,
                 rhnServerGroup sg
            where sg.org_id = from_org_id_in
              and sg.group_type = sgt.id
              and sgt.label = group_label_in;

            if not found then
                perform rhn_exception.raise_exception(
                              'not_enough_entitlements_in_base_org');
            end if;

            select max_members
            into to_org_prev_ent_count
            from rhnServerGroupType sgt,
                 rhnServerGroup sg
            where sg.org_id = to_org_id_in
              and sg.group_type = sgt.id
              and sgt.label = group_label_in;

            if not found then
                to_org_prev_ent_count := 0;
            end if;
    
            select id
            into group_type
            from rhnServerGroupType
            where label = group_label_in;

            if not found then
                perform rhn_exception.raise_exception(
                              'invalid_server_group');
            end if;

        new_ent_count := prev_ent_count - quantity_in;
    
        if prev_ent_count > new_ent_count then
            new_quantity := to_org_prev_ent_count + quantity_in;
        end if;
    
        if new_ent_count < 0 then
            perform rhn_exception.raise_exception(
                          'not_enough_entitlements_in_base_org');
        end if;


        perform rhn_entitlements.set_server_group_count(from_org_id_in,
                                         group_type,
                                         new_ent_count);

        perform rhn_entitlements.set_server_group_count(to_org_id_in,
                                         group_type,
                                         new_quantity);
        
        -- Create or delete the entries in rhnOrgEntitlementType
        if group_label_in = 'enterprise_entitled' then 
            if new_quantity > 0 then
                perform rhn_entitlements.set_customer_enterprise(to_org_id_in);
            else
                perform rhn_entitlements.unset_customer_enterprise(to_org_id_in);
            end if;
        end if;

        if group_label_in = 'provisioning_entitled' then
            if new_quantity > 0 then
                perform rhn_entitlements.set_customer_provisioning(to_org_id_in);
            else
                perform rhn_entitlements.unset_customer_provisioning(to_org_id_in);
            end if;
        end if;

        if group_label_in = 'monitoring_entitled' then
            if new_quantity > 0 then
                perform rhn_entitlements.set_customer_monitoring(to_org_id_in);
            else
                perform rhn_entitlements.unset_customer_monitoring(to_org_id_in);
            end if;
        end if;

    end$$
language plpgsql;

    -- *******************************************************************
    -- PROCEDURE: assign_channel_entitlement
    --
    -- Moves channel entitlements from from_org_id_in to to_org_id_in.
    -- Can raise not_enough_entitlements_in_base_org if from_org_id_in
    -- does not have enough entitlements to cover the move.
    -- Takes care of unentitling systems if necessary by calling 
    -- set_family_count
    -- *******************************************************************
    create or replace function assign_channel_entitlement(
        channel_family_label_in in varchar,
        from_org_id_in in numeric,
        to_org_id_in in numeric,
        quantity_in in numeric,
        flex_in in numeric
    ) returns void
as $$
    declare
        from_org_prev_ent_count numeric;
        from_org_prev_ent_count_flex numeric;
        new_ent_count numeric;
        new_ent_count_flex numeric;
        to_org_prev_ent_count numeric;
        to_org_prev_ent_count_flex numeric;
        new_quantity numeric;
        new_flex numeric;
        cfam_id       numeric;
    begin

            select max_members
            into from_org_prev_ent_count
            from rhnChannelFamily cf,
                 rhnPrivateChannelFamily pcf
            where pcf.org_id = from_org_id_in
              and pcf.channel_family_id = cf.id
              and cf.label = channel_family_label_in;

            if not found then
                perform rhn_exception.raise_exception(
                              'not_enough_entitlements_in_base_org');
            end if;
    
            select max_members
            into to_org_prev_ent_count
            from rhnChannelFamily cf,
                 rhnPrivateChannelFamily pcf
            where pcf.org_id = to_org_id_in
              and pcf.channel_family_id = cf.id
              and cf.label = channel_family_label_in;

            if not found then
                to_org_prev_ent_count := 0;
            end if;

            select fve_max_members
            into from_org_prev_ent_count_flex
            from rhnChannelFamily cf,
                rhnPrivateChannelFamily pcf
            where pcf.org_id = from_org_id_in
              and pcf.channel_family_id = cf.id
              and cf.label = channel_family_label_in;

            if not found then
                perform rhn_exception.raise_exception(
                              'not_enough_flex_entitlements_in_base_org');
            end if;

            select fve_max_members
            into to_org_prev_ent_count_flex
            from rhnChannelFamily cf,
                 rhnPrivateChannelFamily pcf
            where pcf.org_id = to_org_id_in
              and pcf.channel_family_id = cf.id
              and cf.label = channel_family_label_in;

            if not found then
                to_org_prev_ent_count_flex := 0;
            end if;

            select id
            into cfam_id
            from rhnChannelFamily
            where label = channel_family_label_in;

            if not found then
                perform rhn_exception.raise_exception(
                              'invalid_channel_family');
            end if;

        new_ent_count := from_org_prev_ent_count - quantity_in;
        new_ent_count_flex := from_org_prev_ent_count_flex - flex_in;
    
        if from_org_prev_ent_count >= new_ent_count then
            new_quantity := to_org_prev_ent_count + quantity_in;
        end if;

        if from_org_prev_ent_count_flex >= new_ent_count_flex then
            new_flex := to_org_prev_ent_count_flex + flex_in;
        end if;

        if new_ent_count < 0 then
            perform rhn_exception.raise_exception(
                          'not_enough_entitlements_in_base_org');
        end if;

        if new_ent_count_flex < 0 then
            perform rhn_exception.raise_exception(
                          'not_enough_flex_entitlements_in_base_org');
        end if;



        perform rhn_entitlements.set_family_count(from_org_id_in,
                                          cfam_id,
                                          new_ent_count,
                                          new_ent_count_flex);

        perform rhn_entitlements.set_family_count(to_org_id_in,
                                          cfam_id,
                                          new_quantity,
                                          new_flex);

    end$$
language plpgsql;

    -- *******************************************************************
    -- PROCEDURE: activate_system_entitlement
    --
    -- Sets the values in rhnServerGroup for a given rhnServerGroupType.
    -- 
    -- Calls: set_server_group_count to update, prune, or create the group.
    -- Called by: the code that activates a satellite cert. 
    --
    -- Raises not_enough_entitlements_in_base_org if all entitlements
    -- in the org are used so the free entitlements would not cover
    -- the difference when descreasing the number of entitlements.
    -- *******************************************************************
    create or replace function activate_system_entitlement(
        org_id_in in numeric,
        group_label_in in varchar,
        quantity_in in numeric
    ) returns void
as $$
    declare
        prev_ent_count numeric; 
        prev_ent_count_sum numeric; 
        group_type numeric;
    begin

        -- Fetch the current entitlement count for the org
        -- into prev_ent_count

            select current_members
            into prev_ent_count
            from rhnServerGroupType sgt,
                 rhnServerGroup sg
            where sg.group_type = sgt.id
              and sgt.label = group_label_in
              and sg.org_id = org_id_in;

            if not found then
                prev_ent_count := 0;
            end if;

            select id
            into group_type
            from rhnServerGroupType
            where label = group_label_in;

            if not found then
                perform rhn_exception.raise_exception(
                              'invalid_server_group');
            end if;

        -- If we're setting the total entitlemnt count to a lower value,
        -- and that value is less than the allocated count in this org,
        -- we need to raise an exception.
        if quantity_in < prev_ent_count then
            perform rhn_exception.raise_exception(
                          'not_enough_entitlements_in_base_org');
        else
            -- don't update family counts after every server
            -- will do bulk update afterwards
            perform rhn_entitlements.set_server_group_count(org_id_in,
                                             group_type,
                                             quantity_in,
                                             0);
            -- bulk update family counts
            perform rhn_channel.update_group_family_counts(group_label_in, org_id_in);
        end if;

    end$$
language plpgsql;

    -- *******************************************************************
    -- PROCEDURE: activate_channel_entitlement
    --
    -- Calls: set_family_count to update, prune, or create the family
    --        permission bucket.
    -- Called by: the code that activates a satellite cert. 
    --
    -- Raises not_enough_entitlements_in_base_org if there are not enough
    -- entitlements in the org to cover the difference when you are
    -- descreasing the number of entitlements.
    --
    -- The backend code in Python is expected to do whatever arithmetics
    -- is needed.
    -- *******************************************************************
    create or replace function activate_channel_entitlement(
        org_id_in in numeric,
        channel_family_label_in in varchar,
        quantity_in in numeric,
        flex_in in numeric
    ) returns void
as $$
    declare
        prev_ent_count numeric; 
        prev_flex_count numeric;
        prev_ent_count_sum numeric; 
        cfam_id numeric;
        reduce_quantity numeric;
        total_flex_capable numeric;
        to_convert_reg cursor (channel_family_id_val numeric, org_id_in numeric, quantity numeric) for
                     select SC.server_id
                     from rhnServerChannel SC inner join
                          rhnServer S on S.id = SC.server_id
                     where
                         is_fve = 'Y'
                         and S.org_id = org_id_in
                         and SC.channel_id in
                         (select cfm.channel_id from rhnChannelFamilyMembers cfm
                             where cfm.CHANNEL_FAMILY_ID = channel_family_id_val)
                         limit quantity;
         to_convert_flex cursor (channel_family_id_val numeric, org_id_in numeric, quantity numeric) for
                   select server_id
                   from rhnServerFveCapable
                       where SERVER_ORG_ID = org_id_in and
                             channel_family_id = cfam_id
                       limit quantity;

    begin

        -- Fetch the current entitlement count for the org
        -- into prev_ent_count
            select current_members
            into prev_ent_count
            from rhnChannelFamily cf,
                 rhnPrivateChannelFamily pcf
            where pcf.org_id = org_id_in
              and pcf.channel_family_id = cf.id
              and cf.label = channel_family_label_in;

            if not found then
                prev_ent_count := 0;
            end if;

            select pcf.fve_current_members
            into prev_flex_count
            from rhnChannelFamily cf,
                 rhnPrivateChannelFamily pcf
            where pcf.org_id = org_id_in
              and pcf.channel_family_id = cf.id
              and cf.label = channel_family_label_in;

            if not found then
                prev_flex_count := 0;
            end if;

            select id
            into cfam_id
            from rhnChannelFamily
            where label = channel_family_label_in;

            if not found then
                perform rhn_exception.raise_exception(
                              'invalid_channel_family');
            end if;

        -- if there are too few flex entitlements
        if flex_in < prev_flex_count then
            -- and if the extra we need is less than or equal to our extra regular entitlements
            if prev_flex_count - flex_in <= quantity_in - prev_ent_count then
                   reduce_quantity := prev_flex_count - flex_in;
                   -- We need to convert some systems from flex guest to regular
                   for system in to_convert_reg(cfam_id, org_id_in, reduce_quantity) loop
                      --rhn_channel.convert_to_regular(system.server_id, cfam_id);
                      UPDATE rhnServerChannel sc set is_fve = 'N'
                           where sc.server_id = system.server_id
                                 and sc.channel_id in (select cfm.channel_id
                                                          from rhnChannelFamilyMembers cfm
                                                          where cfm.channel_family_id = cfam_id);
                   end loop;

                   --reset previous counts
                   prev_ent_count := prev_ent_count + reduce_quantity;
                   prev_flex_count := prev_flex_count - reduce_quantity;
            else
                perform rhn_exception.raise_exception(
                          'not_enough_flex_entitlements_in_base_org');
            end if;
        end if;

        -- if there are too few regular entitlements, and extra flex entitlements
        if quantity_in < prev_ent_count and prev_flex_count < flex_in then
                -- how many flex-capable systems (that aren't using flex) do we have
                select count(*)
                   into total_flex_capable
                   from rhnServerFveCapable
                       where SERVER_ORG_ID = org_id_in and
                             channel_family_id = cfam_id;
                -- if we have enough flex capable machines that is at least
                --   as many as what we are over on
                if total_flex_capable >= prev_ent_count - quantity_in then
                    reduce_quantity := prev_ent_count - quantity_in;
                    for system in to_convert_flex(cfam_id, org_id_in, reduce_quantity) loop
--                          rhn_channel.convert_to_fve(system.server_id, cfam_id);
                        UPDATE rhnServerChannel sc set is_fve = 'Y'
                           where sc.server_id = system.server_id
                                 and sc.channel_id in (select cfm.channel_id
                                                          from rhnChannelFamilyMembers cfm
                                                          where cfm.channel_family_id = cfam_id);
                    end loop;
                    prev_ent_count := prev_ent_count - reduce_quantity;
                    prev_flex_count := prev_flex_count + reduce_quantity;
                end if;
        end if;

        -- If we're setting the total entitlemnt count to a lower value,
        -- and that value is less than the count in that one org,
        -- we need to raise an exception.
        if quantity_in < prev_ent_count then
            perform rhn_exception.raise_exception(
                          'not_enough_entitlements_in_base_org');
        else
            -- even if we've manually converted systems to/from flex above
            -- set_family_count should call update_family_counts, to reset
            -- current used slots
            perform rhn_entitlements.set_family_count(org_id_in, cfam_id,
                                              quantity_in, flex_in);
        end if;

    end$$
language plpgsql;

    create or replace function set_server_group_count (
        customer_id_in in numeric,  -- customer_id
        group_type_in in numeric,   -- rhn[User|Server]GroupType.id
        quantity_in in numeric,      -- quantity
                update_family_countsYN in numeric default 1
    ) returns void
as $$
    declare
        group_id numeric;
        quantity numeric;
        wasfound boolean;
    begin
        quantity := quantity_in;
        if quantity is not null and quantity < 0 then
            quantity := 0;
        end if;

        select  rsg.id
        into    group_id
        from    rhnServerGroup rsg
        where   1=1
            and rsg.org_id = customer_id_in
            and rsg.group_type = group_type_in;

        -- preserve the not found status across the rhn_entitlements.prune_group invocation
        wasfound := true;
        if not found then
            wasfound := false;
        end if;

        perform rhn_entitlements.prune_group(
            group_id,
            quantity,
                        update_family_countsYN
        );

        if not wasfound then
            insert into rhnServerGroup (
                    id, name, description, max_members, current_members,
                    group_type, org_id, created, modified
                ) (
                    select  nextval('rhn_server_group_id_seq'), name, name,
                            quantity, 0, id, customer_id_in,
                            current_timestamp, current_timestamp
                    from    rhnServerGroupType
                    where   id = group_type_in
            );
        end if;

    end$$
language plpgsql;

    -- *******************************************************************
    -- PROCEDURE: prune_family
    -- Unsubscribes servers consuming physical slots from the channel family 
    --   that are over the org's limit.
    -- Called by: set_family_count
    -- *******************************************************************
    create or replace function prune_family (
        customer_id_in in numeric,
        channel_family_id_in in numeric,
        quantity_in in numeric,
        flex_in in numeric
    ) returns void
as $$
    declare
        serverchannels cursor(tmp_quantity numeric, is_fve_in char) for
            select  sc.server_id,
                    sc.channel_id
            from    rhnServerChannel sc,
                    rhnChannelFamilyMembers cfm
            where   1=1
                and cfm.channel_family_id = channel_family_id_in
                and cfm.channel_id = sc.channel_id
                and server_id in (
                       select server_id from (
                            select  distinct rs.id as server_id
                            from    
                                    rhnServerChannel        rsc,
                                    rhnChannelFamilyMembers rcfm,
                                    rhnServer               rs
                            where   1=1
                                and rs.org_id = customer_id_in
                                and rs.id = rsc.server_id
                                and rsc.channel_id = rcfm.channel_id
                                and rcfm.channel_family_id =  channel_family_id_in
                                and rsc.is_fve = is_fve_in
                                -- we only want to grab servers consuming
                                -- physical slots.
                                and exists (
                                    select 1
                                    from rhnChannelFamilyServerPhysical cfsp
                                    where cfsp.server_id = rs.id
                                    and cfsp.channel_family_id = 
                                        channel_family_id_in
                                    )
                            ) Q
                        order by server_id asc
                        offset quantity_in
                        );
    begin
        -- if we get a null customer_id, this is completely bogus.
        if customer_id_in is null then
            return;
        end if;

        for sc in serverchannels(quantity_in, 'N') loop
            perform rhn_channel.unsubscribe_server(sc.server_id, sc.channel_id,
                                                   1, 1, 0, 0);
        end loop;

        for sc in serverchannels(flex_in, 'Y') loop
            perform rhn_channel.unsubscribe_server(sc.server_id, sc.channel_id,
                                                   1, 1, 0, 0);
        end loop;

        perform rhn_channel.update_family_counts(channel_family_id_in, customer_id_in);
    end$$
language plpgsql;
        
    create or replace function set_family_count (
        customer_id_in in numeric,      -- customer_id
        channel_family_id_in in numeric,    -- 246
        quantity_in in numeric,          -- 3
        flex_in in numeric
    ) returns void
as $$
    declare
        privperms cursor for
            select  1
            from    rhnPrivateChannelFamily
            where   org_id = customer_id_in
                and channel_family_id = channel_family_id_in;
        pubperms cursor for
            select  o.id org_id
            from    web_customer o,
                    rhnPublicChannelFamily pcf
            where   pcf.channel_family_id = channel_family_id_in;
        quantity numeric;
        done numeric := 0;
        flex numeric;
    begin
        quantity := quantity_in;
        if quantity is not null and quantity < 0 then
            quantity := 0;
        end if;
        flex := flex_in;
        if flex is not null and flex < 0 then
            flex := 0;
        end if;

        if customer_id_in is not null then
            for perm in privperms loop
                perform rhn_entitlements.prune_family(
                    customer_id_in,
                    channel_family_id_in,
                    quantity,
                    flex
                );

                if quantity is null and flex is null then
                    delete from rhnPrivateChannelFamily
                        where org_id = customer_id_in
                            and channel_family_id = channel_family_id_in;
                 else
                    update rhnPrivateChannelFamily
                        set max_members = quantity
                        where org_id = customer_id_in
                            and channel_family_id = channel_family_id_in;

                   update rhnPrivateChannelFamily
                        set fve_max_members = flex
                        where org_id = customer_id_in
                            and channel_family_id = channel_family_id_in;
                end if;
                return;
            end loop;

            insert into rhnPrivateChannelFamily (
                    channel_family_id, org_id, max_members, current_members, fve_max_members, fve_current_members
                ) values (
                    channel_family_id_in, customer_id_in, quantity, 0, flex, 0 );
            return;
        end if;

        for perm in pubperms loop
            if quantity = 0 then
                perform rhn_entitlements.prune_family(
                    perm.org_id,
                    channel_family_id_in,
                    quantity,
                    flex
                );
                if done = 0 then
                    delete from rhnPublicChannelFamily
                        where channel_family_id = channel_family_id_in;
                end if;
            end if;
            done := 1;
        end loop;
        -- if done's not 1, then we don't have any entitlements
        if done != 1 then
            insert into rhnPublicChannelFamily (
                    channel_family_id
                ) values (
                    channel_family_id_in
                );
        end if;
    end$$
language plpgsql;

    -- this expects quantity_in to be the number of available slots, not the
    -- max_members of the server group.  If you give it too many, it'll fail
    -- and raise servergroup_max_members.
    -- We should NEVER run this unless we're SURE that we won't
    -- be violating the max.
    create or replace function entitle_last_modified_servers (
        customer_id_in in numeric,  -- customer_id
        type_label_in in varchar,   -- 'enterprise_entitled'
        quantity_in in numeric      -- 3
    ) returns void
as $$
    declare
        -- find the servers that aren't currently in slots
        servers cursor(cid_in numeric, quant_in numeric) for
                                    select  rs.id as server_id
                                    from    rhnServer rs
                                    where   1=1
                                        and rs.org_id = cid_in
                                        and not exists (
                                            select  1
                                            from    rhnServerGroup sg,
                                                    rhnServerGroupMembers rsgm
                                            where   rsgm.server_id = rs.id
                                                and rsgm.server_group_id = sg.id
                                                and sg.group_type is not null
                                        )
                                        and not exists (
                                            select 1
                                            from rhnVirtualInstance vi
                                            where vi.virtual_system_id =
                                                  rs.id
                                        )
                                    order by modified desc
                                    limit quant_in;
    begin
        for server in servers(customer_id_in, quantity_in) loop
            perform rhn_entitlements.entitle_server(server.server_id, type_label_in);
        end loop;
    end$$
language plpgsql;

    create or replace function subscribe_newest_servers (
        customer_id_in in numeric
    ) returns void
as $$
    declare
        -- find servers without base channels
        servers cursor(cid_in numeric) for
            select  s.id
            from    rhnServer           s
            where   1=1
                and s.org_id = cid_in
                and not exists (
                        select 1
                        from    rhnChannel          c,
                                rhnServerChannel    sc
                        where   sc.server_id = s.id
                            and sc.channel_id = c.id
                            and c.parent_channel is null
                    )
                and not exists (
                        select 1
                        from rhnVirtualInstance vi
                        where vi.virtual_system_id = s.id
                    )                        
            order by s.modified desc;
        channel_id numeric;
    begin
        for server in servers(customer_id_in) loop
            channel_id := rhn_channel.guess_server_base(server.id);
            if channel_id is not null then
                begin
                    perform rhn_channel.subscribe_server(server.id, channel_id);
                -- exception is really channel_family_no_subscriptions
                exception
                    when others then
                        null;
                end;
            end if;
        end loop;
    end$$
language plpgsql;


-- restore the original setting
update pg_settings set setting = overlay( setting placing '' from 1 for (length('rhn_entitlements')+1) ) where name = 'search_path';
 07070100000810000081B400000000000000000000000167AE111400001CB4000000000000000000000000000000000000005800000000susemanager-schema/upgrade/spacewalk-schema-2.2-to-spacewalk-schema-2.3/016-rhn_org.sql   --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--

-- create schema rhn_org;

-- setup search_path so that these functions are created in appropriate schema.
update pg_settings set setting = 'rhn_org,' || setting where name = 'search_path';


create or replace function delete_org (
        org_id_in in numeric
    ) returns void
    as
    $$
    declare
        users cursor for
        select id
        from web_contact
        where org_id = org_id_in;

        servers cursor (org_id_in numeric) for
        select  id
        from    rhnServer
        where   org_id = org_id_in;

        config_channels cursor for
        select id
        from rhnConfigChannel
        where org_id = org_id_in;

        custom_channels cursor for
        select  id
        from    rhnChannel
        where   org_id = org_id_in;

        errata cursor for
        select  id
        from    rhnErrata
        where   org_id = org_id_in;

    begin

        if org_id_in = 1 then
            perform rhn_exception.raise_exception('cannot_delete_base_org');
        end if;

        -- Delete all users.
        for u in users loop
            perform rhn_org.delete_user(u.id, 1);
        end loop;

        -- Delete all servers.
        for s in servers(org_id_in) loop
            perform delete_server(s.id);
        end loop;

        -- Delete all config channels.
        for c in config_channels loop
            perform rhn_config.delete_channel(c.id);
        end loop;

        -- Delete all custom channels.
        for cc in custom_channels loop
          delete from rhnServerChannel where channel_id = cc.id;
          delete from rhnServerProfilePackage where server_profile_id in (
            select id from rhnServerProfile where base_channel = cc.id
          );
          delete from rhnServerProfile where base_channel = cc.id;
        end loop;

        -- Delete all errata packages 
        for e in errata loop
            delete from rhnErrataPackage where errata_id = e.id;
        end loop;

        -- Give the org's entitlements back to the main org.
        perform rhn_entitlements.remove_org_entitlements(org_id_in);

        -- Clean up tables where we don't have a cascading delete.
        delete from rhnChannel where org_id = org_id_in;
        delete from rhnDailySummaryQueue where org_id = org_id_in;
        delete from rhnFileList where org_id = org_id_in;
        delete from rhnServerGroup where org_id = org_id_in;
        delete from rhnContentSource where org_id = org_id_in;

        -- Delete the org.
        delete from web_customer where id = org_id_in;

    end;
    $$
    language plpgsql;

create or replace function delete_user(user_id_in in numeric, deleting_org in numeric default 0) returns void 
    as
    $$
    declare
    servergroups_needing_admins cursor for
            select    usgp.server_group_id    server_group_id
            from    rhnUserServerGroupPerms    usgp
            where    1=1
                and usgp.user_id = user_id_in
                and not exists (
                    select    1
                    from    rhnUserServerGroupPerms    sq_usgp
                    where    1=1
                        and sq_usgp.server_group_id = usgp.server_group_id
                        and    sq_usgp.user_id != user_id_in
                );
        users            numeric;
        our_org_id        numeric;
        other_users        numeric;
        other_org_admin    numeric;
        other_user_id  numeric;
        is_admin       numeric;
    begin
        select    wc.org_id
        into    our_org_id
        from    web_contact wc
        where    id = user_id_in;

        -- find any other users
        begin
            select    id, 1
            into    other_user_id, other_users
            from    web_contact
            where    1=1
                and org_id = our_org_id
                and id != user_id_in
                limit 1;
        exception
            when no_data_found then
                other_users := 0;
        end;

        -- now do org admin stuff
        if other_users != 0 then
            -- is user admin?
            select  count(1)
             into   is_admin
            from    rhnUserGroupType    ugt,
                    rhnUserGroup        ug,
                    rhnUserGroupMembers    ugm
            where    ugm.user_id = user_id_in
                and ugm.user_group_id = ug.id
                and ug.group_type = ugt.id
                and ugt.label = 'org_admin';
            if is_admin > 0 then
                begin
                    select    new_ugm.user_id
                    into    other_org_admin
                    from    rhnUserGroupMembers    new_ugm,
                            rhnUserGroupType    ugt,
                            rhnUserGroup        ug,
                            rhnUserGroupMembers    ugm
                    where    ugm.user_id = user_id_in
                        and ugm.user_group_id = ug.id
                        and ug.group_type = ugt.id
                        and ugt.label = 'org_admin'
                        and ug.id = new_ugm.user_group_id
                        and new_ugm.user_id != user_id_in
                        limit 1;
                exception
                    when no_data_found then
                        -- If we're deleting the org, we don't want to raise
                        -- the exception.
                        if deleting_org = 0 then
                           perform rhn_exception.raise_exception('cannot_delete_user');
                        end if;
                end;

                for sg in servergroups_needing_admins loop
                   perform rhn_user.add_servergroup_perm(other_org_admin,
                        sg.server_group_id);
                end loop;
            end if;
        end if;

        -- and now things for every user
        delete from rhnUserServerPerms where user_id = user_id_in;
        update rhnConfigRevision
           set changed_by_id = NULL
         where changed_by_id = user_id_in;
        if other_users != 0 then
            update        rhnRegToken
                set        user_id = coalesce(other_org_admin, other_user_id)
                where    org_id = our_org_id
                    and user_id = user_id_in;
        end if;

        begin
            delete from web_contact where id = user_id_in;
        exception
            when others then
               perform rhn_exception.raise_exception('cannot_delete_user');
        end;
        return;

        end;
        $$
        language plpgsql;


-- restore the original setting
update pg_settings set setting = overlay( setting placing '' from 1 for (length('rhn_org')+1) ) where name = 'search_path';
07070100000811000081B400000000000000000000000167AE11140000089C000000000000000000000000000000000000006700000000susemanager-schema/upgrade/spacewalk-schema-2.2-to-spacewalk-schema-2.3/017-drop_monitoring_tables.sql    
drop function rhn_install_org_satellites(numeric, numeric, character varying);
drop function rhn_prepare_install(character varying, numeric);
drop function rhn_install_satellite(numeric, numeric);
drop function rhn_synch_probe_state();
drop table rhn_probe_param_value;
drop table rhn_command_parameter;
drop view time_series;
drop table time_series_data;
drop table time_series_purge;
drop table rhn_check_probe;
drop table rhn_host_probe;
drop table rhn_sat_cluster_probe;
drop table rhn_url_probe_step;
drop table rhn_url_probe;
drop table rhn_service_probe_origins;
drop table rhn_probe;
drop table rhn_os_commands_xref;
drop table rhn_command_param_threshold;
drop table rhn_command;
drop table rhn_command_groups;
drop table rhn_metrics;
drop table rhn_command_class;
drop table rhn_command_requirements;
drop table rhn_command_queue_execs;
drop table rhn_command_queue_params;
drop table rhn_command_queue_instances;
drop table rhn_command_queue_commands;
drop table rhn_threshold_type;
drop table rhn_units;
drop table rhn_quanta;
drop table rhn_server_monitoring_info;
drop table rhn_os;
drop table rhn_deployed_probe;
drop table rhn_current_state_summaries;
drop table rhn_probe_types;
drop table rhn_probe_state;
drop table rhn_widget;
drop table rhn_check_suite_probe;
drop table rhn_check_suites;
drop table rhn_ll_netsaint;
drop table rhn_snmp_alert;
drop table rhn_redirect_method_targets;
drop table rhn_redirect_group_targets;
drop table rhn_redirect_email_targets;
drop table rhn_redirect_criteria;
drop table rhn_redirects;
drop table rhn_contact_group_members;
drop table rhn_contact_groups;
drop table rhn_contact_methods;
drop table rhn_method_types;
drop table rhn_pager_types;
drop table rhn_notification_formats;
drop table rhn_strategies;
drop table rhn_redirect_match_types;
drop table rhn_redirect_types;
drop table rhn_notifservers;
drop table rhn_semantic_data_type;
drop table rhn_sat_node;
drop table rhn_sat_cluster;
drop table rhn_command_target;
drop table rhn_physical_location;
drop table rhn_multi_scout_threshold;
drop table rhn_satellite_state;
drop table rhn_schedule_days;
drop table rhn_schedule_weeks;
drop table rhn_schedules;
drop table rhn_schedule_types;
07070100000812000081B400000000000000000000000167AE1114000000E8000000000000000000000000000000000000006400000000susemanager-schema/upgrade/spacewalk-schema-2.2-to-spacewalk-schema-2.3/018-drop_solaris_tables.sql   drop table rhnSolarisPatchSet;
drop table rhnSolarisPatch;
drop table rhnSolarisPatchType;
drop table rhnSolarisPatchedPackage;
drop table rhnSolarisPackage;
drop table rhnSolarisPatchSetMembers;
drop table rhnSolarisPatchPackages;
07070100000813000081B400000000000000000000000167AE1114000003ED000000000000000000000000000000000000006300000000susemanager-schema/upgrade/spacewalk-schema-2.2-to-spacewalk-schema-2.3/019-rhnServerGroupType.sql    
delete from rhnServerGroupMembers where server_group_id in
       (select sg.id
          from rhnServerGroup sg,
               rhnServerGroupType sgt
         where sg.group_type = sgt.id
           and sgt.label = 'monitoring_entitled');
alter table rhnServerGroup disable trigger rhnservergroup_log_trig;
delete from rhnServerGroup where group_type in
       (select id from rhnServerGroupType where label = 'monitoring_entitled');
alter table rhnServerGroup enable trigger rhnservergroup_log_trig;
delete from rhnSgTypeBaseAddOnCompat where addon_id in
       (select id from rhnServerGroupType where label = 'monitoring_entitled');
delete from rhnServerServerGroupArchCompat where server_group_type in
       (select id from rhnServerGroupType where label = 'monitoring_entitled');
delete from rhnServerGroupTypeFeature where server_group_type_id in
       (select id from rhnServerGroupType where label = 'monitoring_entitled');
delete from rhnServerGroupType where label = 'monitoring_entitled';
   07070100000814000081B400000000000000000000000167AE111400000035000000000000000000000000000000000000005C00000000susemanager-schema/upgrade/spacewalk-schema-2.2-to-spacewalk-schema-2.3/020-rhnInfoPane.sql   delete from rhnInfoPane where label like '%-probes';
   07070100000815000081B400000000000000000000000167AE1114000000EE000000000000000000000000000000000000006900000000susemanager-schema/upgrade/spacewalk-schema-2.2-to-spacewalk-schema-2.3/021-rhnServerNetwork-trigger.sql  
drop trigger if exists rhn_servnet_ipaddr_mon_trig on rhnServerNetwork;

create or replace function rhn_servernetwork_mod_trig_fun() returns trigger as
$$
begin
	new.modified := current_timestamp;
 	return new;
end;
$$ language plpgsql;
  07070100000816000081B400000000000000000000000167AE111400000407000000000000000000000000000000000000006300000000susemanager-schema/upgrade/spacewalk-schema-2.2-to-spacewalk-schema-2.3/022-armv7l-debian-arch.sql    insert into rhnServerArch (id, label, name, arch_type_id) values (sequence_nextval('rhn_server_arch_id_seq'), 'armv7l-debian-linux', 'arm Debian', lookup_arch_type('deb'));

insert into rhnServerChannelArchCompat (server_arch_id, channel_arch_id) values (LOOKUP_SERVER_ARCH('armv7l-debian-linux'), LOOKUP_CHANNEL_ARCH('channel-arm-deb'));

insert into rhnServerPackageArchCompat (server_arch_id, package_arch_id, preference) values (LOOKUP_SERVER_ARCH('armv7l-debian-linux'), LOOKUP_PACKAGE_ARCH('armhf-deb'), 0);

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type ) values (lookup_server_arch('armv7l-debian-linux'), lookup_sg_type('sw_mgr_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type ) values (lookup_server_arch('armv7l-debian-linux'), lookup_sg_type('enterprise_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type ) values (lookup_server_arch('armv7l-debian-linux'), lookup_sg_type('provisioning_entitled'));
 07070100000817000081B400000000000000000000000167AE1114000000A1000000000000000000000000000000000000005C00000000susemanager-schema/upgrade/spacewalk-schema-2.2-to-spacewalk-schema-2.3/023-rhnUserInfo.sql   ALTER TABLE rhnUserInfo ADD tasko_notify CHAR(1)
      DEFAULT('Y') NOT NULL
      CONSTRAINT rhn_user_info_tasko_ck
        CHECK (tasko_notify in ('Y', 'N'));
   07070100000818000081B400000000000000000000000167AE111400006173000000000000000000000000000000000000007A00000000susemanager-schema/upgrade/spacewalk-schema-2.2-to-spacewalk-schema-2.3/024-avoid_deadlock_update_server_needed_cache.sql --
-- Copyright (c) 2008--2014 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--

-- create schema rhn_server;

--update pg_setting
update pg_settings set setting = 'rhn_server,' || setting where name = 'search_path';

    create or replace function system_service_level(
    	server_id_in in numeric,
	service_level_in in varchar
    ) returns numeric as $$
    declare
    ents cursor is 
      select label from rhnServerEntitlementView
      where server_id = server_id_in;

    retval numeric := 0;

    begin
         for ent in ents loop
            retval := rhn_entitlements.entitlement_grants_service (ent.label, service_level_in);
            if retval = 1 then
               return retval;
            end if;
         end loop;

         return retval;

    end$$ language plpgsql;

        
    create or replace function can_change_base_channel(server_id_in IN NUMERIC)
    returns numeric
    as $$
    declare
    	throwaway numeric;
    begin
    	-- the idea: if we get past this query, the server is
	-- neither sat nor proxy, so base channel is changeable

	select 1 into throwaway
	  from rhnServer S
	 where S.id = server_id_in
	   and not exists (select 1 from rhnSatelliteInfo SI where SI.server_id = S.id)
	   and not exists (select 1 from rhnProxyInfo PI where PI.server_id = S.id);

        if not found then
	    return 0;
        end if;
	   
	return 1;
    end$$ language plpgsql;
	        
    create or replace function set_custom_value(
    	server_id_in in numeric,
	user_id_in in numeric,
	key_label_in in varchar,
	value_in in varchar
    ) returns void
    as $$
    declare
    	key_id_val numeric;
    begin
    	select CDK.id into strict key_id_val
	  from rhnCustomDataKey CDK,
	       rhnServer S
	 where S.id = server_id_in
	   and S.org_id = CDK.org_id
	   and CDK.label = key_label_in;
	   
	begin
	    insert into rhnServerCustomDataValue (server_id, key_id, value, created_by, last_modified_by)
	    values (server_id_in, key_id_val, value_in, user_id_in, user_id_in);
	exception
	    when UNIQUE_VIOLATION
	    	then
		update rhnServerCustomDataValue
		   set value = value_in,
		       last_modified_by = user_id_in
		 where server_id = server_id_in
		   and key_id = key_id_val;		   
	end;

    end$$ language plpgsql;
    
    create or replace function bulk_set_custom_value(
    	key_label_in in varchar,
	value_in in varchar,
	set_label_in in varchar,
	set_uid_in in numeric
    )
    returns integer
    as $$
    declare
        i integer;
        server record;
    begin
        i := 0;
        for server in (
           SELECT user_id, label, element, element_two
	     FROM rhnSet
	    WHERE label = set_label_in
	      AND user_id = set_uid_in
	) loop
	    if rhn_server.system_service_level(server.element, 'provisioning') = 1 then
	    	perform rhn_server.set_custom_value(server.element, set_uid_in, key_label_in, value_in);
            i := i + 1;
	    end if;
	end loop;
    return i;
    end$$ language plpgsql;

    create or replace function bulk_snapshot_tag(
    	org_id_in in numeric,
        tagname_in in varchar,
	set_label_in in varchar,
	set_uid_in in numeric
    ) returns void
    as $$
    declare
        server record;
    	snapshot_id numeric;
    begin
        for server in (
           SELECT user_id, label, element, element_two
	     FROM rhnSet
	    WHERE label = set_label_in
	      AND user_id = set_uid_in
	    ) loop
	    if rhn_server.system_service_level(server.element, 'provisioning') = 1 then
	    	    select max(id) into snapshot_id
	    	    from rhnSnapshot
	    	    where server_id = server.element;

	    	    if snapshot_id is null then
		    	perform rhn_server.snapshot_server(server.element, 'tagging system:  ' || tagname_in);
			
			select max(id) into snapshot_id
			from rhnSnapshot
			where server_id = server.element;
		    end if;
		 
		-- now have a snapshot_id to work with...
		begin
		    perform rhn_server.tag_snapshot(snapshot_id, org_id_in, tagname_in);
		exception
		    when UNIQUE_VIOLATION
		    	then
			-- do nothing, be forgiving...
			null;
		end;
	    end if;
	end loop;    
    end$$ language plpgsql;

    create or replace function tag_delete(
    	server_id_in in numeric,
	tag_id_in in numeric
    ) returns void
    as $$
    declare
    	snapshots cursor is
		select	snapshot_id
		from	rhnSnapshotTag
		where	tag_id = tag_id_in;
	tag_id_tmp numeric;
    begin
    	select	id into tag_id_tmp
	from	rhnTag
	where	id = tag_id_in
	for update;

	delete
		from	rhnSnapshotTag
		where	server_id = server_id_in
			and tag_id = tag_id_in;
	for snapshot in snapshots loop
		return;
	end loop;
	delete
		from rhnTag
		where id = tag_id_in;
    end$$ language plpgsql;

    create or replace function tag_snapshot(
        snapshot_id_in in numeric,
	org_id_in in numeric,
	tagname_in in varchar
    ) returns void
    as $$
    begin
    	insert into rhnSnapshotTag (snapshot_id, server_id, tag_id)
	select snapshot_id_in, server_id, lookup_tag(org_id_in, tagname_in)
	from rhnSnapshot
	where id = snapshot_id_in;
    end$$ language plpgsql;

    create or replace function bulk_snapshot(
    	reason_in in varchar,
	set_label_in in varchar,
	set_uid_in in numeric
    ) returns void
    as $$
    declare
        server record;
    begin
        for server in (
           SELECT user_id, label, element, element_two
	     FROM rhnSet
	    WHERE label = set_label_in
	      AND user_id = set_uid_in
	    ) loop
    	    if rhn_server.system_service_level(server.element, 'provisioning') = 1 then
	    	perform rhn_server.snapshot_server(server.element, reason_in);
	    end if;
	end loop;
    end$$ language plpgsql;

    create or replace function snapshot_server(
    	server_id_in in numeric,
	reason_in in varchar
    ) returns void
    as $$
    declare
    	snapshot_id_v numeric;
	revisions cursor is
		select distinct
			cr.id
		from	rhnConfigRevision	cr,
			rhnConfigFileName	cfn,
			rhnConfigFile		cf,
			rhnConfigChannel	cc,
			rhnServerConfigChannel	scc
		where	1=1
			and scc.server_id = server_id_in
			and scc.config_channel_id = cc.id
			and cc.id = cf.config_channel_id
			and cf.id = cr.config_file_id
			and cr.id = cf.latest_config_revision_id
			and cf.config_file_name_id = cfn.id
			and cf.id = lookup_first_matching_cf(scc.server_id, cfn.path);
	locked integer;
    begin
    	select nextval('rhn_snapshot_id_seq') into snapshot_id_v;

	insert into rhnSnapshot (id, org_id, server_id, reason) (
		select	snapshot_id_v,
			s.org_id,
			server_id_in,
			reason_in
		from	rhnServer s
		where	s.id = server_id_in
	);
	insert into rhnSnapshotChannel (snapshot_id, channel_id) (
		select	snapshot_id_v, sc.channel_id
		from	rhnServerChannel sc
		where	sc.server_id = server_id_in
	);
	insert into rhnSnapshotServerGroup (snapshot_id, server_group_id) (
		select	snapshot_id_v, sgm.server_group_id
		from	rhnServerGroupMembers sgm
		where	sgm.server_id = server_id_in
	);
        locked := 0;
        <<iloop>>
        while true loop
            begin
                insert into rhnPackageNEVRA (id, name_id, evr_id, package_arch_id)
                select nextval('rhn_pkgnevra_id_seq'), sp.name_id, sp.evr_id, sp.package_arch_id
                from rhnServerPackage sp
                where sp.server_id = server_id_in
                        and not exists
                        (select 1
                                from rhnPackageNEVRA nevra
                                where nevra.name_id = sp.name_id
                                        and nevra.evr_id = sp.evr_id
                                        and (nevra.package_arch_id = sp.package_arch_id
                                            or (nevra.package_arch_id is null
                                                and sp.package_arch_id is null)));
                exit iloop;
            exception when unique_violation then
                if locked = 1 then
                    raise;
                else
                    lock table rhnPackageNEVRA in exclusive mode;
                    locked := 1;
                end if;
            end;
        end loop;
	insert into rhnSnapshotPackage (snapshot_id, nevra_id) (
                select distinct snapshot_id_v, nevra.id
                from    rhnServerPackage sp, rhnPackageNEVRA nevra
                where   sp.server_id = server_id_in
                        and nevra.name_id = sp.name_id
                        and nevra.evr_id = sp.evr_id
                        and (nevra.package_arch_id = sp.package_arch_id
                            or (nevra.package_arch_id is null
                                and sp.package_arch_id is null))
	);

	insert into rhnSnapshotConfigChannel ( snapshot_id, config_channel_id ) (
		select	snapshot_id_v, scc.config_channel_id
		from	rhnServerConfigChannel scc
		where	server_id = server_id_in
	);

	for revision in revisions loop
		insert into rhnSnapshotConfigRevision (
				snapshot_id, config_revision_id
			) values (
				snapshot_id_v, revision.id
			);
	end loop;
    end$$ language plpgsql;

    create or replace function remove_action(
    	server_id_in in numeric,
	action_id_in in numeric
    ) returns void
    as $$
    declare
    	-- this really wants "nulls last", but 8.1.7.3.0 sucks ass.
	-- instead, we make a local table that holds our
	-- list of ids with null prereqs.  There's surely a better way
	-- (an array instead of a table maybe?  who knows...)
	-- but I've got code to do this handy that I can look at ;)
    	chained_actions cursor is
                with recursive r(id, prerequisite) as (
			select	id, prerequisite
			from	rhnAction
			where id = action_id_in
		union all
			select	r1.id, r1.prerequisite
			from	rhnAction r1, r
			where r.id = r1.prerequisite
		)
		select * from r
		order by prerequisite desc;
	sessions cursor is
		select	s.id
		from	rhnKickstartSession s
		where	server_id_in in (s.old_server_id, s.new_server_id)
			and s.action_id = action_id_in
			and not exists (
				select	1
				from	rhnKickstartSessionState ss
				where	ss.id = s.state_id
					and ss.label in ('failed','complete')
			);
	chain_ends numeric[];
	i numeric;
	prereq numeric := 1;
    begin
	select	prerequisite
	into	prereq
	from	rhnAction
	where	id = action_id_in;

	if prereq is not null then
		perform rhn_exception.raise_exception('action_is_child');
	end if;

        chain_ends := '{}';
	i := 1;
	for action in chained_actions loop
		if action.prerequisite is null then
			chain_ends[i] := action.id;
			i := i + 1;
		else
			delete from rhnServerAction
				where server_id = server_id_in
				and action_id = action.id;
		end if;
	end loop;

	delete from rhnServerAction
		where server_id = server_id_in
		and action_id = any(chain_ends);

	for s in sessions loop
		update rhnKickstartSession
			set 	state_id = (
					select	id
					from	rhnKickstartSessionState
					where	label = 'failed'
				),
				action_id = null
			where	id = s.id;
		perform set_ks_session_history_message(s.id, 'failed', 'Kickstart cancelled due to action removal');
	end loop;
    end$$ language plpgsql;
   
    create or replace function check_user_access(server_id_in in numeric, user_id_in in numeric)
    returns numeric
    as $$
    declare
    	has_access numeric;
    begin
    	-- first check; if this returns no rows, then the server/user are in different orgs, and we bail
        select 1 into has_access
	  from rhnServer S,
	       web_contact wc
	 where wc.org_id = s.org_id
	   and s.id = server_id_in
	   and wc.id = user_id_in;

        if not found then
          return 0;
        end if;

	-- okay, so they're in the same org.  if we have an org admin, they get a free pass
    	if rhn_user.check_role(user_id_in, 'org_admin') = 1
	then
	    return 1;
	end if;
		   
    	select 1 into has_access
	  from rhnServerGroupMembers SGM,
	       rhnUserServerGroupPerms USG
	 where SGM.server_group_id = USG.server_group_id
	   and SGM.server_id = server_id_in
	   and USG.user_id = user_id_in;

        if not found then
          return 0;
        end if;
	   
	return 1;
    end$$ language plpgsql;

    -- *******************************************************************
    -- FUNCTION: can_server_consume_virt_slot
    -- Returns 1 if the server id is eligible to consume a virtual slot,
    --   else returns 0.
    -- Called by: insert_into_servergroup, delete_from_servergroup
    -- *******************************************************************
    create or replace function can_server_consume_virt_slot(server_id_in in numeric,
                                           group_type_in in varchar)
    returns numeric                                           
    as $$
    declare
        server_virt_slots cursor is
            select vi.VIRTUAL_SYSTEM_ID
            from
                rhnVirtualInstance vi
            where
                -- server id is a virtual instance
                vi.VIRTUAL_SYSTEM_ID = server_id_in
                -- server id's host is virt entitled
                and exists ( select 1
                     from rhnServerEntitlementView sev
                 where vi.HOST_SYSTEM_ID = sev.server_id
                 and sev.label in ('virtualization_host',
                                   'virtualization_host_platform') )
                -- server id's host also has the ent we want
                and exists ( select 1
                     from rhnServerEntitlementView sev2
                 where vi.HOST_SYSTEM_ID = sev2.server_id
                 and sev2.label = group_type_in );

    begin
        for server_virt_slot in server_virt_slots loop
            return 1;
        end loop;
        return 0;
    end$$ language plpgsql;


    create or replace function insert_into_servergroup (
		server_id_in in numeric,
		server_group_id_in in numeric
    ) returns void
    as $$
    declare
		used_slots numeric;
		max_slots numeric;
		org_id numeric;
		mgmt_available numeric;
		mgmt_upgrade numeric;
		mgmt_sgid numeric;
		prov_available numeric;
		prov_upgrade numeric;
		prov_sgid numeric;
		group_label varchar;
		group_type numeric;
	begin
		-- first, group_type = null, because it's easy...

		-- this will rowlock the servergroup we're trying to change;
		-- we probably need to lock the other one, but I think the chances
		-- of it being a real issue are very small for now...
		select	sg.group_type, sg.org_id, sg.current_members, sg.max_members
		into	group_type, org_id, used_slots, max_slots
		from	rhnServerGroup sg
		where	sg.id = server_group_id_in
		for update of sg;

		if group_type is null then
			if used_slots >= max_slots then
				perform rhn_exception.raise_exception('servergroup_max_members');
			end if;

			insert into rhnServerGroupMembers(
					server_id, server_group_id
				) values (
					server_id_in, server_group_id_in
				);
			update rhnServerGroup
				set current_members = current_members + 1
				where id = server_group_id_in;

			perform rhn_cache.update_perms_for_server_group(server_group_id_in);
			return;
		end if;

		-- now for group_type != null
		-- 
		select	label
		into	group_label
		from	rhnServerGroupType	sgt
		where	sgt.id = group_type;

		-- the naive easy path that gets hit most often and has to be quickest.
		if group_label in ('sw_mgr_entitled',
                           'enterprise_entitled',
                           'monitoring_entitled',
                           'provisioning_entitled',
                           'virtualization_host',
                           'virtualization_host_platform') then
			if used_slots >= max_slots and 
               (rhn_server.can_server_consume_virt_slot(server_id_in, group_label) != 1) 
               then
				perform rhn_exception.raise_exception('servergroup_max_members');
			end if;

			insert into rhnServerGroupMembers(
					server_id, server_group_id
				) values (
					server_id_in, server_group_id_in
				);

            -- Only update current members if the system in consuming a 
            -- physical slot.
            if rhn_server.can_server_consume_virt_slot(server_id_in, group_label) = 0 then
                update rhnServerGroup
                set current_members = current_members + 1
                where id = server_group_id_in;
            end if;                

			return;
		end if;
	end$$ language plpgsql;

	create or replace function insert_into_servergroup_maybe (
		server_id_in in numeric,
		server_group_id_in in numeric
	) returns numeric as $$ 
    declare
		retval numeric := 0;
		servergroups cursor is
			select	s.id	server_id,
					sg.id	server_group_id
			from	rhnServerGroup	sg,
					rhnServer		s
			where	s.id = server_id_in
				and sg.id = server_group_id_in
				and s.org_id = sg.org_id
				and not exists (
					select	1
					from	rhnServerGroupMembers sgm
					where	sgm.server_id = s.id
						and sgm.server_group_id = sg.id
				);
	begin
		for sgm in servergroups loop
			perform rhn_server.insert_into_servergroup(sgm.server_id, sgm.server_group_id);
			retval := retval + 1;
		end loop;
		return retval;
	end$$ language plpgsql;

	create or replace function insert_set_into_servergroup (
		server_group_id_in in numeric,
		user_id_in in numeric,
		set_label_in in varchar
	) returns void
        as $$
    declare
		servers cursor is
			select	st.element	id
			from	rhnSet		st
			where	st.user_id = user_id_in
				and st.label = set_label_in
				and exists (
					select	1
					from	rhnUserManagedServerGroups umsg
					where	umsg.server_group_id = server_group_id_in
						and umsg.user_id = user_id_in
					)
				and not exists (
					select	1
					from	rhnServerGroupMembers sgm
					where	sgm.server_id = st.element
						and sgm.server_group_id = server_group_id_in
				);
	begin
		for s in servers loop
			perform rhn_server.insert_into_servergroup(s.id, server_group_id_in);
		end loop;
	end$$ language plpgsql;
		
    create or replace function delete_from_servergroup (
    	server_id_in in numeric,
		server_group_id_in in numeric
    ) returns void
    as $$
    declare
        server_virt_groups cursor is
            select 1
            from rhnServerEntitlementVirtual sev
            where sev.server_id = server_id_in
            and sev.server_group_id = server_group_id_in;

		oid numeric;
		mgmt_sgid numeric;
		label varchar;
		group_type numeric;
	begin
			select	sg.group_type, sg.org_id
			into	group_type,	oid
			from	rhnServerGroupMembers	sgm,
					rhnServerGroup			sg
			where	sg.id = server_group_id_in
				and sg.id = sgm.server_group_id
				and sgm.server_id = server_id_in
			for update of sg;

			if not found then
				perform rhn_exception.raise_exception('server_not_in_group');
			end if;

		-- do group_type is null first
		if group_type is null then
			delete from rhnServerGroupMembers
				where server_group_id = server_group_id_in
				and	server_id = server_id_in;
			update rhnServerGroup
				set current_members = current_members - 1
				where id = server_group_id_in;
			perform rhn_cache.update_perms_for_server_group(server_group_id_in);
			return;
		end if;

		select	sgt.label
		into	label
		from	rhnServerGroupType sgt
		where	sgt.id = group_type;

		if label in ('sw_mgr_entitled',
                     'enterprise_entitled', 
                     'provisioning_entitled', 
                     'monitoring_entitled',
                     'virtualization_host',
                     'virtualization_host_platform') then

            -- Only update current members if the system is consuming
            -- a physical slot.
            for server_virt_group in server_virt_groups loop                
                delete from rhnServerGroupMembers
                where server_group_id = server_group_id_in
                and	server_id = server_id_in;
                return;
            end loop;                

            delete from rhnServerGroupMembers
            where server_group_id = server_group_id_in
            and	server_id = server_id_in;

            update rhnServerGroup
            set current_members = current_members - 1
            where id = server_group_id_in;

		end if;
	end$$ language plpgsql;

	create or replace function delete_set_from_servergroup (
		server_group_id_in in numeric,
		user_id_in in numeric,
		set_label_in in varchar
	) returns void
        as $$	
        declare
		servergroups cursor is
			select	sgm.server_id, sgm.server_group_id
			from	rhnSet st,
					rhnServerGroupMembers sgm
			where	sgm.server_group_id = server_group_id_in
				and st.user_id = user_id_in
				and st.label = set_label_in
				and sgm.server_id = st.element
				and exists (
					select	1
					from	rhnUserManagedServerGroups usgp
					where	usgp.server_group_id = server_group_id_in
						and usgp.user_id = user_id_in
				);
	begin
		for sgm in servergroups loop
			perform rhn_server.delete_from_servergroup(sgm.server_id, server_group_id_in);
		end loop;
	end$$ language plpgsql;

	create or replace function clear_servergroup (
		server_group_id_in in numeric
	) returns void
        as $$
        declare
		servers cursor is
			select	sgm.server_id	id
			from	rhnServerGroupMembers sgm
			where	sgm.server_group_id = server_group_id_in;
	begin
		for s in servers loop
			perform rhn_server.delete_from_servergroup(s.id, server_group_id_in);
		end loop;
	end$$ language plpgsql;

	create or replace function delete_from_org_servergroups (
		server_id_in in numeric
	) returns void
        as $$
        declare
		servergroups cursor is
			select	sgm.server_group_id id
			from	rhnServerGroup sg,
					rhnServerGroupMembers sgm
			where	sgm.server_id = server_id_in
				and sgm.server_group_id = sg.id
				and sg.group_type is null;
	begin
		for sg in servergroups loop
			perform rhn_server.delete_from_servergroup(server_id_in, sg.id);
		end loop;
	end$$ language plpgsql;

	create or replace function get_ip_address (
		server_id_in in numeric
	) returns varchar as $$
        declare
		interfaces cursor is
			select	ni.name as name, na4.address as address
			from	rhnServerNetInterface ni,
			        rhnServerNetAddress4 na4
			where	server_id = server_id_in
                and ni.id = na4.interface_id
				and na4.address != '127.0.0.1';
		addresses cursor is
			select	ipaddr ip_addr
			from	rhnServerNetwork
			where	server_id = server_id_in
				and ipaddr != '127.0.0.1';
	begin
		for addr in addresses loop
			return addr.ip_addr;
		end loop;
		for iface in interfaces loop
			return iface.address;
		end loop;
		return NULL;
	end$$ language plpgsql;

    create or replace function update_needed_cache(
        server_id_in in numeric
	) returns void as $$
    declare
      update_lock numeric;
    begin
      select id into update_lock from rhnServer where id = server_id_in for update;
      delete from rhnServerNeededCache
        where server_id = server_id_in;
      insert into rhnServerNeededCache
             (server_id, errata_id, package_id, channel_id)
        (select distinct sp.server_id, x.errata_id, p.id, x.channel_id
           FROM (SELECT sp_sp.server_id, sp_sp.name_id,
		        sp_sp.package_arch_id, max(sp_pe.evr) AS max_evr
                   FROM rhnServerPackage sp_sp
                   join rhnPackageEvr sp_pe ON sp_pe.id = sp_sp.evr_id
                  GROUP BY sp_sp.server_id, sp_sp.name_id, sp_sp.package_arch_id) sp
           join rhnPackage p ON p.name_id = sp.name_id
           join rhnPackageEvr pe ON pe.id = p.evr_id AND sp.max_evr < pe.evr
           join rhnPackageUpgradeArchCompat puac
	            ON puac.package_arch_id = sp.package_arch_id
		    AND puac.package_upgrade_arch_id = p.package_arch_id
           join rhnServerChannel sc ON sc.server_id = sp.server_id
           join rhnChannelPackage cp ON cp.package_id = p.id
	            AND cp.channel_id = sc.channel_id
           left join (SELECT ep.errata_id, ce.channel_id, ep.package_id
                        FROM rhnChannelErrata ce
                        join rhnErrataPackage ep
			         ON ep.errata_id = ce.errata_id
			join rhnServerChannel sc_sc
			         ON sc_sc.channel_id = ce.channel_id
		       WHERE sc_sc.server_id = server_id_in) x
             ON x.channel_id = sc.channel_id AND x.package_id = cp.package_id
          where sp.server_id = server_id_in);
	end$$ language plpgsql;
-- restore the original setting
update pg_settings set setting = overlay( setting placing '' from 1 for (length('rhn_server')+1) ) where name = 'search_path';
 07070100000819000081B400000000000000000000000167AE11140000019C000000000000000000000000000000000000006500000000susemanager-schema/upgrade/spacewalk-schema-2.2-to-spacewalk-schema-2.3/025-rhnPackageKey-EPEL-7.sql  -- EPEL 7
update rhnPackageKey set provider_id = lookup_package_provider('EPEL')
 where key_id = '6a2faea2352c64e5';

insert into rhnPackageKey (id, key_id, key_type_id, provider_id)
    (select sequence_nextval('rhn_pkey_id_seq'), '6a2faea2352c64e5', lookup_package_key_type('gpg'), lookup_package_provider('EPEL') from dual
     where 1 not in (select 1 from rhnPackageKey where key_id = '6a2faea2352c64e5'));
0707010000081A000081B400000000000000000000000167AE111400000707000000000000000000000000000000000000006B00000000susemanager-schema/upgrade/spacewalk-schema-2.2-to-spacewalk-schema-2.3/026-fixing-not-upgraded-schema.sql    
-- Dropping tables
drop table if exists rhn_command_queue_sessions;

-- Dropping PostgreSQL only functions
drop function if exists rhn_cmeth_val_trig_fun();
drop function if exists rhn_probe_delete_trigger_fun();
drop function if exists rhn_probe_insert_trigger_fun();
drop function if exists rhn_servnet_ipaddr_mon_trig_fun();
drop function if exists rhn_solaris_p_mod_trig_fun();
drop function if exists rhn_solaris_psm_mod_trig_fun();
drop function if exists rhn_solaris_ps_mod_trig_fun();
drop function if exists time_series_purge_mod_trig_fun();

-- Dropping sequences
drop sequence if exists rhn_check_suites_recid_seq;
drop sequence if exists rhn_command_q_comm_recid_seq;
drop sequence if exists rhn_command_q_inst_recid_seq;
drop sequence if exists rhn_commands_recid_seq;
drop sequence if exists rhn_command_target_recid_seq;
drop sequence if exists rhn_contact_groups_recid_seq;
drop sequence if exists rhn_contact_methods_recid_seq;
drop sequence if exists rhn_host_probes_recid_seq;
drop sequence if exists rhn_ntfmt_recid_seq;
drop sequence if exists rhn_pager_types_recid_seq;
drop sequence if exists rhn_physical_loc_recid_seq;
drop sequence if exists rhn_probes_recid_seq;
drop sequence if exists rhn_redirect_crit_recid_seq;
drop sequence if exists rhn_redirects_recid_seq;
drop sequence if exists rhn_redirect_types_recid_seq;
drop sequence if exists rhn_schedule_days_recid_seq;
drop sequence if exists rhn_schedules_recid_seq;
drop sequence if exists rhn_schedule_types_recid_seq;
drop sequence if exists rhn_schedule_weeks_recid_seq;
drop sequence if exists rhn_snmp_alert_recid_seq;
drop sequence if exists rhn_solaris_ps_seq;
drop sequence if exists rhn_solaris_pt_seq;
drop sequence if exists rhn_strategies_recid_seq;
drop sequence if exists rhn_url_probe_step_recid_seq;
 0707010000081B000081B400000000000000000000000167AE1114000006A7000000000000000000000000000000000000006900000000susemanager-schema/upgrade/spacewalk-schema-2.2-to-spacewalk-schema-2.3/027-fixing-not-upgraded-data.sql  -- Inserting into rhnPackageKey
update rhnPackageKey set provider_id = lookup_package_provider('Fedora')
 where key_id = '11adc0948e1431d5';

insert into rhnPackageKey (id, key_id, key_type_id, provider_id)
    (select sequence_nextval('rhn_pkey_id_seq'), '11adc0948e1431d5', lookup_package_key_type('gpg'), lookup_package_provider('Fedora') from dual
     where not exists (select 1 from rhnPackageKey where key_id = '11adc0948e1431d5'));

update rhnPackageKey set provider_id = lookup_package_provider('Fedora')
 where key_id = 'd8d1fa8ca29cb19c';

insert into rhnPackageKey (id, key_id, key_type_id, provider_id)
    (select sequence_nextval('rhn_pkey_id_seq'), 'd8d1fa8ca29cb19c', lookup_package_key_type('gpg'), lookup_package_provider('Fedora') from dual
     where not exists (select 1 from rhnPackageKey where key_id = 'd8d1fa8ca29cb19c'));

update rhnPackageKey set provider_id = lookup_package_provider('Fedora')
 where key_id = 'dbeae2e4efe550f5';

insert into rhnPackageKey (id, key_id, key_type_id, provider_id)
    (select sequence_nextval('rhn_pkey_id_seq'), 'dbeae2e4efe550f5', lookup_package_key_type('gpg'), lookup_package_provider('Fedora') from dual
     where not exists (select 1 from rhnPackageKey where key_id = 'dbeae2e4efe550f5'));

-- Inserting into rhnPackageUpgradeArchCompat
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) select
LOOKUP_PACKAGE_ARCH('ppc64le'), LOOKUP_PACKAGE_ARCH('ppc64le'), current_timestamp, current_timestamp from dual
where not exists (select 1 from rhnPackageUpgradeArchCompat where package_arch_id = LOOKUP_PACKAGE_ARCH('ppc64le') and package_upgrade_arch_id = LOOKUP_PACKAGE_ARCH('ppc64le'));
 0707010000081C000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000004800000000susemanager-schema/upgrade/spacewalk-schema-2.3-to-spacewalk-schema-2.4   0707010000081D000081B400000000000000000000000167AE11140000066F000000000000000000000000000000000000006D00000000susemanager-schema/upgrade/spacewalk-schema-2.3-to-spacewalk-schema-2.4/001-rhnPackageKey-Spacewalk-2014.sql  update rhnPackageKey set provider_id = lookup_package_provider('Spacewalk')
 where key_id = '41605346066e5810';

insert into rhnPackageKey (id, key_id, key_type_id, provider_id)
    (select sequence_nextval('rhn_pkey_id_seq'), '41605346066e5810', lookup_package_key_type('gpg'), lookup_package_provider('Spacewalk') from dual
     where not exists (select 1 from rhnPackageKey where key_id = '41605346066e5810'));

update rhnPackageKey set provider_id = lookup_package_provider('Fedora')
 where key_id = '32474cf834ec9cba';

insert into rhnPackageKey (id, key_id, key_type_id, provider_id)
    (select sequence_nextval('rhn_pkey_id_seq'), '32474cf834ec9cba', lookup_package_key_type('gpg'), lookup_package_provider('Fedora') from dual
     where not exists (select 1 from rhnPackageKey where key_id = '32474cf834ec9cba'));

update rhnPackageKey set provider_id = lookup_package_provider('Fedora')
 where key_id = 'b4bb871c873529b8';

insert into rhnPackageKey (id, key_id, key_type_id, provider_id)
    (select sequence_nextval('rhn_pkey_id_seq'), 'b4bb871c873529b8', lookup_package_key_type('gpg'), lookup_package_provider('Fedora') from dual
     where not exists (select 1 from rhnPackageKey where key_id = 'b4bb871c873529b8'));

update rhnPackageKey set provider_id = lookup_package_provider('Spacewalk')
 where key_id = 'dcc981cdb8002de1';

insert into rhnPackageKey (id, key_id, key_type_id, provider_id)
    (select sequence_nextval('rhn_pkey_id_seq'), 'dcc981cdb8002de1', lookup_package_key_type('gpg'), lookup_package_provider('Spacewalk') from dual
     where not exists (select 1 from rhnPackageKey where key_id = 'dcc981cdb8002de1'));
 0707010000081E000081B400000000000000000000000167AE111400000C79000000000000000000000000000000000000006E00000000susemanager-schema/upgrade/spacewalk-schema-2.3-to-spacewalk-schema-2.4/001-rhnServerGroupOverview-errata.sql --
-- Copyright (c) 2008--2015 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
CREATE OR REPLACE VIEW rhnServerGroupOverview (
         ORG_ID, SECURITY_ERRATA, BUG_ERRATA, ENHANCEMENT_ERRATA, GROUP_ID, GROUP_NAME, GROUP_ADMINS, SERVER_COUNT, MODIFIED, MAX_MEMBERS
)
AS
  SELECT SG.org_id,
         (SELECT COUNT(distinct E.id)
            FROM rhnErrata E,
                 rhnServerNeededErrataCache SNEC,
                 rhnServerGroupMembers SGM
           WHERE E.advisory_type = 'Security Advisory'
                 and SNEC.errata_id = e.id
                 and SNEC.server_id = sgm.server_id
                 and sgm.server_group_id = sg.id
                 AND EXISTS ( SELECT 1
                              FROM rhnServerFeaturesView SFV
                              WHERE SFV.server_id = SGM.server_id
                                    AND SFV.label = 'ftr_system_grouping')),
         (SELECT COUNT(distinct E.id)
            FROM rhnErrata E,
                 rhnServerNeededErrataCache SNEC,
                 rhnServerGroupMembers SGM
           WHERE E.advisory_type = 'Bug Fix Advisory'
                 and SNEC.errata_id = e.id
                 and SNEC.server_id = sgm.server_id
                 and sgm.server_group_id = sg.id
                 AND EXISTS ( SELECT 1
                              FROM rhnServerFeaturesView SFV
                              WHERE SFV.server_id = SGM.server_id
                                    AND SFV.label = 'ftr_system_grouping')),
         (SELECT COUNT(distinct E.id)
            FROM rhnErrata E,
                 rhnServerNeededErrataCache SNEC,
                 rhnServerGroupMembers SGM
           WHERE E.advisory_type = 'Product Enhancement Advisory'
                 and SNEC.errata_id = e.id
                 and SNEC.server_id = sgm.server_id
                 and sgm.server_group_id = sg.id
                 AND EXISTS ( SELECT 1
                              FROM rhnServerFeaturesView SFV
                              WHERE SFV.server_id = SGM.server_id
                                    AND SFV.label = 'ftr_system_grouping')),
         SG.id, SG.name,
         (SELECT COUNT(*) FROM rhnUserManagedServerGroups UMSG WHERE UMSG.server_group_id = SG.id),
         (SELECT COUNT(*) FROM rhnServerGroupMembers SGM WHERE SGM.server_group_id = SG.id
                 AND EXISTS ( SELECT 1
                              FROM rhnServerFeaturesView SFV
                              WHERE SFV.server_id = SGM.server_id
                                    AND SFV.label = 'ftr_system_grouping')),
         CURRENT_TIMESTAMP, MAX_MEMBERS
    FROM rhnServerGroup SG;

   0707010000081F000081B400000000000000000000000167AE1114000004EE000000000000000000000000000000000000007100000000susemanager-schema/upgrade/spacewalk-schema-2.3-to-spacewalk-schema-2.4/001-rhnServerOutdatedPackages-errata.sql  --
-- Copyright (c) 2008--2015 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--

CREATE OR REPLACE VIEW
rhnServerOutdatedPackages
(
    server_id,
    package_name_id,
    package_evr_id,    
    package_arch_id,
    package_nvre,
    errata_id,
    errata_advisory
)
AS
SELECT DISTINCT SNC.server_id,
       P.name_id,
       P.evr_id,
       P.package_arch_id,
       PN.name || '-' || evr_t_as_vre_simple( PE.evr ),
       E.id,
       E.advisory
  FROM rhnPackageName PN,
       rhnPackageEVR PE,
       rhnPackage P,
       rhnServerNeededCache SNC
         left outer join
        rhnErrata E
          on SNC.errata_id = E.id
 WHERE SNC.package_id = P.id
   AND P.name_id = PN.id
   AND P.evr_id = PE.id;

  07070100000820000081B400000000000000000000000167AE1114000003F5000000000000000000000000000000000000006800000000susemanager-schema/upgrade/spacewalk-schema-2.3-to-spacewalk-schema-2.4/002-auto-errata-update-task.sql   INSERT INTO rhnTaskoBunch (id, name, description, org_bunch)
             VALUES (sequence_nextval('rhn_tasko_bunch_id_seq'), 'auto-errata-bunch', 'Schedule automatic errata update actions', null);


INSERT INTO rhnTaskoSchedule (id, job_label, bunch_id, active_from, cron_expr)
    VALUES(sequence_nextval('rhn_tasko_schedule_id_seq'), 'auto-errata-default',
        (SELECT id FROM rhnTaskoBunch WHERE name='auto-errata-bunch'),
        current_timestamp, '0 5/10 * * * ?');

INSERT INTO rhnTaskoTask (id, name, class)
         VALUES (sequence_nextval('rhn_tasko_task_id_seq'), 'auto-errata', 'com.redhat.rhn.taskomatic.task.AutoErrataTask');

INSERT INTO rhnTaskoTemplate (id, bunch_id, task_id, ordering, start_if)
             VALUES (sequence_nextval('rhn_tasko_template_id_seq'),
                        (SELECT id FROM rhnTaskoBunch WHERE name='auto-errata-bunch'),
                        (SELECT id FROM rhnTaskoTask WHERE name='auto-errata'),
                        0,
                        null);
   07070100000821000081B400000000000000000000000167AE111400000030000000000000000000000000000000000000006C00000000susemanager-schema/upgrade/spacewalk-schema-2.3-to-spacewalk-schema-2.4/002-rhnPushDispatcher-drop-port.sql   ALTER TABLE rhnPushDispatcher DROP COLUMN port;
07070100000822000081B400000000000000000000000167AE1114000105B8000000000000000000000000000000000000006500000000susemanager-schema/upgrade/spacewalk-schema-2.3-to-spacewalk-schema-2.4/003-rhn_entitlements.pkb.sql  --
-- Copyright (c) 2008--2015 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

-- create schema rhn_entitlements;

-- setup search_path so that these functions are created in appropriate schema.
update pg_settings set setting = 'rhn_entitlements,' || setting where name = 'search_path';

   create or replace function find_compatible_sg (
      server_id_in in numeric,
      type_label_in in varchar
   )
   returns numeric
as $$
    declare
      servergroups cursor for
         select sg.id
           from rhnServerGroupType             sgt,
                rhnServerGroup                 sg,
                rhnServer                     s,
                rhnServerServerGroupArchCompat ssgac
          where s.id = server_id_in
            and s.org_id = sg.org_id
            and sgt.label = type_label_in
            and sg.group_type = sgt.id
            and ssgac.server_group_type = sgt.id
            and ssgac.server_arch_id = s.server_arch_id
            and not exists (
                     select 1
                      from rhnServerGroupMembers sgm
                     where sgm.server_group_id = sg.id
                       and sgm.server_id = s.id);


   begin
      for servergroup in servergroups loop
         return servergroup.id;
      end loop;

      --no servergroup found
      return NULL;
   end$$
language plpgsql;

    -- *******************************************************************
    -- PROCEDURE: remove_org_entitlements
    --
    -- Removes both system entitlements and channel subscriptions
    -- that are currently assigned to an org and re-assigns to the
    -- master org (org_id = 1).
    --
    -- When we call this we expect everything to already be unentitled
    -- which shoul be handled by delete_org.
    --
    -- Called by: delete_org
    -- *******************************************************************
    create or replace function remove_org_entitlements (
        org_id_in numeric
    ) returns void
as $$
    declare
        system_ents cursor for
        select sg.id, sg.max_members, sg.group_type
        from rhnServerGroup sg
        where group_type is not null
          and org_id = org_id_in;

        channel_subs cursor for
        select pcf.channel_family_id, pcf.max_members
        from rhnChannelFamily cf,
             rhnPrivateChannelFamily pcf
        where pcf.org_id = org_id_in
          and pcf.channel_family_id = cf.id
          and cf.org_id is null;

    begin

        for system_ent in system_ents loop
            update rhnServerGroup
            set max_members = max_members + system_ent.max_members
            where org_id = 1
              and group_type = system_ent.group_type;
        end loop;

        update rhnServerGroup
        set max_members = 0
        where org_id = org_id_in;

        for channel_sub in channel_subs loop
            update rhnPrivateChannelFamily
            set max_members = max_members + channel_sub.max_members
            where org_id = 1
              and channel_family_id = channel_sub.channel_family_id;
        end loop;

        update rhnPrivateChannelFamily
        set max_members = 0
        where org_id = org_id_in;

    end$$
language plpgsql;

    create or replace function entitlement_grants_service (
        entitlement_in in varchar,
        service_level_in in varchar
    ) returns numeric
as $$
    begin
        if service_level_in = 'provisioning' then
            if entitlement_in = 'provisioning_entitled' then
                return 1;
            else
                return 0;
            end if;
        elsif service_level_in = 'management' then
            if entitlement_in = 'enterprise_entitled' then
                return 1;
            else
                return 0;
            end if;
        elsif service_level_in = 'monitoring' then
            if entitlement_in = 'monitoring_entitled' then
                return 1;
            end if;
        elsif service_level_in = 'updates' then
            return 1;
        else
            return 0;
        end if;
    end$$
language plpgsql;

    create or replace function lookup_entitlement_group (
        org_id_in in numeric,
        type_label_in in varchar default 'sw_mgr_entitled'
    ) returns numeric
as $$
    declare
        server_groups cursor for
            select  sg.id               server_group_id
            from    rhnServerGroup      sg,
                    rhnServerGroupType  sgt
            where   sgt.label = type_label_in
                and sgt.id = sg.group_type
                and sg.org_id = org_id_in;
    begin
        for sg in server_groups loop
            return sg.server_group_id;
        end loop;
        return rhn_entitlements.create_entitlement_group(
                org_id_in,
                type_label_in
            );
    end$$
language plpgsql;

    create or replace function create_entitlement_group (
        org_id_in in numeric,
        type_label_in in varchar default 'sw_mgr_entitled'
    ) returns numeric
as $$
    declare
        sg_id_val numeric;
    begin
        select  nextval('rhn_server_group_id_seq')
        into    sg_id_val;

        insert into rhnServerGroup (
                id, name, description, max_members, current_members,
                group_type, org_id
            ) (
                select  sg_id_val, sgt.label, sgt.label,
                        0, 0, sgt.id, org_id_in
                from    rhnServerGroupType sgt
                where   sgt.label = type_label_in
            );

        return sg_id_val;
    end$$
language plpgsql;

   create or replace function can_entitle_server (
      server_id_in   in numeric,
      type_label_in  in varchar
   )
   returns numeric
as $$
    declare
      addon_servergroups cursor (base_label_in varchar,
                                 addon_label_in varchar) for
         select
            addon_id
         from
            rhnSGTypeBaseAddonCompat
         where base_id = lookup_sg_type (base_label_in)
           and addon_id = lookup_sg_type (addon_label_in);

      previous_ent        varchar[];
      is_base_in          char   := 'N';
      is_base_current     char   := 'N';
      i                   numeric := 0;
      sgid                numeric := 0;

   begin

      previous_ent := rhn_entitlements.get_server_entitlement(server_id_in);

      select distinct is_base
      into is_base_in
      from rhnServerGroupType
      where label = type_label_in;

      if array_upper(previous_ent, 1) is null or array_upper(previous_ent, 1) = 0 then
         if is_base_in = 'Y' then
            sgid := rhn_entitlements.find_compatible_sg (server_id_in, type_label_in);
            if sgid is not null then
              -- rhn_server.insert_into_servergroup (server_id_in, sgid);
              return 1;
            else
              -- rhn_exception.raise_exception ('invalid_base_entitlement');
              return 0;
            end if;
         else
            -- rhn_exception.raise_exception ('invalid_base_entitlement');
            return 0;
         end if;

      -- there are previous ents, first make sure we're not trying to entitle a base ent
      elsif is_base_in = 'Y' then
         -- rhn_exception.raise_exception ('invalid_addon_entitlement');
         return 0;

      -- it must be an addon, so proceed with the entitlement
      else

         -- find the servers base ent
         is_base_current := 'N';
         i := 0;
         while is_base_current = 'N' and i < array_upper(previous_ent, 1)
         loop
            i := i + 1;
            select is_base
            into is_base_current
            from rhnServerGroupType
            where label = previous_ent[i];
         end loop;

         -- never found a base ent, that would be strange
         if is_base_current  = 'N' then
            -- rhn_exception.raise_exception ('invalid_base_entitlement');
            return 0;
         end if;

         -- this for loop verifies the validity of the addon path
         for addon_servergroup in addon_servergroups  (previous_ent[i], type_label_in) loop
            -- find an appropriate sgid for the addon and entitle the server
            sgid := rhn_entitlements.find_compatible_sg (server_id_in, type_label_in);
            if sgid is not null then
               -- rhn_server.insert_into_servergroup (server_id_in, sgid);
               return 1;
            else
               -- rhn_exception.raise_exception ('invalid_addon_entitlement');
               return 0;
            end if;
         end loop;

      end if;

      return 0;

   end$$
language plpgsql;

   create or replace function can_switch_base (
      server_id_in   in    integer,
      type_label_in  in    varchar
   )
   returns numeric
as $$
   declare
      type_label_in_is_base   char(1);
      sgid                    numeric;

   begin

       select is_base into type_label_in_is_base
       from rhnServerGroupType
       where label = type_label_in;

       if not found then
          perform rhn_exception.raise_exception ( 'invalid_entitlement' );
       end if;

      if type_label_in_is_base = 'N' then
         perform rhn_exception.raise_exception ( 'invalid_entitlement' );
      else
         sgid := rhn_entitlements.find_compatible_sg ( server_id_in,
                                                       type_label_in );
         if sgid is not null then
           return 1;
         else
           return 0;
         end if;
      end if;

   end$$
language plpgsql;

    create or replace function entitle_server (
        server_id_in in numeric,
        type_label_in in varchar default 'sw_mgr_entitled'
    ) returns void
as $$
    declare
      sgid  numeric := 0;
      is_virt numeric := 0;

    begin

      select 1 into is_virt
        from rhnServerEntitlementView
        where server_id = server_id_in
          and label in ('virtualization_host', 'virtualization_host_platform');

      if not found then
          is_virt := 0;
      end if;

      if is_virt = 0 and (type_label_in = 'virtualization_host' or
                          type_label_in = 'virtualization_host_platform') then

        is_virt := 1;
      end if;

      if rhn_entitlements.can_entitle_server(server_id_in,
                                             type_label_in) = 1 then
         sgid := rhn_entitlements.find_compatible_sg (server_id_in,
                                                      type_label_in);
         if sgid is not null then
            insert into rhnServerHistory ( id, server_id, summary, details )
            values ( nextval('rhn_event_id_seq'), server_id_in,
                     'added system entitlement ',
                      case type_label_in
                       when 'enterprise_entitled' then 'Management'
                       when 'sw_mgr_entitled' then 'Update'
                       when 'provisioning_entitled' then 'Provisioning'
                       when 'monitoring_entitled' then 'Monitoring'
                       when 'virtualization_host' then 'Virtualization'
                       when 'virtualization_host_platform' then
                            'Virtualization Platform' end  );

            perform rhn_server.insert_into_servergroup (server_id_in, sgid);

            if is_virt = 1 then
              perform rhn_entitlements.repoll_virt_guest_entitlements(server_id_in);
            end if;

         else
            perform rhn_exception.raise_exception ('no_available_server_group');
         end if;
      else
         perform rhn_exception.raise_exception ('invalid_entitlement');
      end if;
   end$$
language plpgsql;

    create or replace function remove_server_entitlement (
        server_id_in in numeric,
        type_label_in in varchar default 'sw_mgr_entitled',
        repoll_virt_guests in numeric default 1
    ) returns void
as $$
    declare
      group_id numeric;
      type_is_base char;
      is_virt numeric := 0;
    begin
      -- would be nice if there were a virt attribute of entitlement types, not have to specify 2 different ones...
        select 1 into is_virt
          from rhnServerEntitlementView
          where server_id = server_id_in
            and label in ('virtualization_host', 'virtualization_host_platform');
        if not found then
            is_virt := 0;
        end if;

        select  sg.id, sgt.is_base
        into group_id, type_is_base
        from    rhnServerGroupType sgt,
            rhnServerGroup sg,
                rhnServerGroupMembers sgm,
                rhnServer s
        where   s.id = server_id_in
            and s.id = sgm.server_id
            and sgm.server_group_id = sg.id
            and sg.org_id = s.org_id
            and sgt.label = type_label_in
            and sgt.id = sg.group_type;

        if not found then
          perform rhn_exception.raise_exception('invalid_server_group_member');
        end if;

      if ( type_is_base = 'Y' ) then
         -- unentitle_server should handle everything, don't really need to do anything else special here
         perform rhn_entitlements.unentitle_server ( server_id_in );
      else

         insert into rhnServerHistory ( id, server_id, summary, details )
         values ( nextval('rhn_event_id_seq'), server_id_in,
                  'removed system entitlement ',
                   case type_label_in
                    when 'enterprise_entitled' then 'Management'
                    when 'sw_mgr_entitled' then 'Update'
                    when 'provisioning_entitled' then 'Provisioning'
                    when 'monitoring_entitled' then 'Monitoring'
                    when 'virtualization_host' then 'Virtualization'
                    when 'virtualization_host_platform' then
                         'Virtualization Platforrm' end  );

         perform rhn_server.delete_from_servergroup(server_id_in, group_id);

         if is_virt = 1 and repoll_virt_guests = 1 then
           perform rhn_entitlements.repoll_virt_guest_entitlements(server_id_in);
         end if;
      end if;

    end$$
language plpgsql;

    create or replace function unentitle_server (
        server_id_in in numeric
    ) returns void
as $$
    declare
      servergroups cursor for
         select distinct sgt.label, sg.id server_group_id
         from  rhnServerGroupType sgt,
               rhnServerGroup sg,
               rhnServer s,
               rhnServerGroupMembers sgm
         where s.id = server_id_in
            and s.org_id = sg.org_id
            and sg.group_type = sgt.id
            and sgm.server_group_id = sg.id
            and sgm.server_id = s.id;

     is_virt numeric := 0;

   begin

      select 1 into is_virt
        from rhnServerEntitlementView
        where server_id = server_id_in
         and label in ('virtualization_host', 'virtualization_host_platform');

      if not found then
          is_virt := 0;
      end if;

      for servergroup in servergroups loop

         insert into rhnServerHistory ( id, server_id, summary, details )
         values ( nextval('rhn_event_id_seq'), server_id_in,
                  'removed system entitlement ',
                   case servergroup.label
                    when 'enterprise_entitled' then 'Management'
                    when 'sw_mgr_entitled' then 'Update'
                    when 'provisioning_entitled' then 'Provisioning'
                    when 'monitoring_entitled' then 'Monitoring'
                    when 'virtualization_host' then 'Virtualization'
                    when 'virtualization_host_platform' then
                         'Virtualization Platform' end  );

         perform rhn_server.delete_from_servergroup(server_id_in,
                                            servergroup.server_group_id );
      end loop;

      if is_virt = 1 then
        perform rhn_entitlements.repoll_virt_guest_entitlements(server_id_in);
      end if;

   end$$
language plpgsql;


    -- *******************************************************************
    -- PROCEDURE: repoll_virt_guest_entitlements
    --
    --   Whenever we add/remove a virtualization_host* entitlement from
    --   a host, we can call this procedure to update what type of slots
    --   the guests are consuming.
    --
    --   If you're removing the entitlement, it's
    --   possible the guests will become unentitled if you don't have enough
    --   physical slots to cover them.
    --
    --   If you're adding the entitlement, you end up freeing up physical
    --   slots for other systems.
    --
    -- *******************************************************************
    create or replace function repoll_virt_guest_entitlements(
        server_id_in in numeric
    ) returns void
as $$
    declare
        -- All channel families associated with the guests of server_id_in
        families cursor for
            select distinct cfs.channel_family_id
            from
                rhnChannelFamilyServers cfs,
                rhnVirtualInstance vi
            where
                vi.host_system_id = server_id_in
                and vi.virtual_system_id = cfs.server_id;

        -- All of server group types associated with the guests of
        -- server_id_in
        group_types cursor for
            select distinct sg.group_type, sgt.label, sg.org_id
            from
                rhnServerGroupType sgt,
                rhnServerGroup sg,
                rhnServerGroupMembers sgm,
                rhnVirtualInstance vi
            where
                vi.host_system_id = server_id_in
                and vi.virtual_system_id = sgm.server_id
                and sgm.server_group_id = sg.id
                and sg.group_type = sgt.id;

        -- Virtual servers from a certain family belonging to a specific
        -- host that are consuming physical channel slots over the limit.
        virt_servers_cfam cursor(family_id_in numeric, quantity_in numeric) for
                select vi.virtual_system_id
                from
                    rhnChannelFamilyMembers cfm,
                    rhnServerChannel sc,
                    rhnVirtualInstance vi
                where
                    vi.host_system_id = server_id_in
                    and vi.virtual_system_id = sc.server_id
                    and sc.channel_id = cfm.channel_id
                    and cfm.channel_family_id = family_id_in
                order by sc.modified desc
                limit quantity_in;

        -- Virtual servers from a certain family belonging to a specific
        -- host that are consuming physical system slots over the limit.
        virt_servers_sgt cursor(group_type_in numeric, quantity_in numeric) for
                select vi.virtual_system_id
                from
                    rhnServerGroup sg,
                    rhnServerGroupMembers sgm,
                    rhnVirtualInstance vi
                where
                    vi.host_system_id = server_id_in
                    and vi.virtual_system_id = sgm.server_id
                    and sgm.server_group_id = sg.id
                    and sg.group_type = group_type_in
                order by sgm.modified desc
                limit quantity_in;

        -- Get the orgs of Virtual guests
        -- Since they may belong to different orgs
        virt_guest_orgs cursor for
                select  distinct (s.org_id)
                from rhnServer s
                    inner join  rhnVirtualInstance vi on vi.virtual_system_id = s.id
                where
                    vi.host_system_id = server_id_in
                    and s.org_id <> (select s1.org_id from rhnServer s1 where s1.id = vi.host_system_id) ;

        org_id_val numeric;
        max_members_val numeric;
        max_flex_val numeric;
        current_members_calc numeric;
        sg_id numeric;
        is_virt numeric := 0;
        free_slots numeric := 0;
    begin
          select 1 into is_virt
                from rhnServerEntitlementView
           where server_id = server_id_in
                 and label in ('virtualization_host', 'virtualization_host_platform');

      if not found then
          is_virt := 0;
      end if;

        select org_id
        into org_id_val
        from rhnServer
        where id = server_id_in;

        -- deal w/ channel entitlements first ...
        for family in families loop
            if is_virt = 0 then
            -- if the host_server does not have virt
            --- find all possible flex slots
            -- and set each of the flex eligible guests to Y
                select GREATEST(sfc.max_members - sfc.current_members, 0)
                  into free_slots
                  from rhnServerFveCapable sfc
                 where sfc.channel_family_id = family.channel_family_id;
                UPDATE rhnServerChannel sc set is_fve = 'Y'
                where sc.server_id in (
                            select vi.virtual_system_id
                            from rhnServerFveCapable sfc
                                inner join rhnVirtualInstance vi on vi.virtual_system_id = sfc.server_id
                            where vi.host_system_id = server_id_in
                                  and sfc.channel_family_id = family.channel_family_id
                              order by vi.modified desc
                            limit free_slots
                );
            else
            -- if the host_server has virt
            -- set all its flex guests to N
                UPDATE rhnServerChannel sc set is_fve = 'N'
                where
                    sc.channel_id in (select cfm.channel_id from rhnChannelFamilyMembers cfm
                                      where cfm.CHANNEL_FAMILY_ID = family.channel_family_id)
                    and sc.is_fve = 'Y'
                    and sc.server_id in
                            (select vi.virtual_system_id  from rhnVirtualInstance vi
                                    where vi.host_system_id = server_id_in);
            end if;

            -- get the current (physical) members of the family
            current_members_calc :=
                rhn_channel.channel_family_current_members(family.channel_family_id,
                                                           org_id_val); -- fixed transposed args

            -- get the max members of the family
            select max_members
            into max_members_val
            from rhnPrivateChannelFamily
            where channel_family_id = family.channel_family_id
            and org_id = org_id_val;

            select fve_max_members
            into max_flex_val
            from rhnPrivateChannelFamily
            where channel_family_id = family.channel_family_id
            and org_id = org_id_val;

            if current_members_calc > max_members_val then
                -- A virtualization_host* ent must have been removed, so we'll
                -- unsubscribe guests from the host first.

                -- hm, i don't think max_members - current_members_calc yielding a negative number
                -- will work w/ rownum, swaping 'em in the body of this if...
                for virt_server in virt_servers_cfam(family.channel_family_id,
                                current_members_calc - max_members_val) loop

                    perform rhn_channel.unsubscribe_server_from_family(
                                virt_server.virtual_system_id,
                                family.channel_family_id);
                end loop;

                -- if we're still over the limit, which would be odd,
                -- just prune the group to max_members
                --
                -- er... wouldn't we actually have to refresh the values of
                -- current_members_calc and max_members_val to actually ever
                -- *skip this??
                if current_members_calc > max_members_val then
                    -- argh, transposed again?!
                    perform rhn_entitlements.set_family_count(org_id_val,
                                     family.channel_family_id,
                                     max_members_val, max_flex_val);
                    --TODO calculate this correctly
                end if;

           end if;

            -- update current_members for the family.  This will set the value
            -- to reflect adding/removing the entitlement.
            --
            -- what's the difference of doing this vs the unavoidable set_family_count above?
            perform rhn_channel.update_family_counts(family.channel_family_id,
                                             org_id_val);

            -- It is possible that the guests belong  to a different org than the host
            -- so we are going to update the family counts in the guests orgs also
            for org in virt_guest_orgs loop
                    perform rhn_channel.update_family_counts(family.channel_family_id,
                                             org.org_id);
            end loop;
        end loop;

        for a_group_type in group_types loop
          -- get the current *physical* members of the system entitlement type for the org...
          --
          -- unlike channel families, it appears the standard rhnServerGroup.max_members represents
          -- *physical* slots, vs physical+virt ... boy that's confusing...

          select max_members, id
            into max_members_val, sg_id
            from rhnServerGroup
            where group_type = a_group_type.group_type
            and org_id = a_group_type.org_id;


      select count(sep.server_id) into current_members_calc
            from rhnServerEntitlementPhysical sep
           where sep.server_group_id = sg_id
             and sep.server_group_type_id = a_group_type.group_type;

          if current_members_calc > max_members_val then
            -- A virtualization_host* ent must have been removed, and we're over the limit, so unsubscribe guests
            for virt_server in virt_servers_sgt(a_group_type.group_type,
                                                current_members_calc - max_members_val) loop
              perform rhn_entitlements.remove_server_entitlement(virt_server.virtual_system_id, a_group_type.label);

              -- decrement current_members_calc, we'll use it to reset current_members for the group at the end...
              current_members_calc := current_members_calc - 1;
            end loop;

          end if;

          update rhnServerGroup set current_members = current_members_calc
           where org_id = a_group_type.org_id
             and group_type = a_group_type.group_type;

          -- I think that's all the house-keeping we have to do...
        end loop;

    end$$
language plpgsql;

    create or replace function get_server_entitlement (
        server_id_in in numeric
    ) returns varchar[]
as $$
    declare
        server_groups cursor for
            select  sgt.label
            from    rhnServerGroupType      sgt,
                    rhnServerGroup          sg,
                    rhnServerGroupMembers   sgm
            where   1=1
                and sgm.server_id = server_id_in
                and sg.id = sgm.server_group_id
                and sgt.id = sg.group_type
                and sgt.label in (
                    'sw_mgr_entitled','enterprise_entitled',
                    'provisioning_entitled', 'nonlinux_entitled',
                    'monitoring_entitled', 'virtualization_host',
                                        'virtualization_host_platform'
                    );

         ent_array varchar[];

    begin

      ent_array := '{}';

      for sg in server_groups loop
         ent_array := ent_array || sg.label;
      end loop;

      return ent_array;

    end$$
language plpgsql;

    -- this desperately needs to be table driven.
    create or replace function modify_org_service (
        org_id_in in numeric,
        service_label_in in varchar,
        enable_in in char
    ) returns void
as $$
    declare
        roles_to_process varchar[];
        roles cursor(role_label_in varchar) for
            select  label, id
            from    rhnUserGroupType
            where   label = role_label_in;
        org_roles cursor(role_label_in varchar) for
            select  1
            from    rhnUserGroup ug,
                    rhnUserGroupType ugt
            where   ugt.label = role_label_in
                and ug.org_id = org_id_in
                and ugt.id = ug.group_type;

        ents_to_process varchar[];
        ents cursor(ent_label_in varchar) for
            select  label, id
            from    rhnOrgEntitlementType
            where   label = ent_label_in;
        org_ents cursor(ent_label_in varchar) for
            select  1
            from    rhnOrgEntitlements oe,
                    rhnOrgEntitlementType oet
            where   oet.label = ent_label_in
                and oe.org_id = org_id_in
                and oet.id = oe.entitlement_id;
        create_row char(1);
    begin
        ents_to_process := '{}';
        roles_to_process := '{}';
        -- a bit kludgy, but only for 3.4 really.  Certainly no
        -- worse than the old code...
        if service_label_in = 'enterprise' or
           service_label_in = 'management' then
            ents_to_process := array_append(ents_to_process, 'sw_mgr_enterprise');

            roles_to_process := array_append(roles_to_process, 'org_admin');

            roles_to_process := array_append(roles_to_process, 'system_group_admin');

            roles_to_process := array_append(roles_to_process, 'activation_key_admin');
        elsif service_label_in = 'provisioning' then
            ents_to_process := array_append(ents_to_process, 'rhn_provisioning');

            roles_to_process := array_append(roles_to_process, 'system_group_admin');

            roles_to_process := array_append(roles_to_process, 'activation_key_admin');

            roles_to_process := array_append(roles_to_process, 'config_admin');
            -- another nasty special case...
            if enable_in = 'Y' then
                ents_to_process := array_append(ents_to_process, 'sw_mgr_enterprise');
            end if;
        elsif service_label_in = 'monitoring' then
            ents_to_process := array_append(ents_to_process, 'rhn_monitor');

            roles_to_process := array_append(roles_to_process, 'monitoring_admin');
        elsif service_label_in = 'virtualization' then
            ents_to_process := array_append(ents_to_process, 'rhn_virtualization');

            roles_to_process := array_append(roles_to_process, 'config_admin');
        elsif service_label_in = 'virtualization_platform' then
            ents_to_process := array_append(ents_to_process, 'rhn_virtualization_platform');
            roles_to_process := array_append(roles_to_process, 'config_admin');
    elsif service_label_in = 'nonlinux' then
            ents_to_process := array_append(ents_to_process, 'rhn_nonlinux');
            roles_to_process := array_append(roles_to_process, 'config_admin');
        end if;

        if enable_in = 'Y' then
            for i in 1..array_upper(ents_to_process, 1) loop
                for ent in ents(ents_to_process[i]) loop
                    create_row := 'Y';
                    for oe in org_ents(ent.label) loop
                        create_row := 'N';
                    end loop;
                    if create_row = 'Y' then
                        insert into rhnOrgEntitlements(org_id, entitlement_id)
                            values (org_id_in, ent.id);
                    end if;
                end loop;
            end loop;
            for i in 1..array_upper(roles_to_process, 1) loop
                for role in roles(roles_to_process[i]) loop
                    create_row := 'Y';
                    for o_r in org_roles(role.label) loop
                        create_row := 'N';
                    end loop;
                    if create_row = 'Y' then
                        insert into rhnUserGroup(
                                id, name, description, current_members,
                                group_type, org_id
                            ) (
                                select  nextval('rhn_user_group_id_seq'),
                                        ugt.name || 's',
                                        ugt.name || 's for Org ' ||
                                            o.name || ' ('|| o.id ||')',
                                        0, ugt.id, o.id
                                from    rhnUserGroupType ugt,
                                        web_customer o
                                where   o.id = org_id_in
                                    and ugt.id = role.id
                            );
                    end if;
                end loop;
            end loop;
        else
            for i in 1..coalesce(array_upper(ents_to_process, 1), 0) loop
                for ent in ents(ents_to_process[i]) loop
                    delete from rhnOrgEntitlements
                     where org_id = org_id_in
                       and entitlement_id = ent.id;
                end loop;
            end loop;
        end if;
    end$$
language plpgsql;

    create or replace function set_customer_enterprise (
        customer_id_in in numeric
    ) returns void
as $$
    begin
        perform rhn_entitlements.modify_org_service(customer_id_in, 'enterprise', 'Y');
    end$$
language plpgsql;

    create or replace function set_customer_provisioning (
        customer_id_in in numeric
    ) returns void
as $$
    begin
        perform rhn_entitlements.modify_org_service(customer_id_in, 'provisioning', 'Y');
    end$$
language plpgsql;

    create or replace function set_customer_monitoring (
        customer_id_in in numeric
    ) returns void
as $$
    begin
        perform rhn_entitlements.modify_org_service(customer_id_in, 'monitoring', 'Y');
    end$$
language plpgsql;

    create or replace function set_customer_nonlinux (
        customer_id_in in numeric
    ) returns void
as $$
    begin
        perform rhn_entitlements.modify_org_service(customer_id_in, 'nonlinux', 'Y');
    end$$
language plpgsql;

    create or replace function unset_customer_enterprise (
        customer_id_in in numeric
    ) returns void
as $$
    begin
        perform rhn_entitlements.modify_org_service(customer_id_in, 'enterprise', 'N');
    end$$
language plpgsql;

    create or replace function unset_customer_provisioning (
        customer_id_in in numeric
    ) returns void
as $$
    begin
        perform rhn_entitlements.modify_org_service(customer_id_in, 'provisioning', 'N');
    end$$
language plpgsql;

    create or replace function unset_customer_monitoring (
        customer_id_in in numeric
    ) returns void
as $$
    begin
        perform rhn_entitlements.modify_org_service(customer_id_in, 'monitoring', 'N');
    end$$
language plpgsql;

    create or replace function unset_customer_nonlinux (
        customer_id_in in numeric
    ) returns void
as $$
    begin
        perform rhn_entitlements.modify_org_service(customer_id_in, 'nonlinux', 'N');
    end$$
language plpgsql;

    -- *******************************************************************
    -- PROCEDURE: prune_group
    -- Unsubscribes servers consuming physical slots that over the org's
    --   limit.
    -- Called by: set_server_group_count, repoll_virt_guest_entitlements
    -- *******************************************************************
    create or replace function prune_group (
        group_id_in in numeric,
        quantity_in in numeric,
        update_family_countsYN in numeric default 1
    ) returns void
as $$
    declare
        sgrecord record;
      type_is_base char;
    begin
            update      rhnServerGroup
                set     max_members = quantity_in
                where   id = group_id_in;

            for sgrecord in (
		   select  server_id, server_group_id, sgt.id as group_type_id, sgt.label
		    from    rhnServerGroupType              sgt,
				    rhnServerGroup                  sg,
				    rhnServerGroupMembers   sgm
		    where   1=1
			    and sgm.server_group_id = group_id_in
			    and sgm.server_id in (
				    select  sep.server_id
				    from
					rhnServerEntitlementPhysical sep
				    where
					sep.server_group_id = group_id_in
				    order by sep.modified asc
				    offset quantity_in
				)
			    and sgm.server_group_id = sg.id
			    and sg.group_type = sgt.id
	    ) loop
                perform rhn_entitlements.remove_server_entitlement(sgrecord.server_id, sgrecord.label);

            select is_base
            into type_is_base
            from rhnServerGroupType sgt
            where sgt.id = sgrecord.group_type_id;

            -- if we're removing a base ent, then be sure to
            -- remove the server's channel subscriptions.
            if ( type_is_base = 'Y' ) then
                   perform rhn_channel.clear_subscriptions(sgrecord.server_id, 0, update_family_countsYN);
            end if;

            end loop;
    end$$
language plpgsql;

    -- *******************************************************************
    -- PROCEDURE: assign_system_entitlement
    --
    -- Moves system entitlements from from_org_id_in to to_org_id_in.
    -- Can raise not_enough_entitlements_in_base_org if from_org_id_in
    -- does not have enough entitlements to cover the move.
    -- Takes care of unentitling systems if necessary by calling
    -- set_server_group_count
    -- *******************************************************************
    create or replace function assign_system_entitlement(
        group_label_in in varchar,
        from_org_id_in in numeric,
        to_org_id_in in numeric,
        quantity_in in numeric
    ) returns void
as $$
    declare
        prev_ent_count numeric;
    to_org_prev_ent_count numeric;
        new_ent_count numeric;
    new_quantity numeric;
        group_type numeric;
    begin

            select max_members
            into prev_ent_count
            from rhnServerGroupType sgt,
                 rhnServerGroup sg
            where sg.org_id = from_org_id_in
              and sg.group_type = sgt.id
              and sgt.label = group_label_in;

            if not found then
                perform rhn_exception.raise_exception(
                              'not_enough_entitlements_in_base_org');
            end if;

            select max_members
            into to_org_prev_ent_count
            from rhnServerGroupType sgt,
                 rhnServerGroup sg
            where sg.org_id = to_org_id_in
              and sg.group_type = sgt.id
              and sgt.label = group_label_in;

            if not found then
                to_org_prev_ent_count := 0;
            end if;

            select id
            into group_type
            from rhnServerGroupType
            where label = group_label_in;

            if not found then
                perform rhn_exception.raise_exception(
                              'invalid_server_group');
            end if;

        new_ent_count := prev_ent_count - quantity_in;

        if prev_ent_count > new_ent_count then
            new_quantity := to_org_prev_ent_count + quantity_in;
        end if;

        if new_ent_count < 0 then
            perform rhn_exception.raise_exception(
                          'not_enough_entitlements_in_base_org');
        end if;


        perform rhn_entitlements.set_server_group_count(from_org_id_in,
                                         group_type,
                                         new_ent_count);

        perform rhn_entitlements.set_server_group_count(to_org_id_in,
                                         group_type,
                                         new_quantity);

        -- Create or delete the entries in rhnOrgEntitlementType
        if group_label_in = 'enterprise_entitled' then
            if new_quantity > 0 then
                perform rhn_entitlements.set_customer_enterprise(to_org_id_in);
            else
                perform rhn_entitlements.unset_customer_enterprise(to_org_id_in);
            end if;
        end if;

        if group_label_in = 'provisioning_entitled' then
            if new_quantity > 0 then
                perform rhn_entitlements.set_customer_provisioning(to_org_id_in);
            else
                perform rhn_entitlements.unset_customer_provisioning(to_org_id_in);
            end if;
        end if;

        if group_label_in = 'monitoring_entitled' then
            if new_quantity > 0 then
                perform rhn_entitlements.set_customer_monitoring(to_org_id_in);
            else
                perform rhn_entitlements.unset_customer_monitoring(to_org_id_in);
            end if;
        end if;

    end$$
language plpgsql;

    -- *******************************************************************
    -- PROCEDURE: assign_channel_entitlement
    --
    -- Moves channel entitlements from from_org_id_in to to_org_id_in.
    -- Can raise not_enough_entitlements_in_base_org if from_org_id_in
    -- does not have enough entitlements to cover the move.
    -- Takes care of unentitling systems if necessary by calling
    -- set_family_count
    -- *******************************************************************
    create or replace function assign_channel_entitlement(
        channel_family_label_in in varchar,
        from_org_id_in in numeric,
        to_org_id_in in numeric,
        quantity_in in numeric,
        flex_in in numeric
    ) returns void
as $$
    declare
        from_org_prev_ent_count numeric;
        from_org_prev_ent_count_flex numeric;
        new_ent_count numeric;
        new_ent_count_flex numeric;
        to_org_prev_ent_count numeric;
        to_org_prev_ent_count_flex numeric;
        new_quantity numeric;
        new_flex numeric;
        cfam_id       numeric;
    begin

            select max_members
            into from_org_prev_ent_count
            from rhnChannelFamily cf,
                 rhnPrivateChannelFamily pcf
            where pcf.org_id = from_org_id_in
              and pcf.channel_family_id = cf.id
              and cf.label = channel_family_label_in;

            if not found then
                perform rhn_exception.raise_exception(
                              'not_enough_entitlements_in_base_org');
            end if;

            select max_members
            into to_org_prev_ent_count
            from rhnChannelFamily cf,
                 rhnPrivateChannelFamily pcf
            where pcf.org_id = to_org_id_in
              and pcf.channel_family_id = cf.id
              and cf.label = channel_family_label_in;

            if not found then
                to_org_prev_ent_count := 0;
            end if;

            select fve_max_members
            into from_org_prev_ent_count_flex
            from rhnChannelFamily cf,
                rhnPrivateChannelFamily pcf
            where pcf.org_id = from_org_id_in
              and pcf.channel_family_id = cf.id
              and cf.label = channel_family_label_in;

            if not found then
                perform rhn_exception.raise_exception(
                              'not_enough_flex_entitlements_in_base_org');
            end if;

            select fve_max_members
            into to_org_prev_ent_count_flex
            from rhnChannelFamily cf,
                 rhnPrivateChannelFamily pcf
            where pcf.org_id = to_org_id_in
              and pcf.channel_family_id = cf.id
              and cf.label = channel_family_label_in;

            if not found then
                to_org_prev_ent_count_flex := 0;
            end if;

            select id
            into cfam_id
            from rhnChannelFamily
            where label = channel_family_label_in;

            if not found then
                perform rhn_exception.raise_exception(
                              'invalid_channel_family');
            end if;

        new_ent_count := from_org_prev_ent_count - quantity_in;
        new_ent_count_flex := from_org_prev_ent_count_flex - flex_in;

        if from_org_prev_ent_count >= new_ent_count then
            new_quantity := to_org_prev_ent_count + quantity_in;
        end if;

        if from_org_prev_ent_count_flex >= new_ent_count_flex then
            new_flex := to_org_prev_ent_count_flex + flex_in;
        end if;

        if new_ent_count < 0 then
            perform rhn_exception.raise_exception(
                          'not_enough_entitlements_in_base_org');
        end if;

        if new_ent_count_flex < 0 then
            perform rhn_exception.raise_exception(
                          'not_enough_flex_entitlements_in_base_org');
        end if;



        perform rhn_entitlements.set_family_count(from_org_id_in,
                                          cfam_id,
                                          new_ent_count,
                                          new_ent_count_flex);

        perform rhn_entitlements.set_family_count(to_org_id_in,
                                          cfam_id,
                                          new_quantity,
                                          new_flex);

    end$$
language plpgsql;

    -- *******************************************************************
    -- PROCEDURE: activate_system_entitlement
    --
    -- Sets the values in rhnServerGroup for a given rhnServerGroupType.
    --
    -- Calls: set_server_group_count to update, prune, or create the group.
    -- Called by: the code that activates a satellite cert.
    --
    -- Raises not_enough_entitlements_in_base_org if all entitlements
    -- in the org are used so the free entitlements would not cover
    -- the difference when descreasing the number of entitlements.
    -- *******************************************************************
    create or replace function activate_system_entitlement(
        org_id_in in numeric,
        group_label_in in varchar,
        quantity_in in numeric
    ) returns void
as $$
    declare
        prev_ent_count numeric;
        prev_ent_count_sum numeric;
        group_type numeric;
    begin

        -- Fetch the current entitlement count for the org
        -- into prev_ent_count

            select current_members
            into prev_ent_count
            from rhnServerGroupType sgt,
                 rhnServerGroup sg
            where sg.group_type = sgt.id
              and sgt.label = group_label_in
              and sg.org_id = org_id_in;

            if not found then
                prev_ent_count := 0;
            end if;

            select id
            into group_type
            from rhnServerGroupType
            where label = group_label_in;

            if not found then
                perform rhn_exception.raise_exception(
                              'invalid_server_group');
            end if;

        -- If we're setting the total entitlemnt count to a lower value,
        -- and that value is less than the allocated count in this org,
        -- we need to raise an exception.
        if quantity_in < prev_ent_count then
            perform rhn_exception.raise_exception(
                          'not_enough_entitlements_in_base_org');
        else
            -- don't update family counts after every server
            -- will do bulk update afterwards
            perform rhn_entitlements.set_server_group_count(org_id_in,
                                             group_type,
                                             quantity_in,
                                             0);
            -- bulk update family counts
            perform rhn_channel.update_group_family_counts(group_label_in, org_id_in);
        end if;

    end$$
language plpgsql;

    -- *******************************************************************
    -- PROCEDURE: activate_channel_entitlement
    --
    -- Calls: set_family_count to update, prune, or create the family
    --        permission bucket.
    -- Called by: the code that activates a satellite cert.
    --
    -- Raises not_enough_entitlements_in_base_org if there are not enough
    -- entitlements in the org to cover the difference when you are
    -- descreasing the number of entitlements.
    --
    -- The backend code in Python is expected to do whatever arithmetics
    -- is needed.
    -- *******************************************************************
    create or replace function activate_channel_entitlement(
        org_id_in in numeric,
        channel_family_label_in in varchar,
        quantity_in in numeric,
        flex_in in numeric
    ) returns void
as $$
    declare
        prev_ent_count numeric;
        prev_flex_count numeric;
        prev_ent_count_sum numeric;
        cfam_id numeric;
        reduce_quantity numeric;
        total_flex_capable numeric;
        to_convert_reg cursor (channel_family_id_val numeric, org_id_in numeric, quantity numeric) for
                     select SC.server_id
                     from rhnServerChannel SC inner join
                          rhnServer S on S.id = SC.server_id
                     where
                         is_fve = 'Y'
                         and S.org_id = org_id_in
                         and SC.channel_id in
                         (select cfm.channel_id from rhnChannelFamilyMembers cfm
                             where cfm.CHANNEL_FAMILY_ID = channel_family_id_val)
                         limit quantity;
         to_convert_flex cursor (channel_family_id_val numeric, org_id_in numeric, quantity numeric) for
                   select server_id
                   from rhnServerFveCapable
                       where SERVER_ORG_ID = org_id_in and
                             channel_family_id = cfam_id
                       limit quantity;

    begin

        -- Fetch the current entitlement count for the org
        -- into prev_ent_count
            select current_members
            into prev_ent_count
            from rhnChannelFamily cf,
                 rhnPrivateChannelFamily pcf
            where pcf.org_id = org_id_in
              and pcf.channel_family_id = cf.id
              and cf.label = channel_family_label_in;

            if not found then
                prev_ent_count := 0;
            end if;

            select pcf.fve_current_members
            into prev_flex_count
            from rhnChannelFamily cf,
                 rhnPrivateChannelFamily pcf
            where pcf.org_id = org_id_in
              and pcf.channel_family_id = cf.id
              and cf.label = channel_family_label_in;

            if not found then
                prev_flex_count := 0;
            end if;

            select id
            into cfam_id
            from rhnChannelFamily
            where label = channel_family_label_in;

            if not found then
                perform rhn_exception.raise_exception(
                              'invalid_channel_family');
            end if;

        -- if there are too few flex entitlements
        if flex_in < prev_flex_count then
            -- and if the extra we need is less than or equal to our extra regular entitlements
            if prev_flex_count - flex_in <= quantity_in - prev_ent_count then
                   reduce_quantity := prev_flex_count - flex_in;
                   -- We need to convert some systems from flex guest to regular
                   for system in to_convert_reg(cfam_id, org_id_in, reduce_quantity) loop
                      --rhn_channel.convert_to_regular(system.server_id, cfam_id);
                      UPDATE rhnServerChannel sc set is_fve = 'N'
                           where sc.server_id = system.server_id
                                 and sc.channel_id in (select cfm.channel_id
                                                          from rhnChannelFamilyMembers cfm
                                                          where cfm.channel_family_id = cfam_id);
                   end loop;

                   --reset previous counts
                   prev_ent_count := prev_ent_count + reduce_quantity;
                   prev_flex_count := prev_flex_count - reduce_quantity;
            else
                perform rhn_exception.raise_exception(
                          'not_enough_flex_entitlements_in_base_org');
            end if;
        end if;

        -- if there are too few regular entitlements, and extra flex entitlements
        if quantity_in < prev_ent_count and prev_flex_count < flex_in then
                -- how many flex-capable systems (that aren't using flex) do we have
                select count(*)
                   into total_flex_capable
                   from rhnServerFveCapable
                       where SERVER_ORG_ID = org_id_in and
                             channel_family_id = cfam_id;
                -- if we have enough flex capable machines that is at least
                --   as many as what we are over on
                if total_flex_capable >= prev_ent_count - quantity_in then
                    reduce_quantity := prev_ent_count - quantity_in;
                    for system in to_convert_flex(cfam_id, org_id_in, reduce_quantity) loop
--                          rhn_channel.convert_to_fve(system.server_id, cfam_id);
                        UPDATE rhnServerChannel sc set is_fve = 'Y'
                           where sc.server_id = system.server_id
                                 and sc.channel_id in (select cfm.channel_id
                                                          from rhnChannelFamilyMembers cfm
                                                          where cfm.channel_family_id = cfam_id);
                    end loop;
                    prev_ent_count := prev_ent_count - reduce_quantity;
                    prev_flex_count := prev_flex_count + reduce_quantity;
                end if;
        end if;

        -- If we're setting the total entitlemnt count to a lower value,
        -- and that value is less than the count in that one org,
        -- we need to raise an exception.
        if quantity_in < prev_ent_count then
            perform rhn_exception.raise_exception(
                          'not_enough_entitlements_in_base_org');
        else
            -- even if we've manually converted systems to/from flex above
            -- set_family_count should call update_family_counts, to reset
            -- current used slots
            perform rhn_entitlements.set_family_count(org_id_in, cfam_id,
                                              quantity_in, flex_in);
        end if;

    end$$
language plpgsql;

    create or replace function set_server_group_count (
        customer_id_in in numeric,  -- customer_id
        group_type_in in numeric,   -- rhn[User|Server]GroupType.id
        quantity_in in numeric,      -- quantity
                update_family_countsYN in numeric default 1
    ) returns void
as $$
    declare
        group_id numeric;
        quantity numeric;
        wasfound boolean;
    begin
        quantity := quantity_in;
        if quantity is not null and quantity < 0 then
            quantity := 0;
        end if;

        select  rsg.id
        into    group_id
        from    rhnServerGroup rsg
        where   1=1
            and rsg.org_id = customer_id_in
            and rsg.group_type = group_type_in;

        -- preserve the not found status across the rhn_entitlements.prune_group invocation
        wasfound := true;
        if not found then
            wasfound := false;
        end if;

        perform rhn_entitlements.prune_group(
            group_id,
            quantity,
                        update_family_countsYN
        );

        if not wasfound then
            insert into rhnServerGroup (
                    id, name, description, max_members, current_members,
                    group_type, org_id, created, modified
                ) (
                    select  nextval('rhn_server_group_id_seq'), name, name,
                            quantity, 0, id, customer_id_in,
                            current_timestamp, current_timestamp
                    from    rhnServerGroupType
                    where   id = group_type_in
            );
        end if;

    end$$
language plpgsql;

    -- *******************************************************************
    -- PROCEDURE: prune_family
    -- Unsubscribes servers consuming physical slots from the channel family
    --   that are over the org's limit.
    -- Called by: set_family_count
    -- *******************************************************************
    create or replace function prune_family (
        customer_id_in in numeric,
        channel_family_id_in in numeric,
        quantity_in in numeric,
        flex_in in numeric
    ) returns void
as $$
    declare
        serverchannels cursor(tmp_quantity numeric, is_fve_in char) for
            select  sc.server_id,
                    sc.channel_id
            from    rhnServerChannel sc,
                    rhnChannelFamilyMembers cfm
            where   1=1
                and cfm.channel_family_id = channel_family_id_in
                and cfm.channel_id = sc.channel_id
                and server_id in (
                       select server_id from (
                            select  distinct rs.id as server_id
                            from
                                    rhnServerChannel        rsc,
                                    rhnChannelFamilyMembers rcfm,
                                    rhnServer               rs
                            where   1=1
                                and rs.org_id = customer_id_in
                                and rs.id = rsc.server_id
                                and rsc.channel_id = rcfm.channel_id
                                and rcfm.channel_family_id =  channel_family_id_in
                                and rsc.is_fve = is_fve_in
                                -- we only want to grab servers consuming
                                -- physical slots.
                                and exists (
                                    select 1
                                    from rhnChannelFamilyServerPhysical cfsp
                                    where cfsp.server_id = rs.id
                                    and cfsp.channel_family_id =
                                        channel_family_id_in
                                    )
                            ) Q
                        order by server_id asc
                        offset quantity_in
                        );
    begin
        -- if we get a null customer_id, this is completely bogus.
        if customer_id_in is null then
            return;
        end if;

        for sc in serverchannels(quantity_in, 'N') loop
            perform rhn_channel.unsubscribe_server(sc.server_id, sc.channel_id,
                                                   1, 1, 0, 0);
        end loop;

        for sc in serverchannels(flex_in, 'Y') loop
            perform rhn_channel.unsubscribe_server(sc.server_id, sc.channel_id,
                                                   1, 1, 0, 0);
        end loop;

        perform rhn_channel.update_family_counts(channel_family_id_in, customer_id_in);
    end$$
language plpgsql;

    create or replace function set_family_count (
        customer_id_in in numeric,      -- customer_id
        channel_family_id_in in numeric,    -- 246
        quantity_in in numeric,          -- 3
        flex_in in numeric
    ) returns void
as $$
    declare
        privperms cursor for
            select  1
            from    rhnPrivateChannelFamily
            where   org_id = customer_id_in
                and channel_family_id = channel_family_id_in;
        pubperms cursor for
            select  o.id org_id
            from    web_customer o,
                    rhnPublicChannelFamily pcf
            where   pcf.channel_family_id = channel_family_id_in;
        quantity numeric;
        done numeric := 0;
        flex numeric;
    begin
        quantity := quantity_in;
        if quantity is not null and quantity < 0 then
            quantity := 0;
        end if;
        flex := flex_in;
        if flex is not null and flex < 0 then
            flex := 0;
        end if;

        if customer_id_in is not null then
            for perm in privperms loop
                perform rhn_entitlements.prune_family(
                    customer_id_in,
                    channel_family_id_in,
                    quantity,
                    flex
                );

                if quantity is null and flex is null then
                    delete from rhnPrivateChannelFamily
                        where org_id = customer_id_in
                            and channel_family_id = channel_family_id_in;
                 else
                    update rhnPrivateChannelFamily
                        set max_members = quantity
                        where org_id = customer_id_in
                            and channel_family_id = channel_family_id_in;

                   update rhnPrivateChannelFamily
                        set fve_max_members = flex
                        where org_id = customer_id_in
                            and channel_family_id = channel_family_id_in;
                end if;
                return;
            end loop;

            insert into rhnPrivateChannelFamily (
                    channel_family_id, org_id, max_members, current_members, fve_max_members, fve_current_members
                ) values (
                    channel_family_id_in, customer_id_in, quantity, 0, flex, 0 );
            return;
        end if;

        for perm in pubperms loop
            if quantity = 0 then
                perform rhn_entitlements.prune_family(
                    perm.org_id,
                    channel_family_id_in,
                    quantity,
                    flex
                );
                if done = 0 then
                    delete from rhnPublicChannelFamily
                        where channel_family_id = channel_family_id_in;
                end if;
            end if;
            done := 1;
        end loop;
        -- if done's not 1, then we don't have any entitlements
        if done != 1 then
            insert into rhnPublicChannelFamily (
                    channel_family_id
                ) values (
                    channel_family_id_in
                );
        end if;
    end$$
language plpgsql;

    -- this expects quantity_in to be the number of available slots, not the
    -- max_members of the server group.  If you give it too many, it'll fail
    -- and raise servergroup_max_members.
    -- We should NEVER run this unless we're SURE that we won't
    -- be violating the max.
    create or replace function entitle_last_modified_servers (
        customer_id_in in numeric,  -- customer_id
        type_label_in in varchar,   -- 'enterprise_entitled'
        quantity_in in numeric      -- 3
    ) returns void
as $$
    declare
        -- find the servers that aren't currently in slots
        servers cursor(cid_in numeric, quant_in numeric) for
                                    select  rs.id as server_id
                                    from    rhnServer rs
                                    where   1=1
                                        and rs.org_id = cid_in
                                        and not exists (
                                            select  1
                                            from    rhnServerGroup sg,
                                                    rhnServerGroupMembers rsgm
                                            where   rsgm.server_id = rs.id
                                                and rsgm.server_group_id = sg.id
                                                and sg.group_type is not null
                                        )
                                        and not exists (
                                            select 1
                                            from rhnVirtualInstance vi
                                            where vi.virtual_system_id =
                                                  rs.id
                                        )
                                    order by modified desc
                                    limit quant_in;
    begin
        for server in servers(customer_id_in, quantity_in) loop
            perform rhn_entitlements.entitle_server(server.server_id, type_label_in);
        end loop;
    end$$
language plpgsql;

    create or replace function subscribe_newest_servers (
        customer_id_in in numeric
    ) returns void
as $$
    declare
        -- find servers without base channels
        servers cursor(cid_in numeric) for
            select  s.id
            from    rhnServer           s
            where   1=1
                and s.org_id = cid_in
                and not exists (
                        select 1
                        from    rhnChannel          c,
                                rhnServerChannel    sc
                        where   sc.server_id = s.id
                            and sc.channel_id = c.id
                            and c.parent_channel is null
                    )
                and not exists (
                        select 1
                        from rhnVirtualInstance vi
                        where vi.virtual_system_id = s.id
                    )
            order by s.modified desc;
        channel_id numeric;
    begin
        for server in servers(customer_id_in) loop
            channel_id := rhn_channel.guess_server_base(server.id);
            if channel_id is not null then
                begin
                    perform rhn_channel.subscribe_server(server.id, channel_id);
                -- exception is really channel_family_no_subscriptions
                exception
                    when others then
                        null;
                end;
            end if;
        end loop;
    end$$
language plpgsql;


-- restore the original setting
update pg_settings set setting = overlay( setting placing '' from 1 for (length('rhn_entitlements')+1) ) where name = 'search_path';
07070100000823000081B400000000000000000000000167AE111400000258000000000000000000000000000000000000007300000000susemanager-schema/upgrade/spacewalk-schema-2.3-to-spacewalk-schema-2.4/004-remove_monitoring_taskomatic_tasks.sql    delete from rhnTaskoRun where template_id in
       (select ttemp.id
	  from rhnTaskoTemplate ttemp,
	       rhnTaskoTask ttask
	 where ttemp.task_id = ttask.id
	   and ttask.name = 'cleanup-timeseries-data');

delete from rhnTaskoTemplate where task_id in (SELECT id FROM rhnTaskoTask WHERE name='cleanup-timeseries-data');
update rhnTaskoTemplate set ordering=0 where bunch_id in (SELECT id FROM rhnTaskoBunch WHERE name='cleanup-data-bunch') and task_id in (SELECT id FROM rhnTaskoTask WHERE name='cleanup-packagechangelog-data');

delete from rhnTaskoTask where name = 'cleanup-timeseries-data';
07070100000824000081B400000000000000000000000167AE111400000044000000000000000000000000000000000000006700000000susemanager-schema/upgrade/spacewalk-schema-2.3-to-spacewalk-schema-2.4/005-rhnContentSource-label.sql    
ALTER TABLE rhnContentSource ALTER COLUMN label TYPE VARCHAR(128);
07070100000825000081B400000000000000000000000167AE1114000006FF000000000000000000000000000000000000006B00000000susemanager-schema/upgrade/spacewalk-schema-2.3-to-spacewalk-schema-2.4/006-queue_server-no_duplicates.sql    -- retrieved from ./1241128047/984a347f2afbd47756e90584364799dd670b62db/schema/spacewalk/oracle/procs/queue_server.sql
--
-- Copyright (c) 2008--2015 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--

-- the next two views are basically the same.  the first, though, has an outer join to
-- the errata stuff, in case there are packages the server needs that haven't been
-- errata'd (ie, the fringe case)


CREATE OR REPLACE FUNCTION
queue_server(server_id_in IN NUMERIC, immediate_in IN NUMERIC DEFAULT 1)
RETURNS VOID
AS
$$
DECLARE
    org_id_tmp NUMERIC;
BEGIN
    IF immediate_in > 0
    THEN
          PERFORM rhn_server.update_needed_cache(server_id_in);
    ELSE
          SELECT org_id INTO STRICT org_id_tmp
          FROM rhnServer WHERE id = server_id_in;

          INSERT
            INTO rhnTaskQueue
                 (org_id, task_name, task_data)
          SELECT org_id_tmp,
                 'update_server_errata_cache',
                 server_id_in
          WHERE NOT EXISTS
            (SELECT 1 FROM rhnTaskQueue
               WHERE org_id = org_id_tmp
               AND task_name = 'update_server_errata_cache'
               AND task_data = server_id_in
            );
    END IF;
END;
$$ LANGUAGE plpgsql;
 07070100000826000081B400000000000000000000000167AE11140000B8D1000000000000000000000000000000000000007600000000susemanager-schema/upgrade/spacewalk-schema-2.3-to-spacewalk-schema-2.4/007-rhn_channel-update_needed_cache-async.sql --
-- Copyright (c) 2008--2015 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--

-- create schema rhn_channel;

--update pg_setting
update pg_settings set setting = 'rhn_channel,' || setting where name = 'search_path';

    create or replace function obtain_read_lock(channel_family_id_in in numeric, org_id_in in numeric)
    returns void as $$
    declare
        read_lock timestamptz;
    begin
        select created into read_lock
          from rhnPrivateChannelFamily
         where channel_family_id = channel_family_id_in and org_id = org_id_in
           for update;
    end$$ language plpgsql;

    -- this "emulates" cursor server_base_subscriptions defined in oracle/rhn_channel.pks
    create or replace function server_base_subscriptions(server_id_in NUMERIC)
    returns boolean as $$
    begin
      return exists(SELECT C.id FROM rhnChannel C, rhnServerChannel SC
		    WHERE C.id = SC.channel_id
		      AND SC.server_id = server_id_in
		      AND C.parent_channel IS NULL);
    end$$ language plpgsql;

    -- this "emulates" cursor server_base_subscriptions defined in oracle/rhn_channel.pks
    create or replace function check_server_subscription(server_id_in NUMERIC, channel_id_in NUMERIC)
    returns boolean as $$
    begin
      return exists(SELECT channel_id FROM rhnServerChannel WHERE server_id = server_id_in AND channel_id = channel_id_in);
    end$$ language plpgsql;


    CREATE OR REPLACE FUNCTION subscribe_server(server_id_in IN NUMERIC, channel_id_in NUMERIC, immediate_in NUMERIC default 1, user_id_in in numeric default null, recalcfamily_in NUMERIC default 1) returns void
    AS $$
    declare
        channel_parent_val      rhnChannel.parent_channel%TYPE;
        parent_subscribed       BOOLEAN;
        server_has_base_chan    BOOLEAN;
        server_already_in_chan  BOOLEAN;
        channel_family_id_val   NUMERIC;
        server_org_id_val       NUMERIC;
        available_subscriptions NUMERIC;
        available_fve_subs      numeric;
        consenting_user         NUMERIC;
        allowed                 numeric;
        is_fve_char             char(1) := 'N';
    BEGIN
        if user_id_in is not null then
            allowed := rhn_channel.user_role_check(channel_id_in, user_id_in, 'subscribe');
        else
            allowed := 1;
        end if;

        if allowed = 0 then
            perform rhn_exception.raise_exception('no_subscribe_permissions');
        end if;


        SELECT parent_channel INTO channel_parent_val FROM rhnChannel WHERE id = channel_id_in;

        IF channel_parent_val IS NOT NULL
        THEN    
            -- child channel; if attempting to cross-subscribe a child to the wrong base, silently ignore
            parent_subscribed := rhn_channel.check_server_subscription(server_id_in, channel_parent_val);
        
            IF NOT parent_subscribed
            THEN
                RETURN;
            END IF;
        ELSE
            -- base channel
            server_has_base_chan := rhn_channel.server_base_subscriptions(server_id_in);
            
            IF server_has_base_chan
            THEN
                perform rhn_exception.raise_exception('channel_server_one_base');
            END IF;
        END IF;

        server_already_in_chan := rhn_channel.check_server_subscription(server_id_in, channel_id_in);
    
        IF server_already_in_chan
        THEN
            RETURN;
        END IF;
        
        channel_family_id_val := rhn_channel.family_for_channel(channel_id_in);
        IF channel_family_id_val IS NULL
        THEN
            perform rhn_exception.raise_exception('channel_subscribe_no_family');
        END IF;

        --
        -- Use the org_id of the server only if the org_id of the channel = NULL.
        -- This is required for subscribing to shared channels.
        --
        SELECT COALESCE(org_id, (SELECT org_id FROM rhnServer WHERE id = server_id_in))
          INTO server_org_id_val
          FROM rhnChannel
         WHERE id = channel_id_in;
         
        begin
            perform rhn_channel.obtain_read_lock(channel_family_id_val, server_org_id_val);
        exception
            when no_data_found then
                perform rhn_exception.raise_exception('channel_family_no_subscriptions');
        end;

        available_subscriptions := rhn_channel.available_family_subscriptions(channel_family_id_val, server_org_id_val);
        available_fve_subs := rhn_channel.available_fve_family_subs(channel_family_id_val, server_org_id_val);
        
        IF available_subscriptions IS NULL OR 
           available_subscriptions > 0 or
           rhn_channel.can_server_consume_virt_channl(server_id_in, channel_family_id_val) = 1 OR
            (available_fve_subs > 0 AND rhn_channel.can_server_consume_fve(server_id_in) = 1)
        THEN
            if rhn_channel.can_server_consume_virt_channl(server_id_in, channel_family_id_val) = 0 AND available_fve_subs > 0 AND rhn_channel.can_server_consume_fve(server_id_in) = 1 THEN
                is_fve_char := 'Y';
            end if;

            insert into rhnServerHistory (id,server_id,summary,details) (
                select  nextval('rhn_event_id_seq'),
                        server_id_in,
                        'subscribed to channel ' || SUBSTR(c.label, 0, 106),
                        c.label
                from    rhnChannel c
                where   c.id = channel_id_in
            );

            INSERT INTO rhnServerChannel (server_id, channel_id, is_fve) VALUES (server_id_in, channel_id_in, is_fve_char);
			IF recalcfamily_in > 0
			THEN
                perform rhn_channel.update_family_counts(channel_family_id_val, server_org_id_val);
			END IF;

            perform queue_server(server_id_in, immediate_in);

            update rhnServer
               set channels_changed = current_timestamp
             where id = server_id_in;
        ELSE
            perform rhn_exception.raise_exception('channel_family_no_subscriptions');
        END IF;
            
    END$$ language plpgsql;



    create or replace function can_convert_to_fve(server_id_in IN NUMERIC, channel_family_id_val IN NUMERIC)
    RETURNS NUMERIC
    as $$
    declare
        fve_convertible_entries cursor for
        select 1  from
            rhnServerFveCapable cap
          where cap.server_id = server_id_in
                AND cap.channel_family_id = channel_family_id_val;
    BEGIN
        FOR entry IN fve_convertible_entries LOOP
            return 1;
        END LOOP;
        RETURN 0;
    END$$ language plpgsql;



    -- Converts server channel_family to use a flex entitlement
    create or replace function convert_to_fve(server_id_in IN NUMERIC, channel_family_id_val IN NUMERIC)
    returns void
    as $$
    declare
        available_fve_subs      NUMERIC;
        server_org_id_val       NUMERIC;
    BEGIN

        --
        -- Use the org_id of the server only if the org_id of the channel = NULL.
        -- This is required for subscribing to shared channels.
        --
        SELECT org_id
          INTO server_org_id_val
          FROM rhnServer
         WHERE id = server_id_in;


        perform rhn_channel.obtain_read_lock(channel_family_id_val, server_org_id_val);
        if not found then
                perform rhn_exception.raise_exception('channel_family_no_subscriptions');
        end if;
        IF (rhn_channel.can_convert_to_fve(server_id_in, channel_family_id_val ) = 0)
            THEN
                perform rhn_exception.raise_exception('server_cannot_convert_to_flex');
        END IF;

        available_fve_subs := rhn_channel.available_fve_family_subs(channel_family_id_val, server_org_id_val);

        IF (available_fve_subs > 0)
        THEN

            insert into rhnServerHistory (id,server_id,summary,details) (
                select  nextval('rhn_event_id_seq'),
                        server_id_in,
                        'converted to flex entitlement' || SUBSTR(cf.label, 0, 99),
                        cf.label
                from    rhnChannelFamily cf
                where   cf.id = channel_family_id_val
            );

            UPDATE rhnServerChannel sc set is_fve = 'Y'
                           where sc.server_id = server_id_in and
                                 sc.channel_id in
                                    (select cfm.channel_id from rhnChannelFamilyMembers cfm
                                                where cfm.CHANNEL_FAMILY_ID = channel_family_id_val);

            perform rhn_channel.update_family_counts(channel_family_id_val, server_org_id_val);
        ELSE
            perform rhn_exception.raise_exception('not_enough_flex_entitlements');
        END IF;

    END$$ language plpgsql;
    
    create or replace function can_server_consume_virt_channl(
        server_id_in in numeric,
        family_id_in in numeric )
    returns numeric
    as $$
    begin
      if exists(
            select 1
            from
                rhnChannelFamilyVirtSubLevel cfvsl,
                rhnSGTypeVirtSubLevel sgtvsl,
                rhnVirtualInstance vi
            where
                vi.virtual_system_id = server_id_in 
                and sgtvsl.virt_sub_level_id = cfvsl.virt_sub_level_id
                and cfvsl.channel_family_id = family_id_in
                and exists (
                    select 1
                    from rhnServerEntitlementView sev
                    where vi.host_system_id = sev.server_id
                    and sev.server_group_type_id = sgtvsl.server_group_type_id ))
      then
        return 1;
      else
        return 0;
      end if;
    end$$ language plpgsql;

    create or replace function can_server_consume_fve(server_id_in in numeric) returns numeric
    as $$
    declare
        vi_entries cursor for
            SELECT 1
              FROM rhnVirtualInstance vi
             WHERE vi.virtual_system_id = server_id_in;
        vi_count numeric;

    begin
        FOR vi_entry IN VI_ENTRIES LOOP
            return 1;
        END LOOP;
        RETURN 0;
    end$$ language plpgsql;

    create or replace function guess_server_base(
        server_id_in in numeric
    ) RETURNS numeric as $$
    declare
        server_cursor cursor for
            select s.server_arch_id, s.release, s.org_id
              from rhnServer s
             where s.id = server_id_in;
    -- Cursor that fetches all the possible base channels for a
    -- (server_arch_id, release, org_id) combination
        base_channel_cursor cursor(
                release_in varchar,
                server_arch_id_in numeric,
                org_id_in numeric
        ) for
                select distinct c.*
                from    rhnOrgDistChannelMap                       odcm,
                                rhnServerChannelArchCompat      scac,
                                rhnChannel                                      c
                where   c.parent_channel is null
                        and c.id = odcm.channel_id
                        and c.channel_arch_id = odcm.channel_arch_id
                        and odcm.release = release_in
                        and odcm.for_org_id = org_id_in
                        and scac.server_arch_id = server_arch_id_in
                        and scac.channel_arch_id = c.channel_arch_id;

    begin
        for s in server_cursor loop
            for channel in base_channel_cursor(s.release,
                s.server_arch_id, s.org_id) 
            loop
                return channel.id;
            end loop;
        end loop;
        -- Server not found, or no base channel applies to it
        return null;
    end$$ language plpgsql;

    -- Private function
    create or replace function normalize_server_arch(server_arch_in in varchar)
    returns varchar
    as $$
    declare
        suffix VARCHAR(128) := '-redhat-linux';
    begin
        if server_arch_in is NULL then
            return NULL;
        end if;
        if position('-' IN server_arch_in) > 0
        then
            -- Suffix already present
            return server_arch_in;
        end if;
        return server_arch_in || suffix;
    end$$ language plpgsql;

    --
    -- Raises: 
    --   server_arch_not_found
    --   no_subscribe_permissions
    create or replace function base_channel_for_release_arch(
        release_in in varchar,
        server_arch_in in varchar,
        org_id_in in numeric default -1,
        user_id_in in numeric default null
    ) returns numeric as $$
    declare
        server_arch varchar(256) := rhn_channel.normalize_server_arch(server_arch_in);
        server_arch_id numeric;
    begin
        -- Look up the server arch
            select id
              into server_arch_id
              from rhnServerArch
             where label = server_arch;
            if not found then
                perform rhn_exception.raise_exception('server_arch_not_found');
            end if;

        return rhn_channel.base_channel_rel_archid(release_in, server_arch_id,
            org_id_in, user_id_in);
    end$$ language plpgsql;

    create or replace function base_channel_rel_archid(
        release_in in varchar,
        server_arch_id_in in numeric,
        org_id_in in numeric default -1,
        user_id_in in numeric default null
    ) returns numeric as $$
    declare
        denied_channel_id numeric := null;
        valid_org_id numeric := org_id_in;
        valid_user_id numeric := user_id_in;
        channel_subscribable numeric;
    -- Cursor that fetches all the possible base channels for a
    -- (server_arch_id, release, org_id) combination
        base_channel_cursor cursor(
                release_in varchar,
                server_arch_id_in numeric,
                org_id_in numeric
        ) for
                select distinct c.*
                from    rhnOrgDistChannelMap                       odcm,
                                rhnServerChannelArchCompat      scac,
                                rhnChannel                                      c
                where   c.parent_channel is null
                        and c.id = odcm.channel_id
                        and c.channel_arch_id = odcm.channel_arch_id
                        and odcm.release = release_in
                        and odcm.for_org_id = org_id_in
                        and scac.server_arch_id = server_arch_id_in
                        and scac.channel_arch_id = c.channel_arch_id;

    begin
        if org_id_in = -1 and user_id_in is not null then
            -- Get the org id from the user id

                select org_id
                  into valid_org_id
                  from web_contact
                 where id = user_id_in;

                if not found then
                    -- User doesn't exist
                    -- XXX Only list public stuff for now
                    valid_user_id := null;
                    valid_org_id := -1;
                end if;
        end if;

        for c in base_channel_cursor(release_in, server_arch_id_in, valid_org_id)
        loop
            -- This row is a possible match
            if valid_user_id is null then
                -- User ID not specified, so no user to channel permissions to
                -- check
                return c.id;
            end if;

            -- Check user to channel permissions
            select rhn_channel.loose_user_role_check(c.id, user_id_in, 'subscribe')
              into channel_subscribable;

            if channel_subscribable = 1 then
                return c.id;
            end if;
                
            -- Base channel exists, but is not subscribable; keep trying
            denied_channel_id := c.id;
        end loop;
        
        if denied_channel_id is not null then
            perform rhn_exception.raise_exception('no_subscribe_permissions');
        end if;
        -- No base channel applies
        return NULL;
    end$$ language plpgsql;

    CREATE OR REPLACE FUNCTION clear_subscriptions(server_id_in IN NUMERIC, deleting_server IN NUMERIC default 0,
                                update_family_countsYN IN NUMERIC default 1 ) returns void
    AS $$
    declare
        server_channels cursor(server_id_in numeric) for
                select  s.org_id, sc.channel_id, cfm.channel_family_id
                from    rhnServer s,
                        rhnServerChannel sc,
                        rhnChannelFamilyMembers cfm
                where   s.id = server_id_in
                        and s.id = sc.server_id
                        and sc.channel_id = cfm.channel_id
                order by cfm.channel_family_id;
        last_channel_family_id rhnChannelFamilyMembers.channel_family_id%type := -1;
        last_channel_org_id    rhnServer.org_id%type := -1;
    BEGIN
        for channel in server_channels(server_id_in)
        loop
                perform rhn_channel.unsubscribe_server(server_id_in, channel.channel_id, 1, 1, deleting_server, 0);
                if update_family_countsYN > 0
                    and channel.channel_family_id != last_channel_family_id then
                    -- update family counts only once
                    -- after all channels with same family has been fetched
                    if last_channel_family_id != -1 then
                        perform rhn_channel.update_family_counts(channel.channel_family_id, channel.org_id);
                    end if;
                    last_channel_family_id := channel.channel_family_id;
                    last_channel_org_id    := channel.org_id;
                end if;
        end loop;
        if update_family_countsYN > 0 and last_channel_family_id != -1 then
            -- update the last family fetched
            perform rhn_channel.update_family_counts(last_channel_family_id, last_channel_org_id);
        end if;
    END$$ language plpgsql;

    CREATE OR REPLACE FUNCTION unsubscribe_server(server_id_in IN NUMERIC, channel_id_in NUMERIC, immediate_in NUMERIC default 1, unsubscribe_children_in numeric default 0,
                                 deleting_server in numeric default 0,
                                 update_family_countsYN in numeric default 1) returns void
    AS $$
    declare
        channel_family_id_val   NUMERIC;
        server_org_id_val       NUMERIC;
        available_subscriptions NUMERIC; 
        server_already_in_chan  BOOLEAN;
        channel_family_is_proxy cursor(channel_family_id_in numeric) for
                select  1
                from    rhnChannelFamily
                where   id = channel_family_id_in
                    and label = 'rhn-proxy';
        channel_family_is_satellite cursor(channel_family_id_in numeric) for
                select  1
                from    rhnChannelFamily
                where   id = channel_family_id_in
                    and label = 'rhn-satellite';
        child record;
    BEGIN
        -- In PostgreSQL recursion with opened cursors is not allowed so we use
        -- FOR IN SELECT form which is ok.
        FOR child IN select  c.id
                from    rhnChannel                      c,
                                rhnServerChannel        sc
                where   1=1
                        and c.parent_channel = channel_id_in
                        and c.id = sc.channel_id
                        and sc.server_id = server_id_in
        LOOP
            if unsubscribe_children_in = 1 then
                perform rhn_channel.unsubscribe_server(server_id_in,
                                                       child.id,
                                                       immediate_in,
                                                       unsubscribe_children_in,
                                                       deleting_server,
                                                       update_family_countsYN);
            else
                perform rhn_exception.raise_exception('channel_unsubscribe_child_exists');
            end if;
        END LOOP;
        
        server_already_in_chan := rhn_channel.check_server_subscription(server_id_in, channel_id_in);
    
        IF NOT server_already_in_chan
        THEN
            RETURN;
        END IF;
        
   if deleting_server = 0 then 
      insert into rhnServerHistory (id,server_id,summary,details) (
          select  nextval('rhn_event_id_seq'),
                server_id_in,
             'unsubscribed from channel ' || SUBSTR(c.label, 0, 106),
             c.label
          from    rhnChannel c
          where   c.id = channel_id_in
      );
   end if;
        
   DELETE FROM rhnServerChannel WHERE server_id = server_id_in AND channel_id = channel_id_in;

   if deleting_server = 0 then 
        perform queue_server(server_id_in, immediate_in);

        update rhnServer
           set channels_changed = current_timestamp
         where id = server_id_in;
   end if;

        channel_family_id_val := rhn_channel.family_for_channel(channel_id_in);
        IF channel_family_id_val IS NULL
        THEN
            perform rhn_exception.raise_exception('channel_unsubscribe_no_family');
        END IF;

        for ignore in channel_family_is_satellite(channel_family_id_val) loop
                delete from rhnSatelliteInfo where server_id = server_id_in;
        end loop;

        for ignore in channel_family_is_proxy(channel_family_id_val) loop
                delete from rhnProxyInfo where server_id = server_id_in;
        end loop;
        SELECT org_id INTO server_org_id_val
          FROM rhnServer
         WHERE id = server_id_in;
         
        if update_family_countsYN = 1 then
           perform rhn_channel.update_family_counts(channel_family_id_val, server_org_id_val);
        end if;
    END$$ language plpgsql;

    CREATE OR REPLACE FUNCTION family_for_channel(channel_id_in IN NUMERIC)
    RETURNS NUMERIC
    AS $$
    declare
        channel_family_id_val NUMERIC;
    BEGIN
        SELECT channel_family_id INTO channel_family_id_val
          FROM rhnChannelFamilyMembers
         WHERE channel_id = channel_id_in;

        IF NOT FOUND THEN
          RETURN NULL;
        END IF;
         
        RETURN channel_family_id_val;
    END$$ language plpgsql;

    CREATE OR REPLACE FUNCTION available_family_subscriptions(channel_family_id_in IN NUMERIC, org_id_in IN NUMERIC)
    RETURNS NUMERIC
    AS $$
    declare
        cfp record;
        current_members_val NUMERIC;
        max_members_val     NUMERIC;
        found               NUMERIC;
    BEGIN
        for cfp in SELECT * FROM rhnOrgChannelFamilyPermissions
	    WHERE channel_family_id = channel_family_id_in
	      AND org_id = org_id_in
        LOOP
            found := 1;
            current_members_val := cfp.current_members;
            max_members_val := cfp.max_members;
        END LOOP;

        -- not found: either the channel fam doesn't have an entry in cfp, or the org doesn't have access to it.
        -- either way, there are no available subscriptions

        IF found IS NULL
        THEN
            RETURN 0;
        END IF;

        -- null max members?  in that case, pass it on; NULL means infinite
        IF max_members_val IS NULL
        THEN
            RETURN NULL;
        END IF;

        -- otherwise, return the delta
        RETURN max_members_val - current_members_val;
    END$$ language plpgsql;

    CREATE OR REPLACE FUNCTION available_fve_family_subs(channel_family_id_in IN NUMERIC, org_id_in IN NUMERIC)
    RETURNS NUMERIC
    AS $$
    declare
        cfp record;
        fve_current_members_val NUMERIC;
        fve_max_members_val     NUMERIC;
        found               NUMERIC;
    BEGIN
        for cfp in SELECT * FROM rhnOrgChannelFamilyPermissions
	    WHERE channel_family_id = channel_family_id_in
	      AND org_id = org_id_in
        LOOP
            found := 1;
            fve_current_members_val := cfp.fve_current_members;
            fve_max_members_val := cfp.fve_max_members;
        END LOOP;

        -- not found: either the channel fam doesn't have an entry in cfp, or the org doesn't have access to it.
        -- either way, there are no available subscriptions
        
        IF found IS NULL
        THEN
            RETURN 0;
        END IF;

        -- null max members?  in that case, pass it on; NULL means infinite                     
        IF fve_max_members_val IS NULL
        THEN
            RETURN NULL;
        END IF;

        -- otherwise, return the delta  
        RETURN fve_max_members_val - fve_current_members_val;
    END$$ language plpgsql;
    
    -- *******************************************************************
    -- FUNCTION: channel_family_current_members
    -- Calculates and returns the actual count of systems consuming
    --   physical channel subscriptions.
    -- Called by: update_family_counts 
    --            rhn_entitlements.repoll_virt_guest_entitlements
    -- *******************************************************************
    create or replace function channel_family_current_members(channel_family_id_in IN NUMERIC,
                                            org_id_in IN NUMERIC)
    returns numeric
    as $$
    declare
        current_members_count numeric := 0;
    begin
        select  count(distinct server_id)
        into    current_members_count
          from  rhnChannelFamilyServerPhysical cfsp
         where  cfsp.channel_family_id = channel_family_id_in
           and  cfsp.customer_id = org_id_in;
        return current_members_count;
    end$$ language plpgsql;


    create or replace function cfam_curr_fve_members(
        channel_family_id_in IN NUMERIC,
        org_id_in IN NUMERIC)
    returns numeric
    as $$
    declare
        current_members_count numeric := 0;

    begin
        select count(distinct sc.server_id)
          into current_members_count
          from rhnServerChannel sc,
               rhnChannelFamilyMembers cfm,
               rhnServer s
         where s.org_id = org_id_in
           and s.id = sc.server_id
           and cfm.channel_family_id = channel_family_id_in
           and cfm.channel_id = sc.channel_id
           and exists (
                select 1
                  from rhnChannelFamilyServerFve cfsp
                 where cfsp.CHANNEL_FAMILY_ID = channel_family_id_in
                   and cfsp.server_id = s.id
                );

        return current_members_count;
    end$$ language plpgsql;
    CREATE OR REPLACE FUNCTION update_family_counts(channel_family_id_in IN NUMERIC, 
                                   org_id_in IN NUMERIC) returns void
    AS $$
    BEGIN
        update rhnPrivateChannelFamily
           set current_members = rhn_channel.channel_family_current_members(channel_family_id_in, org_id_in),
               fve_current_members = rhn_channel.cfam_curr_fve_members(channel_family_id_in,org_id_in)
         where org_id = org_id_in
           and channel_family_id = channel_family_id_in;
    END$$ language plpgsql;
    
    create or replace function update_group_family_counts(group_label_in IN VARCHAR,
                                   org_id_in IN NUMERIC)
    returns void
    as $$
    declare
        i record;
    BEGIN
        FOR i IN (
                SELECT DISTINCT CFM.channel_family_id, SG.org_id
                 FROM rhnChannelFamilyMembers CFM
                 JOIN rhnServerChannel SC
                   ON SC.channel_id = CFM.channel_id
                 JOIN rhnServerGroupMembers SGM
                   ON SC.server_id = SGM.server_id
                 JOIN rhnServerGroup SG
                   ON SGM.server_group_id = SG.id
                 JOIN rhnServerGroupType SGT
                   ON SG.group_type = SGT.id
                WHERE SGT.label = group_label_in
                  AND SG.org_id = org_id_in
                  AND SGT.is_base = 'Y'
        ) LOOP
            perform rhn_channel.update_family_counts(i.channel_family_id, i.org_id);
        END LOOP;
    END$$ language plpgsql;

    CREATE OR REPLACE FUNCTION available_chan_subscriptions(channel_id_in IN NUMERIC, 
                                          org_id_in IN NUMERIC)
    RETURNS NUMERIC
    AS $$
    declare
            channel_family_id_val NUMERIC;
    BEGIN
        SELECT channel_family_id INTO STRICT channel_family_id_val
            FROM rhnChannelFamilyMembers
            WHERE channel_id = channel_id_in;
         
            RETURN rhn_channel.available_family_subscriptions(
                           channel_family_id_val, org_id_in);
    END$$ language plpgsql;

    CREATE OR REPLACE FUNCTION available_fve_chan_subs(channel_id_in IN NUMERIC,
                                          org_id_in IN NUMERIC)
    RETURNS NUMERIC
    AS $$
    declare
            channel_family_id_val NUMERIC;
    BEGIN
        SELECT channel_family_id INTO STRICT channel_family_id_val
            FROM rhnChannelFamilyMembers
            WHERE channel_id = channel_id_in;

            RETURN rhn_channel.available_fve_family_subs(
                           channel_family_id_val, org_id_in);
    END$$ language plpgsql;

    create or replace function unsubscribe_server_from_family(server_id_in in numeric, 
                                             channel_family_id_in in numeric)
    returns void
    as $$
    begin
        delete
        from    rhnServerChannel rsc
        where   rsc.server_id = server_id_in
            and channel_id in (
                select  rcfm.channel_id
                from    rhnChannelFamilyMembers rcfm
                where   rcfm.channel_family_id = channel_family_id_in);
    end$$ language plpgsql;

    create or replace function get_org_id(channel_id_in in numeric)
    returns numeric
    as $$
    declare
        org_id_out numeric;
    begin
        select org_id into strict org_id_out
            from rhnChannel
            where id = channel_id_in;
         
            return org_id_out;
    end$$ language plpgsql;
    
    create or replace function get_cfam_org_access(cfam_id_in in numeric, org_id_in in numeric)
    returns numeric
    as $$
    begin
      if exists(
                        select  1
                        from    rhnOrgChannelFamilyPermissions cfp
                        where   cfp.org_id = org_id_in
      ) then
                return 1;
      else
                return 0;
      end if;
    end$$ language plpgsql;

    create or replace function get_org_access(channel_id_in in numeric, org_id_in in numeric)
    returns integer
    as $$
    begin
        -- the idea: if we get past this query, 
        -- the org has access to the channel, else not
        if exists(
        select 1
          from rhnChannelFamilyMembers CFM,
               rhnOrgChannelFamilyPermissions CFP
         where cfp.org_id = org_id_in
           and CFM.channel_family_id = CFP.channel_family_id
           and CFM.channel_id = channel_id_in
           and (CFP.max_members > 0 or CFP.max_members is null or CFP.fve_max_members > 0 or CFP.fve_max_members is null or CFP.org_id = 1) )
        then
          return 1;
        else
          return 0;
        end if;
    end$$ language plpgsql;
    
    -- check if a user has a given role, or if such a role is inferrable
    -- returns NULL if OK, error message otherwise
    create or replace function user_role_check_debug(channel_id_in in numeric, 
                                   user_id_in in numeric, 
                                   role_in in varchar)
    returns varchar
    as $$
    declare
        org_id numeric;
    begin
        org_id := rhn_user.get_org_id(user_id_in);

        -- channel might be shared
        if role_in = 'subscribe' and
           rhn_channel.shared_user_role_check(channel_id_in, user_id_in, role_in) = 1 then
            return NULL;
        end if;
        
        if role_in = 'manage' and 
           COALESCE(rhn_channel.get_org_id(channel_id_in), -1) <> org_id then
               return 'channel_not_owned';
        end if;
        
        if role_in = 'subscribe' and 
           rhn_channel.get_org_access(channel_id_in, org_id) = 0 then
                return 'channel_not_available';
        end if;
        
        -- channel admins have all roles
        if rhn_user.check_role_implied(user_id_in, 'channel_admin') = 1 then
            return NULL;
        end if;

        -- the subscribe permission is inferred 
        -- UNLESS the not_globally_subscribable flag is set
        if role_in = 'subscribe'
        then
            if rhn_channel.org_channel_setting(channel_id_in, 
                       org_id,
                       'not_globally_subscribable') = 0 then
                return NULL;
            end if;
        end if;
        
        -- all other roles (manage right now) are explicitly granted    
        if rhn_channel.direct_user_role_check(channel_id_in,
                                              user_id_in, role_in) = 1 then
            return NULL;
        end if;
        return 'direct_permission';
    end$$ language plpgsql;
    
    -- same as above, but with 1/0 output; useful in views, etc
    create or replace function user_role_check(channel_id_in in numeric, user_id_in in numeric, role_in in varchar)
    returns numeric
    as $$
    begin
        if rhn_channel.user_role_check_debug(channel_id_in,
                                             user_id_in, role_in) is NULL then
            return 1;
        else
            return 0;
        end if;
    end$$ language plpgsql;

    --
    -- For multiorg phase II, this function simply checks to see if the user's
    -- has a trust relationship that includes this channel by id.
    --
    create or replace function shared_user_role_check(channel_id in numeric, user_id in numeric, role in varchar)
    returns numeric
    as $$
    declare
      n numeric;
      oid numeric;
    begin
      oid := rhn_user.get_org_id(user_id);
      select 1 into n
      from rhnSharedChannelView s
      where s.id = channel_id and s.org_trust_id = oid;

      if not found then
        return 0;
      end if;

      return 1;
    end$$ language plpgsql;

    -- same as above, but returns 1 if user_id_in is null
    -- This is useful in queries where user_id is not specified
    create or replace function loose_user_role_check(channel_id_in in numeric, user_id_in in numeric, role_in in varchar)
    returns numeric
    as $$
    begin
        if user_id_in is null then
            return 1;
        end if;
        return rhn_channel.user_role_check(channel_id_in, user_id_in, role_in);
    end$$ language plpgsql;
    
    -- directly checks the table, no inferred permissions
    create or replace function direct_user_role_check(channel_id_in in numeric, user_id_in in numeric, role_in in varchar)
    returns numeric
    as $$
    declare
        throwaway numeric;
    begin
        -- the idea: if we get past this query, the user has the role, else no
        select 1 into throwaway
          from rhnChannelPermissionRole CPR,
               rhnChannelPermission CP
         where CP.user_id = user_id_in
           and CP.channel_id = channel_id_in
           and CPR.label = role_in
           and CP.role_id = CPR.id;

      if not found then
        return 0;
      end if;
           
      return 1;
    end$$ language plpgsql;
    
    -- check if an org has a certain setting
    create or replace function org_channel_setting(channel_id_in in numeric, org_id_in in numeric, setting_in in varchar)
    returns numeric
    as $$
    declare
        throwaway numeric;
    begin
        -- the idea: if we get past this query, the org has the setting
        select 1 into throwaway
          from rhnOrgChannelSettingsType OCST,
               rhnOrgChannelSettings OCS
         where OCS.org_id = org_id_in
           and OCS.channel_id = channel_id_in
           and OCST.label = setting_in
           and OCS.setting_id = OCST.id;

      if not found then
        return 0;
      end if;

      return 1;
    end$$ language plpgsql;
    
    CREATE OR REPLACE FUNCTION channel_priority(channel_id_in IN numeric) 
    RETURNS numeric
    AS $$
    declare
         channel_name varchar(256);
         priority numeric;
         end_of_life_val timestamptz;
         org_id_val numeric;
    BEGIN

        select name, end_of_life, org_id
        into channel_name, end_of_life_val, org_id_val
        from rhnChannel
        where id = channel_id_in;

        if end_of_life_val is not null then
          return -400;
        end if;

        if channel_name like 'Red Hat Enterprise Linux%' or channel_name like 'RHEL%' then
          priority := 1000;
          if channel_name not like '%Beta%' then
            priority := priority + 1000;
          end if;

          priority := priority +
            case
              when channel_name like '%v. 5%' then 600
              when channel_name like '%v. 4%' then 500
              when channel_name like '%v. 3%' then 400
              when channel_name like '%v. 2%' then 300
              when channel_name like '%v. 1%' then 200
              else 0
            end;

          priority := priority +
            case
              when channel_name like 'Red Hat Enterprise Linux (v. 5%' then 60
              when (channel_name like '%AS%' and channel_name not like '%Extras%') then 50
              when (channel_name like '%ES%' and channel_name not like '%Extras%') then 40
              when (channel_name like '%WS%' and channel_name not like '%Extras%') then 30
              when (channel_name like '%Desktop%' and channel_name not like '%Extras%') then 20
              when channel_name like '%Extras%' then 10
              else 0
            end; 

          priority := priority +
            case
              when channel_name like '%)' then 5
              else 0
            end;

          priority := priority +
            case
              when channel_name like '%32-bit x86%' then 4
              when channel_name like '%64-bit Intel Itanium%' then 3
              when channel_name like '%64-bit AMD64/Intel EM64T%' then 2
              else 0
            end;
        elsif channel_name like 'Red Hat Desktop%' then
            priority := 900;

            if channel_name not like '%Beta%' then
               priority := priority + 50;
            end if;

          priority := priority +
            case
              when channel_name like '%v. 4%' then 40
              when channel_name like '%v. 3%' then 30
              when channel_name like '%v. 2%' then 20
              when channel_name like '%v. 1%' then 10
              else 0
            end;
            
          priority := priority +
            case
              when channel_name like '%32-bit x86%' then 4
              when channel_name like '%64-bit Intel Itanium%' then 3
              when channel_name like '%64-bit AMD64/Intel EM64T%' then 2
              else 0
            end;
         
        elsif org_id_val is not null then
          priority := 600;
        else
          priority := 500;
        end if;
      
      return -priority;

    end$$ language plpgsql;

    -- right now this only does the accounting changes; the cascade
    -- actually does the rhnServerChannel delete.
    create or replace function delete_server_channels(server_id_in in numeric) returns void
    as $$
    begin
        update  rhnPrivateChannelFamily
        set     current_members = current_members -1
        where   org_id in (
                        select  org_id
                        from    rhnServer
                        where   id = server_id_in
                )
                and channel_family_id in (
                        select  rcfm.channel_family_id
                        from    rhnChannelFamilyMembers rcfm,
                                rhnServerChannel rsc
                        where   rsc.server_id = server_id_in
                                and rsc.channel_id = rcfm.channel_id
                and not exists (
                    select 1
                    from
                        rhnChannelFamilyVirtSubLevel cfvsl,
                        rhnSGTypeVirtSubLevel sgtvsl,
                        rhnServerEntitlementView sev,
                        rhnVirtualInstance vi
                    where
                        -- system is a virtual instance
                        vi.virtual_system_id = server_id_in
                        and vi.host_system_id = sev.server_id
                        -- system's host has a virt ent
                        and sev.label in ('virtualization_host',
                                          'virtualization_host_platform')
                        and sev.server_group_type_id = 
                            sgtvsl.server_group_type_id
                        -- the host's virt ent grants a cf virt sub level
                        and sgtvsl.virt_sub_level_id = cfvsl.virt_sub_level_id
                        -- the cf is in that virt sub level
                        and cfvsl.channel_family_id = rcfm.channel_family_id
                    )
                );
    end$$ language plpgsql;

    -- this could certainly be optimized to do updates if needs be
    create or replace function refresh_newest_package(channel_id_in in numeric,
                                      caller_in in varchar default '(unknown)',
                                      package_name_id_in in numeric default null)
    returns void
    as $$
    -- procedure refreshes rows for name_id = package_name_id_in or
    -- all rows if package_name_id_in is null
    begin
        delete from rhnChannelNewestPackage
              where channel_id = channel_id_in
                and (package_name_id_in is null
                     or name_id = package_name_id_in);
        insert into rhnChannelNewestPackage
                (channel_id, name_id, evr_id, package_id, package_arch_id)
                (select channel_id,
                        name_id, evr_id,
                        package_id, package_arch_id
                   from rhnChannelNewestPackageView
                  where channel_id = channel_id_in
                    and (package_name_id_in is null
                         or name_id = package_name_id_in)
                );
        insert into rhnChannelNewestPackageAudit (channel_id, caller)
             values (channel_id_in, caller_in);
        update rhnChannel
           set last_modified = greatest(current_timestamp,
                                        last_modified + interval '1 second')
         where id = channel_id_in;
    end$$ language plpgsql;

   create or replace function update_channel ( channel_id_in in numeric, invalidate_ss in numeric default 0, 
                              date_to_use in timestamptz default current_timestamp ) returns void
   as $$
   declare
   channel_last_modified timestamptz;
   last_modified_value timestamptz;

   snapshots cursor for
   select  snapshot_id id
   from    rhnSnapshotChannel
   where   channel_id = channel_id_in;

   begin

      select last_modified
      into channel_last_modified
      from rhnChannel
      where id = channel_id_in;
  
      last_modified_value := date_to_use;

      if last_modified_value <= channel_last_modified then
          last_modified_value := last_modified_value + interval '1 second';
      end if;

      update rhnChannel set last_modified = last_modified_value
      where id = channel_id_in;

      if invalidate_ss = 1 then 
        for snapshot in snapshots loop
            update rhnSnapshot
            set invalid = lookup_snapshot_invalid_reason('channel_modified')
            where id = snapshot.id;
        end loop;
      end if;

   end$$ language plpgsql;

   create or replace function update_channels_by_package ( package_id_in in numeric, date_to_use in timestamptz default current_timestamp ) returns void
   as $$
   declare
   channels cursor for
   select channel_id
   from rhnChannelPackage
   where package_id = package_id_in
   order by channel_id;

   begin
      for channel in channels loop
         -- we want to invalidate the snapshot assocated with the channel when we
         -- do this b/c we know we've added or removed or packages
         perform rhn_channel.update_channel ( channel.channel_id, 1, date_to_use );
      end loop;
   end$$ language plpgsql;

   
   create or replace function update_channels_by_errata ( errata_id_in numeric, date_to_use in timestamptz default current_timestamp ) returns void
   as $$
   declare
   channels cursor for
   select channel_id
   from rhnChannelErrata
   where errata_id = errata_id_in
   order by channel_id;

   begin
      for channel in channels loop
         -- we won't invalidate snapshots, b/c just changing the errata associated with
         -- a channel shouldn't invalidate snapshots
         perform rhn_channel.update_channel ( channel.channel_id, 0, date_to_use );
      end loop;
   end$$ language plpgsql;

   create or replace function update_needed_cache(channel_id_in in numeric) returns void
   as $$
   declare
   server record;
   begin
      -- we intentionaly do a loop here instead of one huge select
      -- b/c we want to break update into smaller transaction to unblock other sessions
      -- querying rhnServerNeededCache
      for server in (
                select sc.server_id as id
                  from rhnServerChannel sc
                 where sc.channel_id = channel_id_in
                 order by id asc
      ) loop
         perform queue_server(server.id, 0); -- NOT IMMEDIATE
      end loop;
   end$$ language plpgsql;

    create or replace function set_comps(channel_id_in in numeric, path_in in varchar, timestamp_in in varchar) returns void
    as $$
    declare
    row record;
    begin
        for row in (
            select relative_filename, last_modified
            from rhnChannelComps
            where channel_id = channel_id_in
            ) loop
            if row.relative_filename = path_in
                and row.last_modified = to_timestamp(timestamp_in, 'YYYYMMDDHH24MISS') then
                return;
            end if;
        end loop;
        delete from rhnChannelComps
        where channel_id = channel_id_in;
        insert into rhnChannelComps (id, channel_id, relative_filename, last_modified, created, modified)
        values (sequence_nextval('rhn_channelcomps_id_seq'), channel_id_in, path_in, to_timestamp(timestamp_in, 'YYYYMMDDHH24MISS'), current_timestamp, current_timestamp);
    end$$ language plpgsql;

-- restore the original setting
update pg_settings set setting = overlay( setting placing '' from 1 for (length('rhn_channel')+1) ) where name = 'search_path';
   07070100000827000081B400000000000000000000000167AE1114000000BB000000000000000000000000000000000000007A00000000susemanager-schema/upgrade/spacewalk-schema-2.3-to-spacewalk-schema-2.4/008-rhnOrgConfiguration-errata_emails_enabled.sql ALTER TABLE rhnOrgConfiguration ADD errata_emails_enabled CHAR(1)
    DEFAULT('Y') NOT NULL
    CONSTRAINT rhn_org_conf_errata_emails_chk
    CHECK (errata_emails_enabled in ('Y', 'N'));
 07070100000828000081B400000000000000000000000167AE111400000596000000000000000000000000000000000000006600000000susemanager-schema/upgrade/spacewalk-schema-2.3-to-spacewalk-schema-2.4/009-rhnOrgAdminManagement.sql --
-- Copyright (c) 2015 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

CREATE TABLE rhnOrgAdminManagement
(
    org_id                  NUMERIC NOT NULL
                                CONSTRAINT rhn_orgadm_mngt_fk
                                    REFERENCES web_customer (id)
                                    ON DELETE CASCADE,
    enabled                 CHAR(1)
                                DEFAULT ('Y') NOT NULL
                                CONSTRAINT rhn_orgadm_mngt_enabled_ck
                                    CHECK (enabled in ('Y', 'N')),
    created                 TIMESTAMPTZ
                                DEFAULT (current_timestamp) NOT NULL,
    modified                TIMESTAMPTZ
                                DEFAULT (current_timestamp) NOT NULL
)

;

CREATE UNIQUE INDEX rhn_orgadm_mngt_org_id
    on rhnOrgAdminManagement (org_id)
        ;
  07070100000829000081B400000000000000000000000167AE11140000004A000000000000000000000000000000000000006B00000000susemanager-schema/upgrade/spacewalk-schema-2.3-to-spacewalk-schema-2.4/010-rhnOrgAdminManagement-data.sql    INSERT INTO rhnOrgAdminManagement (org_id) (SELECT id FROM web_customer);
  0707010000082A000081B400000000000000000000000167AE1114000000FE000000000000000000000000000000000000006500000000susemanager-schema/upgrade/spacewalk-schema-2.3-to-spacewalk-schema-2.4/011-web_customer-trigger.sql  
create or replace function web_customer_insert_trig_fun() returns trigger
as
$$
begin
	insert into rhnOrgConfiguration (org_id) values (new.id);
	insert into rhnOrgAdminManagement (org_id) values (new.id);

        return new;
end;
$$
language plpgsql;
  0707010000082B000081B400000000000000000000000167AE1114000015C1000000000000000000000000000000000000006200000000susemanager-schema/upgrade/spacewalk-schema-2.3-to-spacewalk-schema-2.4/012-rpm-rpmstrcmp-fix.sql -- create schema rpm;

--update pg_setting
update pg_settings set setting = 'rpm,' || setting where name = 'search_path';

create or replace function isdigit(ch CHAR)
    RETURNS BOOLEAN as $$
    BEGIN
        if ascii(ch) between ascii('0') and ascii('9')
        then
            return TRUE;
        end if;
        return FALSE;
    END ;
$$ language 'plpgsql';

    
    create or replace FUNCTION isalpha(ch CHAR)
    RETURNS BOOLEAN as $$
    BEGIN
        if ascii(ch) between ascii('a') and ascii('z') or 
            ascii(ch) between ascii('A') and ascii('Z')
        then
            return TRUE;
        end if;
        return FALSE;
    END;
$$ language 'plpgsql';


    create or replace FUNCTION isalphanum(ch CHAR)
    RETURNS BOOLEAN as $$ 
    BEGIN
        if ascii(ch) between ascii('a') and ascii('z') or 
            ascii(ch) between ascii('A') and ascii('Z') or
            ascii(ch) between ascii('0') and ascii('9')
        then
            return TRUE;
        end if;
        return FALSE;
    END;
    $$ language 'plpgsql';


    create or replace FUNCTION rpmstrcmp (string1 IN VARCHAR, string2 IN VARCHAR)
    RETURNS INTEGER as $$
    declare
        str1 VARCHAR := string1;
        str2 VARCHAR := string2;
        digits VARCHAR(10) := '0123456789';
        lc_alpha VARCHAR(27) := 'abcdefghijklmnopqrstuvwxyz';
        uc_alpha VARCHAR(27) := 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
        alpha VARCHAR(54) := lc_alpha || uc_alpha;
        one VARCHAR;
        two VARCHAR;
        isnum BOOLEAN;
    BEGIN
        if str1 is NULL or str2 is NULL
        then
            RAISE EXCEPTION 'VALUE_ERROR.';
        end if;
      
        if str1 = str2
        then
            return 0;
        end if;
        one := str1;
        two := str2;

        <<segment_loop>>
        while one <> '' and two <> ''
        loop
            declare
                segm1 VARCHAR;
                segm2 VARCHAR;
            begin
                --DBMS_OUTPUT.PUT_LINE('Params: ' || one || ',' || two);
                -- Throw out all non-alphanum characters
                while one <> '' and not rpm.isalphanum(one)
                loop
                    one := substr(one, 2);
                end loop;
                while two <> '' and not rpm.isalphanum(two)
                loop
                    two := substr(two, 2);
                end loop;
                str1 := one;
                str2 := two;
                if str1 <> '' and rpm.isdigit(str1)
                then
                    str1 := ltrim(str1, digits);
                    str2 := ltrim(str2, digits);
                    isnum := true;
                else
                    str1 := ltrim(str1, alpha);
                    str2 := ltrim(str2, alpha);
                    isnum := false;
                end if;
                if str1 <> ''
                then segm1 := substr(one, 1, length(one) - length(str1));
                else segm1 := one;
                end if;
                    
                if str2 <> ''
                then segm2 := substr(two, 1, length(two) - length(str2));
                else segm2 := two;
                end if;
                if segm1 = '' then return -1; end if; /* arbitrary */
                if segm2 = '' then
                                        if isnum then
                                                return 1;
                                        else
                                                return -1;
                                        end if;
                                end if;
                if isnum
                then
                   
                    segm1 := ltrim(segm1, '0');
                    segm2 := ltrim(segm2, '0');

                    if segm1 = '' and segm2 <> ''
                    then
                        return -1;
                    end if;
                    if segm1 <> '' and segm2 = ''
                    then
                        return 1;
                    end if;
                    if length(segm1) > length(segm2) then return 1; end if;
                    if length(segm2) > length(segm1) then return -1; end if;
                end if;
                  if segm1 < segm2 then return -1; end if;
                if segm1 > segm2 then return 1; end if;
               one := str1;
                two := str2;
            end;
        end loop segment_loop;
     
        if one = '' and two = '' then return 0; end if;
        if one = '' then return -1; end if;
        return 1;
    END ;
$$ language 'plpgsql';



   create or replace FUNCTION vercmp(
        e1 VARCHAR, v1 VARCHAR, r1 VARCHAR, 
        e2 VARCHAR, v2 VARCHAR, r2 VARCHAR)
    RETURNS INTEGER as $$
    declare
        rc INTEGER;
          ep1 INTEGER;
          ep2 INTEGER;
          BEGIN
            if e1 is null or e1 = '' then
              ep1 := 0;
            else
              ep1 := e1::integer;
            end if;
            if e2 is null or e2 = '' then
              ep2 := 0;
            else
              ep2 := e2::integer;
            end if;
            -- Epochs are non-null; compare them
            if ep1 < ep2 then return -1; end if;
            if ep1 > ep2 then return 1; end if;
            rc := rpm.rpmstrcmp(v1, v2);
            if rc != 0 then return rc; end if;
           return rpm.rpmstrcmp(r1, r2);
         END;
         $$ language 'plpgsql';

-- restore the original setting
update pg_settings set setting = overlay( setting placing '' from 1 for (length('rpm')+1) ) where name = 'search_path';

   0707010000082C000081B400000000000000000000000167AE11140000053C000000000000000000000000000000000000006100000000susemanager-schema/upgrade/spacewalk-schema-2.3-to-spacewalk-schema-2.4/013-rhnResetPassword.sql  --
-- Copyright (c) 2015 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnResetPassword
(
    id            NUMERIC NOT NULL
                      CONSTRAINT rhn_rstpwd_id_pk primary key,
    user_id       NUMERIC NOT NULL
                      CONSTRAINT rhn_rstpwd_uid_fk REFERENCES web_contact (id)
                      ON DELETE CASCADE,
    token         VARCHAR(64) NOT NULL
                      CONSTRAINT rhn_rstpwd_token_uq UNIQUE,
    is_valid      char(1) DEFAULT 'Y' NOT NULL
                      CONSTRAINT rhn_rstpwd_is_valid_ck CHECK (is_valid IN ('Y', 'N')),
    created       TIMESTAMPTZ DEFAULT (current_timestamp) NOT NULL,
    modified      TIMESTAMPTZ DEFAULT (current_timestamp) NOT NULL
);

CREATE SEQUENCE rhn_reset_password_id_seq START WITH 500;
0707010000082D000081B400000000000000000000000167AE111400000135000000000000000000000000000000000000006900000000susemanager-schema/upgrade/spacewalk-schema-2.3-to-spacewalk-schema-2.4/014-rhnResetPassword-trigger.sql  
create or replace function rhn_rstpwd_mod_trig_fun() returns trigger as
$$
begin
        new.modified := current_timestamp;
        return new;
end;
$$ language plpgsql;

create trigger
rhn_rstpwd_mod_trig
before insert or update on rhnResetPassword
for each row
execute procedure rhn_rstpwd_mod_trig_fun();
   0707010000082E000081B400000000000000000000000167AE111400000707000000000000000000000000000000000000006B00000000susemanager-schema/upgrade/spacewalk-schema-2.3-to-spacewalk-schema-2.4/015-fixing-not-upgraded-schema.sql    
-- Dropping tables
drop table if exists rhn_command_queue_sessions;

-- Dropping PostgreSQL only functions
drop function if exists rhn_cmeth_val_trig_fun();
drop function if exists rhn_probe_delete_trigger_fun();
drop function if exists rhn_probe_insert_trigger_fun();
drop function if exists rhn_servnet_ipaddr_mon_trig_fun();
drop function if exists rhn_solaris_p_mod_trig_fun();
drop function if exists rhn_solaris_psm_mod_trig_fun();
drop function if exists rhn_solaris_ps_mod_trig_fun();
drop function if exists time_series_purge_mod_trig_fun();

-- Dropping sequences
drop sequence if exists rhn_check_suites_recid_seq;
drop sequence if exists rhn_command_q_comm_recid_seq;
drop sequence if exists rhn_command_q_inst_recid_seq;
drop sequence if exists rhn_commands_recid_seq;
drop sequence if exists rhn_command_target_recid_seq;
drop sequence if exists rhn_contact_groups_recid_seq;
drop sequence if exists rhn_contact_methods_recid_seq;
drop sequence if exists rhn_host_probes_recid_seq;
drop sequence if exists rhn_ntfmt_recid_seq;
drop sequence if exists rhn_pager_types_recid_seq;
drop sequence if exists rhn_physical_loc_recid_seq;
drop sequence if exists rhn_probes_recid_seq;
drop sequence if exists rhn_redirect_crit_recid_seq;
drop sequence if exists rhn_redirects_recid_seq;
drop sequence if exists rhn_redirect_types_recid_seq;
drop sequence if exists rhn_schedule_days_recid_seq;
drop sequence if exists rhn_schedules_recid_seq;
drop sequence if exists rhn_schedule_types_recid_seq;
drop sequence if exists rhn_schedule_weeks_recid_seq;
drop sequence if exists rhn_snmp_alert_recid_seq;
drop sequence if exists rhn_solaris_ps_seq;
drop sequence if exists rhn_solaris_pt_seq;
drop sequence if exists rhn_strategies_recid_seq;
drop sequence if exists rhn_url_probe_step_recid_seq;
 0707010000082F000081B400000000000000000000000167AE1114000006A7000000000000000000000000000000000000006900000000susemanager-schema/upgrade/spacewalk-schema-2.3-to-spacewalk-schema-2.4/016-fixing-not-upgraded-data.sql  -- Inserting into rhnPackageKey
update rhnPackageKey set provider_id = lookup_package_provider('Fedora')
 where key_id = '11adc0948e1431d5';

insert into rhnPackageKey (id, key_id, key_type_id, provider_id)
    (select sequence_nextval('rhn_pkey_id_seq'), '11adc0948e1431d5', lookup_package_key_type('gpg'), lookup_package_provider('Fedora') from dual
     where not exists (select 1 from rhnPackageKey where key_id = '11adc0948e1431d5'));

update rhnPackageKey set provider_id = lookup_package_provider('Fedora')
 where key_id = 'd8d1fa8ca29cb19c';

insert into rhnPackageKey (id, key_id, key_type_id, provider_id)
    (select sequence_nextval('rhn_pkey_id_seq'), 'd8d1fa8ca29cb19c', lookup_package_key_type('gpg'), lookup_package_provider('Fedora') from dual
     where not exists (select 1 from rhnPackageKey where key_id = 'd8d1fa8ca29cb19c'));

update rhnPackageKey set provider_id = lookup_package_provider('Fedora')
 where key_id = 'dbeae2e4efe550f5';

insert into rhnPackageKey (id, key_id, key_type_id, provider_id)
    (select sequence_nextval('rhn_pkey_id_seq'), 'dbeae2e4efe550f5', lookup_package_key_type('gpg'), lookup_package_provider('Fedora') from dual
     where not exists (select 1 from rhnPackageKey where key_id = 'dbeae2e4efe550f5'));

-- Inserting into rhnPackageUpgradeArchCompat
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) select
LOOKUP_PACKAGE_ARCH('ppc64le'), LOOKUP_PACKAGE_ARCH('ppc64le'), current_timestamp, current_timestamp from dual
where not exists (select 1 from rhnPackageUpgradeArchCompat where package_arch_id = LOOKUP_PACKAGE_ARCH('ppc64le') and package_upgrade_arch_id = LOOKUP_PACKAGE_ARCH('ppc64le'));
 07070100000830000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000004800000000susemanager-schema/upgrade/spacewalk-schema-2.4-to-spacewalk-schema-2.5   07070100000831000081B400000000000000000000000167AE111400007A8D000000000000000000000000000000000000006000000000susemanager-schema/upgrade/spacewalk-schema-2.4-to-spacewalk-schema-2.5/111-rhn_channel.pkb.sql   --
-- Copyright (c) 2008--2014 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--
--
--
--

-- create schema rhn_channel;

--update pg_setting
update pg_settings set setting = 'rhn_channel,' || setting where name = 'search_path';

    create or replace function obtain_read_lock(channel_family_id_in in numeric, org_id_in in numeric)
    returns void as $$
    declare
        read_lock timestamptz;
    begin
        select created into read_lock
          from rhnPrivateChannelFamily
         where channel_family_id = channel_family_id_in and org_id = org_id_in
           for update;
    end$$ language plpgsql;

    -- this "emulates" cursor server_base_subscriptions defined in oracle/rhn_channel.pks
    create or replace function server_base_subscriptions(server_id_in NUMERIC)
    returns boolean as $$
    begin
      return exists(SELECT C.id FROM rhnChannel C, rhnServerChannel SC
		    WHERE C.id = SC.channel_id
		      AND SC.server_id = server_id_in
		      AND C.parent_channel IS NULL);
    end$$ language plpgsql;

    -- this "emulates" cursor server_base_subscriptions defined in oracle/rhn_channel.pks
    create or replace function check_server_subscription(server_id_in NUMERIC, channel_id_in NUMERIC)
    returns boolean as $$
    begin
      return exists(SELECT channel_id FROM rhnServerChannel WHERE server_id = server_id_in AND channel_id = channel_id_in);
    end$$ language plpgsql;


    CREATE OR REPLACE FUNCTION subscribe_server(server_id_in IN NUMERIC, channel_id_in NUMERIC, immediate_in NUMERIC default 1, user_id_in in numeric default null) returns void
    AS $$
    declare
        channel_parent_val      rhnChannel.parent_channel%TYPE;
        parent_subscribed       BOOLEAN;
        server_has_base_chan    BOOLEAN;
        server_already_in_chan  BOOLEAN;
        channel_family_id_val   NUMERIC;
        server_org_id_val       NUMERIC;
        allowed                 numeric;
    BEGIN
        if user_id_in is not null then
            allowed := rhn_channel.user_role_check(channel_id_in, user_id_in, 'subscribe');
        else
            allowed := 1;
        end if;

        if allowed = 0 then
            perform rhn_exception.raise_exception('no_subscribe_permissions');
        end if;


        SELECT parent_channel INTO channel_parent_val FROM rhnChannel WHERE id = channel_id_in;

        IF channel_parent_val IS NOT NULL
        THEN
            -- child channel; if attempting to cross-subscribe a child to the wrong base, silently ignore
            parent_subscribed := rhn_channel.check_server_subscription(server_id_in, channel_parent_val);

            IF NOT parent_subscribed
            THEN
                RETURN;
            END IF;
        ELSE
            -- base channel
            server_has_base_chan := rhn_channel.server_base_subscriptions(server_id_in);

            IF server_has_base_chan
            THEN
                perform rhn_exception.raise_exception('channel_server_one_base');
            END IF;
        END IF;

        server_already_in_chan := rhn_channel.check_server_subscription(server_id_in, channel_id_in);

        IF server_already_in_chan
        THEN
            RETURN;
        END IF;

        channel_family_id_val := rhn_channel.family_for_channel(channel_id_in);
        IF channel_family_id_val IS NULL
        THEN
            perform rhn_exception.raise_exception('channel_subscribe_no_family');
        END IF;

        --
        -- Use the org_id of the server only if the org_id of the channel = NULL.
        -- This is required for subscribing to shared channels.
        --
        SELECT COALESCE(org_id, (SELECT org_id FROM rhnServer WHERE id = server_id_in))
          INTO server_org_id_val
          FROM rhnChannel
         WHERE id = channel_id_in;

        begin
            perform rhn_channel.obtain_read_lock(channel_family_id_val, server_org_id_val);
        exception
            when no_data_found then
                perform rhn_exception.raise_exception('channel_subscribe_no_family');
        end;

        insert into rhnServerHistory (id,server_id,summary,details) (
            select  nextval('rhn_event_id_seq'),
                    server_id_in,
                    'subscribed to channel ' || SUBSTR(c.label, 0, 106),
                    c.label
            from    rhnChannel c
            where   c.id = channel_id_in
        );

        INSERT INTO rhnServerChannel (server_id, channel_id) VALUES (server_id_in, channel_id_in);

        perform queue_server(server_id_in, immediate_in);

        update rhnServer
           set channels_changed = current_timestamp
         where id = server_id_in;
    END$$ language plpgsql;

    create or replace function guess_server_base(
        server_id_in in numeric
    ) RETURNS numeric as $$
    declare
        server_cursor cursor for
            select s.server_arch_id, s.release, s.org_id
              from rhnServer s
             where s.id = server_id_in;
    -- Cursor that fetches all the possible base channels for a
    -- (server_arch_id, release, org_id) combination
        base_channel_cursor cursor(
                release_in varchar,
                server_arch_id_in numeric,
                org_id_in numeric
        ) for
                select distinct c.*
                from    rhnOrgDistChannelMap                       odcm,
                                rhnServerChannelArchCompat      scac,
                                rhnChannel                                      c
                where   c.parent_channel is null
                        and c.id = odcm.channel_id
                        and c.channel_arch_id = odcm.channel_arch_id
                        and odcm.release = release_in
                        and odcm.for_org_id = org_id_in
                        and scac.server_arch_id = server_arch_id_in
                        and scac.channel_arch_id = c.channel_arch_id;

    begin
        for s in server_cursor loop
            for channel in base_channel_cursor(s.release,
                s.server_arch_id, s.org_id)
            loop
                return channel.id;
            end loop;
        end loop;
        -- Server not found, or no base channel applies to it
        return null;
    end$$ language plpgsql;

    -- Private function
    create or replace function normalize_server_arch(server_arch_in in varchar)
    returns varchar
    as $$
    declare
        suffix VARCHAR(128) := '-redhat-linux';
    begin
        if server_arch_in is NULL then
            return NULL;
        end if;
        if position('-' IN server_arch_in) > 0
        then
            -- Suffix already present
            return server_arch_in;
        end if;
        return server_arch_in || suffix;
    end$$ language plpgsql;

    --
    -- Raises:
    --   server_arch_not_found
    --   no_subscribe_permissions
    create or replace function base_channel_for_release_arch(
        release_in in varchar,
        server_arch_in in varchar,
        org_id_in in numeric default -1,
        user_id_in in numeric default null
    ) returns numeric as $$
    declare
        server_arch varchar(256) := rhn_channel.normalize_server_arch(server_arch_in);
        server_arch_id numeric;
    begin
        -- Look up the server arch
            select id
              into server_arch_id
              from rhnServerArch
             where label = server_arch;
            if not found then
                perform rhn_exception.raise_exception('server_arch_not_found');
            end if;

        return rhn_channel.base_channel_rel_archid(release_in, server_arch_id,
            org_id_in, user_id_in);
    end$$ language plpgsql;

    create or replace function base_channel_rel_archid(
        release_in in varchar,
        server_arch_id_in in numeric,
        org_id_in in numeric default -1,
        user_id_in in numeric default null
    ) returns numeric as $$
    declare
        denied_channel_id numeric := null;
        valid_org_id numeric := org_id_in;
        valid_user_id numeric := user_id_in;
        channel_subscribable numeric;
    -- Cursor that fetches all the possible base channels for a
    -- (server_arch_id, release, org_id) combination
        base_channel_cursor cursor(
                release_in varchar,
                server_arch_id_in numeric,
                org_id_in numeric
        ) for
                select distinct c.*
                from    rhnOrgDistChannelMap                       odcm,
                                rhnServerChannelArchCompat      scac,
                                rhnChannel                                      c
                where   c.parent_channel is null
                        and c.id = odcm.channel_id
                        and c.channel_arch_id = odcm.channel_arch_id
                        and odcm.release = release_in
                        and odcm.for_org_id = org_id_in
                        and scac.server_arch_id = server_arch_id_in
                        and scac.channel_arch_id = c.channel_arch_id;

    begin
        if org_id_in = -1 and user_id_in is not null then
            -- Get the org id from the user id

                select org_id
                  into valid_org_id
                  from web_contact
                 where id = user_id_in;

                if not found then
                    -- User doesn't exist
                    -- XXX Only list public stuff for now
                    valid_user_id := null;
                    valid_org_id := -1;
                end if;
        end if;

        for c in base_channel_cursor(release_in, server_arch_id_in, valid_org_id)
        loop
            -- This row is a possible match
            if valid_user_id is null then
                -- User ID not specified, so no user to channel permissions to
                -- check
                return c.id;
            end if;

            -- Check user to channel permissions
            select rhn_channel.loose_user_role_check(c.id, user_id_in, 'subscribe')
              into channel_subscribable;

            if channel_subscribable = 1 then
                return c.id;
            end if;

            -- Base channel exists, but is not subscribable; keep trying
            denied_channel_id := c.id;
        end loop;

        if denied_channel_id is not null then
            perform rhn_exception.raise_exception('no_subscribe_permissions');
        end if;
        -- No base channel applies
        return NULL;
    end$$ language plpgsql;

    CREATE OR REPLACE FUNCTION clear_subscriptions(server_id_in IN NUMERIC, deleting_server IN NUMERIC default 0) returns void
    AS $$
    declare
        server_channels cursor(server_id_in numeric) for
                select  s.org_id, sc.channel_id, cfm.channel_family_id
                from    rhnServer s,
                        rhnServerChannel sc,
                        rhnChannelFamilyMembers cfm
                where   s.id = server_id_in
                        and s.id = sc.server_id
                        and sc.channel_id = cfm.channel_id
                order by cfm.channel_family_id;
        last_channel_family_id rhnChannelFamilyMembers.channel_family_id%type := -1;
        last_channel_org_id    rhnServer.org_id%type := -1;
    BEGIN
        for channel in server_channels(server_id_in)
        loop
                perform rhn_channel.unsubscribe_server(server_id_in, channel.channel_id, 1, 1, deleting_server);
        end loop;
    END$$ language plpgsql;

    CREATE OR REPLACE FUNCTION unsubscribe_server(server_id_in IN NUMERIC, channel_id_in NUMERIC, immediate_in NUMERIC default 1, unsubscribe_children_in numeric default 0,
                                 deleting_server in numeric default 0) returns void
    AS $$
    declare
        channel_family_id_val   NUMERIC;
        server_org_id_val       NUMERIC;
        server_already_in_chan  BOOLEAN;
        channel_family_is_proxy cursor(channel_family_id_in numeric) for
                select  1
                from    rhnChannelFamily
                where   id = channel_family_id_in
                    and label = 'rhn-proxy';
        channel_family_is_satellite cursor(channel_family_id_in numeric) for
                select  1
                from    rhnChannelFamily
                where   id = channel_family_id_in
                    and label = 'rhn-satellite';
        child record;
    BEGIN
        -- In PostgreSQL recursion with opened cursors is not allowed so we use
        -- FOR IN SELECT form which is ok.
        FOR child IN select  c.id
                from    rhnChannel                      c,
                                rhnServerChannel        sc
                where   1=1
                        and c.parent_channel = channel_id_in
                        and c.id = sc.channel_id
                        and sc.server_id = server_id_in
        LOOP
            if unsubscribe_children_in = 1 then
                perform rhn_channel.unsubscribe_server(server_id_in,
                                                       child.id,
                                                       immediate_in,
                                                       unsubscribe_children_in,
                                                       deleting_server);
            else
                perform rhn_exception.raise_exception('channel_unsubscribe_child_exists');
            end if;
        END LOOP;

        server_already_in_chan := rhn_channel.check_server_subscription(server_id_in, channel_id_in);

        IF NOT server_already_in_chan
        THEN
            RETURN;
        END IF;

   if deleting_server = 0 then
      insert into rhnServerHistory (id,server_id,summary,details) (
          select  nextval('rhn_event_id_seq'),
                server_id_in,
             'unsubscribed from channel ' || SUBSTR(c.label, 0, 106),
             c.label
          from    rhnChannel c
          where   c.id = channel_id_in
      );
   end if;

   DELETE FROM rhnServerChannel WHERE server_id = server_id_in AND channel_id = channel_id_in;

   if deleting_server = 0 then
        perform queue_server(server_id_in, immediate_in);

        update rhnServer
           set channels_changed = current_timestamp
         where id = server_id_in;
   end if;

        channel_family_id_val := rhn_channel.family_for_channel(channel_id_in);
        IF channel_family_id_val IS NULL
        THEN
            perform rhn_exception.raise_exception('channel_unsubscribe_no_family');
        END IF;

        for ignore in channel_family_is_satellite(channel_family_id_val) loop
                delete from rhnSatelliteInfo where server_id = server_id_in;
        end loop;

        for ignore in channel_family_is_proxy(channel_family_id_val) loop
                delete from rhnProxyInfo where server_id = server_id_in;
        end loop;
        SELECT org_id INTO server_org_id_val
          FROM rhnServer
         WHERE id = server_id_in;

    END$$ language plpgsql;

    CREATE OR REPLACE FUNCTION family_for_channel(channel_id_in IN NUMERIC)
    RETURNS NUMERIC
    AS $$
    declare
        channel_family_id_val NUMERIC;
    BEGIN
        SELECT channel_family_id INTO channel_family_id_val
          FROM rhnChannelFamilyMembers
         WHERE channel_id = channel_id_in;

        IF NOT FOUND THEN
          RETURN NULL;
        END IF;

        RETURN channel_family_id_val;
    END$$ language plpgsql;

    create or replace function unsubscribe_server_from_family(server_id_in in numeric,
                                             channel_family_id_in in numeric)
    returns void
    as $$
    begin
        delete
        from    rhnServerChannel rsc
        where   rsc.server_id = server_id_in
            and channel_id in (
                select  rcfm.channel_id
                from    rhnChannelFamilyMembers rcfm
                where   rcfm.channel_family_id = channel_family_id_in);
    end$$ language plpgsql;

    create or replace function get_org_id(channel_id_in in numeric)
    returns numeric
    as $$
    declare
        org_id_out numeric;
    begin
        select org_id into strict org_id_out
            from rhnChannel
            where id = channel_id_in;

            return org_id_out;
    end$$ language plpgsql;

    create or replace function get_cfam_org_access(cfam_id_in in numeric, org_id_in in numeric)
    returns numeric
    as $$
    begin
      if exists(
                        select  1
                        from    rhnOrgChannelFamilyPermissions cfp
                        where   cfp.org_id = org_id_in
      ) then
                return 1;
      else
                return 0;
      end if;
    end$$ language plpgsql;

    create or replace function get_org_access(channel_id_in in numeric, org_id_in in numeric)
    returns integer
    as $$
    begin
        -- the idea: if we get past this query,
        -- the org has access to the channel, else not
        if exists(
        select 1
          from rhnChannelFamilyMembers CFM,
               rhnOrgChannelFamilyPermissions CFP
         where cfp.org_id = org_id_in
           and CFM.channel_family_id = CFP.channel_family_id
           and CFM.channel_id = channel_id_in)
        then
          return 1;
        else
          return 0;
        end if;
    end$$ language plpgsql;

    -- check if a user has a given role, or if such a role is inferrable
    -- returns NULL if OK, error message otherwise
    create or replace function user_role_check_debug(channel_id_in in numeric,
                                   user_id_in in numeric,
                                   role_in in varchar)
    returns varchar
    as $$
    declare
        org_id numeric;
    begin
        org_id := rhn_user.get_org_id(user_id_in);

        -- channel might be shared
        if role_in = 'subscribe' and
           rhn_channel.shared_user_role_check(channel_id_in, user_id_in, role_in) = 1 then
            return NULL;
        end if;

        if role_in = 'manage' and
           COALESCE(rhn_channel.get_org_id(channel_id_in), -1) <> org_id then
               return 'channel_not_owned';
        end if;

        if role_in = 'subscribe' and
           rhn_channel.get_org_access(channel_id_in, org_id) = 0 then
                return 'channel_not_available';
        end if;

        -- channel admins have all roles
        if rhn_user.check_role_implied(user_id_in, 'channel_admin') = 1 then
            return NULL;
        end if;

        -- the subscribe permission is inferred
        -- UNLESS the not_globally_subscribable flag is set
        if role_in = 'subscribe'
        then
            if rhn_channel.org_channel_setting(channel_id_in,
                       org_id,
                       'not_globally_subscribable') = 0 then
                return NULL;
            end if;
        end if;

        -- all other roles (manage right now) are explicitly granted
        if rhn_channel.direct_user_role_check(channel_id_in,
                                              user_id_in, role_in) = 1 then
            return NULL;
        end if;
        return 'direct_permission';
    end$$ language plpgsql;

    -- same as above, but with 1/0 output; useful in views, etc
    create or replace function user_role_check(channel_id_in in numeric, user_id_in in numeric, role_in in varchar)
    returns numeric
    as $$
    begin
        if rhn_channel.user_role_check_debug(channel_id_in,
                                             user_id_in, role_in) is NULL then
            return 1;
        else
            return 0;
        end if;
    end$$ language plpgsql;

    --
    -- For multiorg phase II, this function simply checks to see if the user's
    -- has a trust relationship that includes this channel by id.
    --
    create or replace function shared_user_role_check(channel_id in numeric, user_id in numeric, role in varchar)
    returns numeric
    as $$
    declare
      n numeric;
      oid numeric;
    begin
      oid := rhn_user.get_org_id(user_id);
      select 1 into n
      from rhnSharedChannelView s
      where s.id = channel_id and s.org_trust_id = oid;

      if not found then
        return 0;
      end if;

      return 1;
    end$$ language plpgsql;

    -- same as above, but returns 1 if user_id_in is null
    -- This is useful in queries where user_id is not specified
    create or replace function loose_user_role_check(channel_id_in in numeric, user_id_in in numeric, role_in in varchar)
    returns numeric
    as $$
    begin
        if user_id_in is null then
            return 1;
        end if;
        return rhn_channel.user_role_check(channel_id_in, user_id_in, role_in);
    end$$ language plpgsql;

    -- directly checks the table, no inferred permissions
    create or replace function direct_user_role_check(channel_id_in in numeric, user_id_in in numeric, role_in in varchar)
    returns numeric
    as $$
    declare
        throwaway numeric;
    begin
        -- the idea: if we get past this query, the user has the role, else no
        select 1 into throwaway
          from rhnChannelPermissionRole CPR,
               rhnChannelPermission CP
         where CP.user_id = user_id_in
           and CP.channel_id = channel_id_in
           and CPR.label = role_in
           and CP.role_id = CPR.id;

      if not found then
        return 0;
      end if;

      return 1;
    end$$ language plpgsql;

    -- check if an org has a certain setting
    create or replace function org_channel_setting(channel_id_in in numeric, org_id_in in numeric, setting_in in varchar)
    returns numeric
    as $$
    declare
        throwaway numeric;
    begin
        -- the idea: if we get past this query, the org has the setting
        select 1 into throwaway
          from rhnOrgChannelSettingsType OCST,
               rhnOrgChannelSettings OCS
         where OCS.org_id = org_id_in
           and OCS.channel_id = channel_id_in
           and OCST.label = setting_in
           and OCS.setting_id = OCST.id;

      if not found then
        return 0;
      end if;

      return 1;
    end$$ language plpgsql;

    CREATE OR REPLACE FUNCTION channel_priority(channel_id_in IN numeric)
    RETURNS numeric
    AS $$
    declare
         channel_name varchar(256);
         priority numeric;
         end_of_life_val timestamptz;
         org_id_val numeric;
    BEGIN

        select name, end_of_life, org_id
        into channel_name, end_of_life_val, org_id_val
        from rhnChannel
        where id = channel_id_in;

        if end_of_life_val is not null then
          return -400;
        end if;

        if channel_name like 'Red Hat Enterprise Linux%' or channel_name like 'RHEL%' then
          priority := 1000;
          if channel_name not like '%Beta%' then
            priority := priority + 1000;
          end if;

          priority := priority +
            case
              when channel_name like '%v. 5%' then 600
              when channel_name like '%v. 4%' then 500
              when channel_name like '%v. 3%' then 400
              when channel_name like '%v. 2%' then 300
              when channel_name like '%v. 1%' then 200
              else 0
            end;

          priority := priority +
            case
              when channel_name like 'Red Hat Enterprise Linux (v. 5%' then 60
              when (channel_name like '%AS%' and channel_name not like '%Extras%') then 50
              when (channel_name like '%ES%' and channel_name not like '%Extras%') then 40
              when (channel_name like '%WS%' and channel_name not like '%Extras%') then 30
              when (channel_name like '%Desktop%' and channel_name not like '%Extras%') then 20
              when channel_name like '%Extras%' then 10
              else 0
            end;

          priority := priority +
            case
              when channel_name like '%)' then 5
              else 0
            end;

          priority := priority +
            case
              when channel_name like '%32-bit x86%' then 4
              when channel_name like '%64-bit Intel Itanium%' then 3
              when channel_name like '%64-bit AMD64/Intel EM64T%' then 2
              else 0
            end;
        elsif channel_name like 'Red Hat Desktop%' then
            priority := 900;

            if channel_name not like '%Beta%' then
               priority := priority + 50;
            end if;

          priority := priority +
            case
              when channel_name like '%v. 4%' then 40
              when channel_name like '%v. 3%' then 30
              when channel_name like '%v. 2%' then 20
              when channel_name like '%v. 1%' then 10
              else 0
            end;

          priority := priority +
            case
              when channel_name like '%32-bit x86%' then 4
              when channel_name like '%64-bit Intel Itanium%' then 3
              when channel_name like '%64-bit AMD64/Intel EM64T%' then 2
              else 0
            end;

        elsif org_id_val is not null then
          priority := 600;
        else
          priority := 500;
        end if;

      return -priority;

    end$$ language plpgsql;

    -- this could certainly be optimized to do updates if needs be
    create or replace function refresh_newest_package(channel_id_in in numeric,
                                      caller_in in varchar default '(unknown)',
                                      package_name_id_in in numeric default null)
    returns void
    as $$
    -- procedure refreshes rows for name_id = package_name_id_in or
    -- all rows if package_name_id_in is null
    begin
        delete from rhnChannelNewestPackage
              where channel_id = channel_id_in
                and (package_name_id_in is null
                     or name_id = package_name_id_in);
        insert into rhnChannelNewestPackage
                (channel_id, name_id, evr_id, package_id, package_arch_id)
                (select channel_id,
                        name_id, evr_id,
                        package_id, package_arch_id
                   from rhnChannelNewestPackageView
                  where channel_id = channel_id_in
                    and (package_name_id_in is null
                         or name_id = package_name_id_in)
                );
        insert into rhnChannelNewestPackageAudit (channel_id, caller)
             values (channel_id_in, caller_in);
        update rhnChannel
           set last_modified = greatest(current_timestamp,
                                        last_modified + interval '1 second')
         where id = channel_id_in;
    end$$ language plpgsql;

   create or replace function update_channel ( channel_id_in in numeric, invalidate_ss in numeric default 0,
                              date_to_use in timestamptz default current_timestamp ) returns void
   as $$
   declare
   channel_last_modified timestamptz;
   last_modified_value timestamptz;

   snapshots cursor for
   select  snapshot_id id
   from    rhnSnapshotChannel
   where   channel_id = channel_id_in;

   begin

      select last_modified
      into channel_last_modified
      from rhnChannel
      where id = channel_id_in;

      last_modified_value := date_to_use;

      if last_modified_value <= channel_last_modified then
          last_modified_value := last_modified_value + interval '1 second';
      end if;

      update rhnChannel set last_modified = last_modified_value
      where id = channel_id_in;

      if invalidate_ss = 1 then
        for snapshot in snapshots loop
            update rhnSnapshot
            set invalid = lookup_snapshot_invalid_reason('channel_modified')
            where id = snapshot.id;
        end loop;
      end if;

   end$$ language plpgsql;

   create or replace function update_channels_by_package ( package_id_in in numeric, date_to_use in timestamptz default current_timestamp ) returns void
   as $$
   declare
   channels cursor for
   select channel_id
   from rhnChannelPackage
   where package_id = package_id_in
   order by channel_id;

   begin
      for channel in channels loop
         -- we want to invalidate the snapshot assocated with the channel when we
         -- do this b/c we know we've added or removed or packages
         perform rhn_channel.update_channel ( channel.channel_id, 1, date_to_use );
      end loop;
   end$$ language plpgsql;


   create or replace function update_channels_by_errata ( errata_id_in numeric, date_to_use in timestamptz default current_timestamp ) returns void
   as $$
   declare
   channels cursor for
   select channel_id
   from rhnChannelErrata
   where errata_id = errata_id_in
   order by channel_id;

   begin
      for channel in channels loop
         -- we won't invalidate snapshots, b/c just changing the errata associated with
         -- a channel shouldn't invalidate snapshots
         perform rhn_channel.update_channel ( channel.channel_id, 0, date_to_use );
      end loop;
   end$$ language plpgsql;

   create or replace function update_needed_cache(channel_id_in in numeric) returns void
   as $$
   declare
   server record;
   begin
      -- we intentionaly do a loop here instead of one huge select
      -- b/c we want to break update into smaller transaction to unblock other sessions
      -- querying rhnServerNeededCache
      for server in (
                select sc.server_id as id
                  from rhnServerChannel sc
                 where sc.channel_id = channel_id_in
                 order by id asc
      ) loop
         perform queue_server(server.id, 0); -- NOT IMMEDIATE
      end loop;
   end$$ language plpgsql;

    create or replace function set_comps(channel_id_in in numeric, path_in in varchar, timestamp_in in varchar) returns void
    as $$
    declare
    row record;
    begin
        for row in (
            select relative_filename, last_modified
            from rhnChannelComps
            where channel_id = channel_id_in
            ) loop
            if row.relative_filename = path_in
                and row.last_modified = to_timestamp(timestamp_in, 'YYYYMMDDHH24MISS') then
                return;
            end if;
        end loop;
        delete from rhnChannelComps
        where channel_id = channel_id_in;
        insert into rhnChannelComps (id, channel_id, relative_filename, last_modified, created, modified)
        values (sequence_nextval('rhn_channelcomps_id_seq'), channel_id_in, path_in, to_timestamp(timestamp_in, 'YYYYMMDDHH24MISS'), current_timestamp, current_timestamp);
    end$$ language plpgsql;

-- restore the original setting
update pg_settings set setting = overlay( setting placing '' from 1 for (length('rhn_channel')+1) ) where name = 'search_path';
   07070100000832000081B400000000000000000000000167AE111400009E72000000000000000000000000000000000000006500000000susemanager-schema/upgrade/spacewalk-schema-2.4-to-spacewalk-schema-2.5/113-rhn_entitlements.pkb.sql  --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

-- create schema rhn_entitlements;

-- setup search_path so that these functions are created in appropriate schema.
update pg_settings set setting = 'rhn_entitlements,' || setting where name = 'search_path';

   create or replace function find_compatible_sg (
      server_id_in in numeric,
      type_label_in in varchar
   )
   returns numeric
as $$
    declare
      servergroups cursor for
         select sg.id
           from rhnServerGroupType             sgt,
                rhnServerGroup                 sg,
                rhnServer                     s,
                rhnServerServerGroupArchCompat ssgac
          where s.id = server_id_in
            and s.org_id = sg.org_id
            and sgt.label = type_label_in
            and sg.group_type = sgt.id
            and ssgac.server_group_type = sgt.id
            and ssgac.server_arch_id = s.server_arch_id
            and not exists (
                     select 1
                      from rhnServerGroupMembers sgm
                     where sgm.server_group_id = sg.id
                       and sgm.server_id = s.id);


   begin
      for servergroup in servergroups loop
         return servergroup.id;
      end loop;

      --no servergroup found
      return NULL;
   end$$
language plpgsql;

    -- *******************************************************************
    -- PROCEDURE: remove_org_entitlements
    --
    -- Removes both system entitlements and channel subscriptions
    -- that are currently assigned to an org and re-assigns to the
    -- master org (org_id = 1).
    --
    -- When we call this we expect everything to already be unentitled
    -- which shoul be handled by delete_org.
    --
    -- Called by: delete_org
    -- *******************************************************************
    create or replace function remove_org_entitlements (
        org_id_in numeric
    ) returns void
as $$
    declare
        system_ents cursor for
        select sg.id, sg.max_members, sg.group_type
        from rhnServerGroup sg
        where group_type is not null
          and org_id = org_id_in;

    begin

        for system_ent in system_ents loop
            update rhnServerGroup
            set max_members = max_members + system_ent.max_members
            where org_id = 1
              and group_type = system_ent.group_type;
        end loop;

        update rhnServerGroup
        set max_members = 0
        where org_id = org_id_in;

    end$$
language plpgsql;

    create or replace function entitlement_grants_service (
        entitlement_in in varchar,
        service_level_in in varchar
    ) returns numeric
as $$
    begin
        if service_level_in = 'provisioning' then
            if entitlement_in = 'provisioning_entitled' then
                return 1;
            else
                return 0;
            end if;
        elsif service_level_in = 'management' then
            if entitlement_in = 'enterprise_entitled' then
                return 1;
            else
                return 0;
            end if;
        elsif service_level_in = 'monitoring' then
            if entitlement_in = 'monitoring_entitled' then
                return 1;
            end if;
        elsif service_level_in = 'updates' then
            return 1;
        else
            return 0;
        end if;
    end$$
language plpgsql;

    create or replace function lookup_entitlement_group (
        org_id_in in numeric,
        type_label_in in varchar default 'sw_mgr_entitled'
    ) returns numeric
as $$
    declare
        server_groups cursor for
            select  sg.id               server_group_id
            from    rhnServerGroup      sg,
                    rhnServerGroupType  sgt
            where   sgt.label = type_label_in
                and sgt.id = sg.group_type
                and sg.org_id = org_id_in;
    begin
        for sg in server_groups loop
            return sg.server_group_id;
        end loop;
        return rhn_entitlements.create_entitlement_group(
                org_id_in,
                type_label_in
            );
    end$$
language plpgsql;

    create or replace function create_entitlement_group (
        org_id_in in numeric,
        type_label_in in varchar default 'sw_mgr_entitled'
    ) returns numeric
as $$
    declare
        sg_id_val numeric;
    begin
        select  nextval('rhn_server_group_id_seq')
        into    sg_id_val;

        insert into rhnServerGroup (
                id, name, description, max_members, current_members,
                group_type, org_id
            ) (
                select  sg_id_val, sgt.label, sgt.label,
                        0, 0, sgt.id, org_id_in
                from    rhnServerGroupType sgt
                where   sgt.label = type_label_in
            );

        return sg_id_val;
    end$$
language plpgsql;

   create or replace function can_entitle_server (
      server_id_in   in numeric,
      type_label_in  in varchar
   )
   returns numeric
as $$
    declare
      addon_servergroups cursor (base_label_in varchar,
                                 addon_label_in varchar) for
         select
            addon_id
         from
            rhnSGTypeBaseAddonCompat
         where base_id = lookup_sg_type (base_label_in)
           and addon_id = lookup_sg_type (addon_label_in);

      previous_ent        varchar[];
      is_base_in          char   := 'N';
      is_base_current     char   := 'N';
      i                   numeric := 0;
      sgid                numeric := 0;

   begin

      previous_ent := rhn_entitlements.get_server_entitlement(server_id_in);

      select distinct is_base
      into is_base_in
      from rhnServerGroupType
      where label = type_label_in;

      if array_upper(previous_ent, 1) is null or array_upper(previous_ent, 1) = 0 then
         if is_base_in = 'Y' then
            sgid := rhn_entitlements.find_compatible_sg (server_id_in, type_label_in);
            if sgid is not null then
              -- rhn_server.insert_into_servergroup (server_id_in, sgid);
              return 1;
            else
              -- rhn_exception.raise_exception ('invalid_base_entitlement');
              return 0;
            end if;
         else
            -- rhn_exception.raise_exception ('invalid_base_entitlement');
            return 0;
         end if;

      -- there are previous ents, first make sure we're not trying to entitle a base ent
      elsif is_base_in = 'Y' then
         -- rhn_exception.raise_exception ('invalid_addon_entitlement');
         return 0;

      -- it must be an addon, so proceed with the entitlement
      else

         -- find the servers base ent
         is_base_current := 'N';
         i := 0;
         while is_base_current = 'N' and i < array_upper(previous_ent, 1)
         loop
            i := i + 1;
            select is_base
            into is_base_current
            from rhnServerGroupType
            where label = previous_ent[i];
         end loop;

         -- never found a base ent, that would be strange
         if is_base_current  = 'N' then
            -- rhn_exception.raise_exception ('invalid_base_entitlement');
            return 0;
         end if;

         -- this for loop verifies the validity of the addon path
         for addon_servergroup in addon_servergroups  (previous_ent[i], type_label_in) loop
            -- find an appropriate sgid for the addon and entitle the server
            sgid := rhn_entitlements.find_compatible_sg (server_id_in, type_label_in);
            if sgid is not null then
               -- rhn_server.insert_into_servergroup (server_id_in, sgid);
               return 1;
            else
               -- rhn_exception.raise_exception ('invalid_addon_entitlement');
               return 0;
            end if;
         end loop;

      end if;

      return 0;

   end$$
language plpgsql;

   create or replace function can_switch_base (
      server_id_in   in    integer,
      type_label_in  in    varchar
   )
   returns numeric
as $$
   declare
      type_label_in_is_base   char(1);
      sgid                    numeric;

   begin

       select is_base into type_label_in_is_base
       from rhnServerGroupType
       where label = type_label_in;

       if not found then
          perform rhn_exception.raise_exception ( 'invalid_entitlement' );
       end if;

      if type_label_in_is_base = 'N' then
         perform rhn_exception.raise_exception ( 'invalid_entitlement' );
      else
         sgid := rhn_entitlements.find_compatible_sg ( server_id_in,
                                                       type_label_in );
         if sgid is not null then
           return 1;
         else
           return 0;
         end if;
      end if;

   end$$
language plpgsql;

    create or replace function entitle_server (
        server_id_in in numeric,
        type_label_in in varchar default 'sw_mgr_entitled'
    ) returns void
as $$
    declare
      sgid  numeric := 0;
      is_virt numeric := 0;

    begin

      select 1 into is_virt
        from rhnServerEntitlementView
        where server_id = server_id_in
          and label in ('virtualization_host', 'virtualization_host_platform');

      if not found then
          is_virt := 0;
      end if;

      if is_virt = 0 and (type_label_in = 'virtualization_host' or
                          type_label_in = 'virtualization_host_platform') then

        is_virt := 1;
      end if;

      if rhn_entitlements.can_entitle_server(server_id_in,
                                             type_label_in) = 1 then
         sgid := rhn_entitlements.find_compatible_sg (server_id_in,
                                                      type_label_in);
         if sgid is not null then
            insert into rhnServerHistory ( id, server_id, summary, details )
            values ( nextval('rhn_event_id_seq'), server_id_in,
                     'added system entitlement ',
                      case type_label_in
                       when 'enterprise_entitled' then 'Management'
                       when 'sw_mgr_entitled' then 'Update'
                       when 'provisioning_entitled' then 'Provisioning'
                       when 'monitoring_entitled' then 'Monitoring'
                       when 'virtualization_host' then 'Virtualization'
                       when 'virtualization_host_platform' then
                            'Virtualization Platform' end  );

            perform rhn_server.insert_into_servergroup (server_id_in, sgid);

            if is_virt = 1 then
              perform rhn_entitlements.repoll_virt_guest_entitlements(server_id_in);
            end if;

         else
            perform rhn_exception.raise_exception ('no_available_server_group');
         end if;
      else
         perform rhn_exception.raise_exception ('invalid_entitlement');
      end if;
   end$$
language plpgsql;

    create or replace function remove_server_entitlement (
        server_id_in in numeric,
        type_label_in in varchar default 'sw_mgr_entitled',
        repoll_virt_guests in numeric default 1
    ) returns void
as $$
    declare
      group_id numeric;
      type_is_base char;
      is_virt numeric := 0;
    begin
      -- would be nice if there were a virt attribute of entitlement types, not have to specify 2 different ones...
        select 1 into is_virt
          from rhnServerEntitlementView
          where server_id = server_id_in
            and label in ('virtualization_host', 'virtualization_host_platform');
        if not found then
            is_virt := 0;
        end if;

        select  sg.id, sgt.is_base
        into group_id, type_is_base
        from    rhnServerGroupType sgt,
            rhnServerGroup sg,
                rhnServerGroupMembers sgm,
                rhnServer s
        where   s.id = server_id_in
            and s.id = sgm.server_id
            and sgm.server_group_id = sg.id
            and sg.org_id = s.org_id
            and sgt.label = type_label_in
            and sgt.id = sg.group_type;

        if not found then
          perform rhn_exception.raise_exception('invalid_server_group_member');
        end if;

      if ( type_is_base = 'Y' ) then
         -- unentitle_server should handle everything, don't really need to do anything else special here
         perform rhn_entitlements.unentitle_server ( server_id_in );
      else

         insert into rhnServerHistory ( id, server_id, summary, details )
         values ( nextval('rhn_event_id_seq'), server_id_in,
                  'removed system entitlement ',
                   case type_label_in
                    when 'enterprise_entitled' then 'Management'
                    when 'sw_mgr_entitled' then 'Update'
                    when 'provisioning_entitled' then 'Provisioning'
                    when 'monitoring_entitled' then 'Monitoring'
                    when 'virtualization_host' then 'Virtualization'
                    when 'virtualization_host_platform' then
                         'Virtualization Platforrm' end  );

         perform rhn_server.delete_from_servergroup(server_id_in, group_id);

         if is_virt = 1 and repoll_virt_guests = 1 then
           perform rhn_entitlements.repoll_virt_guest_entitlements(server_id_in);
         end if;
      end if;

    end$$
language plpgsql;

    create or replace function unentitle_server (
        server_id_in in numeric
    ) returns void
as $$
    declare
      servergroups cursor for
         select distinct sgt.label, sg.id server_group_id
         from  rhnServerGroupType sgt,
               rhnServerGroup sg,
               rhnServer s,
               rhnServerGroupMembers sgm
         where s.id = server_id_in
            and s.org_id = sg.org_id
            and sg.group_type = sgt.id
            and sgm.server_group_id = sg.id
            and sgm.server_id = s.id;

     is_virt numeric := 0;

   begin

      select 1 into is_virt
        from rhnServerEntitlementView
        where server_id = server_id_in
         and label in ('virtualization_host', 'virtualization_host_platform');

      if not found then
          is_virt := 0;
      end if;

      for servergroup in servergroups loop

         insert into rhnServerHistory ( id, server_id, summary, details )
         values ( nextval('rhn_event_id_seq'), server_id_in,
                  'removed system entitlement ',
                   case servergroup.label
                    when 'enterprise_entitled' then 'Management'
                    when 'sw_mgr_entitled' then 'Update'
                    when 'provisioning_entitled' then 'Provisioning'
                    when 'monitoring_entitled' then 'Monitoring'
                    when 'virtualization_host' then 'Virtualization'
                    when 'virtualization_host_platform' then
                         'Virtualization Platform' end  );

         perform rhn_server.delete_from_servergroup(server_id_in,
                                            servergroup.server_group_id );
      end loop;

      if is_virt = 1 then
        perform rhn_entitlements.repoll_virt_guest_entitlements(server_id_in);
      end if;

   end$$
language plpgsql;


    -- *******************************************************************
    -- PROCEDURE: repoll_virt_guest_entitlements
    --
    --   Whenever we add/remove a virtualization_host* entitlement from
    --   a host, we can call this procedure to update what type of slots
    --   the guests are consuming.
    --
    --   If you're removing the entitlement, it's
    --   possible the guests will become unentitled if you don't have enough
    --   physical slots to cover them.
    --
    --   If you're adding the entitlement, you end up freeing up physical
    --   slots for other systems.
    --
    -- *******************************************************************
    create or replace function repoll_virt_guest_entitlements(
        server_id_in in numeric
    ) returns void
as $$
    declare
        -- All of server group types associated with the guests of
        -- server_id_in
        group_types cursor for
            select distinct sg.group_type, sgt.label, sg.org_id
            from
                rhnServerGroupType sgt,
                rhnServerGroup sg,
                rhnServerGroupMembers sgm,
                rhnVirtualInstance vi
            where
                vi.host_system_id = server_id_in
                and vi.virtual_system_id = sgm.server_id
                and sgm.server_group_id = sg.id
                and sg.group_type = sgt.id;

        -- Virtual servers from a certain family belonging to a specific
        -- host that are consuming physical system slots over the limit.
        virt_servers_sgt cursor(group_type_in numeric, quantity_in numeric) for
                select vi.virtual_system_id
                from
                    rhnServerGroup sg,
                    rhnServerGroupMembers sgm,
                    rhnVirtualInstance vi
                where
                    vi.host_system_id = server_id_in
                    and vi.virtual_system_id = sgm.server_id
                    and sgm.server_group_id = sg.id
                    and sg.group_type = group_type_in
                order by sgm.modified desc
                limit quantity_in;

        org_id_val numeric;
        max_members_val numeric;
        max_flex_val numeric;
        current_members_calc numeric;
        sg_id numeric;
        is_virt numeric := 0;
        free_slots numeric := 0;
    begin
          select 1 into is_virt
                from rhnServerEntitlementView
           where server_id = server_id_in
                 and label in ('virtualization_host', 'virtualization_host_platform');

      if not found then
          is_virt := 0;
      end if;

        select org_id
        into org_id_val
        from rhnServer
        where id = server_id_in;

        for a_group_type in group_types loop
          -- get the current *physical* members of the system entitlement type for the org...
          --
          -- unlike channel families, it appears the standard rhnServerGroup.max_members represents
          -- *physical* slots, vs physical+virt ... boy that's confusing...

          select max_members, id
            into max_members_val, sg_id
            from rhnServerGroup
            where group_type = a_group_type.group_type
            and org_id = a_group_type.org_id;


      select count(sep.server_id) into current_members_calc
            from rhnServerEntitlementPhysical sep
           where sep.server_group_id = sg_id
             and sep.server_group_type_id = a_group_type.group_type;

          if current_members_calc > max_members_val then
            -- A virtualization_host* ent must have been removed, and we're over the limit, so unsubscribe guests
            for virt_server in virt_servers_sgt(a_group_type.group_type,
                                                current_members_calc - max_members_val) loop
              perform rhn_entitlements.remove_server_entitlement(virt_server.virtual_system_id, a_group_type.label);

              -- decrement current_members_calc, we'll use it to reset current_members for the group at the end...
              current_members_calc := current_members_calc - 1;
            end loop;

          end if;

          update rhnServerGroup set current_members = current_members_calc
           where org_id = a_group_type.org_id
             and group_type = a_group_type.group_type;

          -- I think that's all the house-keeping we have to do...
        end loop;

    end$$
language plpgsql;

    create or replace function get_server_entitlement (
        server_id_in in numeric
    ) returns varchar[]
as $$
    declare
        server_groups cursor for
            select  sgt.label
            from    rhnServerGroupType      sgt,
                    rhnServerGroup          sg,
                    rhnServerGroupMembers   sgm
            where   1=1
                and sgm.server_id = server_id_in
                and sg.id = sgm.server_group_id
                and sgt.id = sg.group_type
                and sgt.label in (
                    'sw_mgr_entitled','enterprise_entitled',
                    'provisioning_entitled', 'nonlinux_entitled',
                    'monitoring_entitled', 'virtualization_host',
                                        'virtualization_host_platform'
                    );

         ent_array varchar[];

    begin

      ent_array := '{}';

      for sg in server_groups loop
         ent_array := ent_array || sg.label;
      end loop;

      return ent_array;

    end$$
language plpgsql;

    -- this desperately needs to be table driven.
    create or replace function modify_org_service (
        org_id_in in numeric,
        service_label_in in varchar,
        enable_in in char
    ) returns void
as $$
    declare
        roles_to_process varchar[];
        roles cursor(role_label_in varchar) for
            select  label, id
            from    rhnUserGroupType
            where   label = role_label_in;
        org_roles cursor(role_label_in varchar) for
            select  1
            from    rhnUserGroup ug,
                    rhnUserGroupType ugt
            where   ugt.label = role_label_in
                and ug.org_id = org_id_in
                and ugt.id = ug.group_type;

        ents_to_process varchar[];
        ents cursor(ent_label_in varchar) for
            select  label, id
            from    rhnOrgEntitlementType
            where   label = ent_label_in;
        org_ents cursor(ent_label_in varchar) for
            select  1
            from    rhnOrgEntitlements oe,
                    rhnOrgEntitlementType oet
            where   oet.label = ent_label_in
                and oe.org_id = org_id_in
                and oet.id = oe.entitlement_id;
        create_row char(1);
    begin
        ents_to_process := '{}';
        roles_to_process := '{}';
        -- a bit kludgy, but only for 3.4 really.  Certainly no
        -- worse than the old code...
        if service_label_in = 'enterprise' or
           service_label_in = 'management' then
            ents_to_process := array_append(ents_to_process, 'sw_mgr_enterprise');

            roles_to_process := array_append(roles_to_process, 'org_admin');

            roles_to_process := array_append(roles_to_process, 'system_group_admin');

            roles_to_process := array_append(roles_to_process, 'activation_key_admin');
        elsif service_label_in = 'provisioning' then
            ents_to_process := array_append(ents_to_process, 'rhn_provisioning');

            roles_to_process := array_append(roles_to_process, 'system_group_admin');

            roles_to_process := array_append(roles_to_process, 'activation_key_admin');

            roles_to_process := array_append(roles_to_process, 'config_admin');
            -- another nasty special case...
            if enable_in = 'Y' then
                ents_to_process := array_append(ents_to_process, 'sw_mgr_enterprise');
            end if;
        elsif service_label_in = 'monitoring' then
            ents_to_process := array_append(ents_to_process, 'rhn_monitor');

            roles_to_process := array_append(roles_to_process, 'monitoring_admin');
        elsif service_label_in = 'virtualization' then
            ents_to_process := array_append(ents_to_process, 'rhn_virtualization');

            roles_to_process := array_append(roles_to_process, 'config_admin');
        elsif service_label_in = 'virtualization_platform' then
            ents_to_process := array_append(ents_to_process, 'rhn_virtualization_platform');
            roles_to_process := array_append(roles_to_process, 'config_admin');
    elsif service_label_in = 'nonlinux' then
            ents_to_process := array_append(ents_to_process, 'rhn_nonlinux');
            roles_to_process := array_append(roles_to_process, 'config_admin');
        end if;

        if enable_in = 'Y' then
            for i in 1..array_upper(ents_to_process, 1) loop
                for ent in ents(ents_to_process[i]) loop
                    create_row := 'Y';
                    for oe in org_ents(ent.label) loop
                        create_row := 'N';
                    end loop;
                    if create_row = 'Y' then
                        insert into rhnOrgEntitlements(org_id, entitlement_id)
                            values (org_id_in, ent.id);
                    end if;
                end loop;
            end loop;
            for i in 1..array_upper(roles_to_process, 1) loop
                for role in roles(roles_to_process[i]) loop
                    create_row := 'Y';
                    for o_r in org_roles(role.label) loop
                        create_row := 'N';
                    end loop;
                    if create_row = 'Y' then
                        insert into rhnUserGroup(
                                id, name, description, current_members,
                                group_type, org_id
                            ) (
                                select  nextval('rhn_user_group_id_seq'),
                                        ugt.name || 's',
                                        ugt.name || 's for Org ' ||
                                            o.name || ' ('|| o.id ||')',
                                        0, ugt.id, o.id
                                from    rhnUserGroupType ugt,
                                        web_customer o
                                where   o.id = org_id_in
                                    and ugt.id = role.id
                            );
                    end if;
                end loop;
            end loop;
        else
            for i in 1..coalesce(array_upper(ents_to_process, 1), 0) loop
                for ent in ents(ents_to_process[i]) loop
                    delete from rhnOrgEntitlements
                     where org_id = org_id_in
                       and entitlement_id = ent.id;
                end loop;
            end loop;
        end if;
    end$$
language plpgsql;

    create or replace function set_customer_enterprise (
        customer_id_in in numeric
    ) returns void
as $$
    begin
        perform rhn_entitlements.modify_org_service(customer_id_in, 'enterprise', 'Y');
    end$$
language plpgsql;

    create or replace function set_customer_provisioning (
        customer_id_in in numeric
    ) returns void
as $$
    begin
        perform rhn_entitlements.modify_org_service(customer_id_in, 'provisioning', 'Y');
    end$$
language plpgsql;

    create or replace function set_customer_monitoring (
        customer_id_in in numeric
    ) returns void
as $$
    begin
        perform rhn_entitlements.modify_org_service(customer_id_in, 'monitoring', 'Y');
    end$$
language plpgsql;

    create or replace function set_customer_nonlinux (
        customer_id_in in numeric
    ) returns void
as $$
    begin
        perform rhn_entitlements.modify_org_service(customer_id_in, 'nonlinux', 'Y');
    end$$
language plpgsql;

    create or replace function unset_customer_enterprise (
        customer_id_in in numeric
    ) returns void
as $$
    begin
        perform rhn_entitlements.modify_org_service(customer_id_in, 'enterprise', 'N');
    end$$
language plpgsql;

    create or replace function unset_customer_provisioning (
        customer_id_in in numeric
    ) returns void
as $$
    begin
        perform rhn_entitlements.modify_org_service(customer_id_in, 'provisioning', 'N');
    end$$
language plpgsql;

    create or replace function unset_customer_monitoring (
        customer_id_in in numeric
    ) returns void
as $$
    begin
        perform rhn_entitlements.modify_org_service(customer_id_in, 'monitoring', 'N');
    end$$
language plpgsql;

    create or replace function unset_customer_nonlinux (
        customer_id_in in numeric
    ) returns void
as $$
    begin
        perform rhn_entitlements.modify_org_service(customer_id_in, 'nonlinux', 'N');
    end$$
language plpgsql;

    -- *******************************************************************
    -- PROCEDURE: prune_group
    -- Unsubscribes servers consuming physical slots that over the org's
    --   limit.
    -- Called by: set_server_group_count, repoll_virt_guest_entitlements
    -- *******************************************************************
    create or replace function prune_group (
        group_id_in in numeric,
        quantity_in in numeric
    ) returns void
as $$
    declare
        sgrecord record;
      type_is_base char;
    begin
            update      rhnServerGroup
                set     max_members = quantity_in
                where   id = group_id_in;

            for sgrecord in (
		   select  server_id, server_group_id, sgt.id as group_type_id, sgt.label
		    from    rhnServerGroupType              sgt,
				    rhnServerGroup                  sg,
				    rhnServerGroupMembers   sgm
		    where   1=1
			    and sgm.server_group_id = group_id_in
			    and sgm.server_id in (
				    select  sep.server_id
				    from
					rhnServerEntitlementPhysical sep
				    where
					sep.server_group_id = group_id_in
				    order by sep.modified asc
				    offset quantity_in
				)
			    and sgm.server_group_id = sg.id
			    and sg.group_type = sgt.id
	    ) loop
                perform rhn_entitlements.remove_server_entitlement(sgrecord.server_id, sgrecord.label);

            select is_base
            into type_is_base
            from rhnServerGroupType sgt
            where sgt.id = sgrecord.group_type_id;

            -- if we're removing a base ent, then be sure to
            -- remove the server's channel subscriptions.
            if ( type_is_base = 'Y' ) then
                   perform rhn_channel.clear_subscriptions(sgrecord.server_id, 0);
            end if;

            end loop;
    end$$
language plpgsql;

    -- *******************************************************************
    -- PROCEDURE: assign_system_entitlement
    --
    -- Moves system entitlements from from_org_id_in to to_org_id_in.
    -- Can raise not_enough_entitlements_in_base_org if from_org_id_in
    -- does not have enough entitlements to cover the move.
    -- Takes care of unentitling systems if necessary by calling
    -- set_server_group_count
    -- *******************************************************************
    create or replace function assign_system_entitlement(
        group_label_in in varchar,
        from_org_id_in in numeric,
        to_org_id_in in numeric,
        quantity_in in numeric
    ) returns void
as $$
    declare
        prev_ent_count numeric;
    to_org_prev_ent_count numeric;
        new_ent_count numeric;
    new_quantity numeric;
        group_type numeric;
    begin

            select max_members
            into prev_ent_count
            from rhnServerGroupType sgt,
                 rhnServerGroup sg
            where sg.org_id = from_org_id_in
              and sg.group_type = sgt.id
              and sgt.label = group_label_in;

            if not found then
                perform rhn_exception.raise_exception(
                              'not_enough_entitlements_in_base_org');
            end if;

            select max_members
            into to_org_prev_ent_count
            from rhnServerGroupType sgt,
                 rhnServerGroup sg
            where sg.org_id = to_org_id_in
              and sg.group_type = sgt.id
              and sgt.label = group_label_in;

            if not found then
                to_org_prev_ent_count := 0;
            end if;

            select id
            into group_type
            from rhnServerGroupType
            where label = group_label_in;

            if not found then
                perform rhn_exception.raise_exception(
                              'invalid_server_group');
            end if;

        new_ent_count := prev_ent_count - quantity_in;

        if prev_ent_count > new_ent_count then
            new_quantity := to_org_prev_ent_count + quantity_in;
        end if;

        if new_ent_count < 0 then
            perform rhn_exception.raise_exception(
                          'not_enough_entitlements_in_base_org');
        end if;


        perform rhn_entitlements.set_server_group_count(from_org_id_in,
                                         group_type,
                                         new_ent_count);

        perform rhn_entitlements.set_server_group_count(to_org_id_in,
                                         group_type,
                                         new_quantity);

        -- Create or delete the entries in rhnOrgEntitlementType
        if group_label_in = 'enterprise_entitled' then
            if new_quantity > 0 then
                perform rhn_entitlements.set_customer_enterprise(to_org_id_in);
            else
                perform rhn_entitlements.unset_customer_enterprise(to_org_id_in);
            end if;
        end if;

        if group_label_in = 'provisioning_entitled' then
            if new_quantity > 0 then
                perform rhn_entitlements.set_customer_provisioning(to_org_id_in);
            else
                perform rhn_entitlements.unset_customer_provisioning(to_org_id_in);
            end if;
        end if;

        if group_label_in = 'monitoring_entitled' then
            if new_quantity > 0 then
                perform rhn_entitlements.set_customer_monitoring(to_org_id_in);
            else
                perform rhn_entitlements.unset_customer_monitoring(to_org_id_in);
            end if;
        end if;

    end$$
language plpgsql;

    -- *******************************************************************
    -- PROCEDURE: activate_system_entitlement
    --
    -- Sets the values in rhnServerGroup for a given rhnServerGroupType.
    --
    -- Calls: set_server_group_count to update, prune, or create the group.
    -- Called by: the code that activates a satellite cert.
    --
    -- Raises not_enough_entitlements_in_base_org if all entitlements
    -- in the org are used so the free entitlements would not cover
    -- the difference when descreasing the number of entitlements.
    -- *******************************************************************
    create or replace function activate_system_entitlement(
        org_id_in in numeric,
        group_label_in in varchar,
        quantity_in in numeric
    ) returns void
as $$
    declare
        prev_ent_count numeric;
        prev_ent_count_sum numeric;
        group_type numeric;
    begin

        -- Fetch the current entitlement count for the org
        -- into prev_ent_count

            select current_members
            into prev_ent_count
            from rhnServerGroupType sgt,
                 rhnServerGroup sg
            where sg.group_type = sgt.id
              and sgt.label = group_label_in
              and sg.org_id = org_id_in;

            if not found then
                prev_ent_count := 0;
            end if;

            select id
            into group_type
            from rhnServerGroupType
            where label = group_label_in;

            if not found then
                perform rhn_exception.raise_exception(
                              'invalid_server_group');
            end if;

        -- If we're setting the total entitlemnt count to a lower value,
        -- and that value is less than the allocated count in this org,
        -- we need to raise an exception.
        if quantity_in < prev_ent_count then
            perform rhn_exception.raise_exception(
                          'not_enough_entitlements_in_base_org');
        else
            -- don't update family counts after every server
            -- will do bulk update afterwards
            perform rhn_entitlements.set_server_group_count(org_id_in,
                                             group_type,
                                             quantity_in);
        end if;

    end$$
language plpgsql;


    create or replace function set_server_group_count (
        customer_id_in in numeric,  -- customer_id
        group_type_in in numeric,   -- rhn[User|Server]GroupType.id
        quantity_in in numeric      -- quantity
    ) returns void
as $$
    declare
        group_id numeric;
        quantity numeric;
        wasfound boolean;
    begin
        quantity := quantity_in;
        if quantity is not null and quantity < 0 then
            quantity := 0;
        end if;

        select  rsg.id
        into    group_id
        from    rhnServerGroup rsg
        where   1=1
            and rsg.org_id = customer_id_in
            and rsg.group_type = group_type_in;

        -- preserve the not found status across the rhn_entitlements.prune_group invocation
        wasfound := true;
        if not found then
            wasfound := false;
        end if;

        perform rhn_entitlements.prune_group(
            group_id,
            quantity
        );

        if not wasfound then
            insert into rhnServerGroup (
                    id, name, description, max_members, current_members,
                    group_type, org_id, created, modified
                ) (
                    select  nextval('rhn_server_group_id_seq'), name, name,
                            quantity, 0, id, customer_id_in,
                            current_timestamp, current_timestamp
                    from    rhnServerGroupType
                    where   id = group_type_in
            );
        end if;

    end$$
language plpgsql;

    -- this expects quantity_in to be the number of available slots, not the
    -- max_members of the server group.  If you give it too many, it'll fail
    -- and raise servergroup_max_members.
    -- We should NEVER run this unless we're SURE that we won't
    -- be violating the max.
    create or replace function entitle_last_modified_servers (
        customer_id_in in numeric,  -- customer_id
        type_label_in in varchar,   -- 'enterprise_entitled'
        quantity_in in numeric      -- 3
    ) returns void
as $$
    declare
        -- find the servers that aren't currently in slots
        servers cursor(cid_in numeric, quant_in numeric) for
                                    select  rs.id as server_id
                                    from    rhnServer rs
                                    where   1=1
                                        and rs.org_id = cid_in
                                        and not exists (
                                            select  1
                                            from    rhnServerGroup sg,
                                                    rhnServerGroupMembers rsgm
                                            where   rsgm.server_id = rs.id
                                                and rsgm.server_group_id = sg.id
                                                and sg.group_type is not null
                                        )
                                        and not exists (
                                            select 1
                                            from rhnVirtualInstance vi
                                            where vi.virtual_system_id =
                                                  rs.id
                                        )
                                    order by modified desc
                                    limit quant_in;
    begin
        for server in servers(customer_id_in, quantity_in) loop
            perform rhn_entitlements.entitle_server(server.server_id, type_label_in);
        end loop;
    end$$
language plpgsql;

-- restore the original setting
update pg_settings set setting = overlay( setting placing '' from 1 for (length('rhn_entitlements')+1) ) where name = 'search_path';
  07070100000833000081B400000000000000000000000167AE111400000E3B000000000000000000000000000000000000009000000000susemanager-schema/upgrade/spacewalk-schema-2.4-to-spacewalk-schema-2.5/115-modify-rhnOrgChannelFamilyPermissions-rhnAvailableChannels-view.sql   --
-- Copyright (c) 2008--2016 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
-- tricky view.  it explodes to a full cartesian product when
-- not queried via org_id, so DO NOT DO THAT :)

drop view rhnOrgErrata;
drop view rhnAvailableChannels;
drop view rhnOrgChannelTreeView;
drop view rhnOrgChannelFamilyPermissions;

create or replace view rhnOrgChannelFamilyPermissions as
        select  pcf.channel_family_id,
                u.org_id as org_id,
                pcf.created,
                pcf.modified
        from    rhnPublicChannelFamily pcf,
                web_contact u
        union
        select  channel_family_id,
                org_id,
                created,
                modified
        from    rhnPrivateChannelFamily;

CREATE OR REPLACE VIEW rhnOrgChannelTreeView
(
	org_id,
        id,
        depth,
	name,
        padded_name,
	channel_arch_id,
        last_modified,
        label,
	parent_or_self_label,
	parent_or_self_id,
	end_of_life
)
AS
select * from (
	select	cfp.org_id		as org_id,
		c.id			as id,
		1			as depth,
		c.name			as name,
		'  ' || c.name		as padded_name,
		c.channel_arch_id	as channel_arch_id,
		c.last_modified		as last_modified,
		c.label			as label,
		c.label			as parent_or_self_label,
		c.id			as parent_or_self_id,
		c.end_of_life		as end_of_life
	from	rhnChannel		c,
		rhnChannelFamilyMembers cfm,
		rhnOrgChannelFamilyPermissions cfp
	where	cfp.channel_family_id = cfm.channel_family_id
		and cfm.channel_id = c.id
		and c.parent_channel is null
	union
	select	cfp.org_id		as org_id,
		c.id			as id,
		2			as depth,
		c.name			as name,
		'' || c.name		as padded_name,
		c.channel_arch_id 	as channel_arch_id,
		c.last_modified		as last_modified,
		c.label			as label,
		pc.label		as parent_or_self_label,
		pc.id			as parent_or_self_id,
		c.end_of_life		as end_of_life
	from	rhnChannel		pc,
		rhnChannel		c,
		rhnChannelFamilyMembers	cfm,
		rhnOrgChannelFamilyPermissions cfp
	where	cfp.channel_family_id = cfm.channel_family_id
		and cfm.channel_id = c.id
		and c.parent_channel = pc.id
) s order by parent_or_self_label, parent_or_self_id;

create or replace view
rhnAvailableChannels
(
    	org_id,
	channel_id,
	channel_depth,
	channel_name,
	channel_arch_id,
	padded_name,
        last_modified,
        channel_label,
	parent_or_self_label,
	parent_or_self_id 
)
as
select
     ct.org_id,
     ct.id,
     CT.depth,
     CT.name,
     CT.channel_arch_id,
     CT.padded_name,
     CT.last_modified,
     CT.label,
     CT.parent_or_self_label,
     CT.parent_or_self_id
from
     rhnOrgChannelTreeView CT
UNION ALL
select
     ct.org_id,
     ct.id,
     CT.depth,
     CT.name,
     CT.channel_arch_id,
     CT.padded_name,
     CT.last_modified,
     CT.label,
     CT.parent_or_self_label,
     CT.parent_or_self_id
from
     rhnSharedChannelTreeView CT
;

create or replace view
rhnOrgErrata
(
        org_id,
        errata_id,
        channel_id
)
as
select
    ac.org_id,
    ce.errata_id,
    ac.channel_id
from
    rhnChannelErrata ce,
    rhnAvailableChannels ac
where
    ce.channel_id = ac.channel_id
;
 07070100000834000081B400000000000000000000000167AE111400000024000000000000000000000000000000000000007300000000susemanager-schema/upgrade/spacewalk-schema-2.4-to-spacewalk-schema-2.5/116-drop-rhnUserAvailableChannels-view.sql    drop view rhnUserAvailableChannels;
07070100000835000081B400000000000000000000000167AE11140000001F000000000000000000000000000000000000006E00000000susemanager-schema/upgrade/spacewalk-schema-2.4-to-spacewalk-schema-2.5/117-drop-rhnServerFveCapable-view.sql drop view rhnServerFveCapable;
 07070100000836000081B400000000000000000000000167AE111400000051000000000000000000000000000000000000007A00000000susemanager-schema/upgrade/spacewalk-schema-2.4-to-spacewalk-schema-2.5/118-channel_family_no_subscriptions-exception.sql -- 'channel_family_no_subscriptions'
delete from rhnException where id = -20235;
   07070100000837000081B400000000000000000000000167AE111400000024000000000000000000000000000000000000007300000000susemanager-schema/upgrade/spacewalk-schema-2.4-to-spacewalk-schema-2.5/119-drop-rhnChannelFamilyOverview-view.sql    drop view rhnChannelFamilyOverview;
07070100000838000081B400000000000000000000000167AE111400000025000000000000000000000000000000000000007400000000susemanager-schema/upgrade/spacewalk-schema-2.4-to-spacewalk-schema-2.5/120-drop-rhnChannelFamilyServerFve-view.sql   drop view rhnChannelFamilyServerFve;
   07070100000839000081B400000000000000000000000167AE111400000023000000000000000000000000000000000000007200000000susemanager-schema/upgrade/spacewalk-schema-2.4-to-spacewalk-schema-2.5/121-drop-rhnChannelFamilyServers-view.sql drop view rhnChannelFamilyServers;
 0707010000083A000081B400000000000000000000000167AE111400000029000000000000000000000000000000000000007800000000susemanager-schema/upgrade/spacewalk-schema-2.4-to-spacewalk-schema-2.5/123-drop-rhnChannelFamilyServerVirtual-view.sql   drop view rhnChannelFamilyServerVirtual;
   0707010000083B000081B400000000000000000000000167AE1114000010AD000000000000000000000000000000000000007A00000000susemanager-schema/upgrade/spacewalk-schema-2.4-to-spacewalk-schema-2.5/124-modify-rhnUserChannelFamilyPerms.sql-view.sql --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--

drop view rhnUserChannel;
drop view rhnUserChannelTreeView;
drop view rhnUserChannelFamilyPerms;

create or replace view rhnUserChannelFamilyPerms as
	select	pcf.channel_family_id,
		u.org_id as org_id,
		u.id as user_id,
		pcf.created,
		pcf.modified
	from	rhnPublicChannelFamily pcf,
		web_contact u
	union
	select	pcf.channel_family_id,
		u.org_id,
		u.id as user_id,
		pcf.created,
		pcf.modified
	from	rhnPrivateChannelFamily pcf,
		web_contact u
	where	u.org_id = pcf.org_id;

CREATE OR REPLACE VIEW rhnUserChannelTreeView
(
        user_id,
        org_id,
        id,
        depth,
        name,
        padded_name,
        channel_arch_id,
        last_modified,
        label,
        parent_or_self_label,
        parent_or_self_id,
        end_of_life
)
AS
select * from (
        select  cfp.user_id             as user_id,
                cfp.org_id              as org_id,
                c.id                    as id,
                1                       as depth,
                c.name                  as name,
                '  ' || c.name          as padded_name,
                c.channel_arch_id       as channel_arch_id,
                c.last_modified         as last_modified,
                c.label                 as label,
                c.label                 as parent_or_self_label,
                c.id                    as parent_or_self_id,
                c.end_of_life           as end_of_life
        from    rhnChannel              c,
                rhnChannelFamilyMembers cfm,
                rhnUserChannelFamilyPerms cfp
        where   cfp.channel_family_id = cfm.channel_family_id
                and cfm.channel_id = c.id
                and c.parent_channel is null
        union
        select  cfp.user_id             as user_id,
                cfp.org_id              as org_id,
                c.id                    as id,
                2                       as depth,
                c.name                  as name,
                '' || c.name            as padded_name,
                c.channel_arch_id       as channel_arch_id,
                c.last_modified         as last_modified,
                c.label                 as label,
                pc.label                as parent_or_self_label,
                pc.id                   as parent_or_self_id,
                c.end_of_life           as end_of_life
        from    rhnChannel              pc,
                rhnChannel              c,
                rhnChannelFamilyMembers cfm,
                rhnUserChannelFamilyPerms cfp
        where   cfp.channel_family_id = cfm.channel_family_id
                and cfm.channel_id = c.id
                and c.parent_channel = pc.id
) S order by parent_or_self_label, parent_or_self_id;

create or replace view rhnUserChannel
as
select
   cfp.user_id,
   cfp.org_id,
   cfm.channel_id,
   'manage' as role
from rhnChannelFamilyMembers cfm,
      rhnUserChannelFamilyPerms cfp
where
   cfp.channel_family_id = cfm.channel_family_id and
   rhn_channel.user_role_check(cfm.channel_id, cfp.user_id, 'manage') = 1
union all
select
   cfp.user_id,
   cfp.org_id,
   cfm.channel_id,
   'subscribe' as role
from rhnChannelFamilyMembers cfm,
      rhnUserChannelFamilyPerms cfp
where
   cfp.channel_family_id = cfm.channel_family_id and
   rhn_channel.user_role_check(cfm.channel_id, cfp.user_id, 'subscribe') = 1
union all
select
   w.id as user_id,
   w.org_id,
   s.id as channel_id,
   'subscribe' as role
from rhnSharedChannelView s,
      web_contact w
where
   w.org_id = s.org_trust_id and
   rhn_channel.user_role_check(s.id, w.id, 'subscribe') = 1;

   0707010000083C000081B400000000000000000000000167AE1114000003B0000000000000000000000000000000000000007800000000susemanager-schema/upgrade/spacewalk-schema-2.4-to-spacewalk-schema-2.5/125-modify-rhnChannelFamilyPermissions-view.sql   --
-- Copyright (c) 2008--2010 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--

drop view rhnChannelFamilyPermissions;

create or replace view rhnChannelFamilyPermissions as
	select	channel_family_id,
		to_number(null, null) as org_id,
		created,
		modified
	from	rhnPublicChannelFamily
	union
	select	channel_family_id,
		org_id,
		created,
		modified
	from	rhnPrivateChannelFamily;

0707010000083D000081B400000000000000000000000167AE111400000104000000000000000000000000000000000000007500000000susemanager-schema/upgrade/spacewalk-schema-2.4-to-spacewalk-schema-2.5/126-drop-columns-rhnPrivateChannelFamily.sql  alter table rhnPrivateChannelFamily drop column max_members;
alter table rhnPrivateChannelFamily drop column current_members;
alter table rhnPrivateChannelFamily drop column fve_max_members;
alter table rhnPrivateChannelFamily drop column fve_current_members;
0707010000083E000081B400000000000000000000000167AE11140000002A000000000000000000000000000000000000007900000000susemanager-schema/upgrade/spacewalk-schema-2.4-to-spacewalk-schema-2.5/127-drop-rhnChannelFamilyServerPhysical-view.sql  drop view rhnChannelFamilyServerPhysical;
  0707010000083F000081B400000000000000000000000167AE11140000007D000000000000000000000000000000000000007200000000susemanager-schema/upgrade/spacewalk-schema-2.4-to-spacewalk-schema-2.5/128-drop-is_fve-from-rhnServerChannel.sql ALTER TABLE rhnServerChannel DROP CONSTRAINT rhn_server_channel_is_fve_ck;
ALTER TABLE rhnServerChannel DROP COLUMN is_fve;

   07070100000840000081B400000000000000000000000167AE111400000048000000000000000000000000000000000000007600000000susemanager-schema/upgrade/spacewalk-schema-2.4-to-spacewalk-schema-2.5/129-drop-invalid_channel_family-exception.sql -- 'invalid_channel_family'
delete from rhnException where id = -20250;
07070100000841000081B400000000000000000000000167AE11140000004F000000000000000000000000000000000000007D00000000susemanager-schema/upgrade/spacewalk-schema-2.4-to-spacewalk-schema-2.5/130-drop-server_cannot_convert_to_flex-exception.sql  -- 'server_cannot_convert_to_flex'
delete from rhnException where id = -20295;
 07070100000842000081B400000000000000000000000167AE11140000005A000000000000000000000000000000000000008800000000susemanager-schema/upgrade/spacewalk-schema-2.4-to-spacewalk-schema-2.5/131-drop-not_enough_flex_entitlements_in_base_org-exception.sql   -- 'not_enough_flex_entitlements_in_base_org'
delete from rhnException where id = -20294;
  07070100000843000081B400000000000000000000000167AE11140000004E000000000000000000000000000000000000007C00000000susemanager-schema/upgrade/spacewalk-schema-2.4-to-spacewalk-schema-2.5/132-drop-not_enough_flex_entitlements-exception.sql   -- 'not_enough_flex_entitlements'
delete from rhnException where id = -20296;
  07070100000844000081B400000000000000000000000167AE11140000287E000000000000000000000000000000000000005E00000000susemanager-schema/upgrade/spacewalk-schema-2.4-to-spacewalk-schema-2.5/133-delete-server.sql --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
-- This deletes a server.  All codepaths which delete servers should hit this
-- or delete_server_bulk()

create or replace
function delete_server (
        server_id_in in numeric
) returns void 
as
$$
declare
         servergroups cursor for
                select  server_id, server_group_id
                from    rhnServerGroupMembers sgm
                where   sgm.server_id = server_id_in;

         configchannels cursor for
                select  cc.id
                from    rhnConfigChannel cc,
                        rhnConfigChannelType cct,
                        rhnServerConfigChannel scc
                where   1=1
                        and scc.server_id = server_id_in
                        and scc.config_channel_id = cc.id
                        -- these config channel types are reserved
                        -- for use by a single server, so we don't
                        -- need to check for other servers subscribed
                        and cct.label in
                                ('local_override','server_import')
                        and cct.id = cc.confchan_type_id;

    is_virt boolean;
begin
        -- filelists
        delete from rhnFileList where id in (
	select	spfl.file_list_id
	  from	rhnServerPreserveFileList spfl
	 where	spfl.server_id = server_id_in
			and not exists (
				select	1
				from	rhnServerPreserveFileList
				where	file_list_id = spfl.file_list_id
					and server_id != server_id_in
				union all
				select	1
				from	rhnKickstartPreserveFileList
				where	file_list_id = spfl.file_list_id
			)
        );

	for configchannel in configchannels loop
		perform rhn_config.delete_channel(configchannel.id);
	end loop;

      is_virt := exists (
       select 1
        from rhnServerEntitlementView
       where server_id = server_id_in
         and label in ('virtualization_host', 'virtualization_host_platform')
      );

	for sgm in servergroups loop
		perform rhn_server.delete_from_servergroup(
			sgm.server_id, sgm.server_group_id);
	end loop;

    if is_virt then
        perform rhn_entitlements.repoll_virt_guest_entitlements(server_id_in);
    end if;

        -- we're handling this instead of letting an "on delete
        -- set null" do it so that we don't run the risk
        -- of setting off the triggers and killing us with a
        -- mutating table

        -- this is merge of two single updates:
        --  update ... set old_server_id = null where old_server_id = server_id_in;
        --  update ... set new_server_id = null where new_server_id = server_id_in;
        -- so we scan rhnKickstartSession table only once
        update rhnKickstartSession
                set old_server_id = case when old_server_id = server_id_in then null else old_server_id end,
                    new_server_id = case when new_server_id = server_id_in then null else new_server_id end
                where old_server_id = server_id_in
                   or new_server_id = server_id_in;

        perform rhn_channel.clear_subscriptions(server_id_in, 1);

        -- A little complicated here, but the goal is to
        -- delete records from rhnVirtualInstace only if we don't
        -- care about them anymore.  We don't care about records
        -- in rhnVirtualInstance if we are deleting the host
        -- system and the virtual system is already null, or
        -- vice-versa.  We *do* care about them if either the
        -- host or virtual system is still registered because we
        -- still want them to show up in the UI.
    -- If there's a newer row in rhnVirtualInstance with the same
    -- uuid, this guest must have been re-registered, so we can clean
    -- this data up.

        delete from rhnVirtualInstance vi
              where (host_system_id = server_id_in and virtual_system_id is null)
                 or (virtual_system_id = server_id_in and host_system_id is null)
                 or (vi.virtual_system_id = server_id_in and vi.modified < (select max(vi2.modified)
                    from rhnVirtualInstance vi2 where vi2.uuid = vi.uuid));

        -- this is merge of two single updates:
        --  update ... set host_system_id = null where host_system_id = server_id_in;
        --  update ... set virtual_system_id = null where virtual_system_id = server_id_in;
        -- so we scan rhnVirtualInstance table only once
        update rhnVirtualInstance
           set host_system_id = case when host_system_id = server_id_in then null else host_system_id end,
               virtual_system_id = case when virtual_system_id = server_id_in then null else virtual_system_id end
         where host_system_id = server_id_in
            or virtual_system_id = server_id_in;

        -- this is merge of two single updates:
        --  update ... set old_host_system_id = null when old_host_system_id = server_id_in;
        --  update ... set new_host_system_id = null when new_host_system_id = server_id_in;
        -- so we scan rhnVirtualInstanceEventLog table only once
        update rhnVirtualInstanceEventLog
           set old_host_system_id = case when old_host_system_id = server_id_in then null else old_host_system_id end,
               new_host_system_id = case when new_host_system_id = server_id_in then null else new_host_system_id end
         where old_host_system_id = server_id_in
            or new_host_system_id = server_id_in;

        -- We're deleting everything with a foreign key to rhnServer
        -- here, now.  I'm hoping this will help aleviate our deadlock
        -- problem.

        delete from rhnActionConfigChannel where server_id = server_id_in;
        delete from rhnActionConfigRevision where server_id = server_id_in;
        delete from rhnActionPackageRemovalFailure where server_id = server_id_in;
        delete from rhnClientCapability where server_id = server_id_in;
        delete from rhnCpu where server_id = server_id_in;
        -- there's still a cascade here, because the constraint keeps the
        -- table locked for too long to rebuild it.  Ugh...
        delete from rhnDevice where server_id = server_id_in;
        delete from rhnProxyInfo where server_id = server_id_in;
        delete from rhnRam where server_id = server_id_in;
        delete from rhnRegToken where server_id = server_id_in;
        delete from rhnSatelliteInfo where server_id = server_id_in;
        -- this cascades to rhnActionConfigChannel and rhnActionConfigFileName
        delete from rhnServerAction where server_id = server_id_in;
        delete from rhnServerActionPackageResult where server_id = server_id_in;
        delete from rhnServerActionScriptResult where server_id = server_id_in;
        delete from rhnServerActionVerifyResult where server_id = server_id_in;
        delete from rhnServerActionVerifyMissing where server_id = server_id_in;
        -- counts are handled above.  this should be a delete_ function.
        delete from rhnServerChannel where server_id = server_id_in;
        delete from rhnServerConfigChannel where server_id = server_id_in;
        delete from rhnServerCustomDataValue where server_id = server_id_in;
        delete from rhnServerDMI where server_id = server_id_in;
        delete from rhnServerEvent where server_id = server_id_in;
        delete from rhnServerHistory where server_id = server_id_in;
        delete from rhnServerInfo where server_id = server_id_in;
        delete from rhnServerInstallInfo where server_id = server_id_in;
        delete from rhnServerLocation where server_id = server_id_in;
        delete from rhnServerLock where server_id = server_id_in;
        delete from rhnServerNeededCache where server_id = server_id_in;
        delete from rhnServerNetwork where server_id = server_id_in;
        delete from rhnServerNotes where server_id = server_id_in;
        -- I'm not removing the foreign key from rhnServerPackage; that'll
        -- take forever.  Do the delete anyway.
        delete from rhnServerPackage where server_id = server_id_in;
        delete from rhnServerTokenRegs where server_id = server_id_in;
        delete from rhnSnapshotTag where server_id = server_id_in;
        -- this cascades to:
        --   rhnSnapshotChannel, rhnSnapshotConfigChannel, rhnSnapshotPackage,
        --   rhnSnapshotConfigRevision, rhnSnapshotServerGroup,
        --   rhnSnapshotTag.
        -- We may want to consider delete_snapshot() at some point, but
        --   I don't think we need to yet.
        delete from rhnSnapshot where server_id = server_id_in;
        delete from rhnUserServerPrefs where server_id = server_id_in;
        -- hrm, this one's interesting... we _probably_ should delete
        -- everything for the parent server_id when we delete the proxy,
        -- but we don't currently.
        delete from rhnServerPath where server_id_in in (server_id, proxy_server_id);
        delete from rhnUserServerPerms where server_id = server_id_in;

        delete from rhnServerNetInterface where server_id = server_id_in;

        delete from rhnServerUuid where server_id = server_id_in;

        delete from rhnPushClient where server_id = server_id_in;

        -- now get rhnServer itself.
        delete
        from    rhnServer
                where id = server_id_in;

        delete
        from    rhnSet
        where   1=1
                and user_id in (
                        select  wc.id
                        from    rhnServer rs,
                                web_contact wc
                        where   rs.id = server_id_in
                                and rs.org_id = wc.org_id
                )
                and label = 'system_list'
                and element = server_id_in;
end;
$$
language plpgsql;

  07070100000845000081B400000000000000000000000167AE11140000007F000000000000000000000000000000000000008200000000susemanager-schema/upgrade/spacewalk-schema-2.4-to-spacewalk-schema-2.5/134-rhnOrgEntitlements-delete_monitoring_entitlements.sql DELETE FROM rhnOrgEntitlements
WHERE entitlement_id IN
    (SELECT id FROM rhnOrgEntitlementType WHERE label = 'rhn_monitor');
 07070100000846000081B400000000000000000000000167AE11140000003F000000000000000000000000000000000000008900000000susemanager-schema/upgrade/spacewalk-schema-2.4-to-spacewalk-schema-2.5/135-rhnOrgEntitlementType-delete_monitoring_entitlement_type.sql  DELETE FROM rhnOrgEntitlementType
WHERE label = 'rhn_monitor';
 07070100000847000081B400000000000000000000000167AE11140000001D000000000000000000000000000000000000006600000000susemanager-schema/upgrade/spacewalk-schema-2.4-to-spacewalk-schema-2.5/138-drop_rhn_config_macro.sql DROP TABLE rhn_config_macro;
   07070100000848000081B400000000000000000000000167AE111400000161000000000000000000000000000000000000006800000000susemanager-schema/upgrade/spacewalk-schema-2.4-to-spacewalk-schema-2.5/139-delete_monitoring_admin.sql   DELETE FROM rhnUserGroupMembers WHERE user_group_id IN (SELECT g.id from rhnUserGroup g JOIN rhnUserGroupType gt ON g.group_type = gt.id WHERE gt.label = 'monitoring_admin');

DELETE FROM rhnUserGroup WHERE group_type IN (SELECT id FROM rhnUserGroupType WHERE label = 'monitoring_admin');

DELETE FROM rhnUserGroupType WHERE label = 'monitoring_admin';
   07070100000849000081B400000000000000000000000167AE111400000022000000000000000000000000000000000000006C00000000susemanager-schema/upgrade/spacewalk-schema-2.4-to-spacewalk-schema-2.5/141-drop_rhn_contact_monitoring.sql   DROP VIEW rhn_contact_monitoring;
  0707010000084A000081B400000000000000000000000167AE111400000023000000000000000000000000000000000000006D00000000susemanager-schema/upgrade/spacewalk-schema-2.4-to-spacewalk-schema-2.5/143-drop_rhn_customer_monitoring.sql  DROP VIEW rhn_customer_monitoring;
 0707010000084B000081B400000000000000000000000167AE11140000001F000000000000000000000000000000000000006900000000susemanager-schema/upgrade/spacewalk-schema-2.4-to-spacewalk-schema-2.5/145-drop_rhn_host_monitoring.sql  DROP VIEW rhn_host_monitoring;
 0707010000084C000081B400000000000000000000000167AE1114000098E0000000000000000000000000000000000000006C00000000susemanager-schema/upgrade/spacewalk-schema-2.4-to-spacewalk-schema-2.5/146-rhn_entitlements_pkb_update.sql   --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

-- create schema rhn_entitlements;

-- setup search_path so that these functions are created in appropriate schema.
update pg_settings set setting = 'rhn_entitlements,' || setting where name = 'search_path';

   create or replace function find_compatible_sg (
      server_id_in in numeric,
      type_label_in in varchar
   )
   returns numeric
as $$
    declare
      servergroups cursor for
         select sg.id
           from rhnServerGroupType             sgt,
                rhnServerGroup                 sg,
                rhnServer                     s,
                rhnServerServerGroupArchCompat ssgac
          where s.id = server_id_in
            and s.org_id = sg.org_id
            and sgt.label = type_label_in
            and sg.group_type = sgt.id
            and ssgac.server_group_type = sgt.id
            and ssgac.server_arch_id = s.server_arch_id
            and not exists (
                     select 1
                      from rhnServerGroupMembers sgm
                     where sgm.server_group_id = sg.id
                       and sgm.server_id = s.id);


   begin
      for servergroup in servergroups loop
         return servergroup.id;
      end loop;

      --no servergroup found
      return NULL;
   end$$
language plpgsql;

    -- *******************************************************************
    -- PROCEDURE: remove_org_entitlements
    --
    -- Removes both system entitlements and channel subscriptions
    -- that are currently assigned to an org and re-assigns to the
    -- master org (org_id = 1).
    --
    -- When we call this we expect everything to already be unentitled
    -- which shoul be handled by delete_org.
    --
    -- Called by: delete_org
    -- *******************************************************************
    create or replace function remove_org_entitlements (
        org_id_in numeric
    ) returns void
as $$
    declare
        system_ents cursor for
        select sg.id, sg.max_members, sg.group_type
        from rhnServerGroup sg
        where group_type is not null
          and org_id = org_id_in;

    begin

        for system_ent in system_ents loop
            update rhnServerGroup
            set max_members = max_members + system_ent.max_members
            where org_id = 1
              and group_type = system_ent.group_type;
        end loop;

        update rhnServerGroup
        set max_members = 0
        where org_id = org_id_in;

    end$$
language plpgsql;

    create or replace function entitlement_grants_service (
        entitlement_in in varchar,
        service_level_in in varchar
    ) returns numeric
as $$
    begin
        if service_level_in = 'provisioning' then
            if entitlement_in = 'provisioning_entitled' then
                return 1;
            else
                return 0;
            end if;
        elsif service_level_in = 'management' then
            if entitlement_in = 'enterprise_entitled' then
                return 1;
            else
                return 0;
            end if;
        elsif service_level_in = 'updates' then
            return 1;
        else
            return 0;
        end if;
    end$$
language plpgsql;

    create or replace function lookup_entitlement_group (
        org_id_in in numeric,
        type_label_in in varchar default 'sw_mgr_entitled'
    ) returns numeric
as $$
    declare
        server_groups cursor for
            select  sg.id               server_group_id
            from    rhnServerGroup      sg,
                    rhnServerGroupType  sgt
            where   sgt.label = type_label_in
                and sgt.id = sg.group_type
                and sg.org_id = org_id_in;
    begin
        for sg in server_groups loop
            return sg.server_group_id;
        end loop;
        return rhn_entitlements.create_entitlement_group(
                org_id_in,
                type_label_in
            );
    end$$
language plpgsql;

    create or replace function create_entitlement_group (
        org_id_in in numeric,
        type_label_in in varchar default 'sw_mgr_entitled'
    ) returns numeric
as $$
    declare
        sg_id_val numeric;
    begin
        select  nextval('rhn_server_group_id_seq')
        into    sg_id_val;

        insert into rhnServerGroup (
                id, name, description, max_members, current_members,
                group_type, org_id
            ) (
                select  sg_id_val, sgt.label, sgt.label,
                        0, 0, sgt.id, org_id_in
                from    rhnServerGroupType sgt
                where   sgt.label = type_label_in
            );

        return sg_id_val;
    end$$
language plpgsql;

   create or replace function can_entitle_server (
      server_id_in   in numeric,
      type_label_in  in varchar
   )
   returns numeric
as $$
    declare
      addon_servergroups cursor (base_label_in varchar,
                                 addon_label_in varchar) for
         select
            addon_id
         from
            rhnSGTypeBaseAddonCompat
         where base_id = lookup_sg_type (base_label_in)
           and addon_id = lookup_sg_type (addon_label_in);

      previous_ent        varchar[];
      is_base_in          char   := 'N';
      is_base_current     char   := 'N';
      i                   numeric := 0;
      sgid                numeric := 0;

   begin

      previous_ent := rhn_entitlements.get_server_entitlement(server_id_in);

      select distinct is_base
      into is_base_in
      from rhnServerGroupType
      where label = type_label_in;

      if array_upper(previous_ent, 1) is null or array_upper(previous_ent, 1) = 0 then
         if is_base_in = 'Y' then
            sgid := rhn_entitlements.find_compatible_sg (server_id_in, type_label_in);
            if sgid is not null then
              -- rhn_server.insert_into_servergroup (server_id_in, sgid);
              return 1;
            else
              -- rhn_exception.raise_exception ('invalid_base_entitlement');
              return 0;
            end if;
         else
            -- rhn_exception.raise_exception ('invalid_base_entitlement');
            return 0;
         end if;

      -- there are previous ents, first make sure we're not trying to entitle a base ent
      elsif is_base_in = 'Y' then
         -- rhn_exception.raise_exception ('invalid_addon_entitlement');
         return 0;

      -- it must be an addon, so proceed with the entitlement
      else

         -- find the servers base ent
         is_base_current := 'N';
         i := 0;
         while is_base_current = 'N' and i < array_upper(previous_ent, 1)
         loop
            i := i + 1;
            select is_base
            into is_base_current
            from rhnServerGroupType
            where label = previous_ent[i];
         end loop;

         -- never found a base ent, that would be strange
         if is_base_current  = 'N' then
            -- rhn_exception.raise_exception ('invalid_base_entitlement');
            return 0;
         end if;

         -- this for loop verifies the validity of the addon path
         for addon_servergroup in addon_servergroups  (previous_ent[i], type_label_in) loop
            -- find an appropriate sgid for the addon and entitle the server
            sgid := rhn_entitlements.find_compatible_sg (server_id_in, type_label_in);
            if sgid is not null then
               -- rhn_server.insert_into_servergroup (server_id_in, sgid);
               return 1;
            else
               -- rhn_exception.raise_exception ('invalid_addon_entitlement');
               return 0;
            end if;
         end loop;

      end if;

      return 0;

   end$$
language plpgsql;

   create or replace function can_switch_base (
      server_id_in   in    integer,
      type_label_in  in    varchar
   )
   returns numeric
as $$
   declare
      type_label_in_is_base   char(1);
      sgid                    numeric;

   begin

       select is_base into type_label_in_is_base
       from rhnServerGroupType
       where label = type_label_in;

       if not found then
          perform rhn_exception.raise_exception ( 'invalid_entitlement' );
       end if;

      if type_label_in_is_base = 'N' then
         perform rhn_exception.raise_exception ( 'invalid_entitlement' );
      else
         sgid := rhn_entitlements.find_compatible_sg ( server_id_in,
                                                       type_label_in );
         if sgid is not null then
           return 1;
         else
           return 0;
         end if;
      end if;

   end$$
language plpgsql;

    create or replace function entitle_server (
        server_id_in in numeric,
        type_label_in in varchar default 'sw_mgr_entitled'
    ) returns void
as $$
    declare
      sgid  numeric := 0;
      is_virt numeric := 0;

    begin

      select 1 into is_virt
        from rhnServerEntitlementView
        where server_id = server_id_in
          and label in ('virtualization_host', 'virtualization_host_platform');

      if not found then
          is_virt := 0;
      end if;

      if is_virt = 0 and (type_label_in = 'virtualization_host' or
                          type_label_in = 'virtualization_host_platform') then

        is_virt := 1;
      end if;

      if rhn_entitlements.can_entitle_server(server_id_in,
                                             type_label_in) = 1 then
         sgid := rhn_entitlements.find_compatible_sg (server_id_in,
                                                      type_label_in);
         if sgid is not null then
            insert into rhnServerHistory ( id, server_id, summary, details )
            values ( nextval('rhn_event_id_seq'), server_id_in,
                     'added system entitlement ',
                      case type_label_in
                       when 'enterprise_entitled' then 'Management'
                       when 'sw_mgr_entitled' then 'Update'
                       when 'provisioning_entitled' then 'Provisioning'
                       when 'virtualization_host' then 'Virtualization'
                       when 'virtualization_host_platform' then
                            'Virtualization Platform' end  );

            perform rhn_server.insert_into_servergroup (server_id_in, sgid);

            if is_virt = 1 then
              perform rhn_entitlements.repoll_virt_guest_entitlements(server_id_in);
            end if;

         else
            perform rhn_exception.raise_exception ('no_available_server_group');
         end if;
      else
         perform rhn_exception.raise_exception ('invalid_entitlement');
      end if;
   end$$
language plpgsql;

    create or replace function remove_server_entitlement (
        server_id_in in numeric,
        type_label_in in varchar default 'sw_mgr_entitled',
        repoll_virt_guests in numeric default 1
    ) returns void
as $$
    declare
      group_id numeric;
      type_is_base char;
      is_virt numeric := 0;
    begin
      -- would be nice if there were a virt attribute of entitlement types, not have to specify 2 different ones...
        select 1 into is_virt
          from rhnServerEntitlementView
          where server_id = server_id_in
            and label in ('virtualization_host', 'virtualization_host_platform');
        if not found then
            is_virt := 0;
        end if;

        select  sg.id, sgt.is_base
        into group_id, type_is_base
        from    rhnServerGroupType sgt,
            rhnServerGroup sg,
                rhnServerGroupMembers sgm,
                rhnServer s
        where   s.id = server_id_in
            and s.id = sgm.server_id
            and sgm.server_group_id = sg.id
            and sg.org_id = s.org_id
            and sgt.label = type_label_in
            and sgt.id = sg.group_type;

        if not found then
          perform rhn_exception.raise_exception('invalid_server_group_member');
        end if;

      if ( type_is_base = 'Y' ) then
         -- unentitle_server should handle everything, don't really need to do anything else special here
         perform rhn_entitlements.unentitle_server ( server_id_in );
      else

         insert into rhnServerHistory ( id, server_id, summary, details )
         values ( nextval('rhn_event_id_seq'), server_id_in,
                  'removed system entitlement ',
                   case type_label_in
                    when 'enterprise_entitled' then 'Management'
                    when 'sw_mgr_entitled' then 'Update'
                    when 'provisioning_entitled' then 'Provisioning'
                    when 'virtualization_host' then 'Virtualization'
                    when 'virtualization_host_platform' then
                         'Virtualization Platforrm' end  );

         perform rhn_server.delete_from_servergroup(server_id_in, group_id);

         if is_virt = 1 and repoll_virt_guests = 1 then
           perform rhn_entitlements.repoll_virt_guest_entitlements(server_id_in);
         end if;
      end if;

    end$$
language plpgsql;

    create or replace function unentitle_server (
        server_id_in in numeric
    ) returns void
as $$
    declare
      servergroups cursor for
         select distinct sgt.label, sg.id server_group_id
         from  rhnServerGroupType sgt,
               rhnServerGroup sg,
               rhnServer s,
               rhnServerGroupMembers sgm
         where s.id = server_id_in
            and s.org_id = sg.org_id
            and sg.group_type = sgt.id
            and sgm.server_group_id = sg.id
            and sgm.server_id = s.id;

     is_virt numeric := 0;

   begin

      select 1 into is_virt
        from rhnServerEntitlementView
        where server_id = server_id_in
         and label in ('virtualization_host', 'virtualization_host_platform');

      if not found then
          is_virt := 0;
      end if;

      for servergroup in servergroups loop

         insert into rhnServerHistory ( id, server_id, summary, details )
         values ( nextval('rhn_event_id_seq'), server_id_in,
                  'removed system entitlement ',
                   case servergroup.label
                    when 'enterprise_entitled' then 'Management'
                    when 'sw_mgr_entitled' then 'Update'
                    when 'provisioning_entitled' then 'Provisioning'
                    when 'virtualization_host' then 'Virtualization'
                    when 'virtualization_host_platform' then
                         'Virtualization Platform' end  );

         perform rhn_server.delete_from_servergroup(server_id_in,
                                            servergroup.server_group_id );
      end loop;

      if is_virt = 1 then
        perform rhn_entitlements.repoll_virt_guest_entitlements(server_id_in);
      end if;

   end$$
language plpgsql;


    -- *******************************************************************
    -- PROCEDURE: repoll_virt_guest_entitlements
    --
    --   Whenever we add/remove a virtualization_host* entitlement from
    --   a host, we can call this procedure to update what type of slots
    --   the guests are consuming.
    --
    --   If you're removing the entitlement, it's
    --   possible the guests will become unentitled if you don't have enough
    --   physical slots to cover them.
    --
    --   If you're adding the entitlement, you end up freeing up physical
    --   slots for other systems.
    --
    -- *******************************************************************
    create or replace function repoll_virt_guest_entitlements(
        server_id_in in numeric
    ) returns void
as $$
    declare
        -- All of server group types associated with the guests of
        -- server_id_in
        group_types cursor for
            select distinct sg.group_type, sgt.label, sg.org_id
            from
                rhnServerGroupType sgt,
                rhnServerGroup sg,
                rhnServerGroupMembers sgm,
                rhnVirtualInstance vi
            where
                vi.host_system_id = server_id_in
                and vi.virtual_system_id = sgm.server_id
                and sgm.server_group_id = sg.id
                and sg.group_type = sgt.id;

        -- Virtual servers from a certain family belonging to a specific
        -- host that are consuming physical system slots over the limit.
        virt_servers_sgt cursor(group_type_in numeric, quantity_in numeric) for
                select vi.virtual_system_id
                from
                    rhnServerGroup sg,
                    rhnServerGroupMembers sgm,
                    rhnVirtualInstance vi
                where
                    vi.host_system_id = server_id_in
                    and vi.virtual_system_id = sgm.server_id
                    and sgm.server_group_id = sg.id
                    and sg.group_type = group_type_in
                order by sgm.modified desc
                limit quantity_in;

        org_id_val numeric;
        max_members_val numeric;
        max_flex_val numeric;
        current_members_calc numeric;
        sg_id numeric;
        is_virt numeric := 0;
        free_slots numeric := 0;
    begin
          select 1 into is_virt
                from rhnServerEntitlementView
           where server_id = server_id_in
                 and label in ('virtualization_host', 'virtualization_host_platform');

      if not found then
          is_virt := 0;
      end if;

        select org_id
        into org_id_val
        from rhnServer
        where id = server_id_in;

        for a_group_type in group_types loop
          -- get the current *physical* members of the system entitlement type for the org...
          --
          -- unlike channel families, it appears the standard rhnServerGroup.max_members represents
          -- *physical* slots, vs physical+virt ... boy that's confusing...

          select max_members, id
            into max_members_val, sg_id
            from rhnServerGroup
            where group_type = a_group_type.group_type
            and org_id = a_group_type.org_id;


      select count(sep.server_id) into current_members_calc
            from rhnServerEntitlementPhysical sep
           where sep.server_group_id = sg_id
             and sep.server_group_type_id = a_group_type.group_type;

          if current_members_calc > max_members_val then
            -- A virtualization_host* ent must have been removed, and we're over the limit, so unsubscribe guests
            for virt_server in virt_servers_sgt(a_group_type.group_type,
                                                current_members_calc - max_members_val) loop
              perform rhn_entitlements.remove_server_entitlement(virt_server.virtual_system_id, a_group_type.label);

              -- decrement current_members_calc, we'll use it to reset current_members for the group at the end...
              current_members_calc := current_members_calc - 1;
            end loop;

          end if;

          update rhnServerGroup set current_members = current_members_calc
           where org_id = a_group_type.org_id
             and group_type = a_group_type.group_type;

          -- I think that's all the house-keeping we have to do...
        end loop;

    end$$
language plpgsql;

    create or replace function get_server_entitlement (
        server_id_in in numeric
    ) returns varchar[]
as $$
    declare
        server_groups cursor for
            select  sgt.label
            from    rhnServerGroupType      sgt,
                    rhnServerGroup          sg,
                    rhnServerGroupMembers   sgm
            where   1=1
                and sgm.server_id = server_id_in
                and sg.id = sgm.server_group_id
                and sgt.id = sg.group_type
                and sgt.label in (
                    'sw_mgr_entitled','enterprise_entitled',
                    'provisioning_entitled', 'nonlinux_entitled',
                    'virtualization_host', 'virtualization_host_platform'
                    );

         ent_array varchar[];

    begin

      ent_array := '{}';

      for sg in server_groups loop
         ent_array := ent_array || sg.label;
      end loop;

      return ent_array;

    end$$
language plpgsql;

    -- this desperately needs to be table driven.
    create or replace function modify_org_service (
        org_id_in in numeric,
        service_label_in in varchar,
        enable_in in char
    ) returns void
as $$
    declare
        roles_to_process varchar[];
        roles cursor(role_label_in varchar) for
            select  label, id
            from    rhnUserGroupType
            where   label = role_label_in;
        org_roles cursor(role_label_in varchar) for
            select  1
            from    rhnUserGroup ug,
                    rhnUserGroupType ugt
            where   ugt.label = role_label_in
                and ug.org_id = org_id_in
                and ugt.id = ug.group_type;

        ents_to_process varchar[];
        ents cursor(ent_label_in varchar) for
            select  label, id
            from    rhnOrgEntitlementType
            where   label = ent_label_in;
        org_ents cursor(ent_label_in varchar) for
            select  1
            from    rhnOrgEntitlements oe,
                    rhnOrgEntitlementType oet
            where   oet.label = ent_label_in
                and oe.org_id = org_id_in
                and oet.id = oe.entitlement_id;
        create_row char(1);
    begin
        ents_to_process := '{}';
        roles_to_process := '{}';
        -- a bit kludgy, but only for 3.4 really.  Certainly no
        -- worse than the old code...
        if service_label_in = 'enterprise' or
           service_label_in = 'management' then
            ents_to_process := array_append(ents_to_process, 'sw_mgr_enterprise');

            roles_to_process := array_append(roles_to_process, 'org_admin');

            roles_to_process := array_append(roles_to_process, 'system_group_admin');

            roles_to_process := array_append(roles_to_process, 'activation_key_admin');
        elsif service_label_in = 'provisioning' then
            ents_to_process := array_append(ents_to_process, 'rhn_provisioning');

            roles_to_process := array_append(roles_to_process, 'system_group_admin');

            roles_to_process := array_append(roles_to_process, 'activation_key_admin');

            roles_to_process := array_append(roles_to_process, 'config_admin');
            -- another nasty special case...
            if enable_in = 'Y' then
                ents_to_process := array_append(ents_to_process, 'sw_mgr_enterprise');
            end if;
        elsif service_label_in = 'virtualization' then
            ents_to_process := array_append(ents_to_process, 'rhn_virtualization');

            roles_to_process := array_append(roles_to_process, 'config_admin');
        elsif service_label_in = 'virtualization_platform' then
            ents_to_process := array_append(ents_to_process, 'rhn_virtualization_platform');
            roles_to_process := array_append(roles_to_process, 'config_admin');
    elsif service_label_in = 'nonlinux' then
            ents_to_process := array_append(ents_to_process, 'rhn_nonlinux');
            roles_to_process := array_append(roles_to_process, 'config_admin');
        end if;

        if enable_in = 'Y' then
            for i in 1..array_upper(ents_to_process, 1) loop
                for ent in ents(ents_to_process[i]) loop
                    create_row := 'Y';
                    for oe in org_ents(ent.label) loop
                        create_row := 'N';
                    end loop;
                    if create_row = 'Y' then
                        insert into rhnOrgEntitlements(org_id, entitlement_id)
                            values (org_id_in, ent.id);
                    end if;
                end loop;
            end loop;
            for i in 1..array_upper(roles_to_process, 1) loop
                for role in roles(roles_to_process[i]) loop
                    create_row := 'Y';
                    for o_r in org_roles(role.label) loop
                        create_row := 'N';
                    end loop;
                    if create_row = 'Y' then
                        insert into rhnUserGroup(
                                id, name, description, current_members,
                                group_type, org_id
                            ) (
                                select  nextval('rhn_user_group_id_seq'),
                                        ugt.name || 's',
                                        ugt.name || 's for Org ' ||
                                            o.name || ' ('|| o.id ||')',
                                        0, ugt.id, o.id
                                from    rhnUserGroupType ugt,
                                        web_customer o
                                where   o.id = org_id_in
                                    and ugt.id = role.id
                            );
                    end if;
                end loop;
            end loop;
        else
            for i in 1..coalesce(array_upper(ents_to_process, 1), 0) loop
                for ent in ents(ents_to_process[i]) loop
                    delete from rhnOrgEntitlements
                     where org_id = org_id_in
                       and entitlement_id = ent.id;
                end loop;
            end loop;
        end if;
    end$$
language plpgsql;

    create or replace function set_customer_enterprise (
        customer_id_in in numeric
    ) returns void
as $$
    begin
        perform rhn_entitlements.modify_org_service(customer_id_in, 'enterprise', 'Y');
    end$$
language plpgsql;

    create or replace function set_customer_provisioning (
        customer_id_in in numeric
    ) returns void
as $$
    begin
        perform rhn_entitlements.modify_org_service(customer_id_in, 'provisioning', 'Y');
    end$$
language plpgsql;

    create or replace function set_customer_nonlinux (
        customer_id_in in numeric
    ) returns void
as $$
    begin
        perform rhn_entitlements.modify_org_service(customer_id_in, 'nonlinux', 'Y');
    end$$
language plpgsql;

    create or replace function unset_customer_enterprise (
        customer_id_in in numeric
    ) returns void
as $$
    begin
        perform rhn_entitlements.modify_org_service(customer_id_in, 'enterprise', 'N');
    end$$
language plpgsql;

    create or replace function unset_customer_provisioning (
        customer_id_in in numeric
    ) returns void
as $$
    begin
        perform rhn_entitlements.modify_org_service(customer_id_in, 'provisioning', 'N');
    end$$
language plpgsql;

    create or replace function unset_customer_nonlinux (
        customer_id_in in numeric
    ) returns void
as $$
    begin
        perform rhn_entitlements.modify_org_service(customer_id_in, 'nonlinux', 'N');
    end$$
language plpgsql;

    -- *******************************************************************
    -- PROCEDURE: prune_group
    -- Unsubscribes servers consuming physical slots that over the org's
    --   limit.
    -- Called by: set_server_group_count, repoll_virt_guest_entitlements
    -- *******************************************************************
    create or replace function prune_group (
        group_id_in in numeric,
        quantity_in in numeric
    ) returns void
as $$
    declare
        sgrecord record;
      type_is_base char;
    begin
            update      rhnServerGroup
                set     max_members = quantity_in
                where   id = group_id_in;

            for sgrecord in (
		   select  server_id, server_group_id, sgt.id as group_type_id, sgt.label
		    from    rhnServerGroupType              sgt,
				    rhnServerGroup                  sg,
				    rhnServerGroupMembers   sgm
		    where   1=1
			    and sgm.server_group_id = group_id_in
			    and sgm.server_id in (
				    select  sep.server_id
				    from
					rhnServerEntitlementPhysical sep
				    where
					sep.server_group_id = group_id_in
				    order by sep.modified asc
				    offset quantity_in
				)
			    and sgm.server_group_id = sg.id
			    and sg.group_type = sgt.id
	    ) loop
                perform rhn_entitlements.remove_server_entitlement(sgrecord.server_id, sgrecord.label);

            select is_base
            into type_is_base
            from rhnServerGroupType sgt
            where sgt.id = sgrecord.group_type_id;

            -- if we're removing a base ent, then be sure to
            -- remove the server's channel subscriptions.
            if ( type_is_base = 'Y' ) then
                   perform rhn_channel.clear_subscriptions(sgrecord.server_id, 0);
            end if;

            end loop;
    end$$
language plpgsql;

    -- *******************************************************************
    -- PROCEDURE: assign_system_entitlement
    --
    -- Moves system entitlements from from_org_id_in to to_org_id_in.
    -- Can raise not_enough_entitlements_in_base_org if from_org_id_in
    -- does not have enough entitlements to cover the move.
    -- Takes care of unentitling systems if necessary by calling
    -- set_server_group_count
    -- *******************************************************************
    create or replace function assign_system_entitlement(
        group_label_in in varchar,
        from_org_id_in in numeric,
        to_org_id_in in numeric,
        quantity_in in numeric
    ) returns void
as $$
    declare
        prev_ent_count numeric;
    to_org_prev_ent_count numeric;
        new_ent_count numeric;
    new_quantity numeric;
        group_type numeric;
    begin

            select max_members
            into prev_ent_count
            from rhnServerGroupType sgt,
                 rhnServerGroup sg
            where sg.org_id = from_org_id_in
              and sg.group_type = sgt.id
              and sgt.label = group_label_in;

            if not found then
                perform rhn_exception.raise_exception(
                              'not_enough_entitlements_in_base_org');
            end if;

            select max_members
            into to_org_prev_ent_count
            from rhnServerGroupType sgt,
                 rhnServerGroup sg
            where sg.org_id = to_org_id_in
              and sg.group_type = sgt.id
              and sgt.label = group_label_in;

            if not found then
                to_org_prev_ent_count := 0;
            end if;

            select id
            into group_type
            from rhnServerGroupType
            where label = group_label_in;

            if not found then
                perform rhn_exception.raise_exception(
                              'invalid_server_group');
            end if;

        new_ent_count := prev_ent_count - quantity_in;

        if prev_ent_count > new_ent_count then
            new_quantity := to_org_prev_ent_count + quantity_in;
        end if;

        if new_ent_count < 0 then
            perform rhn_exception.raise_exception(
                          'not_enough_entitlements_in_base_org');
        end if;


        perform rhn_entitlements.set_server_group_count(from_org_id_in,
                                         group_type,
                                         new_ent_count);

        perform rhn_entitlements.set_server_group_count(to_org_id_in,
                                         group_type,
                                         new_quantity);

        -- Create or delete the entries in rhnOrgEntitlementType
        if group_label_in = 'enterprise_entitled' then
            if new_quantity > 0 then
                perform rhn_entitlements.set_customer_enterprise(to_org_id_in);
            else
                perform rhn_entitlements.unset_customer_enterprise(to_org_id_in);
            end if;
        end if;

        if group_label_in = 'provisioning_entitled' then
            if new_quantity > 0 then
                perform rhn_entitlements.set_customer_provisioning(to_org_id_in);
            else
                perform rhn_entitlements.unset_customer_provisioning(to_org_id_in);
            end if;
        end if;

    end$$
language plpgsql;

    -- *******************************************************************
    -- PROCEDURE: activate_system_entitlement
    --
    -- Sets the values in rhnServerGroup for a given rhnServerGroupType.
    --
    -- Calls: set_server_group_count to update, prune, or create the group.
    -- Called by: the code that activates a satellite cert.
    --
    -- Raises not_enough_entitlements_in_base_org if all entitlements
    -- in the org are used so the free entitlements would not cover
    -- the difference when descreasing the number of entitlements.
    -- *******************************************************************
    create or replace function activate_system_entitlement(
        org_id_in in numeric,
        group_label_in in varchar,
        quantity_in in numeric
    ) returns void
as $$
    declare
        prev_ent_count numeric;
        prev_ent_count_sum numeric;
        group_type numeric;
    begin

        -- Fetch the current entitlement count for the org
        -- into prev_ent_count

            select current_members
            into prev_ent_count
            from rhnServerGroupType sgt,
                 rhnServerGroup sg
            where sg.group_type = sgt.id
              and sgt.label = group_label_in
              and sg.org_id = org_id_in;

            if not found then
                prev_ent_count := 0;
            end if;

            select id
            into group_type
            from rhnServerGroupType
            where label = group_label_in;

            if not found then
                perform rhn_exception.raise_exception(
                              'invalid_server_group');
            end if;

        -- If we're setting the total entitlemnt count to a lower value,
        -- and that value is less than the allocated count in this org,
        -- we need to raise an exception.
        if quantity_in < prev_ent_count then
            perform rhn_exception.raise_exception(
                          'not_enough_entitlements_in_base_org');
        else
            -- don't update family counts after every server
            -- will do bulk update afterwards
            perform rhn_entitlements.set_server_group_count(org_id_in,
                                             group_type,
                                             quantity_in);
        end if;

    end$$
language plpgsql;


    create or replace function set_server_group_count (
        customer_id_in in numeric,  -- customer_id
        group_type_in in numeric,   -- rhn[User|Server]GroupType.id
        quantity_in in numeric      -- quantity
    ) returns void
as $$
    declare
        group_id numeric;
        quantity numeric;
        wasfound boolean;
    begin
        quantity := quantity_in;
        if quantity is not null and quantity < 0 then
            quantity := 0;
        end if;

        select  rsg.id
        into    group_id
        from    rhnServerGroup rsg
        where   1=1
            and rsg.org_id = customer_id_in
            and rsg.group_type = group_type_in;

        -- preserve the not found status across the rhn_entitlements.prune_group invocation
        wasfound := true;
        if not found then
            wasfound := false;
        end if;

        perform rhn_entitlements.prune_group(
            group_id,
            quantity
        );

        if not wasfound then
            insert into rhnServerGroup (
                    id, name, description, max_members, current_members,
                    group_type, org_id, created, modified
                ) (
                    select  nextval('rhn_server_group_id_seq'), name, name,
                            quantity, 0, id, customer_id_in,
                            current_timestamp, current_timestamp
                    from    rhnServerGroupType
                    where   id = group_type_in
            );
        end if;

    end$$
language plpgsql;

    -- this expects quantity_in to be the number of available slots, not the
    -- max_members of the server group.  If you give it too many, it'll fail
    -- and raise servergroup_max_members.
    -- We should NEVER run this unless we're SURE that we won't
    -- be violating the max.
    create or replace function entitle_last_modified_servers (
        customer_id_in in numeric,  -- customer_id
        type_label_in in varchar,   -- 'enterprise_entitled'
        quantity_in in numeric      -- 3
    ) returns void
as $$
    declare
        -- find the servers that aren't currently in slots
        servers cursor(cid_in numeric, quant_in numeric) for
                                    select  rs.id as server_id
                                    from    rhnServer rs
                                    where   1=1
                                        and rs.org_id = cid_in
                                        and not exists (
                                            select  1
                                            from    rhnServerGroup sg,
                                                    rhnServerGroupMembers rsgm
                                            where   rsgm.server_id = rs.id
                                                and rsgm.server_group_id = sg.id
                                                and sg.group_type is not null
                                        )
                                        and not exists (
                                            select 1
                                            from rhnVirtualInstance vi
                                            where vi.virtual_system_id =
                                                  rs.id
                                        )
                                    order by modified desc
                                    limit quant_in;
    begin
        for server in servers(customer_id_in, quantity_in) loop
            perform rhn_entitlements.entitle_server(server.server_id, type_label_in);
        end loop;
    end$$
language plpgsql;

-- restore the original setting
update pg_settings set setting = overlay( setting placing '' from 1 for (length('rhn_entitlements')+1) ) where name = 'search_path';
0707010000084D000081B400000000000000000000000167AE111400006115000000000000000000000000000000000000006600000000susemanager-schema/upgrade/spacewalk-schema-2.4-to-spacewalk-schema-2.5/147-rhn_server_pkb_update.sql --
-- Copyright (c) 2008--2014 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--

-- create schema rhn_server;

--update pg_setting
update pg_settings set setting = 'rhn_server,' || setting where name = 'search_path';

    create or replace function system_service_level(
    	server_id_in in numeric,
	service_level_in in varchar
    ) returns numeric as $$
    declare
    ents cursor is 
      select label from rhnServerEntitlementView
      where server_id = server_id_in;

    retval numeric := 0;

    begin
         for ent in ents loop
            retval := rhn_entitlements.entitlement_grants_service (ent.label, service_level_in);
            if retval = 1 then
               return retval;
            end if;
         end loop;

         return retval;

    end$$ language plpgsql;

        
    create or replace function can_change_base_channel(server_id_in IN NUMERIC)
    returns numeric
    as $$
    declare
    	throwaway numeric;
    begin
    	-- the idea: if we get past this query, the server is
	-- neither sat nor proxy, so base channel is changeable

	select 1 into throwaway
	  from rhnServer S
	 where S.id = server_id_in
	   and not exists (select 1 from rhnSatelliteInfo SI where SI.server_id = S.id)
	   and not exists (select 1 from rhnProxyInfo PI where PI.server_id = S.id);

        if not found then
	    return 0;
        end if;
	   
	return 1;
    end$$ language plpgsql;
	        
    create or replace function set_custom_value(
    	server_id_in in numeric,
	user_id_in in numeric,
	key_label_in in varchar,
	value_in in varchar
    ) returns void
    as $$
    declare
    	key_id_val numeric;
    begin
    	select CDK.id into strict key_id_val
	  from rhnCustomDataKey CDK,
	       rhnServer S
	 where S.id = server_id_in
	   and S.org_id = CDK.org_id
	   and CDK.label = key_label_in;
	   
	begin
	    insert into rhnServerCustomDataValue (server_id, key_id, value, created_by, last_modified_by)
	    values (server_id_in, key_id_val, value_in, user_id_in, user_id_in);
	exception
	    when UNIQUE_VIOLATION
	    	then
		update rhnServerCustomDataValue
		   set value = value_in,
		       last_modified_by = user_id_in
		 where server_id = server_id_in
		   and key_id = key_id_val;		   
	end;

    end$$ language plpgsql;
    
    create or replace function bulk_set_custom_value(
    	key_label_in in varchar,
	value_in in varchar,
	set_label_in in varchar,
	set_uid_in in numeric
    )
    returns integer
    as $$
    declare
        i integer;
        server record;
    begin
        i := 0;
        for server in (
           SELECT user_id, label, element, element_two
	     FROM rhnSet
	    WHERE label = set_label_in
	      AND user_id = set_uid_in
	) loop
	    if rhn_server.system_service_level(server.element, 'provisioning') = 1 then
	    	perform rhn_server.set_custom_value(server.element, set_uid_in, key_label_in, value_in);
            i := i + 1;
	    end if;
	end loop;
    return i;
    end$$ language plpgsql;

    create or replace function bulk_snapshot_tag(
    	org_id_in in numeric,
        tagname_in in varchar,
	set_label_in in varchar,
	set_uid_in in numeric
    ) returns void
    as $$
    declare
        server record;
    	snapshot_id numeric;
    begin
        for server in (
           SELECT user_id, label, element, element_two
	     FROM rhnSet
	    WHERE label = set_label_in
	      AND user_id = set_uid_in
	    ) loop
	    if rhn_server.system_service_level(server.element, 'provisioning') = 1 then
	    	    select max(id) into snapshot_id
	    	    from rhnSnapshot
	    	    where server_id = server.element;

	    	    if snapshot_id is null then
		    	perform rhn_server.snapshot_server(server.element, 'tagging system:  ' || tagname_in);
			
			select max(id) into snapshot_id
			from rhnSnapshot
			where server_id = server.element;
		    end if;
		 
		-- now have a snapshot_id to work with...
		begin
		    perform rhn_server.tag_snapshot(snapshot_id, org_id_in, tagname_in);
		exception
		    when UNIQUE_VIOLATION
		    	then
			-- do nothing, be forgiving...
			null;
		end;
	    end if;
	end loop;    
    end$$ language plpgsql;

    create or replace function tag_delete(
    	server_id_in in numeric,
	tag_id_in in numeric
    ) returns void
    as $$
    declare
    	snapshots cursor is
		select	snapshot_id
		from	rhnSnapshotTag
		where	tag_id = tag_id_in;
	tag_id_tmp numeric;
    begin
    	select	id into tag_id_tmp
	from	rhnTag
	where	id = tag_id_in
	for update;

	delete
		from	rhnSnapshotTag
		where	server_id = server_id_in
			and tag_id = tag_id_in;
	for snapshot in snapshots loop
		return;
	end loop;
	delete
		from rhnTag
		where id = tag_id_in;
    end$$ language plpgsql;

    create or replace function tag_snapshot(
        snapshot_id_in in numeric,
	org_id_in in numeric,
	tagname_in in varchar
    ) returns void
    as $$
    begin
    	insert into rhnSnapshotTag (snapshot_id, server_id, tag_id)
	select snapshot_id_in, server_id, lookup_tag(org_id_in, tagname_in)
	from rhnSnapshot
	where id = snapshot_id_in;
    end$$ language plpgsql;

    create or replace function bulk_snapshot(
    	reason_in in varchar,
	set_label_in in varchar,
	set_uid_in in numeric
    ) returns void
    as $$
    declare
        server record;
    begin
        for server in (
           SELECT user_id, label, element, element_two
	     FROM rhnSet
	    WHERE label = set_label_in
	      AND user_id = set_uid_in
	    ) loop
    	    if rhn_server.system_service_level(server.element, 'provisioning') = 1 then
	    	perform rhn_server.snapshot_server(server.element, reason_in);
	    end if;
	end loop;
    end$$ language plpgsql;

    create or replace function snapshot_server(
    	server_id_in in numeric,
	reason_in in varchar
    ) returns void
    as $$
    declare
    	snapshot_id_v numeric;
	revisions cursor is
		select distinct
			cr.id
		from	rhnConfigRevision	cr,
			rhnConfigFileName	cfn,
			rhnConfigFile		cf,
			rhnConfigChannel	cc,
			rhnServerConfigChannel	scc
		where	1=1
			and scc.server_id = server_id_in
			and scc.config_channel_id = cc.id
			and cc.id = cf.config_channel_id
			and cf.id = cr.config_file_id
			and cr.id = cf.latest_config_revision_id
			and cf.config_file_name_id = cfn.id
			and cf.id = lookup_first_matching_cf(scc.server_id, cfn.path);
	locked integer;
    begin
    	select nextval('rhn_snapshot_id_seq') into snapshot_id_v;

	insert into rhnSnapshot (id, org_id, server_id, reason) (
		select	snapshot_id_v,
			s.org_id,
			server_id_in,
			reason_in
		from	rhnServer s
		where	s.id = server_id_in
	);
	insert into rhnSnapshotChannel (snapshot_id, channel_id) (
		select	snapshot_id_v, sc.channel_id
		from	rhnServerChannel sc
		where	sc.server_id = server_id_in
	);
	insert into rhnSnapshotServerGroup (snapshot_id, server_group_id) (
		select	snapshot_id_v, sgm.server_group_id
		from	rhnServerGroupMembers sgm
		where	sgm.server_id = server_id_in
	);
        locked := 0;
        <<iloop>>
        while true loop
            begin
                insert into rhnPackageNEVRA (id, name_id, evr_id, package_arch_id)
                select nextval('rhn_pkgnevra_id_seq'), sp.name_id, sp.evr_id, sp.package_arch_id
                from rhnServerPackage sp
                where sp.server_id = server_id_in
                        and not exists
                        (select 1
                                from rhnPackageNEVRA nevra
                                where nevra.name_id = sp.name_id
                                        and nevra.evr_id = sp.evr_id
                                        and (nevra.package_arch_id = sp.package_arch_id
                                            or (nevra.package_arch_id is null
                                                and sp.package_arch_id is null)));
                exit iloop;
            exception when unique_violation then
                if locked = 1 then
                    raise;
                else
                    lock table rhnPackageNEVRA in exclusive mode;
                    locked := 1;
                end if;
            end;
        end loop;
	insert into rhnSnapshotPackage (snapshot_id, nevra_id) (
                select distinct snapshot_id_v, nevra.id
                from    rhnServerPackage sp, rhnPackageNEVRA nevra
                where   sp.server_id = server_id_in
                        and nevra.name_id = sp.name_id
                        and nevra.evr_id = sp.evr_id
                        and (nevra.package_arch_id = sp.package_arch_id
                            or (nevra.package_arch_id is null
                                and sp.package_arch_id is null))
	);

	insert into rhnSnapshotConfigChannel ( snapshot_id, config_channel_id ) (
		select	snapshot_id_v, scc.config_channel_id
		from	rhnServerConfigChannel scc
		where	server_id = server_id_in
	);

	for revision in revisions loop
		insert into rhnSnapshotConfigRevision (
				snapshot_id, config_revision_id
			) values (
				snapshot_id_v, revision.id
			);
	end loop;
    end$$ language plpgsql;

    create or replace function remove_action(
    	server_id_in in numeric,
	action_id_in in numeric
    ) returns void
    as $$
    declare
    	-- this really wants "nulls last", but 8.1.7.3.0 sucks ass.
	-- instead, we make a local table that holds our
	-- list of ids with null prereqs.  There's surely a better way
	-- (an array instead of a table maybe?  who knows...)
	-- but I've got code to do this handy that I can look at ;)
    	chained_actions cursor is
                with recursive r(id, prerequisite) as (
			select	id, prerequisite
			from	rhnAction
			where id = action_id_in
		union all
			select	r1.id, r1.prerequisite
			from	rhnAction r1, r
			where r.id = r1.prerequisite
		)
		select * from r
		order by prerequisite desc;
	sessions cursor is
		select	s.id
		from	rhnKickstartSession s
		where	server_id_in in (s.old_server_id, s.new_server_id)
			and s.action_id = action_id_in
			and not exists (
				select	1
				from	rhnKickstartSessionState ss
				where	ss.id = s.state_id
					and ss.label in ('failed','complete')
			);
	chain_ends numeric[];
	i numeric;
	prereq numeric := 1;
    begin
	select	prerequisite
	into	prereq
	from	rhnAction
	where	id = action_id_in;

	if prereq is not null then
		perform rhn_exception.raise_exception('action_is_child');
	end if;

        chain_ends := '{}';
	i := 1;
	for action in chained_actions loop
		if action.prerequisite is null then
			chain_ends[i] := action.id;
			i := i + 1;
		else
			delete from rhnServerAction
				where server_id = server_id_in
				and action_id = action.id;
		end if;
	end loop;

	delete from rhnServerAction
		where server_id = server_id_in
		and action_id = any(chain_ends);

	for s in sessions loop
		update rhnKickstartSession
			set 	state_id = (
					select	id
					from	rhnKickstartSessionState
					where	label = 'failed'
				),
				action_id = null
			where	id = s.id;
		perform set_ks_session_history_message(s.id, 'failed', 'Kickstart cancelled due to action removal');
	end loop;
    end$$ language plpgsql;
   
    create or replace function check_user_access(server_id_in in numeric, user_id_in in numeric)
    returns numeric
    as $$
    declare
    	has_access numeric;
    begin
    	-- first check; if this returns no rows, then the server/user are in different orgs, and we bail
        select 1 into has_access
	  from rhnServer S,
	       web_contact wc
	 where wc.org_id = s.org_id
	   and s.id = server_id_in
	   and wc.id = user_id_in;

        if not found then
          return 0;
        end if;

	-- okay, so they're in the same org.  if we have an org admin, they get a free pass
    	if rhn_user.check_role(user_id_in, 'org_admin') = 1
	then
	    return 1;
	end if;
		   
    	select 1 into has_access
	  from rhnServerGroupMembers SGM,
	       rhnUserServerGroupPerms USG
	 where SGM.server_group_id = USG.server_group_id
	   and SGM.server_id = server_id_in
	   and USG.user_id = user_id_in;

        if not found then
          return 0;
        end if;
	   
	return 1;
    end$$ language plpgsql;

    -- *******************************************************************
    -- FUNCTION: can_server_consume_virt_slot
    -- Returns 1 if the server id is eligible to consume a virtual slot,
    --   else returns 0.
    -- Called by: insert_into_servergroup, delete_from_servergroup
    -- *******************************************************************
    create or replace function can_server_consume_virt_slot(server_id_in in numeric,
                                           group_type_in in varchar)
    returns numeric                                           
    as $$
    declare
        server_virt_slots cursor is
            select vi.VIRTUAL_SYSTEM_ID
            from
                rhnVirtualInstance vi
            where
                -- server id is a virtual instance
                vi.VIRTUAL_SYSTEM_ID = server_id_in
                -- server id's host is virt entitled
                and exists ( select 1
                     from rhnServerEntitlementView sev
                 where vi.HOST_SYSTEM_ID = sev.server_id
                 and sev.label in ('virtualization_host',
                                   'virtualization_host_platform') )
                -- server id's host also has the ent we want
                and exists ( select 1
                     from rhnServerEntitlementView sev2
                 where vi.HOST_SYSTEM_ID = sev2.server_id
                 and sev2.label = group_type_in );

    begin
        for server_virt_slot in server_virt_slots loop
            return 1;
        end loop;
        return 0;
    end$$ language plpgsql;


    create or replace function insert_into_servergroup (
		server_id_in in numeric,
		server_group_id_in in numeric
    ) returns void
    as $$
    declare
		used_slots numeric;
		max_slots numeric;
		org_id numeric;
		mgmt_available numeric;
		mgmt_upgrade numeric;
		mgmt_sgid numeric;
		prov_available numeric;
		prov_upgrade numeric;
		prov_sgid numeric;
		group_label varchar;
		group_type numeric;
	begin
		-- first, group_type = null, because it's easy...

		-- this will rowlock the servergroup we're trying to change;
		-- we probably need to lock the other one, but I think the chances
		-- of it being a real issue are very small for now...
		select	sg.group_type, sg.org_id, sg.current_members, sg.max_members
		into	group_type, org_id, used_slots, max_slots
		from	rhnServerGroup sg
		where	sg.id = server_group_id_in
		for update of sg;

		if group_type is null then
			if used_slots >= max_slots then
				perform rhn_exception.raise_exception('servergroup_max_members');
			end if;

			insert into rhnServerGroupMembers(
					server_id, server_group_id
				) values (
					server_id_in, server_group_id_in
				);
			update rhnServerGroup
				set current_members = current_members + 1
				where id = server_group_id_in;

			perform rhn_cache.update_perms_for_server_group(server_group_id_in);
			return;
		end if;

		-- now for group_type != null
		-- 
		select	label
		into	group_label
		from	rhnServerGroupType	sgt
		where	sgt.id = group_type;

		-- the naive easy path that gets hit most often and has to be quickest.
		if group_label in ('sw_mgr_entitled',
                           'enterprise_entitled',
                           'provisioning_entitled',
                           'virtualization_host',
                           'virtualization_host_platform') then
			if used_slots >= max_slots and 
               (rhn_server.can_server_consume_virt_slot(server_id_in, group_label) != 1) 
               then
				perform rhn_exception.raise_exception('servergroup_max_members');
			end if;

			insert into rhnServerGroupMembers(
					server_id, server_group_id
				) values (
					server_id_in, server_group_id_in
				);

            -- Only update current members if the system in consuming a 
            -- physical slot.
            if rhn_server.can_server_consume_virt_slot(server_id_in, group_label) = 0 then
                update rhnServerGroup
                set current_members = current_members + 1
                where id = server_group_id_in;
            end if;                

			return;
		end if;
	end$$ language plpgsql;

	create or replace function insert_into_servergroup_maybe (
		server_id_in in numeric,
		server_group_id_in in numeric
	) returns numeric as $$ 
    declare
		retval numeric := 0;
		servergroups cursor is
			select	s.id	server_id,
					sg.id	server_group_id
			from	rhnServerGroup	sg,
					rhnServer		s
			where	s.id = server_id_in
				and sg.id = server_group_id_in
				and s.org_id = sg.org_id
				and not exists (
					select	1
					from	rhnServerGroupMembers sgm
					where	sgm.server_id = s.id
						and sgm.server_group_id = sg.id
				);
	begin
		for sgm in servergroups loop
			perform rhn_server.insert_into_servergroup(sgm.server_id, sgm.server_group_id);
			retval := retval + 1;
		end loop;
		return retval;
	end$$ language plpgsql;

	create or replace function insert_set_into_servergroup (
		server_group_id_in in numeric,
		user_id_in in numeric,
		set_label_in in varchar
	) returns void
        as $$
    declare
		servers cursor is
			select	st.element	id
			from	rhnSet		st
			where	st.user_id = user_id_in
				and st.label = set_label_in
				and exists (
					select	1
					from	rhnUserManagedServerGroups umsg
					where	umsg.server_group_id = server_group_id_in
						and umsg.user_id = user_id_in
					)
				and not exists (
					select	1
					from	rhnServerGroupMembers sgm
					where	sgm.server_id = st.element
						and sgm.server_group_id = server_group_id_in
				);
	begin
		for s in servers loop
			perform rhn_server.insert_into_servergroup(s.id, server_group_id_in);
		end loop;
	end$$ language plpgsql;
		
    create or replace function delete_from_servergroup (
    	server_id_in in numeric,
		server_group_id_in in numeric
    ) returns void
    as $$
    declare
        server_virt_groups cursor is
            select 1
            from rhnServerEntitlementVirtual sev
            where sev.server_id = server_id_in
            and sev.server_group_id = server_group_id_in;

		oid numeric;
		mgmt_sgid numeric;
		label varchar;
		group_type numeric;
	begin
			select	sg.group_type, sg.org_id
			into	group_type,	oid
			from	rhnServerGroupMembers	sgm,
					rhnServerGroup			sg
			where	sg.id = server_group_id_in
				and sg.id = sgm.server_group_id
				and sgm.server_id = server_id_in
			for update of sg;

			if not found then
				perform rhn_exception.raise_exception('server_not_in_group');
			end if;

		-- do group_type is null first
		if group_type is null then
			delete from rhnServerGroupMembers
				where server_group_id = server_group_id_in
				and	server_id = server_id_in;
			update rhnServerGroup
				set current_members = current_members - 1
				where id = server_group_id_in;
			perform rhn_cache.update_perms_for_server_group(server_group_id_in);
			return;
		end if;

		select	sgt.label
		into	label
		from	rhnServerGroupType sgt
		where	sgt.id = group_type;

		if label in ('sw_mgr_entitled',
                     'enterprise_entitled', 
                     'provisioning_entitled', 
                     'virtualization_host',
                     'virtualization_host_platform') then

            -- Only update current members if the system is consuming
            -- a physical slot.
            for server_virt_group in server_virt_groups loop                
                delete from rhnServerGroupMembers
                where server_group_id = server_group_id_in
                and	server_id = server_id_in;
                return;
            end loop;                

            delete from rhnServerGroupMembers
            where server_group_id = server_group_id_in
            and	server_id = server_id_in;

            update rhnServerGroup
            set current_members = current_members - 1
            where id = server_group_id_in;

		end if;
	end$$ language plpgsql;

	create or replace function delete_set_from_servergroup (
		server_group_id_in in numeric,
		user_id_in in numeric,
		set_label_in in varchar
	) returns void
        as $$	
        declare
		servergroups cursor is
			select	sgm.server_id, sgm.server_group_id
			from	rhnSet st,
					rhnServerGroupMembers sgm
			where	sgm.server_group_id = server_group_id_in
				and st.user_id = user_id_in
				and st.label = set_label_in
				and sgm.server_id = st.element
				and exists (
					select	1
					from	rhnUserManagedServerGroups usgp
					where	usgp.server_group_id = server_group_id_in
						and usgp.user_id = user_id_in
				);
	begin
		for sgm in servergroups loop
			perform rhn_server.delete_from_servergroup(sgm.server_id, server_group_id_in);
		end loop;
	end$$ language plpgsql;

	create or replace function clear_servergroup (
		server_group_id_in in numeric
	) returns void
        as $$
        declare
		servers cursor is
			select	sgm.server_id	id
			from	rhnServerGroupMembers sgm
			where	sgm.server_group_id = server_group_id_in;
	begin
		for s in servers loop
			perform rhn_server.delete_from_servergroup(s.id, server_group_id_in);
		end loop;
	end$$ language plpgsql;

	create or replace function delete_from_org_servergroups (
		server_id_in in numeric
	) returns void
        as $$
        declare
		servergroups cursor is
			select	sgm.server_group_id id
			from	rhnServerGroup sg,
					rhnServerGroupMembers sgm
			where	sgm.server_id = server_id_in
				and sgm.server_group_id = sg.id
				and sg.group_type is null;
	begin
		for sg in servergroups loop
			perform rhn_server.delete_from_servergroup(server_id_in, sg.id);
		end loop;
	end$$ language plpgsql;

	create or replace function get_ip_address (
		server_id_in in numeric
	) returns varchar as $$
        declare
		interfaces cursor is
			select	ni.name as name, na4.address as address
			from	rhnServerNetInterface ni,
			        rhnServerNetAddress4 na4
			where	server_id = server_id_in
                and ni.id = na4.interface_id
				and na4.address != '127.0.0.1';
		addresses cursor is
			select	ipaddr ip_addr
			from	rhnServerNetwork
			where	server_id = server_id_in
				and ipaddr != '127.0.0.1';
	begin
		for addr in addresses loop
			return addr.ip_addr;
		end loop;
		for iface in interfaces loop
			return iface.address;
		end loop;
		return NULL;
	end$$ language plpgsql;

    create or replace function update_needed_cache(
        server_id_in in numeric
	) returns void as $$
    declare
      update_lock numeric;
    begin
      select id into update_lock from rhnServer where id = server_id_in for update;
      delete from rhnServerNeededCache
        where server_id = server_id_in;
      insert into rhnServerNeededCache
             (server_id, errata_id, package_id, channel_id)
        (select distinct sp.server_id, x.errata_id, p.id, x.channel_id
           FROM (SELECT sp_sp.server_id, sp_sp.name_id,
		        sp_sp.package_arch_id, max(sp_pe.evr) AS max_evr
                   FROM rhnServerPackage sp_sp
                   join rhnPackageEvr sp_pe ON sp_pe.id = sp_sp.evr_id
                  GROUP BY sp_sp.server_id, sp_sp.name_id, sp_sp.package_arch_id) sp
           join rhnPackage p ON p.name_id = sp.name_id
           join rhnPackageEvr pe ON pe.id = p.evr_id AND sp.max_evr < pe.evr
           join rhnPackageUpgradeArchCompat puac
	            ON puac.package_arch_id = sp.package_arch_id
		    AND puac.package_upgrade_arch_id = p.package_arch_id
           join rhnServerChannel sc ON sc.server_id = sp.server_id
           join rhnChannelPackage cp ON cp.package_id = p.id
	            AND cp.channel_id = sc.channel_id
           left join (SELECT ep.errata_id, ce.channel_id, ep.package_id
                        FROM rhnChannelErrata ce
                        join rhnErrataPackage ep
			         ON ep.errata_id = ce.errata_id
			join rhnServerChannel sc_sc
			         ON sc_sc.channel_id = ce.channel_id
		       WHERE sc_sc.server_id = server_id_in) x
             ON x.channel_id = sc.channel_id AND x.package_id = cp.package_id
          where sp.server_id = server_id_in);
	end$$ language plpgsql;
-- restore the original setting
update pg_settings set setting = overlay( setting placing '' from 1 for (length('rhn_server')+1) ) where name = 'search_path';
   0707010000084E000081B400000000000000000000000167AE1114000009F4000000000000000000000000000000000000006A00000000susemanager-schema/upgrade/spacewalk-schema-2.4-to-spacewalk-schema-2.5/148-delete_rhnServerGroupType.sql 
-- rhnServerGroup and dependencies

SELECT .clear_log_id();

DELETE FROM rhnOrgExtGroupMapping
  WHERE server_group_id in (
    SELECT id
      FROM rhnServerGroup
      WHERE group_type = (
        SELECT id
          FROM rhnServerGroupType
          WHERE label = 'provisioning_entitled'
      )
  );

DELETE FROM rhnRegTokenGroups
  WHERE server_group_id in (
    SELECT id
      FROM rhnServerGroup
      WHERE group_type = (
        SELECT id
          FROM rhnServerGroupType
          WHERE label = 'provisioning_entitled'
      )
  );

DELETE FROM rhnServerGroupMembers
  WHERE server_group_id in (
    SELECT id
      FROM rhnServerGroup
      WHERE group_type = (
        SELECT id
          FROM rhnServerGroupType
          WHERE label = 'provisioning_entitled'
      )
  );

DELETE FROM rhnSnapshotServerGroup
  WHERE server_group_id in (
    SELECT id
      FROM rhnServerGroup
      WHERE group_type = (
        SELECT id
          FROM rhnServerGroupType
          WHERE label = 'provisioning_entitled'
      )
  );

DELETE FROM rhnUserDefaultSystemGroups
  WHERE system_group_id in (
    SELECT id
      FROM rhnServerGroup
      WHERE group_type = (
        SELECT id
          FROM rhnServerGroupType
          WHERE label = 'provisioning_entitled'
      )
  );

DELETE FROM rhnUserServerGroupPerms
  WHERE server_group_id in (
    SELECT id
      FROM rhnServerGroup
      WHERE group_type = (
        SELECT id
          FROM rhnServerGroupType
          WHERE label = 'provisioning_entitled'
      )
  );

DELETE FROM rhnServerGroup
  WHERE group_type = (
    SELECT id
      FROM rhnServerGroupType
      WHERE label = 'provisioning_entitled'
  );

-- rhnServerGroupType and dependencies

DELETE FROM rhnRegTokenEntitlement
  WHERE server_group_type_id = (
    SELECT id
      FROM rhnServerGroupType
      WHERE label = 'provisioning_entitled'
  );

UPDATE rhnServerGroupTypeFeature
  SET server_group_type_id = (
    SELECT id
      FROM rhnServerGroupType
      WHERE label = 'enterprise_entitled'
  )
  WHERE server_group_type_id = (
    SELECT id
      FROM rhnServerGroupType
      WHERE label = 'provisioning_entitled'
  );

DELETE FROM rhnServerServerGroupArchCompat
  WHERE server_group_type = (
    SELECT id
      FROM rhnServerGroupType
      WHERE label = 'provisioning_entitled'
  );

DELETE FROM rhnSGTypeBaseAddonCompat
  WHERE addon_id = (
    SELECT id
      FROM rhnServerGroupType
      WHERE label = 'provisioning_entitled'
  );

DELETE FROM rhnServerGroupType
  WHERE label = 'provisioning_entitled';
0707010000084F000081B400000000000000000000000167AE111400000118000000000000000000000000000000000000007100000000susemanager-schema/upgrade/spacewalk-schema-2.4-to-spacewalk-schema-2.5/149-update_rhnServerGroupTypeFeature.sql  UPDATE rhnServerGroupTypeFeature
  SET server_group_type_id = (
    SELECT id
      FROM rhnServerGroupType
      WHERE label = 'enterprise_entitled'
  )
  WHERE server_group_type_id = (
    SELECT id
      FROM rhnServerGroupType
      WHERE label = 'provisioning_entitled'
  );
07070100000850000081B400000000000000000000000167AE1114000000D1000000000000000000000000000000000000006D00000000susemanager-schema/upgrade/spacewalk-schema-2.4-to-spacewalk-schema-2.5/150-update_rhnOrgEntitlementType.sql  DELETE FROM rhnOrgEntitlements
  WHERE entitlement_id IN (
    SELECT id FROM rhnOrgEntitlementType WHERE label = 'rhn_provisioning'
  );

DELETE FROM rhnOrgEntitlementType
  WHERE label = 'rhn_provisioning';
   07070100000851000081B400000000000000000000000167AE1114000091BC000000000000000000000000000000000000007C00000000susemanager-schema/upgrade/spacewalk-schema-2.4-to-spacewalk-schema-2.5/151-drop-provisioning-from-rhn_entitlements_pkb.sql   --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

-- create schema rhn_entitlements;

-- setup search_path so that these functions are created in appropriate schema.
update pg_settings set setting = 'rhn_entitlements,' || setting where name = 'search_path';

   create or replace function find_compatible_sg (
      server_id_in in numeric,
      type_label_in in varchar
   )
   returns numeric
as $$
    declare
      servergroups cursor for
         select sg.id
           from rhnServerGroupType             sgt,
                rhnServerGroup                 sg,
                rhnServer                     s,
                rhnServerServerGroupArchCompat ssgac
          where s.id = server_id_in
            and s.org_id = sg.org_id
            and sgt.label = type_label_in
            and sg.group_type = sgt.id
            and ssgac.server_group_type = sgt.id
            and ssgac.server_arch_id = s.server_arch_id
            and not exists (
                     select 1
                      from rhnServerGroupMembers sgm
                     where sgm.server_group_id = sg.id
                       and sgm.server_id = s.id);


   begin
      for servergroup in servergroups loop
         return servergroup.id;
      end loop;

      --no servergroup found
      return NULL;
   end$$
language plpgsql;

    -- *******************************************************************
    -- PROCEDURE: remove_org_entitlements
    --
    -- Removes both system entitlements and channel subscriptions
    -- that are currently assigned to an org and re-assigns to the
    -- master org (org_id = 1).
    --
    -- When we call this we expect everything to already be unentitled
    -- which shoul be handled by delete_org.
    --
    -- Called by: delete_org
    -- *******************************************************************
    create or replace function remove_org_entitlements (
        org_id_in numeric
    ) returns void
as $$
    declare
        system_ents cursor for
        select sg.id, sg.max_members, sg.group_type
        from rhnServerGroup sg
        where group_type is not null
          and org_id = org_id_in;

    begin

        for system_ent in system_ents loop
            update rhnServerGroup
            set max_members = max_members + system_ent.max_members
            where org_id = 1
              and group_type = system_ent.group_type;
        end loop;

        update rhnServerGroup
        set max_members = 0
        where org_id = org_id_in;

    end$$
language plpgsql;

    create or replace function entitlement_grants_service (
        entitlement_in in varchar,
        service_level_in in varchar
    ) returns numeric
as $$
    begin
        if service_level_in = 'management' then
            if entitlement_in = 'enterprise_entitled' then
                return 1;
            else
                return 0;
            end if;
        elsif service_level_in = 'updates' then
            return 1;
        else
            return 0;
        end if;
    end$$
language plpgsql;

    create or replace function lookup_entitlement_group (
        org_id_in in numeric,
        type_label_in in varchar default 'sw_mgr_entitled'
    ) returns numeric
as $$
    declare
        server_groups cursor for
            select  sg.id               server_group_id
            from    rhnServerGroup      sg,
                    rhnServerGroupType  sgt
            where   sgt.label = type_label_in
                and sgt.id = sg.group_type
                and sg.org_id = org_id_in;
    begin
        for sg in server_groups loop
            return sg.server_group_id;
        end loop;
        return rhn_entitlements.create_entitlement_group(
                org_id_in,
                type_label_in
            );
    end$$
language plpgsql;

    create or replace function create_entitlement_group (
        org_id_in in numeric,
        type_label_in in varchar default 'sw_mgr_entitled'
    ) returns numeric
as $$
    declare
        sg_id_val numeric;
    begin
        select  nextval('rhn_server_group_id_seq')
        into    sg_id_val;

        insert into rhnServerGroup (
                id, name, description, max_members, current_members,
                group_type, org_id
            ) (
                select  sg_id_val, sgt.label, sgt.label,
                        0, 0, sgt.id, org_id_in
                from    rhnServerGroupType sgt
                where   sgt.label = type_label_in
            );

        return sg_id_val;
    end$$
language plpgsql;

   create or replace function can_entitle_server (
      server_id_in   in numeric,
      type_label_in  in varchar
   )
   returns numeric
as $$
    declare
      addon_servergroups cursor (base_label_in varchar,
                                 addon_label_in varchar) for
         select
            addon_id
         from
            rhnSGTypeBaseAddonCompat
         where base_id = lookup_sg_type (base_label_in)
           and addon_id = lookup_sg_type (addon_label_in);

      previous_ent        varchar[];
      is_base_in          char   := 'N';
      is_base_current     char   := 'N';
      i                   numeric := 0;
      sgid                numeric := 0;

   begin

      previous_ent := rhn_entitlements.get_server_entitlement(server_id_in);

      select distinct is_base
      into is_base_in
      from rhnServerGroupType
      where label = type_label_in;

      if array_upper(previous_ent, 1) is null or array_upper(previous_ent, 1) = 0 then
         if is_base_in = 'Y' then
            sgid := rhn_entitlements.find_compatible_sg (server_id_in, type_label_in);
            if sgid is not null then
              -- rhn_server.insert_into_servergroup (server_id_in, sgid);
              return 1;
            else
              -- rhn_exception.raise_exception ('invalid_base_entitlement');
              return 0;
            end if;
         else
            -- rhn_exception.raise_exception ('invalid_base_entitlement');
            return 0;
         end if;

      -- there are previous ents, first make sure we're not trying to entitle a base ent
      elsif is_base_in = 'Y' then
         -- rhn_exception.raise_exception ('invalid_addon_entitlement');
         return 0;

      -- it must be an addon, so proceed with the entitlement
      else

         -- find the servers base ent
         is_base_current := 'N';
         i := 0;
         while is_base_current = 'N' and i < array_upper(previous_ent, 1)
         loop
            i := i + 1;
            select is_base
            into is_base_current
            from rhnServerGroupType
            where label = previous_ent[i];
         end loop;

         -- never found a base ent, that would be strange
         if is_base_current  = 'N' then
            -- rhn_exception.raise_exception ('invalid_base_entitlement');
            return 0;
         end if;

         -- this for loop verifies the validity of the addon path
         for addon_servergroup in addon_servergroups  (previous_ent[i], type_label_in) loop
            -- find an appropriate sgid for the addon and entitle the server
            sgid := rhn_entitlements.find_compatible_sg (server_id_in, type_label_in);
            if sgid is not null then
               -- rhn_server.insert_into_servergroup (server_id_in, sgid);
               return 1;
            else
               -- rhn_exception.raise_exception ('invalid_addon_entitlement');
               return 0;
            end if;
         end loop;

      end if;

      return 0;

   end$$
language plpgsql;

   create or replace function can_switch_base (
      server_id_in   in    integer,
      type_label_in  in    varchar
   )
   returns numeric
as $$
   declare
      type_label_in_is_base   char(1);
      sgid                    numeric;

   begin

       select is_base into type_label_in_is_base
       from rhnServerGroupType
       where label = type_label_in;

       if not found then
          perform rhn_exception.raise_exception ( 'invalid_entitlement' );
       end if;

      if type_label_in_is_base = 'N' then
         perform rhn_exception.raise_exception ( 'invalid_entitlement' );
      else
         sgid := rhn_entitlements.find_compatible_sg ( server_id_in,
                                                       type_label_in );
         if sgid is not null then
           return 1;
         else
           return 0;
         end if;
      end if;

   end$$
language plpgsql;

    create or replace function entitle_server (
        server_id_in in numeric,
        type_label_in in varchar default 'sw_mgr_entitled'
    ) returns void
as $$
    declare
      sgid  numeric := 0;
      is_virt numeric := 0;

    begin

      select 1 into is_virt
        from rhnServerEntitlementView
        where server_id = server_id_in
          and label in ('virtualization_host', 'virtualization_host_platform');

      if not found then
          is_virt := 0;
      end if;

      if is_virt = 0 and (type_label_in = 'virtualization_host' or
                          type_label_in = 'virtualization_host_platform') then

        is_virt := 1;
      end if;

      if rhn_entitlements.can_entitle_server(server_id_in,
                                             type_label_in) = 1 then
         sgid := rhn_entitlements.find_compatible_sg (server_id_in,
                                                      type_label_in);
         if sgid is not null then
            insert into rhnServerHistory ( id, server_id, summary, details )
            values ( nextval('rhn_event_id_seq'), server_id_in,
                     'added system entitlement ',
                      case type_label_in
                       when 'enterprise_entitled' then 'Management'
                       when 'sw_mgr_entitled' then 'Update'
                       when 'virtualization_host' then 'Virtualization'
                       when 'virtualization_host_platform' then
                            'Virtualization Platform' end  );

            perform rhn_server.insert_into_servergroup (server_id_in, sgid);

            if is_virt = 1 then
              perform rhn_entitlements.repoll_virt_guest_entitlements(server_id_in);
            end if;

         else
            perform rhn_exception.raise_exception ('no_available_server_group');
         end if;
      else
         perform rhn_exception.raise_exception ('invalid_entitlement');
      end if;
   end$$
language plpgsql;

    create or replace function remove_server_entitlement (
        server_id_in in numeric,
        type_label_in in varchar default 'sw_mgr_entitled',
        repoll_virt_guests in numeric default 1
    ) returns void
as $$
    declare
      group_id numeric;
      type_is_base char;
      is_virt numeric := 0;
    begin
      -- would be nice if there were a virt attribute of entitlement types, not have to specify 2 different ones...
        select 1 into is_virt
          from rhnServerEntitlementView
          where server_id = server_id_in
            and label in ('virtualization_host', 'virtualization_host_platform');
        if not found then
            is_virt := 0;
        end if;

        select  sg.id, sgt.is_base
        into group_id, type_is_base
        from    rhnServerGroupType sgt,
            rhnServerGroup sg,
                rhnServerGroupMembers sgm,
                rhnServer s
        where   s.id = server_id_in
            and s.id = sgm.server_id
            and sgm.server_group_id = sg.id
            and sg.org_id = s.org_id
            and sgt.label = type_label_in
            and sgt.id = sg.group_type;

        if not found then
          perform rhn_exception.raise_exception('invalid_server_group_member');
        end if;

      if ( type_is_base = 'Y' ) then
         -- unentitle_server should handle everything, don't really need to do anything else special here
         perform rhn_entitlements.unentitle_server ( server_id_in );
      else

         insert into rhnServerHistory ( id, server_id, summary, details )
         values ( nextval('rhn_event_id_seq'), server_id_in,
                  'removed system entitlement ',
                   case type_label_in
                    when 'enterprise_entitled' then 'Management'
                    when 'sw_mgr_entitled' then 'Update'
                    when 'virtualization_host' then 'Virtualization'
                    when 'virtualization_host_platform' then
                         'Virtualization Platforrm' end  );

         perform rhn_server.delete_from_servergroup(server_id_in, group_id);

         if is_virt = 1 and repoll_virt_guests = 1 then
           perform rhn_entitlements.repoll_virt_guest_entitlements(server_id_in);
         end if;
      end if;

    end$$
language plpgsql;

    create or replace function unentitle_server (
        server_id_in in numeric
    ) returns void
as $$
    declare
      servergroups cursor for
         select distinct sgt.label, sg.id server_group_id
         from  rhnServerGroupType sgt,
               rhnServerGroup sg,
               rhnServer s,
               rhnServerGroupMembers sgm
         where s.id = server_id_in
            and s.org_id = sg.org_id
            and sg.group_type = sgt.id
            and sgm.server_group_id = sg.id
            and sgm.server_id = s.id;

     is_virt numeric := 0;

   begin

      select 1 into is_virt
        from rhnServerEntitlementView
        where server_id = server_id_in
         and label in ('virtualization_host', 'virtualization_host_platform');

      if not found then
          is_virt := 0;
      end if;

      for servergroup in servergroups loop

         insert into rhnServerHistory ( id, server_id, summary, details )
         values ( nextval('rhn_event_id_seq'), server_id_in,
                  'removed system entitlement ',
                   case servergroup.label
                    when 'enterprise_entitled' then 'Management'
                    when 'sw_mgr_entitled' then 'Update'
                    when 'virtualization_host' then 'Virtualization'
                    when 'virtualization_host_platform' then
                         'Virtualization Platform' end  );

         perform rhn_server.delete_from_servergroup(server_id_in,
                                            servergroup.server_group_id );
      end loop;

      if is_virt = 1 then
        perform rhn_entitlements.repoll_virt_guest_entitlements(server_id_in);
      end if;

   end$$
language plpgsql;


    -- *******************************************************************
    -- PROCEDURE: repoll_virt_guest_entitlements
    --
    --   Whenever we add/remove a virtualization_host* entitlement from
    --   a host, we can call this procedure to update what type of slots
    --   the guests are consuming.
    --
    --   If you're removing the entitlement, it's
    --   possible the guests will become unentitled if you don't have enough
    --   physical slots to cover them.
    --
    --   If you're adding the entitlement, you end up freeing up physical
    --   slots for other systems.
    --
    -- *******************************************************************
    create or replace function repoll_virt_guest_entitlements(
        server_id_in in numeric
    ) returns void
as $$
    declare
        -- All of server group types associated with the guests of
        -- server_id_in
        group_types cursor for
            select distinct sg.group_type, sgt.label, sg.org_id
            from
                rhnServerGroupType sgt,
                rhnServerGroup sg,
                rhnServerGroupMembers sgm,
                rhnVirtualInstance vi
            where
                vi.host_system_id = server_id_in
                and vi.virtual_system_id = sgm.server_id
                and sgm.server_group_id = sg.id
                and sg.group_type = sgt.id;

        -- Virtual servers from a certain family belonging to a specific
        -- host that are consuming physical system slots over the limit.
        virt_servers_sgt cursor(group_type_in numeric, quantity_in numeric) for
                select vi.virtual_system_id
                from
                    rhnServerGroup sg,
                    rhnServerGroupMembers sgm,
                    rhnVirtualInstance vi
                where
                    vi.host_system_id = server_id_in
                    and vi.virtual_system_id = sgm.server_id
                    and sgm.server_group_id = sg.id
                    and sg.group_type = group_type_in
                order by sgm.modified desc
                limit quantity_in;

        org_id_val numeric;
        max_members_val numeric;
        max_flex_val numeric;
        current_members_calc numeric;
        sg_id numeric;
        is_virt numeric := 0;
        free_slots numeric := 0;
    begin
          select 1 into is_virt
                from rhnServerEntitlementView
           where server_id = server_id_in
                 and label in ('virtualization_host', 'virtualization_host_platform');

      if not found then
          is_virt := 0;
      end if;

        select org_id
        into org_id_val
        from rhnServer
        where id = server_id_in;

        for a_group_type in group_types loop
          -- get the current *physical* members of the system entitlement type for the org...
          --
          -- unlike channel families, it appears the standard rhnServerGroup.max_members represents
          -- *physical* slots, vs physical+virt ... boy that's confusing...

          select max_members, id
            into max_members_val, sg_id
            from rhnServerGroup
            where group_type = a_group_type.group_type
            and org_id = a_group_type.org_id;


      select count(sep.server_id) into current_members_calc
            from rhnServerEntitlementPhysical sep
           where sep.server_group_id = sg_id
             and sep.server_group_type_id = a_group_type.group_type;

          if current_members_calc > max_members_val then
            -- A virtualization_host* ent must have been removed, and we're over the limit, so unsubscribe guests
            for virt_server in virt_servers_sgt(a_group_type.group_type,
                                                current_members_calc - max_members_val) loop
              perform rhn_entitlements.remove_server_entitlement(virt_server.virtual_system_id, a_group_type.label);

              -- decrement current_members_calc, we'll use it to reset current_members for the group at the end...
              current_members_calc := current_members_calc - 1;
            end loop;

          end if;

          update rhnServerGroup set current_members = current_members_calc
           where org_id = a_group_type.org_id
             and group_type = a_group_type.group_type;

          -- I think that's all the house-keeping we have to do...
        end loop;

    end$$
language plpgsql;

    create or replace function get_server_entitlement (
        server_id_in in numeric
    ) returns varchar[]
as $$
    declare
        server_groups cursor for
            select  sgt.label
            from    rhnServerGroupType      sgt,
                    rhnServerGroup          sg,
                    rhnServerGroupMembers   sgm
            where   1=1
                and sgm.server_id = server_id_in
                and sg.id = sgm.server_group_id
                and sgt.id = sg.group_type
                and sgt.label in (
                    'sw_mgr_entitled','enterprise_entitled',
                    'nonlinux_entitled',
                    'virtualization_host', 'virtualization_host_platform'
                    );

         ent_array varchar[];

    begin

      ent_array := '{}';

      for sg in server_groups loop
         ent_array := ent_array || sg.label;
      end loop;

      return ent_array;

    end$$
language plpgsql;

    -- this desperately needs to be table driven.
    create or replace function modify_org_service (
        org_id_in in numeric,
        service_label_in in varchar,
        enable_in in char
    ) returns void
as $$
    declare
        roles_to_process varchar[];
        roles cursor(role_label_in varchar) for
            select  label, id
            from    rhnUserGroupType
            where   label = role_label_in;
        org_roles cursor(role_label_in varchar) for
            select  1
            from    rhnUserGroup ug,
                    rhnUserGroupType ugt
            where   ugt.label = role_label_in
                and ug.org_id = org_id_in
                and ugt.id = ug.group_type;

        ents_to_process varchar[];
        ents cursor(ent_label_in varchar) for
            select  label, id
            from    rhnOrgEntitlementType
            where   label = ent_label_in;
        org_ents cursor(ent_label_in varchar) for
            select  1
            from    rhnOrgEntitlements oe,
                    rhnOrgEntitlementType oet
            where   oet.label = ent_label_in
                and oe.org_id = org_id_in
                and oet.id = oe.entitlement_id;
        create_row char(1);
    begin
        ents_to_process := '{}';
        roles_to_process := '{}';
        -- a bit kludgy, but only for 3.4 really.  Certainly no
        -- worse than the old code...
        if service_label_in = 'enterprise' or
           service_label_in = 'management' then
            ents_to_process := array_append(ents_to_process, 'sw_mgr_enterprise');

            roles_to_process := array_append(roles_to_process, 'org_admin');

            roles_to_process := array_append(roles_to_process, 'system_group_admin');

            roles_to_process := array_append(roles_to_process, 'activation_key_admin');
        elsif service_label_in = 'virtualization' then
            ents_to_process := array_append(ents_to_process, 'rhn_virtualization');

            roles_to_process := array_append(roles_to_process, 'config_admin');
        elsif service_label_in = 'virtualization_platform' then
            ents_to_process := array_append(ents_to_process, 'rhn_virtualization_platform');
            roles_to_process := array_append(roles_to_process, 'config_admin');
    elsif service_label_in = 'nonlinux' then
            ents_to_process := array_append(ents_to_process, 'rhn_nonlinux');
            roles_to_process := array_append(roles_to_process, 'config_admin');
        end if;

        if enable_in = 'Y' then
            for i in 1..array_upper(ents_to_process, 1) loop
                for ent in ents(ents_to_process[i]) loop
                    create_row := 'Y';
                    for oe in org_ents(ent.label) loop
                        create_row := 'N';
                    end loop;
                    if create_row = 'Y' then
                        insert into rhnOrgEntitlements(org_id, entitlement_id)
                            values (org_id_in, ent.id);
                    end if;
                end loop;
            end loop;
            for i in 1..array_upper(roles_to_process, 1) loop
                for role in roles(roles_to_process[i]) loop
                    create_row := 'Y';
                    for o_r in org_roles(role.label) loop
                        create_row := 'N';
                    end loop;
                    if create_row = 'Y' then
                        insert into rhnUserGroup(
                                id, name, description, current_members,
                                group_type, org_id
                            ) (
                                select  nextval('rhn_user_group_id_seq'),
                                        ugt.name || 's',
                                        ugt.name || 's for Org ' ||
                                            o.name || ' ('|| o.id ||')',
                                        0, ugt.id, o.id
                                from    rhnUserGroupType ugt,
                                        web_customer o
                                where   o.id = org_id_in
                                    and ugt.id = role.id
                            );
                    end if;
                end loop;
            end loop;
        else
            for i in 1..coalesce(array_upper(ents_to_process, 1), 0) loop
                for ent in ents(ents_to_process[i]) loop
                    delete from rhnOrgEntitlements
                     where org_id = org_id_in
                       and entitlement_id = ent.id;
                end loop;
            end loop;
        end if;
    end$$
language plpgsql;

    create or replace function set_customer_enterprise (
        customer_id_in in numeric
    ) returns void
as $$
    begin
        perform rhn_entitlements.modify_org_service(customer_id_in, 'enterprise', 'Y');
    end$$
language plpgsql;

    create or replace function set_customer_nonlinux (
        customer_id_in in numeric
    ) returns void
as $$
    begin
        perform rhn_entitlements.modify_org_service(customer_id_in, 'nonlinux', 'Y');
    end$$
language plpgsql;

    create or replace function unset_customer_enterprise (
        customer_id_in in numeric
    ) returns void
as $$
    begin
        perform rhn_entitlements.modify_org_service(customer_id_in, 'enterprise', 'N');
    end$$
language plpgsql;

    create or replace function unset_customer_nonlinux (
        customer_id_in in numeric
    ) returns void
as $$
    begin
        perform rhn_entitlements.modify_org_service(customer_id_in, 'nonlinux', 'N');
    end$$
language plpgsql;

    -- *******************************************************************
    -- PROCEDURE: prune_group
    -- Unsubscribes servers consuming physical slots that over the org's
    --   limit.
    -- Called by: set_server_group_count, repoll_virt_guest_entitlements
    -- *******************************************************************
    create or replace function prune_group (
        group_id_in in numeric,
        quantity_in in numeric
    ) returns void
as $$
    declare
        sgrecord record;
      type_is_base char;
    begin
            update      rhnServerGroup
                set     max_members = quantity_in
                where   id = group_id_in;

            for sgrecord in (
		   select  server_id, server_group_id, sgt.id as group_type_id, sgt.label
		    from    rhnServerGroupType              sgt,
				    rhnServerGroup                  sg,
				    rhnServerGroupMembers   sgm
		    where   1=1
			    and sgm.server_group_id = group_id_in
			    and sgm.server_id in (
				    select  sep.server_id
				    from
					rhnServerEntitlementPhysical sep
				    where
					sep.server_group_id = group_id_in
				    order by sep.modified asc
				    offset quantity_in
				)
			    and sgm.server_group_id = sg.id
			    and sg.group_type = sgt.id
	    ) loop
                perform rhn_entitlements.remove_server_entitlement(sgrecord.server_id, sgrecord.label);

            select is_base
            into type_is_base
            from rhnServerGroupType sgt
            where sgt.id = sgrecord.group_type_id;

            -- if we're removing a base ent, then be sure to
            -- remove the server's channel subscriptions.
            if ( type_is_base = 'Y' ) then
                   perform rhn_channel.clear_subscriptions(sgrecord.server_id, 0);
            end if;

            end loop;
    end$$
language plpgsql;

    -- *******************************************************************
    -- PROCEDURE: assign_system_entitlement
    --
    -- Moves system entitlements from from_org_id_in to to_org_id_in.
    -- Can raise not_enough_entitlements_in_base_org if from_org_id_in
    -- does not have enough entitlements to cover the move.
    -- Takes care of unentitling systems if necessary by calling
    -- set_server_group_count
    -- *******************************************************************
    create or replace function assign_system_entitlement(
        group_label_in in varchar,
        from_org_id_in in numeric,
        to_org_id_in in numeric,
        quantity_in in numeric
    ) returns void
as $$
    declare
        prev_ent_count numeric;
    to_org_prev_ent_count numeric;
        new_ent_count numeric;
    new_quantity numeric;
        group_type numeric;
    begin

            select max_members
            into prev_ent_count
            from rhnServerGroupType sgt,
                 rhnServerGroup sg
            where sg.org_id = from_org_id_in
              and sg.group_type = sgt.id
              and sgt.label = group_label_in;

            if not found then
                perform rhn_exception.raise_exception(
                              'not_enough_entitlements_in_base_org');
            end if;

            select max_members
            into to_org_prev_ent_count
            from rhnServerGroupType sgt,
                 rhnServerGroup sg
            where sg.org_id = to_org_id_in
              and sg.group_type = sgt.id
              and sgt.label = group_label_in;

            if not found then
                to_org_prev_ent_count := 0;
            end if;

            select id
            into group_type
            from rhnServerGroupType
            where label = group_label_in;

            if not found then
                perform rhn_exception.raise_exception(
                              'invalid_server_group');
            end if;

        new_ent_count := prev_ent_count - quantity_in;

        if prev_ent_count > new_ent_count then
            new_quantity := to_org_prev_ent_count + quantity_in;
        end if;

        if new_ent_count < 0 then
            perform rhn_exception.raise_exception(
                          'not_enough_entitlements_in_base_org');
        end if;


        perform rhn_entitlements.set_server_group_count(from_org_id_in,
                                         group_type,
                                         new_ent_count);

        perform rhn_entitlements.set_server_group_count(to_org_id_in,
                                         group_type,
                                         new_quantity);

        -- Create or delete the entries in rhnOrgEntitlementType
        if group_label_in = 'enterprise_entitled' then
            if new_quantity > 0 then
                perform rhn_entitlements.set_customer_enterprise(to_org_id_in);
            else
                perform rhn_entitlements.unset_customer_enterprise(to_org_id_in);
            end if;
        end if;

    end$$
language plpgsql;

    -- *******************************************************************
    -- PROCEDURE: activate_system_entitlement
    --
    -- Sets the values in rhnServerGroup for a given rhnServerGroupType.
    --
    -- Calls: set_server_group_count to update, prune, or create the group.
    -- Called by: the code that activates a satellite cert.
    --
    -- Raises not_enough_entitlements_in_base_org if all entitlements
    -- in the org are used so the free entitlements would not cover
    -- the difference when descreasing the number of entitlements.
    -- *******************************************************************
    create or replace function activate_system_entitlement(
        org_id_in in numeric,
        group_label_in in varchar,
        quantity_in in numeric
    ) returns void
as $$
    declare
        prev_ent_count numeric;
        prev_ent_count_sum numeric;
        group_type numeric;
    begin

        -- Fetch the current entitlement count for the org
        -- into prev_ent_count

            select current_members
            into prev_ent_count
            from rhnServerGroupType sgt,
                 rhnServerGroup sg
            where sg.group_type = sgt.id
              and sgt.label = group_label_in
              and sg.org_id = org_id_in;

            if not found then
                prev_ent_count := 0;
            end if;

            select id
            into group_type
            from rhnServerGroupType
            where label = group_label_in;

            if not found then
                perform rhn_exception.raise_exception(
                              'invalid_server_group');
            end if;

        -- If we're setting the total entitlemnt count to a lower value,
        -- and that value is less than the allocated count in this org,
        -- we need to raise an exception.
        if quantity_in < prev_ent_count then
            perform rhn_exception.raise_exception(
                          'not_enough_entitlements_in_base_org');
        else
            -- don't update family counts after every server
            -- will do bulk update afterwards
            perform rhn_entitlements.set_server_group_count(org_id_in,
                                             group_type,
                                             quantity_in);
        end if;

    end$$
language plpgsql;


    create or replace function set_server_group_count (
        customer_id_in in numeric,  -- customer_id
        group_type_in in numeric,   -- rhn[User|Server]GroupType.id
        quantity_in in numeric      -- quantity
    ) returns void
as $$
    declare
        group_id numeric;
        quantity numeric;
        wasfound boolean;
    begin
        quantity := quantity_in;
        if quantity is not null and quantity < 0 then
            quantity := 0;
        end if;

        select  rsg.id
        into    group_id
        from    rhnServerGroup rsg
        where   1=1
            and rsg.org_id = customer_id_in
            and rsg.group_type = group_type_in;

        -- preserve the not found status across the rhn_entitlements.prune_group invocation
        wasfound := true;
        if not found then
            wasfound := false;
        end if;

        perform rhn_entitlements.prune_group(
            group_id,
            quantity
        );

        if not wasfound then
            insert into rhnServerGroup (
                    id, name, description, max_members, current_members,
                    group_type, org_id, created, modified
                ) (
                    select  nextval('rhn_server_group_id_seq'), name, name,
                            quantity, 0, id, customer_id_in,
                            current_timestamp, current_timestamp
                    from    rhnServerGroupType
                    where   id = group_type_in
            );
        end if;

    end$$
language plpgsql;

    -- this expects quantity_in to be the number of available slots, not the
    -- max_members of the server group.  If you give it too many, it'll fail
    -- and raise servergroup_max_members.
    -- We should NEVER run this unless we're SURE that we won't
    -- be violating the max.
    create or replace function entitle_last_modified_servers (
        customer_id_in in numeric,  -- customer_id
        type_label_in in varchar,   -- 'enterprise_entitled'
        quantity_in in numeric      -- 3
    ) returns void
as $$
    declare
        -- find the servers that aren't currently in slots
        servers cursor(cid_in numeric, quant_in numeric) for
                                    select  rs.id as server_id
                                    from    rhnServer rs
                                    where   1=1
                                        and rs.org_id = cid_in
                                        and not exists (
                                            select  1
                                            from    rhnServerGroup sg,
                                                    rhnServerGroupMembers rsgm
                                            where   rsgm.server_id = rs.id
                                                and rsgm.server_group_id = sg.id
                                                and sg.group_type is not null
                                        )
                                        and not exists (
                                            select 1
                                            from rhnVirtualInstance vi
                                            where vi.virtual_system_id =
                                                  rs.id
                                        )
                                    order by modified desc
                                    limit quant_in;
    begin
        for server in servers(customer_id_in, quantity_in) loop
            perform rhn_entitlements.entitle_server(server.server_id, type_label_in);
        end loop;
    end$$
language plpgsql;

-- restore the original setting
update pg_settings set setting = overlay( setting placing '' from 1 for (length('rhn_entitlements')+1) ) where name = 'search_path';
07070100000852000081B400000000000000000000000167AE111400000C8A000000000000000000000000000000000000006100000000susemanager-schema/upgrade/spacewalk-schema-2.4-to-spacewalk-schema-2.5/153-create_first_org.sql  --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
-- This creates an org with ID of 1, and errors if there already is one
--

create or replace function
create_first_org
(
	name_in in varchar,
	password_in in varchar
)
returns void as
$$
declare
	ug_type			numeric;
	group_val		numeric;
begin
	insert into web_customer (
		id, name
	) values (
		1, name_in
	);

	select nextval( 'rhn_user_group_id_seq' ) into group_val from dual;

	select	id
	into	ug_type
	from	rhnUserGroupType
	where	label = 'org_admin';

	insert into rhnUserGroup (
		id, name,
		description,
		max_members, group_type, org_id
	) values (
		group_val, 'Organization Administrators',
		'Organization Administrators for Org ' || name_in || ' (1)',
		NULL, ug_type, 1
	);

	select nextval('rhn_user_group_id_seq') into group_val from dual;

	select	id
	into	ug_type
	from	rhnUserGroupType
	where	label = 'system_group_admin';

	insert into rhnUserGroup (
		id, name,
		description,
		max_members, group_type, org_id
	) values (
		group_val, 'System Group Administrators',
		'System Group Administrators for Org ' || name_in || ' (1)',
		NULL, ug_type, 1
	);


	select nextval('rhn_user_group_id_seq') into group_val from dual;

	select	id
	into	ug_type
	from	rhnUserGroupType
	where	label = 'activation_key_admin';

	insert into rhnUserGroup (
		id, name,
		description,
		max_members, group_type, org_id
	) values (
		group_val, 'Activation Key Administrators',
		'Activation Key Administrators for Org ' || name_in || ' (1)',
		NULL, ug_type, 1
	);

	select nextval('rhn_user_group_id_seq') into group_val from dual;

	select	id
	into	ug_type
	from	rhnUserGroupType
	where	label = 'channel_admin';

	insert into rhnUserGroup (
		id, name,
		description,
		max_members, group_type, org_id
	) values (
		group_val, 'Channel Administrators',
		'Channel Administrators for Org ' || name_in || ' (1)',
		NULL, ug_type, 1
	);

	select nextval('rhn_user_group_id_seq') into group_val from dual;

	select	id
	into	ug_type
	from	rhnUserGroupType
	where	label = 'satellite_admin';

	insert into rhnUserGroup (
		id, name,
		description,
		max_members, group_type, org_id
	) values (
		group_val, 'Satellite Administrators',
		'Satellite Administrators for Org ' || name_in || ' (1)',
		NULL, ug_type, 1
	);


	-- there aren't any users yet, so we don't need to update
	-- rhnUserServerPerms
        insert into rhnServerGroup 
		( id, name, description, max_members, group_type, org_id )
		select nextval('rhn_server_group_id_seq'), sgt.name, sgt.name, 
			0, sgt.id, 1
		from rhnServerGroupType sgt
		where sgt.label = 'sw_mgr_entitled';
		
end
$$ language plpgsql;

  07070100000853000081B400000000000000000000000167AE111400000ED4000000000000000000000000000000000000005F00000000susemanager-schema/upgrade/spacewalk-schema-2.4-to-spacewalk-schema-2.5/154-create_new_org.sql    --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--

create or replace function create_new_org
(
        name_in      in varchar,
        password_in  in varchar
        --org_id_out   out NUMERIC
) returns numeric
as
$$
declare
        ug_type                 numeric;
        group_val               numeric;
        new_org_id              numeric;
        org_id_out		numeric;
begin

        select nextval('web_customer_id_seq') into new_org_id;

        insert into web_customer (
                id, name
        ) values (
                new_org_id, name_in
        );

        select nextval('rhn_user_group_id_seq') into group_val;

        select  id
        into    ug_type
        from    rhnUserGroupType
        where   label = 'org_admin';

        insert into rhnUserGroup (
                id, name,
                description,
                max_members, group_type, org_id
        ) values (
                group_val, 'Organization Administrators',
                'Organization Administrators for Org ' || name_in,
                NULL, ug_type, new_org_id
        );

        select nextval('rhn_user_group_id_seq') into group_val;

        select  id
        into    ug_type
        from    rhnUserGroupType
        where   label = 'system_group_admin';

        insert into rhnUserGroup (
                id, name,
                description,
                max_members, group_type, org_id
        ) values (
                group_val, 'System Group Administrators',
                'System Group Administrators for Org ' || name_in,
                NULL, ug_type, new_org_id
        );


        select nextval('rhn_user_group_id_seq') into group_val;

        select  id
        into    ug_type
        from    rhnUserGroupType
        where   label = 'activation_key_admin';

        insert into rhnUserGroup (
                id, name,
                description,
                max_members, group_type, org_id
        ) values (
                group_val, 'Activation Key Administrators',
                'Activation Key Administrators for Org ' || name_in,
                NULL, ug_type, new_org_id
        );

        select nextval('rhn_user_group_id_seq') into group_val;

        select  id
        into    ug_type
        from    rhnUserGroupType
        where   label = 'channel_admin';

        insert into rhnUserGroup (
                id, name,
                description,
                max_members, group_type, org_id
        ) values (
                group_val, 'Channel Administrators',
                'Channel Administrators for Org ' || name_in,
                NULL, ug_type, new_org_id
        );

        -- there aren't any users yet, so we don't need to update
        -- rhnUserServerPerms
        insert into rhnServerGroup
                ( id, name, description, max_members, group_type, org_id )
                select nextval('rhn_server_group_id_seq'), sgt.name, sgt.name,
                        0, sgt.id, new_org_id
                from rhnServerGroupType sgt
                where sgt.label = 'sw_mgr_entitled';

        org_id_out := new_org_id;

	-- Returning the value of OUT parameter
        return org_id_out;

end;
$$
language plpgsql;


07070100000854000081B400000000000000000000000167AE1114000060A8000000000000000000000000000000000000007600000000susemanager-schema/upgrade/spacewalk-schema-2.4-to-spacewalk-schema-2.5/155-drop-provisioning-from-rhn_server_pkb.sql --
-- Copyright (c) 2008--2014 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--

-- create schema rhn_server;

--update pg_setting
update pg_settings set setting = 'rhn_server,' || setting where name = 'search_path';

    create or replace function system_service_level(
    	server_id_in in numeric,
	service_level_in in varchar
    ) returns numeric as $$
    declare
    ents cursor is 
      select label from rhnServerEntitlementView
      where server_id = server_id_in;

    retval numeric := 0;

    begin
         for ent in ents loop
            retval := rhn_entitlements.entitlement_grants_service (ent.label, service_level_in);
            if retval = 1 then
               return retval;
            end if;
         end loop;

         return retval;

    end$$ language plpgsql;

        
    create or replace function can_change_base_channel(server_id_in IN NUMERIC)
    returns numeric
    as $$
    declare
    	throwaway numeric;
    begin
    	-- the idea: if we get past this query, the server is
	-- neither sat nor proxy, so base channel is changeable

	select 1 into throwaway
	  from rhnServer S
	 where S.id = server_id_in
	   and not exists (select 1 from rhnSatelliteInfo SI where SI.server_id = S.id)
	   and not exists (select 1 from rhnProxyInfo PI where PI.server_id = S.id);

        if not found then
	    return 0;
        end if;
	   
	return 1;
    end$$ language plpgsql;
	        
    create or replace function set_custom_value(
    	server_id_in in numeric,
	user_id_in in numeric,
	key_label_in in varchar,
	value_in in varchar
    ) returns void
    as $$
    declare
    	key_id_val numeric;
    begin
    	select CDK.id into strict key_id_val
	  from rhnCustomDataKey CDK,
	       rhnServer S
	 where S.id = server_id_in
	   and S.org_id = CDK.org_id
	   and CDK.label = key_label_in;
	   
	begin
	    insert into rhnServerCustomDataValue (server_id, key_id, value, created_by, last_modified_by)
	    values (server_id_in, key_id_val, value_in, user_id_in, user_id_in);
	exception
	    when UNIQUE_VIOLATION
	    	then
		update rhnServerCustomDataValue
		   set value = value_in,
		       last_modified_by = user_id_in
		 where server_id = server_id_in
		   and key_id = key_id_val;		   
	end;

    end$$ language plpgsql;
    
    create or replace function bulk_set_custom_value(
    	key_label_in in varchar,
	value_in in varchar,
	set_label_in in varchar,
	set_uid_in in numeric
    )
    returns integer
    as $$
    declare
        i integer;
        server record;
    begin
        i := 0;
        for server in (
           SELECT user_id, label, element, element_two
	     FROM rhnSet
	    WHERE label = set_label_in
	      AND user_id = set_uid_in
	) loop
	    if rhn_server.system_service_level(server.element, 'management') = 1 then
	    	perform rhn_server.set_custom_value(server.element, set_uid_in, key_label_in, value_in);
            i := i + 1;
	    end if;
	end loop;
    return i;
    end$$ language plpgsql;

    create or replace function bulk_snapshot_tag(
    	org_id_in in numeric,
        tagname_in in varchar,
	set_label_in in varchar,
	set_uid_in in numeric
    ) returns void
    as $$
    declare
        server record;
    	snapshot_id numeric;
    begin
        for server in (
           SELECT user_id, label, element, element_two
	     FROM rhnSet
	    WHERE label = set_label_in
	      AND user_id = set_uid_in
	    ) loop
	    if rhn_server.system_service_level(server.element, 'management') = 1 then
	    	    select max(id) into snapshot_id
	    	    from rhnSnapshot
	    	    where server_id = server.element;

	    	    if snapshot_id is null then
		    	perform rhn_server.snapshot_server(server.element, 'tagging system:  ' || tagname_in);
			
			select max(id) into snapshot_id
			from rhnSnapshot
			where server_id = server.element;
		    end if;
		 
		-- now have a snapshot_id to work with...
		begin
		    perform rhn_server.tag_snapshot(snapshot_id, org_id_in, tagname_in);
		exception
		    when UNIQUE_VIOLATION
		    	then
			-- do nothing, be forgiving...
			null;
		end;
	    end if;
	end loop;    
    end$$ language plpgsql;

    create or replace function tag_delete(
    	server_id_in in numeric,
	tag_id_in in numeric
    ) returns void
    as $$
    declare
    	snapshots cursor is
		select	snapshot_id
		from	rhnSnapshotTag
		where	tag_id = tag_id_in;
	tag_id_tmp numeric;
    begin
    	select	id into tag_id_tmp
	from	rhnTag
	where	id = tag_id_in
	for update;

	delete
		from	rhnSnapshotTag
		where	server_id = server_id_in
			and tag_id = tag_id_in;
	for snapshot in snapshots loop
		return;
	end loop;
	delete
		from rhnTag
		where id = tag_id_in;
    end$$ language plpgsql;

    create or replace function tag_snapshot(
        snapshot_id_in in numeric,
	org_id_in in numeric,
	tagname_in in varchar
    ) returns void
    as $$
    begin
    	insert into rhnSnapshotTag (snapshot_id, server_id, tag_id)
	select snapshot_id_in, server_id, lookup_tag(org_id_in, tagname_in)
	from rhnSnapshot
	where id = snapshot_id_in;
    end$$ language plpgsql;

    create or replace function bulk_snapshot(
    	reason_in in varchar,
	set_label_in in varchar,
	set_uid_in in numeric
    ) returns void
    as $$
    declare
        server record;
    begin
        for server in (
           SELECT user_id, label, element, element_two
	     FROM rhnSet
	    WHERE label = set_label_in
	      AND user_id = set_uid_in
	    ) loop
	    if rhn_server.system_service_level(server.element, 'management') = 1 then
	    	perform rhn_server.snapshot_server(server.element, reason_in);
	    end if;
	end loop;
    end$$ language plpgsql;

    create or replace function snapshot_server(
    	server_id_in in numeric,
	reason_in in varchar
    ) returns void
    as $$
    declare
    	snapshot_id_v numeric;
	revisions cursor is
		select distinct
			cr.id
		from	rhnConfigRevision	cr,
			rhnConfigFileName	cfn,
			rhnConfigFile		cf,
			rhnConfigChannel	cc,
			rhnServerConfigChannel	scc
		where	1=1
			and scc.server_id = server_id_in
			and scc.config_channel_id = cc.id
			and cc.id = cf.config_channel_id
			and cf.id = cr.config_file_id
			and cr.id = cf.latest_config_revision_id
			and cf.config_file_name_id = cfn.id
			and cf.id = lookup_first_matching_cf(scc.server_id, cfn.path);
	locked integer;
    begin
    	select nextval('rhn_snapshot_id_seq') into snapshot_id_v;

	insert into rhnSnapshot (id, org_id, server_id, reason) (
		select	snapshot_id_v,
			s.org_id,
			server_id_in,
			reason_in
		from	rhnServer s
		where	s.id = server_id_in
	);
	insert into rhnSnapshotChannel (snapshot_id, channel_id) (
		select	snapshot_id_v, sc.channel_id
		from	rhnServerChannel sc
		where	sc.server_id = server_id_in
	);
	insert into rhnSnapshotServerGroup (snapshot_id, server_group_id) (
		select	snapshot_id_v, sgm.server_group_id
		from	rhnServerGroupMembers sgm
		where	sgm.server_id = server_id_in
	);
        locked := 0;
        <<iloop>>
        while true loop
            begin
                insert into rhnPackageNEVRA (id, name_id, evr_id, package_arch_id)
                select nextval('rhn_pkgnevra_id_seq'), sp.name_id, sp.evr_id, sp.package_arch_id
                from rhnServerPackage sp
                where sp.server_id = server_id_in
                        and not exists
                        (select 1
                                from rhnPackageNEVRA nevra
                                where nevra.name_id = sp.name_id
                                        and nevra.evr_id = sp.evr_id
                                        and (nevra.package_arch_id = sp.package_arch_id
                                            or (nevra.package_arch_id is null
                                                and sp.package_arch_id is null)));
                exit iloop;
            exception when unique_violation then
                if locked = 1 then
                    raise;
                else
                    lock table rhnPackageNEVRA in exclusive mode;
                    locked := 1;
                end if;
            end;
        end loop;
	insert into rhnSnapshotPackage (snapshot_id, nevra_id) (
                select distinct snapshot_id_v, nevra.id
                from    rhnServerPackage sp, rhnPackageNEVRA nevra
                where   sp.server_id = server_id_in
                        and nevra.name_id = sp.name_id
                        and nevra.evr_id = sp.evr_id
                        and (nevra.package_arch_id = sp.package_arch_id
                            or (nevra.package_arch_id is null
                                and sp.package_arch_id is null))
	);

	insert into rhnSnapshotConfigChannel ( snapshot_id, config_channel_id ) (
		select	snapshot_id_v, scc.config_channel_id
		from	rhnServerConfigChannel scc
		where	server_id = server_id_in
	);

	for revision in revisions loop
		insert into rhnSnapshotConfigRevision (
				snapshot_id, config_revision_id
			) values (
				snapshot_id_v, revision.id
			);
	end loop;
    end$$ language plpgsql;

    create or replace function remove_action(
    	server_id_in in numeric,
	action_id_in in numeric
    ) returns void
    as $$
    declare
    	-- this really wants "nulls last", but 8.1.7.3.0 sucks ass.
	-- instead, we make a local table that holds our
	-- list of ids with null prereqs.  There's surely a better way
	-- (an array instead of a table maybe?  who knows...)
	-- but I've got code to do this handy that I can look at ;)
    	chained_actions cursor is
                with recursive r(id, prerequisite) as (
			select	id, prerequisite
			from	rhnAction
			where id = action_id_in
		union all
			select	r1.id, r1.prerequisite
			from	rhnAction r1, r
			where r.id = r1.prerequisite
		)
		select * from r
		order by prerequisite desc;
	sessions cursor is
		select	s.id
		from	rhnKickstartSession s
		where	server_id_in in (s.old_server_id, s.new_server_id)
			and s.action_id = action_id_in
			and not exists (
				select	1
				from	rhnKickstartSessionState ss
				where	ss.id = s.state_id
					and ss.label in ('failed','complete')
			);
	chain_ends numeric[];
	i numeric;
	prereq numeric := 1;
    begin
	select	prerequisite
	into	prereq
	from	rhnAction
	where	id = action_id_in;

	if prereq is not null then
		perform rhn_exception.raise_exception('action_is_child');
	end if;

        chain_ends := '{}';
	i := 1;
	for action in chained_actions loop
		if action.prerequisite is null then
			chain_ends[i] := action.id;
			i := i + 1;
		else
			delete from rhnServerAction
				where server_id = server_id_in
				and action_id = action.id;
		end if;
	end loop;

	delete from rhnServerAction
		where server_id = server_id_in
		and action_id = any(chain_ends);

	for s in sessions loop
		update rhnKickstartSession
			set 	state_id = (
					select	id
					from	rhnKickstartSessionState
					where	label = 'failed'
				),
				action_id = null
			where	id = s.id;
		perform set_ks_session_history_message(s.id, 'failed', 'Kickstart cancelled due to action removal');
	end loop;
    end$$ language plpgsql;
   
    create or replace function check_user_access(server_id_in in numeric, user_id_in in numeric)
    returns numeric
    as $$
    declare
    	has_access numeric;
    begin
    	-- first check; if this returns no rows, then the server/user are in different orgs, and we bail
        select 1 into has_access
	  from rhnServer S,
	       web_contact wc
	 where wc.org_id = s.org_id
	   and s.id = server_id_in
	   and wc.id = user_id_in;

        if not found then
          return 0;
        end if;

	-- okay, so they're in the same org.  if we have an org admin, they get a free pass
    	if rhn_user.check_role(user_id_in, 'org_admin') = 1
	then
	    return 1;
	end if;
		   
    	select 1 into has_access
	  from rhnServerGroupMembers SGM,
	       rhnUserServerGroupPerms USG
	 where SGM.server_group_id = USG.server_group_id
	   and SGM.server_id = server_id_in
	   and USG.user_id = user_id_in;

        if not found then
          return 0;
        end if;
	   
	return 1;
    end$$ language plpgsql;

    -- *******************************************************************
    -- FUNCTION: can_server_consume_virt_slot
    -- Returns 1 if the server id is eligible to consume a virtual slot,
    --   else returns 0.
    -- Called by: insert_into_servergroup, delete_from_servergroup
    -- *******************************************************************
    create or replace function can_server_consume_virt_slot(server_id_in in numeric,
                                           group_type_in in varchar)
    returns numeric                                           
    as $$
    declare
        server_virt_slots cursor is
            select vi.VIRTUAL_SYSTEM_ID
            from
                rhnVirtualInstance vi
            where
                -- server id is a virtual instance
                vi.VIRTUAL_SYSTEM_ID = server_id_in
                -- server id's host is virt entitled
                and exists ( select 1
                     from rhnServerEntitlementView sev
                 where vi.HOST_SYSTEM_ID = sev.server_id
                 and sev.label in ('virtualization_host',
                                   'virtualization_host_platform') )
                -- server id's host also has the ent we want
                and exists ( select 1
                     from rhnServerEntitlementView sev2
                 where vi.HOST_SYSTEM_ID = sev2.server_id
                 and sev2.label = group_type_in );

    begin
        for server_virt_slot in server_virt_slots loop
            return 1;
        end loop;
        return 0;
    end$$ language plpgsql;


    create or replace function insert_into_servergroup (
		server_id_in in numeric,
		server_group_id_in in numeric
    ) returns void
    as $$
    declare
		used_slots numeric;
		max_slots numeric;
		org_id numeric;
		mgmt_available numeric;
		mgmt_upgrade numeric;
		mgmt_sgid numeric;
		prov_available numeric;
		prov_upgrade numeric;
		prov_sgid numeric;
		group_label varchar;
		group_type numeric;
	begin
		-- first, group_type = null, because it's easy...

		-- this will rowlock the servergroup we're trying to change;
		-- we probably need to lock the other one, but I think the chances
		-- of it being a real issue are very small for now...
		select	sg.group_type, sg.org_id, sg.current_members, sg.max_members
		into	group_type, org_id, used_slots, max_slots
		from	rhnServerGroup sg
		where	sg.id = server_group_id_in
		for update of sg;

		if group_type is null then
			if used_slots >= max_slots then
				perform rhn_exception.raise_exception('servergroup_max_members');
			end if;

			insert into rhnServerGroupMembers(
					server_id, server_group_id
				) values (
					server_id_in, server_group_id_in
				);
			update rhnServerGroup
				set current_members = current_members + 1
				where id = server_group_id_in;

			perform rhn_cache.update_perms_for_server_group(server_group_id_in);
			return;
		end if;

		-- now for group_type != null
		-- 
		select	label
		into	group_label
		from	rhnServerGroupType	sgt
		where	sgt.id = group_type;

		-- the naive easy path that gets hit most often and has to be quickest.
		if group_label in ('sw_mgr_entitled',
                           'enterprise_entitled',
                           'virtualization_host',
                           'virtualization_host_platform') then
			if used_slots >= max_slots and 
               (rhn_server.can_server_consume_virt_slot(server_id_in, group_label) != 1) 
               then
				perform rhn_exception.raise_exception('servergroup_max_members');
			end if;

			insert into rhnServerGroupMembers(
					server_id, server_group_id
				) values (
					server_id_in, server_group_id_in
				);

            -- Only update current members if the system in consuming a 
            -- physical slot.
            if rhn_server.can_server_consume_virt_slot(server_id_in, group_label) = 0 then
                update rhnServerGroup
                set current_members = current_members + 1
                where id = server_group_id_in;
            end if;                

			return;
		end if;
	end$$ language plpgsql;

	create or replace function insert_into_servergroup_maybe (
		server_id_in in numeric,
		server_group_id_in in numeric
	) returns numeric as $$ 
    declare
		retval numeric := 0;
		servergroups cursor is
			select	s.id	server_id,
					sg.id	server_group_id
			from	rhnServerGroup	sg,
					rhnServer		s
			where	s.id = server_id_in
				and sg.id = server_group_id_in
				and s.org_id = sg.org_id
				and not exists (
					select	1
					from	rhnServerGroupMembers sgm
					where	sgm.server_id = s.id
						and sgm.server_group_id = sg.id
				);
	begin
		for sgm in servergroups loop
			perform rhn_server.insert_into_servergroup(sgm.server_id, sgm.server_group_id);
			retval := retval + 1;
		end loop;
		return retval;
	end$$ language plpgsql;

	create or replace function insert_set_into_servergroup (
		server_group_id_in in numeric,
		user_id_in in numeric,
		set_label_in in varchar
	) returns void
        as $$
    declare
		servers cursor is
			select	st.element	id
			from	rhnSet		st
			where	st.user_id = user_id_in
				and st.label = set_label_in
				and exists (
					select	1
					from	rhnUserManagedServerGroups umsg
					where	umsg.server_group_id = server_group_id_in
						and umsg.user_id = user_id_in
					)
				and not exists (
					select	1
					from	rhnServerGroupMembers sgm
					where	sgm.server_id = st.element
						and sgm.server_group_id = server_group_id_in
				);
	begin
		for s in servers loop
			perform rhn_server.insert_into_servergroup(s.id, server_group_id_in);
		end loop;
	end$$ language plpgsql;
		
    create or replace function delete_from_servergroup (
    	server_id_in in numeric,
		server_group_id_in in numeric
    ) returns void
    as $$
    declare
        server_virt_groups cursor is
            select 1
            from rhnServerEntitlementVirtual sev
            where sev.server_id = server_id_in
            and sev.server_group_id = server_group_id_in;

		oid numeric;
		mgmt_sgid numeric;
		label varchar;
		group_type numeric;
	begin
			select	sg.group_type, sg.org_id
			into	group_type,	oid
			from	rhnServerGroupMembers	sgm,
					rhnServerGroup			sg
			where	sg.id = server_group_id_in
				and sg.id = sgm.server_group_id
				and sgm.server_id = server_id_in
			for update of sg;

			if not found then
				perform rhn_exception.raise_exception('server_not_in_group');
			end if;

		-- do group_type is null first
		if group_type is null then
			delete from rhnServerGroupMembers
				where server_group_id = server_group_id_in
				and	server_id = server_id_in;
			update rhnServerGroup
				set current_members = current_members - 1
				where id = server_group_id_in;
			perform rhn_cache.update_perms_for_server_group(server_group_id_in);
			return;
		end if;

		select	sgt.label
		into	label
		from	rhnServerGroupType sgt
		where	sgt.id = group_type;

		if label in ('sw_mgr_entitled',
                     'enterprise_entitled', 
                     'virtualization_host',
                     'virtualization_host_platform') then

            -- Only update current members if the system is consuming
            -- a physical slot.
            for server_virt_group in server_virt_groups loop                
                delete from rhnServerGroupMembers
                where server_group_id = server_group_id_in
                and	server_id = server_id_in;
                return;
            end loop;                

            delete from rhnServerGroupMembers
            where server_group_id = server_group_id_in
            and	server_id = server_id_in;

            update rhnServerGroup
            set current_members = current_members - 1
            where id = server_group_id_in;

		end if;
	end$$ language plpgsql;

	create or replace function delete_set_from_servergroup (
		server_group_id_in in numeric,
		user_id_in in numeric,
		set_label_in in varchar
	) returns void
        as $$	
        declare
		servergroups cursor is
			select	sgm.server_id, sgm.server_group_id
			from	rhnSet st,
					rhnServerGroupMembers sgm
			where	sgm.server_group_id = server_group_id_in
				and st.user_id = user_id_in
				and st.label = set_label_in
				and sgm.server_id = st.element
				and exists (
					select	1
					from	rhnUserManagedServerGroups usgp
					where	usgp.server_group_id = server_group_id_in
						and usgp.user_id = user_id_in
				);
	begin
		for sgm in servergroups loop
			perform rhn_server.delete_from_servergroup(sgm.server_id, server_group_id_in);
		end loop;
	end$$ language plpgsql;

	create or replace function clear_servergroup (
		server_group_id_in in numeric
	) returns void
        as $$
        declare
		servers cursor is
			select	sgm.server_id	id
			from	rhnServerGroupMembers sgm
			where	sgm.server_group_id = server_group_id_in;
	begin
		for s in servers loop
			perform rhn_server.delete_from_servergroup(s.id, server_group_id_in);
		end loop;
	end$$ language plpgsql;

	create or replace function delete_from_org_servergroups (
		server_id_in in numeric
	) returns void
        as $$
        declare
		servergroups cursor is
			select	sgm.server_group_id id
			from	rhnServerGroup sg,
					rhnServerGroupMembers sgm
			where	sgm.server_id = server_id_in
				and sgm.server_group_id = sg.id
				and sg.group_type is null;
	begin
		for sg in servergroups loop
			perform rhn_server.delete_from_servergroup(server_id_in, sg.id);
		end loop;
	end$$ language plpgsql;

	create or replace function get_ip_address (
		server_id_in in numeric
	) returns varchar as $$
        declare
		interfaces cursor is
			select	ni.name as name, na4.address as address
			from	rhnServerNetInterface ni,
			        rhnServerNetAddress4 na4
			where	server_id = server_id_in
                and ni.id = na4.interface_id
				and na4.address != '127.0.0.1';
		addresses cursor is
			select	ipaddr ip_addr
			from	rhnServerNetwork
			where	server_id = server_id_in
				and ipaddr != '127.0.0.1';
	begin
		for addr in addresses loop
			return addr.ip_addr;
		end loop;
		for iface in interfaces loop
			return iface.address;
		end loop;
		return NULL;
	end$$ language plpgsql;

    create or replace function update_needed_cache(
        server_id_in in numeric
	) returns void as $$
    declare
      update_lock numeric;
    begin
      select id into update_lock from rhnServer where id = server_id_in for update;
      delete from rhnServerNeededCache
        where server_id = server_id_in;
      insert into rhnServerNeededCache
             (server_id, errata_id, package_id, channel_id)
        (select distinct sp.server_id, x.errata_id, p.id, x.channel_id
           FROM (SELECT sp_sp.server_id, sp_sp.name_id,
		        sp_sp.package_arch_id, max(sp_pe.evr) AS max_evr
                   FROM rhnServerPackage sp_sp
                   join rhnPackageEvr sp_pe ON sp_pe.id = sp_sp.evr_id
                  GROUP BY sp_sp.server_id, sp_sp.name_id, sp_sp.package_arch_id) sp
           join rhnPackage p ON p.name_id = sp.name_id
           join rhnPackageEvr pe ON pe.id = p.evr_id AND sp.max_evr < pe.evr
           join rhnPackageUpgradeArchCompat puac
	            ON puac.package_arch_id = sp.package_arch_id
		    AND puac.package_upgrade_arch_id = p.package_arch_id
           join rhnServerChannel sc ON sc.server_id = sp.server_id
           join rhnChannelPackage cp ON cp.package_id = p.id
	            AND cp.channel_id = sc.channel_id
           left join (SELECT ep.errata_id, ce.channel_id, ep.package_id
                        FROM rhnChannelErrata ce
                        join rhnErrataPackage ep
			         ON ep.errata_id = ce.errata_id
			join rhnServerChannel sc_sc
			         ON sc_sc.channel_id = ce.channel_id
		       WHERE sc_sc.server_id = server_id_in) x
             ON x.channel_id = sc.channel_id AND x.package_id = cp.package_id
          where sp.server_id = server_id_in);
	end$$ language plpgsql;
-- restore the original setting
update pg_settings set setting = overlay( setting placing '' from 1 for (length('rhn_server')+1) ) where name = 'search_path';
07070100000855000081B400000000000000000000000167AE111400000467000000000000000000000000000000000000007A00000000susemanager-schema/upgrade/spacewalk-schema-2.4-to-spacewalk-schema-2.5/156-drop-provisioning-from-rhnEntitledServers.sql --
-- Copyright (c) 2008 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--

create or replace view
rhnEntitledServers
as
select distinct
    S.id,
    S.org_id,
    S.digital_server_id,
    S.server_arch_id,
    S.os,
    S.release,
    S.name,
    S.description,
    S.info,
    S.secret
from
    rhnServerGroup SG,
    rhnServerGroupType SGT,
    rhnServerGroupMembers SGM,
    rhnServer S
where
    S.id = SGM.server_id
and SG.id = SGM.server_group_id
and SGT.label IN ('sw_mgr_entitled', 'enterprise_entitled')
and SG.group_type = SGT.id
and SG.org_id = S.org_id
;

 07070100000856000081B400000000000000000000000167AE111400000B3C000000000000000000000000000000000000007300000000susemanager-schema/upgrade/spacewalk-schema-2.4-to-spacewalk-schema-2.5/157-create_first_org_remove_update_ent.sql    --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
-- This creates an org with ID of 1, and errors if there already is one
--

create or replace function
create_first_org
(
	name_in in varchar,
	password_in in varchar
)
returns void as
$$
declare
	ug_type			numeric;
	group_val		numeric;
begin
	insert into web_customer (
		id, name
	) values (
		1, name_in
	);

	select nextval( 'rhn_user_group_id_seq' ) into group_val from dual;

	select	id
	into	ug_type
	from	rhnUserGroupType
	where	label = 'org_admin';

	insert into rhnUserGroup (
		id, name,
		description,
		max_members, group_type, org_id
	) values (
		group_val, 'Organization Administrators',
		'Organization Administrators for Org ' || name_in || ' (1)',
		NULL, ug_type, 1
	);

	select nextval('rhn_user_group_id_seq') into group_val from dual;

	select	id
	into	ug_type
	from	rhnUserGroupType
	where	label = 'system_group_admin';

	insert into rhnUserGroup (
		id, name,
		description,
		max_members, group_type, org_id
	) values (
		group_val, 'System Group Administrators',
		'System Group Administrators for Org ' || name_in || ' (1)',
		NULL, ug_type, 1
	);


	select nextval('rhn_user_group_id_seq') into group_val from dual;

	select	id
	into	ug_type
	from	rhnUserGroupType
	where	label = 'activation_key_admin';

	insert into rhnUserGroup (
		id, name,
		description,
		max_members, group_type, org_id
	) values (
		group_val, 'Activation Key Administrators',
		'Activation Key Administrators for Org ' || name_in || ' (1)',
		NULL, ug_type, 1
	);

	select nextval('rhn_user_group_id_seq') into group_val from dual;

	select	id
	into	ug_type
	from	rhnUserGroupType
	where	label = 'channel_admin';

	insert into rhnUserGroup (
		id, name,
		description,
		max_members, group_type, org_id
	) values (
		group_val, 'Channel Administrators',
		'Channel Administrators for Org ' || name_in || ' (1)',
		NULL, ug_type, 1
	);

	select nextval('rhn_user_group_id_seq') into group_val from dual;

	select	id
	into	ug_type
	from	rhnUserGroupType
	where	label = 'satellite_admin';

	insert into rhnUserGroup (
		id, name,
		description,
		max_members, group_type, org_id
	) values (
		group_val, 'Satellite Administrators',
		'Satellite Administrators for Org ' || name_in || ' (1)',
		NULL, ug_type, 1
	);

end
$$ language plpgsql;

07070100000857000081B400000000000000000000000167AE111400000D27000000000000000000000000000000000000007100000000susemanager-schema/upgrade/spacewalk-schema-2.4-to-spacewalk-schema-2.5/158-create_new_org_remove_update_ent.sql  --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--

create or replace function create_new_org
(
        name_in      in varchar,
        password_in  in varchar
        --org_id_out   out NUMERIC
) returns numeric
as
$$
declare
        ug_type                 numeric;
        group_val               numeric;
        new_org_id              numeric;
        org_id_out		numeric;
begin

        select nextval('web_customer_id_seq') into new_org_id;

        insert into web_customer (
                id, name
        ) values (
                new_org_id, name_in
        );

        select nextval('rhn_user_group_id_seq') into group_val;

        select  id
        into    ug_type
        from    rhnUserGroupType
        where   label = 'org_admin';

        insert into rhnUserGroup (
                id, name,
                description,
                max_members, group_type, org_id
        ) values (
                group_val, 'Organization Administrators',
                'Organization Administrators for Org ' || name_in,
                NULL, ug_type, new_org_id
        );

        select nextval('rhn_user_group_id_seq') into group_val;

        select  id
        into    ug_type
        from    rhnUserGroupType
        where   label = 'system_group_admin';

        insert into rhnUserGroup (
                id, name,
                description,
                max_members, group_type, org_id
        ) values (
                group_val, 'System Group Administrators',
                'System Group Administrators for Org ' || name_in,
                NULL, ug_type, new_org_id
        );


        select nextval('rhn_user_group_id_seq') into group_val;

        select  id
        into    ug_type
        from    rhnUserGroupType
        where   label = 'activation_key_admin';

        insert into rhnUserGroup (
                id, name,
                description,
                max_members, group_type, org_id
        ) values (
                group_val, 'Activation Key Administrators',
                'Activation Key Administrators for Org ' || name_in,
                NULL, ug_type, new_org_id
        );

        select nextval('rhn_user_group_id_seq') into group_val;

        select  id
        into    ug_type
        from    rhnUserGroupType
        where   label = 'channel_admin';

        insert into rhnUserGroup (
                id, name,
                description,
                max_members, group_type, org_id
        ) values (
                group_val, 'Channel Administrators',
                'Channel Administrators for Org ' || name_in,
                NULL, ug_type, new_org_id
        );

        org_id_out := new_org_id;

	-- Returning the value of OUT parameter
        return org_id_out;

end;
$$
language plpgsql;


 07070100000858000081B400000000000000000000000167AE11140000872F000000000000000000000000000000000000006500000000susemanager-schema/upgrade/spacewalk-schema-2.4-to-spacewalk-schema-2.5/160-rhn_entitlements.pkb.sql  --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

-- create schema rhn_entitlements;

-- setup search_path so that these functions are created in appropriate schema.
update pg_settings set setting = 'rhn_entitlements,' || setting where name = 'search_path';

   create or replace function find_compatible_sg (
      server_id_in in numeric,
      type_label_in in varchar
   )
   returns numeric
as $$
    declare
      servergroups cursor for
         select sg.id
           from rhnServerGroupType             sgt,
                rhnServerGroup                 sg,
                rhnServer                     s,
                rhnServerServerGroupArchCompat ssgac
          where s.id = server_id_in
            and s.org_id = sg.org_id
            and sgt.label = type_label_in
            and sg.group_type = sgt.id
            and ssgac.server_group_type = sgt.id
            and ssgac.server_arch_id = s.server_arch_id
            and not exists (
                     select 1
                      from rhnServerGroupMembers sgm
                     where sgm.server_group_id = sg.id
                       and sgm.server_id = s.id);


   begin
      for servergroup in servergroups loop
         return servergroup.id;
      end loop;

      --no servergroup found
      return NULL;
   end$$
language plpgsql;

    -- *******************************************************************
    -- PROCEDURE: remove_org_entitlements
    --
    -- Removes both system entitlements and channel subscriptions
    -- that are currently assigned to an org and re-assigns to the
    -- master org (org_id = 1).
    --
    -- When we call this we expect everything to already be unentitled
    -- which shoul be handled by delete_org.
    --
    -- Called by: delete_org
    -- *******************************************************************
    create or replace function remove_org_entitlements (
        org_id_in numeric
    ) returns void
as $$
    declare
        system_ents cursor for
        select sg.id, sg.max_members, sg.group_type
        from rhnServerGroup sg
        where group_type is not null
          and org_id = org_id_in;

    begin

        for system_ent in system_ents loop
            update rhnServerGroup
            set max_members = max_members + system_ent.max_members
            where org_id = 1
              and group_type = system_ent.group_type;
        end loop;

        update rhnServerGroup
        set max_members = 0
        where org_id = org_id_in;

    end$$
language plpgsql;

    create or replace function entitlement_grants_service (
        entitlement_in in varchar,
        service_level_in in varchar
    ) returns numeric
as $$
    begin
        if service_level_in = 'management' then
            if entitlement_in = 'enterprise_entitled' then
                return 1;
            else
                return 0;
            end if;
        elsif service_level_in = 'updates' then
            return 1;
        else
            return 0;
        end if;
    end$$
language plpgsql;

   create or replace function can_entitle_server (
      server_id_in   in numeric,
      type_label_in  in varchar
   )
   returns numeric
as $$
    declare
      addon_servergroups cursor (base_label_in varchar,
                                 addon_label_in varchar) for
         select
            addon_id
         from
            rhnSGTypeBaseAddonCompat
         where base_id = lookup_sg_type (base_label_in)
           and addon_id = lookup_sg_type (addon_label_in);

      previous_ent        varchar[];
      is_base_in          char   := 'N';
      is_base_current     char   := 'N';
      i                   numeric := 0;
      sgid                numeric := 0;

   begin

      previous_ent := rhn_entitlements.get_server_entitlement(server_id_in);

      select distinct is_base
      into is_base_in
      from rhnServerGroupType
      where label = type_label_in;

      if array_upper(previous_ent, 1) is null or array_upper(previous_ent, 1) = 0 then
         if is_base_in = 'Y' then
            sgid := rhn_entitlements.find_compatible_sg (server_id_in, type_label_in);
            if sgid is not null then
              -- rhn_server.insert_into_servergroup (server_id_in, sgid);
              return 1;
            else
              -- rhn_exception.raise_exception ('invalid_base_entitlement');
              return 0;
            end if;
         else
            -- rhn_exception.raise_exception ('invalid_base_entitlement');
            return 0;
         end if;

      -- there are previous ents, first make sure we're not trying to entitle a base ent
      elsif is_base_in = 'Y' then
         -- rhn_exception.raise_exception ('invalid_addon_entitlement');
         return 0;

      -- it must be an addon, so proceed with the entitlement
      else

         -- find the servers base ent
         is_base_current := 'N';
         i := 0;
         while is_base_current = 'N' and i < array_upper(previous_ent, 1)
         loop
            i := i + 1;
            select is_base
            into is_base_current
            from rhnServerGroupType
            where label = previous_ent[i];
         end loop;

         -- never found a base ent, that would be strange
         if is_base_current  = 'N' then
            -- rhn_exception.raise_exception ('invalid_base_entitlement');
            return 0;
         end if;

         -- this for loop verifies the validity of the addon path
         for addon_servergroup in addon_servergroups  (previous_ent[i], type_label_in) loop
            -- find an appropriate sgid for the addon and entitle the server
            sgid := rhn_entitlements.find_compatible_sg (server_id_in, type_label_in);
            if sgid is not null then
               -- rhn_server.insert_into_servergroup (server_id_in, sgid);
               return 1;
            else
               -- rhn_exception.raise_exception ('invalid_addon_entitlement');
               return 0;
            end if;
         end loop;

      end if;

      return 0;

   end$$
language plpgsql;

   create or replace function can_switch_base (
      server_id_in   in    integer,
      type_label_in  in    varchar
   )
   returns numeric
as $$
   declare
      type_label_in_is_base   char(1);
      sgid                    numeric;

   begin

       select is_base into type_label_in_is_base
       from rhnServerGroupType
       where label = type_label_in;

       if not found then
          perform rhn_exception.raise_exception ( 'invalid_entitlement' );
       end if;

      if type_label_in_is_base = 'N' then
         perform rhn_exception.raise_exception ( 'invalid_entitlement' );
      else
         sgid := rhn_entitlements.find_compatible_sg ( server_id_in,
                                                       type_label_in );
         if sgid is not null then
           return 1;
         else
           return 0;
         end if;
      end if;

   end$$
language plpgsql;

    -- workaround: dropping the function - in past default arg. values were
    -- changed and postgres doesn't like it (ERROR: cannot remove parameter
    -- defaults from existing function)
    drop function if exists entitle_server(numeric, varchar);

    create or replace function entitle_server (
        server_id_in in numeric,
        type_label_in in varchar
    ) returns void
as $$
    declare
      sgid  numeric := 0;
      is_virt numeric := 0;

    begin

      select 1 into is_virt
        from rhnServerEntitlementView
        where server_id = server_id_in
          and label = 'virtualization_host';

      if not found then
          is_virt := 0;
      end if;

      if is_virt = 0 and type_label_in = 'virtualization_host' then
        is_virt := 1;
      end if;

      if rhn_entitlements.can_entitle_server(server_id_in,
                                             type_label_in) = 1 then
         sgid := rhn_entitlements.find_compatible_sg (server_id_in,
                                                      type_label_in);
         if sgid is not null then
            insert into rhnServerHistory ( id, server_id, summary, details )
            values ( nextval('rhn_event_id_seq'), server_id_in,
                     'added system entitlement ',
                      case type_label_in
                       when 'enterprise_entitled' then 'Management'
                       when 'virtualization_host' then 'Virtualization'
                      end  );

            perform rhn_server.insert_into_servergroup (server_id_in, sgid);

            if is_virt = 1 then
              perform rhn_entitlements.repoll_virt_guest_entitlements(server_id_in);
            end if;

         else
            perform rhn_exception.raise_exception ('no_available_server_group');
         end if;
      else
         perform rhn_exception.raise_exception ('invalid_entitlement');
      end if;
   end$$
language plpgsql;

    -- workaround: dropping the function - in past default arg. values were
    -- changed and postgres doesn't like it (ERROR: cannot remove parameter
    -- defaults from existing function)
    drop function if exists remove_server_entitlement(numeric, varchar, numeric);

    create or replace function remove_server_entitlement (
        server_id_in in numeric,
        type_label_in in varchar,
        repoll_virt_guests in numeric default 1
    ) returns void
as $$
    declare
      group_id numeric;
      type_is_base char;
      is_virt numeric := 0;
    begin
      -- would be nice if there were a virt attribute of entitlement types, not have to specify 2 different ones...
        select 1 into is_virt
          from rhnServerEntitlementView
          where server_id = server_id_in
            and label = 'virtualization_host';
        if not found then
            is_virt := 0;
        end if;

        select  sg.id, sgt.is_base
        into group_id, type_is_base
        from    rhnServerGroupType sgt,
            rhnServerGroup sg,
                rhnServerGroupMembers sgm,
                rhnServer s
        where   s.id = server_id_in
            and s.id = sgm.server_id
            and sgm.server_group_id = sg.id
            and sg.org_id = s.org_id
            and sgt.label = type_label_in
            and sgt.id = sg.group_type;

        if not found then
          perform rhn_exception.raise_exception('invalid_server_group_member');
        end if;

      if ( type_is_base = 'Y' ) then
         -- unentitle_server should handle everything, don't really need to do anything else special here
         perform rhn_entitlements.unentitle_server ( server_id_in );
      else

         insert into rhnServerHistory ( id, server_id, summary, details )
         values ( nextval('rhn_event_id_seq'), server_id_in,
                  'removed system entitlement ',
                   case type_label_in
                    when 'enterprise_entitled' then 'Management'
                    when 'virtualization_host' then 'Virtualization'
                   end  );

         perform rhn_server.delete_from_servergroup(server_id_in, group_id);

         if is_virt = 1 and repoll_virt_guests = 1 then
           perform rhn_entitlements.repoll_virt_guest_entitlements(server_id_in);
         end if;
      end if;

    end$$
language plpgsql;

    create or replace function unentitle_server (
        server_id_in in numeric
    ) returns void
as $$
    declare
      servergroups cursor for
         select distinct sgt.label, sg.id server_group_id
         from  rhnServerGroupType sgt,
               rhnServerGroup sg,
               rhnServer s,
               rhnServerGroupMembers sgm
         where s.id = server_id_in
            and s.org_id = sg.org_id
            and sg.group_type = sgt.id
            and sgm.server_group_id = sg.id
            and sgm.server_id = s.id;

     is_virt numeric := 0;

   begin

      select 1 into is_virt
        from rhnServerEntitlementView
        where server_id = server_id_in
         and label = 'virtualization_host';

      if not found then
          is_virt := 0;
      end if;

      for servergroup in servergroups loop

         insert into rhnServerHistory ( id, server_id, summary, details )
         values ( nextval('rhn_event_id_seq'), server_id_in,
                  'removed system entitlement ',
                   case servergroup.label
                    when 'enterprise_entitled' then 'Management'
                    when 'virtualization_host' then 'Virtualization'
                   end  );

         perform rhn_server.delete_from_servergroup(server_id_in,
                                            servergroup.server_group_id );
      end loop;

      if is_virt = 1 then
        perform rhn_entitlements.repoll_virt_guest_entitlements(server_id_in);
      end if;

   end$$
language plpgsql;


    -- *******************************************************************
    -- PROCEDURE: repoll_virt_guest_entitlements
    --
    --   Whenever we add/remove a virtualization_host* entitlement from
    --   a host, we can call this procedure to update what type of slots
    --   the guests are consuming.
    --
    --   If you're removing the entitlement, it's
    --   possible the guests will become unentitled if you don't have enough
    --   physical slots to cover them.
    --
    --   If you're adding the entitlement, you end up freeing up physical
    --   slots for other systems.
    --
    -- *******************************************************************
    create or replace function repoll_virt_guest_entitlements(
        server_id_in in numeric
    ) returns void
as $$
    declare
        -- All of server group types associated with the guests of
        -- server_id_in
        group_types cursor for
            select distinct sg.group_type, sgt.label, sg.org_id
            from
                rhnServerGroupType sgt,
                rhnServerGroup sg,
                rhnServerGroupMembers sgm,
                rhnVirtualInstance vi
            where
                vi.host_system_id = server_id_in
                and vi.virtual_system_id = sgm.server_id
                and sgm.server_group_id = sg.id
                and sg.group_type = sgt.id;

        -- Virtual servers from a certain family belonging to a specific
        -- host that are consuming physical system slots over the limit.
        virt_servers_sgt cursor(group_type_in numeric, quantity_in numeric) for
                select vi.virtual_system_id
                from
                    rhnServerGroup sg,
                    rhnServerGroupMembers sgm,
                    rhnVirtualInstance vi
                where
                    vi.host_system_id = server_id_in
                    and vi.virtual_system_id = sgm.server_id
                    and sgm.server_group_id = sg.id
                    and sg.group_type = group_type_in
                order by sgm.modified desc
                limit quantity_in;

        org_id_val numeric;
        max_members_val numeric;
        max_flex_val numeric;
        current_members_calc numeric;
        sg_id numeric;
        is_virt numeric := 0;
        free_slots numeric := 0;
    begin
          select 1 into is_virt
                from rhnServerEntitlementView
           where server_id = server_id_in
                 and label = 'virtualization_host';

      if not found then
          is_virt := 0;
      end if;

        select org_id
        into org_id_val
        from rhnServer
        where id = server_id_in;

        for a_group_type in group_types loop
          -- get the current *physical* members of the system entitlement type for the org...
          --
          -- unlike channel families, it appears the standard rhnServerGroup.max_members represents
          -- *physical* slots, vs physical+virt ... boy that's confusing...

          select max_members, id
            into max_members_val, sg_id
            from rhnServerGroup
            where group_type = a_group_type.group_type
            and org_id = a_group_type.org_id;


      select count(sep.server_id) into current_members_calc
            from rhnServerEntitlementPhysical sep
           where sep.server_group_id = sg_id
             and sep.server_group_type_id = a_group_type.group_type;

          if current_members_calc > max_members_val then
            -- A virtualization_host* ent must have been removed, and we're over the limit, so unsubscribe guests
            for virt_server in virt_servers_sgt(a_group_type.group_type,
                                                current_members_calc - max_members_val) loop
              perform rhn_entitlements.remove_server_entitlement(virt_server.virtual_system_id, a_group_type.label);

              -- decrement current_members_calc, we'll use it to reset current_members for the group at the end...
              current_members_calc := current_members_calc - 1;
            end loop;

          end if;

          update rhnServerGroup set current_members = current_members_calc
           where org_id = a_group_type.org_id
             and group_type = a_group_type.group_type;

          -- I think that's all the house-keeping we have to do...
        end loop;

    end$$
language plpgsql;

    create or replace function get_server_entitlement (
        server_id_in in numeric
    ) returns varchar[]
as $$
    declare
        server_groups cursor for
            select  sgt.label
            from    rhnServerGroupType      sgt,
                    rhnServerGroup          sg,
                    rhnServerGroupMembers   sgm
            where   1=1
                and sgm.server_id = server_id_in
                and sg.id = sgm.server_group_id
                and sgt.id = sg.group_type
                and sgt.label in (
                    'enterprise_entitled',
                    'virtualization_host'
                    );

         ent_array varchar[];

    begin

      ent_array := '{}';

      for sg in server_groups loop
         ent_array := ent_array || sg.label;
      end loop;

      return ent_array;

    end$$
language plpgsql;

    -- this desperately needs to be table driven.
    create or replace function modify_org_service (
        org_id_in in numeric,
        service_label_in in varchar,
        enable_in in char
    ) returns void
as $$
    declare
        roles_to_process varchar[];
        roles cursor(role_label_in varchar) for
            select  label, id
            from    rhnUserGroupType
            where   label = role_label_in;
        org_roles cursor(role_label_in varchar) for
            select  1
            from    rhnUserGroup ug,
                    rhnUserGroupType ugt
            where   ugt.label = role_label_in
                and ug.org_id = org_id_in
                and ugt.id = ug.group_type;

        ents_to_process varchar[];
        ents cursor(ent_label_in varchar) for
            select  label, id
            from    rhnOrgEntitlementType
            where   label = ent_label_in;
        org_ents cursor(ent_label_in varchar) for
            select  1
            from    rhnOrgEntitlements oe,
                    rhnOrgEntitlementType oet
            where   oet.label = ent_label_in
                and oe.org_id = org_id_in
                and oet.id = oe.entitlement_id;
        create_row char(1);
    begin
        ents_to_process := '{}';
        roles_to_process := '{}';
        -- a bit kludgy, but only for 3.4 really.  Certainly no
        -- worse than the old code...
        if service_label_in = 'enterprise' or
           service_label_in = 'management' then
            ents_to_process := array_append(ents_to_process, 'sw_mgr_enterprise');

            roles_to_process := array_append(roles_to_process, 'org_admin');

            roles_to_process := array_append(roles_to_process, 'system_group_admin');

            roles_to_process := array_append(roles_to_process, 'activation_key_admin');
        elsif service_label_in = 'virtualization' then
            ents_to_process := array_append(ents_to_process, 'rhn_virtualization');

            roles_to_process := array_append(roles_to_process, 'config_admin');
        end if;

        if enable_in = 'Y' then
            for i in 1..array_upper(ents_to_process, 1) loop
                for ent in ents(ents_to_process[i]) loop
                    create_row := 'Y';
                    for oe in org_ents(ent.label) loop
                        create_row := 'N';
                    end loop;
                    if create_row = 'Y' then
                        insert into rhnOrgEntitlements(org_id, entitlement_id)
                            values (org_id_in, ent.id);
                    end if;
                end loop;
            end loop;
            for i in 1..array_upper(roles_to_process, 1) loop
                for role in roles(roles_to_process[i]) loop
                    create_row := 'Y';
                    for o_r in org_roles(role.label) loop
                        create_row := 'N';
                    end loop;
                    if create_row = 'Y' then
                        insert into rhnUserGroup(
                                id, name, description, current_members,
                                group_type, org_id
                            ) (
                                select  nextval('rhn_user_group_id_seq'),
                                        ugt.name || 's',
                                        ugt.name || 's for Org ' ||
                                            o.name || ' ('|| o.id ||')',
                                        0, ugt.id, o.id
                                from    rhnUserGroupType ugt,
                                        web_customer o
                                where   o.id = org_id_in
                                    and ugt.id = role.id
                            );
                    end if;
                end loop;
            end loop;
        else
            for i in 1..coalesce(array_upper(ents_to_process, 1), 0) loop
                for ent in ents(ents_to_process[i]) loop
                    delete from rhnOrgEntitlements
                     where org_id = org_id_in
                       and entitlement_id = ent.id;
                end loop;
            end loop;
        end if;
    end$$
language plpgsql;

    create or replace function set_customer_enterprise (
        customer_id_in in numeric
    ) returns void
as $$
    begin
        perform rhn_entitlements.modify_org_service(customer_id_in, 'enterprise', 'Y');
    end$$
language plpgsql;

    create or replace function unset_customer_enterprise (
        customer_id_in in numeric
    ) returns void
as $$
    begin
        perform rhn_entitlements.modify_org_service(customer_id_in, 'enterprise', 'N');
    end$$
language plpgsql;

    -- *******************************************************************
    -- PROCEDURE: prune_group
    -- Unsubscribes servers consuming physical slots that over the org's
    --   limit.
    -- Called by: set_server_group_count, repoll_virt_guest_entitlements
    -- *******************************************************************
    create or replace function prune_group (
        group_id_in in numeric,
        quantity_in in numeric
    ) returns void
as $$
    declare
        sgrecord record;
      type_is_base char;
    begin
            update      rhnServerGroup
                set     max_members = quantity_in
                where   id = group_id_in;

            for sgrecord in (
		   select  server_id, server_group_id, sgt.id as group_type_id, sgt.label
		    from    rhnServerGroupType              sgt,
				    rhnServerGroup                  sg,
				    rhnServerGroupMembers   sgm
		    where   1=1
			    and sgm.server_group_id = group_id_in
			    and sgm.server_id in (
				    select  sep.server_id
				    from
					rhnServerEntitlementPhysical sep
				    where
					sep.server_group_id = group_id_in
				    order by sep.modified asc
				    offset quantity_in
				)
			    and sgm.server_group_id = sg.id
			    and sg.group_type = sgt.id
	    ) loop
                perform rhn_entitlements.remove_server_entitlement(sgrecord.server_id, sgrecord.label);

            select is_base
            into type_is_base
            from rhnServerGroupType sgt
            where sgt.id = sgrecord.group_type_id;

            -- if we're removing a base ent, then be sure to
            -- remove the server's channel subscriptions.
            if ( type_is_base = 'Y' ) then
                   perform rhn_channel.clear_subscriptions(sgrecord.server_id, 0);
            end if;

            end loop;
    end$$
language plpgsql;

    -- *******************************************************************
    -- PROCEDURE: assign_system_entitlement
    --
    -- Moves system entitlements from from_org_id_in to to_org_id_in.
    -- Can raise not_enough_entitlements_in_base_org if from_org_id_in
    -- does not have enough entitlements to cover the move.
    -- Takes care of unentitling systems if necessary by calling
    -- set_server_group_count
    -- *******************************************************************
    create or replace function assign_system_entitlement(
        group_label_in in varchar,
        from_org_id_in in numeric,
        to_org_id_in in numeric,
        quantity_in in numeric
    ) returns void
as $$
    declare
        prev_ent_count numeric;
    to_org_prev_ent_count numeric;
        new_ent_count numeric;
    new_quantity numeric;
        group_type numeric;
    begin

            select max_members
            into prev_ent_count
            from rhnServerGroupType sgt,
                 rhnServerGroup sg
            where sg.org_id = from_org_id_in
              and sg.group_type = sgt.id
              and sgt.label = group_label_in;

            if not found then
                perform rhn_exception.raise_exception(
                              'not_enough_entitlements_in_base_org');
            end if;

            select max_members
            into to_org_prev_ent_count
            from rhnServerGroupType sgt,
                 rhnServerGroup sg
            where sg.org_id = to_org_id_in
              and sg.group_type = sgt.id
              and sgt.label = group_label_in;

            if not found then
                to_org_prev_ent_count := 0;
            end if;

            select id
            into group_type
            from rhnServerGroupType
            where label = group_label_in;

            if not found then
                perform rhn_exception.raise_exception(
                              'invalid_server_group');
            end if;

        new_ent_count := prev_ent_count - quantity_in;

        if prev_ent_count > new_ent_count then
            new_quantity := to_org_prev_ent_count + quantity_in;
        end if;

        if new_ent_count < 0 then
            perform rhn_exception.raise_exception(
                          'not_enough_entitlements_in_base_org');
        end if;


        perform rhn_entitlements.set_server_group_count(from_org_id_in,
                                         group_type,
                                         new_ent_count);

        perform rhn_entitlements.set_server_group_count(to_org_id_in,
                                         group_type,
                                         new_quantity);

        -- Create or delete the entries in rhnOrgEntitlementType
        if group_label_in = 'enterprise_entitled' then
            if new_quantity > 0 then
                perform rhn_entitlements.set_customer_enterprise(to_org_id_in);
            else
                perform rhn_entitlements.unset_customer_enterprise(to_org_id_in);
            end if;
        end if;

    end$$
language plpgsql;

    -- *******************************************************************
    -- PROCEDURE: activate_system_entitlement
    --
    -- Sets the values in rhnServerGroup for a given rhnServerGroupType.
    --
    -- Calls: set_server_group_count to update, prune, or create the group.
    -- Called by: the code that activates a satellite cert.
    --
    -- Raises not_enough_entitlements_in_base_org if all entitlements
    -- in the org are used so the free entitlements would not cover
    -- the difference when descreasing the number of entitlements.
    -- *******************************************************************
    create or replace function activate_system_entitlement(
        org_id_in in numeric,
        group_label_in in varchar,
        quantity_in in numeric
    ) returns void
as $$
    declare
        prev_ent_count numeric;
        prev_ent_count_sum numeric;
        group_type numeric;
    begin

        -- Fetch the current entitlement count for the org
        -- into prev_ent_count

            select current_members
            into prev_ent_count
            from rhnServerGroupType sgt,
                 rhnServerGroup sg
            where sg.group_type = sgt.id
              and sgt.label = group_label_in
              and sg.org_id = org_id_in;

            if not found then
                prev_ent_count := 0;
            end if;

            select id
            into group_type
            from rhnServerGroupType
            where label = group_label_in;

            if not found then
                perform rhn_exception.raise_exception(
                              'invalid_server_group');
            end if;

        -- If we're setting the total entitlemnt count to a lower value,
        -- and that value is less than the allocated count in this org,
        -- we need to raise an exception.
        if quantity_in < prev_ent_count then
            perform rhn_exception.raise_exception(
                          'not_enough_entitlements_in_base_org');
        else
            -- don't update family counts after every server
            -- will do bulk update afterwards
            perform rhn_entitlements.set_server_group_count(org_id_in,
                                             group_type,
                                             quantity_in);
        end if;

    end$$
language plpgsql;


    create or replace function set_server_group_count (
        customer_id_in in numeric,  -- customer_id
        group_type_in in numeric,   -- rhn[User|Server]GroupType.id
        quantity_in in numeric      -- quantity
    ) returns void
as $$
    declare
        group_id numeric;
        quantity numeric;
        wasfound boolean;
    begin
        quantity := quantity_in;
        if quantity is not null and quantity < 0 then
            quantity := 0;
        end if;

        select  rsg.id
        into    group_id
        from    rhnServerGroup rsg
        where   1=1
            and rsg.org_id = customer_id_in
            and rsg.group_type = group_type_in;

        -- preserve the not found status across the rhn_entitlements.prune_group invocation
        wasfound := true;
        if not found then
            wasfound := false;
        end if;

        perform rhn_entitlements.prune_group(
            group_id,
            quantity
        );

        if not wasfound then
            insert into rhnServerGroup (
                    id, name, description, max_members, current_members,
                    group_type, org_id, created, modified
                ) (
                    select  nextval('rhn_server_group_id_seq'), name, name,
                            quantity, 0, id, customer_id_in,
                            current_timestamp, current_timestamp
                    from    rhnServerGroupType
                    where   id = group_type_in
            );
        end if;

    end$$
language plpgsql;

    -- this expects quantity_in to be the number of available slots, not the
    -- max_members of the server group.  If you give it too many, it'll fail
    -- and raise servergroup_max_members.
    -- We should NEVER run this unless we're SURE that we won't
    -- be violating the max.
    create or replace function entitle_last_modified_servers (
        customer_id_in in numeric,  -- customer_id
        type_label_in in varchar,   -- 'enterprise_entitled'
        quantity_in in numeric      -- 3
    ) returns void
as $$
    declare
        -- find the servers that aren't currently in slots
        servers cursor(cid_in numeric, quant_in numeric) for
                                    select  rs.id as server_id
                                    from    rhnServer rs
                                    where   1=1
                                        and rs.org_id = cid_in
                                        and not exists (
                                            select  1
                                            from    rhnServerGroup sg,
                                                    rhnServerGroupMembers rsgm
                                            where   rsgm.server_id = rs.id
                                                and rsgm.server_group_id = sg.id
                                                and sg.group_type is not null
                                        )
                                        and not exists (
                                            select 1
                                            from rhnVirtualInstance vi
                                            where vi.virtual_system_id =
                                                  rs.id
                                        )
                                    order by modified desc
                                    limit quant_in;
    begin
        for server in servers(customer_id_in, quantity_in) loop
            perform rhn_entitlements.entitle_server(server.server_id, type_label_in);
        end loop;
    end$$
language plpgsql;

-- restore the original setting
update pg_settings set setting = overlay( setting placing '' from 1 for (length('rhn_entitlements')+1) ) where name = 'search_path';
 07070100000859000081B400000000000000000000000167AE111400005FF6000000000000000000000000000000000000005F00000000susemanager-schema/upgrade/spacewalk-schema-2.4-to-spacewalk-schema-2.5/161-rhn_server.pkb.sql    --
-- Copyright (c) 2008--2014 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--

-- create schema rhn_server;

--update pg_setting
update pg_settings set setting = 'rhn_server,' || setting where name = 'search_path';

    create or replace function system_service_level(
    	server_id_in in numeric,
	service_level_in in varchar
    ) returns numeric as $$
    declare
    ents cursor is 
      select label from rhnServerEntitlementView
      where server_id = server_id_in;

    retval numeric := 0;

    begin
         for ent in ents loop
            retval := rhn_entitlements.entitlement_grants_service (ent.label, service_level_in);
            if retval = 1 then
               return retval;
            end if;
         end loop;

         return retval;

    end$$ language plpgsql;

        
    create or replace function can_change_base_channel(server_id_in IN NUMERIC)
    returns numeric
    as $$
    declare
    	throwaway numeric;
    begin
    	-- the idea: if we get past this query, the server is
	-- neither sat nor proxy, so base channel is changeable

	select 1 into throwaway
	  from rhnServer S
	 where S.id = server_id_in
	   and not exists (select 1 from rhnSatelliteInfo SI where SI.server_id = S.id)
	   and not exists (select 1 from rhnProxyInfo PI where PI.server_id = S.id);

        if not found then
	    return 0;
        end if;
	   
	return 1;
    end$$ language plpgsql;
	        
    create or replace function set_custom_value(
    	server_id_in in numeric,
	user_id_in in numeric,
	key_label_in in varchar,
	value_in in varchar
    ) returns void
    as $$
    declare
    	key_id_val numeric;
    begin
    	select CDK.id into strict key_id_val
	  from rhnCustomDataKey CDK,
	       rhnServer S
	 where S.id = server_id_in
	   and S.org_id = CDK.org_id
	   and CDK.label = key_label_in;
	   
	begin
	    insert into rhnServerCustomDataValue (server_id, key_id, value, created_by, last_modified_by)
	    values (server_id_in, key_id_val, value_in, user_id_in, user_id_in);
	exception
	    when UNIQUE_VIOLATION
	    	then
		update rhnServerCustomDataValue
		   set value = value_in,
		       last_modified_by = user_id_in
		 where server_id = server_id_in
		   and key_id = key_id_val;		   
	end;

    end$$ language plpgsql;
    
    create or replace function bulk_set_custom_value(
    	key_label_in in varchar,
	value_in in varchar,
	set_label_in in varchar,
	set_uid_in in numeric
    )
    returns integer
    as $$
    declare
        i integer;
        server record;
    begin
        i := 0;
        for server in (
           SELECT user_id, label, element, element_two
	     FROM rhnSet
	    WHERE label = set_label_in
	      AND user_id = set_uid_in
	) loop
	    if rhn_server.system_service_level(server.element, 'management') = 1 then
	    	perform rhn_server.set_custom_value(server.element, set_uid_in, key_label_in, value_in);
            i := i + 1;
	    end if;
	end loop;
    return i;
    end$$ language plpgsql;

    create or replace function bulk_snapshot_tag(
    	org_id_in in numeric,
        tagname_in in varchar,
	set_label_in in varchar,
	set_uid_in in numeric
    ) returns void
    as $$
    declare
        server record;
    	snapshot_id numeric;
    begin
        for server in (
           SELECT user_id, label, element, element_two
	     FROM rhnSet
	    WHERE label = set_label_in
	      AND user_id = set_uid_in
	    ) loop
	    if rhn_server.system_service_level(server.element, 'management') = 1 then
	    	    select max(id) into snapshot_id
	    	    from rhnSnapshot
	    	    where server_id = server.element;

	    	    if snapshot_id is null then
		    	perform rhn_server.snapshot_server(server.element, 'tagging system:  ' || tagname_in);
			
			select max(id) into snapshot_id
			from rhnSnapshot
			where server_id = server.element;
		    end if;
		 
		-- now have a snapshot_id to work with...
		begin
		    perform rhn_server.tag_snapshot(snapshot_id, org_id_in, tagname_in);
		exception
		    when UNIQUE_VIOLATION
		    	then
			-- do nothing, be forgiving...
			null;
		end;
	    end if;
	end loop;    
    end$$ language plpgsql;

    create or replace function tag_delete(
    	server_id_in in numeric,
	tag_id_in in numeric
    ) returns void
    as $$
    declare
    	snapshots cursor is
		select	snapshot_id
		from	rhnSnapshotTag
		where	tag_id = tag_id_in;
	tag_id_tmp numeric;
    begin
    	select	id into tag_id_tmp
	from	rhnTag
	where	id = tag_id_in
	for update;

	delete
		from	rhnSnapshotTag
		where	server_id = server_id_in
			and tag_id = tag_id_in;
	for snapshot in snapshots loop
		return;
	end loop;
	delete
		from rhnTag
		where id = tag_id_in;
    end$$ language plpgsql;

    create or replace function tag_snapshot(
        snapshot_id_in in numeric,
	org_id_in in numeric,
	tagname_in in varchar
    ) returns void
    as $$
    begin
    	insert into rhnSnapshotTag (snapshot_id, server_id, tag_id)
	select snapshot_id_in, server_id, lookup_tag(org_id_in, tagname_in)
	from rhnSnapshot
	where id = snapshot_id_in;
    end$$ language plpgsql;

    create or replace function bulk_snapshot(
    	reason_in in varchar,
	set_label_in in varchar,
	set_uid_in in numeric
    ) returns void
    as $$
    declare
        server record;
    begin
        for server in (
           SELECT user_id, label, element, element_two
	     FROM rhnSet
	    WHERE label = set_label_in
	      AND user_id = set_uid_in
	    ) loop
	    if rhn_server.system_service_level(server.element, 'management') = 1 then
	    	perform rhn_server.snapshot_server(server.element, reason_in);
	    end if;
	end loop;
    end$$ language plpgsql;

    create or replace function snapshot_server(
    	server_id_in in numeric,
	reason_in in varchar
    ) returns void
    as $$
    declare
    	snapshot_id_v numeric;
	revisions cursor is
		select distinct
			cr.id
		from	rhnConfigRevision	cr,
			rhnConfigFileName	cfn,
			rhnConfigFile		cf,
			rhnConfigChannel	cc,
			rhnServerConfigChannel	scc
		where	1=1
			and scc.server_id = server_id_in
			and scc.config_channel_id = cc.id
			and cc.id = cf.config_channel_id
			and cf.id = cr.config_file_id
			and cr.id = cf.latest_config_revision_id
			and cf.config_file_name_id = cfn.id
			and cf.id = lookup_first_matching_cf(scc.server_id, cfn.path);
	locked integer;
    begin
    	select nextval('rhn_snapshot_id_seq') into snapshot_id_v;

	insert into rhnSnapshot (id, org_id, server_id, reason) (
		select	snapshot_id_v,
			s.org_id,
			server_id_in,
			reason_in
		from	rhnServer s
		where	s.id = server_id_in
	);
	insert into rhnSnapshotChannel (snapshot_id, channel_id) (
		select	snapshot_id_v, sc.channel_id
		from	rhnServerChannel sc
		where	sc.server_id = server_id_in
	);
	insert into rhnSnapshotServerGroup (snapshot_id, server_group_id) (
		select	snapshot_id_v, sgm.server_group_id
		from	rhnServerGroupMembers sgm
		where	sgm.server_id = server_id_in
	);
        locked := 0;
        <<iloop>>
        while true loop
            begin
                insert into rhnPackageNEVRA (id, name_id, evr_id, package_arch_id)
                select nextval('rhn_pkgnevra_id_seq'), sp.name_id, sp.evr_id, sp.package_arch_id
                from rhnServerPackage sp
                where sp.server_id = server_id_in
                        and not exists
                        (select 1
                                from rhnPackageNEVRA nevra
                                where nevra.name_id = sp.name_id
                                        and nevra.evr_id = sp.evr_id
                                        and (nevra.package_arch_id = sp.package_arch_id
                                            or (nevra.package_arch_id is null
                                                and sp.package_arch_id is null)));
                exit iloop;
            exception when unique_violation then
                if locked = 1 then
                    raise;
                else
                    lock table rhnPackageNEVRA in exclusive mode;
                    locked := 1;
                end if;
            end;
        end loop;
	insert into rhnSnapshotPackage (snapshot_id, nevra_id) (
                select distinct snapshot_id_v, nevra.id
                from    rhnServerPackage sp, rhnPackageNEVRA nevra
                where   sp.server_id = server_id_in
                        and nevra.name_id = sp.name_id
                        and nevra.evr_id = sp.evr_id
                        and (nevra.package_arch_id = sp.package_arch_id
                            or (nevra.package_arch_id is null
                                and sp.package_arch_id is null))
	);

	insert into rhnSnapshotConfigChannel ( snapshot_id, config_channel_id ) (
		select	snapshot_id_v, scc.config_channel_id
		from	rhnServerConfigChannel scc
		where	server_id = server_id_in
	);

	for revision in revisions loop
		insert into rhnSnapshotConfigRevision (
				snapshot_id, config_revision_id
			) values (
				snapshot_id_v, revision.id
			);
	end loop;
    end$$ language plpgsql;

    create or replace function remove_action(
    	server_id_in in numeric,
	action_id_in in numeric
    ) returns void
    as $$
    declare
    	-- this really wants "nulls last", but 8.1.7.3.0 sucks ass.
	-- instead, we make a local table that holds our
	-- list of ids with null prereqs.  There's surely a better way
	-- (an array instead of a table maybe?  who knows...)
	-- but I've got code to do this handy that I can look at ;)
    	chained_actions cursor is
                with recursive r(id, prerequisite) as (
			select	id, prerequisite
			from	rhnAction
			where id = action_id_in
		union all
			select	r1.id, r1.prerequisite
			from	rhnAction r1, r
			where r.id = r1.prerequisite
		)
		select * from r
		order by prerequisite desc;
	sessions cursor is
		select	s.id
		from	rhnKickstartSession s
		where	server_id_in in (s.old_server_id, s.new_server_id)
			and s.action_id = action_id_in
			and not exists (
				select	1
				from	rhnKickstartSessionState ss
				where	ss.id = s.state_id
					and ss.label in ('failed','complete')
			);
	chain_ends numeric[];
	i numeric;
	prereq numeric := 1;
    begin
	select	prerequisite
	into	prereq
	from	rhnAction
	where	id = action_id_in;

	if prereq is not null then
		perform rhn_exception.raise_exception('action_is_child');
	end if;

        chain_ends := '{}';
	i := 1;
	for action in chained_actions loop
		if action.prerequisite is null then
			chain_ends[i] := action.id;
			i := i + 1;
		else
			delete from rhnServerAction
				where server_id = server_id_in
				and action_id = action.id;
		end if;
	end loop;

	delete from rhnServerAction
		where server_id = server_id_in
		and action_id = any(chain_ends);

	for s in sessions loop
		update rhnKickstartSession
			set 	state_id = (
					select	id
					from	rhnKickstartSessionState
					where	label = 'failed'
				),
				action_id = null
			where	id = s.id;
		perform set_ks_session_history_message(s.id, 'failed', 'Kickstart cancelled due to action removal');
	end loop;
    end$$ language plpgsql;
   
    create or replace function check_user_access(server_id_in in numeric, user_id_in in numeric)
    returns numeric
    as $$
    declare
    	has_access numeric;
    begin
    	-- first check; if this returns no rows, then the server/user are in different orgs, and we bail
        select 1 into has_access
	  from rhnServer S,
	       web_contact wc
	 where wc.org_id = s.org_id
	   and s.id = server_id_in
	   and wc.id = user_id_in;

        if not found then
          return 0;
        end if;

	-- okay, so they're in the same org.  if we have an org admin, they get a free pass
    	if rhn_user.check_role(user_id_in, 'org_admin') = 1
	then
	    return 1;
	end if;
		   
    	select 1 into has_access
	  from rhnServerGroupMembers SGM,
	       rhnUserServerGroupPerms USG
	 where SGM.server_group_id = USG.server_group_id
	   and SGM.server_id = server_id_in
	   and USG.user_id = user_id_in;

        if not found then
          return 0;
        end if;
	   
	return 1;
    end$$ language plpgsql;

    -- *******************************************************************
    -- FUNCTION: can_server_consume_virt_slot
    -- Returns 1 if the server id is eligible to consume a virtual slot,
    --   else returns 0.
    -- Called by: insert_into_servergroup, delete_from_servergroup
    -- *******************************************************************
    create or replace function can_server_consume_virt_slot(server_id_in in numeric,
                                           group_type_in in varchar)
    returns numeric                                           
    as $$
    declare
        server_virt_slots cursor is
            select vi.VIRTUAL_SYSTEM_ID
            from
                rhnVirtualInstance vi
            where
                -- server id is a virtual instance
                vi.VIRTUAL_SYSTEM_ID = server_id_in
                -- server id's host is virt entitled
                and exists ( select 1
                     from rhnServerEntitlementView sev
                 where vi.HOST_SYSTEM_ID = sev.server_id
                 and sev.label = 'virtualization_host' )
                -- server id's host also has the ent we want
                and exists ( select 1
                     from rhnServerEntitlementView sev2
                 where vi.HOST_SYSTEM_ID = sev2.server_id
                 and sev2.label = group_type_in );

    begin
        for server_virt_slot in server_virt_slots loop
            return 1;
        end loop;
        return 0;
    end$$ language plpgsql;


    create or replace function insert_into_servergroup (
		server_id_in in numeric,
		server_group_id_in in numeric
    ) returns void
    as $$
    declare
		used_slots numeric;
		max_slots numeric;
		org_id numeric;
		mgmt_available numeric;
		mgmt_upgrade numeric;
		mgmt_sgid numeric;
		prov_available numeric;
		prov_upgrade numeric;
		prov_sgid numeric;
		group_label varchar;
		group_type numeric;
	begin
		-- first, group_type = null, because it's easy...

		-- this will rowlock the servergroup we're trying to change;
		-- we probably need to lock the other one, but I think the chances
		-- of it being a real issue are very small for now...
		select	sg.group_type, sg.org_id, sg.current_members, sg.max_members
		into	group_type, org_id, used_slots, max_slots
		from	rhnServerGroup sg
		where	sg.id = server_group_id_in
		for update of sg;

		if group_type is null then
			if used_slots >= max_slots then
				perform rhn_exception.raise_exception('servergroup_max_members');
			end if;

			insert into rhnServerGroupMembers(
					server_id, server_group_id
				) values (
					server_id_in, server_group_id_in
				);
			update rhnServerGroup
				set current_members = current_members + 1
				where id = server_group_id_in;

			perform rhn_cache.update_perms_for_server_group(server_group_id_in);
			return;
		end if;

		-- now for group_type != null
		-- 
		select	label
		into	group_label
		from	rhnServerGroupType	sgt
		where	sgt.id = group_type;

		-- the naive easy path that gets hit most often and has to be quickest.
		if group_label in (
                           'enterprise_entitled',
                           'virtualization_host'
                      ) then
			if used_slots >= max_slots and 
               (rhn_server.can_server_consume_virt_slot(server_id_in, group_label) != 1) 
               then
				perform rhn_exception.raise_exception('servergroup_max_members');
			end if;

			insert into rhnServerGroupMembers(
					server_id, server_group_id
				) values (
					server_id_in, server_group_id_in
				);

            -- Only update current members if the system in consuming a 
            -- physical slot.
            if rhn_server.can_server_consume_virt_slot(server_id_in, group_label) = 0 then
                update rhnServerGroup
                set current_members = current_members + 1
                where id = server_group_id_in;
            end if;                

			return;
		end if;
	end$$ language plpgsql;

	create or replace function insert_into_servergroup_maybe (
		server_id_in in numeric,
		server_group_id_in in numeric
	) returns numeric as $$ 
    declare
		retval numeric := 0;
		servergroups cursor is
			select	s.id	server_id,
					sg.id	server_group_id
			from	rhnServerGroup	sg,
					rhnServer		s
			where	s.id = server_id_in
				and sg.id = server_group_id_in
				and s.org_id = sg.org_id
				and not exists (
					select	1
					from	rhnServerGroupMembers sgm
					where	sgm.server_id = s.id
						and sgm.server_group_id = sg.id
				);
	begin
		for sgm in servergroups loop
			perform rhn_server.insert_into_servergroup(sgm.server_id, sgm.server_group_id);
			retval := retval + 1;
		end loop;
		return retval;
	end$$ language plpgsql;

	create or replace function insert_set_into_servergroup (
		server_group_id_in in numeric,
		user_id_in in numeric,
		set_label_in in varchar
	) returns void
        as $$
    declare
		servers cursor is
			select	st.element	id
			from	rhnSet		st
			where	st.user_id = user_id_in
				and st.label = set_label_in
				and exists (
					select	1
					from	rhnUserManagedServerGroups umsg
					where	umsg.server_group_id = server_group_id_in
						and umsg.user_id = user_id_in
					)
				and not exists (
					select	1
					from	rhnServerGroupMembers sgm
					where	sgm.server_id = st.element
						and sgm.server_group_id = server_group_id_in
				);
	begin
		for s in servers loop
			perform rhn_server.insert_into_servergroup(s.id, server_group_id_in);
		end loop;
	end$$ language plpgsql;
		
    create or replace function delete_from_servergroup (
    	server_id_in in numeric,
		server_group_id_in in numeric
    ) returns void
    as $$
    declare
        server_virt_groups cursor is
            select 1
            from rhnServerEntitlementVirtual sev
            where sev.server_id = server_id_in
            and sev.server_group_id = server_group_id_in;

		oid numeric;
		mgmt_sgid numeric;
		label varchar;
		group_type numeric;
	begin
			select	sg.group_type, sg.org_id
			into	group_type,	oid
			from	rhnServerGroupMembers	sgm,
					rhnServerGroup			sg
			where	sg.id = server_group_id_in
				and sg.id = sgm.server_group_id
				and sgm.server_id = server_id_in
			for update of sg;

			if not found then
				perform rhn_exception.raise_exception('server_not_in_group');
			end if;

		-- do group_type is null first
		if group_type is null then
			delete from rhnServerGroupMembers
				where server_group_id = server_group_id_in
				and	server_id = server_id_in;
			update rhnServerGroup
				set current_members = current_members - 1
				where id = server_group_id_in;
			perform rhn_cache.update_perms_for_server_group(server_group_id_in);
			return;
		end if;

		select	sgt.label
		into	label
		from	rhnServerGroupType sgt
		where	sgt.id = group_type;

		if label in (
                     'enterprise_entitled', 
                     'virtualization_host'
                ) then

            -- Only update current members if the system is consuming
            -- a physical slot.
            for server_virt_group in server_virt_groups loop                
                delete from rhnServerGroupMembers
                where server_group_id = server_group_id_in
                and	server_id = server_id_in;
                return;
            end loop;                

            delete from rhnServerGroupMembers
            where server_group_id = server_group_id_in
            and	server_id = server_id_in;

            update rhnServerGroup
            set current_members = current_members - 1
            where id = server_group_id_in;

		end if;
	end$$ language plpgsql;

	create or replace function delete_set_from_servergroup (
		server_group_id_in in numeric,
		user_id_in in numeric,
		set_label_in in varchar
	) returns void
        as $$	
        declare
		servergroups cursor is
			select	sgm.server_id, sgm.server_group_id
			from	rhnSet st,
					rhnServerGroupMembers sgm
			where	sgm.server_group_id = server_group_id_in
				and st.user_id = user_id_in
				and st.label = set_label_in
				and sgm.server_id = st.element
				and exists (
					select	1
					from	rhnUserManagedServerGroups usgp
					where	usgp.server_group_id = server_group_id_in
						and usgp.user_id = user_id_in
				);
	begin
		for sgm in servergroups loop
			perform rhn_server.delete_from_servergroup(sgm.server_id, server_group_id_in);
		end loop;
	end$$ language plpgsql;

	create or replace function clear_servergroup (
		server_group_id_in in numeric
	) returns void
        as $$
        declare
		servers cursor is
			select	sgm.server_id	id
			from	rhnServerGroupMembers sgm
			where	sgm.server_group_id = server_group_id_in;
	begin
		for s in servers loop
			perform rhn_server.delete_from_servergroup(s.id, server_group_id_in);
		end loop;
	end$$ language plpgsql;

	create or replace function delete_from_org_servergroups (
		server_id_in in numeric
	) returns void
        as $$
        declare
		servergroups cursor is
			select	sgm.server_group_id id
			from	rhnServerGroup sg,
					rhnServerGroupMembers sgm
			where	sgm.server_id = server_id_in
				and sgm.server_group_id = sg.id
				and sg.group_type is null;
	begin
		for sg in servergroups loop
			perform rhn_server.delete_from_servergroup(server_id_in, sg.id);
		end loop;
	end$$ language plpgsql;

	create or replace function get_ip_address (
		server_id_in in numeric
	) returns varchar as $$
        declare
		interfaces cursor is
			select	ni.name as name, na4.address as address
			from	rhnServerNetInterface ni,
			        rhnServerNetAddress4 na4
			where	server_id = server_id_in
                and ni.id = na4.interface_id
				and na4.address != '127.0.0.1';
		addresses cursor is
			select	ipaddr ip_addr
			from	rhnServerNetwork
			where	server_id = server_id_in
				and ipaddr != '127.0.0.1';
	begin
		for addr in addresses loop
			return addr.ip_addr;
		end loop;
		for iface in interfaces loop
			return iface.address;
		end loop;
		return NULL;
	end$$ language plpgsql;

    create or replace function update_needed_cache(
        server_id_in in numeric
	) returns void as $$
    declare
      update_lock numeric;
    begin
      select id into update_lock from rhnServer where id = server_id_in for update;
      delete from rhnServerNeededCache
        where server_id = server_id_in;
      insert into rhnServerNeededCache
             (server_id, errata_id, package_id, channel_id)
        (select distinct sp.server_id, x.errata_id, p.id, x.channel_id
           FROM (SELECT sp_sp.server_id, sp_sp.name_id,
		        sp_sp.package_arch_id, max(sp_pe.evr) AS max_evr
                   FROM rhnServerPackage sp_sp
                   join rhnPackageEvr sp_pe ON sp_pe.id = sp_sp.evr_id
                  GROUP BY sp_sp.server_id, sp_sp.name_id, sp_sp.package_arch_id) sp
           join rhnPackage p ON p.name_id = sp.name_id
           join rhnPackageEvr pe ON pe.id = p.evr_id AND sp.max_evr < pe.evr
           join rhnPackageUpgradeArchCompat puac
	            ON puac.package_arch_id = sp.package_arch_id
		    AND puac.package_upgrade_arch_id = p.package_arch_id
           join rhnServerChannel sc ON sc.server_id = sp.server_id
           join rhnChannelPackage cp ON cp.package_id = p.id
	            AND cp.channel_id = sc.channel_id
           left join (SELECT ep.errata_id, ce.channel_id, ep.package_id
                        FROM rhnChannelErrata ce
                        join rhnErrataPackage ep
			         ON ep.errata_id = ce.errata_id
			join rhnServerChannel sc_sc
			         ON sc_sc.channel_id = ce.channel_id
		       WHERE sc_sc.server_id = server_id_in) x
             ON x.channel_id = sc.channel_id AND x.package_id = cp.package_id
          where sp.server_id = server_id_in);
	end$$ language plpgsql;
-- restore the original setting
update pg_settings set setting = overlay( setting placing '' from 1 for (length('rhn_server')+1) ) where name = 'search_path';
  0707010000085A000081B400000000000000000000000167AE111400000F3A000000000000000000000000000000000000006D00000000susemanager-schema/upgrade/spacewalk-schema-2.4-to-spacewalk-schema-2.5/162-delete_update_ent_references.sql  
-- rhnServerGroup and dependencies

SELECT .clear_log_id();

DELETE FROM rhnOrgExtGroupMapping
  WHERE server_group_id in (
    SELECT id
      FROM rhnServerGroup
      WHERE group_type = (
        SELECT id
          FROM rhnServerGroupType
          WHERE label = 'sw_mgr_entitled'
      )
  );

DELETE FROM rhnRegTokenGroups
  WHERE server_group_id in (
    SELECT id
      FROM rhnServerGroup
      WHERE group_type = (
        SELECT id
          FROM rhnServerGroupType
          WHERE label = 'sw_mgr_entitled'
      )
  );

-- create server group for 'enterprise_entitled' everywhere
insert into rhnServerGroup ( id, name, description, group_type, org_id )
  select nextval('rhn_server_group_id_seq'), sgt.name, sgt.name, sgt.id, X.org_id
  from rhnServerGroupType sgt,
     (select distinct msg.org_id
        from rhnServerGroup msg
       where msg.org_id not in (select org_id
                                  from rhnServerGroup sg
                                  join rhnServerGroupType sgt ON sgt.id = sg.group_type
                                 where sgt.label = 'enterprise_entitled')
     ) X
  where sgt.label = 'enterprise_entitled';

-- add membership to 'enterprise_entitled' for all server which
-- are currently in the group 'sw_mgr_entitled'
  insert into rhnServerGroupMembers (server_id, server_group_id)
    select * from (
      select sgm.server_id,
        (select nsg.id
           from rhnServerGroup nsg
           join rhnServerGroupType nsgt on nsg.group_type = nsgt.id
          where nsgt.label = 'enterprise_entitled'
            and nsg.org_id = sg.org_id) new_group_id
        from rhnServerGroupMembers sgm
        join rhnServerGroup sg on sgm.server_group_id = sg.id
        join rhnServerGroupType sgt on sg.group_type = sgt.id
       where sgt.label = 'sw_mgr_entitled'
    ) X
    where not exists (select 1
                       from rhnServerGroupMembers csgm
                      where csgm.server_id = X.server_id
                        and csgm.server_group_id = X.new_group_id);

-- remove 'sw_mgr_entitled'
DELETE FROM rhnServerGroupMembers
  WHERE server_group_id in (
    SELECT id
      FROM rhnServerGroup
      WHERE group_type = (
        SELECT id
          FROM rhnServerGroupType
          WHERE label = 'sw_mgr_entitled'
      )
  );


DELETE FROM rhnSnapshotServerGroup
  WHERE server_group_id in (
    SELECT id
      FROM rhnServerGroup
      WHERE group_type = (
        SELECT id
          FROM rhnServerGroupType
          WHERE label = 'sw_mgr_entitled'
      )
  );

DELETE FROM rhnUserDefaultSystemGroups
  WHERE system_group_id in (
    SELECT id
      FROM rhnServerGroup
      WHERE group_type = (
        SELECT id
          FROM rhnServerGroupType
          WHERE label = 'sw_mgr_entitled'
      )
  );

DELETE FROM rhnUserServerGroupPerms
  WHERE server_group_id in (
    SELECT id
      FROM rhnServerGroup
      WHERE group_type = (
        SELECT id
          FROM rhnServerGroupType
          WHERE label = 'sw_mgr_entitled'
      )
  );

DELETE FROM rhnServerGroup
  WHERE group_type = (
    SELECT id
      FROM rhnServerGroupType
      WHERE label = 'sw_mgr_entitled'
  );

-- rhnServerGroupType and dependencies

DELETE FROM rhnRegTokenEntitlement
  WHERE server_group_type_id = (
    SELECT id
      FROM rhnServerGroupType
      WHERE label = 'sw_mgr_entitled'
  );

DELETE FROM rhnServerGroupTypeFeature
  WHERE server_group_type_id = (
    SELECT id
      FROM rhnServerGroupType
      WHERE label = 'sw_mgr_entitled'
  );

DELETE FROM rhnServerServerGroupArchCompat
  WHERE server_group_type = (
    SELECT id
      FROM rhnServerGroupType
      WHERE label = 'sw_mgr_entitled'
  );

DELETE FROM rhnSGTypeBaseAddonCompat
  WHERE base_id = (
    SELECT id
      FROM rhnServerGroupType
      WHERE label = 'sw_mgr_entitled'
  );

DELETE FROM rhnServerGroupType
  WHERE label = 'sw_mgr_entitled';
  0707010000085B000081B400000000000000000000000167AE111400000454000000000000000000000000000000000000006300000000susemanager-schema/upgrade/spacewalk-schema-2.4-to-spacewalk-schema-2.5/163-rhnEntitledServers.sql    --
-- Copyright (c) 2008 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--

create or replace view
rhnEntitledServers
as
select distinct
    S.id,
    S.org_id,
    S.digital_server_id,
    S.server_arch_id,
    S.os,
    S.release,
    S.name,
    S.description,
    S.info,
    S.secret
from
    rhnServerGroup SG,
    rhnServerGroupType SGT,
    rhnServerGroupMembers SGM,
    rhnServer S
where
    S.id = SGM.server_id
and SG.id = SGM.server_group_id
and SGT.label IN ('enterprise_entitled')
and SG.group_type = SGT.id
and SG.org_id = S.org_id
;

0707010000085C000081B400000000000000000000000167AE111400000A8D000000000000000000000000000000000000006C00000000susemanager-schema/upgrade/spacewalk-schema-2.4-to-spacewalk-schema-2.5/164-remove_non_linux_references.sql   
-- rhnServerGroup and dependencies

SELECT .clear_log_id();

DELETE FROM rhnOrgExtGroupMapping
  WHERE server_group_id in (
    SELECT id
      FROM rhnServerGroup
      WHERE group_type = (
        SELECT id
          FROM rhnServerGroupType
          WHERE label = 'nonlinux_entitled'
      )
  );

DELETE FROM rhnRegTokenGroups
  WHERE server_group_id in (
    SELECT id
      FROM rhnServerGroup
      WHERE group_type = (
        SELECT id
          FROM rhnServerGroupType
          WHERE label = 'nonlinux_entitled'
      )
  );

DELETE FROM rhnServerGroupMembers
  WHERE server_group_id in (
    SELECT id
      FROM rhnServerGroup
      WHERE group_type = (
        SELECT id
          FROM rhnServerGroupType
          WHERE label = 'nonlinux_entitled'
      )
  );

DELETE FROM rhnSnapshotServerGroup
  WHERE server_group_id in (
    SELECT id
      FROM rhnServerGroup
      WHERE group_type = (
        SELECT id
          FROM rhnServerGroupType
          WHERE label = 'nonlinux_entitled'
      )
  );

DELETE FROM rhnUserDefaultSystemGroups
  WHERE system_group_id in (
    SELECT id
      FROM rhnServerGroup
      WHERE group_type = (
        SELECT id
          FROM rhnServerGroupType
          WHERE label = 'nonlinux_entitled'
      )
  );

DELETE FROM rhnUserServerGroupPerms
  WHERE server_group_id in (
    SELECT id
      FROM rhnServerGroup
      WHERE group_type = (
        SELECT id
          FROM rhnServerGroupType
          WHERE label = 'nonlinux_entitled'
      )
  );

DELETE FROM rhnServerGroup
  WHERE group_type = (
    SELECT id
      FROM rhnServerGroupType
      WHERE label = 'nonlinux_entitled'
  );

-- rhnServerGroupType and dependencies

DELETE FROM rhnRegTokenEntitlement
  WHERE server_group_type_id = (
    SELECT id
      FROM rhnServerGroupType
      WHERE label = 'nonlinux_entitled'
  );

DELETE FROM rhnServerGroupTypeFeature
  WHERE server_group_type_id = (
    SELECT id
      FROM rhnServerGroupType
      WHERE label = 'nonlinux_entitled'
  );

DELETE FROM rhnServerServerGroupArchCompat
  WHERE server_group_type = (
    SELECT id
      FROM rhnServerGroupType
      WHERE label = 'nonlinux_entitled'
  );

DELETE FROM rhnSGTypeBaseAddonCompat
  WHERE base_id = (
    SELECT id
      FROM rhnServerGroupType
      WHERE label = 'nonlinux_entitled'
  );

DELETE FROM rhnServerGroupType
  WHERE label = 'nonlinux_entitled';

-- rhnOrgEntitlementType

DELETE FROM rhnOrgEntitlements
  WHERE entitlement_id = (
    SELECT id
      FROM rhnOrgEntitlementType
      WHERE label = 'rhn_nonlinux'
  );

DELETE FROM rhnOrgEntitlementType
  WHERE label = 'rhn_nonlinux';

-- rhnFeature

DELETE FROM rhnFeature
  WHERE label = 'ftr_nonlinux_support';
   0707010000085D000081B400000000000000000000000167AE11140000285B000000000000000000000000000000000000005E00000000susemanager-schema/upgrade/spacewalk-schema-2.4-to-spacewalk-schema-2.5/165-delete_server.sql --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
-- This deletes a server.  All codepaths which delete servers should hit this
-- or delete_server_bulk()

create or replace
function delete_server (
        server_id_in in numeric
) returns void 
as
$$
declare
         servergroups cursor for
                select  server_id, server_group_id
                from    rhnServerGroupMembers sgm
                where   sgm.server_id = server_id_in;

         configchannels cursor for
                select  cc.id
                from    rhnConfigChannel cc,
                        rhnConfigChannelType cct,
                        rhnServerConfigChannel scc
                where   1=1
                        and scc.server_id = server_id_in
                        and scc.config_channel_id = cc.id
                        -- these config channel types are reserved
                        -- for use by a single server, so we don't
                        -- need to check for other servers subscribed
                        and cct.label in
                                ('local_override','server_import')
                        and cct.id = cc.confchan_type_id;

    is_virt boolean;
begin
        -- filelists
        delete from rhnFileList where id in (
	select	spfl.file_list_id
	  from	rhnServerPreserveFileList spfl
	 where	spfl.server_id = server_id_in
			and not exists (
				select	1
				from	rhnServerPreserveFileList
				where	file_list_id = spfl.file_list_id
					and server_id != server_id_in
				union all
				select	1
				from	rhnKickstartPreserveFileList
				where	file_list_id = spfl.file_list_id
			)
        );

	for configchannel in configchannels loop
		perform rhn_config.delete_channel(configchannel.id);
	end loop;

      is_virt := exists (
       select 1
        from rhnServerEntitlementView
       where server_id = server_id_in
         and label = 'virtualization_host'
      );

	for sgm in servergroups loop
		perform rhn_server.delete_from_servergroup(
			sgm.server_id, sgm.server_group_id);
	end loop;

    if is_virt then
        perform rhn_entitlements.repoll_virt_guest_entitlements(server_id_in);
    end if;

        -- we're handling this instead of letting an "on delete
        -- set null" do it so that we don't run the risk
        -- of setting off the triggers and killing us with a
        -- mutating table

        -- this is merge of two single updates:
        --  update ... set old_server_id = null where old_server_id = server_id_in;
        --  update ... set new_server_id = null where new_server_id = server_id_in;
        -- so we scan rhnKickstartSession table only once
        update rhnKickstartSession
                set old_server_id = case when old_server_id = server_id_in then null else old_server_id end,
                    new_server_id = case when new_server_id = server_id_in then null else new_server_id end
                where old_server_id = server_id_in
                   or new_server_id = server_id_in;

        perform rhn_channel.clear_subscriptions(server_id_in, 1);

        -- A little complicated here, but the goal is to
        -- delete records from rhnVirtualInstace only if we don't
        -- care about them anymore.  We don't care about records
        -- in rhnVirtualInstance if we are deleting the host
        -- system and the virtual system is already null, or
        -- vice-versa.  We *do* care about them if either the
        -- host or virtual system is still registered because we
        -- still want them to show up in the UI.
    -- If there's a newer row in rhnVirtualInstance with the same
    -- uuid, this guest must have been re-registered, so we can clean
    -- this data up.

        delete from rhnVirtualInstance vi
              where (host_system_id = server_id_in and virtual_system_id is null)
                 or (virtual_system_id = server_id_in and host_system_id is null)
                 or (vi.virtual_system_id = server_id_in and vi.modified < (select max(vi2.modified)
                    from rhnVirtualInstance vi2 where vi2.uuid = vi.uuid));

        -- this is merge of two single updates:
        --  update ... set host_system_id = null where host_system_id = server_id_in;
        --  update ... set virtual_system_id = null where virtual_system_id = server_id_in;
        -- so we scan rhnVirtualInstance table only once
        update rhnVirtualInstance
           set host_system_id = case when host_system_id = server_id_in then null else host_system_id end,
               virtual_system_id = case when virtual_system_id = server_id_in then null else virtual_system_id end
         where host_system_id = server_id_in
            or virtual_system_id = server_id_in;

        -- this is merge of two single updates:
        --  update ... set old_host_system_id = null when old_host_system_id = server_id_in;
        --  update ... set new_host_system_id = null when new_host_system_id = server_id_in;
        -- so we scan rhnVirtualInstanceEventLog table only once
        update rhnVirtualInstanceEventLog
           set old_host_system_id = case when old_host_system_id = server_id_in then null else old_host_system_id end,
               new_host_system_id = case when new_host_system_id = server_id_in then null else new_host_system_id end
         where old_host_system_id = server_id_in
            or new_host_system_id = server_id_in;

        -- We're deleting everything with a foreign key to rhnServer
        -- here, now.  I'm hoping this will help aleviate our deadlock
        -- problem.

        delete from rhnActionConfigChannel where server_id = server_id_in;
        delete from rhnActionConfigRevision where server_id = server_id_in;
        delete from rhnActionPackageRemovalFailure where server_id = server_id_in;
        delete from rhnClientCapability where server_id = server_id_in;
        delete from rhnCpu where server_id = server_id_in;
        -- there's still a cascade here, because the constraint keeps the
        -- table locked for too long to rebuild it.  Ugh...
        delete from rhnDevice where server_id = server_id_in;
        delete from rhnProxyInfo where server_id = server_id_in;
        delete from rhnRam where server_id = server_id_in;
        delete from rhnRegToken where server_id = server_id_in;
        delete from rhnSatelliteInfo where server_id = server_id_in;
        -- this cascades to rhnActionConfigChannel and rhnActionConfigFileName
        delete from rhnServerAction where server_id = server_id_in;
        delete from rhnServerActionPackageResult where server_id = server_id_in;
        delete from rhnServerActionScriptResult where server_id = server_id_in;
        delete from rhnServerActionVerifyResult where server_id = server_id_in;
        delete from rhnServerActionVerifyMissing where server_id = server_id_in;
        -- counts are handled above.  this should be a delete_ function.
        delete from rhnServerChannel where server_id = server_id_in;
        delete from rhnServerConfigChannel where server_id = server_id_in;
        delete from rhnServerCustomDataValue where server_id = server_id_in;
        delete from rhnServerDMI where server_id = server_id_in;
        delete from rhnServerEvent where server_id = server_id_in;
        delete from rhnServerHistory where server_id = server_id_in;
        delete from rhnServerInfo where server_id = server_id_in;
        delete from rhnServerInstallInfo where server_id = server_id_in;
        delete from rhnServerLocation where server_id = server_id_in;
        delete from rhnServerLock where server_id = server_id_in;
        delete from rhnServerNeededCache where server_id = server_id_in;
        delete from rhnServerNetwork where server_id = server_id_in;
        delete from rhnServerNotes where server_id = server_id_in;
        -- I'm not removing the foreign key from rhnServerPackage; that'll
        -- take forever.  Do the delete anyway.
        delete from rhnServerPackage where server_id = server_id_in;
        delete from rhnServerTokenRegs where server_id = server_id_in;
        delete from rhnSnapshotTag where server_id = server_id_in;
        -- this cascades to:
        --   rhnSnapshotChannel, rhnSnapshotConfigChannel, rhnSnapshotPackage,
        --   rhnSnapshotConfigRevision, rhnSnapshotServerGroup,
        --   rhnSnapshotTag.
        -- We may want to consider delete_snapshot() at some point, but
        --   I don't think we need to yet.
        delete from rhnSnapshot where server_id = server_id_in;
        delete from rhnUserServerPrefs where server_id = server_id_in;
        -- hrm, this one's interesting... we _probably_ should delete
        -- everything for the parent server_id when we delete the proxy,
        -- but we don't currently.
        delete from rhnServerPath where server_id_in in (server_id, proxy_server_id);
        delete from rhnUserServerPerms where server_id = server_id_in;

        delete from rhnServerNetInterface where server_id = server_id_in;

        delete from rhnServerUuid where server_id = server_id_in;

        delete from rhnPushClient where server_id = server_id_in;

        -- now get rhnServer itself.
        delete
        from    rhnServer
                where id = server_id_in;

        delete
        from    rhnSet
        where   1=1
                and user_id in (
                        select  wc.id
                        from    rhnServer rs,
                                web_contact wc
                        where   rs.id = server_id_in
                                and rs.org_id = wc.org_id
                )
                and label = 'system_list'
                and element = server_id_in;
end;
$$
language plpgsql;

 0707010000085E000081B400000000000000000000000167AE111400001225000000000000000000000000000000000000007900000000susemanager-schema/upgrade/spacewalk-schema-2.4-to-spacewalk-schema-2.5/166-remove_virtualization_host_platform_refs.sql  
SELECT .clear_log_id();

-- rhnServerGroup and dependencies

DELETE FROM rhnOrgExtGroupMapping
  WHERE server_group_id in (
    SELECT id
      FROM rhnServerGroup
      WHERE group_type = (
        SELECT id
          FROM rhnServerGroupType
          WHERE label = 'virtualization_host_platform'
      )
  );

DELETE FROM rhnRegTokenGroups
  WHERE server_group_id in (
    SELECT id
      FROM rhnServerGroup
      WHERE group_type = (
        SELECT id
          FROM rhnServerGroupType
          WHERE label = 'virtualization_host_platform'
      )
  );

-- create server group for 'virtualization_host' everywhere
insert into rhnServerGroup ( id, name, description, group_type, org_id )
  select nextval('rhn_server_group_id_seq'), sgt.name, sgt.name, sgt.id, X.org_id
  from rhnServerGroupType sgt,
     (select distinct msg.org_id
        from rhnServerGroup msg
       where msg.org_id not in (select org_id
                                  from rhnServerGroup sg
                                  join rhnServerGroupType sgt ON sgt.id = sg.group_type
                                 where sgt.label = 'virtualization_host')
     ) X
  where sgt.label = 'virtualization_host';

-- add membership to 'virtualization_host' for all server which
-- are currently in the group 'virtualization_host_platform'
  insert into rhnServerGroupMembers (server_id, server_group_id)
    select * from (
      select sgm.server_id,
        (select nsg.id
           from rhnServerGroup nsg
           join rhnServerGroupType nsgt on nsg.group_type = nsgt.id
          where nsgt.label = 'virtualization_host'
            and nsg.org_id = sg.org_id) new_group_id
        from rhnServerGroupMembers sgm
        join rhnServerGroup sg on sgm.server_group_id = sg.id
        join rhnServerGroupType sgt on sg.group_type = sgt.id
       where sgt.label = 'virtualization_host_platform'
    ) X
    where not exists (select 1
                       from rhnServerGroupMembers csgm
                      where csgm.server_id = X.server_id
                        and csgm.server_group_id = X.new_group_id);

-- remove 'virtualization_host_platform'
DELETE FROM rhnServerGroupMembers
  WHERE server_group_id in (
    SELECT id
      FROM rhnServerGroup
      WHERE group_type = (
        SELECT id
          FROM rhnServerGroupType
          WHERE label = 'virtualization_host_platform'
      )
  );

DELETE FROM rhnSnapshotServerGroup
  WHERE server_group_id in (
    SELECT id
      FROM rhnServerGroup
      WHERE group_type = (
        SELECT id
          FROM rhnServerGroupType
          WHERE label = 'virtualization_host_platform'
      )
  );

DELETE FROM rhnUserDefaultSystemGroups
  WHERE system_group_id in (
    SELECT id
      FROM rhnServerGroup
      WHERE group_type = (
        SELECT id
          FROM rhnServerGroupType
          WHERE label = 'virtualization_host_platform'
      )
  );

DELETE FROM rhnUserServerGroupPerms
  WHERE server_group_id in (
    SELECT id
      FROM rhnServerGroup
      WHERE group_type = (
        SELECT id
          FROM rhnServerGroupType
          WHERE label = 'virtualization_host_platform'
      )
  );

DELETE FROM rhnServerGroup
  WHERE group_type = (
    SELECT id
      FROM rhnServerGroupType
      WHERE label = 'virtualization_host_platform'
  );

-- rhnServerGroupType and dependencies

UPDATE rhnRegTokenEntitlement
  SET server_group_type_id = (
    SELECT id
      FROM rhnServerGroupType
      WHERE label = 'virtualization_host'
  )
  WHERE server_group_type_id = (
    SELECT id
      FROM rhnServerGroupType
      WHERE label = 'virtualization_host_platform'
  );

DELETE FROM rhnServerGroupTypeFeature
  WHERE server_group_type_id = (
    SELECT id
      FROM rhnServerGroupType
      WHERE label = 'virtualization_host_platform'
  );

DELETE FROM rhnServerServerGroupArchCompat
  WHERE server_group_type = (
    SELECT id
      FROM rhnServerGroupType
      WHERE label = 'virtualization_host_platform'
  );

DELETE FROM rhnSGTypeBaseAddonCompat
  WHERE addon_id = (
    SELECT id
      FROM rhnServerGroupType
      WHERE label = 'virtualization_host_platform'
  );

DELETE FROM rhnSGTypeVirtSublevel
  WHERE server_group_type_id = (
    SELECT id
      FROM rhnServerGroupType
      WHERE label = 'virtualization_host_platform'
  );

DELETE FROM rhnServerGroupType
  WHERE label = 'virtualization_host_platform';

--rhnOrgEntitlementType

DELETE FROM rhnOrgEntitlements
  WHERE entitlement_id = (
    SELECT id
      FROM rhnOrgEntitlementType
      WHERE label = 'rhn_virtualization_platform'
  );

DELETE FROM rhnOrgEntitlementType
  WHERE label = 'rhn_virtualization_platform';
   0707010000085F000081B400000000000000000000000167AE11140000025B000000000000000000000000000000000000006B00000000susemanager-schema/upgrade/spacewalk-schema-2.4-to-spacewalk-schema-2.5/167-remove_virt_sub_level_refs.sql    DELETE FROM rhnException
WHERE label = 'invalid_virt_sub_level';

DELETE FROM rhnSGTypeVirtSubLevel
WHERE
    server_group_type_id = lookup_sg_type('virtualization_host') AND
    virt_sub_level_id = lookup_virt_sub_level('virtualization_free');

DELETE FROM rhnChannelFamilyVirtSubLevel
WHERE
  virt_sub_level_id IN (
    SELECT id
    FROM rhnVirtSubLevel
    WHERE label = 'virtualization_free'
  );

DELETE FROM rhnVirtSubLevel
WHERE label = 'virtualization_free';

DROP TABLE rhnChannelFamilyVirtSubLevel;
DROP TABLE rhnSGTypeVirtSubLevel;
DROP TABLE rhnVirtSubLevel;
DROP SEQUENCE rhn_virt_sl_seq;
 07070100000860000081B400000000000000000000000167AE111400000052000000000000000000000000000000000000007000000000susemanager-schema/upgrade/spacewalk-schema-2.4-to-spacewalk-schema-2.5/168-remove_virt_sub_level_functions.sql   DROP FUNCTION lookup_virt_sub_level(varchar); -- TODO really 'character varying'?
  07070100000861000081B400000000000000000000000167AE111400000265000000000000000000000000000000000000006600000000susemanager-schema/upgrade/spacewalk-schema-2.4-to-spacewalk-schema-2.5/169-remove_sat_check_task.sql DELETE FROM rhnTaskoRun
  WHERE template_id IN (
    SELECT id
      FROM rhnTaskoTemplate
      WHERE task_id IN (
        SELECT id
          FROM rhnTaskoTask
          WHERE name = 'sat-cert-check'
      )
  );

DELETE FROM rhnTaskoTemplate
  WHERE bunch_id IN (
    SELECT id
      FROM rhnTaskoBunch
      WHERE name = 'satcert-check-bunch'
  );

DELETE FROM rhnTaskoTask
  WHERE name = 'sat-cert-check';

DELETE FROM rhnTaskoSchedule
  WHERE bunch_id IN (
    SELECT id
      FROM rhnTaskoBunch
      WHERE name = 'satcert-check-bunch'
  );

DELETE FROM rhnTaskoBunch
  WHERE name = 'satcert-check-bunch';
   07070100000862000081B400000000000000000000000167AE11140000001D000000000000000000000000000000000000006600000000susemanager-schema/upgrade/spacewalk-schema-2.4-to-spacewalk-schema-2.5/170-drop_rhnSatelliteCert.sql DROP TABLE rhnSatelliteCert;
   07070100000863000081B400000000000000000000000167AE111400001243000000000000000000000000000000000000006100000000susemanager-schema/upgrade/spacewalk-schema-2.4-to-spacewalk-schema-2.5/171-create_first_org.sql  --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
-- This creates an org with ID of 1, and errors if there already is one
--

create or replace function
create_first_org
(
	name_in in varchar,
	password_in in varchar
)
returns void as
$$
declare
	ug_type			numeric;
	group_val		numeric;
begin
	insert into web_customer (
		id, name
	) values (
		1, name_in
	);

	select nextval( 'rhn_user_group_id_seq' ) into group_val from dual;

	select	id
	into	ug_type
	from	rhnUserGroupType
	where	label = 'org_admin';

	insert into rhnUserGroup (
		id, name,
		description,
		max_members, group_type, org_id
	) values (
		group_val, 'Organization Administrators',
		'Organization Administrators for Org ' || name_in || ' (1)',
		NULL, ug_type, 1
	);

	select nextval('rhn_user_group_id_seq') into group_val from dual;

	select	id
	into	ug_type
	from	rhnUserGroupType
	where	label = 'system_group_admin';

	insert into rhnUserGroup (
		id, name,
		description,
		max_members, group_type, org_id
	) values (
		group_val, 'System Group Administrators',
		'System Group Administrators for Org ' || name_in || ' (1)',
		NULL, ug_type, 1
	);


	select nextval('rhn_user_group_id_seq') into group_val from dual;

	select	id
	into	ug_type
	from	rhnUserGroupType
	where	label = 'activation_key_admin';

	insert into rhnUserGroup (
		id, name,
		description,
		max_members, group_type, org_id
	) values (
		group_val, 'Activation Key Administrators',
		'Activation Key Administrators for Org ' || name_in || ' (1)',
		NULL, ug_type, 1
	);

	select nextval('rhn_user_group_id_seq') into group_val from dual;

	select	id
	into	ug_type
	from	rhnUserGroupType
	where	label = 'channel_admin';

	insert into rhnUserGroup (
		id, name,
		description,
		max_members, group_type, org_id
	) values (
		group_val, 'Channel Administrators',
		'Channel Administrators for Org ' || name_in || ' (1)',
		NULL, ug_type, 1
	);

	select nextval('rhn_user_group_id_seq') into group_val from dual;

	select	id
	into	ug_type
	from	rhnUserGroupType
	where	label = 'satellite_admin';

	insert into rhnUserGroup (
		id, name,
		description,
		max_members, group_type, org_id
	) values (
		group_val, 'Satellite Administrators',
		'Satellite Administrators for Org ' || name_in || ' (1)',
		NULL, ug_type, 1
	);

	select nextval('rhn_user_group_id_seq') into group_val from dual;

	select	id
	into	ug_type
	from	rhnUserGroupType
	where	label = 'config_admin';

	insert into rhnUserGroup (
		id, name,
		description,
		max_members, group_type, org_id
	) values (
		group_val, 'Configuration Administrators',
		'Configuration Administrators for Org ' || name_in || ' (1)',
		NULL, ug_type, 1
	);

	-- there aren't any users yet, so we don't need to update
	-- rhnUserServerPerms

        insert into rhnServerGroup
                ( id, name, description, group_type, org_id )
                select nextval('rhn_server_group_id_seq'), sgt.name, sgt.name,
                        sgt.id, 1
                from rhnServerGroupType sgt
                where sgt.label = 'bootstrap_entitled';

        insert into rhnServerGroup
                ( id, name, description, group_type, org_id )
                select nextval('rhn_server_group_id_seq'), sgt.name, sgt.name,
                        sgt.id, 1
                from rhnServerGroupType sgt
                where sgt.label = 'enterprise_entitled';

        insert into rhnServerGroup
                ( id, name, description, group_type, org_id )
                select nextval('rhn_server_group_id_seq'), sgt.name, sgt.name,
                        sgt.id, 1
                from rhnServerGroupType sgt
                where sgt.label = 'virtualization_host';

        -- set org entitlements
        insert into rhnOrgEntitlements (org_id, entitlement_id)
               select 1, oet.id from rhnOrgEntitlementType oet
                where oet.label = 'sw_mgr_enterprise';

        insert into rhnOrgEntitlements (org_id, entitlement_id)
               select 1, oet.id from rhnOrgEntitlementType oet
                where oet.label = 'rhn_virtualization';

end
$$ language plpgsql;

 07070100000864000081B400000000000000000000000167AE1114000014FD000000000000000000000000000000000000005F00000000susemanager-schema/upgrade/spacewalk-schema-2.4-to-spacewalk-schema-2.5/172-create_new_org.sql    --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--

create or replace function create_new_org
(
        name_in      in varchar,
        password_in  in varchar
        --org_id_out   out NUMERIC
) returns numeric
as
$$
declare
        ug_type                 numeric;
        group_val               numeric;
        new_org_id              numeric;
        org_id_out		numeric;
begin

        select nextval('web_customer_id_seq') into new_org_id;

        insert into web_customer (
                id, name
        ) values (
                new_org_id, name_in
        );

        select nextval('rhn_user_group_id_seq') into group_val;

        select  id
        into    ug_type
        from    rhnUserGroupType
        where   label = 'org_admin';

        insert into rhnUserGroup (
                id, name,
                description,
                max_members, group_type, org_id
        ) values (
                group_val, 'Organization Administrators',
                'Organization Administrators for Org ' || name_in,
                NULL, ug_type, new_org_id
        );

        select nextval('rhn_user_group_id_seq') into group_val;

        select  id
        into    ug_type
        from    rhnUserGroupType
        where   label = 'system_group_admin';

        insert into rhnUserGroup (
                id, name,
                description,
                max_members, group_type, org_id
        ) values (
                group_val, 'System Group Administrators',
                'System Group Administrators for Org ' || name_in,
                NULL, ug_type, new_org_id
        );


        select nextval('rhn_user_group_id_seq') into group_val;

        select  id
        into    ug_type
        from    rhnUserGroupType
        where   label = 'activation_key_admin';

        insert into rhnUserGroup (
                id, name,
                description,
                max_members, group_type, org_id
        ) values (
                group_val, 'Activation Key Administrators',
                'Activation Key Administrators for Org ' || name_in,
                NULL, ug_type, new_org_id
        );

        select nextval('rhn_user_group_id_seq') into group_val;

        select  id
        into    ug_type
        from    rhnUserGroupType
        where   label = 'channel_admin';

        insert into rhnUserGroup (
                id, name,
                description,
                max_members, group_type, org_id
        ) values (
                group_val, 'Channel Administrators',
                'Channel Administrators for Org ' || name_in,
                NULL, ug_type, new_org_id
        );

        select nextval('rhn_user_group_id_seq') into group_val from dual;

        select  id
        into    ug_type
        from    rhnUserGroupType
        where   label = 'config_admin';

        insert into rhnUserGroup (
                id, name,
                description,
                max_members, group_type, org_id
        ) values (
                group_val, 'Configuration Administrators',
                'Configuration Administrators for Org ' || name_in,
                NULL, ug_type, new_org_id
        );

        -- there aren't any users yet, so we don't need to update
        -- rhnUserServerPerms

        insert into rhnServerGroup
                ( id, name, description, group_type, org_id )
                select nextval('rhn_server_group_id_seq'), sgt.name, sgt.name,
                        sgt.id, new_org_id
                from rhnServerGroupType sgt
                where sgt.label = 'bootstrap_entitled';

        insert into rhnServerGroup
                ( id, name, description, group_type, org_id )
                select nextval('rhn_server_group_id_seq'), sgt.name, sgt.name,
                        sgt.id, new_org_id
                from rhnServerGroupType sgt
                where sgt.label = 'enterprise_entitled';

        insert into rhnServerGroup
                ( id, name, description, group_type, org_id )
                select nextval('rhn_server_group_id_seq'), sgt.name, sgt.name,
                        sgt.id, new_org_id
                from rhnServerGroupType sgt
                where sgt.label = 'virtualization_host';

        -- set org entitlements
        insert into rhnOrgEntitlements (org_id, entitlement_id)
               select new_org_id, oet.id from rhnOrgEntitlementType oet
                where oet.label = 'sw_mgr_enterprise';

        insert into rhnOrgEntitlements (org_id, entitlement_id)
               select new_org_id, oet.id from rhnOrgEntitlementType oet
                where oet.label = 'rhn_virtualization';

        org_id_out := new_org_id;

	-- Returning the value of OUT parameter
        return org_id_out;

end;
$$
language plpgsql;


   07070100000865000081B400000000000000000000000167AE111400002C1B000000000000000000000000000000000000006500000000susemanager-schema/upgrade/spacewalk-schema-2.4-to-spacewalk-schema-2.5/174-rhn_entitlements.pkb.sql  --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

-- create schema rhn_entitlements;

-- setup search_path so that these functions are created in appropriate schema.
update pg_settings set setting = 'rhn_entitlements,' || setting where name = 'search_path';

   create or replace function find_compatible_sg (
      server_id_in in numeric,
      type_label_in in varchar
   )
   returns numeric
as $$
    declare
      servergroups cursor for
         select sg.id
           from rhnServerGroupType             sgt,
                rhnServerGroup                 sg,
                rhnServer                     s,
                rhnServerServerGroupArchCompat ssgac
          where s.id = server_id_in
            and s.org_id = sg.org_id
            and sgt.label = type_label_in
            and sg.group_type = sgt.id
            and ssgac.server_group_type = sgt.id
            and ssgac.server_arch_id = s.server_arch_id
            and not exists (
                     select 1
                      from rhnServerGroupMembers sgm
                     where sgm.server_group_id = sg.id
                       and sgm.server_id = s.id);


   begin
      for servergroup in servergroups loop
         return servergroup.id;
      end loop;

      --no servergroup found
      return NULL;
   end$$
language plpgsql;


    create or replace function entitlement_grants_service (
        entitlement_in in varchar,
        service_level_in in varchar
    ) returns numeric
as $$
    begin
        if service_level_in = 'management' then
            if entitlement_in = 'enterprise_entitled' then
                return 1;
            else
                return 0;
            end if;
        elsif service_level_in = 'updates' then
            return 1;
        else
            return 0;
        end if;
    end$$
language plpgsql;

   create or replace function can_entitle_server (
      server_id_in   in numeric,
      type_label_in  in varchar
   )
   returns numeric
as $$
    declare
      addon_servergroups cursor (base_label_in varchar,
                                 addon_label_in varchar) for
         select
            addon_id
         from
            rhnSGTypeBaseAddonCompat
         where base_id = lookup_sg_type (base_label_in)
           and addon_id = lookup_sg_type (addon_label_in);

      previous_ent        varchar[];
      is_base_in          char   := 'N';
      is_base_current     char   := 'N';
      i                   numeric := 0;
      sgid                numeric := 0;

   begin

      previous_ent := rhn_entitlements.get_server_entitlement(server_id_in);

      select distinct is_base
      into is_base_in
      from rhnServerGroupType
      where label = type_label_in;

      if array_upper(previous_ent, 1) is null or array_upper(previous_ent, 1) = 0 then
         if is_base_in = 'Y' then
            sgid := rhn_entitlements.find_compatible_sg (server_id_in, type_label_in);
            if sgid is not null then
              -- rhn_server.insert_into_servergroup (server_id_in, sgid);
              return 1;
            else
              -- rhn_exception.raise_exception ('invalid_base_entitlement');
              return 0;
            end if;
         else
            -- rhn_exception.raise_exception ('invalid_base_entitlement');
            return 0;
         end if;

      -- there are previous ents, first make sure we're not trying to entitle a base ent
      elsif is_base_in = 'Y' then
         -- rhn_exception.raise_exception ('invalid_addon_entitlement');
         return 0;

      -- it must be an addon, so proceed with the entitlement
      else

         -- find the servers base ent
         is_base_current := 'N';
         i := 0;
         while is_base_current = 'N' and i < array_upper(previous_ent, 1)
         loop
            i := i + 1;
            select is_base
            into is_base_current
            from rhnServerGroupType
            where label = previous_ent[i];
         end loop;

         -- never found a base ent, that would be strange
         if is_base_current  = 'N' then
            -- rhn_exception.raise_exception ('invalid_base_entitlement');
            return 0;
         end if;

         -- this for loop verifies the validity of the addon path
         for addon_servergroup in addon_servergroups  (previous_ent[i], type_label_in) loop
            -- find an appropriate sgid for the addon and entitle the server
            sgid := rhn_entitlements.find_compatible_sg (server_id_in, type_label_in);
            if sgid is not null then
               -- rhn_server.insert_into_servergroup (server_id_in, sgid);
               return 1;
            else
               -- rhn_exception.raise_exception ('invalid_addon_entitlement');
               return 0;
            end if;
         end loop;

      end if;

      return 0;

   end$$
language plpgsql;

   create or replace function can_switch_base (
      server_id_in   in    integer,
      type_label_in  in    varchar
   )
   returns numeric
as $$
   declare
      type_label_in_is_base   char(1);
      sgid                    numeric;

   begin

       select is_base into type_label_in_is_base
       from rhnServerGroupType
       where label = type_label_in;

       if not found then
          perform rhn_exception.raise_exception ( 'invalid_entitlement' );
       end if;

      if type_label_in_is_base = 'N' then
         perform rhn_exception.raise_exception ( 'invalid_entitlement' );
      else
         sgid := rhn_entitlements.find_compatible_sg ( server_id_in,
                                                       type_label_in );
         if sgid is not null then
           return 1;
         else
           return 0;
         end if;
      end if;

   end$$
language plpgsql;

    create or replace function entitle_server (
        server_id_in in numeric,
        type_label_in in varchar
    ) returns void
as $$
    declare
      sgid  numeric := 0;

    begin

      if rhn_entitlements.can_entitle_server(server_id_in,
                                             type_label_in) = 1 then
         sgid := rhn_entitlements.find_compatible_sg (server_id_in,
                                                      type_label_in);
         if sgid is not null then
            insert into rhnServerHistory ( id, server_id, summary, details )
            values ( nextval('rhn_event_id_seq'), server_id_in,
                     'added system entitlement ',
                      case type_label_in
                       when 'enterprise_entitled' then 'Management'
                       when 'virtualization_host' then 'Virtualization'
                      end  );

            perform rhn_server.insert_into_servergroup (server_id_in, sgid);

         else
            perform rhn_exception.raise_exception ('no_available_server_group');
         end if;
      else
         perform rhn_exception.raise_exception ('invalid_entitlement');
      end if;
   end$$
language plpgsql;

    create or replace function remove_server_entitlement (
        server_id_in in numeric,
        type_label_in in varchar
    ) returns void
as $$
    declare
      group_id numeric;
      type_is_base char;
    begin

        select  sg.id, sgt.is_base
        into group_id, type_is_base
        from    rhnServerGroupType sgt,
            rhnServerGroup sg,
                rhnServerGroupMembers sgm,
                rhnServer s
        where   s.id = server_id_in
            and s.id = sgm.server_id
            and sgm.server_group_id = sg.id
            and sg.org_id = s.org_id
            and sgt.label = type_label_in
            and sgt.id = sg.group_type;

        if not found then
          perform rhn_exception.raise_exception('invalid_server_group_member');
        end if;

      if ( type_is_base = 'Y' ) then
         -- unentitle_server should handle everything, don't really need to do anything else special here
         perform rhn_entitlements.unentitle_server ( server_id_in );
      else

         insert into rhnServerHistory ( id, server_id, summary, details )
         values ( nextval('rhn_event_id_seq'), server_id_in,
                  'removed system entitlement ',
                   case type_label_in
                    when 'enterprise_entitled' then 'Management'
                    when 'virtualization_host' then 'Virtualization'
                   end  );

         perform rhn_server.delete_from_servergroup(server_id_in, group_id);

      end if;

    end$$
language plpgsql;

    create or replace function unentitle_server (
        server_id_in in numeric
    ) returns void
as $$
    declare
      servergroups cursor for
         select distinct sgt.label, sg.id server_group_id
         from  rhnServerGroupType sgt,
               rhnServerGroup sg,
               rhnServer s,
               rhnServerGroupMembers sgm
         where s.id = server_id_in
            and s.org_id = sg.org_id
            and sg.group_type = sgt.id
            and sgm.server_group_id = sg.id
            and sgm.server_id = s.id;

   begin

      for servergroup in servergroups loop

         insert into rhnServerHistory ( id, server_id, summary, details )
         values ( nextval('rhn_event_id_seq'), server_id_in,
                  'removed system entitlement ',
                   case servergroup.label
                    when 'enterprise_entitled' then 'Management'
                    when 'virtualization_host' then 'Virtualization'
                   end  );

         perform rhn_server.delete_from_servergroup(server_id_in,
                                            servergroup.server_group_id );
      end loop;

   end$$
language plpgsql;


    create or replace function get_server_entitlement (
        server_id_in in numeric
    ) returns varchar[]
as $$
    declare
        server_groups cursor for
            select  sgt.label
            from    rhnServerGroupType      sgt,
                    rhnServerGroup          sg,
                    rhnServerGroupMembers   sgm
            where   1=1
                and sgm.server_id = server_id_in
                and sg.id = sgm.server_group_id
                and sgt.id = sg.group_type
                and sgt.label in (
                    'enterprise_entitled',
                    'virtualization_host'
                    );

         ent_array varchar[];

    begin

      ent_array := '{}';

      for sg in server_groups loop
         ent_array := ent_array || sg.label;
      end loop;

      return ent_array;

    end$$
language plpgsql;

-- restore the original setting
update pg_settings set setting = overlay( setting placing '' from 1 for (length('rhn_entitlements')+1) ) where name = 'search_path';
 07070100000866000081B400000000000000000000000167AE111400001C31000000000000000000000000000000000000005C00000000susemanager-schema/upgrade/spacewalk-schema-2.4-to-spacewalk-schema-2.5/175-rhn_org.pkb.sql   --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--

-- create schema rhn_org;

-- setup search_path so that these functions are created in appropriate schema.
update pg_settings set setting = 'rhn_org,' || setting where name = 'search_path';


create or replace function delete_org (
        org_id_in in numeric
    ) returns void
    as
    $$
    declare
        users cursor for
        select id
        from web_contact
        where org_id = org_id_in;

        servers cursor (org_id_in numeric) for
        select  id
        from    rhnServer
        where   org_id = org_id_in;

        config_channels cursor for
        select id
        from rhnConfigChannel
        where org_id = org_id_in;

        custom_channels cursor for
        select  id
        from    rhnChannel
        where   org_id = org_id_in;

        errata cursor for
        select  id
        from    rhnErrata
        where   org_id = org_id_in;

    begin

        if org_id_in = 1 then
            perform rhn_exception.raise_exception('cannot_delete_base_org');
        end if;

        -- Delete all users.
        for u in users loop
            perform rhn_org.delete_user(u.id, 1);
        end loop;

        -- Delete all servers.
        for s in servers(org_id_in) loop
            perform delete_server(s.id);
        end loop;

        -- Delete all config channels.
        for c in config_channels loop
            perform rhn_config.delete_channel(c.id);
        end loop;

        -- Delete all custom channels.
        for cc in custom_channels loop
          delete from rhnServerChannel where channel_id = cc.id;
          delete from rhnServerProfilePackage where server_profile_id in (
            select id from rhnServerProfile where base_channel = cc.id
          );
          delete from rhnServerProfile where base_channel = cc.id;
        end loop;

        -- Delete all errata packages 
        for e in errata loop
            delete from rhnErrataPackage where errata_id = e.id;
        end loop;

        -- Clean up tables where we don't have a cascading delete.
        delete from rhnChannel where org_id = org_id_in;
        delete from rhnDailySummaryQueue where org_id = org_id_in;
        delete from rhnFileList where org_id = org_id_in;
        delete from rhnServerGroup where org_id = org_id_in;
        delete from rhnContentSource where org_id = org_id_in;

        -- Delete the org.
        delete from web_customer where id = org_id_in;

    end;
    $$
    language plpgsql;

create or replace function delete_user(user_id_in in numeric, deleting_org in numeric default 0) returns void 
    as
    $$
    declare
    servergroups_needing_admins cursor for
            select    usgp.server_group_id    server_group_id
            from    rhnUserServerGroupPerms    usgp
            where    1=1
                and usgp.user_id = user_id_in
                and not exists (
                    select    1
                    from    rhnUserServerGroupPerms    sq_usgp
                    where    1=1
                        and sq_usgp.server_group_id = usgp.server_group_id
                        and    sq_usgp.user_id != user_id_in
                );
        users            numeric;
        our_org_id        numeric;
        other_users        numeric;
        other_org_admin    numeric;
        other_user_id  numeric;
        is_admin       numeric;
    begin
        select    wc.org_id
        into    our_org_id
        from    web_contact wc
        where    id = user_id_in;

        -- find any other users
        begin
            select    id, 1
            into    other_user_id, other_users
            from    web_contact
            where    1=1
                and org_id = our_org_id
                and id != user_id_in
                limit 1;
        exception
            when no_data_found then
                other_users := 0;
        end;

        -- now do org admin stuff
        if other_users != 0 then
            -- is user admin?
            select  count(1)
             into   is_admin
            from    rhnUserGroupType    ugt,
                    rhnUserGroup        ug,
                    rhnUserGroupMembers    ugm
            where    ugm.user_id = user_id_in
                and ugm.user_group_id = ug.id
                and ug.group_type = ugt.id
                and ugt.label = 'org_admin';
            if is_admin > 0 then
                begin
                    select    new_ugm.user_id
                    into    other_org_admin
                    from    rhnUserGroupMembers    new_ugm,
                            rhnUserGroupType    ugt,
                            rhnUserGroup        ug,
                            rhnUserGroupMembers    ugm
                    where    ugm.user_id = user_id_in
                        and ugm.user_group_id = ug.id
                        and ug.group_type = ugt.id
                        and ugt.label = 'org_admin'
                        and ug.id = new_ugm.user_group_id
                        and new_ugm.user_id != user_id_in
                        limit 1;
                exception
                    when no_data_found then
                        -- If we're deleting the org, we don't want to raise
                        -- the exception.
                        if deleting_org = 0 then
                           perform rhn_exception.raise_exception('cannot_delete_user');
                        end if;
                end;

                for sg in servergroups_needing_admins loop
                   perform rhn_user.add_servergroup_perm(other_org_admin,
                        sg.server_group_id);
                end loop;
            end if;
        end if;

        -- and now things for every user
        delete from rhnUserServerPerms where user_id = user_id_in;
        update rhnConfigRevision
           set changed_by_id = NULL
         where changed_by_id = user_id_in;
        if other_users != 0 then
            update        rhnRegToken
                set        user_id = coalesce(other_org_admin, other_user_id)
                where    org_id = our_org_id
                    and user_id = user_id_in;
        end if;

        begin
            delete from web_contact where id = user_id_in;
        exception
            when others then
               perform rhn_exception.raise_exception('cannot_delete_user');
        end;
        return;

        end;
        $$
        language plpgsql;


-- restore the original setting
update pg_settings set setting = overlay( setting placing '' from 1 for (length('rhn_org')+1) ) where name = 'search_path';
   07070100000867000081B400000000000000000000000167AE111400004F22000000000000000000000000000000000000005F00000000susemanager-schema/upgrade/spacewalk-schema-2.4-to-spacewalk-schema-2.5/177-rhn_server.pkb.sql    --
-- Copyright (c) 2008--2014 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--

-- create schema rhn_server;

--update pg_setting
update pg_settings set setting = 'rhn_server,' || setting where name = 'search_path';

    create or replace function system_service_level(
    	server_id_in in numeric,
	service_level_in in varchar
    ) returns numeric as $$
    declare
    ents cursor is 
      select label from rhnServerEntitlementView
      where server_id = server_id_in;

    retval numeric := 0;

    begin
         for ent in ents loop
            retval := rhn_entitlements.entitlement_grants_service (ent.label, service_level_in);
            if retval = 1 then
               return retval;
            end if;
         end loop;

         return retval;

    end$$ language plpgsql;

        
    create or replace function can_change_base_channel(server_id_in IN NUMERIC)
    returns numeric
    as $$
    declare
    	throwaway numeric;
    begin
    	-- the idea: if we get past this query, the server is
	-- neither sat nor proxy, so base channel is changeable

	select 1 into throwaway
	  from rhnServer S
	 where S.id = server_id_in
	   and not exists (select 1 from rhnSatelliteInfo SI where SI.server_id = S.id)
	   and not exists (select 1 from rhnProxyInfo PI where PI.server_id = S.id);

        if not found then
	    return 0;
        end if;
	   
	return 1;
    end$$ language plpgsql;
	        
    create or replace function set_custom_value(
    	server_id_in in numeric,
	user_id_in in numeric,
	key_label_in in varchar,
	value_in in varchar
    ) returns void
    as $$
    declare
    	key_id_val numeric;
    begin
    	select CDK.id into strict key_id_val
	  from rhnCustomDataKey CDK,
	       rhnServer S
	 where S.id = server_id_in
	   and S.org_id = CDK.org_id
	   and CDK.label = key_label_in;
	   
	begin
	    insert into rhnServerCustomDataValue (server_id, key_id, value, created_by, last_modified_by)
	    values (server_id_in, key_id_val, value_in, user_id_in, user_id_in);
	exception
	    when UNIQUE_VIOLATION
	    	then
		update rhnServerCustomDataValue
		   set value = value_in,
		       last_modified_by = user_id_in
		 where server_id = server_id_in
		   and key_id = key_id_val;		   
	end;

    end$$ language plpgsql;
    
    create or replace function bulk_set_custom_value(
    	key_label_in in varchar,
	value_in in varchar,
	set_label_in in varchar,
	set_uid_in in numeric
    )
    returns integer
    as $$
    declare
        i integer;
        server record;
    begin
        i := 0;
        for server in (
           SELECT user_id, label, element, element_two
	     FROM rhnSet
	    WHERE label = set_label_in
	      AND user_id = set_uid_in
	) loop
	    if rhn_server.system_service_level(server.element, 'management') = 1 then
	    	perform rhn_server.set_custom_value(server.element, set_uid_in, key_label_in, value_in);
            i := i + 1;
	    end if;
	end loop;
    return i;
    end$$ language plpgsql;

    create or replace function bulk_snapshot_tag(
    	org_id_in in numeric,
        tagname_in in varchar,
	set_label_in in varchar,
	set_uid_in in numeric
    ) returns void
    as $$
    declare
        server record;
    	snapshot_id numeric;
    begin
        for server in (
           SELECT user_id, label, element, element_two
	     FROM rhnSet
	    WHERE label = set_label_in
	      AND user_id = set_uid_in
	    ) loop
	    if rhn_server.system_service_level(server.element, 'management') = 1 then
	    	    select max(id) into snapshot_id
	    	    from rhnSnapshot
	    	    where server_id = server.element;

	    	    if snapshot_id is null then
		    	perform rhn_server.snapshot_server(server.element, 'tagging system:  ' || tagname_in);
			
			select max(id) into snapshot_id
			from rhnSnapshot
			where server_id = server.element;
		    end if;
		 
		-- now have a snapshot_id to work with...
		begin
		    perform rhn_server.tag_snapshot(snapshot_id, org_id_in, tagname_in);
		exception
		    when UNIQUE_VIOLATION
		    	then
			-- do nothing, be forgiving...
			null;
		end;
	    end if;
	end loop;    
    end$$ language plpgsql;

    create or replace function tag_delete(
    	server_id_in in numeric,
	tag_id_in in numeric
    ) returns void
    as $$
    declare
    	snapshots cursor is
		select	snapshot_id
		from	rhnSnapshotTag
		where	tag_id = tag_id_in;
	tag_id_tmp numeric;
    begin
    	select	id into tag_id_tmp
	from	rhnTag
	where	id = tag_id_in
	for update;

	delete
		from	rhnSnapshotTag
		where	server_id = server_id_in
			and tag_id = tag_id_in;
	for snapshot in snapshots loop
		return;
	end loop;
	delete
		from rhnTag
		where id = tag_id_in;
    end$$ language plpgsql;

    create or replace function tag_snapshot(
        snapshot_id_in in numeric,
	org_id_in in numeric,
	tagname_in in varchar
    ) returns void
    as $$
    begin
    	insert into rhnSnapshotTag (snapshot_id, server_id, tag_id)
	select snapshot_id_in, server_id, lookup_tag(org_id_in, tagname_in)
	from rhnSnapshot
	where id = snapshot_id_in;
    end$$ language plpgsql;

    create or replace function bulk_snapshot(
    	reason_in in varchar,
	set_label_in in varchar,
	set_uid_in in numeric
    ) returns void
    as $$
    declare
        server record;
    begin
        for server in (
           SELECT user_id, label, element, element_two
	     FROM rhnSet
	    WHERE label = set_label_in
	      AND user_id = set_uid_in
	    ) loop
	    if rhn_server.system_service_level(server.element, 'management') = 1 then
	    	perform rhn_server.snapshot_server(server.element, reason_in);
	    end if;
	end loop;
    end$$ language plpgsql;

    create or replace function snapshot_server(
    	server_id_in in numeric,
	reason_in in varchar
    ) returns void
    as $$
    declare
    	snapshot_id_v numeric;
	revisions cursor is
		select distinct
			cr.id
		from	rhnConfigRevision	cr,
			rhnConfigFileName	cfn,
			rhnConfigFile		cf,
			rhnConfigChannel	cc,
			rhnServerConfigChannel	scc
		where	1=1
			and scc.server_id = server_id_in
			and scc.config_channel_id = cc.id
			and cc.id = cf.config_channel_id
			and cf.id = cr.config_file_id
			and cr.id = cf.latest_config_revision_id
			and cf.config_file_name_id = cfn.id
			and cf.id = lookup_first_matching_cf(scc.server_id, cfn.path);
	locked integer;
    begin
    	select nextval('rhn_snapshot_id_seq') into snapshot_id_v;

	insert into rhnSnapshot (id, org_id, server_id, reason) (
		select	snapshot_id_v,
			s.org_id,
			server_id_in,
			reason_in
		from	rhnServer s
		where	s.id = server_id_in
	);
	insert into rhnSnapshotChannel (snapshot_id, channel_id) (
		select	snapshot_id_v, sc.channel_id
		from	rhnServerChannel sc
		where	sc.server_id = server_id_in
	);
	insert into rhnSnapshotServerGroup (snapshot_id, server_group_id) (
		select	snapshot_id_v, sgm.server_group_id
		from	rhnServerGroupMembers sgm
		where	sgm.server_id = server_id_in
	);
        locked := 0;
        <<iloop>>
        while true loop
            begin
                insert into rhnPackageNEVRA (id, name_id, evr_id, package_arch_id)
                select nextval('rhn_pkgnevra_id_seq'), sp.name_id, sp.evr_id, sp.package_arch_id
                from rhnServerPackage sp
                where sp.server_id = server_id_in
                        and not exists
                        (select 1
                                from rhnPackageNEVRA nevra
                                where nevra.name_id = sp.name_id
                                        and nevra.evr_id = sp.evr_id
                                        and (nevra.package_arch_id = sp.package_arch_id
                                            or (nevra.package_arch_id is null
                                                and sp.package_arch_id is null)));
                exit iloop;
            exception when unique_violation then
                if locked = 1 then
                    raise;
                else
                    lock table rhnPackageNEVRA in exclusive mode;
                    locked := 1;
                end if;
            end;
        end loop;
	insert into rhnSnapshotPackage (snapshot_id, nevra_id) (
                select distinct snapshot_id_v, nevra.id
                from    rhnServerPackage sp, rhnPackageNEVRA nevra
                where   sp.server_id = server_id_in
                        and nevra.name_id = sp.name_id
                        and nevra.evr_id = sp.evr_id
                        and (nevra.package_arch_id = sp.package_arch_id
                            or (nevra.package_arch_id is null
                                and sp.package_arch_id is null))
	);

	insert into rhnSnapshotConfigChannel ( snapshot_id, config_channel_id ) (
		select	snapshot_id_v, scc.config_channel_id
		from	rhnServerConfigChannel scc
		where	server_id = server_id_in
	);

	for revision in revisions loop
		insert into rhnSnapshotConfigRevision (
				snapshot_id, config_revision_id
			) values (
				snapshot_id_v, revision.id
			);
	end loop;
    end$$ language plpgsql;

    create or replace function remove_action(
    	server_id_in in numeric,
	action_id_in in numeric
    ) returns void
    as $$
    declare
    	-- this really wants "nulls last", but 8.1.7.3.0 sucks ass.
	-- instead, we make a local table that holds our
	-- list of ids with null prereqs.  There's surely a better way
	-- (an array instead of a table maybe?  who knows...)
	-- but I've got code to do this handy that I can look at ;)
    	chained_actions cursor is
                with recursive r(id, prerequisite) as (
			select	id, prerequisite
			from	rhnAction
			where id = action_id_in
		union all
			select	r1.id, r1.prerequisite
			from	rhnAction r1, r
			where r.id = r1.prerequisite
		)
		select * from r
		order by prerequisite desc;
	sessions cursor is
		select	s.id
		from	rhnKickstartSession s
		where	server_id_in in (s.old_server_id, s.new_server_id)
			and s.action_id = action_id_in
			and not exists (
				select	1
				from	rhnKickstartSessionState ss
				where	ss.id = s.state_id
					and ss.label in ('failed','complete')
			);
	chain_ends numeric[];
	i numeric;
	prereq numeric := 1;
    begin
	select	prerequisite
	into	prereq
	from	rhnAction
	where	id = action_id_in;

	if prereq is not null then
		perform rhn_exception.raise_exception('action_is_child');
	end if;

        chain_ends := '{}';
	i := 1;
	for action in chained_actions loop
		if action.prerequisite is null then
			chain_ends[i] := action.id;
			i := i + 1;
		else
			delete from rhnServerAction
				where server_id = server_id_in
				and action_id = action.id;
		end if;
	end loop;

	delete from rhnServerAction
		where server_id = server_id_in
		and action_id = any(chain_ends);

	for s in sessions loop
		update rhnKickstartSession
			set 	state_id = (
					select	id
					from	rhnKickstartSessionState
					where	label = 'failed'
				),
				action_id = null
			where	id = s.id;
		perform set_ks_session_history_message(s.id, 'failed', 'Kickstart cancelled due to action removal');
	end loop;
    end$$ language plpgsql;
   
    create or replace function check_user_access(server_id_in in numeric, user_id_in in numeric)
    returns numeric
    as $$
    declare
    	has_access numeric;
    begin
    	-- first check; if this returns no rows, then the server/user are in different orgs, and we bail
        select 1 into has_access
	  from rhnServer S,
	       web_contact wc
	 where wc.org_id = s.org_id
	   and s.id = server_id_in
	   and wc.id = user_id_in;

        if not found then
          return 0;
        end if;

	-- okay, so they're in the same org.  if we have an org admin, they get a free pass
    	if rhn_user.check_role(user_id_in, 'org_admin') = 1
	then
	    return 1;
	end if;
		   
    	select 1 into has_access
	  from rhnServerGroupMembers SGM,
	       rhnUserServerGroupPerms USG
	 where SGM.server_group_id = USG.server_group_id
	   and SGM.server_id = server_id_in
	   and USG.user_id = user_id_in;

        if not found then
          return 0;
        end if;
	   
	return 1;
    end$$ language plpgsql;

    create or replace function insert_into_servergroup (
		server_id_in in numeric,
		server_group_id_in in numeric
    ) returns void
    as $$
    declare
		group_type numeric;
	begin
		-- this will rowlock the servergroup we're trying to change;
		-- we probably need to lock the other one, but I think the chances
		-- of it being a real issue are very small for now...
		select	sg.group_type
		into	group_type
		from	rhnServerGroup sg
		where	sg.id = server_group_id_in
		for update of sg;

		insert into rhnServerGroupMembers(server_id, server_group_id)
		values (server_id_in, server_group_id_in);

		update rhnServerGroup
		set current_members = current_members + 1
		where id = server_group_id_in;

		if group_type is null then
			perform rhn_cache.update_perms_for_server_group(server_group_id_in);
		end if;

		return;
	end$$ language plpgsql;

	create or replace function insert_into_servergroup_maybe (
		server_id_in in numeric,
		server_group_id_in in numeric
	) returns numeric as $$ 
    declare
		retval numeric := 0;
		servergroups cursor is
			select	s.id	server_id,
					sg.id	server_group_id
			from	rhnServerGroup	sg,
					rhnServer		s
			where	s.id = server_id_in
				and sg.id = server_group_id_in
				and s.org_id = sg.org_id
				and not exists (
					select	1
					from	rhnServerGroupMembers sgm
					where	sgm.server_id = s.id
						and sgm.server_group_id = sg.id
				);
	begin
		for sgm in servergroups loop
			perform rhn_server.insert_into_servergroup(sgm.server_id, sgm.server_group_id);
			retval := retval + 1;
		end loop;
		return retval;
	end$$ language plpgsql;

	create or replace function insert_set_into_servergroup (
		server_group_id_in in numeric,
		user_id_in in numeric,
		set_label_in in varchar
	) returns void
        as $$
    declare
		servers cursor is
			select	st.element	id
			from	rhnSet		st
			where	st.user_id = user_id_in
				and st.label = set_label_in
				and exists (
					select	1
					from	rhnUserManagedServerGroups umsg
					where	umsg.server_group_id = server_group_id_in
						and umsg.user_id = user_id_in
					)
				and not exists (
					select	1
					from	rhnServerGroupMembers sgm
					where	sgm.server_id = st.element
						and sgm.server_group_id = server_group_id_in
				);
	begin
		for s in servers loop
			perform rhn_server.insert_into_servergroup(s.id, server_group_id_in);
		end loop;
	end$$ language plpgsql;
		
    create or replace function delete_from_servergroup (
    	server_id_in in numeric,
	server_group_id_in in numeric
    ) returns void
    as $$
    declare

		oid numeric;
		label varchar;
		group_type numeric;
	begin
		select	sg.group_type, sg.org_id
		into	group_type,	oid
		from	rhnServerGroupMembers	sgm,
			rhnServerGroup		sg
		where	sg.id = server_group_id_in
		and 	sg.id = sgm.server_group_id
		and 	sgm.server_id = server_id_in
		for update of sg;

		if not found then
			perform rhn_exception.raise_exception('server_not_in_group');
		end if;

		delete from rhnServerGroupMembers
		where server_group_id = server_group_id_in
		and	server_id = server_id_in;

		update rhnServerGroup
		set current_members = current_members - 1
		where id = server_group_id_in;

		-- do group_type is null first
		if group_type is null then
			perform rhn_cache.update_perms_for_server_group(server_group_id_in);
		end if;

	end$$ language plpgsql;

	create or replace function delete_set_from_servergroup (
		server_group_id_in in numeric,
		user_id_in in numeric,
		set_label_in in varchar
	) returns void
        as $$	
        declare
		servergroups cursor is
			select	sgm.server_id, sgm.server_group_id
			from	rhnSet st,
					rhnServerGroupMembers sgm
			where	sgm.server_group_id = server_group_id_in
				and st.user_id = user_id_in
				and st.label = set_label_in
				and sgm.server_id = st.element
				and exists (
					select	1
					from	rhnUserManagedServerGroups usgp
					where	usgp.server_group_id = server_group_id_in
						and usgp.user_id = user_id_in
				);
	begin
		for sgm in servergroups loop
			perform rhn_server.delete_from_servergroup(sgm.server_id, server_group_id_in);
		end loop;
	end$$ language plpgsql;

	create or replace function clear_servergroup (
		server_group_id_in in numeric
	) returns void
        as $$
        declare
		servers cursor is
			select	sgm.server_id	id
			from	rhnServerGroupMembers sgm
			where	sgm.server_group_id = server_group_id_in;
	begin
		for s in servers loop
			perform rhn_server.delete_from_servergroup(s.id, server_group_id_in);
		end loop;
	end$$ language plpgsql;

	create or replace function delete_from_org_servergroups (
		server_id_in in numeric
	) returns void
        as $$
        declare
		servergroups cursor is
			select	sgm.server_group_id id
			from	rhnServerGroup sg,
					rhnServerGroupMembers sgm
			where	sgm.server_id = server_id_in
				and sgm.server_group_id = sg.id
				and sg.group_type is null;
	begin
		for sg in servergroups loop
			perform rhn_server.delete_from_servergroup(server_id_in, sg.id);
		end loop;
	end$$ language plpgsql;

	create or replace function get_ip_address (
		server_id_in in numeric
	) returns varchar as $$
        declare
		interfaces cursor is
			select	ni.name as name, na4.address as address
			from	rhnServerNetInterface ni,
			        rhnServerNetAddress4 na4
			where	server_id = server_id_in
                and ni.id = na4.interface_id
				and na4.address != '127.0.0.1';
		addresses cursor is
			select	ipaddr ip_addr
			from	rhnServerNetwork
			where	server_id = server_id_in
				and ipaddr != '127.0.0.1';
	begin
		for addr in addresses loop
			return addr.ip_addr;
		end loop;
		for iface in interfaces loop
			return iface.address;
		end loop;
		return NULL;
	end$$ language plpgsql;

    create or replace function update_needed_cache(
        server_id_in in numeric
	) returns void as $$
    declare
      update_lock numeric;
    begin
      select id into update_lock from rhnServer where id = server_id_in for update;
      delete from rhnServerNeededCache
        where server_id = server_id_in;
      insert into rhnServerNeededCache
             (server_id, errata_id, package_id, channel_id)
        (select distinct sp.server_id, x.errata_id, p.id, x.channel_id
           FROM (SELECT sp_sp.server_id, sp_sp.name_id,
		        sp_sp.package_arch_id, max(sp_pe.evr) AS max_evr
                   FROM rhnServerPackage sp_sp
                   join rhnPackageEvr sp_pe ON sp_pe.id = sp_sp.evr_id
                  GROUP BY sp_sp.server_id, sp_sp.name_id, sp_sp.package_arch_id) sp
           join rhnPackage p ON p.name_id = sp.name_id
           join rhnPackageEvr pe ON pe.id = p.evr_id AND sp.max_evr < pe.evr
           join rhnPackageUpgradeArchCompat puac
	            ON puac.package_arch_id = sp.package_arch_id
		    AND puac.package_upgrade_arch_id = p.package_arch_id
           join rhnServerChannel sc ON sc.server_id = sp.server_id
           join rhnChannelPackage cp ON cp.package_id = p.id
	            AND cp.channel_id = sc.channel_id
           left join (SELECT ep.errata_id, ce.channel_id, ep.package_id
                        FROM rhnChannelErrata ce
                        join rhnErrataPackage ep
			         ON ep.errata_id = ce.errata_id
			join rhnServerChannel sc_sc
			         ON sc_sc.channel_id = ce.channel_id
		       WHERE sc_sc.server_id = server_id_in) x
             ON x.channel_id = sc.channel_id AND x.package_id = cp.package_id
          where sp.server_id = server_id_in);
	end$$ language plpgsql;
-- restore the original setting
update pg_settings set setting = overlay( setting placing '' from 1 for (length('rhn_server')+1) ) where name = 'search_path';
  07070100000868000081B400000000000000000000000167AE111400000058000000000000000000000000000000000000005D00000000susemanager-schema/upgrade/spacewalk-schema-2.4-to-spacewalk-schema-2.5/178-rhnexception.sql  DELETE FROM rhnException WHERE id = -20220;
DELETE FROM rhnException WHERE id = -20290;
07070100000869000081B400000000000000000000000167AE111400000DD1000000000000000000000000000000000000005600000000susemanager-schema/upgrade/spacewalk-schema-2.4-to-spacewalk-schema-2.5/179-views.sql DROP VIEW rhnServerGroupMembership;

CREATE OR REPLACE VIEW rhnServerGroupMembership (
         ORG_ID, SERVER_ID, GROUP_ID, GROUP_NAME, GROUP_TYPE, CURRENT_MEMBERS
)
AS
SELECT   SG.org_id, SGM.server_id, SG.id, SG.name, SGT.label, SG.current_members
  FROM
	 rhnServerGroupMembers SGM
             right join
    	 rhnServerGroup SG on (SG.id = SGM.server_group_id)
             left join
         rhnServerGroupType SGT on (SG.group_type = SGT.id)
;

DROP VIEW rhnVisServerGroupMembership;

CREATE OR REPLACE VIEW rhnVisServerGroupMembership (
         ORG_ID, SERVER_ID, GROUP_ID, GROUP_NAME, GROUP_TYPE, CURRENT_MEMBERS
)
AS
SELECT   SG.org_id, SGM.server_id, SG.id, SG.name, SGT.label, SG.current_members
  FROM
	 rhnServerGroupMembers SGM
            right outer join
    	 rhnVisibleServerGroup SG on (SG.id = SGM.server_group_id)
            left outer join
         rhnServerGroupType SGT on (SG.group_type = SGT.id)
;

DROP VIEW rhnVisServerGroupOverviewLite;

DROP VIEW rhnServerGroupOverview;

CREATE OR REPLACE VIEW rhnServerGroupOverview (
         ORG_ID, SECURITY_ERRATA, BUG_ERRATA, ENHANCEMENT_ERRATA, GROUP_ID, GROUP_NAME, GROUP_ADMINS, SERVER_COUNT, MODIFIED
)
AS
  SELECT SG.org_id,
         (SELECT COUNT(distinct E.id)
            FROM rhnErrata E,
                 rhnServerNeededErrataCache SNEC,
                 rhnServerGroupMembers SGM
           WHERE E.advisory_type = 'Security Advisory'
                 and SNEC.errata_id = e.id
                 and SNEC.server_id = sgm.server_id
                 and sgm.server_group_id = sg.id
                 AND EXISTS ( SELECT 1
                              FROM rhnServerFeaturesView SFV
                              WHERE SFV.server_id = SGM.server_id
                                    AND SFV.label = 'ftr_system_grouping')),
         (SELECT COUNT(distinct E.id)
            FROM rhnErrata E,
                 rhnServerNeededErrataCache SNEC,
                 rhnServerGroupMembers SGM
           WHERE E.advisory_type = 'Bug Fix Advisory'
                 and SNEC.errata_id = e.id
                 and SNEC.server_id = sgm.server_id
                 and sgm.server_group_id = sg.id
                 AND EXISTS ( SELECT 1
                              FROM rhnServerFeaturesView SFV
                              WHERE SFV.server_id = SGM.server_id
                                    AND SFV.label = 'ftr_system_grouping')),
         (SELECT COUNT(distinct E.id)
            FROM rhnErrata E,
                 rhnServerNeededErrataCache SNEC,
                 rhnServerGroupMembers SGM
           WHERE E.advisory_type = 'Product Enhancement Advisory'
                 and SNEC.errata_id = e.id
                 and SNEC.server_id = sgm.server_id
                 and sgm.server_group_id = sg.id
                 AND EXISTS ( SELECT 1
                              FROM rhnServerFeaturesView SFV
                              WHERE SFV.server_id = SGM.server_id
                                    AND SFV.label = 'ftr_system_grouping')),
         SG.id, SG.name,
         (SELECT COUNT(*) FROM rhnUserManagedServerGroups UMSG WHERE UMSG.server_group_id = SG.id),
         (SELECT COUNT(*) FROM rhnServerGroupMembers SGM WHERE SGM.server_group_id = SG.id
                 AND EXISTS ( SELECT 1
                              FROM rhnServerFeaturesView SFV
                              WHERE SFV.server_id = SGM.server_id
                                    AND SFV.label = 'ftr_system_grouping')),
         CURRENT_TIMESTAMP
    FROM rhnServerGroup SG;
   0707010000086A000081B400000000000000000000000167AE11140000272C000000000000000000000000000000000000005E00000000susemanager-schema/upgrade/spacewalk-schema-2.4-to-spacewalk-schema-2.5/180-delete_server.sql --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
-- This deletes a server.  All codepaths which delete servers should hit this
-- or delete_server_bulk()

create or replace
function delete_server (
        server_id_in in numeric
) returns void 
as
$$
declare
         servergroups cursor for
                select  server_id, server_group_id
                from    rhnServerGroupMembers sgm
                where   sgm.server_id = server_id_in;

         configchannels cursor for
                select  cc.id
                from    rhnConfigChannel cc,
                        rhnConfigChannelType cct,
                        rhnServerConfigChannel scc
                where   1=1
                        and scc.server_id = server_id_in
                        and scc.config_channel_id = cc.id
                        -- these config channel types are reserved
                        -- for use by a single server, so we don't
                        -- need to check for other servers subscribed
                        and cct.label in
                                ('local_override','server_import')
                        and cct.id = cc.confchan_type_id;

begin
        -- filelists
        delete from rhnFileList where id in (
	select	spfl.file_list_id
	  from	rhnServerPreserveFileList spfl
	 where	spfl.server_id = server_id_in
			and not exists (
				select	1
				from	rhnServerPreserveFileList
				where	file_list_id = spfl.file_list_id
					and server_id != server_id_in
				union all
				select	1
				from	rhnKickstartPreserveFileList
				where	file_list_id = spfl.file_list_id
			)
        );

	for configchannel in configchannels loop
		perform rhn_config.delete_channel(configchannel.id);
	end loop;

	for sgm in servergroups loop
		perform rhn_server.delete_from_servergroup(
			sgm.server_id, sgm.server_group_id);
	end loop;


        -- we're handling this instead of letting an "on delete
        -- set null" do it so that we don't run the risk
        -- of setting off the triggers and killing us with a
        -- mutating table

        -- this is merge of two single updates:
        --  update ... set old_server_id = null where old_server_id = server_id_in;
        --  update ... set new_server_id = null where new_server_id = server_id_in;
        -- so we scan rhnKickstartSession table only once
        update rhnKickstartSession
                set old_server_id = case when old_server_id = server_id_in then null else old_server_id end,
                    new_server_id = case when new_server_id = server_id_in then null else new_server_id end
                where old_server_id = server_id_in
                   or new_server_id = server_id_in;

        perform rhn_channel.clear_subscriptions(server_id_in, 1);

        -- A little complicated here, but the goal is to
        -- delete records from rhnVirtualInstace only if we don't
        -- care about them anymore.  We don't care about records
        -- in rhnVirtualInstance if we are deleting the host
        -- system and the virtual system is already null, or
        -- vice-versa.  We *do* care about them if either the
        -- host or virtual system is still registered because we
        -- still want them to show up in the UI.
    -- If there's a newer row in rhnVirtualInstance with the same
    -- uuid, this guest must have been re-registered, so we can clean
    -- this data up.

        delete from rhnVirtualInstance vi
              where (host_system_id = server_id_in and virtual_system_id is null)
                 or (virtual_system_id = server_id_in and host_system_id is null)
                 or (vi.virtual_system_id = server_id_in and vi.modified < (select max(vi2.modified)
                    from rhnVirtualInstance vi2 where vi2.uuid = vi.uuid));

        -- this is merge of two single updates:
        --  update ... set host_system_id = null where host_system_id = server_id_in;
        --  update ... set virtual_system_id = null where virtual_system_id = server_id_in;
        -- so we scan rhnVirtualInstance table only once
        update rhnVirtualInstance
           set host_system_id = case when host_system_id = server_id_in then null else host_system_id end,
               virtual_system_id = case when virtual_system_id = server_id_in then null else virtual_system_id end
         where host_system_id = server_id_in
            or virtual_system_id = server_id_in;

        -- this is merge of two single updates:
        --  update ... set old_host_system_id = null when old_host_system_id = server_id_in;
        --  update ... set new_host_system_id = null when new_host_system_id = server_id_in;
        -- so we scan rhnVirtualInstanceEventLog table only once
        update rhnVirtualInstanceEventLog
           set old_host_system_id = case when old_host_system_id = server_id_in then null else old_host_system_id end,
               new_host_system_id = case when new_host_system_id = server_id_in then null else new_host_system_id end
         where old_host_system_id = server_id_in
            or new_host_system_id = server_id_in;

        -- We're deleting everything with a foreign key to rhnServer
        -- here, now.  I'm hoping this will help aleviate our deadlock
        -- problem.

        delete from rhnActionConfigChannel where server_id = server_id_in;
        delete from rhnActionConfigRevision where server_id = server_id_in;
        delete from rhnActionPackageRemovalFailure where server_id = server_id_in;
        delete from rhnClientCapability where server_id = server_id_in;
        delete from rhnCpu where server_id = server_id_in;
        -- there's still a cascade here, because the constraint keeps the
        -- table locked for too long to rebuild it.  Ugh...
        delete from rhnDevice where server_id = server_id_in;
        delete from rhnProxyInfo where server_id = server_id_in;
        delete from rhnRam where server_id = server_id_in;
        delete from rhnRegToken where server_id = server_id_in;
        delete from rhnSatelliteInfo where server_id = server_id_in;
        -- this cascades to rhnActionConfigChannel and rhnActionConfigFileName
        delete from rhnServerAction where server_id = server_id_in;
        delete from rhnServerActionPackageResult where server_id = server_id_in;
        delete from rhnServerActionScriptResult where server_id = server_id_in;
        delete from rhnServerActionVerifyResult where server_id = server_id_in;
        delete from rhnServerActionVerifyMissing where server_id = server_id_in;
        -- counts are handled above.  this should be a delete_ function.
        delete from rhnServerChannel where server_id = server_id_in;
        delete from rhnServerConfigChannel where server_id = server_id_in;
        delete from rhnServerCustomDataValue where server_id = server_id_in;
        delete from rhnServerDMI where server_id = server_id_in;
        delete from rhnServerEvent where server_id = server_id_in;
        delete from rhnServerHistory where server_id = server_id_in;
        delete from rhnServerInfo where server_id = server_id_in;
        delete from rhnServerInstallInfo where server_id = server_id_in;
        delete from rhnServerLocation where server_id = server_id_in;
        delete from rhnServerLock where server_id = server_id_in;
        delete from rhnServerNeededCache where server_id = server_id_in;
        delete from rhnServerNetwork where server_id = server_id_in;
        delete from rhnServerNotes where server_id = server_id_in;
        -- I'm not removing the foreign key from rhnServerPackage; that'll
        -- take forever.  Do the delete anyway.
        delete from rhnServerPackage where server_id = server_id_in;
        delete from rhnServerTokenRegs where server_id = server_id_in;
        delete from rhnSnapshotTag where server_id = server_id_in;
        -- this cascades to:
        --   rhnSnapshotChannel, rhnSnapshotConfigChannel, rhnSnapshotPackage,
        --   rhnSnapshotConfigRevision, rhnSnapshotServerGroup,
        --   rhnSnapshotTag.
        -- We may want to consider delete_snapshot() at some point, but
        --   I don't think we need to yet.
        delete from rhnSnapshot where server_id = server_id_in;
        delete from rhnUserServerPrefs where server_id = server_id_in;
        -- hrm, this one's interesting... we _probably_ should delete
        -- everything for the parent server_id when we delete the proxy,
        -- but we don't currently.
        delete from rhnServerPath where server_id_in in (server_id, proxy_server_id);
        delete from rhnUserServerPerms where server_id = server_id_in;

        delete from rhnServerNetInterface where server_id = server_id_in;

        delete from rhnServerUuid where server_id = server_id_in;

        delete from rhnPushClient where server_id = server_id_in;

        -- now get rhnServer itself.
        delete
        from    rhnServer
                where id = server_id_in;

        delete
        from    rhnSet
        where   1=1
                and user_id in (
                        select  wc.id
                        from    rhnServer rs,
                                web_contact wc
                        where   rs.id = server_id_in
                                and rs.org_id = wc.org_id
                )
                and label = 'system_list'
                and element = server_id_in;
end;
$$
language plpgsql;

0707010000086B000081B400000000000000000000000167AE11140000065E000000000000000000000000000000000000006100000000susemanager-schema/upgrade/spacewalk-schema-2.4-to-spacewalk-schema-2.5/181-drop_max_members.sql  
DROP VIEW rhnVisServerGroupMembership;
DROP VIEW rhnUsersInOrgOverview;
DROP VIEW rhnVisibleServerGroup;

ALTER TABLE rhnServerGroup DROP COLUMN max_members;
ALTER TABLE rhnservergroup_log DROP COLUMN max_members;
SELECT .recreate_trigger('rhnservergroup');

CREATE OR REPLACE VIEW
rhnVisibleServerGroup
AS
  SELECT *
    FROM rhnServerGroup SG
   WHERE SG.group_type IS NULL;

create or replace view rhnUsersInOrgOverview as
select    
  u.org_id          as org_id,
  u.id            as user_id,
  u.login           as user_login,
  pi.first_names          as user_first_name,
  pi.last_name          as user_last_name,
  u.modified          as user_modified,
      ( select  count(server_id)
    from  rhnUserServerPerms sp
    where sp.user_id = u.id)
              as server_count,
  ( select  count(server_group_id)
    from  rhnUserManagedServerGroups umsg
    where umsg.user_id = u.id and exists (
      select  1
      from  rhnVisibleServerGroup sg
      where sg.id = umsg.server_group_id))
              as server_group_count,
  coalesce(rhn_user.role_names(u.id), '(normal user)') as role_names
from  web_user_personal_info pi, 
  web_contact u 
where
  u.id = pi.web_user_id;

CREATE OR REPLACE VIEW rhnVisServerGroupMembership (
         ORG_ID, SERVER_ID, GROUP_ID, GROUP_NAME, GROUP_TYPE, CURRENT_MEMBERS
)
AS
SELECT   SG.org_id, SGM.server_id, SG.id, SG.name, SGT.label, SG.current_members
  FROM
   rhnServerGroupMembers SGM
            right outer join
       rhnVisibleServerGroup SG on (SG.id = SGM.server_group_id)
            left outer join
         rhnServerGroupType SGT on (SG.group_type = SGT.id)
;
  0707010000086C000081B400000000000000000000000167AE1114000010B4000000000000000000000000000000000000006100000000susemanager-schema/upgrade/spacewalk-schema-2.4-to-spacewalk-schema-2.5/182-create_first_org.sql  --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
-- This creates an org with ID of 1, and errors if there already is one
--

create or replace function
create_first_org
(
	name_in in varchar,
	password_in in varchar
)
returns void as
$$
declare
	ug_type			numeric;
	group_val		numeric;
begin
	insert into web_customer (
		id, name
	) values (
		1, name_in
	);

	select nextval( 'rhn_user_group_id_seq' ) into group_val from dual;

	select	id
	into	ug_type
	from	rhnUserGroupType
	where	label = 'org_admin';

	insert into rhnUserGroup (
		id, name,
		description,
		max_members, group_type, org_id
	) values (
		group_val, 'Organization Administrators',
		'Organization Administrators for Org ' || name_in || ' (1)',
		NULL, ug_type, 1
	);

	select nextval('rhn_user_group_id_seq') into group_val from dual;

	select	id
	into	ug_type
	from	rhnUserGroupType
	where	label = 'system_group_admin';

	insert into rhnUserGroup (
		id, name,
		description,
		max_members, group_type, org_id
	) values (
		group_val, 'System Group Administrators',
		'System Group Administrators for Org ' || name_in || ' (1)',
		NULL, ug_type, 1
	);


	select nextval('rhn_user_group_id_seq') into group_val from dual;

	select	id
	into	ug_type
	from	rhnUserGroupType
	where	label = 'activation_key_admin';

	insert into rhnUserGroup (
		id, name,
		description,
		max_members, group_type, org_id
	) values (
		group_val, 'Activation Key Administrators',
		'Activation Key Administrators for Org ' || name_in || ' (1)',
		NULL, ug_type, 1
	);

	select nextval('rhn_user_group_id_seq') into group_val from dual;

	select	id
	into	ug_type
	from	rhnUserGroupType
	where	label = 'channel_admin';

	insert into rhnUserGroup (
		id, name,
		description,
		max_members, group_type, org_id
	) values (
		group_val, 'Channel Administrators',
		'Channel Administrators for Org ' || name_in || ' (1)',
		NULL, ug_type, 1
	);

	select nextval('rhn_user_group_id_seq') into group_val from dual;

	select	id
	into	ug_type
	from	rhnUserGroupType
	where	label = 'satellite_admin';

	insert into rhnUserGroup (
		id, name,
		description,
		max_members, group_type, org_id
	) values (
		group_val, 'Satellite Administrators',
		'Satellite Administrators for Org ' || name_in || ' (1)',
		NULL, ug_type, 1
	);

	select nextval('rhn_user_group_id_seq') into group_val from dual;

	select	id
	into	ug_type
	from	rhnUserGroupType
	where	label = 'config_admin';

	insert into rhnUserGroup (
		id, name,
		description,
		max_members, group_type, org_id
	) values (
		group_val, 'Configuration Administrators',
		'Configuration Administrators for Org ' || name_in || ' (1)',
		NULL, ug_type, 1
	);

	-- there aren't any users yet, so we don't need to update
	-- rhnUserServerPerms

        insert into rhnServerGroup
                ( id, name, description, group_type, org_id )
                select nextval('rhn_server_group_id_seq'), sgt.name, sgt.name,
                        sgt.id, 1
                from rhnServerGroupType sgt
                where sgt.label = 'bootstrap_entitled';

        insert into rhnServerGroup
                ( id, name, description, group_type, org_id )
                select nextval('rhn_server_group_id_seq'), sgt.name, sgt.name,
                        sgt.id, 1
                from rhnServerGroupType sgt
                where sgt.label = 'enterprise_entitled';

        insert into rhnServerGroup
                ( id, name, description, group_type, org_id )
                select nextval('rhn_server_group_id_seq'), sgt.name, sgt.name,
                        sgt.id, 1
                from rhnServerGroupType sgt
                where sgt.label = 'virtualization_host';

end
$$ language plpgsql;

0707010000086D000081B400000000000000000000000167AE11140000135C000000000000000000000000000000000000005F00000000susemanager-schema/upgrade/spacewalk-schema-2.4-to-spacewalk-schema-2.5/183-create_new_org.sql    --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--

create or replace function create_new_org
(
        name_in      in varchar,
        password_in  in varchar
        --org_id_out   out NUMERIC
) returns numeric
as
$$
declare
        ug_type                 numeric;
        group_val               numeric;
        new_org_id              numeric;
        org_id_out		numeric;
begin

        select nextval('web_customer_id_seq') into new_org_id;

        insert into web_customer (
                id, name
        ) values (
                new_org_id, name_in
        );

        select nextval('rhn_user_group_id_seq') into group_val;

        select  id
        into    ug_type
        from    rhnUserGroupType
        where   label = 'org_admin';

        insert into rhnUserGroup (
                id, name,
                description,
                max_members, group_type, org_id
        ) values (
                group_val, 'Organization Administrators',
                'Organization Administrators for Org ' || name_in,
                NULL, ug_type, new_org_id
        );

        select nextval('rhn_user_group_id_seq') into group_val;

        select  id
        into    ug_type
        from    rhnUserGroupType
        where   label = 'system_group_admin';

        insert into rhnUserGroup (
                id, name,
                description,
                max_members, group_type, org_id
        ) values (
                group_val, 'System Group Administrators',
                'System Group Administrators for Org ' || name_in,
                NULL, ug_type, new_org_id
        );


        select nextval('rhn_user_group_id_seq') into group_val;

        select  id
        into    ug_type
        from    rhnUserGroupType
        where   label = 'activation_key_admin';

        insert into rhnUserGroup (
                id, name,
                description,
                max_members, group_type, org_id
        ) values (
                group_val, 'Activation Key Administrators',
                'Activation Key Administrators for Org ' || name_in,
                NULL, ug_type, new_org_id
        );

        select nextval('rhn_user_group_id_seq') into group_val;

        select  id
        into    ug_type
        from    rhnUserGroupType
        where   label = 'channel_admin';

        insert into rhnUserGroup (
                id, name,
                description,
                max_members, group_type, org_id
        ) values (
                group_val, 'Channel Administrators',
                'Channel Administrators for Org ' || name_in,
                NULL, ug_type, new_org_id
        );

        select nextval('rhn_user_group_id_seq') into group_val from dual;

        select  id
        into    ug_type
        from    rhnUserGroupType
        where   label = 'config_admin';

        insert into rhnUserGroup (
                id, name,
                description,
                max_members, group_type, org_id
        ) values (
                group_val, 'Configuration Administrators',
                'Configuration Administrators for Org ' || name_in,
                NULL, ug_type, new_org_id
        );

        -- there aren't any users yet, so we don't need to update
        -- rhnUserServerPerms

        insert into rhnServerGroup
                ( id, name, description, group_type, org_id )
                select nextval('rhn_server_group_id_seq'), sgt.name, sgt.name,
                        sgt.id, new_org_id
                from rhnServerGroupType sgt
                where sgt.label = 'bootstrap_entitled';

        insert into rhnServerGroup
                ( id, name, description, group_type, org_id )
                select nextval('rhn_server_group_id_seq'), sgt.name, sgt.name,
                        sgt.id, new_org_id
                from rhnServerGroupType sgt
                where sgt.label = 'enterprise_entitled';

        insert into rhnServerGroup
                ( id, name, description, group_type, org_id )
                select nextval('rhn_server_group_id_seq'), sgt.name, sgt.name,
                        sgt.id, new_org_id
                from rhnServerGroupType sgt
                where sgt.label = 'virtualization_host';

        org_id_out := new_org_id;

	-- Returning the value of OUT parameter
        return org_id_out;

end;
$$
language plpgsql;


0707010000086E000081B400000000000000000000000167AE11140000006E000000000000000000000000000000000000008200000000susemanager-schema/upgrade/spacewalk-schema-2.4-to-spacewalk-schema-2.5/184-drop-rhnOrgEntitlements-and-rhnOrgEntitlementType.sql DROP TABLE rhnOrgEntitlements;
DROP TABLE rhnOrgEntitlementType;

DROP SEQUENCE rhn_org_entitlement_type_seq;
  0707010000086F000081B400000000000000000000000167AE111400000048000000000000000000000000000000000000006700000000susemanager-schema/upgrade/spacewalk-schema-2.4-to-spacewalk-schema-2.5/185-update-rhnInfoPane-acl.sql    UPDATE rhnInfoPane SET acl = NULL where label = 'system-groups-widget';
07070100000870000081B400000000000000000000000167AE1114000000A2000000000000000000000000000000000000005F00000000susemanager-schema/upgrade/spacewalk-schema-2.4-to-spacewalk-schema-2.5/186-drop-functions.sql    
drop function if exists rhn_org_ent_mod_trig_fun();
drop function if exists rhn_org_ent_type_mod_trig_fun();
drop function if exists rhn_satcert_mod_trig_fun();
  07070100000871000081B400000000000000000000000167AE11140000085C000000000000000000000000000000000000006B00000000susemanager-schema/upgrade/spacewalk-schema-2.4-to-spacewalk-schema-2.5/187-drop-rhn_channel-functions.sql    
update pg_settings set setting = 'rhn_channel,' || setting where name = 'search_path';

drop function if exists available_chan_subscriptions(channel_id_in numeric, org_id_in numeric);
drop function if exists available_family_subscriptions(channel_family_id_in numeric, org_id_in numeric);
drop function if exists available_fve_chan_subs(channel_id_in numeric, org_id_in numeric);
drop function if exists available_fve_family_subs(channel_family_id_in numeric, org_id_in numeric);
drop function if exists can_convert_to_fve(server_id_in numeric, channel_family_id_val numeric);
drop function if exists can_server_consume_fve(server_id_in numeric);
drop function if exists can_server_consume_virt_channl(server_id_in numeric, family_id_in numeric);
drop function if exists cfam_curr_fve_members(channel_family_id_in numeric, org_id_in numeric);
drop function if exists channel_family_current_members(channel_family_id_in numeric, org_id_in numeric);
drop function if exists clear_subscriptions(server_id_in numeric, deleting_server numeric, update_family_countsyn numeric);
drop function if exists convert_to_fve(server_id_in numeric, channel_family_id_val numeric);
drop function if exists delete_server_channels(server_id_in numeric);
drop function if exists obtain_read_lock(channel_family_id_in numeric, org_id_in numeric);
drop function if exists subscribe_server(server_id_in numeric, channel_id_in numeric, immediate_in numeric, user_id_in numeric, recalcfamily_in numeric);
drop function if exists subscribe_server(server_id_in numeric, channel_id_in numeric, immediate_in numeric, user_id_in numeric);
drop function if exists unsubscribe_server(server_id_in numeric, channel_id_in numeric, immediate_in numeric, unsubscribe_children_in numeric, deleting_server numeric, update_family_countsyn numeric);
drop function if exists update_family_counts(channel_family_id_in numeric, org_id_in numeric);
drop function if exists update_group_family_counts(group_label_in character varying, org_id_in numeric);

update pg_settings set setting = overlay( setting placing '' from 1 for (length('rhn_channel')+1) ) where name = 'search_path';
07070100000872000081B400000000000000000000000167AE111400000B91000000000000000000000000000000000000007000000000susemanager-schema/upgrade/spacewalk-schema-2.4-to-spacewalk-schema-2.5/188-drop-rhn_entitlements-functions.sql   
update pg_settings set setting = 'rhn_entitlements,' || setting where name = 'search_path';

drop function if exists activate_channel_entitlement(org_id_in numeric, channel_family_label_in character varying, quantity_in numeric, flex_in numeric);
drop function if exists activate_system_entitlement(org_id_in numeric, group_label_in character varying, quantity_in numeric);
drop function if exists assign_channel_entitlement(channel_family_label_in character varying, from_org_id_in numeric, to_org_id_in numeric, quantity_in numeric, flex_in numeric);
drop function if exists assign_system_entitlement(group_label_in character varying, from_org_id_in numeric, to_org_id_in numeric, quantity_in numeric);
drop function if exists create_entitlement_group(org_id_in numeric, type_label_in character varying);
drop function if exists entitle_last_modified_servers(customer_id_in numeric, type_label_in character varying, quantity_in numeric);
drop function if exists lookup_entitlement_group(org_id_in numeric, type_label_in character varying);
drop function if exists modify_org_service(org_id_in numeric, service_label_in character varying, enable_in character);
drop function if exists prune_family(customer_id_in numeric, channel_family_id_in numeric, quantity_in numeric, flex_in numeric);
drop function if exists prune_group(group_id_in numeric, quantity_in numeric);
drop function if exists prune_group(group_id_in numeric, quantity_in numeric, update_family_countsyn numeric);
drop function if exists remove_org_entitlements(org_id_in numeric);
drop function if exists remove_server_entitlement(server_id_in numeric, type_label_in character varying, repoll_virt_guests numeric);
drop function if exists repoll_virt_guest_entitlements(server_id_in numeric);
drop function if exists set_customer_enterprise(customer_id_in numeric);
drop function if exists set_customer_monitoring(customer_id_in numeric);
drop function if exists set_customer_nonlinux(customer_id_in numeric);
drop function if exists set_customer_provisioning(customer_id_in numeric);
drop function if exists set_family_count(customer_id_in numeric, channel_family_id_in numeric, quantity_in numeric, flex_in numeric);
drop function if exists set_server_group_count(customer_id_in numeric, group_type_in numeric, quantity_in numeric);
drop function if exists set_server_group_count(customer_id_in numeric, group_type_in numeric, quantity_in numeric, update_family_countsyn numeric);
drop function if exists subscribe_newest_servers(customer_id_in numeric);
drop function if exists unset_customer_enterprise(customer_id_in numeric);
drop function if exists unset_customer_monitoring(customer_id_in numeric);
drop function if exists unset_customer_nonlinux(customer_id_in numeric);
drop function if exists unset_customer_provisioning(customer_id_in numeric);

update pg_settings set setting = overlay( setting placing '' from 1 for (length('rhn_entitlements')+1) ) where name = 'search_path';
   07070100000873000081B400000000000000000000000167AE111400000145000000000000000000000000000000000000006A00000000susemanager-schema/upgrade/spacewalk-schema-2.4-to-spacewalk-schema-2.5/189-drop-rhn_server-functions.sql 
update pg_settings set setting = 'rhn_server,' || setting where name = 'search_path';

drop function if exists can_server_consume_virt_slot(server_id_in numeric, group_type_in character varying);

update pg_settings set setting = overlay( setting placing '' from 1 for (length('rhn_server')+1) ) where name = 'search_path';
   07070100000874000081B400000000000000000000000167AE11140000003E000000000000000000000000000000000000006D00000000susemanager-schema/upgrade/spacewalk-schema-2.4-to-spacewalk-schema-2.5/200-rhnCryptoKey-enable-org-null.sql  
ALTER TABLE rhnCryptoKey ALTER COLUMN org_id DROP NOT NULL;

  07070100000875000081B400000000000000000000000167AE111400000126000000000000000000000000000000000000006300000000susemanager-schema/upgrade/spacewalk-schema-2.4-to-spacewalk-schema-2.5/201-rhnVirtualInstance.sql    delete from rhnVirtualInstance where virtual_system_id is NULL and host_system_id is not NULL and uuid in (select uuid from rhnVirtualInstance group by uuid having count(uuid) > 1);
delete from rhnVirtualInstance where virtual_system_id is NULL and host_system_id is NULL and uuid is not NULL;
  07070100000876000081B400000000000000000000000167AE11140000767E000000000000000000000000000000000000006800000000susemanager-schema/upgrade/spacewalk-schema-2.4-to-spacewalk-schema-2.5/202-no-lock-rhn_channel.pkb.sql   --
-- Copyright (c) 2008--2016 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--
--
--
--

-- create schema rhn_channel;

--update pg_setting
update pg_settings set setting = 'rhn_channel,' || setting where name = 'search_path';

    -- this "emulates" cursor server_base_subscriptions defined in oracle/rhn_channel.pks
    create or replace function server_base_subscriptions(server_id_in NUMERIC)
    returns boolean as $$
    begin
      return exists(SELECT C.id FROM rhnChannel C, rhnServerChannel SC
		    WHERE C.id = SC.channel_id
		      AND SC.server_id = server_id_in
		      AND C.parent_channel IS NULL);
    end$$ language plpgsql;

    -- this "emulates" cursor server_base_subscriptions defined in oracle/rhn_channel.pks
    create or replace function check_server_subscription(server_id_in NUMERIC, channel_id_in NUMERIC)
    returns boolean as $$
    begin
      return exists(SELECT channel_id FROM rhnServerChannel WHERE server_id = server_id_in AND channel_id = channel_id_in);
    end$$ language plpgsql;


    CREATE OR REPLACE FUNCTION subscribe_server(server_id_in IN NUMERIC, channel_id_in NUMERIC, immediate_in NUMERIC default 1, user_id_in in numeric default null) returns void
    AS $$
    declare
        channel_parent_val      rhnChannel.parent_channel%TYPE;
        parent_subscribed       BOOLEAN;
        server_has_base_chan    BOOLEAN;
        server_already_in_chan  BOOLEAN;
        channel_family_id_val   NUMERIC;
        allowed                 numeric;
    BEGIN
        if user_id_in is not null then
            allowed := rhn_channel.user_role_check(channel_id_in, user_id_in, 'subscribe');
        else
            allowed := 1;
        end if;

        if allowed = 0 then
            perform rhn_exception.raise_exception('no_subscribe_permissions');
        end if;


        SELECT parent_channel INTO channel_parent_val FROM rhnChannel WHERE id = channel_id_in;

        IF channel_parent_val IS NOT NULL
        THEN
            -- child channel; if attempting to cross-subscribe a child to the wrong base, silently ignore
            parent_subscribed := rhn_channel.check_server_subscription(server_id_in, channel_parent_val);

            IF NOT parent_subscribed
            THEN
                RETURN;
            END IF;
        ELSE
            -- base channel
            server_has_base_chan := rhn_channel.server_base_subscriptions(server_id_in);

            IF server_has_base_chan
            THEN
                perform rhn_exception.raise_exception('channel_server_one_base');
            END IF;
        END IF;

        server_already_in_chan := rhn_channel.check_server_subscription(server_id_in, channel_id_in);

        IF server_already_in_chan
        THEN
            RETURN;
        END IF;

        channel_family_id_val := rhn_channel.family_for_channel(channel_id_in);
        IF channel_family_id_val IS NULL
        THEN
            perform rhn_exception.raise_exception('channel_subscribe_no_family');
        END IF;

        insert into rhnServerHistory (id,server_id,summary,details) (
            select  nextval('rhn_event_id_seq'),
                    server_id_in,
                    'subscribed to channel ' || SUBSTR(c.label, 0, 106),
                    c.label
            from    rhnChannel c
            where   c.id = channel_id_in
        );

        INSERT INTO rhnServerChannel (server_id, channel_id) VALUES (server_id_in, channel_id_in);

        perform queue_server(server_id_in, immediate_in);

        update rhnServer
           set channels_changed = current_timestamp
         where id = server_id_in;
    END$$ language plpgsql;

    create or replace function guess_server_base(
        server_id_in in numeric
    ) RETURNS numeric as $$
    declare
        server_cursor cursor for
            select s.server_arch_id, s.release, s.org_id
              from rhnServer s
             where s.id = server_id_in;
    -- Cursor that fetches all the possible base channels for a
    -- (server_arch_id, release, org_id) combination
        base_channel_cursor cursor(
                release_in varchar,
                server_arch_id_in numeric,
                org_id_in numeric
        ) for
                select distinct c.*
                from    rhnOrgDistChannelMap                       odcm,
                                rhnServerChannelArchCompat      scac,
                                rhnChannel                                      c
                where   c.parent_channel is null
                        and c.id = odcm.channel_id
                        and c.channel_arch_id = odcm.channel_arch_id
                        and odcm.release = release_in
                        and odcm.for_org_id = org_id_in
                        and scac.server_arch_id = server_arch_id_in
                        and scac.channel_arch_id = c.channel_arch_id;

    begin
        for s in server_cursor loop
            for channel in base_channel_cursor(s.release,
                s.server_arch_id, s.org_id)
            loop
                return channel.id;
            end loop;
        end loop;
        -- Server not found, or no base channel applies to it
        return null;
    end$$ language plpgsql;

    -- Private function
    create or replace function normalize_server_arch(server_arch_in in varchar)
    returns varchar
    as $$
    declare
        suffix VARCHAR(128) := '-redhat-linux';
    begin
        if server_arch_in is NULL then
            return NULL;
        end if;
        if position('-' IN server_arch_in) > 0
        then
            -- Suffix already present
            return server_arch_in;
        end if;
        return server_arch_in || suffix;
    end$$ language plpgsql;

    --
    -- Raises:
    --   server_arch_not_found
    --   no_subscribe_permissions
    create or replace function base_channel_for_release_arch(
        release_in in varchar,
        server_arch_in in varchar,
        org_id_in in numeric default -1,
        user_id_in in numeric default null
    ) returns numeric as $$
    declare
        server_arch varchar(256) := rhn_channel.normalize_server_arch(server_arch_in);
        server_arch_id numeric;
    begin
        -- Look up the server arch
            select id
              into server_arch_id
              from rhnServerArch
             where label = server_arch;
            if not found then
                perform rhn_exception.raise_exception('server_arch_not_found');
            end if;

        return rhn_channel.base_channel_rel_archid(release_in, server_arch_id,
            org_id_in, user_id_in);
    end$$ language plpgsql;

    create or replace function base_channel_rel_archid(
        release_in in varchar,
        server_arch_id_in in numeric,
        org_id_in in numeric default -1,
        user_id_in in numeric default null
    ) returns numeric as $$
    declare
        denied_channel_id numeric := null;
        valid_org_id numeric := org_id_in;
        valid_user_id numeric := user_id_in;
        channel_subscribable numeric;
    -- Cursor that fetches all the possible base channels for a
    -- (server_arch_id, release, org_id) combination
        base_channel_cursor cursor(
                release_in varchar,
                server_arch_id_in numeric,
                org_id_in numeric
        ) for
                select distinct c.*
                from    rhnOrgDistChannelMap                       odcm,
                                rhnServerChannelArchCompat      scac,
                                rhnChannel                                      c
                where   c.parent_channel is null
                        and c.id = odcm.channel_id
                        and c.channel_arch_id = odcm.channel_arch_id
                        and odcm.release = release_in
                        and odcm.for_org_id = org_id_in
                        and scac.server_arch_id = server_arch_id_in
                        and scac.channel_arch_id = c.channel_arch_id;

    begin
        if org_id_in = -1 and user_id_in is not null then
            -- Get the org id from the user id

                select org_id
                  into valid_org_id
                  from web_contact
                 where id = user_id_in;

                if not found then
                    -- User doesn't exist
                    -- XXX Only list public stuff for now
                    valid_user_id := null;
                    valid_org_id := -1;
                end if;
        end if;

        for c in base_channel_cursor(release_in, server_arch_id_in, valid_org_id)
        loop
            -- This row is a possible match
            if valid_user_id is null then
                -- User ID not specified, so no user to channel permissions to
                -- check
                return c.id;
            end if;

            -- Check user to channel permissions
            select rhn_channel.loose_user_role_check(c.id, user_id_in, 'subscribe')
              into channel_subscribable;

            if channel_subscribable = 1 then
                return c.id;
            end if;

            -- Base channel exists, but is not subscribable; keep trying
            denied_channel_id := c.id;
        end loop;

        if denied_channel_id is not null then
            perform rhn_exception.raise_exception('no_subscribe_permissions');
        end if;
        -- No base channel applies
        return NULL;
    end$$ language plpgsql;

    CREATE OR REPLACE FUNCTION clear_subscriptions(server_id_in IN NUMERIC, deleting_server IN NUMERIC default 0) returns void
    AS $$
    declare
        server_channels cursor(server_id_in numeric) for
                select  s.org_id, sc.channel_id, cfm.channel_family_id
                from    rhnServer s,
                        rhnServerChannel sc,
                        rhnChannelFamilyMembers cfm
                where   s.id = server_id_in
                        and s.id = sc.server_id
                        and sc.channel_id = cfm.channel_id
                order by cfm.channel_family_id;
        last_channel_family_id rhnChannelFamilyMembers.channel_family_id%type := -1;
        last_channel_org_id    rhnServer.org_id%type := -1;
    BEGIN
        for channel in server_channels(server_id_in)
        loop
                perform rhn_channel.unsubscribe_server(server_id_in, channel.channel_id, 1, 1, deleting_server);
        end loop;
    END$$ language plpgsql;

    CREATE OR REPLACE FUNCTION unsubscribe_server(server_id_in IN NUMERIC, channel_id_in NUMERIC, immediate_in NUMERIC default 1, unsubscribe_children_in numeric default 0,
                                 deleting_server in numeric default 0) returns void
    AS $$
    declare
        channel_family_id_val   NUMERIC;
        server_org_id_val       NUMERIC;
        server_already_in_chan  BOOLEAN;
        channel_family_is_proxy cursor(channel_family_id_in numeric) for
                select  1
                from    rhnChannelFamily
                where   id = channel_family_id_in
                    and label = 'rhn-proxy';
        channel_family_is_satellite cursor(channel_family_id_in numeric) for
                select  1
                from    rhnChannelFamily
                where   id = channel_family_id_in
                    and label = 'rhn-satellite';
        child record;
    BEGIN
        -- In PostgreSQL recursion with opened cursors is not allowed so we use
        -- FOR IN SELECT form which is ok.
        FOR child IN select  c.id
                from    rhnChannel                      c,
                                rhnServerChannel        sc
                where   1=1
                        and c.parent_channel = channel_id_in
                        and c.id = sc.channel_id
                        and sc.server_id = server_id_in
        LOOP
            if unsubscribe_children_in = 1 then
                perform rhn_channel.unsubscribe_server(server_id_in,
                                                       child.id,
                                                       immediate_in,
                                                       unsubscribe_children_in,
                                                       deleting_server);
            else
                perform rhn_exception.raise_exception('channel_unsubscribe_child_exists');
            end if;
        END LOOP;

        server_already_in_chan := rhn_channel.check_server_subscription(server_id_in, channel_id_in);

        IF NOT server_already_in_chan
        THEN
            RETURN;
        END IF;

   if deleting_server = 0 then
      insert into rhnServerHistory (id,server_id,summary,details) (
          select  nextval('rhn_event_id_seq'),
                server_id_in,
             'unsubscribed from channel ' || SUBSTR(c.label, 0, 106),
             c.label
          from    rhnChannel c
          where   c.id = channel_id_in
      );
   end if;

   DELETE FROM rhnServerChannel WHERE server_id = server_id_in AND channel_id = channel_id_in;

   if deleting_server = 0 then
        perform queue_server(server_id_in, immediate_in);

        update rhnServer
           set channels_changed = current_timestamp
         where id = server_id_in;
   end if;

        channel_family_id_val := rhn_channel.family_for_channel(channel_id_in);
        IF channel_family_id_val IS NULL
        THEN
            perform rhn_exception.raise_exception('channel_unsubscribe_no_family');
        END IF;

        for ignore in channel_family_is_satellite(channel_family_id_val) loop
                delete from rhnSatelliteInfo where server_id = server_id_in;
        end loop;

        for ignore in channel_family_is_proxy(channel_family_id_val) loop
                delete from rhnProxyInfo where server_id = server_id_in;
        end loop;
        SELECT org_id INTO server_org_id_val
          FROM rhnServer
         WHERE id = server_id_in;

    END$$ language plpgsql;

    CREATE OR REPLACE FUNCTION family_for_channel(channel_id_in IN NUMERIC)
    RETURNS NUMERIC
    AS $$
    declare
        channel_family_id_val NUMERIC;
    BEGIN
        SELECT channel_family_id INTO channel_family_id_val
          FROM rhnChannelFamilyMembers
         WHERE channel_id = channel_id_in;

        IF NOT FOUND THEN
          RETURN NULL;
        END IF;

        RETURN channel_family_id_val;
    END$$ language plpgsql;

    create or replace function unsubscribe_server_from_family(server_id_in in numeric,
                                             channel_family_id_in in numeric)
    returns void
    as $$
    begin
        delete
        from    rhnServerChannel rsc
        where   rsc.server_id = server_id_in
            and channel_id in (
                select  rcfm.channel_id
                from    rhnChannelFamilyMembers rcfm
                where   rcfm.channel_family_id = channel_family_id_in);
    end$$ language plpgsql;

    create or replace function get_org_id(channel_id_in in numeric)
    returns numeric
    as $$
    declare
        org_id_out numeric;
    begin
        select org_id into strict org_id_out
            from rhnChannel
            where id = channel_id_in;

            return org_id_out;
    end$$ language plpgsql;

    create or replace function get_cfam_org_access(cfam_id_in in numeric, org_id_in in numeric)
    returns numeric
    as $$
    begin
      if exists(
                        select  1
                        from    rhnOrgChannelFamilyPermissions cfp
                        where   cfp.org_id = org_id_in
      ) then
                return 1;
      else
                return 0;
      end if;
    end$$ language plpgsql;

    create or replace function get_org_access(channel_id_in in numeric, org_id_in in numeric)
    returns integer
    as $$
    begin
        -- the idea: if we get past this query,
        -- the org has access to the channel, else not
        if exists(
        select 1
          from rhnChannelFamilyMembers CFM,
               rhnOrgChannelFamilyPermissions CFP
         where cfp.org_id = org_id_in
           and CFM.channel_family_id = CFP.channel_family_id
           and CFM.channel_id = channel_id_in)
        then
          return 1;
        else
          return 0;
        end if;
    end$$ language plpgsql;

    -- check if a user has a given role, or if such a role is inferrable
    -- returns NULL if OK, error message otherwise
    create or replace function user_role_check_debug(channel_id_in in numeric,
                                   user_id_in in numeric,
                                   role_in in varchar)
    returns varchar
    as $$
    declare
        org_id numeric;
    begin
        org_id := rhn_user.get_org_id(user_id_in);

        -- channel might be shared
        if role_in = 'subscribe' and
           rhn_channel.shared_user_role_check(channel_id_in, user_id_in, role_in) = 1 then
            return NULL;
        end if;

        if role_in = 'manage' and
           COALESCE(rhn_channel.get_org_id(channel_id_in), -1) <> org_id then
               return 'channel_not_owned';
        end if;

        if role_in = 'subscribe' and
           rhn_channel.get_org_access(channel_id_in, org_id) = 0 then
                return 'channel_not_available';
        end if;

        -- channel admins have all roles
        if rhn_user.check_role_implied(user_id_in, 'channel_admin') = 1 then
            return NULL;
        end if;

        -- the subscribe permission is inferred
        -- UNLESS the not_globally_subscribable flag is set
        if role_in = 'subscribe'
        then
            if rhn_channel.org_channel_setting(channel_id_in,
                       org_id,
                       'not_globally_subscribable') = 0 then
                return NULL;
            end if;
        end if;

        -- all other roles (manage right now) are explicitly granted
        if rhn_channel.direct_user_role_check(channel_id_in,
                                              user_id_in, role_in) = 1 then
            return NULL;
        end if;
        return 'direct_permission';
    end$$ language plpgsql;

    -- same as above, but with 1/0 output; useful in views, etc
    create or replace function user_role_check(channel_id_in in numeric, user_id_in in numeric, role_in in varchar)
    returns numeric
    as $$
    begin
        if rhn_channel.user_role_check_debug(channel_id_in,
                                             user_id_in, role_in) is NULL then
            return 1;
        else
            return 0;
        end if;
    end$$ language plpgsql;

    --
    -- For multiorg phase II, this function simply checks to see if the user's
    -- has a trust relationship that includes this channel by id.
    --
    create or replace function shared_user_role_check(channel_id in numeric, user_id in numeric, role in varchar)
    returns numeric
    as $$
    declare
      n numeric;
      oid numeric;
    begin
      oid := rhn_user.get_org_id(user_id);
      select 1 into n
      from rhnSharedChannelView s
      where s.id = channel_id and s.org_trust_id = oid;

      if not found then
        return 0;
      end if;

      return 1;
    end$$ language plpgsql;

    -- same as above, but returns 1 if user_id_in is null
    -- This is useful in queries where user_id is not specified
    create or replace function loose_user_role_check(channel_id_in in numeric, user_id_in in numeric, role_in in varchar)
    returns numeric
    as $$
    begin
        if user_id_in is null then
            return 1;
        end if;
        return rhn_channel.user_role_check(channel_id_in, user_id_in, role_in);
    end$$ language plpgsql;

    -- directly checks the table, no inferred permissions
    create or replace function direct_user_role_check(channel_id_in in numeric, user_id_in in numeric, role_in in varchar)
    returns numeric
    as $$
    declare
        throwaway numeric;
    begin
        -- the idea: if we get past this query, the user has the role, else no
        select 1 into throwaway
          from rhnChannelPermissionRole CPR,
               rhnChannelPermission CP
         where CP.user_id = user_id_in
           and CP.channel_id = channel_id_in
           and CPR.label = role_in
           and CP.role_id = CPR.id;

      if not found then
        return 0;
      end if;

      return 1;
    end$$ language plpgsql;

    -- check if an org has a certain setting
    create or replace function org_channel_setting(channel_id_in in numeric, org_id_in in numeric, setting_in in varchar)
    returns numeric
    as $$
    declare
        throwaway numeric;
    begin
        -- the idea: if we get past this query, the org has the setting
        select 1 into throwaway
          from rhnOrgChannelSettingsType OCST,
               rhnOrgChannelSettings OCS
         where OCS.org_id = org_id_in
           and OCS.channel_id = channel_id_in
           and OCST.label = setting_in
           and OCS.setting_id = OCST.id;

      if not found then
        return 0;
      end if;

      return 1;
    end$$ language plpgsql;

    CREATE OR REPLACE FUNCTION channel_priority(channel_id_in IN numeric)
    RETURNS numeric
    AS $$
    declare
         channel_name varchar(256);
         priority numeric;
         end_of_life_val timestamptz;
         org_id_val numeric;
    BEGIN

        select name, end_of_life, org_id
        into channel_name, end_of_life_val, org_id_val
        from rhnChannel
        where id = channel_id_in;

        if end_of_life_val is not null then
          return -400;
        end if;

        if channel_name like 'Red Hat Enterprise Linux%' or channel_name like 'RHEL%' then
          priority := 1000;
          if channel_name not like '%Beta%' then
            priority := priority + 1000;
          end if;

          priority := priority +
            case
              when channel_name like '%v. 5%' then 600
              when channel_name like '%v. 4%' then 500
              when channel_name like '%v. 3%' then 400
              when channel_name like '%v. 2%' then 300
              when channel_name like '%v. 1%' then 200
              else 0
            end;

          priority := priority +
            case
              when channel_name like 'Red Hat Enterprise Linux (v. 5%' then 60
              when (channel_name like '%AS%' and channel_name not like '%Extras%') then 50
              when (channel_name like '%ES%' and channel_name not like '%Extras%') then 40
              when (channel_name like '%WS%' and channel_name not like '%Extras%') then 30
              when (channel_name like '%Desktop%' and channel_name not like '%Extras%') then 20
              when channel_name like '%Extras%' then 10
              else 0
            end;

          priority := priority +
            case
              when channel_name like '%)' then 5
              else 0
            end;

          priority := priority +
            case
              when channel_name like '%32-bit x86%' then 4
              when channel_name like '%64-bit Intel Itanium%' then 3
              when channel_name like '%64-bit AMD64/Intel EM64T%' then 2
              else 0
            end;
        elsif channel_name like 'Red Hat Desktop%' then
            priority := 900;

            if channel_name not like '%Beta%' then
               priority := priority + 50;
            end if;

          priority := priority +
            case
              when channel_name like '%v. 4%' then 40
              when channel_name like '%v. 3%' then 30
              when channel_name like '%v. 2%' then 20
              when channel_name like '%v. 1%' then 10
              else 0
            end;

          priority := priority +
            case
              when channel_name like '%32-bit x86%' then 4
              when channel_name like '%64-bit Intel Itanium%' then 3
              when channel_name like '%64-bit AMD64/Intel EM64T%' then 2
              else 0
            end;

        elsif org_id_val is not null then
          priority := 600;
        else
          priority := 500;
        end if;

      return -priority;

    end$$ language plpgsql;

    -- this could certainly be optimized to do updates if needs be
    create or replace function refresh_newest_package(channel_id_in in numeric,
                                      caller_in in varchar default '(unknown)',
                                      package_name_id_in in numeric default null)
    returns void
    as $$
    -- procedure refreshes rows for name_id = package_name_id_in or
    -- all rows if package_name_id_in is null
    begin
        delete from rhnChannelNewestPackage
              where channel_id = channel_id_in
                and (package_name_id_in is null
                     or name_id = package_name_id_in);
        insert into rhnChannelNewestPackage
                (channel_id, name_id, evr_id, package_id, package_arch_id)
                (select channel_id,
                        name_id, evr_id,
                        package_id, package_arch_id
                   from rhnChannelNewestPackageView
                  where channel_id = channel_id_in
                    and (package_name_id_in is null
                         or name_id = package_name_id_in)
                );
        insert into rhnChannelNewestPackageAudit (channel_id, caller)
             values (channel_id_in, caller_in);
        update rhnChannel
           set last_modified = greatest(current_timestamp,
                                        last_modified + interval '1 second')
         where id = channel_id_in;
    end$$ language plpgsql;

   create or replace function update_channel ( channel_id_in in numeric, invalidate_ss in numeric default 0,
                              date_to_use in timestamptz default current_timestamp ) returns void
   as $$
   declare
   channel_last_modified timestamptz;
   last_modified_value timestamptz;

   snapshots cursor for
   select  snapshot_id id
   from    rhnSnapshotChannel
   where   channel_id = channel_id_in;

   begin

      select last_modified
      into channel_last_modified
      from rhnChannel
      where id = channel_id_in;

      last_modified_value := date_to_use;

      if last_modified_value <= channel_last_modified then
          last_modified_value := last_modified_value + interval '1 second';
      end if;

      update rhnChannel set last_modified = last_modified_value
      where id = channel_id_in;

      if invalidate_ss = 1 then
        for snapshot in snapshots loop
            update rhnSnapshot
            set invalid = lookup_snapshot_invalid_reason('channel_modified')
            where id = snapshot.id;
        end loop;
      end if;

   end$$ language plpgsql;

   create or replace function update_channels_by_package ( package_id_in in numeric, date_to_use in timestamptz default current_timestamp ) returns void
   as $$
   declare
   channels cursor for
   select channel_id
   from rhnChannelPackage
   where package_id = package_id_in
   order by channel_id;

   begin
      for channel in channels loop
         -- we want to invalidate the snapshot assocated with the channel when we
         -- do this b/c we know we've added or removed or packages
         perform rhn_channel.update_channel ( channel.channel_id, 1, date_to_use );
      end loop;
   end$$ language plpgsql;


   create or replace function update_channels_by_errata ( errata_id_in numeric, date_to_use in timestamptz default current_timestamp ) returns void
   as $$
   declare
   channels cursor for
   select channel_id
   from rhnChannelErrata
   where errata_id = errata_id_in
   order by channel_id;

   begin
      for channel in channels loop
         -- we won't invalidate snapshots, b/c just changing the errata associated with
         -- a channel shouldn't invalidate snapshots
         perform rhn_channel.update_channel ( channel.channel_id, 0, date_to_use );
      end loop;
   end$$ language plpgsql;

   create or replace function update_needed_cache(channel_id_in in numeric) returns void
   as $$
   declare
   server record;
   begin
      -- we intentionaly do a loop here instead of one huge select
      -- b/c we want to break update into smaller transaction to unblock other sessions
      -- querying rhnServerNeededCache
      for server in (
                select sc.server_id as id
                  from rhnServerChannel sc
                 where sc.channel_id = channel_id_in
                 order by id asc
      ) loop
         perform queue_server(server.id, 0); -- NOT IMMEDIATE
      end loop;
   end$$ language plpgsql;

    create or replace function set_comps(channel_id_in in numeric, path_in in varchar, timestamp_in in varchar) returns void
    as $$
    declare
    row record;
    begin
        for row in (
            select relative_filename, last_modified
            from rhnChannelComps
            where channel_id = channel_id_in
            ) loop
            if row.relative_filename = path_in
                and row.last_modified = to_timestamp(timestamp_in, 'YYYYMMDDHH24MISS') then
                return;
            end if;
        end loop;
        delete from rhnChannelComps
        where channel_id = channel_id_in;
        insert into rhnChannelComps (id, channel_id, relative_filename, last_modified, created, modified)
        values (sequence_nextval('rhn_channelcomps_id_seq'), channel_id_in, path_in, to_timestamp(timestamp_in, 'YYYYMMDDHH24MISS'), current_timestamp, current_timestamp);
    end$$ language plpgsql;

-- restore the original setting
update pg_settings set setting = overlay( setting placing '' from 1 for (length('rhn_channel')+1) ) where name = 'search_path';
  07070100000877000081B400000000000000000000000167AE1114000002F5000000000000000000000000000000000000006100000000susemanager-schema/upgrade/spacewalk-schema-2.4-to-spacewalk-schema-2.5/202-rhnTimezone-data.sql  insert into rhnTimezone (id, olson_name, display_name) (
    select sequence_nextval('rhn_timezone_id_seq'),
           'America/Santiago',
           'Chile (Continental)'
      from dual
     where not exists (
           select 1
             from rhnTimezone
            where olson_name = 'America/Santiago'
              and display_name = 'Chile (Continental)'
     )
);

insert into rhnTimezone (id, olson_name, display_name) (
    select sequence_nextval('rhn_timezone_id_seq'),
           'Pacific/Easter',
           'Chile (Easter Island)'
      from dual
     where not exists (
           select 1
             from rhnTimezone
            where olson_name = 'Pacific/Easter'
              and display_name = 'Chile (Easter Island)'
     )
);
   07070100000878000081B400000000000000000000000167AE1114000025EF000000000000000000000000000000000000005E00000000susemanager-schema/upgrade/spacewalk-schema-2.4-to-spacewalk-schema-2.5/205-delete_server.sql --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
-- This deletes a server.  All codepaths which delete servers should hit this
-- or delete_server_bulk()

create or replace
function delete_server (
        server_id_in in numeric
) returns void 
as
$$
declare
         servergroups cursor for
                select  server_id, server_group_id
                from    rhnServerGroupMembers sgm
                where   sgm.server_id = server_id_in;

         configchannels cursor for
                select  cc.id
                from    rhnConfigChannel cc,
                        rhnConfigChannelType cct,
                        rhnServerConfigChannel scc
                where   1=1
                        and scc.server_id = server_id_in
                        and scc.config_channel_id = cc.id
                        -- these config channel types are reserved
                        -- for use by a single server, so we don't
                        -- need to check for other servers subscribed
                        and cct.label in
                                ('local_override','server_import')
                        and cct.id = cc.confchan_type_id;

begin
        -- filelists
        delete from rhnFileList where id in (
	select	spfl.file_list_id
	  from	rhnServerPreserveFileList spfl
	 where	spfl.server_id = server_id_in
			and not exists (
				select	1
				from	rhnServerPreserveFileList
				where	file_list_id = spfl.file_list_id
					and server_id != server_id_in
				union all
				select	1
				from	rhnKickstartPreserveFileList
				where	file_list_id = spfl.file_list_id
			)
        );

	for configchannel in configchannels loop
		perform rhn_config.delete_channel(configchannel.id);
	end loop;

	for sgm in servergroups loop
		perform rhn_server.delete_from_servergroup(
			sgm.server_id, sgm.server_group_id);
	end loop;


        -- we're handling this instead of letting an "on delete
        -- set null" do it so that we don't run the risk
        -- of setting off the triggers and killing us with a
        -- mutating table

        -- this is merge of two single updates:
        --  update ... set old_server_id = null where old_server_id = server_id_in;
        --  update ... set new_server_id = null where new_server_id = server_id_in;
        -- so we scan rhnKickstartSession table only once
        update rhnKickstartSession
                set old_server_id = case when old_server_id = server_id_in then null else old_server_id end,
                    new_server_id = case when new_server_id = server_id_in then null else new_server_id end
                where old_server_id = server_id_in
                   or new_server_id = server_id_in;

        perform rhn_channel.clear_subscriptions(server_id_in, 1);

        -- A little complicated here, but the goal is to
        -- delete records from rhnVirtualInstace only if we don't
        -- care about them anymore.  We don't care about records
        -- in rhnVirtualInstance if we are deleting the host
        -- system and the virtual system is already null, or
        -- vice-versa.  We *do* care about them if either the
        -- host or virtual system is still registered because we
        -- still want them to show up in the UI.
    -- If there's a newer row in rhnVirtualInstance with the same
    -- uuid, this guest must have been re-registered, so we can clean
    -- this data up.

        delete from rhnVirtualInstance vi
              where (host_system_id = server_id_in and virtual_system_id is null)
                 or (virtual_system_id = server_id_in and host_system_id is null)
                 or (vi.virtual_system_id = server_id_in and vi.modified < (select max(vi2.modified)
                    from rhnVirtualInstance vi2 where vi2.uuid = vi.uuid));

        -- this is merge of two single updates:
        --  update ... set host_system_id = null where host_system_id = server_id_in;
        --  update ... set virtual_system_id = null where virtual_system_id = server_id_in;
        -- so we scan rhnVirtualInstance table only once
        update rhnVirtualInstance
           set host_system_id = case when host_system_id = server_id_in then null else host_system_id end,
               virtual_system_id = case when virtual_system_id = server_id_in then null else virtual_system_id end
         where host_system_id = server_id_in
            or virtual_system_id = server_id_in;

        -- this is merge of two single updates:
        --  update ... set old_host_system_id = null when old_host_system_id = server_id_in;
        --  update ... set new_host_system_id = null when new_host_system_id = server_id_in;
        -- so we scan rhnVirtualInstanceEventLog table only once
        update rhnVirtualInstanceEventLog
           set old_host_system_id = case when old_host_system_id = server_id_in then null else old_host_system_id end,
               new_host_system_id = case when new_host_system_id = server_id_in then null else new_host_system_id end
         where old_host_system_id = server_id_in
            or new_host_system_id = server_id_in;

        -- We're deleting everything with a foreign key to rhnServer
        -- here, now.  I'm hoping this will help aleviate our deadlock
        -- problem.

        delete from rhnActionConfigChannel where server_id = server_id_in;
        delete from rhnActionConfigRevision where server_id = server_id_in;
        delete from rhnActionPackageRemovalFailure where server_id = server_id_in;
        delete from rhnClientCapability where server_id = server_id_in;
        delete from rhnCpu where server_id = server_id_in;
        -- there's still a cascade here, because the constraint keeps the
        -- table locked for too long to rebuild it.  Ugh...
        delete from rhnDevice where server_id = server_id_in;
        delete from rhnProxyInfo where server_id = server_id_in;
        delete from rhnRam where server_id = server_id_in;
        delete from rhnRegToken where server_id = server_id_in;
        delete from rhnSatelliteInfo where server_id = server_id_in;
        -- this cascades to rhnActionConfigChannel and rhnActionConfigFileName
        delete from rhnServerAction where server_id = server_id_in;
        delete from rhnServerActionPackageResult where server_id = server_id_in;
        delete from rhnServerActionScriptResult where server_id = server_id_in;
        delete from rhnServerActionVerifyResult where server_id = server_id_in;
        delete from rhnServerActionVerifyMissing where server_id = server_id_in;
        -- counts are handled above.  this should be a delete_ function.
        delete from rhnServerChannel where server_id = server_id_in;
        delete from rhnServerConfigChannel where server_id = server_id_in;
        delete from rhnServerCustomDataValue where server_id = server_id_in;
        delete from rhnServerDMI where server_id = server_id_in;
        delete from rhnServerEvent where server_id = server_id_in;
        delete from rhnServerHistory where server_id = server_id_in;
        delete from rhnServerInfo where server_id = server_id_in;
        delete from rhnServerInstallInfo where server_id = server_id_in;
        delete from rhnServerLocation where server_id = server_id_in;
        delete from rhnServerLock where server_id = server_id_in;
        delete from rhnServerNeededCache where server_id = server_id_in;
        delete from rhnServerNetwork where server_id = server_id_in;
        delete from rhnServerNotes where server_id = server_id_in;
        -- I'm not removing the foreign key from rhnServerPackage; that'll
        -- take forever.  Do the delete anyway.
        delete from rhnServerPackage where server_id = server_id_in;
        delete from rhnServerTokenRegs where server_id = server_id_in;
        delete from rhnSnapshotTag where server_id = server_id_in;
        -- this cascades to:
        --   rhnSnapshotChannel, rhnSnapshotConfigChannel, rhnSnapshotPackage,
        --   rhnSnapshotConfigRevision, rhnSnapshotServerGroup,
        --   rhnSnapshotTag.
        -- We may want to consider delete_snapshot() at some point, but
        --   I don't think we need to yet.
        delete from rhnSnapshot where server_id = server_id_in;
        delete from rhnUserServerPrefs where server_id = server_id_in;
        -- hrm, this one's interesting... we _probably_ should delete
        -- everything for the parent server_id when we delete the proxy,
        -- but we don't currently.
        delete from rhnServerPath where server_id_in in (server_id, proxy_server_id);
        delete from rhnUserServerPerms where server_id = server_id_in;

        delete from rhnServerNetInterface where server_id = server_id_in;

        delete from rhnServerUuid where server_id = server_id_in;

        delete from rhnPushClient where server_id = server_id_in;

        -- now get rhnServer itself.
        delete
        from    rhnServer
                where id = server_id_in;

        delete
        from    rhnSet
        where   label = 'system_list'
                and element = server_id_in;
end;
$$
language plpgsql;

 07070100000879000081B400000000000000000000000167AE111400000560000000000000000000000000000000000000005D00000000susemanager-schema/upgrade/spacewalk-schema-2.4-to-spacewalk-schema-2.5/206-uuid-cleanup.sql  INSERT INTO rhnTaskoBunch (id, name, description, org_bunch)
    select sequence_nextval('rhn_tasko_bunch_id_seq'), 'uuid-cleanup-bunch', 'purge orphaned uuid records', null from dual
        where not exists (select 1 from rhnTaskoBunch where name = 'uuid-cleanup-bunch');

-- Every hour

INSERT INTO rhnTaskoSchedule (id, job_label, bunch_id, active_from, cron_expr)
    select sequence_nextval('rhn_tasko_schedule_id_seq'), 'uuid-cleanup-default',
        (SELECT id FROM rhnTaskoBunch WHERE name='uuid-cleanup-bunch'),
        current_timestamp, '0 0 * * * ?' from dual
        where not exists (select 1 from rhnTaskoSchedule where job_label = 'uuid-cleanup-default');

INSERT INTO rhnTaskoTask (id, name, class)
    select sequence_nextval('rhn_tasko_task_id_seq'), 'uuid-cleanup', 'com.redhat.rhn.taskomatic.task.UuidCleanup' from dual
where not exists (select 1 from rhnTaskoTask where name = 'uuid-cleanup');

INSERT INTO rhnTaskoTemplate (id, bunch_id, task_id, ordering, start_if)
    select sequence_nextval('rhn_tasko_template_id_seq'),
            (SELECT id FROM rhnTaskoBunch WHERE name='uuid-cleanup-bunch'),
            (SELECT id FROM rhnTaskoTask WHERE name='uuid-cleanup'),
            0,
            null from dual
        where not exists (select 1 from rhnTaskoTemplate where bunch_id = (SELECT id FROM rhnTaskoBunch WHERE name='uuid-cleanup-bunch'));
0707010000087A000081B400000000000000000000000167AE111400000260000000000000000000000000000000000000006700000000susemanager-schema/upgrade/spacewalk-schema-2.4-to-spacewalk-schema-2.5/207-remove-sync-probe-task.sql    DELETE FROM rhnTaskoRun
  WHERE template_id IN (
    SELECT id
      FROM rhnTaskoTemplate
      WHERE task_id IN (
        SELECT id
          FROM rhnTaskoTask
          WHERE name = 'sync-probe-state'
      )
  );

DELETE FROM rhnTaskoTemplate
  WHERE bunch_id IN (
    SELECT id
      FROM rhnTaskoBunch
      WHERE name = 'sync-probe-bunch'
  );

DELETE FROM rhnTaskoTask
  WHERE name = 'sync-probe-state';

DELETE FROM rhnTaskoSchedule
  WHERE bunch_id IN (
    SELECT id
      FROM rhnTaskoBunch
      WHERE name = 'sync-probe-bunch'
  );

DELETE FROM rhnTaskoBunch
  WHERE name = 'sync-probe-bunch';
0707010000087B000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000004800000000susemanager-schema/upgrade/spacewalk-schema-2.5-to-spacewalk-schema-2.6   0707010000087C000081B400000000000000000000000167AE111400000350000000000000000000000000000000000000007300000000susemanager-schema/upgrade/spacewalk-schema-2.5-to-spacewalk-schema-2.6/001-drop-rhnContentSourceSsl-move-data.sql    -- Add columns
alter table rhnContentSource add ssl_ca_cert_id NUMERIC constraint rhn_cs_cacertid_fk references rhnCryptoKey(id) on delete set null;
alter table rhnContentSource add ssl_client_cert_id NUMERIC constraint rhn_cs_clcertid_fk references rhnCryptoKey(id) on delete set null;
alter table rhnContentSource add ssl_client_key_id NUMERIC constraint rhn_cs_clkeyid_fk references rhnCryptoKey(id) on delete set null;

-- Copy values
update rhnContentSource cs set
    ssl_ca_cert_id = (select csssl.ssl_ca_cert_id from rhnContentSourceSsl csssl where csssl.content_source_id = cs.id),
    ssl_client_cert_id = (select csssl.ssl_client_cert_id from rhnContentSourceSsl csssl where csssl.content_source_id = cs.id),
    ssl_client_key_id = (select csssl.ssl_client_key_id from rhnContentSourceSsl csssl where csssl.content_source_id = cs.id);

0707010000087D000081B400000000000000000000000167AE1114000000D5000000000000000000000000000000000000007100000000susemanager-schema/upgrade/spacewalk-schema-2.5-to-spacewalk-schema-2.6/002-drop-rhnContentSourceSsl-cleanup.sql  -- Drop old stuff
delete from rhnContentSourceSsl;
drop table rhnContentSourceSsl;
drop function rhn_csssl_ins_trig_fun();
drop function rhn_cont_source_ssl_mod_trig_fun();
drop sequence rhn_contentsourcessl_seq;
   0707010000087E000081B400000000000000000000000167AE111400000071000000000000000000000000000000000000006800000000susemanager-schema/upgrade/spacewalk-schema-2.5-to-spacewalk-schema-2.6/002-uln-content-source-type.sql   insert into rhnContentSourceType (id, label) values
(sequence_nextval('rhn_content_source_type_id_seq'), 'uln');
   0707010000087F000081B400000000000000000000000167AE111400000071000000000000000000000000000000000000006800000000susemanager-schema/upgrade/spacewalk-schema-2.5-to-spacewalk-schema-2.6/003-deb-content-source-type.sql   insert into rhnContentSourceType (id, label) values
(sequence_nextval('rhn_content_source_type_id_seq'), 'deb');
   07070100000880000081B400000000000000000000000167AE111400000418000000000000000000000000000000000000006D00000000susemanager-schema/upgrade/spacewalk-schema-2.5-to-spacewalk-schema-2.6/004-rhnChannelPackage-autovacuum.sql  -- oracle equivalent source none
--
-- Copyright (c) 2016 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

-- Set some postgres-specific parameters that can strongly affect performance
-- when cloning channels
ALTER TABLE rhnChannelPackage SET (autovacuum_vacuum_scale_factor = 0.0);
ALTER TABLE rhnChannelPackage SET (autovacuum_vacuum_threshold = 15);
ALTER TABLE rhnChannelPackage SET (autovacuum_analyze_scale_factor = 0.0);
ALTER TABLE rhnChannelPackage SET (autovacuum_analyze_threshold = 15);
07070100000881000081B400000000000000000000000167AE1114000026DC000000000000000000000000000000000000006D00000000susemanager-schema/upgrade/spacewalk-schema-2.5-to-spacewalk-schema-2.6/005-avoid_deadlock_delete_server.sql  --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--
--
--
-- This deletes a server.  All codepaths which delete servers should hit this
-- or delete_server_bulk()

create or replace
function delete_server (
        server_id_in in numeric
) returns void
as
$$
declare
         servergroups cursor for
                select  server_id, server_group_id
                from    rhnServerGroupMembers sgm
                where   sgm.server_id = server_id_in;

         configchannels cursor for
                select  cc.id
                from    rhnConfigChannel cc,
                        rhnConfigChannelType cct,
                        rhnServerConfigChannel scc
                where   1=1
                        and scc.server_id = server_id_in
                        and scc.config_channel_id = cc.id
                        -- these config channel types are reserved
                        -- for use by a single server, so we don't
                        -- need to check for other servers subscribed
                        and cct.label in
                                ('local_override','server_import')
                        and cct.id = cc.confchan_type_id;

    update_lock numeric;
begin
    -- lock the rhnServer row to prevent deadlocks
    -- we want rhnServer to be locked first, followed by tables that depend on it
    select id into update_lock from rhnServer where id = server_id_in for update;

        -- filelists
        delete from rhnFileList where id in (
	select	spfl.file_list_id
	  from	rhnServerPreserveFileList spfl
	 where	spfl.server_id = server_id_in
			and not exists (
				select	1
				from	rhnServerPreserveFileList
				where	file_list_id = spfl.file_list_id
					and server_id != server_id_in
				union all
				select	1
				from	rhnKickstartPreserveFileList
				where	file_list_id = spfl.file_list_id
			)
        );

	for configchannel in configchannels loop
		perform rhn_config.delete_channel(configchannel.id);
	end loop;

	for sgm in servergroups loop
		perform rhn_server.delete_from_servergroup(
			sgm.server_id, sgm.server_group_id);
	end loop;


        -- we're handling this instead of letting an "on delete
        -- set null" do it so that we don't run the risk
        -- of setting off the triggers and killing us with a
        -- mutating table

        -- this is merge of two single updates:
        --  update ... set old_server_id = null where old_server_id = server_id_in;
        --  update ... set new_server_id = null where new_server_id = server_id_in;
        -- so we scan rhnKickstartSession table only once
        update rhnKickstartSession
                set old_server_id = case when old_server_id = server_id_in then null else old_server_id end,
                    new_server_id = case when new_server_id = server_id_in then null else new_server_id end
                where old_server_id = server_id_in
                   or new_server_id = server_id_in;

        perform rhn_channel.clear_subscriptions(server_id_in, 1);

        -- A little complicated here, but the goal is to
        -- delete records from rhnVirtualInstace only if we don't
        -- care about them anymore.  We don't care about records
        -- in rhnVirtualInstance if we are deleting the host
        -- system and the virtual system is already null, or
        -- vice-versa.  We *do* care about them if either the
        -- host or virtual system is still registered because we
        -- still want them to show up in the UI.
    -- If there's a newer row in rhnVirtualInstance with the same
    -- uuid, this guest must have been re-registered, so we can clean
    -- this data up.

        delete from rhnVirtualInstance vi
              where (host_system_id = server_id_in and virtual_system_id is null)
                 or (virtual_system_id = server_id_in and host_system_id is null)
                 or (vi.virtual_system_id = server_id_in and vi.modified < (select max(vi2.modified)
                    from rhnVirtualInstance vi2 where vi2.uuid = vi.uuid));

        -- this is merge of two single updates:
        --  update ... set host_system_id = null where host_system_id = server_id_in;
        --  update ... set virtual_system_id = null where virtual_system_id = server_id_in;
        -- so we scan rhnVirtualInstance table only once
        update rhnVirtualInstance
           set host_system_id = case when host_system_id = server_id_in then null else host_system_id end,
               virtual_system_id = case when virtual_system_id = server_id_in then null else virtual_system_id end
         where host_system_id = server_id_in
            or virtual_system_id = server_id_in;

        -- this is merge of two single updates:
        --  update ... set old_host_system_id = null when old_host_system_id = server_id_in;
        --  update ... set new_host_system_id = null when new_host_system_id = server_id_in;
        -- so we scan rhnVirtualInstanceEventLog table only once
        update rhnVirtualInstanceEventLog
           set old_host_system_id = case when old_host_system_id = server_id_in then null else old_host_system_id end,
               new_host_system_id = case when new_host_system_id = server_id_in then null else new_host_system_id end
         where old_host_system_id = server_id_in
            or new_host_system_id = server_id_in;

        -- We're deleting everything with a foreign key to rhnServer
        -- here, now.  I'm hoping this will help aleviate our deadlock
        -- problem.

        delete from rhnActionConfigChannel where server_id = server_id_in;
        delete from rhnActionConfigRevision where server_id = server_id_in;
        delete from rhnActionPackageRemovalFailure where server_id = server_id_in;
        delete from rhnClientCapability where server_id = server_id_in;
        delete from rhnCpu where server_id = server_id_in;
        -- there's still a cascade here, because the constraint keeps the
        -- table locked for too long to rebuild it.  Ugh...
        delete from rhnDevice where server_id = server_id_in;
        delete from rhnProxyInfo where server_id = server_id_in;
        delete from rhnRam where server_id = server_id_in;
        delete from rhnRegToken where server_id = server_id_in;
        delete from rhnSatelliteInfo where server_id = server_id_in;
        -- this cascades to rhnActionConfigChannel and rhnActionConfigFileName
        delete from rhnServerAction where server_id = server_id_in;
        delete from rhnServerActionPackageResult where server_id = server_id_in;
        delete from rhnServerActionScriptResult where server_id = server_id_in;
        delete from rhnServerActionVerifyResult where server_id = server_id_in;
        delete from rhnServerActionVerifyMissing where server_id = server_id_in;
        -- counts are handled above.  this should be a delete_ function.
        delete from rhnServerChannel where server_id = server_id_in;
        delete from rhnServerConfigChannel where server_id = server_id_in;
        delete from rhnServerCustomDataValue where server_id = server_id_in;
        delete from rhnServerDMI where server_id = server_id_in;
        delete from rhnServerEvent where server_id = server_id_in;
        delete from rhnServerHistory where server_id = server_id_in;
        delete from rhnServerInfo where server_id = server_id_in;
        delete from rhnServerInstallInfo where server_id = server_id_in;
        delete from rhnServerLocation where server_id = server_id_in;
        delete from rhnServerLock where server_id = server_id_in;
        delete from rhnServerNeededCache where server_id = server_id_in;
        delete from rhnServerNetwork where server_id = server_id_in;
        delete from rhnServerNotes where server_id = server_id_in;
        -- I'm not removing the foreign key from rhnServerPackage; that'll
        -- take forever.  Do the delete anyway.
        delete from rhnServerPackage where server_id = server_id_in;
        delete from rhnServerTokenRegs where server_id = server_id_in;
        delete from rhnSnapshotTag where server_id = server_id_in;
        -- this cascades to:
        --   rhnSnapshotChannel, rhnSnapshotConfigChannel, rhnSnapshotPackage,
        --   rhnSnapshotConfigRevision, rhnSnapshotServerGroup,
        --   rhnSnapshotTag.
        -- We may want to consider delete_snapshot() at some point, but
        --   I don't think we need to yet.
        delete from rhnSnapshot where server_id = server_id_in;
        delete from rhnUserServerPrefs where server_id = server_id_in;
        -- hrm, this one's interesting... we _probably_ should delete
        -- everything for the parent server_id when we delete the proxy,
        -- but we don't currently.
        delete from rhnServerPath where server_id_in in (server_id, proxy_server_id);
        delete from rhnUserServerPerms where server_id = server_id_in;

        delete from rhnServerNetInterface where server_id = server_id_in;

        delete from rhnServerUuid where server_id = server_id_in;

        delete from rhnPushClient where server_id = server_id_in;

        -- now get rhnServer itself.
        delete
        from    rhnServer
                where id = server_id_in;

        delete
        from    rhnSet
        where   label = 'system_list'
                and element = server_id_in;
end;
$$
language plpgsql;
07070100000882000081B400000000000000000000000167AE111400000240000000000000000000000000000000000000006200000000susemanager-schema/upgrade/spacewalk-schema-2.5-to-spacewalk-schema-2.6/006-add-fedora24-keys.sql insert into rhnPackageKey (id, key_id, key_type_id, provider_id) select sequence_nextval('rhn_pkey_id_seq'), '73bde98381b46521', lookup_package_key_type('gpg'), lookup_package_provider('Fedora') from dual where not exists (select 1 from rhnPackageKey where key_id = '73bde98381b46521');

insert into rhnPackageKey (id, key_id, key_type_id, provider_id) select sequence_nextval('rhn_pkey_id_seq'), 'b8635eeb030d5aed', lookup_package_key_type('gpg'), lookup_package_provider('Fedora') from dual where not exists (select 1 from rhnPackageKey where key_id = 'b8635eeb030d5aed');

07070100000883000081B400000000000000000000000167AE111400002BCC000000000000000000000000000000000000006400000000susemanager-schema/upgrade/spacewalk-schema-2.5-to-spacewalk-schema-2.6/007-remove-solaris-arch.sql   
create or replace
function delete_server_tmp (
  arch_in varchar
)
returns void as
$$
declare
  rec record;
begin
  for rec in select server.id as id
      from rhnServer server
      where server_arch_id = LOOKUP_SERVER_ARCH(arch_in) loop
    perform .clear_log_id();
    perform delete_server(rec.id);
  end loop;
end;
$$ language plpgsql;

select delete_server_tmp('sparc-sun4m-solaris');
select delete_server_tmp('sparc-sun4u-solaris');
select delete_server_tmp('sparc-sun4v-solaris');
select delete_server_tmp('i386-i86pc-solaris');

drop function delete_server_tmp(varchar);

create or replace
function delete_channel_tmp (
  arch_in varchar
)
returns void as
$$
declare
  rec record;
begin
  for rec in select channel.id as id
      from rhnChannel channel
      where channel_arch_id = LOOKUP_CHANNEL_ARCH(arch_in) loop
    perform delete_channel(rec.id);
  end loop;
end;
$$ language plpgsql;

create or replace
function delete_channel_tmp_child (
  arch_in varchar
)
returns void as
$$
declare
  rec record;
begin
  for rec in select channel.id as id
      from rhnChannel channel
      where channel.parent_channel in
        (select id from rhnChannel c2
          where c2.channel_arch_id = LOOKUP_CHANNEL_ARCH(arch_in))
    loop
    perform delete_channel(rec.id);
  end loop;
end;
$$ language plpgsql;

select delete_channel_tmp_child('channel-sparc-sun-solaris');
select delete_channel_tmp_child('channel-i386-sun-solaris');
select delete_channel_tmp('channel-sparc-sun-solaris');
select delete_channel_tmp('channel-i386-sun-solaris');

drop function delete_channel_tmp(varchar);
drop function delete_channel_tmp_child(varchar);

delete from rhnChannelPackageArchCompat where channel_arch_id = LOOKUP_CHANNEL_ARCH('channel-sparc-sun-solaris');
delete from rhnChannelPackageArchCompat where channel_arch_id = LOOKUP_CHANNEL_ARCH('channel-i386-sun-solaris');

delete from rhnServerChannelArchCompat where channel_arch_id = LOOKUP_CHANNEL_ARCH('channel-sparc-sun-solaris');
delete from rhnServerChannelArchCompat where channel_arch_id = LOOKUP_CHANNEL_ARCH('channel-i386-sun-solaris');

delete from rhnChildChannelArchCompat where parent_arch_id = LOOKUP_CHANNEL_ARCH('channel-sparc-sun-solaris');
delete from rhnChildChannelArchCompat where parent_arch_id = LOOKUP_CHANNEL_ARCH('channel-i386-sun-solaris');
delete from rhnChildChannelArchCompat where child_arch_id = LOOKUP_CHANNEL_ARCH('channel-sparc-sun-solaris');
delete from rhnChildChannelArchCompat where child_arch_id = LOOKUP_CHANNEL_ARCH('channel-i386-sun-solaris');

delete from rhnChannelArch where label = 'channel-sparc-sun-solaris';
delete from rhnChannelArch where label = 'channel-i386-sun-solaris';

delete from rhnPackageUpgradeArchCompat where package_arch_id = LOOKUP_PACKAGE_ARCH('sparc-solaris');
delete from rhnPackageUpgradeArchCompat where package_arch_id = LOOKUP_PACKAGE_ARCH('sparc.sun4u-solaris');
delete from rhnPackageUpgradeArchCompat where package_arch_id = LOOKUP_PACKAGE_ARCH('sparc.sun4v-solaris');
delete from rhnPackageUpgradeArchCompat where package_arch_id = LOOKUP_PACKAGE_ARCH('i386-solaris');
delete from rhnPackageUpgradeArchCompat where package_arch_id = LOOKUP_PACKAGE_ARCH('sparc-solaris-patch');
delete from rhnPackageUpgradeArchCompat where package_arch_id = LOOKUP_PACKAGE_ARCH('i386-solaris-patch');
delete from rhnPackageUpgradeArchCompat where package_arch_id = LOOKUP_PACKAGE_ARCH('sparc-solaris-patch-cluster');
delete from rhnPackageUpgradeArchCompat where package_arch_id = LOOKUP_PACKAGE_ARCH('i386-solaris-patch-cluster');
delete from rhnPackageUpgradeArchCompat where package_arch_id = LOOKUP_PACKAGE_ARCH('noarch-solaris');
delete from rhnPackageUpgradeArchCompat where package_arch_id = LOOKUP_PACKAGE_ARCH('noarch-solaris-patch');
delete from rhnPackageUpgradeArchCompat where package_arch_id = LOOKUP_PACKAGE_ARCH('noarch-solaris-patch-cluster');

delete from rhnPackageUpgradeArchCompat where package_upgrade_arch_id = LOOKUP_PACKAGE_ARCH('sparc-solaris');
delete from rhnPackageUpgradeArchCompat where package_upgrade_arch_id = LOOKUP_PACKAGE_ARCH('sparc.sun4u-solaris');
delete from rhnPackageUpgradeArchCompat where package_upgrade_arch_id = LOOKUP_PACKAGE_ARCH('sparc.sun4v-solaris');
delete from rhnPackageUpgradeArchCompat where package_upgrade_arch_id = LOOKUP_PACKAGE_ARCH('i386-solaris');
delete from rhnPackageUpgradeArchCompat where package_upgrade_arch_id = LOOKUP_PACKAGE_ARCH('sparc-solaris-patch');
delete from rhnPackageUpgradeArchCompat where package_upgrade_arch_id = LOOKUP_PACKAGE_ARCH('i386-solaris-patch');
delete from rhnPackageUpgradeArchCompat where package_upgrade_arch_id = LOOKUP_PACKAGE_ARCH('sparc-solaris-patch-cluster');
delete from rhnPackageUpgradeArchCompat where package_upgrade_arch_id = LOOKUP_PACKAGE_ARCH('i386-solaris-patch-cluster');
delete from rhnPackageUpgradeArchCompat where package_upgrade_arch_id = LOOKUP_PACKAGE_ARCH('noarch-solaris');
delete from rhnPackageUpgradeArchCompat where package_upgrade_arch_id = LOOKUP_PACKAGE_ARCH('noarch-solaris-patch');
delete from rhnPackageUpgradeArchCompat where package_upgrade_arch_id = LOOKUP_PACKAGE_ARCH('noarch-solaris-patch-cluster');

delete from rhnServerPackageArchCompat where package_arch_id = LOOKUP_PACKAGE_ARCH('sparc-solaris');
delete from rhnServerPackageArchCompat where package_arch_id = LOOKUP_PACKAGE_ARCH('sparc.sun4u-solaris');
delete from rhnServerPackageArchCompat where package_arch_id = LOOKUP_PACKAGE_ARCH('sparc.sun4v-solaris');
delete from rhnServerPackageArchCompat where package_arch_id = LOOKUP_PACKAGE_ARCH('i386-solaris');
delete from rhnServerPackageArchCompat where package_arch_id = LOOKUP_PACKAGE_ARCH('sparc-solaris-patch');
delete from rhnServerPackageArchCompat where package_arch_id = LOOKUP_PACKAGE_ARCH('i386-solaris-patch');
delete from rhnServerPackageArchCompat where package_arch_id = LOOKUP_PACKAGE_ARCH('sparc-solaris-patch-cluster');
delete from rhnServerPackageArchCompat where package_arch_id = LOOKUP_PACKAGE_ARCH('i386-solaris-patch-cluster');
delete from rhnServerPackageArchCompat where package_arch_id = LOOKUP_PACKAGE_ARCH('noarch-solaris');
delete from rhnServerPackageArchCompat where package_arch_id = LOOKUP_PACKAGE_ARCH('noarch-solaris-patch');
delete from rhnServerPackageArchCompat where package_arch_id = LOOKUP_PACKAGE_ARCH('noarch-solaris-patch-cluster');

delete from rhnPackage where package_arch_id = (select id from rhnPackageArch where label = 'sparc-solaris');
delete from rhnPackage where package_arch_id = (select id from rhnPackageArch where label = 'sparc.sun4u-solaris');
delete from rhnPackage where package_arch_id = (select id from rhnPackageArch where label = 'sparc.sun4v-solaris');
delete from rhnPackage where package_arch_id = (select id from rhnPackageArch where label = 'i386-solaris');
delete from rhnPackage where package_arch_id = (select id from rhnPackageArch where label = 'sparc-solaris-patch');
delete from rhnPackage where package_arch_id = (select id from rhnPackageArch where label = 'i386-solaris-patch');
delete from rhnPackage where package_arch_id = (select id from rhnPackageArch where label = 'sparc-solaris-patch-cluster');
delete from rhnPackage where package_arch_id = (select id from rhnPackageArch where label = 'i386-solaris-patch-cluster');
delete from rhnPackage where package_arch_id = (select id from rhnPackageArch where label = 'noarch-solaris');
delete from rhnPackage where package_arch_id = (select id from rhnPackageArch where label = 'noarch-solaris-patch');
delete from rhnPackage where package_arch_id = (select id from rhnPackageArch where label = 'noarch-solaris-patch-cluster');

delete from rhnPackageNEVRA where package_arch_id = (select id from rhnPackageArch where label = 'sparc-solaris');
delete from rhnPackageNEVRA where package_arch_id = (select id from rhnPackageArch where label = 'sparc.sun4u-solaris');
delete from rhnPackageNEVRA where package_arch_id = (select id from rhnPackageArch where label = 'sparc.sun4v-solaris');
delete from rhnPackageNEVRA where package_arch_id = (select id from rhnPackageArch where label = 'i386-solaris');
delete from rhnPackageNEVRA where package_arch_id = (select id from rhnPackageArch where label = 'sparc-solaris-patch');
delete from rhnPackageNEVRA where package_arch_id = (select id from rhnPackageArch where label = 'i386-solaris-patch');
delete from rhnPackageNEVRA where package_arch_id = (select id from rhnPackageArch where label = 'sparc-solaris-patch-cluster');
delete from rhnPackageNEVRA where package_arch_id = (select id from rhnPackageArch where label = 'i386-solaris-patch-cluster');
delete from rhnPackageNEVRA where package_arch_id = (select id from rhnPackageArch where label = 'noarch-solaris');
delete from rhnPackageNEVRA where package_arch_id = (select id from rhnPackageArch where label = 'noarch-solaris-patch');
delete from rhnPackageNEVRA where package_arch_id = (select id from rhnPackageArch where label = 'noarch-solaris-patch-cluster');

delete from rhnPackageArch where label = 'sparc-solaris';
delete from rhnPackageArch where label = 'sparc.sun4u-solaris';
delete from rhnPackageArch where label = 'sparc.sun4v-solaris';
delete from rhnPackageArch where label = 'i386-solaris';
delete from rhnPackageArch where label = 'sparc-solaris-patch';
delete from rhnPackageArch where label = 'i386-solaris-patch';
delete from rhnPackageArch where label = 'sparc-solaris-patch-cluster';
delete from rhnPackageArch where label = 'i386-solaris-patch-cluster';
delete from rhnPackageArch where label = 'noarch-solaris';
delete from rhnPackageArch where label = 'noarch-solaris-patch';
delete from rhnPackageArch where label = 'noarch-solaris-patch-cluster';

delete from rhnPackageArch where arch_type_id = (select id from rhnArchType where label = 'solaris-patch');
delete from rhnPackageArch where arch_type_id = (select id from rhnArchType where label = 'solaris-patch-cluster');
delete from rhnPackageArch where arch_type_id = (select id from rhnArchType where label = 'sysv-solaris');

delete from rhnServerServerGroupArchCompat where server_arch_id = LOOKUP_SERVER_ARCH('sparc-sun4m-solaris');
delete from rhnServerServerGroupArchCompat where server_arch_id = LOOKUP_SERVER_ARCH('sparc-sun4u-solaris');
delete from rhnServerServerGroupArchCompat where server_arch_id = LOOKUP_SERVER_ARCH('sparc-sun4v-solaris');
delete from rhnServerServerGroupArchCompat where server_arch_id = LOOKUP_SERVER_ARCH('i386-i86pc-solaris');

delete from rhnServerArch where label = 'sparc-sun4m-solaris';
delete from rhnServerArch where label = 'sparc-sun4u-solaris';
delete from rhnServerArch where label = 'sparc-sun4v-solaris';
delete from rhnServerArch where label = 'i386-i86pc-solaris';

delete from rhnArchTypeActions where arch_type_id = (select id from rhnArchType where label = 'solaris-patch');
delete from rhnArchTypeActions where arch_type_id = (select id from rhnArchType where label = 'solaris-patch-cluster');
delete from rhnArchTypeActions where arch_type_id = (select id from rhnArchType where label = 'sysv-solaris');

delete from rhnArchType where label = 'solaris-patch';
delete from rhnArchType where label = 'solaris-patch-cluster';
delete from rhnArchType where label = 'sysv-solaris';
07070100000884000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000004800000000susemanager-schema/upgrade/spacewalk-schema-2.6-to-spacewalk-schema-2.7   07070100000885000081B400000000000000000000000167AE111400000030000000000000000000000000000000000000006C00000000susemanager-schema/upgrade/spacewalk-schema-2.6-to-spacewalk-schema-2.7/001-rhnPushDispatcher-drop-port.sql   ALTER TABLE rhnPushDispatcher DROP COLUMN port;
07070100000886000081B400000000000000000000000167AE11140000003D000000000000000000000000000000000000007400000000susemanager-schema/upgrade/spacewalk-schema-2.6-to-spacewalk-schema-2.7/002-rhnKickstartCommand-custom-position.sql   ALTER TABLE rhnKickstartCommand ADD custom_position NUMERIC;
   07070100000887000081B400000000000000000000000167AE111400000583000000000000000000000000000000000000007100000000susemanager-schema/upgrade/spacewalk-schema-2.6-to-spacewalk-schema-2.7/003-rhnContentSourceSsl-create-table.sql  --
-- Copyright (c) 2017 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnContentSourceSsl
(
	content_source_id NUMERIC not null
		constraint rhn_csssl_csid_fk references rhnContentSource(id) on delete cascade,
	ssl_ca_cert_id NUMERIC not null
		constraint rhn_csssl_cacertid_fk references rhnCryptoKey(id) on delete cascade,
	ssl_client_cert_id NUMERIC
		constraint rhn_csssl_clcertid_fk references rhnCryptoKey(id) on delete cascade,
	ssl_client_key_id NUMERIC
		constraint rhn_csssl_clkeyid_fk references rhnCryptoKey(id) on delete cascade,
	constraint rhn_csssl_client_chk check(ssl_client_key_id is null or ssl_client_cert_id is not null),
	created TIMESTAMPTZ default(current_timestamp) not null,
	modified TIMESTAMPTZ default(current_timestamp) not null
)

;

CREATE INDEX rhn_csssl_cs
    ON rhnContentSourceSsl (content_source_id)
    ;
 07070100000888000081B400000000000000000000000167AE1114000004BA000000000000000000000000000000000000007300000000susemanager-schema/upgrade/spacewalk-schema-2.6-to-spacewalk-schema-2.7/004-rhnContentSourceSsl-create-indexes.sql    --
-- Copyright (c) 2017 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

CREATE UNIQUE INDEX rhn_csssl_ca_uq
    ON rhnContentSourceSsl (content_source_id, ssl_ca_cert_id)
    WHERE ssl_client_cert_id IS NULL AND ssl_client_key_id IS NULL;

CREATE UNIQUE INDEX rhn_csssl_ca_cert_uq
    ON rhnContentSourceSsl (content_source_id, ssl_ca_cert_id, ssl_client_cert_id)
    WHERE ssl_client_cert_id IS NOT NULL AND ssl_client_key_id IS NULL;

CREATE UNIQUE INDEX rhn_csssl_ca_cert_key_uq
    ON rhnContentSourceSsl (content_source_id, ssl_ca_cert_id, ssl_client_cert_id, ssl_client_key_id)
    WHERE ssl_client_cert_id IS NOT NULL AND ssl_client_key_id IS NOT NULL;
  07070100000889000081B400000000000000000000000167AE1114000003B3000000000000000000000000000000000000007400000000susemanager-schema/upgrade/spacewalk-schema-2.6-to-spacewalk-schema-2.7/004-rhnContentSourceSsl-create-triggers.sql   --
-- Copyright (c) 2017 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


create or replace function rhn_cont_source_ssl_mod_trig_fun() returns trigger as
$$
begin
	new.modified := current_timestamp;
	return new;
end;
$$ language plpgsql;

create trigger
rhn_cont_source_ssl_mod_trig
before insert or update on rhnContentSourceSsl
for each row
execute procedure rhn_cont_source_ssl_mod_trig_fun();
 0707010000088A000081B400000000000000000000000167AE1114000001E1000000000000000000000000000000000000006E00000000susemanager-schema/upgrade/spacewalk-schema-2.6-to-spacewalk-schema-2.7/005-rhnContentSourceSsl-move-data.sql insert into rhnContentSourceSsl
  (content_source_id, ssl_ca_cert_id, ssl_client_cert_id, ssl_client_key_id)
select id, ssl_ca_cert_id, ssl_client_cert_id, ssl_client_key_id
  from rhnContentSource where
  ssl_ca_cert_id is not null and
  (ssl_client_key_id is null or ssl_client_cert_id is not null);

alter table rhnContentSource drop column ssl_ca_cert_id;
alter table rhnContentSource drop column ssl_client_cert_id;
alter table rhnContentSource drop column ssl_client_key_id;
   0707010000088B000081B400000000000000000000000167AE1114000002C0000000000000000000000000000000000000006600000000susemanager-schema/upgrade/spacewalk-schema-2.6-to-spacewalk-schema-2.7/006-drop-create_first_org.sql --
-- Copyright (c) 2015 SUSE LLC.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

drop function if exists create_first_org(name_in in varchar, password_in in varchar);
0707010000088C000081B400000000000000000000000167AE111400000064000000000000000000000000000000000000006A00000000susemanager-schema/upgrade/spacewalk-schema-2.6-to-spacewalk-schema-2.7/007-drop-monitoring-leftovers.sql DROP TABLE rhn_config_parameter;
DROP TABLE rhn_config_group;
DROP TABLE rhn_config_security_type;

0707010000088D000081B400000000000000000000000167AE1114000005D1000000000000000000000000000000000000006200000000susemanager-schema/upgrade/spacewalk-schema-2.6-to-spacewalk-schema-2.7/008-rhnSet-uniqueness.sql --
-- Copyright (c) 2017 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

SELECT * INTO TEMPORARY rhnSet_all from rhnSet;
DELETE FROM rhnSet;
INSERT INTO rhnSet SELECT DISTINCT * FROM rhnSet_all;

ALTER TABLE rhnSet DROP CONSTRAINT rhn_set_user_label_elem_unq;

CREATE UNIQUE INDEX rhn_set_user_label_elem_unq
    ON rhnSet (user_id, label, element)
    WHERE element_two IS NULL AND element_three IS NULL;

CREATE UNIQUE INDEX rhn_set_user_label_elem_elem2_unq
    ON rhnSet (user_id, label, element, element_two)
    WHERE element_two IS NOT NULL AND element_three IS NULL;

CREATE UNIQUE INDEX rhn_set_user_label_elem_elem3_unq
    ON rhnSet (user_id, label, element, element_three)
    WHERE element_two IS NULL AND element_three IS NOT NULL;

CREATE UNIQUE INDEX rhn_set_user_label_elem_elem2_elem3_unq
    ON rhnSet (user_id, label, element, element_two, element_three)
    WHERE element_two IS NOT NULL AND element_three IS NOT NULL;
   0707010000088E000081B400000000000000000000000167AE111400000453000000000000000000000000000000000000005F00000000susemanager-schema/upgrade/spacewalk-schema-2.6-to-spacewalk-schema-2.7/009-rhnErrata-uniq.sql    --
-- Copyright (c) 2017 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

DROP INDEX rhn_errata_advisory_name_uq;
DROP INDEX rhn_errata_advisory_uq;

CREATE UNIQUE INDEX rhn_errata_advname_uq
    ON rhnErrata (advisory_name)
 WHERE org_id IS NULL;

CREATE UNIQUE INDEX rhn_errata_advname_org_uq
    ON rhnErrata (advisory_name, org_id)
 WHERE org_id IS NOT NULL;

CREATE UNIQUE INDEX rhn_errata_adv_uq
    ON rhnErrata (advisory)
 WHERE org_id IS NULL;

CREATE UNIQUE INDEX rhn_errata_adv_org_uq
    ON rhnErrata (advisory, org_id)
 WHERE org_id IS NOT NULL;
 0707010000088F000081B400000000000000000000000167AE11140000059D000000000000000000000000000000000000006900000000susemanager-schema/upgrade/spacewalk-schema-2.6-to-spacewalk-schema-2.7/010-remove-misaligned-errata.sql  --
-- Copyright (c) 2017 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

DELETE FROM rhnchannelerrata
      WHERE (channel_id, errata_id) in (SELECT ce.channel_id, ce.errata_id
                                          FROM rhnchannelerrata ce
                                          JOIN rhnchannel c ON c.id = ce.channel_id
                                          JOIN rhnerrata e ON e.id = ce.errata_id
                                         WHERE e.org_id <> c.org_id);

DELETE FROM rhnerratapackage
      WHERE (errata_id, package_id) in (SELECT pe.errata_id, pe.package_id
                                          FROM rhnerratapackage pe
                                          JOIN rhnpackage p ON p.id = pe.package_id
                                          JOIN rhnerrata e ON e.id = pe.errata_id
                                         WHERE e.org_id <> p.org_id);
   07070100000890000081B400000000000000000000000167AE1114000000DD000000000000000000000000000000000000006F00000000susemanager-schema/upgrade/spacewalk-schema-2.6-to-spacewalk-schema-2.7/011-rhncontentsourcefilter-cascade.sql    alter table rhnContentSourceFilter drop constraint rhn_csf_source_fk;

alter table rhnContentSourceFilter add constraint rhn_csf_source_fk
  foreign key (source_id)
  references rhnContentSource (id)
  on delete cascade;
   07070100000891000081B400000000000000000000000167AE111400004DE4000000000000000000000000000000000000006600000000susemanager-schema/upgrade/spacewalk-schema-2.6-to-spacewalk-schema-2.7/012-rhnConfigInfo_indexes.sql --
-- Copyright (c) 2017 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--
-- We have to fix rhnConfigInfo in the presence of dups (and the rhnCOnfigRevisions that
-- might be pointing at them)
-- Clean up table, and then create corrected postgresql indicies to prevent dups
-- in the future
--
-- FOUR CASES:
--  Cfg-file is a FILE - username/groupname/filemode are NOT NULL, symlink_target_filename_id IS NULL, AND:
--    selinux_ctx IS NULL
--    selinux_ctx IS NOT NULL
--  Cfg-file is a LINK - username/groupname/filemode ARE ALL NULL, AND symlink_target_filename_id is NOT NULL, AND:
--    selinux_ctx NULL
--    selinux_ctx IS NOT NULL
--
-- Check all FOUR - if ANY show multiple rows, table is broken :(
--
create or replace function
is_cfginfo_broken() returns boolean
as
$$
declare
    throwaway       numeric;
    bad_data_exists boolean := false;
begin
    -- (1) Count username, groupname, filemode combinations where
    --     selinux_ctx is null
    select 1 into throwaway
    from (
        select username, groupname, filemode, count(id) as num
          from rhnConfigInfo
         where username is not null and groupname is not null and filemode is not null
           and symlink_target_filename_id is null and selinux_ctx is null
         group by username, groupname, filemode
    ) x
    where x.num > 1;

    if found then
        raise info 'DUP FILE INFO found, selinux NULL';
        bad_data_exists := true;
    end if;

    -- (2) Count username, groupname, filemode, selinux_ctx combinations where
    --     selinux is not null
    select 1 into throwaway
    from (
        select username, groupname, filemode, selinux_ctx, count(id) as num
          from rhnConfigInfo
         where username is not null and groupname is not null and filemode is not null
           and symlink_target_filename_id is null and selinux_ctx is not null
         group by username, groupname, filemode, selinux_ctx
    ) x
    where x.num > 1;

    if found then
        raise info 'DUP FILE INFO found, selinux is NOT NULL';
        bad_data_exists := true;
    end if;

    -- (3) Count symlink_target_filename_id combinations
    --     where username, groupname, filemode are null and selinux_ctx is null
    select 1 into throwaway
    from (
        select symlink_target_filename_id, count(id) as num
          from rhnConfigInfo
         where symlink_target_filename_id is not null
           and username is null and groupname is null and filemode is null
           and selinux_ctx is null
         group by symlink_target_filename_id
    ) x
    where x.num > 1;

    if found then
        raise info 'DUP LINK INFO found, selinux IS NULL';
        bad_data_exists := true;
    end if;

    -- (4) Count symlink_target_filename_id combinations
    --     where username, groupname, filemode are null and selinux_ctx IS NOT null
    select 1 into throwaway
    from (
        select symlink_target_filename_id, count(id) as num
          from rhnConfigInfo
         where symlink_target_filename_id is not null
           and username is null and groupname is null and filemode is null
           and selinux_ctx is not null
         group by symlink_target_filename_id
    ) x
    where x.num > 1;

    if found then
        raise info 'DUP LINK INFO found, selinux NOT NULL';
        bad_data_exists := true;
    end if;

    return bad_data_exists;
end
$$
language plpgsql;

--
-- Fix rhnConfigRevision pointers into rhnConfigInfo where there are dups
--  Cfg-file is a FILE - username/groupname/filemode are NOT NULL, AND symlink_target_filename_id NULL, AND:
--    fix_cfgrev_files_SELINUX_NULL     : selinux_ctx NULL
--    fix_cfgrev_files_SELINUX_NOT_NULL : selinux_ctx NOT NULL
--  Cfg-file is a LINK - username/groupname/filemode ARE ALL NULL, AND symlink_target_filename_id is NOT NULL, AND:
--    fix_cfgrev_links_SELINUX_NULL     : selinux_ctx NULL
--    fix_cfgrev_links_SELINUX_NOT_NULL : selinux_ctx NOT NULL
--
-- (The following is Ugly Repetitive Code - but it's one-use-only and gets the job done in the most obvious way possible)
--
create or replace function
fix_cfgrev_files_SELINUX_NULL() returns void
as
$$
declare
    d record;
    first_time      boolean               := true;
    good_cfginfo_id numeric               := -1;
    good_username   character varying(32) := '';
    good_groupname  character varying(32) := '';
    good_filemode   numeric               := -1;
begin
    for d in
        -- Find the cardinality of the IDs of the dups
        -- We will remember the most-used rhnConfigInfo.id, and repoint rhnConfigRevisions at it
        SELECT z.id as dup_cfginfo_id, z.username, z.groupname, z.filemode, count(crev.id) as num_rhnConfigRevision_using
        from (
            -- Find the IDs of the dups
            SELECT ci.id, ci.username, ci.groupname, ci.filemode
              from rhnConfigInfo ci
                   inner join (
			-- Find just the ones that are dups
			SELECT x.username, x.groupname, x.filemode, x.num
			from (
			    -- Count username,groupname,filemode combinations where symlink_target_filename_id and selinux_ctx are null
			    select username, groupname, filemode, count(id) as num
			      from rhnConfigInfo
			     where symlink_target_filename_id is null and selinux_ctx is null
			     group by username, groupname, filemode
			     ) x
			where x.num > 1
		    ) y on y.username = ci.username and y.groupname = ci.groupname and y.filemode = ci.filemode
             where 1=1
               and ci.symlink_target_filename_id is null and ci.selinux_ctx is null
             order by username, groupname, filemode, id
        ) z
        left outer join rhnConfigRevision crev on crev.config_info_id = z.id
        group by z.id, z.username, z.groupname, z.filemode
        order by z.username, z.groupname, z.filemode, count(crev.id) desc, z.id
    loop
        -- First time in, or when we move to a new kind-of dup, remember that one
        if first_time or (d.username <> good_username or d.groupname <> good_groupname or d.filemode <> good_filemode)
        then
            first_time := false;
            -- Remember the 'good values' so we can tell when we've moved to a new set in the dataresult
            good_cfginfo_id := d.dup_cfginfo_id;
            good_username   := d.username;
            good_groupname  := d.groupname;
            good_filemode   := d.filemode;
        -- we have seen this one before - repoint users at 'good' and remove this one
        else
            if d.num_rhnconfigrevision_using > 0
            then
                raise info '...REPOINTING RECORDS, rhnConfigInfo = %',d.dup_cfginfo_id;
                UPDATE rhnConfigRevision
                   set config_info_id = good_cfginfo_id
                 where config_info_id = d.dup_cfginfo_id;
            end if;
            DELETE from rhnConfigInfo ci
             where 1=1
               and ci.username = good_username
               and ci.groupname = good_groupname
               and ci.filemode = good_filemode
               and ci.selinux_ctx is null
               and ci.id = d.dup_cfginfo_id;
        end if;
    end loop;
end
$$
language plpgsql;

create or replace function
fix_cfgrev_files_SELINUX_NOT_NULL() returns void
as
$$
declare
    d record;
    first_time       boolean               := true;
    good_cfginfo_id  numeric               := -1;
    good_username    character varying(32) := '';
    good_groupname   character varying(32) := '';
    good_selinux_ctx character varying(64) := '';
    good_filemode    numeric               := -1;
begin
    for d in
        -- Find the cardinality of the IDs of the dups
        -- We will remember the most-used rhnConfigInfo.id, and repoint rhnConfigRevisions at it
        SELECT z.id as dup_cfginfo_id, z.username, z.groupname, z.filemode, z.selinux_ctx, count(crev.id) as num_rhnConfigRevision_using
        from (
            -- Find the IDs of the dups
            SELECT ci.id, ci.username, ci.groupname, ci.filemode, ci.selinux_ctx
              from rhnConfigInfo ci
                   inner join (
			-- Find just the ones that are dups
			SELECT x.username, x.groupname, x.filemode, x.selinux_ctx, x.num
			from (
			    -- Count username,groupname,filemode combinations where symlink_target_filename_id and selinux_ctx are null
			    select username, groupname, filemode, selinux_ctx, count(id) as num
			      from rhnConfigInfo
			     where symlink_target_filename_id is null and selinux_ctx is not null
			     group by username, groupname, filemode, selinux_ctx
			     ) x
			where x.num > 1
		    ) y on y.username = ci.username and y.groupname = ci.groupname and y.filemode = ci.filemode and y.selinux_ctx = ci.selinux_ctx
             where 1=1
               and ci.symlink_target_filename_id is null and ci.selinux_ctx is not null
             order by username, groupname, filemode, selinux_ctx, id
        ) z
        left outer join rhnConfigRevision crev on crev.config_info_id = z.id
        group by z.id, z.username, z.groupname, z.filemode, z.selinux_ctx
        order by z.username, z.groupname, z.filemode, z.selinux_ctx, count(crev.id) desc, z.id
    loop
        -- First time in, or when we move to a new kind-of dup, remember that one
        if first_time or (d.username <> good_username or d.groupname <> good_groupname or d.filemode <> good_filemode)
        then
            first_time := false;
            -- Remember the 'good values' so we can tell when we've moved to a new set in the dataresult
            good_cfginfo_id  := d.dup_cfginfo_id;
            good_username    := d.username;
            good_groupname   := d.groupname;
            good_filemode    := d.filemode;
            good_selinux_ctx := d.selinux_ctx;
        -- we have seen this one before - repoint users at 'good' and remove this one
        else
            if d.num_rhnconfigrevision_using > 0
            then
                raise info '...REPOINTING RECORDS, rhnConfigInfo = %',d.dup_cfginfo_id;
                UPDATE rhnConfigRevision
                   set config_info_id = good_cfginfo_id
                 where config_info_id = d.dup_cfginfo_id;
            end if;
            DELETE from rhnConfigInfo ci
             where 1=1
               and ci.username = good_username
               and ci.groupname = good_groupname
               and ci.filemode = good_filemode
               and ci.selinux_ctx = good_selinux_ctx
               and ci.id = d.dup_cfginfo_id;
        end if;
    end loop;
end
$$
language plpgsql;

create or replace function
fix_cfgrev_links_SELINUX_NOT_NULL() returns void
as
$$
declare
    d record;
    first_time                      boolean               := true;
    good_cfginfo_id                 numeric               := -1;
    good_symlink_target_filename_id numeric               := -1;
    good_selinux_ctx                character varying(64) := null;
begin
    for d in
        -- Find the cardinality of the IDs of the dups
        -- We will remember the most-used rhnConfigInfo.id, and repoint rhnConfigRevisions at it
        SELECT z.id as dup_cfginfo_id, z.symlink_target_filename_id, z.selinux_ctx, count(crev.id) as num_rhnConfigRevision_using
        from (
            -- Find the IDs of the dups
            SELECT ci.id, ci.symlink_target_filename_id, ci.selinux_ctx
              from rhnConfigInfo ci
                   inner join (
			-- Find just the ones that are dups
			SELECT x.symlink_target_filename_id, x.selinux_ctx, x.num
			from (
			    -- Count where symlink_target_filename_id is not null and selinux_ctx is not null
			    select symlink_target_filename_id, selinux_ctx, count(id) as num
			      from rhnConfigInfo
			     where username is null
                               and groupname is null
                               and filemode is null
                               and symlink_target_filename_id is not null
                               and selinux_ctx is not null
			     group by symlink_target_filename_id, selinux_ctx
			     ) x
			where x.num > 1
		    ) y on y.symlink_target_filename_id = ci.symlink_target_filename_id and y.selinux_ctx = ci.selinux_ctx
             where 1=1
               and ci.symlink_target_filename_id is not null and ci.selinux_ctx is not null
             order by symlink_target_filename_id, selinux_ctx, id
        ) z
        left outer join rhnConfigRevision crev on crev.config_info_id = z.id
        group by z.id, z.symlink_target_filename_id, z.selinux_ctx
        order by z.symlink_target_filename_id, z.selinux_ctx, count(crev.id) desc, z.id
    loop
        -- First time in, or when we move to a new kind-of dup, remember that one
        if first_time or (d.symlink_target_filename_id <> good_symlink_target_filename_id or d.selinux_ctx <> good_selinux_ctx)
        then
            first_time := false;
            -- Remember the 'good values' so we can tell when we've moved to a new set in the dataresult
            good_cfginfo_id                 := d.dup_cfginfo_id;
            good_symlink_target_filename_id := d.symlink_target_filename_id;
            good_selinux_ctx                := d.selinux_ctx;
        -- we have seen this one before - repoint users at 'good' and remove this one
        else
            if d.num_rhnconfigrevision_using > 0
            then
                raise info '...REPOINTING RECORDS, rhnConfigInfo = %',d.dup_cfginfo_id;
                UPDATE rhnConfigRevision
                   set config_info_id = good_cfginfo_id
                 where config_info_id = d.dup_cfginfo_id;
            end if;
            DELETE from rhnConfigInfo ci
             where 1=1
               and ci.symlink_target_filename_id = good_symlink_target_filename_id
               and ci.selinux_ctx                = good_selinux_ctx
               and ci.id = d.dup_cfginfo_id;
        end if;
    end loop;
end
$$
language plpgsql;

create or replace function
fix_cfgrev_links_SELINUX_NULL() returns void
as
$$
declare
    d record;
    first_time      boolean                 := true;
    good_cfginfo_id numeric                 := -1;
    good_symlink_target_filename_id numeric := -1;
begin
    raise info 'ENTERING fix_cfgrev_links_SELINUX_NULL';
    for d in
        -- Find the cardinality of the IDs of the dups
        -- We will remember the most-used rhnConfigInfo.id, and repoint rhnConfigRevisions at it
        SELECT z.id as dup_cfginfo_id, z.symlink_target_filename_id, count(crev.id) as num_rhnConfigRevision_using
        from (
            -- Find the IDs of the dups
            SELECT ci.id, ci.symlink_target_filename_id
              from rhnConfigInfo ci
                   inner join (
			-- Find just the ones that are dups
			SELECT x.symlink_target_filename_id, x.num
			from (
			    -- Count where symlink_target_filename_id is not null and selinux_ctx is null
			    select symlink_target_filename_id, count(id) as num
			      from rhnConfigInfo
			     where username is null
                               and groupname is null
                               and filemode is null
                               and symlink_target_filename_id is not null
                               and selinux_ctx is null
			     group by symlink_target_filename_id
			     ) x
			where x.num > 1
		    ) y on y.symlink_target_filename_id = ci.symlink_target_filename_id
             where 1=1
               and ci.symlink_target_filename_id is not null and ci.selinux_ctx is null
             order by symlink_target_filename_id, id
        ) z
        left outer join rhnConfigRevision crev on crev.config_info_id = z.id
        group by z.id, z.symlink_target_filename_id
        order by z.symlink_target_filename_id, count(crev.id) desc, z.id
    loop
        -- First time in, or when we move to a new kind-of dup, remember that one
        if first_time or (d.symlink_target_filename_id <> good_symlink_target_filename_id)
        then
            raise info '...NEW GOOD rhnConfigInfo = %',d.dup_cfginfo_id;
            first_time := false;
            -- Remember the 'good values' so we can tell when we've moved to a new set in the dataresult
            good_cfginfo_id                 := d.dup_cfginfo_id;
            good_symlink_target_filename_id := d.symlink_target_filename_id;
        -- we have seen this one before - repoint users at 'good' and remove this one
        else
            if d.num_rhnconfigrevision_using > 0
            then
                raise info '...REPOINTING RECORDS, rhnConfigInfo = %',d.dup_cfginfo_id;
                UPDATE rhnConfigRevision
                   set config_info_id = good_cfginfo_id
                 where config_info_id = d.dup_cfginfo_id;
            end if;
            DELETE from rhnConfigInfo ci
             where 1=1
               and ci.symlink_target_filename_id = good_symlink_target_filename_id
               and ci.selinux_ctx                is null
               and ci.id = d.dup_cfginfo_id;
        end if;
    end loop;
    raise info 'EXITING fix_cfgrev_links_SELINUX_NULL';
end
$$
language plpgsql;

create or replace function
fix_cfgrev_files() returns void
as
$$
declare
 throwaway character varying(32);
 is_broken boolean := false;
begin
  select is_cfginfo_broken() into is_broken;
  if is_broken then
    select fix_cfgrev_files_SELINUX_NOT_NULL() into throwaway;
    select fix_cfgrev_files_SELINUX_NULL() into throwaway;
    select fix_cfgrev_links_SELINUX_NOT_NULL() into throwaway;
    select fix_cfgrev_links_SELINUX_NULL() into throwaway;
  end if;
end
$$
language plpgsql;

-- FOUR CASES:
-- u|g|f-not  link-null selinux-null
-- u|g|f-not  link-null selinux-not
-- u|g|f null link-not  selinux-not
-- u|g|f null link-not  selinux-null

-- Fix potential dups
select fix_cfgrev_files();

-- Drop no-longer-necessary functions
drop function if exists fix_cfgrev_files();
drop function if exists is_cfginfo_broken();
drop function if exists fix_cfgrev_files_SELINUX_NOT_NULL();
drop function if exists fix_cfgrev_files_SELINUX_NULL();
drop function if exists fix_cfgrev_links_SELINUX_NOT_NULL();
drop function if exists fix_cfgrev_links_SELINUX_NULL();

-- Make adding new indices idempotent
drop index if exists rhn_confinfo_ugf_uq;
drop index if exists rhn_confinfo_ugf_se_uq;
drop index if exists rhn_confinfo_s_uq;
drop index if exists rhn_confinfo_s_se_uq;

-- 
-- Create correct multiple indices to handle null-column cases
create unique index rhn_confinfo_ugf_uq
    on rhnConfigInfo (username, groupname, filemode)
where username is not null and groupname is not null and filemode is not null
  and selinux_ctx is null and symlink_target_filename_id is null;

create unique index rhn_confinfo_ugf_se_uq
    on rhnConfigInfo (username, groupname, filemode, selinux_ctx)
where username is not null and groupname is not null and filemode is not null
  and selinux_ctx is not null and symlink_target_filename_id is null;

create unique index rhn_confinfo_s_uq
    on rhnConfigInfo (symlink_target_filename_id)
where username is null and groupname is null and filemode is null
  and selinux_ctx is null and symlink_target_filename_id is not null;

create unique index rhn_confinfo_s_se_uq
    on rhnConfigInfo (symlink_target_filename_id, selinux_ctx)
where username is null and groupname is null and filemode is null
  and selinux_ctx is not null and symlink_target_filename_id is not null;
07070100000892000081B400000000000000000000000167AE111400000160000000000000000000000000000000000000006500000000susemanager-schema/upgrade/spacewalk-schema-2.6-to-spacewalk-schema-2.7/013-nonlinux-entitlement.sql  
select .clear_log_id();

delete from rhnServerGroupMembers where server_group_id in (select id from rhnServerGroup where name = 'Non-Linux Entitled Servers' and group_type is not null);

delete from rhnServerGroup where name = 'Non-Linux Entitled Servers' and group_type is not null;

delete from rhnServerGroupType where label = 'nonlinux_entitled';
07070100000893000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000004800000000susemanager-schema/upgrade/spacewalk-schema-2.7-to-spacewalk-schema-2.8   07070100000894000081B400000000000000000000000167AE111400000C50000000000000000000000000000000000000006E00000000susemanager-schema/upgrade/spacewalk-schema-2.7-to-spacewalk-schema-2.8/001-rhnpackageevr-rhn_pe_v_r_e_uq.sql 
create or replace function fix_rhn_pe_v_r_e_uq()
returns void as
$$
declare original record;
declare duplicate record;
declare nevra_orig record;
declare nevra_dup record;
begin
  for original in select min(id) as id
          from rhnpackageevr
      group by version, release, epoch
        having count(*) > 1 loop
    for duplicate in select evr2.id
             from rhnpackageevr evr1, rhnpackageevr evr2
            where evr1.version = evr2.version
              and evr1.release = evr2.release
              and (evr1.epoch = evr2.epoch
               or (evr1.epoch is NULL and evr2.epoch is NULL))
              and evr1.id != evr2.id
              and evr1.id = original.id loop
      update rhnactionpackage set evr_id = original.id where evr_id = duplicate.id;
      update rhnactionpackageremovalfailure set evr_id = original.id where evr_id = duplicate.id;
      update rhnchannelnewestpackage set evr_id = original.id where evr_id = duplicate.id;
      update rhnpackage set evr_id = original.id where evr_id = duplicate.id;
      select id into nevra_orig from rhnpackagenevra where evr_id = original.id;
      for nevra_dup in select id
                from rhnpackagenevra
               where evr_id = duplicate.id loop
        delete from rhnsnapshotpackage where nevra_id = nevra_dup.id and snapshot_id in (select snapshot_id from rhnsnapshotpackage where nevra_id = nevra_orig.id intersect select snapshot_id from rhnsnapshotpackage where nevra_id = nevra_dup.id);
        update rhnsnapshotpackage set nevra_id = nevra_orig.id where nevra_id = nevra_dup.id;
      end loop;
      delete from rhnpackagenevra where evr_id = duplicate.id;
      update rhnproxyinfo set proxy_evr_id = original.id where proxy_evr_id = duplicate.id;
      update rhnserveractionverifymissing set package_evr_id = original.id where package_evr_id = duplicate.id;
      update rhnserveractionverifyresult set package_evr_id = original.id where package_evr_id = duplicate.id;
      update rhnsatelliteinfo set evr_id = original.id where evr_id = duplicate.id;
      update rhnservercrash set package_evr_id = original.id where package_evr_id = duplicate.id;
      update rhnserverprofilepackage set evr_id = original.id where evr_id = duplicate.id;
      update rhntransactionpackage set evr_id = original.id where evr_id = duplicate.id;
      update rhnversioninfo set evr_id = original.id where evr_id = duplicate.id;
      update rhnserverpackage set evr_id = original.id where evr_id = duplicate.id;
      delete from rhnpackageevr where id = duplicate.id;
    end loop;
  end loop;
end;
$$ language plpgsql;

drop trigger rhn_pack_evr_no_updel_trig on rhnpackageevr;

select fix_rhn_pe_v_r_e_uq();

drop function fix_rhn_pe_v_r_e_uq();

create trigger
rhn_pack_evr_no_updel_trig
before update or delete on rhnpackageevr
execute procedure no_operation_trig_fun();

drop index if exists rhn_pe_v_r_e_uq;
drop index if exists rhn_pe_v_r_uq;

create unique index rhn_pe_v_r_e_uq
    on rhnpackageevr (version, release, epoch)
 where epoch is not null;

create unique index rhn_pe_v_r_uq
    on rhnpackageevr (version, release)
 where epoch is null;
07070100000895000081B400000000000000000000000167AE1114000003B0000000000000000000000000000000000000005D00000000susemanager-schema/upgrade/spacewalk-schema-2.7-to-spacewalk-schema-2.8/002-rhnCompsType.sql  --
-- Copyright (c) 2018 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

CREATE TABLE rhnCompsType
(
  id      NUMERIC NOT NULL
              CONSTRAINT rhn_comps_type_id_pk primary key,
  label   VARCHAR(32) NOT NULL
              CONSTRAINT rhn_comps_type_type_uq UNIQUE
);

INSERT INTO rhnCompsType (id, label) VALUES (1, 'comps');
INSERT INTO rhnCompsType (id, label) VALUES (2, 'modules');
07070100000896000081B400000000000000000000000167AE1114000001E1000000000000000000000000000000000000006000000000susemanager-schema/upgrade/spacewalk-schema-2.7-to-spacewalk-schema-2.8/003-rhnChannelComps.sql   
alter table rhnChannelComps add column comps_type_id numeric not null default 1 constraint rhn_channelcomps_comps_type_fk references rhnCompsType(id);

update rhnChannelComps set comps_type_id = (select id from rhnCompsType where label = 'comps');

alter table rhnChannelComps alter comps_type_id drop default;

alter table rhnChannelComps drop constraint rhn_channelcomps_cid_uq;

create unique index rhn_channelcomps_cid_ctype_uq on rhnChannelComps (channel_id, comps_type_id);
   07070100000897000081B400000000000000000000000167AE111400000440000000000000000000000000000000000000005A00000000susemanager-schema/upgrade/spacewalk-schema-2.7-to-spacewalk-schema-2.8/004-set_comps.sql 
drop function rhn_channel.set_comps(channel_id_in in numeric, path_in in varchar, timestamp_in in varchar);

create or replace function rhn_channel.set_comps(channel_id_in in numeric, path_in in varchar, comps_type_id_in in numeric, timestamp_in in varchar) returns void
as $$
declare
row record;
begin
  for row in (
    select relative_filename, last_modified
      from rhnChannelComps
      where channel_id = channel_id_in
      and comps_type_id = comps_type_id_in
      ) loop
      if row.relative_filename = path_in
        and row.last_modified = to_timestamp(timestamp_in, 'YYYYMMDDHH24MISS') then
        return;
      end if;
    end loop;
    delete from rhnChannelComps
    where channel_id = channel_id_in and comps_type_id = comps_type_id_in;
    insert into rhnChannelComps (id, channel_id, relative_filename, comps_type_id, last_modified, created, modified)
    values (sequence_nextval('rhn_channelcomps_id_seq'), channel_id_in, path_in, comps_type_id_in, to_timestamp(timestamp_in, 'YYYYMMDDHH24MISS'), current_timestamp, current_timestamp);
end$$ language plpgsql;
07070100000898000081B400000000000000000000000167AE111400000642000000000000000000000000000000000000006100000000susemanager-schema/upgrade/spacewalk-schema-2.7-to-spacewalk-schema-2.8/005-rhnChannelCloned.sql  --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--

drop trigger rhn_channel_cloned_comps_trig on rhnChannelCloned;

create or replace function rhn_channel_cloned_comps_trig_fun() returns trigger
as
$$
begin
	new.modified := current_timestamp;

	if tg_op = 'INSERT' then
		-- if there are not comps in the cloned channel by now,
		-- we shall clone comps from the original channel
		insert into rhnChannelComps
			( id, channel_id, comps_type_id, relative_filename,
				last_modified, created, modified )
		select nextval('rhn_channelcomps_id_seq'), new.id, comps_type_id, relative_filename,
				current_timestamp, current_timestamp, current_timestamp
		from rhnChannelComps
		where channel_id = new.original_id
			and not exists (
				select 1
				from rhnChannelComps x
				where x.channel_id = new.id
			);
	end if;
        return new;
end;
$$
language plpgsql;


create trigger
rhn_channel_cloned_comps_trig
before insert or update on rhnChannelCloned
for each row
execute procedure rhn_channel_cloned_comps_trig_fun();
  07070100000899000081B400000000000000000000000167AE11140000043F000000000000000000000000000000000000006700000000susemanager-schema/upgrade/spacewalk-schema-2.7-to-spacewalk-schema-2.8/006-add-latest-fedora-keys.sql    insert into rhnPackageKey (id, key_id, key_type_id, provider_id) select sequence_nextval('rhn_pkey_id_seq'), 'FDB19C98', lookup_package_key_type('gpg'), lookup_package_provider('Fedora') from dual where not exists (select 1 from rhnPackageKey where key_id = 'FDB19C98');

insert into rhnPackageKey (id, key_id, key_type_id, provider_id) select sequence_nextval('rhn_pkey_id_seq'), '64DAB85D', lookup_package_key_type('gpg'), lookup_package_provider('Fedora') from dual where not exists (select 1 from rhnPackageKey where key_id = '64DAB85D');

insert into rhnPackageKey (id, key_id, key_type_id, provider_id) select sequence_nextval('rhn_pkey_id_seq'), 'F5282EE4', lookup_package_key_type('gpg'), lookup_package_provider('Fedora') from dual where not exists (select 1 from rhnPackageKey where key_id = 'F5282EE4');

insert into rhnPackageKey (id, key_id, key_type_id, provider_id) select sequence_nextval('rhn_pkey_id_seq'), '9DB62FB1', lookup_package_key_type('gpg'), lookup_package_provider('Fedora') from dual where not exists (select 1 from rhnPackageKey where key_id = '9DB62FB1');
 0707010000089A000081B400000000000000000000000167AE11140000017F000000000000000000000000000000000000006D00000000susemanager-schema/upgrade/spacewalk-schema-2.7-to-spacewalk-schema-2.8/010-rhnerratatmp-add_severity_id.sql  -- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
-- $Id$
--

ALTER TABLE rhnErrataTmp
 ADD severity_id NUMERIC;

ALTER TABLE rhnErrataTmp
 ADD CONSTRAINT rhn_erratatmp_sevid_fk
 FOREIGN KEY (severity_id) REFERENCES rhnErrataSeverity(id);
 0707010000089B000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000004800000000susemanager-schema/upgrade/spacewalk-schema-2.8-to-spacewalk-schema-2.9   0707010000089C000081B400000000000000000000000167AE111400000115000000000000000000000000000000000000006100000000susemanager-schema/upgrade/spacewalk-schema-2.8-to-spacewalk-schema-2.9/003-rhnKSInstallType.sql  insert into rhnKSInstallType (id, label, name) (
        select sequence_nextval('rhn_ksinstalltype_id_seq'),
               'rhel_8','Red Hat Enterprise Linux 8'
          from dual
         where not exists (select 1 from rhnKSInstallType where  label = 'rhel_8')
        );
   0707010000089D000081B400000000000000000000000167AE11140001D64D000000000000000000000000000000000000006500000000susemanager-schema/upgrade/spacewalk-schema-2.8-to-spacewalk-schema-2.9/004-rhnKickstartTimezome.sql  insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Abidjan',
                'Africa/Abidjan',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Accra',
                'Africa/Accra',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Addis_Ababa',
                'Africa/Addis_Ababa',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Algiers',
                'Africa/Algiers',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Asmara',
                'Africa/Asmara',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Bamako',
                'Africa/Bamako',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Bangui',
                'Africa/Bangui',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Banjul',
                'Africa/Banjul',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Bissau',
                'Africa/Bissau',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Blantyre',
                'Africa/Blantyre',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Brazzaville',
                'Africa/Brazzaville',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Bujumbura',
                'Africa/Bujumbura',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Cairo',
                'Africa/Cairo',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Casablanca',
                'Africa/Casablanca',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Ceuta',
                'Africa/Ceuta',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Conakry',
                'Africa/Conakry',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Dakar',
                'Africa/Dakar',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Dar_es_Salaam',
                'Africa/Dar_es_Salaam',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Djibouti',
                'Africa/Djibouti',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Douala',
                'Africa/Douala',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/El_Aaiun',
                'Africa/El_Aaiun',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Freetown',
                'Africa/Freetown',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Gaborone',
                'Africa/Gaborone',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Harare',
                'Africa/Harare',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Johannesburg',
                'Africa/Johannesburg',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Juba',
                'Africa/Juba',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Kampala',
                'Africa/Kampala',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Khartoum',
                'Africa/Khartoum',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Kigali',
                'Africa/Kigali',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Kinshasa',
                'Africa/Kinshasa',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Lagos',
                'Africa/Lagos',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Libreville',
                'Africa/Libreville',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Lome',
                'Africa/Lome',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Luanda',
                'Africa/Luanda',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Lubumbashi',
                'Africa/Lubumbashi',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Lusaka',
                'Africa/Lusaka',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Malabo',
                'Africa/Malabo',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Maputo',
                'Africa/Maputo',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Maseru',
                'Africa/Maseru',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Mbabane',
                'Africa/Mbabane',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Mogadishu',
                'Africa/Mogadishu',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Monrovia',
                'Africa/Monrovia',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Nairobi',
                'Africa/Nairobi',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Ndjamena',
                'Africa/Ndjamena',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Niamey',
                'Africa/Niamey',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Nouakchott',
                'Africa/Nouakchott',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Ouagadougou',
                'Africa/Ouagadougou',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Porto-Novo',
                'Africa/Porto-Novo',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Sao_Tome',
                'Africa/Sao_Tome',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Tripoli',
                'Africa/Tripoli',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Tunis',
                'Africa/Tunis',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Windhoek',
                'Africa/Windhoek',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Adak',
                'America/Adak',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Anchorage',
                'America/Anchorage',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Anguilla',
                'America/Anguilla',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Antigua',
                'America/Antigua',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Araguaina',
                'America/Araguaina',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Argentina/Buenos_Aires',
                'America/Argentina/Buenos_Aires',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Argentina/Catamarca',
                'America/Argentina/Catamarca',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Argentina/Cordoba',
                'America/Argentina/Cordoba',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Argentina/Jujuy',
                'America/Argentina/Jujuy',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Argentina/La_Rioja',
                'America/Argentina/La_Rioja',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Argentina/Mendoza',
                'America/Argentina/Mendoza',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Argentina/Rio_Gallegos',
                'America/Argentina/Rio_Gallegos',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Argentina/Salta',
                'America/Argentina/Salta',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Argentina/San_Juan',
                'America/Argentina/San_Juan',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Argentina/San_Luis',
                'America/Argentina/San_Luis',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Argentina/Tucuman',
                'America/Argentina/Tucuman',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Argentina/Ushuaia',
                'America/Argentina/Ushuaia',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Aruba',
                'America/Aruba',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Asuncion',
                'America/Asuncion',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Atikokan',
                'America/Atikokan',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Bahia',
                'America/Bahia',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Bahia_Banderas',
                'America/Bahia_Banderas',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Barbados',
                'America/Barbados',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Belem',
                'America/Belem',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Belize',
                'America/Belize',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Blanc-Sablon',
                'America/Blanc-Sablon',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Boa_Vista',
                'America/Boa_Vista',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Bogota',
                'America/Bogota',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Boise',
                'America/Boise',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Cambridge_Bay',
                'America/Cambridge_Bay',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Campo_Grande',
                'America/Campo_Grande',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Cancun',
                'America/Cancun',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Caracas',
                'America/Caracas',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Cayenne',
                'America/Cayenne',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Cayman',
                'America/Cayman',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Chicago',
                'America/Chicago',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Chihuahua',
                'America/Chihuahua',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Costa_Rica',
                'America/Costa_Rica',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Creston',
                'America/Creston',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Cuiaba',
                'America/Cuiaba',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Curacao',
                'America/Curacao',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Danmarkshavn',
                'America/Danmarkshavn',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Dawson',
                'America/Dawson',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Dawson_Creek',
                'America/Dawson_Creek',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Denver',
                'America/Denver',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Detroit',
                'America/Detroit',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Dominica',
                'America/Dominica',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Edmonton',
                'America/Edmonton',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Eirunepe',
                'America/Eirunepe',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/El_Salvador',
                'America/El_Salvador',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Fortaleza',
                'America/Fortaleza',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Glace_Bay',
                'America/Glace_Bay',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Godthab',
                'America/Godthab',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Goose_Bay',
                'America/Goose_Bay',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Grand_Turk',
                'America/Grand_Turk',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Grenada',
                'America/Grenada',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Guadeloupe',
                'America/Guadeloupe',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Guatemala',
                'America/Guatemala',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Guayaquil',
                'America/Guayaquil',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Guyana',
                'America/Guyana',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Halifax',
                'America/Halifax',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Havana',
                'America/Havana',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Hermosillo',
                'America/Hermosillo',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Indiana/Indianapolis',
                'America/Indiana/Indianapolis',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Indiana/Knox',
                'America/Indiana/Knox',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Indiana/Marengo',
                'America/Indiana/Marengo',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Indiana/Petersburg',
                'America/Indiana/Petersburg',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Indiana/Tell_City',
                'America/Indiana/Tell_City',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Indiana/Vevay',
                'America/Indiana/Vevay',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Indiana/Vincennes',
                'America/Indiana/Vincennes',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Indiana/Winamac',
                'America/Indiana/Winamac',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Inuvik',
                'America/Inuvik',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Iqaluit',
                'America/Iqaluit',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Jamaica',
                'America/Jamaica',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Juneau',
                'America/Juneau',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Kentucky/Louisville',
                'America/Kentucky/Louisville',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Kentucky/Monticello',
                'America/Kentucky/Monticello',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Kralendijk',
                'America/Kralendijk',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/La_Paz',
                'America/La_Paz',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Lima',
                'America/Lima',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Los_Angeles',
                'America/Los_Angeles',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Lower_Princes',
                'America/Lower_Princes',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Maceio',
                'America/Maceio',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Managua',
                'America/Managua',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Manaus',
                'America/Manaus',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Marigot',
                'America/Marigot',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Martinique',
                'America/Martinique',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Matamoros',
                'America/Matamoros',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Mazatlan',
                'America/Mazatlan',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Menominee',
                'America/Menominee',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Merida',
                'America/Merida',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Metlakatla',
                'America/Metlakatla',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Mexico_City',
                'America/Mexico_City',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Miquelon',
                'America/Miquelon',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Moncton',
                'America/Moncton',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Monterrey',
                'America/Monterrey',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Montevideo',
                'America/Montevideo',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Montreal',
                'America/Montreal',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Montserrat',
                'America/Montserrat',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Nassau',
                'America/Nassau',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/New_York',
                'America/New_York',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Nipigon',
                'America/Nipigon',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Nome',
                'America/Nome',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Noronha',
                'America/Noronha',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/North_Dakota/Beulah',
                'America/North_Dakota/Beulah',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/North_Dakota/Center',
                'America/North_Dakota/Center',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/North_Dakota/New_Salem',
                'America/North_Dakota/New_Salem',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Ojinaga',
                'America/Ojinaga',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Panama',
                'America/Panama',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Pangnirtung',
                'America/Pangnirtung',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Paramaribo',
                'America/Paramaribo',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Phoenix',
                'America/Phoenix',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Port_of_Spain',
                'America/Port_of_Spain',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Port-au-Prince',
                'America/Port-au-Prince',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Porto_Velho',
                'America/Porto_Velho',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Puerto_Rico',
                'America/Puerto_Rico',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Rainy_River',
                'America/Rainy_River',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Rankin_Inlet',
                'America/Rankin_Inlet',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Recife',
                'America/Recife',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Regina',
                'America/Regina',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Resolute',
                'America/Resolute',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Rio_Branco',
                'America/Rio_Branco',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Santa_Isabel',
                'America/Santa_Isabel',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Santarem',
                'America/Santarem',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Santiago',
                'America/Santiago',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Santo_Domingo',
                'America/Santo_Domingo',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Sao_Paulo',
                'America/Sao_Paulo',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Scoresbysund',
                'America/Scoresbysund',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Shiprock',
                'America/Shiprock',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Sitka',
                'America/Sitka',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/St_Barthelemy',
                'America/St_Barthelemy',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/St_Johns',
                'America/St_Johns',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/St_Kitts',
                'America/St_Kitts',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/St_Lucia',
                'America/St_Lucia',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/St_Thomas',
                'America/St_Thomas',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/St_Vincent',
                'America/St_Vincent',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Swift_Current',
                'America/Swift_Current',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Tegucigalpa',
                'America/Tegucigalpa',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Thule',
                'America/Thule',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Thunder_Bay',
                'America/Thunder_Bay',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Tijuana',
                'America/Tijuana',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Toronto',
                'America/Toronto',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Tortola',
                'America/Tortola',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Vancouver',
                'America/Vancouver',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Whitehorse',
                'America/Whitehorse',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Winnipeg',
                'America/Winnipeg',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Yakutat',
                'America/Yakutat',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Yellowknife',
                'America/Yellowknife',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Antarctica/Casey',
                'Antarctica/Casey',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Antarctica/Davis',
                'Antarctica/Davis',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Antarctica/DumontDUrville',
                'Antarctica/DumontDUrville',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Antarctica/Macquarie',
                'Antarctica/Macquarie',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Antarctica/Mawson',
                'Antarctica/Mawson',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Antarctica/McMurdo',
                'Antarctica/McMurdo',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Antarctica/Palmer',
                'Antarctica/Palmer',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Antarctica/Rothera',
                'Antarctica/Rothera',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Antarctica/South_Pole',
                'Antarctica/South_Pole',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Antarctica/Syowa',
                'Antarctica/Syowa',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Antarctica/Vostok',
                'Antarctica/Vostok',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Arctic/Longyearbyen',
                'Arctic/Longyearbyen',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Aden',
                'Asia/Aden',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Almaty',
                'Asia/Almaty',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Amman',
                'Asia/Amman',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Anadyr',
                'Asia/Anadyr',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Aqtau',
                'Asia/Aqtau',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Aqtobe',
                'Asia/Aqtobe',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Ashgabat',
                'Asia/Ashgabat',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Baghdad',
                'Asia/Baghdad',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Bahrain',
                'Asia/Bahrain',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Baku',
                'Asia/Baku',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Bangkok',
                'Asia/Bangkok',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Beirut',
                'Asia/Beirut',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Bishkek',
                'Asia/Bishkek',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Brunei',
                'Asia/Brunei',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Choibalsan',
                'Asia/Choibalsan',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Chongqing',
                'Asia/Chongqing',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Colombo',
                'Asia/Colombo',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Damascus',
                'Asia/Damascus',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Dhaka',
                'Asia/Dhaka',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Dili',
                'Asia/Dili',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Dubai',
                'Asia/Dubai',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Dushanbe',
                'Asia/Dushanbe',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Gaza',
                'Asia/Gaza',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Harbin',
                'Asia/Harbin',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Hebron',
                'Asia/Hebron',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Ho_Chi_Minh',
                'Asia/Ho_Chi_Minh',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Hong_Kong',
                'Asia/Hong_Kong',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Hovd',
                'Asia/Hovd',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Irkutsk',
                'Asia/Irkutsk',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Jakarta',
                'Asia/Jakarta',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Jayapura',
                'Asia/Jayapura',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Jerusalem',
                'Asia/Jerusalem',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Kabul',
                'Asia/Kabul',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Kamchatka',
                'Asia/Kamchatka',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Karachi',
                'Asia/Karachi',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Kashgar',
                'Asia/Kashgar',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Kathmandu',
                'Asia/Kathmandu',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Kolkata',
                'Asia/Kolkata',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Krasnoyarsk',
                'Asia/Krasnoyarsk',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Kuala_Lumpur',
                'Asia/Kuala_Lumpur',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Kuching',
                'Asia/Kuching',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Kuwait',
                'Asia/Kuwait',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Macau',
                'Asia/Macau',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Magadan',
                'Asia/Magadan',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Makassar',
                'Asia/Makassar',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Manila',
                'Asia/Manila',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Muscat',
                'Asia/Muscat',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Nicosia',
                'Asia/Nicosia',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Novokuznetsk',
                'Asia/Novokuznetsk',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Novosibirsk',
                'Asia/Novosibirsk',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Omsk',
                'Asia/Omsk',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Oral',
                'Asia/Oral',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Phnom_Penh',
                'Asia/Phnom_Penh',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Pontianak',
                'Asia/Pontianak',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Pyongyang',
                'Asia/Pyongyang',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Qatar',
                'Asia/Qatar',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Qyzylorda',
                'Asia/Qyzylorda',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Rangoon',
                'Asia/Rangoon',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Riyadh',
                'Asia/Riyadh',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Sakhalin',
                'Asia/Sakhalin',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Samarkand',
                'Asia/Samarkand',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Seoul',
                'Asia/Seoul',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Shanghai',
                'Asia/Shanghai',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Singapore',
                'Asia/Singapore',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Taipei',
                'Asia/Taipei',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Tashkent',
                'Asia/Tashkent',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Tbilisi',
                'Asia/Tbilisi',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Tehran',
                'Asia/Tehran',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Thimphu',
                'Asia/Thimphu',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Tokyo',
                'Asia/Tokyo',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Ulaanbaatar',
                'Asia/Ulaanbaatar',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Urumqi',
                'Asia/Urumqi',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Vientiane',
                'Asia/Vientiane',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Vladivostok',
                'Asia/Vladivostok',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Yakutsk',
                'Asia/Yakutsk',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Yekaterinburg',
                'Asia/Yekaterinburg',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Yerevan',
                'Asia/Yerevan',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Atlantic/Azores',
                'Atlantic/Azores',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Atlantic/Bermuda',
                'Atlantic/Bermuda',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Atlantic/Canary',
                'Atlantic/Canary',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Atlantic/Cape_Verde',
                'Atlantic/Cape_Verde',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Atlantic/Faroe',
                'Atlantic/Faroe',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Atlantic/Madeira',
                'Atlantic/Madeira',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Atlantic/Reykjavik',
                'Atlantic/Reykjavik',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Atlantic/South_Georgia',
                'Atlantic/South_Georgia',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Atlantic/St_Helena',
                'Atlantic/St_Helena',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Atlantic/Stanley',
                'Atlantic/Stanley',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Australia/Adelaide',
                'Australia/Adelaide',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Australia/Brisbane',
                'Australia/Brisbane',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Australia/Broken_Hill',
                'Australia/Broken_Hill',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Australia/Currie',
                'Australia/Currie',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Australia/Darwin',
                'Australia/Darwin',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Australia/Eucla',
                'Australia/Eucla',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Australia/Hobart',
                'Australia/Hobart',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Australia/Lindeman',
                'Australia/Lindeman',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Australia/Lord_Howe',
                'Australia/Lord_Howe',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Australia/Melbourne',
                'Australia/Melbourne',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Australia/Perth',
                'Australia/Perth',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Australia/Sydney',
                'Australia/Sydney',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Amsterdam',
                'Europe/Amsterdam',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Andorra',
                'Europe/Andorra',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Athens',
                'Europe/Athens',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Belgrade',
                'Europe/Belgrade',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Berlin',
                'Europe/Berlin',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Bratislava',
                'Europe/Bratislava',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Brussels',
                'Europe/Brussels',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Bucharest',
                'Europe/Bucharest',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Budapest',
                'Europe/Budapest',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Chisinau',
                'Europe/Chisinau',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Copenhagen',
                'Europe/Copenhagen',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Dublin',
                'Europe/Dublin',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Gibraltar',
                'Europe/Gibraltar',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Guernsey',
                'Europe/Guernsey',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Helsinki',
                'Europe/Helsinki',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Isle_of_Man',
                'Europe/Isle_of_Man',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Istanbul',
                'Europe/Istanbul',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Jersey',
                'Europe/Jersey',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Kaliningrad',
                'Europe/Kaliningrad',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Kiev',
                'Europe/Kiev',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Lisbon',
                'Europe/Lisbon',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Ljubljana',
                'Europe/Ljubljana',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/London',
                'Europe/London',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Luxembourg',
                'Europe/Luxembourg',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Madrid',
                'Europe/Madrid',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Malta',
                'Europe/Malta',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Mariehamn',
                'Europe/Mariehamn',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Minsk',
                'Europe/Minsk',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Monaco',
                'Europe/Monaco',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Moscow',
                'Europe/Moscow',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Oslo',
                'Europe/Oslo',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Paris',
                'Europe/Paris',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Podgorica',
                'Europe/Podgorica',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Prague',
                'Europe/Prague',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Riga',
                'Europe/Riga',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Rome',
                'Europe/Rome',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Samara',
                'Europe/Samara',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/San_Marino',
                'Europe/San_Marino',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Sarajevo',
                'Europe/Sarajevo',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Simferopol',
                'Europe/Simferopol',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Skopje',
                'Europe/Skopje',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Sofia',
                'Europe/Sofia',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Stockholm',
                'Europe/Stockholm',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Tallinn',
                'Europe/Tallinn',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Tirane',
                'Europe/Tirane',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Uzhgorod',
                'Europe/Uzhgorod',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Vaduz',
                'Europe/Vaduz',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Vatican',
                'Europe/Vatican',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Vienna',
                'Europe/Vienna',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Vilnius',
                'Europe/Vilnius',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Volgograd',
                'Europe/Volgograd',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Warsaw',
                'Europe/Warsaw',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Zagreb',
                'Europe/Zagreb',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Zaporozhye',
                'Europe/Zaporozhye',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Zurich',
                'Europe/Zurich',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Indian/Antananarivo',
                'Indian/Antananarivo',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Indian/Chagos',
                'Indian/Chagos',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Indian/Christmas',
                'Indian/Christmas',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Indian/Cocos',
                'Indian/Cocos',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Indian/Comoro',
                'Indian/Comoro',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Indian/Kerguelen',
                'Indian/Kerguelen',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Indian/Mahe',
                'Indian/Mahe',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Indian/Maldives',
                'Indian/Maldives',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Indian/Mauritius',
                'Indian/Mauritius',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Indian/Mayotte',
                'Indian/Mayotte',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Indian/Reunion',
                'Indian/Reunion',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Apia',
                'Pacific/Apia',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Auckland',
                'Pacific/Auckland',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Chatham',
                'Pacific/Chatham',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Chuuk',
                'Pacific/Chuuk',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Easter',
                'Pacific/Easter',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Efate',
                'Pacific/Efate',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Enderbury',
                'Pacific/Enderbury',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Fakaofo',
                'Pacific/Fakaofo',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Fiji',
                'Pacific/Fiji',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Funafuti',
                'Pacific/Funafuti',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Galapagos',
                'Pacific/Galapagos',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Gambier',
                'Pacific/Gambier',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Guadalcanal',
                'Pacific/Guadalcanal',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Guam',
                'Pacific/Guam',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Honolulu',
                'Pacific/Honolulu',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Johnston',
                'Pacific/Johnston',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Kiritimati',
                'Pacific/Kiritimati',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Kosrae',
                'Pacific/Kosrae',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Kwajalein',
                'Pacific/Kwajalein',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Majuro',
                'Pacific/Majuro',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Marquesas',
                'Pacific/Marquesas',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Midway',
                'Pacific/Midway',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Nauru',
                'Pacific/Nauru',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Niue',
                'Pacific/Niue',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Norfolk',
                'Pacific/Norfolk',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Noumea',
                'Pacific/Noumea',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Pago_Pago',
                'Pacific/Pago_Pago',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Palau',
                'Pacific/Palau',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Pitcairn',
                'Pacific/Pitcairn',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Pohnpei',
                'Pacific/Pohnpei',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Port_Moresby',
                'Pacific/Port_Moresby',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Rarotonga',
                'Pacific/Rarotonga',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Saipan',
                'Pacific/Saipan',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Tahiti',
                'Pacific/Tahiti',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Tarawa',
                'Pacific/Tarawa',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Tongatapu',
                'Pacific/Tongatapu',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Wake',
                'Pacific/Wake',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Wallis',
                'Pacific/Wallis',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        );

   0707010000089E000081B400000000000000000000000167AE1114000000BF000000000000000000000000000000000000005C00000000susemanager-schema/upgrade/spacewalk-schema-2.8-to-spacewalk-schema-2.9/005-fedora-keys.sql   insert into rhnPackageKey (id, key_id, key_type_id, provider_id) values
(sequence_nextval('rhn_pkey_id_seq'), '429476B4', lookup_package_key_type('gpg'), lookup_package_provider('Fedora'));

 0707010000089F000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000004900000000susemanager-schema/upgrade/spacewalk-schema-2.9-to-spacewalk-schema-2.10  070701000008A0000081B400000000000000000000000167AE111400000046000000000000000000000000000000000000006500000000susemanager-schema/upgrade/spacewalk-schema-2.9-to-spacewalk-schema-2.10/001-rhnXccdfIdent-ident.sql  
alter table rhnXccdfIdent alter column identifier type varchar(255);
  070701000008A1000081B400000000000000000000000167AE11140000067F000000000000000000000000000000000000006D00000000susemanager-schema/upgrade/spacewalk-schema-2.9-to-spacewalk-schema-2.10/002-rhnXccdfIdent-ident-upgrade.sql  -- select data about tests with truncated identifiers into temp table
create table tmp_oscap_upgrade as
        select row_number() over (partition by testresult_id order by rr.id) as rn,
               rr.id, rr.testresult_id, rr.result_id,
               xi.id as ident_id,
               0 as new_ident_id
          from rhnXccdfRuleresult rr
          join rhnXccdfRuleIdentmap rim
            on rim.rresult_id=rr.id
          join rhnxccdfident xi
            on xi.id = rim.ident_id
         where xi.identifier like '%...';

-- create new ids to truncated identifiers
create table tmp_oscap_upgrade_ids as
        select rn, ident_id, sequence_nextval('rhn_xccdf_ident_id_seq') as new_id
          from (select distinct rn, ident_id from tmp_oscap_upgrade) X;

-- assign new ids to selected identifiers
update tmp_oscap_upgrade u set new_ident_id = (select new_id from tmp_oscap_upgrade_ids i 
                                                where i.rn = u.rn and i.ident_id = u.ident_id);

-- create new (separated) test identifiers
insert into rhnxccdfident (id, identsystem_id, identifier)
        select distinct u.new_ident_id, o.identsystem_id, o.identifier || u.rn
          from tmp_oscap_upgrade u
          join rhnxccdfident o on u.ident_id = o.id
         where o.identifier like '%...';

-- create new rule maps
insert into rhnXccdfRuleIdentmap (rresult_id, ident_id)
        select id, new_ident_id from tmp_oscap_upgrade;

-- delete old rule maps
delete from rhnXccdfRuleIdentmap where ident_id in
        (select ident_id from tmp_oscap_upgrade);

-- remove temporary tables
drop table tmp_oscap_upgrade_ids;
drop table tmp_oscap_upgrade;
 070701000008A2000081B400000000000000000000000167AE1114000000D4000000000000000000000000000000000000007100000000susemanager-schema/upgrade/spacewalk-schema-2.9-to-spacewalk-schema-2.10/003-rhnContentSource-rhn_cs_repo_uq.sql  
DROP INDEX rhn_cs_repo_uq;

CREATE UNIQUE INDEX rhn_cs_repo_uq
    ON rhnContentSource(org_id, type_id, source_url, 
                            (case when label like 'manifest_%' then 1 else 0 end))
        ;

070701000008A3000081B400000000000000000000000167AE111400001E75000000000000000000000000000000000000005900000000susemanager-schema/upgrade/spacewalk-schema-2.9-to-spacewalk-schema-2.10/004-rpm.pkb.sql  -- create schema rpm;

--update pg_setting
update pg_settings set setting = 'rpm,' || setting where name = 'search_path';

create or replace function isdigit(ch CHAR)
    RETURNS BOOLEAN as $$
    BEGIN
        if ascii(ch) between ascii('0') and ascii('9')
        then
            return TRUE;
        end if;
        return FALSE;
    END ;
$$ language 'plpgsql';

    
    create or replace FUNCTION isalpha(ch CHAR)
    RETURNS BOOLEAN as $$
    BEGIN
        if ascii(ch) between ascii('a') and ascii('z') or 
            ascii(ch) between ascii('A') and ascii('Z')
        then
            return TRUE;
        end if;
        return FALSE;
    END;
$$ language 'plpgsql';


    create or replace FUNCTION isalphanum(ch CHAR)
    RETURNS BOOLEAN as $$ 
    BEGIN
        if ascii(ch) between ascii('a') and ascii('z') or 
            ascii(ch) between ascii('A') and ascii('Z') or
            ascii(ch) between ascii('0') and ascii('9')
        then
            return TRUE;
        end if;
        return FALSE;
    END;
    $$ language 'plpgsql';


    create or replace FUNCTION rpmstrcmp (string1 IN VARCHAR, string2 IN VARCHAR)
    RETURNS INTEGER as $$
    declare
        str1 VARCHAR := string1;
        str2 VARCHAR := string2;
        digits VARCHAR(10) := '0123456789';
        lc_alpha VARCHAR(27) := 'abcdefghijklmnopqrstuvwxyz';
        uc_alpha VARCHAR(27) := 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
        alpha VARCHAR(54) := lc_alpha || uc_alpha;
        one VARCHAR;
        two VARCHAR;
        isnum BOOLEAN;
    BEGIN
        if str1 is NULL or str2 is NULL
        then
            RAISE EXCEPTION 'VALUE_ERROR.';
        end if;
      
        if str1 = str2
        then
            return 0;
        end if;
        one := str1;
        two := str2;

        <<segment_loop>>
        while one <> '' or two <> ''
        loop
            declare
                segm1 VARCHAR;
                segm2 VARCHAR;
                onechar CHAR(1);
                twochar CHAR(1);
            begin
                --raise notice 'Params: %, %',  one, two;
                -- Throw out all non-alphanum characters
                onechar := substr(one, 1, 1);
                twochar := substr(two, 1, 1);
                while one <> '' and not rpm.isalphanum(one) and onechar != '~' and onechar != '^'
                loop
                    one := substr(one, 2);
                end loop;
                while two <> '' and not rpm.isalphanum(two) and twochar != '~' and twochar != '^'
                loop
                    two := substr(two, 2);
                end loop;
                --raise notice 'new params: %, %', one, two;

                onechar := substr(one, 1, 1);
                twochar := substr(two, 1, 1);
                --raise notice 'new chars 1: %, %', onechar, twochar;
                /* handle the tilde separator, it sorts before everything else */
                if (onechar = '~' or twochar = '~')
                then
                    if (onechar != '~') then return 1; end if;
                    if (twochar != '~') then return -1; end if;
                    --raise notice 'passed tilde chars: %, %', onechar, twochar;
                    one := substr(one, 2);
                    two := substr(two, 2);
                    continue;
                end if;

                /*
                 * Handle caret separator. Concept is the same as tilde,
                 * except that if one of the strings ends (base version),
                 * the other is considered as higher version.
                 */
                onechar := substr(one, 1, 1);
                twochar := substr(two, 1, 1);
                --raise notice 'new chars 2: %, %', onechar, twochar;
                if (onechar = '^' or twochar = '^')
                then
                    if (one = '') then return -1; end if;
                    --raise notice 'passed caret chars 1: %, %', onechar, twochar;
                    if (two = '') then return 1; end if;
                    --raise notice 'passed caret chars 2: %, %', onechar, twochar;
                    if (onechar != '^') then return 1; end if;
                    --raise notice 'passed caret chars 3: %, %', onechar, twochar;
                    if (twochar != '^') then return -1; end if;
                    --raise notice 'passed caret chars 4: %, %', onechar, twochar;
                    one := substr(one, 2);
                    two := substr(two, 2);
                    continue;
                end if;

                if (not (one <> '' and two <> '')) then exit segment_loop; end if;

                str1 := one;
                str2 := two;
                if str1 <> '' and rpm.isdigit(str1)
                then
                    str1 := ltrim(str1, digits);
                    str2 := ltrim(str2, digits);
                    isnum := true;
                else
                    str1 := ltrim(str1, alpha);
                    str2 := ltrim(str2, alpha);
                    isnum := false;
                end if;
                if str1 <> ''
                then segm1 := substr(one, 1, length(one) - length(str1));
                else segm1 := one;
                end if;
                    
                if str2 <> ''
                then segm2 := substr(two, 1, length(two) - length(str2));
                else segm2 := two;
                end if;
                if segm1 = '' then return -1; end if; /* arbitrary */
                if segm2 = '' then
                                        if isnum then
                                                return 1;
                                        else
                                                return -1;
                                        end if;
                                end if;
                if isnum
                then
                   
                    segm1 := ltrim(segm1, '0');
                    segm2 := ltrim(segm2, '0');

                    if segm1 = '' and segm2 <> ''
                    then
                        return -1;
                    end if;
                    if segm1 <> '' and segm2 = ''
                    then
                        return 1;
                    end if;
                    if length(segm1) > length(segm2) then return 1; end if;
                    if length(segm2) > length(segm1) then return -1; end if;
                end if;
                  if segm1 < segm2 then return -1; end if;
                if segm1 > segm2 then return 1; end if;
               one := str1;
                two := str2;
            end;
        end loop segment_loop;
     
        if one = '' and two = '' then return 0; end if;
        if one = '' then return -1; end if;
        return 1;
    END ;
$$ language 'plpgsql';



   create or replace FUNCTION vercmp(
        e1 VARCHAR, v1 VARCHAR, r1 VARCHAR, 
        e2 VARCHAR, v2 VARCHAR, r2 VARCHAR)
    RETURNS INTEGER as $$
    declare
        rc INTEGER;
          ep1 INTEGER;
          ep2 INTEGER;
          BEGIN
            if e1 is null or e1 = '' then
              ep1 := 0;
            else
              ep1 := e1::integer;
            end if;
            if e2 is null or e2 = '' then
              ep2 := 0;
            else
              ep2 := e2::integer;
            end if;
            -- Epochs are non-null; compare them
            if ep1 < ep2 then return -1; end if;
            if ep1 > ep2 then return 1; end if;
            rc := rpm.rpmstrcmp(v1, v2);
            if rc != 0 then return rc; end if;
           return rpm.rpmstrcmp(r1, r2);
         END;
         $$ language 'plpgsql';

-- restore the original setting
update pg_settings set setting = overlay( setting placing '' from 1 for (length('rpm')+1) ) where name = 'search_path';

   070701000008A4000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005200000000susemanager-schema/upgrade/susemanager-schema-1.2.69-to-susemanager-schema-1.2.70 070701000008A5000081B400000000000000000000000167AE111400000308000000000000000000000000000000000000006C00000000susemanager-schema/upgrade/susemanager-schema-1.2.69-to-susemanager-schema-1.2.70/001-suseOSTarget-Data.sql   --
-- Copyright (c) 2011 Novell
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
--

insert into suseOSTarget (id, os, target, channel_arch_id) values
(sequence_nextval('suse_ostarget_id_seq'), 'i386', 'i386', LOOKUP_CHANNEL_ARCH('channel-ia32'));

insert into suseOSTarget (id, os, target, channel_arch_id) values
(sequence_nextval('suse_ostarget_id_seq'), 'x86_64', 'x86_64', LOOKUP_CHANNEL_ARCH('channel-x86_64'));

commit;


070701000008A6000081B400000000000000000000000167AE111400000263000000000000000000000000000000000000006A00000000susemanager-schema/upgrade/susemanager-schema-1.2.69-to-susemanager-schema-1.2.70/002-rhnFeature-Data.sql --
-- Copyright (c) 2011 Novell
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
--

update rhnFeature set name = 'SUSE Manager Capable' where label = 'ftr_sat_capable' ;
update rhnFeature set name = 'SUSE Manager Applet'  where label = 'ftr_satellite_applet' ;


 070701000008A7000081B400000000000000000000000167AE111400000239000000000000000000000000000000000000006D00000000susemanager-schema/upgrade/susemanager-schema-1.2.69-to-susemanager-schema-1.2.70/003-rhnTaskoBunch-Data.sql  --
-- Copyright (c) 2011 Novell
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
--

update rhnTaskoBunch set description = 'Checks whether SUSE Manager certificate has not expired' where name = 'satcert-check-bunch' ;



   070701000008A8000081B400000000000000000000000167AE111400000273000000000000000000000000000000000000007A00000000susemanager-schema/upgrade/susemanager-schema-1.2.69-to-susemanager-schema-1.2.70/004-rhn_command_queue_commands-Data.sql --
-- Copyright (c) 2011 Novell
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
--

update rhn_command_queue_commands set description = 'SUSE Manager configuration installation', notes = '"Install Changes" on a SUSE Manager (i.e. push the monitoring config)' where recid = 1 ;


 070701000008A9000081B400000000000000000000000167AE11140000035C000000000000000000000000000000000000007000000000susemanager-schema/upgrade/susemanager-schema-1.2.69-to-susemanager-schema-1.2.70/005-rhn_config_group-Data.sql   --
-- Copyright (c) 2011 Novell
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
--

update rhn_config_group set description = 'SUSE Manager time synchronization' where name = 'timesync' ;
update rhn_config_group set description = 'General satellite configuration' where name = 'satellite' ;
update rhn_config_group set description = 'SUSE Manager dequeuer configuration' where name = 'queues' ;
update rhn_config_group set description = 'SUSE Manager configurator configuration' where name = 'ConfigPusher' ;



070701000008AA000081B400000000000000000000000167AE111400000282000000000000000000000000000000000000007000000000susemanager-schema/upgrade/susemanager-schema-1.2.69-to-susemanager-schema-1.2.70/006-rhn_config_macro-Data.sql   --
-- Copyright (c) 2011 Novell
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
--

update rhn_config_macro set description = 'SUSE Manager configuration host' where name = 'SATCFGHOST' ;
update rhn_config_macro set description = 'SUSE Manager configurator URL'   where name = 'SATCFGURL' ;



  070701000008AB000081B400000000000000000000000167AE11140000021C000000000000000000000000000000000000007400000000susemanager-schema/upgrade/susemanager-schema-1.2.69-to-susemanager-schema-1.2.70/007-rhn_config_parameter-Data.sql   --
-- Copyright (c) 2011 Novell
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
--

update rhn_config_parameter set value = 'Monitoring SUSE Manager Notification' where name = 'fromname' ;



070701000008AC000081B400000000000000000000000167AE111400000528000000000000000000000000000000000000007800000000susemanager-schema/upgrade/susemanager-schema-1.2.69-to-susemanager-schema-1.2.70/008-rhn_notification_formats-Data.sql   --
-- Copyright (c) 2011 Novell
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
--

update rhn_notification_formats set body_format = 'This is a Monitoring event notification.\n\nTime:      ^[timestamp:"%a %b %d, %H:%M:%S %Z"]\nState:     ^[probe state]\nHost:      ^[hostname] (^[host IP])\nCheck:     ^[probe description]\nMessage:   ^[probe output]\nRun from:  ^[satellite description]\n\nTo acknowledge, reply to this message with this subject line:\n     ACK ^[alert id]\n\nTo immediately escalate, reply to this message with this subject line:\n     NACK ^[alert id]' where description = 'New Default (2.15)' ;

update rhn_notification_formats set body_format = 'This is Monitoring notification ^[alert id].\n\nTime:      ^[timestamp:"%a %b %d, %H:%M:%S %Z"]\nState:     ^[probe state]\nHost:      ^[hostname] (^[host IP])\nCheck:     ^[probe description]\nMessage:   ^[probe output]\nRun from:  ^[satellite description]' where description = 'New Default (2.18)' ;

070701000008AD000081B400000000000000000000000167AE11140000026B000000000000000000000000000000000000006F00000000susemanager-schema/upgrade/susemanager-schema-1.2.69-to-susemanager-schema-1.2.70/009-rhn_probe_types-Data.sql    --
-- Copyright (c) 2011 Novell
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
--

update rhn_probe_types set type_description = 'Node Probe' where probe_type = 'satnode' ;
update rhn_probe_types set type_description = 'Cluster Probe' where probe_type = 'satcluster' ;

 070701000008AE000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005200000000susemanager-schema/upgrade/susemanager-schema-1.2.70-to-susemanager-schema-1.2.71 070701000008AF000081B400000000000000000000000167AE111400000208000000000000000000000000000000000000006700000000susemanager-schema/upgrade/susemanager-schema-1.2.70-to-susemanager-schema-1.2.71/010-errata-patch.sql    --
-- Copyright (c) 2011 Novell
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
--

update rhnactiontype set name = 'Patch Update' where label = 'errata.update';

commit;

070701000008B0000081B400000000000000000000000167AE111400000384000000000000000000000000000000000000006400000000susemanager-schema/upgrade/susemanager-schema-1.2.70-to-susemanager-schema-1.2.71/011-kickstart.sql   --
-- Copyright (c) 2011 Novell
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
--

update rhnactiontype set name = 'Initiate an auto installation' where label = 'kickstart.initiate';
update rhnactiontype set name = 'Schedule a package sync for auto installations' where label = 'kickstart.schedule_sync';
update rhnactiontype set name = 'SUSE Manager Network Daemon Configuration' where label = 'rhnsd.configure';
update rhnactiontype set name = 'Initiate an auto installation for a virtual guest.' where label = 'kickstart_guest.initiate';

commit;

070701000008B1000081B400000000000000000000000167AE11140000041F000000000000000000000000000000000000006C00000000susemanager-schema/upgrade/susemanager-schema-1.2.70-to-susemanager-schema-1.2.71/999-suseOSTarget-Data.sql   --
-- Copyright (c) 2011 Novell
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
--
declare
  c_i386 number := 0;
  c_x86_64 number := 0;
begin
select count(*) into c_i386 from suseOSTarget where target = 'i386';
select count(*) into c_x86_64 from suseOSTarget where target = 'x86_64';

if c_i386 = 0 then
  insert into suseOSTarget (id, os, target, channel_arch_id) values (sequence_nextval('suse_ostarget_id_seq'), 'i386', 'i386', LOOKUP_CHANNEL_ARCH('channel-ia32'));
  commit;
end if;
if c_x86_64 = 0 then
  insert into suseOSTarget (id, os, target, channel_arch_id) values (sequence_nextval('suse_ostarget_id_seq'), 'x86_64', 'x86_64', LOOKUP_CHANNEL_ARCH('channel-x86_64'));
  commit;
end if;

end;
/

 070701000008B2000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005200000000susemanager-schema/upgrade/susemanager-schema-1.2.71-to-susemanager-schema-1.2.72 070701000008B3000081B400000000000000000000000167AE11140000078C000000000000000000000000000000000000006C00000000susemanager-schema/upgrade/susemanager-schema-1.2.71-to-susemanager-schema-1.2.72/001-suseOSTarget-Data.sql   --
-- Copyright (c) 2011 SUSE Linux Products GmbH, Nuremberg, Germany
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
--

insert into suseOSTarget (id, os, target, channel_arch_id) values
(sequence_nextval('suse_ostarget_id_seq'), 'sled-10-i586', 'sled-10-i586', LOOKUP_CHANNEL_ARCH('channel-ia32'));

insert into suseOSTarget (id, os, target, channel_arch_id) values
(sequence_nextval('suse_ostarget_id_seq'), 'sled-10-x86_64', 'sled-10-x86_64', LOOKUP_CHANNEL_ARCH('channel-x86_64'));

insert into suseOSTarget (id, os, target, channel_arch_id) values
(sequence_nextval('suse_ostarget_id_seq'), 'sles-10-i586', 'sles-10-i586', LOOKUP_CHANNEL_ARCH('channel-ia32'));

insert into suseOSTarget (id, os, target, channel_arch_id) values
(sequence_nextval('suse_ostarget_id_seq'), 'sles-10-ia64', 'sles-10-ia64', LOOKUP_CHANNEL_ARCH('channel-ia64'));

insert into suseOSTarget (id, os, target, channel_arch_id) values
(sequence_nextval('suse_ostarget_id_seq'), 'sles-10-ppc', 'sles-10-ppc', LOOKUP_CHANNEL_ARCH('channel-ppc'));

insert into suseOSTarget (id, os, target, channel_arch_id) values
(sequence_nextval('suse_ostarget_id_seq'), 'sles-10-s390x', 'sles-10-s390x', LOOKUP_CHANNEL_ARCH('channel-s390x'));

insert into suseOSTarget (id, os, target, channel_arch_id) values
(sequence_nextval('suse_ostarget_id_seq'), 'sles-10-s390', 'sles-10-s390', LOOKUP_CHANNEL_ARCH('channel-s390'));

insert into suseOSTarget (id, os, target, channel_arch_id) values
(sequence_nextval('suse_ostarget_id_seq'), 'sles-10-x86_64', 'sles-10-x86_64', LOOKUP_CHANNEL_ARCH('channel-x86_64'));

commit;


070701000008B4000081B400000000000000000000000167AE111400000225000000000000000000000000000000000000007A00000000susemanager-schema/upgrade/susemanager-schema-1.2.71-to-susemanager-schema-1.2.72/002-rhnServerAction-result_msg-size.sql --
-- Copyright (c) 2011 SUSE Linux Products GmbH, Nuremberg, Germany
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
--

alter table rhnServerAction modify ( result_msg VARCHAR2(1024 CHAR) );

commit;   070701000008B5000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005200000000susemanager-schema/upgrade/susemanager-schema-1.2.72-to-susemanager-schema-1.2.73 070701000008B6000081B400000000000000000000000167AE111400000348000000000000000000000000000000000000006C00000000susemanager-schema/upgrade/susemanager-schema-1.2.72-to-susemanager-schema-1.2.73/001-suseOSTarget-Data.sql   --
-- Copyright (c) 2011 SUSE Linux Products GmbH, Nuremberg, Germany
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
--

insert into suseOSTarget (id, os, target, channel_arch_id) values
(sequence_nextval('suse_ostarget_id_seq'), 'sled-10-i686', 'sled-10-i586', LOOKUP_CHANNEL_ARCH('channel-ia32'));

insert into suseOSTarget (id, os, target, channel_arch_id) values
(sequence_nextval('suse_ostarget_id_seq'), 'sles-10-i686', 'sles-10-i586', LOOKUP_CHANNEL_ARCH('channel-ia32'));

commit;


070701000008B7000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005200000000susemanager-schema/upgrade/susemanager-schema-1.2.73-to-susemanager-schema-1.2.74 070701000008B8000081B400000000000000000000000167AE11140000024F000000000000000000000000000000000000007200000000susemanager-schema/upgrade/susemanager-schema-1.2.73-to-susemanager-schema-1.2.74/001-create-index-rhnPackage.sql --
-- Copyright (c) 2011 SUSE Linux Products GmbH, Nuremberg, Germany
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
--

CREATE INDEX rhn_package_chksum_id_idx
    ON rhnPackage (checksum_id)
    TABLESPACE [[2m_tbs]]
    NOLOGGING;

commit;
 070701000008B9000081B400000000000000000000000167AE111400000220000000000000000000000000000000000000007200000000susemanager-schema/upgrade/susemanager-schema-1.2.73-to-susemanager-schema-1.2.74/010-add-image-deploy-action.sql --
-- Copyright (c) 2012 Novell
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
--

insert into rhnActionType values (500, 'image.deploy', 'Deploy an image to a virtual host.', 'N', 'N');
commit;
070701000008BA000081B400000000000000000000000167AE111400000448000000000000000000000000000000000000007600000000susemanager-schema/upgrade/susemanager-schema-1.2.73-to-susemanager-schema-1.2.74/011-create-rhnActionImageDeploy.sql --
-- Copyright (c) 2012 Novell
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
--

CREATE TABLE rhnActionImageDeploy
(
    id            NUMBER NOT NULL PRIMARY KEY,
    action_id     NUMBER NOT NULL
                   CONSTRAINT rhn_act_idp_act_fk
                       REFERENCES rhnAction (id)
                       ON DELETE CASCADE,
    vcpus         NUMBER DEFAULT(1) NOT NULL,
    mem_kb        NUMBER DEFAULT(524288) NOT NULL,
    bridge_device VARCHAR2(32)  DEFAULT('br0') NOT NULL,
    image_type    VARCHAR2(32)  NOT NULL,
    download_url  VARCHAR2(256) NOT NULL,
    proxy_server  VARCHAR2(64),
    proxy_user    VARCHAR2(32),
    proxy_pass    VARCHAR2(64)
)
ENABLE ROW MOVEMENT
;

CREATE SEQUENCE rhn_action_image_deploy_id_seq;

070701000008BB000081B400000000000000000000000167AE111400000407000000000000000000000000000000000000006A00000000susemanager-schema/upgrade/susemanager-schema-1.2.73-to-susemanager-schema-1.2.74/012-suseCredentials.sql --
-- Copyright (c) 2012 Novell
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
--

CREATE TABLE suseCredentials
(
    id       NUMBER NOT NULL
                 CONSTRAINT suse_credentials_pk PRIMARY KEY,
    user_id  NUMBER NOT NULL UNIQUE
                 CONSTRAINT suse_credentials_oid_fk
                 REFERENCES web_contact (id)
                 ON DELETE CASCADE,
    type     VARCHAR2(32) NOT NULL,
    url      VARCHAR2(256),
    username VARCHAR2(64) NOT NULL,
    password VARCHAR2(64) NOT NULL,
    created  DATE DEFAULT (sysdate) NOT NULL,
    modified DATE DEFAULT (sysdate) NOT NULL
)
ENABLE ROW MOVEMENT
;

CREATE SEQUENCE suse_credentials_id_seq START WITH 100;

 070701000008BC000081B400000000000000000000000167AE1114000002F1000000000000000000000000000000000000008200000000susemanager-schema/upgrade/susemanager-schema-1.2.73-to-susemanager-schema-1.2.74/020-create-index-suseServerInstalledProduct.sql --
-- Copyright (c) 2012 SUSE Linux Products GmbH, Nuremberg, Germany
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
--

CREATE UNIQUE INDEX suse_srv_inprod_uq
    ON suseServerInstalledProduct (rhn_server_id, suse_installed_product_id)
    TABLESPACE [[64k_tbs]];

CREATE INDEX suse_srv_inprod_pkg_idx
    ON suseServerInstalledProduct (rhn_server_id)
    TABLESPACE [[64k_tbs]]
    NOLOGGING;

commit;
   070701000008BD000081B400000000000000000000000167AE11140000045C000000000000000000000000000000000000007A00000000susemanager-schema/upgrade/susemanager-schema-1.2.73-to-susemanager-schema-1.2.74/021-create-index-suseProductChannel.sql --
-- Copyright (c) 2012 SUSE Linux Products GmbH, Nuremberg, Germany
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
--

declare
    cursor product_to_channel is
    select distinct  product_id, channel_id
    from suseProductCHannel;

begin

    for ps in product_to_channel loop

        delete from suseproductchannel where product_id = ps.product_id and channel_id = ps.channel_id;
        insert into suseproductchannel (product_id, channel_id) values (ps.product_id, ps.channel_id);

    end loop;
    commit;
end;
/

CREATE UNIQUE INDEX suse_prd_chan_uq
    ON suseProductChannel (product_id, channel_id)
    TABLESPACE [[64k_tbs]];

CREATE INDEX suse_prd_chan_chan_idx
    ON suseProductChannel (channel_id)
    TABLESPACE [[64k_tbs]]
    NOLOGGING;

commit;
070701000008BE000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005200000000susemanager-schema/upgrade/susemanager-schema-1.2.74-to-susemanager-schema-1.2.75 070701000008BF000081B400000000000000000000000167AE1114000004EE000000000000000000000000000000000000006E00000000susemanager-schema/upgrade/susemanager-schema-1.2.74-to-susemanager-schema-1.2.75/001-suseCredentialsType.sql --
-- Copyright (c) 2012 Novell
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

CREATE TABLE suseCredentialsType
(
    id        NUMBER NOT NULL
                  CONSTRAINT suse_credtype_id_pk PRIMARY KEY
                  USING INDEX TABLESPACE [[64k_tbs]],
    label     VARCHAR2(64) NOT NULL,
    name      VARCHAR2(128) NOT NULL,
    created   DATE
                  DEFAULT (sysdate) NOT NULL,
    modified  DATE
                  DEFAULT (sysdate) NOT NULL
)
ENABLE ROW MOVEMENT
;

CREATE INDEX suse_credtype_label_id_idx
    ON suseCredentialsType (label, id)
    TABLESPACE [[64k_tbs]];

CREATE SEQUENCE suse_credtype_id_seq;

ALTER TABLE suseCredentialsType
    ADD CONSTRAINT suse_credtype_label_uq UNIQUE (label);

  070701000008C0000081B400000000000000000000000167AE1114000002F3000000000000000000000000000000000000007300000000susemanager-schema/upgrade/susemanager-schema-1.2.74-to-susemanager-schema-1.2.75/002-suseCredentialsType_data.sql    --
-- Copyright (c) 2012 Novell
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

insert into suseCredentialsType (id, label, name) values
	(sequence_nextval('suse_credtype_id_seq'), 'susestudio', 'SUSE Studio');
commit;

 070701000008C1000081B400000000000000000000000167AE1114000005A6000000000000000000000000000000000000007200000000susemanager-schema/upgrade/susemanager-schema-1.2.74-to-susemanager-schema-1.2.75/003-suseCredentials_migrate.sql --
-- Copyright (c) 2012 Novell
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--

-- Backup table 'suseCredentials'
CREATE TABLE  suseCredentialsBackup
    AS SELECT * FROM suseCredentials;

-- Truncate the original table
TRUNCATE TABLE suseCredentials;

-- Add new (NOT NULL) column 'type_id' to 'suseCredentials'
ALTER TABLE suseCredentials ADD type_id NUMBER NOT NULL
    CONSTRAINT suse_credentials_type_fk
    REFERENCES suseCredentialsType (id);

-- Re-insert everything including the 'type_id'
INSERT INTO suseCredentials
SELECT c.id, c.user_id, c.type, c.url, c.username, c.password, c.created, c.modified, d.id as type_id
    FROM suseCredentialsBackup c, suseCredentialsType d
    WHERE d.label = 'susestudio';

-- Delete column 'type' and the backup table
ALTER TABLE suseCredentials DROP COLUMN type;
DROP TABLE suseCredentialsBackup;

-- Rename foreign key constraint on the user
ALTER TABLE suseCredentials
    RENAME CONSTRAINT suse_credentials_oid_fk
    TO suse_credentials_user_fk;

-- Allow more than one pair of creds per user
ALTER TABLE suseCredentials DROP UNIQUE (user_id);

  070701000008C2000081B400000000000000000000000167AE11140000027C000000000000000000000000000000000000007700000000susemanager-schema/upgrade/susemanager-schema-1.2.74-to-susemanager-schema-1.2.75/004-rhnActionImageDeploy_migrate.sql    --
-- Copyright (c) 2012 Novell
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--

-- Drop column 'image_type'
ALTER TABLE rhnActionImageDeploy DROP COLUMN image_type;

-- Allow NULL values in column 'bridge_device'
ALTER TABLE rhnActionImageDeploy MODIFY bridge_device VARCHAR2(32) NULL;

070701000008C3000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000004F00000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7    070701000008C4000081B400000000000000000000000167AE11140000020B000000000000000000000000000000000000007400000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/002-add-update_tag-to-rhnChannel.sql   --
-- Copyright (c) 2011 SUSE Linux Products GmbH, Nuremberg, Germany
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
--

ALTER TABLE rhnChannel ADD update_tag varchar2(20);

 070701000008C5000081B400000000000000000000000167AE111400000511000000000000000000000000000000000000006700000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/050-suseProductFile.sql    --
-- Copyright (c) 2011 Novell
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
--
create table suseProductFile
(
  id              NUMBER NOT NULL PRIMARY KEY,
  name            VARCHAR2(256) NOT NULL,
  evr_id          NUMBER NOT NULL
                         CONSTRAINT suse_prod_file_eid_fk
                         REFERENCES rhnpackageevr (id),
  package_arch_id NUMBER NOT NULL
                         CONSTRAINT suse_prod_file_paid_fk
                         REFERENCES rhnpackagearch (id),
  vendor          VARCHAR2(256),
  summary         VARCHAR2(4000),
  description     VARCHAR2(4000),
  created         date default(sysdate) not null,
  modified        date default(sysdate) not null
);

CREATE SEQUENCE suse_prod_file_id_seq START WITH 100;

create or replace trigger
suse_product_file_mod_trig
before insert or update on suseProductFile
for each row
begin
	:new.modified := sysdate;
end suse_product_file_mod_trig;
/
show errors

   070701000008C6000081B400000000000000000000000167AE11140000052C000000000000000000000000000000000000006E00000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/051-susePackageProductFile.sql --
-- Copyright (c) 2011 Novell
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
--

create table
susePackageProductFile
(
    package_id numeric        not null
                             CONSTRAINT sppf_pid_fk
                             REFERENCES rhnPackage (id),
    prodfile_id numeric        not null
                             CONSTRAINT sppf_pfid_fk
                             REFERENCES suseProductFile (id),
    created     date default(sysdate) not null,
    modified    date default(sysdate) not null
)
ENABLE ROW MOVEMENT
;

CREATE UNIQUE INDEX sppf_pi_pi_uq
    ON susePackageProductFile (package_id, prodfile_id)
    TABLESPACE [[64k_tbs]];

CREATE INDEX sppf_pid_idx
    ON susePackageProductFile (package_id)
    TABLESPACE [[64k_tbs]]
    NOLOGGING;

create or replace trigger
suse_pack_prod_file_mod_trig
before insert or update on susePackageProductFile
for each row
begin
	:new.modified := sysdate;
end suse_pack_prod_file_mod_trig;
/
show errors

070701000008C7000081B400000000000000000000000167AE11140000036C000000000000000000000000000000000000006500000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/052-suseMdKeyword.sql  --
-- Copyright (c) 2012 Novell
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
--

create table
suseMdKeyword
(
    id                number PRIMARY KEY,
    label             varchar(128) NOT NULL,
    created           date default(sysdate) not null,
    modified          date default(sysdate) not null
)
ENABLE ROW MOVEMENT
;

CREATE SEQUENCE suse_mdkeyword_id_seq;

create or replace trigger
susemdkeyw_mod_trig
before insert or update on suseMdKeyword
for each row
begin
    :new.modified := sysdate;
end;
/
show errors

070701000008C8000081B400000000000000000000000167AE1114000005A6000000000000000000000000000000000000006200000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/053-suseMdData.sql --
-- Copyright (c) 2012 Novell
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
--

create table
suseMdData
(
    channel_id        number
                      CONSTRAINT susemddata_chn_id_fk
                      REFERENCES rhnChannel (id)
                      ON DELETE CASCADE,
    package_id        number
                      CONSTRAINT susemddata_pkg_id_fk
                      REFERENCES rhnPackage (id)
                      On DELETE CASCADE,
    keyword_id        number
                      CONSTRAINT susemdkeyword_id_fk
                      REFERENCES suseMdKeyword (id),
    created           date default(sysdate) not null,
    modified          date default(sysdate) not null
)
ENABLE ROW MOVEMENT
;

CREATE UNIQUE INDEX susemddata_chn_pkg_key_uq
ON suseMdData (channel_id, package_id, keyword_id)
TABLESPACE [[64k_tbs]];

CREATE INDEX susemddata_chn_pkg_idx
ON suseMdData (channel_id, package_id)
TABLESPACE [[64k_tbs]];

create or replace trigger
susemddata_mod_trig
before insert or update on suseMdData
for each row
begin
    :new.modified := sysdate;
end;
/
show errors

  070701000008C9000081B400000000000000000000000167AE111400000578000000000000000000000000000000000000006900000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/054-lookup_md_keyword.sql  -- Copyright (c) 2012 Novell
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--

create or replace function insert_md_keyword(label_in in varchar2)
return number
is
    pragma autonomous_transaction;
    md_keyword_id  number;
begin
    insert into suseMdKeyword (id, label)
    values (suse_mdkeyword_id_seq.nextval, label_in) returning id into md_keyword_id;
    commit;
    return md_keyword_id;
end;
/
show errors

create or replace function
lookup_md_keyword(label_in in varchar2)
return number
is
    pragma autonomous_transaction;
    md_keyword_id number;
begin
    begin
        select id
          into md_keyword_id
          from suseMdKeyword
         where label = label_in;
    exception when no_data_found then
        begin
            md_keyword_id := insert_md_keyword(label_in);
        exception when dup_val_on_index then
            select id
              into md_keyword_id
              from suseMdKeyword
             where label = label_in;
        end;
    end;

    return md_keyword_id;
end lookup_md_keyword;
/
show errors
070701000008CA000081B400000000000000000000000167AE11140000015E000000000000000000000000000000000000006A00000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/057-rename-primary-key.sql declare
  cname varchar2(30) := '';
begin
    select constraint_name
      into cname
      from user_constraints
     where table_name = 'RHNACTIONIMAGEDEPLOY' and constraint_type = 'P';
    if cname like 'SYS%' then
        execute immediate 'alter table RHNACTIONIMAGEDEPLOY rename constraint ' || cname || ' to rhn_aid_id_pk';
    end if;
end;
/
  070701000008CB000081B400000000000000000000000167AE111400000244000000000000000000000000000000000000006B00000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/058-remove-metadata-cpp.sql    --
-- Copyright (c) 2012 Novell
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
--

delete from rhnPackageRepodata where package_id in (select p.id
from rhnPackage p
join rhnPackageName pn ON p.name_id = pn.id
where name = 'cpp');

070701000008CC000081B400000000000000000000000167AE1114000000C0000000000000000000000000000000000000006900000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/101-rhnTaskoTask_data.sql  INSERT INTO rhnTaskoTask (id, name, class)
             VALUES (sequence_nextval('rhn_tasko_task_id_seq'), 'cleanup-packagechangelog-data', 'com.redhat.rhn.taskomatic.task.ChangeLogCleanUp');
070701000008CD000081B400000000000000000000000167AE1114000002CE000000000000000000000000000000000000006D00000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/102-rhnTaskoTemplate_data.sql  declare
  data_bunch_id number := 0;
begin
  begin
      SELECT id INTO data_bunch_id FROM rhnTaskoBunch WHERE name='cleanup-data-bunch';
  exception
    WHEN no_data_found THEN

      INSERT INTO rhnTaskoBunch (id, name, description, org_bunch)
      VALUES (sequence_nextval('rhn_tasko_bunch_id_seq'), 'cleanup-data-bunch', 'Cleans up orphaned and outdated data', null);

      commit;
  end;
  INSERT INTO rhnTaskoTemplate (id, bunch_id, task_id, ordering, start_if)
    VALUES (sequence_nextval('rhn_tasko_template_id_seq'),
        (SELECT id FROM rhnTaskoBunch WHERE name='cleanup-data-bunch'),
        (SELECT id FROM rhnTaskoTask WHERE name='cleanup-packagechangelog-data'),
        1,
        null);

end;
/

  070701000008CE000081B400000000000000000000000167AE11140000001C000000000000000000000000000000000000006600000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/103-rhnDaemonState.sql DROP TABLE rhnDaemonState;

070701000008CF000081B400000000000000000000000167AE11140000003B000000000000000000000000000000000000006800000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/105-rhn_package-drop.sql   
drop package body rhn_package;
drop package rhn_package;

 070701000008D0000081B400000000000000000000000167AE11140000033E000000000000000000000000000000000000005F00000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/106-rhn_org.sql    --
-- Copyright (c) 2008--2011 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--

CREATE OR REPLACE
PACKAGE rhn_org
IS
    procedure delete_org(org_id_in in number);
    procedure delete_user(user_id_in in number, deleting_org in number := 0);

END rhn_org;
/
SHOW ERRORS

  070701000008D1000081B400000000000000000000000167AE1114000020DB000000000000000000000000000000000000006400000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/107-rhn_org-body.sql   --
-- Copyright (c) 2008--2011 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--

CREATE OR REPLACE
PACKAGE BODY rhn_org
IS  
    procedure delete_org (
        org_id_in in number
    )
    is
        cursor users is
        select id
        from web_contact
        where org_id = org_id_in;

    cursor servers(org_id_in in number) is
        select    id
        from    rhnServer
        where    org_id = org_id_in;

        cursor config_channels is
        select id
        from rhnConfigChannel
        where org_id = org_id_in;

    cursor custom_channels is
        select    id
        from    rhnChannel
        where    org_id = org_id_in;

    cursor errata is
        select    id
        from    rhnErrata
        where    org_id = org_id_in;

    begin

        if org_id_in = 1 then
            rhn_exception.raise_exception('cannot_delete_base_org');
        end if;

        -- Delete all users.
        for u in users loop
            rhn_org.delete_user(u.id, 1);
        end loop;

        -- Delete all servers.
        for s in servers(org_id_in) loop
            delete_server(s.id);
        end loop;

        -- Delete all config channels.
        for c in config_channels loop
            rhn_config.delete_channel(c.id);
        end loop;

        -- Delete all custom channels.
        for cc in custom_channels loop
          delete from rhnServerChannel where channel_id = cc.id;
          delete from rhnServerProfilePackage where server_profile_id in (
            select id from rhnServerProfile where base_channel = cc.id
          );
          delete from rhnServerProfile where base_channel = cc.id;
        end loop;

        -- Delete all errata packages 
        for e in errata loop
            delete from rhnErrataPackage where errata_id = e.id;
        end loop;

        -- Give the org's entitlements back to the main org.
        rhn_entitlements.remove_org_entitlements(org_id_in);

        -- Clean up tables where we don't have a cascading delete.
        delete from rhnChannel where org_id = org_id_in;
        delete from rhnDailySummaryQueue where org_id = org_id_in;
        delete from rhnOrgQuota where org_id = org_id_in;
        delete from rhnFileList where org_id = org_id_in;
        delete from rhnServerGroup where org_id = org_id_in;
        delete from rhn_check_suites where customer_id = org_id_in;
        delete from rhn_command_target where customer_id = org_id_in;
        delete from rhn_contact_groups where customer_id = org_id_in;
        delete from rhn_notification_formats where customer_id = org_id_in;
        delete from rhn_probe where customer_id = org_id_in;
        delete from rhn_redirects where customer_id = org_id_in;
        delete from rhn_sat_cluster where customer_id = org_id_in;
        delete from rhn_schedules where customer_id = org_id_in;

        -- Delete the org.
        delete from web_customer where id = org_id_in;

    end delete_org;

    procedure delete_user(user_id_in in number, deleting_org in number := 0) is
        cursor servergroups_needing_admins is
            select    usgp.server_group_id    server_group_id
            from    rhnUserServerGroupPerms    usgp
            where    1=1
                and usgp.user_id = user_id_in
                and not exists (
                    select    1
                    from    rhnUserServerGroupPerms    sq_usgp
                    where    1=1
                        and sq_usgp.server_group_id = usgp.server_group_id
                        and    sq_usgp.user_id != user_id_in
                );
        users            number;
        our_org_id        number;
        other_users        number;
        other_org_admin    number;
        other_user_id  number;
        is_admin       number;
    begin
        select    wc.org_id
        into    our_org_id
        from    web_contact wc
        where    id = user_id_in;

        -- find any other users
        begin
            select    id, 1
            into    other_user_id, other_users
            from    web_contact
            where    1=1
                and org_id = our_org_id
                and id != user_id_in
                and rownum = 1;
        exception
            when no_data_found then
                other_users := 0;
        end;

        -- now do org admin stuff
        if other_users != 0 then
            -- is user admin?
            select  count(1)
             into   is_admin
            from    rhnUserGroupType    ugt,
                    rhnUserGroup        ug,
                    rhnUserGroupMembers    ugm
            where    ugm.user_id = user_id_in
                and ugm.user_group_id = ug.id
                and ug.group_type = ugt.id
                and ugt.label = 'org_admin';
            if is_admin > 0 then
                begin
                    select    new_ugm.user_id
                    into    other_org_admin
                    from    rhnUserGroupMembers    new_ugm,
                            rhnUserGroupType    ugt,
                            rhnUserGroup        ug,
                            rhnUserGroupMembers    ugm
                    where    ugm.user_id = user_id_in
                        and ugm.user_group_id = ug.id
                        and ug.group_type = ugt.id
                        and ugt.label = 'org_admin'
                        and ug.id = new_ugm.user_group_id
                        and new_ugm.user_id != user_id_in
                        and rownum = 1;
                exception
                    when no_data_found then
                        -- If we're deleting the org, we don't want to raise
                        -- the exception.
                        if deleting_org = 0 then
                            rhn_exception.raise_exception('cannot_delete_user');
                        end if;
                end;

                for sg in servergroups_needing_admins loop
                    rhn_user.add_servergroup_perm(other_org_admin,
                        sg.server_group_id);
                end loop;
            end if;
        end if;

        -- and now things for every user
        delete from rhn_command_queue_sessions where contact_id = user_id_in;
        delete from rhn_contact_groups
        where recid in (
            select contact_group_id
            from rhn_contact_group_members
            where member_contact_method_id in (
                select recid from rhn_contact_methods
                where contact_id = user_id_in
                )
            )
            and not exists (
                select 1
                from rhn_contact_group_members, rhn_contact_methods
                where rhn_contact_groups.recid = rhn_contact_group_members.contact_group_id
                    and rhn_contact_group_members.member_contact_method_id = rhn_contact_methods.recid
                    and rhn_contact_methods.contact_id <> user_id_in
            );
        delete from rhn_contact_methods where contact_id = user_id_in;
        delete from rhn_redirects where contact_id = user_id_in;
        delete from rhnUserServerPerms where user_id = user_id_in;
        delete from rhnAppInstallSession where user_id = user_id_in;
        update rhnConfigRevision
           set changed_by_id = NULL
         where changed_by_id = user_id_in;
        if other_users != 0 then
            update        rhnRegToken
                set        user_id = nvl(other_org_admin, other_user_id)
                where    org_id = our_org_id
                    and user_id = user_id_in;
        end if;

        begin
            delete from web_contact where id = user_id_in;
        exception
            when others then
                rhn_exception.raise_exception('cannot_delete_user');
        end;
        return;
    end delete_user;

END rhn_org;
/
SHOW ERRORS

 070701000008D2000081B400000000000000000000000167AE111400000023000000000000000000000000000000000000006E00000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/108-channel_name_join-drop.sql 
drop function channel_name_join;

 070701000008D3000081B400000000000000000000000167AE11140000001C000000000000000000000000000000000000006B00000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/109-channel_name_t-drop.sql    
drop type channel_name_t;

070701000008D4000081B400000000000000000000000167AE1114000003CE000000000000000000000000000000000000005B00000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/110-rpm.sql    --
-- Copyright (c) 2008--2011 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--
-- PL/SQL version of rpmvercompare
-- 

CREATE OR REPLACE PACKAGE rpm AS
    FUNCTION vercmp(
        e1 VARCHAR2, v1 VARCHAR2, r1 VARCHAR2, 
        e2 VARCHAR2, v2 VARCHAR2, r2 VARCHAR2)
    RETURN NUMBER
        DETERMINISTIC
        PARALLEL_ENABLE;
    PRAGMA RESTRICT_REFERENCES(vercmp, WNDS, RNDS);
    
END rpm;
/
SHOW ERRORS;

  070701000008D5000081B400000000000000000000000167AE111400001DFC000000000000000000000000000000000000006000000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/111-rpm-body.sql   --
-- Copyright (c) 2008--2011 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--
-- PL/SQL version of rpmvercompare

CREATE OR REPLACE PACKAGE BODY rpm AS

    FUNCTION isdigit(ch CHAR)
    RETURN BOOLEAN
    deterministic
    IS
    BEGIN
        if ascii(ch) between ascii('0') and ascii('9')
        then
            return TRUE;
        end if;
        return FALSE;
    END isdigit;

    
    FUNCTION isalpha(ch CHAR)
    RETURN BOOLEAN
    deterministic
    IS
    BEGIN
        if ascii(ch) between ascii('a') and ascii('z') or 
            ascii(ch) between ascii('A') and ascii('Z')
        then
            return TRUE;
        end if;
        return FALSE;
    END isalpha;


    FUNCTION isalphanum(ch CHAR)
    RETURN BOOLEAN
    deterministic
    IS
    BEGIN
        if ascii(ch) between ascii('a') and ascii('z') or 
            ascii(ch) between ascii('A') and ascii('Z') or
            ascii(ch) between ascii('0') and ascii('9')
        then
            return TRUE;
        end if;
        return FALSE;
    END isalphanum;


    FUNCTION rpmstrcmp (string1 IN VARCHAR2, string2 IN VARCHAR2)
    RETURN NUMBER
    deterministic
    IS
        digits CHAR(10) := '0123456789';
        lc_alpha CHAR(27) := 'abcdefghijklmnopqrstuvwxyz';
        uc_alpha CHAR(27) := 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
        alpha CHAR(54) := lc_alpha || uc_alpha;
        str1 VARCHAR2(32767) := string1;
        str2 VARCHAR2(32767) := string2;
        one VARCHAR2(32767);
        two VARCHAR2(32767);
        isnum BOOLEAN;
    BEGIN
        if str1 is NULL or str2 is NULL
        then
            raise VALUE_ERROR;
        end if;
        -- easy comparison to see if versions are identical
        if str1 = str2
        then
            return 0;
        end if;
        -- loop through each version segment of str1 and str2 and compare them
        one := str1;
        two := str2;

        <<segment_loop>>
        while one is not null and two is not null
        loop
            declare
                segm1 VARCHAR2(32767);
                segm2 VARCHAR2(32767);
            begin
                --DBMS_OUTPUT.PUT_LINE('Params: ' || one || ',' || two);
                -- Throw out all non-alphanum characters
                while one is not null and not isalphanum(one)
                loop
                    one := substr(one, 2);
                end loop;
                while two is not null and not isalphanum(two)
                loop
                    two := substr(two, 2);
                end loop;
                --DBMS_OUTPUT.PUT_LINE('new params: ' || one || ',' || two);

                str1 := one;
                str2 := two;

                /* grab first completely alpha or completely numeric segment */
                /* leave one and two pointing to the start of the alpha or numeric */
                /* segment and walk str1 and str2 to end of segment */
                
                if str1 is not null and isdigit(str1)
                then
                    str1 := ltrim(str1, digits);
                    str2 := ltrim(str2, digits);
                    isnum := true;
                else
                    str1 := ltrim(str1, alpha);
                    str2 := ltrim(str2, alpha);
                    isnum := false;
                end if;

                --DBMS_OUTPUT.PUT_LINE('Len: ' || length(str1) || ',' || length(str2));
                -- Oracle trats the length of an empty string as null
                if str1 is not null
                then segm1 := substr(one, 1, length(one) - length(str1));
                else segm1 := one;
                end if;
                    
                if str2 is not null
                then segm2 := substr(two, 1, length(two) - length(str2));
                else segm2 := two;
                end if;

                --DBMS_OUTPUT.PUT_LINE('Segments: ' || segm1 || ',' || segm2);
                --DBMS_OUTPUT.PUT_LINE('Rest: ' || str1 || ',' || str2);
                /* take care of the case where the two version segments are */
                /* different types: one numeric and one alpha */
                if segm1 is null then return -1; end if; /* arbitrary */
                if segm2 is null then
					if isnum then
						return 1;
					else
						return -1;
					end if;
				end if;

                if isnum
                then
                    /* this used to be done by converting the digit segments */
                    /* to ints using atoi() - it's changed because long */
                    /* digit segments can overflow an int - this should fix that. */

                    /* throw away any leading zeros - it's a number, right? */
                    segm1 := ltrim(segm1, '0');
                    segm2 := ltrim(segm2, '0');

                    /* whichever number has more digits wins */
                    -- length of empty string is null
                    if segm1 is null and segm2 is not null
                    then
                        return -1;
                    end if;
                    if segm1 is not null and segm2 is null
                    then
                        return 1;
                    end if;
                    if length(segm1) > length(segm2) then return 1; end if;
                    if length(segm2) > length(segm1) then return -1; end if;
                end if;
                
                /* strcmp will return which one is greater - even if the two */
                /* segments are alpha or if they are numeric.  don't return  */
                /* if they are equal because there might be more segments to */
                /* compare */
                
                if segm1 < segm2 then return -1; end if;
                if segm1 > segm2 then return 1; end if;

                one := str1;
                two := str2;
            end;
        end loop segment_loop;
        /* this catches the case where all numeric and alpha segments have */
        /* compared identically but the segment sepparating characters were */
        /* different */
        if one is null and two is null then return 0; end if;

        /* whichever version still has characters left over wins */
        if one is null then return -1; end if;
        return 1;
    END rpmstrcmp;


    FUNCTION vercmp(
        e1 VARCHAR2, v1 VARCHAR2, r1 VARCHAR2, 
        e2 VARCHAR2, v2 VARCHAR2, r2 VARCHAR2)
    RETURN NUMBER
    IS
        rc NUMBER;
    BEGIN
        DECLARE
          ep1 NUMBER;
          ep2 NUMBER;
          BEGIN
            if e1 is null then
              ep1 := 0;
            else
              ep1 := TO_NUMBER(e1);
            end if;
            if e2 is null then
              ep2 := 0;
            else
              ep2 := TO_NUMBER(e2);
            end if;
            -- Epochs are non-null; compare them
            if ep1 < ep2 then return -1; end if;
            if ep1 > ep2 then return 1; end if;
            rc := rpmstrcmp(v1, v2);
            if rc != 0 then return rc; end if;
           return rpmstrcmp(r1, r2);
         END;

    END vercmp;

END rpm;
/
SHOW ERRORS;

070701000008D6000081B400000000000000000000000167AE111400000641000000000000000000000000000000000000006000000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/112-rhn_user.sql   --
-- Copyright (c) 2008--2011 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--

create or replace
package rhn_user
is
	version varchar2(100) := '';

    function check_role(user_id_in in number, role_in in varchar2) return number;
    PRAGMA RESTRICT_REFERENCES(check_role, WNDS, RNPS, WNPS);

    function check_role_implied(user_id_in in number, role_in in varchar2) return number;
    PRAGMA RESTRICT_REFERENCES(check_role_implied, WNDS, RNPS, WNPS);

    function get_org_id(user_id_in in number) return number;
    PRAGMA RESTRICT_REFERENCES(get_org_id, WNDS, RNPS, WNPS);
    
	function find_mailable_address(user_id_in in number) return varchar2;

	procedure add_servergroup_perm(
		user_id_in in number,
		server_group_id_in in number
	);

	procedure remove_servergroup_perm(
		user_id_in in number,
		server_group_id_in in number
	);

	procedure add_to_usergroup(
		user_id_in in number,
		user_group_id_in in number
	);

	procedure remove_from_usergroup(
		user_id_in in number,
		user_group_id_in in number
	);

end rhn_user;
/
SHOW ERRORS
   070701000008D7000081B400000000000000000000000167AE111400001AC7000000000000000000000000000000000000006500000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/113-rhn_user-body.sql  --
-- Copyright (c) 2008--2011 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--

create or replace
package body rhn_user
is
	body_version varchar2(100) := '';
	
    function check_role(user_id_in in number, role_in in varchar2)
    return number
    is
    	throwaway number;
    begin
    	-- the idea: if we get past this query, the org has the setting, else catch the exception and return 0
	select 1 into throwaway
	  from rhnUserGroupType UGT,
	       rhnUserGroup UG,
	       rhnUserGroupMembers UGM
	 where UGM.user_id = user_id_in
	   and UGM.user_group_id = UG.id
	   and UG.group_type = UGT.id
	   and UGT.label = role_in;
	   
	return 1;
    exception
    	when no_data_found
	    then
	    return 0;
    end check_role;
    
    function check_role_implied(user_id_in in number, role_in in varchar2)
    return number
    is
    	throwaway number;
    begin
    	-- if the user directly has the role, they win
    	if rhn_user.check_role(user_id_in, role_in) = 1
	then
	    return 1;
    	end if;

	-- config_admin and channel_admin are automatically implied for org admins	
	if role_in = 'config_admin' and rhn_user.check_role(user_id_in, 'org_admin') = 1
	then
	    return 1;
	end if;

	if role_in = 'channel_admin' and rhn_user.check_role(user_id_in, 'org_admin') = 1
	then
	    return 1;
	end if;

	return 0;	
    end check_role_implied;
    
    function get_org_id(user_id_in in number)
    return number
    is
    	org_id_out number;
    begin
    	select org_id into org_id_out
	  from web_contact
	 where id = user_id_in;
	 
	return org_id_out;
    end get_org_id;

	-- paid users often don't have verified email addresses, so
	-- try to find an address that is useful to us.
	function find_mailable_address(user_id_in in number)
	return varchar2 is
		PRAGMA AUTONOMOUS_TRANSACTION;
		-- this would be so much prettier if we just had an order built
		-- into rhnEmailAddressState
		cursor addrs is
			select	ea.state_id, ea.address
			from	rhnEmailAddressState eas,
					rhnEmailAddress ea
			where	ea.user_id = user_id_in
				and eas.label = 'verified'
				and ea.state_id = eas.id
			union all
			select	ea.state_id, ea.address
			from	rhnEmailAddressState eas,
					rhnEmailAddress ea
			where	ea.user_id = user_id_in
				and eas.label = 'unverified'
				and ea.state_id = eas.id
			union all
			select	ea.state_id, ea.address
			from	rhnEmailAddressState eas,
					rhnEmailAddress ea
			where	ea.user_id = user_id_in
				and eas.label = 'pending'
				and ea.state_id = eas.id
			union all
			select	ea.state_id, ea.address
			from	rhnEmailAddressState eas,
					rhnEmailAddress ea
			where	ea.user_id = user_id_in
				and eas.label = 'pending_warned'
				and ea.state_id = eas.id
			union all
			select	ea.state_id, ea.address
			from	rhnEmailAddressState eas,
					rhnEmailAddress ea
			where	ea.user_id = user_id_in
				and eas.label = 'needs_verifying'
				and ea.state_id = eas.id
			union all
			select	-1 state_id,
					email address
			from	web_user_personal_info
			where	web_user_id = user_id_in;
		retval rhnEmailAddress.address%TYPE;
	begin
		for addr in addrs loop
			retval := addr.address;
			if addr.address is null then
				update web_user_contact_permission
					set email = 'N'
					where web_user_id = user_id_in;
				commit;
				return null;
			end if;
			if addr.state_id = -1 then
				insert into rhnEmailAddress (
						id, address,
						user_id, state_id
					) (
						select	rhn_eaddress_id_seq.nextval, addr.address,
								user_id_in, eas.id
						from	rhnEmailAddressState eas
						where	eas.label = 'unverified'
					);
			end if;
			commit;
			return retval;
		end loop;
		return null;
	end;

	procedure add_servergroup_perm(
		user_id_in in number,
		server_group_id_in in number
	) is
		cursor	orgs_match is
			select	1
			from	rhnServerGroup sg,
					web_contact u
			where	u.id = user_id_in
				and sg.id = server_group_id_in
				and sg.org_id = u.org_id;
	begin
		for okay in orgs_match loop
			insert into rhnUserServerGroupPerms(user_id, server_group_id)
				values (user_id_in, server_group_id_in);
			rhn_cache.update_perms_for_user(user_id_in);
			return;
		end loop;
		rhn_exception.raise_exception('usgp_different_orgs');
	exception when dup_val_on_index then
		rhn_exception.raise_exception('usgp_already_allowed');
	end add_servergroup_perm;

	procedure remove_servergroup_perm(
		user_id_in in number,
		server_group_id_in in number
	) is
		cursor perms is
			select	1
			from	rhnUserServerGroupPerms
			where	user_id = user_id_in
				and server_group_id = server_group_id_in;
	begin
		for perm in perms loop
			delete from rhnUserServerGroupPerms
				where	user_id = user_id_in
					and server_group_id = server_group_id_in;
			rhn_cache.update_perms_for_user(user_id_in);
			return;
		end loop;
		rhn_exception.raise_exception('usgp_not_allowed');
	end remove_servergroup_perm;

	procedure add_to_usergroup(
		user_id_in in number,
		user_group_id_in in number
	) is
		cursor perm_granting_usergroups is
			select	user_group_id_in
			from	rhnUserGroup		ug,
					rhnUserGroupType	ugt
			where	ugt.label in ('org_admin') -- and server_group_admin ?
				and ug.id = user_group_id_in
				and ug.group_type = ugt.id;
	begin
		insert into rhnUserGroupMembers(user_id, user_group_id)
			values (user_id_in, user_group_id_in);

		for ug in perm_granting_usergroups loop
			rhn_cache.update_perms_for_user(user_id_in);
			return;
		end loop;
	end add_to_usergroup;

	procedure remove_from_usergroup(
		user_id_in in number,
		user_group_id_in in number
	) is
		cursor perm_granting_usergroups is
			select	label
			from	rhnUserGroupType	ugt,
					rhnUserGroupMembers	ugm,
					rhnUserGroup		ug
			where	1=1
				and ug.id = user_group_id_in
				and ugm.user_group_id = user_group_id_in
				and ug.group_type = ugt.id
				and ugm.user_id = user_id_in;
	begin
		-- we only do anything if you're really in the group, because
		-- testing is significantly cheaper than rebuilding the user's
		-- cache for no reason.
		for ug in perm_granting_usergroups loop
			delete from rhnUserGroupMembers
				where	user_id = user_id_in
					and user_group_id = user_group_id_in;
			if ug.label in ('org_admin') then
				rhn_cache.update_perms_for_user(user_id_in);
			end if;
		end loop;
	end remove_from_usergroup;

end rhn_user;
/
SHOW ERRORS
 070701000008D8000081B400000000000000000000000167AE11140000067F000000000000000000000000000000000000006A00000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/117-rhnPackageKey-data.sql -- Fedora 13
update rhnPackageKey set provider_id = lookup_package_provider('Fedora')
 where key_id = '7edc6ad6e8e40fde';
insert into rhnPackageKey (id, key_id, key_type_id, provider_id)
select sequence_nextval('rhn_pkey_id_seq'), '7edc6ad6e8e40fde', lookup_package_key_type('gpg'), lookup_package_provider('Fedora')
from dual
where not exists ( select 1 from rhnPackageKey where key_id = '7edc6ad6e8e40fde' );

-- Fedora 14
update rhnPackageKey set provider_id = lookup_package_provider('Fedora')
 where key_id = '421caddb97a1071f';
insert into rhnPackageKey (id, key_id, key_type_id, provider_id)
select sequence_nextval('rhn_pkey_id_seq'), '421caddb97a1071f', lookup_package_key_type('gpg'), lookup_package_provider('Fedora')
from dual
where not exists ( select 1 from rhnPackageKey where key_id = '421caddb97a1071f' );

-- Spacewalk
update rhnPackageKey set provider_id = lookup_package_provider('Spacewalk')
 where key_id = 'ed635379b3892132';
insert into rhnPackageKey (id, key_id, key_type_id, provider_id)
select sequence_nextval('rhn_pkey_id_seq'), 'ed635379b3892132', lookup_package_key_type('gpg'), lookup_package_provider('Spacewalk')
from dual
where not exists ( select 1 from rhnPackageKey where key_id = 'ed635379b3892132' );

-- RHEL 6
update rhnPackageKey set provider_id = lookup_package_provider('Red Hat Inc.')
 where key_id = '199e2f91fd431d51';
insert into rhnPackageKey (id, key_id, key_type_id, provider_id)
select sequence_nextval('rhn_pkey_id_seq'), '199e2f91fd431d51', lookup_package_key_type('gpg'), lookup_package_provider('Red Hat Inc.')
from dual
where not exists ( select 1 from rhnPackageKey where key_id = '199e2f91fd431d51' );

 070701000008D9000081B400000000000000000000000167AE111400000080000000000000000000000000000000000000007400000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/202-rhnActionErrataUpdate-unique.sql   
drop index rhn_act_eu_aid_eid_idx;
create unique index rhn_act_eu_aid_eid_uq on rhnActionErrataUpdate (action_id, errata_id);

070701000008DA000081B400000000000000000000000167AE111400000026000000000000000000000000000000000000007600000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/203-web_customer_notification_drop.sql drop table web_customer_notification;
  070701000008DB000081B400000000000000000000000167AE11140000001F000000000000000000000000000000000000006F00000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/204-rhn_sat_node_probe_drop.sql    drop table rhn_sat_node_probe;
 070701000008DC000081B400000000000000000000000167AE111400000022000000000000000000000000000000000000006F00000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/205-web_cust_notif_seq_drop.sql    drop sequence web_cust_notif_seq;
  070701000008DD000081B400000000000000000000000167AE11140000001D000000000000000000000000000000000000006B00000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/206-sat_node_probe_drop.sql    drop synonym sat_node_probe;
   070701000008DE000081B400000000000000000000000167AE11140000005A000000000000000000000000000000000000006900000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/208-rhnVirtualization.sql  CREATE INDEX rhn_vi_uuid_idx
    ON rhnVirtualInstance (uuid)
    TABLESPACE [[64k_tbs]];
  070701000008DF000081B400000000000000000000000167AE111400000022000000000000000000000000000000000000006D00000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/209-rhnBlacklistObsoletes.sql  drop table rhnBlacklistObsoletes;
  070701000008E0000081B400000000000000000000000167AE111400000022000000000000000000000000000000000000006D00000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/210-concat_list_clob-drop.sql  
drop function concat_list_clob;

  070701000008E1000081B400000000000000000000000167AE1114000002AC000000000000000000000000000000000000006B00000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/211-get_hw_info_as_clob.sql    
create or replace function get_hw_info_as_clob(
	sid in rhnserver.id%TYPE,
	separator in varchar
)
return clob
is
	ret clob;
	tmp varchar2(4000);
begin
	dbms_lob.createtemporary(ret, true); 
	for rec in (
		select m
		from (
			select 1 n, sum(nrcpu) || ' CPUs' m
			from rhncpu where rhncpu.server_id = sid
			union all
			select 2, name||' '||ip_addr||'/'||netmask||' '||hw_addr val
			from rhnservernetinterface
			where rhnservernetinterface.server_id = sid
			)
		order by n, m
		) loop
		if dbms_lob.getlength(ret) > 0 then
			dbms_lob.writeappend(ret, length(separator), separator);
		end if;
		dbms_lob.writeappend(ret, length(rec.m), rec.m);
	end loop;
	return ret;
end;
/

070701000008E2000081B400000000000000000000000167AE111400000203000000000000000000000000000000000000006700000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/213-rhn_sg_del_trig.sql    
create or replace trigger
rhn_sg_del_trig
before delete on rhnServerGroup
for each row
declare
	cursor snapshots is
		select	snapshot_id id
		from	rhnSnapshotServerGroup
		where	server_group_id = :old.id
		order by snapshot_id;
begin
	for snapshot in snapshots loop
		update rhnSnapshot
			set invalid = lookup_snapshot_invalid_reason('sg_removed')
			where id = snapshot.id;
		delete from rhnSnapshotServerGroup
			where snapshot_id = snapshot.id
				and server_group_id = :old.id;
	end loop;
end;
/
show errors

 070701000008E3000081B400000000000000000000000167AE11140001134B000000000000000000000000000000000000006800000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/222-rhn_entitlements.sql   --
-- Copyright (c) 2008--2011 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--
--
--
--

create or replace
package body rhn_entitlements
is
    body_version varchar2(100) := '';

   function find_compatible_sg (
      server_id_in    in   number,
      type_label_in   in   varchar2
   ) return number is

      cursor servergroups is
         select sg.id            id
           from rhnServerGroupType             sgt,
                rhnServerGroup                 sg,
                rhnServer                     s,
                rhnServerServerGroupArchCompat ssgac
          where s.id = server_id_in
            and s.org_id = sg.org_id
            and sgt.label = type_label_in
            and sg.group_type = sgt.id
            and ssgac.server_group_type = sgt.id
            and ssgac.server_arch_id = s.server_arch_id
            and not exists (
                     select 1
                      from rhnServerGroupMembers sgm
                     where sgm.server_group_id = sg.id
                       and sgm.server_id = s.id);


   begin
      for servergroup in servergroups loop
         return servergroup.id;
      end loop;

      --no servergroup found
      return null;
   end find_compatible_sg;


    -- *******************************************************************
    -- PROCEDURE: remove_org_entitlements
    --
    -- Removes both system entitlements and channel subscriptions
    -- that are currently assigned to an org and re-assigns to the
    -- master org (org_id = 1).
    --
    -- When we call this we expect everything to already be unentitled
    -- which shoul be handled by delete_org.
    --
    -- Called by: delete_org
    -- *******************************************************************
    procedure remove_org_entitlements(
        org_id_in in number
    )
    is

        cursor system_ents is
        select sg.id, sg.max_members, sg.group_type
        from rhnServerGroup sg
        where group_type is not null
          and org_id = org_id_in;

        cursor channel_subs is
        select pcf.channel_family_id, pcf.max_members
        from rhnChannelFamily cf,
             rhnPrivateChannelFamily pcf
        where pcf.org_id = org_id_in
          and pcf.channel_family_id = cf.id
          and cf.org_id is null;

    begin

        for system_ent in system_ents loop
            update rhnServerGroup
            set max_members = max_members + system_ent.max_members
            where org_id = 1
              and group_type = system_ent.group_type;
        end loop;

        update rhnServerGroup
        set max_members = 0
        where org_id = org_id_in;

        for channel_sub in channel_subs loop
            update rhnPrivateChannelFamily
            set max_members = max_members + channel_sub.max_members
            where org_id = 1
              and channel_family_id = channel_sub.channel_family_id;
        end loop;

        update rhnPrivateChannelFamily
        set max_members = 0
        where org_id = org_id_in;

    end remove_org_entitlements;

    function entitlement_grants_service (
        entitlement_in in varchar2,
        service_level_in in varchar2
    ) return number    is
    begin
        if service_level_in = 'provisioning' then
            if entitlement_in = 'provisioning_entitled' then
                return 1;
            else
                return 0;
            end if;
        elsif service_level_in = 'management' then
            if entitlement_in = 'enterprise_entitled' then
                return 1;
            else
                return 0;
            end if;
        elsif service_level_in = 'monitoring' then
            if entitlement_in = 'monitoring_entitled' then
                return 1;
            end if;
        elsif service_level_in = 'updates' then
            return 1;
        else
            return 0;
        end if;
    end entitlement_grants_service;

    function lookup_entitlement_group (
        org_id_in in number,
        type_label_in in varchar2 := 'sw_mgr_entitled'
    ) return number is
        cursor server_groups is
            select    sg.id                server_group_id
            from    rhnServerGroup        sg,
                    rhnServerGroupType    sgt
            where    sgt.label = type_label_in
                and sgt.id = sg.group_type
                and sg.org_id = org_id_in;
    begin
        for sg in server_groups loop
            return sg.server_group_id;
        end loop;
        return rhn_entitlements.create_entitlement_group(
                org_id_in,
                type_label_in
            );
    end lookup_entitlement_group;

    function create_entitlement_group (
        org_id_in in number,
        type_label_in in varchar2 := 'sw_mgr_entitled'
    ) return number is
        sg_id_val number;
    begin
        select    rhn_server_group_id_seq.nextval
        into    sg_id_val
        from    dual;

        insert into rhnServerGroup (
                id, name, description, max_members, current_members,
                group_type, org_id
            ) (
                select    sg_id_val, sgt.label, sgt.label,
                        0, 0, sgt.id, org_id_in
                from    rhnServerGroupType sgt
                where    sgt.label = type_label_in
            );

        return sg_id_val;
    end create_entitlement_group;

   function can_entitle_server (
        server_id_in in number,
        type_label_in in varchar2 )
   return number is
      cursor addon_servergroups (base_label_in in varchar2,
                                 addon_label_in in varchar2) is
         select
            addon_id
         from
            rhnSGTypeBaseAddonCompat
         where base_id = lookup_sg_type (base_label_in)
           and addon_id = lookup_sg_type (addon_label_in);

      previous_ent        rhn_entitlements.ents_array;
      is_base_in          char   := 'N';
      is_base_current     char   := 'N';
      i                   number := 0;
      sgid                number := 0;

   begin

      previous_ent := rhn_entitlements.ents_array();
      previous_ent := rhn_entitlements.get_server_entitlement(server_id_in);

      select distinct is_base
      into is_base_in
      from rhnServerGroupType
      where label = type_label_in;

      if previous_ent.count = 0 then
         sgid := find_compatible_sg (server_id_in, type_label_in);
         if (is_base_in = 'Y' and sgid is not null) then
            -- rhn_server.insert_into_servergroup (server_id_in, sgid);
            return 1;
         else
            -- rhn_exception.raise_exception ('invalid_base_entitlement');
            return 0;
         end if;

      -- there are previous ents, first make sure we're not trying to entitle a base ent
      elsif is_base_in = 'Y' then
         -- rhn_exception.raise_exception ('invalid_addon_entitlement');
         return 0;

      -- it must be an addon, so proceed with the entitlement
      else

         -- find the servers base ent
         is_base_current := 'N';
         i := 0;
         while is_base_current = 'N' and i <= previous_ent.count
         loop
            i := i + 1;
            select is_base
            into is_base_current
            from rhnServerGroupType
            where label = previous_ent(i);
         end loop;

         -- never found a base ent, that would be strange
         if is_base_current  = 'N' then
            -- rhn_exception.raise_exception ('invalid_base_entitlement');
            return 0;
         end if;

         -- this for loop verifies the validity of the addon path
         for addon_servergroup in addon_servergroups  (previous_ent(i), type_label_in) loop
            -- find an appropriate sgid for the addon and entitle the server
            sgid := find_compatible_sg (server_id_in, type_label_in);
            if sgid is not null then
               -- rhn_server.insert_into_servergroup (server_id_in, sgid);
               return 1;
            else
               -- rhn_exception.raise_exception ('invalid_addon_entitlement');
               return 0;
            end if;
         end loop;

      end if;

      return 0;

   end can_entitle_server;

   function can_switch_base (
      server_id_in   in    integer,
      type_label_in  in    varchar2
   ) return number is

      type_label_in_is_base   char(1);
      sgid                    number;

   begin

      begin
         select is_base into type_label_in_is_base
         from rhnServerGroupType
         where label = type_label_in;
      exception
         when no_data_found then
            rhn_exception.raise_exception ( 'invalid_entitlement' );
      end;

      if type_label_in_is_base = 'N' then
         rhn_exception.raise_exception ( 'invalid_entitlement' );
      else
         sgid := find_compatible_sg ( server_id_in, type_label_in );
         if sgid is not null then
            return 1;
         else
            return 0;
         end if;
      end if;

   end can_switch_base;


    procedure entitle_server (
        server_id_in in number,
        type_label_in in varchar2 := 'sw_mgr_entitled'
    ) is
      sgid  number := 0;
      is_virt number := 0;

    begin

          begin
          select 1 into is_virt
            from rhnServerEntitlementView
           where server_id = server_id_in
             and label in ('virtualization_host', 'virtualization_host_platform');
      exception
            when no_data_found then
              is_virt := 0;
          end;

      if is_virt = 0 and (type_label_in = 'virtualization_host' or
                          type_label_in = 'virtualization_host_platform') then

        is_virt := 1;
      end if;



      if rhn_entitlements.can_entitle_server(server_id_in,
                                             type_label_in) = 1 then
         sgid := find_compatible_sg (server_id_in, type_label_in);
         if sgid is not null then
            insert into rhnServerHistory ( id, server_id, summary, details )
            values ( rhn_event_id_seq.nextval, server_id_in,
                     'added system entitlement ',
                      case type_label_in
                       when 'enterprise_entitled' then 'Management'
                       when 'sw_mgr_entitled' then 'Update'
                       when 'provisioning_entitled' then 'Provisioning'
                       when 'monitoring_entitled' then 'Monitoring'
                       when 'virtualization_host' then 'Virtualization'
                       when 'virtualization_host_platform' then
                            'Virtualization Platform' end  );

            rhn_server.insert_into_servergroup (server_id_in, sgid);

            if is_virt = 1 then
              rhn_entitlements.repoll_virt_guest_entitlements(server_id_in);
            end if;

         else
            rhn_exception.raise_exception ('no_available_server_group');
         end if;
      else
         rhn_exception.raise_exception ('invalid_entitlement');
      end if;
   end entitle_server;

    procedure remove_server_entitlement (
        server_id_in in number,
        type_label_in in varchar2 := 'sw_mgr_entitled',
        repoll_virt_guests in number := 1
    ) is
        group_id number;
      type_is_base char;
      is_virt number := 0;
    begin
      begin


      -- would be nice if there were a virt attribute of entitlement types, not have to specify 2 different ones...
        begin
          select 1 into is_virt
            from rhnServerEntitlementView
           where server_id = server_id_in
             and label in ('virtualization_host', 'virtualization_host_platform');
        exception
          when no_data_found then
            is_virt := 0;
        end;

        select    sg.id, sgt.is_base
          into    group_id, type_is_base
          from    rhnServerGroupType sgt,
               rhnServerGroup sg,
                  rhnServerGroupMembers sgm,
                  rhnServer s
          where    s.id = server_id_in
              and s.id = sgm.server_id
              and sgm.server_group_id = sg.id
              and sg.org_id = s.org_id
              and sgt.label = type_label_in
              and sgt.id = sg.group_type;

      if ( type_is_base = 'Y' ) then
         -- unentitle_server should handle everything, don't really need to do anything else special here
         unentitle_server ( server_id_in );
      else

         insert into rhnServerHistory ( id, server_id, summary, details )
         values ( rhn_event_id_seq.nextval, server_id_in,
                  'removed system entitlement ',
                   case type_label_in
                    when 'enterprise_entitled' then 'Management'
                    when 'sw_mgr_entitled' then 'Update'
                    when 'provisioning_entitled' then 'Provisioning'
                    when 'monitoring_entitled' then 'Monitoring'
                    when 'virtualization_host' then 'Virtualization'
                    when 'virtualization_host_platform' then
                         'Virtualization Platforrm' end  );

         rhn_server.delete_from_servergroup(server_id_in, group_id);

         -- special case: clean up related monitornig data
         if type_label_in = 'monitoring_entitled' then
           DELETE
             FROM state_change
            WHERE o_id IN (SELECT probe_id
                             FROM rhn_check_probe
                            WHERE host_id = server_id_in);
           DELETE /*+index(time_series time_series_probe_id_idx)*/
             FROM time_series
            WHERE SUBSTR(o_id, INSTR(o_id, '-') + 1,
                        (INSTR(o_id, '-', INSTR(o_id, '-') + 1) - INSTR(o_id, '-')) - 1)
              IN (SELECT to_char(probe_id)
                    FROM rhn_check_probe
                   WHERE host_id = server_id_in);
           DELETE
             FROM rhn_probe
            WHERE recid IN (SELECT probe_id
                              FROM rhn_check_probe
                             WHERE host_id = server_id_in);
         end if;

         if is_virt = 1 and repoll_virt_guests = 1 then
           rhn_entitlements.repoll_virt_guest_entitlements(server_id_in);
         end if;
      end if;

          exception
          when no_data_found then
                  rhn_exception.raise_exception('invalid_server_group_member');
      end;

     end remove_server_entitlement;


   procedure unentitle_server (server_id_in in number) is

      cursor servergroups is
         select distinct sgt.label, sg.id server_group_id
         from  rhnServerGroupType sgt,
               rhnServerGroup sg,
               rhnServer s,
               rhnServerGroupMembers sgm
         where s.id = server_id_in
            and s.org_id = sg.org_id
            and sg.group_type = sgt.id
            and sgm.server_group_id = sg.id
            and sgm.server_id = s.id;

     is_virt number := 0;

   begin

      begin
        select 1 into is_virt
          from rhnServerEntitlementView
         where server_id = server_id_in
           and label in ('virtualization_host', 'virtualization_host_platform');
      exception
        when no_data_found then
          is_virt := 0;
      end;

      for servergroup in servergroups loop

         insert into rhnServerHistory ( id, server_id, summary, details )
         values ( rhn_event_id_seq.nextval, server_id_in,
                  'removed system entitlement ',
                   case servergroup.label
                    when 'enterprise_entitled' then 'Management'
                    when 'sw_mgr_entitled' then 'Update'
                    when 'provisioning_entitled' then 'Provisioning'
                    when 'monitoring_entitled' then 'Monitoring'
                    when 'virtualization_host' then 'Virtualization'
                    when 'virtualization_host_platform' then
                         'Virtualization Platform' end  );

         rhn_server.delete_from_servergroup(server_id_in,
                                            servergroup.server_group_id );
      end loop;

      if is_virt = 1 then
        rhn_entitlements.repoll_virt_guest_entitlements(server_id_in);
      end if;

   end unentitle_server;


    -- *******************************************************************
    -- PROCEDURE: repoll_virt_guest_entitlements
    --
    --   Whenever we add/remove a virtualization_host* entitlement from
    --   a host, we can call this procedure to update what type of slots
    --   the guests are consuming.
    --
    --   If you're removing the entitlement, it's
    --   possible the guests will become unentitled if you don't have enough
    --   physical slots to cover them.
    --
    --   If you're adding the entitlement, you end up freeing up physical
    --   slots for other systems.
    --
    -- *******************************************************************
    procedure repoll_virt_guest_entitlements(server_id_in in number)
    is

        -- All channel families associated with the guests of server_id_in
        cursor families is
            select distinct cfs.channel_family_id
            from
                rhnChannelFamilyServers cfs,
                rhnVirtualInstance vi
            where
                vi.host_system_id = server_id_in
                and vi.virtual_system_id = cfs.server_id;

        -- All of server group types associated with the guests of
        -- server_id_in
        cursor group_types is
            select distinct sg.group_type, sgt.label
            from
                rhnServerGroupType sgt,
                rhnServerGroup sg,
                rhnServerGroupMembers sgm,
                rhnVirtualInstance vi
            where
                vi.host_system_id = server_id_in
                and vi.virtual_system_id = sgm.server_id
                and sgm.server_group_id = sg.id
                and sg.group_type = sgt.id;

        -- Virtual servers from a certain family belonging to a speicifc
        -- host that are consuming physical channel slots over the limit.
        cursor virt_servers_cfam(family_id_in in number, quantity_in in number)  is
            select virtual_system_id
            from (
                select rownum, vi.virtual_system_id
                from
                    rhnChannelFamilyMembers cfm,
                    rhnServerChannel sc,
                    rhnVirtualInstance vi
                where
                    vi.host_system_id = server_id_in
                    and vi.virtual_system_id = sc.server_id
                    and sc.channel_id = cfm.channel_id
                    and cfm.channel_family_id = family_id_in
                order by sc.modified desc
                )
            where rownum <= quantity_in;

        -- Virtual servers from a certain family belonging to a speicifc
        -- host that are consuming physical system slots over the limit.
        cursor virt_servers_sgt(group_type_in in number, quantity_in in number)  is
            select virtual_system_id
            from (
                select rownum, vi.virtual_system_id
                from
                    rhnServerGroup sg,
                    rhnServerGroupMembers sgm,
                    rhnVirtualInstance vi
                where
                    vi.host_system_id = server_id_in
                    and vi.virtual_system_id = sgm.server_id
                    and sgm.server_group_id = sg.id
                    and sg.group_type = group_type_in
                order by sgm.modified desc
                )
            where rownum <= quantity_in;
        -- Get the orgs of Virtual guests
        -- Since they may belong to different orgs
        cursor virt_guest_orgs  is
                select  distinct (s.org_id)
                from rhnServer s
                    inner join  rhnVirtualInstance vi on vi.virtual_system_id = s.id
                where
                    vi.host_system_id = server_id_in
                    and s.org_id <> (select s1.org_id from rhnServer s1 where s1.id = vi.host_system_id) ;


        org_id_val number;
        max_members_val number;
        max_flex_val number;
        current_members_calc number;
        sg_id number;
        is_virt number := 0;
    begin
        begin
          select 1 into is_virt
                from rhnServerEntitlementView
           where server_id = server_id_in
                 and label in ('virtualization_host', 'virtualization_host_platform');
           exception
                when no_data_found then
                  is_virt := 0;
        end;

        select org_id
        into org_id_val
        from rhnServer
        where id = server_id_in;

        -- deal w/ channel entitlements first ...
        for family in families loop
            if is_virt = 0 then
            -- if the host_server does not have virt
            --- find all possible flex slots
            -- and set each of the flex eligible guests to Y
                UPDATE rhnServerChannel sc set sc.is_fve = 'Y'
                where sc.server_id in (
                       select virtual_system_id from (
                            select rownum, vi.virtual_system_id,  sfc.max_members - sfc.current_members as free_slots
                            from rhnServerFveCapable sfc
                                inner join rhnVirtualInstance vi on vi.virtual_system_id = sfc.server_id
                            where vi.host_system_id = server_id_in
                                  and sfc.channel_family_id = family.channel_family_id
                              order by vi.modified desc
                          )
                        where rownum <=  free_slots
                );
            else
            -- if the host_server has virt
            -- set all its flex guests to N
                UPDATE rhnServerChannel sc set sc.is_fve = 'N'
                where
                    sc.channel_id in (select cfm.channel_id from rhnChannelFamilyMembers cfm
                                      where cfm.CHANNEL_FAMILY_ID = family.channel_family_id)
                    and sc.is_fve = 'Y'
                    and sc.server_id in
                            (select vi.virtual_system_id  from rhnVirtualInstance vi
                                    where vi.host_system_id = server_id_in);
            end if;

            -- get the current (physical) members of the family
            current_members_calc :=
                rhn_channel.channel_family_current_members(family.channel_family_id,
                                                           org_id_val); -- fixed transposed args

            -- get the max members of the family
            select max_members
            into max_members_val
            from rhnPrivateChannelFamily
            where channel_family_id = family.channel_family_id
            and org_id = org_id_val;

            select fve_max_members
            into max_flex_val
            from rhnPrivateChannelFamily
            where channel_family_id = family.channel_family_id
            and org_id = org_id_val;

            if current_members_calc > max_members_val then
                -- A virtualization_host* ent must have been removed, so we'll
                -- unsubscribe guests from the host first.

                -- hm, i don't think max_members - current_members_calc yielding a negative number
                -- will work w/ rownum, swaping 'em in the body of this if...
                for virt_server in virt_servers_cfam(family.channel_family_id,
                                current_members_calc - max_members_val) loop

                    rhn_channel.unsubscribe_server_from_family(
                                virt_server.virtual_system_id,
                                family.channel_family_id);
                end loop;

                -- if we're still over the limit, which would be odd,
                -- just prune the group to max_members
                --
                -- er... wouldn't we actually have to refresh the values of
                -- current_members_calc and max_members_val to actually ever
                -- *skip this??
                if current_members_calc > max_members_val then
                    -- argh, transposed again?!
                    set_family_count(org_id_val,
                                     family.channel_family_id,
                                     max_members_val, max_flex_val);
                    --TODO calculate this correctly
                end if;

           end if;

            -- update current_members for the family.  This will set the value
            -- to reflect adding/removing the entitlement.
            --
            -- what's the difference of doing this vs the unavoidable set_family_count above?
            rhn_channel.update_family_counts(family.channel_family_id,
                                             org_id_val);

            -- It is possible that the guests belong  to a different org than the host
            -- so we are going to update the family counts in the guests orgs also
            for org in virt_guest_orgs loop
                    rhn_channel.update_family_counts(family.channel_family_id,
                                             org.org_id);
            end loop;
        end loop;

        for a_group_type in group_types loop
          -- get the current *physical* members of the system entitlement type for the org...
          --
          -- unlike channel families, it appears the standard rhnServerGroup.max_members represents
          -- *physical* slots, vs physical+virt ... boy that's confusing...

          select max_members, id
            into max_members_val, sg_id
            from rhnServerGroup
            where group_type = a_group_type.group_type
            and org_id = org_id_val;


      select count(sep.server_id) into current_members_calc
            from rhnServerEntitlementPhysical sep
           where sep.server_group_id = sg_id
             and sep.server_group_type_id = a_group_type.group_type;

          if current_members_calc > max_members_val then
            -- A virtualization_host* ent must have been removed, and we're over the limit, so unsubscribe guests
            for virt_server in virt_servers_sgt(a_group_type.group_type,
                                                current_members_calc - max_members_val) loop
              rhn_entitlements.remove_server_entitlement(virt_server.virtual_system_id, a_group_type.label);

              -- decrement current_members_calc, we'll use it to reset current_members for the group at the end...
              current_members_calc := current_members_calc - 1;
            end loop;

          end if;

          update rhnServerGroup set current_members = current_members_calc
           where org_id = org_id_val
             and group_type = a_group_type.group_type;

          -- I think that's all the house-keeping we have to do...
        end loop;

    end repoll_virt_guest_entitlements;


    function get_server_entitlement (
        server_id_in in number
    ) return ents_array is

        cursor server_groups is
            select    sgt.label
            from    rhnServerGroupType        sgt,
                    rhnServerGroup            sg,
                    rhnServerGroupMembers    sgm
            where    1=1
                and sgm.server_id = server_id_in
                and sg.id = sgm.server_group_id
                and sgt.id = sg.group_type
                and sgt.label in (
                    'sw_mgr_entitled','enterprise_entitled',
                    'provisioning_entitled', 'nonlinux_entitled',
                    'monitoring_entitled', 'virtualization_host',
                                        'virtualization_host_platform'
                    );

         ent_array ents_array;

    begin

      ent_array := ents_array();

        for sg in server_groups loop
         ent_array.extend;
         ent_array(ent_array.count) := sg.label;
        end loop;

        return ent_array;

    end get_server_entitlement;


    -- this desperately needs to be table driven.
    procedure modify_org_service (
        org_id_in in number,
        service_label_in in varchar2,
        enable_in in char
    ) is
        type roles_v is varray(10) of rhnUserGroupType.label%TYPE;
        roles_to_process roles_v;
        cursor roles(role_label_in in varchar2) is
            select    label, id
            from    rhnUserGroupType
            where    label = role_label_in;
        cursor org_roles(role_label_in in varchar2) is
            select    1
            from    rhnUserGroup ug,
                    rhnUserGroupType ugt
            where    ugt.label = role_label_in
                and ug.org_id = org_id_in
                and ugt.id = ug.group_type;

        type ents_v is varray(10) of rhnOrgEntitlementType.label%TYPE;
        ents_to_process ents_v;
        cursor ents(ent_label_in in varchar2) is
            select    label, id
            from    rhnOrgEntitlementType
            where    label = ent_label_in;
        cursor org_ents(ent_label_in in varchar2) is
            select    1
            from    rhnOrgEntitlements oe,
                    rhnOrgEntitlementType oet
            where    oet.label = ent_label_in
                and oe.org_id = org_id_in
                and oet.id = oe.entitlement_id;
        create_row char(1);
    begin
        ents_to_process := ents_v();
        roles_to_process := roles_v();
        -- a bit kludgy, but only for 3.4 really.  Certainly no
        -- worse than the old code...
        if service_label_in = 'enterprise' or
           service_label_in = 'management' then
            ents_to_process.extend;
            ents_to_process(ents_to_process.count) := 'sw_mgr_enterprise';

            roles_to_process.extend;
            roles_to_process(roles_to_process.count) := 'org_admin';

            roles_to_process.extend;
            roles_to_process(roles_to_process.count) := 'system_group_admin';

            roles_to_process.extend;
            roles_to_process(roles_to_process.count) := 'activation_key_admin';

            roles_to_process.extend;
            roles_to_process(roles_to_process.count) := 'org_applicant';
        elsif service_label_in = 'provisioning' then
            ents_to_process.extend;
            ents_to_process(ents_to_process.count) := 'rhn_provisioning';

            roles_to_process.extend;
            roles_to_process(roles_to_process.count) := 'system_group_admin';

            roles_to_process.extend;
            roles_to_process(roles_to_process.count) := 'activation_key_admin';

            roles_to_process.extend;
            roles_to_process(roles_to_process.count) := 'config_admin';
            -- another nasty special case...
            if enable_in = 'Y' then
                ents_to_process.extend;
                ents_to_process(ents_to_process.count) := 'sw_mgr_enterprise';
            end if;
        elsif service_label_in = 'monitoring' then
            ents_to_process.extend;
            ents_to_process(ents_to_process.count) := 'rhn_monitor';

            roles_to_process.extend;
            roles_to_process(roles_to_process.count) := 'monitoring_admin';
        elsif service_label_in = 'virtualization' then
            ents_to_process.extend;
            ents_to_process(ents_to_process.count) := 'rhn_virtualization';

            roles_to_process.extend;
            roles_to_process(roles_to_process.count) := 'config_admin';
        elsif service_label_in = 'virtualization_platform' then
            ents_to_process.extend;
            ents_to_process(ents_to_process.count) := 'rhn_virtualization_platform';
            roles_to_process.extend;
            roles_to_process(roles_to_process.count) := 'config_admin';
    elsif service_label_in = 'nonlinux' then
            ents_to_process.extend;
            ents_to_process(ents_to_process.count) := 'rhn_nonlinux';
            roles_to_process.extend;
            roles_to_process(roles_to_process.count) := 'config_admin';
        end if;

        if enable_in = 'Y' then
            for i in 1..ents_to_process.count loop
                for ent in ents(ents_to_process(i)) loop
                    create_row := 'Y';
                    for oe in org_ents(ent.label) loop
                        create_row := 'N';
                    end loop;
                    if create_row = 'Y' then
                        insert into rhnOrgEntitlements(org_id, entitlement_id)
                            values (org_id_in, ent.id);
                    end if;
                end loop;
            end loop;
            for i in 1..roles_to_process.count loop
                for role in roles(roles_to_process(i)) loop
                    create_row := 'Y';
                    for o_r in org_roles(role.label) loop
                        create_row := 'N';
                    end loop;
                    if create_row = 'Y' then
                        insert into rhnUserGroup(
                                id, name, description, current_members,
                                group_type, org_id
                            ) (
                                select    rhn_user_group_id_seq.nextval,
                                        ugt.name || 's',
                                        ugt.name || 's for Org ' ||
                                            o.name || ' ('|| o.id ||')',
                                        0, ugt.id, o.id
                                from    rhnUserGroupType ugt,
                                        web_customer o
                                where    o.id = org_id_in
                                    and ugt.id = role.id
                            );
                    end if;
                end loop;
            end loop;
        else
            for i in 1..ents_to_process.count loop
                for ent in ents(ents_to_process(i)) loop
                    delete from rhnOrgEntitlements
                     where org_id = org_id_in
                       and entitlement_id = ent.id;
                end loop;
            end loop;
        end if;
    end modify_org_service;

    procedure set_customer_enterprise (
        customer_id_in in number
    ) is
    begin
        modify_org_service(customer_id_in, 'enterprise', 'Y');
    end set_customer_enterprise;

    procedure set_customer_provisioning (
        customer_id_in in number
    ) is
    begin
        modify_org_service(customer_id_in, 'provisioning', 'Y');
    end set_customer_provisioning;

    procedure set_customer_monitoring (
        customer_id_in in number
    ) is
    begin
        modify_org_service(customer_id_in, 'monitoring', 'Y');
    end set_customer_monitoring;

    procedure set_customer_nonlinux (
        customer_id_in in number
    ) is
    begin
        modify_org_service(customer_id_in, 'nonlinux', 'Y');
    end set_customer_nonlinux;

    procedure unset_customer_enterprise (
        customer_id_in in number
    ) is
    begin
        modify_org_service(customer_id_in, 'enterprise', 'N');
    end unset_customer_enterprise;

    procedure unset_customer_provisioning (
        customer_id_in in number
    ) is
    begin
        modify_org_service(customer_id_in, 'provisioning', 'N');
    end unset_customer_provisioning;

    procedure unset_customer_monitoring (
        customer_id_in in number
    ) is
    begin
        modify_org_service(customer_id_in, 'monitoring', 'N');
    end unset_customer_monitoring;

    procedure unset_customer_nonlinux (
        customer_id_in in number
    ) is
    begin
        modify_org_service(customer_id_in, 'nonlinux', 'N');
    end unset_customer_nonlinux;

    -- *******************************************************************
    -- PROCEDURE: prune_group
    -- Unsubscribes servers consuming physical slots that over the org's
    --   limit.
    -- Called by: set_group_count, repoll_virt_guest_entitlements
    -- *******************************************************************
    procedure prune_group (
        group_id_in in number,
        type_in in char,
        quantity_in in number,
                update_family_countsYN in number := 1
    ) is
        cursor usergroups is
            select    user_id, user_group_id, ugt.label
            from    rhnUserGroupType    ugt,
                    rhnUserGroup        ug,
                    rhnUserGroupMembers    ugm
            where    1=1
                and ugm.user_group_id = group_id_in
                and ugm.user_id in (
                    select    user_id
                    from    (
                        select    rownum row_number,
                                user_id,
                                time
                        from    (
                            select    user_id,
                                    modified time
                            from    rhnUserGroupMembers
                            where    user_group_id = group_id_in
                            order by time asc
                        )
                    )
                    where    row_number > quantity_in
                )
                and ugm.user_group_id = ug.id
                and ug.group_type = ugt.id;
        cursor servergroups is
           select  server_id, server_group_id, sgt.id as group_type_id, sgt.label
            from    rhnServerGroupType              sgt,
                            rhnServerGroup                  sg,
                            rhnServerGroupMembers   sgm
            where   1=1
                    and sgm.server_group_id = group_id_in
                    and sgm.server_id in (
                            select  server_id
                            from    (
                                    select  rownum row_number,
                                                    server_id,
                                                    time
                                    from    (
                                            select  sep.server_id,
                                                    sep.modified time
                                            from
                                                rhnServerEntitlementPhysical sep
                                            where
                                                sep.server_group_id = group_id_in
                                            order by time asc
                                    )
                            )
                            where   row_number > quantity_in
                    )
                    and sgm.server_group_id = sg.id
                    and sg.group_type = sgt.id;
      type_is_base char;
    begin
        if type_in = 'U' then
            update        rhnUserGroup
                set        max_members = quantity_in
                where    id = group_id_in;

            for ug in usergroups loop
                rhn_user.remove_from_usergroup(ug.user_id, ug.user_group_id);
            end loop;
        elsif type_in = 'S' then
            update        rhnServerGroup
                set        max_members = quantity_in
                where    id = group_id_in;

            for sg in servergroups loop
                remove_server_entitlement(sg.server_id, sg.label);

            select is_base
            into type_is_base
            from rhnServerGroupType sgt
            where sgt.id = sg.group_type_id;

            -- if we're removing a base ent, then be sure to
            -- remove the server's channel subscriptions.
            if ( type_is_base = 'Y' ) then
                   rhn_channel.clear_subscriptions(sg.server_id,
                                        update_family_countsYN => update_family_countsYN);
            end if;

            end loop;
        end if;
    end prune_group;

    -- *******************************************************************
    -- PROCEDURE: assign_system_entitlement
    --
    -- Moves system entitlements from from_org_id_in to to_org_id_in.
    -- Can raise not_enough_entitlements_in_base_org if from_org_id_in
    -- does not have enough entitlements to cover the move.
    -- Takes care of unentitling systems if necessary by calling
    -- set_group_count
    -- *******************************************************************
    procedure assign_system_entitlement(
        group_label_in in varchar2,
        from_org_id_in in number,
        to_org_id_in in number,
        quantity_in in number
    )
    is
        prev_ent_count number;
    to_org_prev_ent_count number;
        new_ent_count number;
    new_quantity number;
        group_type number;
    begin

        begin
            select max_members
            into prev_ent_count
            from rhnServerGroupType sgt,
                 rhnServerGroup sg
            where sg.org_id = from_org_id_in
              and sg.group_type = sgt.id
              and sgt.label = group_label_in;
        exception
            when NO_DATA_FOUND then
                rhn_exception.raise_exception(
                              'not_enough_entitlements_in_base_org');
        end;

        begin
            select max_members
            into to_org_prev_ent_count
            from rhnServerGroupType sgt,
                 rhnServerGroup sg
            where sg.org_id = to_org_id_in
              and sg.group_type = sgt.id
              and sgt.label = group_label_in;
        exception
            when NO_DATA_FOUND then
                to_org_prev_ent_count := 0;
        end;

        begin
            select id
            into group_type
            from rhnServerGroupType
            where label = group_label_in;
        exception
            when NO_DATA_FOUND then
                rhn_exception.raise_exception(
                              'invalid_server_group');
        end;

        new_ent_count := prev_ent_count - quantity_in;

        if prev_ent_count > new_ent_count then
            new_quantity := to_org_prev_ent_count + quantity_in;
        end if;

        if new_ent_count < 0 then
            rhn_exception.raise_exception(
                          'not_enough_entitlements_in_base_org');
        end if;


        rhn_entitlements.set_group_count(from_org_id_in,
                                         'S',
                                         group_type,
                                         new_ent_count);

        rhn_entitlements.set_group_count(to_org_id_in,
                                         'S',
                                         group_type,
                                         new_quantity);

        -- Create or delete the entries in rhnOrgEntitlementType
        if group_label_in = 'enterprise_entitled' then
            if new_quantity > 0 then
                set_customer_enterprise(to_org_id_in);
            else
                unset_customer_enterprise(to_org_id_in);
            end if;
        end if;

        if group_label_in = 'provisioning_entitled' then
            if new_quantity > 0 then
                set_customer_provisioning(to_org_id_in);
            else
                unset_customer_provisioning(to_org_id_in);
            end if;
        end if;

        if group_label_in = 'monitoring_entitled' then
            if new_quantity > 0 then
                set_customer_monitoring(to_org_id_in);
            else
                unset_customer_monitoring(to_org_id_in);
            end if;
        end if;

    end assign_system_entitlement;

    -- *******************************************************************
    -- PROCEDURE: assign_channel_entitlement
    --
    -- Moves channel entitlements from from_org_id_in to to_org_id_in.
    -- Can raise not_enough_entitlements_in_base_org if from_org_id_in
    -- does not have enough entitlements to cover the move.
    -- Takes care of unentitling systems if necessary by calling
    -- set_family_count
    -- *******************************************************************
    procedure assign_channel_entitlement(
        channel_family_label_in in varchar2,
        from_org_id_in in number,
        to_org_id_in in number,
        quantity_in in number,
        flex_in in number
    )
    is
        from_org_prev_ent_count number;
        from_org_prev_ent_count_flex number;
        new_ent_count number;
        new_ent_count_flex number;
        to_org_prev_ent_count number;
        to_org_prev_ent_count_flex number;
        new_quantity number;
        new_flex number;
        cfam_id       number;
    begin

        begin
            select max_members
            into from_org_prev_ent_count
            from rhnChannelFamily cf,
                 rhnPrivateChannelFamily pcf
            where pcf.org_id = from_org_id_in
              and pcf.channel_family_id = cf.id
              and cf.label = channel_family_label_in;
        exception
            when NO_DATA_FOUND then
                rhn_exception.raise_exception(
                              'not_enough_entitlements_in_base_org');
        end;

        begin
            select max_members
            into to_org_prev_ent_count
            from rhnChannelFamily cf,
                 rhnPrivateChannelFamily pcf
            where pcf.org_id = to_org_id_in
              and pcf.channel_family_id = cf.id
              and cf.label = channel_family_label_in;
        exception
            when NO_DATA_FOUND then
                to_org_prev_ent_count := 0;
        end;

        begin
            select fve_max_members
            into from_org_prev_ent_count_flex
            from rhnChannelFamily cf,
                 rhnPrivateChannelFamily pcf
            where pcf.org_id = from_org_id_in
              and pcf.channel_family_id = cf.id
              and cf.label = channel_family_label_in;
        exception
            when NO_DATA_FOUND then
                rhn_exception.raise_exception(
                              'not_enough_flex_entitlements_in_base_org');
        end;

        begin
            select fve_max_members
            into to_org_prev_ent_count_flex
            from rhnChannelFamily cf,
                 rhnPrivateChannelFamily pcf
            where pcf.org_id = to_org_id_in
              and pcf.channel_family_id = cf.id
              and cf.label = channel_family_label_in;
        exception
            when NO_DATA_FOUND then
                to_org_prev_ent_count_flex := 0;
        end;

        begin
            select id
            into cfam_id
            from rhnChannelFamily
            where label = channel_family_label_in;
        exception
            when NO_DATA_FOUND then
                rhn_exception.raise_exception(
                              'invalid_channel_family');
        end;

        new_ent_count := from_org_prev_ent_count - quantity_in;
        new_ent_count_flex := from_org_prev_ent_count_flex - flex_in;

        if from_org_prev_ent_count >= new_ent_count then
            new_quantity := to_org_prev_ent_count + quantity_in;
       end if;

       if from_org_prev_ent_count_flex >= new_ent_count_flex then
            new_flex := to_org_prev_ent_count_flex + flex_in;
       end if;


        if new_ent_count < 0 then
            rhn_exception.raise_exception(
                          'not_enough_entitlements_in_base_org');
        end if;

        if new_ent_count_flex < 0 then
            rhn_exception.raise_exception(
                          'not_enough_flex_entitlements_in_base_org');
        end if;



        rhn_entitlements.set_family_count(from_org_id_in, cfam_id,
                                           new_ent_count, new_ent_count_flex);

        rhn_entitlements.set_family_count(to_org_id_in,
                                          cfam_id,
                                          new_quantity, new_flex);

    end assign_channel_entitlement;

    -- *******************************************************************
    -- PROCEDURE: activate_system_entitlement
    --
    -- Sets the values in rhnServerGroup for a given rhnServerGroupType.
    --
    -- Calls: set_group_count to update, prune, or create the group.
    -- Called by: the code that activates a satellite cert.
    --
    -- Raises not_enough_entitlements_in_base_org if all entitlements
    -- in the org are used so the free entitlements would not cover
    -- the difference when descreasing the number of entitlements.
    -- *******************************************************************
    procedure activate_system_entitlement(
        org_id_in in number,
        group_label_in in varchar2,
        quantity_in in number
    )
    is
        prev_ent_count number;
        prev_ent_count_sum number;
        group_type number;
    begin

        -- Fetch the current entitlement count for the org
        -- into prev_ent_count
        begin
            select current_members
            into prev_ent_count
            from rhnServerGroupType sgt,
                 rhnServerGroup sg
            where sg.group_type = sgt.id
              and sgt.label = group_label_in
              and sg.org_id = org_id_in;
        exception
            when NO_DATA_FOUND then
                prev_ent_count := 0;
        end;

        begin
            select id
            into group_type
            from rhnServerGroupType
            where label = group_label_in;
        exception
            when NO_DATA_FOUND then
                rhn_exception.raise_exception(
                              'invalid_server_group');
        end;

        -- If we're setting the total entitlemnt count to a lower value,
        -- and that value is less than the allocated count in this org,
        -- we need to raise an exception.
        if quantity_in < prev_ent_count then
            rhn_exception.raise_exception(
                          'not_enough_entitlements_in_base_org');
        else
            -- don't update family counts after every server
            -- will do bulk update afterwards
            rhn_entitlements.set_group_count(org_id_in,
                                             'S',
                                             group_type,
                                             quantity_in,
                                             update_family_countsYN => 0);
            -- bulk update family counts
            rhn_channel.update_group_family_counts(group_label_in, org_id_in);
        end if;


    end activate_system_entitlement;

    -- *******************************************************************
    -- PROCEDURE: activate_channel_entitlement
    --
    -- Calls: set_family_count to update, prune, or create the family
    --        permission bucket.
    -- Called by: the code that activates a satellite cert.
    --
    -- Raises not_enough_entitlements_in_base_org if there are not enough
    -- entitlements in the org to cover the difference when you are
    -- descreasing the number of entitlements.
    --
    -- The backend code in Python is expected to do whatever arithmetics
    -- is needed.
    -- *******************************************************************
    procedure activate_channel_entitlement(
        org_id_in in number,
        channel_family_label_in in varchar2,
        quantity_in in number,
        flex_in in number

    )
    is
        prev_ent_count number;
        prev_flex_count number;
        prev_ent_count_sum number;
        cfam_id number;
        reduce_quantity number;
        total_flex_capable number;
        cursor to_convert_reg (channel_family_id_val in number, org_id_in in number, quantity in number)
                is
                     select SC.server_id
                     from rhnServerChannel SC inner join
                          rhnServer S on S.id = SC.server_id
                     where
                         is_fve = 'Y'
                         and S.org_id = org_id_in
                         and SC.channel_id in
                         (select cfm.channel_id from rhnChannelFamilyMembers cfm
                             where cfm.CHANNEL_FAMILY_ID = channel_family_id_val)
                          and rownum <= quantity;
         cursor to_convert_flex (channel_family_id_val in number, org_id_in in number, quantity in number)
                 is
                   select server_id
                   from rhnServerFveCapable
                       where SERVER_ORG_ID = org_id_in and
                             channel_family_id = cfam_id and
                             rownum <= quantity;

    begin

        -- Fetch the current entitlement count for the org
        -- into prev_ent_count
        begin
            select current_members
            into prev_ent_count
            from rhnChannelFamily cf,
                 rhnPrivateChannelFamily pcf
            where pcf.org_id = org_id_in
              and pcf.channel_family_id = cf.id
              and cf.label = channel_family_label_in;
        exception
            when NO_DATA_FOUND then
                prev_ent_count := 0;
        end;

        begin
            select pcf.fve_current_members
            into prev_flex_count
            from rhnChannelFamily cf,
                 rhnPrivateChannelFamily pcf
            where pcf.org_id = org_id_in
              and pcf.channel_family_id = cf.id
              and cf.label = channel_family_label_in;
        exception
            when NO_DATA_FOUND then
                prev_flex_count := 0;
        end;


        begin
            select id
            into cfam_id
            from rhnChannelFamily
            where label = channel_family_label_in;
        exception
            when NO_DATA_FOUND then
                rhn_exception.raise_exception(
                              'invalid_channel_family');
        end;

        -- if there are too few flex entitlements
        if flex_in < prev_flex_count then
            -- and if the extra we need is less than or equal to our extra regular entitlements
            if prev_flex_count - flex_in <= quantity_in - prev_ent_count then
                   reduce_quantity := prev_flex_count - flex_in;
                   -- We need to convert some systems from flex guest to regular
                   for system in to_convert_reg(cfam_id, org_id_in, reduce_quantity) loop
                      --rhn_channel.convert_to_regular(system.server_id, cfam_id);
                      UPDATE rhnServerChannel sc set sc.is_fve = 'N'
                           where sc.server_id = system.server_id
                                 and sc.channel_id in (select cfm.channel_id
                                                          from rhnChannelFamilyMembers cfm
                                                          where cfm.channel_family_id = cfam_id);
                   end loop;

                   --reset previous counts
                   prev_ent_count := prev_ent_count + reduce_quantity;
                   prev_flex_count := prev_flex_count - reduce_quantity;
            else
                rhn_exception.raise_exception(
                          'not_enough_flex_entitlements_in_base_org');
            end if;
        end if;

        -- if there are too few regular entitlements, and extra flex entitlements
        if quantity_in < prev_ent_count and prev_flex_count < flex_in then
                -- how many flex-capable systems (that aren't using flex) do we have
                select count(*)
                   into total_flex_capable
                   from rhnServerFveCapable
                       where SERVER_ORG_ID = org_id_in and
                             channel_family_id = cfam_id;
                -- if we have enough flex capable machines that is at least
                --   as many as what we are over on
                if total_flex_capable >= prev_ent_count - quantity_in then
                    reduce_quantity := prev_ent_count - quantity_in;
                    for system in to_convert_flex(cfam_id, org_id_in, reduce_quantity) loop
--                          rhn_channel.convert_to_fve(system.server_id, cfam_id);
                        UPDATE rhnServerChannel sc set sc.is_fve = 'Y'
                           where sc.server_id = system.server_id
                                 and sc.channel_id in (select cfm.channel_id
                                                          from rhnChannelFamilyMembers cfm
                                                          where cfm.channel_family_id = cfam_id);
                    end loop;
                    prev_ent_count := prev_ent_count - reduce_quantity;
                    prev_flex_count := prev_flex_count + reduce_quantity;
                end if;
        end if;




        -- If we're setting the total entitlemnt count to a lower value,
        -- and that value is less than the count in that one org,
        -- we need to raise an exception.
        if quantity_in < prev_ent_count then
            rhn_exception.raise_exception(
                          'not_enough_entitlements_in_base_org');
        else
            -- even if we've manually converted systems to/from flex above
            -- set_family_count should call update_family_counts, to reset
            -- current used slots
            rhn_entitlements.set_family_count(org_id_in, cfam_id,
                                              quantity_in, flex_in);
        end if;

    end activate_channel_entitlement;


    procedure set_group_count (
        customer_id_in in number,
        type_in in char,
        group_type_in in number,
        quantity_in in number,
                update_family_countsYN in number := 1
    ) is
        group_id number;
        quantity number;
    begin
        quantity := quantity_in;
        if quantity is not null and quantity < 0 then
            quantity := 0;
        end if;

        if type_in = 'U' then
            select    rug.id
            into    group_id
            from    rhnUserGroup rug
            where    1=1
                and rug.org_id = customer_id_in
                and rug.group_type = group_type_in;
        elsif type_in = 'S' then
            select    rsg.id
            into    group_id
            from    rhnServerGroup rsg
            where    1=1
                and rsg.org_id = customer_id_in
                and rsg.group_type = group_type_in;
        end if;

        rhn_entitlements.prune_group(
            group_id,
            type_in,
            quantity,
                        update_family_countsYN
        );
    exception
        when no_data_found then
            if type_in = 'U' then
                insert into rhnUserGroup (
                        id, name, description, max_members, current_members,
                        group_type, org_id, created, modified
                    ) (
                        select    rhn_user_group_id_seq.nextval, name, name,
                                quantity, 0, id, customer_id_in,
                                sysdate, sysdate
                        from    rhnUserGroupType
                        where    id = group_type_in
                );
            elsif type_in = 'S' then
                insert into rhnServerGroup (
                        id, name, description, max_members, current_members,
                        group_type, org_id, created, modified
                    ) (
                        select    rhn_server_group_id_seq.nextval, name, name,
                                quantity, 0, id, customer_id_in,
                                sysdate, sysdate
                        from    rhnServerGroupType
                        where    id = group_type_in
                );
            end if;
    end set_group_count;

    -- *******************************************************************
    -- PROCEDURE: prune_family
    -- Unsubscribes servers consuming physical slots from the channel family
    --   that are over the org's limit.
    -- Called by: set_family_count
    -- *******************************************************************
    procedure prune_family (
        customer_id_in in number,
        channel_family_id_in in number,
        quantity_in in number,
        flex_in in number
    ) is
       is_fve_in char;
       tmp_quantity number;

        cursor serverchannels is
            select    sc.server_id,
                    sc.channel_id
            from    rhnServerChannel sc,
                    rhnChannelFamilyMembers cfm
            where    1=1
                and cfm.channel_family_id = channel_family_id_in
                and cfm.channel_id = sc.channel_id
                and server_id in (
                    select    server_id
                      from    (
                        select server_id, time, rownum row_number
                        from    (
                            select rs.id  server_id, rcfm.modified time
                            from    rhnServerChannel         rsc,
                                    rhnChannelFamilyMembers  rcfm,
                                    rhnServer                rs
                            where    1=1
                                and rs.org_id = customer_id_in
                                and rs.id = rsc.server_id
                                and rsc.channel_id = rcfm.channel_id
                                and rcfm.channel_family_id =  channel_family_id_in
                                and rsc.is_fve = is_fve_in
                                -- we only want to grab servers consuming
                                -- physical slots.
                                and exists (
                                    select 1
                                    from rhnChannelFamilyServerPhysical cfsp
                                    where cfsp.server_id = rs.id
                                    and cfsp.channel_family_id =
                                        channel_family_id_in
                                    )
                            order by time asc
                        )
                    )
                    where row_number > tmp_quantity
                );
    begin
        -- if we get a null customer_id, this is completely bogus.
        if customer_id_in is null then
            return;
        end if;

        tmp_quantity := quantity_in;
        is_fve_in := 'N';

        for sc in serverchannels loop
            rhn_channel.unsubscribe_server(sc.server_id, sc.channel_id, 1, 1,
                                                       update_family_countsYN => 0);

        tmp_quantity := flex_in;
        is_fve_in := 'Y';
        for sc in serverchannels loop
            rhn_channel.unsubscribe_server(sc.server_id, sc.channel_id, 1, 1,
                                                        update_family_countsYN => 0);
        end loop;



        end loop;
                rhn_channel.update_family_counts(channel_family_id_in, customer_id_in);
    end prune_family;

    procedure set_family_count (
        customer_id_in in number,
        channel_family_id_in in number,
        quantity_in in number,
        flex_in in number
    ) is
        cursor privperms is
            select    1
            from    rhnPrivateChannelFamily
            where    org_id = customer_id_in
                and channel_family_id = channel_family_id_in;
        cursor pubperms is
            select    o.id org_id
            from    web_customer o,
                    rhnPublicChannelFamily pcf
            where    pcf.channel_family_id = channel_family_id_in;
        quantity number;
        done number := 0;
        flex number;
    begin
        quantity := quantity_in;
        if quantity is not null and quantity < 0 then
            quantity := 0;
        end if;
        flex := flex_in;
        if flex is not null and flex < 0 then
            flex := 0;
        end if;


        if customer_id_in is not null then
            for perm in privperms loop
                rhn_entitlements.prune_family(customer_id_in, channel_family_id_in,
                    quantity, flex);

                if quantity is null and flex is null then
                    delete from rhnPrivateChannelFamily
                        where org_id = customer_id_in
                            and channel_family_id = channel_family_id_in;
                else
                    update rhnPrivateChannelFamily
                        set max_members = quantity
                        where org_id = customer_id_in
                            and channel_family_id = channel_family_id_in;

                   update rhnPrivateChannelFamily
                        set fve_max_members = flex
                        where org_id = customer_id_in
                            and channel_family_id = channel_family_id_in;
                end if;
                return;
            end loop;

            insert into rhnPrivateChannelFamily (
                    channel_family_id, org_id, max_members, current_members, fve_max_members, fve_current_members
                ) values (
                    channel_family_id_in, customer_id_in, quantity, 0, flex, 0 );
            return;
        end if;

        for perm in pubperms loop
            if quantity = 0 then
                rhn_entitlements.prune_family(
                    perm.org_id,
                    channel_family_id_in,
                    quantity,
                    flex
                );
                if done = 0 then
                    delete from rhnPublicChannelFamily
                        where channel_family_id = channel_family_id_in;
                end if;
            end if;
            done := 1;
        end loop;
        -- if done's not 1, then we don't have any entitlements
        if done != 1 then
            insert into rhnPublicChannelFamily (
                    channel_family_id
                ) values (
                    channel_family_id_in
                );
        end if;
    end set_family_count;

    -- this expects quantity_in to be the number of available slots, not the
    -- max_members of the server group.  If you give it too many, it'll fail
    -- and raise servergroup_max_members.
    -- We should NEVER run this unless we're SURE that we won't
    -- be violating the max.
    procedure entitle_last_modified_servers (
        customer_id_in in number,
        type_label_in in varchar2,
        quantity_in in number
    ) is
        -- find the servers that aren't currently in slots
        cursor servers(cid_in in number, quant_in in number) is
            select    server_id
            from    (
                        select    rownum row_number,
                                server_id
                        from    (
                                    select    rs.id server_iD
                                    from    rhnServer rs
                                    where    1=1
                                        and rs.org_id = cid_in
                                        and not exists (
                                            select    1
                                            from    rhnServerGroup sg,
                                                    rhnServerGroupMembers rsgm
                                            where    rsgm.server_id = rs.id
                                                and rsgm.server_group_id = sg.id
                                                and sg.group_type is not null
                                        )
                                        and not exists (
                                            select 1
                                            from rhnVirtualInstance vi
                                            where vi.virtual_system_id =
                                                  rs.id
                                        )                                                                           order by modified desc
                                )
                    )
            where    row_number <= quant_in;
    begin
        for server in servers(customer_id_in, quantity_in) loop
            rhn_entitlements.entitle_server(server.server_id, type_label_in);
        end loop;
    end entitle_last_modified_servers;

    procedure subscribe_newest_servers (
        customer_id_in in number
    ) is
        -- find servers without base channels
        cursor servers(cid_in in number) is
            select    s.id
            from    rhnServer            s
            where    1=1
                and s.org_id = cid_in
                and not exists (
                        select 1
                        from    rhnChannel            c,
                                rhnServerChannel    sc
                        where    sc.server_id = s.id
                            and sc.channel_id = c.id
                            and c.parent_channel is null
                    )
                and not exists (
                        select 1
                        from rhnVirtualInstance vi
                        where vi.virtual_system_id = s.id
                    )
            order by s.modified desc;
        channel_id number;
    begin
        for server in servers(customer_id_in) loop
            channel_id := rhn_channel.guess_server_base(server.id);
            if channel_id is not null then
                begin
                    rhn_channel.subscribe_server(server.id, channel_id);
                    commit;
                -- exception is really channel_family_no_subscriptions
                exception
                    when others then
                        null;
                end;
            end if;
        end loop;
    end subscribe_newest_servers;
end rhn_entitlements;
/
show errors
 070701000008E4000081B400000000000000000000000167AE111400002884000000000000000000000000000000000000006200000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/317-rhn_server.sql create or replace
procedure delete_server (
	server_id_in in number
) is
	cursor servergroups is
		select	server_id, server_group_id
		from	rhnServerGroupMembers sgm
		where	sgm.server_id = server_id_in;
	cursor configchannels is
		select	cc.id
		from	rhnConfigChannel cc,
			rhnConfigChannelType cct,
			rhnServerConfigChannel scc
		where	1=1
			and scc.server_id = server_id_in
			and scc.config_channel_id = cc.id
			-- these config channel types are reserved
			-- for use by a single server, so we don't
			-- need to check for other servers subscribed
			and cct.label in
				('local_override','server_import')
			and cct.id = cc.confchan_type_id;
        type filelistsid_t is table of rhnServerPreserveFileList.file_list_id%type;
        filelistsid_c filelistsid_t;

        type probesid_t is table of rhn_check_probe.probe_id%type;
        probesid_c probesid_t;

    is_virt number := 0;
begin
	rhn_channel.delete_server_channels(server_id_in);
	-- rhn_channel.clear_subscriptions(server_id_in);

        -- filelists
	select	spfl.file_list_id id bulk collect into filelistsid_c
	  from	rhnServerPreserveFileList spfl
	 where	spfl.server_id = server_id_in
			and not exists (
				select	1
				from	rhnServerPreserveFileList
				where	file_list_id = spfl.file_list_id
					and server_id != server_id_in
				union
				select	1
				from	rhnKickstartPreserveFileList
				where	file_list_id = spfl.file_list_id
			);
        if filelistsid_c.first is not null then
            forall i in filelistsid_c.first..filelistsid_c.last
                delete from rhnFileList where id = filelistsid_c(i);
        end if;

	for configchannel in configchannels loop
		rhn_config.delete_channel(configchannel.id);
	end loop;

      select count(1) into is_virt
        from rhnServerEntitlementView
       where server_id = server_id_in
         and label in ('virtualization_host', 'virtualization_host_platform')
         and rownum <= 1;

	for sgm in servergroups loop
		rhn_server.delete_from_servergroup(
			sgm.server_id, sgm.server_group_id);
	end loop;

    if is_virt = 1 then
        rhn_entitlements.repoll_virt_guest_entitlements(server_id_in);
    end if;

	-- we're handling this instead of letting an "on delete
	-- set null" do it so that we don't run the risk
	-- of setting off the triggers and killing us with a
	-- mutating table

	-- this is merge of two single updates:
        --  update ... set old_server_id = null where old_server_id = server_id_in;
        --  update ... set new_server_id = null where new_server_id = server_id_in;
        -- so we scan rhnKickstartSession table only once
	update rhnKickstartSession
		set old_server_id = case when old_server_id = server_id_in then null else old_server_id end,
		    new_server_id = case when new_server_id = server_id_in then null else new_server_id end
		where old_server_id = server_id_in 
		   or new_server_id = server_id_in;

	rhn_channel.clear_subscriptions(server_id_in,1);

    	-- A little complicated here, but the goal is to
	-- delete records from rhnVirtualInstace only if we don't
	-- care about them anymore.  We don't care about records
	-- in rhnVirtualInstance if we are deleting the host
	-- system and the virtual system is already null, or
	-- vice-versa.  We *do* care about them if either the
	-- host or virtual system is still registered because we
	-- still want them to show up in the UI.
    -- If there's a newer row in rhnVirtualInstance with the same
    -- uuid, this guest must have been re-registered, so we can clean
    -- this data up.
				
        delete from rhnVirtualInstance vi
	      where (host_system_id = server_id_in and virtual_system_id is null)
                 or (virtual_system_id = server_id_in and host_system_id is null)
                 or (vi.virtual_system_id = server_id_in and vi.modified < (select max(vi2.modified)
                    from rhnVirtualInstance vi2 where vi2.uuid = vi.uuid));
						
        -- this is merge of two single updates:
        --  update ... set host_system_id = null where host_system_id = server_id_in;
        --  update ... set virtual_system_id = null where virtual_system_id = server_id_in;
        -- so we scan rhnVirtualInstance table only once
        update rhnVirtualInstance
	   set host_system_id = case when host_system_id = server_id_in then null else host_system_id end,
	       virtual_system_id = case when virtual_system_id = server_id_in then null else virtual_system_id end
	 where host_system_id = server_id_in
	    or virtual_system_id = server_id_in;
		
        -- this is merge of two single updates:
        --  update ... set old_host_system_id = null when old_host_system_id = server_id_in;
        --  update ... set new_host_system_id = null when new_host_system_id = server_id_in;
        -- so we scan rhnVirtualInstanceEventLog table only once
	update rhnVirtualInstanceEventLog
	   set old_host_system_id = case when old_host_system_id = server_id_in then null else old_host_system_id end,
               new_host_system_id = case when new_host_system_id = server_id_in then null else new_host_system_id end
         where old_host_system_id = server_id_in
            or new_host_system_id = server_id_in;
		 
	-- We're deleting everything with a foreign key to rhnServer
	-- here, now.  I'm hoping this will help aleviate our deadlock
	-- problem.

	delete from rhnActionConfigChannel where server_id = server_id_in;
	delete from rhnActionConfigRevision where server_id = server_id_in;
	delete from rhnActionPackageRemovalFailure where server_id = server_id_in;
	delete from rhnClientCapability where server_id = server_id_in;
	delete from rhnCpu where server_id = server_id_in;
	-- there's still a cascade here, because the constraint keeps the
	-- table locked for too long to rebuild it.  Ugh...
	delete from rhnDevice where server_id = server_id_in;
	delete from rhnProxyInfo where server_id = server_id_in;
	delete from rhnRam where server_id = server_id_in;
	delete from rhnRegToken where server_id = server_id_in;
	delete from rhnSatelliteInfo where server_id = server_id_in;
	-- this cascades to rhnActionConfigChannel and rhnActionConfigFileName
	delete from rhnServerAction where server_id = server_id_in;
	delete from rhnServerActionPackageResult where server_id = server_id_in;
	delete from rhnServerActionScriptResult where server_id = server_id_in;
	delete from rhnServerActionVerifyResult where server_id = server_id_in;
	delete from rhnServerActionVerifyMissing where server_id = server_id_in;
	-- counts are handled above.  this should be a delete_ function.
	delete from rhnServerChannel where server_id = server_id_in;
	delete from rhnServerConfigChannel where server_id = server_id_in;
	delete from rhnServerCustomDataValue where server_id = server_id_in;
	delete from rhnServerDMI where server_id = server_id_in;
	delete from rhnServerEvent where server_id = server_id_in;
	delete from rhnServerHistory where server_id = server_id_in;
	delete from rhnServerInfo where server_id = server_id_in;
	delete from rhnServerInstallInfo where server_id = server_id_in;
	delete from rhnServerLocation where server_id = server_id_in;
	delete from rhnServerLock where server_id = server_id_in;
	delete from rhnServerNeededCache where server_id = server_id_in;
	delete from rhnServerNetwork where server_id = server_id_in;
	delete from rhnServerNotes where server_id = server_id_in;
	-- I'm not removing the foreign key from rhnServerPackage; that'll
	-- take forever.  Do the delete anyway.
	delete from rhnServerPackage where server_id = server_id_in;
	delete from rhnServerTokenRegs where server_id = server_id_in;
	delete from rhnSnapshotTag where server_id = server_id_in;
	-- this cascades to:
	--   rhnSnapshotChannel, rhnSnapshotConfigChannel, rhnSnapshotPackage, 
	--   rhnSnapshotConfigRevision, rhnSnapshotServerGroup, 
	--   rhnSnapshotTag.
	-- We may want to consider delete_snapshot() at some point, but
	--   I don't think we need to yet.
	delete from rhnSnapshot where server_id = server_id_in;
	delete from rhnUserServerPrefs where server_id = server_id_in;
	-- hrm, this one's interesting... we _probably_ should delete
	-- everything for the parent server_id when we delete the proxy,
	-- but we don't currently.
	delete from rhnServerPath where server_id_in in (server_id, proxy_server_id);
	delete from rhnUserServerPerms where server_id = server_id_in;

	delete from rhnServerNetInterface where server_id = server_id_in;
	delete from rhn_server_monitoring_info where recid = server_id_in;

	delete from rhnAppInstallSession where server_id = server_id_in;
	delete from rhnServerUuid where server_id = server_id_in;
    -- We delete all the probes running directly against this system
    -- and any probes that were using this Server as a Proxy Scout.
     SELECT CP.probe_id bulk collect into probesid_c
       FROM rhn_check_probe CP  
      WHERE CP.host_id = server_id_in
         OR CP.sat_cluster_id in
    (SELECT SN.sat_cluster_id
       FROM rhn_sat_node SN
      WHERE SN.server_id = server_id_in);

    if probesid_c.first is not null then
        FORALL i IN probesid_c.first..probesid_c.last
            DELETE FROM rhn_probe_state PS WHERE PS.probe_id = probesid_c(i);
        FORALL i IN probesid_c.first..probesid_c.last
            DELETE FROM rhn_probe P  WHERE P.recid = probesid_c(i);
        FORALL i IN probesid_c.first..probesid_c.last
            DELETE /*+index(time_series time_series_probe_id_idx)*/
            FROM time_series
            WHERE substr(o_id, instr(o_id, '-') + 1,
                (instr(o_id, '-', instr(o_id, '-') + 1) - instr(o_id, '-'))	- 1) = probesid_c(i);
    end if;

	delete from rhn_check_probe where host_id = server_id_in;
	delete from rhn_host_probe where host_id = server_id_in;

    delete from rhn_sat_cluster where recid in
      ( select sat_cluster_id from rhn_sat_node where server_id = server_id_in );

	delete from rhn_sat_node where server_id = server_id_in;

    delete from rhnPushClient where server_id = server_id_in;
	
	-- now get rhnServer itself.
	delete
	from	rhnServer
		where id = server_id_in;

	delete
	from	rhnSet
	where	1=1
		and user_id in (
			select	wc.id
			from	rhnServer rs,
				web_contact wc
			where	rs.id = server_id_in
				and rs.org_id = wc.org_id
		)
		and label = 'system_list'
		and element = server_id_in;
end delete_server;
/
show errors;
070701000008E5000081B400000000000000000000000167AE1114000000A0000000000000000000000000000000000000007F00000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/320-rhnKickstartCommandName-iscsi-iscsiname.sql    
update rhnKickstartCommandName set sort_order = 40 where name = 'iscsiname';
update rhnKickstartCommandName set sort_order = 41 where name = 'iscsi';
commit;

070701000008E6000081B400000000000000000000000167AE111400000264000000000000000000000000000000000000007500000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/401-add-missing-cascade-on-delete.sql  
alter table rhnerratanotificationqueue drop constraint rhn_enqueue_cid_fk;
alter table rhnerratanotificationqueue add constraint rhn_enqueue_cid_fk foreign key (channel_id) references rhnchannel(id) on delete cascade;

alter table rhnerrataqueue drop constraint rhn_equeue_cid_fk;
alter table rhnerrataqueue add constraint rhn_equeue_cid_fk foreign key (channel_id) references rhnchannel(id) on delete cascade;

alter table rhnreleasechannelmap drop constraint rhn_rcm_cid_fk;
alter table rhnreleasechannelmap add constraint rhn_rcm_cid_fk foreign key (channel_id) references rhnchannel(id) on delete cascade;

070701000008E7000081B400000000000000000000000167AE111400000514000000000000000000000000000000000000006B00000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/402-rhnServerNeededView.sql    CREATE OR REPLACE VIEW
rhnServerNeededView
(
    org_id,
    server_id,
    errata_id,
    package_id,
    package_name_id,
    channel_id
)
AS
SELECT s.org_id,
       sp.server_id,
       x.errata_id,
       up.id,
       up.name_id,
       x.channel_id
    FROM rhnServer s
        join (SELECT sp_sp.server_id, sp_sp.name_id, sp_sp.package_arch_id, max(sp_pe.evr) AS max_evr
                FROM rhnServerPackage sp_sp
                    join rhnPackageEvr sp_pe ON sp_pe.id = sp_sp.evr_id
                    GROUP BY sp_sp.server_id, sp_sp.name_id, sp_sp.package_arch_id) sp ON sp.server_id = s.id
        join rhnPackage up ON up.name_id = sp.name_id
        join rhnPackageEvr upe ON upe.id = up.evr_id AND sp.max_evr < upe.evr
        join rhnPackageUpgradeArchCompat puac ON puac.package_arch_id = sp.package_arch_id AND puac.package_upgrade_arch_id = up.package_arch_id
        join rhnServerChannel sc ON sc.server_id = sp.server_id
        join rhnChannelPackage cp ON cp.package_id = up.id AND cp.channel_id = sc.channel_id
        left join
        (SELECT ep.errata_id, cp.channel_id, ep.package_id
         FROM rhnChannelErrata cp
             join rhnErrataPackage ep ON ep.errata_id = cp.errata_id) x
            ON x.channel_id = sc.channel_id AND x.package_id = cp.package_id
;
070701000008E8000081B400000000000000000000000167AE11140000011D000000000000000000000000000000000000006800000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/405-all_primary_keys.sql   create or replace view all_primary_keys as
select
       ac.table_name,
       ac.constraint_name,
       acc.column_name
  from all_constraints ac
  join all_cons_columns acc
    on ac.constraint_name = acc.constraint_name
   and ac.owner = acc.owner
 where ac.constraint_type = 'P';
   070701000008E9000081B400000000000000000000000167AE11140000003C000000000000000000000000000000000000006700000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/406-strategies-drop.sql    drop synonym strategies;
drop synonym strategies_recid_seq;
070701000008EA000081B400000000000000000000000167AE111400000120000000000000000000000000000000000000006600000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/407-PXTSessions-pk.sql alter table rhnVisibleObjects disable constraint rhn_vis_objs_sess_fk;
alter table PXTSessions disable constraint pxt_sessions_pk;
drop index pxt_sessions_pk;
alter table PXTSessions enable constraint pxt_sessions_pk;
alter table rhnVisibleObjects enable constraint rhn_vis_objs_sess_fk;
070701000008EB000081B400000000000000000000000167AE111400000147000000000000000000000000000000000000007300000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/408-rhnChannelPermissionRole-pk.sql    alter table rhnChannelPermission disable constraint rhn_cperm_rid_fk;
alter table rhnChannelPermissionRole disable constraint rhn_cperm_role_id_pk;
drop index rhn_cperm_role_id_pk;
alter table rhnChannelPermissionRole enable constraint rhn_cperm_role_id_pk;
alter table rhnChannelPermission enable constraint rhn_cperm_rid_fk;
 070701000008EC000081B400000000000000000000000167AE1114000002EC000000000000000000000000000000000000006C00000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/409-rhnConfigFileName-pk.sql   alter table rhnActionConfigFileName disable constraint rhn_actioncf_name_cfnid_fk;
alter table rhnConfigFile disable constraint rhn_conffile_cfnid_fk;
alter table rhnConfigInfo disable constraint rhn_confinfo_symlink_fk;
alter table rhnFileListMembers disable constraint rhn_flmembers_cfnid_fk;
alter table rhnConfigFileName disable constraint rhn_cfname_id_pk;
drop index rhn_cfname_id_pk;
alter table rhnConfigFileName enable constraint rhn_cfname_id_pk;
alter table rhnActionConfigFileName enable constraint rhn_actioncf_name_cfnid_fk;
alter table rhnConfigFile enable constraint rhn_conffile_cfnid_fk;
alter table rhnConfigInfo enable constraint rhn_confinfo_symlink_fk;
alter table rhnFileListMembers enable constraint rhn_flmembers_cfnid_fk;
070701000008ED000081B400000000000000000000000167AE111400000251000000000000000000000000000000000000006F00000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/410-rhnKickstartableTree-pk.sql    alter table rhnKSTreeFile disable constraint rhn_kstreefile_kid_fk;
alter table rhnKickstartDefaults disable constraint rhn_ksd_kstid_fk;
alter table rhnKickstartSession disable constraint rhn_ks_session_kstid_fk;
alter table rhnKickstartableTree disable constraint rhn_kstree_id_pk;
drop index rhn_kstree_id_pk;
alter table rhnKickstartableTree enable constraint rhn_kstree_id_pk;
alter table rhnKSTreeFile enable constraint rhn_kstreefile_kid_fk;
alter table rhnKickstartDefaults enable constraint rhn_ksd_kstid_fk;
alter table rhnKickstartSession enable constraint rhn_ks_session_kstid_fk;
   070701000008EE000081B400000000000000000000000167AE11140000050C000000000000000000000000000000000000006600000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/411-rhn_command-pk.sql alter table rhn_command_param_threshold disable constraint rhn_coptr_cmd_id_cmd_cl_fk;
alter table rhn_command_parameter disable constraint rhn_cparm_cmd_command_id_fk;
alter table rhn_os_commands_xref disable constraint rhn_oscxr_cmmnd_commands_id_fk;
alter table rhn_probe disable constraint rhn_probe_cmmnd_command_id_fk;

-- in spacewalk <0.6 constraint RHN_CMMND_RECID_COMM_CL_UQ had been
-- miscalled RHN_CMMND_NAME_UQ
declare
  cname varchar2(30);
begin
    select constraint_name into cname
      from user_constraints
     where table_name = 'RHN_COMMAND' and index_name = 'RHN_CMMND_RECID_COMM_CL_UQ';
    if cname = 'RHN_CMMND_NAME_UQ' then
        execute immediate 'alter table rhn_command rename constraint RHN_CMMND_NAME_UQ to RHN_CMMND_RECID_COMM_CL_UQ';
    end if;
end;
/
alter table rhn_command disable constraint rhn_cmmnd_recid_comm_cl_uq;
drop index rhn_cmmnd_recid_comm_cl_uq;
alter table rhn_command enable constraint rhn_cmmnd_recid_comm_cl_uq;

alter table rhn_command_param_threshold enable constraint rhn_coptr_cmd_id_cmd_cl_fk;
alter table rhn_command_parameter enable constraint rhn_cparm_cmd_command_id_fk;
alter table rhn_os_commands_xref enable constraint rhn_oscxr_cmmnd_commands_id_fk;
alter table rhn_probe enable constraint rhn_probe_cmmnd_command_id_fk;
070701000008EF000081B400000000000000000000000167AE1114000000DD000000000000000000000000000000000000007600000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/412-rhn_command_param_threshold-pk.sql alter table rhn_command_param_threshold disable constraint rhn_coptr_id_p_name_p_type_pk;
drop index rhn_coptr_id_p_name_p_type_pk;
alter table rhn_command_param_threshold enable constraint rhn_coptr_id_p_name_p_type_pk;
   070701000008F0000081B400000000000000000000000167AE1114000000CF000000000000000000000000000000000000007200000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/413-rhn_command_queue_execs-pk.sql alter table rhn_command_queue_execs disable constraint rhn_cqexe_inst_id_nsaint_pk;
drop index rhn_cqexe_inst_id_nsaint_pk;
alter table rhn_command_queue_execs enable constraint rhn_cqexe_inst_id_nsaint_pk;
 070701000008F1000081B400000000000000000000000167AE1114000000D4000000000000000000000000000000000000007300000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/414-rhn_command_queue_params-pk.sql    alter table rhn_command_queue_params disable constraint rhn_cqprm_instance_id_ord_pk;
drop index rhn_cqprm_instance_id_ord_pk;
alter table rhn_command_queue_params enable constraint rhn_cqprm_instance_id_ord_pk;
070701000008F2000081B400000000000000000000000167AE1114000000A3000000000000000000000000000000000000006B00000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/415-rhn_config_macro-pk.sql    alter table rhn_config_macro disable constraint rhn_confm_name_pk;
drop index rhn_confm_name_pk;
alter table rhn_config_macro enable constraint rhn_confm_name_pk;
 070701000008F3000081B400000000000000000000000167AE1114000000CC000000000000000000000000000000000000006F00000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/416-rhn_config_parameter-pk.sql    alter table rhn_config_parameter disable constraint rhn_confp_group_name_name_pk;
drop index rhn_confp_group_name_name_pk;
alter table rhn_config_parameter enable constraint rhn_confp_group_name_name_pk;
070701000008F4000081B400000000000000000000000167AE1114000000E0000000000000000000000000000000000000007600000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/417-rhn_current_state_summaries-pk.sql alter table rhn_current_state_summaries disable constraint rhn_current_state_summaries_pk;
drop index rhn_current_state_summaries_pk;
alter table rhn_current_state_summaries enable constraint rhn_current_state_summaries_pk;
070701000008F5000081B400000000000000000000000167AE1114000000D2000000000000000000000000000000000000006F00000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/418-rhn_os_commands_xref-pk.sql    alter table rhn_os_commands_xref disable constraint rhn_oscxr_os_id_commands_id_pk;
drop index rhn_oscxr_os_id_commands_id_pk;
alter table rhn_os_commands_xref enable constraint rhn_oscxr_os_id_commands_id_pk;
  070701000008F6000081B400000000000000000000000167AE111400000469000000000000000000000000000000000000006400000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/419-rhn_probe-pk.sql   alter table rhn_check_probe disable constraint rhn_chkpb_recid_probe_typ_fk;
alter table rhn_host_probe disable constraint rhn_hstpb_probe_probe_id_fk;
alter table rhn_probe_param_value disable constraint rhn_ppval_chkpb_probe_id_fk;
alter table rhn_sat_cluster_probe disable constraint rhn_sclpb_prb_recid_prb_typ_fk;
alter table rhn_service_probe_origins disable constraint rhn_srvpo_pr_serv_pr_fk;
alter table rhn_url_probe disable constraint rhn_urlpb_probe_pr_id_pr_fk;
alter table rhn_probe disable constraint rhn_probe_recid_probe_type_uq;
drop index rhn_probe_recid_probe_type_uq;
alter table rhn_probe enable constraint rhn_probe_recid_probe_type_uq;
alter table rhn_check_probe enable constraint rhn_chkpb_recid_probe_typ_fk;
alter table rhn_host_probe enable constraint rhn_hstpb_probe_probe_id_fk;
alter table rhn_probe_param_value enable constraint rhn_ppval_chkpb_probe_id_fk;
alter table rhn_sat_cluster_probe enable constraint rhn_sclpb_prb_recid_prb_typ_fk;
alter table rhn_service_probe_origins enable constraint rhn_srvpo_pr_serv_pr_fk;
alter table rhn_url_probe enable constraint rhn_urlpb_probe_pr_id_pr_fk;
   070701000008F7000081B400000000000000000000000167AE1114000000D1000000000000000000000000000000000000007000000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/420-rhn_probe_param_value-pk.sql   alter table rhn_probe_param_value disable constraint rhn_ppval_p_id_cmd_id_parm_pk;
drop index rhn_ppval_p_id_cmd_id_parm_pk;
alter table rhn_probe_param_value enable constraint rhn_ppval_p_id_cmd_id_parm_pk;
   070701000008F8000081B400000000000000000000000167AE1114000000A8000000000000000000000000000000000000007500000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/421-rhn_redirect_email_targets-pk.sql  alter table rhn_redirect_email_targets disable constraint rhn_rdret_pk;
drop index rhn_rdret_pk;
alter table rhn_redirect_email_targets enable constraint rhn_rdret_pk;
070701000008F9000081B400000000000000000000000167AE1114000000A8000000000000000000000000000000000000007500000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/422-rhn_redirect_group_targets-pk.sql  alter table rhn_redirect_group_targets disable constraint rhn_rdrgt_pk;
drop index rhn_rdrgt_pk;
alter table rhn_redirect_group_targets enable constraint rhn_rdrgt_pk;
070701000008FA000081B400000000000000000000000167AE1114000000AA000000000000000000000000000000000000007600000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/423-rhn_redirect_method_targets-pk.sql alter table rhn_redirect_method_targets disable constraint rhn_rdrme_pk;
drop index rhn_rdrme_pk;
alter table rhn_redirect_method_targets enable constraint rhn_rdrme_pk;
  070701000008FB000081B400000000000000000000000167AE1114000000FF000000000000000000000000000000000000007400000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/424-rhn_service_probe_origins-pk.sql   alter table rhn_service_probe_origins disable constraint rhn_srvpo_serv_pr_id_orig_uq;
drop index rhn_srvpo_serv_pr_id_orig_uq;
drop index rhn_srvpo_serv_orig_pr_id_uq;
alter table rhn_service_probe_origins enable constraint rhn_srvpo_serv_pr_id_orig_uq;
 070701000008FC000081B400000000000000000000000167AE1114000000B8000000000000000000000000000000000000006E00000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/425-rhn_time_zone_names-pk.sql alter table rhn_time_zone_names disable constraint rhn_time_zone_names_uq;
drop index rhn_time_zone_names_uq;
alter table rhn_time_zone_names enable constraint rhn_time_zone_names_uq;
070701000008FD000081B400000000000000000000000167AE1114000001AA000000000000000000000000000000000000006F00000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/426-rhnReleaseChannelMap-uq.sql    -- during 05 -> 0.6 schema upgrade RHN_RCM_PVA_DEF_UNIQ had been mis-renamed
-- to RHN_RCM_PVAR_UNIQ

declare
    constraint_not_exists exception;
    pragma exception_init(constraint_not_exists, -23292);
begin
    execute immediate 'alter table RHNRELEASECHANNELMAP rename constraint RHN_RCM_PVAR_UNIQ to RHN_RCM_PVA_DEF_UNIQ';
exception
    when constraint_not_exists then
        null; -- constraint has right name
end;
/

  070701000008FE000081B400000000000000000000000167AE111400000076000000000000000000000000000000000000006F00000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/482-rhnPackageProvider-data.sql    insert into rhnPackageProvider (id, name) values
(sequence_nextval('rhn_package_provider_id_seq'), 'EPEL' );

commit;
  070701000008FF000081B400000000000000000000000167AE1114000009E9000000000000000000000000000000000000006A00000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/483-rhnPackageKey-data.sql -- Fedora 15
update rhnPackageKey set provider_id = lookup_package_provider('Fedora')
 where key_id = 'b4ebf579069c8460';
insert into rhnPackageKey (id, key_id, key_type_id, provider_id)
    (select sequence_nextval('rhn_pkey_id_seq'), 'b4ebf579069c8460', lookup_package_key_type('gpg'), lookup_package_provider('Fedora') from dual
      where 1 not in (select 1 from rhnPackageKey where key_id = 'b4ebf579069c8460'));

-- CentOS 6
update rhnPackageKey set provider_id = lookup_package_provider('CentOS')
 where key_id = '0946fca2c105b9de';
insert into rhnPackageKey (id, key_id, key_type_id, provider_id)
    (select sequence_nextval('rhn_pkey_id_seq'), '0946fca2c105b9de', lookup_package_key_type('gpg'), lookup_package_provider('CentOS') from dual
    where 1 not in (select 1 from rhnPackageKey where key_id = '0946fca2c105b9de'));

-- Scientific Linux 6
update rhnPackageKey set provider_id = lookup_package_provider('Scientific Linux')
 where key_id = '915d75e09b1fd350';
insert into rhnPackageKey (id, key_id, key_type_id, provider_id)
    (select sequence_nextval('rhn_pkey_id_seq'), '915d75e09b1fd350', lookup_package_key_type('gpg'), lookup_package_provider('Scientific Linux') from dual
    where 1 not in (select 1 from rhnPackageKey where key_id = '915d75e09b1fd350'));
update rhnPackageKey set provider_id = lookup_package_provider('Scientific Linux')
 where key_id = 'b0b4183f192a7d7d';
insert into rhnPackageKey (id, key_id, key_type_id, provider_id)
    (select sequence_nextval('rhn_pkey_id_seq'), 'b0b4183f192a7d7d', lookup_package_key_type('gpg'), lookup_package_provider('Scientific Linux') from dual
    where 1 not in (select 1 from rhnPackageKey where key_id = 'b0b4183f192a7d7d'));

-- EPEL 5
update rhnPackageKey set provider_id = lookup_package_provider('EPEL')
 where key_id = '119cc036217521f6';
insert into rhnPackageKey (id, key_id, key_type_id, provider_id)
    (select sequence_nextval('rhn_pkey_id_seq'), '119cc036217521f6', lookup_package_key_type('gpg'), lookup_package_provider('EPEL') from dual
    where 1 not in (select 1 from rhnPackageKey where key_id = '119cc036217521f6'));
-- EPEL 6
update rhnPackageKey set provider_id = lookup_package_provider('EPEL')
 where key_id = '3b49df2a0608b895';
insert into rhnPackageKey (id, key_id, key_type_id, provider_id)
    (select sequence_nextval('rhn_pkey_id_seq'), '3b49df2a0608b895', lookup_package_key_type('gpg'), lookup_package_provider('EPEL') from dual
    where 1 not in (select 1 from rhnPackageKey where key_id = '3b49df2a0608b895'));

commit;
   07070100000900000081B400000000000000000000000167AE111400000236000000000000000000000000000000000000006B00000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/495-rhn_host_monitoring.sql    drop view rhn_host_monitoring;
create or replace view rhn_host_monitoring
(
	recid,
	ip,
	name,
	description,
	customer_id,
	os_id,
	asset_id,
	last_update_user,
	last_update_date
) as
select  s.id            as recid,
	rhn_server.get_ip_address(s.id)	as ip,
        s.name          as name,
        s.description   as description,
        s.org_id        as customer_id,
        4               as os_id,
        to_number(null,null) as asset_id,
        cast(null as char)   as last_update_user,
        cast(null as date)   as last_update_date
from	rhnServer	s
;
  07070100000901000081B400000000000000000000000167AE111400000037000000000000000000000000000000000000006B00000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/496-add_rhnServerNetwor.sql    alter table rhnServerNetwork add ip6addr varchar2(45);
 07070100000902000081B400000000000000000000000167AE1114000002D2000000000000000000000000000000000000006E00000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/500-rhnContentSourceFilter.sql 
create table
rhnContentSourceFilter
(
        id		number NOT NULL
			constraint rhn_csf_id_pk primary key,
        source_id		number
			constraint rhn_csf_source_fk
                                references rhnContentSource (id),
        sort_order	number NOT NULL,
        flag            varchar2(1) NOT NULL
                        check (flag in ('+','-')),
        filter          varchar2(4000) NOT NULL,
        created         date default(sysdate) NOT NULL,
        modified        date default(sysdate) NOT NULL
)
	enable row movement
  ;


create sequence rhn_csf_id_seq start with 500;

CREATE UNIQUE INDEX rhn_csf_sid_so_uq
    ON rhnContentSourceFilter (source_id, sort_order)
    tablespace [[64k_tbs]];

  07070100000903000081B400000000000000000000000167AE11140000003D000000000000000000000000000000000000007900000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/501-add_rhnKickstartScript_scriptname.sql  alter table rhnKickstartScript add script_name varchar2(40);
   07070100000904000081B400000000000000000000000167AE1114000001A4000000000000000000000000000000000000007300000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/505-alter_rhnServerNetInterface.sql    alter table rhnServerNetInterface add id number;

create sequence rhn_srv_net_iface_id_seq;

alter trigger rhn_srv_net_iface_mod_trig disable;
update rhnServerNetInterface set id = rhn_srv_net_iface_id_seq.nextval;
alter trigger rhn_srv_net_iface_mod_trig enable;

alter table rhnServerNetInterface modify id number not null;

alter table rhnServerNetInterface add constraint rhn_srv_net_iface_id_pk primary key ( id );
07070100000905000081B400000000000000000000000167AE11140000053B000000000000000000000000000000000000007000000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/510-add_rhnServerNetAddress4.sql   --
-- Copyright (c) 2011 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnServerNetAddress4
(
    interface_id  NUMBER NOT NULL
                   CONSTRAINT rhn_srv_net_iaddress4_iid_fk
                       REFERENCES rhnServerNetInterface (id)
                       ON DELETE CASCADE,
    address    VARCHAR2(64),
    netmask    VARCHAR2(64),
    broadcast  VARCHAR2(64),
    created    DATE
                   DEFAULT (sysdate) NOT NULL,
    modified   DATE
                   DEFAULT (sysdate) NOT NULL
)
ENABLE ROW MOVEMENT
;

CREATE INDEX rhn_srv_net_addr4_iid_addr_idx
    ON rhnServerNetAddress4 (interface_id, address)
    TABLESPACE [[64k_tbs]];

ALTER TABLE rhnServerNetAddress4
    ADD CONSTRAINT rhn_srv_net_addr4_iid_addr_uq UNIQUE (interface_id, address);
 07070100000906000081B400000000000000000000000167AE1114000000B7000000000000000000000000000000000000007500000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/511-add_rhnServerNetAddress4_data.sql  INSERT INTO rhnServerNetAddress4
    (interface_id, address, netmask, broadcast, created)
    SELECT id, ip_addr, netmask, broadcast, created
    FROM rhnServerNetInterface;

COMMIT;
 07070100000907000081B400000000000000000000000167AE1114000000A7000000000000000000000000000000000000007A00000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/515-drop_columns_rhnServerNetInterface.sql ALTER TABLE rhnServerNetInterface DROP COLUMN ip_addr;
ALTER TABLE rhnServerNetInterface DROP COLUMN netmask;
ALTER TABLE rhnServerNetInterface DROP COLUMN broadcast;
 07070100000908000081B400000000000000000000000167AE111400000547000000000000000000000000000000000000007000000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/520-add_rhnServerNetAddress6.sql   --
-- Copyright (c) 2011 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnServerNetAddress6
(
    interface_id  NUMBER NOT NULL
                   CONSTRAINT rhn_srv_net_iaddress6_iid_fk
                       REFERENCES rhnServerNetInterface (id)
                       ON DELETE CASCADE,
    address    VARCHAR2(45),
    netmask    VARCHAR2(49),
    scope      VARCHAR2(64),
    created    DATE
                   DEFAULT (sysdate) NOT NULL,
    modified   DATE
                   DEFAULT (sysdate) NOT NULL
)
ENABLE ROW MOVEMENT
;

CREATE INDEX rhn_srv_net_ad6_iid_sc_ad_idx
    ON rhnServerNetAddress6 (interface_id, scope, address)
    TABLESPACE [[64k_tbs]];

ALTER TABLE rhnServerNetAddress6
    ADD CONSTRAINT rhn_srv_net_ad6_iid_sc_ad_uq UNIQUE (interface_id, scope, address);
 07070100000909000081B400000000000000000000000167AE1114000054FE000000000000000000000000000000000000007100000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/521-rhn_server-get_ip_address.sql  --
-- Copyright (c) 2008--2011 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--
--
--
--

create or replace
package body rhn_server
is
    function system_service_level(
	server_id_in in number,
	service_level_in in varchar2
    ) return number is

    cursor ents is
      select label from rhnServerEntitlementView
      where server_id = server_id_in;

    retval number := 0;

    begin
         for ent in ents loop
            retval := rhn_entitlements.entitlement_grants_service (ent.label, service_level_in);
            if retval = 1 then
               return retval;
            end if;
         end loop;

         return retval;

    end system_service_level;


    function can_change_base_channel(server_id_in IN NUMBER)
    return number
    is
	throwaway number;
    begin
	-- the idea: if we get past this query, the server is
	-- neither sat nor proxy, so base channel is changeable

	select 1 into throwaway
	  from rhnServer S
	 where S.id = server_id_in
	   and not exists (select 1 from rhnSatelliteInfo SI where SI.server_id = S.id)
	   and not exists (select 1 from rhnProxyInfo PI where PI.server_id = S.id);

	return 1;
    exception
	when no_data_found
	    then
	    return 0;
    end can_change_base_channel;

    procedure set_custom_value(
	server_id_in in number,
	user_id_in in number,
	key_label_in in varchar2,
	value_in in varchar2
    ) is
	key_id_val number;
    begin
	select CDK.id into key_id_val
	  from rhnCustomDataKey CDK,
	       rhnServer S
	 where S.id = server_id_in
	   and S.org_id = CDK.org_id
	   and CDK.label = key_label_in;

	begin
	    insert into rhnServerCustomDataValue (server_id, key_id, value, created_by, last_modified_by)
	    values (server_id_in, key_id_val, value_in, user_id_in, user_id_in);
	exception
	    when DUP_VAL_ON_INDEX
		then
		update rhnServerCustomDataValue
		   set value = value_in,
		       last_modified_by = user_id_in
		 where server_id = server_id_in
		   and key_id = key_id_val;
	end;

    end set_custom_value;

    function bulk_set_custom_value(
	key_label_in in varchar2,
	value_in in varchar2,
	set_label_in in varchar2,
	set_uid_in in number
    )
    return integer
    is
    i integer := 0;
    begin
        i := 0;
	for server in rhn_set.set_iterator(set_label_in, set_uid_in)
	loop
	    if rhn_server.system_service_level(server.element, 'provisioning') = 1 then
		rhn_server.set_custom_value(server.element, set_uid_in, key_label_in, value_in);
            i := i + 1;
	    end if;
	end loop server;
    return i;
    end bulk_set_custom_value;

    procedure bulk_snapshot_tag(
	org_id_in in number,
        tagname_in in varchar2,
	set_label_in in varchar2,
	set_uid_in in number
    ) is
	snapshot_id number;
    begin
	for server in rhn_set.set_iterator(set_label_in, set_uid_in)
	loop
	    if rhn_server.system_service_level(server.element, 'provisioning') = 1 then
		begin
		    select max(id) into snapshot_id
		    from rhnSnapshot
		    where server_id = server.element;
		exception
		    when NO_DATA_FOUND then
			rhn_server.snapshot_server(server.element, 'tagging system:  ' || tagname_in);

			select max(id) into snapshot_id
			from rhnSnapshot
			where server_id = server.element;
		end;

		-- now have a snapshot_id to work with...
		begin
		    rhn_server.tag_snapshot(snapshot_id, org_id_in, tagname_in);
		exception
		    when DUP_VAL_ON_INDEX
			then
			-- do nothing, be forgiving...
			null;
		end;
	    end if;
	end loop server;
    end bulk_snapshot_tag;

    procedure tag_delete(
	server_id_in in number,
	tag_id_in in number
    ) is
	cursor snapshots is
		select	snapshot_id
		from	rhnSnapshotTag
		where	tag_id = tag_id_in;
	tag_id_tmp number;
    begin
	select	id into tag_id_tmp
	from	rhnTag
	where	id = tag_id_in
	for update;

	delete
		from	rhnSnapshotTag
		where	server_id = server_id_in
			and tag_id = tag_id_in;
	for snapshot in snapshots loop
		return;
	end loop;
	delete
		from rhnTag
		where id = tag_id_in;
    end tag_delete;

    procedure tag_snapshot(
        snapshot_id_in in number,
	org_id_in in number,
	tagname_in in varchar2
    ) is
    begin
	insert into rhnSnapshotTag (snapshot_id, server_id, tag_id)
	select snapshot_id_in, server_id, lookup_tag(org_id_in, tagname_in)
	from rhnSnapshot
	where id = snapshot_id_in;
    end tag_snapshot;

    procedure bulk_snapshot(
	reason_in in varchar2,
	set_label_in in varchar2,
	set_uid_in in number
    ) is
    begin
	for server in rhn_set.set_iterator(set_label_in, set_uid_in)
	loop
	    if rhn_server.system_service_level(server.element, 'provisioning') = 1 then
		rhn_server.snapshot_server(server.element, reason_in);
	    end if;
	end loop server;
    end bulk_snapshot;

    procedure snapshot_server(
	server_id_in in number,
	reason_in in varchar2
    ) is
	snapshot_id number;
	cursor revisions is
		select distinct
			cr.id
		from	rhnConfigRevision	cr,
			rhnConfigFileName	cfn,
			rhnConfigFile		cf,
			rhnConfigChannel	cc,
			rhnServerConfigChannel	scc
		where	1=1
			and scc.server_id = server_id_in
			and scc.config_channel_id = cc.id
			and cc.id = cf.config_channel_id
			and cf.id = cr.config_file_id
			and cr.id = cf.latest_config_revision_id
			and cf.config_file_name_id = cfn.id
			and cf.id = lookup_first_matching_cf(scc.server_id, cfn.path);
	locked integer;
    begin
	select rhn_snapshot_id_seq.nextval into snapshot_id from dual;

	insert into rhnSnapshot (id, org_id, server_id, reason) (
		select	snapshot_id,
			s.org_id,
			server_id_in,
			reason_in
		from	rhnServer s
		where	s.id = server_id_in
	);
	insert into rhnSnapshotChannel (snapshot_id, channel_id) (
		select	snapshot_id, sc.channel_id
		from	rhnServerChannel sc
		where	sc.server_id = server_id_in
	);
	insert into rhnSnapshotServerGroup (snapshot_id, server_group_id) (
		select	snapshot_id, sgm.server_group_id
		from	rhnServerGroupMembers sgm
		where	sgm.server_id = server_id_in
	);
        locked := 0;
        while true loop
            begin
                insert into rhnPackageNEVRA (id, name_id, evr_id, package_arch_id)
                select rhn_pkgnevra_id_seq.nextval, sp.name_id, sp.evr_id, sp.package_arch_id
                from rhnServerPackage sp
                where sp.server_id = server_id_in
                        and not exists
                        (select 1
                                from rhnPackageNEVRA nevra
                                where nevra.name_id = sp.name_id
                                        and nevra.evr_id = sp.evr_id
                                        and (nevra.package_arch_id = sp.package_arch_id
                                            or (nevra.package_arch_id is null
                                                and sp.package_arch_id is null)));
                exit;
            exception when dup_val_on_index then
                if locked = 1 then
                    raise;
                else
                    lock table rhnPackageNEVRA in exclusive mode;
                    locked := 1;
                end if;
            end;
        end loop;
	insert into rhnSnapshotPackage (snapshot_id, nevra_id) (
                select distinct snapshot_id, nevra.id
                from    rhnServerPackage sp, rhnPackageNEVRA nevra
                where   sp.server_id = server_id_in
                        and nevra.name_id = sp.name_id
                        and nevra.evr_id = sp.evr_id
                        and (nevra.package_arch_id = sp.package_arch_id
                            or (nevra.package_arch_id is null
                                and sp.package_arch_id is null))
	);

	insert into rhnSnapshotConfigChannel ( snapshot_id, config_channel_id ) (
		select	snapshot_id, scc.config_channel_id
		from	rhnServerConfigChannel scc
		where	server_id = server_id_in
	);

	for revision in revisions loop
		insert into rhnSnapshotConfigRevision (
				snapshot_id, config_revision_id
			) values (
				snapshot_id, revision.id
			);
	end loop;
    end snapshot_server;

    procedure remove_action(
	server_id_in in number,
	action_id_in in number
    ) is
	-- this really wants "nulls last", but 8.1.7.3.0 sucks ass.
	-- instead, we make a local table that holds our
	-- list of ids with null prereqs.  There's surely a better way
	-- (an array instead of a table maybe?  who knows...)
	-- but I've got code to do this handy that I can look at ;)
	cursor chained_actions is
		select	id, prerequisite
		from	rhnAction
		start with id = action_id_in
		connect by prior id = prerequisite
		order by prerequisite desc;
	cursor sessions is
		select	s.id
		from	rhnKickstartSession s
		where	server_id_in in (s.old_server_id, s.new_server_id)
			and s.action_id = action_id_in
			and not exists (
				select	1
				from	rhnKickstartSessionState ss
				where	ss.id = s.state_id
					and ss.label in ('failed','complete')
			);
	type chain_end_type is table of number index by binary_integer;
	chain_ends chain_end_type;
	i number;
	prereq number := 1;
    begin
	select	prerequisite
	into	prereq
	from	rhnAction
	where	id = action_id_in;

	if prereq is not null then
		rhn_exception.raise_exception('action_is_child');
	end if;

	i := 0;
	for action in chained_actions loop
		if action.prerequisite is null then
			chain_ends(i) := action.id;
			i := i + 1;
		else
			delete from rhnServerAction
				where server_id = server_id_in
				and action_id = action.id;
		end if;
	end loop;
	i := chain_ends.first;
	while i is not null loop
		delete from rhnServerAction
			where server_id = server_id_in
			and action_id = chain_ends(i);
		i := chain_ends.next(i);
	end loop;
	for s in sessions loop
		update rhnKickstartSession
			set 	state_id = (
					select	id
					from	rhnKickstartSessionState
					where	label = 'failed'
				),
				action_id = null
			where	id = s.id;
		set_ks_session_history_message(s.id, 'failed', 'Kickstart cancelled due to action removal');
	end loop;
    end remove_action;

    function check_user_access(server_id_in in number, user_id_in in number)
    return number
    is
	has_access number;
    begin
	-- first check; if this returns no rows, then the server/user are in different orgs, and we bail
        select 1 into has_access
	  from rhnServer S,
	       web_contact wc
	 where wc.org_id = s.org_id
	   and s.id = server_id_in
	   and wc.id = user_id_in;

	-- okay, so they're in the same org.  if we have an org admin, they get a free pass
	if rhn_user.check_role(user_id_in, 'org_admin') = 1
	then
	    return 1;
	end if;

	select 1 into has_access
	  from rhnServerGroupMembers SGM,
	       rhnUserServerGroupPerms USG
	 where SGM.server_group_id = USG.server_group_id
	   and SGM.server_id = server_id_in
	   and USG.user_id = user_id_in
	   and rownum = 1;

	return 1;
    exception
	when no_data_found
	    then
	    return 0;
    end check_user_access;

    -- *******************************************************************
    -- FUNCTION: can_server_consume_virt_slot
    -- Returns 1 if the server id is eligible to consume a virtual slot,
    --   else returns 0.
    -- Called by: insert_into_servergroup, delete_from_servergroup
    -- *******************************************************************
    function can_server_consume_virt_slot(server_id_in in number,
                                           group_type_in in
                                           rhnServerGroupType.label%TYPE)
    return number
    is

        cursor server_virt_slots is
            select vi.VIRTUAL_SYSTEM_ID
            from
                rhnVirtualInstance vi
            where
                -- server id is a virtual instance
                vi.VIRTUAL_SYSTEM_ID = server_id_in
                -- server id's host is virt entitled
                and exists ( select 1
                     from rhnServerEntitlementView sev
                 where vi.HOST_SYSTEM_ID = sev.server_id
                 and sev.label in ('virtualization_host',
                                   'virtualization_host_platform') )
                -- server id's host also has the ent we want
                and exists ( select 1
                     from rhnServerEntitlementView sev2
                 where vi.HOST_SYSTEM_ID = sev2.server_id
                 and sev2.label = group_type_in );

    begin
        for server_virt_slot in server_virt_slots loop
            return 1;
        end loop;
        return 0;
    end can_server_consume_virt_slot;


    procedure insert_into_servergroup (
		server_id_in in number,
		server_group_id_in in number
    ) is
		used_slots number;
		max_slots number;
		org_id number;
		mgmt_available number;
		mgmt_upgrade number;
		mgmt_sgid number;
		prov_available number;
		prov_upgrade number;
		prov_sgid number;
		group_label rhnServerGroupType.label%TYPE;
		group_type number;
	begin
		-- frist, group_type = null, because it's easy...

		-- this will rowlock the servergroup we're trying to change;
		-- we probably need to lock the other one, but I think the chances
		-- of it being a real issue are very small for now...
		select	sg.group_type, sg.org_id, sg.current_members, sg.max_members
		into	group_type, org_id, used_slots, max_slots
		from	rhnServerGroup sg
		where	sg.id = server_group_id_in
		for update of sg.current_members;

		if group_type is null then
			if used_slots >= max_slots then
				rhn_exception.raise_exception('servergroup_max_members');
			end if;

			insert into rhnServerGroupMembers(
					server_id, server_group_id
				) values (
					server_id_in, server_group_id_in
				);
			update rhnServerGroup
				set current_members = current_members + 1
				where id = server_group_id_in;

			rhn_cache.update_perms_for_server_group(server_group_id_in);
			return;
		end if;

		-- now for group_type != null
		--
		select	label
		into	group_label
		from	rhnServerGroupType	sgt
		where	sgt.id = group_type;

		-- the naive easy path that gets hit most often and has to be quickest.
		if group_label in ('sw_mgr_entitled',
                           'enterprise_entitled',
                           'monitoring_entitled',
                           'provisioning_entitled',
                           'virtualization_host',
                           'virtualization_host_platform') then
			if used_slots >= max_slots and
               (can_server_consume_virt_slot(server_id_in, group_label) != 1)
               then
				rhn_exception.raise_exception('servergroup_max_members');
			end if;

			insert into rhnServerGroupMembers(
					server_id, server_group_id
				) values (
					server_id_in, server_group_id_in
				);

            -- Only update current members if the system in consuming a
            -- physical slot.
            if can_server_consume_virt_slot(server_id_in, group_label) = 0 then
                update rhnServerGroup
                set current_members = current_members + 1
                where id = server_group_id_in;
            end if;

			return;
		end if;
	end;

	function insert_into_servergroup_maybe (
		server_id_in in number,
		server_group_id_in in number
	) return number is
		retval number := 0;
		cursor servergroups is
			select	s.id	server_id,
					sg.id	server_group_id
			from	rhnServerGroup	sg,
					rhnServer		s
			where	s.id = server_id_in
				and sg.id = server_group_id_in
				and s.org_id = sg.org_id
				and not exists (
					select	1
					from	rhnServerGroupMembers sgm
					where	sgm.server_id = s.id
						and sgm.server_group_id = sg.id
				);
	begin
		for sgm in servergroups loop
			rhn_server.insert_into_servergroup(sgm.server_id, sgm.server_group_id);
			retval := retval + 1;
		end loop;
		return retval;
	end insert_into_servergroup_maybe;

	procedure insert_set_into_servergroup (
		server_group_id_in in number,
		user_id_in in number,
		set_label_in in varchar2
	) is
		cursor servers is
			select	st.element	id
			from	rhnSet		st
			where	st.user_id = user_id_in
				and st.label = set_label_in
				and exists (
					select	1
					from	rhnUserManagedServerGroups umsg
					where	umsg.server_group_id = server_group_id_in
						and umsg.user_id = user_id_in
					)
				and not exists (
					select	1
					from	rhnServerGroupMembers sgm
					where	sgm.server_id = st.element
						and sgm.server_group_id = server_group_id_in
				);
	begin
		for s in servers loop
			rhn_server.insert_into_servergroup(s.id, server_group_id_in);
		end loop;
	end insert_set_into_servergroup;

    procedure delete_from_servergroup (
	server_id_in in number,
		server_group_id_in in number
    ) is
        cursor server_virt_groups is
            select 1
            from rhnServerEntitlementVirtual sev
            where sev.server_id = server_id_in
            and sev.server_group_id = server_group_id_in;

		oid number;
		mgmt_sgid number;
		label rhnServerGroupType.label%TYPE;
		group_type number;
	begin
		begin
			select	sg.group_type, sg.org_id
			into	group_type,	oid
			from	rhnServerGroupMembers	sgm,
					rhnServerGroup			sg
			where	sg.id = server_group_id_in
				and sg.id = sgm.server_group_id
				and sgm.server_id = server_id_in
			for update of sg.current_members;
		exception
			when no_data_found then
				rhn_exception.raise_exception('server_not_in_group');
		end;

		-- do group_type is null first
		if group_type is null then
			delete from rhnServerGroupMembers
				where server_group_id = server_group_id_in
				and	server_id = server_id_in;
			update rhnServerGroup
				set current_members = current_members - 1
				where id = server_group_id_in;
			rhn_cache.update_perms_for_server_group(server_group_id_in);
			return;
		end if;

		select	sgt.label
		into	label
		from	rhnServerGroupType sgt
		where	sgt.id = group_type;

		if label in ('sw_mgr_entitled',
                     'enterprise_entitled',
                     'provisioning_entitled',
                     'monitoring_entitled',
                     'virtualization_host',
                     'virtualization_host_platform') then

            -- Only update current members if the system is consuming
            -- a physical slot.
            for server_virt_group in server_virt_groups loop
                delete from rhnServerGroupMembers
                where server_group_id = server_group_id_in
                and	server_id = server_id_in;
                return;
            end loop;

            delete from rhnServerGroupMembers
            where server_group_id = server_group_id_in
            and	server_id = server_id_in;

            update rhnServerGroup
            set current_members = current_members - 1
            where id = server_group_id_in;

		end if;
	end;

	procedure delete_set_from_servergroup (
		server_group_id_in in number,
		user_id_in in number,
		set_label_in in varchar2
	) is
		cursor servergroups is
			select	sgm.server_id, sgm.server_group_id
			from	rhnSet st,
					rhnServerGroupMembers sgm
			where	sgm.server_group_id = server_group_id_in
				and st.user_id = user_id_in
				and st.label = set_label_in
				and sgm.server_id = st.element
				and exists (
					select	1
					from	rhnUserManagedServerGroups usgp
					where	usgp.server_group_id = server_group_id_in
						and usgp.user_id = user_id_in
				);
	begin
		for sgm in servergroups loop
			rhn_server.delete_from_servergroup(sgm.server_id, server_group_id_in);
		end loop;
	end delete_set_from_servergroup;

	procedure clear_servergroup (
		server_group_id_in in number
	) is
		cursor servers is
			select	sgm.server_id	id
			from	rhnServerGroupMembers sgm
			where	sgm.server_group_id = server_group_id_in;
	begin
		for s in servers loop
			rhn_server.delete_from_servergroup(s.id, server_group_id_in);
		end loop;
	end clear_servergroup;

	procedure delete_from_org_servergroups (
		server_id_in in number
	) is
		cursor servergroups is
			select	sgm.server_group_id id
			from	rhnServerGroup sg,
					rhnServerGroupMembers sgm
			where	sgm.server_id = server_id_in
				and sgm.server_group_id = sg.id
				and sg.group_type is null;
	begin
		for sg in servergroups loop
			rhn_server.delete_from_servergroup(server_id_in, sg.id);
		end loop;
	end delete_from_org_servergroups;

	function get_ip_address (
		server_id_in in number
	) return varchar2 is
		cursor interfaces is
			select	ni.name as name, na4.address as address
			from	rhnServerNetInterface ni,
                    rhnServerNetAddress4 na4
			where	ni.server_id = server_id_in
                and ni.id = na4.interface_id
				and na4.address != '127.0.0.1';
		cursor addresses is
			select	ipaddr ip_addr
			from	rhnServerNetwork
			where	server_id = server_id_in
				and ipaddr != '127.0.0.1';
	begin
		for addr in addresses loop
			return addr.ip_addr;
		end loop;
		for iface in interfaces loop
			return iface.address;
		end loop;
		return NULL;
	end get_ip_address;

        procedure update_needed_cache(server_id_in in number)
        is
        begin
            delete from rhnServerNeededCache
             where server_id = server_id_in;
            insert into rhnServerNeededCache
                   (server_id, errata_id, package_id)
                   (select distinct server_id, errata_id, package_id
                      from rhnServerNeededView
                     where server_id = server_id_in);
        end update_needed_cache;

end rhn_server;
/
SHOW ERRORS
  0707010000090A000081B400000000000000000000000167AE1114000002EC000000000000000000000000000000000000006B00000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/522-get_hw_info_as_clob.sql    
create or replace function get_hw_info_as_clob(
	sid in rhnserver.id%TYPE,
	separator in varchar
)
return clob
is
	ret clob;
	tmp varchar2(4000);
begin
	dbms_lob.createtemporary(ret, true);
	for rec in (
		select m
		from (
			select 1 n, sum(nrcpu) || ' CPUs' m
			from rhncpu where rhncpu.server_id = sid
			union all
			select 2, ni.name||' '||na4.address||'/'||na4.netmask||' '||ni.hw_addr val
			from rhnservernetinterface ni,
			     rhnServerNetAddress4 na4
			where ni.server_id = sid
			  and ni.id = na4.interface_id
			)
		order by n, m
		) loop
		if dbms_lob.getlength(ret) > 0 then
			dbms_lob.writeappend(ret, length(separator), separator);
		end if;
		dbms_lob.writeappend(ret, length(rec.m), rec.m);
	end loop;
	return ret;
end;
/
0707010000090B000081B400000000000000000000000167AE11140000011E000000000000000000000000000000000000007500000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/523-trigger-rhnServerNetInterface.sql  create or replace trigger
rhn_srv_net_iface_mod_trig
before insert or update on rhnServerNetInterface
for each row
begin
		if :new.id is null then
	        select rhn_srv_net_iface_id_seq.nextval into :new.id from dual;
	    end if;
        :new.modified := sysdate;
end;
/
show errors
  0707010000090C000081B400000000000000000000000167AE111400000039000000000000000000000000000000000000006900000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/524-rhnPushDispatcher.sql  alter table rhnPushDispatcher add password varchar2(32);
   0707010000090D000081B400000000000000000000000167AE11140000016D000000000000000000000000000000000000006A00000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/525-alter-index-rhnRam.sql delete from rhnram X
	where server_id in (select server_id from rhnram group by server_id having count(server_id)>1)
	 and id<(select max(id) from rhnram Y where X.server_id=Y.server_id group by server_id having count(server_id)>1);

DROP INDEX rhn_ram_sid_idx;

CREATE UNIQUE INDEX rhn_ram_sid_uq
    ON rhnRam (server_id)
    TABLESPACE [[4m_tbs]]
    NOLOGGING;
   0707010000090E000081B400000000000000000000000167AE111400000179000000000000000000000000000000000000006A00000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/526-alter-index-rhnCpu.sql delete from rhncpu X
	where server_id in (select server_id from rhncpu group by server_id having count(server_id)>1)
	 and id<(select max(id) from rhncpu Y where X.server_id=Y.server_id group by server_id having count(server_id)>1);

DROP INDEX rhn_cpu_server_id_idx;

CREATE UNIQUE INDEX rhn_cpu_server_id_uq
    ON rhnCpu (server_id)
    TABLESPACE [[4m_tbs]]
    NOLOGGING;
   0707010000090F000081B400000000000000000000000167AE11140000019F000000000000000000000000000000000000007000000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/527-alter-index-rhnServerDmi.sql   delete from rhnServerDMI X
       where server_id in (select server_id from rhnServerDMI group by server_id having count(server_id)>1)
        and id<(select max(id) from rhnServerDMI Y where X.server_id=Y.server_id group by server_id having count(server_id)>1);

DROP INDEX rhn_server_dmi_sid_idx;

CREATE UNIQUE INDEX rhn_server_dmi_sid_uq
    ON rhnServerDMI (server_id)
    TABLESPACE [[2m_tbs]]
    NOLOGGING;
 07070100000910000081B400000000000000000000000167AE111400000295000000000000000000000000000000000000007900000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/532-rhnServerNetwork-update-rhn_probe.sql  
create or replace trigger
rhn_servnet_ipaddr_mon_trig
after insert or update on rhnServerNetwork
for each row
begin
	if inserting
		or :old.ipaddr is null and :new.ipaddr is not null
		or :old.ipaddr is not null and :new.ipaddr is null
		or :old.ipaddr <> :new.ipaddr
		or :old.ip6addr is null and :new.ip6addr is not null
		or :old.ip6addr is not null and :new.ip6addr is null
		or :old.ip6addr <> :new.ip6addr then
		update rhn_probe
		set last_update_user = 'IP change',
			last_update_date = sysdate
		where (recid, probe_type) in (
			select probe_id, probe_type
			from rhn_check_probe
			where host_id = :new.server_id
		);
	end if;
end;
/

show errors
   07070100000911000081B400000000000000000000000167AE111400000317000000000000000000000000000000000000006C00000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/533-rhn_tasko_run_id_seq.sql   BEGIN
   DECLARE
      seq_template_number NUMBER;
      seq_run_number NUMBER;
   BEGIN

        EXECUTE IMMEDIATE
            'SELECT rhn_tasko_template_id_seq.nextval FROM dual'
        INTO seq_template_number;

        EXECUTE IMMEDIATE
            'SELECT rhn_tasko_run_id_seq.nextval FROM dual'
        INTO seq_run_number;

        IF (seq_template_number != seq_run_number) THEN
            EXECUTE IMMEDIATE
                'ALTER SEQUENCE rhn_tasko_run_id_seq INCREMENT BY ' || (seq_template_number - seq_run_number);

            EXECUTE IMMEDIATE
                'SELECT rhn_tasko_run_id_seq.nextval FROM dual'
            INTO seq_run_number;

            EXECUTE IMMEDIATE
                'ALTER SEQUENCE rhn_tasko_run_id_seq INCREMENT BY 1';
        END IF;

    END;
END;
/
 07070100000912000081B400000000000000000000000167AE111400000F33000000000000000000000000000000000000006C00000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/601-rhn_entitlements.pks.sql   --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--

create or replace
package rhn_entitlements
is
	body_version varchar2(100) := '';

   type ents_array is varray(10) of rhnServerGroupType.label%TYPE;

    procedure remove_org_entitlements (
        org_id_in number
    );

    function entitlement_grants_service (
	    entitlement_in in varchar2,
		service_level_in in varchar2
	) return number;

	function lookup_entitlement_group (
		org_id_in in number,
		type_label_in in varchar2 := 'sw_mgr_entitled'
	) return number;

	function create_entitlement_group (
		org_id_in in number,
		type_label_in in varchar2 := 'sw_mgr_entitled'
	) return number;

   function can_entitle_server ( 
      server_id_in   in number, 
      type_label_in  in varchar2
   )
   return number;

   function can_switch_base ( 
      server_id_in   in    integer, 
      type_label_in  in    varchar2
   )
   return number;

	procedure entitle_server (
		server_id_in in number,
		type_label_in in varchar2 := 'sw_mgr_entitled'
	);

	procedure remove_server_entitlement (
		server_id_in in number,
		type_label_in in varchar2 := 'sw_mgr_entitled',
        repoll_virt_guests in number := 1
	);

	procedure unentitle_server (
		server_id_in in number
	);

    procedure repoll_virt_guest_entitlements(
        server_id_in in number
    );

	function get_server_entitlement (
		server_id_in in number
	) return ents_array;

	procedure modify_org_service (
		org_id_in in number,
		service_label_in in varchar2,
		enable_in in char
	);

    procedure set_customer_enterprise (
		customer_id_in in number
	);

	procedure set_customer_provisioning (
		customer_id_in in number
	);

	procedure set_customer_nonlinux (
		customer_id_in in number
	);

    procedure unset_customer_enterprise (
		customer_id_in in number
	);

	procedure unset_customer_provisioning (
		customer_id_in in number
	);

	procedure unset_customer_nonlinux (
		customer_id_in in number
	);

    procedure assign_system_entitlement(
        group_label_in in varchar2,
        from_org_id_in in number,
        to_org_id_in in number,
        quantity_in in number
    );

    procedure assign_channel_entitlement(
        channel_family_label_in in varchar2,
        from_org_id_in in number,
        to_org_id_in in number,
        quantity_in in number,
        flex_in in number
    );

    procedure activate_system_entitlement(
        org_id_in in number,
        group_label_in in varchar2,
        quantity_in in number
    );

    procedure activate_channel_entitlement(
        org_id_in in number,
        channel_family_label_in in varchar2,
        quantity_in in number,
        flex_in in number
    );

    procedure set_family_count (
		customer_id_in in number,		-- customer_id
		channel_family_id_in in number,	-- 246
		quantity_in in number,			-- 3
                flex_in in number
    );

    -- this makes NO checks that the quantity is within max,
    -- so we should NEVER run this unless we KNOW that we won't be
    -- violating the max
    procedure entitle_last_modified_servers (
		customer_id_in in number,	-- customer_id
		type_label_in in varchar2,	-- 'enterprise_entitled'
		quantity_in in number		-- 3
    );

	procedure subscribe_newest_servers (
		customer_id_in in number
	);
end rhn_entitlements;
/
show errors

 07070100000913000081B400000000000000000000000167AE111400010A65000000000000000000000000000000000000006C00000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/602-rhn_entitlements.pkb.sql   --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--

create or replace
package body rhn_entitlements
is
    body_version varchar2(100) := '';

   function find_compatible_sg (
      server_id_in    in   number,
      type_label_in   in   varchar2
   ) return number is

      cursor servergroups is
         select sg.id            id
           from rhnServerGroupType             sgt,
                rhnServerGroup                 sg,
                rhnServer                     s,
                rhnServerServerGroupArchCompat ssgac
          where s.id = server_id_in
            and s.org_id = sg.org_id
            and sgt.label = type_label_in
            and sg.group_type = sgt.id
            and ssgac.server_group_type = sgt.id
            and ssgac.server_arch_id = s.server_arch_id
            and not exists ( 
                     select 1
                      from rhnServerGroupMembers sgm
                     where sgm.server_group_id = sg.id 
                       and sgm.server_id = s.id);

         
   begin
      for servergroup in servergroups loop
         return servergroup.id;
      end loop;

      --no servergroup found
      return null;
   end find_compatible_sg;


    -- *******************************************************************
    -- PROCEDURE: remove_org_entitlements
    --
    -- Removes both system entitlements and channel subscriptions
    -- that are currently assigned to an org and re-assigns to the
    -- master org (org_id = 1).
    --
    -- When we call this we expect everything to already be unentitled
    -- which shoul be handled by delete_org.
    --
    -- Called by: delete_org
    -- *******************************************************************
    procedure remove_org_entitlements(
        org_id_in in number
    )
    is

        cursor system_ents is
        select sg.id, sg.max_members, sg.group_type
        from rhnServerGroup sg
        where group_type is not null
          and org_id = org_id_in;

        cursor channel_subs is
        select pcf.channel_family_id, pcf.max_members
        from rhnChannelFamily cf,
             rhnPrivateChannelFamily pcf
        where pcf.org_id = org_id_in
          and pcf.channel_family_id = cf.id
          and cf.org_id is null;

    begin

        for system_ent in system_ents loop
            update rhnServerGroup
            set max_members = max_members + system_ent.max_members
            where org_id = 1
              and group_type = system_ent.group_type;
        end loop;

        update rhnServerGroup
        set max_members = 0
        where org_id = org_id_in;

        for channel_sub in channel_subs loop
            update rhnPrivateChannelFamily
            set max_members = max_members + channel_sub.max_members
            where org_id = 1
              and channel_family_id = channel_sub.channel_family_id;
        end loop;
        
        update rhnPrivateChannelFamily
        set max_members = 0
        where org_id = org_id_in;

    end remove_org_entitlements;
 
    function entitlement_grants_service (
        entitlement_in in varchar2,
        service_level_in in varchar2
    ) return number    is
    begin
        if service_level_in = 'provisioning' then
            if entitlement_in = 'provisioning_entitled' then
                return 1;
            else
                return 0;
            end if;
        elsif service_level_in = 'management' then
            if entitlement_in = 'enterprise_entitled' then
                return 1;
            else
                return 0;
            end if;
        elsif service_level_in = 'monitoring' then
            if entitlement_in = 'monitoring_entitled' then
                return 1;
            end if;
        elsif service_level_in = 'updates' then
            return 1;
        else
            return 0;
        end if;
    end entitlement_grants_service;

    function lookup_entitlement_group (
        org_id_in in number,
        type_label_in in varchar2 := 'sw_mgr_entitled'
    ) return number is
        cursor server_groups is
            select    sg.id                server_group_id
            from    rhnServerGroup        sg,
                    rhnServerGroupType    sgt
            where    sgt.label = type_label_in
                and sgt.id = sg.group_type
                and sg.org_id = org_id_in;
    begin
        for sg in server_groups loop
            return sg.server_group_id;
        end loop;
        return rhn_entitlements.create_entitlement_group(
                org_id_in,
                type_label_in
            );
    end lookup_entitlement_group;

    function create_entitlement_group (
        org_id_in in number,
        type_label_in in varchar2 := 'sw_mgr_entitled'
    ) return number is
        sg_id_val number;
    begin
        select    rhn_server_group_id_seq.nextval
        into    sg_id_val
        from    dual;

        insert into rhnServerGroup (
                id, name, description, max_members, current_members,
                group_type, org_id
            ) (
                select    sg_id_val, sgt.label, sgt.label,
                        0, 0, sgt.id, org_id_in
                from    rhnServerGroupType sgt
                where    sgt.label = type_label_in
            );

        return sg_id_val;
    end create_entitlement_group;

   function can_entitle_server ( 
        server_id_in in number, 
        type_label_in in varchar2 ) 
   return number is
      cursor addon_servergroups (base_label_in in varchar2, 
                                 addon_label_in in varchar2) is
         select
            addon_id
         from
            rhnSGTypeBaseAddonCompat
         where base_id = lookup_sg_type (base_label_in)
           and addon_id = lookup_sg_type (addon_label_in);

      previous_ent        rhn_entitlements.ents_array;
      is_base_in          char   := 'N';
      is_base_current     char   := 'N';
      i                   number := 0;
      sgid                number := 0;

   begin

      previous_ent := rhn_entitlements.ents_array();
      previous_ent := rhn_entitlements.get_server_entitlement(server_id_in);

      select distinct is_base
      into is_base_in
      from rhnServerGroupType
      where label = type_label_in;

      if previous_ent.count = 0 then
         sgid := find_compatible_sg (server_id_in, type_label_in);
         if (is_base_in = 'Y' and sgid is not null) then
            -- rhn_server.insert_into_servergroup (server_id_in, sgid);
            return 1;
         else
            -- rhn_exception.raise_exception ('invalid_base_entitlement');
            return 0;
         end if;

      -- there are previous ents, first make sure we're not trying to entitle a base ent
      elsif is_base_in = 'Y' then
         -- rhn_exception.raise_exception ('invalid_addon_entitlement');
         return 0;

      -- it must be an addon, so proceed with the entitlement
      else

         -- find the servers base ent
         is_base_current := 'N';
         i := 0;
         while is_base_current = 'N' and i <= previous_ent.count
         loop
            i := i + 1;
            select is_base
            into is_base_current
            from rhnServerGroupType
            where label = previous_ent(i);
         end loop;

         -- never found a base ent, that would be strange
         if is_base_current  = 'N' then
            -- rhn_exception.raise_exception ('invalid_base_entitlement');
            return 0;
         end if;

         -- this for loop verifies the validity of the addon path
         for addon_servergroup in addon_servergroups  (previous_ent(i), type_label_in) loop
            -- find an appropriate sgid for the addon and entitle the server
            sgid := find_compatible_sg (server_id_in, type_label_in);
            if sgid is not null then
               -- rhn_server.insert_into_servergroup (server_id_in, sgid);
               return 1;
            else
               -- rhn_exception.raise_exception ('invalid_addon_entitlement');
               return 0;
            end if;
         end loop;

      end if;

      return 0;

   end can_entitle_server;

   function can_switch_base (
      server_id_in   in    integer,
      type_label_in  in    varchar2
   ) return number is

      type_label_in_is_base   char(1);
      sgid                    number;

   begin

      begin
         select is_base into type_label_in_is_base
         from rhnServerGroupType
         where label = type_label_in;
      exception
         when no_data_found then
            rhn_exception.raise_exception ( 'invalid_entitlement' );
      end;

      if type_label_in_is_base = 'N' then
         rhn_exception.raise_exception ( 'invalid_entitlement' );
      else
         sgid := find_compatible_sg ( server_id_in, type_label_in );
         if sgid is not null then
            return 1;
         else
            return 0;
         end if;
      end if;

   end can_switch_base;


    procedure entitle_server (
        server_id_in in number,
        type_label_in in varchar2 := 'sw_mgr_entitled'
    ) is
      sgid  number := 0;
      is_virt number := 0;

    begin

          begin
          select 1 into is_virt
            from rhnServerEntitlementView
           where server_id = server_id_in
             and label in ('virtualization_host', 'virtualization_host_platform');
      exception
            when no_data_found then
              is_virt := 0;
          end;
      
      if is_virt = 0 and (type_label_in = 'virtualization_host' or
                          type_label_in = 'virtualization_host_platform') then

        is_virt := 1;
      end if;



      if rhn_entitlements.can_entitle_server(server_id_in, 
                                             type_label_in) = 1 then
         sgid := find_compatible_sg (server_id_in, type_label_in);
         if sgid is not null then
            insert into rhnServerHistory ( id, server_id, summary, details )
            values ( rhn_event_id_seq.nextval, server_id_in,
                     'added system entitlement ',
                      case type_label_in
                       when 'enterprise_entitled' then 'Management'
                       when 'sw_mgr_entitled' then 'Update'
                       when 'provisioning_entitled' then 'Provisioning'
                       when 'monitoring_entitled' then 'Monitoring'  
                       when 'virtualization_host' then 'Virtualization'
                       when 'virtualization_host_platform' then 
                            'Virtualization Platform' end  );

            rhn_server.insert_into_servergroup (server_id_in, sgid);

            if is_virt = 1 then
              rhn_entitlements.repoll_virt_guest_entitlements(server_id_in);
            end if;

         else
            rhn_exception.raise_exception ('no_available_server_group');
         end if;
      else
         rhn_exception.raise_exception ('invalid_entitlement');
      end if;
   end entitle_server;

    procedure remove_server_entitlement (
        server_id_in in number,
        type_label_in in varchar2 := 'sw_mgr_entitled',
        repoll_virt_guests in number := 1
    ) is
        group_id number;
      type_is_base char;
      is_virt number := 0;
    begin
      begin


      -- would be nice if there were a virt attribute of entitlement types, not have to specify 2 different ones...
        begin
          select 1 into is_virt
            from rhnServerEntitlementView
           where server_id = server_id_in
             and label in ('virtualization_host', 'virtualization_host_platform');
        exception
          when no_data_found then
            is_virt := 0;
        end;

        select    sg.id, sgt.is_base
          into    group_id, type_is_base
          from    rhnServerGroupType sgt,
               rhnServerGroup sg,
                  rhnServerGroupMembers sgm,
                  rhnServer s
          where    s.id = server_id_in
              and s.id = sgm.server_id
              and sgm.server_group_id = sg.id
              and sg.org_id = s.org_id
              and sgt.label = type_label_in
              and sgt.id = sg.group_type;

      if ( type_is_base = 'Y' ) then
         -- unentitle_server should handle everything, don't really need to do anything else special here
         unentitle_server ( server_id_in );
      else

         insert into rhnServerHistory ( id, server_id, summary, details )
         values ( rhn_event_id_seq.nextval, server_id_in,
                  'removed system entitlement ',
                   case type_label_in
                    when 'enterprise_entitled' then 'Management'
                    when 'sw_mgr_entitled' then 'Update'
                    when 'provisioning_entitled' then 'Provisioning'
                    when 'monitoring_entitled' then 'Monitoring'
                    when 'virtualization_host' then 'Virtualization'
                    when 'virtualization_host_platform' then 
                         'Virtualization Platforrm' end  );

         rhn_server.delete_from_servergroup(server_id_in, group_id);

         -- special case: clean up related monitornig data
         if type_label_in = 'monitoring_entitled' then
           DELETE
             FROM state_change
            WHERE o_id IN (SELECT probe_id
                             FROM rhn_check_probe
                            WHERE host_id = server_id_in);
           DELETE /*+index(time_series time_series_probe_id_idx)*/
             FROM time_series
            WHERE SUBSTR(o_id, INSTR(o_id, '-') + 1, 
                        (INSTR(o_id, '-', INSTR(o_id, '-') + 1) - INSTR(o_id, '-')) - 1)
              IN (SELECT to_char(probe_id)
                    FROM rhn_check_probe
                   WHERE host_id = server_id_in);
           DELETE
             FROM rhn_probe
            WHERE recid IN (SELECT probe_id
                              FROM rhn_check_probe
                             WHERE host_id = server_id_in);
         end if;

         if is_virt = 1 and repoll_virt_guests = 1 then
           rhn_entitlements.repoll_virt_guest_entitlements(server_id_in);
         end if;
      end if;

          exception
          when no_data_found then
                  rhn_exception.raise_exception('invalid_server_group_member');
      end;

     end remove_server_entitlement;


   procedure unentitle_server (server_id_in in number) is

      cursor servergroups is
         select distinct sgt.label, sg.id server_group_id
         from  rhnServerGroupType sgt,
               rhnServerGroup sg,
               rhnServer s,
               rhnServerGroupMembers sgm
         where s.id = server_id_in
            and s.org_id = sg.org_id
            and sg.group_type = sgt.id
            and sgm.server_group_id = sg.id
            and sgm.server_id = s.id;
            
     is_virt number := 0;

   begin

      begin
        select 1 into is_virt
          from rhnServerEntitlementView
         where server_id = server_id_in
           and label in ('virtualization_host', 'virtualization_host_platform');
      exception
        when no_data_found then
          is_virt := 0;
      end;

      for servergroup in servergroups loop

         insert into rhnServerHistory ( id, server_id, summary, details )
         values ( rhn_event_id_seq.nextval, server_id_in,
                  'removed system entitlement ',
                   case servergroup.label
                    when 'enterprise_entitled' then 'Management'
                    when 'sw_mgr_entitled' then 'Update'
                    when 'provisioning_entitled' then 'Provisioning'
                    when 'monitoring_entitled' then 'Monitoring'
                    when 'virtualization_host' then 'Virtualization'
                    when 'virtualization_host_platform' then 
                         'Virtualization Platform' end  );
  
         rhn_server.delete_from_servergroup(server_id_in, 
                                            servergroup.server_group_id );
      end loop;

      if is_virt = 1 then
        rhn_entitlements.repoll_virt_guest_entitlements(server_id_in);
      end if;

   end unentitle_server;


    -- *******************************************************************
    -- PROCEDURE: repoll_virt_guest_entitlements
    --
    --   Whenever we add/remove a virtualization_host* entitlement from 
    --   a host, we can call this procedure to update what type of slots
    --   the guests are consuming.  
    -- 
    --   If you're removing the entitlement, it's 
    --   possible the guests will become unentitled if you don't have enough
    --   physical slots to cover them.
    --
    --   If you're adding the entitlement, you end up freeing up physical
    --   slots for other systems.
    --
    -- *******************************************************************
    procedure repoll_virt_guest_entitlements(server_id_in in number)
    is

        -- All channel families associated with the guests of server_id_in
        cursor families is 
            select distinct cfs.channel_family_id
            from
                rhnChannelFamilyServers cfs,
                rhnVirtualInstance vi
            where
                vi.host_system_id = server_id_in
                and vi.virtual_system_id = cfs.server_id;
        
        -- All of server group types associated with the guests of
        -- server_id_in
        cursor group_types is
            select distinct sg.group_type, sgt.label
            from
                rhnServerGroupType sgt,
                rhnServerGroup sg,
                rhnServerGroupMembers sgm,
                rhnVirtualInstance vi
            where
                vi.host_system_id = server_id_in
                and vi.virtual_system_id = sgm.server_id
                and sgm.server_group_id = sg.id
                and sg.group_type = sgt.id;

        -- Virtual servers from a certain family belonging to a speicifc
        -- host that are consuming physical channel slots over the limit.
        cursor virt_servers_cfam(family_id_in in number, quantity_in in number)  is
            select virtual_system_id
            from (
                select rownum, vi.virtual_system_id
                from
                    rhnChannelFamilyMembers cfm,
                    rhnServerChannel sc,
                    rhnVirtualInstance vi
                where
                    vi.host_system_id = server_id_in
                    and vi.virtual_system_id = sc.server_id
                    and sc.channel_id = cfm.channel_id
                    and cfm.channel_family_id = family_id_in
                order by sc.modified desc
                )
            where rownum <= quantity_in;

        -- Virtual servers from a certain family belonging to a speicifc
        -- host that are consuming physical system slots over the limit.
        cursor virt_servers_sgt(group_type_in in number, quantity_in in number)  is
            select virtual_system_id
            from (
                select rownum, vi.virtual_system_id
                from
                    rhnServerGroup sg,
                    rhnServerGroupMembers sgm,
                    rhnVirtualInstance vi
                where
                    vi.host_system_id = server_id_in
                    and vi.virtual_system_id = sgm.server_id
                    and sgm.server_group_id = sg.id
                    and sg.group_type = group_type_in
                order by sgm.modified desc
                )
            where rownum <= quantity_in;
        -- Get the orgs of Virtual guests
        -- Since they may belong to different orgs
        cursor virt_guest_orgs  is
                select  distinct (s.org_id)
                from rhnServer s
                    inner join  rhnVirtualInstance vi on vi.virtual_system_id = s.id
                where
                    vi.host_system_id = server_id_in 
                    and s.org_id <> (select s1.org_id from rhnServer s1 where s1.id = vi.host_system_id) ;


        org_id_val number;
        max_members_val number;
        max_flex_val number;
        current_members_calc number;
        sg_id number;
        is_virt number := 0;
    begin
        begin
          select 1 into is_virt
                from rhnServerEntitlementView
           where server_id = server_id_in
                 and label in ('virtualization_host', 'virtualization_host_platform');
           exception
                when no_data_found then
                  is_virt := 0;
        end;

        select org_id
        into org_id_val
        from rhnServer
        where id = server_id_in;

        -- deal w/ channel entitlements first ...
        for family in families loop
            if is_virt = 0 then
            -- if the host_server does not have virt
            --- find all possible flex slots
            -- and set each of the flex eligible guests to Y
                UPDATE rhnServerChannel sc set sc.is_fve = 'Y'
                where sc.server_id in (
                       select virtual_system_id from (
                            select rownum, vi.virtual_system_id,  sfc.max_members - sfc.current_members as free_slots
                            from rhnServerFveCapable sfc
                                inner join rhnVirtualInstance vi on vi.virtual_system_id = sfc.server_id
                            where vi.host_system_id = server_id_in
                                  and sfc.channel_family_id = family.channel_family_id
                              order by vi.modified desc
                          )
                        where rownum <=  free_slots
                );
            else
            -- if the host_server has virt
            -- set all its flex guests to N
                UPDATE rhnServerChannel sc set sc.is_fve = 'N'
                where 
                    sc.channel_id in (select cfm.channel_id from rhnChannelFamilyMembers cfm
                                      where cfm.CHANNEL_FAMILY_ID = family.channel_family_id)
                    and sc.is_fve = 'Y'
                    and sc.server_id in  
                            (select vi.virtual_system_id  from rhnVirtualInstance vi 
                                    where vi.host_system_id = server_id_in);
            end if;
        
            -- get the current (physical) members of the family
            current_members_calc := 
                rhn_channel.channel_family_current_members(family.channel_family_id,
                                                           org_id_val); -- fixed transposed args

            begin

            -- get the max members of the family
            select max_members
            into max_members_val
            from rhnPrivateChannelFamily
            where channel_family_id = family.channel_family_id
            and org_id = org_id_val;

            select fve_max_members
            into max_flex_val
            from rhnPrivateChannelFamily
            where channel_family_id = family.channel_family_id
            and org_id = org_id_val;

            if current_members_calc > max_members_val then
                -- A virtualization_host* ent must have been removed, so we'll
                -- unsubscribe guests from the host first.

                -- hm, i don't think max_members - current_members_calc yielding a negative number
                -- will work w/ rownum, swaping 'em in the body of this if...
                for virt_server in virt_servers_cfam(family.channel_family_id,
                                current_members_calc - max_members_val) loop 

                    rhn_channel.unsubscribe_server_from_family(
                                virt_server.virtual_system_id,
                                family.channel_family_id);
                end loop;                               

                -- if we're still over the limit, which would be odd,
                -- just prune the group to max_members
                --
                -- er... wouldn't we actually have to refresh the values of
                -- current_members_calc and max_members_val to actually ever
                -- *skip this??
                if current_members_calc > max_members_val then
                    -- argh, transposed again?!
                    set_family_count(org_id_val,
                                     family.channel_family_id,
                                     max_members_val, max_flex_val);
                    --TODO calculate this correctly
                end if; 

           end if;

            -- update current_members for the family.  This will set the value
            -- to reflect adding/removing the entitlement.
            --
            -- what's the difference of doing this vs the unavoidable set_family_count above?
            rhn_channel.update_family_counts(family.channel_family_id,
                                             org_id_val);

            exception when no_data_found then null;
            end;

            -- It is possible that the guests belong  to a different org than the host
            -- so we are going to update the family counts in the guests orgs also
            for org in virt_guest_orgs loop
                    rhn_channel.update_family_counts(family.channel_family_id,
                                             org.org_id);
            end loop;
        end loop;

        for a_group_type in group_types loop
          -- get the current *physical* members of the system entitlement type for the org...
          -- 
          -- unlike channel families, it appears the standard rhnServerGroup.max_members represents
          -- *physical* slots, vs physical+virt ... boy that's confusing...

          select max_members, id
            into max_members_val, sg_id
            from rhnServerGroup
            where group_type = a_group_type.group_type
            and org_id = org_id_val;


      select count(sep.server_id) into current_members_calc
            from rhnServerEntitlementPhysical sep
           where sep.server_group_id = sg_id
             and sep.server_group_type_id = a_group_type.group_type;
          
          if current_members_calc > max_members_val then
            -- A virtualization_host* ent must have been removed, and we're over the limit, so unsubscribe guests
            for virt_server in virt_servers_sgt(a_group_type.group_type,
                                                current_members_calc - max_members_val) loop
              rhn_entitlements.remove_server_entitlement(virt_server.virtual_system_id, a_group_type.label);

              -- decrement current_members_calc, we'll use it to reset current_members for the group at the end...
              current_members_calc := current_members_calc - 1;
            end loop;

          end if;

          update rhnServerGroup set current_members = current_members_calc
           where org_id = org_id_val
             and group_type = a_group_type.group_type;

          -- I think that's all the house-keeping we have to do...
        end loop;

    end repoll_virt_guest_entitlements;


    function get_server_entitlement (
        server_id_in in number
    ) return ents_array is

        cursor server_groups is
            select    sgt.label
            from    rhnServerGroupType        sgt,
                    rhnServerGroup            sg,
                    rhnServerGroupMembers    sgm
            where    1=1
                and sgm.server_id = server_id_in
                and sg.id = sgm.server_group_id
                and sgt.id = sg.group_type
                and sgt.label in (
                    'sw_mgr_entitled','enterprise_entitled',
                    'provisioning_entitled', 'nonlinux_entitled',
                    'monitoring_entitled', 'virtualization_host',
                                        'virtualization_host_platform'
                    );

         ent_array ents_array;

    begin
      
      ent_array := ents_array();

        for sg in server_groups loop
         ent_array.extend;
         ent_array(ent_array.count) := sg.label;
        end loop;

        return ent_array;

    end get_server_entitlement;


    -- this desperately needs to be table driven.
    procedure modify_org_service (
        org_id_in in number,
        service_label_in in varchar2,
        enable_in in char
    ) is
        type roles_v is varray(10) of rhnUserGroupType.label%TYPE;
        roles_to_process roles_v;
        cursor roles(role_label_in in varchar2) is
            select    label, id
            from    rhnUserGroupType
            where    label = role_label_in;
        cursor org_roles(role_label_in in varchar2) is
            select    1
            from    rhnUserGroup ug,
                    rhnUserGroupType ugt
            where    ugt.label = role_label_in
                and ug.org_id = org_id_in
                and ugt.id = ug.group_type;

        type ents_v is varray(10) of rhnOrgEntitlementType.label%TYPE;
        ents_to_process ents_v;
        cursor ents(ent_label_in in varchar2) is
            select    label, id
            from    rhnOrgEntitlementType
            where    label = ent_label_in;
        cursor org_ents(ent_label_in in varchar2) is
            select    1
            from    rhnOrgEntitlements oe,
                    rhnOrgEntitlementType oet
            where    oet.label = ent_label_in
                and oe.org_id = org_id_in
                and oet.id = oe.entitlement_id;
        create_row char(1);
    begin
        ents_to_process := ents_v();
        roles_to_process := roles_v();
        -- a bit kludgy, but only for 3.4 really.  Certainly no
        -- worse than the old code...
        if service_label_in = 'enterprise' or
           service_label_in = 'management' then
            ents_to_process.extend;
            ents_to_process(ents_to_process.count) := 'sw_mgr_enterprise';

            roles_to_process.extend;
            roles_to_process(roles_to_process.count) := 'org_admin';

            roles_to_process.extend;
            roles_to_process(roles_to_process.count) := 'system_group_admin';

            roles_to_process.extend;
            roles_to_process(roles_to_process.count) := 'activation_key_admin';

            roles_to_process.extend;
            roles_to_process(roles_to_process.count) := 'org_applicant';
        elsif service_label_in = 'provisioning' then
            ents_to_process.extend;
            ents_to_process(ents_to_process.count) := 'rhn_provisioning';

            roles_to_process.extend;
            roles_to_process(roles_to_process.count) := 'system_group_admin';

            roles_to_process.extend;
            roles_to_process(roles_to_process.count) := 'activation_key_admin';

            roles_to_process.extend;
            roles_to_process(roles_to_process.count) := 'config_admin';
            -- another nasty special case...
            if enable_in = 'Y' then
                ents_to_process.extend;
                ents_to_process(ents_to_process.count) := 'sw_mgr_enterprise';
            end if;
        elsif service_label_in = 'monitoring' then
            ents_to_process.extend;
            ents_to_process(ents_to_process.count) := 'rhn_monitor';

            roles_to_process.extend;
            roles_to_process(roles_to_process.count) := 'monitoring_admin';
        elsif service_label_in = 'virtualization' then
            ents_to_process.extend;
            ents_to_process(ents_to_process.count) := 'rhn_virtualization';

            roles_to_process.extend;
            roles_to_process(roles_to_process.count) := 'config_admin';
        elsif service_label_in = 'virtualization_platform' then
            ents_to_process.extend;
            ents_to_process(ents_to_process.count) := 'rhn_virtualization_platform';
            roles_to_process.extend;
            roles_to_process(roles_to_process.count) := 'config_admin';
    elsif service_label_in = 'nonlinux' then
            ents_to_process.extend;
            ents_to_process(ents_to_process.count) := 'rhn_nonlinux';
            roles_to_process.extend;
            roles_to_process(roles_to_process.count) := 'config_admin';
        end if;

        if enable_in = 'Y' then
            for i in 1..ents_to_process.count loop
                for ent in ents(ents_to_process(i)) loop
                    create_row := 'Y';
                    for oe in org_ents(ent.label) loop
                        create_row := 'N';
                    end loop;
                    if create_row = 'Y' then
                        insert into rhnOrgEntitlements(org_id, entitlement_id)
                            values (org_id_in, ent.id);
                    end if;
                end loop;
            end loop;
            for i in 1..roles_to_process.count loop
                for role in roles(roles_to_process(i)) loop
                    create_row := 'Y';
                    for o_r in org_roles(role.label) loop
                        create_row := 'N';
                    end loop;
                    if create_row = 'Y' then
                        insert into rhnUserGroup(
                                id, name, description, current_members,
                                group_type, org_id
                            ) (
                                select    rhn_user_group_id_seq.nextval,
                                        ugt.name || 's',
                                        ugt.name || 's for Org ' ||
                                            o.name || ' ('|| o.id ||')',
                                        0, ugt.id, o.id
                                from    rhnUserGroupType ugt,
                                        web_customer o
                                where    o.id = org_id_in
                                    and ugt.id = role.id
                            );
                    end if;
                end loop;
            end loop;
        else
            for i in 1..ents_to_process.count loop
                for ent in ents(ents_to_process(i)) loop
                    delete from rhnOrgEntitlements
                     where org_id = org_id_in
                       and entitlement_id = ent.id;
                end loop;
            end loop;
        end if;
    end modify_org_service;

    procedure set_customer_enterprise (
        customer_id_in in number
    ) is
    begin
        modify_org_service(customer_id_in, 'enterprise', 'Y');
    end set_customer_enterprise;

    procedure set_customer_provisioning (
        customer_id_in in number
    ) is
    begin
        modify_org_service(customer_id_in, 'provisioning', 'Y');
    end set_customer_provisioning;

    procedure set_customer_monitoring (
        customer_id_in in number
    ) is
    begin
        modify_org_service(customer_id_in, 'monitoring', 'Y');
    end set_customer_monitoring;

    procedure set_customer_nonlinux (
        customer_id_in in number
    ) is
    begin
        modify_org_service(customer_id_in, 'nonlinux', 'Y');
    end set_customer_nonlinux;

    procedure unset_customer_enterprise (
        customer_id_in in number
    ) is
    begin
        modify_org_service(customer_id_in, 'enterprise', 'N');
    end unset_customer_enterprise;

    procedure unset_customer_provisioning (
        customer_id_in in number
    ) is
    begin
        modify_org_service(customer_id_in, 'provisioning', 'N');
    end unset_customer_provisioning;

    procedure unset_customer_monitoring (
        customer_id_in in number
    ) is
    begin
        modify_org_service(customer_id_in, 'monitoring', 'N');
    end unset_customer_monitoring;

    procedure unset_customer_nonlinux (
        customer_id_in in number
    ) is
    begin
        modify_org_service(customer_id_in, 'nonlinux', 'N');
    end unset_customer_nonlinux;

    -- *******************************************************************
    -- PROCEDURE: prune_group
    -- Unsubscribes servers consuming physical slots that over the org's
    --   limit.
    -- Called by: set_server_group_count, repoll_virt_guest_entitlements
    -- *******************************************************************
    procedure prune_group (
        group_id_in in number,
        quantity_in in number,
                update_family_countsYN in number := 1
    ) is
        cursor servergroups is
           select  server_id, server_group_id, sgt.id as group_type_id, sgt.label
            from    rhnServerGroupType              sgt,
                            rhnServerGroup                  sg,
                            rhnServerGroupMembers   sgm
            where   1=1
                    and sgm.server_group_id = group_id_in
                    and sgm.server_id in (
                            select  server_id
                            from    (
                                    select  rownum row_number,
                                                    server_id,
                                                    time
                                    from    (
                                            select  sep.server_id,
                                                    sep.modified time
                                            from
                                                rhnServerEntitlementPhysical sep
                                            where
                                                sep.server_group_id = group_id_in
                                            order by time asc
                                    )
                            )
                            where   row_number > quantity_in
                    )
                    and sgm.server_group_id = sg.id
                    and sg.group_type = sgt.id;
      type_is_base char;
    begin
        update        rhnServerGroup
            set        max_members = quantity_in
            where    id = group_id_in;

        for sg in servergroups loop
            remove_server_entitlement(sg.server_id, sg.label);
            
            select is_base 
            into type_is_base
            from rhnServerGroupType sgt
            where sgt.id = sg.group_type_id;
 
            -- if we're removing a base ent, then be sure to
            -- remove the server's channel subscriptions.
            if ( type_is_base = 'Y' ) then
                   rhn_channel.clear_subscriptions(sg.server_id,
                                        update_family_countsYN => update_family_countsYN);
            end if;

        end loop;
    end prune_group;

    procedure set_server_group_count (
        customer_id_in in number,
        group_type_in in number,
        quantity_in in number,
                update_family_countsYN in number := 1
    ) is
        group_id number;
        quantity number;
    begin
        quantity := quantity_in;
        if quantity is not null and quantity < 0 then
            quantity := 0;
        end if;

        select    rsg.id
        into    group_id
        from    rhnServerGroup rsg
        where    1=1
            and rsg.org_id = customer_id_in
            and rsg.group_type = group_type_in;

        rhn_entitlements.prune_group(
            group_id,
            quantity,
                        update_family_countsYN
        );
    exception
        when no_data_found then
            insert into rhnServerGroup (
                    id, name, description, max_members, current_members,
                    group_type, org_id, created, modified
                ) (
                    select    rhn_server_group_id_seq.nextval, name, name,
                            quantity, 0, id, customer_id_in,
                            sysdate, sysdate
                    from    rhnServerGroupType
                    where    id = group_type_in
            );
    end set_server_group_count;

    -- *******************************************************************
    -- PROCEDURE: assign_system_entitlement
    --
    -- Moves system entitlements from from_org_id_in to to_org_id_in.
    -- Can raise not_enough_entitlements_in_base_org if from_org_id_in
    -- does not have enough entitlements to cover the move.
    -- Takes care of unentitling systems if necessary by calling 
    -- set_server_group_count
    -- *******************************************************************
    procedure assign_system_entitlement(
        group_label_in in varchar2,
        from_org_id_in in number,
        to_org_id_in in number,
        quantity_in in number
    )
    is
        prev_ent_count number;
    to_org_prev_ent_count number;
        new_ent_count number;
    new_quantity number;
        group_type number;
    begin

        begin
            select max_members
            into prev_ent_count
            from rhnServerGroupType sgt,
                 rhnServerGroup sg
            where sg.org_id = from_org_id_in
              and sg.group_type = sgt.id
              and sgt.label = group_label_in;
        exception
            when NO_DATA_FOUND then
                rhn_exception.raise_exception(
                              'not_enough_entitlements_in_base_org');
        end;

        begin
            select max_members
            into to_org_prev_ent_count
            from rhnServerGroupType sgt,
                 rhnServerGroup sg
            where sg.org_id = to_org_id_in
              and sg.group_type = sgt.id
              and sgt.label = group_label_in;
        exception
            when NO_DATA_FOUND then
                to_org_prev_ent_count := 0;
        end;

        begin
            select id
            into group_type
            from rhnServerGroupType
            where label = group_label_in;
        exception
            when NO_DATA_FOUND then
                rhn_exception.raise_exception(
                              'invalid_server_group');
        end;

        new_ent_count := prev_ent_count - quantity_in;

        if prev_ent_count > new_ent_count then
            new_quantity := to_org_prev_ent_count + quantity_in;
        end if;

        if new_ent_count < 0 then
            rhn_exception.raise_exception(
                          'not_enough_entitlements_in_base_org');
        end if;


        set_server_group_count(from_org_id_in,
                                         group_type,
                                         new_ent_count);

        set_server_group_count(to_org_id_in,
                                         group_type,
                                         new_quantity);
        
        -- Create or delete the entries in rhnOrgEntitlementType
        if group_label_in = 'enterprise_entitled' then 
            if new_quantity > 0 then
                set_customer_enterprise(to_org_id_in);
            else
                unset_customer_enterprise(to_org_id_in);
            end if;
        end if;

        if group_label_in = 'provisioning_entitled' then
            if new_quantity > 0 then
                set_customer_provisioning(to_org_id_in);
            else
                unset_customer_provisioning(to_org_id_in);
            end if;
        end if;

        if group_label_in = 'monitoring_entitled' then
            if new_quantity > 0 then
                set_customer_monitoring(to_org_id_in);
            else
                unset_customer_monitoring(to_org_id_in);
            end if;
        end if;

    end assign_system_entitlement;

    -- *******************************************************************
    -- PROCEDURE: assign_channel_entitlement
    --
    -- Moves channel entitlements from from_org_id_in to to_org_id_in.
    -- Can raise not_enough_entitlements_in_base_org if from_org_id_in
    -- does not have enough entitlements to cover the move.
    -- Takes care of unentitling systems if necessary by calling 
    -- set_family_count
    -- *******************************************************************
    procedure assign_channel_entitlement(
        channel_family_label_in in varchar2,
        from_org_id_in in number,
        to_org_id_in in number,
        quantity_in in number,
        flex_in in number
    )
    is
        from_org_prev_ent_count number;
        from_org_prev_ent_count_flex number;
        new_ent_count number;
        new_ent_count_flex number;
        to_org_prev_ent_count number;
        to_org_prev_ent_count_flex number;
        new_quantity number;
        new_flex number;
        cfam_id       number;
    begin

        begin
            select max_members
            into from_org_prev_ent_count
            from rhnChannelFamily cf,
                 rhnPrivateChannelFamily pcf
            where pcf.org_id = from_org_id_in
              and pcf.channel_family_id = cf.id
              and cf.label = channel_family_label_in;
        exception
            when NO_DATA_FOUND then
                rhn_exception.raise_exception(
                              'not_enough_entitlements_in_base_org');
        end;

        begin
            select max_members
            into to_org_prev_ent_count
            from rhnChannelFamily cf,
                 rhnPrivateChannelFamily pcf
            where pcf.org_id = to_org_id_in
              and pcf.channel_family_id = cf.id
              and cf.label = channel_family_label_in;
        exception
            when NO_DATA_FOUND then
                to_org_prev_ent_count := 0;
        end;

        begin
            select fve_max_members
            into from_org_prev_ent_count_flex
            from rhnChannelFamily cf,
                 rhnPrivateChannelFamily pcf
            where pcf.org_id = from_org_id_in
              and pcf.channel_family_id = cf.id
              and cf.label = channel_family_label_in;
        exception
            when NO_DATA_FOUND then
                rhn_exception.raise_exception(
                              'not_enough_flex_entitlements_in_base_org');
        end;

        begin
            select fve_max_members
            into to_org_prev_ent_count_flex
            from rhnChannelFamily cf,
                 rhnPrivateChannelFamily pcf
            where pcf.org_id = to_org_id_in
              and pcf.channel_family_id = cf.id
              and cf.label = channel_family_label_in;
        exception
            when NO_DATA_FOUND then
                to_org_prev_ent_count_flex := 0;
        end;

        begin
            select id
            into cfam_id
            from rhnChannelFamily
            where label = channel_family_label_in;
        exception
            when NO_DATA_FOUND then
                rhn_exception.raise_exception(
                              'invalid_channel_family');
        end;

        new_ent_count := from_org_prev_ent_count - quantity_in;
        new_ent_count_flex := from_org_prev_ent_count_flex - flex_in;

        if from_org_prev_ent_count >= new_ent_count then
            new_quantity := to_org_prev_ent_count + quantity_in;
       end if;

       if from_org_prev_ent_count_flex >= new_ent_count_flex then
            new_flex := to_org_prev_ent_count_flex + flex_in;
       end if;


        if new_ent_count < 0 then
            rhn_exception.raise_exception(
                          'not_enough_entitlements_in_base_org');
        end if;

        if new_ent_count_flex < 0 then
            rhn_exception.raise_exception(
                          'not_enough_flex_entitlements_in_base_org');
        end if;



        rhn_entitlements.set_family_count(from_org_id_in, cfam_id,
                                           new_ent_count, new_ent_count_flex);

        rhn_entitlements.set_family_count(to_org_id_in,
                                          cfam_id,
                                          new_quantity, new_flex);

    end assign_channel_entitlement;

    -- *******************************************************************
    -- PROCEDURE: activate_system_entitlement
    --
    -- Sets the values in rhnServerGroup for a given rhnServerGroupType.
    -- 
    -- Calls: set_server_group_count to update, prune, or create the group.
    -- Called by: the code that activates a satellite cert. 
    --
    -- Raises not_enough_entitlements_in_base_org if all entitlements
    -- in the org are used so the free entitlements would not cover
    -- the difference when descreasing the number of entitlements.
    -- *******************************************************************
    procedure activate_system_entitlement(
        org_id_in in number,
        group_label_in in varchar2,
        quantity_in in number
    )
    is
        prev_ent_count number; 
        prev_ent_count_sum number; 
        group_type number;
    begin

        -- Fetch the current entitlement count for the org
        -- into prev_ent_count
        begin
            select current_members
            into prev_ent_count
            from rhnServerGroupType sgt,
                 rhnServerGroup sg
            where sg.group_type = sgt.id
              and sgt.label = group_label_in
              and sg.org_id = org_id_in;
        exception
            when NO_DATA_FOUND then
                prev_ent_count := 0;
        end;

        begin
            select id
            into group_type
            from rhnServerGroupType
            where label = group_label_in;
        exception
            when NO_DATA_FOUND then
                rhn_exception.raise_exception(
                              'invalid_server_group');
        end;

        -- If we're setting the total entitlemnt count to a lower value,
        -- and that value is less than the allocated count in this org,
        -- we need to raise an exception.
        if quantity_in < prev_ent_count then
            rhn_exception.raise_exception(
                          'not_enough_entitlements_in_base_org');
        else
            -- don't update family counts after every server
            -- will do bulk update afterwards
            set_server_group_count(org_id_in,
                                             group_type,
                                             quantity_in,
                                             update_family_countsYN => 0);
            -- bulk update family counts
            rhn_channel.update_group_family_counts(group_label_in, org_id_in);
        end if;


    end activate_system_entitlement;

    -- *******************************************************************
    -- PROCEDURE: activate_channel_entitlement
    --
    -- Calls: set_family_count to update, prune, or create the family
    --        permission bucket.
    -- Called by: the code that activates a satellite cert. 
    --
    -- Raises not_enough_entitlements_in_base_org if there are not enough
    -- entitlements in the org to cover the difference when you are
    -- descreasing the number of entitlements.
    --
    -- The backend code in Python is expected to do whatever arithmetics
    -- is needed.
    -- *******************************************************************
    procedure activate_channel_entitlement(
        org_id_in in number,
        channel_family_label_in in varchar2,
        quantity_in in number,
        flex_in in number

    )
    is
        prev_ent_count number; 
        prev_flex_count number;
        prev_ent_count_sum number; 
        cfam_id number;
        reduce_quantity number;
        total_flex_capable number;
        cursor to_convert_reg (channel_family_id_val in number, org_id_in in number, quantity in number) 
                is
                     select SC.server_id
                     from rhnServerChannel SC inner join
                          rhnServer S on S.id = SC.server_id
                     where
                         is_fve = 'Y'
                         and S.org_id = org_id_in 
                         and SC.channel_id in
                         (select cfm.channel_id from rhnChannelFamilyMembers cfm
                             where cfm.CHANNEL_FAMILY_ID = channel_family_id_val)
                          and rownum <= quantity;
         cursor to_convert_flex (channel_family_id_val in number, org_id_in in number, quantity in number)
                 is
                   select server_id
                   from rhnServerFveCapable
                       where SERVER_ORG_ID = org_id_in and
                             channel_family_id = cfam_id and
                             rownum <= quantity;

    begin

        -- Fetch the current entitlement count for the org
        -- into prev_ent_count
        begin
            select current_members
            into prev_ent_count
            from rhnChannelFamily cf,
                 rhnPrivateChannelFamily pcf
            where pcf.org_id = org_id_in
              and pcf.channel_family_id = cf.id
              and cf.label = channel_family_label_in;
        exception
            when NO_DATA_FOUND then
                prev_ent_count := 0;
        end;

        begin
            select pcf.fve_current_members
            into prev_flex_count
            from rhnChannelFamily cf,
                 rhnPrivateChannelFamily pcf
            where pcf.org_id = org_id_in
              and pcf.channel_family_id = cf.id
              and cf.label = channel_family_label_in;
        exception
            when NO_DATA_FOUND then
                prev_flex_count := 0;
        end;


        begin
            select id
            into cfam_id
            from rhnChannelFamily
            where label = channel_family_label_in;
        exception
            when NO_DATA_FOUND then
                rhn_exception.raise_exception(
                              'invalid_channel_family');
        end;                              

        -- if there are too few flex entitlements
        if flex_in < prev_flex_count then
            -- and if the extra we need is less than or equal to our extra regular entitlements
            if prev_flex_count - flex_in <= quantity_in - prev_ent_count then
                   reduce_quantity := prev_flex_count - flex_in;
                   -- We need to convert some systems from flex guest to regular
                   for system in to_convert_reg(cfam_id, org_id_in, reduce_quantity) loop
                      --rhn_channel.convert_to_regular(system.server_id, cfam_id);
                      UPDATE rhnServerChannel sc set sc.is_fve = 'N'
                           where sc.server_id = system.server_id
                                 and sc.channel_id in (select cfm.channel_id
                                                          from rhnChannelFamilyMembers cfm
                                                          where cfm.channel_family_id = cfam_id);
                   end loop;

                   --reset previous counts 
                   prev_ent_count := prev_ent_count + reduce_quantity;
                   prev_flex_count := prev_flex_count - reduce_quantity; 
            else
                rhn_exception.raise_exception(
                          'not_enough_flex_entitlements_in_base_org');
            end if;
        end if;

        -- if there are too few regular entitlements, and extra flex entitlements
        if quantity_in < prev_ent_count and prev_flex_count < flex_in then
                -- how many flex-capable systems (that aren't using flex) do we have
                select count(*)
                   into total_flex_capable 
                   from rhnServerFveCapable
                       where SERVER_ORG_ID = org_id_in and
                             channel_family_id = cfam_id;
                -- if we have enough flex capable machines that is at least 
                --   as many as what we are over on 
                if total_flex_capable >= prev_ent_count - quantity_in then
                    reduce_quantity := prev_ent_count - quantity_in;
                    for system in to_convert_flex(cfam_id, org_id_in, reduce_quantity) loop 
--                          rhn_channel.convert_to_fve(system.server_id, cfam_id);
                        UPDATE rhnServerChannel sc set sc.is_fve = 'Y'
                           where sc.server_id = system.server_id 
                                 and sc.channel_id in (select cfm.channel_id
                                                          from rhnChannelFamilyMembers cfm
                                                          where cfm.channel_family_id = cfam_id);
                    end loop;
                    prev_ent_count := prev_ent_count - reduce_quantity;
                    prev_flex_count := prev_flex_count + reduce_quantity;
                end if; 
        end if;




        -- If we're setting the total entitlemnt count to a lower value,
        -- and that value is less than the count in that one org,
        -- we need to raise an exception.
        if quantity_in < prev_ent_count then
            rhn_exception.raise_exception(
                          'not_enough_entitlements_in_base_org');
        else
            -- even if we've manually converted systems to/from flex above
            -- set_family_count should call update_family_counts, to reset
            -- current used slots
            rhn_entitlements.set_family_count(org_id_in, cfam_id,
                                              quantity_in, flex_in);
        end if;

    end activate_channel_entitlement;


    -- *******************************************************************
    -- PROCEDURE: prune_family
    -- Unsubscribes servers consuming physical slots from the channel family 
    --   that are over the org's limit.
    -- Called by: set_family_count
    -- *******************************************************************
    procedure prune_family (
        customer_id_in in number,
        channel_family_id_in in number,
        quantity_in in number,
        flex_in in number
    ) is
       is_fve_in char;
       tmp_quantity number;

        cursor serverchannels is
            select    sc.server_id,
                    sc.channel_id
            from    rhnServerChannel sc,
                    rhnChannelFamilyMembers cfm
            where    1=1
                and cfm.channel_family_id = channel_family_id_in
                and cfm.channel_id = sc.channel_id
                and server_id in (
                    select    server_id
                      from    (
                        select server_id, time, rownum row_number
                        from    (
                            select rs.id  server_id, rcfm.modified time
                            from    rhnServerChannel         rsc,
                                    rhnChannelFamilyMembers  rcfm,
                                    rhnServer                rs
                            where    1=1
                                and rs.org_id = customer_id_in
                                and rs.id = rsc.server_id
                                and rsc.channel_id = rcfm.channel_id
                                and rcfm.channel_family_id =  channel_family_id_in
                                and rsc.is_fve = is_fve_in
                                -- we only want to grab servers consuming
                                -- physical slots.
                                and exists (
                                    select 1
                                    from rhnChannelFamilyServerPhysical cfsp
                                    where cfsp.server_id = rs.id
                                    and cfsp.channel_family_id = 
                                        channel_family_id_in
                                    )
                            order by time asc
                        )
                    )
                    where row_number > tmp_quantity
                );
    begin
        -- if we get a null customer_id, this is completely bogus.
        if customer_id_in is null then
            return;
        end if;

        tmp_quantity := quantity_in;
        is_fve_in := 'N';

        for sc in serverchannels loop
            rhn_channel.unsubscribe_server(sc.server_id, sc.channel_id, 1, 1,
                                                       update_family_countsYN => 0);

        tmp_quantity := flex_in;
        is_fve_in := 'Y';
        for sc in serverchannels loop
            rhn_channel.unsubscribe_server(sc.server_id, sc.channel_id, 1, 1,
                                                        update_family_countsYN => 0);
        end loop;



        end loop;
                rhn_channel.update_family_counts(channel_family_id_in, customer_id_in);
    end prune_family;

    procedure set_family_count (
        customer_id_in in number,
        channel_family_id_in in number,
        quantity_in in number,
        flex_in in number
    ) is
        cursor privperms is
            select    1
            from    rhnPrivateChannelFamily
            where    org_id = customer_id_in
                and channel_family_id = channel_family_id_in;
        cursor pubperms is
            select    o.id org_id
            from    web_customer o,
                    rhnPublicChannelFamily pcf
            where    pcf.channel_family_id = channel_family_id_in;
        quantity number;
        done number := 0;
        flex number;
    begin
        quantity := quantity_in;
        if quantity is not null and quantity < 0 then
            quantity := 0;
        end if;
        flex := flex_in;
        if flex is not null and flex < 0 then
            flex := 0;
        end if;


        if customer_id_in is not null then
            for perm in privperms loop
                rhn_entitlements.prune_family(customer_id_in, channel_family_id_in,
                    quantity, flex);

                if quantity is null and flex is null then
                    delete from rhnPrivateChannelFamily
                        where org_id = customer_id_in
                            and channel_family_id = channel_family_id_in;
                else
                    update rhnPrivateChannelFamily
                        set max_members = quantity
                        where org_id = customer_id_in
                            and channel_family_id = channel_family_id_in;

                   update rhnPrivateChannelFamily
                        set fve_max_members = flex
                        where org_id = customer_id_in
                            and channel_family_id = channel_family_id_in;
                end if;
                return;
            end loop;

            insert into rhnPrivateChannelFamily (
                    channel_family_id, org_id, max_members, current_members, fve_max_members, fve_current_members
                ) values (
                    channel_family_id_in, customer_id_in, quantity, 0, flex, 0 );
            return;
        end if;

        for perm in pubperms loop
            if quantity = 0 then
                rhn_entitlements.prune_family(
                    perm.org_id,
                    channel_family_id_in,
                    quantity,
                    flex
                );
                if done = 0 then
                    delete from rhnPublicChannelFamily
                        where channel_family_id = channel_family_id_in;
                end if;
            end if;
            done := 1;
        end loop;
        -- if done's not 1, then we don't have any entitlements
        if done != 1 then
            insert into rhnPublicChannelFamily (
                    channel_family_id
                ) values (
                    channel_family_id_in
                );
        end if;
    end set_family_count;

    -- this expects quantity_in to be the number of available slots, not the
    -- max_members of the server group.  If you give it too many, it'll fail
    -- and raise servergroup_max_members.
    -- We should NEVER run this unless we're SURE that we won't
    -- be violating the max.
    procedure entitle_last_modified_servers (
        customer_id_in in number,
        type_label_in in varchar2,
        quantity_in in number
    ) is
        -- find the servers that aren't currently in slots
        cursor servers(cid_in in number, quant_in in number) is
            select    server_id
            from    (
                        select    rownum row_number,
                                server_id
                        from    (
                                    select    rs.id server_iD
                                    from    rhnServer rs
                                    where    1=1
                                        and rs.org_id = cid_in
                                        and not exists (
                                            select    1
                                            from    rhnServerGroup sg,
                                                    rhnServerGroupMembers rsgm
                                            where    rsgm.server_id = rs.id
                                                and rsgm.server_group_id = sg.id
                                                and sg.group_type is not null
                                        )
                                        and not exists (
                                            select 1
                                            from rhnVirtualInstance vi
                                            where vi.virtual_system_id =
                                                  rs.id
                                        )                                                                           order by modified desc
                                )
                    )
            where    row_number <= quant_in;
    begin
        for server in servers(customer_id_in, quantity_in) loop
            rhn_entitlements.entitle_server(server.server_id, type_label_in);
        end loop;
    end entitle_last_modified_servers;

    procedure subscribe_newest_servers (
        customer_id_in in number
    ) is
        -- find servers without base channels
        cursor servers(cid_in in number) is
            select    s.id
            from    rhnServer            s
            where    1=1
                and s.org_id = cid_in
                and not exists (
                        select 1
                        from    rhnChannel            c,
                                rhnServerChannel    sc
                        where    sc.server_id = s.id
                            and sc.channel_id = c.id
                            and c.parent_channel is null
                    )
                and not exists (
                        select 1
                        from rhnVirtualInstance vi
                        where vi.virtual_system_id = s.id
                    )                        
            order by s.modified desc;
        channel_id number;
    begin
        for server in servers(customer_id_in) loop
            channel_id := rhn_channel.guess_server_base(server.id);
            if channel_id is not null then
                begin
                    rhn_channel.subscribe_server(server.id, channel_id);
                    commit;
                -- exception is really channel_family_no_subscriptions
                exception
                    when others then
                        null;
                end;
            end if;
        end loop;
    end subscribe_newest_servers;
end rhn_entitlements;
/
show errors

   07070100000914000081B400000000000000000000000167AE11140000ADB9000000000000000000000000000000000000006700000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/603-rhn_channel.pkb.sql    --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

CREATE OR REPLACE
PACKAGE BODY rhn_channel
IS
        body_version varchar2(100) := '';

    -- Cursor that fetches all the possible base channels for a
    -- (server_arch_id, release, org_id) combination
        cursor  base_channel_cursor(
                release_in in varchar2,
                server_arch_id_in in number,
                org_id_in in number
        ) return rhnChannel%ROWTYPE is
                select distinct c.*
                from    rhnDistChannelMap                       dcm,
                                rhnServerChannelArchCompat      scac,
                                rhnChannel                                      c,
                                rhnChannelPermissions           cp
                where   cp.org_id = org_id_in
                        and cp.channel_id = c.id
                        and c.parent_channel is null
                        and c.id = dcm.channel_id
                        and c.channel_arch_id = dcm.channel_arch_id
                        and dcm.release = release_in
                        and scac.server_arch_id = server_arch_id_in
                        and scac.channel_arch_id = c.channel_arch_id;

    procedure obtain_read_lock(channel_family_id_in in number, org_id_in in number)
    is
        read_lock date;

    begin
        select created into read_lock
          from rhnPrivateChannelFamily
         where channel_family_id = channel_family_id_in and org_id = org_id_in
           for update;
    end obtain_read_lock;

    PROCEDURE subscribe_server(server_id_in IN NUMBER, channel_id_in NUMBER, immediate_in NUMBER := 1, user_id_in in number := null, recalcfamily_in number := 1)
    IS
        channel_parent_val      rhnChannel.parent_channel%TYPE;
        parent_subscribed       BOOLEAN;
        server_has_base_chan    BOOLEAN;
        server_already_in_chan  BOOLEAN;
        channel_family_id_val   NUMBER;
        server_org_id_val       NUMBER;
        available_subscriptions NUMBER;
        available_fve_subs      NUMBER;
        has_family_subscription NUMBER;
        consenting_user         NUMBER;
        allowed                 number := 0;
        is_fve                  CHAR(1) := 'N';
    BEGIN
        if user_id_in is not null then
            allowed := rhn_channel.user_role_check(channel_id_in, user_id_in, 'subscribe');
        else
            allowed := 1;
        end if;

        if allowed = 0 then
            rhn_exception.raise_exception('no_subscribe_permissions');
        end if;


        SELECT parent_channel INTO channel_parent_val FROM rhnChannel WHERE id = channel_id_in;

        IF channel_parent_val IS NOT NULL
        THEN
            -- child channel; if attempting to cross-subscribe a child to the wrong base, silently ignore
            parent_subscribed := FALSE;

            FOR check_subscription IN check_server_subscription(server_id_in, channel_parent_val)
            LOOP
                parent_subscribed := TRUE;
            END LOOP check_subscription;

            IF NOT parent_subscribed
            THEN
                RETURN;
            END IF;
        ELSE
            -- base channel
            server_has_base_chan := FALSE;
            FOR base IN server_base_subscriptions(server_id_in)
            LOOP
                server_has_base_chan := TRUE;
            END LOOP base;

            IF server_has_base_chan
            THEN
                rhn_exception.raise_exception('channel_server_one_base');
            END IF;
        END IF;

        FOR check_subscription IN check_server_subscription(server_id_in, channel_id_in)
        LOOP
            server_already_in_chan := TRUE;
        END LOOP check_subscription;

        IF server_already_in_chan
        THEN
            RETURN;
        END IF;

        channel_family_id_val := rhn_channel.family_for_channel(channel_id_in);
        IF channel_family_id_val IS NULL
        THEN
            rhn_exception.raise_exception('channel_subscribe_no_family');
        END IF;

        --
        -- Use the org_id of the server only if the org_id of the channel = NULL.
        -- This is required for subscribing to shared channels.
        --
        SELECT NVL(org_id, (SELECT org_id FROM rhnServer WHERE id = server_id_in))
          INTO server_org_id_val
          FROM rhnChannel
         WHERE id = channel_id_in;

        begin
            obtain_read_lock(channel_family_id_val, server_org_id_val);
        exception
            when no_data_found then
                rhn_exception.raise_exception('channel_family_no_subscriptions');
        end;

        available_subscriptions := rhn_channel.available_family_subscriptions(channel_family_id_val, server_org_id_val);
        available_fve_subs := rhn_channel.available_fve_family_subs(channel_family_id_val, server_org_id_val);
        has_family_subscription := rhn_channel.server_has_family_subscription(server_id_in, channel_family_id_val);

        IF available_subscriptions IS NULL OR
            available_subscriptions > 0 or
            can_server_consume_virt_channl(server_id_in, channel_family_id_val) = 1 OR
            (available_fve_subs > 0 AND can_server_consume_fve(server_id_in) = 1) OR
            has_family_subscription > 0
        THEN
            if can_server_consume_virt_channl(server_id_in, channel_family_id_val) = 0 AND available_fve_subs > 0 AND can_server_consume_fve(server_id_in) = 1 THEN
                is_fve := 'Y';
            END IF;
            insert into rhnServerHistory (id,server_id,summary,details) (
                select  rhn_event_id_seq.nextval,
                        server_id_in,
                        'subscribed to channel ' || SUBSTR(c.label, 0, 106),
                        c.label
                from    rhnChannel c
                where   c.id = channel_id_in
            );
            UPDATE rhnServer SET channels_changed = sysdate WHERE id = server_id_in;
            INSERT INTO rhnServerChannel (server_id, channel_id, is_fve) VALUES (server_id_in, channel_id_in, is_fve);
			IF recalcfamily_in > 0
			THEN
                rhn_channel.update_family_counts(channel_family_id_val, server_org_id_val);
			END IF;
            queue_server(server_id_in, immediate_in);
        ELSE
            rhn_exception.raise_exception('channel_family_no_subscriptions');
        END IF;

    END subscribe_server;



    FUNCTION can_convert_to_fve(server_id_in IN NUMBER, channel_family_id_val IN NUMBER)
    RETURN NUMBER
    IS
        CURSOR fve_convertible_entries IS
        select 1  from
            rhnServerFveCapable cap
          where cap.server_id = server_id_in
                AND cap.channel_family_id = channel_family_id_val;
    BEGIN
        FOR entry IN fve_convertible_entries LOOP
            return 1;
        END LOOP;
        RETURN 0;
    END can_convert_to_fve;



    -- Converts server channel_family to use a flex entitlement
    PROCEDURE convert_to_fve(server_id_in IN NUMBER, channel_family_id_val IN NUMBER)
    IS
        available_fve_subs      NUMBER;
        server_org_id_val       NUMBER;
    BEGIN

        --
        -- Use the org_id of the server only if the org_id of the channel = NULL.
        -- This is required for subscribing to shared channels.
        --
        SELECT org_id
          INTO server_org_id_val
          FROM rhnServer
         WHERE id = server_id_in;

        begin
            obtain_read_lock(channel_family_id_val, server_org_id_val);
        exception
            when no_data_found then
                rhn_exception.raise_exception('channel_family_no_subscriptions');
        end;
        IF (can_convert_to_fve(server_id_in, channel_family_id_val ) = 0)
            THEN
                rhn_exception.raise_exception('server_cannot_convert_to_flex');
        END IF;

        available_fve_subs := rhn_channel.available_fve_family_subs(channel_family_id_val, server_org_id_val);

        IF (available_fve_subs > 0)
        THEN

            insert into rhnServerHistory (id,server_id,summary,details) (
                select  rhn_event_id_seq.nextval,
                        server_id_in,
                        'converted to flex entitlement' || SUBSTR(cf.label, 0, 99),
                        cf.label
                from    rhnChannelFamily cf
                where   cf.id = channel_family_id_val
            );

            UPDATE rhnServerChannel sc set sc.is_fve = 'Y'
                           where sc.server_id = server_id_in and
                                 sc.channel_id in
                                    (select cfm.channel_id from rhnChannelFamilyMembers cfm
                                                where cfm.CHANNEL_FAMILY_ID = channel_family_id_val);

            rhn_channel.update_family_counts(channel_family_id_val, server_org_id_val);
        ELSE
            rhn_exception.raise_exception('not_enough_flex_entitlements');
        END IF;

    END convert_to_fve;

    function can_server_consume_virt_channl(
        server_id_in in number,
        family_id_in in number )
    return number
    is

        cursor server_virt_families is
            select vi.virtual_system_id, cfvsl.channel_family_id
            from
                rhnChannelFamilyVirtSubLevel cfvsl,
                rhnSGTypeVirtSubLevel sgtvsl,
                rhnVirtualInstance vi
            where
                vi.virtual_system_id = server_id_in
                and sgtvsl.virt_sub_level_id = cfvsl.virt_sub_level_id
                and cfvsl.channel_family_id = family_id_in
                and exists (
                    select 1
                    from rhnServerEntitlementView sev
                    where vi.host_system_id = sev.server_id
                    and sev.server_group_type_id = sgtvsl.server_group_type_id );
    begin

        for server_virt_family in server_virt_families loop
            return 1;
        end loop;

        return 0;

    end;

    FUNCTION can_server_consume_fve(server_id_in IN NUMBER)
    RETURN NUMBER
    IS
        CURSOR vi_entries IS
            SELECT 1
              FROM rhnVirtualInstance vi
             WHERE vi.virtual_system_id = server_id_in;
        vi_count NUMBER;

    BEGIN
        FOR vi_entry IN VI_ENTRIES LOOP
            return 1;
        END LOOP;
        RETURN 0;
    END;

    function guess_server_base(
        server_id_in in number
    ) RETURN number is
        cursor server_cursor is
            select s.server_arch_id, s.release, s.org_id
              from rhnServer s
             where s.id = server_id_in;
    begin
        for s in server_cursor loop
            for channel in base_channel_cursor(s.release,
                s.server_arch_id, s.org_id)
            loop
                return channel.id;
            end loop base_channel_cursor;
        end loop server_cursor;
        -- Server not found, or no base channel applies to it
        return null;
    end;

    -- Private function
    function normalize_server_arch(server_arch_in in varchar2)
    return varchar2
    deterministic
    is
        suffix VARCHAR2(128) := '-redhat-linux';
        suffix_len NUMBER := length(suffix);
    begin
        if server_arch_in is NULL then
            return NULL;
        end if;
        if instr(server_arch_in, '-') > 0
        then
            -- Suffix already present
            return server_arch_in;
        end if;
        return server_arch_in || suffix;
    end normalize_server_arch;

    --
    --
    -- Raises:
    --   server_arch_not_found
    --   no_subscribe_permissions
    function base_channel_for_release_arch(
        release_in in varchar2,
        server_arch_in in varchar2,
        org_id_in in number := -1,
        user_id_in in number := null
    ) return number is
        server_arch varchar2(256) := normalize_server_arch(server_arch_in);
        server_arch_id number;
    begin
        -- Look up the server arch
        begin
            select id
              into server_arch_id
              from rhnServerArch
             where label = server_arch;
        exception
            when no_data_found then
                rhn_exception.raise_exception('server_arch_not_found');
        end;
        return base_channel_rel_archid(release_in, server_arch_id,
            org_id_in, user_id_in);
    end base_channel_for_release_arch;

    function base_channel_rel_archid(
        release_in in varchar2,
        server_arch_id_in in number,
        org_id_in in number := -1,
        user_id_in in number := null
    ) return number is
        denied_channel_id number := null;
        valid_org_id number := org_id_in;
        valid_user_id number := user_id_in;
        channel_subscribable number;
    begin
        if org_id_in = -1 and user_id_in is not null then
            -- Get the org id from the user id
            begin
                select org_id
                  into valid_org_id
                  from web_contact
                 where id = user_id_in;
            exception
                when no_data_found then
                    -- User doesn't exist
                    -- XXX Only list public stuff for now
                    valid_user_id := null;
                    valid_org_id := -1;
            end;
        end if;

        for c in base_channel_cursor(release_in, server_arch_id_in, valid_org_id)
        loop
            -- This row is a possible match
            if valid_user_id is null then
                -- User ID not specified, so no user to channel permissions to
                -- check
                return c.id;
            end if;

            -- Check user to channel permissions
            select loose_user_role_check(c.id, user_id_in, 'subscribe')
              into channel_subscribable
              from dual;

            if channel_subscribable = 1 then
                return c.id;
            end if;

            -- Base channel exists, but is not subscribable; keep trying
            denied_channel_id := c.id;
        end loop base_channel_fetch;

        if denied_channel_id is not null then
            rhn_exception.raise_exception('no_subscribe_permissions');
        end if;
        -- No base channel applies
        return NULL;
    end base_channel_rel_archid;

    PROCEDURE clear_subscriptions(server_id_in IN NUMBER, deleting_server IN NUMBER := 0,
                                update_family_countsYN IN NUMBER := 1)
    IS
        cursor server_channels(server_id_in in number) is
                select  s.org_id, sc.channel_id, cfm.channel_family_id
                from    rhnServer s,
                        rhnServerChannel sc,
                        rhnChannelFamilyMembers cfm
                where   s.id = server_id_in
                        and s.id = sc.server_id
                        and sc.channel_id = cfm.channel_id
                order by cfm.channel_family_id;
        last_channel_family_id rhnChannelFamilyMembers.channel_family_id%type := -1;
        last_channel_org_id    rhnServer.org_id%type := -1;
    BEGIN
        for channel in server_channels(server_id_in)
        loop
                unsubscribe_server(server_id_in, channel.channel_id, 1, 1, deleting_server, 0);
                if update_family_countsYN > 0
                    and channel.channel_family_id != last_channel_family_id then
                    -- update family counts only once
                    -- after all channels with same family has been fetched
                    if last_channel_family_id != -1 then
                        update_family_counts(last_channel_family_id, last_channel_org_id);
                    end if;
                    last_channel_family_id := channel.channel_family_id;
                    last_channel_org_id    := channel.org_id;
                end if;
        end loop channel;
        if update_family_countsYN > 0 and last_channel_family_id != -1 then
            -- update the last family fetched
            update_family_counts(last_channel_family_id, last_channel_org_id);
        end if;
    END clear_subscriptions;

    PROCEDURE unsubscribe_server(server_id_in IN NUMBER, channel_id_in NUMBER, immediate_in NUMBER := 1, unsubscribe_children_in number := 0,
                                 deleting_server IN NUMBER := 0,
                                 update_family_countsYN IN NUMBER := 1)
    IS
        channel_family_id_val   NUMBER;
        server_org_id_val       NUMBER;
        available_subscriptions NUMBER;
        server_already_in_chan  BOOLEAN;
        cursor  channel_family_is_proxy(channel_family_id_in in number) is
                select  1
                from    rhnChannelFamily
                where   id = channel_family_id_in
                    and label = 'rhn-proxy';
        cursor  channel_family_is_satellite(channel_family_id_in in number) is
                select  1
                from    rhnChannelFamily
                where   id = channel_family_id_in
                    and label = 'rhn-satellite';
        -- this is *EXACTLY* like check_server_parent_membership, but if we recurse
        -- with the package-level one, we get a "cursor already open", so we need a
        -- copy on our call stack instead.  GROAN.
        cursor local_chk_server_parent_memb (
                        server_id_in number,
                        channel_id_in number ) is
                select  c.id
                from    rhnChannel                      c,
                                rhnServerChannel        sc
                where   1=1
                        and c.parent_channel = channel_id_in
                        and c.id = sc.channel_id
                        and sc.server_id = server_id_in;
    BEGIN
        FOR child IN local_chk_server_parent_memb(server_id_in, channel_id_in)
        LOOP
            if unsubscribe_children_in = 1 then
                unsubscribe_server(server_id_in => server_id_in,
                                                                channel_id_in => child.id,
                                                                immediate_in => immediate_in,
                                                                unsubscribe_children_in => unsubscribe_children_in,
                        deleting_server => deleting_server,
                        update_family_countsYN => update_family_countsYN);
            else
                rhn_exception.raise_exception('channel_unsubscribe_child_exists');
            end if;
        END LOOP child;

        server_already_in_chan := FALSE;

        FOR check_subscription IN check_server_subscription(server_id_in, channel_id_in)
        LOOP
            server_already_in_chan := TRUE;
        END LOOP check_subscription;

        IF NOT server_already_in_chan
        THEN
            RETURN;
        END IF;

   if deleting_server = 0 then

      insert into rhnServerHistory (id,server_id,summary,details) (
          select  rhn_event_id_seq.nextval,
                server_id_in,
             'unsubscribed from channel ' || SUBSTR(c.label, 0, 106),
             c.label
          from    rhnChannel c
          where   c.id = channel_id_in
      );

        UPDATE rhnServer SET channels_changed = sysdate WHERE id = server_id_in;
   end if;

   DELETE FROM rhnServerChannel WHERE server_id = server_id_in AND channel_id = channel_id_in;

   if deleting_server = 0 then
        queue_server(server_id_in, immediate_in);
   end if;

        channel_family_id_val := rhn_channel.family_for_channel(channel_id_in);
        IF channel_family_id_val IS NULL
        THEN
            rhn_exception.raise_exception('channel_unsubscribe_no_family');
        END IF;

        for ignore in channel_family_is_satellite(channel_family_id_val) loop
                delete from rhnSatelliteInfo where server_id = server_id_in;
        end loop;

        for ignore in channel_family_is_proxy(channel_family_id_val) loop
                delete from rhnProxyInfo where server_id = server_id_in;
        end loop;
        SELECT org_id INTO server_org_id_val
          FROM rhnServer
         WHERE id = server_id_in;

        if update_family_countsYN = 1 then
            rhn_channel.update_family_counts(channel_family_id_val, server_org_id_val);
        end if;
    END unsubscribe_server;


    FUNCTION family_for_channel(channel_id_in IN NUMBER)
    RETURN NUMBER
    IS
        channel_family_id_val NUMBER;
    BEGIN
        SELECT channel_family_id INTO channel_family_id_val
          FROM rhnChannelFamilyMembers
         WHERE channel_id = channel_id_in;

        RETURN channel_family_id_val;
    EXCEPTION
        WHEN NO_DATA_FOUND
        THEN
            RETURN NULL;
    END family_for_channel;

    FUNCTION available_family_subscriptions(channel_family_id_in IN NUMBER, org_id_in IN NUMBER)
    RETURN NUMBER
    IS
        cfp channel_family_perm_cursor%ROWTYPE;
        current_members_val NUMBER;
        max_members_val     NUMBER;
        found               NUMBER;
    BEGIN
        IF NOT channel_family_perm_cursor%ISOPEN
        THEN
            OPEN channel_family_perm_cursor(channel_family_id_in, org_id_in);
        END IF;

        FETCH channel_family_perm_cursor INTO cfp;

        WHILE channel_family_perm_cursor%FOUND
        LOOP
            found := 1;

            current_members_val := cfp.current_members;
            max_members_val := cfp.max_members;

            FETCH channel_family_perm_cursor INTO cfp;
        END LOOP;

        IF channel_family_perm_cursor%ISOPEN
        THEN
            CLOSE channel_family_perm_cursor;
        END IF;

        -- not found: either the channel fam doesn't have an entry in cfp, or the org doesn't have access to it.
        -- either way, there are no available subscriptions

        IF found IS NULL
        THEN
            RETURN 0;
        END IF;

        -- null max members?  in that case, pass it on; NULL means infinite
        IF max_members_val IS NULL
        THEN
            RETURN NULL;
        END IF;

        -- otherwise, return the delta
        RETURN max_members_val - current_members_val;
    END available_family_subscriptions;

    FUNCTION available_fve_family_subs(channel_family_id_in IN NUMBER, org_id_in IN NUMBER)
    RETURN NUMBER
    IS
        cfp channel_family_perm_cursor%ROWTYPE;
        fve_current_members_val NUMBER;
        fve_max_members_val     NUMBER;
        found               NUMBER;

    BEGIN
        IF NOT channel_family_perm_cursor%ISOPEN THEN
            OPEN channel_family_perm_cursor(channel_family_id_in, org_id_in);
        END IF;

        FETCH channel_family_perm_cursor INTO cfp;

        WHILE channel_family_perm_cursor%FOUND LOOP
            found := 1;
            fve_current_members_val := cfp.fve_current_members;
            fve_max_members_val := cfp.fve_max_members;
            FETCH channel_family_perm_cursor INTO cfp;
        END LOOP;

        IF channel_family_perm_cursor%ISOPEN THEN
            CLOSE channel_family_perm_cursor;
        END IF;

        IF found IS NULL THEN
            RETURN 0;
        END IF;

        IF fve_max_members_val IS NULL THEN
            RETURN NULL;
        END IF;

        RETURN fve_max_members_val - fve_current_members_val;

    END available_fve_family_subs;


    -- *******************************************************************
    -- FUNCTION: channel_family_current_members
    -- Calculates and returns the actual count of systems consuming
    --   physical channel subscriptions.
    -- Called by: update_family_counts
    --            rhn_entitlements.repoll_virt_guest_entitlements
    -- *******************************************************************
    function channel_family_current_members(channel_family_id_in IN NUMBER,
                                            org_id_in IN NUMBER)
    return number
    is
        current_members_count number := 0;
    begin
        select  count(distinct server_id)
        into    current_members_count
          from  rhnChannelFamilyServerPhysical cfsp
         where  cfsp.channel_family_id = channel_family_id_in
           and  cfsp.customer_id = org_id_in;
        return current_members_count;
    end;


    function cfam_curr_fve_members(
        channel_family_id_in IN NUMBER,
        org_id_in IN NUMBER)
    return number
    is
        current_members_count number := 0;

    begin
        select count(sc.server_id)
          into current_members_count
          from rhnServerChannel sc,
               rhnChannelFamilyMembers cfm,
               rhnServer s
         where s.org_id = org_id_in
           and s.id = sc.server_id
           and cfm.channel_family_id = channel_family_id_in
           and cfm.channel_id = sc.channel_id
           and exists (
                select 1
                  from rhnChannelFamilyServerFve cfsp
                 where cfsp.CHANNEL_FAMILY_ID = channel_family_id_in
                   and cfsp.server_id = s.id
                );

        return current_members_count;
    end;
    PROCEDURE update_family_counts(channel_family_id_in IN NUMBER,
                                   org_id_in IN NUMBER)
    IS
    BEGIN
        update rhnPrivateChannelFamily
           set current_members = ( channel_family_current_members(channel_family_id_in, org_id_in)),
               fve_current_members = ( cfam_curr_fve_members(channel_family_id_in, org_id_in))
         where org_id = org_id_in
           and channel_family_id = channel_family_id_in;
    END update_family_counts;

    PROCEDURE update_group_family_counts(group_label_in IN VARCHAR2,
                                   org_id_in IN NUMBER)
    IS
    BEGIN
        FOR i IN (
                SELECT DISTINCT CFM.channel_family_id, SG.org_id
                 FROM rhnChannelFamilyMembers CFM
                 JOIN rhnServerChannel SC
                   ON SC.channel_id = CFM.channel_id
                 JOIN rhnServerGroupMembers SGM
                   ON SC.server_id = SGM.server_id
                 JOIN rhnServerGroup SG
                   ON SGM.server_group_id = SG.id
                 JOIN rhnServerGroupType SGT
                   ON SG.group_type = SGT.id
                WHERE SGT.label = group_label_in
                  AND SG.org_id = org_id_in
                  AND SGT.is_base = 'Y'
        ) LOOP
            rhn_channel.update_family_counts(i.channel_family_id, i.org_id);
        END LOOP;
    END update_group_family_counts;

    FUNCTION available_chan_subscriptions(channel_id_in IN NUMBER,
                                          org_id_in IN NUMBER)
    RETURN NUMBER
    IS
            channel_family_id_val NUMBER;
    BEGIN
        SELECT channel_family_id INTO channel_family_id_val
            FROM rhnChannelFamilyMembers
            WHERE channel_id = channel_id_in;

            RETURN rhn_channel.available_family_subscriptions(
                           channel_family_id_val, org_id_in);
    END available_chan_subscriptions;

	FUNCTION available_fve_chan_subs(channel_id_in IN NUMBER,
                                          org_id_in IN NUMBER)
    RETURN NUMBER
    IS
        channel_family_id_val NUMBER;

    BEGIN
        SELECT channel_family_id INTO channel_family_id_val
          FROM rhnChannelFamilyMembers
         WHERE channel_id = channel_id_in;

        RETURN rhn_channel.available_fve_family_subs( channel_family_id_val, org_id_in);
    END available_fve_chan_subs;

    procedure unsubscribe_server_from_family(server_id_in in number,
                                             channel_family_id_in in number)
    is
    begin
        delete
        from    rhnServerChannel rsc
        where   rsc.server_id = server_id_in
            and channel_id in (
                select  rcfm.channel_id
                from    rhnChannelFamilyMembers rcfm
                where   rcfm.channel_family_id = channel_family_id_in);
    end;

    function get_org_id(channel_id_in in number)
    return number
    is
        org_id_out number;
    begin
        select org_id into org_id_out
            from rhnChannel
            where id = channel_id_in;

            return org_id_out;
    end get_org_id;

    function get_cfam_org_access(cfam_id_in in number, org_id_in in number)
    return number
    is
        cursor  families is
                        select  1
                        from    rhnOrgChannelFamilyPermissions cfp
                        where   cfp.org_id = org_id_in;
    begin
                -- the idea: if we get past this query,
        -- the user has the role, else catch the exception and return 0
                for family in families loop
                return 1;
                end loop;
                return 0;
    end;

    function get_org_access(channel_id_in in number, org_id_in in number)
    return number
    is
        throwaway number;
    begin
        -- the idea: if we get past this query,
        -- the org has access to the channel, else catch the exception and return 0
        select distinct 1 into throwaway
          from rhnChannelFamilyMembers CFM,
               rhnOrgChannelFamilyPermissions CFP
         where cfp.org_id = org_id_in
           and CFM.channel_family_id = CFP.channel_family_id
           and CFM.channel_id = channel_id_in
           and (CFP.max_members > 0 or CFP.max_members is null or CFP.fve_max_members > 0 or CFP.fve_max_members is null or CFP.org_id = 1);

        return 1;
        exception
            when no_data_found
            then
            return 0;
    end;

    -- check if a user has a given role, or if such a role is inferrable
    function user_role_check_debug(channel_id_in in number,
                                   user_id_in in number,
                                   role_in in varchar2,
                                   reason_out out varchar2)
    return number
    is
        org_id number;
    begin
        org_id := rhn_user.get_org_id(user_id_in);

        -- channel might be shared
        if role_in = 'subscribe' and
           rhn_channel.shared_user_role_check(channel_id_in, user_id_in, role_in) = 1 then
            return 1;
        end if;

        if role_in = 'manage' and
           NVL(rhn_channel.get_org_id(channel_id_in), -1) <> org_id then
                reason_out := 'channel_not_owned';
               return 0;
            end if;

        if role_in = 'subscribe' and
           rhn_channel.get_org_access(channel_id_in, org_id) = 0 then
                reason_out := 'channel_not_available';
                return 0;
            end if;

        -- channel admins have all roles
        if rhn_user.check_role_implied(user_id_in, 'channel_admin') = 1 then
            reason_out := 'channel_admin';
            return 1;
            end if;

        -- the subscribe permission is inferred
    -- UNLESS the not_globally_subscribable flag is set
        if role_in = 'subscribe'
        then
            if rhn_channel.org_channel_setting(channel_id_in,
                       org_id,
                       'not_globally_subscribable') = 0 then
                reason_out := 'globally_subscribable';
                    return 1;
            end if;
        end if;

        -- all other roles (manage right now) are explicitly granted
        reason_out := 'direct_permission';
        return rhn_channel.direct_user_role_check(channel_id_in,
                                              user_id_in, role_in);
    end;

    -- same as above, but with no OUT param; useful in views, etc
    function user_role_check(channel_id_in in number, user_id_in in number, role_in in varchar2)
    return number
    is
        throwaway varchar2(256);
    begin
        return rhn_channel.user_role_check_debug(channel_id_in, user_id_in, role_in, throwaway);
    end;

    --
    -- For multiorg phase II, this function simply checks to see if the user's
    -- has a trust relationship that includes this channel by id.
    --
    function shared_user_role_check(channel_id in number, user_id in number, role in varchar2)
    return number
    is
      n number;
      oid number;
    begin
      oid := rhn_user.get_org_id(user_id);
      select 1 into n
      from rhnSharedChannelView s
      where s.id = channel_id and s.org_trust_id = oid;
      return 1;
      exception
        when no_data_found then
          return 0;
    end;

    -- same as above, but returns 1 if user_id_in is null
    -- This is useful in queries where user_id is not specified
    function loose_user_role_check(channel_id_in in number, user_id_in in number, role_in in varchar2)
    return number
    is
    begin
        if user_id_in is null then
            return 1;
        end if;
        return user_role_check(channel_id_in, user_id_in, role_in);
    end loose_user_role_check;

    -- directly checks the table, no inferred permissions
    function direct_user_role_check(channel_id_in in number, user_id_in in number, role_in in varchar2)
    return number
    is
        throwaway number;
    begin
        -- the idea: if we get past this query, the user has the role, else catch the exception and return 0
        select 1 into throwaway
          from rhnChannelPermissionRole CPR,
               rhnChannelPermission CP
         where CP.user_id = user_id_in
           and CP.channel_id = channel_id_in
           and CPR.label = role_in
           and CP.role_id = CPR.id;

        return 1;
    exception
        when no_data_found
            then
            return 0;
    end;

    -- check if an org has a certain setting
    function org_channel_setting(channel_id_in in number, org_id_in in number, setting_in in varchar2)
    return number
    is
        throwaway number;
    begin
        -- the idea: if we get past this query, the org has the setting, else catch the exception and return 0
        select 1 into throwaway
          from rhnOrgChannelSettingsType OCST,
               rhnOrgChannelSettings OCS
         where OCS.org_id = org_id_in
           and OCS.channel_id = channel_id_in
           and OCST.label = setting_in
           and OCS.setting_id = OCST.id;

        return 1;
    exception
        when no_data_found
            then
            return 0;
    end;

    FUNCTION channel_priority(channel_id_in IN number)
    RETURN number
    IS
         channel_name varchar2(256);
         priority number;
         end_of_life_val date;
         org_id_val number;
    BEGIN

        select name, end_of_life, org_id
        into channel_name, end_of_life_val, org_id_val
        from rhnChannel
        where id = channel_id_in;

        if end_of_life_val is not null then
          return -400;
        end if;

        if channel_name like 'Red Hat Enterprise Linux%' or channel_name like 'RHEL%' then
          priority := 1000;
          if channel_name not like '%Beta%' then
            priority := priority + 1000;
          end if;

          priority := priority +
            case
              when channel_name like '%v. 5%' then 600
              when channel_name like '%v. 4%' then 500
              when channel_name like '%v. 3%' then 400
              when channel_name like '%v. 2%' then 300
              when channel_name like '%v. 1%' then 200
              else 0
            end;

          priority := priority +
            case
              when channel_name like 'Red Hat Enterprise Linux (v. 5%' then 60
              when (channel_name like '%AS%' and channel_name not like '%Extras%') then 50
              when (channel_name like '%ES%' and channel_name not like '%Extras%') then 40
              when (channel_name like '%WS%' and channel_name not like '%Extras%') then 30
              when (channel_name like '%Desktop%' and channel_name not like '%Extras%') then 20
              when channel_name like '%Extras%' then 10
              else 0
            end;

          priority := priority +
            case
              when channel_name like '%)' then 5
              else 0
            end;

          priority := priority +
            case
              when channel_name like '%32-bit x86%' then 4
              when channel_name like '%64-bit Intel Itanium%' then 3
              when channel_name like '%64-bit AMD64/Intel EM64T%' then 2
              else 0
            end;
        elsif channel_name like 'Red Hat Desktop%' then
            priority := 900;

            if channel_name not like '%Beta%' then
               priority := priority + 50;
            end if;

          priority := priority +
            case
              when channel_name like '%v. 4%' then 40
              when channel_name like '%v. 3%' then 30
              when channel_name like '%v. 2%' then 20
              when channel_name like '%v. 1%' then 10
              else 0
            end;

          priority := priority +
            case
              when channel_name like '%32-bit x86%' then 4
              when channel_name like '%64-bit Intel Itanium%' then 3
              when channel_name like '%64-bit AMD64/Intel EM64T%' then 2
              else 0
            end;

        elsif org_id_val is not null then
          priority := 600;
        else
          priority := 500;
        end if;

      return -priority;

    end channel_priority;

    -- right now this only does the accounting changes; the cascade
    -- actually does the rhnServerChannel delete.
    procedure delete_server_channels(server_id_in in number)
    is
    begin
        update  rhnPrivateChannelFamily
        set     current_members = current_members -1
        where   org_id in (
                        select  org_id
                        from    rhnServer
                        where   id = server_id_in
                )
                and channel_family_id in (
                        select  rcfm.channel_family_id
                        from    rhnChannelFamilyMembers rcfm,
                                rhnServerChannel rsc
                        where   rsc.server_id = server_id_in
                                and rsc.channel_id = rcfm.channel_id
                and not exists (
                    select 1
                    from
                        rhnChannelFamilyVirtSubLevel cfvsl,
                        rhnSGTypeVirtSubLevel sgtvsl,
                        rhnServerEntitlementView sev,
                        rhnVirtualInstance vi
                    where
                        -- system is a virtual instance
                        vi.virtual_system_id = server_id_in
                        and vi.host_system_id = sev.server_id
                        -- system's host has a virt ent
                        and sev.label in ('virtualization_host',
                                          'virtualization_host_platform')
                        and sev.server_group_type_id =
                            sgtvsl.server_group_type_id
                        -- the host's virt ent grants a cf virt sub level
                        and sgtvsl.virt_sub_level_id = cfvsl.virt_sub_level_id
                        -- the cf is in that virt sub level
                        and cfvsl.channel_family_id = rcfm.channel_family_id
                    )
                );
    end;

        -- this could certainly be optimized to do updates if needs be
        procedure refresh_newest_package(channel_id_in in number, caller_in in varchar2 := '(unknown)')
        is
        begin
                delete from rhnChannelNewestPackage where channel_id = channel_id_in;
                insert into rhnChannelNewestPackage
                        ( channel_id, name_id, evr_id, package_id, package_arch_id )
                        (       select  channel_id,
                                                name_id, evr_id,
                                                package_id, package_arch_id
                                from    rhnChannelNewestPackageView
                                where   channel_id = channel_id_in
                        );
                insert into rhnChannelNewestPackageAudit (channel_id, caller)
                    values (channel_id_in, caller_in);
                update rhnChannel
                    set last_modified = greatest(sysdate, last_modified + 1/86400)
                    where id = channel_id_in;
        end;

   procedure update_channel ( channel_id_in in number, invalidate_ss in number := 0,
                              date_to_use in date := sysdate )
   is

   channel_last_modified date;
   last_modified_value date;

   cursor snapshots is
   select  snapshot_id id
   from    rhnSnapshotChannel
   where   channel_id = channel_id_in;

   begin

      select last_modified
      into channel_last_modified
      from rhnChannel
      where id = channel_id_in;

      last_modified_value := date_to_use;

      if last_modified_value <= channel_last_modified then
          last_modified_value := last_modified_value + 1/86400;
      end if;

      update rhnChannel set last_modified = last_modified_value
      where id = channel_id_in;

      if invalidate_ss = 1 then
        for snapshot in snapshots loop
            update rhnSnapshot
            set invalid = lookup_snapshot_invalid_reason('channel_modified')
            where id = snapshot.id;
        end loop;
      end if;

   end update_channel;

   procedure update_channels_by_package ( package_id_in in number, date_to_use in date := sysdate )
   is

   cursor channels is
   select channel_id
   from rhnChannelPackage
   where package_id = package_id_in
   order by channel_id;

   begin
      for channel in channels loop
         -- we want to invalidate the snapshot assocated with the channel when we
         -- do this b/c we know we've added or removed or packages
         rhn_channel.update_channel ( channel.channel_id, 1, date_to_use );
      end loop;
   end update_channels_by_package;


   procedure update_channels_by_errata ( errata_id_in number, date_to_use in date := sysdate )
   is

   cursor channels is
   select channel_id
   from rhnChannelErrata
   where errata_id = errata_id_in
   order by channel_id;

   begin
      for channel in channels loop
         -- we won't invalidate snapshots, b/c just changing the errata associated with
         -- a channel shouldn't invalidate snapshots
         rhn_channel.update_channel ( channel.channel_id, 0, date_to_use );
      end loop;
   end update_channels_by_errata;

   procedure update_needed_cache(channel_id_in in number)
   is
       pragma autonomous_transaction;
                -- update of needed cache ican be commited on a per server basis
                -- b/c failure of update for a server means nothing for the other servers
   begin
      -- we intentionaly do a loop here instead of one huge select
      -- b/c we want to break update into smaller transaction to unblock other sessions
      -- querying rhnServerNeededCache
      for server in (
                select sc.server_id as id
                  from rhnServerChannel sc
                 where sc.channel_id = channel_id_in
      ) loop
         rhn_server.update_needed_cache(server.id);
         commit;
      end loop;
   end update_needed_cache;

   -- return true if the given server has a subs to a channel of channel_family_id_in
   FUNCTION server_has_family_subscription(server_id_in IN NUMBER, channel_family_id_in IN NUMBER)
   RETURN NUMBER
   IS
      CURSOR fam_entries IS
         SELECT DISTINCT cfm.channel_family_id
           FROM rhnchannelfamilymembers cfm
           JOIN rhnserverchannel sc on sc.channel_id = cfm.channel_id
          WHERE sc.server_id =  server_id_in
            AND cfm.channel_family_id = channel_family_id_in;
      fam_count NUMBER;
   BEGIN
      FOR fam_entry IN fam_entries LOOP
         RETURN 1;
      END LOOP;
      RETURN 0;
   END server_has_family_subscription;

END rhn_channel;
/
SHOW ERRORS
   07070100000915000081B400000000000000000000000167AE11140000196A000000000000000000000000000000000000006700000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/605-rhn_channel-pks.sql    --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

CREATE OR REPLACE
PACKAGE rhn_channel
IS
	version varchar2(100) := '';

    CURSOR server_base_subscriptions(server_id_in NUMBER) IS
	   SELECT C.id
	     FROM rhnChannel C, rhnServerChannel SC
	    WHERE C.id = SC.channel_id
	      AND SC.server_id = server_id_in
	      AND C.parent_channel IS NULL;

    CURSOR check_server_subscription(server_id_in NUMBER, channel_id_in NUMBER) IS
           SELECT channel_id
	     FROM rhnServerChannel
	    WHERE server_id = server_id_in
	      AND channel_id = channel_id_in;

    CURSOR check_server_parent_membership(server_id_in NUMBER, channel_id_in NUMBER) IS
	   SELECT C.id
	     FROM rhnChannel C, rhnServerChannel SC
	    WHERE C.parent_channel = channel_id_in
	      AND C.id = SC.channel_id
	      AND SC.server_id = server_id_in;

    CURSOR channel_family_perm_cursor(channel_family_id_in NUMBER, org_id_in NUMBER) IS
           SELECT *
	     FROM rhnOrgChannelFamilyPermissions
	    WHERE channel_family_id = channel_family_id_in
	      AND org_id = org_id_in;


    PROCEDURE unsubscribe_server(server_id_in IN NUMBER, channel_id_in NUMBER, immediate_in NUMBER := 1, unsubscribe_children_in number := 0,
                                 deleting_server in number := 0,
                                 update_family_countsYN IN NUMBER := 1);
    PROCEDURE subscribe_server(server_id_in IN NUMBER, channel_id_in NUMBER, immediate_in NUMBER := 1, user_id_in number := null, recalcfamily_in number := 1);

    PROCEDURE convert_to_fve(server_id_in IN NUMBER, channel_family_id_val IN NUMBER);

    FUNCTION can_convert_to_fve(server_id_in IN NUMBER, channel_family_id_val IN NUMBER)  RETURN NUMBER;

    function can_server_consume_virt_channl(
        server_id_in IN NUMBER,
        family_id_in in number)
    return number;
    FUNCTION can_server_consume_fve( server_id_in IN NUMBER) RETURN NUMBER;

    FUNCTION guess_server_base(server_id_in IN NUMBER) RETURN NUMBER;

    FUNCTION base_channel_for_release_arch(release_in in varchar2,
	server_arch_in in varchar2, org_id_in in number := -1,
	user_id_in in number := null) RETURN number;

    FUNCTION base_channel_rel_archid(release_in in varchar2,
	server_arch_id_in in number, org_id_in in number := -1,
	user_id_in in number := null) RETURN number;

    FUNCTION channel_priority(channel_id_in in number) RETURN number;

    PROCEDURE clear_subscriptions(server_id_in IN NUMBER, deleting_server in number := 0,
                                update_family_countsYN IN NUMBER := 1);

    FUNCTION available_family_subscriptions(channel_family_id_in IN NUMBER, org_id_in IN NUMBER) RETURN NUMBER;

    FUNCTION available_fve_family_subs(channel_family_id_in IN NUMBER, org_id_in IN NUMBER) RETURN NUMBER;

    FUNCTION channel_family_current_members(channel_family_id_in IN NUMBER, org_id_in IN NUMBER) return number;

    FUNCTION cfam_curr_fve_members(channel_family_id_in IN NUMBER, org_id_in IN NUMBER) return number;

    PROCEDURE update_family_counts(channel_family_id_in IN NUMBER, org_id_in IN NUMBER);
    PROCEDURE update_group_family_counts(group_label_in IN VARCHAR2, org_id_in IN NUMBER);
    FUNCTION family_for_channel(channel_id_in IN NUMBER) RETURN NUMBER;

    FUNCTION available_chan_subscriptions(channel_id_in IN NUMBER, org_id_in IN NUMBER) RETURN NUMBER;

    FUNCTION available_fve_chan_subs(channel_id_in IN NUMBER, org_id_in IN NUMBER) RETURN NUMBER;

    PROCEDURE unsubscribe_server_from_family(server_id_in in number, channel_family_id_in in number);

    PROCEDURE delete_server_channels(server_id_in in number);

    PROCEDURE refresh_newest_package(channel_id_in in number,
                                     caller_in in varchar2 := '(unknown)',
                                     package_name_id_in in number := null);

    FUNCTION get_org_id(channel_id_in in number) return number;
    PRAGMA RESTRICT_REFERENCES(get_org_id, WNDS, RNPS, WNPS);

    function get_org_access(channel_id_in in number, org_id_in in number) return number;
    PRAGMA RESTRICT_REFERENCES(get_org_access, WNDS, RNPS, WNPS);

    function get_cfam_org_access(cfam_id_in in number, org_id_in in number) return number;

    function user_role_check_debug(channel_id_in in number, user_id_in in number, role_in in varchar2, reason_out out varchar2)
	RETURN NUMBER;
    PRAGMA RESTRICT_REFERENCES(user_role_check_debug, WNDS, RNPS, WNPS);

    function user_role_check(channel_id_in in number, user_id_in in number, role_in in varchar2)
	RETURN NUMBER;
    PRAGMA RESTRICT_REFERENCES(user_role_check, WNDS, RNPS, WNPS);

    function loose_user_role_check(channel_id_in in number, user_id_in in number, role_in in varchar2)
	RETURN NUMBER;
    PRAGMA RESTRICT_REFERENCES(loose_user_role_check, WNDS, RNPS, WNPS);

    function direct_user_role_check(channel_id_in in number, user_id_in in number, role_in in varchar2)
	RETURN NUMBER;
    PRAGMA RESTRICT_REFERENCES(direct_user_role_check, WNDS, RNPS, WNPS);

    function shared_user_role_check(channel_id in number, user_id in number, role in varchar2)
	RETURN NUMBER;
    PRAGMA RESTRICT_REFERENCES(shared_user_role_check, WNDS, RNPS, WNPS);

    function org_channel_setting(channel_id_in in number, org_id_in in number, setting_in in varchar2)
	RETURN NUMBER;

    PROCEDURE update_channel ( channel_id_in in number, invalidate_ss in number := 0,
                               date_to_use in date := sysdate );

    PROCEDURE  update_channels_by_package ( package_id_in in number, date_to_use in date := sysdate );

     PROCEDURE update_channels_by_errata ( errata_id_in number, date_to_use in date := sysdate );


    PRAGMA RESTRICT_REFERENCES(org_channel_setting, WNDS, RNPS, WNPS);

    PROCEDURE update_needed_cache(channel_id_in in number);

    FUNCTION server_has_family_subscription(server_id_in IN NUMBER, channel_family_id_in IN NUMBER) RETURN NUMBER;

END rhn_channel;
/
SHOW ERRORS
  07070100000916000081B400000000000000000000000167AE11140000AEBC000000000000000000000000000000000000006700000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/606-rhn_channel-pkb.sql    --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

CREATE OR REPLACE
PACKAGE BODY rhn_channel
IS
        body_version varchar2(100) := '';

    -- Cursor that fetches all the possible base channels for a
    -- (server_arch_id, release, org_id) combination
        cursor  base_channel_cursor(
                release_in in varchar2,
                server_arch_id_in in number,
                org_id_in in number
        ) return rhnChannel%ROWTYPE is
                select distinct c.*
                from    rhnDistChannelMap                       dcm,
                                rhnServerChannelArchCompat      scac,
                                rhnChannel                                      c,
                                rhnChannelPermissions           cp
                where   cp.org_id = org_id_in
                        and cp.channel_id = c.id
                        and c.parent_channel is null
                        and c.id = dcm.channel_id
                        and c.channel_arch_id = dcm.channel_arch_id
                        and dcm.release = release_in
                        and scac.server_arch_id = server_arch_id_in
                        and scac.channel_arch_id = c.channel_arch_id;

    procedure obtain_read_lock(channel_family_id_in in number, org_id_in in number)
    is
        read_lock date;

    begin
        select created into read_lock
          from rhnPrivateChannelFamily
         where channel_family_id = channel_family_id_in and org_id = org_id_in
           for update;
    end obtain_read_lock;

    PROCEDURE subscribe_server(server_id_in IN NUMBER, channel_id_in NUMBER, immediate_in NUMBER := 1, user_id_in in number := null, recalcfamily_in number := 1)
    IS
        channel_parent_val      rhnChannel.parent_channel%TYPE;
        parent_subscribed       BOOLEAN;
        server_has_base_chan    BOOLEAN;
        server_already_in_chan  BOOLEAN;
        channel_family_id_val   NUMBER;
        server_org_id_val       NUMBER;
        available_subscriptions NUMBER;
        available_fve_subs      NUMBER;
        has_family_subscription NUMBER;
        consenting_user         NUMBER;
        allowed                 number := 0;
        is_fve                  CHAR(1) := 'N';
    BEGIN
        if user_id_in is not null then
            allowed := rhn_channel.user_role_check(channel_id_in, user_id_in, 'subscribe');
        else
            allowed := 1;
        end if;

        if allowed = 0 then
            rhn_exception.raise_exception('no_subscribe_permissions');
        end if;


        SELECT parent_channel INTO channel_parent_val FROM rhnChannel WHERE id = channel_id_in;

        IF channel_parent_val IS NOT NULL
        THEN
            -- child channel; if attempting to cross-subscribe a child to the wrong base, silently ignore
            parent_subscribed := FALSE;

            FOR check_subscription IN check_server_subscription(server_id_in, channel_parent_val)
            LOOP
                parent_subscribed := TRUE;
            END LOOP check_subscription;

            IF NOT parent_subscribed
            THEN
                RETURN;
            END IF;
        ELSE
            -- base channel
            server_has_base_chan := FALSE;
            FOR base IN server_base_subscriptions(server_id_in)
            LOOP
                server_has_base_chan := TRUE;
            END LOOP base;

            IF server_has_base_chan
            THEN
                rhn_exception.raise_exception('channel_server_one_base');
            END IF;
        END IF;

        FOR check_subscription IN check_server_subscription(server_id_in, channel_id_in)
        LOOP
            server_already_in_chan := TRUE;
        END LOOP check_subscription;

        IF server_already_in_chan
        THEN
            RETURN;
        END IF;

        channel_family_id_val := rhn_channel.family_for_channel(channel_id_in);
        IF channel_family_id_val IS NULL
        THEN
            rhn_exception.raise_exception('channel_subscribe_no_family');
        END IF;

        --
        -- Use the org_id of the server only if the org_id of the channel = NULL.
        -- This is required for subscribing to shared channels.
        --
        SELECT NVL(org_id, (SELECT org_id FROM rhnServer WHERE id = server_id_in))
          INTO server_org_id_val
          FROM rhnChannel
         WHERE id = channel_id_in;

        begin
            obtain_read_lock(channel_family_id_val, server_org_id_val);
        exception
            when no_data_found then
                rhn_exception.raise_exception('channel_family_no_subscriptions');
        end;

        available_subscriptions := rhn_channel.available_family_subscriptions(channel_family_id_val, server_org_id_val);
        available_fve_subs := rhn_channel.available_fve_family_subs(channel_family_id_val, server_org_id_val);
        has_family_subscription := rhn_channel.server_has_family_subscription(server_id_in, channel_family_id_val);

        IF available_subscriptions IS NULL OR
            available_subscriptions > 0 or
            can_server_consume_virt_channl(server_id_in, channel_family_id_val) = 1 OR
            (available_fve_subs > 0 AND can_server_consume_fve(server_id_in) = 1) OR
            has_family_subscription > 0
        THEN
            if can_server_consume_virt_channl(server_id_in, channel_family_id_val) = 0 AND available_fve_subs > 0 AND can_server_consume_fve(server_id_in) = 1 THEN
                is_fve := 'Y';
            END IF;
            insert into rhnServerHistory (id,server_id,summary,details) (
                select  rhn_event_id_seq.nextval,
                        server_id_in,
                        'subscribed to channel ' || SUBSTR(c.label, 0, 106),
                        c.label
                from    rhnChannel c
                where   c.id = channel_id_in
            );
            UPDATE rhnServer SET channels_changed = sysdate WHERE id = server_id_in;
            INSERT INTO rhnServerChannel (server_id, channel_id, is_fve) VALUES (server_id_in, channel_id_in, is_fve);
			IF recalcfamily_in > 0
			THEN
                rhn_channel.update_family_counts(channel_family_id_val, server_org_id_val);
			END IF;
            queue_server(server_id_in, immediate_in);
        ELSE
            rhn_exception.raise_exception('channel_family_no_subscriptions');
        END IF;

    END subscribe_server;



    FUNCTION can_convert_to_fve(server_id_in IN NUMBER, channel_family_id_val IN NUMBER)
    RETURN NUMBER
    IS
        CURSOR fve_convertible_entries IS
        select 1  from
            rhnServerFveCapable cap
          where cap.server_id = server_id_in
                AND cap.channel_family_id = channel_family_id_val;
    BEGIN
        FOR entry IN fve_convertible_entries LOOP
            return 1;
        END LOOP;
        RETURN 0;
    END can_convert_to_fve;



    -- Converts server channel_family to use a flex entitlement
    PROCEDURE convert_to_fve(server_id_in IN NUMBER, channel_family_id_val IN NUMBER)
    IS
        available_fve_subs      NUMBER;
        server_org_id_val       NUMBER;
    BEGIN

        --
        -- Use the org_id of the server only if the org_id of the channel = NULL.
        -- This is required for subscribing to shared channels.
        --
        SELECT org_id
          INTO server_org_id_val
          FROM rhnServer
         WHERE id = server_id_in;

        begin
            obtain_read_lock(channel_family_id_val, server_org_id_val);
        exception
            when no_data_found then
                rhn_exception.raise_exception('channel_family_no_subscriptions');
        end;
        IF (can_convert_to_fve(server_id_in, channel_family_id_val ) = 0)
            THEN
                rhn_exception.raise_exception('server_cannot_convert_to_flex');
        END IF;

        available_fve_subs := rhn_channel.available_fve_family_subs(channel_family_id_val, server_org_id_val);

        IF (available_fve_subs > 0)
        THEN

            insert into rhnServerHistory (id,server_id,summary,details) (
                select  rhn_event_id_seq.nextval,
                        server_id_in,
                        'converted to flex entitlement' || SUBSTR(cf.label, 0, 99),
                        cf.label
                from    rhnChannelFamily cf
                where   cf.id = channel_family_id_val
            );

            UPDATE rhnServerChannel sc set sc.is_fve = 'Y'
                           where sc.server_id = server_id_in and
                                 sc.channel_id in
                                    (select cfm.channel_id from rhnChannelFamilyMembers cfm
                                                where cfm.CHANNEL_FAMILY_ID = channel_family_id_val);

            rhn_channel.update_family_counts(channel_family_id_val, server_org_id_val);
        ELSE
            rhn_exception.raise_exception('not_enough_flex_entitlements');
        END IF;

    END convert_to_fve;

    function can_server_consume_virt_channl(
        server_id_in in number,
        family_id_in in number )
    return number
    is

        cursor server_virt_families is
            select vi.virtual_system_id, cfvsl.channel_family_id
            from
                rhnChannelFamilyVirtSubLevel cfvsl,
                rhnSGTypeVirtSubLevel sgtvsl,
                rhnVirtualInstance vi
            where
                vi.virtual_system_id = server_id_in
                and sgtvsl.virt_sub_level_id = cfvsl.virt_sub_level_id
                and cfvsl.channel_family_id = family_id_in
                and exists (
                    select 1
                    from rhnServerEntitlementView sev
                    where vi.host_system_id = sev.server_id
                    and sev.server_group_type_id = sgtvsl.server_group_type_id );
    begin

        for server_virt_family in server_virt_families loop
            return 1;
        end loop;

        return 0;

    end;

    FUNCTION can_server_consume_fve(server_id_in IN NUMBER)
    RETURN NUMBER
    IS
        CURSOR vi_entries IS
            SELECT 1
              FROM rhnVirtualInstance vi
             WHERE vi.virtual_system_id = server_id_in;
        vi_count NUMBER;

    BEGIN
        FOR vi_entry IN VI_ENTRIES LOOP
            return 1;
        END LOOP;
        RETURN 0;
    END;

    function guess_server_base(
        server_id_in in number
    ) RETURN number is
        cursor server_cursor is
            select s.server_arch_id, s.release, s.org_id
              from rhnServer s
             where s.id = server_id_in;
    begin
        for s in server_cursor loop
            for channel in base_channel_cursor(s.release,
                s.server_arch_id, s.org_id)
            loop
                return channel.id;
            end loop base_channel_cursor;
        end loop server_cursor;
        -- Server not found, or no base channel applies to it
        return null;
    end;

    -- Private function
    function normalize_server_arch(server_arch_in in varchar2)
    return varchar2
    deterministic
    is
        suffix VARCHAR2(128) := '-redhat-linux';
        suffix_len NUMBER := length(suffix);
    begin
        if server_arch_in is NULL then
            return NULL;
        end if;
        if instr(server_arch_in, '-') > 0
        then
            -- Suffix already present
            return server_arch_in;
        end if;
        return server_arch_in || suffix;
    end normalize_server_arch;

    --
    --
    -- Raises:
    --   server_arch_not_found
    --   no_subscribe_permissions
    function base_channel_for_release_arch(
        release_in in varchar2,
        server_arch_in in varchar2,
        org_id_in in number := -1,
        user_id_in in number := null
    ) return number is
        server_arch varchar2(256) := normalize_server_arch(server_arch_in);
        server_arch_id number;
    begin
        -- Look up the server arch
        begin
            select id
              into server_arch_id
              from rhnServerArch
             where label = server_arch;
        exception
            when no_data_found then
                rhn_exception.raise_exception('server_arch_not_found');
        end;
        return base_channel_rel_archid(release_in, server_arch_id,
            org_id_in, user_id_in);
    end base_channel_for_release_arch;

    function base_channel_rel_archid(
        release_in in varchar2,
        server_arch_id_in in number,
        org_id_in in number := -1,
        user_id_in in number := null
    ) return number is
        denied_channel_id number := null;
        valid_org_id number := org_id_in;
        valid_user_id number := user_id_in;
        channel_subscribable number;
    begin
        if org_id_in = -1 and user_id_in is not null then
            -- Get the org id from the user id
            begin
                select org_id
                  into valid_org_id
                  from web_contact
                 where id = user_id_in;
            exception
                when no_data_found then
                    -- User doesn't exist
                    -- XXX Only list public stuff for now
                    valid_user_id := null;
                    valid_org_id := -1;
            end;
        end if;

        for c in base_channel_cursor(release_in, server_arch_id_in, valid_org_id)
        loop
            -- This row is a possible match
            if valid_user_id is null then
                -- User ID not specified, so no user to channel permissions to
                -- check
                return c.id;
            end if;

            -- Check user to channel permissions
            select loose_user_role_check(c.id, user_id_in, 'subscribe')
              into channel_subscribable
              from dual;

            if channel_subscribable = 1 then
                return c.id;
            end if;

            -- Base channel exists, but is not subscribable; keep trying
            denied_channel_id := c.id;
        end loop base_channel_fetch;

        if denied_channel_id is not null then
            rhn_exception.raise_exception('no_subscribe_permissions');
        end if;
        -- No base channel applies
        return NULL;
    end base_channel_rel_archid;

    PROCEDURE clear_subscriptions(server_id_in IN NUMBER, deleting_server IN NUMBER := 0,
                                update_family_countsYN IN NUMBER := 1)
    IS
        cursor server_channels(server_id_in in number) is
                select  s.org_id, sc.channel_id, cfm.channel_family_id
                from    rhnServer s,
                        rhnServerChannel sc,
                        rhnChannelFamilyMembers cfm
                where   s.id = server_id_in
                        and s.id = sc.server_id
                        and sc.channel_id = cfm.channel_id
                order by cfm.channel_family_id;
        last_channel_family_id rhnChannelFamilyMembers.channel_family_id%type := -1;
        last_channel_org_id    rhnServer.org_id%type := -1;
    BEGIN
        for channel in server_channels(server_id_in)
        loop
                unsubscribe_server(server_id_in, channel.channel_id, 1, 1, deleting_server, 0);
                if update_family_countsYN > 0
                    and channel.channel_family_id != last_channel_family_id then
                    -- update family counts only once
                    -- after all channels with same family has been fetched
                    if last_channel_family_id != -1 then
                        update_family_counts(last_channel_family_id, last_channel_org_id);
                    end if;
                    last_channel_family_id := channel.channel_family_id;
                    last_channel_org_id    := channel.org_id;
                end if;
        end loop channel;
        if update_family_countsYN > 0 and last_channel_family_id != -1 then
            -- update the last family fetched
            update_family_counts(last_channel_family_id, last_channel_org_id);
        end if;
    END clear_subscriptions;

    PROCEDURE unsubscribe_server(server_id_in IN NUMBER, channel_id_in NUMBER, immediate_in NUMBER := 1, unsubscribe_children_in number := 0,
                                 deleting_server IN NUMBER := 0,
                                 update_family_countsYN IN NUMBER := 1)
    IS
        channel_family_id_val   NUMBER;
        server_org_id_val       NUMBER;
        available_subscriptions NUMBER;
        server_already_in_chan  BOOLEAN;
        cursor  channel_family_is_proxy(channel_family_id_in in number) is
                select  1
                from    rhnChannelFamily
                where   id = channel_family_id_in
                    and label = 'rhn-proxy';
        cursor  channel_family_is_satellite(channel_family_id_in in number) is
                select  1
                from    rhnChannelFamily
                where   id = channel_family_id_in
                    and label = 'rhn-satellite';
        -- this is *EXACTLY* like check_server_parent_membership, but if we recurse
        -- with the package-level one, we get a "cursor already open", so we need a
        -- copy on our call stack instead.  GROAN.
        cursor local_chk_server_parent_memb (
                        server_id_in number,
                        channel_id_in number ) is
                select  c.id
                from    rhnChannel                      c,
                                rhnServerChannel        sc
                where   1=1
                        and c.parent_channel = channel_id_in
                        and c.id = sc.channel_id
                        and sc.server_id = server_id_in;
    BEGIN
        FOR child IN local_chk_server_parent_memb(server_id_in, channel_id_in)
        LOOP
            if unsubscribe_children_in = 1 then
                unsubscribe_server(server_id_in => server_id_in,
                                                                channel_id_in => child.id,
                                                                immediate_in => immediate_in,
                                                                unsubscribe_children_in => unsubscribe_children_in,
                        deleting_server => deleting_server,
                        update_family_countsYN => update_family_countsYN);
            else
                rhn_exception.raise_exception('channel_unsubscribe_child_exists');
            end if;
        END LOOP child;

        server_already_in_chan := FALSE;

        FOR check_subscription IN check_server_subscription(server_id_in, channel_id_in)
        LOOP
            server_already_in_chan := TRUE;
        END LOOP check_subscription;

        IF NOT server_already_in_chan
        THEN
            RETURN;
        END IF;

   if deleting_server = 0 then

      insert into rhnServerHistory (id,server_id,summary,details) (
          select  rhn_event_id_seq.nextval,
                server_id_in,
             'unsubscribed from channel ' || SUBSTR(c.label, 0, 106),
             c.label
          from    rhnChannel c
          where   c.id = channel_id_in
      );

        UPDATE rhnServer SET channels_changed = sysdate WHERE id = server_id_in;
   end if;

   DELETE FROM rhnServerChannel WHERE server_id = server_id_in AND channel_id = channel_id_in;

   if deleting_server = 0 then
        queue_server(server_id_in, immediate_in);
   end if;

        channel_family_id_val := rhn_channel.family_for_channel(channel_id_in);
        IF channel_family_id_val IS NULL
        THEN
            rhn_exception.raise_exception('channel_unsubscribe_no_family');
        END IF;

        for ignore in channel_family_is_satellite(channel_family_id_val) loop
                delete from rhnSatelliteInfo where server_id = server_id_in;
        end loop;

        for ignore in channel_family_is_proxy(channel_family_id_val) loop
                delete from rhnProxyInfo where server_id = server_id_in;
        end loop;
        SELECT org_id INTO server_org_id_val
          FROM rhnServer
         WHERE id = server_id_in;

        if update_family_countsYN = 1 then
            rhn_channel.update_family_counts(channel_family_id_val, server_org_id_val);
        end if;
    END unsubscribe_server;


    FUNCTION family_for_channel(channel_id_in IN NUMBER)
    RETURN NUMBER
    IS
        channel_family_id_val NUMBER;
    BEGIN
        SELECT channel_family_id INTO channel_family_id_val
          FROM rhnChannelFamilyMembers
         WHERE channel_id = channel_id_in;

        RETURN channel_family_id_val;
    EXCEPTION
        WHEN NO_DATA_FOUND
        THEN
            RETURN NULL;
    END family_for_channel;

    FUNCTION available_family_subscriptions(channel_family_id_in IN NUMBER, org_id_in IN NUMBER)
    RETURN NUMBER
    IS
        cfp channel_family_perm_cursor%ROWTYPE;
        current_members_val NUMBER;
        max_members_val     NUMBER;
        found               NUMBER;
    BEGIN
        IF NOT channel_family_perm_cursor%ISOPEN
        THEN
            OPEN channel_family_perm_cursor(channel_family_id_in, org_id_in);
        END IF;

        FETCH channel_family_perm_cursor INTO cfp;

        WHILE channel_family_perm_cursor%FOUND
        LOOP
            found := 1;

            current_members_val := cfp.current_members;
            max_members_val := cfp.max_members;

            FETCH channel_family_perm_cursor INTO cfp;
        END LOOP;

        IF channel_family_perm_cursor%ISOPEN
        THEN
            CLOSE channel_family_perm_cursor;
        END IF;

        -- not found: either the channel fam doesn't have an entry in cfp, or the org doesn't have access to it.
        -- either way, there are no available subscriptions

        IF found IS NULL
        THEN
            RETURN 0;
        END IF;

        -- null max members?  in that case, pass it on; NULL means infinite
        IF max_members_val IS NULL
        THEN
            RETURN NULL;
        END IF;

        -- otherwise, return the delta
        RETURN max_members_val - current_members_val;
    END available_family_subscriptions;

    FUNCTION available_fve_family_subs(channel_family_id_in IN NUMBER, org_id_in IN NUMBER)
    RETURN NUMBER
    IS
        cfp channel_family_perm_cursor%ROWTYPE;
        fve_current_members_val NUMBER;
        fve_max_members_val     NUMBER;
        found               NUMBER;

    BEGIN
        IF NOT channel_family_perm_cursor%ISOPEN THEN
            OPEN channel_family_perm_cursor(channel_family_id_in, org_id_in);
        END IF;

        FETCH channel_family_perm_cursor INTO cfp;

        WHILE channel_family_perm_cursor%FOUND LOOP
            found := 1;
            fve_current_members_val := cfp.fve_current_members;
            fve_max_members_val := cfp.fve_max_members;
            FETCH channel_family_perm_cursor INTO cfp;
        END LOOP;

        IF channel_family_perm_cursor%ISOPEN THEN
            CLOSE channel_family_perm_cursor;
        END IF;

        IF found IS NULL THEN
            RETURN 0;
        END IF;

        IF fve_max_members_val IS NULL THEN
            RETURN NULL;
        END IF;

        RETURN fve_max_members_val - fve_current_members_val;

    END available_fve_family_subs;


    -- *******************************************************************
    -- FUNCTION: channel_family_current_members
    -- Calculates and returns the actual count of systems consuming
    --   physical channel subscriptions.
    -- Called by: update_family_counts
    --            rhn_entitlements.repoll_virt_guest_entitlements
    -- *******************************************************************
    function channel_family_current_members(channel_family_id_in IN NUMBER,
                                            org_id_in IN NUMBER)
    return number
    is
        current_members_count number := 0;
    begin
        select  count(distinct server_id)
        into    current_members_count
          from  rhnChannelFamilyServerPhysical cfsp
         where  cfsp.channel_family_id = channel_family_id_in
           and  cfsp.customer_id = org_id_in;
        return current_members_count;
    end;


    function cfam_curr_fve_members(
        channel_family_id_in IN NUMBER,
        org_id_in IN NUMBER)
    return number
    is
        current_members_count number := 0;

    begin
        select count(sc.server_id)
          into current_members_count
          from rhnServerChannel sc,
               rhnChannelFamilyMembers cfm,
               rhnServer s
         where s.org_id = org_id_in
           and s.id = sc.server_id
           and cfm.channel_family_id = channel_family_id_in
           and cfm.channel_id = sc.channel_id
           and exists (
                select 1
                  from rhnChannelFamilyServerFve cfsp
                 where cfsp.CHANNEL_FAMILY_ID = channel_family_id_in
                   and cfsp.server_id = s.id
                );

        return current_members_count;
    end;
    PROCEDURE update_family_counts(channel_family_id_in IN NUMBER,
                                   org_id_in IN NUMBER)
    IS
    BEGIN
        update rhnPrivateChannelFamily
           set current_members = ( channel_family_current_members(channel_family_id_in, org_id_in)),
               fve_current_members = ( cfam_curr_fve_members(channel_family_id_in, org_id_in))
         where org_id = org_id_in
           and channel_family_id = channel_family_id_in;
    END update_family_counts;

    PROCEDURE update_group_family_counts(group_label_in IN VARCHAR2,
                                   org_id_in IN NUMBER)
    IS
    BEGIN
        FOR i IN (
                SELECT DISTINCT CFM.channel_family_id, SG.org_id
                 FROM rhnChannelFamilyMembers CFM
                 JOIN rhnServerChannel SC
                   ON SC.channel_id = CFM.channel_id
                 JOIN rhnServerGroupMembers SGM
                   ON SC.server_id = SGM.server_id
                 JOIN rhnServerGroup SG
                   ON SGM.server_group_id = SG.id
                 JOIN rhnServerGroupType SGT
                   ON SG.group_type = SGT.id
                WHERE SGT.label = group_label_in
                  AND SG.org_id = org_id_in
                  AND SGT.is_base = 'Y'
        ) LOOP
            rhn_channel.update_family_counts(i.channel_family_id, i.org_id);
        END LOOP;
    END update_group_family_counts;

    FUNCTION available_chan_subscriptions(channel_id_in IN NUMBER,
                                          org_id_in IN NUMBER)
    RETURN NUMBER
    IS
            channel_family_id_val NUMBER;
    BEGIN
        SELECT channel_family_id INTO channel_family_id_val
            FROM rhnChannelFamilyMembers
            WHERE channel_id = channel_id_in;

            RETURN rhn_channel.available_family_subscriptions(
                           channel_family_id_val, org_id_in);
    END available_chan_subscriptions;

	FUNCTION available_fve_chan_subs(channel_id_in IN NUMBER,
                                          org_id_in IN NUMBER)
    RETURN NUMBER
    IS
        channel_family_id_val NUMBER;

    BEGIN
        SELECT channel_family_id INTO channel_family_id_val
          FROM rhnChannelFamilyMembers
         WHERE channel_id = channel_id_in;

        RETURN rhn_channel.available_fve_family_subs( channel_family_id_val, org_id_in);
    END available_fve_chan_subs;

    procedure unsubscribe_server_from_family(server_id_in in number,
                                             channel_family_id_in in number)
    is
    begin
        delete
        from    rhnServerChannel rsc
        where   rsc.server_id = server_id_in
            and channel_id in (
                select  rcfm.channel_id
                from    rhnChannelFamilyMembers rcfm
                where   rcfm.channel_family_id = channel_family_id_in);
    end;

    function get_org_id(channel_id_in in number)
    return number
    is
        org_id_out number;
    begin
        select org_id into org_id_out
            from rhnChannel
            where id = channel_id_in;

            return org_id_out;
    end get_org_id;

    function get_cfam_org_access(cfam_id_in in number, org_id_in in number)
    return number
    is
        cursor  families is
                        select  1
                        from    rhnOrgChannelFamilyPermissions cfp
                        where   cfp.org_id = org_id_in;
    begin
                -- the idea: if we get past this query,
        -- the user has the role, else catch the exception and return 0
                for family in families loop
                return 1;
                end loop;
                return 0;
    end;

    function get_org_access(channel_id_in in number, org_id_in in number)
    return number
    is
        throwaway number;
    begin
        -- the idea: if we get past this query,
        -- the org has access to the channel, else catch the exception and return 0
        select distinct 1 into throwaway
          from rhnChannelFamilyMembers CFM,
               rhnOrgChannelFamilyPermissions CFP
         where cfp.org_id = org_id_in
           and CFM.channel_family_id = CFP.channel_family_id
           and CFM.channel_id = channel_id_in
           and (CFP.max_members > 0 or CFP.max_members is null or CFP.fve_max_members > 0 or CFP.fve_max_members is null or CFP.org_id = 1);

        return 1;
        exception
            when no_data_found
            then
            return 0;
    end;

    -- check if a user has a given role, or if such a role is inferrable
    function user_role_check_debug(channel_id_in in number,
                                   user_id_in in number,
                                   role_in in varchar2,
                                   reason_out out varchar2)
    return number
    is
        org_id number;
    begin
        org_id := rhn_user.get_org_id(user_id_in);

        -- channel might be shared
        if role_in = 'subscribe' and
           rhn_channel.shared_user_role_check(channel_id_in, user_id_in, role_in) = 1 then
            return 1;
        end if;

        if role_in = 'manage' and
           NVL(rhn_channel.get_org_id(channel_id_in), -1) <> org_id then
                reason_out := 'channel_not_owned';
               return 0;
            end if;

        if role_in = 'subscribe' and
           rhn_channel.get_org_access(channel_id_in, org_id) = 0 then
                reason_out := 'channel_not_available';
                return 0;
            end if;

        -- channel admins have all roles
        if rhn_user.check_role_implied(user_id_in, 'channel_admin') = 1 then
            reason_out := 'channel_admin';
            return 1;
            end if;

        -- the subscribe permission is inferred
    -- UNLESS the not_globally_subscribable flag is set
        if role_in = 'subscribe'
        then
            if rhn_channel.org_channel_setting(channel_id_in,
                       org_id,
                       'not_globally_subscribable') = 0 then
                reason_out := 'globally_subscribable';
                    return 1;
            end if;
        end if;

        -- all other roles (manage right now) are explicitly granted
        reason_out := 'direct_permission';
        return rhn_channel.direct_user_role_check(channel_id_in,
                                              user_id_in, role_in);
    end;

    -- same as above, but with no OUT param; useful in views, etc
    function user_role_check(channel_id_in in number, user_id_in in number, role_in in varchar2)
    return number
    is
        throwaway varchar2(256);
    begin
        return rhn_channel.user_role_check_debug(channel_id_in, user_id_in, role_in, throwaway);
    end;

    --
    -- For multiorg phase II, this function simply checks to see if the user's
    -- has a trust relationship that includes this channel by id.
    --
    function shared_user_role_check(channel_id in number, user_id in number, role in varchar2)
    return number
    is
      n number;
      oid number;
    begin
      oid := rhn_user.get_org_id(user_id);
      select 1 into n
      from rhnSharedChannelView s
      where s.id = channel_id and s.org_trust_id = oid;
      return 1;
      exception
        when no_data_found then
          return 0;
    end;

    -- same as above, but returns 1 if user_id_in is null
    -- This is useful in queries where user_id is not specified
    function loose_user_role_check(channel_id_in in number, user_id_in in number, role_in in varchar2)
    return number
    is
    begin
        if user_id_in is null then
            return 1;
        end if;
        return user_role_check(channel_id_in, user_id_in, role_in);
    end loose_user_role_check;

    -- directly checks the table, no inferred permissions
    function direct_user_role_check(channel_id_in in number, user_id_in in number, role_in in varchar2)
    return number
    is
        throwaway number;
    begin
        -- the idea: if we get past this query, the user has the role, else catch the exception and return 0
        select 1 into throwaway
          from rhnChannelPermissionRole CPR,
               rhnChannelPermission CP
         where CP.user_id = user_id_in
           and CP.channel_id = channel_id_in
           and CPR.label = role_in
           and CP.role_id = CPR.id;

        return 1;
    exception
        when no_data_found
            then
            return 0;
    end;

    -- check if an org has a certain setting
    function org_channel_setting(channel_id_in in number, org_id_in in number, setting_in in varchar2)
    return number
    is
        throwaway number;
    begin
        -- the idea: if we get past this query, the org has the setting, else catch the exception and return 0
        select 1 into throwaway
          from rhnOrgChannelSettingsType OCST,
               rhnOrgChannelSettings OCS
         where OCS.org_id = org_id_in
           and OCS.channel_id = channel_id_in
           and OCST.label = setting_in
           and OCS.setting_id = OCST.id;

        return 1;
    exception
        when no_data_found
            then
            return 0;
    end;

    FUNCTION channel_priority(channel_id_in IN number)
    RETURN number
    IS
         channel_name varchar2(256);
         priority number;
         end_of_life_val date;
         org_id_val number;
    BEGIN

        select name, end_of_life, org_id
        into channel_name, end_of_life_val, org_id_val
        from rhnChannel
        where id = channel_id_in;

        if end_of_life_val is not null then
          return -400;
        end if;

        if channel_name like 'Red Hat Enterprise Linux%' or channel_name like 'RHEL%' then
          priority := 1000;
          if channel_name not like '%Beta%' then
            priority := priority + 1000;
          end if;

          priority := priority +
            case
              when channel_name like '%v. 5%' then 600
              when channel_name like '%v. 4%' then 500
              when channel_name like '%v. 3%' then 400
              when channel_name like '%v. 2%' then 300
              when channel_name like '%v. 1%' then 200
              else 0
            end;

          priority := priority +
            case
              when channel_name like 'Red Hat Enterprise Linux (v. 5%' then 60
              when (channel_name like '%AS%' and channel_name not like '%Extras%') then 50
              when (channel_name like '%ES%' and channel_name not like '%Extras%') then 40
              when (channel_name like '%WS%' and channel_name not like '%Extras%') then 30
              when (channel_name like '%Desktop%' and channel_name not like '%Extras%') then 20
              when channel_name like '%Extras%' then 10
              else 0
            end;

          priority := priority +
            case
              when channel_name like '%)' then 5
              else 0
            end;

          priority := priority +
            case
              when channel_name like '%32-bit x86%' then 4
              when channel_name like '%64-bit Intel Itanium%' then 3
              when channel_name like '%64-bit AMD64/Intel EM64T%' then 2
              else 0
            end;
        elsif channel_name like 'Red Hat Desktop%' then
            priority := 900;

            if channel_name not like '%Beta%' then
               priority := priority + 50;
            end if;

          priority := priority +
            case
              when channel_name like '%v. 4%' then 40
              when channel_name like '%v. 3%' then 30
              when channel_name like '%v. 2%' then 20
              when channel_name like '%v. 1%' then 10
              else 0
            end;

          priority := priority +
            case
              when channel_name like '%32-bit x86%' then 4
              when channel_name like '%64-bit Intel Itanium%' then 3
              when channel_name like '%64-bit AMD64/Intel EM64T%' then 2
              else 0
            end;

        elsif org_id_val is not null then
          priority := 600;
        else
          priority := 500;
        end if;

      return -priority;

    end channel_priority;

    -- right now this only does the accounting changes; the cascade
    -- actually does the rhnServerChannel delete.
    procedure delete_server_channels(server_id_in in number)
    is
    begin
        update  rhnPrivateChannelFamily
        set     current_members = current_members -1
        where   org_id in (
                        select  org_id
                        from    rhnServer
                        where   id = server_id_in
                )
                and channel_family_id in (
                        select  rcfm.channel_family_id
                        from    rhnChannelFamilyMembers rcfm,
                                rhnServerChannel rsc
                        where   rsc.server_id = server_id_in
                                and rsc.channel_id = rcfm.channel_id
                and not exists (
                    select 1
                    from
                        rhnChannelFamilyVirtSubLevel cfvsl,
                        rhnSGTypeVirtSubLevel sgtvsl,
                        rhnServerEntitlementView sev,
                        rhnVirtualInstance vi
                    where
                        -- system is a virtual instance
                        vi.virtual_system_id = server_id_in
                        and vi.host_system_id = sev.server_id
                        -- system's host has a virt ent
                        and sev.label in ('virtualization_host',
                                          'virtualization_host_platform')
                        and sev.server_group_type_id =
                            sgtvsl.server_group_type_id
                        -- the host's virt ent grants a cf virt sub level
                        and sgtvsl.virt_sub_level_id = cfvsl.virt_sub_level_id
                        -- the cf is in that virt sub level
                        and cfvsl.channel_family_id = rcfm.channel_family_id
                    )
                );
    end;

    -- this could certainly be optimized to do updates if needs be
    procedure refresh_newest_package(channel_id_in in number,
                                     caller_in in varchar2 := '(unknown)',
                                     package_name_id_in in number := null)
    is
    -- procedure refreshes rows for name_id = package_name_id_in or
    -- all rows if package_name_id_in is null
    begin
        delete from rhnChannelNewestPackage
              where channel_id = channel_id_in
                and (package_name_id_in is null
                     or name_id = package_name_id_in);
        insert into rhnChannelNewestPackage
                (channel_id, name_id, evr_id, package_id, package_arch_id)
                (select channel_id,
                        name_id, evr_id,
                        package_id, package_arch_id
                   from rhnChannelNewestPackageView
                  where channel_id = channel_id_in
                    and (package_name_id_in is null
                         or name_id = package_name_id_in)
                );
        insert into rhnChannelNewestPackageAudit (channel_id, caller)
             values (channel_id_in, caller_in);
        update rhnChannel
           set last_modified = greatest(sysdate, last_modified + 1/86400)
         where id = channel_id_in;
    end;

   procedure update_channel ( channel_id_in in number, invalidate_ss in number := 0,
                              date_to_use in date := sysdate )
   is

   channel_last_modified date;
   last_modified_value date;

   cursor snapshots is
   select  snapshot_id id
   from    rhnSnapshotChannel
   where   channel_id = channel_id_in;

   begin

      select last_modified
      into channel_last_modified
      from rhnChannel
      where id = channel_id_in;

      last_modified_value := date_to_use;

      if last_modified_value <= channel_last_modified then
          last_modified_value := last_modified_value + 1/86400;
      end if;

      update rhnChannel set last_modified = last_modified_value
      where id = channel_id_in;

      if invalidate_ss = 1 then
        for snapshot in snapshots loop
            update rhnSnapshot
            set invalid = lookup_snapshot_invalid_reason('channel_modified')
            where id = snapshot.id;
        end loop;
      end if;

   end update_channel;

   procedure update_channels_by_package ( package_id_in in number, date_to_use in date := sysdate )
   is

   cursor channels is
   select channel_id
   from rhnChannelPackage
   where package_id = package_id_in
   order by channel_id;

   begin
      for channel in channels loop
         -- we want to invalidate the snapshot assocated with the channel when we
         -- do this b/c we know we've added or removed or packages
         rhn_channel.update_channel ( channel.channel_id, 1, date_to_use );
      end loop;
   end update_channels_by_package;


   procedure update_channels_by_errata ( errata_id_in number, date_to_use in date := sysdate )
   is

   cursor channels is
   select channel_id
   from rhnChannelErrata
   where errata_id = errata_id_in
   order by channel_id;

   begin
      for channel in channels loop
         -- we won't invalidate snapshots, b/c just changing the errata associated with
         -- a channel shouldn't invalidate snapshots
         rhn_channel.update_channel ( channel.channel_id, 0, date_to_use );
      end loop;
   end update_channels_by_errata;

   procedure update_needed_cache(channel_id_in in number)
   is
       pragma autonomous_transaction;
                -- update of needed cache ican be commited on a per server basis
                -- b/c failure of update for a server means nothing for the other servers
   begin
      -- we intentionaly do a loop here instead of one huge select
      -- b/c we want to break update into smaller transaction to unblock other sessions
      -- querying rhnServerNeededCache
      for server in (
                select sc.server_id as id
                  from rhnServerChannel sc
                 where sc.channel_id = channel_id_in
      ) loop
         rhn_server.update_needed_cache(server.id);
         commit;
      end loop;
   end update_needed_cache;

   -- return true if the given server has a subs to a channel of channel_family_id_in
   FUNCTION server_has_family_subscription(server_id_in IN NUMBER, channel_family_id_in IN NUMBER)
   RETURN NUMBER
   IS
      CURSOR fam_entries IS
         SELECT DISTINCT cfm.channel_family_id
           FROM rhnchannelfamilymembers cfm
           JOIN rhnserverchannel sc on sc.channel_id = cfm.channel_id
          WHERE sc.server_id =  server_id_in
            AND cfm.channel_family_id = channel_family_id_in;
      fam_count NUMBER;
   BEGIN
      FOR fam_entry IN fam_entries LOOP
         RETURN 1;
      END LOOP;
      RETURN 0;
   END server_has_family_subscription;

END rhn_channel;
/
SHOW ERRORS
07070100000917000081B400000000000000000000000167AE1114000002F5000000000000000000000000000000000000006C00000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/607-rhnPackageGroup-trim.sql   begin
    for rec in (
        select id as old_id,
               min(id) over ( partition by rtrim(translate(name, chr(10), ' ')) ) as new_id
          from rhnPackageGroup
    ) loop
        if rec.new_id < rec.old_id then

            update rhnPackage
               set package_group = rec.new_id
             where package_group = rec.old_id;

            update rhnPackageSource
               set package_group = rec.new_id
             where package_group = rec.old_id;

            delete
              from rhnPackageGroup
             where id = rec.old_id;
        end if;
    end loop;

    update rhnPackageGroup
       set name = rtrim(translate(name, chr(10), ' '))
     where name <> rtrim(translate(name, chr(10), ' '));
end;
/

commit;
   07070100000918000081B400000000000000000000000167AE111400000616000000000000000000000000000000000000006B00000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/611-rhn_contact_methods.sql    
--
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

create or replace trigger
rhn_cmeth_val_trig
before insert or update on rhn_contact_methods
referencing new as new old as old
for each row
declare
    msg  varchar2(200);
    missing_data exception;
begin
    msg :='missing or invalid data for contact_methods table';

    if :new.method_type_id = 1
    then

    --- pager fields pager_email,pager_split_long_messages should be not null
        if (
            :new.pager_email   is null     or
            :new.pager_split_long_messages  is null )
        then
            raise missing_data;
        end if;
    end if;

    if :new.method_type_id = 2
    then

    --- the all email fields but email_reply_to should be not null
        if :new.email_address is null
        then
            raise missing_data;
        end if;
    end if;

    exception
    when missing_data then
    raise_application_error (-20012,msg);
    when others then
    raise;
end;
/
show errors
  07070100000919000081B400000000000000000000000167AE111400005773000000000000000000000000000000000000006600000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/612-rhn_server.pkb.sql --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--

create or replace
package body rhn_server
is
    function system_service_level(
    	server_id_in in number,
	service_level_in in varchar2
    ) return number is

    cursor ents is 
      select label from rhnServerEntitlementView
      where server_id = server_id_in;

    retval number := 0;

    begin
         for ent in ents loop
            retval := rhn_entitlements.entitlement_grants_service (ent.label, service_level_in);
            if retval = 1 then
               return retval;
            end if;
         end loop;

         return retval;

    end system_service_level;

        
    function can_change_base_channel(server_id_in IN NUMBER)
    return number
    is
    	throwaway number;
    begin
    	-- the idea: if we get past this query, the server is
	-- neither sat nor proxy, so base channel is changeable
	
	select 1 into throwaway
	  from rhnServer S
	 where S.id = server_id_in
	   and not exists (select 1 from rhnSatelliteInfo SI where SI.server_id = S.id)
	   and not exists (select 1 from rhnProxyInfo PI where PI.server_id = S.id);
	   
	return 1;
    exception
    	when no_data_found
	    then
	    return 0;
    end can_change_base_channel;
	        
    procedure set_custom_value(
    	server_id_in in number,
	user_id_in in number,
	key_label_in in varchar2,
	value_in in varchar2
    ) is
    	key_id_val number;
    begin
    	select CDK.id into key_id_val
	  from rhnCustomDataKey CDK,
	       rhnServer S
	 where S.id = server_id_in
	   and S.org_id = CDK.org_id
	   and CDK.label = key_label_in;
	   
	begin
	    insert into rhnServerCustomDataValue (server_id, key_id, value, created_by, last_modified_by)
	    values (server_id_in, key_id_val, value_in, user_id_in, user_id_in);
	exception
	    when DUP_VAL_ON_INDEX
	    	then
		update rhnServerCustomDataValue
		   set value = value_in,
		       last_modified_by = user_id_in
		 where server_id = server_id_in
		   and key_id = key_id_val;		   
	end;
	
    end set_custom_value;
    
    function bulk_set_custom_value(
    	key_label_in in varchar2,
	value_in in varchar2,
	set_label_in in varchar2,
	set_uid_in in number
    )
    return integer
    is
    i integer := 0;
    begin
        i := 0;
        for server in (
           SELECT user_id, label, element, element_two
	     FROM rhnSet
	    WHERE label = set_label_in
	      AND user_id = set_uid_in
	) loop
	    if rhn_server.system_service_level(server.element, 'provisioning') = 1 then
	    	rhn_server.set_custom_value(server.element, set_uid_in, key_label_in, value_in);
            i := i + 1;
	    end if;
	end loop server;
    return i;
    end bulk_set_custom_value;

    procedure bulk_snapshot_tag(
    	org_id_in in number,
        tagname_in in varchar2,
	set_label_in in varchar2,
	set_uid_in in number
    ) is
    	snapshot_id number;
    begin
        for server in (
           SELECT user_id, label, element, element_two
	     FROM rhnSet
	    WHERE label = set_label_in
	      AND user_id = set_uid_in
	    ) loop
	    if rhn_server.system_service_level(server.element, 'provisioning') = 1 then
	    	begin
	    	    select max(id) into snapshot_id
	    	    from rhnSnapshot
	    	    where server_id = server.element;
	    	exception
	    	    when NO_DATA_FOUND then
		    	rhn_server.snapshot_server(server.element, 'tagging system:  ' || tagname_in);
			
			select max(id) into snapshot_id
			from rhnSnapshot
			where server_id = server.element;
		end;
		 
		-- now have a snapshot_id to work with...
		begin
		    rhn_server.tag_snapshot(snapshot_id, org_id_in, tagname_in);
		exception
		    when DUP_VAL_ON_INDEX
		    	then
			-- do nothing, be forgiving...
			null;
		end;
	    end if;
	end loop server;    
    end bulk_snapshot_tag;

    procedure tag_delete(
    	server_id_in in number,
	tag_id_in in number
    ) is
    	cursor snapshots is
		select	snapshot_id
		from	rhnSnapshotTag
		where	tag_id = tag_id_in;
	tag_id_tmp number;
    begin
    	select	id into tag_id_tmp
	from	rhnTag
	where	id = tag_id_in
	for update;

	delete
		from	rhnSnapshotTag
		where	server_id = server_id_in
			and tag_id = tag_id_in;
	for snapshot in snapshots loop
		return;
	end loop;
	delete
		from rhnTag
		where id = tag_id_in;
    end tag_delete;

    procedure tag_snapshot(
        snapshot_id_in in number,
	org_id_in in number,
	tagname_in in varchar2
    ) is
    begin
    	insert into rhnSnapshotTag (snapshot_id, server_id, tag_id)
	select snapshot_id_in, server_id, lookup_tag(org_id_in, tagname_in)
	from rhnSnapshot
	where id = snapshot_id_in;
    end tag_snapshot;

    procedure bulk_snapshot(
    	reason_in in varchar2,
	set_label_in in varchar2,
	set_uid_in in number
    ) is
    begin
        for server in (
           SELECT user_id, label, element, element_two
	     FROM rhnSet
	    WHERE label = set_label_in
	      AND user_id = set_uid_in
	    ) loop
    	    if rhn_server.system_service_level(server.element, 'provisioning') = 1 then
	    	rhn_server.snapshot_server(server.element, reason_in);
	    end if;
	end loop server;
    end bulk_snapshot;

    procedure snapshot_server(
    	server_id_in in number,
	reason_in in varchar2
    ) is
    	snapshot_id number;
	cursor revisions is
		select distinct
			cr.id
		from	rhnConfigRevision	cr,
			rhnConfigFileName	cfn,
			rhnConfigFile		cf,
			rhnConfigChannel	cc,
			rhnServerConfigChannel	scc
		where	1=1
			and scc.server_id = server_id_in
			and scc.config_channel_id = cc.id
			and cc.id = cf.config_channel_id
			and cf.id = cr.config_file_id
			and cr.id = cf.latest_config_revision_id
			and cf.config_file_name_id = cfn.id
			and cf.id = lookup_first_matching_cf(scc.server_id, cfn.path);
	locked integer;
    begin
    	select rhn_snapshot_id_seq.nextval into snapshot_id from dual;

	insert into rhnSnapshot (id, org_id, server_id, reason) (
		select	snapshot_id,
			s.org_id,
			server_id_in,
			reason_in
		from	rhnServer s
		where	s.id = server_id_in
	);
	insert into rhnSnapshotChannel (snapshot_id, channel_id) (
		select	snapshot_id, sc.channel_id
		from	rhnServerChannel sc
		where	sc.server_id = server_id_in
	);
	insert into rhnSnapshotServerGroup (snapshot_id, server_group_id) (
		select	snapshot_id, sgm.server_group_id
		from	rhnServerGroupMembers sgm
		where	sgm.server_id = server_id_in
	);
        locked := 0;
        while true loop
            begin
                insert into rhnPackageNEVRA (id, name_id, evr_id, package_arch_id)
                select rhn_pkgnevra_id_seq.nextval, sp.name_id, sp.evr_id, sp.package_arch_id
                from rhnServerPackage sp
                where sp.server_id = server_id_in
                        and not exists
                        (select 1
                                from rhnPackageNEVRA nevra
                                where nevra.name_id = sp.name_id
                                        and nevra.evr_id = sp.evr_id
                                        and (nevra.package_arch_id = sp.package_arch_id
                                            or (nevra.package_arch_id is null
                                                and sp.package_arch_id is null)));
                exit;
            exception when dup_val_on_index then
                if locked = 1 then
                    raise;
                else
                    lock table rhnPackageNEVRA in exclusive mode;
                    locked := 1;
                end if;
            end;
        end loop;
	insert into rhnSnapshotPackage (snapshot_id, nevra_id) (
                select distinct snapshot_id, nevra.id
                from    rhnServerPackage sp, rhnPackageNEVRA nevra
                where   sp.server_id = server_id_in
                        and nevra.name_id = sp.name_id
                        and nevra.evr_id = sp.evr_id
                        and (nevra.package_arch_id = sp.package_arch_id
                            or (nevra.package_arch_id is null
                                and sp.package_arch_id is null))
	);

	insert into rhnSnapshotConfigChannel ( snapshot_id, config_channel_id ) (
		select	snapshot_id, scc.config_channel_id
		from	rhnServerConfigChannel scc
		where	server_id = server_id_in
	);

	for revision in revisions loop
		insert into rhnSnapshotConfigRevision (
				snapshot_id, config_revision_id
			) values (
				snapshot_id, revision.id
			);
	end loop;
    end snapshot_server;

    procedure remove_action(
    	server_id_in in number,
	action_id_in in number
    ) is
    	-- this really wants "nulls last", but 8.1.7.3.0 sucks ass.
	-- instead, we make a local table that holds our
	-- list of ids with null prereqs.  There's surely a better way
	-- (an array instead of a table maybe?  who knows...)
	-- but I've got code to do this handy that I can look at ;)
    	cursor chained_actions is
		select	id, prerequisite
		from	rhnAction
		start with id = action_id_in
		connect by prior id = prerequisite
		order by prerequisite desc;
	cursor sessions is
		select	s.id
		from	rhnKickstartSession s
		where	server_id_in in (s.old_server_id, s.new_server_id)
			and s.action_id = action_id_in
			and not exists (
				select	1
				from	rhnKickstartSessionState ss
				where	ss.id = s.state_id
					and ss.label in ('failed','complete')
			);
	type chain_end_type is table of number index by binary_integer;
	chain_ends chain_end_type;
	i number;
	prereq number := 1;
    begin
	select	prerequisite
	into	prereq
	from	rhnAction
	where	id = action_id_in;

	if prereq is not null then
		rhn_exception.raise_exception('action_is_child');
	end if;

	i := 0;
	for action in chained_actions loop
		if action.prerequisite is null then
			chain_ends(i) := action.id;
			i := i + 1;
		else
			delete from rhnServerAction
				where server_id = server_id_in
				and action_id = action.id;
		end if;
	end loop;
	i := chain_ends.first;
	while i is not null loop
		delete from rhnServerAction
			where server_id = server_id_in
			and action_id = chain_ends(i);
		i := chain_ends.next(i);
	end loop;
	for s in sessions loop
		update rhnKickstartSession
			set 	state_id = (
					select	id
					from	rhnKickstartSessionState
					where	label = 'failed'
				),
				action_id = null
			where	id = s.id;
		set_ks_session_history_message(s.id, 'failed', 'Kickstart cancelled due to action removal');
	end loop;
    end remove_action;
   
    function check_user_access(server_id_in in number, user_id_in in number)
    return number
    is
    	has_access number;
    begin
    	-- first check; if this returns no rows, then the server/user are in different orgs, and we bail
        select 1 into has_access
	  from rhnServer S,
	       web_contact wc
	 where wc.org_id = s.org_id
	   and s.id = server_id_in
	   and wc.id = user_id_in;

	-- okay, so they're in the same org.  if we have an org admin, they get a free pass
    	if rhn_user.check_role(user_id_in, 'org_admin') = 1
	then
	    return 1;
	end if;
		   
    	select 1 into has_access
	  from rhnServerGroupMembers SGM,
	       rhnUserServerGroupPerms USG
	 where SGM.server_group_id = USG.server_group_id
	   and SGM.server_id = server_id_in
	   and USG.user_id = user_id_in
	   and rownum = 1;
	   
	return 1;
    exception
    	when no_data_found
	    then
	    return 0;
    end check_user_access;

    -- *******************************************************************
    -- FUNCTION: can_server_consume_virt_slot
    -- Returns 1 if the server id is eligible to consume a virtual slot,
    --   else returns 0.
    -- Called by: insert_into_servergroup, delete_from_servergroup
    -- *******************************************************************
    function can_server_consume_virt_slot(server_id_in in number,
                                           group_type_in in
                                           rhnServerGroupType.label%TYPE)
    return number                                           
    is

        cursor server_virt_slots is
            select vi.VIRTUAL_SYSTEM_ID
            from
                rhnVirtualInstance vi
            where
                -- server id is a virtual instance
                vi.VIRTUAL_SYSTEM_ID = server_id_in
                -- server id's host is virt entitled
                and exists ( select 1
                     from rhnServerEntitlementView sev
                 where vi.HOST_SYSTEM_ID = sev.server_id
                 and sev.label in ('virtualization_host',
                                   'virtualization_host_platform') )
                -- server id's host also has the ent we want
                and exists ( select 1
                     from rhnServerEntitlementView sev2
                 where vi.HOST_SYSTEM_ID = sev2.server_id
                 and sev2.label = group_type_in );

    begin
        for server_virt_slot in server_virt_slots loop
            return 1;
        end loop;
        return 0;
    end can_server_consume_virt_slot;


    procedure insert_into_servergroup (
		server_id_in in number,
		server_group_id_in in number
    ) is
		used_slots number;
		max_slots number;
		org_id number;
		mgmt_available number;
		mgmt_upgrade number;
		mgmt_sgid number;
		prov_available number;
		prov_upgrade number;
		prov_sgid number;
		group_label rhnServerGroupType.label%TYPE;
		group_type number;
	begin
		-- frist, group_type = null, because it's easy...

		-- this will rowlock the servergroup we're trying to change;
		-- we probably need to lock the other one, but I think the chances
		-- of it being a real issue are very small for now...
		select	sg.group_type, sg.org_id, sg.current_members, sg.max_members
		into	group_type, org_id, used_slots, max_slots
		from	rhnServerGroup sg
		where	sg.id = server_group_id_in
		for update of sg.current_members;

		if group_type is null then
			if used_slots >= max_slots then
				rhn_exception.raise_exception('servergroup_max_members');
			end if;

			insert into rhnServerGroupMembers(
					server_id, server_group_id
				) values (
					server_id_in, server_group_id_in
				);
			update rhnServerGroup
				set current_members = current_members + 1
				where id = server_group_id_in;

			rhn_cache.update_perms_for_server_group(server_group_id_in);
			return;
		end if;

		-- now for group_type != null
		-- 
		select	label
		into	group_label
		from	rhnServerGroupType	sgt
		where	sgt.id = group_type;

		-- the naive easy path that gets hit most often and has to be quickest.
		if group_label in ('sw_mgr_entitled',
                           'enterprise_entitled',
                           'monitoring_entitled',
                           'provisioning_entitled',
                           'virtualization_host',
                           'virtualization_host_platform') then
			if used_slots >= max_slots and 
               (can_server_consume_virt_slot(server_id_in, group_label) != 1) 
               then
				rhn_exception.raise_exception('servergroup_max_members');
			end if;

			insert into rhnServerGroupMembers(
					server_id, server_group_id
				) values (
					server_id_in, server_group_id_in
				);

            -- Only update current members if the system in consuming a 
            -- physical slot.
            if can_server_consume_virt_slot(server_id_in, group_label) = 0 then
                update rhnServerGroup
                set current_members = current_members + 1
                where id = server_group_id_in;
            end if;                

			return;
		end if;
	end;

	function insert_into_servergroup_maybe (
		server_id_in in number,
		server_group_id_in in number
	) return number is 
		retval number := 0;
		cursor servergroups is
			select	s.id	server_id,
					sg.id	server_group_id
			from	rhnServerGroup	sg,
					rhnServer		s
			where	s.id = server_id_in
				and sg.id = server_group_id_in
				and s.org_id = sg.org_id
				and not exists (
					select	1
					from	rhnServerGroupMembers sgm
					where	sgm.server_id = s.id
						and sgm.server_group_id = sg.id
				);
	begin
		for sgm in servergroups loop
			rhn_server.insert_into_servergroup(sgm.server_id, sgm.server_group_id);
			retval := retval + 1;
		end loop;
		return retval;
	end insert_into_servergroup_maybe;

	procedure insert_set_into_servergroup (
		server_group_id_in in number,
		user_id_in in number,
		set_label_in in varchar2
	) is
		cursor servers is
			select	st.element	id
			from	rhnSet		st
			where	st.user_id = user_id_in
				and st.label = set_label_in
				and exists (
					select	1
					from	rhnUserManagedServerGroups umsg
					where	umsg.server_group_id = server_group_id_in
						and umsg.user_id = user_id_in
					)
				and not exists (
					select	1
					from	rhnServerGroupMembers sgm
					where	sgm.server_id = st.element
						and sgm.server_group_id = server_group_id_in
				);
	begin
		for s in servers loop
			rhn_server.insert_into_servergroup(s.id, server_group_id_in);
		end loop;
	end insert_set_into_servergroup;
		
    procedure delete_from_servergroup (
    	server_id_in in number,
		server_group_id_in in number
    ) is
        cursor server_virt_groups is
            select 1
            from rhnServerEntitlementVirtual sev
            where sev.server_id = server_id_in
            and sev.server_group_id = server_group_id_in;

		oid number;
		mgmt_sgid number;
		label rhnServerGroupType.label%TYPE;
		group_type number;
	begin
		begin
			select	sg.group_type, sg.org_id
			into	group_type,	oid
			from	rhnServerGroupMembers	sgm,
					rhnServerGroup			sg
			where	sg.id = server_group_id_in
				and sg.id = sgm.server_group_id
				and sgm.server_id = server_id_in
			for update of sg.current_members;
		exception
			when no_data_found then
				rhn_exception.raise_exception('server_not_in_group');
		end;

		-- do group_type is null first
		if group_type is null then
			delete from rhnServerGroupMembers
				where server_group_id = server_group_id_in
				and	server_id = server_id_in;
			update rhnServerGroup
				set current_members = current_members - 1
				where id = server_group_id_in;
			rhn_cache.update_perms_for_server_group(server_group_id_in);
			return;
		end if;

		select	sgt.label
		into	label
		from	rhnServerGroupType sgt
		where	sgt.id = group_type;

		if label in ('sw_mgr_entitled',
                     'enterprise_entitled', 
                     'provisioning_entitled', 
                     'monitoring_entitled',
                     'virtualization_host',
                     'virtualization_host_platform') then

            -- Only update current members if the system is consuming
            -- a physical slot.
            for server_virt_group in server_virt_groups loop                
                delete from rhnServerGroupMembers
                where server_group_id = server_group_id_in
                and	server_id = server_id_in;
                return;
            end loop;                

            delete from rhnServerGroupMembers
            where server_group_id = server_group_id_in
            and	server_id = server_id_in;

            update rhnServerGroup
            set current_members = current_members - 1
            where id = server_group_id_in;
 
		end if;
	end;

	procedure delete_set_from_servergroup (
		server_group_id_in in number,
		user_id_in in number,
		set_label_in in varchar2
	) is
		cursor servergroups is
			select	sgm.server_id, sgm.server_group_id
			from	rhnSet st,
					rhnServerGroupMembers sgm
			where	sgm.server_group_id = server_group_id_in
				and st.user_id = user_id_in
				and st.label = set_label_in
				and sgm.server_id = st.element
				and exists (
					select	1
					from	rhnUserManagedServerGroups usgp
					where	usgp.server_group_id = server_group_id_in
						and usgp.user_id = user_id_in
				);
	begin
		for sgm in servergroups loop
			rhn_server.delete_from_servergroup(sgm.server_id, server_group_id_in);
		end loop;
	end delete_set_from_servergroup;

	procedure clear_servergroup (
		server_group_id_in in number
	) is
		cursor servers is
			select	sgm.server_id	id
			from	rhnServerGroupMembers sgm
			where	sgm.server_group_id = server_group_id_in;
	begin
		for s in servers loop
			rhn_server.delete_from_servergroup(s.id, server_group_id_in);
		end loop;
	end clear_servergroup;

	procedure delete_from_org_servergroups (
		server_id_in in number
	) is
		cursor servergroups is
			select	sgm.server_group_id id
			from	rhnServerGroup sg,
					rhnServerGroupMembers sgm
			where	sgm.server_id = server_id_in
				and sgm.server_group_id = sg.id
				and sg.group_type is null;
	begin
		for sg in servergroups loop
			rhn_server.delete_from_servergroup(server_id_in, sg.id);
		end loop;
	end delete_from_org_servergroups;

	function get_ip_address (
		server_id_in in number
	) return varchar2 is
		cursor interfaces is
			select	ni.name as name, na4.address as address
			from	rhnServerNetInterface ni,
                    rhnServerNetAddress4 na4
			where	ni.server_id = server_id_in
                and ni.id = na4.interface_id
				and na4.address != '127.0.0.1';
		cursor addresses is
			select	ipaddr ip_addr
			from	rhnServerNetwork
			where	server_id = server_id_in
				and ipaddr != '127.0.0.1';
	begin
		for addr in addresses loop
			return addr.ip_addr;
		end loop;
		for iface in interfaces loop
			return iface.address;
		end loop;
		return NULL;
	end get_ip_address;

        procedure update_needed_cache(server_id_in in number)
        is
        begin
            delete from rhnServerNeededCache
             where server_id = server_id_in;
            insert into rhnServerNeededCache
                   (server_id, errata_id, package_id)
                   (select distinct server_id, errata_id, package_id
                      from rhnServerNeededView
                     where server_id = server_id_in);
        end update_needed_cache;

end rhn_server;
/
SHOW ERRORS
 0707010000091A000081B400000000000000000000000167AE111400000018000000000000000000000000000000000000006300000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/613-rhn_set.pkb.sql    
drop package rhn_set;

0707010000091B000081B400000000000000000000000167AE111400000341000000000000000000000000000000000000006500000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/614-rhn_quota.pks.sql  --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--

create or replace package
rhn_quota
is
	function recompute_org_quota_used (
		org_id_in in number
	) return number;

	procedure update_org_quota (
		org_id_in in number
	);
end rhn_quota;
/
show errors

   0707010000091C000081B400000000000000000000000167AE1114000005DA000000000000000000000000000000000000006500000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/615-rhn_quota.pkb.sql  --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--

create or replace package body
rhn_quota
is
	function recompute_org_quota_used (
		org_id_in in number
	) return number is
		retval number := 0;
	begin
		begin
			select	NVL(sum(a.file_size),0)
			into	retval
			from	(
				select	distinct content.id, content.file_size
				from	rhnConfigContent	content,
						rhnConfigRevision	cr,
						rhnConfigFile		cf,
						rhnConfigChannel	cc
				where	cc.org_id = org_id_in
					and cc.id = cf.config_channel_id
					and cf.id = cr.config_file_id
					and cr.config_content_id = content.id
				) a;
		exception
			when others then
				null;
		end;

		return retval;
	end recompute_org_quota_used;


	procedure update_org_quota (
		org_id_in in number
	) is
	begin
		update rhnOrgQuota
			set used = rhn_quota.recompute_org_quota_used(org_id_in)
			where org_id = org_id_in;
	end update_org_quota;
end rhn_quota;
/
show errors

  0707010000091D000081B400000000000000000000000167AE11140000001F000000000000000000000000000000000000006B00000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/616-rhn_date_manip-drop.sql    
drop package rhn_date_manip;

 0707010000091E000081B400000000000000000000000167AE11140000067F000000000000000000000000000000000000006400000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/617-rhn_user.pks.sql   --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--

create or replace
package rhn_user
is
	version varchar2(100) := '';

    function check_role(user_id_in in number, role_in in varchar2) return number;
    PRAGMA RESTRICT_REFERENCES(check_role, WNDS, RNPS, WNPS);

    function check_role_implied(user_id_in in number, role_in in varchar2) return number;
    PRAGMA RESTRICT_REFERENCES(check_role_implied, WNDS, RNPS, WNPS);

    function get_org_id(user_id_in in number) return number;
    PRAGMA RESTRICT_REFERENCES(get_org_id, WNDS, RNPS, WNPS);
    
	function find_mailable_address(user_id_in in number) return varchar2;

	procedure add_servergroup_perm(
		user_id_in in number,
		server_group_id_in in number
	);

	procedure remove_servergroup_perm(
		user_id_in in number,
		server_group_id_in in number
	);

	procedure add_to_usergroup(
		user_id_in in number,
		user_group_id_in in number
	);

	procedure remove_from_usergroup(
		user_id_in in number,
		user_group_id_in in number
	);

	function role_names (user_id_in in number) return varchar2;

end rhn_user;
/
SHOW ERRORS
 0707010000091F000081B400000000000000000000000167AE111400001C21000000000000000000000000000000000000006400000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/618-rhn_user.pkb.sql   --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--

create or replace
package body rhn_user
is
	body_version varchar2(100) := '';
	
    function check_role(user_id_in in number, role_in in varchar2)
    return number
    is
    	throwaway number;
    begin
    	-- the idea: if we get past this query, the org has the setting, else catch the exception and return 0
	select 1 into throwaway
	  from rhnUserGroupType UGT,
	       rhnUserGroup UG,
	       rhnUserGroupMembers UGM
	 where UGM.user_id = user_id_in
	   and UGM.user_group_id = UG.id
	   and UG.group_type = UGT.id
	   and UGT.label = role_in;
	   
	return 1;
    exception
    	when no_data_found
	    then
	    return 0;
    end check_role;
    
    function check_role_implied(user_id_in in number, role_in in varchar2)
    return number
    is
    	throwaway number;
    begin
    	-- if the user directly has the role, they win
    	if rhn_user.check_role(user_id_in, role_in) = 1
	then
	    return 1;
    	end if;

	-- config_admin and channel_admin are automatically implied for org admins	
	if role_in = 'config_admin' and rhn_user.check_role(user_id_in, 'org_admin') = 1
	then
	    return 1;
	end if;

	if role_in = 'channel_admin' and rhn_user.check_role(user_id_in, 'org_admin') = 1
	then
	    return 1;
	end if;

	return 0;	
    end check_role_implied;
    
    function get_org_id(user_id_in in number)
    return number
    is
    	org_id_out number;
    begin
    	select org_id into org_id_out
	  from web_contact
	 where id = user_id_in;
	 
	return org_id_out;
    end get_org_id;

	-- paid users often don't have verified email addresses, so
	-- try to find an address that is useful to us.
	function find_mailable_address(user_id_in in number)
	return varchar2 is
		PRAGMA AUTONOMOUS_TRANSACTION;
		-- this would be so much prettier if we just had an order built
		-- into rhnEmailAddressState
		cursor addrs is
			select	ea.state_id, ea.address
			from	rhnEmailAddressState eas,
					rhnEmailAddress ea
			where	ea.user_id = user_id_in
				and eas.label = 'verified'
				and ea.state_id = eas.id
			union all
			select	ea.state_id, ea.address
			from	rhnEmailAddressState eas,
					rhnEmailAddress ea
			where	ea.user_id = user_id_in
				and eas.label = 'unverified'
				and ea.state_id = eas.id
			union all
			select	ea.state_id, ea.address
			from	rhnEmailAddressState eas,
					rhnEmailAddress ea
			where	ea.user_id = user_id_in
				and eas.label = 'pending'
				and ea.state_id = eas.id
			union all
			select	ea.state_id, ea.address
			from	rhnEmailAddressState eas,
					rhnEmailAddress ea
			where	ea.user_id = user_id_in
				and eas.label = 'pending_warned'
				and ea.state_id = eas.id
			union all
			select	ea.state_id, ea.address
			from	rhnEmailAddressState eas,
					rhnEmailAddress ea
			where	ea.user_id = user_id_in
				and eas.label = 'needs_verifying'
				and ea.state_id = eas.id
			union all
			select	-1 state_id,
					email address
			from	web_user_personal_info
			where	web_user_id = user_id_in;
		retval rhnEmailAddress.address%TYPE;
	begin
		for addr in addrs loop
			retval := addr.address;
			if addr.address is null then
				update web_user_contact_permission
					set email = 'N'
					where web_user_id = user_id_in;
				commit;
				return null;
			end if;
			if addr.state_id = -1 then
				insert into rhnEmailAddress (
						id, address,
						user_id, state_id
					) (
						select	rhn_eaddress_id_seq.nextval, addr.address,
								user_id_in, eas.id
						from	rhnEmailAddressState eas
						where	eas.label = 'unverified'
					);
			end if;
			commit;
			return retval;
		end loop;
		return null;
	end;

	procedure add_servergroup_perm(
		user_id_in in number,
		server_group_id_in in number
	) is
		cursor	orgs_match is
			select	1
			from	rhnServerGroup sg,
					web_contact u
			where	u.id = user_id_in
				and sg.id = server_group_id_in
				and sg.org_id = u.org_id;
	begin
		for okay in orgs_match loop
			insert into rhnUserServerGroupPerms(user_id, server_group_id)
				values (user_id_in, server_group_id_in);
			rhn_cache.update_perms_for_user(user_id_in);
			return;
		end loop;
		rhn_exception.raise_exception('usgp_different_orgs');
	exception when dup_val_on_index then
		rhn_exception.raise_exception('usgp_already_allowed');
	end add_servergroup_perm;

	procedure remove_servergroup_perm(
		user_id_in in number,
		server_group_id_in in number
	) is
		cursor perms is
			select	1
			from	rhnUserServerGroupPerms
			where	user_id = user_id_in
				and server_group_id = server_group_id_in;
	begin
		for perm in perms loop
			delete from rhnUserServerGroupPerms
				where	user_id = user_id_in
					and server_group_id = server_group_id_in;
			rhn_cache.update_perms_for_user(user_id_in);
			return;
		end loop;
		rhn_exception.raise_exception('usgp_not_allowed');
	end remove_servergroup_perm;

	procedure add_to_usergroup(
		user_id_in in number,
		user_group_id_in in number
	) is
		cursor perm_granting_usergroups is
			select	user_group_id_in
			from	rhnUserGroup		ug,
					rhnUserGroupType	ugt
			where	ugt.label in ('org_admin') -- and server_group_admin ?
				and ug.id = user_group_id_in
				and ug.group_type = ugt.id;
	begin
		insert into rhnUserGroupMembers(user_id, user_group_id)
			values (user_id_in, user_group_id_in);

		for ug in perm_granting_usergroups loop
			rhn_cache.update_perms_for_user(user_id_in);
			return;
		end loop;
	end add_to_usergroup;

	procedure remove_from_usergroup(
		user_id_in in number,
		user_group_id_in in number
	) is
		cursor perm_granting_usergroups is
			select	label
			from	rhnUserGroupType	ugt,
					rhnUserGroupMembers	ugm,
					rhnUserGroup		ug
			where	1=1
				and ug.id = user_group_id_in
				and ugm.user_group_id = user_group_id_in
				and ug.group_type = ugt.id
				and ugm.user_id = user_id_in;
	begin
		-- we only do anything if you're really in the group, because
		-- testing is significantly cheaper than rebuilding the user's
		-- cache for no reason.
		for ug in perm_granting_usergroups loop
			delete from rhnUserGroupMembers
				where	user_id = user_id_in
					and user_group_id = user_group_id_in;
			if ug.label in ('org_admin') then
				rhn_cache.update_perms_for_user(user_id_in);
			end if;
		end loop;
	end remove_from_usergroup;

	function role_names (user_id_in in number)
	return varchar2
	is
		tmp varchar2(4000);
	begin
		for rec in (
			select type_name
			from rhnUserTypeBase
			where user_id = user_id_in
			order by type_id
			) loop
			if tmp is null then
				tmp := rec.type_name;
			else
				tmp := tmp || ', ' || rec.type_name;
			end if;
		end loop;
		return tmp;
	end;

end rhn_user;
/
SHOW ERRORS
   07070100000920000081B400000000000000000000000167AE11140000056F000000000000000000000000000000000000006D00000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/619-rhnUsersInOrgOverview.sql  --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
drop view rhnUsersInOrgOverview;
create view rhnUsersInOrgOverview as
select    
	u.org_id					as org_id,
	u.id						as user_id,
	u.login						as user_login,
	pi.first_names					as user_first_name,
	pi.last_name					as user_last_name,
	u.modified					as user_modified,
    	(	select	count(server_id)
		from	rhnUserServerPerms sp
		where	sp.user_id = u.id)
							as server_count,
	(	select	count(server_group_id)
		from	rhnUserManagedServerGroups umsg
		where	umsg.user_id = u.id and exists (
			select	1
			from	rhnVisibleServerGroup sg
			where	sg.id = umsg.server_group_id))
							as server_group_count,
	coalesce(rhn_user.role_names(u.id), '(normal user)') as role_names
from	web_user_personal_info pi, 
	web_contact u 
where
	u.id = pi.web_user_id;

 07070100000921000081B400000000000000000000000167AE111400000022000000000000000000000000000000000000007100000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/620-rhnUserTypeCommaView-drop.sql  
drop view rhnUserTypeCommaView;

  07070100000922000081B400000000000000000000000167AE11140000004C000000000000000000000000000000000000007900000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/621-id_join-name_join-label_join-drop.sql  
drop function id_join;
drop function name_join;
drop function label_join;

07070100000923000081B400000000000000000000000167AE11140000001E000000000000000000000000000000000000006D00000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/622-rhnUserTypeArray-drop.sql  
drop view rhnUserTypeArray;

  07070100000924000081B400000000000000000000000167AE111400000058000000000000000000000000000000000000009100000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/623-user_group_id_t-user_group_label_t-user_group_name_t-drop.sql  
drop type user_group_id_t;
drop type user_group_label_t;
drop type user_group_name_t;

07070100000925000081B400000000000000000000000167AE11140000100F000000000000000000000000000000000000007100000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/624-time-series-revamp-tables.sql  --
-- Copyright (c) 2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

create table time_series_purge
(
    id        number not null
                  constraint time_series_purge_pk primary key,
    probe_id  number
                  constraint time_series_purge_pid_fk
                  references rhn_probe(recid),
    deleted   number,
    created   date default (sysdate) not null,
    modified  date default (sysdate) not null
)
enable row movement;

alter table time_series_purge
        add constraint time_series_purge
      check (id = probe_id);

create index time_series_purge_id_del_idx
          on time_series_purge(id, deleted);

create or replace trigger time_series_purge_mod_trig
before insert or update on time_series_purge
for each row
begin
    :new.modified := sysdate;
end;
/

-- populate time_series_purge with values from rhn_probe
insert into time_series_purge (id, probe_id, deleted) (select rp.recid, rp.recid, 0 from rhn_probe rp);
commit;

create table time_series_data
(
    org_id      number not null,
    probe_id    number not null
                    constraint time_series_data_pid_fk references
                    time_series_purge(id),
    probe_desc  varchar2(64),
    entry_time  number not null,
    data        varchar2(1024)
)
enable row movement;

create index time_series_data_pid_time_idx on time_series_data(probe_id, entry_time)
  tablespace [[64k_tbs]]
  nologging;

-- triggers
create or replace trigger rhn_probe_insert_trigger after insert on rhn_probe
for each row
begin
    insert into time_series_purge (id, probe_id, deleted) values (:new.recid, :new.recid, 0);
end;
/

create or replace trigger rhn_probe_delete_trigger before delete on rhn_probe
for each row
begin
    update time_series_purge
       set probe_id = null
     where id = :old.recid;

    update time_series_purge
       set deleted = 1
     where id = :old.recid;
end;
/

-- migration from time_series to time_series_data
declare
    cur_rec_id number;
    pre_rec_id number;
    max_rec_id number;
begin
    select max(recid) into max_rec_id
      from rhn_probe;

	if max_rec_id is null then
		return;
    end if;

    pre_rec_id := 0;

    loop
        select min(recid) into cur_rec_id
          from rhn_probe
         where recid > pre_rec_id;

        insert /*+ append */ into time_series_data (org_id, probe_id, probe_desc, entry_time, data) (
            select t_ts.*
              from (select substr(ts.o_id, 1, instr(ts.o_id, '-', 1, 1) - 1),
                           substr(ts.o_id,
                                  instr(ts.o_id, '-') + 1,
                                  (instr(ts.o_id,
                                         '-',
                                         instr(ts.o_id, '-') + 1) -
                                   instr(ts.o_id, '-')) - 1
                                 ) as probe_id,
                           substr(ts.o_id, instr(ts.o_id, '-', 1, 2) + 1),
                           ts.entry_time,
                           ts.data
                      from time_series ts
                   ) t_ts
             where t_ts.probe_id = to_char(cur_rec_id)
        );
        commit;

        exit when cur_rec_id = max_rec_id;

        pre_rec_id := cur_rec_id;
    end loop;
end;
/

-- drop old time_series
drop table time_series;

-- compatibility view
create or replace view time_series as (
    select tsd.org_id || '-' || tsd.probe_id || '-' || tsd.probe_desc as o_id,
           tsd.entry_time as entry_time,
           tsd.data as data
      from time_series_data tsd
    );
 07070100000926000081B400000000000000000000000167AE111400012E01000000000000000000000000000000000000007000000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/625-time-series-revamp-plsql.sql   --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--
--
--
--

create or replace
package body rhn_entitlements
is
    body_version varchar2(100) := '';

   function find_compatible_sg (
      server_id_in    in   number,
      type_label_in   in   varchar2
   ) return number is

      cursor servergroups is
         select sg.id            id
           from rhnServerGroupType             sgt,
                rhnServerGroup                 sg,
                rhnServer                     s,
                rhnServerServerGroupArchCompat ssgac
          where s.id = server_id_in
            and s.org_id = sg.org_id
            and sgt.label = type_label_in
            and sg.group_type = sgt.id
            and ssgac.server_group_type = sgt.id
            and ssgac.server_arch_id = s.server_arch_id
            and not exists (
                     select 1
                      from rhnServerGroupMembers sgm
                     where sgm.server_group_id = sg.id
                       and sgm.server_id = s.id);


   begin
      for servergroup in servergroups loop
         return servergroup.id;
      end loop;

      --no servergroup found
      return null;
   end find_compatible_sg;


    -- *******************************************************************
    -- PROCEDURE: remove_org_entitlements
    --
    -- Removes both system entitlements and channel subscriptions
    -- that are currently assigned to an org and re-assigns to the
    -- master org (org_id = 1).
    --
    -- When we call this we expect everything to already be unentitled
    -- which shoul be handled by delete_org.
    --
    -- Called by: delete_org
    -- *******************************************************************
    procedure remove_org_entitlements(
        org_id_in in number
    )
    is

        cursor system_ents is
        select sg.id, sg.max_members, sg.group_type
        from rhnServerGroup sg
        where group_type is not null
          and org_id = org_id_in;

        cursor channel_subs is
        select pcf.channel_family_id, pcf.max_members
        from rhnChannelFamily cf,
             rhnPrivateChannelFamily pcf
        where pcf.org_id = org_id_in
          and pcf.channel_family_id = cf.id
          and cf.org_id is null;

    begin

        for system_ent in system_ents loop
            update rhnServerGroup
            set max_members = max_members + system_ent.max_members
            where org_id = 1
              and group_type = system_ent.group_type;
        end loop;

        update rhnServerGroup
        set max_members = 0
        where org_id = org_id_in;

        for channel_sub in channel_subs loop
            update rhnPrivateChannelFamily
            set max_members = max_members + channel_sub.max_members
            where org_id = 1
              and channel_family_id = channel_sub.channel_family_id;
        end loop;

        update rhnPrivateChannelFamily
        set max_members = 0
        where org_id = org_id_in;

    end remove_org_entitlements;

    function entitlement_grants_service (
        entitlement_in in varchar2,
        service_level_in in varchar2
    ) return number    is
    begin
        if service_level_in = 'provisioning' then
            if entitlement_in = 'provisioning_entitled' then
                return 1;
            else
                return 0;
            end if;
        elsif service_level_in = 'management' then
            if entitlement_in = 'enterprise_entitled' then
                return 1;
            else
                return 0;
            end if;
        elsif service_level_in = 'monitoring' then
            if entitlement_in = 'monitoring_entitled' then
                return 1;
            end if;
        elsif service_level_in = 'updates' then
            return 1;
        else
            return 0;
        end if;
    end entitlement_grants_service;

    function lookup_entitlement_group (
        org_id_in in number,
        type_label_in in varchar2 := 'sw_mgr_entitled'
    ) return number is
        cursor server_groups is
            select    sg.id                server_group_id
            from    rhnServerGroup        sg,
                    rhnServerGroupType    sgt
            where    sgt.label = type_label_in
                and sgt.id = sg.group_type
                and sg.org_id = org_id_in;
    begin
        for sg in server_groups loop
            return sg.server_group_id;
        end loop;
        return rhn_entitlements.create_entitlement_group(
                org_id_in,
                type_label_in
            );
    end lookup_entitlement_group;

    function create_entitlement_group (
        org_id_in in number,
        type_label_in in varchar2 := 'sw_mgr_entitled'
    ) return number is
        sg_id_val number;
    begin
        select    rhn_server_group_id_seq.nextval
        into    sg_id_val
        from    dual;

        insert into rhnServerGroup (
                id, name, description, max_members, current_members,
                group_type, org_id
            ) (
                select    sg_id_val, sgt.label, sgt.label,
                        0, 0, sgt.id, org_id_in
                from    rhnServerGroupType sgt
                where    sgt.label = type_label_in
            );

        return sg_id_val;
    end create_entitlement_group;

   function can_entitle_server (
        server_id_in in number,
        type_label_in in varchar2 )
   return number is
      cursor addon_servergroups (base_label_in in varchar2,
                                 addon_label_in in varchar2) is
         select
            addon_id
         from
            rhnSGTypeBaseAddonCompat
         where base_id = lookup_sg_type (base_label_in)
           and addon_id = lookup_sg_type (addon_label_in);

      previous_ent        rhn_entitlements.ents_array;
      is_base_in          char   := 'N';
      is_base_current     char   := 'N';
      i                   number := 0;
      sgid                number := 0;

   begin

      previous_ent := rhn_entitlements.ents_array();
      previous_ent := rhn_entitlements.get_server_entitlement(server_id_in);

      select distinct is_base
      into is_base_in
      from rhnServerGroupType
      where label = type_label_in;

      if previous_ent.count = 0 then
         sgid := find_compatible_sg (server_id_in, type_label_in);
         if (is_base_in = 'Y' and sgid is not null) then
            -- rhn_server.insert_into_servergroup (server_id_in, sgid);
            return 1;
         else
            -- rhn_exception.raise_exception ('invalid_base_entitlement');
            return 0;
         end if;

      -- there are previous ents, first make sure we're not trying to entitle a base ent
      elsif is_base_in = 'Y' then
         -- rhn_exception.raise_exception ('invalid_addon_entitlement');
         return 0;

      -- it must be an addon, so proceed with the entitlement
      else

         -- find the servers base ent
         is_base_current := 'N';
         i := 0;
         while is_base_current = 'N' and i <= previous_ent.count
         loop
            i := i + 1;
            select is_base
            into is_base_current
            from rhnServerGroupType
            where label = previous_ent(i);
         end loop;

         -- never found a base ent, that would be strange
         if is_base_current  = 'N' then
            -- rhn_exception.raise_exception ('invalid_base_entitlement');
            return 0;
         end if;

         -- this for loop verifies the validity of the addon path
         for addon_servergroup in addon_servergroups  (previous_ent(i), type_label_in) loop
            -- find an appropriate sgid for the addon and entitle the server
            sgid := find_compatible_sg (server_id_in, type_label_in);
            if sgid is not null then
               -- rhn_server.insert_into_servergroup (server_id_in, sgid);
               return 1;
            else
               -- rhn_exception.raise_exception ('invalid_addon_entitlement');
               return 0;
            end if;
         end loop;

      end if;

      return 0;

   end can_entitle_server;

   function can_switch_base (
      server_id_in   in    integer,
      type_label_in  in    varchar2
   ) return number is

      type_label_in_is_base   char(1);
      sgid                    number;

   begin

      begin
         select is_base into type_label_in_is_base
         from rhnServerGroupType
         where label = type_label_in;
      exception
         when no_data_found then
            rhn_exception.raise_exception ( 'invalid_entitlement' );
      end;

      if type_label_in_is_base = 'N' then
         rhn_exception.raise_exception ( 'invalid_entitlement' );
      else
         sgid := find_compatible_sg ( server_id_in, type_label_in );
         if sgid is not null then
            return 1;
         else
            return 0;
         end if;
      end if;

   end can_switch_base;


    procedure entitle_server (
        server_id_in in number,
        type_label_in in varchar2 := 'sw_mgr_entitled'
    ) is
      sgid  number := 0;
      is_virt number := 0;

    begin

          begin
          select 1 into is_virt
            from rhnServerEntitlementView
           where server_id = server_id_in
             and label in ('virtualization_host', 'virtualization_host_platform');
      exception
            when no_data_found then
              is_virt := 0;
          end;

      if is_virt = 0 and (type_label_in = 'virtualization_host' or
                          type_label_in = 'virtualization_host_platform') then

        is_virt := 1;
      end if;



      if rhn_entitlements.can_entitle_server(server_id_in,
                                             type_label_in) = 1 then
         sgid := find_compatible_sg (server_id_in, type_label_in);
         if sgid is not null then
            insert into rhnServerHistory ( id, server_id, summary, details )
            values ( rhn_event_id_seq.nextval, server_id_in,
                     'added system entitlement ',
                      case type_label_in
                       when 'enterprise_entitled' then 'Management'
                       when 'sw_mgr_entitled' then 'Update'
                       when 'provisioning_entitled' then 'Provisioning'
                       when 'monitoring_entitled' then 'Monitoring'
                       when 'virtualization_host' then 'Virtualization'
                       when 'virtualization_host_platform' then
                            'Virtualization Platform' end  );

            rhn_server.insert_into_servergroup (server_id_in, sgid);

            if is_virt = 1 then
              rhn_entitlements.repoll_virt_guest_entitlements(server_id_in);
            end if;

         else
            rhn_exception.raise_exception ('no_available_server_group');
         end if;
      else
         rhn_exception.raise_exception ('invalid_entitlement');
      end if;
   end entitle_server;

    procedure remove_server_entitlement (
        server_id_in in number,
        type_label_in in varchar2 := 'sw_mgr_entitled',
        repoll_virt_guests in number := 1
    ) is
        group_id number;
      type_is_base char;
      is_virt number := 0;
    begin
      begin


      -- would be nice if there were a virt attribute of entitlement types, not have to specify 2 different ones...
        begin
          select 1 into is_virt
            from rhnServerEntitlementView
           where server_id = server_id_in
             and label in ('virtualization_host', 'virtualization_host_platform');
        exception
          when no_data_found then
            is_virt := 0;
        end;

        select    sg.id, sgt.is_base
          into    group_id, type_is_base
          from    rhnServerGroupType sgt,
               rhnServerGroup sg,
                  rhnServerGroupMembers sgm,
                  rhnServer s
          where    s.id = server_id_in
              and s.id = sgm.server_id
              and sgm.server_group_id = sg.id
              and sg.org_id = s.org_id
              and sgt.label = type_label_in
              and sgt.id = sg.group_type;

      if ( type_is_base = 'Y' ) then
         -- unentitle_server should handle everything, don't really need to do anything else special here
         unentitle_server ( server_id_in );
      else

         insert into rhnServerHistory ( id, server_id, summary, details )
         values ( rhn_event_id_seq.nextval, server_id_in,
                  'removed system entitlement ',
                   case type_label_in
                    when 'enterprise_entitled' then 'Management'
                    when 'sw_mgr_entitled' then 'Update'
                    when 'provisioning_entitled' then 'Provisioning'
                    when 'monitoring_entitled' then 'Monitoring'
                    when 'virtualization_host' then 'Virtualization'
                    when 'virtualization_host_platform' then
                         'Virtualization Platforrm' end  );

         rhn_server.delete_from_servergroup(server_id_in, group_id);

         if type_label_in = 'monitoring_entitled' then
           DELETE
             FROM rhn_probe
            WHERE recid IN (SELECT probe_id
                              FROM rhn_check_probe
                             WHERE host_id = server_id_in);
         end if;

         if is_virt = 1 and repoll_virt_guests = 1 then
           rhn_entitlements.repoll_virt_guest_entitlements(server_id_in);
         end if;
      end if;

          exception
          when no_data_found then
                  rhn_exception.raise_exception('invalid_server_group_member');
      end;

     end remove_server_entitlement;


   procedure unentitle_server (server_id_in in number) is

      cursor servergroups is
         select distinct sgt.label, sg.id server_group_id
         from  rhnServerGroupType sgt,
               rhnServerGroup sg,
               rhnServer s,
               rhnServerGroupMembers sgm
         where s.id = server_id_in
            and s.org_id = sg.org_id
            and sg.group_type = sgt.id
            and sgm.server_group_id = sg.id
            and sgm.server_id = s.id;

     is_virt number := 0;

   begin

      begin
        select 1 into is_virt
          from rhnServerEntitlementView
         where server_id = server_id_in
           and label in ('virtualization_host', 'virtualization_host_platform');
      exception
        when no_data_found then
          is_virt := 0;
      end;

      for servergroup in servergroups loop

         insert into rhnServerHistory ( id, server_id, summary, details )
         values ( rhn_event_id_seq.nextval, server_id_in,
                  'removed system entitlement ',
                   case servergroup.label
                    when 'enterprise_entitled' then 'Management'
                    when 'sw_mgr_entitled' then 'Update'
                    when 'provisioning_entitled' then 'Provisioning'
                    when 'monitoring_entitled' then 'Monitoring'
                    when 'virtualization_host' then 'Virtualization'
                    when 'virtualization_host_platform' then
                         'Virtualization Platform' end  );

         rhn_server.delete_from_servergroup(server_id_in,
                                            servergroup.server_group_id );
      end loop;

      if is_virt = 1 then
        rhn_entitlements.repoll_virt_guest_entitlements(server_id_in);
      end if;

   end unentitle_server;


    -- *******************************************************************
    -- PROCEDURE: repoll_virt_guest_entitlements
    --
    --   Whenever we add/remove a virtualization_host* entitlement from
    --   a host, we can call this procedure to update what type of slots
    --   the guests are consuming.
    --
    --   If you're removing the entitlement, it's
    --   possible the guests will become unentitled if you don't have enough
    --   physical slots to cover them.
    --
    --   If you're adding the entitlement, you end up freeing up physical
    --   slots for other systems.
    --
    -- *******************************************************************
    procedure repoll_virt_guest_entitlements(server_id_in in number)
    is

        -- All channel families associated with the guests of server_id_in
        cursor families is
            select distinct cfs.channel_family_id
            from
                rhnChannelFamilyServers cfs,
                rhnVirtualInstance vi
            where
                vi.host_system_id = server_id_in
                and vi.virtual_system_id = cfs.server_id;

        -- All of server group types associated with the guests of
        -- server_id_in
        cursor group_types is
            select distinct sg.group_type, sgt.label
            from
                rhnServerGroupType sgt,
                rhnServerGroup sg,
                rhnServerGroupMembers sgm,
                rhnVirtualInstance vi
            where
                vi.host_system_id = server_id_in
                and vi.virtual_system_id = sgm.server_id
                and sgm.server_group_id = sg.id
                and sg.group_type = sgt.id;

        -- Virtual servers from a certain family belonging to a speicifc
        -- host that are consuming physical channel slots over the limit.
        cursor virt_servers_cfam(family_id_in in number, quantity_in in number)  is
            select virtual_system_id
            from (
                select rownum, vi.virtual_system_id
                from
                    rhnChannelFamilyMembers cfm,
                    rhnServerChannel sc,
                    rhnVirtualInstance vi
                where
                    vi.host_system_id = server_id_in
                    and vi.virtual_system_id = sc.server_id
                    and sc.channel_id = cfm.channel_id
                    and cfm.channel_family_id = family_id_in
                order by sc.modified desc
                )
            where rownum <= quantity_in;

        -- Virtual servers from a certain family belonging to a speicifc
        -- host that are consuming physical system slots over the limit.
        cursor virt_servers_sgt(group_type_in in number, quantity_in in number)  is
            select virtual_system_id
            from (
                select rownum, vi.virtual_system_id
                from
                    rhnServerGroup sg,
                    rhnServerGroupMembers sgm,
                    rhnVirtualInstance vi
                where
                    vi.host_system_id = server_id_in
                    and vi.virtual_system_id = sgm.server_id
                    and sgm.server_group_id = sg.id
                    and sg.group_type = group_type_in
                order by sgm.modified desc
                )
            where rownum <= quantity_in;
        -- Get the orgs of Virtual guests
        -- Since they may belong to different orgs
        cursor virt_guest_orgs  is
                select  distinct (s.org_id)
                from rhnServer s
                    inner join  rhnVirtualInstance vi on vi.virtual_system_id = s.id
                where
                    vi.host_system_id = server_id_in
                    and s.org_id <> (select s1.org_id from rhnServer s1 where s1.id = vi.host_system_id) ;


        org_id_val number;
        max_members_val number;
        max_flex_val number;
        current_members_calc number;
        sg_id number;
        is_virt number := 0;
    begin
        begin
          select 1 into is_virt
                from rhnServerEntitlementView
           where server_id = server_id_in
                 and label in ('virtualization_host', 'virtualization_host_platform');
           exception
                when no_data_found then
                  is_virt := 0;
        end;

        select org_id
        into org_id_val
        from rhnServer
        where id = server_id_in;

        -- deal w/ channel entitlements first ...
        for family in families loop
            if is_virt = 0 then
            -- if the host_server does not have virt
            --- find all possible flex slots
            -- and set each of the flex eligible guests to Y
                UPDATE rhnServerChannel sc set sc.is_fve = 'Y'
                where sc.server_id in (
                       select virtual_system_id from (
                            select rownum, vi.virtual_system_id,  sfc.max_members - sfc.current_members as free_slots
                            from rhnServerFveCapable sfc
                                inner join rhnVirtualInstance vi on vi.virtual_system_id = sfc.server_id
                            where vi.host_system_id = server_id_in
                                  and sfc.channel_family_id = family.channel_family_id
                              order by vi.modified desc
                          )
                        where rownum <=  free_slots
                );
            else
            -- if the host_server has virt
            -- set all its flex guests to N
                UPDATE rhnServerChannel sc set sc.is_fve = 'N'
                where
                    sc.channel_id in (select cfm.channel_id from rhnChannelFamilyMembers cfm
                                      where cfm.CHANNEL_FAMILY_ID = family.channel_family_id)
                    and sc.is_fve = 'Y'
                    and sc.server_id in
                            (select vi.virtual_system_id  from rhnVirtualInstance vi
                                    where vi.host_system_id = server_id_in);
            end if;

            -- get the current (physical) members of the family
            current_members_calc :=
                rhn_channel.channel_family_current_members(family.channel_family_id,
                                                           org_id_val); -- fixed transposed args

            begin

            -- get the max members of the family
            select max_members
            into max_members_val
            from rhnPrivateChannelFamily
            where channel_family_id = family.channel_family_id
            and org_id = org_id_val;

            select fve_max_members
            into max_flex_val
            from rhnPrivateChannelFamily
            where channel_family_id = family.channel_family_id
            and org_id = org_id_val;

            if current_members_calc > max_members_val then
                -- A virtualization_host* ent must have been removed, so we'll
                -- unsubscribe guests from the host first.

                -- hm, i don't think max_members - current_members_calc yielding a negative number
                -- will work w/ rownum, swaping 'em in the body of this if...
                for virt_server in virt_servers_cfam(family.channel_family_id,
                                current_members_calc - max_members_val) loop

                    rhn_channel.unsubscribe_server_from_family(
                                virt_server.virtual_system_id,
                                family.channel_family_id);
                end loop;

                -- if we're still over the limit, which would be odd,
                -- just prune the group to max_members
                --
                -- er... wouldn't we actually have to refresh the values of
                -- current_members_calc and max_members_val to actually ever
                -- *skip this??
                if current_members_calc > max_members_val then
                    -- argh, transposed again?!
                    set_family_count(org_id_val,
                                     family.channel_family_id,
                                     max_members_val, max_flex_val);
                    --TODO calculate this correctly
                end if;

           end if;

            -- update current_members for the family.  This will set the value
            -- to reflect adding/removing the entitlement.
            --
            -- what's the difference of doing this vs the unavoidable set_family_count above?
            rhn_channel.update_family_counts(family.channel_family_id,
                                             org_id_val);

            exception when no_data_found then null;
            end;

            -- It is possible that the guests belong  to a different org than the host
            -- so we are going to update the family counts in the guests orgs also
            for org in virt_guest_orgs loop
                    rhn_channel.update_family_counts(family.channel_family_id,
                                             org.org_id);
            end loop;
        end loop;

        for a_group_type in group_types loop
          -- get the current *physical* members of the system entitlement type for the org...
          --
          -- unlike channel families, it appears the standard rhnServerGroup.max_members represents
          -- *physical* slots, vs physical+virt ... boy that's confusing...

          select max_members, id
            into max_members_val, sg_id
            from rhnServerGroup
            where group_type = a_group_type.group_type
            and org_id = org_id_val;


      select count(sep.server_id) into current_members_calc
            from rhnServerEntitlementPhysical sep
           where sep.server_group_id = sg_id
             and sep.server_group_type_id = a_group_type.group_type;

          if current_members_calc > max_members_val then
            -- A virtualization_host* ent must have been removed, and we're over the limit, so unsubscribe guests
            for virt_server in virt_servers_sgt(a_group_type.group_type,
                                                current_members_calc - max_members_val) loop
              rhn_entitlements.remove_server_entitlement(virt_server.virtual_system_id, a_group_type.label);

              -- decrement current_members_calc, we'll use it to reset current_members for the group at the end...
              current_members_calc := current_members_calc - 1;
            end loop;

          end if;

          update rhnServerGroup set current_members = current_members_calc
           where org_id = org_id_val
             and group_type = a_group_type.group_type;

          -- I think that's all the house-keeping we have to do...
        end loop;

    end repoll_virt_guest_entitlements;


    function get_server_entitlement (
        server_id_in in number
    ) return ents_array is

        cursor server_groups is
            select    sgt.label
            from    rhnServerGroupType        sgt,
                    rhnServerGroup            sg,
                    rhnServerGroupMembers    sgm
            where    1=1
                and sgm.server_id = server_id_in
                and sg.id = sgm.server_group_id
                and sgt.id = sg.group_type
                and sgt.label in (
                    'sw_mgr_entitled','enterprise_entitled',
                    'provisioning_entitled', 'nonlinux_entitled',
                    'monitoring_entitled', 'virtualization_host',
                                        'virtualization_host_platform'
                    );

         ent_array ents_array;

    begin

      ent_array := ents_array();

        for sg in server_groups loop
         ent_array.extend;
         ent_array(ent_array.count) := sg.label;
        end loop;

        return ent_array;

    end get_server_entitlement;


    -- this desperately needs to be table driven.
    procedure modify_org_service (
        org_id_in in number,
        service_label_in in varchar2,
        enable_in in char
    ) is
        type roles_v is varray(10) of rhnUserGroupType.label%TYPE;
        roles_to_process roles_v;
        cursor roles(role_label_in in varchar2) is
            select    label, id
            from    rhnUserGroupType
            where    label = role_label_in;
        cursor org_roles(role_label_in in varchar2) is
            select    1
            from    rhnUserGroup ug,
                    rhnUserGroupType ugt
            where    ugt.label = role_label_in
                and ug.org_id = org_id_in
                and ugt.id = ug.group_type;

        type ents_v is varray(10) of rhnOrgEntitlementType.label%TYPE;
        ents_to_process ents_v;
        cursor ents(ent_label_in in varchar2) is
            select    label, id
            from    rhnOrgEntitlementType
            where    label = ent_label_in;
        cursor org_ents(ent_label_in in varchar2) is
            select    1
            from    rhnOrgEntitlements oe,
                    rhnOrgEntitlementType oet
            where    oet.label = ent_label_in
                and oe.org_id = org_id_in
                and oet.id = oe.entitlement_id;
        create_row char(1);
    begin
        ents_to_process := ents_v();
        roles_to_process := roles_v();
        -- a bit kludgy, but only for 3.4 really.  Certainly no
        -- worse than the old code...
        if service_label_in = 'enterprise' or
           service_label_in = 'management' then
            ents_to_process.extend;
            ents_to_process(ents_to_process.count) := 'sw_mgr_enterprise';

            roles_to_process.extend;
            roles_to_process(roles_to_process.count) := 'org_admin';

            roles_to_process.extend;
            roles_to_process(roles_to_process.count) := 'system_group_admin';

            roles_to_process.extend;
            roles_to_process(roles_to_process.count) := 'activation_key_admin';

            roles_to_process.extend;
            roles_to_process(roles_to_process.count) := 'org_applicant';
        elsif service_label_in = 'provisioning' then
            ents_to_process.extend;
            ents_to_process(ents_to_process.count) := 'rhn_provisioning';

            roles_to_process.extend;
            roles_to_process(roles_to_process.count) := 'system_group_admin';

            roles_to_process.extend;
            roles_to_process(roles_to_process.count) := 'activation_key_admin';

            roles_to_process.extend;
            roles_to_process(roles_to_process.count) := 'config_admin';
            -- another nasty special case...
            if enable_in = 'Y' then
                ents_to_process.extend;
                ents_to_process(ents_to_process.count) := 'sw_mgr_enterprise';
            end if;
        elsif service_label_in = 'monitoring' then
            ents_to_process.extend;
            ents_to_process(ents_to_process.count) := 'rhn_monitor';

            roles_to_process.extend;
            roles_to_process(roles_to_process.count) := 'monitoring_admin';
        elsif service_label_in = 'virtualization' then
            ents_to_process.extend;
            ents_to_process(ents_to_process.count) := 'rhn_virtualization';

            roles_to_process.extend;
            roles_to_process(roles_to_process.count) := 'config_admin';
        elsif service_label_in = 'virtualization_platform' then
            ents_to_process.extend;
            ents_to_process(ents_to_process.count) := 'rhn_virtualization_platform';
            roles_to_process.extend;
            roles_to_process(roles_to_process.count) := 'config_admin';
    elsif service_label_in = 'nonlinux' then
            ents_to_process.extend;
            ents_to_process(ents_to_process.count) := 'rhn_nonlinux';
            roles_to_process.extend;
            roles_to_process(roles_to_process.count) := 'config_admin';
        end if;

        if enable_in = 'Y' then
            for i in 1..ents_to_process.count loop
                for ent in ents(ents_to_process(i)) loop
                    create_row := 'Y';
                    for oe in org_ents(ent.label) loop
                        create_row := 'N';
                    end loop;
                    if create_row = 'Y' then
                        insert into rhnOrgEntitlements(org_id, entitlement_id)
                            values (org_id_in, ent.id);
                    end if;
                end loop;
            end loop;
            for i in 1..roles_to_process.count loop
                for role in roles(roles_to_process(i)) loop
                    create_row := 'Y';
                    for o_r in org_roles(role.label) loop
                        create_row := 'N';
                    end loop;
                    if create_row = 'Y' then
                        insert into rhnUserGroup(
                                id, name, description, current_members,
                                group_type, org_id
                            ) (
                                select    rhn_user_group_id_seq.nextval,
                                        ugt.name || 's',
                                        ugt.name || 's for Org ' ||
                                            o.name || ' ('|| o.id ||')',
                                        0, ugt.id, o.id
                                from    rhnUserGroupType ugt,
                                        web_customer o
                                where    o.id = org_id_in
                                    and ugt.id = role.id
                            );
                    end if;
                end loop;
            end loop;
        else
            for i in 1..ents_to_process.count loop
                for ent in ents(ents_to_process(i)) loop
                    delete from rhnOrgEntitlements
                     where org_id = org_id_in
                       and entitlement_id = ent.id;
                end loop;
            end loop;
        end if;
    end modify_org_service;

    procedure set_customer_enterprise (
        customer_id_in in number
    ) is
    begin
        modify_org_service(customer_id_in, 'enterprise', 'Y');
    end set_customer_enterprise;

    procedure set_customer_provisioning (
        customer_id_in in number
    ) is
    begin
        modify_org_service(customer_id_in, 'provisioning', 'Y');
    end set_customer_provisioning;

    procedure set_customer_monitoring (
        customer_id_in in number
    ) is
    begin
        modify_org_service(customer_id_in, 'monitoring', 'Y');
    end set_customer_monitoring;

    procedure set_customer_nonlinux (
        customer_id_in in number
    ) is
    begin
        modify_org_service(customer_id_in, 'nonlinux', 'Y');
    end set_customer_nonlinux;

    procedure unset_customer_enterprise (
        customer_id_in in number
    ) is
    begin
        modify_org_service(customer_id_in, 'enterprise', 'N');
    end unset_customer_enterprise;

    procedure unset_customer_provisioning (
        customer_id_in in number
    ) is
    begin
        modify_org_service(customer_id_in, 'provisioning', 'N');
    end unset_customer_provisioning;

    procedure unset_customer_monitoring (
        customer_id_in in number
    ) is
    begin
        modify_org_service(customer_id_in, 'monitoring', 'N');
    end unset_customer_monitoring;

    procedure unset_customer_nonlinux (
        customer_id_in in number
    ) is
    begin
        modify_org_service(customer_id_in, 'nonlinux', 'N');
    end unset_customer_nonlinux;

    -- *******************************************************************
    -- PROCEDURE: prune_group
    -- Unsubscribes servers consuming physical slots that over the org's
    --   limit.
    -- Called by: set_server_group_count, repoll_virt_guest_entitlements
    -- *******************************************************************
    procedure prune_group (
        group_id_in in number,
        quantity_in in number,
                update_family_countsYN in number := 1
    ) is
        cursor servergroups is
           select  server_id, server_group_id, sgt.id as group_type_id, sgt.label
            from    rhnServerGroupType              sgt,
                            rhnServerGroup                  sg,
                            rhnServerGroupMembers   sgm
            where   1=1
                    and sgm.server_group_id = group_id_in
                    and sgm.server_id in (
                            select  server_id
                            from    (
                                    select  rownum row_number,
                                                    server_id,
                                                    time
                                    from    (
                                            select  sep.server_id,
                                                    sep.modified time
                                            from
                                                rhnServerEntitlementPhysical sep
                                            where
                                                sep.server_group_id = group_id_in
                                            order by time asc
                                    )
                            )
                            where   row_number > quantity_in
                    )
                    and sgm.server_group_id = sg.id
                    and sg.group_type = sgt.id;
      type_is_base char;
    begin
        update        rhnServerGroup
            set        max_members = quantity_in
            where    id = group_id_in;

        for sg in servergroups loop
            remove_server_entitlement(sg.server_id, sg.label);

            select is_base
            into type_is_base
            from rhnServerGroupType sgt
            where sgt.id = sg.group_type_id;

            -- if we're removing a base ent, then be sure to
            -- remove the server's channel subscriptions.
            if ( type_is_base = 'Y' ) then
                   rhn_channel.clear_subscriptions(sg.server_id,
                                        update_family_countsYN => update_family_countsYN);
            end if;

        end loop;
    end prune_group;

    procedure set_server_group_count (
        customer_id_in in number,
        group_type_in in number,
        quantity_in in number,
                update_family_countsYN in number := 1
    ) is
        group_id number;
        quantity number;
    begin
        quantity := quantity_in;
        if quantity is not null and quantity < 0 then
            quantity := 0;
        end if;

        select    rsg.id
        into    group_id
        from    rhnServerGroup rsg
        where    1=1
            and rsg.org_id = customer_id_in
            and rsg.group_type = group_type_in;

        rhn_entitlements.prune_group(
            group_id,
            quantity,
                        update_family_countsYN
        );
    exception
        when no_data_found then
            insert into rhnServerGroup (
                    id, name, description, max_members, current_members,
                    group_type, org_id, created, modified
                ) (
                    select    rhn_server_group_id_seq.nextval, name, name,
                            quantity, 0, id, customer_id_in,
                            sysdate, sysdate
                    from    rhnServerGroupType
                    where    id = group_type_in
            );
    end set_server_group_count;

    -- *******************************************************************
    -- PROCEDURE: assign_system_entitlement
    --
    -- Moves system entitlements from from_org_id_in to to_org_id_in.
    -- Can raise not_enough_entitlements_in_base_org if from_org_id_in
    -- does not have enough entitlements to cover the move.
    -- Takes care of unentitling systems if necessary by calling
    -- set_server_group_count
    -- *******************************************************************
    procedure assign_system_entitlement(
        group_label_in in varchar2,
        from_org_id_in in number,
        to_org_id_in in number,
        quantity_in in number
    )
    is
        prev_ent_count number;
    to_org_prev_ent_count number;
        new_ent_count number;
    new_quantity number;
        group_type number;
    begin

        begin
            select max_members
            into prev_ent_count
            from rhnServerGroupType sgt,
                 rhnServerGroup sg
            where sg.org_id = from_org_id_in
              and sg.group_type = sgt.id
              and sgt.label = group_label_in;
        exception
            when NO_DATA_FOUND then
                rhn_exception.raise_exception(
                              'not_enough_entitlements_in_base_org');
        end;

        begin
            select max_members
            into to_org_prev_ent_count
            from rhnServerGroupType sgt,
                 rhnServerGroup sg
            where sg.org_id = to_org_id_in
              and sg.group_type = sgt.id
              and sgt.label = group_label_in;
        exception
            when NO_DATA_FOUND then
                to_org_prev_ent_count := 0;
        end;

        begin
            select id
            into group_type
            from rhnServerGroupType
            where label = group_label_in;
        exception
            when NO_DATA_FOUND then
                rhn_exception.raise_exception(
                              'invalid_server_group');
        end;

        new_ent_count := prev_ent_count - quantity_in;

        if prev_ent_count > new_ent_count then
            new_quantity := to_org_prev_ent_count + quantity_in;
        end if;

        if new_ent_count < 0 then
            rhn_exception.raise_exception(
                          'not_enough_entitlements_in_base_org');
        end if;


        set_server_group_count(from_org_id_in,
                                         group_type,
                                         new_ent_count);

        set_server_group_count(to_org_id_in,
                                         group_type,
                                         new_quantity);

        -- Create or delete the entries in rhnOrgEntitlementType
        if group_label_in = 'enterprise_entitled' then
            if new_quantity > 0 then
                set_customer_enterprise(to_org_id_in);
            else
                unset_customer_enterprise(to_org_id_in);
            end if;
        end if;

        if group_label_in = 'provisioning_entitled' then
            if new_quantity > 0 then
                set_customer_provisioning(to_org_id_in);
            else
                unset_customer_provisioning(to_org_id_in);
            end if;
        end if;

        if group_label_in = 'monitoring_entitled' then
            if new_quantity > 0 then
                set_customer_monitoring(to_org_id_in);
            else
                unset_customer_monitoring(to_org_id_in);
            end if;
        end if;

    end assign_system_entitlement;

    -- *******************************************************************
    -- PROCEDURE: assign_channel_entitlement
    --
    -- Moves channel entitlements from from_org_id_in to to_org_id_in.
    -- Can raise not_enough_entitlements_in_base_org if from_org_id_in
    -- does not have enough entitlements to cover the move.
    -- Takes care of unentitling systems if necessary by calling
    -- set_family_count
    -- *******************************************************************
    procedure assign_channel_entitlement(
        channel_family_label_in in varchar2,
        from_org_id_in in number,
        to_org_id_in in number,
        quantity_in in number,
        flex_in in number
    )
    is
        from_org_prev_ent_count number;
        from_org_prev_ent_count_flex number;
        new_ent_count number;
        new_ent_count_flex number;
        to_org_prev_ent_count number;
        to_org_prev_ent_count_flex number;
        new_quantity number;
        new_flex number;
        cfam_id       number;
    begin

        begin
            select max_members
            into from_org_prev_ent_count
            from rhnChannelFamily cf,
                 rhnPrivateChannelFamily pcf
            where pcf.org_id = from_org_id_in
              and pcf.channel_family_id = cf.id
              and cf.label = channel_family_label_in;
        exception
            when NO_DATA_FOUND then
                rhn_exception.raise_exception(
                              'not_enough_entitlements_in_base_org');
        end;

        begin
            select max_members
            into to_org_prev_ent_count
            from rhnChannelFamily cf,
                 rhnPrivateChannelFamily pcf
            where pcf.org_id = to_org_id_in
              and pcf.channel_family_id = cf.id
              and cf.label = channel_family_label_in;
        exception
            when NO_DATA_FOUND then
                to_org_prev_ent_count := 0;
        end;

        begin
            select fve_max_members
            into from_org_prev_ent_count_flex
            from rhnChannelFamily cf,
                 rhnPrivateChannelFamily pcf
            where pcf.org_id = from_org_id_in
              and pcf.channel_family_id = cf.id
              and cf.label = channel_family_label_in;
        exception
            when NO_DATA_FOUND then
                rhn_exception.raise_exception(
                              'not_enough_flex_entitlements_in_base_org');
        end;

        begin
            select fve_max_members
            into to_org_prev_ent_count_flex
            from rhnChannelFamily cf,
                 rhnPrivateChannelFamily pcf
            where pcf.org_id = to_org_id_in
              and pcf.channel_family_id = cf.id
              and cf.label = channel_family_label_in;
        exception
            when NO_DATA_FOUND then
                to_org_prev_ent_count_flex := 0;
        end;

        begin
            select id
            into cfam_id
            from rhnChannelFamily
            where label = channel_family_label_in;
        exception
            when NO_DATA_FOUND then
                rhn_exception.raise_exception(
                              'invalid_channel_family');
        end;

        new_ent_count := from_org_prev_ent_count - quantity_in;
        new_ent_count_flex := from_org_prev_ent_count_flex - flex_in;

        if from_org_prev_ent_count >= new_ent_count then
            new_quantity := to_org_prev_ent_count + quantity_in;
       end if;

       if from_org_prev_ent_count_flex >= new_ent_count_flex then
            new_flex := to_org_prev_ent_count_flex + flex_in;
       end if;


        if new_ent_count < 0 then
            rhn_exception.raise_exception(
                          'not_enough_entitlements_in_base_org');
        end if;

        if new_ent_count_flex < 0 then
            rhn_exception.raise_exception(
                          'not_enough_flex_entitlements_in_base_org');
        end if;



        rhn_entitlements.set_family_count(from_org_id_in, cfam_id,
                                           new_ent_count, new_ent_count_flex);

        rhn_entitlements.set_family_count(to_org_id_in,
                                          cfam_id,
                                          new_quantity, new_flex);

    end assign_channel_entitlement;

    -- *******************************************************************
    -- PROCEDURE: activate_system_entitlement
    --
    -- Sets the values in rhnServerGroup for a given rhnServerGroupType.
    --
    -- Calls: set_server_group_count to update, prune, or create the group.
    -- Called by: the code that activates a satellite cert.
    --
    -- Raises not_enough_entitlements_in_base_org if all entitlements
    -- in the org are used so the free entitlements would not cover
    -- the difference when descreasing the number of entitlements.
    -- *******************************************************************
    procedure activate_system_entitlement(
        org_id_in in number,
        group_label_in in varchar2,
        quantity_in in number
    )
    is
        prev_ent_count number;
        prev_ent_count_sum number;
        group_type number;
    begin

        -- Fetch the current entitlement count for the org
        -- into prev_ent_count
        begin
            select current_members
            into prev_ent_count
            from rhnServerGroupType sgt,
                 rhnServerGroup sg
            where sg.group_type = sgt.id
              and sgt.label = group_label_in
              and sg.org_id = org_id_in;
        exception
            when NO_DATA_FOUND then
                prev_ent_count := 0;
        end;

        begin
            select id
            into group_type
            from rhnServerGroupType
            where label = group_label_in;
        exception
            when NO_DATA_FOUND then
                rhn_exception.raise_exception(
                              'invalid_server_group');
        end;

        -- If we're setting the total entitlemnt count to a lower value,
        -- and that value is less than the allocated count in this org,
        -- we need to raise an exception.
        if quantity_in < prev_ent_count then
            rhn_exception.raise_exception(
                          'not_enough_entitlements_in_base_org');
        else
            -- don't update family counts after every server
            -- will do bulk update afterwards
            set_server_group_count(org_id_in,
                                             group_type,
                                             quantity_in,
                                             update_family_countsYN => 0);
            -- bulk update family counts
            rhn_channel.update_group_family_counts(group_label_in, org_id_in);
        end if;


    end activate_system_entitlement;

    -- *******************************************************************
    -- PROCEDURE: activate_channel_entitlement
    --
    -- Calls: set_family_count to update, prune, or create the family
    --        permission bucket.
    -- Called by: the code that activates a satellite cert.
    --
    -- Raises not_enough_entitlements_in_base_org if there are not enough
    -- entitlements in the org to cover the difference when you are
    -- descreasing the number of entitlements.
    --
    -- The backend code in Python is expected to do whatever arithmetics
    -- is needed.
    -- *******************************************************************
    procedure activate_channel_entitlement(
        org_id_in in number,
        channel_family_label_in in varchar2,
        quantity_in in number,
        flex_in in number

    )
    is
        prev_ent_count number;
        prev_flex_count number;
        prev_ent_count_sum number;
        cfam_id number;
        reduce_quantity number;
        total_flex_capable number;
        cursor to_convert_reg (channel_family_id_val in number, org_id_in in number, quantity in number)
                is
                     select SC.server_id
                     from rhnServerChannel SC inner join
                          rhnServer S on S.id = SC.server_id
                     where
                         is_fve = 'Y'
                         and S.org_id = org_id_in
                         and SC.channel_id in
                         (select cfm.channel_id from rhnChannelFamilyMembers cfm
                             where cfm.CHANNEL_FAMILY_ID = channel_family_id_val)
                          and rownum <= quantity;
         cursor to_convert_flex (channel_family_id_val in number, org_id_in in number, quantity in number)
                 is
                   select server_id
                   from rhnServerFveCapable
                       where SERVER_ORG_ID = org_id_in and
                             channel_family_id = cfam_id and
                             rownum <= quantity;

    begin

        -- Fetch the current entitlement count for the org
        -- into prev_ent_count
        begin
            select current_members
            into prev_ent_count
            from rhnChannelFamily cf,
                 rhnPrivateChannelFamily pcf
            where pcf.org_id = org_id_in
              and pcf.channel_family_id = cf.id
              and cf.label = channel_family_label_in;
        exception
            when NO_DATA_FOUND then
                prev_ent_count := 0;
        end;

        begin
            select pcf.fve_current_members
            into prev_flex_count
            from rhnChannelFamily cf,
                 rhnPrivateChannelFamily pcf
            where pcf.org_id = org_id_in
              and pcf.channel_family_id = cf.id
              and cf.label = channel_family_label_in;
        exception
            when NO_DATA_FOUND then
                prev_flex_count := 0;
        end;


        begin
            select id
            into cfam_id
            from rhnChannelFamily
            where label = channel_family_label_in;
        exception
            when NO_DATA_FOUND then
                rhn_exception.raise_exception(
                              'invalid_channel_family');
        end;

        -- if there are too few flex entitlements
        if flex_in < prev_flex_count then
            -- and if the extra we need is less than or equal to our extra regular entitlements
            if prev_flex_count - flex_in <= quantity_in - prev_ent_count then
                   reduce_quantity := prev_flex_count - flex_in;
                   -- We need to convert some systems from flex guest to regular
                   for system in to_convert_reg(cfam_id, org_id_in, reduce_quantity) loop
                      --rhn_channel.convert_to_regular(system.server_id, cfam_id);
                      UPDATE rhnServerChannel sc set sc.is_fve = 'N'
                           where sc.server_id = system.server_id
                                 and sc.channel_id in (select cfm.channel_id
                                                          from rhnChannelFamilyMembers cfm
                                                          where cfm.channel_family_id = cfam_id);
                   end loop;

                   --reset previous counts
                   prev_ent_count := prev_ent_count + reduce_quantity;
                   prev_flex_count := prev_flex_count - reduce_quantity;
            else
                rhn_exception.raise_exception(
                          'not_enough_flex_entitlements_in_base_org');
            end if;
        end if;

        -- if there are too few regular entitlements, and extra flex entitlements
        if quantity_in < prev_ent_count and prev_flex_count < flex_in then
                -- how many flex-capable systems (that aren't using flex) do we have
                select count(*)
                   into total_flex_capable
                   from rhnServerFveCapable
                       where SERVER_ORG_ID = org_id_in and
                             channel_family_id = cfam_id;
                -- if we have enough flex capable machines that is at least
                --   as many as what we are over on
                if total_flex_capable >= prev_ent_count - quantity_in then
                    reduce_quantity := prev_ent_count - quantity_in;
                    for system in to_convert_flex(cfam_id, org_id_in, reduce_quantity) loop
--                          rhn_channel.convert_to_fve(system.server_id, cfam_id);
                        UPDATE rhnServerChannel sc set sc.is_fve = 'Y'
                           where sc.server_id = system.server_id
                                 and sc.channel_id in (select cfm.channel_id
                                                          from rhnChannelFamilyMembers cfm
                                                          where cfm.channel_family_id = cfam_id);
                    end loop;
                    prev_ent_count := prev_ent_count - reduce_quantity;
                    prev_flex_count := prev_flex_count + reduce_quantity;
                end if;
        end if;




        -- If we're setting the total entitlemnt count to a lower value,
        -- and that value is less than the count in that one org,
        -- we need to raise an exception.
        if quantity_in < prev_ent_count then
            rhn_exception.raise_exception(
                          'not_enough_entitlements_in_base_org');
        else
            -- even if we've manually converted systems to/from flex above
            -- set_family_count should call update_family_counts, to reset
            -- current used slots
            rhn_entitlements.set_family_count(org_id_in, cfam_id,
                                              quantity_in, flex_in);
        end if;

    end activate_channel_entitlement;


    -- *******************************************************************
    -- PROCEDURE: prune_family
    -- Unsubscribes servers consuming physical slots from the channel family
    --   that are over the org's limit.
    -- Called by: set_family_count
    -- *******************************************************************
    procedure prune_family (
        customer_id_in in number,
        channel_family_id_in in number,
        quantity_in in number,
        flex_in in number
    ) is
       is_fve_in char;
       tmp_quantity number;

        cursor serverchannels is
            select    sc.server_id,
                    sc.channel_id
            from    rhnServerChannel sc,
                    rhnChannelFamilyMembers cfm
            where    1=1
                and cfm.channel_family_id = channel_family_id_in
                and cfm.channel_id = sc.channel_id
                and server_id in (
                    select    server_id
                      from    (
                        select server_id, time, rownum row_number
                        from    (
                            select rs.id  server_id, rcfm.modified time
                            from    rhnServerChannel         rsc,
                                    rhnChannelFamilyMembers  rcfm,
                                    rhnServer                rs
                            where    1=1
                                and rs.org_id = customer_id_in
                                and rs.id = rsc.server_id
                                and rsc.channel_id = rcfm.channel_id
                                and rcfm.channel_family_id =  channel_family_id_in
                                and rsc.is_fve = is_fve_in
                                -- we only want to grab servers consuming
                                -- physical slots.
                                and exists (
                                    select 1
                                    from rhnChannelFamilyServerPhysical cfsp
                                    where cfsp.server_id = rs.id
                                    and cfsp.channel_family_id =
                                        channel_family_id_in
                                    )
                            order by time asc
                        )
                    )
                    where row_number > tmp_quantity
                );
    begin
        -- if we get a null customer_id, this is completely bogus.
        if customer_id_in is null then
            return;
        end if;

        tmp_quantity := quantity_in;
        is_fve_in := 'N';

        for sc in serverchannels loop
            rhn_channel.unsubscribe_server(sc.server_id, sc.channel_id, 1, 1,
                                                       update_family_countsYN => 0);

        tmp_quantity := flex_in;
        is_fve_in := 'Y';
        for sc in serverchannels loop
            rhn_channel.unsubscribe_server(sc.server_id, sc.channel_id, 1, 1,
                                                        update_family_countsYN => 0);
        end loop;



        end loop;
                rhn_channel.update_family_counts(channel_family_id_in, customer_id_in);
    end prune_family;

    procedure set_family_count (
        customer_id_in in number,
        channel_family_id_in in number,
        quantity_in in number,
        flex_in in number
    ) is
        cursor privperms is
            select    1
            from    rhnPrivateChannelFamily
            where    org_id = customer_id_in
                and channel_family_id = channel_family_id_in;
        cursor pubperms is
            select    o.id org_id
            from    web_customer o,
                    rhnPublicChannelFamily pcf
            where    pcf.channel_family_id = channel_family_id_in;
        quantity number;
        done number := 0;
        flex number;
    begin
        quantity := quantity_in;
        if quantity is not null and quantity < 0 then
            quantity := 0;
        end if;
        flex := flex_in;
        if flex is not null and flex < 0 then
            flex := 0;
        end if;


        if customer_id_in is not null then
            for perm in privperms loop
                rhn_entitlements.prune_family(customer_id_in, channel_family_id_in,
                    quantity, flex);

                if quantity is null and flex is null then
                    delete from rhnPrivateChannelFamily
                        where org_id = customer_id_in
                            and channel_family_id = channel_family_id_in;
                else
                    update rhnPrivateChannelFamily
                        set max_members = quantity
                        where org_id = customer_id_in
                            and channel_family_id = channel_family_id_in;

                   update rhnPrivateChannelFamily
                        set fve_max_members = flex
                        where org_id = customer_id_in
                            and channel_family_id = channel_family_id_in;
                end if;
                return;
            end loop;

            insert into rhnPrivateChannelFamily (
                    channel_family_id, org_id, max_members, current_members, fve_max_members, fve_current_members
                ) values (
                    channel_family_id_in, customer_id_in, quantity, 0, flex, 0 );
            return;
        end if;

        for perm in pubperms loop
            if quantity = 0 then
                rhn_entitlements.prune_family(
                    perm.org_id,
                    channel_family_id_in,
                    quantity,
                    flex
                );
                if done = 0 then
                    delete from rhnPublicChannelFamily
                        where channel_family_id = channel_family_id_in;
                end if;
            end if;
            done := 1;
        end loop;
        -- if done's not 1, then we don't have any entitlements
        if done != 1 then
            insert into rhnPublicChannelFamily (
                    channel_family_id
                ) values (
                    channel_family_id_in
                );
        end if;
    end set_family_count;

    -- this expects quantity_in to be the number of available slots, not the
    -- max_members of the server group.  If you give it too many, it'll fail
    -- and raise servergroup_max_members.
    -- We should NEVER run this unless we're SURE that we won't
    -- be violating the max.
    procedure entitle_last_modified_servers (
        customer_id_in in number,
        type_label_in in varchar2,
        quantity_in in number
    ) is
        -- find the servers that aren't currently in slots
        cursor servers(cid_in in number, quant_in in number) is
            select    server_id
            from    (
                        select    rownum row_number,
                                server_id
                        from    (
                                    select    rs.id server_iD
                                    from    rhnServer rs
                                    where    1=1
                                        and rs.org_id = cid_in
                                        and not exists (
                                            select    1
                                            from    rhnServerGroup sg,
                                                    rhnServerGroupMembers rsgm
                                            where    rsgm.server_id = rs.id
                                                and rsgm.server_group_id = sg.id
                                                and sg.group_type is not null
                                        )
                                        and not exists (
                                            select 1
                                            from rhnVirtualInstance vi
                                            where vi.virtual_system_id =
                                                  rs.id
                                        )                                                                           order by modified desc
                                )
                    )
            where    row_number <= quant_in;
    begin
        for server in servers(customer_id_in, quantity_in) loop
            rhn_entitlements.entitle_server(server.server_id, type_label_in);
        end loop;
    end entitle_last_modified_servers;

    procedure subscribe_newest_servers (
        customer_id_in in number
    ) is
        -- find servers without base channels
        cursor servers(cid_in in number) is
            select    s.id
            from    rhnServer            s
            where    1=1
                and s.org_id = cid_in
                and not exists (
                        select 1
                        from    rhnChannel            c,
                                rhnServerChannel    sc
                        where    sc.server_id = s.id
                            and sc.channel_id = c.id
                            and c.parent_channel is null
                    )
                and not exists (
                        select 1
                        from rhnVirtualInstance vi
                        where vi.virtual_system_id = s.id
                    )
            order by s.modified desc;
        channel_id number;
    begin
        for server in servers(customer_id_in) loop
            channel_id := rhn_channel.guess_server_base(server.id);
            if channel_id is not null then
                begin
                    rhn_channel.subscribe_server(server.id, channel_id);
                    commit;
                -- exception is really channel_family_no_subscriptions
                exception
                    when others then
                        null;
                end;
            end if;
        end loop;
    end subscribe_newest_servers;
end rhn_entitlements;
/
show errors

create or replace
procedure delete_server (
	server_id_in in number
) is
	cursor servergroups is
		select	server_id, server_group_id
		from	rhnServerGroupMembers sgm
		where	sgm.server_id = server_id_in;
	cursor configchannels is
		select	cc.id
		from	rhnConfigChannel cc,
			rhnConfigChannelType cct,
			rhnServerConfigChannel scc
		where	1=1
			and scc.server_id = server_id_in
			and scc.config_channel_id = cc.id
			-- these config channel types are reserved
			-- for use by a single server, so we don't
			-- need to check for other servers subscribed
			and cct.label in
				('local_override','server_import')
			and cct.id = cc.confchan_type_id;
        type filelistsid_t is table of rhnServerPreserveFileList.file_list_id%type;
        filelistsid_c filelistsid_t;

        type probesid_t is table of rhn_check_probe.probe_id%type;
        probesid_c probesid_t;

    is_virt number := 0;
begin
	rhn_channel.delete_server_channels(server_id_in);
	-- rhn_channel.clear_subscriptions(server_id_in);

        -- filelists
	select	spfl.file_list_id id bulk collect into filelistsid_c
	  from	rhnServerPreserveFileList spfl
	 where	spfl.server_id = server_id_in
			and not exists (
				select	1
				from	rhnServerPreserveFileList
				where	file_list_id = spfl.file_list_id
					and server_id != server_id_in
				union
				select	1
				from	rhnKickstartPreserveFileList
				where	file_list_id = spfl.file_list_id
			);
        if filelistsid_c.first is not null then
            forall i in filelistsid_c.first..filelistsid_c.last
                delete from rhnFileList where id = filelistsid_c(i);
        end if;

	for configchannel in configchannels loop
		rhn_config.delete_channel(configchannel.id);
	end loop;

      select count(1) into is_virt
        from rhnServerEntitlementView
       where server_id = server_id_in
         and label in ('virtualization_host', 'virtualization_host_platform')
         and rownum <= 1;

	for sgm in servergroups loop
		rhn_server.delete_from_servergroup(
			sgm.server_id, sgm.server_group_id);
	end loop;

    if is_virt = 1 then
        rhn_entitlements.repoll_virt_guest_entitlements(server_id_in);
    end if;

	-- we're handling this instead of letting an "on delete
	-- set null" do it so that we don't run the risk
	-- of setting off the triggers and killing us with a
	-- mutating table

	-- this is merge of two single updates:
        --  update ... set old_server_id = null where old_server_id = server_id_in;
        --  update ... set new_server_id = null where new_server_id = server_id_in;
        -- so we scan rhnKickstartSession table only once
	update rhnKickstartSession
		set old_server_id = case when old_server_id = server_id_in then null else old_server_id end,
		    new_server_id = case when new_server_id = server_id_in then null else new_server_id end
		where old_server_id = server_id_in
		   or new_server_id = server_id_in;

	rhn_channel.clear_subscriptions(server_id_in,1);

	-- A little complicated here, but the goal is to
	-- delete records from rhnVirtualInstace only if we don't
	-- care about them anymore.  We don't care about records
	-- in rhnVirtualInstance if we are deleting the host
	-- system and the virtual system is already null, or
	-- vice-versa.  We *do* care about them if either the
	-- host or virtual system is still registered because we
	-- still want them to show up in the UI.
    -- If there's a newer row in rhnVirtualInstance with the same
    -- uuid, this guest must have been re-registered, so we can clean
    -- this data up.

        delete from rhnVirtualInstance vi
	      where (host_system_id = server_id_in and virtual_system_id is null)
                 or (virtual_system_id = server_id_in and host_system_id is null)
                 or (vi.virtual_system_id = server_id_in and vi.modified < (select max(vi2.modified)
                    from rhnVirtualInstance vi2 where vi2.uuid = vi.uuid));

        -- this is merge of two single updates:
        --  update ... set host_system_id = null where host_system_id = server_id_in;
        --  update ... set virtual_system_id = null where virtual_system_id = server_id_in;
        -- so we scan rhnVirtualInstance table only once
        update rhnVirtualInstance
	   set host_system_id = case when host_system_id = server_id_in then null else host_system_id end,
	       virtual_system_id = case when virtual_system_id = server_id_in then null else virtual_system_id end
	 where host_system_id = server_id_in
	    or virtual_system_id = server_id_in;

        -- this is merge of two single updates:
        --  update ... set old_host_system_id = null when old_host_system_id = server_id_in;
        --  update ... set new_host_system_id = null when new_host_system_id = server_id_in;
        -- so we scan rhnVirtualInstanceEventLog table only once
	update rhnVirtualInstanceEventLog
	   set old_host_system_id = case when old_host_system_id = server_id_in then null else old_host_system_id end,
               new_host_system_id = case when new_host_system_id = server_id_in then null else new_host_system_id end
         where old_host_system_id = server_id_in
            or new_host_system_id = server_id_in;

	-- We're deleting everything with a foreign key to rhnServer
	-- here, now.  I'm hoping this will help aleviate our deadlock
	-- problem.

	delete from rhnActionConfigChannel where server_id = server_id_in;
	delete from rhnActionConfigRevision where server_id = server_id_in;
	delete from rhnActionPackageRemovalFailure where server_id = server_id_in;
	delete from rhnClientCapability where server_id = server_id_in;
	delete from rhnCpu where server_id = server_id_in;
	-- there's still a cascade here, because the constraint keeps the
	-- table locked for too long to rebuild it.  Ugh...
	delete from rhnDevice where server_id = server_id_in;
	delete from rhnProxyInfo where server_id = server_id_in;
	delete from rhnRam where server_id = server_id_in;
	delete from rhnRegToken where server_id = server_id_in;
	delete from rhnSatelliteInfo where server_id = server_id_in;
	-- this cascades to rhnActionConfigChannel and rhnActionConfigFileName
	delete from rhnServerAction where server_id = server_id_in;
	delete from rhnServerActionPackageResult where server_id = server_id_in;
	delete from rhnServerActionScriptResult where server_id = server_id_in;
	delete from rhnServerActionVerifyResult where server_id = server_id_in;
	delete from rhnServerActionVerifyMissing where server_id = server_id_in;
	-- counts are handled above.  this should be a delete_ function.
	delete from rhnServerChannel where server_id = server_id_in;
	delete from rhnServerConfigChannel where server_id = server_id_in;
	delete from rhnServerCustomDataValue where server_id = server_id_in;
	delete from rhnServerDMI where server_id = server_id_in;
	delete from rhnServerEvent where server_id = server_id_in;
	delete from rhnServerHistory where server_id = server_id_in;
	delete from rhnServerInfo where server_id = server_id_in;
	delete from rhnServerInstallInfo where server_id = server_id_in;
	delete from rhnServerLocation where server_id = server_id_in;
	delete from rhnServerLock where server_id = server_id_in;
	delete from rhnServerNeededCache where server_id = server_id_in;
	delete from rhnServerNetwork where server_id = server_id_in;
	delete from rhnServerNotes where server_id = server_id_in;
	-- I'm not removing the foreign key from rhnServerPackage; that'll
	-- take forever.  Do the delete anyway.
	delete from rhnServerPackage where server_id = server_id_in;
	delete from rhnServerTokenRegs where server_id = server_id_in;
	delete from rhnSnapshotTag where server_id = server_id_in;
	-- this cascades to:
	--   rhnSnapshotChannel, rhnSnapshotConfigChannel, rhnSnapshotPackage,
	--   rhnSnapshotConfigRevision, rhnSnapshotServerGroup,
	--   rhnSnapshotTag.
	-- We may want to consider delete_snapshot() at some point, but
	--   I don't think we need to yet.
	delete from rhnSnapshot where server_id = server_id_in;
	delete from rhnUserServerPrefs where server_id = server_id_in;
	-- hrm, this one's interesting... we _probably_ should delete
	-- everything for the parent server_id when we delete the proxy,
	-- but we don't currently.
	delete from rhnServerPath where server_id_in in (server_id, proxy_server_id);
	delete from rhnUserServerPerms where server_id = server_id_in;

	delete from rhnServerNetInterface where server_id = server_id_in;
	delete from rhn_server_monitoring_info where recid = server_id_in;

	delete from rhnServerUuid where server_id = server_id_in;
    -- We delete all the probes running directly against this system
    -- and any probes that were using this Server as a Proxy Scout.
     SELECT CP.probe_id bulk collect into probesid_c
       FROM rhn_check_probe CP
      WHERE CP.host_id = server_id_in
         OR CP.sat_cluster_id in
    (SELECT SN.sat_cluster_id
       FROM rhn_sat_node SN
      WHERE SN.server_id = server_id_in);

    if probesid_c.first is not null then
        FORALL i IN probesid_c.first..probesid_c.last
            DELETE FROM rhn_probe_state PS WHERE PS.probe_id = probesid_c(i);
        FORALL i IN probesid_c.first..probesid_c.last
            DELETE FROM rhn_probe P  WHERE P.recid = probesid_c(i);
    end if;

	delete from rhn_check_probe where host_id = server_id_in;
	delete from rhn_host_probe where host_id = server_id_in;

    delete from rhn_sat_cluster where recid in
      ( select sat_cluster_id from rhn_sat_node where server_id = server_id_in );

	delete from rhn_sat_node where server_id = server_id_in;

    delete from rhnPushClient where server_id = server_id_in;

	-- now get rhnServer itself.
	delete
	from	rhnServer
		where id = server_id_in;

	delete
	from	rhnSet
	where	1=1
		and user_id in (
			select	wc.id
			from	rhnServer rs,
				web_contact wc
			where	rs.id = server_id_in
				and rs.org_id = wc.org_id
		)
		and label = 'system_list'
		and element = server_id_in;
end delete_server;
/
show errors;
   07070100000927000081B400000000000000000000000167AE111400000E84000000000000000000000000000000000000006900000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/626-rhnServerOverview.sql  --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
drop view rhnServerOverview;
create view
rhnServerOverview
(
    org_id, 
    server_id, 
    server_name, 
    modified, 
    server_admins, 
    group_count, 
    channel_id,
    channel_labels, 
    history_count, 
    security_errata, 
    bug_errata, 
    enhancement_errata,
    outdated_packages,
	config_files_with_differences,
    last_checkin_days_ago,
    last_checkin,
    pending_updates,
    os,
    release,
    server_arch_name,
    locked
)
as
select
    s.org_id, s.id, s.name, s.modified,
    ( select count(user_id) from rhnUserServerPerms ap 
      where server_id = s.id ), 
    ( select count(server_group_id) from rhnVisibleServerGroupMembers
      where server_id = s.id ),
    ( select C.id
        from rhnChannel C,
	     rhnServerChannel SC
       where SC.server_id = S.id
         and SC.channel_id = C.id
	 and C.parent_channel IS NULL),
    coalesce(( select C.name
        from rhnChannel C,
	     rhnServerChannel SC
       where SC.server_id = S.id
         and SC.channel_id = C.id
	 and C.parent_channel IS NULL), '(none)'),
    ( select count(id) from rhnServerHistory
      where
            server_id = S.id),
    ( select count(*) from rhnServerErrataTypeView setv 
      where
            setv.server_id = s.id
        and setv.errata_type = 'Security Advisory'), 
    ( select count(*) from rhnServerErrataTypeView setv 
      where 
            setv.server_id = s.id
        and setv.errata_type = 'Bug Fix Advisory'),
    ( select count(*) from rhnServerErrataTypeView setv 
      where 
            setv.server_id = s.id
        and setv.errata_type = 'Product Enhancement Advisory'),
    ( select count(distinct p.name_id) from rhnPackage p, rhnServerNeededPackageCache snpc
      where
             snpc.server_id = S.id
	 and p.id = snpc.package_id
	 ),
    ( select count(*)
        from rhnActionConfigRevision ACR
             INNER JOIN rhnActionConfigRevisionResult ACRR on ACR.id = ACRR.action_config_revision_id
       where ACR.server_id = S.id
         and ACR.action_id = (
              select MAX(rA.id)
                from rhnAction rA
                     INNER JOIN rhnServerAction rSA on rSA.action_id = rA.id
                     INNER JOIN rhnActionStatus rAS on rAS.id = rSA.status
                     INNER JOIN rhnActionType rAT on rAT.id = rA.action_type
               where rSA.server_id = S.id
                 and rAS.name in ('Completed', 'Failed')
                 and rAT.label = 'configfiles.diff'
         )
         and ACR.failure_id is null
         and ACRR.result is not null
        ),
    ( select date_diff_in_days(checkin, current_timestamp) from rhnServerInfo where server_id = S.id ),
    ( select TO_CHAR(checkin, 'YYYY-MM-DD HH24:MI:SS') from rhnServerInfo where server_id = S.id ),
    ( select count(1) 
        from rhnServerAction
       where server_id = S.id
         and status in (0, 1)),
    os,
    release,
    ( select name from rhnServerArch where id = s.server_arch_id),
    coalesce((select 1 from rhnServerLock SL WHERE SL.server_id = S.id), 0)
from 
    rhnServer S
;
07070100000928000081B400000000000000000000000167AE111400000113000000000000000000000000000000000000006F00000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/627-monitoring-data-cleanup.sql    -- delete orphaned data from state_change
delete from state_change sc where sc.o_id not in (select rp.recid || '' from rhn_probe rp);

-- delete orphaned data from rhn_probe_state
delete from rhn_probe_state rps where rps.probe_id not in (select rp.recid from rhn_probe rp);
 07070100000929000081B400000000000000000000000167AE1114000005E9000000000000000000000000000000000000006900000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/628-rhnActionOverview.sql  --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
CREATE OR REPLACE VIEW
rhnActionOverview
(
	org_id,
	action_id,
	type_id,
	type_name,
	name,
    	scheduler,
	scheduler_login,
	earliest_action,
	total_count,
	successful_count,
	failed_count,
	in_progress_count,
	archived
)
AS
SELECT    A.org_id,
	  A.id,
	  AT.id,
	  AT.name,
	  A.name,
	  A.scheduler,
	  U.login,
	  A.earliest_action,
	  (SELECT COUNT(*) FROM rhnServerAction WHERE action_id = A.id),
	  (SELECT COUNT(*) FROM rhnServerAction WHERE action_id = A.id AND status = 2), -- XXX: don''t hard code status here :)
	  (SELECT COUNT(*) FROM rhnServerAction WHERE action_id = A.id AND status = 3),
	  (SELECT COUNT(*) FROM rhnServerAction WHERE action_id = A.id AND status NOT IN (2, 3)),
	  A.archived
FROM
	  rhnActionType AT,
	  rhnAction A
		left outer join
          web_contact U
		on A.scheduler = U.id
WHERE A.action_type = AT.id
ORDER BY  A.earliest_action;

   0707010000092A000081B400000000000000000000000167AE111400000434000000000000000000000000000000000000006F00000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/629-rhnChannelFamilyServers.sql    --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--

create or replace view rhnChannelFamilyServers as
	select	rs.org_id			as customer_id,
		rcfm.channel_family_id		as channel_family_id,
		rsc.server_id			as server_id,
		rsc.created			as created,
		rsc.modified			as modified
	from	rhnChannelFamilyMembers		rcfm,
		rhnChannelFamily		rcf,
		rhnServerChannel		rsc,
		rhnServer			rs
	where
		rcfm.channel_id = rsc.channel_id
		and rcfm.channel_family_id = rcf.id
		and rsc.server_id = rs.id;

0707010000092B000081B400000000000000000000000167AE1114000004B7000000000000000000000000000000000000006D00000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/630-rhnChannelPermissions.sql  --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--

create or replace view
rhnChannelPermissions
(
    org_id, channel_id
)
as
select distinct org_id, channel_id
 from ( select privcf.org_id,
               cfm.channel_id
        from   rhnChannelFamilyMembers cfm,
               rhnPrivateChannelFamily privcf
        where  privcf.channel_family_id = cfm.channel_family_id
       union all
       select  u.org_id, cfm.channel_id
       from    web_contact u,
               rhnChannelFamilyMembers cfm,
               rhnPublicChannelFamily pubcf
       where   pubcf.channel_family_id = cfm.channel_family_id
) S;

 0707010000092C000081B400000000000000000000000167AE111400000665000000000000000000000000000000000000006A00000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/631-rhnChannelTreeView.sql --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--

CREATE OR REPLACE VIEW rhnChannelTreeView
(
        id,
        depth,
	name,
        padded_name,
	channel_arch_id,
        last_modified,
        label,
	parent_or_self_label,
	parent_or_self_id,
	end_of_life
)
AS
select * from (
	select	c.id			as id,
		1			as depth,
		c.name			as name,
		'  ' || c.name		as padded_name,
		c.channel_arch_id	as channel_arch_id,
		c.last_modified		as last_modified,
		c.label			as label,
		c.label			as parent_or_self_label,
		c.id			as parent_or_self_id,
		c.end_of_life		as end_of_life
	from	rhnChannel		c
	where	c.parent_channel is null
	union
	select	c.id			as id,
		2			as depth,
		c.name			as name,
		'' || c.name		as padded_name,
		c.channel_arch_id 	as channel_arch_id,
		c.last_modified		as last_modified,
		c.label			as label,
		pc.label		as parent_or_self_label,
		pc.id			as parent_or_self_id,
		c.end_of_life		as end_of_life
	from	rhnChannel		pc,
		rhnChannel		c
	where	c.parent_channel = pc.id
) S order by parent_or_self_label, parent_or_self_id;

   0707010000092D000081B400000000000000000000000167AE111400000473000000000000000000000000000000000000007600000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/632-rhnOrgChannelFamilyPermissions.sql --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--

create or replace view rhnOrgChannelFamilyPermissions as
	select	pcf.channel_family_id,
		u.org_id as org_id,
		to_number(null, null) as max_members,
		0 as current_members,
		to_number(null, null) as fve_max_members,
		0 as fve_current_members,
		pcf.created,
		pcf.modified
	from	rhnPublicChannelFamily pcf,
		web_contact u
	union
	select	channel_family_id,
		org_id,
		max_members,
		current_members,
		fve_max_members,
		fve_current_members,
		created,
		modified
	from	rhnPrivateChannelFamily;

 0707010000092E000081B400000000000000000000000167AE1114000007CD000000000000000000000000000000000000006D00000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/633-rhnOrgChannelTreeView.sql  --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--

CREATE OR REPLACE VIEW rhnOrgChannelTreeView
(
	org_id,
        id,
        depth,
	name,
        padded_name,
	channel_arch_id,
        last_modified,
        label,
	parent_or_self_label,
	parent_or_self_id,
	end_of_life
)
AS
select * from (
	select	cfp.org_id		as org_id,
		c.id			as id,
		1			as depth,
		c.name			as name,
		'  ' || c.name		as padded_name,
		c.channel_arch_id	as channel_arch_id,
		c.last_modified		as last_modified,
		c.label			as label,
		c.label			as parent_or_self_label,
		c.id			as parent_or_self_id,
		c.end_of_life		as end_of_life
	from	rhnChannel		c,
		rhnChannelFamilyMembers cfm,
		rhnOrgChannelFamilyPermissions cfp
	where	cfp.channel_family_id = cfm.channel_family_id
		and cfm.channel_id = c.id
		and c.parent_channel is null
	union
	select	cfp.org_id		as org_id,
		c.id			as id,
		2			as depth,
		c.name			as name,
		'' || c.name		as padded_name,
		c.channel_arch_id 	as channel_arch_id,
		c.last_modified		as last_modified,
		c.label			as label,
		pc.label		as parent_or_self_label,
		pc.id			as parent_or_self_id,
		c.end_of_life		as end_of_life
	from	rhnChannel		pc,
		rhnChannel		c,
		rhnChannelFamilyMembers	cfm,
		rhnOrgChannelFamilyPermissions cfp
	where	cfp.channel_family_id = cfm.channel_family_id
		and cfm.channel_id = c.id
		and c.parent_channel = pc.id
) s order by parent_or_self_label, parent_or_self_id;

   0707010000092F000081B400000000000000000000000167AE11140000043A000000000000000000000000000000000000007000000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/634-rhnServerGroupMembership.sql   --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--


CREATE OR REPLACE VIEW rhnServerGroupMembership (
         ORG_ID, SERVER_ID, GROUP_ID, GROUP_NAME, GROUP_TYPE, CURRENT_MEMBERS, MAX_MEMBERS
)
AS
SELECT   SG.org_id, SGM.server_id, SG.id, SG.name, SGT.label, SG.current_members, SG.max_members
  FROM
	 rhnServerGroupMembers SGM
             right join
    	 rhnServerGroup SG on (SG.id = SGM.server_group_id)
             left join
         rhnServerGroupType SGT on (SG.group_type = SGT.id)
;

  07070100000930000081B400000000000000000000000167AE1114000003FF000000000000000000000000000000000000007200000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/635-rhnServerGroupOVLiteHelper.sql --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--
-- this is a helper for rhnServerGroupOverviewLite and it's Vis brother.

create or replace view
rhnServerGroupOVLiteHelper as
select	sgm.server_group_id						as server_group_id,
		e.advisory_type							as advisory_type
from	rhnErrata								e,
		rhnServerNeededPackageCache				snpc,
		rhnServerGroupMembers					sgm
where   sgm.server_id = snpc.server_id
	and snpc.errata_id = e.id
;

 07070100000931000081B400000000000000000000000167AE111400000631000000000000000000000000000000000000007000000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/636-rhnSharedChannelTreeView.sql   --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--

CREATE OR REPLACE VIEW RHNSHAREDCHANNELTREEVIEW
(
  ORG_ID,
  ID,
  DEPTH,
  NAME,
  PADDED_NAME,
  CHANNEL_ARCH_ID,
  LAST_MODIFIED,
  LABEL,
  PARENT_OR_SELF_LABEL,
  PARENT_OR_SELF_ID,
  END_OF_LIFE
)
AS
SELECT * FROM (
  SELECT
    C.ORG_TRUST_ID AS ORG_ID,
    C.ID,
    1 AS DEPTH,
    C.NAME,
    '  '||C.NAME AS PADDED_NAME,
    C.CHANNEL_ARCH_ID,
    C.LAST_MODIFIED,
    C.LABEL,
    C.LABEL AS PARENT_OR_SELF_LABEL,
    C.ID AS PARENT_OR_SELF_ID,
    C.END_OF_LIFE
  FROM RHNSHAREDCHANNELVIEW C
  WHERE C.PARENT_CHANNEL IS NULL
  UNION
  SELECT
    C.ORG_TRUST_ID AS ORG_ID,
    C.ID,
    2 AS DEPTH,
    c.name,
    ''||C.NAME AS PADDED_NAME,
    C.CHANNEL_ARCH_ID,
    C.LAST_MODIFIED,
    C.LABEL,
    PC.LABEL AS PARENT_OR_SELF_LABEL,
    PC.ID AS PARENT_OR_SELF_ID,
    C.END_OF_LIFE
  FROM RHNCHANNEL PC,
       RHNSHAREDCHANNELVIEW C
  WHERE C.PARENT_CHANNEL = PC.ID
) SHARRED
ORDER BY PARENT_OR_SELF_LABEL, PARENT_OR_SELF_ID;

   07070100000932000081B400000000000000000000000167AE111400000427000000000000000000000000000000000000006C00000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/637-rhnSharedChannelView.sql   CREATE OR REPLACE VIEW RHNSHAREDCHANNELVIEW
AS
SELECT 
   CH.ID,
   CH.PARENT_CHANNEL,
   CH.ORG_ID,
   CH.CHANNEL_ARCH_ID,
   CH.LABEL,
   CH.BASEDIR,
   CH.NAME,
   CH.SUMMARY,
   CH.DESCRIPTION,
   CH.PRODUCT_NAME_ID,
   CH.GPG_KEY_URL,
   CH.GPG_KEY_ID,
   CH.GPG_KEY_FP,
   CH.END_OF_LIFE,
   CH.RECEIVING_UPDATES,
   CH.LAST_MODIFIED,
   CH.CHANNEL_PRODUCT_ID,
   CH.CREATED,
   CH.MODIFIED,
   CH.CHANNEL_ACCESS,
   TR.ORG_TRUST_ID
FROM RHNCHANNEL CH,
     RHNTRUSTEDORGS TR
WHERE CH.ORG_ID = TR.ORG_ID AND
      CH.CHANNEL_ACCESS = 'public'
UNION
SELECT
   CH.ID,
   CH.PARENT_CHANNEL,
   CH.ORG_ID,
   CH.CHANNEL_ARCH_ID,
   CH.LABEL,
   CH.BASEDIR,
   CH.NAME,
   CH.SUMMARY,
   CH.DESCRIPTION,
   CH.PRODUCT_NAME_ID,
   CH.GPG_KEY_URL,
   CH.GPG_KEY_ID,
   CH.GPG_KEY_FP,
   CH.END_OF_LIFE,
   CH.RECEIVING_UPDATES,
   CH.LAST_MODIFIED,
   CH.CHANNEL_PRODUCT_ID,
   CH.CREATED,
   CH.MODIFIED,
   CH.CHANNEL_ACCESS,
   TR.ORG_TRUST_ID
FROM RHNCHANNEL CH,
     RHNCHANNELTRUST TR
WHERE CH.ID = TR.CHANNEL_ID AND
      CH.CHANNEL_ACCESS = 'protected'
;

 07070100000933000081B400000000000000000000000167AE111400000787000000000000000000000000000000000000006D00000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/638-rhnUserActionOverview.sql  --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--
-- rhnActionOverview, but on a per-user basis.

-- invoke as:
--
-- select	*
-- from		rhnUserActionOverview
-- where	org_id = :oid
--		and user_id = :uid;
--

create or replace view rhnUserActionOverview as
select	ao.org_id                                       as org_id,
	usp.user_id                                     as user_id,
    	ao.action_id                                    as id,
	ao.type_name                                    as type_name,
        ao.scheduler                                    as scheduler,
	ao.earliest_action                              as earliest_action,
	coalesce( ao.name, ao.type_name )		as action_name,
	sa.status					as action_status_id,
	astat.name                                      as action_status,
	count(sa.action_id)				as tally,
	ao.archived                                     as archived
from	rhnActionStatus            astat,
    	rhnUserServerPerms         usp,
	rhnServerAction            sa,
	rhnActionOverview	   ao
where	ao.action_id = sa.action_id
  and   sa.server_id = usp.server_id
  and   sa.status = astat.id
group by ao.org_id,
	 usp.user_id,
	 ao.action_id,
	 ao.type_name,
	 ao.scheduler,
	 ao.earliest_action,
	 coalesce( ao.name, ao.type_name ),
	 sa.status,
	 astat.name,
	 ao.archived
order by earliest_action;

 07070100000934000081B400000000000000000000000167AE1114000005DE000000000000000000000000000000000000006600000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/639-rhnUserChannel.sql --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--

create or replace view rhnUserChannel
as
select
   cfp.user_id,
   cfp.org_id,
   cfm.channel_id,
   'manage' as role
from rhnChannelFamilyMembers cfm,
      rhnUserChannelFamilyPerms cfp
where
   cfp.channel_family_id = cfm.channel_family_id and
   rhn_channel.user_role_check(cfm.channel_id, cfp.user_id, 'manage') = 1
union all
select
   cfp.user_id,
   cfp.org_id,
   cfm.channel_id,
   'subscribe' as role
from rhnChannelFamilyMembers cfm,
      rhnUserChannelFamilyPerms cfp
where
   cfp.channel_family_id = cfm.channel_family_id and
   rhn_channel.user_role_check(cfm.channel_id, cfp.user_id, 'subscribe') = 1
union all
select
   w.id as user_id,
   w.org_id,
   s.id as channel_id,
   'subscribe' as role
from rhnSharedChannelView s,
      web_contact w
where
   w.org_id = s.org_trust_id and
   rhn_channel.user_role_check(s.id, w.id, 'subscribe') = 1;

  07070100000935000081B400000000000000000000000167AE111400000804000000000000000000000000000000000000006E00000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/640-rhnUserChannelTreeView.sql --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--

CREATE OR REPLACE VIEW rhnUserChannelTreeView
(
	user_id,
	org_id,
        id,
        depth,
	name,
        padded_name,
	channel_arch_id,
        last_modified,
        label,
	parent_or_self_label,
	parent_or_self_id,
	end_of_life
)
AS
select * from (
	select	cfp.user_id		as user_id,
		cfp.org_id		as org_id,
		c.id			as id,
		1			as depth,
		c.name			as name,
		'  ' || c.name		as padded_name,
		c.channel_arch_id	as channel_arch_id,
		c.last_modified		as last_modified,
		c.label			as label,
		c.label			as parent_or_self_label,
		c.id			as parent_or_self_id,
		c.end_of_life		as end_of_life
	from	rhnChannel		c,
		rhnChannelFamilyMembers cfm,
		rhnUserChannelFamilyPerms cfp
	where	cfp.channel_family_id = cfm.channel_family_id
		and cfm.channel_id = c.id
		and c.parent_channel is null
	union
	select	cfp.user_id		as user_id,
		cfp.org_id		as org_id,
		c.id			as id,
		2			as depth,
		c.name			as name,
		'' || c.name		as padded_name,
		c.channel_arch_id 	as channel_arch_id,
		c.last_modified		as last_modified,
		c.label			as label,
		pc.label		as parent_or_self_label,
		pc.id			as parent_or_self_id,
		c.end_of_life		as end_of_life
	from	rhnChannel		pc,
		rhnChannel		c,
		rhnChannelFamilyMembers	cfm,
		rhnUserChannelFamilyPerms cfp
	where	cfp.channel_family_id = cfm.channel_family_id
		and cfm.channel_id = c.id
		and c.parent_channel = pc.id
) S order by parent_or_self_label, parent_or_self_id;

07070100000936000081B400000000000000000000000167AE111400000446000000000000000000000000000000000000007300000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/641-rhnVisServerGroupMembership.sql    --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
CREATE OR REPLACE VIEW rhnVisServerGroupMembership (
         ORG_ID, SERVER_ID, GROUP_ID, GROUP_NAME, GROUP_TYPE, CURRENT_MEMBERS, MAX_MEMBERS
)
AS
SELECT   SG.org_id, SGM.server_id, SG.id, SG.name, SGT.label, SG.current_members, SG.max_members
  FROM
	 rhnServerGroupMembers SGM
            right outer join
    	 rhnVisibleServerGroup SG on (SG.id = SGM.server_group_id)
            left outer join
         rhnServerGroupType SGT on (SG.group_type = SGT.id)
;

  07070100000937000081B400000000000000000000000167AE111400000517000000000000000000000000000000000000006D00000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/642-rhnWebContactDisabled.sql  --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--
create or replace view
rhnWebContactDisabled
as
select
   wcon.id,
   wcon.org_id,
   wcon.login,
   wcon.login_uc,
   wcon.password,
   wcon.old_password,
   wcon.oracle_contact_id,
   wcon.created,
   wcon.modified,
   wcon.ignore_flag
from
   rhnWebContactChangeLog   wccl,
   rhnWebContactChangeState wccs,
   web_contact              wcon
where wccl.change_state_id = wccs.id
   and wccs.label = 'disabled'
   and wccl.web_contact_id = wcon.id
   and wccl.date_completed =
              (select max(wccl_exists.date_completed)
                 from rhnWebContactChangeLog   wccl_exists
                where wccl.web_contact_id = wccl_exists.web_contact_id);

 07070100000938000081B400000000000000000000000167AE111400000468000000000000000000000000000000000000006E00000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/643-rhn_contact_monitoring.sql --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--
--

create or replace view rhn_contact_monitoring as
select	u.id			as recid,
	u.org_id		as customer_id,
	wupi.last_name		as contact_last_name,
	wupi.first_names	as contact_first_name,
	rhn_user.find_mailable_address(u.id)
				as email_address,
	u.login			as username,
	u.password		as password,
	1			as schedule_id,
	'GMT'			as preferred_time_zone
from 
	web_user_personal_info wupi,
	web_contact u
where	u.id = wupi.web_user_id
	--  and some logic here to check org id for entitlements?
;

07070100000939000081B400000000000000000000000167AE111400000082000000000000000000000000000000000000006B00000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/644-rhnHistoryView-drop.sql    
drop view rhnhistoryview;
drop view rhnhistoryview_errata;
drop view rhnhistoryview_packages;
drop view rhnhistoryview_refresh;

  0707010000093A000081B400000000000000000000000167AE111400000051000000000000000000000000000000000000008D00000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/645-rhnHistoryView_erratalist-rhnHistoryView_pkglist.drop.sql  
drop function rhnHistoryView_erratalist;
drop function rhnHistoryView_pkglist;

   0707010000093B000081B400000000000000000000000167AE111400000C93000000000000000000000000000000000000006E00000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/646-rhnServerGroupOverview.sql --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
drop VIEW rhnServerGroupOverview;
CREATE VIEW rhnServerGroupOverview (
         ORG_ID, SECURITY_ERRATA, BUG_ERRATA, ENHANCEMENT_ERRATA, GROUP_ID, GROUP_NAME, GROUP_ADMINS, SERVER_COUNT, MODIFIED, MAX_MEMBERS
)
AS
  SELECT SG.org_id,
         (SELECT COUNT(distinct E.id)
            FROM rhnErrata E,
                 rhnServerNeededPackageCache SNPC,
                 rhnServerGroupMembers SGM
           WHERE E.advisory_type = 'Security Advisory'
                 and snpc.errata_id = e.id
                 and snpc.server_id = sgm.server_id
                 and sgm.server_group_id = sg.id
                 AND EXISTS ( SELECT 1
                              FROM rhnServerFeaturesView SFV
                              WHERE SFV.server_id = SGM.server_id
                                    AND SFV.label = 'ftr_system_grouping')),
         (SELECT COUNT(distinct E.id)
            FROM rhnErrata E,
                 rhnServerNeededPackageCache SNPC,
                 rhnServerGroupMembers SGM
           WHERE E.advisory_type = 'Bug Fix Advisory'
                 and snpc.errata_id = e.id
                 and snpc.server_id = sgm.server_id
                 and sgm.server_group_id = sg.id
                 AND EXISTS ( SELECT 1
                              FROM rhnServerFeaturesView SFV
                              WHERE SFV.server_id = SGM.server_id
                                    AND SFV.label = 'ftr_system_grouping')),
         (SELECT COUNT(distinct E.id)
            FROM rhnErrata E,
                 rhnServerNeededPackageCache SNPC,
                 rhnServerGroupMembers SGM
           WHERE E.advisory_type = 'Product Enhancement Advisory'
                 and snpc.errata_id = e.id
                 and snpc.server_id = sgm.server_id
                 and sgm.server_group_id = sg.id
                 AND EXISTS ( SELECT 1
                              FROM rhnServerFeaturesView SFV
                              WHERE SFV.server_id = SGM.server_id
                                    AND SFV.label = 'ftr_system_grouping')),
         SG.id, SG.name,
         (SELECT COUNT(*) FROM rhnUserManagedServerGroups UMSG WHERE UMSG.server_group_id = SG.id),
         (SELECT COUNT(*) FROM rhnServerGroupMembers SGM WHERE SGM.server_group_id = SG.id
                 AND EXISTS ( SELECT 1
                              FROM rhnServerFeaturesView SFV
                              WHERE SFV.server_id = SGM.server_id
                                    AND SFV.label = 'ftr_system_grouping')),
         CURRENT_TIMESTAMP, MAX_MEMBERS
    FROM rhnServerGroup SG;

 0707010000093C000081B400000000000000000000000167AE111400000027000000000000000000000000000000000000007600000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/647-rhnVisServerGroupOverview-drop.sql 
drop view rhnVisServerGroupOverview;

 0707010000093D000081B400000000000000000000000167AE111400000737000000000000000000000000000000000000007500000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/648-rhnVisServerGroupOverviewLite.sql  --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--
-- This is much more readable with tabsize as 4.  You've been warned ;)

drop view rhnVisServerGroupOverviewLite;
create view
rhnVisServerGroupOverviewLite as
select	sg.org_id					as org_id,
		case when exists (
			select	1
			from	rhnServerGroupOVLiteHelper
			where	server_group_id = sg.id
				and advisory_type = 'Security Advisory'
			)
			then 1
			else 0
			end						as security_errata,
		case when exists (
			select	1
			from	rhnServerGroupOVLiteHelper
			where	server_group_id = sg.id
				and advisory_type = 'Bug Fix Advisory'
			)
			then 1
			else 0
			end						as bug_errata,
		case when exists (
			select	1
			from	rhnServerGroupOVLiteHelper
			where	server_group_id = sg.id
				and advisory_type = 'Product Enhancement Advisory'
			)
			then 1
			else 0
			end						as enhancement_errata,
		sg.id						as group_id,
		sg.name						as group_name,
		(	select	count(*)
			from	rhnUserManagedServerGroups	umsg
			where	umsg.server_group_id = sg.id
		)							as group_admins,
		(	select	count(*)
			from	rhnServerGroupMembers		sgm
			where	sgm.server_group_id = sg.id
		)							as server_count,
		current_timestamp					as modified,
		max_members					as max_members
from	rhnVisibleServerGroup		sg
;

 0707010000093E000081B400000000000000000000000167AE111400000028000000000000000000000000000000000000007200000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/649-rhnServerNeededPackageView.sql 
drop view rhnServerNeededPackageView;

0707010000093F000081B400000000000000000000000167AE111400000461000000000000000000000000000000000000007100000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/650-rhnUserChannelFamilyPerms.sql  --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--

create or replace view rhnUserChannelFamilyPerms as
	select	pcf.channel_family_id,
		u.org_id as org_id,
		u.id as user_id,
		to_number(null, null) as max_members,
		0 as current_members,
		pcf.created,
		pcf.modified
	from	rhnPublicChannelFamily pcf,
		web_contact u
	union
	select	pcf.channel_family_id,
		u.org_id,
		u.id as user_id,
		pcf.max_members,
		pcf.current_members,
		pcf.created,
		pcf.modified
	from	rhnPrivateChannelFamily pcf,
		web_contact u
	where	u.org_id = pcf.org_id;

   07070100000940000081B400000000000000000000000167AE1114000003ED000000000000000000000000000000000000006C00000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/651-rhnWebContactEnabled.sql   --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--

create or replace view
rhnWebContactEnabled
as
select
   wcon.id,
   wcon.org_id,
   wcon.login,
   wcon.login_uc,
   wcon.password,
   wcon.old_password,
   wcon.oracle_contact_id,
   wcon.created,
   wcon.modified,
   wcon.ignore_flag
from
   web_contact wcon
where not exists (
     select 1 from rhnWebContactDisabled
     where wcon.id = rhnWebContactDisabled.id
   );

   07070100000941000081B400000000000000000000000167AE1114000003B6000000000000000000000000000000000000006F00000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/652-rhn_customer_monitoring.sql    --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--

drop view rhn_customer_monitoring;
create view rhn_customer_monitoring as
select	org.id			as recid,
	org.name		as description,
	1			as schedule_id,	--24 x 7
	0			as def_ack_wait,
	1			as def_strategy,	--Broadcast, No Ack
	'GMT' || ''		as preferred_time_zone,
	0			as auto_update	--Windows only
from
	web_customer org
;

  07070100000942000081B400000000000000000000000167AE111400000022000000000000000000000000000000000000006C00000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/653-new_user_postop-drop.sql   
drop procedure new_user_postop;

  07070100000943000081B400000000000000000000000167AE111400000033000000000000000000000000000000000000006700000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/653-rhn_sat_cluster.sql    ALTER TABLE rhn_sat_cluster ADD vip6 VARCHAR2(45);
 07070100000944000081B400000000000000000000000167AE11140000002F000000000000000000000000000000000000006400000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/654-rhn_sat_node.sql   ALTER TABLE rhn_sat_node ADD ip6 VARCHAR2(45);
 07070100000945000081B400000000000000000000000167AE111400000021000000000000000000000000000000000000006F00000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/654-valid_countries_tl-drop.sql    
drop table valid_countries_tl;

   07070100000946000081B400000000000000000000000167AE111400000018000000000000000000000000000000000000006400000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/655-rhnUser-drop.sql   
drop synonym rhnUser;

07070100000947000081B400000000000000000000000167AE11140000002C000000000000000000000000000000000000007800000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/656-command_parameter_threshold-drop.sql   
drop synonym command_parameter_threshold;

07070100000948000081B400000000000000000000000167AE111400000051000000000000000000000000000000000000007300000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/657-command_queue_commands-drop.sql    
drop synonym command_queue_commands;
drop synonym command_q_command_recid_seq;

   07070100000949000081B400000000000000000000000167AE111400000053000000000000000000000000000000000000007400000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/658-command_queue_instances-drop.sql   
drop synonym command_queue_instances;
drop synonym command_q_instance_recid_seq;

 0707010000094A000081B400000000000000000000000167AE111400000043000000000000000000000000000000000000007100000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/659-notification_formats-drop.sql  
drop synonym notification_formats;
drop synonym ntfmt_recid_seq;

 0707010000094B000081B400000000000000000000000167AE11140000004F000000000000000000000000000000000000007500000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/660-rhnAppInstallSessionData-drop.sql  
drop table rhnAppInstallSessionData;
drop sequence rhn_appinst_sdata_id_seq;

 0707010000094C000081B400000000000000000000000167AE111400002096000000000000000000000000000000000000006300000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/662-rhn_org.pkb.sql    --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--

CREATE OR REPLACE
PACKAGE BODY rhn_org
IS  
    procedure delete_org (
        org_id_in in number
    )
    is
        cursor users is
        select id
        from web_contact
        where org_id = org_id_in;

    cursor servers(org_id_in in number) is
        select    id
        from    rhnServer
        where    org_id = org_id_in;

        cursor config_channels is
        select id
        from rhnConfigChannel
        where org_id = org_id_in;

    cursor custom_channels is
        select    id
        from    rhnChannel
        where    org_id = org_id_in;

    cursor errata is
        select    id
        from    rhnErrata
        where    org_id = org_id_in;

    begin

        if org_id_in = 1 then
            rhn_exception.raise_exception('cannot_delete_base_org');
        end if;

        -- Delete all users.
        for u in users loop
            rhn_org.delete_user(u.id, 1);
        end loop;

        -- Delete all servers.
        for s in servers(org_id_in) loop
            delete_server(s.id);
        end loop;

        -- Delete all config channels.
        for c in config_channels loop
            rhn_config.delete_channel(c.id);
        end loop;

        -- Delete all custom channels.
        for cc in custom_channels loop
          delete from rhnServerChannel where channel_id = cc.id;
          delete from rhnServerProfilePackage where server_profile_id in (
            select id from rhnServerProfile where base_channel = cc.id
          );
          delete from rhnServerProfile where base_channel = cc.id;
        end loop;

        -- Delete all errata packages 
        for e in errata loop
            delete from rhnErrataPackage where errata_id = e.id;
        end loop;

        -- Give the org's entitlements back to the main org.
        rhn_entitlements.remove_org_entitlements(org_id_in);

        -- Clean up tables where we don't have a cascading delete.
        delete from rhnChannel where org_id = org_id_in;
        delete from rhnDailySummaryQueue where org_id = org_id_in;
        delete from rhnOrgQuota where org_id = org_id_in;
        delete from rhnFileList where org_id = org_id_in;
        delete from rhnServerGroup where org_id = org_id_in;
        delete from rhn_check_suites where customer_id = org_id_in;
        delete from rhn_command_target where customer_id = org_id_in;
        delete from rhn_contact_groups where customer_id = org_id_in;
        delete from rhn_notification_formats where customer_id = org_id_in;
        delete from rhn_probe where customer_id = org_id_in;
        delete from rhn_redirects where customer_id = org_id_in;
        delete from rhn_sat_cluster where customer_id = org_id_in;
        delete from rhn_schedules where customer_id = org_id_in;

        -- Delete the org.
        delete from web_customer where id = org_id_in;

    end delete_org;

    procedure delete_user(user_id_in in number, deleting_org in number := 0) is
        cursor servergroups_needing_admins is
            select    usgp.server_group_id    server_group_id
            from    rhnUserServerGroupPerms    usgp
            where    1=1
                and usgp.user_id = user_id_in
                and not exists (
                    select    1
                    from    rhnUserServerGroupPerms    sq_usgp
                    where    1=1
                        and sq_usgp.server_group_id = usgp.server_group_id
                        and    sq_usgp.user_id != user_id_in
                );
        users            number;
        our_org_id        number;
        other_users        number;
        other_org_admin    number;
        other_user_id  number;
        is_admin       number;
    begin
        select    wc.org_id
        into    our_org_id
        from    web_contact wc
        where    id = user_id_in;

        -- find any other users
        begin
            select    id, 1
            into    other_user_id, other_users
            from    web_contact
            where    1=1
                and org_id = our_org_id
                and id != user_id_in
                and rownum = 1;
        exception
            when no_data_found then
                other_users := 0;
        end;

        -- now do org admin stuff
        if other_users != 0 then
            -- is user admin?
            select  count(1)
             into   is_admin
            from    rhnUserGroupType    ugt,
                    rhnUserGroup        ug,
                    rhnUserGroupMembers    ugm
            where    ugm.user_id = user_id_in
                and ugm.user_group_id = ug.id
                and ug.group_type = ugt.id
                and ugt.label = 'org_admin';
            if is_admin > 0 then
                begin
                    select    new_ugm.user_id
                    into    other_org_admin
                    from    rhnUserGroupMembers    new_ugm,
                            rhnUserGroupType    ugt,
                            rhnUserGroup        ug,
                            rhnUserGroupMembers    ugm
                    where    ugm.user_id = user_id_in
                        and ugm.user_group_id = ug.id
                        and ug.group_type = ugt.id
                        and ugt.label = 'org_admin'
                        and ug.id = new_ugm.user_group_id
                        and new_ugm.user_id != user_id_in
                        and rownum = 1;
                exception
                    when no_data_found then
                        -- If we're deleting the org, we don't want to raise
                        -- the exception.
                        if deleting_org = 0 then
                            rhn_exception.raise_exception('cannot_delete_user');
                        end if;
                end;

                for sg in servergroups_needing_admins loop
                    rhn_user.add_servergroup_perm(other_org_admin,
                        sg.server_group_id);
                end loop;
            end if;
        end if;

        -- and now things for every user
        delete from rhn_command_queue_sessions where contact_id = user_id_in;
        delete from rhn_contact_groups
        where recid in (
            select contact_group_id
            from rhn_contact_group_members
            where member_contact_method_id in (
                select recid from rhn_contact_methods
                where contact_id = user_id_in
                )
            )
            and not exists (
                select 1
                from rhn_contact_group_members, rhn_contact_methods
                where rhn_contact_groups.recid = rhn_contact_group_members.contact_group_id
                    and rhn_contact_group_members.member_contact_method_id = rhn_contact_methods.recid
                    and rhn_contact_methods.contact_id <> user_id_in
            );
        delete from rhn_contact_methods where contact_id = user_id_in;
        delete from rhn_redirects where contact_id = user_id_in;
        delete from rhnUserServerPerms where user_id = user_id_in;
        update rhnConfigRevision
           set changed_by_id = NULL
         where changed_by_id = user_id_in;
        if other_users != 0 then
            update        rhnRegToken
                set        user_id = nvl(other_org_admin, other_user_id)
                where    org_id = our_org_id
                    and user_id = user_id_in;
        end if;

        begin
            delete from web_contact where id = user_id_in;
        exception
            when others then
                rhn_exception.raise_exception('cannot_delete_user');
        end;
        return;
    end delete_user;

END rhn_org;
/
SHOW ERRORS

  0707010000094D000081B400000000000000000000000167AE11140000004D000000000000000000000000000000000000007100000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/663-rhnAppInstallSession-drop.sql  
drop table rhnAppInstallSession;
drop sequence rhn_appinst_session_id_seq;

   0707010000094E000081B400000000000000000000000167AE11140000004F000000000000000000000000000000000000007200000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/665-rhnAppInstallInstance-drop.sql 
drop table rhnAppInstallInstance;
drop sequence rhn_appinst_instance_id_seq;

 0707010000094F000081B400000000000000000000000167AE111400000541000000000000000000000000000000000000007000000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/667-rhnChannelCloned-trigger.sql   --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--

drop trigger rhn_channelclone_mod_trig;

create or replace trigger
rhn_channel_cloned_comps_trig
before insert or update on rhnChannelCloned
for each row
begin
	:new.modified := sysdate;

	if inserting then
		-- if there are not comps in the cloned channel by now,
		-- we shall clone comps from the original channel
		insert into rhnChannelComps
			( id, channel_id, relative_filename,
				last_modified, created, modified )
		select rhn_channelcomps_id_seq.nextval, :new.id, relative_filename,
				sysdate, sysdate, sysdate
		from rhnChannelComps
		where channel_id = :new.original_id
			and not exists (
				select 1
				from rhnChannelComps x
				where x.channel_id = :new.id
			);
	end if;
end;
/
show errors

   07070100000950000081B400000000000000000000000167AE111400000336000000000000000000000000000000000000007100000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/670-rhnConfigFileType-trigger.sql  --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--

drop trigger rhn_conffiletype_mod_trig;

create trigger
rhn_conffiletype_mod_trig
before insert or update on rhnConfigFileType
for each row
begin
	:new.modified := sysdate;
end;
/
show errors
  07070100000951000081B400000000000000000000000167AE111400000345000000000000000000000000000000000000007200000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/671-rhnKickstartScript-trigger.sql --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--

drop trigger rhn_ksscript_mod_trig;

create trigger
rhn_ksscript_mod_trig
before insert or update on rhnKickstartScript
for each row
begin
	:new.modified := sysdate;
end rhn_ksscript_mod_trig;
/
show errors
   07070100000952000081B400000000000000000000000167AE111400000046000000000000000000000000000000000000006B00000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/672-current_alerts-drop.sql    
drop synonym current_alerts;
drop synonym current_alerts_recid_seq;

  07070100000953000081B400000000000000000000000167AE1114000002B0000000000000000000000000000000000000007300000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/673-clean-current-alerts-delete.sql    
delete from rhnTaskoRun
where template_id in (
	select id from rhnTaskoTemplate
	where task_id in (
		select id from rhnTaskoTask
		where class = 'com.redhat.rhn.taskomatic.task.CleanCurrentAlerts'
	)
);

delete from rhnTaskoTemplate
where task_id in (
	select id from rhnTaskoTask
	where class = 'com.redhat.rhn.taskomatic.task.CleanCurrentAlerts'
);

delete from rhnTaskoTask
where class = 'com.redhat.rhn.taskomatic.task.CleanCurrentAlerts';

delete from rhnTaskoSchedule
where bunch_id in (
	select id from rhnTaskoBunch
	where id not in (
		select bunch_id from rhnTaskoTemplate
	)
);

delete from rhnTaskoBunch
where id not in (
	select bunch_id from rhnTaskoTemplate
);

commit;

07070100000954000081B400000000000000000000000167AE11140000004D000000000000000000000000000000000000006F00000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/674-rhn_current_alerts-drop.sql    
drop table rhn_current_alerts;
drop sequence rhn_current_alerts_recid_seq;

   07070100000955000081B400000000000000000000000167AE111400000508000000000000000000000000000000000000006700000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/677-lookup-checksum.sql    create or replace function insert_checksum(checksum_in in varchar2, checksum_type_in in varchar2)
return number
is
    checksum_id number;
    pragma autonomous_transaction;
begin
    insert into rhnChecksum (id, checksum_type_id, checksum)
    values (rhnChecksum_seq.nextval,
            (select id from rhnChecksumType where label = checksum_type_in),
             checksum_in) returning id into checksum_id;
    commit;
    return checksum_id;
end;
/

create or replace function
lookup_checksum(checksum_type_in in varchar2, checksum_in in varchar2)
return number
is
        checksum_id     number;
begin
        if checksum_in is null then
                return null;
        end if;

        select c.id
          into checksum_id
          from rhnChecksumView c
         where c.checksum = checksum_in
           and c.checksum_type = checksum_type_in;

        return checksum_id;
exception when no_data_found then
    begin
        select insert_checksum(checksum_in, checksum_type_in) into checksum_id from dual;
    exception when dup_val_on_index then
        select c.id
          into checksum_id
          from rhnChecksumView c
         where c.checksum = checksum_in
          and c.checksum_type = checksum_type_in;
    end;
    return checksum_id;
end;
/
show errors
07070100000956000081B400000000000000000000000167AE11140000038E000000000000000000000000000000000000007000000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/678-lookup_client_capability.sql   create or replace function insert_client_capability(name_in varchar2)
return number
is
    pragma autonomous_transaction;
    cap_name_id     number;
begin
    insert into rhnClientCapabilityName (id, name)
    values (rhn_client_capname_id_seq.nextval, name_in) returning id into cap_name_id;

    commit;
    return cap_name_id;
end;
/

create or replace function
lookup_client_capability(name_in in varchar2)
return number
is
    cap_name_id		number;
begin
    select id
      into cap_name_id
      from rhnClientCapabilityName
     where name = name_in;

    return cap_name_id;
exception when no_data_found then
    begin
        select insert_client_capability(name_in) into cap_name_id from dual;
    exception when dup_val_on_index then
        select id
          into cap_name_id
          from rhnClientCapabilityName
         where name = name_in;
    end;
	return cap_name_id;
end;
/
show errors
  07070100000957000081B400000000000000000000000167AE11140000036D000000000000000000000000000000000000006E00000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/679-lookup_config_filename.sql create or replace function
insert_config_filename(name_in in varchar2)
return number
is
    pragma autonomous_transaction;
    name_id number;
begin
    insert into rhnConfigFileName (id, path)
    values (rhn_cfname_id_seq.nextval, name_in) returning id into name_id;
    commit;

    return name_id;
end;
/

create or replace function
lookup_config_filename(name_in in varchar2)
return number
is
    pragma autonomous_transaction;
    name_id		number;
begin
    select id
      into name_id
      from rhnConfigFileName
     where path = name_in;

    return name_id;
exception when no_data_found then
    begin
        select insert_config_filename(name_in) into name_id from dual;
    exception when dup_val_on_index then
        select id
          into name_id
          from rhnConfigFileName
         where path = name_in;
    end;

	return name_id;
end;
/
show errors
   07070100000958000081B400000000000000000000000167AE111400000064000000000000000000000000000000000000006A00000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/680-rhnActionType_data.sql 
insert into rhnActionType
    values (50, 'scap.xccdf_eval', 'OpenSCAP xccdf scanning', 'N', 'Y');
07070100000959000081B400000000000000000000000167AE1114000002FD000000000000000000000000000000000000006500000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/681-rhnActionScap.sql  
CREATE TABLE rhnActionScap
(
    id               NUMBER NOT NULL
                         CONSTRAINT rhn_act_scap_id_pk PRIMARY KEY
                         USING INDEX TABLESPACE [[4m_tbs]],
    action_id        NUMBER NOT NULL
                         CONSTRAINT rhn_act_scap_act_fk
                             REFERENCES rhnAction (id)
                             ON DELETE CASCADE,
    path             VARCHAR2(2048) NOT NULL,
    parameters       BLOB
)
TABLESPACE [[blob]]
ENABLE ROW MOVEMENT
;

CREATE UNIQUE INDEX rhn_act_scap_aid_idx
    ON rhnActionScap (action_id)
    TABLESPACE [[4m_tbs]]
    NOLOGGING;

CREATE INDEX rhn_act_scap_path_idx
    ON rhnActionScap (path)
    TABLESPACE [[4m_tbs]]
    NOLOGGING;

CREATE SEQUENCE rhn_act_scap_id_seq;
   0707010000095A000081B400000000000000000000000167AE1114000001E4000000000000000000000000000000000000006900000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/682-rhnXccdfBenchmark.sql  
CREATE TABLE rhnXccdfBenchmark
(
    id            NUMBER NOT NULL
                      CONSTRAINT rhn_xccdf_benchmark_id_pk PRIMARY KEY
                      USING INDEX TABLESPACE [[64k_tbs]],
    identifier    VARCHAR2(120) NOT NULL,
    version       VARCHAR2(80) NOT NULL
)
ENABLE ROW MOVEMENT
;

CREATE UNIQUE INDEX rhn_xccdf_benchmark_iv_uq
    ON rhnXccdfBenchmark (identifier, version)
    TABLESPACE [[64k_tbs]]
    NOLOGGING;

CREATE SEQUENCE rhn_xccdf_benchmark_id_seq;
0707010000095B000081B400000000000000000000000167AE1114000001D9000000000000000000000000000000000000006700000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/683-rhnXccdfProfile.sql    
CREATE TABLE rhnXccdfProfile
(
    id            NUMBER NOT NULL
                      CONSTRAINT rhn_xccdf_profile_id_pk PRIMARY KEY
                      USING INDEX TABLESPACE [[64k_tbs]],
    identifier    VARCHAR2(120) NOT NULL,
    title         VARCHAR2(120) NOT NULL
)
ENABLE ROW MOVEMENT
;

CREATE UNIQUE INDEX rhn_xccdf_profile_it_uq
    ON rhnXccdfProfile (identifier, title)
    TABLESPACE [[64k_tbs]]
    NOLOGGING;

CREATE SEQUENCE rhn_xccdf_profile_id_seq;
   0707010000095C000081B400000000000000000000000167AE11140000019D000000000000000000000000000000000000006B00000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/684-rhnXccdfIdentsystem.sql    
CREATE TABLE rhnXccdfIdentsystem
(
    id      NUMBER NOT NULL
                CONSTRAINT rhn_xccdf_identsytem_id_pk PRIMARY KEY
                USING INDEX TABLESPACE [[64k_tbs]],
    system  VARCHAR2(80) NOT NULL
)
ENABLE ROW MOVEMENT
;

CREATE UNIQUE INDEX rhn_xccdf_identsystem_id_uq
    ON rhnXccdfIdentsystem (system)
    TABLESPACE [[64k_tbs]]
    NOLOGGING;

CREATE SEQUENCE rhn_xccdf_identsytem_id_seq;
   0707010000095D000081B400000000000000000000000167AE111400000256000000000000000000000000000000000000006500000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/685-rhnXccdfIdent.sql  
CREATE TABLE rhnXccdfIdent
(
    id              NUMBER NOT NULL
                        CONSTRAINT rhn_xccdf_ident_id_pk PRIMARY KEY
                        USING INDEX TABLESPACE [[2m_tbs]],
    identsystem_id  NUMBER NOT NULL
                        CONSTRAINT rhn_xccdf_ident_system_fk
                            REFERENCES rhnXccdfIdentsystem (id),
    identifier      VARCHAR (20) NOT NULL
)
ENABLE ROW MOVEMENT
;

CREATE UNIQUE INDEX rhn_xccdf_ident_isi_uq
    ON rhnXccdfIdent (identsystem_id, identifier)
    TABLESPACE [[2m_tbs]]
    NOLOGGING;

CREATE SEQUENCE rhn_xccdf_ident_id_seq;
  0707010000095E000081B400000000000000000000000167AE1114000004EA000000000000000000000000000000000000006A00000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/686-rhnXccdfTestresult.sql 
CREATE TABLE rhnXccdfTestresult
(
    id             NUMBER NOT NULL
                       CONSTRAINT rhn_xccdf_tresult_id_pk PRIMARY KEY
                       USING INDEX TABLESPACE [[2m_tbs]],
    server_id      NUMBER NOT NULL
                       CONSTRAINT rhn_xccdf_tresult_srvr_fk
                           REFERENCES rhnServer (id)
                           ON DELETE CASCADE,
    action_scap_id NUMBER NOT NULL
                       CONSTRAINT rhn_xccdf_tresult_act_fk
                           REFERENCES rhnActionScap (id)
                           ON DELETE CASCADE,
    benchmark_id   NUMBER NOT NULL
                       CONSTRAINT rhn_xccdf_tresult_bench_fk
                           REFERENCES rhnXccdfBenchmark (id),
    profile_id     NUMBER NOT NULL
                       CONSTRAINT rhn_xccdf_tresult_profile_fk
                           REFERENCES rhnXccdfProfile (id),
    identifier     VARCHAR2(120) NOT NULL,
    start_time     DATE,
    end_time       DATE NOT NULL,
    errors         BLOB
)
TABLESPACE [[blob]]
ENABLE ROW MOVEMENT
;

CREATE UNIQUE INDEX rhn_xccdf_tresult_sa_uq
    ON rhnXccdfTestresult (server_id, action_scap_id)
    TABLESPACE [[2m_tbs]]
    NOLOGGING;

CREATE SEQUENCE rhn_xccdf_tresult_id_seq;
  0707010000095F000081B400000000000000000000000167AE1114000001DA000000000000000000000000000000000000006E00000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/687-rhnXccdfRuleresultType.sql 
CREATE TABLE rhnXccdfRuleresultType
(
    id            NUMBER NOT NULL
                      CONSTRAINT rhn_xccdf_rresult_t_id_pk PRIMARY KEY
                      USING INDEX TABLESPACE [[64k_tbs]],
    abbreviation  CHAR(1) NOT NULL,
    label         VARCHAR2(16) NOT NULL,
    description   VARCHAR2(120) NOT NULL
)
ENABLE ROW MOVEMENT
;

CREATE UNIQUE INDEX rhn_xccdf_rresult_t_label_uq
    ON rhnXccdfRuleresultType (label)
    TABLESPACE [[64k_tbs]]
    NOLOGGING;
  07070100000960000081B400000000000000000000000167AE1114000004FB000000000000000000000000000000000000007300000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/688-rhnXccdfRuleresultType_data.sql    
insert into rhnXccdfRuleresultType values (1, 'P', 'pass',
    'The target system satisfied all the conditions of the xccdf:Rule.');
insert into rhnXccdfRuleresultType values (2, 'F', 'fail',
    'The target system did not satisfy all the conditions of the xccdf:Rule');
insert into rhnXccdfRuleresultType values (3, 'E', 'error',
    'The checking engine could not complete the evaluation, therefore the status of compliance is uncertain.');
insert into rhnXccdfRuleresultType values (4, 'U', 'unknown',
    'The testing tool encountered some problem and the result is unknown.');
insert into rhnXccdfRuleresultType values (5, 'N', 'notapplicable',
    'The xccdf:Rule was not applicable to the target.');
insert into rhnXccdfRuleresultType values (6, 'K', 'notchecked',
    'The xccdf:Rule was not evaluated by the checking engine; xccdf:check was either unspecified or unsupported.');
insert into rhnXccdfRuleresultType values (7, 'S', 'notselected',
    'The xccdf:Rule was not selected in the profile.');
insert into rhnXccdfRuleresultType values (8, 'I', 'informational',
    'The xccdf:Rule was not checked; it is not a compliance category.');
insert into rhnXccdfRuleresultType values (9, 'X', 'fixed',
    'The xccdf:Rule had failed, but was then fixed by tool.');
 07070100000961000081B400000000000000000000000167AE1114000002C7000000000000000000000000000000000000006A00000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/689-rhnXccdfRuleresult.sql 
CREATE TABLE rhnXccdfRuleresult
(
    testresult_id NUMBER NOT NULL
                      CONSTRAINT rhn_xccdf_rresult_tresult_fk
                          REFERENCES rhnXccdfTestresult (id)
                          ON DELETE CASCADE,
    ident_id      NUMBER NOT NULL
                      CONSTRAINT rhn_xccdf_rresult_ident_fk
                          REFERENCES rhnXccdfIdent (id),
    result_id     NUMBER NOT NULL
                      CONSTRAINT rhn_xccdf_rresult_result_fk
                          REFERENCES rhnXccdfRuleresultType (id)
)
ENABLE ROW MOVEMENT
;

CREATE UNIQUE INDEX rhn_xccdf_rresult_tri_uq
    ON rhnXccdfRuleresult (testresult_id, ident_id)
    TABLESPACE [[8m_tbs]]
    NOLOGGING;
 07070100000962000081B400000000000000000000000167AE1114000002B0000000000000000000000000000000000000006E00000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/690-lookup_xccdf_benchmark.sql 
CREATE OR REPLACE FUNCTION
lookup_xccdf_benchmark(identifier_in IN VARCHAR2, version_in IN VARCHAR2)
RETURN NUMBER
IS
    PRAGMA AUTONOMOUS_TRANSACTION;
    benchmark_id NUMBER;
BEGIN
    SELECT id
        INTO benchmark_id
        FROM rhnXccdfBenchmark
        WHERE identifier = identifier_in
            AND version = version_in;
    RETURN benchmark_id;
EXCEPTION
    WHEN NO_DATA_FOUND THEN
        INSERT INTO rhnXccdfBenchmark (id, identifier, version)
            VALUES (rhn_xccdf_benchmark_id_seq.nextval,
                identifier_in, version_in)
            RETURNING id INTO benchmark_id;
        COMMIT;
    RETURN benchmark_id;
END lookup_xccdf_benchmark;
/
SHOW ERRORS
07070100000963000081B400000000000000000000000167AE111400000292000000000000000000000000000000000000006C00000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/691-lookup_xccdf_profile.sql   
CREATE OR REPLACE FUNCTION
lookup_xccdf_profile(identifier_in IN VARCHAR2, title_in IN VARCHAR2)
RETURN NUMBER
IS
    PRAGMA AUTONOMOUS_TRANSACTION;
    profile_id NUMBER;
BEGIN
    SELECT id
        INTO profile_id
        FROM rhnXccdfProfile
        WHERE identifier = identifier_in
            AND title = title_in;
    RETURN profile_id;
EXCEPTION
    WHEN NO_DATA_FOUND THEN
        INSERT INTO rhnXccdfProfile (id, identifier, title)
            VALUES (rhn_xccdf_profile_id_seq.nextval,
                identifier_in, title_in)
            RETURNING id INTO profile_id;
        COMMIT;
    RETURN profile_id;
END lookup_xccdf_profile;
/
SHOW ERRORS
  07070100000964000081B400000000000000000000000167AE11140000042E000000000000000000000000000000000000006A00000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/692-lookup_xccdf_ident.sql 
CREATE OR REPLACE FUNCTION
lookup_xccdf_ident(system_in IN VARCHAR2, identifier_in IN VARCHAR2)
RETURN NUMBER
IS
    PRAGMA AUTONOMOUS_TRANSACTION;
    xccdf_ident_id NUMBER;
    ident_sys_id NUMBER;
BEGIN
    BEGIN
        SELECT id
            INTO ident_sys_id
            FROM rhnXccdfIdentsystem
            WHERE system = system_in;
    EXCEPTION
        WHEN NO_DATA_FOUND THEN
            INSERT INTO rhnXccdfIdentsystem (id, system)
                VALUES (rhn_xccdf_identsytem_id_seq.nextval, system_in)
                RETURNING id INTO ident_sys_id;
    END;

    SELECT id
        INTO xccdf_ident_id
        FROM rhnXccdfIdent
        WHERE identsystem_id = ident_sys_id
            AND identifier = identifier_in;
    RETURN xccdf_ident_id;
EXCEPTION
    WHEN NO_DATA_FOUND THEN
        INSERT INTO rhnXccdfIdent (id, identsystem_id, identifier)
            VALUES (rhn_xccdf_ident_id_seq.nextval, ident_sys_id, identifier_in)
            RETURNING id INTO xccdf_ident_id;
        COMMIT;
    RETURN xccdf_ident_id;
END lookup_xccdf_ident;
/
SHOW ERRORS
  07070100000965000081B400000000000000000000000167AE1114000006D2000000000000000000000000000000000000006A00000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/693-lookup_config_info.sql create or replace function insert_config_info (
    username_in         in varchar2,
    groupname_in        in varchar2,
    filemode_in         in number,
    selinux_ctx_in      in varchar2,
    symlink_target_id   in number
) return number
is
    pragma autonomous_transaction;
    v_id    number;
begin
    select rhn_confinfo_id_seq.nextval
      into v_id
      from dual;
    insert into rhnConfigInfo (id, username, groupname, filemode, selinux_ctx, symlink_target_filename_id)
    values (v_id, username_in, groupname_in, filemode_in, selinux_ctx_in, symlink_target_id);
    commit;
    return v_id;
end;
/

create or replace function
lookup_config_info (
    username_in     in varchar2,
    groupname_in    in varchar2,
    filemode_in     in number,
    selinux_ctx_in  in varchar2,
    symlink_target_id in number
) return number
deterministic
is
    v_id    number;
    cursor lookup_cursor is
        select id
          from rhnConfigInfo
         where 1=1
           and nvl(username, ' ') = nvl(username_in, ' ')
           and nvl(groupname,' ') = nvl(groupname_in, ' ')
           and nvl(filemode, -1) = nvl(filemode_in, -1)
           and nvl(selinux_ctx, ' ') = nvl(selinux_ctx_in, ' ')
           and nvl(symlink_target_filename_id, -1) = nvl(symlink_target_id, -1)
        ;
begin
    for r in lookup_cursor loop
        return r.id;
    end loop;
    -- If we got here, we don't have the id
    v_id := insert_config_info(
            username_in,
            groupname_in,
            filemode_in,
            selinux_ctx_in,
            symlink_target_id);
    return v_id;
exception when dup_val_on_index then
    for r in lookup_cursor loop
        return r.id;
    end loop;
end lookup_config_info;
/
show errors
  07070100000966000081B400000000000000000000000167AE111400000300000000000000000000000000000000000000006200000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/694-lookup_cve.sql create or replace function insert_cve(name_in in varchar2)
return number
is
    pragma autonomous_transaction;
    name_id     number;
begin
    insert into rhnCVE (id, name)
    values (rhn_cve_id_seq.nextval, name_in) returning id into name_id;
    commit;
    return name_id;
end;
/
show errors

create or replace function
lookup_cve(name_in in varchar2)
return number
is
    name_id		number;
begin
    select id
      into name_id
      from rhnCVE
     where name = name_in;

    return name_id;
exception when no_data_found then
    begin
        name_id := insert_cve(name_in);
    exception when dup_val_on_index then
        select id
          into name_id
          from rhnCVE
         where name = name_in;
    end;
    return name_id;
end;
/
show errors
07070100000967000081B400000000000000000000000167AE111400000173000000000000000000000000000000000000006E00000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/695-lookup_erratafile_type.sql create or replace function
lookup_erratafile_type (
	label_in in varchar2
) return number deterministic is
	erratafile_type_id number;
begin
	select	id
	into	erratafile_type_id
	from	rhnErrataFileType
	where	label = label_in;

	return erratafile_type_id;
exception
	when no_data_found then
		rhn_exception.raise_exception('erratafile_type_not_found');
end;
/
show errors
 07070100000968000081B400000000000000000000000167AE111400000482000000000000000000000000000000000000006200000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/696-lookup_evr.sql create or replace function insert_evr(e_in in varchar2, v_in in varchar2, r_in in varchar2)
return number
is
    pragma autonomous_transaction;
    evr_id  number;
begin
    insert into rhnPackageEVR(id, epoch, version, release, evr)
    values (rhn_pkg_evr_seq.nextval,
            e_in,
            v_in,
            r_in,
            evr_t(e_in, v_in, r_in)) returning id into evr_id;
    commit;
    return evr_id;
end;
/
show errors

create or replace function
lookup_evr(e_in in varchar2, v_in in varchar2, r_in in varchar2)
return number
is
    evr_id  number;
begin
    select id
      into evr_id
      from rhnPackageEVR
    where ((epoch is null and e_in is null) or (epoch = e_in)) and
          version = v_in and
          release = r_in;

    return evr_id;
exception when no_data_found then
    begin
        evr_id := insert_evr(e_in, v_in, r_in);
    exception when dup_val_on_index then
        select id
          into evr_id
          from rhnPackageEVR
        where ((epoch is null and e_in is null) or (epoch = e_in)) and
              version = v_in and
              release = r_in;
    end;

	return evr_id;
end;
/
show errors
  07070100000969000081B400000000000000000000000167AE1114000005CB000000000000000000000000000000000000007100000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/697-lookup_package_capability.sql  create or replace function insert_package_capability(name_in in varchar2, version_in in varchar2 default null)
return number
is
    pragma autonomous_transaction;
    name_id number;
begin
    insert into rhnPackageCapability (id, name, version)
        values (rhn_pkg_capability_id_seq.nextval, name_in, version_in) returning id into name_id;
    commit;
    return name_id;
end;
/

create or replace function
lookup_package_capability(name_in in varchar2, version_in in varchar2 default null)
return number
is
    name_id		number;
begin
    if version_in is null then
        select id
          into name_id
          from rhnPackageCapability
         where name = name_in and
               version is null;
    else
        select id
          into name_id
          from rhnPackageCapability
         where name = name_in and
               version = version_in;
	end if;
	return name_id;
exception when no_data_found then
    begin
        name_id := insert_package_capability(name_in, version_in);
    exception when dup_val_on_index then
        if version_in is null then
            select id
              into name_id
              from rhnPackageCapability
             where name = name_in and
                   version is null;
        else
            select id
              into name_id
              from rhnPackageCapability
             where name = name_in and
                   version = version_in;
	end if;

    end;
	return name_id;
end;
/
show errors
 0707010000096A000081B400000000000000000000000167AE111400000324000000000000000000000000000000000000006C00000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/698-lookup_package_delta.sql   create or replace function insert_package_delta(n_in in varchar2)
return number
is
    pragma autonomous_transaction;
    name_id     number;
begin
    insert into rhnPackageDelta(id, label)
    values (rhn_packagedelta_id_seq.nextval, n_in) returning id into name_id;
    commit;
    return name_id;
end;
/

create or replace function
lookup_package_delta(n_in in varchar2)
return number
is
	name_id         number;
begin
    select id
      into name_id
      from rhnpackagedelta
     where label = n_in;

	return name_id;
exception when no_data_found then
    begin
        name_id := insert_package_delta(n_in);
    exception when dup_val_on_index then
        select id
          into name_id
          from rhnPackageDelta
         where label = n_in;
    end;
	return name_id;
end;
/
show errors
0707010000096B000081B400000000000000000000000167AE111400000395000000000000000000000000000000000000006B00000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/699-lookup_package_name.sql    create or replace function insert_package_name(name_in in varchar2)
return number
is
    pragma  autonomous_transaction;
    name_id number;
begin
    insert into rhnPackageName(id, name)
    values (rhn_pkg_name_seq.nextval, name_in) returning id into name_id;
    commit;
    return name_id;
end;
/

create or replace function
lookup_package_name(name_in in varchar2, ignore_null in number := 0)
return number
is
    name_id		number;
begin
    if ignore_null = 1 and name_in is null then
        return null;
    end if;

    select id
      into name_id
      from rhnPackageName 
     where name = name_in;

    return name_id;
exception when no_data_found then
    begin
        name_id := insert_package_name(name_in);
    exception when dup_val_on_index then
        select id
          into name_id
          from rhnPackageName 
         where name = name_in;
    end;
    return name_id;
end;
/
show errors
   0707010000096C000081B400000000000000000000000167AE111400000650000000000000000000000000000000000000006C00000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/700-lookup_package_nevra.sql   create or replace function insert_package_nevra(
    name_id_in in varchar2,
    evr_id_in in varchar2,
    package_arch_id_in in varchar2
) return number
is
    pragma autonomous_transaction;
    nevra_id number;
begin
    insert into rhnPackageNEVRA(id, name_id, evr_id, package_arch_id) values
        (rhn_pkgnevra_id_seq.nextval,
         name_id_in,
         evr_id_in,
         package_arch_id_in) returning id into nevra_id;
    commit;
    return nevra_id;
end;
/
show errors

create or replace function
lookup_package_nevra(
	name_id_in in varchar2,
	evr_id_in in varchar2,
	package_arch_id_in in varchar2,
	ignore_null_name in number := 0
) return number
deterministic
is
	nevra_id number;
begin
    if ignore_null_name = 1 and name_id_in is null then
        return null;
    end if;

    select id
      into nevra_id
      from rhnPackageNEVRA
     where 1=1 and
           name_id = name_id_in and
           evr_id = evr_id_in and
           (package_arch_id = package_arch_id_in or
            (package_arch_id is null and package_arch_id_in is null));

    return nevra_id;
exception when no_data_found then
    begin
        nevra_id := insert_package_nevra(name_id_in, evr_id_in, package_arch_id_in);
    exception when dup_val_on_index then
        select id
          into nevra_id
          from rhnPackageNEVRA
         where 1=1 and
               name_id = name_id_in and
               evr_id = evr_id_in and
               (package_arch_id = package_arch_id_in or
                (package_arch_id is null and package_arch_id_in is null));
    end;
    return nevra_id;
end;
/
show errors
0707010000096D000081B400000000000000000000000167AE1114000001A3000000000000000000000000000000000000007600000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/701-lookup_snapshot_invalid_reason.sql create or replace function
lookup_snapshot_invalid_reason(label_in in varchar2)
return number
is
	snapshot_invalid_reason_id number;
begin
    select id
      into snapshot_invalid_reason_id
      from rhnsnapshotinvalidreason
     where label = label_in;

    return snapshot_invalid_reason_id;
exception when no_data_found then
    rhn_exception.raise_exception('invalid_snapshot_invalid_reason');
end;
/
show errors
 0707010000096E000081B400000000000000000000000167AE1114000005AC000000000000000000000000000000000000006A00000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/702-lookup_source_name.sql create or replace function insert_source_name(name_in in varchar2)
return number
is
    pragma autonomous_transaction;
    source_id   number;
begin
    insert into rhnSourceRPM(id, name)
    values (rhn_sourcerpm_id_seq.nextval, name_in) returning id into source_id;
    commit;
    return source_id;
end;
/
show errors
-- Copyright (c) 2008-2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.

create or replace function
lookup_source_name(name_in in varchar2)
return number
is
    source_id   number;
begin
    select id
      into source_id
      from rhnSourceRPM
     where name = name_in;

    return source_id;
exception when no_data_found then
    begin
        source_id := insert_source_name(name_in);
    exception when dup_val_on_index then
        select id
          into source_id
          from rhnSourceRPM
         where name = name_in;
    end;
    return source_id;
end;
/
show errors
0707010000096F000081B400000000000000000000000167AE1114000003E2000000000000000000000000000000000000006200000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/703-lookup_tag.sql create or replace function insert_tag(org_id_in in number, name_in in varchar2)
return number
is
    pragma autonomous_transaction;
    tag_id  number;
begin
    insert into rhnTag(id, org_id, name_id)
    values (rhn_tag_id_seq.nextval, org_id_in, lookup_tag_name(name_in)) returning id into tag_id;
    commit;
    return tag_id;
end;
/
show errors

create or replace function
lookup_tag(org_id_in in number, name_in in varchar2)
return number
is
    pragma autonomous_transaction;
    tag_id  number;
begin
    select id
      into tag_id
      from rhnTag
     where org_id = org_id_in and
           name_id = lookup_tag_name(name_in);

    return tag_id;
exception when no_data_found then
    begin
        tag_id := insert_tag(org_id_in, name_in);
    exception when dup_val_on_index then
        select id
          into tag_id
          from rhnTag
         where org_id = org_id_in and
               name_id = lookup_tag_name(name_in);
    end;
    return tag_id;
end;
/
show errors
  07070100000970000081B400000000000000000000000167AE111400000332000000000000000000000000000000000000006700000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/704-lookup_tag_name.sql    create or replace function insert_tag_name(name_in in varchar2)
return number
is
    pragma autonomous_transaction;
    name_id     number;
begin
    insert into rhnTagName(id, name)
    values (rhn_tagname_id_seq.nextval, name_in) returning id into name_id;
    commit;
    return name_id;
end;
/
show errors

create or replace function
lookup_tag_name(name_in in varchar2)
return number
is
	pragma autonomous_transaction;
	name_id     number;
begin
    select id
      into name_id
	  from rhnTagName
	 where name = name_in;

    return name_id;
exception when no_data_found then
    begin
        name_id := insert_tag_name(name_in);
    exception when dup_val_on_index then
        select id
          into name_id
    	  from rhnTagName
    	 where name = name_in;
    end;
    return name_id;
end;
/
show errors
  07070100000971000081B400000000000000000000000167AE1114000007CF000000000000000000000000000000000000007200000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/705-lookup_transaction_package.sql create or replace function insert_transaction_package(
    o_id in number,
    n_id in number,
    e_id in number,
    p_arch_id in number)
return number
is
    pragma autonomous_transaction;
    tp_id   number;
begin
    insert into rhnTransactionPackage (id, operation, name_id, evr_id, package_arch_id)
    values (rhn_transpack_id_seq.nextval, o_id, n_id, e_id, p_arch_id) returning id into tp_id;
    commit;
    return tp_id;
end;
/
show errors

create or replace function
lookup_transaction_package(
    o_in in varchar2,
    n_in in varchar2,
    e_in in varchar2,
    v_in in varchar2,
    r_in in varchar2,
    a_in in varchar2)
return number
is
    pragma autonomous_transaction;
    o_id        number;
    n_id        number;
    e_id        number;
    p_arch_id   number;
    tp_id       number;
begin
    begin
        select id
          into o_id
          from rhnTransactionOperation
         where label = o_in;
    exception when no_data_found then
        rhn_exception.raise_exception('invalid_transaction_operation');
    end;

    n_id := lookup_package_name(n_in);
    e_id := lookup_evr(e_in, v_in, r_in);
    p_arch_id := null;

    if a_in is not null then
        p_arch_id := lookup_package_arch(a_in);
	end if;

    select id
      into tp_id
      from rhnTransactionPackage
     where operation = o_id and
           name_id = n_id and
           evr_id = e_id and
           (package_arch_id = p_arch_id or (p_arch_id is null and package_arch_id is null));
    return tp_id;
exception when no_data_found then
    begin
        tp_id := insert_transaction_package(o_id, n_id, e_id, p_arch_id);
    exception when dup_val_on_index then
        select id
          into tp_id
          from rhnTransactionPackage
         where operation = o_id and
               name_id = n_id and
               evr_id = e_id and
               (package_arch_id = p_arch_id or (p_arch_id is null and package_arch_id is null));       
    end;
    return tp_id;
end;
/
show errors
 07070100000972000081B400000000000000000000000167AE1114000000B0000000000000000000000000000000000000006D00000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/705-rhnUserGroupType_data.sql  DELETE FROM rhnUserGroupType WHERE label = 'coma_admin';
DELETE FROM rhnUserGroupType WHERE label = 'coma_author';
DELETE FROM rhnUserGroupType WHERE label = 'coma_publisher';
07070100000973000081B400000000000000000000000167AE11140000044E000000000000000000000000000000000000006E00000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/706-lookup_xccdf_benchmark.sql create or replace function insert_xccdf_benchmark(identifier_in in varchar2, version_in in varchar2)
return number
is
    pragma autonomous_transaction;
    benchmark_id    number;
begin
    insert into rhnXccdfBenchmark (id, identifier, version)
    values (rhn_xccdf_benchmark_id_seq.nextval, identifier_in, version_in) returning id into benchmark_id;
    commit;
    return benchmark_id;
end;
/
show errors

create or replace function
lookup_xccdf_benchmark(identifier_in in varchar2, version_in in varchar2)
return number
is
    benchmark_id    number;
begin
    select id
      into benchmark_id
      from rhnXccdfBenchmark
     where identifier = identifier_in and version = version_in;
    return benchmark_id;
exception when no_data_found then
    begin
        benchmark_id := insert_xccdf_benchmark(identifier_in, version_in);
    exception when dup_val_on_index then
        select id
          into benchmark_id
          from rhnXccdfBenchmark
         where identifier = identifier_in and version = version_in;
    end;
    return benchmark_id;
end lookup_xccdf_benchmark;
/
show errors
  07070100000974000081B400000000000000000000000167AE1114000007A2000000000000000000000000000000000000006A00000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/707-lookup_xccdf_ident.sql create or replace function insert_xccdf_ident_system(system_in varchar2)
return number
is
    pragma autonomous_transaction;
    ident_sys_id number;
begin
    insert into rhnXccdfIdentSystem (id, system)
    values (rhn_xccdf_identsytem_id_seq.nextval, system_in) returning id into ident_sys_id;
    commit;
    return ident_sys_id;
end;
/
show errors

create or replace function insert_xccdf_ident(ident_sys_id number, identifier_in in varchar2)
return number
is
    pragma autonomous_transaction;
    xccdf_ident_id  number;
begin
    insert into rhnXccdfIdent (id, identsystem_id, identifier)
    values (rhn_xccdf_ident_id_seq.nextval, ident_sys_id, identifier_in) returning id into xccdf_ident_id;
    commit;
    return xccdf_ident_id;
end;
/

create or replace function
lookup_xccdf_ident(system_in in varchar2, identifier_in in varchar2)
return number
is
    pragma autonomous_transaction;
    xccdf_ident_id number;
    ident_sys_id number;
begin
    begin
        select id
          into ident_sys_id
          from rhnXccdfIdentSystem
         where system = system_in;
    exception when no_data_found then
        begin
            ident_sys_id := insert_xccdf_ident_system(system_in);
        exception when dup_val_on_index then
            select id
              into ident_sys_id
              from rhnXccdfIdentSystem
             where system = system_in;
        end;
    end;

    select id
      into xccdf_ident_id
      from rhnXccdfIdent
     where identsystem_id = ident_sys_id and identifier = identifier_in;
    return xccdf_ident_id;
exception when no_data_found then
    begin
        xccdf_ident_id := insert_xccdf_ident(ident_sys_id, identifier_in);
    exception when dup_val_on_index then
        select id
          into xccdf_ident_id
          from rhnXccdfIdent
         where identsystem_id = ident_sys_id and identifier = identifier_in;
    end;
    return xccdf_ident_id;
end lookup_xccdf_ident;
/
show errors
  07070100000975000081B400000000000000000000000167AE111400000416000000000000000000000000000000000000006C00000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/708-lookup_xccdf_profile.sql   create or replace function
insert_xccdf_profile(identifier_in in varchar2, title_in in varchar2)
return number
is
    pragma autonomous_transaction;
    profile_id  number;
begin
    insert into rhnXccdfProfile (id, identifier, title)
    values (rhn_xccdf_profile_id_seq.nextval, identifier_in, title_in) returning id into profile_id;
    commit;
    return profile_id;
end;
/
show errors

create or replace function
lookup_xccdf_profile(identifier_in in varchar2, title_in in varchar2)
return number
is
    profile_id  number;
begin
    select id
      into profile_id
      from rhnXccdfProfile
     where identifier = identifier_in and title = title_in;
    return profile_id;
exception when no_data_found then
    begin
        profile_id := insert_xccdf_profile(identifier_in, title_in);
    exception when dup_val_on_index then
        select id
          into profile_id
          from rhnXccdfProfile
         where identifier = identifier_in and title = title_in;
    end;
    return profile_id;
end lookup_xccdf_profile;
/
show errors
  07070100000976000081B400000000000000000000000167AE1114000006A6000000000000000000000000000000000000006A00000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/711-rhnPackageKey-data.sql --
-- Copyright (c) 2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

-- Fedora 16, 17, 18
update rhnPackageKey set provider_id = lookup_package_provider('Fedora')
where key_id in ('067f00b6a82ba4b7', '50e94c991aca3465', '0983129322b3b81a');

-- Fedora 16
insert into rhnPackageKey (id, key_id, key_type_id, provider_id)
select sequence_nextval('rhn_pkey_id_seq'), '067f00b6a82ba4b7', lookup_package_key_type('gpg'), lookup_package_provider('Fedora')
from dual
where not exists ( select 1 from rhnPackageKey where key_id = '067f00b6a82ba4b7' );
-- Fedora 17
insert into rhnPackageKey (id, key_id, key_type_id, provider_id)
select sequence_nextval('rhn_pkey_id_seq'), '50e94c991aca3465', lookup_package_key_type('gpg'), lookup_package_provider('Fedora')
from dual
where not exists ( select 1 from rhnPackageKey where key_id = '50e94c991aca3465' );
-- Fedora 18
insert into rhnPackageKey (id, key_id, key_type_id, provider_id)
select sequence_nextval('rhn_pkey_id_seq'), '0983129322b3b81a', lookup_package_key_type('gpg'), lookup_package_provider('Fedora')
from dual
where not exists ( select 1 from rhnPackageKey where key_id = '0983129322b3b81a' );

  07070100000977000081B400000000000000000000000167AE1114000003BD000000000000000000000000000000000000006400000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/803-rhn_user.pks.sql   create or replace
package rhn_user
is
	version varchar2(100) := '';

    function check_role(user_id_in in number, role_in in varchar2) return number;
    PRAGMA RESTRICT_REFERENCES(check_role, WNDS, RNPS, WNPS);

    function check_role_implied(user_id_in in number, role_in in varchar2) return number;
    PRAGMA RESTRICT_REFERENCES(check_role_implied, WNDS, RNPS, WNPS);

    function get_org_id(user_id_in in number) return number;
    PRAGMA RESTRICT_REFERENCES(get_org_id, WNDS, RNPS, WNPS);

	procedure add_servergroup_perm(
		user_id_in in number,
		server_group_id_in in number
	);

	procedure remove_servergroup_perm(
		user_id_in in number,
		server_group_id_in in number
	);

	procedure add_to_usergroup(
		user_id_in in number,
		user_group_id_in in number
	);

	procedure remove_from_usergroup(
		user_id_in in number,
		user_group_id_in in number
	);

	function role_names (user_id_in in number) return varchar2;

end rhn_user;
/
SHOW ERRORS
   07070100000978000081B400000000000000000000000167AE1114000001BC000000000000000000000000000000000000006E00000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/802-rhn_contact_monitoring.sql drop view rhn_contact_monitoring;
create or replace view rhn_contact_monitoring as
select	u.id			as recid,
	u.org_id		as customer_id,
	wupi.last_name		as contact_last_name,
	wupi.first_names	as contact_first_name,
	wupi.email          as email_address,
	u.login			as username,
	u.password		as password,
	1			as schedule_id,
	'GMT' || ''			as preferred_time_zone
from
	web_user_personal_info wupi,
	web_contact u
where	u.id = wupi.web_user_id
;
07070100000979000081B400000000000000000000000167AE1114000013D9000000000000000000000000000000000000006400000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/804-rhn_user.pkb.sql   --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

create or replace
package body rhn_user
is
	body_version varchar2(100) := '';

    function check_role(user_id_in in number, role_in in varchar2)
    return number
    is
	throwaway number;
    begin
	-- the idea: if we get past this query, the org has the setting, else catch the exception and return 0
	select 1 into throwaway
	  from rhnUserGroupType UGT,
	       rhnUserGroup UG,
	       rhnUserGroupMembers UGM
	 where UGM.user_id = user_id_in
	   and UGM.user_group_id = UG.id
	   and UG.group_type = UGT.id
	   and UGT.label = role_in;

	return 1;
    exception
	when no_data_found
	    then
	    return 0;
    end check_role;

    function check_role_implied(user_id_in in number, role_in in varchar2)
    return number
    is
	throwaway number;
    begin
	-- if the user directly has the role, they win
	if rhn_user.check_role(user_id_in, role_in) = 1
	then
	    return 1;
	end if;

	-- config_admin and channel_admin are automatically implied for org admins
	if role_in = 'config_admin' and rhn_user.check_role(user_id_in, 'org_admin') = 1
	then
	    return 1;
	end if;

	if role_in = 'channel_admin' and rhn_user.check_role(user_id_in, 'org_admin') = 1
	then
	    return 1;
	end if;

	return 0;
    end check_role_implied;

    function get_org_id(user_id_in in number)
    return number
    is
	org_id_out number;
    begin
	select org_id into org_id_out
	  from web_contact
	 where id = user_id_in;

	return org_id_out;
    end get_org_id;

	procedure add_servergroup_perm(
		user_id_in in number,
		server_group_id_in in number
	) is
		cursor	orgs_match is
			select	1
			from	rhnServerGroup sg,
					web_contact u
			where	u.id = user_id_in
				and sg.id = server_group_id_in
				and sg.org_id = u.org_id;
	begin
		for okay in orgs_match loop
			insert into rhnUserServerGroupPerms(user_id, server_group_id)
				values (user_id_in, server_group_id_in);
			rhn_cache.update_perms_for_user(user_id_in);
			return;
		end loop;
		rhn_exception.raise_exception('usgp_different_orgs');
	exception when dup_val_on_index then
		rhn_exception.raise_exception('usgp_already_allowed');
	end add_servergroup_perm;

	procedure remove_servergroup_perm(
		user_id_in in number,
		server_group_id_in in number
	) is
		cursor perms is
			select	1
			from	rhnUserServerGroupPerms
			where	user_id = user_id_in
				and server_group_id = server_group_id_in;
	begin
		for perm in perms loop
			delete from rhnUserServerGroupPerms
				where	user_id = user_id_in
					and server_group_id = server_group_id_in;
			rhn_cache.update_perms_for_user(user_id_in);
			return;
		end loop;
		rhn_exception.raise_exception('usgp_not_allowed');
	end remove_servergroup_perm;

	procedure add_to_usergroup(
		user_id_in in number,
		user_group_id_in in number
	) is
		cursor perm_granting_usergroups is
			select	user_group_id_in
			from	rhnUserGroup		ug,
					rhnUserGroupType	ugt
			where	ugt.label in ('org_admin') -- and server_group_admin ?
				and ug.id = user_group_id_in
				and ug.group_type = ugt.id;
	begin
		insert into rhnUserGroupMembers(user_id, user_group_id)
			values (user_id_in, user_group_id_in);

		for ug in perm_granting_usergroups loop
			rhn_cache.update_perms_for_user(user_id_in);
			return;
		end loop;
	end add_to_usergroup;

	procedure remove_from_usergroup(
		user_id_in in number,
		user_group_id_in in number
	) is
		cursor perm_granting_usergroups is
			select	label
			from	rhnUserGroupType	ugt,
					rhnUserGroupMembers	ugm,
					rhnUserGroup		ug
			where	1=1
				and ug.id = user_group_id_in
				and ugm.user_group_id = user_group_id_in
				and ug.group_type = ugt.id
				and ugm.user_id = user_id_in;
	begin
		-- we only do anything if you're really in the group, because
		-- testing is significantly cheaper than rebuilding the user's
		-- cache for no reason.
		for ug in perm_granting_usergroups loop
			delete from rhnUserGroupMembers
				where	user_id = user_id_in
					and user_group_id = user_group_id_in;
			if ug.label in ('org_admin') then
				rhn_cache.update_perms_for_user(user_id_in);
			end if;
		end loop;
	end remove_from_usergroup;

	function role_names (user_id_in in number)
	return varchar2
	is
		tmp varchar2(4000);
	begin
		for rec in (
			select type_name
			from rhnUserTypeBase
			where user_id = user_id_in
			order by type_id
			) loop
			if tmp is null then
				tmp := rec.type_name;
			else
				tmp := tmp || ', ' || rec.type_name;
			end if;
		end loop;
		return tmp;
	end;

end rhn_user;
/
SHOW ERRORS
   0707010000097A000081B400000000000000000000000167AE111400000083000000000000000000000000000000000000006C00000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/805-rhnEmailAddress_drop.sql   drop table rhnEmailAddress;
drop sequence rhn_eaddress_id_seq;

drop table rhnEmailAddressState;
drop sequence rhn_eastate_id_seq;
 0707010000097B000081B400000000000000000000000167AE11140000030C000000000000000000000000000000000000006B00000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/806-pxt_session_cleanup.sql    create or replace procedure pxt_session_cleanup (
    bound_in in number,
    commit_interval in number := 100,
    batch_size in number := 50000,
    sessions_deleted in out number)
is
    cursor sessions (bound_val in number) is
        select rowid
          from pxtsessions
         where expires < bound_val;

    counter number := 0;
begin
   for session in sessions (bound_in) loop
       delete
         from pxtsessions
        where rowid = session.rowid;

       counter := counter + 1;
       if mod(counter, commit_interval) = 0 then
           commit;
       end if;

       if counter >= batch_size then
           commit;
           sessions_deleted := counter;
           return;
       end if;
    end loop;

    commit;
    sessions_deleted := counter;
end;
/
0707010000097C000081B400000000000000000000000167AE1114000000E0000000000000000000000000000000000000006D00000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/810-rhn_config-tableowner.sql  delete from rhn_config_parameter where group_name='cf_db' and name='tableowner';
delete from rhn_config_parameter where group_name='cs_db' and name='tableowner';
delete from rhn_config_macro where name='RHN_DB_TABLE_OWNER';
0707010000097D000081B400000000000000000000000167AE11140000016D000000000000000000000000000000000000006E00000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/811-rhn-config-rhn_db_name.sql delete from rhn_config_macro where name='CFDB_NAME';
delete from rhn_config_macro where name='CSDB_NAME';
delete from rhn_config_macro where name='RHN_DB_NAME';
delete from rhn_config_macro where name='SCDB_NAME';

delete from rhn_config_parameter where group_name='cf_db' and name='name';
delete from rhn_config_parameter where group_name='cs_db' and name='name';
   0707010000097E000081B400000000000000000000000167AE1114000002DC000000000000000000000000000000000000007000000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/812-rhn-config-rhn_db_passwd.sql   delete from rhn_config_macro where name='CFDB_NOTIF_PASSWD';
delete from rhn_config_macro where name='CFDB_PASSWD';
delete from rhn_config_macro where name='RHN_DB_PASSWD';
delete from rhn_config_macro where name='CSDB_PASSWD';

delete from rhn_config_parameter where group_name='cf_db' and name='password';
delete from rhn_config_parameter where group_name='cf_db' and name='portal_password';
delete from rhn_config_parameter where group_name='cf_db' and name='proxy_password';
delete from rhn_config_parameter where group_name='cf_db' and name='ui_password';
delete from rhn_config_parameter where group_name='cf_db' and name='notification_password';
delete from rhn_config_parameter where group_name='cs_db' and name='password';
0707010000097F000081B400000000000000000000000167AE111400000233000000000000000000000000000000000000007200000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/813-rhn-config-rhn_db_username.sql delete from rhn_config_macro where name='RHN_DB_USERNAME';

delete from rhn_config_parameter where group_name='cf_db' and name='notification_username';
delete from rhn_config_parameter where group_name='cf_db' and name='portal_username';
delete from rhn_config_parameter where group_name='cf_db' and name='proxy_username';
delete from rhn_config_parameter where group_name='cf_db' and name='ui_username';
delete from rhn_config_parameter where group_name='cf_db' and name='username';
delete from rhn_config_parameter where group_name='cs_db' and name='username';
 07070100000980000081B400000000000000000000000167AE111400000331000000000000000000000000000000000000006700000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/814-rhnChecksumView.sql    --
-- Copyright (c) 2009 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--

create or replace view rhnChecksumView 
as
select c.id,
       ct.label checksum_type,
       c.checksum
  from rhnChecksum c
  left join rhnChecksumType ct
    on c.checksum_type_id = ct.id;

   07070100000981000081B400000000000000000000000167AE11140000003C000000000000000000000000000000000000006500000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/816-rhnXccdfIdent.sql  
ALTER TABLE rhnXccdfIdent MODIFY identifier VARCHAR2(100);
07070100000982000081B400000000000000000000000167AE11140000015E000000000000000000000000000000000000006A00000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/817-rhnXccdfRuleresult.sql 
ALTER TABLE rhnXccdfRuleresult ADD id NUMBER;

CREATE SEQUENCE rhn_xccdf_rresult_id_seq;

UPDATE rhnXccdfRuleresult SET id = rhn_xccdf_rresult_id_seq.nextval;

ALTER TABLE rhnXccdfRuleresult MODIFY id NUMBER NOT NULL;

ALTER TABLE rhnXccdfRuleresult
    ADD CONSTRAINT rhn_xccdf_rresult_id_pk PRIMARY KEY (id)
    USING INDEX TABLESPACE [[8m_tbs]];
  07070100000983000081B400000000000000000000000167AE11140000021A000000000000000000000000000000000000006C00000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/818-rhnXccdfRuleIdentMap.sql   
CREATE TABLE rhnXccdfRuleIdentMap
(
    rresult_id    NUMBER NOT NULL
                      CONSTRAINT rhn_xccdf_rim_rresult_fk
                          REFERENCES rhnXccdfRuleresult (id)
                          ON DELETE CASCADE,
    ident_id      NUMBER NOT NULL
                      CONSTRAINT rhn_xccdf_rim_ident_fk
                          REFERENCES rhnXccdfIdent (id)
)
ENABLE ROW MOVEMENT
;

CREATE UNIQUE INDEX rhn_xccdf_rim_ri_uq
    ON rhnXccdfRuleIdentMap (rresult_id, ident_id)
    TABLESPACE [[8m_tbs]]
    NOLOGGING;
  07070100000984000081B400000000000000000000000167AE11140000008B000000000000000000000000000000000000007100000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/819-rhnXccdfRuleIdentMap_data.sql  
INSERT INTO rhnXccdfRuleIdentMap
    (rresult_id, ident_id)
    SELECT xrr.id, xrr.ident_id
        FROM rhnXccdfRuleresult xrr;

COMMIT;
 07070100000985000081B400000000000000000000000167AE111400000036000000000000000000000000000000000000006A00000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/820-rhnXccdfRuleresult.sql 
ALTER TABLE rhnXccdfRuleresult DROP COLUMN ident_id;
  07070100000986000081B400000000000000000000000167AE111400000059000000000000000000000000000000000000007200000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/821-rhn_command-check_log_size.sql 
update rhn_command set description = 'Log Size Growth' where name = 'check_log_size' ;

   07070100000987000081B400000000000000000000000167AE111400000095000000000000000000000000000000000000007A00000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/822-rhnPackageUpgradeArchCompat-unique.sql 
drop index rhn_puac_pa_pua;
create unique index rhn_puac_pa_pua_uq
     on rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id);

   07070100000988000081B400000000000000000000000167AE111400000B78000000000000000000000000000000000000007600000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/823-rhn_schedule_days-to_timestamp.sql 
update rhn_schedule_days
set start_1 = to_timestamp('2000-09-08 12:00:02 AM','YYYY-MM-DD HH:MI:SS AM')
where schedule_id = ( select recid from rhn_schedules where customer_id is null and description = '24x7' )
and ord = 0
	and end_1 = to_timestamp('2000-09-09 12:00:00 AM','YYYY-MM-DD HH:MI:SS AM')
	and start_2 is null and end_2 is null
	and start_3 is null and end_3 is null
	and start_4 is null and end_4 is null;

update rhn_schedule_days
set start_1 = to_timestamp('2000-09-08 12:00:09 AM','YYYY-MM-DD HH:MI:SS AM')
where schedule_id = ( select recid from rhn_schedules where customer_id is null and description = '24x7' )
and ord = 1
	and end_1 = to_timestamp('2000-09-09 12:00:00 AM','YYYY-MM-DD HH:MI:SS AM')
	and start_2 is null and end_2 is null
	and start_3 is null and end_3 is null
	and start_4 is null and end_4 is null;

update rhn_schedule_days
set start_1 = to_timestamp('2000-09-08 12:00:14 AM','YYYY-MM-DD HH:MI:SS AM')
where schedule_id = ( select recid from rhn_schedules where customer_id is null and description = '24x7' )
and ord = 2
	and end_1 = to_timestamp('2000-09-09 12:00:00 AM','YYYY-MM-DD HH:MI:SS AM')
	and start_2 is null and end_2 is null
	and start_3 is null and end_3 is null
	and start_4 is null and end_4 is null;

update rhn_schedule_days
set start_1 = to_timestamp('2000-09-08 12:00:20 AM','YYYY-MM-DD HH:MI:SS AM')
where schedule_id = ( select recid from rhn_schedules where customer_id is null and description = '24x7' )
and ord = 3
	and end_1 = to_timestamp('2000-09-09 12:00:00 AM','YYYY-MM-DD HH:MI:SS AM')
	and start_2 is null and end_2 is null
	and start_3 is null and end_3 is null
	and start_4 is null and end_4 is null;

update rhn_schedule_days
set start_1 = to_timestamp('2000-09-08 12:00:25 AM','YYYY-MM-DD HH:MI:SS AM')
where schedule_id = ( select recid from rhn_schedules where customer_id is null and description = '24x7' )
and ord = 4
	and end_1 = to_timestamp('2000-09-09 12:00:00 AM','YYYY-MM-DD HH:MI:SS AM')
	and start_2 is null and end_2 is null
	and start_3 is null and end_3 is null
	and start_4 is null and end_4 is null;

update rhn_schedule_days
set start_1 = to_timestamp('2000-09-08 12:00:31 AM','YYYY-MM-DD HH:MI:SS AM')
where schedule_id = ( select recid from rhn_schedules where customer_id is null and description = '24x7' )
and ord = 5
	and end_1 = to_timestamp('2000-09-09 12:00:00 AM','YYYY-MM-DD HH:MI:SS AM')
	and start_2 is null and end_2 is null
	and start_3 is null and end_3 is null
	and start_4 is null and end_4 is null;

update rhn_schedule_days
set start_1 = to_timestamp('2000-09-08 12:00:36 AM','YYYY-MM-DD HH:MI:SS AM')
where schedule_id = ( select recid from rhn_schedules where customer_id is null and description = '24x7' )
and ord = 6
	and end_1 = to_timestamp('2000-09-09 12:00:00 AM','YYYY-MM-DD HH:MI:SS AM')
	and start_2 is null and end_2 is null
	and start_3 is null and end_3 is null
	and start_4 is null and end_4 is null;

commit;

07070100000989000081B400000000000000000000000167AE111400000075000000000000000000000000000000000000006600000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/834-rhnChannelArch.sql ALTER TABLE rhnChannelArch
    ADD CONSTRAINT rhn_carch_name_uq UNIQUE (name)
    USING INDEX TABLESPACE [[2m_tbs]];
   0707010000098A000081B400000000000000000000000167AE1114000020D5000000000000000000000000000000000000006300000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/835-rhn_org.pkb.sql    --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--

CREATE OR REPLACE
PACKAGE BODY rhn_org
IS  
    procedure delete_org (
        org_id_in in number
    )
    is
        cursor users is
        select id
        from web_contact
        where org_id = org_id_in;

    cursor servers(org_id_in in number) is
        select    id
        from    rhnServer
        where    org_id = org_id_in;

        cursor config_channels is
        select id
        from rhnConfigChannel
        where org_id = org_id_in;

    cursor custom_channels is
        select    id
        from    rhnChannel
        where    org_id = org_id_in;

    cursor errata is
        select    id
        from    rhnErrata
        where    org_id = org_id_in;

    begin

        if org_id_in = 1 then
            rhn_exception.raise_exception('cannot_delete_base_org');
        end if;

        -- Delete all users.
        for u in users loop
            rhn_org.delete_user(u.id, 1);
        end loop;

        -- Delete all servers.
        for s in servers(org_id_in) loop
            delete_server(s.id);
        end loop;

        -- Delete all config channels.
        for c in config_channels loop
            rhn_config.delete_channel(c.id);
        end loop;

        -- Delete all custom channels.
        for cc in custom_channels loop
          delete from rhnServerChannel where channel_id = cc.id;
          delete from rhnServerProfilePackage where server_profile_id in (
            select id from rhnServerProfile where base_channel = cc.id
          );
          delete from rhnServerProfile where base_channel = cc.id;
        end loop;

        -- Delete all errata packages 
        for e in errata loop
            delete from rhnErrataPackage where errata_id = e.id;
        end loop;

        -- Give the org's entitlements back to the main org.
        rhn_entitlements.remove_org_entitlements(org_id_in);

        -- Clean up tables where we don't have a cascading delete.
        delete from rhnChannel where org_id = org_id_in;
        delete from rhnDailySummaryQueue where org_id = org_id_in;
        delete from rhnOrgQuota where org_id = org_id_in;
        delete from rhnFileList where org_id = org_id_in;
        delete from rhnServerGroup where org_id = org_id_in;
        delete from rhn_check_suites where customer_id = org_id_in;
        delete from rhn_command_target where customer_id = org_id_in;
        delete from rhn_contact_groups where customer_id = org_id_in;
        delete from rhn_notification_formats where customer_id = org_id_in;
        delete from rhn_probe where customer_id = org_id_in;
        delete from rhn_redirects where customer_id = org_id_in;
        delete from rhn_sat_cluster where customer_id = org_id_in;
        delete from rhn_schedules where customer_id = org_id_in;
        delete from rhnContentSource where org_id = org_id_in;

        -- Delete the org.
        delete from web_customer where id = org_id_in;

    end delete_org;

    procedure delete_user(user_id_in in number, deleting_org in number := 0) is
        cursor servergroups_needing_admins is
            select    usgp.server_group_id    server_group_id
            from    rhnUserServerGroupPerms    usgp
            where    1=1
                and usgp.user_id = user_id_in
                and not exists (
                    select    1
                    from    rhnUserServerGroupPerms    sq_usgp
                    where    1=1
                        and sq_usgp.server_group_id = usgp.server_group_id
                        and    sq_usgp.user_id != user_id_in
                );
        users            number;
        our_org_id        number;
        other_users        number;
        other_org_admin    number;
        other_user_id  number;
        is_admin       number;
    begin
        select    wc.org_id
        into    our_org_id
        from    web_contact wc
        where    id = user_id_in;

        -- find any other users
        begin
            select    id, 1
            into    other_user_id, other_users
            from    web_contact
            where    1=1
                and org_id = our_org_id
                and id != user_id_in
                and rownum = 1;
        exception
            when no_data_found then
                other_users := 0;
        end;

        -- now do org admin stuff
        if other_users != 0 then
            -- is user admin?
            select  count(1)
             into   is_admin
            from    rhnUserGroupType    ugt,
                    rhnUserGroup        ug,
                    rhnUserGroupMembers    ugm
            where    ugm.user_id = user_id_in
                and ugm.user_group_id = ug.id
                and ug.group_type = ugt.id
                and ugt.label = 'org_admin';
            if is_admin > 0 then
                begin
                    select    new_ugm.user_id
                    into    other_org_admin
                    from    rhnUserGroupMembers    new_ugm,
                            rhnUserGroupType    ugt,
                            rhnUserGroup        ug,
                            rhnUserGroupMembers    ugm
                    where    ugm.user_id = user_id_in
                        and ugm.user_group_id = ug.id
                        and ug.group_type = ugt.id
                        and ugt.label = 'org_admin'
                        and ug.id = new_ugm.user_group_id
                        and new_ugm.user_id != user_id_in
                        and rownum = 1;
                exception
                    when no_data_found then
                        -- If we're deleting the org, we don't want to raise
                        -- the exception.
                        if deleting_org = 0 then
                            rhn_exception.raise_exception('cannot_delete_user');
                        end if;
                end;

                for sg in servergroups_needing_admins loop
                    rhn_user.add_servergroup_perm(other_org_admin,
                        sg.server_group_id);
                end loop;
            end if;
        end if;

        -- and now things for every user
        delete from rhn_command_queue_sessions where contact_id = user_id_in;
        delete from rhn_contact_groups
        where recid in (
            select contact_group_id
            from rhn_contact_group_members
            where member_contact_method_id in (
                select recid from rhn_contact_methods
                where contact_id = user_id_in
                )
            )
            and not exists (
                select 1
                from rhn_contact_group_members, rhn_contact_methods
                where rhn_contact_groups.recid = rhn_contact_group_members.contact_group_id
                    and rhn_contact_group_members.member_contact_method_id = rhn_contact_methods.recid
                    and rhn_contact_methods.contact_id <> user_id_in
            );
        delete from rhn_contact_methods where contact_id = user_id_in;
        delete from rhn_redirects where contact_id = user_id_in;
        delete from rhnUserServerPerms where user_id = user_id_in;
        update rhnConfigRevision
           set changed_by_id = NULL
         where changed_by_id = user_id_in;
        if other_users != 0 then
            update        rhnRegToken
                set        user_id = nvl(other_org_admin, other_user_id)
                where    org_id = our_org_id
                    and user_id = user_id_in;
        end if;

        begin
            delete from web_contact where id = user_id_in;
        exception
            when others then
                rhn_exception.raise_exception('cannot_delete_user');
        end;
        return;
    end delete_user;

END rhn_org;
/
SHOW ERRORS

   0707010000098B000081B400000000000000000000000167AE11140000001E000000000000000000000000000000000000006700000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/839-time_zone_names.sql    DROP SYNONYM time_zone_names;
  0707010000098C000081B400000000000000000000000167AE111400000020000000000000000000000000000000000000006B00000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/840-rhn_time_zone_names.sql    DROP TABLE rhn_time_zone_names;
0707010000098D000081B400000000000000000000000167AE1114000000CD000000000000000000000000000000000000006C00000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/841-rhnKickstartableTree.sql   ALTER TABLE rhnKickstartableTree DROP CONSTRAINT rhn_kstree_cid_fk;
ALTER TABLE rhnKickstartableTree ADD CONSTRAINT rhn_kstree_cid_fk FOREIGN KEY (channel_id) REFERENCES rhnChannel (id) ON DELETE CASCADE;
   0707010000098E000081B400000000000000000000000167AE1114000015CB000000000000000000000000000000000000006600000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/842-rhn_config.pkb.sql create or replace package body
rhn_config
is
	-- just a stub for now
	procedure prune_org_configs (
		org_id_in in number,
		total_in in number
	) is
	begin
		null;
	end prune_org_configs;

	function insert_revision (
		revision_in in number,
		config_file_id_in in number,
		config_content_id_in in number,
		config_info_id_in in number,
      config_file_type_id_in in number := 1
	) return number is
		retval number;

	begin
      
		insert into rhnConfigRevision(id, revision, config_file_id,
				config_content_id, config_info_id, config_file_type_id
			) values (
				rhn_confrevision_id_seq.nextval, revision_in, config_file_id_in,
				config_content_id_in, config_info_id_in, config_file_type_id_in
			)
			returning id into retval;

		return retval;
	end insert_revision;

	procedure delete_revision (
		config_revision_id_in in number,
		org_id_in in number := -1
	) is
		cfid number;
		ccid number;
		oid number;
		latest_crid number;
		others number := 0;
		cursor snapshots is
			select	scr.snapshot_id id
			from	rhnSnapshot s,
					rhnSnapshotConfigRevision scr
			where	scr.config_revision_id = config_revision_id_in
					and scr.snapshot_id = s.id
					and s.invalid is null;
		cursor other_revisions(config_content_id_in in number) is
			select	1
			from	rhnConfigRevision
			where	config_content_id = config_content_id_in;
	begin
		for snapshot in snapshots loop
			update		rhnSnapshot s
				set		s.invalid =
							lookup_snapshot_invalid_reason('cr_removed')
				where	s.id = snapshot.id;
		end loop;

		if org_id_in < 0 then
			select	cr.config_content_id, cc.org_id
			into	ccid, oid
			from	rhnConfigChannel cc,
					rhnConfigFile cf,
					rhnConfigRevision cr
			where	cr.id = config_revision_id_in
				and cr.config_file_id = cf.id
				and cf.config_channel_id = cc.id;
		else
			select	cr.config_content_id, org_id_in
			into	ccid, oid
			from	rhnConfigRevision cr
			where	cr.id = config_revision_id_in;
		end if;

		-- right now this will set rhnActionConfigFileName.config_revision_id
		-- to null, and will remove an entry from rhnActionConfigRevision.
		-- might we want to prune and/or kill the action in some way?  maybe
		-- mark it failed or something?
		delete from rhnConfigRevision where id = config_revision_id_in;

		-- now prune away content if there aren't any other revisions pointing
		-- at it
		for other_revision in other_revisions(ccid) loop
			others := 1;
			exit;
		end loop;
		if others = 0 then
			delete from rhnConfigContent where id = ccid;
		end if;

		-- now make sure rhnConfigFile points at a valid revision;
		-- if there isn't one, we're deleting it, _unless_ org_id_in is
		-- >= 0, in which case we're in the delete trigger anyway
		if org_id_in < 0 then
			select	cf.latest_config_revision_id,
					cf.id
			into	latest_crid,
					cfid
			from	rhnConfigFile cf,
					rhnConfigRevision cr
			where	cr.id = config_revision_id_in
				and cr.config_file_id = cf.id;

			if latest_crid = config_revision_id_in then
				latest_crid := rhn_config.get_latest_revision(cfid);
				if latest_crid is not null then
					update rhnConfigFile set latest_config_revision_id = latest_crid
						where id = cfid;
				else
					delete from rhnConfigFile where id = cfid;
				end if;
			end if;

		end if;
	end delete_revision;

	function get_latest_revision (
		config_file_id_in in number
	) return number is
		cursor revisions is
			select	cr.id
			from	rhnConfigRevision cr
			where	cr.config_file_id = config_file_id_in
			order by revision desc;
	begin
		for revision in revisions loop
			return revision.id;
		end loop;
		return null;
	end get_latest_revision;

	function insert_file (
		config_channel_id_in in number,
		name_in in varchar2
	) return number is
		retval number;
	begin
		select	rhn_conffile_id_seq.nextval
		into	retval
		from	dual;

		insert into rhnConfigFile(id, config_channel_id, config_file_name_id, 
				state_id
			) (
				select	retval,
						config_channel_id_in,
						lookup_config_filename(name_in),
						id
				from	rhnConfigFileState
				where	label = 'alive'
			);

		return retval;
	end insert_file;

	procedure delete_file (
		config_file_id_in in number
	) is
		cursor revisions is
			select	cr.id, cc.org_id
			from	rhnConfigChannel cc,
					rhnConfigRevision cr,
					rhnConfigFile cf
			where	cf.id = config_file_id_in
				and cf.config_channel_id = cc.id
				and cr.config_file_id = cf.id;
		org_id number;
	begin
		for revision in revisions loop
			rhn_config.delete_revision(revision.id, revision.org_id);
			org_id := revision.org_id;
		end loop;
		delete from rhnConfigFile where id = config_file_id_in;
	end delete_file;

	function insert_channel (
		org_id_in in number,
		type_in in varchar2,
		name_in in varchar2,
		label_in in varchar2,
		description_in in varchar2
	) return number is
		retval number;
	begin
		select	rhn_confchan_id_seq.nextval
		into	retval
		from	dual;

		insert into rhnConfigChannel(id, org_id, confchan_type_id,
				name, label, description
			) (
				select	retval,
						org_id_in,
						cct.id,
						name_in,
						label_in,
						description_in
				from	rhnConfigChannelType cct
				where	label = type_in
			);
		return retval;
	end insert_channel;

	procedure delete_channel (
		config_channel_id_in in number
	) is
		cursor config_files is
			select	id
			from	rhnConfigFile
			where	config_channel_id = config_channel_id_in;
	begin
		for config_file in config_files loop
			rhn_config.delete_file(config_file.id);
		end loop;
		delete from rhnConfigChannel where id = config_channel_id_in;
	end delete_channel;
end rhn_config;
/
show errors

 0707010000098F000081B400000000000000000000000167AE111400000018000000000000000000000000000000000000006100000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/843-rhn_quota.sql  DROP PACKAGE rhn_quota;
07070100000990000081B400000000000000000000000167AE111400001E1C000000000000000000000000000000000000006300000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/844-rhn_org.pkb.sql    CREATE OR REPLACE
PACKAGE BODY rhn_org
IS  
    procedure delete_org (
        org_id_in in number
    )
    is
        cursor users is
        select id
        from web_contact
        where org_id = org_id_in;

    cursor servers(org_id_in in number) is
        select    id
        from    rhnServer
        where    org_id = org_id_in;

        cursor config_channels is
        select id
        from rhnConfigChannel
        where org_id = org_id_in;

    cursor custom_channels is
        select    id
        from    rhnChannel
        where    org_id = org_id_in;

    cursor errata is
        select    id
        from    rhnErrata
        where    org_id = org_id_in;

    begin

        if org_id_in = 1 then
            rhn_exception.raise_exception('cannot_delete_base_org');
        end if;

        -- Delete all users.
        for u in users loop
            rhn_org.delete_user(u.id, 1);
        end loop;

        -- Delete all servers.
        for s in servers(org_id_in) loop
            delete_server(s.id);
        end loop;

        -- Delete all config channels.
        for c in config_channels loop
            rhn_config.delete_channel(c.id);
        end loop;

        -- Delete all custom channels.
        for cc in custom_channels loop
          delete from rhnServerChannel where channel_id = cc.id;
          delete from rhnServerProfilePackage where server_profile_id in (
            select id from rhnServerProfile where base_channel = cc.id
          );
          delete from rhnServerProfile where base_channel = cc.id;
        end loop;

        -- Delete all errata packages 
        for e in errata loop
            delete from rhnErrataPackage where errata_id = e.id;
        end loop;

        -- Give the org's entitlements back to the main org.
        rhn_entitlements.remove_org_entitlements(org_id_in);

        -- Clean up tables where we don't have a cascading delete.
        delete from rhnChannel where org_id = org_id_in;
        delete from rhnDailySummaryQueue where org_id = org_id_in;
        delete from rhnFileList where org_id = org_id_in;
        delete from rhnServerGroup where org_id = org_id_in;
        delete from rhn_check_suites where customer_id = org_id_in;
        delete from rhn_command_target where customer_id = org_id_in;
        delete from rhn_contact_groups where customer_id = org_id_in;
        delete from rhn_notification_formats where customer_id = org_id_in;
        delete from rhn_probe where customer_id = org_id_in;
        delete from rhn_redirects where customer_id = org_id_in;
        delete from rhn_sat_cluster where customer_id = org_id_in;
        delete from rhn_schedules where customer_id = org_id_in;
        delete from rhnContentSource where org_id = org_id_in;

        -- Delete the org.
        delete from web_customer where id = org_id_in;

    end delete_org;

    procedure delete_user(user_id_in in number, deleting_org in number := 0) is
        cursor servergroups_needing_admins is
            select    usgp.server_group_id    server_group_id
            from    rhnUserServerGroupPerms    usgp
            where    1=1
                and usgp.user_id = user_id_in
                and not exists (
                    select    1
                    from    rhnUserServerGroupPerms    sq_usgp
                    where    1=1
                        and sq_usgp.server_group_id = usgp.server_group_id
                        and    sq_usgp.user_id != user_id_in
                );
        users            number;
        our_org_id        number;
        other_users        number;
        other_org_admin    number;
        other_user_id  number;
        is_admin       number;
    begin
        select    wc.org_id
        into    our_org_id
        from    web_contact wc
        where    id = user_id_in;

        -- find any other users
        begin
            select    id, 1
            into    other_user_id, other_users
            from    web_contact
            where    1=1
                and org_id = our_org_id
                and id != user_id_in
                and rownum = 1;
        exception
            when no_data_found then
                other_users := 0;
        end;

        -- now do org admin stuff
        if other_users != 0 then
            -- is user admin?
            select  count(1)
             into   is_admin
            from    rhnUserGroupType    ugt,
                    rhnUserGroup        ug,
                    rhnUserGroupMembers    ugm
            where    ugm.user_id = user_id_in
                and ugm.user_group_id = ug.id
                and ug.group_type = ugt.id
                and ugt.label = 'org_admin';
            if is_admin > 0 then
                begin
                    select    new_ugm.user_id
                    into    other_org_admin
                    from    rhnUserGroupMembers    new_ugm,
                            rhnUserGroupType    ugt,
                            rhnUserGroup        ug,
                            rhnUserGroupMembers    ugm
                    where    ugm.user_id = user_id_in
                        and ugm.user_group_id = ug.id
                        and ug.group_type = ugt.id
                        and ugt.label = 'org_admin'
                        and ug.id = new_ugm.user_group_id
                        and new_ugm.user_id != user_id_in
                        and rownum = 1;
                exception
                    when no_data_found then
                        -- If we're deleting the org, we don't want to raise
                        -- the exception.
                        if deleting_org = 0 then
                            rhn_exception.raise_exception('cannot_delete_user');
                        end if;
                end;

                for sg in servergroups_needing_admins loop
                    rhn_user.add_servergroup_perm(other_org_admin,
                        sg.server_group_id);
                end loop;
            end if;
        end if;

        -- and now things for every user
        delete from rhn_command_queue_sessions where contact_id = user_id_in;
        delete from rhn_contact_groups
        where recid in (
            select contact_group_id
            from rhn_contact_group_members
            where member_contact_method_id in (
                select recid from rhn_contact_methods
                where contact_id = user_id_in
                )
            )
            and not exists (
                select 1
                from rhn_contact_group_members, rhn_contact_methods
                where rhn_contact_groups.recid = rhn_contact_group_members.contact_group_id
                    and rhn_contact_group_members.member_contact_method_id = rhn_contact_methods.recid
                    and rhn_contact_methods.contact_id <> user_id_in
            );
        delete from rhn_contact_methods where contact_id = user_id_in;
        delete from rhn_redirects where contact_id = user_id_in;
        delete from rhnUserServerPerms where user_id = user_id_in;
        update rhnConfigRevision
           set changed_by_id = NULL
         where changed_by_id = user_id_in;
        if other_users != 0 then
            update        rhnRegToken
                set        user_id = nvl(other_org_admin, other_user_id)
                where    org_id = our_org_id
                    and user_id = user_id_in;
        end if;

        begin
            delete from web_contact where id = user_id_in;
        exception
            when others then
                rhn_exception.raise_exception('cannot_delete_user');
        end;
        return;
    end delete_user;

END rhn_org;
/
SHOW ERRORS

07070100000991000081B400000000000000000000000167AE111400000B89000000000000000000000000000000000000006800000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/845-create_first_org.sql   create or replace procedure
create_first_org
(
	name_in in varchar2,
	password_in in varchar2
) is
	ug_type			number;
	group_val		number;
begin
	insert into web_customer (
		id, name
	) values (
		1, name_in
	);

	select rhn_user_group_id_seq.nextval into group_val from dual;

	select	id
	into	ug_type
	from	rhnUserGroupType
	where	label = 'org_admin';

	insert into rhnUserGroup (
		id, name,
		description,
		max_members, group_type, org_id
	) values (
		group_val, 'Organization Administrators',
		'Organization Administrators for Org ' || name_in || ' (1)',
		NULL, ug_type, 1
	);

	select rhn_user_group_id_seq.nextval into group_val from dual;

	select	id
	into	ug_type
	from	rhnUserGroupType
	where	label = 'org_applicant';

	insert into rhnUserGroup (
		id, name,
		description,
		max_members, group_type, org_id
	) VALues (
		group_val, 'Organization Applicants',
		'Organization Applicants for Org ' || name_in || ' (1)',
		NULL, ug_type, 1
	);

	select rhn_user_group_id_seq.nextval into group_val from dual;

	select	id
	into	ug_type
	from	rhnUserGroupType
	where	label = 'system_group_admin';

	insert into rhnUserGroup (
		id, name,
		description,
		max_members, group_type, org_id
	) values (
		group_val, 'System Group Administrators',
		'System Group Administrators for Org ' || name_in || ' (1)',
		NULL, ug_type, 1
	);


	select rhn_user_group_id_seq.nextval into group_val from dual;

	select	id
	into	ug_type
	from	rhnUserGroupType
	where	label = 'activation_key_admin';

	insert into rhnUserGroup (
		id, name,
		description,
		max_members, group_type, org_id
	) values (
		group_val, 'Activation Key Administrators',
		'Activation Key Administrators for Org ' || name_in || ' (1)',
		NULL, ug_type, 1
	);

	-- config admin is special; it gets created in
	-- rhn_entitlements.set_customer_provisioning instead.
	
	select rhn_user_group_id_seq.nextval into group_val from dual;

	select	id
	into	ug_type
	from	rhnUserGroupType
	where	label = 'channel_admin';

	insert into rhnUserGroup (
		id, name,
		description,
		max_members, group_type, org_id
	) values (
		group_val, 'Channel Administrators',
		'Channel Administrators for Org ' || name_in || ' (1)',
		NULL, ug_type, 1
	);

	select rhn_user_group_id_seq.nextval into group_val from dual;

	select	id
	into	ug_type
	from	rhnUserGroupType
	where	label = 'satellite_admin';

	insert into rhnUserGroup (
		id, name,
		description,
		max_members, group_type, org_id
	) values (
		group_val, 'SUSE Manager Administrators',
		'SUSE Manager Administrators for Org ' || name_in || ' (1)',
		NULL, ug_type, 1
	);


	-- there aren't any users yet, so we don't need to update
	-- rhnUserServerPerms
        insert into rhnServerGroup 
		( id, name, description, max_members, group_type, org_id )
		select rhn_server_group_id_seq.nextval, sgt.name, sgt.name, 
			0, sgt.id, 1
		from rhnServerGroupType sgt
		where sgt.label = 'sw_mgr_entitled';
		
end create_first_org;
/
show errors;

   07070100000992000081B400000000000000000000000167AE11140000004D000000000000000000000000000000000000006C00000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/846-rhnOrgQuota-triggers.sql   DROP TRIGGER rhn_confrevision_acct_trig;
DROP TRIGGER rhn_orgquota_mod_trig;
   07070100000993000081B400000000000000000000000167AE111400000039000000000000000000000000000000000000006300000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/847-rhnOrgQuota.sql    DROP INDEX rhn_orgquota_oid_uq;
DROP TABLE rhnOrgQuota;

   07070100000994000081B400000000000000000000000167AE111400000029000000000000000000000000000000000000007700000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/850-rhn_versioninfo_nid_eid_uq-drop.sql    
drop index rhn_versioninfo_nid_eid_uq;

   07070100000995000081B400000000000000000000000167AE11140000AE50000000000000000000000000000000000000006700000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/851-rhn_channel.pkb.sql    --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

CREATE OR REPLACE
PACKAGE BODY rhn_channel
IS
        body_version varchar2(100) := '';

    -- Cursor that fetches all the possible base channels for a
    -- (server_arch_id, release, org_id) combination
        cursor  base_channel_cursor(
                release_in in varchar2,
                server_arch_id_in in number,
                org_id_in in number
        ) return rhnChannel%ROWTYPE is
                select distinct c.*
                from    rhnDistChannelMap                       dcm,
                                rhnServerChannelArchCompat      scac,
                                rhnChannel                                      c,
                                rhnChannelPermissions           cp
                where   cp.org_id = org_id_in
                        and cp.channel_id = c.id
                        and c.parent_channel is null
                        and c.id = dcm.channel_id
                        and c.channel_arch_id = dcm.channel_arch_id
                        and dcm.release = release_in
                        and scac.server_arch_id = server_arch_id_in
                        and scac.channel_arch_id = c.channel_arch_id;

    procedure obtain_read_lock(channel_family_id_in in number, org_id_in in number)
    is
        read_lock date;

    begin
        select created into read_lock
          from rhnPrivateChannelFamily
         where channel_family_id = channel_family_id_in and org_id = org_id_in
           for update;
    end obtain_read_lock;

    PROCEDURE subscribe_server(server_id_in IN NUMBER, channel_id_in NUMBER, immediate_in NUMBER := 1, user_id_in in number := null, recalcfamily_in number := 1)
    IS
        channel_parent_val      rhnChannel.parent_channel%TYPE;
        parent_subscribed       BOOLEAN;
        server_has_base_chan    BOOLEAN;
        server_already_in_chan  BOOLEAN;
        channel_family_id_val   NUMBER;
        server_org_id_val       NUMBER;
        available_subscriptions NUMBER;
        available_fve_subs      NUMBER;
        has_family_subscription NUMBER;
        consenting_user         NUMBER;
        allowed                 number := 0;
        is_fve                  CHAR(1) := 'N';
    BEGIN
        if user_id_in is not null then
            allowed := rhn_channel.user_role_check(channel_id_in, user_id_in, 'subscribe');
        else
            allowed := 1;
        end if;

        if allowed = 0 then
            rhn_exception.raise_exception('no_subscribe_permissions');
        end if;


        SELECT parent_channel INTO channel_parent_val FROM rhnChannel WHERE id = channel_id_in;

        IF channel_parent_val IS NOT NULL
        THEN
            -- child channel; if attempting to cross-subscribe a child to the wrong base, silently ignore
            parent_subscribed := FALSE;

            FOR check_subscription IN check_server_subscription(server_id_in, channel_parent_val)
            LOOP
                parent_subscribed := TRUE;
            END LOOP check_subscription;

            IF NOT parent_subscribed
            THEN
                RETURN;
            END IF;
        ELSE
            -- base channel
            server_has_base_chan := FALSE;
            FOR base IN server_base_subscriptions(server_id_in)
            LOOP
                server_has_base_chan := TRUE;
            END LOOP base;

            IF server_has_base_chan
            THEN
                rhn_exception.raise_exception('channel_server_one_base');
            END IF;
        END IF;

        FOR check_subscription IN check_server_subscription(server_id_in, channel_id_in)
        LOOP
            server_already_in_chan := TRUE;
        END LOOP check_subscription;

        IF server_already_in_chan
        THEN
            RETURN;
        END IF;

        channel_family_id_val := rhn_channel.family_for_channel(channel_id_in);
        IF channel_family_id_val IS NULL
        THEN
            rhn_exception.raise_exception('channel_subscribe_no_family');
        END IF;

        --
        -- Use the org_id of the server only if the org_id of the channel = NULL.
        -- This is required for subscribing to shared channels.
        --
        SELECT NVL(org_id, (SELECT org_id FROM rhnServer WHERE id = server_id_in))
          INTO server_org_id_val
          FROM rhnChannel
         WHERE id = channel_id_in;

        begin
            obtain_read_lock(channel_family_id_val, server_org_id_val);
        exception
            when no_data_found then
                rhn_exception.raise_exception('channel_family_no_subscriptions');
        end;

        available_subscriptions := rhn_channel.available_family_subscriptions(channel_family_id_val, server_org_id_val);
        available_fve_subs := rhn_channel.available_fve_family_subs(channel_family_id_val, server_org_id_val);
        has_family_subscription := rhn_channel.server_has_family_subscription(server_id_in, channel_family_id_val);

        IF available_subscriptions IS NULL OR
            available_subscriptions > 0 or
            can_server_consume_virt_channl(server_id_in, channel_family_id_val) = 1 OR
            (available_fve_subs > 0 AND can_server_consume_fve(server_id_in) = 1) OR
            has_family_subscription > 0
        THEN
            if can_server_consume_virt_channl(server_id_in, channel_family_id_val) = 0 AND available_fve_subs > 0 AND can_server_consume_fve(server_id_in) = 1 THEN
                is_fve := 'Y';
            END IF;
            insert into rhnServerHistory (id,server_id,summary,details) (
                select  rhn_event_id_seq.nextval,
                        server_id_in,
                        'subscribed to channel ' || SUBSTR(c.label, 0, 106),
                        c.label
                from    rhnChannel c
                where   c.id = channel_id_in
            );
            UPDATE rhnServer SET channels_changed = sysdate WHERE id = server_id_in;
            INSERT INTO rhnServerChannel (server_id, channel_id, is_fve) VALUES (server_id_in, channel_id_in, is_fve);
			IF recalcfamily_in > 0
			THEN
                rhn_channel.update_family_counts(channel_family_id_val, server_org_id_val);
			END IF;
            queue_server(server_id_in, immediate_in);
        ELSE
            rhn_exception.raise_exception('channel_family_no_subscriptions');
        END IF;

    END subscribe_server;



    FUNCTION can_convert_to_fve(server_id_in IN NUMBER, channel_family_id_val IN NUMBER)
    RETURN NUMBER
    IS
        CURSOR fve_convertible_entries IS
        select 1  from
            rhnServerFveCapable cap
          where cap.server_id = server_id_in
                AND cap.channel_family_id = channel_family_id_val;
    BEGIN
        FOR entry IN fve_convertible_entries LOOP
            return 1;
        END LOOP;
        RETURN 0;
    END can_convert_to_fve;



    -- Converts server channel_family to use a flex entitlement
    PROCEDURE convert_to_fve(server_id_in IN NUMBER, channel_family_id_val IN NUMBER)
    IS
        available_fve_subs      NUMBER;
        server_org_id_val       NUMBER;
    BEGIN

        --
        -- Use the org_id of the server only if the org_id of the channel = NULL.
        -- This is required for subscribing to shared channels.
        --
        SELECT org_id
          INTO server_org_id_val
          FROM rhnServer
         WHERE id = server_id_in;

        begin
            obtain_read_lock(channel_family_id_val, server_org_id_val);
        exception
            when no_data_found then
                rhn_exception.raise_exception('channel_family_no_subscriptions');
        end;
        IF (can_convert_to_fve(server_id_in, channel_family_id_val ) = 0)
            THEN
                rhn_exception.raise_exception('server_cannot_convert_to_flex');
        END IF;

        available_fve_subs := rhn_channel.available_fve_family_subs(channel_family_id_val, server_org_id_val);

        IF (available_fve_subs > 0)
        THEN

            insert into rhnServerHistory (id,server_id,summary,details) (
                select  rhn_event_id_seq.nextval,
                        server_id_in,
                        'converted to flex entitlement' || SUBSTR(cf.label, 0, 99),
                        cf.label
                from    rhnChannelFamily cf
                where   cf.id = channel_family_id_val
            );

            UPDATE rhnServerChannel sc set sc.is_fve = 'Y'
                           where sc.server_id = server_id_in and
                                 sc.channel_id in
                                    (select cfm.channel_id from rhnChannelFamilyMembers cfm
                                                where cfm.CHANNEL_FAMILY_ID = channel_family_id_val);

            rhn_channel.update_family_counts(channel_family_id_val, server_org_id_val);
        ELSE
            rhn_exception.raise_exception('not_enough_flex_entitlements');
        END IF;

    END convert_to_fve;

    function can_server_consume_virt_channl(
        server_id_in in number,
        family_id_in in number )
    return number
    is

        cursor server_virt_families is
            select vi.virtual_system_id, cfvsl.channel_family_id
            from
                rhnChannelFamilyVirtSubLevel cfvsl,
                rhnSGTypeVirtSubLevel sgtvsl,
                rhnVirtualInstance vi
            where
                vi.virtual_system_id = server_id_in
                and sgtvsl.virt_sub_level_id = cfvsl.virt_sub_level_id
                and cfvsl.channel_family_id = family_id_in
                and exists (
                    select 1
                    from rhnServerEntitlementView sev
                    where vi.host_system_id = sev.server_id
                    and sev.server_group_type_id = sgtvsl.server_group_type_id );
    begin

        for server_virt_family in server_virt_families loop
            return 1;
        end loop;

        return 0;

    end;

    FUNCTION can_server_consume_fve(server_id_in IN NUMBER)
    RETURN NUMBER
    IS
        CURSOR vi_entries IS
            SELECT 1
              FROM rhnVirtualInstance vi
             WHERE vi.virtual_system_id = server_id_in;
        vi_count NUMBER;

    BEGIN
        FOR vi_entry IN VI_ENTRIES LOOP
            return 1;
        END LOOP;
        RETURN 0;
    END;

    function guess_server_base(
        server_id_in in number
    ) RETURN number is
        cursor server_cursor is
            select s.server_arch_id, s.release, s.org_id
              from rhnServer s
             where s.id = server_id_in;
    begin
        for s in server_cursor loop
            for channel in base_channel_cursor(s.release,
                s.server_arch_id, s.org_id)
            loop
                return channel.id;
            end loop base_channel_cursor;
        end loop server_cursor;
        -- Server not found, or no base channel applies to it
        return null;
    end;

    -- Private function
    function normalize_server_arch(server_arch_in in varchar2)
    return varchar2
    deterministic
    is
        suffix VARCHAR2(128) := '-redhat-linux';
        suffix_len NUMBER := length(suffix);
    begin
        if server_arch_in is NULL then
            return NULL;
        end if;
        if instr(server_arch_in, '-') > 0
        then
            -- Suffix already present
            return server_arch_in;
        end if;
        return server_arch_in || suffix;
    end normalize_server_arch;

    --
    --
    -- Raises:
    --   server_arch_not_found
    --   no_subscribe_permissions
    function base_channel_for_release_arch(
        release_in in varchar2,
        server_arch_in in varchar2,
        org_id_in in number := -1,
        user_id_in in number := null
    ) return number is
        server_arch varchar2(256) := normalize_server_arch(server_arch_in);
        server_arch_id number;
    begin
        -- Look up the server arch
        begin
            select id
              into server_arch_id
              from rhnServerArch
             where label = server_arch;
        exception
            when no_data_found then
                rhn_exception.raise_exception('server_arch_not_found');
        end;
        return base_channel_rel_archid(release_in, server_arch_id,
            org_id_in, user_id_in);
    end base_channel_for_release_arch;

    function base_channel_rel_archid(
        release_in in varchar2,
        server_arch_id_in in number,
        org_id_in in number := -1,
        user_id_in in number := null
    ) return number is
        denied_channel_id number := null;
        valid_org_id number := org_id_in;
        valid_user_id number := user_id_in;
        channel_subscribable number;
    begin
        if org_id_in = -1 and user_id_in is not null then
            -- Get the org id from the user id
            begin
                select org_id
                  into valid_org_id
                  from web_contact
                 where id = user_id_in;
            exception
                when no_data_found then
                    -- User doesn't exist
                    -- XXX Only list public stuff for now
                    valid_user_id := null;
                    valid_org_id := -1;
            end;
        end if;

        for c in base_channel_cursor(release_in, server_arch_id_in, valid_org_id)
        loop
            -- This row is a possible match
            if valid_user_id is null then
                -- User ID not specified, so no user to channel permissions to
                -- check
                return c.id;
            end if;

            -- Check user to channel permissions
            select loose_user_role_check(c.id, user_id_in, 'subscribe')
              into channel_subscribable
              from dual;

            if channel_subscribable = 1 then
                return c.id;
            end if;

            -- Base channel exists, but is not subscribable; keep trying
            denied_channel_id := c.id;
        end loop base_channel_fetch;

        if denied_channel_id is not null then
            rhn_exception.raise_exception('no_subscribe_permissions');
        end if;
        -- No base channel applies
        return NULL;
    end base_channel_rel_archid;

    PROCEDURE clear_subscriptions(server_id_in IN NUMBER, deleting_server IN NUMBER := 0,
                                update_family_countsYN IN NUMBER := 1)
    IS
        cursor server_channels(server_id_in in number) is
                select  s.org_id, sc.channel_id, cfm.channel_family_id
                from    rhnServer s,
                        rhnServerChannel sc,
                        rhnChannelFamilyMembers cfm
                where   s.id = server_id_in
                        and s.id = sc.server_id
                        and sc.channel_id = cfm.channel_id
                order by cfm.channel_family_id;
        last_channel_family_id rhnChannelFamilyMembers.channel_family_id%type := -1;
        last_channel_org_id    rhnServer.org_id%type := -1;
    BEGIN
        for channel in server_channels(server_id_in)
        loop
                unsubscribe_server(server_id_in, channel.channel_id, 1, 1, deleting_server, 0);
                if update_family_countsYN > 0
                    and channel.channel_family_id != last_channel_family_id then
                    -- update family counts only once
                    -- after all channels with same family has been fetched
                    if last_channel_family_id != -1 then
                        update_family_counts(last_channel_family_id, last_channel_org_id);
                    end if;
                    last_channel_family_id := channel.channel_family_id;
                    last_channel_org_id    := channel.org_id;
                end if;
        end loop channel;
        if update_family_countsYN > 0 and last_channel_family_id != -1 then
            -- update the last family fetched
            update_family_counts(last_channel_family_id, last_channel_org_id);
        end if;
    END clear_subscriptions;

    PROCEDURE unsubscribe_server(server_id_in IN NUMBER, channel_id_in NUMBER, immediate_in NUMBER := 1, unsubscribe_children_in number := 0,
                                 deleting_server IN NUMBER := 0,
                                 update_family_countsYN IN NUMBER := 1)
    IS
        channel_family_id_val   NUMBER;
        server_org_id_val       NUMBER;
        available_subscriptions NUMBER;
        server_already_in_chan  BOOLEAN;
        cursor  channel_family_is_proxy(channel_family_id_in in number) is
                select  1
                from    rhnChannelFamily
                where   id = channel_family_id_in
                    and label = 'rhn-proxy';
        cursor  channel_family_is_satellite(channel_family_id_in in number) is
                select  1
                from    rhnChannelFamily
                where   id = channel_family_id_in
                    and label = 'rhn-satellite';
        -- this is *EXACTLY* like check_server_parent_membership, but if we recurse
        -- with the package-level one, we get a "cursor already open", so we need a
        -- copy on our call stack instead.  GROAN.
        cursor local_chk_server_parent_memb (
                        server_id_in number,
                        channel_id_in number ) is
                select  c.id
                from    rhnChannel                      c,
                                rhnServerChannel        sc
                where   1=1
                        and c.parent_channel = channel_id_in
                        and c.id = sc.channel_id
                        and sc.server_id = server_id_in;
    BEGIN
        FOR child IN local_chk_server_parent_memb(server_id_in, channel_id_in)
        LOOP
            if unsubscribe_children_in = 1 then
                unsubscribe_server(server_id_in => server_id_in,
                                                                channel_id_in => child.id,
                                                                immediate_in => immediate_in,
                                                                unsubscribe_children_in => unsubscribe_children_in,
                        deleting_server => deleting_server,
                        update_family_countsYN => update_family_countsYN);
            else
                rhn_exception.raise_exception('channel_unsubscribe_child_exists');
            end if;
        END LOOP child;

        server_already_in_chan := FALSE;

        FOR check_subscription IN check_server_subscription(server_id_in, channel_id_in)
        LOOP
            server_already_in_chan := TRUE;
        END LOOP check_subscription;

        IF NOT server_already_in_chan
        THEN
            RETURN;
        END IF;

   if deleting_server = 0 then

      insert into rhnServerHistory (id,server_id,summary,details) (
          select  rhn_event_id_seq.nextval,
                server_id_in,
             'unsubscribed from channel ' || SUBSTR(c.label, 0, 106),
             c.label
          from    rhnChannel c
          where   c.id = channel_id_in
      );

        UPDATE rhnServer SET channels_changed = sysdate WHERE id = server_id_in;
   end if;

   DELETE FROM rhnServerChannel WHERE server_id = server_id_in AND channel_id = channel_id_in;

   if deleting_server = 0 then
        queue_server(server_id_in, immediate_in);
   end if;

        channel_family_id_val := rhn_channel.family_for_channel(channel_id_in);
        IF channel_family_id_val IS NULL
        THEN
            rhn_exception.raise_exception('channel_unsubscribe_no_family');
        END IF;

        for ignore in channel_family_is_satellite(channel_family_id_val) loop
                delete from rhnSatelliteInfo where server_id = server_id_in;
        end loop;

        for ignore in channel_family_is_proxy(channel_family_id_val) loop
                delete from rhnProxyInfo where server_id = server_id_in;
        end loop;
        SELECT org_id INTO server_org_id_val
          FROM rhnServer
         WHERE id = server_id_in;

        if update_family_countsYN = 1 then
            rhn_channel.update_family_counts(channel_family_id_val, server_org_id_val);
        end if;
    END unsubscribe_server;


    FUNCTION family_for_channel(channel_id_in IN NUMBER)
    RETURN NUMBER
    IS
        channel_family_id_val NUMBER;
    BEGIN
        SELECT channel_family_id INTO channel_family_id_val
          FROM rhnChannelFamilyMembers
         WHERE channel_id = channel_id_in;

        RETURN channel_family_id_val;
    EXCEPTION
        WHEN NO_DATA_FOUND
        THEN
            RETURN NULL;
    END family_for_channel;

    FUNCTION available_family_subscriptions(channel_family_id_in IN NUMBER, org_id_in IN NUMBER)
    RETURN NUMBER
    IS
        cfp channel_family_perm_cursor%ROWTYPE;
        current_members_val NUMBER;
        max_members_val     NUMBER;
        found               NUMBER;
    BEGIN
        IF NOT channel_family_perm_cursor%ISOPEN
        THEN
            OPEN channel_family_perm_cursor(channel_family_id_in, org_id_in);
        END IF;

        FETCH channel_family_perm_cursor INTO cfp;

        WHILE channel_family_perm_cursor%FOUND
        LOOP
            found := 1;

            current_members_val := cfp.current_members;
            max_members_val := cfp.max_members;

            FETCH channel_family_perm_cursor INTO cfp;
        END LOOP;

        IF channel_family_perm_cursor%ISOPEN
        THEN
            CLOSE channel_family_perm_cursor;
        END IF;

        -- not found: either the channel fam doesn't have an entry in cfp, or the org doesn't have access to it.
        -- either way, there are no available subscriptions

        IF found IS NULL
        THEN
            RETURN 0;
        END IF;

        -- null max members?  in that case, pass it on; NULL means infinite
        IF max_members_val IS NULL
        THEN
            RETURN NULL;
        END IF;

        -- otherwise, return the delta
        RETURN max_members_val - current_members_val;
    END available_family_subscriptions;

    FUNCTION available_fve_family_subs(channel_family_id_in IN NUMBER, org_id_in IN NUMBER)
    RETURN NUMBER
    IS
        cfp channel_family_perm_cursor%ROWTYPE;
        fve_current_members_val NUMBER;
        fve_max_members_val     NUMBER;
        found               NUMBER;

    BEGIN
        IF NOT channel_family_perm_cursor%ISOPEN THEN
            OPEN channel_family_perm_cursor(channel_family_id_in, org_id_in);
        END IF;

        FETCH channel_family_perm_cursor INTO cfp;

        WHILE channel_family_perm_cursor%FOUND LOOP
            found := 1;
            fve_current_members_val := cfp.fve_current_members;
            fve_max_members_val := cfp.fve_max_members;
            FETCH channel_family_perm_cursor INTO cfp;
        END LOOP;

        IF channel_family_perm_cursor%ISOPEN THEN
            CLOSE channel_family_perm_cursor;
        END IF;

        IF found IS NULL THEN
            RETURN 0;
        END IF;

        IF fve_max_members_val IS NULL THEN
            RETURN NULL;
        END IF;

        RETURN fve_max_members_val - fve_current_members_val;

    END available_fve_family_subs;


    -- *******************************************************************
    -- FUNCTION: channel_family_current_members
    -- Calculates and returns the actual count of systems consuming
    --   physical channel subscriptions.
    -- Called by: update_family_counts
    --            rhn_entitlements.repoll_virt_guest_entitlements
    -- *******************************************************************
    function channel_family_current_members(channel_family_id_in IN NUMBER,
                                            org_id_in IN NUMBER)
    return number
    is
        current_members_count number := 0;
    begin
        select  count(distinct server_id)
        into    current_members_count
          from  rhnChannelFamilyServerPhysical cfsp
         where  cfsp.channel_family_id = channel_family_id_in
           and  cfsp.customer_id = org_id_in;
        return current_members_count;
    end;


    function cfam_curr_fve_members(
        channel_family_id_in IN NUMBER,
        org_id_in IN NUMBER)
    return number
    is
        current_members_count number := 0;

    begin
        select count(sc.server_id)
          into current_members_count
          from rhnServerChannel sc,
               rhnChannelFamilyMembers cfm,
               rhnServer s
         where s.org_id = org_id_in
           and s.id = sc.server_id
           and cfm.channel_family_id = channel_family_id_in
           and cfm.channel_id = sc.channel_id
           and exists (
                select 1
                  from rhnChannelFamilyServerFve cfsp
                 where cfsp.CHANNEL_FAMILY_ID = channel_family_id_in
                   and cfsp.server_id = s.id
                );

        return current_members_count;
    end;
    PROCEDURE update_family_counts(channel_family_id_in IN NUMBER,
                                   org_id_in IN NUMBER)
    IS
    BEGIN
        update rhnPrivateChannelFamily
           set current_members = ( channel_family_current_members(channel_family_id_in, org_id_in)),
               fve_current_members = ( cfam_curr_fve_members(channel_family_id_in, org_id_in))
         where org_id = org_id_in
           and channel_family_id = channel_family_id_in;
    END update_family_counts;

    PROCEDURE update_group_family_counts(group_label_in IN VARCHAR2,
                                   org_id_in IN NUMBER)
    IS
    BEGIN
        FOR i IN (
                SELECT DISTINCT CFM.channel_family_id, SG.org_id
                 FROM rhnChannelFamilyMembers CFM
                 JOIN rhnServerChannel SC
                   ON SC.channel_id = CFM.channel_id
                 JOIN rhnServerGroupMembers SGM
                   ON SC.server_id = SGM.server_id
                 JOIN rhnServerGroup SG
                   ON SGM.server_group_id = SG.id
                 JOIN rhnServerGroupType SGT
                   ON SG.group_type = SGT.id
                WHERE SGT.label = group_label_in
                  AND SG.org_id = org_id_in
                  AND SGT.is_base = 'Y'
        ) LOOP
            rhn_channel.update_family_counts(i.channel_family_id, i.org_id);
        END LOOP;
    END update_group_family_counts;

    FUNCTION available_chan_subscriptions(channel_id_in IN NUMBER,
                                          org_id_in IN NUMBER)
    RETURN NUMBER
    IS
            channel_family_id_val NUMBER;
    BEGIN
        SELECT channel_family_id INTO channel_family_id_val
            FROM rhnChannelFamilyMembers
            WHERE channel_id = channel_id_in;

            RETURN rhn_channel.available_family_subscriptions(
                           channel_family_id_val, org_id_in);
    END available_chan_subscriptions;

	FUNCTION available_fve_chan_subs(channel_id_in IN NUMBER,
                                          org_id_in IN NUMBER)
    RETURN NUMBER
    IS
        channel_family_id_val NUMBER;

    BEGIN
        SELECT channel_family_id INTO channel_family_id_val
          FROM rhnChannelFamilyMembers
         WHERE channel_id = channel_id_in;

        RETURN rhn_channel.available_fve_family_subs( channel_family_id_val, org_id_in);
    END available_fve_chan_subs;

    procedure unsubscribe_server_from_family(server_id_in in number,
                                             channel_family_id_in in number)
    is
    begin
        delete
        from    rhnServerChannel rsc
        where   rsc.server_id = server_id_in
            and channel_id in (
                select  rcfm.channel_id
                from    rhnChannelFamilyMembers rcfm
                where   rcfm.channel_family_id = channel_family_id_in);
    end;

    function get_org_id(channel_id_in in number)
    return number
    is
        org_id_out number;
    begin
        select org_id into org_id_out
            from rhnChannel
            where id = channel_id_in;

            return org_id_out;
    end get_org_id;

    function get_cfam_org_access(cfam_id_in in number, org_id_in in number)
    return number
    is
        cursor  families is
                        select  1
                        from    rhnOrgChannelFamilyPermissions cfp
                        where   cfp.org_id = org_id_in;
    begin
                -- the idea: if we get past this query,
        -- the user has the role, else catch the exception and return 0
                for family in families loop
                return 1;
                end loop;
                return 0;
    end;

    function get_org_access(channel_id_in in number, org_id_in in number)
    return number
    is
        throwaway number;
    begin
        -- the idea: if we get past this query,
        -- the org has access to the channel, else catch the exception and return 0
        select distinct 1 into throwaway
          from rhnChannelFamilyMembers CFM,
               rhnOrgChannelFamilyPermissions CFP
         where cfp.org_id = org_id_in
           and CFM.channel_family_id = CFP.channel_family_id
           and CFM.channel_id = channel_id_in
           and (CFP.max_members > 0 or CFP.max_members is null or CFP.fve_max_members > 0 or CFP.fve_max_members is null or CFP.org_id = 1);

        return 1;
        exception
            when no_data_found
            then
            return 0;
    end;

    -- check if a user has a given role, or if such a role is inferrable
    -- returns NULL if OK, error message otherwise
    function user_role_check_debug(channel_id_in in number,
                                   user_id_in in number,
                                   role_in in varchar2)
    return varchar2
    is
        org_id number;
    begin
        org_id := rhn_user.get_org_id(user_id_in);

        -- channel might be shared
        if role_in = 'subscribe' and
           rhn_channel.shared_user_role_check(channel_id_in, user_id_in, role_in) = 1 then
            return NULL;
        end if;

        if role_in = 'manage' and
           NVL(rhn_channel.get_org_id(channel_id_in), -1) <> org_id then
               return 'channel_not_owned';
        end if;

        if role_in = 'subscribe' and
           rhn_channel.get_org_access(channel_id_in, org_id) = 0 then
                return 'channel_not_available';
        end if;

        -- channel admins have all roles
        if rhn_user.check_role_implied(user_id_in, 'channel_admin') = 1 then
            return NULL;
        end if;

        -- the subscribe permission is inferred
        -- UNLESS the not_globally_subscribable flag is set
        if role_in = 'subscribe'
        then
            if rhn_channel.org_channel_setting(channel_id_in,
                       org_id,
                       'not_globally_subscribable') = 0 then
                    return NULL;
            end if;
        end if;

        -- all other roles (manage right now) are explicitly granted
        if rhn_channel.direct_user_role_check(channel_id_in,
                                              user_id_in, role_in) = 1 then
            return NULL;
        end if;
        return 'direct_permission';
    end;

    -- same as above, but with 1/0 output; useful in views, etc
    function user_role_check(channel_id_in in number, user_id_in in number, role_in in varchar2)
    return number
    is
    begin
        if rhn_channel.user_role_check_debug(channel_id_in,
                                             user_id_in, role_in) is NULL then
            return 1;
        else
            return 0;
        end if;
    end;

    --
    -- For multiorg phase II, this function simply checks to see if the user's
    -- has a trust relationship that includes this channel by id.
    --
    function shared_user_role_check(channel_id in number, user_id in number, role in varchar2)
    return number
    is
      n number;
      oid number;
    begin
      oid := rhn_user.get_org_id(user_id);
      select 1 into n
      from rhnSharedChannelView s
      where s.id = channel_id and s.org_trust_id = oid;
      return 1;
      exception
        when no_data_found then
          return 0;
    end;

    -- same as above, but returns 1 if user_id_in is null
    -- This is useful in queries where user_id is not specified
    function loose_user_role_check(channel_id_in in number, user_id_in in number, role_in in varchar2)
    return number
    is
    begin
        if user_id_in is null then
            return 1;
        end if;
        return user_role_check(channel_id_in, user_id_in, role_in);
    end loose_user_role_check;

    -- directly checks the table, no inferred permissions
    function direct_user_role_check(channel_id_in in number, user_id_in in number, role_in in varchar2)
    return number
    is
        throwaway number;
    begin
        -- the idea: if we get past this query, the user has the role, else catch the exception and return 0
        select 1 into throwaway
          from rhnChannelPermissionRole CPR,
               rhnChannelPermission CP
         where CP.user_id = user_id_in
           and CP.channel_id = channel_id_in
           and CPR.label = role_in
           and CP.role_id = CPR.id;

        return 1;
    exception
        when no_data_found
            then
            return 0;
    end;

    -- check if an org has a certain setting
    function org_channel_setting(channel_id_in in number, org_id_in in number, setting_in in varchar2)
    return number
    is
        throwaway number;
    begin
        -- the idea: if we get past this query, the org has the setting, else catch the exception and return 0
        select 1 into throwaway
          from rhnOrgChannelSettingsType OCST,
               rhnOrgChannelSettings OCS
         where OCS.org_id = org_id_in
           and OCS.channel_id = channel_id_in
           and OCST.label = setting_in
           and OCS.setting_id = OCST.id;

        return 1;
    exception
        when no_data_found
            then
            return 0;
    end;

    FUNCTION channel_priority(channel_id_in IN number)
    RETURN number
    IS
         channel_name varchar2(256);
         priority number;
         end_of_life_val date;
         org_id_val number;
    BEGIN

        select name, end_of_life, org_id
        into channel_name, end_of_life_val, org_id_val
        from rhnChannel
        where id = channel_id_in;

        if end_of_life_val is not null then
          return -400;
        end if;

        if channel_name like 'Red Hat Enterprise Linux%' or channel_name like 'RHEL%' then
          priority := 1000;
          if channel_name not like '%Beta%' then
            priority := priority + 1000;
          end if;

          priority := priority +
            case
              when channel_name like '%v. 5%' then 600
              when channel_name like '%v. 4%' then 500
              when channel_name like '%v. 3%' then 400
              when channel_name like '%v. 2%' then 300
              when channel_name like '%v. 1%' then 200
              else 0
            end;

          priority := priority +
            case
              when channel_name like 'Red Hat Enterprise Linux (v. 5%' then 60
              when (channel_name like '%AS%' and channel_name not like '%Extras%') then 50
              when (channel_name like '%ES%' and channel_name not like '%Extras%') then 40
              when (channel_name like '%WS%' and channel_name not like '%Extras%') then 30
              when (channel_name like '%Desktop%' and channel_name not like '%Extras%') then 20
              when channel_name like '%Extras%' then 10
              else 0
            end;

          priority := priority +
            case
              when channel_name like '%)' then 5
              else 0
            end;

          priority := priority +
            case
              when channel_name like '%32-bit x86%' then 4
              when channel_name like '%64-bit Intel Itanium%' then 3
              when channel_name like '%64-bit AMD64/Intel EM64T%' then 2
              else 0
            end;
        elsif channel_name like 'Red Hat Desktop%' then
            priority := 900;

            if channel_name not like '%Beta%' then
               priority := priority + 50;
            end if;

          priority := priority +
            case
              when channel_name like '%v. 4%' then 40
              when channel_name like '%v. 3%' then 30
              when channel_name like '%v. 2%' then 20
              when channel_name like '%v. 1%' then 10
              else 0
            end;

          priority := priority +
            case
              when channel_name like '%32-bit x86%' then 4
              when channel_name like '%64-bit Intel Itanium%' then 3
              when channel_name like '%64-bit AMD64/Intel EM64T%' then 2
              else 0
            end;

        elsif org_id_val is not null then
          priority := 600;
        else
          priority := 500;
        end if;

      return -priority;

    end channel_priority;

    -- right now this only does the accounting changes; the cascade
    -- actually does the rhnServerChannel delete.
    procedure delete_server_channels(server_id_in in number)
    is
    begin
        update  rhnPrivateChannelFamily
        set     current_members = current_members -1
        where   org_id in (
                        select  org_id
                        from    rhnServer
                        where   id = server_id_in
                )
                and channel_family_id in (
                        select  rcfm.channel_family_id
                        from    rhnChannelFamilyMembers rcfm,
                                rhnServerChannel rsc
                        where   rsc.server_id = server_id_in
                                and rsc.channel_id = rcfm.channel_id
                and not exists (
                    select 1
                    from
                        rhnChannelFamilyVirtSubLevel cfvsl,
                        rhnSGTypeVirtSubLevel sgtvsl,
                        rhnServerEntitlementView sev,
                        rhnVirtualInstance vi
                    where
                        -- system is a virtual instance
                        vi.virtual_system_id = server_id_in
                        and vi.host_system_id = sev.server_id
                        -- system's host has a virt ent
                        and sev.label in ('virtualization_host',
                                          'virtualization_host_platform')
                        and sev.server_group_type_id =
                            sgtvsl.server_group_type_id
                        -- the host's virt ent grants a cf virt sub level
                        and sgtvsl.virt_sub_level_id = cfvsl.virt_sub_level_id
                        -- the cf is in that virt sub level
                        and cfvsl.channel_family_id = rcfm.channel_family_id
                    )
                );
    end;

    -- this could certainly be optimized to do updates if needs be
    procedure refresh_newest_package(channel_id_in in number,
                                     caller_in in varchar2 := '(unknown)',
                                     package_name_id_in in number := null)
    is
    -- procedure refreshes rows for name_id = package_name_id_in or
    -- all rows if package_name_id_in is null
    begin
        delete from rhnChannelNewestPackage
              where channel_id = channel_id_in
                and (package_name_id_in is null
                     or name_id = package_name_id_in);
        insert into rhnChannelNewestPackage
                (channel_id, name_id, evr_id, package_id, package_arch_id)
                (select channel_id,
                        name_id, evr_id,
                        package_id, package_arch_id
                   from rhnChannelNewestPackageView
                  where channel_id = channel_id_in
                    and (package_name_id_in is null
                         or name_id = package_name_id_in)
                );
        insert into rhnChannelNewestPackageAudit (channel_id, caller)
             values (channel_id_in, caller_in);
        update rhnChannel
           set last_modified = greatest(sysdate, last_modified + 1/86400)
         where id = channel_id_in;
    end;

   procedure update_channel ( channel_id_in in number, invalidate_ss in number := 0,
                              date_to_use in date := sysdate )
   is

   channel_last_modified date;
   last_modified_value date;

   cursor snapshots is
   select  snapshot_id id
   from    rhnSnapshotChannel
   where   channel_id = channel_id_in;

   begin

      select last_modified
      into channel_last_modified
      from rhnChannel
      where id = channel_id_in;

      last_modified_value := date_to_use;

      if last_modified_value <= channel_last_modified then
          last_modified_value := last_modified_value + 1/86400;
      end if;

      update rhnChannel set last_modified = last_modified_value
      where id = channel_id_in;

      if invalidate_ss = 1 then
        for snapshot in snapshots loop
            update rhnSnapshot
            set invalid = lookup_snapshot_invalid_reason('channel_modified')
            where id = snapshot.id;
        end loop;
      end if;

   end update_channel;

   procedure update_channels_by_package ( package_id_in in number, date_to_use in date := sysdate )
   is

   cursor channels is
   select channel_id
   from rhnChannelPackage
   where package_id = package_id_in
   order by channel_id;

   begin
      for channel in channels loop
         -- we want to invalidate the snapshot assocated with the channel when we
         -- do this b/c we know we've added or removed or packages
         rhn_channel.update_channel ( channel.channel_id, 1, date_to_use );
      end loop;
   end update_channels_by_package;


   procedure update_channels_by_errata ( errata_id_in number, date_to_use in date := sysdate )
   is

   cursor channels is
   select channel_id
   from rhnChannelErrata
   where errata_id = errata_id_in
   order by channel_id;

   begin
      for channel in channels loop
         -- we won't invalidate snapshots, b/c just changing the errata associated with
         -- a channel shouldn't invalidate snapshots
         rhn_channel.update_channel ( channel.channel_id, 0, date_to_use );
      end loop;
   end update_channels_by_errata;

   procedure update_needed_cache(channel_id_in in number)
   is
       -- update of needed cache ican be commited on a per server basis
       -- b/c failure of update for a server means nothing for the other servers
   begin
      -- we intentionaly do a loop here instead of one huge select
      -- b/c we want to break update into smaller transaction to unblock other sessions
      -- querying rhnServerNeededCache
      for server in (
                select sc.server_id as id
                  from rhnServerChannel sc
                 where sc.channel_id = channel_id_in
      ) loop
         rhn_server.update_needed_cache(server.id);
         commit;
      end loop;
   end update_needed_cache;

   -- return true if the given server has a subs to a channel of channel_family_id_in
   FUNCTION server_has_family_subscription(server_id_in IN NUMBER, channel_family_id_in IN NUMBER)
   RETURN NUMBER
   IS
      CURSOR fam_entries IS
         SELECT DISTINCT cfm.channel_family_id
           FROM rhnchannelfamilymembers cfm
           JOIN rhnserverchannel sc on sc.channel_id = cfm.channel_id
          WHERE sc.server_id =  server_id_in
            AND cfm.channel_family_id = channel_family_id_in;
      fam_count NUMBER;
   BEGIN
      FOR fam_entry IN fam_entries LOOP
         RETURN 1;
      END LOOP;
      RETURN 0;
   END server_has_family_subscription;

END rhn_channel;
/
SHOW ERRORS
07070100000996000081B400000000000000000000000167AE11140000195A000000000000000000000000000000000000006700000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/852-rhn_channel.pks.sql    --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

CREATE OR REPLACE
PACKAGE rhn_channel
IS
	version varchar2(100) := '';

    CURSOR server_base_subscriptions(server_id_in NUMBER) IS
	   SELECT C.id
	     FROM rhnChannel C, rhnServerChannel SC
	    WHERE C.id = SC.channel_id
	      AND SC.server_id = server_id_in
	      AND C.parent_channel IS NULL;

    CURSOR check_server_subscription(server_id_in NUMBER, channel_id_in NUMBER) IS
           SELECT channel_id
	     FROM rhnServerChannel
	    WHERE server_id = server_id_in
	      AND channel_id = channel_id_in;

    CURSOR check_server_parent_membership(server_id_in NUMBER, channel_id_in NUMBER) IS
	   SELECT C.id
	     FROM rhnChannel C, rhnServerChannel SC
	    WHERE C.parent_channel = channel_id_in
	      AND C.id = SC.channel_id
	      AND SC.server_id = server_id_in;

    CURSOR channel_family_perm_cursor(channel_family_id_in NUMBER, org_id_in NUMBER) IS
           SELECT *
	     FROM rhnOrgChannelFamilyPermissions
	    WHERE channel_family_id = channel_family_id_in
	      AND org_id = org_id_in;


    PROCEDURE unsubscribe_server(server_id_in IN NUMBER, channel_id_in NUMBER, immediate_in NUMBER := 1, unsubscribe_children_in number := 0,
                                 deleting_server in number := 0,
                                 update_family_countsYN IN NUMBER := 1);
    PROCEDURE subscribe_server(server_id_in IN NUMBER, channel_id_in NUMBER, immediate_in NUMBER := 1, user_id_in number := null, recalcfamily_in number := 1);

    PROCEDURE convert_to_fve(server_id_in IN NUMBER, channel_family_id_val IN NUMBER);

    FUNCTION can_convert_to_fve(server_id_in IN NUMBER, channel_family_id_val IN NUMBER)  RETURN NUMBER;

    function can_server_consume_virt_channl(
        server_id_in IN NUMBER,
        family_id_in in number)
    return number;
    FUNCTION can_server_consume_fve( server_id_in IN NUMBER) RETURN NUMBER;

    FUNCTION guess_server_base(server_id_in IN NUMBER) RETURN NUMBER;

    FUNCTION base_channel_for_release_arch(release_in in varchar2,
	server_arch_in in varchar2, org_id_in in number := -1,
	user_id_in in number := null) RETURN number;

    FUNCTION base_channel_rel_archid(release_in in varchar2,
	server_arch_id_in in number, org_id_in in number := -1,
	user_id_in in number := null) RETURN number;

    FUNCTION channel_priority(channel_id_in in number) RETURN number;

    PROCEDURE clear_subscriptions(server_id_in IN NUMBER, deleting_server in number := 0,
                                update_family_countsYN IN NUMBER := 1);

    FUNCTION available_family_subscriptions(channel_family_id_in IN NUMBER, org_id_in IN NUMBER) RETURN NUMBER;

    FUNCTION available_fve_family_subs(channel_family_id_in IN NUMBER, org_id_in IN NUMBER) RETURN NUMBER;

    FUNCTION channel_family_current_members(channel_family_id_in IN NUMBER, org_id_in IN NUMBER) return number;

    FUNCTION cfam_curr_fve_members(channel_family_id_in IN NUMBER, org_id_in IN NUMBER) return number;

    PROCEDURE update_family_counts(channel_family_id_in IN NUMBER, org_id_in IN NUMBER);
    PROCEDURE update_group_family_counts(group_label_in IN VARCHAR2, org_id_in IN NUMBER);
    FUNCTION family_for_channel(channel_id_in IN NUMBER) RETURN NUMBER;

    FUNCTION available_chan_subscriptions(channel_id_in IN NUMBER, org_id_in IN NUMBER) RETURN NUMBER;

    FUNCTION available_fve_chan_subs(channel_id_in IN NUMBER, org_id_in IN NUMBER) RETURN NUMBER;

    PROCEDURE unsubscribe_server_from_family(server_id_in in number, channel_family_id_in in number);

    PROCEDURE delete_server_channels(server_id_in in number);

    PROCEDURE refresh_newest_package(channel_id_in in number,
                                     caller_in in varchar2 := '(unknown)',
                                     package_name_id_in in number := null);

    FUNCTION get_org_id(channel_id_in in number) return number;
    PRAGMA RESTRICT_REFERENCES(get_org_id, WNDS, RNPS, WNPS);

    function get_org_access(channel_id_in in number, org_id_in in number) return number;
    PRAGMA RESTRICT_REFERENCES(get_org_access, WNDS, RNPS, WNPS);

    function get_cfam_org_access(cfam_id_in in number, org_id_in in number) return number;

    function user_role_check_debug(channel_id_in in number, user_id_in in number, role_in in varchar2)
        RETURN VARCHAR2;
    PRAGMA RESTRICT_REFERENCES(user_role_check_debug, WNDS, RNPS, WNPS);

    function user_role_check(channel_id_in in number, user_id_in in number, role_in in varchar2)
	RETURN NUMBER;
    PRAGMA RESTRICT_REFERENCES(user_role_check, WNDS, RNPS, WNPS);

    function loose_user_role_check(channel_id_in in number, user_id_in in number, role_in in varchar2)
	RETURN NUMBER;
    PRAGMA RESTRICT_REFERENCES(loose_user_role_check, WNDS, RNPS, WNPS);

    function direct_user_role_check(channel_id_in in number, user_id_in in number, role_in in varchar2)
	RETURN NUMBER;
    PRAGMA RESTRICT_REFERENCES(direct_user_role_check, WNDS, RNPS, WNPS);

    function shared_user_role_check(channel_id in number, user_id in number, role in varchar2)
	RETURN NUMBER;
    PRAGMA RESTRICT_REFERENCES(shared_user_role_check, WNDS, RNPS, WNPS);

    function org_channel_setting(channel_id_in in number, org_id_in in number, setting_in in varchar2)
	RETURN NUMBER;

    PROCEDURE update_channel ( channel_id_in in number, invalidate_ss in number := 0,
                               date_to_use in date := sysdate );

    PROCEDURE  update_channels_by_package ( package_id_in in number, date_to_use in date := sysdate );

     PROCEDURE update_channels_by_errata ( errata_id_in number, date_to_use in date := sysdate );


    PRAGMA RESTRICT_REFERENCES(org_channel_setting, WNDS, RNPS, WNPS);

    PROCEDURE update_needed_cache(channel_id_in in number);

    FUNCTION server_has_family_subscription(server_id_in IN NUMBER, channel_family_id_in IN NUMBER) RETURN NUMBER;

END rhn_channel;
/
SHOW ERRORS
  07070100000997000081B400000000000000000000000167AE111400000022000000000000000000000000000000000000007200000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/856-rhnRedHatCanonVersion-drop.sql drop table rhnRedHatCanonVersion;
  07070100000998000081B400000000000000000000000167AE11140000007E000000000000000000000000000000000000007000000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/905-rhnXccdfRuleresult-index.sql   CREATE INDEX rhn_xccdf_rresult_tresult_idx
    ON rhnXccdfRuleresult (testresult_id)
    TABLESPACE [[4m_tbs]]
    NOLOGGING;
  07070100000999000081B400000000000000000000000167AE111400000075000000000000000000000000000000000000007200000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/906-rhnXccdfRuleIdentMap-index.sql CREATE INDEX rhn_xccdf_rim_ident_idx
    ON rhnXccdfRuleIdentMap (ident_id)
    TABLESPACE [[8m_tbs]]
    NOLOGGING;
   0707010000099A000081B400000000000000000000000167AE111400000042000000000000000000000000000000000000008600000000susemanager-schema/upgrade/susemanager-schema-1.2.75-to-susemanager-schema-1.7/909-rhnactionkickstartguest_mac_address_column_add.sql alter table rhnactionkickstartguest add mac_address varchar2(17);
  0707010000099B000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005200000000susemanager-schema/upgrade/susemanager-schema-1.7-to-susemanager-schema-1.7.56.13 0707010000099C000081B400000000000000000000000167AE11140000002A000000000000000000000000000000000000006100000000susemanager-schema/upgrade/susemanager-schema-1.7-to-susemanager-schema-1.7.56.13/0001-empty.sql  -- This file is intentionally left empty.
  0707010000099D000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005800000000susemanager-schema/upgrade/susemanager-schema-1.7.56.11-to-susemanager-schema-1.7.56.12   0707010000099E000081B400000000000000000000000167AE111400000041000000000000000000000000000000000000008F00000000susemanager-schema/upgrade/susemanager-schema-1.7.56.11-to-susemanager-schema-1.7.56.12/001-rhnactionkickstartguest_mac_address_column_add.sql    alter table rhnactionkickstartguest add mac_address varchar(17);
   0707010000099F000081B400000000000000000000000167AE11140000077F000000000000000000000000000000000000006B00000000susemanager-schema/upgrade/susemanager-schema-1.7.56.11-to-susemanager-schema-1.7.56.12/002-lookup_evr.sql    --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.

create or replace function
lookup_evr(e_in in varchar, v_in in varchar, r_in in varchar)
returns numeric
as
$$
declare
    evr_id  numeric;
begin
    select id
      into evr_id
      from rhnPackageEVR
     where ((epoch is null and e_in is null) or (epoch = e_in)) and
           version = v_in and
           release = r_in;
            
    if not found then
        evr_id := nextval('rhn_pkg_evr_seq');
        declare
            e_text varchar = coalesce(quote_literal(e_in), 'NULL');
            v_text varchar = coalesce(quote_literal(v_in), 'NULL');
            r_text varchar = coalesce(quote_literal(r_in), 'NULL');
        begin
            perform pg_dblink_exec(
                'insert into rhnPackageEVR(id, epoch, version, release, evr) values (' ||
                evr_id || ', ' || e_text || ', ' || v_text || ', ' || r_text
		|| ', evr_t(' || e_text || ', ' || v_text || ', ' || r_text || '))'
            );
        exception when unique_violation then
            select id
              into strict evr_id
              from rhnPackageEVR
             where ((epoch is null and e_in is null) or (epoch = e_in)) and
                   version = v_in and
                   release = r_in;
        end;
    end if;

    return evr_id;
end;
$$ language plpgsql immutable;
 070701000009A0000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005800000000susemanager-schema/upgrade/susemanager-schema-1.7.56.12-to-susemanager-schema-1.7.56.13   070701000009A1000081B400000000000000000000000167AE11140000046D000000000000000000000000000000000000006F00000000susemanager-schema/upgrade/susemanager-schema-1.7.56.12-to-susemanager-schema-1.7.56.13/001-pg_dblink_exec.sql    --
-- Copyright (c) 2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.

create or replace function pg_dblink_exec(in_sql in varchar) returns void as
$$
declare
    conn text[];
begin
    if in_sql is null then
	raise 'pg_dblink_exec in_sql is null';
    end if;
    conn := dblink_get_connections();
    if conn is NULL or NOT(conn @> '{at_conn}') then
        perform dblink_connect('at_conn', 'dbname=' || current_database());
    end if;
    begin
        perform dblink_exec('at_conn', in_sql, true);
    exception when others then
        raise;
    end;
end;
$$
language plpgsql;
   070701000009A2000081B400000000000000000000000167AE1114000009AC000000000000000000000000000000000000007B00000000susemanager-schema/upgrade/susemanager-schema-1.7.56.12-to-susemanager-schema-1.7.56.13/002-lookup_transaction_package.sql    --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 

create or replace function
lookup_transaction_package(
    o_in in varchar,
    n_in in varchar,
    e_in in varchar,
    v_in in varchar,
    r_in in varchar,
    a_in in varchar)
returns numeric
as
$$
declare
    o_id        numeric;
    n_id        numeric;
    e_id        numeric;
    p_arch_id   numeric;
    tp_id       numeric;
begin
    select id
      into o_id
      from rhnTransactionOperation
     where label = o_in;

    if not found then
        perform rhn_exception.raise_exception('invalid_transaction_operation');
    end if;

    n_id := lookup_package_name(n_in);
    e_id := lookup_evr(e_in, v_in, r_in);
    p_arch_id := null;

    if a_in is not null then
        p_arch_id := lookup_package_arch(a_in);
    end if;

    select id
      into tp_id
      from rhnTransactionPackage
     where operation = o_id and
           name_id = n_id and
           evr_id = e_id and
           (package_arch_id = p_arch_id or (p_arch_id is null and package_arch_id is null));

    if not found then
        tp_id := nextval('rhn_transpack_id_seq');
        begin
            perform pg_dblink_exec(
                'insert into rhnTransactionPackage (id, operation, name_id, evr_id, package_arch_id)' ||
                ' values (' || tp_id || ', ' || o_id || ', ' || n_id || ', ' || e_id ||
                ', ' || ( case when p_arch_id is null then 'NULL' else p_arch_id::varchar end )  || ')');
        exception when unique_violation then
            select id
              into strict tp_id
              from rhnTransactionPackage
             where operation = o_id and
                   name_id = n_id and
                   evr_id = e_id and
                   (package_arch_id = p_arch_id or (p_arch_id is null and package_arch_id is null));
        end;
    end if;

    return tp_id;
end;
$$
language plpgsql immutable;
070701000009A3000081B400000000000000000000000167AE111400000040000000000000000000000000000000000000007300000000susemanager-schema/upgrade/susemanager-schema-1.7.56.12-to-susemanager-schema-1.7.56.13/003-rename-primary-key.sql    ALTER INDEX rhnactionimagedeploy_pkey RENAME to rhn_aid_id_pk;

070701000009A4000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005800000000susemanager-schema/upgrade/susemanager-schema-1.7.56.13-to-susemanager-schema-1.7.56.14   070701000009A5000081B400000000000000000000000167AE111400000488000000000000000000000000000000000000007300000000susemanager-schema/upgrade/susemanager-schema-1.7.56.13-to-susemanager-schema-1.7.56.14/001-create_pxt_session.sql    --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--

create or replace function
create_pxt_session(p_web_user_id in numeric, p_expires in numeric, p_value in varchar)
returns numeric as $$
declare
	l_id numeric;
begin
    l_id := nextval( 'pxt_id_seq' );

    perform pg_dblink_exec(
        'insert into PXTSessions (id, value, expires, web_user_id) values (' ||
        l_id || ', ' || coalesce(quote_literal(p_value), 'NULL') ||
        ', ' || p_expires || ', ' || coalesce(quote_literal(p_web_user_id), 'NULL') || '); commit');

	return l_id;
end;
$$ language plpgsql;
070701000009A6000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005800000000susemanager-schema/upgrade/susemanager-schema-1.7.56.14-to-susemanager-schema-1.7.56.15   070701000009A7000081B400000000000000000000000167AE111400000350000000000000000000000000000000000000007C00000000susemanager-schema/upgrade/susemanager-schema-1.7.56.14-to-susemanager-schema-1.7.56.15/001-allServerKeywordSinceReboot.sql   
create or replace view allServerKeywordSinceReboot as
SELECT DISTINCT S.id, S.NAME,
       (SELECT 1
          FROM rhnServerFeaturesView SFV
         WHERE SFV.server_id = S.id
           AND SFV.label = 'ftr_system_grouping') AS selectable,
        S.org_id,
        EK.keyword,
        USP.user_id
  FROM rhnServer S,
       rhnErrata E,
       rhnServerInfo SI,
       rhnServerPackage SP,
       rhnPackage P,
       rhnErrataPackage EP,
       rhnerratakeyword EK,
       rhnUserServerPerms USP
 WHERE USP.server_id = S.id
   AND SI.server_id = S.id
   AND SP.server_id = S.id
   AND P.evr_id = SP.evr_id
   AND P.name_id = SP.name_id
   AND EP.errata_id = E.id 
   AND EP.package_id = P.id
   AND (to_date('1970-01-01', 'YYYY-MM-DD') + numtodsinterval(S.last_boot, 'second')) < SP.installtime at time zone 'UTC'
   AND E.id = EK.errata_id;
070701000009A8000081B400000000000000000000000167AE1114000007C5000000000000000000000000000000000000007C00000000susemanager-schema/upgrade/susemanager-schema-1.7.56.14-to-susemanager-schema-1.7.56.15/123-rhnChannelNewestPackageView.sql   --
-- Copyright (c) 2008--2010 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--
--
--
--
-- this is much more readable with ts=4, enjoy!

create or replace view
rhnChannelNewestPackageView
as
SELECT channel_id,
       name_id,
       evr_id,
       package_arch_id,
       max(package_id) as package_id
FROM (
       SELECT m.channel_id          as channel_id,
              p.name_id             as name_id,
              p.evr_id              as evr_id,
              m.package_arch_id     as package_arch_id,
              p.id                  as package_id
         FROM
              (select max(pe.evr) AS max_evr,
                      cp.channel_id,
                      p.name_id,
                      p.package_arch_id
                 from rhnPackageEVR       pe,
                      rhnPackage          p,
                      rhnChannelPackage   cp
                where p.evr_id = pe.id
                  and cp.package_id = p.id
                group by cp.channel_id, p.name_id, p.package_arch_id) m,
              rhnPackageEVR       pe,
              rhnPackage          p,
              rhnChannelPackage   chp
        WHERE m.max_evr = pe.evr
          AND m.name_id = p.name_id
          AND m.package_arch_id = p.package_arch_id
          AND p.evr_id = pe.id
          AND chp.package_id = p.id
          AND chp.channel_id = m.channel_id
) latest_packages
group by channel_id, name_id, evr_id, package_arch_id
;
   070701000009A9000081B400000000000000000000000167AE111400000045000000000000000000000000000000000000007D00000000susemanager-schema/upgrade/susemanager-schema-1.7.56.14-to-susemanager-schema-1.7.56.15/127-rhnPackageCapability-version.sql  
alter table rhnPackageCapability alter version type varchar(512) ;

   070701000009AA000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005800000000susemanager-schema/upgrade/susemanager-schema-1.7.56.15-to-susemanager-schema-1.7.56.16   070701000009AB000081B400000000000000000000000167AE1114000006C8000000000000000000000000000000000000007900000000susemanager-schema/upgrade/susemanager-schema-1.7.56.15-to-susemanager-schema-1.7.56.16/001-rhnKickstartSessionState.sql  --
-- Copyright (c) 2012 Novell, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
--
--

update rhnKickstartSessionState
   set description='Autoinstallation session created, but has not yet been used.'
 where label='created';

update rhnKickstartSessionState
   set description='Files required for autoinstall action have been installed.'
 where label='deployed';

update rhnKickstartSessionState
   set description='The system configuration has been modified to begin autoinstallation upon next boot.'
 where label='injected';

update rhnKickstartSessionState
   set description='The system has been restarted in order to begin the autoinstallation process.'
 where label='restarted';

update rhnKickstartSessionState
   set description='The system has downloaded the autoinstallation configuraton file from Spacewalk.'
 where label='configuration_accessed';

update rhnKickstartSessionState
   set description='The initial files required for autoinstallation have been downloaded.'
 where label='started';

update rhnKickstartSessionState
   set description='The system has successfully registered with Spacewalk after autoinstalling.'
 where label='registered';

update rhnKickstartSessionState
   set description='Autoinstallation complete.'
 where label='complete';

update rhnKickstartSessionState
   set description='Autoinstallation failed.'
 where label='failed';

commit;

070701000009AC000081B400000000000000000000000167AE111400000233000000000000000000000000000000000000007800000000susemanager-schema/upgrade/susemanager-schema-1.7.56.15-to-susemanager-schema-1.7.56.16/002-rhnPackageProvider-data.sql   --
-- Copyright (c) 2012 Novell, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
--
--
insert into rhnPackageProvider (id, name) values
(sequence_nextval('rhn_package_provider_id_seq'), 'openSUSE' );

commit;

 070701000009AD000081B400000000000000000000000167AE111400000356000000000000000000000000000000000000007300000000susemanager-schema/upgrade/susemanager-schema-1.7.56.15-to-susemanager-schema-1.7.56.16/003-rhnPackageKey-data.sql    --
-- Copyright (c) 2012 Novell, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
--
--

update rhnPackageKey set provider_id = lookup_package_provider('openSUSE')
 where key_id = 'b88b2fd43dbdc284';
insert into rhnPackageKey (id, key_id, key_type_id, provider_id)
select sequence_nextval('rhn_pkey_id_seq'), 'b88b2fd43dbdc284', lookup_package_key_type('gpg'), lookup_package_provider('openSUSE')
from dual
where not exists ( select 1 from rhnPackageKey where key_id = 'b88b2fd43dbdc284' );


commit;

  070701000009AE000081B400000000000000000000000167AE1114000001EE000000000000000000000000000000000000008300000000susemanager-schema/upgrade/susemanager-schema-1.7.56.15-to-susemanager-schema-1.7.56.16/055-add_idx_on_suseProducts_product_id.sql    --
-- Copyright (c) 2012 Novell
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
--

CREATE INDEX suseprod_pdid_idx
ON suseProducts (product_id);

  070701000009AF000081B400000000000000000000000167AE11140000052F000000000000000000000000000000000000007000000000susemanager-schema/upgrade/susemanager-schema-1.7.56.15-to-susemanager-schema-1.7.56.16/056-suseUpgradePath.sql   --
-- Copyright (c) 2012 Novell
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
--


create table
suseUpgradePath
(
    from_pdid     numeric not null
                  CONSTRAINT suse_upgpath_fromid_fk
                  REFERENCES suseProducts (id)
                  ON DELETE CASCADE,
    to_pdid       numeric not null
                  CONSTRAINT suse_upgpath_toid_fk
                  REFERENCES suseProducts (id)
                  ON DELETE CASCADE,
    created       timestamptz default (current_timestamp) not null,
    modified      timestamptz default (current_timestamp) not null
);

CREATE INDEX suseupgpath_fromid_idx
ON suseUpgradePath (from_pdid);

create or replace function suse_upgpath_mod_trig_fun() returns trigger
as
$$
begin
        new.modified := current_timestamp;

        return new;
end;
$$
language plpgsql;


create trigger
suseupgpath_mod_trig
before insert or update on suseUpgradePath
for each row
execute procedure suse_upgpath_mod_trig_fun();

 070701000009B0000081B400000000000000000000000167AE11140000021B000000000000000000000000000000000000007C00000000susemanager-schema/upgrade/susemanager-schema-1.7.56.15-to-susemanager-schema-1.7.56.16/099-add-distupgrade-action-type.sql   --
-- Copyright (c) 2012 Novell
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
--

insert into rhnActionType values (501, 'distupgrade.upgrade', 'Service Pack Migration', 'N', 'N');
commit;
 070701000009B1000081B400000000000000000000000167AE1114000006D9000000000000000000000000000000000000006D00000000susemanager-schema/upgrade/susemanager-schema-1.7.56.15-to-susemanager-schema-1.7.56.16/100-rhnActionDup.sql  --
-- Copyright (c) 2012, Novell Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--


CREATE TABLE rhnActionDup
(
    id                  NUMERIC NOT NULL
                            CONSTRAINT rhn_actiondup_id_pk PRIMARY KEY,
    action_id           NUMERIC NOT NULL
                            CONSTRAINT rhn_actiondup_aid_fk
                            REFERENCES rhnAction (id)
                            ON DELETE CASCADE,
    dry_run             CHAR(1)
                            DEFAULT ('N') NOT NULL
                            CONSTRAINT rhn_actiondup_dr_ck
                                CHECK (dry_run in ('Y','N')),
    full_update         CHAR(1)
                            DEFAULT ('Y') NOT NULL
                            CONSTRAINT rhn_actiondup_fu_ck
                                CHECK (full_update in ('Y','N')),
    created             timestamptz default (current_timestamp) not null,
    modified            timestamptz default (current_timestamp) not null
)
;

CREATE UNIQUE INDEX rhn_actiondup_aid_uq
ON rhnActionDup (action_id);

CREATE SEQUENCE rhn_actiondup_id_seq;

create or replace function rhn_actiondup_mod_trig_fun() returns trigger as
$$
begin
	new.modified := current_timestamp;
	return new;
end;
$$ language plpgsql;

create trigger
rhn_actiondup_mod_trig
before insert or update on rhnActionDup
for each row
execute procedure rhn_actiondup_mod_trig_fun();

   070701000009B2000081B400000000000000000000000167AE1114000006CE000000000000000000000000000000000000007400000000susemanager-schema/upgrade/susemanager-schema-1.7.56.15-to-susemanager-schema-1.7.56.16/101-rhnActionDupChannel.sql   --
-- Copyright (c) 2012, Novell Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--


CREATE TABLE rhnActionDupChannel
(
    action_dup_id       NUMERIC NOT NULL
                            CONSTRAINT rhn_actdupchan_dupid_fk
                            REFERENCES rhnActionDup (id)
                            ON DELETE CASCADE,
    channel_id          NUMERIC NOT NULL
                            CONSTRAINT rhn_actdupchan_chanid_fk
                            REFERENCES rhnChannel (id)
                            ON DELETE CASCADE,
    task                CHAR(1)
                            DEFAULT ('S') NOT NULL
                            CONSTRAINT rhn_actdupchan_task_ck
                                CHECK (task in ('S','U')),
    created             timestamptz default (current_timestamp) not null,
    modified            timestamptz default (current_timestamp) not null
)
;

CREATE UNIQUE INDEX rhn_actdupchan_aid_cid_uq
    ON rhnActionDupChannel (action_dup_id, channel_id);

CREATE INDEX rhn_actdupchan_cid_idx
    ON rhnActionDupChannel (channel_id);

create or replace function rhn_actiondupchan_mod_trig_fun() returns trigger as
$$
begin
	new.modified := current_timestamp;
	return new;
end;
$$ language plpgsql;

create trigger
rhn_actiondupchan_mod_trig
before insert or update on rhnActionDupChannel
for each row
execute procedure rhn_actiondupchan_mod_trig_fun();

  070701000009B3000081B400000000000000000000000167AE11140000069B000000000000000000000000000000000000007400000000susemanager-schema/upgrade/susemanager-schema-1.7.56.15-to-susemanager-schema-1.7.56.16/102-rhnActionDupProduct.sql   --
-- Copyright (c) 2012, Novell Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--


CREATE TABLE rhnActionDupProduct
(
    action_dup_id       NUMERIC NOT NULL
                            CONSTRAINT rhn_actdupchanprof_dupid_fk
                            REFERENCES rhnActionDup (id)
                            ON DELETE CASCADE,
    from_pdid           NUMERIC NOT NULL
                            CONSTRAINT rhn_actdupchanprod_fpdid_fk
                            REFERENCES suseProducts (id)
                            ON DELETE CASCADE,
    to_pdid             NUMERIC NOT NULL
                            CONSTRAINT rhn_actdupchanprod_tpdid_fk
                            REFERENCES suseProducts (id)
                            ON DELETE CASCADE,
    created             timestamptz default (current_timestamp) not null,
    modified            timestamptz default (current_timestamp) not null
)
;

CREATE UNIQUE INDEX rhn_actdupchan_aid_pdids_uq
    ON rhnActionDupProduct (action_dup_id, from_pdid, to_pdid);

create or replace function rhn_actiondupprod_mod_trig_fun() returns trigger as
$$
begin
	new.modified := current_timestamp;
	return new;
end;
$$ language plpgsql;

create trigger
rhn_actiondupprod_mod_trig
before insert or update on rhnActionDupProduct
for each row
execute procedure rhn_actiondupprod_mod_trig_fun();

 070701000009B4000081B400000000000000000000000167AE11140000059F000000000000000000000000000000000000007D00000000susemanager-schema/upgrade/susemanager-schema-1.7.56.15-to-susemanager-schema-1.7.56.16/103-suseProductChannel-add-label.sql  --
-- Copyright (c) 2010-2012 Novell
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
--

drop index suse_prd_chan_uq;

alter table suseProductChannel alter column channel_id drop not null;

alter table suseProductChannel add column channel_label VARCHAR(128) NOT NULL DEFAULT '';
alter table suseProductChannel add column parent_channel_label VARCHAR(128);

update suseProductChannel
   set channel_label = c.label
  from rhnChannel c
 where suseProductChannel.channel_id = c.id;

update suseProductChannel
   set parent_channel_label = ( select c.label
                                  from rhnChannel c
                                 where c.id = (select c2.parent_channel
                                                 from rhnChannel c2
                                                where c2.id = suseProductChannel.channel_id));

CREATE UNIQUE INDEX suse_prd_chan_label_uq
ON suseProductChannel (product_id, channel_label);

alter table suseProductChannel alter column channel_label drop default;

CREATE INDEX suse_prd_chan_pcl_idx
ON suseProductChannel (parent_channel_label);
 070701000009B5000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005A00000000susemanager-schema/upgrade/susemanager-schema-1.7.56.16-to-susemanager-schema-1.7.56.16.1 070701000009B6000081B400000000000000000000000167AE111400000249000000000000000000000000000000000000007D00000000susemanager-schema/upgrade/susemanager-schema-1.7.56.16-to-susemanager-schema-1.7.56.16.1/001-add-column-ssh-server-push.sql  --
-- Copyright (c) 2012 Novell, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--

ALTER TABLE rhnServer ADD ssh_server_push CHAR(1) DEFAULT ('N') NOT NULL
    CONSTRAINT rhn_ssh_server_push_ck CHECK (ssh_server_push in ('Y', 'N'));
   070701000009B7000081B400000000000000000000000167AE1114000005EE000000000000000000000000000000000000007B00000000susemanager-schema/upgrade/susemanager-schema-1.7.56.16-to-susemanager-schema-1.7.56.16.1/002-add-task-ssh-server-push.sql    --
-- Copyright (c) 2012 Novell, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--

-- Insert task and map to the Java class
INSERT INTO rhnTaskoTask (id, name, class)
    VALUES (sequence_nextval('rhn_tasko_task_id_seq'), 'ssh-server-push',
        'com.redhat.rhn.taskomatic.task.SSHServerPush');

-- Insert bunch
INSERT INTO rhnTaskoBunch (id, name, description, org_bunch)
    VALUES (sequence_nextval('rhn_tasko_bunch_id_seq'), 'ssh-server-push-bunch',
        'Push scheduled actions to clients via ssh', null);

-- Insert template
INSERT INTO rhnTaskoTemplate (id, bunch_id, task_id, ordering, start_if)
    VALUES (sequence_nextval('rhn_tasko_template_id_seq'),
        (SELECT id FROM rhnTaskoBunch WHERE name='ssh-server-push-bunch'),
        (SELECT id FROM rhnTaskoTask WHERE name='ssh-server-push'),
        0, null);

-- Insert schedule for task (run once every minute)
INSERT INTO rhnTaskoSchedule (id, job_label, bunch_id, active_from, cron_expr)
    VALUES (sequence_nextval('rhn_tasko_schedule_id_seq'), 'ssh-server-push-default',
        (SELECT id FROM rhnTaskoBunch WHERE name='ssh-server-push-bunch'),
        current_timestamp, '0 * * * * ?');
  070701000009B8000081B400000000000000000000000167AE111400000117000000000000000000000000000000000000006E00000000susemanager-schema/upgrade/susemanager-schema-1.7.56.16-to-susemanager-schema-1.7.56.16.1/004-rhnTimezone.sql update rhnTimezone
   set display_name = 'Australia (Eastern Daylight)'
 where olson_name = 'Australia/Sydney';

insert into rhnTimezone
  (id, olson_name, display_name)
values
  (sequence_nextval('rhn_timezone_id_seq'),
   'Australia/Brisbane', 'Australia (Eastern Standard)');
 070701000009B9000081B400000000000000000000000167AE111400000088000000000000000000000000000000000000006E00000000susemanager-schema/upgrade/susemanager-schema-1.7.56.16-to-susemanager-schema-1.7.56.16.1/005-rhnTimezone.sql update rhnTimezone
   set olson_name = 'Australia/Perth'
 where olson_name = 'Asia/Hong_Kong' and display_name = 'Australia (Western)';
070701000009BA000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005C00000000susemanager-schema/upgrade/susemanager-schema-1.7.56.16.1-to-susemanager-schema-1.7.56.16.2   070701000009BB000081B400000000000000000000000167AE111400000352000000000000000000000000000000000000008300000000susemanager-schema/upgrade/susemanager-schema-1.7.56.16.1-to-susemanager-schema-1.7.56.16.2/001-suseServerContactMethod_create.sql    --
-- Copyright (c) 2013 SUSE
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--

CREATE TABLE suseServerContactMethod
(
    id        NUMERIC NOT NULL
                  CONSTRAINT suse_cont_meth_id_pk PRIMARY KEY,
    label     VARCHAR(64) NOT NULL,
    name      VARCHAR(128) NOT NULL,
    rank      NUMERIC NOT NULL
);

CREATE INDEX suse_cont_meth_label_id_idx
    ON suseServerContactMethod (label, id);

ALTER TABLE suseServerContactMethod
    ADD CONSTRAINT suse_cont_meth_label_uq UNIQUE (label);

  070701000009BC000081B400000000000000000000000167AE111400000328000000000000000000000000000000000000008300000000susemanager-schema/upgrade/susemanager-schema-1.7.56.16.1-to-susemanager-schema-1.7.56.16.2/002-suseServerContactMethod_insert.sql    --
-- Copyright (c) 2013 SUSE
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--

insert into suseServerContactMethod (id, label, name, rank) values
	(0, 'default', 'server.contact-method.default', 0);
insert into suseServerContactMethod (id, label, name, rank) values
	(1, 'ssh-push', 'server.contact-method.ssh-push', 10);
insert into suseServerContactMethod (id, label, name, rank) values
	(2, 'ssh-push-tunnel', 'server.contact-method.ssh-push-tunnel', 20);

070701000009BD000081B400000000000000000000000167AE1114000003EA000000000000000000000000000000000000007E00000000susemanager-schema/upgrade/susemanager-schema-1.7.56.16.1-to-susemanager-schema-1.7.56.16.2/003-add-column-contact-method.sql --
-- Copyright (c) 2013 SUSE
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--

-- Create new column for rhnServer
ALTER TABLE rhnServer ADD contact_method_id NUMERIC DEFAULT (0) NOT NULL
    CONSTRAINT rhn_server_cmid_fk
        REFERENCES suseServerContactMethod (id);

-- Migrate values from old column
UPDATE rhnServer
   SET contact_method_id = 2
 WHERE ssh_server_push = 'Y';

-- Remove old column
ALTER TABLE rhnServer DROP COLUMN ssh_server_push;

-- Create new column for rhnRegToken
ALTER TABLE rhnRegToken ADD contact_method_id NUMERIC DEFAULT (0) NOT NULL
    CONSTRAINT rhn_reg_token_cmid_fk
        REFERENCES suseServerContactMethod (id);

  070701000009BE000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005A00000000susemanager-schema/upgrade/susemanager-schema-1.7.56.16.2-to-susemanager-schema-1.7.56.18 070701000009BF000081B400000000000000000000000167AE11140000032B000000000000000000000000000000000000007300000000susemanager-schema/upgrade/susemanager-schema-1.7.56.16.2-to-susemanager-schema-1.7.56.18/0001-rename-ssh-push.sql    --
-- Copyright (c) 2013 Novell, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--

UPDATE rhnTaskoTask
SET name = 'ssh-push', class = 'com.redhat.rhn.taskomatic.task.SSHPush'
WHERE name = 'ssh-server-push';

UPDATE rhnTaskoBunch
SET name = 'ssh-push-bunch', description = 'Push scheduled actions to clients via SSH'
WHERE name = 'ssh-server-push-bunch';

UPDATE rhnTaskoSchedule
SET job_label = 'ssh-push-default'
WHERE job_label = 'ssh-server-push-default';
 070701000009C0000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005800000000susemanager-schema/upgrade/susemanager-schema-1.7.56.17-to-susemanager-schema-1.7.56.18   070701000009C1000081B400000000000000000000000167AE1114000005BE000000000000000000000000000000000000007900000000susemanager-schema/upgrade/susemanager-schema-1.7.56.17-to-susemanager-schema-1.7.56.18/001-add-task-ssh-server-push.sql  --
-- Copyright (c) 2013 Novell, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--

-- Insert task and map to the Java class
INSERT INTO rhnTaskoTask (id, name, class)
    VALUES (sequence_nextval('rhn_tasko_task_id_seq'), 'ssh-push',
        'com.redhat.rhn.taskomatic.task.SSHPush');

-- Insert bunch
INSERT INTO rhnTaskoBunch (id, name, description, org_bunch)
    VALUES (sequence_nextval('rhn_tasko_bunch_id_seq'), 'ssh-push-bunch',
        'Push scheduled actions to clients via ssh', null);

-- Insert template
INSERT INTO rhnTaskoTemplate (id, bunch_id, task_id, ordering, start_if)
    VALUES (sequence_nextval('rhn_tasko_template_id_seq'),
        (SELECT id FROM rhnTaskoBunch WHERE name='ssh-push-bunch'),
        (SELECT id FROM rhnTaskoTask WHERE name='ssh-push'),
        0, null);

-- Insert schedule for task (run once every minute)
INSERT INTO rhnTaskoSchedule (id, job_label, bunch_id, active_from, cron_expr)
    VALUES (sequence_nextval('rhn_tasko_schedule_id_seq'), 'ssh-push-default',
        (SELECT id FROM rhnTaskoBunch WHERE name='ssh-push-bunch'),
        current_timestamp, '0 * * * * ?');
  070701000009C2000081B400000000000000000000000167AE11140000035A000000000000000000000000000000000000007F00000000susemanager-schema/upgrade/susemanager-schema-1.7.56.17-to-susemanager-schema-1.7.56.18/002-suseServerContactMethod_create.sql    --
-- Copyright (c) 2013 Novell, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--

CREATE TABLE suseServerContactMethod
(
    id        NUMERIC NOT NULL
                  CONSTRAINT suse_cont_meth_id_pk PRIMARY KEY,
    label     VARCHAR(64) NOT NULL,
    name      VARCHAR(128) NOT NULL,
    rank      NUMERIC NOT NULL
);

CREATE INDEX suse_cont_meth_label_id_idx
    ON suseServerContactMethod (label, id);

ALTER TABLE suseServerContactMethod
    ADD CONSTRAINT suse_cont_meth_label_uq UNIQUE (label);

  070701000009C3000081B400000000000000000000000167AE111400000330000000000000000000000000000000000000007F00000000susemanager-schema/upgrade/susemanager-schema-1.7.56.17-to-susemanager-schema-1.7.56.18/003-suseServerContactMethod_insert.sql    --
-- Copyright (c) 2013 Novell, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--

insert into suseServerContactMethod (id, label, name, rank) values
	(0, 'default', 'server.contact-method.default', 0);
insert into suseServerContactMethod (id, label, name, rank) values
	(1, 'ssh-push', 'server.contact-method.ssh-push', 10);
insert into suseServerContactMethod (id, label, name, rank) values
	(2, 'ssh-push-tunnel', 'server.contact-method.ssh-push-tunnel', 20);

070701000009C4000081B400000000000000000000000167AE11140000033A000000000000000000000000000000000000007A00000000susemanager-schema/upgrade/susemanager-schema-1.7.56.17-to-susemanager-schema-1.7.56.18/004-add-column-contact-method.sql --
-- Copyright (c) 2013 Novell, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--

-- Create new column for rhnServer
ALTER TABLE rhnServer ADD contact_method_id NUMERIC DEFAULT (0) NOT NULL
    CONSTRAINT rhn_server_cmid_fk
        REFERENCES suseServerContactMethod (id);

-- Create new column for rhnRegToken
ALTER TABLE rhnRegToken ADD contact_method_id NUMERIC DEFAULT (0) NOT NULL
    CONSTRAINT rhn_reg_token_cmid_fk
        REFERENCES suseServerContactMethod (id);

  070701000009C5000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005800000000susemanager-schema/upgrade/susemanager-schema-1.7.56.18-to-susemanager-schema-1.7.56.19   070701000009C6000081B400000000000000000000000167AE111400000067000000000000000000000000000000000000007500000000susemanager-schema/upgrade/susemanager-schema-1.7.56.18-to-susemanager-schema-1.7.56.19/001-trim-package-summary.sql  
update rhnPackage
   set summary = rtrim(summary, chr(10))
 where summary <> rtrim(summary, chr(10));
 070701000009C7000081B400000000000000000000000167AE1114000000F8000000000000000000000000000000000000007700000000susemanager-schema/upgrade/susemanager-schema-1.7.56.18-to-susemanager-schema-1.7.56.19/002-delete-cached-repodata.sql    delete from rhnPackageRepodata;

insert into rhnRepoRegenQueue (id, CHANNEL_LABEL, REASON, FORCE)
(select sequence_nextval('rhn_repo_regen_queue_id_seq'),
        C.label,
        'package summary modification',
        'Y'
   from rhnChannel C);

070701000009C8000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005A00000000susemanager-schema/upgrade/susemanager-schema-1.7.56.19-to-susemanager-schema-1.7.56.19.1 070701000009C9000081B400000000000000000000000167AE111400000472000000000000000000000000000000000000007700000000susemanager-schema/upgrade/susemanager-schema-1.7.56.19-to-susemanager-schema-1.7.56.19.1/000-suseCVEServerChannel.sql    --
-- Copyright (c) 2013 SUSE
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--

CREATE TABLE suseCVEServerChannel
(
    server_id    NUMERIC NOT NULL
                     CONSTRAINT suse_cvesc_sid_fk
                         REFERENCES rhnServer (id),
    channel_id   NUMERIC NOT NULL
                     CONSTRAINT suse_cvesc_cid_fk
                         REFERENCES rhnChannel (id),
    channel_rank NUMERIC NOT NULL,
    created      TIMESTAMPTZ
                     DEFAULT (CURRENT_TIMESTAMP) NOT NULL,
    modified     TIMESTAMPTZ
                     DEFAULT (CURRENT_TIMESTAMP) NOT NULL
)

;

CREATE UNIQUE INDEX suse_cvesc_sid_cid_uq
    ON suseCVEServerChannel (server_id, channel_id)
    ;

CREATE INDEX suse_cvesc_cid_idx
    ON suseCVEServerChannel (channel_id)
    
    ;

  070701000009CA000081B400000000000000000000000167AE111400000613000000000000000000000000000000000000007100000000susemanager-schema/upgrade/susemanager-schema-1.7.56.19-to-susemanager-schema-1.7.56.19.1/001-taskomatic-job.sql  --
-- Copyright (c) 2013 SUSE
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--

-- Insert task and map to the Java class
INSERT INTO rhnTaskoTask (id, name, class)
    VALUES (sequence_nextval('rhn_tasko_task_id_seq'), 'cve-server-channels',
        'com.redhat.rhn.taskomatic.task.CVEServerChannels');

-- Insert bunch
INSERT INTO rhnTaskoBunch (id, name, description, org_bunch)
    VALUES (sequence_nextval('rhn_tasko_bunch_id_seq'), 'cve-server-channels-bunch',
        'Generate data required for performing CVE audit queries.', null);

-- Insert template
INSERT INTO rhnTaskoTemplate (id, bunch_id, task_id, ordering, start_if)
    VALUES (sequence_nextval('rhn_tasko_template_id_seq'),
        (SELECT id FROM rhnTaskoBunch WHERE name='cve-server-channels-bunch'),
        (SELECT id FROM rhnTaskoTask WHERE name='cve-server-channels'),
        0, null);

-- Insert schedule for task (once a day at 11:00 PM)
INSERT INTO rhnTaskoSchedule (id, job_label, bunch_id, active_from, cron_expr)
    VALUES (sequence_nextval('rhn_tasko_schedule_id_seq'), 'cve-server-channels-default',
        (SELECT id FROM rhnTaskoBunch WHERE name='cve-server-channels-bunch'),
        current_timestamp, '0 0 23 ? * *');
 070701000009CB000081B400000000000000000000000167AE11140000026A000000000000000000000000000000000000007B00000000susemanager-schema/upgrade/susemanager-schema-1.7.56.19-to-susemanager-schema-1.7.56.19.1/002-add-column-csv-separator.sql    --
-- Copyright (c) 2013 SUSE
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--

-- Create new column for rhnUserInfo
ALTER TABLE rhnUserInfo ADD csv_separator CHAR(1) DEFAULT (',') NOT NULL
    CONSTRAINT rhn_user_info_csv_ck
        CHECK (csv_separator in (',',';'));

  070701000009CC000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005800000000susemanager-schema/upgrade/susemanager-schema-1.7.56.19-to-susemanager-schema-1.7.56.20   070701000009CD000081B400000000000000000000000167AE11140000004B000000000000000000000000000000000000007D00000000susemanager-schema/upgrade/susemanager-schema-1.7.56.19-to-susemanager-schema-1.7.56.20/001-mgr-register-bunch-as-common.sql  update rhntaskobunch set org_bunch=null where name = 'mgr-register-bunch';
 070701000009CE000081B400000000000000000000000167AE1114000000F8000000000000000000000000000000000000007700000000susemanager-schema/upgrade/susemanager-schema-1.7.56.19-to-susemanager-schema-1.7.56.20/002-delete-cached-repodata.sql    delete from rhnPackageRepodata;

insert into rhnRepoRegenQueue (id, CHANNEL_LABEL, REASON, FORCE)
(select sequence_nextval('rhn_repo_regen_queue_id_seq'),
        C.label,
        'package summary modification',
        'Y'
   from rhnChannel C);

070701000009CF000081B400000000000000000000000167AE111400000472000000000000000000000000000000000000007500000000susemanager-schema/upgrade/susemanager-schema-1.7.56.19-to-susemanager-schema-1.7.56.20/003-suseCVEServerChannel.sql  --
-- Copyright (c) 2013 SUSE
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--

CREATE TABLE suseCVEServerChannel
(
    server_id    NUMERIC NOT NULL
                     CONSTRAINT suse_cvesc_sid_fk
                         REFERENCES rhnServer (id),
    channel_id   NUMERIC NOT NULL
                     CONSTRAINT suse_cvesc_cid_fk
                         REFERENCES rhnChannel (id),
    channel_rank NUMERIC NOT NULL,
    created      TIMESTAMPTZ
                     DEFAULT (CURRENT_TIMESTAMP) NOT NULL,
    modified     TIMESTAMPTZ
                     DEFAULT (CURRENT_TIMESTAMP) NOT NULL
)

;

CREATE UNIQUE INDEX suse_cvesc_sid_cid_uq
    ON suseCVEServerChannel (server_id, channel_id)
    ;

CREATE INDEX suse_cvesc_cid_idx
    ON suseCVEServerChannel (channel_id)
    
    ;

  070701000009D0000081B400000000000000000000000167AE111400000613000000000000000000000000000000000000006F00000000susemanager-schema/upgrade/susemanager-schema-1.7.56.19-to-susemanager-schema-1.7.56.20/004-taskomatic-job.sql    --
-- Copyright (c) 2013 SUSE
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--

-- Insert task and map to the Java class
INSERT INTO rhnTaskoTask (id, name, class)
    VALUES (sequence_nextval('rhn_tasko_task_id_seq'), 'cve-server-channels',
        'com.redhat.rhn.taskomatic.task.CVEServerChannels');

-- Insert bunch
INSERT INTO rhnTaskoBunch (id, name, description, org_bunch)
    VALUES (sequence_nextval('rhn_tasko_bunch_id_seq'), 'cve-server-channels-bunch',
        'Generate data required for performing CVE audit queries.', null);

-- Insert template
INSERT INTO rhnTaskoTemplate (id, bunch_id, task_id, ordering, start_if)
    VALUES (sequence_nextval('rhn_tasko_template_id_seq'),
        (SELECT id FROM rhnTaskoBunch WHERE name='cve-server-channels-bunch'),
        (SELECT id FROM rhnTaskoTask WHERE name='cve-server-channels'),
        0, null);

-- Insert schedule for task (once a day at 11:00 PM)
INSERT INTO rhnTaskoSchedule (id, job_label, bunch_id, active_from, cron_expr)
    VALUES (sequence_nextval('rhn_tasko_schedule_id_seq'), 'cve-server-channels-default',
        (SELECT id FROM rhnTaskoBunch WHERE name='cve-server-channels-bunch'),
        current_timestamp, '0 0 23 ? * *');
 070701000009D1000081B400000000000000000000000167AE11140000026A000000000000000000000000000000000000007900000000susemanager-schema/upgrade/susemanager-schema-1.7.56.19-to-susemanager-schema-1.7.56.20/005-add-column-csv-separator.sql  --
-- Copyright (c) 2013 SUSE
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--

-- Create new column for rhnUserInfo
ALTER TABLE rhnUserInfo ADD csv_separator CHAR(1) DEFAULT (',') NOT NULL
    CONSTRAINT rhn_user_info_csv_ck
        CHECK (csv_separator in (',',';'));

  070701000009D2000081B400000000000000000000000167AE1114000001E7000000000000000000000000000000000000007E00000000susemanager-schema/upgrade/susemanager-schema-1.7.56.19-to-susemanager-schema-1.7.56.20/006-add-missing-on-delete-cascade.sql -- Recreate FK constraint on rhnChannel
ALTER TABLE suseCVEServerChannel DROP CONSTRAINT suse_cvesc_cid_fk;
ALTER TABLE suseCVEServerChannel ADD CONSTRAINT suse_cvesc_cid_fk FOREIGN KEY (channel_id) REFERENCES rhnChannel(id) ON DELETE CASCADE;

-- Recreate FK constraint on rhnServer
ALTER TABLE suseCVEServerChannel DROP CONSTRAINT suse_cvesc_sid_fk;
ALTER TABLE suseCVEServerChannel ADD CONSTRAINT suse_cvesc_sid_fk FOREIGN KEY (server_id) REFERENCES rhnServer(id) ON DELETE CASCADE;

 070701000009D3000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005A00000000susemanager-schema/upgrade/susemanager-schema-1.7.56.19.1-to-susemanager-schema-1.7.56.20 070701000009D4000081B400000000000000000000000167AE11140000004B000000000000000000000000000000000000007F00000000susemanager-schema/upgrade/susemanager-schema-1.7.56.19.1-to-susemanager-schema-1.7.56.20/001-mgr-register-bunch-as-common.sql    update rhntaskobunch set org_bunch=null where name = 'mgr-register-bunch';
 070701000009D5000081B400000000000000000000000167AE1114000000F8000000000000000000000000000000000000007900000000susemanager-schema/upgrade/susemanager-schema-1.7.56.19.1-to-susemanager-schema-1.7.56.20/002-delete-cached-repodata.sql  delete from rhnPackageRepodata;

insert into rhnRepoRegenQueue (id, CHANNEL_LABEL, REASON, FORCE)
(select sequence_nextval('rhn_repo_regen_queue_id_seq'),
        C.label,
        'package summary modification',
        'Y'
   from rhnChannel C);

070701000009D6000081B400000000000000000000000167AE1114000001E7000000000000000000000000000000000000008000000000susemanager-schema/upgrade/susemanager-schema-1.7.56.19.1-to-susemanager-schema-1.7.56.20/003-add-missing-on-delete-cascade.sql   -- Recreate FK constraint on rhnChannel
ALTER TABLE suseCVEServerChannel DROP CONSTRAINT suse_cvesc_cid_fk;
ALTER TABLE suseCVEServerChannel ADD CONSTRAINT suse_cvesc_cid_fk FOREIGN KEY (channel_id) REFERENCES rhnChannel(id) ON DELETE CASCADE;

-- Recreate FK constraint on rhnServer
ALTER TABLE suseCVEServerChannel DROP CONSTRAINT suse_cvesc_sid_fk;
ALTER TABLE suseCVEServerChannel ADD CONSTRAINT suse_cvesc_sid_fk FOREIGN KEY (server_id) REFERENCES rhnServer(id) ON DELETE CASCADE;

 070701000009D7000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005800000000susemanager-schema/upgrade/susemanager-schema-1.7.56.20-to-susemanager-schema-1.7.56.21   070701000009D8000081B400000000000000000000000167AE111400000CCC000000000000000000000000000000000000007200000000susemanager-schema/upgrade/susemanager-schema-1.7.56.20-to-susemanager-schema-1.7.56.21/015-evr_t-max-replace.sql 
CREATE OR REPLACE VIEW
rhnServerNeededView
(
    org_id,
    server_id,
    errata_id,
    package_id,
    package_name_id,
    channel_id
)
AS
select 1.0, 1.0, 1.0, 1.0, 1.0, 1.0 from dual;

create or replace view
rhnChannelNewestPackageView
as
SELECT 1.0 as channel_id,
       1.0 as name_id,
       1.0 as evr_id,
       1.0 as package_arch_id,
       1.0 as package_id from dual;

-- this is the part we actually care about, messing with the views
-- is just a dance to get this to work
drop aggregate if exists max(evr_t);

create aggregate max (
  sfunc=evr_t_larger,
  basetype=evr_t,
  stype=evr_t
);

-- replace the views back to what they actually should be
CREATE OR REPLACE VIEW
rhnServerNeededView
(
    org_id,
    server_id,
    errata_id,
    package_id,
    package_name_id,
    channel_id
)
AS
SELECT s.org_id,
       sp.server_id,
       x.errata_id,
       up.id,
       up.name_id,
       x.channel_id
    FROM rhnServer s
        join (SELECT sp_sp.server_id, sp_sp.name_id, sp_sp.package_arch_id, max(sp_pe.evr) AS max_evr
                FROM rhnServerPackage sp_sp
                    join rhnPackageEvr sp_pe ON sp_pe.id = sp_sp.evr_id
                    GROUP BY sp_sp.server_id, sp_sp.name_id, sp_sp.package_arch_id) sp ON sp.server_id = s.id
        join rhnPackage up ON up.name_id = sp.name_id
        join rhnPackageEvr upe ON upe.id = up.evr_id AND sp.max_evr < upe.evr
        join rhnPackageUpgradeArchCompat puac ON puac.package_arch_id = sp.package_arch_id AND puac.package_upgrade_arch_id = up.package_arch_id
        join rhnServerChannel sc ON sc.server_id = sp.server_id
        join rhnChannelPackage cp ON cp.package_id = up.id AND cp.channel_id = sc.channel_id
        left join
        (SELECT ep.errata_id, cp.channel_id, ep.package_id
         FROM rhnChannelErrata cp
             join rhnErrataPackage ep ON ep.errata_id = cp.errata_id) x
            ON x.channel_id = sc.channel_id AND x.package_id = cp.package_id
;


create or replace view
rhnChannelNewestPackageView
as
SELECT channel_id,
       name_id,
       evr_id,
       package_arch_id,
       max(package_id) as package_id
FROM (
       SELECT m.channel_id          as channel_id,
              p.name_id             as name_id,
              p.evr_id              as evr_id,
              m.package_arch_id     as package_arch_id,
              p.id                  as package_id
         FROM
              (select max(pe.evr) AS max_evr,
                      cp.channel_id,
                      p.name_id,
                      p.package_arch_id
                 from rhnPackageEVR       pe,
                      rhnPackage          p,
                      rhnChannelPackage   cp
                where p.evr_id = pe.id
                  and cp.package_id = p.id
                group by cp.channel_id, p.name_id, p.package_arch_id) m,
              rhnPackageEVR       pe,
              rhnPackage          p,
              rhnChannelPackage   chp
        WHERE m.max_evr = pe.evr
          AND m.name_id = p.name_id
          AND m.package_arch_id = p.package_arch_id
          AND p.evr_id = pe.id
          AND chp.package_id = p.id
          AND chp.channel_id = m.channel_id
) latest_packages
group by channel_id, name_id, evr_id, package_arch_id
;

070701000009D9000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005800000000susemanager-schema/upgrade/susemanager-schema-1.7.56.21-to-susemanager-schema-1.7.56.22   070701000009DA000081B400000000000000000000000167AE1114000004C4000000000000000000000000000000000000007300000000susemanager-schema/upgrade/susemanager-schema-1.7.56.21-to-susemanager-schema-1.7.56.22/001-rhnPackageEnhances.sql    --
-- Copyright (c) 2013 Novell
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
--


CREATE TABLE rhnPackageEnhances
(
    package_id     NUMERIC NOT NULL
                       CONSTRAINT rhn_pkg_enh_package_fk
                           REFERENCES rhnPackage (id)
                           ON DELETE CASCADE,
    capability_id  NUMERIC NOT NULL
                       CONSTRAINT rhn_pkg_enh_capability_fk
                           REFERENCES rhnPackageCapability (id),
    sense          NUMERIC
                       DEFAULT (0) NOT NULL,
    created        timestamptz default (current_timestamp) not null,
    modified       timestamptz default (current_timestamp) not null
)
;

CREATE UNIQUE INDEX rhn_pkg_enh_pid_cid_s_uq
    ON rhnPackageEnhances (package_id, capability_id, sense);

CREATE INDEX rhn_pkg_enh_cid_idx
    ON rhnPackageEnhances (capability_id);

070701000009DB000081B400000000000000000000000167AE1114000002E3000000000000000000000000000000000000007300000000susemanager-schema/upgrade/susemanager-schema-1.7.56.21-to-susemanager-schema-1.7.56.22/002-rhnPackageEnhances.sql    --
-- Copyright (c) 2013 Novell, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
--

create or replace function rhn_pkg_enh_mod_trig_fun() returns trigger as
$$
begin
	new.modified := current_timestamp;

	return new;
end;
$$ language plpgsql;

create trigger
rhn_pkg_enh_mod_trig
before insert or update on rhnPackageEnhances
for each row
execute procedure rhn_pkg_enh_mod_trig_fun();

 070701000009DC000081B400000000000000000000000167AE11140000014B000000000000000000000000000000000000007900000000susemanager-schema/upgrade/susemanager-schema-1.7.56.21-to-susemanager-schema-1.7.56.22/003-fix-supplements-enhances.sql  
insert into rhnPackageEnhances (package_id, capability_id, sense)
  select s.package_id, s.capability_id, s.sense
    from rhnPackageSupplements s
   where (s.sense::bigint & 134217728) != 134217728;
-- 134217728 == (1 << 27) STRONG FLAG in RPM

delete from rhnPackageSupplements
 where (sense::bigint & 134217728) != 134217728;

 070701000009DD000081B400000000000000000000000167AE1114000000F8000000000000000000000000000000000000007700000000susemanager-schema/upgrade/susemanager-schema-1.7.56.21-to-susemanager-schema-1.7.56.22/004-delete-cached-repodata.sql    delete from rhnPackageRepodata;

insert into rhnRepoRegenQueue (id, CHANNEL_LABEL, REASON, FORCE)
(select sequence_nextval('rhn_repo_regen_queue_id_seq'),
        C.label,
        'package summary modification',
        'Y'
   from rhnChannel C);

070701000009DE000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005800000000susemanager-schema/upgrade/susemanager-schema-1.7.56.22-to-susemanager-schema-1.7.56.23   070701000009DF000081B400000000000000000000000167AE11140000003C000000000000000000000000000000000000007700000000susemanager-schema/upgrade/susemanager-schema-1.7.56.22-to-susemanager-schema-1.7.56.23/001-inc-length-rhnCVE-name.sql    
ALTER TABLE rhnCVE
    ALTER COLUMN name TYPE varchar(20);
070701000009E0000081B400000000000000000000000167AE111400000163000000000000000000000000000000000000007100000000susemanager-schema/upgrade/susemanager-schema-1.7.56.22-to-susemanager-schema-1.7.56.23/002-rhnTimezone-data.sql  insert into rhnTimezone (id, olson_name, display_name) (
    select sequence_nextval('rhn_timezone_id_seq'),
           'Asia/Riyadh',
           'Saudi Arabia'
      from dual
     where not exists (
           select 1
             from rhnTimezone
            where olson_name = 'Asia/Riyadh'
              and display_name = 'Saudi Arabia'
     )
);

 070701000009E1000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005500000000susemanager-schema/upgrade/susemanager-schema-1.7.56.22-to-susemanager-schema-1.7.57  070701000009E2000081B400000000000000000000000167AE111400000155000000000000000000000000000000000000005C00000000susemanager-schema/upgrade/susemanager-schema-1.7.56.22-to-susemanager-schema-1.7.57/README   -- Schema upgrade scripts.
-- leave this directory empty, all upgrades from 1.7 to 2.1 are covered by 1.7.57 to 2.1 upgrade
-- all scripts in susemanager-schema-1.7.56.22-to-susemanager-schema-1.7.56.23/ are repeated
-- in susemanager-schema-1.7.57-to-susemanager-schema-2.1/ and written in a way that they can
-- be executed multiple times
   070701000009E3000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005800000000susemanager-schema/upgrade/susemanager-schema-1.7.56.23-to-susemanager-schema-1.7.56.24   070701000009E4000081B400000000000000000000000167AE111400000277000000000000000000000000000000000000007400000000susemanager-schema/upgrade/susemanager-schema-1.7.56.23-to-susemanager-schema-1.7.56.24/001-add-SLES12-GPG-keys.sql   insert into rhnPackageKey (id, key_id, key_type_id, provider_id)
    (select sequence_nextval('rhn_pkey_id_seq'), '70af9e8139db7c82', lookup_package_key_type('gpg'), lookup_package_provider('SUSE LINUX Products GmbH') from dual
      where 1 not in (select 1 from rhnPackageKey where key_id = '70af9e8139db7c82'));

insert into rhnPackageKey (id, key_id, key_type_id, provider_id)
    (select sequence_nextval('rhn_pkey_id_seq'), '5eaf444450a3dd1c', lookup_package_key_type('gpg'), lookup_package_provider('SUSE LINUX Products GmbH') from dual
      where 1 not in (select 1 from rhnPackageKey where key_id = '5eaf444450a3dd1c'));
 070701000009E5000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005500000000susemanager-schema/upgrade/susemanager-schema-1.7.56.23-to-susemanager-schema-1.7.57  070701000009E6000081B400000000000000000000000167AE11140000007C000000000000000000000000000000000000005C00000000susemanager-schema/upgrade/susemanager-schema-1.7.56.23-to-susemanager-schema-1.7.57/README   -- Schema upgrade scripts.
-- leave this directory empty, all upgrades from 1.7 to 2.1 are covered by 1.7.57 to 2.1 upgrade
070701000009E7000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005500000000susemanager-schema/upgrade/susemanager-schema-1.7.56.24-to-susemanager-schema-1.7.57  070701000009E8000081B400000000000000000000000167AE111400000155000000000000000000000000000000000000005C00000000susemanager-schema/upgrade/susemanager-schema-1.7.56.24-to-susemanager-schema-1.7.57/README   -- Schema upgrade scripts.
-- leave this directory empty, all upgrades from 1.7 to 2.1 are covered by 1.7.57 to 2.1 upgrade
-- all scripts in susemanager-schema-1.7.56.23-to-susemanager-schema-1.7.56.24/ are repeated
-- in susemanager-schema-1.7.57-to-susemanager-schema-2.1/ and written in a way that they can
-- be executed multiple times
   070701000009E9000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000004F00000000susemanager-schema/upgrade/susemanager-schema-1.7.57-to-susemanager-schema-2.1    070701000009EA000081B400000000000000000000000167AE1114000000D1000000000000000000000000000000000000006E00000000susemanager-schema/upgrade/susemanager-schema-1.7.57-to-susemanager-schema-2.1/0031-no_operation_trig_fun.sql -- oracle equivalent source none

create function no_operation_trig_fun()
returns trigger as
$$
begin
	raise exception 'Permission denied: % is not allowed on %', TG_OP, TG_RELNAME;
end;
$$ language plpgsql;

   070701000009EB000081B400000000000000000000000167AE111400000080000000000000000000000000000000000000006E00000000susemanager-schema/upgrade/susemanager-schema-1.7.57-to-susemanager-schema-2.1/0032-rhnPackageEvr-trigger.sql 
create trigger
rhn_pack_evr_no_updel_trig
before update or delete on rhnPackageEvr
execute procedure no_operation_trig_fun();

070701000009EC000081B400000000000000000000000167AE11140000113B000000000000000000000000000000000000006A00000000susemanager-schema/upgrade/susemanager-schema-1.7.57-to-susemanager-schema-2.1/0036-support-for-armv7.sql insert into rhnChannelArch (id, label, name, arch_type_id) select
sequence_nextval('rhn_channel_arch_id_seq'), 'channel-armhfp', 'ARM hard. FP', lookup_arch_type('rpm') from dual
where not exists (select 1 from rhnChannelArch where label = 'channel-armhfp');

insert into rhnPackageArch (id, label, name, arch_type_id) select
sequence_nextval('rhn_package_arch_id_seq'), 'armv7hnl', 'ARMv7hnl', lookup_arch_type('rpm') from dual
where not exists (select 1 from rhnPackageArch where label = 'armv7hnl');
insert into rhnPackageArch (id, label, name, arch_type_id) select
sequence_nextval('rhn_package_arch_id_seq'), 'armv7hl', 'ARMv7hl', lookup_arch_type('rpm') from dual
where not exists (select 1 from rhnPackageArch where label = 'armv7hl');

insert into rhnChannelPackageArchCompat (channel_arch_id, package_arch_id) select
LOOKUP_CHANNEL_ARCH('channel-armhfp'), LOOKUP_PACKAGE_ARCH('armv7hnl') from dual
where not exists (select 1 from rhnChannelPackageArchCompat where channel_arch_id = LOOKUP_CHANNEL_ARCH('channel-armhfp') and package_arch_id = LOOKUP_PACKAGE_ARCH('armv7hnl'));
insert into rhnChannelPackageArchCompat (channel_arch_id, package_arch_id) select
LOOKUP_CHANNEL_ARCH('channel-armhfp'), LOOKUP_PACKAGE_ARCH('armv7hl') from dual
where not exists (select 1 from rhnChannelPackageArchCompat where channel_arch_id = LOOKUP_CHANNEL_ARCH('channel-armhfp') and package_arch_id = LOOKUP_PACKAGE_ARCH('armv7hnl'));
insert into rhnChannelPackageArchCompat (channel_arch_id, package_arch_id) select
LOOKUP_CHANNEL_ARCH('channel-armhfp'), LOOKUP_PACKAGE_ARCH('noarch') from dual
where not exists (select 1 from rhnChannelPackageArchCompat where channel_arch_id = LOOKUP_CHANNEL_ARCH('channel-armhfp') and package_arch_id = LOOKUP_PACKAGE_ARCH('noarch'));

insert into rhnServerArch (id, label, name, arch_type_id) select
sequence_nextval('rhn_server_arch_id_seq'), 'armv7l-redhat-linux', 'armv7l', lookup_arch_type('rpm') from dual
where not exists (select 1 from rhnServerArch where label = 'armv7l-redhat-linux');

insert into rhnServerChannelArchCompat (server_arch_id, channel_arch_id) select
LOOKUP_SERVER_ARCH('armv7l-redhat-linux'), LOOKUP_CHANNEL_ARCH('channel-armhfp') from dual
where not exists (select 1 from rhnServerChannelArchCompat where server_arch_id = LOOKUP_SERVER_ARCH('armv7l-redhat-linux') and channel_arch_id = LOOKUP_CHANNEL_ARCH('channel-armhfp'));


insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type) select
LOOKUP_SERVER_ARCH('armv7l-redhat-linux'), LOOKUP_SG_TYPE('sw_mgr_entitled') from dual
where not exists (select 1 from rhnServerServerGroupArchCompat where server_arch_id = LOOKUP_SERVER_ARCH('armv7l-redhat-linux') and server_group_type = LOOKUP_SG_TYPE('sw_mgr_entitled'));
insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type) select
LOOKUP_SERVER_ARCH('armv7l-redhat-linux'), LOOKUP_SG_TYPE('enterprise_entitled') from dual
where not exists (select 1 from rhnServerServerGroupArchCompat where server_arch_id = LOOKUP_SERVER_ARCH('armv7l-redhat-linux') and server_group_type = LOOKUP_SG_TYPE('enterprise_entitled'));
insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type) select
LOOKUP_SERVER_ARCH('armv7l-redhat-linux'), LOOKUP_SG_TYPE('provisioning_entitled') from dual
where not exists (select 1 from rhnServerServerGroupArchCompat where server_arch_id = LOOKUP_SERVER_ARCH('armv7l-redhat-linux') and server_group_type = LOOKUP_SG_TYPE('provisioning_entitled'));
insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type) select
LOOKUP_SERVER_ARCH('armv7l-redhat-linux'), LOOKUP_SG_TYPE('monitoring_entitled') from dual
where not exists (select 1 from rhnServerServerGroupArchCompat where server_arch_id = LOOKUP_SERVER_ARCH('armv7l-redhat-linux') and server_group_type = LOOKUP_SG_TYPE('monitoring_entitled'));
insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type) select
LOOKUP_SERVER_ARCH('armv7l-redhat-linux'), LOOKUP_SG_TYPE('virtualization_host') from dual
where not exists (select 1 from rhnServerServerGroupArchCompat where server_arch_id = LOOKUP_SERVER_ARCH('armv7l-redhat-linux') and server_group_type = LOOKUP_SG_TYPE('virtualization_host'));

insert into rhnCpuArch (id, label, name) select
sequence_nextval('rhn_cpu_arch_id_seq'), 'armv7l', 'ARMv7l' from dual
where not exists (select 1 from rhnCpuArch where label = 'armv7l');
 070701000009ED000081B400000000000000000000000167AE111400000B53000000000000000000000000000000000000007200000000susemanager-schema/upgrade/susemanager-schema-1.7.57-to-susemanager-schema-2.1/0037-support-for-armv5-channel.sql insert into rhnChannelArch (id, label, name, arch_type_id) values
        (sequence_nextval('rhn_channel_arch_id_seq'), 'channel-arm', 'ARM soft. FP', lookup_arch_type('rpm'));

insert into rhnPackageArch (id, label, name, arch_type_id) values
(sequence_nextval('rhn_package_arch_id_seq'), 'armv7l', 'ARMv7l', lookup_arch_type('rpm'));
insert into rhnPackageArch (id, label, name, arch_type_id) values
(sequence_nextval('rhn_package_arch_id_seq'), 'armv6l', 'ARMv6l', lookup_arch_type('rpm'));
insert into rhnPackageArch (id, label, name, arch_type_id) values
(sequence_nextval('rhn_package_arch_id_seq'), 'armv5tel', 'ARMv5tel', lookup_arch_type('rpm'));

insert into rhnChannelPackageArchCompat (channel_arch_id, package_arch_id)
        values (LOOKUP_CHANNEL_ARCH('channel-arm'), LOOKUP_PACKAGE_ARCH('armv7l'));
insert into rhnChannelPackageArchCompat (channel_arch_id, package_arch_id)
        values (LOOKUP_CHANNEL_ARCH('channel-arm'), LOOKUP_PACKAGE_ARCH('armv6l'));
insert into rhnChannelPackageArchCompat (channel_arch_id, package_arch_id)
        values (LOOKUP_CHANNEL_ARCH('channel-arm'), LOOKUP_PACKAGE_ARCH('armv5tel'));
insert into rhnChannelPackageArchCompat (channel_arch_id, package_arch_id)
		values (LOOKUP_CHANNEL_ARCH('channel-arm'), LOOKUP_PACKAGE_ARCH('noarch'));

insert into rhnServerArch (id, label, name, arch_type_id) values
(sequence_nextval('rhn_server_arch_id_seq'), 'armv5tejl-redhat-linux', 'armv5tejl', lookup_arch_type('rpm'));

insert into rhnServerChannelArchCompat (server_arch_id, channel_arch_id) values
        (LOOKUP_SERVER_ARCH('armv7l-redhat-linux'), LOOKUP_CHANNEL_ARCH('channel-arm'));
insert into rhnServerChannelArchCompat (server_arch_id, channel_arch_id) values
        (LOOKUP_SERVER_ARCH('armv5tejl-redhat-linux'), LOOKUP_CHANNEL_ARCH('channel-arm'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
        values (lookup_server_arch('armv5tejl-redhat-linux'),
            lookup_sg_type('sw_mgr_entitled'));
insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
        values (lookup_server_arch('armv5tejl-redhat-linux'),
            lookup_sg_type('enterprise_entitled'));
insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
        values (lookup_server_arch('armv5tejl-redhat-linux'),
            lookup_sg_type('provisioning_entitled'));
insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
        values (lookup_server_arch('armv5tejl-redhat-linux'),
            lookup_sg_type('monitoring_entitled'));
insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
        values (lookup_server_arch('armv5tejl-redhat-linux'),
            lookup_sg_type('virtualization_host'));

insert into rhnCpuArch (id, label, name) values
(sequence_nextval('rhn_cpu_arch_id_seq'), 'armv5tejl', 'ARMv5tejl');
 070701000009EE000081B400000000000000000000000167AE111400000033000000000000000000000000000000000000007600000000susemanager-schema/upgrade/susemanager-schema-1.7.57-to-susemanager-schema-2.1/0048-add_rhnPackage_installed_size.sql alter table rhnPackage add installed_size NUMERIC;
 070701000009EF000081B400000000000000000000000167AE111400000C71000000000000000000000000000000000000007400000000susemanager-schema/upgrade/susemanager-schema-1.7.57-to-susemanager-schema-2.1/0049-rhnPackageUpgradeArchCompat.sql   insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('noarch'), LOOKUP_PACKAGE_ARCH('armv7l'), current_timestamp, current_timestamp);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('armv7l'), LOOKUP_PACKAGE_ARCH('armv7l'), current_timestamp, current_timestamp);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('armv7l'), LOOKUP_PACKAGE_ARCH('noarch'), current_timestamp, current_timestamp);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('noarch'), LOOKUP_PACKAGE_ARCH('armv6l'), current_timestamp, current_timestamp);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('armv6l'), LOOKUP_PACKAGE_ARCH('armv6l'), current_timestamp, current_timestamp);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('armv6l'), LOOKUP_PACKAGE_ARCH('noarch'), current_timestamp, current_timestamp);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('noarch'), LOOKUP_PACKAGE_ARCH('armv5tel'), current_timestamp, current_timestamp);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('armv5tel'), LOOKUP_PACKAGE_ARCH('armv5tel'), current_timestamp, current_timestamp);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('armv5tel'), LOOKUP_PACKAGE_ARCH('noarch'), current_timestamp, current_timestamp);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('noarch'), LOOKUP_PACKAGE_ARCH('armv7hl'), current_timestamp, current_timestamp);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('armv7hl'), LOOKUP_PACKAGE_ARCH('armv7hl'), current_timestamp, current_timestamp);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('armv7hl'), LOOKUP_PACKAGE_ARCH('noarch'), current_timestamp, current_timestamp);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('noarch'), LOOKUP_PACKAGE_ARCH('armv7hnl'), current_timestamp, current_timestamp);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('armv7hnl'), LOOKUP_PACKAGE_ARCH('armv7hnl'), current_timestamp, current_timestamp);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('armv7hnl'), LOOKUP_PACKAGE_ARCH('noarch'), current_timestamp, current_timestamp);
   070701000009F0000081B400000000000000000000000167AE111400000577000000000000000000000000000000000000007300000000susemanager-schema/upgrade/susemanager-schema-1.7.57-to-susemanager-schema-2.1/0050-rhnServerPackageArchCompat.sql    insert into rhnServerPackageArchCompat
(server_arch_id, package_arch_id, preference) values
(LOOKUP_SERVER_ARCH('armv7l-redhat-linux'), LOOKUP_PACKAGE_ARCH('armv7hnl'), 0);

insert into rhnServerPackageArchCompat
(server_arch_id, package_arch_id, preference) values
(LOOKUP_SERVER_ARCH('armv7l-redhat-linux'), LOOKUP_PACKAGE_ARCH('armv7hl'), 10);

insert into rhnServerPackageArchCompat
(server_arch_id, package_arch_id, preference) values
(LOOKUP_SERVER_ARCH('armv7l-redhat-linux'), LOOKUP_PACKAGE_ARCH('armv7l'), 20);

insert into rhnServerPackageArchCompat
(server_arch_id, package_arch_id, preference) values
(LOOKUP_SERVER_ARCH('armv7l-redhat-linux'), LOOKUP_PACKAGE_ARCH('armv6l'), 30);

insert into rhnServerPackageArchCompat
(server_arch_id, package_arch_id, preference) values
(LOOKUP_SERVER_ARCH('armv7l-redhat-linux'), LOOKUP_PACKAGE_ARCH('armv5tel'), 40);

insert into rhnServerPackageArchCompat
(server_arch_id, package_arch_id, preference) values
(LOOKUP_SERVER_ARCH('armv7l-redhat-linux'), LOOKUP_PACKAGE_ARCH('noarch'), 1000);


insert into rhnServerPackageArchCompat
(server_arch_id, package_arch_id, preference) values
(LOOKUP_SERVER_ARCH('armv5tejl-redhat-linux'), LOOKUP_PACKAGE_ARCH('armv5tel'), 0);

insert into rhnServerPackageArchCompat
(server_arch_id, package_arch_id, preference) values
(LOOKUP_SERVER_ARCH('armv5tejl-redhat-linux'), LOOKUP_PACKAGE_ARCH('noarch'), 1000);
 070701000009F1000081B400000000000000000000000167AE11140000084D000000000000000000000000000000000000005F00000000susemanager-schema/upgrade/susemanager-schema-1.7.57-to-susemanager-schema-2.1/0055-armv6l.sql    insert into rhnCpuArch (id, label, name) values
(sequence_nextval('rhn_cpu_arch_id_seq'), 'armv6l', 'ARMv6l');

insert into rhnServerArch (id, label, name, arch_type_id) values
(sequence_nextval('rhn_server_arch_id_seq'), 'armv6l-redhat-linux', 'armv6l', lookup_arch_type('rpm'));

insert into rhnServerChannelArchCompat (server_arch_id, channel_arch_id) values
(LOOKUP_SERVER_ARCH('armv6l-redhat-linux'), LOOKUP_CHANNEL_ARCH('channel-arm'));

insert into rhnServerPackageArchCompat
(server_arch_id, package_arch_id, preference) values
(LOOKUP_SERVER_ARCH('armv6l-redhat-linux'), LOOKUP_PACKAGE_ARCH('armv6l'), 0);

insert into rhnServerPackageArchCompat
(server_arch_id, package_arch_id, preference) values
(LOOKUP_SERVER_ARCH('armv6l-redhat-linux'), LOOKUP_PACKAGE_ARCH('armv5tel'), 10);

insert into rhnServerPackageArchCompat
(server_arch_id, package_arch_id, preference) values
(LOOKUP_SERVER_ARCH('armv6l-redhat-linux'), LOOKUP_PACKAGE_ARCH('noarch'), 1000);

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
        values (lookup_server_arch('armv6l-redhat-linux'),
            lookup_sg_type('sw_mgr_entitled'));
insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
        values (lookup_server_arch('armv6l-redhat-linux'),
            lookup_sg_type('enterprise_entitled'));
insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
        values (lookup_server_arch('armv6l-redhat-linux'),
            lookup_sg_type('provisioning_entitled'));
insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
        values (lookup_server_arch('armv6l-redhat-linux'),
            lookup_sg_type('monitoring_entitled'));
insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
        values (lookup_server_arch('armv6l-redhat-linux'),
            lookup_sg_type('virtualization_host'));
insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
        values (lookup_server_arch('armv6l-redhat-linux'),
            lookup_sg_type('virtualization_host_platform'));
   070701000009F2000081B400000000000000000000000167AE11140000004C000000000000000000000000000000000000007100000000susemanager-schema/upgrade/susemanager-schema-1.7.57-to-susemanager-schema-2.1/0107-rhnServerGroupNotes-drop.sql  
drop table rhnServerGroupNotes;

drop sequence rhn_servergrp_note_id_seq;

070701000009F3000081B400000000000000000000000167AE111400000035000000000000000000000000000000000000007F00000000susemanager-schema/upgrade/susemanager-schema-1.7.57-to-susemanager-schema-2.1/0108-rhn_servergroup_note_mod_trig_fun-drop.sql    
drop function rhn_servergroup_note_mod_trig_fun();

   070701000009F4000081B400000000000000000000000167AE111400000426000000000000000000000000000000000000006B00000000susemanager-schema/upgrade/susemanager-schema-1.7.57-to-susemanager-schema-2.1/0111-rhnAbrtInfo_create.sql    --
-- Copyright (c) 2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

CREATE TABLE rhnAbrtInfo
(
    id             NUMERIC NOT NULL
                        CONSTRAINT rhn_abrt_info_pk PRIMARY KEY,
    server_id      NUMERIC NOT NULL
                       CONSTRAINT rhn_abrt_info_srvr_fk
                           REFERENCES rhnServer (id)
                           ON DELETE CASCADE,
    num_crashes    NUMERIC NOT NULL,
    created        TIMESTAMPTZ NOT NULL
)

;

CREATE SEQUENCE rhn_abrt_info_id_seq;
  070701000009F5000081B400000000000000000000000167AE111400000158000000000000000000000000000000000000007700000000susemanager-schema/upgrade/susemanager-schema-1.7.57-to-susemanager-schema-2.1/0114-rhnUserGroupType_rhn_superuser.sql    DELETE FROM rhnUserGroupMembers WHERE user_group_id IN (SELECT g.id from rhnUserGroup g JOIN rhnUserGroupType gt ON g.group_type = gt.id WHERE gt.label = 'rhn_superuser');

DELETE FROM rhnUserGroup WHERE group_type IN (SELECT id FROM rhnUserGroupType WHERE label = 'rhn_superuser');

DELETE FROM rhnUserGroupType WHERE label = 'rhn_superuser';
070701000009F6000081B400000000000000000000000167AE111400000152000000000000000000000000000000000000007500000000susemanager-schema/upgrade/susemanager-schema-1.7.57-to-susemanager-schema-2.1/0115-rhnUserGroupType_rhn_support.sql  DELETE FROM rhnUserGroupMembers WHERE user_group_id IN (SELECT g.id from rhnUserGroup g JOIN rhnUserGroupType gt ON g.group_type = gt.id WHERE gt.label = 'rhn_support');

DELETE FROM rhnUserGroup WHERE group_type IN (SELECT id FROM rhnUserGroupType WHERE label = 'rhn_support');

DELETE FROM rhnUserGroupType WHERE label = 'rhn_support';
  070701000009F7000081B400000000000000000000000167AE11140000014F000000000000000000000000000000000000007400000000susemanager-schema/upgrade/susemanager-schema-1.7.57-to-susemanager-schema-2.1/0116-rhnUserGroupType_cert_admin.sql   DELETE FROM rhnUserGroupMembers WHERE user_group_id IN (SELECT g.id from rhnUserGroup g JOIN rhnUserGroupType gt ON g.group_type = gt.id WHERE gt.label = 'cert_admin');

DELETE FROM rhnUserGroup WHERE group_type IN (SELECT id FROM rhnUserGroupType WHERE label = 'cert_admin');

DELETE FROM rhnUserGroupType WHERE label = 'cert_admin';
 070701000009F8000081B400000000000000000000000167AE11140000003C000000000000000000000000000000000000006A00000000susemanager-schema/upgrade/susemanager-schema-1.7.57-to-susemanager-schema-2.1/0117-is_user_applicant.sql --

DROP FUNCTION is_user_applicant(user_id_in IN numeric);
070701000009F9000081B400000000000000000000000167AE111400000CEC000000000000000000000000000000000000006900000000susemanager-schema/upgrade/susemanager-schema-1.7.57-to-susemanager-schema-2.1/0118-create_first_org.sql  --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--
--
-- This creates an org with ID of 1, and errors if there already is one
--

create or replace function
create_first_org
(
	name_in in varchar,
	password_in in varchar
)
returns void as
$$
declare
	ug_type			numeric;
	group_val		numeric;
begin
	insert into web_customer (
		id, name
	) values (
		1, name_in
	);

	select nextval( 'rhn_user_group_id_seq' ) into group_val from dual;

	select	id
	into	ug_type
	from	rhnUserGroupType
	where	label = 'org_admin';

	insert into rhnUserGroup (
		id, name,
		description,
		max_members, group_type, org_id
	) values (
		group_val, 'Organization Administrators',
		'Organization Administrators for Org ' || name_in || ' (1)',
		NULL, ug_type, 1
	);

	select nextval('rhn_user_group_id_seq') into group_val from dual;

	select	id
	into	ug_type
	from	rhnUserGroupType
	where	label = 'system_group_admin';

	insert into rhnUserGroup (
		id, name,
		description,
		max_members, group_type, org_id
	) values (
		group_val, 'System Group Administrators',
		'System Group Administrators for Org ' || name_in || ' (1)',
		NULL, ug_type, 1
	);


	select nextval('rhn_user_group_id_seq') into group_val from dual;

	select	id
	into	ug_type
	from	rhnUserGroupType
	where	label = 'activation_key_admin';

	insert into rhnUserGroup (
		id, name,
		description,
		max_members, group_type, org_id
	) values (
		group_val, 'Activation Key Administrators',
		'Activation Key Administrators for Org ' || name_in || ' (1)',
		NULL, ug_type, 1
	);

	-- config admin is special; it gets created in
	-- rhn_entitlements.set_customer_provisioning instead.

	select nextval('rhn_user_group_id_seq') into group_val from dual;

	select	id
	into	ug_type
	from	rhnUserGroupType
	where	label = 'channel_admin';

	insert into rhnUserGroup (
		id, name,
		description,
		max_members, group_type, org_id
	) values (
		group_val, 'Channel Administrators',
		'Channel Administrators for Org ' || name_in || ' (1)',
		NULL, ug_type, 1
	);

	select nextval('rhn_user_group_id_seq') into group_val from dual;

	select	id
	into	ug_type
	from	rhnUserGroupType
	where	label = 'satellite_admin';

	insert into rhnUserGroup (
		id, name,
		description,
		max_members, group_type, org_id
	) values (
		group_val, 'Satellite Administrators',
		'Satellite Administrators for Org ' || name_in || ' (1)',
		NULL, ug_type, 1
	);


	-- there aren't any users yet, so we don't need to update
	-- rhnUserServerPerms
        insert into rhnServerGroup
		( id, name, description, max_members, group_type, org_id )
		select nextval('rhn_server_group_id_seq'), sgt.name, sgt.name,
			0, sgt.id, 1
		from rhnServerGroupType sgt
		where sgt.label = 'sw_mgr_entitled';

end
$$ language plpgsql;
070701000009FA000081B400000000000000000000000167AE111400000F47000000000000000000000000000000000000006700000000susemanager-schema/upgrade/susemanager-schema-1.7.57-to-susemanager-schema-2.1/0119-create_new_org.sql    --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

create or replace function create_new_org
(
        name_in      in varchar,
        password_in  in varchar
        --org_id_out   out NUMERIC
) returns numeric
as
$$
declare
        ug_type                 numeric;
        group_val               numeric;
        new_org_id              numeric;
        org_id_out		numeric;
begin

        select nextval('web_customer_id_seq') into new_org_id;

        insert into web_customer (
                id, name
        ) values (
                new_org_id, name_in
        );

        select nextval('rhn_user_group_id_seq') into group_val;

        select  id
        into    ug_type
        from    rhnUserGroupType
        where   label = 'org_admin';

        insert into rhnUserGroup (
                id, name,
                description,
                max_members, group_type, org_id
        ) values (
                group_val, 'Organization Administrators',
                'Organization Administrators for Org ' || name_in,
                NULL, ug_type, new_org_id
        );

        select nextval('rhn_user_group_id_seq') into group_val;

        select  id
        into    ug_type
        from    rhnUserGroupType
        where   label = 'system_group_admin';

        insert into rhnUserGroup (
                id, name,
                description,
                max_members, group_type, org_id
        ) values (
                group_val, 'System Group Administrators',
                'System Group Administrators for Org ' || name_in,
                NULL, ug_type, new_org_id
        );


        select nextval('rhn_user_group_id_seq') into group_val;

        select  id
        into    ug_type
        from    rhnUserGroupType
        where   label = 'activation_key_admin';

        insert into rhnUserGroup (
                id, name,
                description,
                max_members, group_type, org_id
        ) values (
                group_val, 'Activation Key Administrators',
                'Activation Key Administrators for Org ' || name_in,
                NULL, ug_type, new_org_id
        );

        -- config admin is special; it gets created in
        -- rhn_entitlements.set_customer_provisioning instead.

        select nextval('rhn_user_group_id_seq') into group_val;

        select  id
        into    ug_type
        from    rhnUserGroupType
        where   label = 'channel_admin';

        insert into rhnUserGroup (
                id, name,
                description,
                max_members, group_type, org_id
        ) values (
                group_val, 'Channel Administrators',
                'Channel Administrators for Org ' || name_in,
                NULL, ug_type, new_org_id
        );

        -- there aren't any users yet, so we don't need to update
        -- rhnUserServerPerms
        insert into rhnServerGroup
                ( id, name, description, max_members, group_type, org_id )
                select nextval('rhn_server_group_id_seq'), sgt.name, sgt.name,
                        0, sgt.id, new_org_id
                from rhnServerGroupType sgt
                where sgt.label = 'sw_mgr_entitled';

        org_id_out := new_org_id;

	-- Returning the value of OUT parameter
        return org_id_out;

end;
$$
language plpgsql;
 070701000009FB000081B400000000000000000000000167AE1114000016BA000000000000000000000000000000000000006D00000000susemanager-schema/upgrade/susemanager-schema-1.7.57-to-susemanager-schema-2.1/0120-rhn_entitlements.pkb.sql  --
-- setup search_path so that these functions are created in appropriate schema.
update pg_settings set setting = 'rhn_entitlements,' || setting where name = 'search_path';

    -- this desperately needs to be table driven.
    create or replace function modify_org_service (
        org_id_in in numeric,
        service_label_in in varchar,
        enable_in in char
    ) returns void
as $$
    declare
        roles_to_process varchar[];
        roles cursor(role_label_in varchar) for
            select  label, id
            from    rhnUserGroupType
            where   label = role_label_in;
        org_roles cursor(role_label_in varchar) for
            select  1
            from    rhnUserGroup ug,
                    rhnUserGroupType ugt
            where   ugt.label = role_label_in
                and ug.org_id = org_id_in
                and ugt.id = ug.group_type;

        ents_to_process varchar[];
        ents cursor(ent_label_in varchar) for
            select  label, id
            from    rhnOrgEntitlementType
            where   label = ent_label_in;
        org_ents cursor(ent_label_in varchar) for
            select  1
            from    rhnOrgEntitlements oe,
                    rhnOrgEntitlementType oet
            where   oet.label = ent_label_in
                and oe.org_id = org_id_in
                and oet.id = oe.entitlement_id;
        create_row char(1);
    begin
        ents_to_process := '{}';
        roles_to_process := '{}';
        -- a bit kludgy, but only for 3.4 really.  Certainly no
        -- worse than the old code...
        if service_label_in = 'enterprise' or
           service_label_in = 'management' then
            ents_to_process := array_append(ents_to_process, 'sw_mgr_enterprise');

            roles_to_process := array_append(roles_to_process, 'org_admin');

            roles_to_process := array_append(roles_to_process, 'system_group_admin');

            roles_to_process := array_append(roles_to_process, 'activation_key_admin');
        elsif service_label_in = 'provisioning' then
            ents_to_process := array_append(ents_to_process, 'rhn_provisioning');

            roles_to_process := array_append(roles_to_process, 'system_group_admin');

            roles_to_process := array_append(roles_to_process, 'activation_key_admin');

            roles_to_process := array_append(roles_to_process, 'config_admin');
            -- another nasty special case...
            if enable_in = 'Y' then
                ents_to_process := array_append(ents_to_process, 'sw_mgr_enterprise');
            end if;
        elsif service_label_in = 'monitoring' then
            ents_to_process := array_append(ents_to_process, 'rhn_monitor');

            roles_to_process := array_append(roles_to_process, 'monitoring_admin');
        elsif service_label_in = 'virtualization' then
            ents_to_process := array_append(ents_to_process, 'rhn_virtualization');

            roles_to_process := array_append(roles_to_process, 'config_admin');
        elsif service_label_in = 'virtualization_platform' then
            ents_to_process := array_append(ents_to_process, 'rhn_virtualization_platform');
            roles_to_process := array_append(roles_to_process, 'config_admin');
    elsif service_label_in = 'nonlinux' then
            ents_to_process := array_append(ents_to_process, 'rhn_nonlinux');
            roles_to_process := array_append(roles_to_process, 'config_admin');
        end if;

        if enable_in = 'Y' then
            for i in 1..array_upper(ents_to_process, 1) loop
                for ent in ents(ents_to_process[i]) loop
                    create_row := 'Y';
                    for oe in org_ents(ent.label) loop
                        create_row := 'N';
                    end loop;
                    if create_row = 'Y' then
                        insert into rhnOrgEntitlements(org_id, entitlement_id)
                            values (org_id_in, ent.id);
                    end if;
                end loop;
            end loop;
            for i in 1..array_upper(roles_to_process, 1) loop
                for role in roles(roles_to_process[i]) loop
                    create_row := 'Y';
                    for o_r in org_roles(role.label) loop
                        create_row := 'N';
                    end loop;
                    if create_row = 'Y' then
                        insert into rhnUserGroup(
                                id, name, description, current_members,
                                group_type, org_id
                            ) (
                                select  nextval('rhn_user_group_id_seq'),
                                        ugt.name || 's',
                                        ugt.name || 's for Org ' ||
                                            o.name || ' ('|| o.id ||')',
                                        0, ugt.id, o.id
                                from    rhnUserGroupType ugt,
                                        web_customer o
                                where   o.id = org_id_in
                                    and ugt.id = role.id
                            );
                    end if;
                end loop;
            end loop;
        else
            for i in 1..coalesce(array_upper(ents_to_process, 1), 0) loop
                for ent in ents(ents_to_process[i]) loop
                    delete from rhnOrgEntitlements
                     where org_id = org_id_in
                       and entitlement_id = ent.id;
                end loop;
            end loop;
        end if;
    end$$
language plpgsql;

-- restore the original setting
update pg_settings set setting = overlay( setting placing '' from 1 for (length('rhn_entitlements')+1) ) where name = 'search_path';
  070701000009FC000081B400000000000000000000000167AE11140000006B000000000000000000000000000000000000007400000000susemanager-schema/upgrade/susemanager-schema-1.7.57-to-susemanager-schema-2.1/0121-rhnUserGroupMembers-trigger.sql   --

DROP TRIGGER rhn_ugm_applicant_fix ON rhnUserGroupMembers;

DROP FUNCTION rhn_ugm_applicant_fix_fun();
 070701000009FD000081B400000000000000000000000167AE111400000158000000000000000000000000000000000000007700000000susemanager-schema/upgrade/susemanager-schema-1.7.57-to-susemanager-schema-2.1/0122-rhnUserGroupType_org_applicant.sql    DELETE FROM rhnUserGroupMembers WHERE user_group_id IN (SELECT g.id from rhnUserGroup g JOIN rhnUserGroupType gt ON g.group_type = gt.id WHERE gt.label = 'org_applicant');

DELETE FROM rhnUserGroup WHERE group_type IN (SELECT id FROM rhnUserGroupType WHERE label = 'org_applicant');

DELETE FROM rhnUserGroupType WHERE label = 'org_applicant';
070701000009FE000081B400000000000000000000000167AE111400000290000000000000000000000000000000000000007900000000susemanager-schema/upgrade/susemanager-schema-1.7.57-to-susemanager-schema-2.1/0125-rhn_channel-obtain_read_lock.pkb.sql  
--update pg_setting
update pg_settings set setting = 'rhn_channel,' || setting where name = 'search_path';

    create or replace function obtain_read_lock(channel_family_id_in in numeric, org_id_in in numeric)
    returns void as $$
    declare
        read_lock timestamptz;
    begin
        select created into read_lock
          from rhnPrivateChannelFamily
         where channel_family_id = channel_family_id_in and org_id = org_id_in
           for update;
    end$$ language plpgsql;

-- restore the original setting
update pg_settings set setting = overlay( setting placing '' from 1 for (length('rhn_channel')+1) ) where name = 'search_path';
070701000009FF000081B400000000000000000000000167AE11140000005E000000000000000000000000000000000000007A00000000susemanager-schema/upgrade/susemanager-schema-1.7.57-to-susemanager-schema-2.1/0126-rhn_command-command_class-default.sql 
alter table rhn_command
alter command_class set default '/var/lib/nocpulse/libexec/plugin';

  07070100000A00000081B400000000000000000000000167AE1114000000D6000000000000000000000000000000000000006A00000000susemanager-schema/upgrade/susemanager-schema-1.7.57-to-susemanager-schema-2.1/0131-rhnPackage-common.sql 
alter table rhnpackage alter compat type numeric(1) ;

alter table rhnpackage drop constraint rhn_package_compat_check;
alter table rhnpackage add constraint rhn_package_compat_check CHECK (compat in ( 1 , 0 ));

  07070100000A01000081B400000000000000000000000167AE111400000283000000000000000000000000000000000000007D00000000susemanager-schema/upgrade/susemanager-schema-1.7.57-to-susemanager-schema-2.1/0133-rhn_host_monitoring-last_update_date.sql  
drop view rhn_host_monitoring;
create view rhn_host_monitoring
(
        recid,
        ip,
        name,
        description,
        customer_id,
        os_id,
        asset_id,
        last_update_user,
        last_update_date
) as
select  s.id            as recid,
        rhn_server.get_ip_address(s.id) as ip,
        s.name          as name,
        s.description   as description,
        s.org_id        as customer_id,
        4               as os_id,
        to_number(null,null) as asset_id,
        cast(null as char)   as last_update_user,
        cast(null as TIMESTAMPTZ)   as last_update_date
from    rhnServer       s
;

 07070100000A02000081B400000000000000000000000167AE111400000036000000000000000000000000000000000000006A00000000susemanager-schema/upgrade/susemanager-schema-1.7.57-to-susemanager-schema-2.1/0136-date_diff_in_days.sql 
drop function date_diff_in_days(TIMESTAMPTZ, date);

  07070100000A03000081B400000000000000000000000167AE11140000070D000000000000000000000000000000000000007700000000susemanager-schema/upgrade/susemanager-schema-1.7.57-to-susemanager-schema-2.1/0138-rhn_prepare_install-timestamps.sql    --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--

--monitoring stored procedure

create or replace function
rhn_prepare_install
(
    username            in rhn_command_queue_instances.last_update_user%type,
    install_command     in rhn_command_queue_instances.command_id%type
)
returns rhn_command_queue_instances.recid%type
as $$
declare
    command_instance_id rhn_command_queue_instances.recid%type;
begin
    select nextval('rhn_command_q_inst_recid_seq')
    into command_instance_id;
    

    insert into rhn_command_queue_instances (
        recid,
        command_id,
        notes,
        expiration_date,
        notify_email,
        timeout,
        date_submitted,
        last_update_user,
        last_update_date
    )
    values (
        command_instance_id,
        install_command,
        null, /* no notes */
        /* ignore this command if it has not been run after ten minutes */
        current_timestamp + '10 minute'::interval,
        null, /* no notification email */
        /* should take no more than five minutes to run the install */
        600,
        current_timestamp,
        username,
        current_timestamp
    );

    return command_instance_id;
end; $$
language plpgsql;
   07070100000A04000081B400000000000000000000000167AE111400000190000000000000000000000000000000000000006900000000susemanager-schema/upgrade/susemanager-schema-1.7.57-to-susemanager-schema-2.1/0144-rhnTimezone-data.sql  insert into rhnTimezone (id, olson_name, display_name) (
    select sequence_nextval('rhn_timezone_id_seq'),
           'Africa/Johannesburg',
           'South Africa (Johannesburg)'
      from dual
     where not exists (
           select 1
             from rhnTimezone
            where olson_name = 'Africa/Johannesburg'
              and display_name = 'South Africa (Johannesburg)'
     )
);
07070100000A05000081B400000000000000000000000167AE111400000342000000000000000000000000000000000000006A00000000susemanager-schema/upgrade/susemanager-schema-1.7.57-to-susemanager-schema-2.1/0145-rhnDistChannelMap.sql 
ALTER TABLE rhnDistChannelMap ADD org_id NUMERIC;
ALTER TABLE rhnDistChannelMap ADD CONSTRAINT rhn_dcm_oid_fk FOREIGN KEY (org_id) REFERENCES web_customer (id) ON DELETE CASCADE;
DROP INDEX if exists rhn_dcm_os_release_caid_idx;
ALTER TABLE rhnDistChannelMap DROP CONSTRAINT rhn_dcm_os_release_caid_uq;

delete
 from rhnDistChannelMap
where channel_id in (
      select id
        from rhnChannel
       where parent_channel is not null);

ALTER TABLE rhnDistChannelMap ADD CONSTRAINT rhn_dcm_release_caid_oid_uq UNIQUE (release, channel_arch_id, org_id);

ALTER TABLE rhnDistChannelMap ADD id NUMERIC;
CREATE SEQUENCE rhn_dcm_id_seq;
UPDATE rhnDistChannelMap SET id = nextval('rhn_dcm_id_seq');
ALTER TABLE rhnDistChannelMap ALTER COLUMN id SET NOT NULL;
ALTER TABLE rhnDistChannelMap ADD CONSTRAINT rhn_dcm_id_pk PRIMARY KEY (id);
  07070100000A06000081B400000000000000000000000167AE1114000001A8000000000000000000000000000000000000006E00000000susemanager-schema/upgrade/susemanager-schema-1.7.57-to-susemanager-schema-2.1/0145-spacewalk-package-key.sql 
update rhnPackageKey set provider_id = lookup_package_provider('Spacewalk')
 where key_id = '0e646f68863a853d';

insert into rhnPackageKey (id, key_id, key_type_id, provider_id)
    (select sequence_nextval('rhn_pkey_id_seq'), '0e646f68863a853d', lookup_package_key_type('gpg'), lookup_package_provider('Spacewalk') from dual
     where not exists (select 1 from rhnPackageKey where key_id = '0e646f68863a853d'));

commit;
07070100000A07000081B400000000000000000000000167AE11140000006B000000000000000000000000000000000000006F00000000susemanager-schema/upgrade/susemanager-schema-1.7.57-to-susemanager-schema-2.1/0146-rhnDistChannelMap-data.sql    UPDATE rhnDistChannelMap dcm SET org_id = (SELECT c.org_id FROM rhnChannel c where c.id = dcm.channel_id);
 07070100000A08000081B400000000000000000000000167AE11140000072C000000000000000000000000000000000000006D00000000susemanager-schema/upgrade/susemanager-schema-1.7.57-to-susemanager-schema-2.1/0147-rhnOrgDistChannelMap.sql  --
-- Copyright (c) 2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--
--
--
CREATE OR REPLACE VIEW
rhnOrgDistChannelMap
(
    id,
    for_org_id,
    org_id,
    os,
    release,
    channel_arch_id,
    channel_id
)
AS
SELECT CASE WHEN dcm_o.org_id IS NOT NULL THEN dcm_o.id ELSE dcm_n.id END id,
        o.id as for_org_id,
        dcm_o.org_id,
        CASE WHEN dcm_o.org_id IS NOT NULL THEN dcm_o.os ELSE dcm_n.os END os,
        CASE WHEN dcm_o.org_id IS NOT NULL THEN dcm_o.release ELSE dcm_n.release END as release,
        CASE WHEN dcm_o.org_id IS NOT NULL THEN dcm_o.channel_arch_id ELSE dcm_n.channel_arch_id END as channel_arch_id,
        CASE WHEN dcm_o.org_id IS NOT NULL THEN dcm_o.channel_id ELSE dcm_n.channel_id END as channel_id
FROM web_customer o
    JOIN (SELECT DISTINCT release, channel_arch_id from rhnDistChannelMap) dcm ON 1 = 1
    LEFT JOIN rhnDistChannelMap dcm_n ON dcm_n.org_id IS NULL
        AND dcm_n.release = dcm.release
        AND dcm_n.channel_arch_id = dcm.channel_arch_id
    LEFT JOIN rhnDistChannelMap dcm_o ON dcm_o.org_id = o.id
        AND dcm_o.release = dcm.release
        AND dcm_o.channel_arch_id = dcm.channel_arch_id
WHERE (dcm_o.channel_id IS NOT NULL OR dcm_n.channel_id IS NOT NULL)
ORDER BY org_id, release, channel_arch_id;
07070100000A09000081B400000000000000000000000167AE11140000017D000000000000000000000000000000000000007200000000susemanager-schema/upgrade/susemanager-schema-1.7.57-to-susemanager-schema-2.1/0148-rhnDistChannelMap-trigger.sql 
create or replace function rhn_dist_channel_map_mod_trig_fun() returns trigger as
$$
begin
    if new.id is null then
        new.id := nextval('rhn_rhn_dcm_id_seq');
    end if;
    return new;
end;
$$ language plpgsql;

create trigger
rhn_dist_channel_map_mod_trig
before insert or update on rhnDistChannelMap
for each row
execute procedure rhn_dist_channel_map_mod_trig_fun();
   07070100000A0A000081B400000000000000000000000167AE11140000126E000000000000000000000000000000000000006800000000susemanager-schema/upgrade/susemanager-schema-1.7.57-to-susemanager-schema-2.1/0149-rhn_channel.pkb.sql   
--update pg_setting
update pg_settings set setting = 'rhn_channel,' || setting where name = 'search_path';

    create or replace function guess_server_base(
        server_id_in in numeric
    ) RETURNS numeric as $$
    declare
        server_cursor cursor for
            select s.server_arch_id, s.release, s.org_id
              from rhnServer s
             where s.id = server_id_in;
    -- Cursor that fetches all the possible base channels for a
    -- (server_arch_id, release, org_id) combination
        base_channel_cursor cursor(
                release_in varchar,
                server_arch_id_in numeric,
                org_id_in numeric
        ) for
                select distinct c.*
                from    rhnOrgDistChannelMap                       odcm,
                                rhnServerChannelArchCompat      scac,
                                rhnChannel                                      c
                where   c.parent_channel is null
                        and c.id = odcm.channel_id
                        and c.channel_arch_id = odcm.channel_arch_id
                        and odcm.release = release_in
                        and odcm.for_org_id = org_id_in
                        and scac.server_arch_id = server_arch_id_in
                        and scac.channel_arch_id = c.channel_arch_id;

    begin
        for s in server_cursor loop
            for channel in base_channel_cursor(s.release,
                s.server_arch_id, s.org_id)
            loop
                return channel.id;
            end loop;
        end loop;
        -- Server not found, or no base channel applies to it
        return null;
    end$$ language plpgsql;

    create or replace function base_channel_rel_archid(
        release_in in varchar,
        server_arch_id_in in numeric,
        org_id_in in numeric default -1,
        user_id_in in numeric default null
    ) returns numeric as $$
    declare
        denied_channel_id numeric := null;
        valid_org_id numeric := org_id_in;
        valid_user_id numeric := user_id_in;
        channel_subscribable numeric;
    -- Cursor that fetches all the possible base channels for a
    -- (server_arch_id, release, org_id) combination
        base_channel_cursor cursor(
                release_in varchar,
                server_arch_id_in numeric,
                org_id_in numeric
        ) for
                select distinct c.*
                from    rhnOrgDistChannelMap                       odcm,
                                rhnServerChannelArchCompat      scac,
                                rhnChannel                                      c
                where   c.parent_channel is null
                        and c.id = odcm.channel_id
                        and c.channel_arch_id = odcm.channel_arch_id
                        and odcm.release = release_in
                        and odcm.for_org_id = org_id_in
                        and scac.server_arch_id = server_arch_id_in
                        and scac.channel_arch_id = c.channel_arch_id;

    begin
        if org_id_in = -1 and user_id_in is not null then
            -- Get the org id from the user id

                select org_id
                  into valid_org_id
                  from web_contact
                 where id = user_id_in;

                if not found then
                    -- User doesn't exist
                    -- XXX Only list public stuff for now
                    valid_user_id := null;
                    valid_org_id := -1;
                end if;
        end if;

        for c in base_channel_cursor(release_in, server_arch_id_in, valid_org_id)
        loop
            -- This row is a possible match
            if valid_user_id is null then
                -- User ID not specified, so no user to channel permissions to
                -- check
                return c.id;
            end if;

            -- Check user to channel permissions
            select rhn_channel.loose_user_role_check(c.id, user_id_in, 'subscribe')
              into channel_subscribable;

            if channel_subscribable = 1 then
                return c.id;
            end if;

            -- Base channel exists, but is not subscribable; keep trying
            denied_channel_id := c.id;
        end loop;

        if denied_channel_id is not null then
            perform rhn_exception.raise_exception('no_subscribe_permissions');
        end if;
        -- No base channel applies
        return NULL;
    end$$ language plpgsql;

-- restore the original setting
update pg_settings set setting = overlay( setting placing '' from 1 for (length('rhn_channel')+1) ) where name = 'search_path';
  07070100000A0B000081B400000000000000000000000167AE1114000000DB000000000000000000000000000000000000007200000000susemanager-schema/upgrade/susemanager-schema-1.7.57-to-susemanager-schema-2.1/1001-rhnDistChannelMap-trigger.sql 
create or replace function rhn_dist_channel_map_mod_trig_fun() returns trigger as
$$
begin
    if new.id is null then
        new.id := nextval('rhn_dcm_id_seq');
    end if;
    return new;
end;
$$ language plpgsql;

 07070100000A0C000081B400000000000000000000000167AE1114000000AE000000000000000000000000000000000000006900000000susemanager-schema/upgrade/susemanager-schema-1.7.57-to-susemanager-schema-2.1/1002-rhnKSInstallType.sql  insert into rhnKSInstallType (id, label, name)
        values (sequence_nextval('rhn_ksinstalltype_id_seq'),
                'rhel_7','Red Hat Enterprise Linux 7'
        );
  07070100000A0D000081B400000000000000000000000167AE11140001D64D000000000000000000000000000000000000006D00000000susemanager-schema/upgrade/susemanager-schema-1.7.57-to-susemanager-schema-2.1/1003-rhnKickstartTimezome.sql  insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Abidjan',
                'Africa/Abidjan',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Accra',
                'Africa/Accra',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Addis_Ababa',
                'Africa/Addis_Ababa',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Algiers',
                'Africa/Algiers',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Asmara',
                'Africa/Asmara',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Bamako',
                'Africa/Bamako',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Bangui',
                'Africa/Bangui',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Banjul',
                'Africa/Banjul',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Bissau',
                'Africa/Bissau',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Blantyre',
                'Africa/Blantyre',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Brazzaville',
                'Africa/Brazzaville',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Bujumbura',
                'Africa/Bujumbura',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Cairo',
                'Africa/Cairo',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Casablanca',
                'Africa/Casablanca',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Ceuta',
                'Africa/Ceuta',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Conakry',
                'Africa/Conakry',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Dakar',
                'Africa/Dakar',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Dar_es_Salaam',
                'Africa/Dar_es_Salaam',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Djibouti',
                'Africa/Djibouti',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Douala',
                'Africa/Douala',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/El_Aaiun',
                'Africa/El_Aaiun',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Freetown',
                'Africa/Freetown',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Gaborone',
                'Africa/Gaborone',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Harare',
                'Africa/Harare',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Johannesburg',
                'Africa/Johannesburg',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Juba',
                'Africa/Juba',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Kampala',
                'Africa/Kampala',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Khartoum',
                'Africa/Khartoum',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Kigali',
                'Africa/Kigali',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Kinshasa',
                'Africa/Kinshasa',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Lagos',
                'Africa/Lagos',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Libreville',
                'Africa/Libreville',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Lome',
                'Africa/Lome',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Luanda',
                'Africa/Luanda',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Lubumbashi',
                'Africa/Lubumbashi',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Lusaka',
                'Africa/Lusaka',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Malabo',
                'Africa/Malabo',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Maputo',
                'Africa/Maputo',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Maseru',
                'Africa/Maseru',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Mbabane',
                'Africa/Mbabane',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Mogadishu',
                'Africa/Mogadishu',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Monrovia',
                'Africa/Monrovia',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Nairobi',
                'Africa/Nairobi',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Ndjamena',
                'Africa/Ndjamena',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Niamey',
                'Africa/Niamey',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Nouakchott',
                'Africa/Nouakchott',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Ouagadougou',
                'Africa/Ouagadougou',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Porto-Novo',
                'Africa/Porto-Novo',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Sao_Tome',
                'Africa/Sao_Tome',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Tripoli',
                'Africa/Tripoli',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Tunis',
                'Africa/Tunis',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Windhoek',
                'Africa/Windhoek',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Adak',
                'America/Adak',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Anchorage',
                'America/Anchorage',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Anguilla',
                'America/Anguilla',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Antigua',
                'America/Antigua',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Araguaina',
                'America/Araguaina',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Argentina/Buenos_Aires',
                'America/Argentina/Buenos_Aires',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Argentina/Catamarca',
                'America/Argentina/Catamarca',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Argentina/Cordoba',
                'America/Argentina/Cordoba',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Argentina/Jujuy',
                'America/Argentina/Jujuy',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Argentina/La_Rioja',
                'America/Argentina/La_Rioja',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Argentina/Mendoza',
                'America/Argentina/Mendoza',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Argentina/Rio_Gallegos',
                'America/Argentina/Rio_Gallegos',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Argentina/Salta',
                'America/Argentina/Salta',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Argentina/San_Juan',
                'America/Argentina/San_Juan',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Argentina/San_Luis',
                'America/Argentina/San_Luis',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Argentina/Tucuman',
                'America/Argentina/Tucuman',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Argentina/Ushuaia',
                'America/Argentina/Ushuaia',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Aruba',
                'America/Aruba',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Asuncion',
                'America/Asuncion',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Atikokan',
                'America/Atikokan',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Bahia',
                'America/Bahia',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Bahia_Banderas',
                'America/Bahia_Banderas',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Barbados',
                'America/Barbados',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Belem',
                'America/Belem',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Belize',
                'America/Belize',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Blanc-Sablon',
                'America/Blanc-Sablon',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Boa_Vista',
                'America/Boa_Vista',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Bogota',
                'America/Bogota',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Boise',
                'America/Boise',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Cambridge_Bay',
                'America/Cambridge_Bay',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Campo_Grande',
                'America/Campo_Grande',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Cancun',
                'America/Cancun',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Caracas',
                'America/Caracas',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Cayenne',
                'America/Cayenne',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Cayman',
                'America/Cayman',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Chicago',
                'America/Chicago',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Chihuahua',
                'America/Chihuahua',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Costa_Rica',
                'America/Costa_Rica',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Creston',
                'America/Creston',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Cuiaba',
                'America/Cuiaba',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Curacao',
                'America/Curacao',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Danmarkshavn',
                'America/Danmarkshavn',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Dawson',
                'America/Dawson',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Dawson_Creek',
                'America/Dawson_Creek',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Denver',
                'America/Denver',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Detroit',
                'America/Detroit',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Dominica',
                'America/Dominica',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Edmonton',
                'America/Edmonton',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Eirunepe',
                'America/Eirunepe',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/El_Salvador',
                'America/El_Salvador',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Fortaleza',
                'America/Fortaleza',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Glace_Bay',
                'America/Glace_Bay',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Godthab',
                'America/Godthab',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Goose_Bay',
                'America/Goose_Bay',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Grand_Turk',
                'America/Grand_Turk',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Grenada',
                'America/Grenada',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Guadeloupe',
                'America/Guadeloupe',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Guatemala',
                'America/Guatemala',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Guayaquil',
                'America/Guayaquil',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Guyana',
                'America/Guyana',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Halifax',
                'America/Halifax',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Havana',
                'America/Havana',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Hermosillo',
                'America/Hermosillo',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Indiana/Indianapolis',
                'America/Indiana/Indianapolis',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Indiana/Knox',
                'America/Indiana/Knox',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Indiana/Marengo',
                'America/Indiana/Marengo',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Indiana/Petersburg',
                'America/Indiana/Petersburg',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Indiana/Tell_City',
                'America/Indiana/Tell_City',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Indiana/Vevay',
                'America/Indiana/Vevay',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Indiana/Vincennes',
                'America/Indiana/Vincennes',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Indiana/Winamac',
                'America/Indiana/Winamac',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Inuvik',
                'America/Inuvik',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Iqaluit',
                'America/Iqaluit',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Jamaica',
                'America/Jamaica',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Juneau',
                'America/Juneau',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Kentucky/Louisville',
                'America/Kentucky/Louisville',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Kentucky/Monticello',
                'America/Kentucky/Monticello',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Kralendijk',
                'America/Kralendijk',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/La_Paz',
                'America/La_Paz',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Lima',
                'America/Lima',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Los_Angeles',
                'America/Los_Angeles',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Lower_Princes',
                'America/Lower_Princes',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Maceio',
                'America/Maceio',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Managua',
                'America/Managua',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Manaus',
                'America/Manaus',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Marigot',
                'America/Marigot',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Martinique',
                'America/Martinique',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Matamoros',
                'America/Matamoros',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Mazatlan',
                'America/Mazatlan',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Menominee',
                'America/Menominee',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Merida',
                'America/Merida',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Metlakatla',
                'America/Metlakatla',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Mexico_City',
                'America/Mexico_City',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Miquelon',
                'America/Miquelon',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Moncton',
                'America/Moncton',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Monterrey',
                'America/Monterrey',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Montevideo',
                'America/Montevideo',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Montreal',
                'America/Montreal',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Montserrat',
                'America/Montserrat',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Nassau',
                'America/Nassau',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/New_York',
                'America/New_York',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Nipigon',
                'America/Nipigon',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Nome',
                'America/Nome',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Noronha',
                'America/Noronha',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/North_Dakota/Beulah',
                'America/North_Dakota/Beulah',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/North_Dakota/Center',
                'America/North_Dakota/Center',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/North_Dakota/New_Salem',
                'America/North_Dakota/New_Salem',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Ojinaga',
                'America/Ojinaga',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Panama',
                'America/Panama',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Pangnirtung',
                'America/Pangnirtung',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Paramaribo',
                'America/Paramaribo',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Phoenix',
                'America/Phoenix',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Port_of_Spain',
                'America/Port_of_Spain',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Port-au-Prince',
                'America/Port-au-Prince',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Porto_Velho',
                'America/Porto_Velho',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Puerto_Rico',
                'America/Puerto_Rico',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Rainy_River',
                'America/Rainy_River',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Rankin_Inlet',
                'America/Rankin_Inlet',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Recife',
                'America/Recife',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Regina',
                'America/Regina',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Resolute',
                'America/Resolute',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Rio_Branco',
                'America/Rio_Branco',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Santa_Isabel',
                'America/Santa_Isabel',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Santarem',
                'America/Santarem',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Santiago',
                'America/Santiago',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Santo_Domingo',
                'America/Santo_Domingo',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Sao_Paulo',
                'America/Sao_Paulo',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Scoresbysund',
                'America/Scoresbysund',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Shiprock',
                'America/Shiprock',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Sitka',
                'America/Sitka',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/St_Barthelemy',
                'America/St_Barthelemy',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/St_Johns',
                'America/St_Johns',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/St_Kitts',
                'America/St_Kitts',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/St_Lucia',
                'America/St_Lucia',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/St_Thomas',
                'America/St_Thomas',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/St_Vincent',
                'America/St_Vincent',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Swift_Current',
                'America/Swift_Current',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Tegucigalpa',
                'America/Tegucigalpa',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Thule',
                'America/Thule',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Thunder_Bay',
                'America/Thunder_Bay',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Tijuana',
                'America/Tijuana',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Toronto',
                'America/Toronto',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Tortola',
                'America/Tortola',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Vancouver',
                'America/Vancouver',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Whitehorse',
                'America/Whitehorse',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Winnipeg',
                'America/Winnipeg',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Yakutat',
                'America/Yakutat',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Yellowknife',
                'America/Yellowknife',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Antarctica/Casey',
                'Antarctica/Casey',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Antarctica/Davis',
                'Antarctica/Davis',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Antarctica/DumontDUrville',
                'Antarctica/DumontDUrville',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Antarctica/Macquarie',
                'Antarctica/Macquarie',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Antarctica/Mawson',
                'Antarctica/Mawson',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Antarctica/McMurdo',
                'Antarctica/McMurdo',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Antarctica/Palmer',
                'Antarctica/Palmer',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Antarctica/Rothera',
                'Antarctica/Rothera',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Antarctica/South_Pole',
                'Antarctica/South_Pole',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Antarctica/Syowa',
                'Antarctica/Syowa',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Antarctica/Vostok',
                'Antarctica/Vostok',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Arctic/Longyearbyen',
                'Arctic/Longyearbyen',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Aden',
                'Asia/Aden',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Almaty',
                'Asia/Almaty',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Amman',
                'Asia/Amman',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Anadyr',
                'Asia/Anadyr',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Aqtau',
                'Asia/Aqtau',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Aqtobe',
                'Asia/Aqtobe',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Ashgabat',
                'Asia/Ashgabat',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Baghdad',
                'Asia/Baghdad',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Bahrain',
                'Asia/Bahrain',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Baku',
                'Asia/Baku',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Bangkok',
                'Asia/Bangkok',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Beirut',
                'Asia/Beirut',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Bishkek',
                'Asia/Bishkek',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Brunei',
                'Asia/Brunei',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Choibalsan',
                'Asia/Choibalsan',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Chongqing',
                'Asia/Chongqing',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Colombo',
                'Asia/Colombo',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Damascus',
                'Asia/Damascus',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Dhaka',
                'Asia/Dhaka',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Dili',
                'Asia/Dili',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Dubai',
                'Asia/Dubai',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Dushanbe',
                'Asia/Dushanbe',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Gaza',
                'Asia/Gaza',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Harbin',
                'Asia/Harbin',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Hebron',
                'Asia/Hebron',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Ho_Chi_Minh',
                'Asia/Ho_Chi_Minh',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Hong_Kong',
                'Asia/Hong_Kong',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Hovd',
                'Asia/Hovd',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Irkutsk',
                'Asia/Irkutsk',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Jakarta',
                'Asia/Jakarta',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Jayapura',
                'Asia/Jayapura',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Jerusalem',
                'Asia/Jerusalem',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Kabul',
                'Asia/Kabul',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Kamchatka',
                'Asia/Kamchatka',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Karachi',
                'Asia/Karachi',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Kashgar',
                'Asia/Kashgar',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Kathmandu',
                'Asia/Kathmandu',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Kolkata',
                'Asia/Kolkata',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Krasnoyarsk',
                'Asia/Krasnoyarsk',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Kuala_Lumpur',
                'Asia/Kuala_Lumpur',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Kuching',
                'Asia/Kuching',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Kuwait',
                'Asia/Kuwait',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Macau',
                'Asia/Macau',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Magadan',
                'Asia/Magadan',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Makassar',
                'Asia/Makassar',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Manila',
                'Asia/Manila',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Muscat',
                'Asia/Muscat',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Nicosia',
                'Asia/Nicosia',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Novokuznetsk',
                'Asia/Novokuznetsk',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Novosibirsk',
                'Asia/Novosibirsk',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Omsk',
                'Asia/Omsk',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Oral',
                'Asia/Oral',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Phnom_Penh',
                'Asia/Phnom_Penh',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Pontianak',
                'Asia/Pontianak',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Pyongyang',
                'Asia/Pyongyang',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Qatar',
                'Asia/Qatar',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Qyzylorda',
                'Asia/Qyzylorda',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Rangoon',
                'Asia/Rangoon',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Riyadh',
                'Asia/Riyadh',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Sakhalin',
                'Asia/Sakhalin',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Samarkand',
                'Asia/Samarkand',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Seoul',
                'Asia/Seoul',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Shanghai',
                'Asia/Shanghai',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Singapore',
                'Asia/Singapore',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Taipei',
                'Asia/Taipei',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Tashkent',
                'Asia/Tashkent',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Tbilisi',
                'Asia/Tbilisi',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Tehran',
                'Asia/Tehran',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Thimphu',
                'Asia/Thimphu',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Tokyo',
                'Asia/Tokyo',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Ulaanbaatar',
                'Asia/Ulaanbaatar',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Urumqi',
                'Asia/Urumqi',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Vientiane',
                'Asia/Vientiane',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Vladivostok',
                'Asia/Vladivostok',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Yakutsk',
                'Asia/Yakutsk',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Yekaterinburg',
                'Asia/Yekaterinburg',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Yerevan',
                'Asia/Yerevan',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Atlantic/Azores',
                'Atlantic/Azores',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Atlantic/Bermuda',
                'Atlantic/Bermuda',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Atlantic/Canary',
                'Atlantic/Canary',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Atlantic/Cape_Verde',
                'Atlantic/Cape_Verde',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Atlantic/Faroe',
                'Atlantic/Faroe',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Atlantic/Madeira',
                'Atlantic/Madeira',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Atlantic/Reykjavik',
                'Atlantic/Reykjavik',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Atlantic/South_Georgia',
                'Atlantic/South_Georgia',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Atlantic/St_Helena',
                'Atlantic/St_Helena',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Atlantic/Stanley',
                'Atlantic/Stanley',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Australia/Adelaide',
                'Australia/Adelaide',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Australia/Brisbane',
                'Australia/Brisbane',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Australia/Broken_Hill',
                'Australia/Broken_Hill',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Australia/Currie',
                'Australia/Currie',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Australia/Darwin',
                'Australia/Darwin',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Australia/Eucla',
                'Australia/Eucla',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Australia/Hobart',
                'Australia/Hobart',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Australia/Lindeman',
                'Australia/Lindeman',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Australia/Lord_Howe',
                'Australia/Lord_Howe',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Australia/Melbourne',
                'Australia/Melbourne',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Australia/Perth',
                'Australia/Perth',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Australia/Sydney',
                'Australia/Sydney',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Amsterdam',
                'Europe/Amsterdam',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Andorra',
                'Europe/Andorra',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Athens',
                'Europe/Athens',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Belgrade',
                'Europe/Belgrade',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Berlin',
                'Europe/Berlin',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Bratislava',
                'Europe/Bratislava',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Brussels',
                'Europe/Brussels',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Bucharest',
                'Europe/Bucharest',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Budapest',
                'Europe/Budapest',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Chisinau',
                'Europe/Chisinau',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Copenhagen',
                'Europe/Copenhagen',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Dublin',
                'Europe/Dublin',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Gibraltar',
                'Europe/Gibraltar',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Guernsey',
                'Europe/Guernsey',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Helsinki',
                'Europe/Helsinki',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Isle_of_Man',
                'Europe/Isle_of_Man',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Istanbul',
                'Europe/Istanbul',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Jersey',
                'Europe/Jersey',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Kaliningrad',
                'Europe/Kaliningrad',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Kiev',
                'Europe/Kiev',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Lisbon',
                'Europe/Lisbon',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Ljubljana',
                'Europe/Ljubljana',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/London',
                'Europe/London',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Luxembourg',
                'Europe/Luxembourg',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Madrid',
                'Europe/Madrid',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Malta',
                'Europe/Malta',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Mariehamn',
                'Europe/Mariehamn',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Minsk',
                'Europe/Minsk',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Monaco',
                'Europe/Monaco',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Moscow',
                'Europe/Moscow',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Oslo',
                'Europe/Oslo',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Paris',
                'Europe/Paris',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Podgorica',
                'Europe/Podgorica',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Prague',
                'Europe/Prague',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Riga',
                'Europe/Riga',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Rome',
                'Europe/Rome',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Samara',
                'Europe/Samara',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/San_Marino',
                'Europe/San_Marino',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Sarajevo',
                'Europe/Sarajevo',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Simferopol',
                'Europe/Simferopol',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Skopje',
                'Europe/Skopje',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Sofia',
                'Europe/Sofia',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Stockholm',
                'Europe/Stockholm',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Tallinn',
                'Europe/Tallinn',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Tirane',
                'Europe/Tirane',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Uzhgorod',
                'Europe/Uzhgorod',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Vaduz',
                'Europe/Vaduz',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Vatican',
                'Europe/Vatican',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Vienna',
                'Europe/Vienna',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Vilnius',
                'Europe/Vilnius',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Volgograd',
                'Europe/Volgograd',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Warsaw',
                'Europe/Warsaw',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Zagreb',
                'Europe/Zagreb',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Zaporozhye',
                'Europe/Zaporozhye',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Zurich',
                'Europe/Zurich',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Indian/Antananarivo',
                'Indian/Antananarivo',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Indian/Chagos',
                'Indian/Chagos',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Indian/Christmas',
                'Indian/Christmas',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Indian/Cocos',
                'Indian/Cocos',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Indian/Comoro',
                'Indian/Comoro',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Indian/Kerguelen',
                'Indian/Kerguelen',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Indian/Mahe',
                'Indian/Mahe',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Indian/Maldives',
                'Indian/Maldives',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Indian/Mauritius',
                'Indian/Mauritius',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Indian/Mayotte',
                'Indian/Mayotte',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Indian/Reunion',
                'Indian/Reunion',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Apia',
                'Pacific/Apia',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Auckland',
                'Pacific/Auckland',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Chatham',
                'Pacific/Chatham',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Chuuk',
                'Pacific/Chuuk',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Easter',
                'Pacific/Easter',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Efate',
                'Pacific/Efate',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Enderbury',
                'Pacific/Enderbury',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Fakaofo',
                'Pacific/Fakaofo',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Fiji',
                'Pacific/Fiji',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Funafuti',
                'Pacific/Funafuti',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Galapagos',
                'Pacific/Galapagos',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Gambier',
                'Pacific/Gambier',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Guadalcanal',
                'Pacific/Guadalcanal',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Guam',
                'Pacific/Guam',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Honolulu',
                'Pacific/Honolulu',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Johnston',
                'Pacific/Johnston',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Kiritimati',
                'Pacific/Kiritimati',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Kosrae',
                'Pacific/Kosrae',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Kwajalein',
                'Pacific/Kwajalein',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Majuro',
                'Pacific/Majuro',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Marquesas',
                'Pacific/Marquesas',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Midway',
                'Pacific/Midway',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Nauru',
                'Pacific/Nauru',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Niue',
                'Pacific/Niue',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Norfolk',
                'Pacific/Norfolk',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Noumea',
                'Pacific/Noumea',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Pago_Pago',
                'Pacific/Pago_Pago',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Palau',
                'Pacific/Palau',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Pitcairn',
                'Pacific/Pitcairn',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Pohnpei',
                'Pacific/Pohnpei',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Port_Moresby',
                'Pacific/Port_Moresby',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Rarotonga',
                'Pacific/Rarotonga',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Saipan',
                'Pacific/Saipan',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Tahiti',
                'Pacific/Tahiti',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Tarawa',
                'Pacific/Tarawa',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Tongatapu',
                'Pacific/Tongatapu',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Wake',
                'Pacific/Wake',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

insert into rhnKickstartTimezone (id, label, name, install_type)
        values (sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Wallis',
                'Pacific/Wallis',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_7')
        );

   07070100000A0E000081B400000000000000000000000167AE11140000007A000000000000000000000000000000000000006A00000000susemanager-schema/upgrade/susemanager-schema-1.7.57-to-susemanager-schema-2.1/1006-rhnDownloads-drop.sql 
drop table rhnChannelDownloads;
drop table rhnDownloads;
drop table rhnDownloadType;
drop sequence rhn_download_id_seq;

  07070100000A0F000081B400000000000000000000000167AE111400000C69000000000000000000000000000000000000006A00000000susemanager-schema/upgrade/susemanager-schema-1.7.57-to-susemanager-schema-2.1/1006-rhnServerOverview.sql drop view rhnServerOverview;
create or replace view
rhnServerOverview
(
    org_id, 
    server_id, 
    server_name, 
    modified, 
    server_admins, 
    group_count, 
    channel_id,
    channel_labels, 
    history_count, 
    security_errata, 
    bug_errata, 
    enhancement_errata,
    outdated_packages,
	config_files_with_differences,
    crash_count,
    last_checkin_days_ago,
    last_checkin,
    pending_updates,
    os,
    release,
    server_arch_name,
    locked
)
as
select
    s.org_id, s.id, s.name, s.modified,
    ( select count(user_id) from rhnUserServerPerms ap 
      where server_id = s.id ), 
    ( select count(server_group_id) from rhnVisibleServerGroupMembers
      where server_id = s.id ),
    ( select C.id
        from rhnChannel C,
	     rhnServerChannel SC
       where SC.server_id = S.id
         and SC.channel_id = C.id
	 and C.parent_channel IS NULL),
    coalesce(( select C.name
        from rhnChannel C,
	     rhnServerChannel SC
       where SC.server_id = S.id
         and SC.channel_id = C.id
	 and C.parent_channel IS NULL), '(none)'),
    ( select count(id) from rhnServerHistory
      where
            server_id = S.id),
    ( select count(*) from rhnServerErrataTypeView setv 
      where
            setv.server_id = s.id
        and setv.errata_type = 'Security Advisory'), 
    ( select count(*) from rhnServerErrataTypeView setv 
      where 
            setv.server_id = s.id
        and setv.errata_type = 'Bug Fix Advisory'),
    ( select count(*) from rhnServerErrataTypeView setv 
      where 
            setv.server_id = s.id
        and setv.errata_type = 'Product Enhancement Advisory'),
    ( select count(distinct p.name_id) from rhnPackage p, rhnServerNeededPackageCache snpc
      where
             snpc.server_id = S.id
	 and p.id = snpc.package_id
	 ),
    ( select count(*)
        from rhnActionConfigRevision ACR
             INNER JOIN rhnActionConfigRevisionResult ACRR on ACR.id = ACRR.action_config_revision_id
       where ACR.server_id = S.id
         and ACR.action_id = (
              select MAX(rA.id)
                from rhnAction rA
                     INNER JOIN rhnServerAction rSA on rSA.action_id = rA.id
                     INNER JOIN rhnActionStatus rAS on rAS.id = rSA.status
                     INNER JOIN rhnActionType rAT on rAT.id = rA.action_type
               where rSA.server_id = S.id
                 and rAS.name in ('Completed', 'Failed')
                 and rAT.label = 'configfiles.diff'
         )
         and ACR.failure_id is null
         and ACRR.result is not null
        ),
    ( select num_crashes from rhnAbrtInfo where server_id = S.id ),
    ( select date_diff_in_days(checkin, current_timestamp) from rhnServerInfo where server_id = S.id ),
    ( select TO_CHAR(checkin, 'YYYY-MM-DD HH24:MI:SS') from rhnServerInfo where server_id = S.id ),
    ( select count(1) 
        from rhnServerAction
       where server_id = S.id
         and status in (0, 1)),
    os,
    release,
    ( select name from rhnServerArch where id = s.server_arch_id),
    coalesce((select 1 from rhnServerLock SL WHERE SL.server_id = S.id), 0)
from 
    rhnServer S
;
   07070100000A10000081B400000000000000000000000167AE11140000002D000000000000000000000000000000000000007700000000susemanager-schema/upgrade/susemanager-schema-1.7.57-to-susemanager-schema-2.1/1007-rhn_download_mod_trig_fun-drop.sql    
drop function rhn_download_mod_trig_fun();

   07070100000A11000081B400000000000000000000000167AE111400000320000000000000000000000000000000000000006C00000000susemanager-schema/upgrade/susemanager-schema-1.7.57-to-susemanager-schema-2.1/1008-rhnContentSourceSsl.sql   
create table
rhnContentSourceSsl
(
	id NUMERIC not null
		constraint rhn_csssl_id_pk primary key,
	content_source_id NUMERIC not null
		constraint rhn_csssl_csid_uq unique
		constraint rhn_csssl_csid_fk references rhnContentSource(id) on delete cascade,
	ssl_ca_cert_id NUMERIC not null
		constraint rhn_csssl_cacertid_fk references rhnCryptoKey(id),
	ssl_client_cert_id NUMERIC
		constraint rhn_csssl_clcertid_fk references rhnCryptoKey(id),
	ssl_client_key_id NUMERIC
		constraint rhn_csssl_clkeyid_fk references rhnCryptoKey(id),
	constraint rhn_csssl_client_chk check(ssl_client_key_id is null or ssl_client_cert_id is not null),
	created TIMESTAMPTZ default(current_timestamp) not null,
	modified TIMESTAMPTZ default(current_timestamp) not null
)

;

create sequence rhn_contentsourcessl_seq;

07070100000A12000081B400000000000000000000000167AE111400000146000000000000000000000000000000000000007800000000susemanager-schema/upgrade/susemanager-schema-1.7.57-to-susemanager-schema-2.1/1009-rhn_content_source_ssl_mod_trig.sql   
create or replace function rhn_cont_source_ssl_mod_trig_fun() returns trigger as
$$
begin
	new.modified := current_timestamp;
	return new;
end;
$$ language plpgsql;


create trigger
rhn_cont_source_ssl_mod_trig
before insert or update on rhnContentSourceSsl
for each row
execute procedure rhn_cont_source_ssl_mod_trig_fun();
  07070100000A13000081B400000000000000000000000167AE111400000741000000000000000000000000000000000000006800000000susemanager-schema/upgrade/susemanager-schema-1.7.57-to-susemanager-schema-2.1/1011-rhn_channel.pkb.sql   --
-- Copyright (c) 2008--2013 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--

-- create schema rhn_channel;

--update pg_setting
update pg_settings set setting = 'rhn_channel,' || setting where name = 'search_path';

    create or replace function set_comps(channel_id_in in numeric, path_in in varchar, timestamp_in in varchar) returns void
    as $$
    declare
    row record;
    begin
        for row in (
            select relative_filename, last_modified
            from rhnChannelComps
            where channel_id = channel_id_in
            ) loop
            if row.relative_filename = path_in
                and row.last_modified = to_date(timestamp_in, 'YYYYMMDDHH24MISS') then
                return;
            end if;
        end loop;
        delete from rhnChannelComps
        where channel_id = channel_id_in;
        insert into rhnChannelComps (id, channel_id, relative_filename, last_modified, created, modified)
        values (sequence_nextval('rhn_channelcomps_id_seq'), channel_id_in, path_in, to_date(timestamp_in, 'YYYYMMDDHH24MISS'), current_timestamp, current_timestamp);
    end$$ language plpgsql;

-- restore the original setting
update pg_settings set setting = overlay( setting placing '' from 1 for (length('rhn_channel')+1) ) where name = 'search_path';
   07070100000A14000081B400000000000000000000000167AE111400000166000000000000000000000000000000000000007600000000susemanager-schema/upgrade/susemanager-schema-1.7.57-to-susemanager-schema-2.1/1012-epoch_seconds_to_timestamp_tz.sql --
-- Take seconds since epoch (January 1, 1970 UTC) and convert it
-- to time-zone'd timestamp. Mainly as compatibility with Oracle
-- which does not have the single-parameter to_timestamp.
--

create function epoch_seconds_to_timestamp_tz(secs in numeric)
returns timestamp with time zone
as
$$
begin
	return to_timestamp(secs);
end;
$$ language plpgsql;

  07070100000A15000081B400000000000000000000000167AE111400000852000000000000000000000000000000000000006700000000susemanager-schema/upgrade/susemanager-schema-1.7.57-to-susemanager-schema-2.1/1013-rhnServerCrash.sql    --
-- Copyright (c) 2013 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

create table rhnServerCrash
(
    id              NUMERIC not null
                    constraint rhn_server_crash_id_pk primary key,
    server_id       NUMERIC not null
                    constraint rhn_server_crash_sid_fk
                        references rhnServer(id)
                        on delete cascade,
    crash           VARCHAR(512) not null,
    path            VARCHAR(1024) not null,
    count           NUMERIC not null,
    analyzer        VARCHAR(128),
    architecture    VARCHAR(16),
    cmdline         VARCHAR(2048),
    component       VARCHAR(256),
    executable      VARCHAR(512),
    kernel          VARCHAR(128),
    reason          VARCHAR(512),
    username        VARCHAR(256),
    package_name_id NUMERIC
                    constraint rhn_server_crash_pname_id_fk
                        references rhnPackageName(id),
    package_evr_id  NUMERIC
                    constraint rhn_server_crash_evr_id_fk
                        references rhnPackageEVR(id),
    package_arch_id NUMERIC
                    constraint rhn_server_crash_arch_id_fk
                        references rhnPackageArch(id),
    storage_path    VARCHAR(1024),
    created         TIMESTAMPTZ
                        default (current_timestamp) not null,
    modified        TIMESTAMPTZ
                        default (current_timestamp) not null
)

;

create sequence rhn_server_crash_id_seq start with 1;

create unique index rhn_scr_sid_crash
    on rhnServerCrash (server_id, crash)
    ;
  07070100000A16000081B400000000000000000000000167AE1114000003B2000000000000000000000000000000000000007000000000susemanager-schema/upgrade/susemanager-schema-1.7.57-to-susemanager-schema-2.1/1014-rhnServerCrash-triggers.sql   --
-- Copyright (c) 2013 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

create or replace function rhn_server_crash_mod_trig_fun() returns trigger as
$$
begin
        new.modified := current_timestamp;
        return new;
end;
$$ language plpgsql;

create trigger
rhn_server_crash_mod_trig
before insert or update on rhnServerCrash
for each row
execute procedure rhn_server_crash_mod_trig_fun();
  07070100000A17000081B400000000000000000000000167AE111400000608000000000000000000000000000000000000006B00000000susemanager-schema/upgrade/susemanager-schema-1.7.57-to-susemanager-schema-2.1/1015-rhnServerCrashFile.sql    --
-- Copyright (c) 2013 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

create table rhnServerCrashFile
(
    id          NUMERIC not null
                constraint rhn_server_crash_file_id_pk primary key,
    crash_id    NUMERIC not null
                constraint rhn_server_crash_file_cis_fk
                    references rhnServerCrash(id)
                    on delete cascade,
    filename    VARCHAR(512) not null,
    path        VARCHAR(1024) not null,
    filesize    NUMERIC not null,
    is_uploaded char(1)
                default ('N') not null
                constraint rhn_server_crash_file_upl_ck
                check (is_uploaded in ('Y', 'N')),
    created     TIMESTAMPTZ
                    default (current_timestamp) not null,
    modified    TIMESTAMPTZ
                    default (current_timestamp) not null
)

;

create sequence rhn_server_crash_file_id_seq start with 1;

create unique index rhn_scrf_cid_fn
    on rhnServerCrashFile (crash_id, filename)
    ;
07070100000A18000081B400000000000000000000000167AE11140000059B000000000000000000000000000000000000006A00000000susemanager-schema/upgrade/susemanager-schema-1.7.57-to-susemanager-schema-2.1/1016-insert_crash_file.sql --
-- Copyright (c) 2013 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

create or replace function
insert_crash_file(
    crash_id_in in numeric,
    filename_in in varchar,
    path_in in varchar,
    filesize_in in numeric)
returns numeric
as
$$
declare
    crash_file_id numeric;
begin
    crash_file_id := nextval('rhn_server_crash_file_id_seq');
    insert into rhnServerCrashFile (id, crash_id, filename, path, filesize)
    values (crash_file_id, crash_id_in, filename_in, path_in, filesize_in);

    return crash_file_id;
exception when unique_violation then
    select id
      into crash_file_id
      from rhnServerCrashFile
     where crash_id = crash_id_in and
           filename = filename_in;

    update rhnServerCrashFile
       set path = path_in,
           filesize = filesize_in
     where id = crash_file_id;

    return crash_file_id;
end;
$$ language plpgsql;
 07070100000A19000081B400000000000000000000000167AE1114000003C5000000000000000000000000000000000000007400000000susemanager-schema/upgrade/susemanager-schema-1.7.57-to-susemanager-schema-2.1/1017-rhnServerCrashFile-triggers.sql   --
-- Copyright (c) 2013 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

create or replace function rhn_server_crash_file_mod_trig_fun() returns trigger as
$$
begin
        new.modified := current_timestamp;
        return new;
end;
$$ language plpgsql;

create trigger
rhn_server_crash_file_mod_trig
before insert or update on rhnServerCrashFile
for each row
execute procedure rhn_server_crash_file_mod_trig_fun();
   07070100000A1A000081B400000000000000000000000167AE111400000341000000000000000000000000000000000000006C00000000susemanager-schema/upgrade/susemanager-schema-1.7.57-to-susemanager-schema-2.1/1018-rhnServerCrashCount.sql   --
-- Copyright (c) 2013 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

create or replace view rhnServerCrashCount
as
select server_id,
       count(id) as unique_count,
       sum(count) as total_count,
       max(modified) as last_report
  from rhnServerCrash
 group by server_id;
   07070100000A1B000081B400000000000000000000000167AE1114000000A8000000000000000000000000000000000000006500000000susemanager-schema/upgrade/susemanager-schema-1.7.57-to-susemanager-schema-2.1/1019-web_customer.sql  alter table web_customer
  add crash_file_sizelimit
      NUMERIC default(2048) not null
      constraint web_customer_sizelimit_chk check (crash_file_sizelimit >= 0);
07070100000A1C000081B400000000000000000000000167AE111400000F43000000000000000000000000000000000000006A00000000susemanager-schema/upgrade/susemanager-schema-1.7.57-to-susemanager-schema-2.1/1020-rhnServerOverview.sql --
-- Copyright (c) 2008--2013 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--
--
--

drop view rhnServerOverview;

create or replace view
rhnServerOverview
(
    org_id,
    server_id,
    server_name,
    modified,
    server_admins,
    group_count,
    channel_id,
    channel_labels,
    history_count,
    security_errata,
    bug_errata,
    enhancement_errata,
    outdated_packages,
	config_files_with_differences,
    unique_crash_count,
    total_crash_count,
    last_checkin_days_ago,
    last_checkin,
    pending_updates,
    os,
    release,
    server_arch_name,
    locked
)
as
select
    s.org_id, s.id, s.name, s.modified,
    ( select count(user_id) from rhnUserServerPerms ap
      where server_id = s.id ),
    ( select count(server_group_id) from rhnVisibleServerGroupMembers
      where server_id = s.id ),
    ( select C.id
        from rhnChannel C,
	     rhnServerChannel SC
       where SC.server_id = S.id
         and SC.channel_id = C.id
	 and C.parent_channel IS NULL),
    coalesce(( select C.name
        from rhnChannel C,
	     rhnServerChannel SC
       where SC.server_id = S.id
         and SC.channel_id = C.id
	 and C.parent_channel IS NULL), '(none)'),
    ( select count(id) from rhnServerHistory
      where
            server_id = S.id),
    ( select count(*) from rhnServerErrataTypeView setv
      where
            setv.server_id = s.id
        and setv.errata_type = 'Security Advisory'),
    ( select count(*) from rhnServerErrataTypeView setv
      where
            setv.server_id = s.id
        and setv.errata_type = 'Bug Fix Advisory'),
    ( select count(*) from rhnServerErrataTypeView setv
      where
            setv.server_id = s.id
        and setv.errata_type = 'Product Enhancement Advisory'),
    ( select count(distinct p.name_id) from rhnPackage p, rhnServerNeededPackageCache snpc
      where
             snpc.server_id = S.id
	 and p.id = snpc.package_id
	 ),
    ( select count(*)
        from rhnActionConfigRevision ACR
             INNER JOIN rhnActionConfigRevisionResult ACRR on ACR.id = ACRR.action_config_revision_id
       where ACR.server_id = S.id
         and ACR.action_id = (
              select MAX(rA.id)
                from rhnAction rA
                     INNER JOIN rhnServerAction rSA on rSA.action_id = rA.id
                     INNER JOIN rhnActionStatus rAS on rAS.id = rSA.status
                     INNER JOIN rhnActionType rAT on rAT.id = rA.action_type
               where rSA.server_id = S.id
                 and rAS.name in ('Completed', 'Failed')
                 and rAT.label = 'configfiles.diff'
         )
         and ACR.failure_id is null
         and ACRR.result is not null
        ),
    ( select unique_count from rhnServerCrashCount where server_id = S.id ),
    ( select total_count from rhnServerCrashCount where server_id = S.id ),
    ( select date_diff_in_days(checkin, current_timestamp) from rhnServerInfo where server_id = S.id ),
    ( select TO_CHAR(checkin, 'YYYY-MM-DD HH24:MI:SS') from rhnServerInfo where server_id = S.id ),
    ( select count(1)
        from rhnServerAction
       where server_id = S.id
         and status in (0, 1)),
    os,
    release,
    ( select name from rhnServerArch where id = s.server_arch_id),
    coalesce((select 1 from rhnServerLock SL WHERE SL.server_id = S.id), 0)
from
    rhnServer S
;
 07070100000A1D000081B400000000000000000000000167AE11140000003C000000000000000000000000000000000000006400000000susemanager-schema/upgrade/susemanager-schema-1.7.57-to-susemanager-schema-2.1/1021-rhnAbrtInfo.sql   drop table rhnAbrtInfo;
drop sequence rhn_abrt_info_id_seq;
07070100000A1E000081B400000000000000000000000167AE1114000000BE000000000000000000000000000000000000006E00000000susemanager-schema/upgrade/susemanager-schema-1.7.57-to-susemanager-schema-2.1/1022-rhnServerNetInterface.sql 
ALTER TABLE rhnServerNetInterface ADD COLUMN is_primary VARCHAR(1);

CREATE UNIQUE INDEX rhn_srv_net_iface_prim_iface
  ON rhnServerNetInterface
  (server_id) where is_primary is not null;
  07070100000A1F000081B400000000000000000000000167AE1114000000B7000000000000000000000000000000000000006200000000susemanager-schema/upgrade/susemanager-schema-1.7.57-to-susemanager-schema-2.1/1023-rhnKsData.sql alter table rhnksdata add update_type VARCHAR(7) default ('none') not null;
alter table rhnksdata add constraint rhn_ks_update_type check (update_type in ('all', 'red_hat', 'none'));
 07070100000A20000081B400000000000000000000000167AE111400000163000000000000000000000000000000000000007400000000susemanager-schema/upgrade/susemanager-schema-1.7.57-to-susemanager-schema-2.1/2001-rhnContentSourceSsl-trigger.sql   
create or replace function rhn_csssl_ins_trig_fun() returns trigger as
$$
begin
    if new.id is null then
        new.id := sequence_nextval('rhn_contentsourcessl_seq');
    end if;
    return new;
end;
$$ language plpgsql;

create trigger
rhn_csssl_ins_trig
before insert on rhnContentSourceSsl
for each row
execute procedure rhn_csssl_ins_trig_fun();
 07070100000A21000081B400000000000000000000000167AE1114000008A9000000000000000000000000000000000000006C00000000susemanager-schema/upgrade/susemanager-schema-1.7.57-to-susemanager-schema-2.1/2002-rhnOrgConfiguration.sql   --
-- Copyright (c) 2013 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

create table rhnOrgConfiguration
(
    org_id                     NUMERIC not null
                                   constraint rhn_org_conf_org_id_fk
                                   references web_customer(id)
                                   on delete cascade,
    staging_content_enabled    char(1)
                                   default ('N') not null
                                   constraint rhn_org_conf_stage_content_chk
                                   check (staging_content_enabled in ('Y', 'N')),
    crash_reporting_enabled    char(1)
                                   default ('Y') not null
                                   constraint rhn_org_conf_crash_report_chk
                                   check (crash_reporting_enabled in ('Y', 'N')),
    crashfile_upload_enabled   char(1)
                                   default ('Y') not null
                                   constraint rhn_org_conf_crash_upload_chk
                                   check (crashfile_upload_enabled in ('Y', 'N')),
    crash_file_sizelimit       NUMERIC
                                   default(2048) not null
                                   constraint rhn_org_conf_sizelimit_chk
                                   check (crash_file_sizelimit >= 0),
    created                    TIMESTAMPTZ
                                   default (current_timestamp) not null,
    modified                   TIMESTAMPTZ
                                   default (current_timestamp) not null
)

;

create unique index rhn_org_conf_org_id
    on rhnOrgConfiguration (org_id)
    ;
   07070100000A22000081B400000000000000000000000167AE1114000003AB000000000000000000000000000000000000007400000000susemanager-schema/upgrade/susemanager-schema-1.7.57-to-susemanager-schema-2.1/2003-rhnOrgConfiguration-trigger.sql   --
-- Copyright (c) 2013 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

create or replace function rhn_org_conf_mod_trig_fun() returns trigger as
$$
begin
        new.modified := current_timestamp;
        return new;
end;
$$ language plpgsql;

create trigger
rhn_org_conf_mod_trig
before insert or update on rhnOrgConfiguration
for each row
execute procedure rhn_org_conf_mod_trig_fun();
 07070100000A23000081B400000000000000000000000167AE11140000039F000000000000000000000000000000000000007100000000susemanager-schema/upgrade/susemanager-schema-1.7.57-to-susemanager-schema-2.1/2004-rhnOrgConfiguration-data.sql  --
-- Copyright (c) 2013 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

insert into rhnOrgConfiguration (
    org_id,
    staging_content_enabled,
    crash_reporting_enabled,
    crashfile_upload_enabled,
    crash_file_sizelimit )
(
    select id,
           staging_content_enabled,
           'Y',
           'Y',
           crash_file_sizelimit
      from web_customer
);
 07070100000A24000081B400000000000000000000000167AE1114000002E7000000000000000000000000000000000000006500000000susemanager-schema/upgrade/susemanager-schema-1.7.57-to-susemanager-schema-2.1/2005-web_customer.sql  --
-- Copyright (c) 2013 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

alter table web_customer drop column staging_content_enabled;
alter table web_customer drop column crash_file_sizelimit;
 07070100000A25000081B400000000000000000000000167AE1114000003BB000000000000000000000000000000000000006E00000000susemanager-schema/upgrade/susemanager-schema-1.7.57-to-susemanager-schema-2.1/2006-web_customer-triggers.sql --
-- Copyright (c) 2013 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

create or replace function web_customer_insert_trig_fun() returns trigger
as
$$
begin
        insert into rhnOrgConfiguration (org_id) values (new.id);

        return new;
end;
$$
language plpgsql;


create trigger
web_customer_insert_trig
after insert on web_customer
for each row
execute procedure web_customer_insert_trig_fun();
 07070100000A26000081B400000000000000000000000167AE111400000644000000000000000000000000000000000000006B00000000susemanager-schema/upgrade/susemanager-schema-1.7.57-to-susemanager-schema-2.1/2007-rhnServerCrashNote.sql    --
-- Copyright (c) 2013 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnServerCrashNote
(
    id         NUMERIC NOT NULL
                   CONSTRAINT rhn_server_crash_note_id_pk PRIMARY KEY
                   ,
    creator    NUMERIC
                   CONSTRAINT rhn_srv_crash_note_creator_fk
                       REFERENCES web_contact (id)
                       ON DELETE SET NULL,
    crash_id  NUMERIC NOT NULL
                   CONSTRAINT rhn_srv_crash_note_sid_fk
                       REFERENCES rhnServerCrash (id)
                       ON DELETE CASCADE,
    subject    VARCHAR(80) NOT NULL,
    note       VARCHAR(4000),
    created    TIMESTAMPTZ
                   DEFAULT (current_timestamp) NOT NULL,
    modified   TIMESTAMPTZ
                   DEFAULT (current_timestamp) NOT NULL
)

;

CREATE INDEX rhn_srv_crash_note_sid_idx
    ON rhnServerCrashNote (crash_id)
    
    ;

CREATE INDEX rhn_srv_crash_note_creator_idx
    ON rhnServerCrashNote (creator)
    
    ;

CREATE SEQUENCE rhn_srv_crash_note_id_seq;
07070100000A27000081B400000000000000000000000167AE111400000154000000000000000000000000000000000000007300000000susemanager-schema/upgrade/susemanager-schema-1.7.57-to-susemanager-schema-2.1/2008-rhnServerCrashNote-trigger.sql    
create or replace function rhn_server_crash_note_mod_trig_fun() returns trigger as
$$
begin
    new.modified := current_timestamp;
    return new;
end;
$$ language plpgsql;

create trigger rhn_server_crash_note_mod_trig
before insert or update on rhnServerCrashNote
for each row
    execute procedure rhn_server_crash_note_mod_trig_fun();
07070100000A28000081B400000000000000000000000167AE111400000032000000000000000000000000000000000000006700000000susemanager-schema/upgrade/susemanager-schema-1.7.57-to-susemanager-schema-2.1/2009-rhnServerCrash.sql    alter table rhnServerCrash add uuid VARCHAR(256);
  07070100000A29000081B400000000000000000000000167AE111400000029000000000000000000000000000000000000006C00000000susemanager-schema/upgrade/susemanager-schema-1.7.57-to-susemanager-schema-2.1/2010-add_rhncpu_nrsocket.sql   ALTER TABLE rhnCpu ADD nrsocket NUMERIC;
   07070100000A2A000081B400000000000000000000000167AE11140000074B000000000000000000000000000000000000006800000000susemanager-schema/upgrade/susemanager-schema-1.7.57-to-susemanager-schema-2.1/2011-rhn_channel.pkb.sql   --
-- Copyright (c) 2008--2013 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--

-- create schema rhn_channel;

--update pg_setting
update pg_settings set setting = 'rhn_channel,' || setting where name = 'search_path';

    create or replace function set_comps(channel_id_in in numeric, path_in in varchar, timestamp_in in varchar) returns void
    as $$
    declare
    row record;
    begin
        for row in (
            select relative_filename, last_modified
            from rhnChannelComps
            where channel_id = channel_id_in
            ) loop
            if row.relative_filename = path_in
                and row.last_modified = to_timestamp(timestamp_in, 'YYYYMMDDHH24MISS') then
                return;
            end if;
        end loop;
        delete from rhnChannelComps
        where channel_id = channel_id_in;
        insert into rhnChannelComps (id, channel_id, relative_filename, last_modified, created, modified)
        values (sequence_nextval('rhn_channelcomps_id_seq'), channel_id_in, path_in, to_timestamp(timestamp_in, 'YYYYMMDDHH24MISS'), current_timestamp, current_timestamp);
    end$$ language plpgsql;

-- restore the original setting
update pg_settings set setting = overlay( setting placing '' from 1 for (length('rhn_channel')+1) ) where name = 'search_path';
 07070100000A2B000081B400000000000000000000000167AE1114000002FF000000000000000000000000000000000000006C00000000susemanager-schema/upgrade/susemanager-schema-1.7.57-to-susemanager-schema-2.1/2013-get_hw_info_as_clob.sql   
create or replace function get_hw_info_as_clob(
	sid in rhnserver.id%TYPE,
	separator in varchar
)
returns text
as
$$
declare
	ret text;
	rec record;
begin
	for rec in (
		select m
		from (
			select 1 n, sum(nrcpu) || ' CPUs ' || coalesce(to_char(sum(nrsocket), 'FM999'), 'unknown') || ' Sockets' m
			from rhncpu where rhncpu.server_id = sid
			union all
			select 2, ni.name||' '||coalesce(na4.address,'')||'/'||coalesce(na4.netmask,'')||' '||ni.hw_addr val
			from rhnservernetinterface ni,
			     rhnServerNetAddress4 na4
			where ni.server_id = sid
			  and ni.id = na4.interface_id
			) X
		order by n, m
		) loop
		if ret is null then
			ret := rec.m;
		else
			ret := ret || separator || rec.m;
		end if;
	end loop;
	return ret;
end;
$$ language plpgsql;

 07070100000A2C000081B400000000000000000000000167AE1114000004A8000000000000000000000000000000000000006700000000susemanager-schema/upgrade/susemanager-schema-1.7.57-to-susemanager-schema-2.1/2014-pg_dblink_exec.sql    --
-- Copyright (c) 2012 - 2013 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.

create or replace function pg_dblink_exec(in_sql in varchar) returns void as
$$
declare
    conn text[];
begin
    if in_sql is null then
	raise 'pg_dblink_exec in_sql is null';
    end if;
    conn := dblink_get_connections();
    if conn is NULL or NOT(conn @> '{at_conn}') then
        perform dblink_connect('at_conn', 'dbname=' || current_database() || ' port=' || coalesce(inet_server_port(), '5432'));
    end if;
    begin
        perform dblink_exec('at_conn', in_sql, true);
    exception when others then
        raise;
    end;
end;
$$
language plpgsql;
07070100000A2D000081B400000000000000000000000167AE1114000000A7000000000000000000000000000000000000007700000000susemanager-schema/upgrade/susemanager-schema-1.7.57-to-susemanager-schema-2.1/2015-rhnKickstartScript-erroronfail.sql    ALTER TABLE rhnkickstartscript ADD error_on_fail CHAR(1)
    DEFAULT ('N') not NULL CONSTRAINT rhn_ksscript_erroronfail_ck
        CHECK (error_on_fail in ('Y','N'));
 07070100000A2E000081B400000000000000000000000167AE111400000572000000000000000000000000000000000000006D00000000susemanager-schema/upgrade/susemanager-schema-1.7.57-to-susemanager-schema-2.1/2016-lookup_package_group.sql  --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 

create or replace function
lookup_package_group(name_in in varchar)
returns numeric
as
$$
declare
    package_id   numeric;
begin
    select id
      into package_id
      from rhnPackageGroup
     where name = name_in;

    if not found then
        package_id := nextval('rhn_package_group_id_seq');
        begin
            perform pg_dblink_exec(
                'insert into rhnPackageGroup(id, name) values (' ||
                package_id || ', ' || coalesce(quote_literal(name_in), 'NULL') || ')');
        exception when unique_violation then
            select id
              into strict package_id
              from rhnPackageGroup
             where name = name_in;
        end;
    end if;

    return package_id;
end;
$$
language plpgsql immutable;
  07070100000A2F000081B400000000000000000000000167AE1114000001BA000000000000000000000000000000000000006800000000susemanager-schema/upgrade/susemanager-schema-1.7.57-to-susemanager-schema-2.1/2018-all_tab_columns.sql   
drop view all_tab_columns;

create or replace view all_tab_columns
as
select
        table_name              as table_name,
        column_name             as column_name,
        ordinal_position        as column_id,
        data_type               as data_type,
        numeric_precision       as data_precision,
        character_maximum_length as data_length,
        substr(is_nullable,1,1) as nullable
from information_schema.columns;
  07070100000A30000081B400000000000000000000000167AE111400000171000000000000000000000000000000000000007100000000susemanager-schema/upgrade/susemanager-schema-1.7.57-to-susemanager-schema-2.1/2019-rhnOrgConfiguration-scap.sql  alter table rhnOrgConfiguration
  add scapfile_upload_enabled
      char(1) default ('N') not null
      constraint rhn_org_conf_scap_upload_chk check (scapfile_upload_enabled in ('Y', 'N'));
alter table rhnOrgConfiguration
  add scap_file_sizelimit
      NUMERIC default(2097152) not null
      constraint rhn_org_conf_scap_szlmt_chk check (scap_file_sizelimit >= 0);
   07070100000A31000081B400000000000000000000000167AE111400000038000000000000000000000000000000000000006B00000000susemanager-schema/upgrade/susemanager-schema-1.7.57-to-susemanager-schema-2.1/2019-rhnTaskoRun-status.sql    
ALTER TABLE rhnTaskoRun ALTER status TYPE VARCHAR(12);
07070100000A32000081B400000000000000000000000167AE111400000052000000000000000000000000000000000000007000000000susemanager-schema/upgrade/susemanager-schema-1.7.57-to-susemanager-schema-2.1/2020-rhnConfigRevision-index.sql   
create index rhn_confrevision_ccid_idx on rhnConfigRevision (config_content_id);
  07070100000A33000081B400000000000000000000000167AE11140000182B000000000000000000000000000000000000006700000000susemanager-schema/upgrade/susemanager-schema-1.7.57-to-susemanager-schema-2.1/2021-rhn_config.pkb.sql    --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--

-- setup search_path so that these functions are created in appropriate schema.
update pg_settings set setting = 'rhn_config,' || setting where name = 'search_path';


	-- just a stub for now
create or replace function prune_org_configs (
		org_id_in in numeric,
		total_in in numeric
	)
returns void
as $$	
begin
end;
$$ LANGUAGE 'plpgsql';


	create or replace function insert_revision (
		revision_in in numeric,
		config_file_id_in in numeric,
		config_content_id_in in numeric,
		config_info_id_in in numeric,
		config_file_type_id_in in numeric default 1
	) returns numeric as $$
               declare
		retval numeric;

	begin
      
		insert into rhnConfigRevision(id, revision, config_file_id,
				config_content_id, config_info_id, config_file_type_id
			) values (
				nextval('rhn_confrevision_id_seq'), revision_in, config_file_id_in,
				config_content_id_in, config_info_id_in, config_file_type_id_in
			)
			returning id into retval;

		return retval;
	end$$ language 'plpgsql';

	create or replace function delete_revision (
		config_revision_id_in in numeric,
		org_id_in in numeric default -1
	) returns void as $$
	declare
		cfid numeric;
		ccid numeric;
		latest_crid numeric;
		others numeric := 0;
	begin
		select	cr.config_content_id
		into	ccid
		from	rhnConfigRevision cr
		where	cr.id = config_revision_id_in;

		-- right now this will set rhnActionConfigFileName.config_revision_id
		-- to null, and will remove an entry from rhnActionConfigRevision.
		-- might we want to prune and/or kill the action in some way?  maybe
		-- mark it failed or something?
                -- this delete also triggers rhn_confrevision_del_trig() which
                -- a) updates rhnSnapshot.invalid to 'cr_removed'
                -- and b) deletes snapshots from rhnSnapshotConfigRevision
		delete from rhnConfigRevision where id = config_revision_id_in;

		-- now prune away content if there aren't any other revisions pointing
		-- at it
		select count(*)
                  into others
                  from rhnConfigRevision
                 where config_content_id = ccid;
		if others = 0 then
			delete from rhnConfigContent where id = ccid;
		end if;

		-- now make sure rhnConfigFile points at a valid revision;
		-- if there isn't one, we're deleting it, _unless_ org_id_in is
		-- >= 0, in which case we're in the delete trigger anyway
		if org_id_in < 0 then
			select	cf.latest_config_revision_id,
					cf.id
			into latest_crid,
					cfid
			from rhnConfigFile cf,
					rhnConfigRevision cr
			where cr.id = config_revision_id_in
				and cr.config_file_id = cf.id;

			if latest_crid = config_revision_id_in then
				latest_crid := rhn_config.get_latest_revision(cfid);
				if latest_crid is not null then
					update rhnConfigFile set latest_config_revision_id = latest_crid
						where id = cfid;
				else
					delete from rhnConfigFile where id = cfid;
				end if;
			end if;

		end if;

	end ;
$$ LANGUAGE 'plpgsql';

	create or replace function get_latest_revision (
		config_file_id_in in numeric
		) 
		returns numeric as $$
		declare 
 		revision1 record;
		begin
		for revision1 in 
			select cr.id 
			from rhnConfigRevision cr
			where cr.config_file_id = config_file_id_in
			order by revision desc
		loop
			return revision1.id;
		end loop;
		return null;
end;
$$ LANGUAGE 'plpgsql';

	create or replace function insert_file (
		config_channel_id_in in numeric,
		name_in in varchar
	) returns numeric as $$
		declare
		retval numeric;
	begin
		select nextval('rhn_conffile_id_seq')
		into retval;

		insert into rhnConfigFile(id, config_channel_id, config_file_name_id, 
				state_id
			) (
				select retval,
						config_channel_id_in,
						lookup_config_filename(name_in),
						id
				from rhnConfigFileState
				where label = 'alive'
			);

		return retval;
	end;
$$ LANGUAGE 'plpgsql';

	create or replace function delete_file (
		config_file_id_in in numeric
	) returns void as $$
declare
revision record;
			
	begin
		for revision in 
		select cr.id, cc.org_id
			from rhnConfigChannel cc,
					rhnConfigRevision cr,
					rhnConfigFile cf
			where cf.id = config_file_id_in
				and cf.config_channel_id = cc.id
				and cr.config_file_id = cf.id
		
                loop
			perform rhn_config.delete_revision(revision.id, revision.org_id);
		end loop;
		delete from rhnConfigFile where id = config_file_id_in;
	end;
$$ LANGUAGE 'plpgsql';

	create or replace function insert_channel (
		org_id_in in numeric,
		type_in in varchar,
		name_in in varchar,
		label_in in varchar,
		description_in in varchar
	) returns numeric as $$
declare
		retval numeric;
	begin
		select nextval ('rhn_confchan_id_seq')
		into retval;

		insert into rhnConfigChannel(id, org_id, confchan_type_id,
				name, label, description
			) (
				select	retval,
						org_id_in,
						cct.id,
						name_in,
						label_in,
						description_in
				from rhnConfigChannelType cct
				where label = type_in
			);
		return retval;
	end;
$$ LANGUAGE 'plpgsql';

	create or replace function delete_channel (
		config_channel_id_in in numeric
	) returns void as $$
declare
	config_file record;		
	begin
		for config_file in 
		select id
			from rhnConfigFile
			where config_channel_id = config_channel_id_in
                loop
                    perform rhn_config.delete_file(config_file.id);
		end loop;
		delete from rhnConfigChannel where id = config_channel_id_in;

end;
$$ LANGUAGE 'plpgsql';

update pg_settings set setting = overlay( setting placing '' from 1 for (length('rhn_config')+1) ) where name = 'search_path';
 07070100000A34000081B400000000000000000000000167AE111400000230000000000000000000000000000000000000006400000000susemanager-schema/upgrade/susemanager-schema-1.7.57-to-susemanager-schema-2.1/2022-rhnISSSlave.sql   create table rhnISSSlave (
    id NUMERIC not null constraint rhn_isss_id_pk primary key,
    slave VARCHAR(512) not null constraint rhn_isss_name_uq unique,
    enabled char(1) default 'Y' not null
        constraint rhn_isss_enabled_yn check (enabled in ( 'Y', 'N' )),
    allow_all_orgs char(1) default 'Y' not null
        constraint rhn_isss_allorgs_yn check (allow_all_orgs in ( 'Y', 'N' )),
    created TIMESTAMPTZ default (current_timestamp) not null,
    modified TIMESTAMPTZ default (current_timestamp) not null
);

create sequence rhn_issslave_seq;
07070100000A35000081B400000000000000000000000167AE111400000132000000000000000000000000000000000000006800000000susemanager-schema/upgrade/susemanager-schema-1.7.57-to-susemanager-schema-2.1/2023-rhnISSSlaveOrgs.sql   create table rhnISSSlaveOrgs (
    slave_id NUMERIC not null constraint rhn_isssorg_sid_fk references rhnISSSlave(id) on delete cascade,
    org_id NUMERIC not null constraint rhn_isssorg_oid_fk references web_customer(id) on delete cascade,
    created TIMESTAMPTZ default (current_timestamp) not null
);
  07070100000A36000081B400000000000000000000000167AE111400000110000000000000000000000000000000000000006500000000susemanager-schema/upgrade/susemanager-schema-1.7.57-to-susemanager-schema-2.1/2024-rhnISSMaster.sql  create table rhnIssMaster (
    id NUMERIC not null constraint rhn_iss_master_id_pk primary key,
    label VARCHAR(256) not null constraint rhn_iss_master_label_uq unique,
    created TIMESTAMPTZ default (current_timestamp) not null
);

create sequence rhn_issmaster_seq;
07070100000A37000081B400000000000000000000000167AE1114000001FB000000000000000000000000000000000000006900000000susemanager-schema/upgrade/susemanager-schema-1.7.57-to-susemanager-schema-2.1/2025-rhnISSMasterOrgs.sql  create table rhnIssMasterOrgs (
    id NUMERIC not null constraint rhn_issmasterorgs_id_pk primary key,
    master_id NUMERIC not null
        constraint rhn_issmasterorgs_cid_fk references rhnIssMaster(id) on delete cascade,
    master_org_id NUMERIC not null,
    master_org_name VARCHAR(512) not null,
    local_org_id NUMERIC
        constraint rhn_issmasterorgs_lid_fk references web_customer(id),
    created TIMESTAMPTZ default (current_timestamp) not null
);

create sequence rhn_issmasterorgs_seq;
 07070100000A38000081B400000000000000000000000167AE1114000002C4000000000000000000000000000000000000007300000000susemanager-schema/upgrade/susemanager-schema-1.7.57-to-susemanager-schema-2.1/2026-rhnConfigRevision-triggers.sql    
create or replace function rhn_confrevision_del_trig_fun() returns trigger 
as
$$
declare
        cr_removed numeric := lookup_snapshot_invalid_reason('cr_removed');
begin
        update rhnSnapshot
           set invalid = cr_removed
         where id in (select snapshot_id
                        from rhnSnapshotConfigRevision
                       where config_revision_id = old.id);
        delete from rhnSnapshotConfigRevision
         where config_revision_id = old.id
           and snapshot_id in (select snapshot_id
                                 from rhnSnapshotConfigRevision
                                where config_revision_id = old.id);
        return old;
end;
$$ language plpgsql;
07070100000A39000081B400000000000000000000000167AE11140000008E000000000000000000000000000000000000006700000000susemanager-schema/upgrade/susemanager-schema-1.7.57-to-susemanager-schema-2.1/2027-web_contact-ro.sql    alter table web_contact
    add read_only char(1) default('N') not null
        constraint web_contact_ro_ck check (read_only in ('Y', 'N'));
  07070100000A3A000081B400000000000000000000000167AE111400000143000000000000000000000000000000000000007400000000susemanager-schema/upgrade/susemanager-schema-1.7.57-to-susemanager-schema-2.1/2028-satellite_sync_master_in_db.sql   
alter table rhnISSMaster add is_current_master char(1) default 'N' not null
    constraint rhn_issm_master_yn check (is_current_master in ('Y', 'N'));

alter table rhnISSMaster add ca_cert varchar(1024);

create unique index rhn_issm_only_one_default on rhnISSMaster
    (is_current_master) where is_current_master = 'Y';
 07070100000A3B000081B400000000000000000000000167AE111400000030000000000000000000000000000000000000006200000000susemanager-schema/upgrade/susemanager-schema-1.7.57-to-susemanager-schema-2.1/2029-rhnServer.sql ALTER TABLE rhnServer DROP COLUMN auto_deliver;
07070100000A3C000081B400000000000000000000000167AE1114000000F0000000000000000000000000000000000000006800000000susemanager-schema/upgrade/susemanager-schema-1.7.57-to-susemanager-schema-2.1/2030-web_contact_all.sql   CREATE TABLE web_contact_all
(
    id                 NUMERIC
                           CONSTRAINT web_contact_all_pk PRIMARY KEY
                           ,
    org_id             NUMERIC,
    login              VARCHAR(64) NOT NULL
)
;
07070100000A3D000081B400000000000000000000000167AE111400000108000000000000000000000000000000000000006D00000000susemanager-schema/upgrade/susemanager-schema-1.7.57-to-susemanager-schema-2.1/2031-web_contact_all-data.sql  INSERT INTO web_contact_all (id, org_id, login)
        VALUES (-1, null, 'SETUP');
INSERT INTO web_contact_all (id, org_id, login)
        VALUES (-2, null, 'CLIENT');
INSERT INTO web_contact_all (id, org_id, login)
    SELECT id, org_id, login FROM web_contact;
07070100000A3E000081B400000000000000000000000167AE111400000144000000000000000000000000000000000000006D00000000susemanager-schema/upgrade/susemanager-schema-1.7.57-to-susemanager-schema-2.1/2032-web_contact-triggers.sql  
create or replace function web_contact_ins_trig_fun() returns trigger
as
$$
begin
        new.modified := current_timestamp;
        new.login_uc := UPPER(new.login);
        insert into web_contact_all (id, org_id, login)
            values (new.id, new.org_id, new.login);

        return new;
end;
$$
language plpgsql;

07070100000A3F000081B400000000000000000000000167AE1114000000AE000000000000000000000000000000000000005C00000000susemanager-schema/upgrade/susemanager-schema-1.7.57-to-susemanager-schema-2.1/2033-log.sql   CREATE TABLE log
(
    id INTEGER NOT NULL PRIMARY KEY,
    stamp TIMESTAMP WITH TIME ZONE,
    user_id INTEGER REFERENCES web_contact_all(id)
)

;

CREATE SEQUENCE log_seq;
  07070100000A40000081B400000000000000000000000167AE11140000027E000000000000000000000000000000000000006400000000susemanager-schema/upgrade/susemanager-schema-1.7.57-to-susemanager-schema-2.1/2034-logging.pks.sql   --
-- Copyright (c) 2013 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

create schema ;
  07070100000A41000081B400000000000000000000000167AE111400001961000000000000000000000000000000000000006400000000susemanager-schema/upgrade/susemanager-schema-1.7.57-to-susemanager-schema-2.1/2035-logging.pkb.sql   --
-- Copyright (c) 2013 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

-- create schema ;

update pg_settings set setting = ',' || setting where name = 'search_path';

create or replace function clear_log_id()
returns void
as
$$
    global the_log_id
    set the_log_id 0
    global the_user_id
    set the_user_id 0
    global the_stamp
    set the_stamp ""
    return
$$ language pltclu set search_path from current;

create or replace function _set_log_auth(user_id in integer, stamp in varchar)
returns void
as
$$
    global the_user_id
    set the_user_id $1
    global the_stamp
    set the_stamp $2
$$ language pltclu set search_path from current;

create or replace function set_log_auth(user_id in integer)
returns void
as
$$
begin
    perform _set_log_auth(user_id, current_timestamp::varchar);
end
$$ language plpgsql set search_path from current;

create or replace function _get_log_auth()
returns integer
as
$$
    global the_user_id
    return $the_user_id
$$ language pltclu set search_path from current;

create or replace function _get_log_stamp()
returns varchar
as
$$
    global the_stamp
    return $the_stamp
$$ language pltclu set search_path from current;

create or replace function _get_log_id()
returns integer
as
$$
    global the_log_id
    return $the_log_id
$$ language pltclu set search_path from current;

create or replace function _set_log_id(log_id in integer)
returns void
as
$$
    global the_log_id
    set the_log_id $1
    return
$$ language pltclu set search_path from current;

create or replace function get_log_id()
returns integer
as
$$
declare
    the_log_id integer;
    the_user_id integer;
    the_stamp varchar;
begin
    the_log_id := _get_log_id();
    if the_log_id is not null and the_log_id > 0 then return the_log_id ; end if;
    the_log_id := nextval('log_seq');
    the_user_id := _get_log_auth();
    the_stamp := _get_log_stamp();
    insert into public.log (id, stamp, user_id)
    values (the_log_id,
        case when the_stamp = '' then current_timestamp else the_stamp::timestamp with time zone end,
        case when the_user_id = '0' then null else the_user_id::integer end);
    perform _set_log_id(the_log_id);
    return the_log_id;
end;
$$ language plpgsql set search_path from current;

create or replace function enable_(table_name_in in varchar)
returns void
as
$$
declare
    pk_column varchar;
    ddl_columns varchar;
    the_insert varchar;
    rec record;
begin
    select constraint_column_usage.column_name into strict pk_column
    from information_schema.table_constraints, information_schema.constraint_column_usage
    where constraint_column_usage.table_catalog = current_catalog
        and constraint_column_usage.table_schema = 'public'
        and constraint_column_usage.table_name = table_name_in
        and constraint_column_usage.constraint_catalog = current_catalog
        and constraint_column_usage.constraint_schema = 'public'
        and constraint_column_usage.table_catalog = table_constraints.constraint_catalog
        and constraint_column_usage.table_catalog = table_constraints.table_catalog
        and constraint_column_usage.table_schema = table_constraints.constraint_schema
        and constraint_column_usage.table_schema = table_constraints.table_schema
        and constraint_column_usage.constraint_catalog = table_constraints.constraint_catalog
        and constraint_column_usage.constraint_name = table_constraints.constraint_name
        and table_constraints.constraint_type = 'PRIMARY KEY';
    ddl_columns := '';
    for rec in (
        select column_name
        from information_schema.columns
        where table_catalog = current_catalog
            and table_schema = 'public'
            and table_name = table_name_in
            and column_name not in ( pk_column, 'created', 'modified' )
    ) loop
        ddl_columns := ddl_columns || ', ' || rec.column_name;
    end loop;

    execute 'create table public.' || table_name_in || '_log
        as select ' || pk_column || ', .get_log_id()::integer as log_id, ''A''::char as action' || ddl_columns
        || ' from ' || table_name_in;
    execute 'alter table public.' || table_name_in || '_log alter ' || pk_column || ' set not null';
    execute 'create index ' || table_name_in || '_log_idx on public.' || table_name_in || '_log(' || pk_column || ')';
    execute 'alter table public.' || table_name_in || '_log alter log_id set not null';
    execute 'alter table public.' || table_name_in || '_log add foreign key (log_id) references log(id)';
    execute 'alter table public.' || table_name_in || '_log alter action set not null';

    the_insert := 'insert into public.' || table_name_in || '_log (log_id, action, ' || pk_column || ddl_columns ||')
                values (log_id_v, substr(tg_op, 1, 1)' || replace(', ' || pk_column || ddl_columns, ', ', ', old.') || ');';
    execute 'create or replace function public.' || table_name_in || '_log_trig_fun() returns trigger as
        ''
        declare
            log_id_v integer;
        begin
            log_id_v := .get_log_id();
            if tg_op = ''''UPDATE'''' then
                if old.' || pk_column || ' <> new.' || pk_column || ' then raise exception ''''Cannot update column ' || table_name_in || '.' || pk_column || '.''''; end if;
            end if;
            if tg_op = ''''DELETE'''' then
                ' || the_insert || '
            else
                ' || replace(the_insert, 'old.', 'new.') || '
            end if;
            return new;
        end;
        ''
        language plpgsql;';

    execute 'create trigger ' || table_name_in || '_log_trig
        after insert or update or delete on public.' || table_name_in || '
        for each row
        execute procedure ' || table_name_in || '_log_trig_fun()';

end;
$$
language plpgsql;

update pg_settings set setting = overlay( setting placing '' from 1 for (length('')+1) ) where name = 'search_path';
   07070100000A42000081B400000000000000000000000167AE1114000002FC000000000000000000000000000000000000006700000000susemanager-schema/upgrade/susemanager-schema-1.7.57-to-susemanager-schema-2.1/2036-enable_logging.sql    --
-- Copyright (c) 2013 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

select .clear_log_id();
select .enable_logging('web_contact');
select .enable_logging('rhnserver');
select .enable_logging('rhnservergroup');
07070100000A43000081B400000000000000000000000167AE111400000198000000000000000000000000000000000000006600000000susemanager-schema/upgrade/susemanager-schema-1.7.57-to-susemanager-schema-2.1/2037-rhnPackageKey.sql update rhnPackageKey set provider_id = lookup_package_provider('Fedora')
 where key_id = '07477e65fb4b18e6';

insert into rhnPackageKey (id, key_id, key_type_id, provider_id)
    (select sequence_nextval('rhn_pkey_id_seq'), '07477e65fb4b18e6', lookup_package_key_type('gpg'), lookup_package_provider('Fedora') from dual
     where not exists (select 1 from rhnPackageKey where key_id = '07477e65fb4b18e6'));
07070100000A44000081B400000000000000000000000167AE111400000054000000000000000000000000000000000000005C00000000susemanager-schema/upgrade/susemanager-schema-1.7.57-to-susemanager-schema-2.1/4001-log.sql   
ALTER TABLE log ALTER id TYPE numeric;
ALTER TABLE log ALTER user_id TYPE numeric;
07070100000A45000081B400000000000000000000000167AE1114000000A7000000000000000000000000000000000000006300000000susemanager-schema/upgrade/susemanager-schema-1.7.57-to-susemanager-schema-2.1/4002-log-tables.sql    
ALTER TABLE web_contact_log ALTER log_id TYPE numeric;
ALTER TABLE rhnServer_log ALTER log_id TYPE numeric;
ALTER TABLE rhnServerGroup_log ALTER log_id TYPE numeric;
 07070100000A46000081B400000000000000000000000167AE111400001F07000000000000000000000000000000000000006400000000susemanager-schema/upgrade/susemanager-schema-1.7.57-to-susemanager-schema-2.1/4004-logging.pkb.sql   --
-- Copyright (c) 2013 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

-- create schema ;

update pg_settings set setting = ',' || setting where name = 'search_path';

drop function clear_log_id();
drop function _set_log_auth(user_id in integer, stamp in varchar);
drop function set_log_auth(user_id in integer);
drop function _get_log_auth();
drop function _get_log_stamp();
drop function _get_log_id();
drop function _set_log_id(log_id in integer);
drop function get_log_id();
drop function enable_(table_name_in in varchar);

create or replace function clear_log_id()
returns void
as
$$
    global the_log_id
    set the_log_id 0
    global the_user_id
    set the_user_id 0
    global the_stamp
    set the_stamp ""
    return
$$ language pltclu set search_path from current;

create or replace function _set_log_auth(user_id in numeric, stamp in varchar)
returns void
as
$$
    global the_user_id
    set the_user_id $1
    global the_stamp
    set the_stamp $2
$$ language pltclu set search_path from current;

create or replace function set_log_auth(user_id in numeric)
returns void
as
$$
begin
    perform _set_log_auth(user_id, current_timestamp::varchar);
end
$$ language plpgsql set search_path from current;

create or replace function _get_log_auth()
returns numeric
as
$$
    global the_user_id
    return $the_user_id
$$ language pltclu set search_path from current;

create or replace function _get_log_stamp()
returns varchar
as
$$
    global the_stamp
    return $the_stamp
$$ language pltclu set search_path from current;

create or replace function _get_log_id()
returns numeric
as
$$
    global the_log_id
    return $the_log_id
$$ language pltclu set search_path from current;

create or replace function _set_log_id(log_id in numeric)
returns void
as
$$
    global the_log_id
    set the_log_id $1
    return
$$ language pltclu set search_path from current;

create or replace function get_log_id()
returns numeric
as
$$
declare
    the_log_id numeric;
    the_user_id numeric;
    the_stamp varchar;
begin
    the_log_id := _get_log_id();
    if the_log_id is not null and the_log_id > 0 then return the_log_id ; end if;
    the_log_id := nextval('log_seq');
    the_user_id := _get_log_auth();
    the_stamp := _get_log_stamp();
    insert into public.log (id, stamp, user_id)
    values (the_log_id,
        case when the_stamp = '' then current_timestamp else the_stamp::timestamp with time zone end,
        case when the_user_id = '0' then null else the_user_id::numeric end);
    perform _set_log_id(the_log_id);
    return the_log_id;
end;
$$ language plpgsql set search_path from current;

create or replace function _get_primary_key_column(table_name_in in varchar)
returns varchar
as
$$
declare
    pk_column varchar;
begin
    select constraint_column_usage.column_name into strict pk_column
    from information_schema.table_constraints, information_schema.constraint_column_usage
    where constraint_column_usage.table_catalog = current_catalog
        and constraint_column_usage.table_schema = 'public'
        and constraint_column_usage.table_name = lower(table_name_in)
        and constraint_column_usage.constraint_catalog = current_catalog
        and constraint_column_usage.constraint_schema = 'public'
        and constraint_column_usage.table_catalog = table_constraints.constraint_catalog
        and constraint_column_usage.table_catalog = table_constraints.table_catalog
        and constraint_column_usage.table_schema = table_constraints.constraint_schema
        and constraint_column_usage.table_schema = table_constraints.table_schema
        and constraint_column_usage.constraint_catalog = table_constraints.constraint_catalog
        and constraint_column_usage.constraint_name = table_constraints.constraint_name
        and table_constraints.constraint_type = 'PRIMARY KEY';
    return pk_column;
end;
$$
language plpgsql set search_path from current;

create or replace function _get_ddl_columns(table_name_in in varchar, pk_column_in in varchar)
returns varchar
as
$$
declare
    ddl_columns varchar;
    rec record;
begin
    ddl_columns := '';
    for rec in (
        select column_name
        from information_schema.columns
        where table_catalog = current_catalog
            and table_schema = 'public'
            and table_name = lower(table_name_in)
            and column_name not in (pk_column_in, 'created', 'modified' )
    ) loop
        ddl_columns := ddl_columns || ', ' || rec.column_name;
    end loop;
    return ddl_columns;
end;
$$
language plpgsql set search_path from current;


create or replace function recreate_trigger(table_name_in in varchar)
returns void
as
$$
declare
    pk_column varchar;
    ddl_columns varchar;
    the_insert varchar;
begin
    pk_column := _get_primary_key_column(table_name_in);
    ddl_columns := _get_ddl_columns(table_name_in, pk_column);
    the_insert := 'insert into public.' || table_name_in || '_log (log_id, action, ' || pk_column || ddl_columns ||')
                values (log_id_v, substr(tg_op, 1, 1)' || replace(', ' || pk_column || ddl_columns, ', ', ', old.') || ');';
    execute 'create or replace function public.' || table_name_in || '_log_trig_fun() returns trigger as
        ''
        declare
            log_id_v numeric;
        begin
            log_id_v := .get_log_id();
            if tg_op = ''''UPDATE'''' then
                if old.' || pk_column || ' <> new.' || pk_column || ' then raise exception ''''Cannot update column ' || table_name_in || '.' || pk_column || '.''''; end if;
            end if;
            if tg_op = ''''DELETE'''' then
                ' || the_insert || '
            else
                ' || replace(the_insert, 'old.', 'new.') || '
            end if;
            return new;
        end;
        ''
        language plpgsql;';

    execute 'drop trigger if exists ' || table_name_in || '_log_trig' || ' on ' || table_name_in;
    execute 'create trigger ' || table_name_in || '_log_trig
        after insert or update or delete on public.' || table_name_in || '
        for each row
        execute procedure ' || table_name_in || '_log_trig_fun()';

end;
$$
language plpgsql set search_path from current;

create or replace function enable_(table_name_in in varchar)
returns void
as
$$
declare
    pk_column varchar;
    ddl_columns varchar;
begin
    pk_column := _get_primary_key_column(table_name_in);
    ddl_columns := _get_ddl_columns(table_name_in, pk_column);

    execute 'create table public.' || table_name_in || '_log
        as select ' || pk_column || ', .get_log_id()::numeric as log_id, ''A''::char as action' || ddl_columns
        || ' from ' || table_name_in;
    execute 'alter table public.' || table_name_in || '_log alter ' || pk_column || ' set not null';
    execute 'create index ' || table_name_in || '_log_idx on public.' || table_name_in || '_log(' || pk_column || ')';
    execute 'alter table public.' || table_name_in || '_log alter log_id set not null';
    execute 'alter table public.' || table_name_in || '_log add foreign key (log_id) references log(id)';
    execute 'alter table public.' || table_name_in || '_log alter action set not null';
    perform recreate_trigger(table_name_in);
end;
$$
language plpgsql set search_path from current;

update pg_settings set setting = overlay( setting placing '' from 1 for (length('')+1) ) where name = 'search_path';
 07070100000A47000081B400000000000000000000000167AE11140000007D000000000000000000000000000000000000007200000000susemanager-schema/upgrade/susemanager-schema-1.7.57-to-susemanager-schema-2.1/4005-logging-recreate-triggers.sql 
select .recreate_trigger('web_contact');
select .recreate_trigger('rhnserver');
select .recreate_trigger('rhnservergroup');
   07070100000A48000081B400000000000000000000000167AE111400010654000000000000000000000000000000000000006D00000000susemanager-schema/upgrade/susemanager-schema-1.7.57-to-susemanager-schema-2.1/4010-rhn_entitlements.pkb.sql  --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

-- create schema rhn_entitlements;

-- setup search_path so that these functions are created in appropriate schema.
update pg_settings set setting = 'rhn_entitlements,' || setting where name = 'search_path';

   create or replace function find_compatible_sg (
      server_id_in in numeric,
      type_label_in in varchar
   )
   returns numeric
as $$
    declare
      servergroups cursor for
         select sg.id
           from rhnServerGroupType             sgt,
                rhnServerGroup                 sg,
                rhnServer                     s,
                rhnServerServerGroupArchCompat ssgac
          where s.id = server_id_in
            and s.org_id = sg.org_id
            and sgt.label = type_label_in
            and sg.group_type = sgt.id
            and ssgac.server_group_type = sgt.id
            and ssgac.server_arch_id = s.server_arch_id
            and not exists (
                     select 1
                      from rhnServerGroupMembers sgm
                     where sgm.server_group_id = sg.id
                       and sgm.server_id = s.id);


   begin
      for servergroup in servergroups loop
         return servergroup.id;
      end loop;

      --no servergroup found
      return NULL;
   end$$
language plpgsql;

    -- *******************************************************************
    -- PROCEDURE: remove_org_entitlements
    --
    -- Removes both system entitlements and channel subscriptions
    -- that are currently assigned to an org and re-assigns to the
    -- master org (org_id = 1).
    --
    -- When we call this we expect everything to already be unentitled
    -- which shoul be handled by delete_org.
    --
    -- Called by: delete_org
    -- *******************************************************************
    create or replace function remove_org_entitlements (
        org_id_in numeric
    ) returns void
as $$
    declare
        system_ents cursor for
        select sg.id, sg.max_members, sg.group_type
        from rhnServerGroup sg
        where group_type is not null
          and org_id = org_id_in;

        channel_subs cursor for
        select pcf.channel_family_id, pcf.max_members
        from rhnChannelFamily cf,
             rhnPrivateChannelFamily pcf
        where pcf.org_id = org_id_in
          and pcf.channel_family_id = cf.id
          and cf.org_id is null;

    begin

        for system_ent in system_ents loop
            update rhnServerGroup
            set max_members = max_members + system_ent.max_members
            where org_id = 1
              and group_type = system_ent.group_type;
        end loop;

        update rhnServerGroup
        set max_members = 0
        where org_id = org_id_in;

        for channel_sub in channel_subs loop
            update rhnPrivateChannelFamily
            set max_members = max_members + channel_sub.max_members
            where org_id = 1
              and channel_family_id = channel_sub.channel_family_id;
        end loop;

        update rhnPrivateChannelFamily
        set max_members = 0
        where org_id = org_id_in;

    end$$
language plpgsql;

    create or replace function entitlement_grants_service (
        entitlement_in in varchar,
        service_level_in in varchar
    ) returns numeric
as $$
    begin
        if service_level_in = 'provisioning' then
            if entitlement_in = 'provisioning_entitled' then
                return 1;
            else
                return 0;
            end if;
        elsif service_level_in = 'management' then
            if entitlement_in = 'enterprise_entitled' then
                return 1;
            else
                return 0;
            end if;
        elsif service_level_in = 'monitoring' then
            if entitlement_in = 'monitoring_entitled' then
                return 1;
            end if;
        elsif service_level_in = 'updates' then
            return 1;
        else
            return 0;
        end if;
    end$$
language plpgsql;

    create or replace function lookup_entitlement_group (
        org_id_in in numeric,
        type_label_in in varchar default 'sw_mgr_entitled'
    ) returns numeric
as $$
    declare
        server_groups cursor for
            select  sg.id               server_group_id
            from    rhnServerGroup      sg,
                    rhnServerGroupType  sgt
            where   sgt.label = type_label_in
                and sgt.id = sg.group_type
                and sg.org_id = org_id_in;
    begin
        for sg in server_groups loop
            return sg.server_group_id;
        end loop;
        return rhn_entitlements.create_entitlement_group(
                org_id_in,
                type_label_in
            );
    end$$
language plpgsql;

    create or replace function create_entitlement_group (
        org_id_in in numeric,
        type_label_in in varchar default 'sw_mgr_entitled'
    ) returns numeric
as $$
    declare
        sg_id_val numeric;
    begin
        select  nextval('rhn_server_group_id_seq')
        into    sg_id_val;

        insert into rhnServerGroup (
                id, name, description, max_members, current_members,
                group_type, org_id
            ) (
                select  sg_id_val, sgt.label, sgt.label,
                        0, 0, sgt.id, org_id_in
                from    rhnServerGroupType sgt
                where   sgt.label = type_label_in
            );

        return sg_id_val;
    end$$
language plpgsql;

   create or replace function can_entitle_server (
      server_id_in   in numeric,
      type_label_in  in varchar
   )
   returns numeric
as $$
    declare
      addon_servergroups cursor (base_label_in varchar,
                                 addon_label_in varchar) for
         select
            addon_id
         from
            rhnSGTypeBaseAddonCompat
         where base_id = lookup_sg_type (base_label_in)
           and addon_id = lookup_sg_type (addon_label_in);

      previous_ent        varchar[];
      is_base_in          char   := 'N';
      is_base_current     char   := 'N';
      i                   numeric := 0;
      sgid                numeric := 0;

   begin

      previous_ent := rhn_entitlements.get_server_entitlement(server_id_in);

      select distinct is_base
      into is_base_in
      from rhnServerGroupType
      where label = type_label_in;

      if array_upper(previous_ent, 1) is null or array_upper(previous_ent, 1) = 0 then
         if is_base_in = 'Y' then
            sgid := rhn_entitlements.find_compatible_sg (server_id_in, type_label_in);
            if sgid is not null then
              -- rhn_server.insert_into_servergroup (server_id_in, sgid);
              return 1;
            else
              -- rhn_exception.raise_exception ('invalid_base_entitlement');
              return 0;
            end if;
         else
            -- rhn_exception.raise_exception ('invalid_base_entitlement');
            return 0;
         end if;

      -- there are previous ents, first make sure we're not trying to entitle a base ent
      elsif is_base_in = 'Y' then
         -- rhn_exception.raise_exception ('invalid_addon_entitlement');
         return 0;

      -- it must be an addon, so proceed with the entitlement
      else

         -- find the servers base ent
         is_base_current := 'N';
         i := 0;
         while is_base_current = 'N' and i < array_upper(previous_ent, 1)
         loop
            i := i + 1;
            select is_base
            into is_base_current
            from rhnServerGroupType
            where label = previous_ent[i];
         end loop;

         -- never found a base ent, that would be strange
         if is_base_current  = 'N' then
            -- rhn_exception.raise_exception ('invalid_base_entitlement');
            return 0;
         end if;

         -- this for loop verifies the validity of the addon path
         for addon_servergroup in addon_servergroups  (previous_ent[i], type_label_in) loop
            -- find an appropriate sgid for the addon and entitle the server
            sgid := rhn_entitlements.find_compatible_sg (server_id_in, type_label_in);
            if sgid is not null then
               -- rhn_server.insert_into_servergroup (server_id_in, sgid);
               return 1;
            else
               -- rhn_exception.raise_exception ('invalid_addon_entitlement');
               return 0;
            end if;
         end loop;

      end if;

      return 0;

   end$$
language plpgsql;

   create or replace function can_switch_base (
      server_id_in   in    integer,
      type_label_in  in    varchar
   )
   returns numeric
as $$
   declare
      type_label_in_is_base   char(1);
      sgid                    numeric;

   begin

       select is_base into type_label_in_is_base
       from rhnServerGroupType
       where label = type_label_in;

       if not found then
          perform rhn_exception.raise_exception ( 'invalid_entitlement' );
       end if;

      if type_label_in_is_base = 'N' then
         perform rhn_exception.raise_exception ( 'invalid_entitlement' );
      else
         sgid := rhn_entitlements.find_compatible_sg ( server_id_in,
                                                       type_label_in );
         if sgid is not null then
           return 1;
         else
           return 0;
         end if;
      end if;

   end$$
language plpgsql;

    create or replace function entitle_server (
        server_id_in in numeric,
        type_label_in in varchar default 'sw_mgr_entitled'
    ) returns void
as $$
    declare
      sgid  numeric := 0;
      is_virt numeric := 0;

    begin

      select 1 into is_virt
        from rhnServerEntitlementView
        where server_id = server_id_in
          and label in ('virtualization_host', 'virtualization_host_platform');

      if not found then
          is_virt := 0;
      end if;

      if is_virt = 0 and (type_label_in = 'virtualization_host' or
                          type_label_in = 'virtualization_host_platform') then

        is_virt := 1;
      end if;

      if rhn_entitlements.can_entitle_server(server_id_in,
                                             type_label_in) = 1 then
         sgid := rhn_entitlements.find_compatible_sg (server_id_in,
                                                      type_label_in);
         if sgid is not null then
            insert into rhnServerHistory ( id, server_id, summary, details )
            values ( nextval('rhn_event_id_seq'), server_id_in,
                     'added system entitlement ',
                      case type_label_in
                       when 'enterprise_entitled' then 'Management'
                       when 'sw_mgr_entitled' then 'Update'
                       when 'provisioning_entitled' then 'Provisioning'
                       when 'monitoring_entitled' then 'Monitoring'
                       when 'virtualization_host' then 'Virtualization'
                       when 'virtualization_host_platform' then
                            'Virtualization Platform' end  );

            perform rhn_server.insert_into_servergroup (server_id_in, sgid);

            if is_virt = 1 then
              perform rhn_entitlements.repoll_virt_guest_entitlements(server_id_in);
            end if;

         else
            perform rhn_exception.raise_exception ('no_available_server_group');
         end if;
      else
         perform rhn_exception.raise_exception ('invalid_entitlement');
      end if;
   end$$
language plpgsql;

    create or replace function remove_server_entitlement (
        server_id_in in numeric,
        type_label_in in varchar default 'sw_mgr_entitled',
        repoll_virt_guests in numeric default 1
    ) returns void
as $$
    declare
      group_id numeric;
      type_is_base char;
      is_virt numeric := 0;
    begin
      -- would be nice if there were a virt attribute of entitlement types, not have to specify 2 different ones...
        select 1 into is_virt
          from rhnServerEntitlementView
          where server_id = server_id_in
            and label in ('virtualization_host', 'virtualization_host_platform');
        if not found then
            is_virt := 0;
        end if;

        select  sg.id, sgt.is_base
        into group_id, type_is_base
        from    rhnServerGroupType sgt,
            rhnServerGroup sg,
                rhnServerGroupMembers sgm,
                rhnServer s
        where   s.id = server_id_in
            and s.id = sgm.server_id
            and sgm.server_group_id = sg.id
            and sg.org_id = s.org_id
            and sgt.label = type_label_in
            and sgt.id = sg.group_type;

        if not found then
          perform rhn_exception.raise_exception('invalid_server_group_member');
        end if;

      if ( type_is_base = 'Y' ) then
         -- unentitle_server should handle everything, don't really need to do anything else special here
         perform rhn_entitlements.unentitle_server ( server_id_in );
      else

         insert into rhnServerHistory ( id, server_id, summary, details )
         values ( nextval('rhn_event_id_seq'), server_id_in,
                  'removed system entitlement ',
                   case type_label_in
                    when 'enterprise_entitled' then 'Management'
                    when 'sw_mgr_entitled' then 'Update'
                    when 'provisioning_entitled' then 'Provisioning'
                    when 'monitoring_entitled' then 'Monitoring'
                    when 'virtualization_host' then 'Virtualization'
                    when 'virtualization_host_platform' then
                         'Virtualization Platforrm' end  );

         perform rhn_server.delete_from_servergroup(server_id_in, group_id);

         if type_label_in = 'monitoring_entitled' then
           DELETE
             FROM rhn_probe
            WHERE recid IN (SELECT probe_id
                              FROM rhn_check_probe
                             WHERE host_id = server_id_in);
         end if;

         if is_virt = 1 and repoll_virt_guests = 1 then
           perform rhn_entitlements.repoll_virt_guest_entitlements(server_id_in);
         end if;
      end if;

    end$$
language plpgsql;

    create or replace function unentitle_server (
        server_id_in in numeric
    ) returns void
as $$
    declare
      servergroups cursor for
         select distinct sgt.label, sg.id server_group_id
         from  rhnServerGroupType sgt,
               rhnServerGroup sg,
               rhnServer s,
               rhnServerGroupMembers sgm
         where s.id = server_id_in
            and s.org_id = sg.org_id
            and sg.group_type = sgt.id
            and sgm.server_group_id = sg.id
            and sgm.server_id = s.id;

     is_virt numeric := 0;

   begin

      select 1 into is_virt
        from rhnServerEntitlementView
        where server_id = server_id_in
         and label in ('virtualization_host', 'virtualization_host_platform');

      if not found then
          is_virt := 0;
      end if;

      for servergroup in servergroups loop

         insert into rhnServerHistory ( id, server_id, summary, details )
         values ( nextval('rhn_event_id_seq'), server_id_in,
                  'removed system entitlement ',
                   case servergroup.label
                    when 'enterprise_entitled' then 'Management'
                    when 'sw_mgr_entitled' then 'Update'
                    when 'provisioning_entitled' then 'Provisioning'
                    when 'monitoring_entitled' then 'Monitoring'
                    when 'virtualization_host' then 'Virtualization'
                    when 'virtualization_host_platform' then
                         'Virtualization Platform' end  );

         perform rhn_server.delete_from_servergroup(server_id_in,
                                            servergroup.server_group_id );
      end loop;

      if is_virt = 1 then
        perform rhn_entitlements.repoll_virt_guest_entitlements(server_id_in);
      end if;

   end$$
language plpgsql;


    -- *******************************************************************
    -- PROCEDURE: repoll_virt_guest_entitlements
    --
    --   Whenever we add/remove a virtualization_host* entitlement from
    --   a host, we can call this procedure to update what type of slots
    --   the guests are consuming.
    --
    --   If you're removing the entitlement, it's
    --   possible the guests will become unentitled if you don't have enough
    --   physical slots to cover them.
    --
    --   If you're adding the entitlement, you end up freeing up physical
    --   slots for other systems.
    --
    -- *******************************************************************
    create or replace function repoll_virt_guest_entitlements(
        server_id_in in numeric
    ) returns void
as $$
    declare
        -- All channel families associated with the guests of server_id_in
        families cursor for
            select distinct cfs.channel_family_id
            from
                rhnChannelFamilyServers cfs,
                rhnVirtualInstance vi
            where
                vi.host_system_id = server_id_in
                and vi.virtual_system_id = cfs.server_id;

        -- All of server group types associated with the guests of
        -- server_id_in
        group_types cursor for
            select distinct sg.group_type, sgt.label
            from
                rhnServerGroupType sgt,
                rhnServerGroup sg,
                rhnServerGroupMembers sgm,
                rhnVirtualInstance vi
            where
                vi.host_system_id = server_id_in
                and vi.virtual_system_id = sgm.server_id
                and sgm.server_group_id = sg.id
                and sg.group_type = sgt.id;

        -- Virtual servers from a certain family belonging to a specific
        -- host that are consuming physical channel slots over the limit.
        virt_servers_cfam cursor(family_id_in numeric, quantity_in numeric) for
                select vi.virtual_system_id
                from
                    rhnChannelFamilyMembers cfm,
                    rhnServerChannel sc,
                    rhnVirtualInstance vi
                where
                    vi.host_system_id = server_id_in
                    and vi.virtual_system_id = sc.server_id
                    and sc.channel_id = cfm.channel_id
                    and cfm.channel_family_id = family_id_in
                order by sc.modified desc
                limit quantity_in;

        -- Virtual servers from a certain family belonging to a specific
        -- host that are consuming physical system slots over the limit.
        virt_servers_sgt cursor(group_type_in numeric, quantity_in numeric) for
                select vi.virtual_system_id
                from
                    rhnServerGroup sg,
                    rhnServerGroupMembers sgm,
                    rhnVirtualInstance vi
                where
                    vi.host_system_id = server_id_in
                    and vi.virtual_system_id = sgm.server_id
                    and sgm.server_group_id = sg.id
                    and sg.group_type = group_type_in
                order by sgm.modified desc
                limit quantity_in;

        -- Get the orgs of Virtual guests
        -- Since they may belong to different orgs
        virt_guest_orgs cursor for
                select  distinct (s.org_id)
                from rhnServer s
                    inner join  rhnVirtualInstance vi on vi.virtual_system_id = s.id
                where
                    vi.host_system_id = server_id_in
                    and s.org_id <> (select s1.org_id from rhnServer s1 where s1.id = vi.host_system_id) ;

        org_id_val numeric;
        max_members_val numeric;
        max_flex_val numeric;
        current_members_calc numeric;
        sg_id numeric;
        is_virt numeric := 0;
        free_slots numeric := 0;
    begin
          select 1 into is_virt
                from rhnServerEntitlementView
           where server_id = server_id_in
                 and label in ('virtualization_host', 'virtualization_host_platform');

      if not found then
          is_virt := 0;
      end if;

        select org_id
        into org_id_val
        from rhnServer
        where id = server_id_in;

        -- deal w/ channel entitlements first ...
        for family in families loop
            if is_virt = 0 then
            -- if the host_server does not have virt
            --- find all possible flex slots
            -- and set each of the flex eligible guests to Y
                select sfc.max_members - sfc.current_members
                  into free_slots
                  from rhnServerFveCapable sfc
                 where sfc.channel_family_id = family.channel_family_id;
                UPDATE rhnServerChannel sc set is_fve = 'Y'
                where sc.server_id in (
                            select vi.virtual_system_id
                            from rhnServerFveCapable sfc
                                inner join rhnVirtualInstance vi on vi.virtual_system_id = sfc.server_id
                            where vi.host_system_id = server_id_in
                                  and sfc.channel_family_id = family.channel_family_id
                              order by vi.modified desc
                            limit free_slots
                );
            else
            -- if the host_server has virt
            -- set all its flex guests to N
                UPDATE rhnServerChannel sc set is_fve = 'N'
                where
                    sc.channel_id in (select cfm.channel_id from rhnChannelFamilyMembers cfm
                                      where cfm.CHANNEL_FAMILY_ID = family.channel_family_id)
                    and sc.is_fve = 'Y'
                    and sc.server_id in
                            (select vi.virtual_system_id  from rhnVirtualInstance vi
                                    where vi.host_system_id = server_id_in);
            end if;

            -- get the current (physical) members of the family
            current_members_calc :=
                rhn_channel.channel_family_current_members(family.channel_family_id,
                                                           org_id_val); -- fixed transposed args

            -- get the max members of the family
            select max_members
            into max_members_val
            from rhnPrivateChannelFamily
            where channel_family_id = family.channel_family_id
            and org_id = org_id_val;

            select fve_max_members
            into max_flex_val
            from rhnPrivateChannelFamily
            where channel_family_id = family.channel_family_id
            and org_id = org_id_val;

            if current_members_calc > max_members_val then
                -- A virtualization_host* ent must have been removed, so we'll
                -- unsubscribe guests from the host first.

                -- hm, i don't think max_members - current_members_calc yielding a negative number
                -- will work w/ rownum, swaping 'em in the body of this if...
                for virt_server in virt_servers_cfam(family.channel_family_id,
                                current_members_calc - max_members_val) loop

                    perform rhn_channel.unsubscribe_server_from_family(
                                virt_server.virtual_system_id,
                                family.channel_family_id);
                end loop;

                -- if we're still over the limit, which would be odd,
                -- just prune the group to max_members
                --
                -- er... wouldn't we actually have to refresh the values of
                -- current_members_calc and max_members_val to actually ever
                -- *skip this??
                if current_members_calc > max_members_val then
                    -- argh, transposed again?!
                    perform rhn_entitlements.set_family_count(org_id_val,
                                     family.channel_family_id,
                                     max_members_val, max_flex_val);
                    --TODO calculate this correctly
                end if;

           end if;

            -- update current_members for the family.  This will set the value
            -- to reflect adding/removing the entitlement.
            --
            -- what's the difference of doing this vs the unavoidable set_family_count above?
            perform rhn_channel.update_family_counts(family.channel_family_id,
                                             org_id_val);

            -- It is possible that the guests belong  to a different org than the host
            -- so we are going to update the family counts in the guests orgs also
            for org in virt_guest_orgs loop
                    perform rhn_channel.update_family_counts(family.channel_family_id,
                                             org.org_id);
            end loop;
        end loop;

        for a_group_type in group_types loop
          -- get the current *physical* members of the system entitlement type for the org...
          --
          -- unlike channel families, it appears the standard rhnServerGroup.max_members represents
          -- *physical* slots, vs physical+virt ... boy that's confusing...

          select max_members, id
            into max_members_val, sg_id
            from rhnServerGroup
            where group_type = a_group_type.group_type
            and org_id = org_id_val;


      select count(sep.server_id) into current_members_calc
            from rhnServerEntitlementPhysical sep
           where sep.server_group_id = sg_id
             and sep.server_group_type_id = a_group_type.group_type;

          if current_members_calc > max_members_val then
            -- A virtualization_host* ent must have been removed, and we're over the limit, so unsubscribe guests
            for virt_server in virt_servers_sgt(a_group_type.group_type,
                                                current_members_calc - max_members_val) loop
              perform rhn_entitlements.remove_server_entitlement(virt_server.virtual_system_id, a_group_type.label);

              -- decrement current_members_calc, we'll use it to reset current_members for the group at the end...
              current_members_calc := current_members_calc - 1;
            end loop;

          end if;

          update rhnServerGroup set current_members = current_members_calc
           where org_id = org_id_val
             and group_type = a_group_type.group_type;

          -- I think that's all the house-keeping we have to do...
        end loop;

    end$$
language plpgsql;

    create or replace function get_server_entitlement (
        server_id_in in numeric
    ) returns varchar[]
as $$
    declare
        server_groups cursor for
            select  sgt.label
            from    rhnServerGroupType      sgt,
                    rhnServerGroup          sg,
                    rhnServerGroupMembers   sgm
            where   1=1
                and sgm.server_id = server_id_in
                and sg.id = sgm.server_group_id
                and sgt.id = sg.group_type
                and sgt.label in (
                    'sw_mgr_entitled','enterprise_entitled',
                    'provisioning_entitled', 'nonlinux_entitled',
                    'monitoring_entitled', 'virtualization_host',
                                        'virtualization_host_platform'
                    );

         ent_array varchar[];

    begin

      ent_array := '{}';

      for sg in server_groups loop
         ent_array := ent_array || sg.label;
      end loop;

      return ent_array;

    end$$
language plpgsql;

    -- this desperately needs to be table driven.
    create or replace function modify_org_service (
        org_id_in in numeric,
        service_label_in in varchar,
        enable_in in char
    ) returns void
as $$
    declare
        roles_to_process varchar[];
        roles cursor(role_label_in varchar) for
            select  label, id
            from    rhnUserGroupType
            where   label = role_label_in;
        org_roles cursor(role_label_in varchar) for
            select  1
            from    rhnUserGroup ug,
                    rhnUserGroupType ugt
            where   ugt.label = role_label_in
                and ug.org_id = org_id_in
                and ugt.id = ug.group_type;

        ents_to_process varchar[];
        ents cursor(ent_label_in varchar) for
            select  label, id
            from    rhnOrgEntitlementType
            where   label = ent_label_in;
        org_ents cursor(ent_label_in varchar) for
            select  1
            from    rhnOrgEntitlements oe,
                    rhnOrgEntitlementType oet
            where   oet.label = ent_label_in
                and oe.org_id = org_id_in
                and oet.id = oe.entitlement_id;
        create_row char(1);
    begin
        ents_to_process := '{}';
        roles_to_process := '{}';
        -- a bit kludgy, but only for 3.4 really.  Certainly no
        -- worse than the old code...
        if service_label_in = 'enterprise' or
           service_label_in = 'management' then
            ents_to_process := array_append(ents_to_process, 'sw_mgr_enterprise');

            roles_to_process := array_append(roles_to_process, 'org_admin');

            roles_to_process := array_append(roles_to_process, 'system_group_admin');

            roles_to_process := array_append(roles_to_process, 'activation_key_admin');
        elsif service_label_in = 'provisioning' then
            ents_to_process := array_append(ents_to_process, 'rhn_provisioning');

            roles_to_process := array_append(roles_to_process, 'system_group_admin');

            roles_to_process := array_append(roles_to_process, 'activation_key_admin');

            roles_to_process := array_append(roles_to_process, 'config_admin');
            -- another nasty special case...
            if enable_in = 'Y' then
                ents_to_process := array_append(ents_to_process, 'sw_mgr_enterprise');
            end if;
        elsif service_label_in = 'monitoring' then
            ents_to_process := array_append(ents_to_process, 'rhn_monitor');

            roles_to_process := array_append(roles_to_process, 'monitoring_admin');
        elsif service_label_in = 'virtualization' then
            ents_to_process := array_append(ents_to_process, 'rhn_virtualization');

            roles_to_process := array_append(roles_to_process, 'config_admin');
        elsif service_label_in = 'virtualization_platform' then
            ents_to_process := array_append(ents_to_process, 'rhn_virtualization_platform');
            roles_to_process := array_append(roles_to_process, 'config_admin');
    elsif service_label_in = 'nonlinux' then
            ents_to_process := array_append(ents_to_process, 'rhn_nonlinux');
            roles_to_process := array_append(roles_to_process, 'config_admin');
        end if;

        if enable_in = 'Y' then
            for i in 1..array_upper(ents_to_process, 1) loop
                for ent in ents(ents_to_process[i]) loop
                    create_row := 'Y';
                    for oe in org_ents(ent.label) loop
                        create_row := 'N';
                    end loop;
                    if create_row = 'Y' then
                        insert into rhnOrgEntitlements(org_id, entitlement_id)
                            values (org_id_in, ent.id);
                    end if;
                end loop;
            end loop;
            for i in 1..array_upper(roles_to_process, 1) loop
                for role in roles(roles_to_process[i]) loop
                    create_row := 'Y';
                    for o_r in org_roles(role.label) loop
                        create_row := 'N';
                    end loop;
                    if create_row = 'Y' then
                        insert into rhnUserGroup(
                                id, name, description, current_members,
                                group_type, org_id
                            ) (
                                select  nextval('rhn_user_group_id_seq'),
                                        ugt.name || 's',
                                        ugt.name || 's for Org ' ||
                                            o.name || ' ('|| o.id ||')',
                                        0, ugt.id, o.id
                                from    rhnUserGroupType ugt,
                                        web_customer o
                                where   o.id = org_id_in
                                    and ugt.id = role.id
                            );
                    end if;
                end loop;
            end loop;
        else
            for i in 1..coalesce(array_upper(ents_to_process, 1), 0) loop
                for ent in ents(ents_to_process[i]) loop
                    delete from rhnOrgEntitlements
                     where org_id = org_id_in
                       and entitlement_id = ent.id;
                end loop;
            end loop;
        end if;
    end$$
language plpgsql;

    create or replace function set_customer_enterprise (
        customer_id_in in numeric
    ) returns void
as $$
    begin
        perform rhn_entitlements.modify_org_service(customer_id_in, 'enterprise', 'Y');
    end$$
language plpgsql;

    create or replace function set_customer_provisioning (
        customer_id_in in numeric
    ) returns void
as $$
    begin
        perform rhn_entitlements.modify_org_service(customer_id_in, 'provisioning', 'Y');
    end$$
language plpgsql;

    create or replace function set_customer_monitoring (
        customer_id_in in numeric
    ) returns void
as $$
    begin
        perform rhn_entitlements.modify_org_service(customer_id_in, 'monitoring', 'Y');
    end$$
language plpgsql;

    create or replace function set_customer_nonlinux (
        customer_id_in in numeric
    ) returns void
as $$
    begin
        perform rhn_entitlements.modify_org_service(customer_id_in, 'nonlinux', 'Y');
    end$$
language plpgsql;

    create or replace function unset_customer_enterprise (
        customer_id_in in numeric
    ) returns void
as $$
    begin
        perform rhn_entitlements.modify_org_service(customer_id_in, 'enterprise', 'N');
    end$$
language plpgsql;

    create or replace function unset_customer_provisioning (
        customer_id_in in numeric
    ) returns void
as $$
    begin
        perform rhn_entitlements.modify_org_service(customer_id_in, 'provisioning', 'N');
    end$$
language plpgsql;

    create or replace function unset_customer_monitoring (
        customer_id_in in numeric
    ) returns void
as $$
    begin
        perform rhn_entitlements.modify_org_service(customer_id_in, 'monitoring', 'N');
    end$$
language plpgsql;

    create or replace function unset_customer_nonlinux (
        customer_id_in in numeric
    ) returns void
as $$
    begin
        perform rhn_entitlements.modify_org_service(customer_id_in, 'nonlinux', 'N');
    end$$
language plpgsql;

    -- *******************************************************************
    -- PROCEDURE: prune_group
    -- Unsubscribes servers consuming physical slots that over the org's
    --   limit.
    -- Called by: set_server_group_count, repoll_virt_guest_entitlements
    -- *******************************************************************
    create or replace function prune_group (
        group_id_in in numeric,
        quantity_in in numeric,
        update_family_countsYN in numeric default 1
    ) returns void
as $$
    declare
        sgrecord record;
      type_is_base char;
    begin
            update      rhnServerGroup
                set     max_members = quantity_in
                where   id = group_id_in;

            for sgrecord in (
		   select  server_id, server_group_id, sgt.id as group_type_id, sgt.label
		    from    rhnServerGroupType              sgt,
				    rhnServerGroup                  sg,
				    rhnServerGroupMembers   sgm
		    where   1=1
			    and sgm.server_group_id = group_id_in
			    and sgm.server_id in (
				    select  sep.server_id
				    from
					rhnServerEntitlementPhysical sep
				    where
					sep.server_group_id = group_id_in
				    order by sep.modified asc
				    offset quantity_in
				)
			    and sgm.server_group_id = sg.id
			    and sg.group_type = sgt.id
	    ) loop
                perform rhn_entitlements.remove_server_entitlement(sgrecord.server_id, sgrecord.label);

            select is_base
            into type_is_base
            from rhnServerGroupType sgt
            where sgt.id = sgrecord.group_type_id;

            -- if we're removing a base ent, then be sure to
            -- remove the server's channel subscriptions.
            if ( type_is_base = 'Y' ) then
                   perform rhn_channel.clear_subscriptions(sgrecord.server_id, 0, update_family_countsYN);
            end if;

            end loop;
    end$$
language plpgsql;

    -- *******************************************************************
    -- PROCEDURE: assign_system_entitlement
    --
    -- Moves system entitlements from from_org_id_in to to_org_id_in.
    -- Can raise not_enough_entitlements_in_base_org if from_org_id_in
    -- does not have enough entitlements to cover the move.
    -- Takes care of unentitling systems if necessary by calling
    -- set_server_group_count
    -- *******************************************************************
    create or replace function assign_system_entitlement(
        group_label_in in varchar,
        from_org_id_in in numeric,
        to_org_id_in in numeric,
        quantity_in in numeric
    ) returns void
as $$
    declare
        prev_ent_count numeric;
    to_org_prev_ent_count numeric;
        new_ent_count numeric;
    new_quantity numeric;
        group_type numeric;
    begin

            select max_members
            into prev_ent_count
            from rhnServerGroupType sgt,
                 rhnServerGroup sg
            where sg.org_id = from_org_id_in
              and sg.group_type = sgt.id
              and sgt.label = group_label_in;

            if not found then
                perform rhn_exception.raise_exception(
                              'not_enough_entitlements_in_base_org');
            end if;

            select max_members
            into to_org_prev_ent_count
            from rhnServerGroupType sgt,
                 rhnServerGroup sg
            where sg.org_id = to_org_id_in
              and sg.group_type = sgt.id
              and sgt.label = group_label_in;

            if not found then
                to_org_prev_ent_count := 0;
            end if;

            select id
            into group_type
            from rhnServerGroupType
            where label = group_label_in;

            if not found then
                perform rhn_exception.raise_exception(
                              'invalid_server_group');
            end if;

        new_ent_count := prev_ent_count - quantity_in;

        if prev_ent_count > new_ent_count then
            new_quantity := to_org_prev_ent_count + quantity_in;
        end if;

        if new_ent_count < 0 then
            perform rhn_exception.raise_exception(
                          'not_enough_entitlements_in_base_org');
        end if;


        perform rhn_entitlements.set_server_group_count(from_org_id_in,
                                         group_type,
                                         new_ent_count);

        perform rhn_entitlements.set_server_group_count(to_org_id_in,
                                         group_type,
                                         new_quantity);

        -- Create or delete the entries in rhnOrgEntitlementType
        if group_label_in = 'enterprise_entitled' then
            if new_quantity > 0 then
                perform rhn_entitlements.set_customer_enterprise(to_org_id_in);
            else
                perform rhn_entitlements.unset_customer_enterprise(to_org_id_in);
            end if;
        end if;

        if group_label_in = 'provisioning_entitled' then
            if new_quantity > 0 then
                perform rhn_entitlements.set_customer_provisioning(to_org_id_in);
            else
                perform rhn_entitlements.unset_customer_provisioning(to_org_id_in);
            end if;
        end if;

        if group_label_in = 'monitoring_entitled' then
            if new_quantity > 0 then
                perform rhn_entitlements.set_customer_monitoring(to_org_id_in);
            else
                perform rhn_entitlements.unset_customer_monitoring(to_org_id_in);
            end if;
        end if;

    end$$
language plpgsql;

    -- *******************************************************************
    -- PROCEDURE: assign_channel_entitlement
    --
    -- Moves channel entitlements from from_org_id_in to to_org_id_in.
    -- Can raise not_enough_entitlements_in_base_org if from_org_id_in
    -- does not have enough entitlements to cover the move.
    -- Takes care of unentitling systems if necessary by calling
    -- set_family_count
    -- *******************************************************************
    create or replace function assign_channel_entitlement(
        channel_family_label_in in varchar,
        from_org_id_in in numeric,
        to_org_id_in in numeric,
        quantity_in in numeric,
        flex_in in numeric
    ) returns void
as $$
    declare
        from_org_prev_ent_count numeric;
        from_org_prev_ent_count_flex numeric;
        new_ent_count numeric;
        new_ent_count_flex numeric;
        to_org_prev_ent_count numeric;
        to_org_prev_ent_count_flex numeric;
        new_quantity numeric;
        new_flex numeric;
        cfam_id       numeric;
    begin

            select max_members
            into from_org_prev_ent_count
            from rhnChannelFamily cf,
                 rhnPrivateChannelFamily pcf
            where pcf.org_id = from_org_id_in
              and pcf.channel_family_id = cf.id
              and cf.label = channel_family_label_in;

            if not found then
                perform rhn_exception.raise_exception(
                              'not_enough_entitlements_in_base_org');
            end if;

            select max_members
            into to_org_prev_ent_count
            from rhnChannelFamily cf,
                 rhnPrivateChannelFamily pcf
            where pcf.org_id = to_org_id_in
              and pcf.channel_family_id = cf.id
              and cf.label = channel_family_label_in;

            if not found then
                to_org_prev_ent_count := 0;
            end if;

            select fve_max_members
            into from_org_prev_ent_count_flex
            from rhnChannelFamily cf,
                rhnPrivateChannelFamily pcf
            where pcf.org_id = from_org_id_in
              and pcf.channel_family_id = cf.id
              and cf.label = channel_family_label_in;

            if not found then
                perform rhn_exception.raise_exception(
                              'not_enough_flex_entitlements_in_base_org');
            end if;

            select fve_max_members
            into to_org_prev_ent_count_flex
            from rhnChannelFamily cf,
                 rhnPrivateChannelFamily pcf
            where pcf.org_id = to_org_id_in
              and pcf.channel_family_id = cf.id
              and cf.label = channel_family_label_in;

            if not found then
                to_org_prev_ent_count_flex := 0;
            end if;

            select id
            into cfam_id
            from rhnChannelFamily
            where label = channel_family_label_in;

            if not found then
                perform rhn_exception.raise_exception(
                              'invalid_channel_family');
            end if;

        new_ent_count := from_org_prev_ent_count - quantity_in;
        new_ent_count_flex := from_org_prev_ent_count_flex - flex_in;

        if from_org_prev_ent_count >= new_ent_count then
            new_quantity := to_org_prev_ent_count + quantity_in;
        end if;

        if from_org_prev_ent_count_flex >= new_ent_count_flex then
            new_flex := to_org_prev_ent_count_flex + flex_in;
        end if;

        if new_ent_count < 0 then
            perform rhn_exception.raise_exception(
                          'not_enough_entitlements_in_base_org');
        end if;

        if new_ent_count_flex < 0 then
            perform rhn_exception.raise_exception(
                          'not_enough_flex_entitlements_in_base_org');
        end if;



        perform rhn_entitlements.set_family_count(from_org_id_in,
                                          cfam_id,
                                          new_ent_count,
                                          new_ent_count_flex);

        perform rhn_entitlements.set_family_count(to_org_id_in,
                                          cfam_id,
                                          new_quantity,
                                          new_flex);

    end$$
language plpgsql;

    -- *******************************************************************
    -- PROCEDURE: activate_system_entitlement
    --
    -- Sets the values in rhnServerGroup for a given rhnServerGroupType.
    --
    -- Calls: set_server_group_count to update, prune, or create the group.
    -- Called by: the code that activates a satellite cert.
    --
    -- Raises not_enough_entitlements_in_base_org if all entitlements
    -- in the org are used so the free entitlements would not cover
    -- the difference when descreasing the number of entitlements.
    -- *******************************************************************
    create or replace function activate_system_entitlement(
        org_id_in in numeric,
        group_label_in in varchar,
        quantity_in in numeric
    ) returns void
as $$
    declare
        prev_ent_count numeric;
        prev_ent_count_sum numeric;
        group_type numeric;
    begin

        -- Fetch the current entitlement count for the org
        -- into prev_ent_count

            select current_members
            into prev_ent_count
            from rhnServerGroupType sgt,
                 rhnServerGroup sg
            where sg.group_type = sgt.id
              and sgt.label = group_label_in
              and sg.org_id = org_id_in;

            if not found then
                prev_ent_count := 0;
            end if;

            select id
            into group_type
            from rhnServerGroupType
            where label = group_label_in;

            if not found then
                perform rhn_exception.raise_exception(
                              'invalid_server_group');
            end if;

        -- If we're setting the total entitlemnt count to a lower value,
        -- and that value is less than the allocated count in this org,
        -- we need to raise an exception.
        if quantity_in < prev_ent_count then
            perform rhn_exception.raise_exception(
                          'not_enough_entitlements_in_base_org');
        else
            -- don't update family counts after every server
            -- will do bulk update afterwards
            perform rhn_entitlements.set_server_group_count(org_id_in,
                                             group_type,
                                             quantity_in,
                                             0);
            -- bulk update family counts
            perform rhn_channel.update_group_family_counts(group_label_in, org_id_in);
        end if;

    end$$
language plpgsql;

    -- *******************************************************************
    -- PROCEDURE: activate_channel_entitlement
    --
    -- Calls: set_family_count to update, prune, or create the family
    --        permission bucket.
    -- Called by: the code that activates a satellite cert.
    --
    -- Raises not_enough_entitlements_in_base_org if there are not enough
    -- entitlements in the org to cover the difference when you are
    -- descreasing the number of entitlements.
    --
    -- The backend code in Python is expected to do whatever arithmetics
    -- is needed.
    -- *******************************************************************
    create or replace function activate_channel_entitlement(
        org_id_in in numeric,
        channel_family_label_in in varchar,
        quantity_in in numeric,
        flex_in in numeric
    ) returns void
as $$
    declare
        prev_ent_count numeric;
        prev_flex_count numeric;
        prev_ent_count_sum numeric;
        cfam_id numeric;
        reduce_quantity numeric;
        total_flex_capable numeric;
        to_convert_reg cursor (channel_family_id_val numeric, org_id_in numeric, quantity numeric) for
                     select SC.server_id
                     from rhnServerChannel SC inner join
                          rhnServer S on S.id = SC.server_id
                     where
                         is_fve = 'Y'
                         and S.org_id = org_id_in
                         and SC.channel_id in
                         (select cfm.channel_id from rhnChannelFamilyMembers cfm
                             where cfm.CHANNEL_FAMILY_ID = channel_family_id_val)
                         limit quantity;
         to_convert_flex cursor (channel_family_id_val numeric, org_id_in numeric, quantity numeric) for
                   select server_id
                   from rhnServerFveCapable
                       where SERVER_ORG_ID = org_id_in and
                             channel_family_id = cfam_id
                       limit quantity;

    begin

        -- Fetch the current entitlement count for the org
        -- into prev_ent_count
            select current_members
            into prev_ent_count
            from rhnChannelFamily cf,
                 rhnPrivateChannelFamily pcf
            where pcf.org_id = org_id_in
              and pcf.channel_family_id = cf.id
              and cf.label = channel_family_label_in;

            if not found then
                prev_ent_count := 0;
            end if;

            select pcf.fve_current_members
            into prev_flex_count
            from rhnChannelFamily cf,
                 rhnPrivateChannelFamily pcf
            where pcf.org_id = org_id_in
              and pcf.channel_family_id = cf.id
              and cf.label = channel_family_label_in;

            if not found then
                prev_flex_count := 0;
            end if;

            select id
            into cfam_id
            from rhnChannelFamily
            where label = channel_family_label_in;

            if not found then
                perform rhn_exception.raise_exception(
                              'invalid_channel_family');
            end if;

        -- if there are too few flex entitlements
        if flex_in < prev_flex_count then
            -- and if the extra we need is less than or equal to our extra regular entitlements
            if prev_flex_count - flex_in <= quantity_in - prev_ent_count then
                   reduce_quantity := prev_flex_count - flex_in;
                   -- We need to convert some systems from flex guest to regular
                   for system in to_convert_reg(cfam_id, org_id_in, reduce_quantity) loop
                      --rhn_channel.convert_to_regular(system.server_id, cfam_id);
                      UPDATE rhnServerChannel sc set is_fve = 'N'
                           where sc.server_id = system.server_id
                                 and sc.channel_id in (select cfm.channel_id
                                                          from rhnChannelFamilyMembers cfm
                                                          where cfm.channel_family_id = cfam_id);
                   end loop;

                   --reset previous counts
                   prev_ent_count := prev_ent_count + reduce_quantity;
                   prev_flex_count := prev_flex_count - reduce_quantity;
            else
                perform rhn_exception.raise_exception(
                          'not_enough_flex_entitlements_in_base_org');
            end if;
        end if;

        -- if there are too few regular entitlements, and extra flex entitlements
        if quantity_in < prev_ent_count and prev_flex_count < flex_in then
                -- how many flex-capable systems (that aren't using flex) do we have
                select count(*)
                   into total_flex_capable
                   from rhnServerFveCapable
                       where SERVER_ORG_ID = org_id_in and
                             channel_family_id = cfam_id;
                -- if we have enough flex capable machines that is at least
                --   as many as what we are over on
                if total_flex_capable >= prev_ent_count - quantity_in then
                    reduce_quantity := prev_ent_count - quantity_in;
                    for system in to_convert_flex(cfam_id, org_id_in, reduce_quantity) loop
--                          rhn_channel.convert_to_fve(system.server_id, cfam_id);
                        UPDATE rhnServerChannel sc set is_fve = 'Y'
                           where sc.server_id = system.server_id
                                 and sc.channel_id in (select cfm.channel_id
                                                          from rhnChannelFamilyMembers cfm
                                                          where cfm.channel_family_id = cfam_id);
                    end loop;
                    prev_ent_count := prev_ent_count - reduce_quantity;
                    prev_flex_count := prev_flex_count + reduce_quantity;
                end if;
        end if;

        -- If we're setting the total entitlemnt count to a lower value,
        -- and that value is less than the count in that one org,
        -- we need to raise an exception.
        if quantity_in < prev_ent_count then
            perform rhn_exception.raise_exception(
                          'not_enough_entitlements_in_base_org');
        else
            -- even if we've manually converted systems to/from flex above
            -- set_family_count should call update_family_counts, to reset
            -- current used slots
            perform rhn_entitlements.set_family_count(org_id_in, cfam_id,
                                              quantity_in, flex_in);
        end if;

    end$$
language plpgsql;

    create or replace function set_server_group_count (
        customer_id_in in numeric,  -- customer_id
        group_type_in in numeric,   -- rhn[User|Server]GroupType.id
        quantity_in in numeric,      -- quantity
                update_family_countsYN in numeric default 1
    ) returns void
as $$
    declare
        group_id numeric;
        quantity numeric;
        wasfound boolean;
    begin
        quantity := quantity_in;
        if quantity is not null and quantity < 0 then
            quantity := 0;
        end if;

        select  rsg.id
        into    group_id
        from    rhnServerGroup rsg
        where   1=1
            and rsg.org_id = customer_id_in
            and rsg.group_type = group_type_in;

        -- preserve the not found status across the rhn_entitlements.prune_group invocation
        wasfound := true;
        if not found then
            wasfound := false;
        end if;

        perform rhn_entitlements.prune_group(
            group_id,
            quantity,
                        update_family_countsYN
        );

        if not wasfound then
            insert into rhnServerGroup (
                    id, name, description, max_members, current_members,
                    group_type, org_id, created, modified
                ) (
                    select  nextval('rhn_server_group_id_seq'), name, name,
                            quantity, 0, id, customer_id_in,
                            current_timestamp, current_timestamp
                    from    rhnServerGroupType
                    where   id = group_type_in
            );
        end if;

    end$$
language plpgsql;

    -- *******************************************************************
    -- PROCEDURE: prune_family
    -- Unsubscribes servers consuming physical slots from the channel family
    --   that are over the org's limit.
    -- Called by: set_family_count
    -- *******************************************************************
    create or replace function prune_family (
        customer_id_in in numeric,
        channel_family_id_in in numeric,
        quantity_in in numeric,
        flex_in in numeric
    ) returns void
as $$
    declare
        serverchannels cursor(tmp_quantity numeric, is_fve_in char) for
            select  sc.server_id,
                    sc.channel_id
            from    rhnServerChannel sc,
                    rhnChannelFamilyMembers cfm
            where   1=1
                and cfm.channel_family_id = channel_family_id_in
                and cfm.channel_id = sc.channel_id
                and server_id in (
                            select  rs.id as server_id
                            from
                                    rhnServerChannel        rsc,
                                    rhnChannelFamilyMembers rcfm,
                                    rhnServer               rs
                            where   1=1
                                and rs.org_id = customer_id_in
                                and rs.id = rsc.server_id
                                and rsc.channel_id = rcfm.channel_id
                                and rcfm.channel_family_id =  channel_family_id_in
                                and rsc.is_fve = is_fve_in
                                -- we only want to grab servers consuming
                                -- physical slots.
                                and exists (
                                    select 1
                                    from rhnChannelFamilyServerPhysical cfsp
                                    where cfsp.server_id = rs.id
                                    and cfsp.channel_family_id =
                                        channel_family_id_in
                                    )
                            order by rcfm.modified asc
                            offset quantity_in
                        );
    begin
        -- if we get a null customer_id, this is completely bogus.
        if customer_id_in is null then
            return;
        end if;

        for sc in serverchannels(quantity_in, 'N') loop
            perform rhn_channel.unsubscribe_server(sc.server_id, sc.channel_id,
                                                   1, 1, 0, 0);
        end loop;

        for sc in serverchannels(flex_in, 'Y') loop
            perform rhn_channel.unsubscribe_server(sc.server_id, sc.channel_id,
                                                   1, 1, 0, 0);
        end loop;

        perform rhn_channel.update_family_counts(channel_family_id_in, customer_id_in);
    end$$
language plpgsql;

    create or replace function set_family_count (
        customer_id_in in numeric,      -- customer_id
        channel_family_id_in in numeric,    -- 246
        quantity_in in numeric,          -- 3
        flex_in in numeric
    ) returns void
as $$
    declare
        privperms cursor for
            select  1
            from    rhnPrivateChannelFamily
            where   org_id = customer_id_in
                and channel_family_id = channel_family_id_in;
        pubperms cursor for
            select  o.id org_id
            from    web_customer o,
                    rhnPublicChannelFamily pcf
            where   pcf.channel_family_id = channel_family_id_in;
        quantity numeric;
        done numeric := 0;
        flex numeric;
    begin
        quantity := quantity_in;
        if quantity is not null and quantity < 0 then
            quantity := 0;
        end if;
        flex := flex_in;
        if flex is not null and flex < 0 then
            flex := 0;
        end if;

        if customer_id_in is not null then
            for perm in privperms loop
                perform rhn_entitlements.prune_family(
                    customer_id_in,
                    channel_family_id_in,
                    quantity,
                    flex
                );

                if quantity is null and flex is null then
                    delete from rhnPrivateChannelFamily
                        where org_id = customer_id_in
                            and channel_family_id = channel_family_id_in;
                 else
                    update rhnPrivateChannelFamily
                        set max_members = quantity
                        where org_id = customer_id_in
                            and channel_family_id = channel_family_id_in;

                   update rhnPrivateChannelFamily
                        set fve_max_members = flex
                        where org_id = customer_id_in
                            and channel_family_id = channel_family_id_in;
                end if;
                return;
            end loop;

            insert into rhnPrivateChannelFamily (
                    channel_family_id, org_id, max_members, current_members, fve_max_members, fve_current_members
                ) values (
                    channel_family_id_in, customer_id_in, quantity, 0, flex, 0 );
            return;
        end if;

        for perm in pubperms loop
            if quantity = 0 then
                perform rhn_entitlements.prune_family(
                    perm.org_id,
                    channel_family_id_in,
                    quantity,
                    flex
                );
                if done = 0 then
                    delete from rhnPublicChannelFamily
                        where channel_family_id = channel_family_id_in;
                end if;
            end if;
            done := 1;
        end loop;
        -- if done's not 1, then we don't have any entitlements
        if done != 1 then
            insert into rhnPublicChannelFamily (
                    channel_family_id
                ) values (
                    channel_family_id_in
                );
        end if;
    end$$
language plpgsql;

    -- this expects quantity_in to be the number of available slots, not the
    -- max_members of the server group.  If you give it too many, it'll fail
    -- and raise servergroup_max_members.
    -- We should NEVER run this unless we're SURE that we won't
    -- be violating the max.
    create or replace function entitle_last_modified_servers (
        customer_id_in in numeric,  -- customer_id
        type_label_in in varchar,   -- 'enterprise_entitled'
        quantity_in in numeric      -- 3
    ) returns void
as $$
    declare
        -- find the servers that aren't currently in slots
        servers cursor(cid_in numeric, quant_in numeric) for
                                    select  rs.id as server_id
                                    from    rhnServer rs
                                    where   1=1
                                        and rs.org_id = cid_in
                                        and not exists (
                                            select  1
                                            from    rhnServerGroup sg,
                                                    rhnServerGroupMembers rsgm
                                            where   rsgm.server_id = rs.id
                                                and rsgm.server_group_id = sg.id
                                                and sg.group_type is not null
                                        )
                                        and not exists (
                                            select 1
                                            from rhnVirtualInstance vi
                                            where vi.virtual_system_id =
                                                  rs.id
                                        )
                                    order by modified desc
                                    limit quant_in;
    begin
        for server in servers(customer_id_in, quantity_in) loop
            perform rhn_entitlements.entitle_server(server.server_id, type_label_in);
        end loop;
    end$$
language plpgsql;

    create or replace function subscribe_newest_servers (
        customer_id_in in numeric
    ) returns void
as $$
    declare
        -- find servers without base channels
        servers cursor(cid_in numeric) for
            select  s.id
            from    rhnServer           s
            where   1=1
                and s.org_id = cid_in
                and not exists (
                        select 1
                        from    rhnChannel          c,
                                rhnServerChannel    sc
                        where   sc.server_id = s.id
                            and sc.channel_id = c.id
                            and c.parent_channel is null
                    )
                and not exists (
                        select 1
                        from rhnVirtualInstance vi
                        where vi.virtual_system_id = s.id
                    )
            order by s.modified desc;
        channel_id numeric;
    begin
        for server in servers(customer_id_in) loop
            channel_id := rhn_channel.guess_server_base(server.id);
            if channel_id is not null then
                begin
                    perform rhn_channel.subscribe_server(server.id, channel_id);
                -- exception is really channel_family_no_subscriptions
                exception
                    when others then
                        null;
                end;
            end if;
        end loop;
    end$$
language plpgsql;


-- restore the original setting
update pg_settings set setting = overlay( setting placing '' from 1 for (length('rhn_entitlements')+1) ) where name = 'search_path';
07070100000A49000081B400000000000000000000000167AE1114000000B2000000000000000000000000000000000000007400000000susemanager-schema/upgrade/susemanager-schema-1.7.57-to-susemanager-schema-2.1/4011-rhnOrgConfiguration-scapret.sql   alter table rhnOrgConfiguration
  add scap_retention_period_days
      NUMERIC default (90)
      constraint rhn_org_conf_scap_reten_chk check (scap_retention_period_days >= 0);
  07070100000A4A000081B400000000000000000000000167AE11140000034D000000000000000000000000000000000000005C00000000susemanager-schema/upgrade/susemanager-schema-1.7.57-to-susemanager-schema-2.1/4013-log.sql   
CREATE OR REPLACE FUNCTION log_rename_constrains()
RETURNS VOID
LANGUAGE plpgsql
AS
$$
DECLARE
    pk_constraint_name varchar;
    fk_constraint_name varchar;
BEGIN
    SELECT constraint_name INTO pk_constraint_name
    FROM information_schema.table_constraints
    WHERE table_name = 'log'
    AND constraint_type = 'PRIMARY KEY';

    SELECT constraint_name INTO fk_constraint_name
    FROM information_schema.table_constraints
    WHERE table_name = 'log'
    AND constraint_type = 'FOREIGN KEY';

    EXECUTE 'ALTER INDEX ' || pk_constraint_name || ' RENAME TO log_id_pk';

    EXECUTE 'ALTER TABLE log DROP CONSTRAINT ' || fk_constraint_name;
    EXECUTE 'ALTER TABLE log ADD CONSTRAINT log_user_id_fk FOREIGN KEY (user_id) REFERENCES web_contact_all(id)';
END;
$$;

SELECT log_rename_constrains();

DROP FUNCTION log_rename_constrains();
   07070100000A4B000081B400000000000000000000000167AE11140000025E000000000000000000000000000000000000006400000000susemanager-schema/upgrade/susemanager-schema-1.7.57-to-susemanager-schema-2.1/4017-queu_server.sql   
CREATE OR REPLACE FUNCTION
queue_server(server_id_in IN NUMERIC, immediate_in IN NUMERIC DEFAULT 1)
RETURNS VOID
AS
$$
DECLARE
    org_id_tmp NUMERIC;
BEGIN
    IF immediate_in > 0
    THEN
          PERFORM rhn_server.update_needed_cache(server_id_in);
    ELSE
          SELECT org_id INTO STRICT org_id_tmp
          FROM rhnServer WHERE id = server_id_in;

          INSERT
            INTO rhnTaskQueue
                 (org_id, task_name, task_data)
          VALUES (org_id_tmp,
                  'update_server_errata_cache',
                  server_id_in);
    END IF;
END;
$$ LANGUAGE plpgsql;
  07070100000A4C000081B400000000000000000000000167AE11140000002A000000000000000000000000000000000000006C00000000susemanager-schema/upgrade/susemanager-schema-1.7.57-to-susemanager-schema-2.1/4018-rhnServerNeededView.sql   
DROP VIEW IF EXISTS rhnServerNeededView;
  07070100000A4D000081B400000000000000000000000167AE1114000001A2000000000000000000000000000000000000006600000000susemanager-schema/upgrade/susemanager-schema-1.7.57-to-susemanager-schema-2.1/4019-rhnPackageKey.sql update rhnPackageKey set provider_id = lookup_package_provider('Oracle Inc.')
 where key_id = '72f97b74ec551f03';

insert into rhnPackageKey (id, key_id, key_type_id, provider_id)
    (select sequence_nextval('rhn_pkey_id_seq'), '72f97b74ec551f03', lookup_package_key_type('gpg'), lookup_package_provider('Oracle Inc.') from dual
     where not exists (select 1 from rhnPackageKey where key_id = '72f97b74ec551f03'));
  07070100000A4E000081B400000000000000000000000167AE111400010785000000000000000000000000000000000000006D00000000susemanager-schema/upgrade/susemanager-schema-1.7.57-to-susemanager-schema-2.1/4020-rhn_entitlements.pkb.sql  --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--

-- create schema rhn_entitlements;

-- setup search_path so that these functions are created in appropriate schema.
update pg_settings set setting = 'rhn_entitlements,' || setting where name = 'search_path';

   create or replace function find_compatible_sg (
      server_id_in in numeric,
      type_label_in in varchar
   )
   returns numeric
as $$
    declare
      servergroups cursor for
         select sg.id
           from rhnServerGroupType             sgt,
                rhnServerGroup                 sg,
                rhnServer                     s,
                rhnServerServerGroupArchCompat ssgac
          where s.id = server_id_in
            and s.org_id = sg.org_id
            and sgt.label = type_label_in
            and sg.group_type = sgt.id
            and ssgac.server_group_type = sgt.id
            and ssgac.server_arch_id = s.server_arch_id
            and not exists ( 
                     select 1
                      from rhnServerGroupMembers sgm
                     where sgm.server_group_id = sg.id 
                       and sgm.server_id = s.id);

         
   begin
      for servergroup in servergroups loop
         return servergroup.id;
      end loop;

      --no servergroup found
      return NULL;
   end$$
language plpgsql;

    -- *******************************************************************
    -- PROCEDURE: remove_org_entitlements
    --
    -- Removes both system entitlements and channel subscriptions
    -- that are currently assigned to an org and re-assigns to the
    -- master org (org_id = 1).
    --
    -- When we call this we expect everything to already be unentitled
    -- which shoul be handled by delete_org.
    --
    -- Called by: delete_org
    -- *******************************************************************
    create or replace function remove_org_entitlements (
        org_id_in numeric
    ) returns void
as $$
    declare
        system_ents cursor for
        select sg.id, sg.max_members, sg.group_type
        from rhnServerGroup sg
        where group_type is not null
          and org_id = org_id_in;

        channel_subs cursor for
        select pcf.channel_family_id, pcf.max_members
        from rhnChannelFamily cf,
             rhnPrivateChannelFamily pcf
        where pcf.org_id = org_id_in
          and pcf.channel_family_id = cf.id
          and cf.org_id is null;

    begin

        for system_ent in system_ents loop
            update rhnServerGroup
            set max_members = max_members + system_ent.max_members
            where org_id = 1
              and group_type = system_ent.group_type;
        end loop;

        update rhnServerGroup
        set max_members = 0
        where org_id = org_id_in;

        for channel_sub in channel_subs loop
            update rhnPrivateChannelFamily
            set max_members = max_members + channel_sub.max_members
            where org_id = 1
              and channel_family_id = channel_sub.channel_family_id;
        end loop;
        
        update rhnPrivateChannelFamily
        set max_members = 0
        where org_id = org_id_in;

    end$$
language plpgsql;

    create or replace function entitlement_grants_service (
        entitlement_in in varchar,
        service_level_in in varchar
    ) returns numeric
as $$
    begin
        if service_level_in = 'provisioning' then
            if entitlement_in = 'provisioning_entitled' then
                return 1;
            else
                return 0;
            end if;
        elsif service_level_in = 'management' then
            if entitlement_in = 'enterprise_entitled' then
                return 1;
            else
                return 0;
            end if;
        elsif service_level_in = 'monitoring' then
            if entitlement_in = 'monitoring_entitled' then
                return 1;
            end if;
        elsif service_level_in = 'updates' then
            return 1;           
        else
            return 0;
        end if;
    end$$
language plpgsql;

    create or replace function lookup_entitlement_group (
        org_id_in in numeric,
        type_label_in in varchar default 'sw_mgr_entitled'
    ) returns numeric
as $$
    declare
        server_groups cursor for
            select  sg.id               server_group_id
            from    rhnServerGroup      sg,
                    rhnServerGroupType  sgt
            where   sgt.label = type_label_in
                and sgt.id = sg.group_type
                and sg.org_id = org_id_in;
    begin
        for sg in server_groups loop
            return sg.server_group_id;
        end loop;
        return rhn_entitlements.create_entitlement_group(
                org_id_in, 
                type_label_in
            );
    end$$
language plpgsql;

    create or replace function create_entitlement_group (
        org_id_in in numeric,
        type_label_in in varchar default 'sw_mgr_entitled'
    ) returns numeric
as $$
    declare
        sg_id_val numeric;
    begin
        select  nextval('rhn_server_group_id_seq')
        into    sg_id_val;

        insert into rhnServerGroup (
                id, name, description, max_members, current_members,
                group_type, org_id
            ) (
                select  sg_id_val, sgt.label, sgt.label,
                        0, 0, sgt.id, org_id_in
                from    rhnServerGroupType sgt
                where   sgt.label = type_label_in
            );

        return sg_id_val;
    end$$
language plpgsql;

   create or replace function can_entitle_server ( 
      server_id_in   in numeric, 
      type_label_in  in varchar
   )
   returns numeric
as $$
    declare
      addon_servergroups cursor (base_label_in varchar, 
                                 addon_label_in varchar) for
         select
            addon_id
         from
            rhnSGTypeBaseAddonCompat
         where base_id = lookup_sg_type (base_label_in)
           and addon_id = lookup_sg_type (addon_label_in);

      previous_ent        varchar[];
      is_base_in          char   := 'N';
      is_base_current     char   := 'N';
      i                   numeric := 0;
      sgid                numeric := 0;

   begin

      previous_ent := rhn_entitlements.get_server_entitlement(server_id_in);

      select distinct is_base
      into is_base_in
      from rhnServerGroupType
      where label = type_label_in;

      if array_upper(previous_ent, 1) is null or array_upper(previous_ent, 1) = 0 then
         if is_base_in = 'Y' then
            sgid := rhn_entitlements.find_compatible_sg (server_id_in, type_label_in);
            if sgid is not null then
              -- rhn_server.insert_into_servergroup (server_id_in, sgid);
              return 1;
            else
              -- rhn_exception.raise_exception ('invalid_base_entitlement');
              return 0;
            end if;
         else
            -- rhn_exception.raise_exception ('invalid_base_entitlement');
            return 0;
         end if;

      -- there are previous ents, first make sure we're not trying to entitle a base ent
      elsif is_base_in = 'Y' then
         -- rhn_exception.raise_exception ('invalid_addon_entitlement');
         return 0;

      -- it must be an addon, so proceed with the entitlement
      else

         -- find the servers base ent
         is_base_current := 'N';
         i := 0;
         while is_base_current = 'N' and i < array_upper(previous_ent, 1)
         loop
            i := i + 1;
            select is_base
            into is_base_current
            from rhnServerGroupType
            where label = previous_ent[i];
         end loop;

         -- never found a base ent, that would be strange
         if is_base_current  = 'N' then
            -- rhn_exception.raise_exception ('invalid_base_entitlement');
            return 0;
         end if;

         -- this for loop verifies the validity of the addon path
         for addon_servergroup in addon_servergroups  (previous_ent[i], type_label_in) loop
            -- find an appropriate sgid for the addon and entitle the server
            sgid := rhn_entitlements.find_compatible_sg (server_id_in, type_label_in);
            if sgid is not null then
               -- rhn_server.insert_into_servergroup (server_id_in, sgid);
               return 1;
            else
               -- rhn_exception.raise_exception ('invalid_addon_entitlement');
               return 0;
            end if;
         end loop;

      end if;

      return 0;

   end$$
language plpgsql;

   create or replace function can_switch_base ( 
      server_id_in   in    integer, 
      type_label_in  in    varchar
   )
   returns numeric
as $$
   declare
      type_label_in_is_base   char(1);
      sgid                    numeric;

   begin

       select is_base into type_label_in_is_base
       from rhnServerGroupType
       where label = type_label_in;

       if not found then
          perform rhn_exception.raise_exception ( 'invalid_entitlement' );
       end if;

      if type_label_in_is_base = 'N' then
         perform rhn_exception.raise_exception ( 'invalid_entitlement' );
      else
         sgid := rhn_entitlements.find_compatible_sg ( server_id_in,
                                                       type_label_in );
         if sgid is not null then
           return 1;
         else
           return 0;
         end if;
      end if;

   end$$
language plpgsql;

    create or replace function entitle_server (
        server_id_in in numeric,
        type_label_in in varchar default 'sw_mgr_entitled'
    ) returns void
as $$
    declare
      sgid  numeric := 0;
      is_virt numeric := 0;

    begin

      select 1 into is_virt
        from rhnServerEntitlementView
        where server_id = server_id_in
          and label in ('virtualization_host', 'virtualization_host_platform');

      if not found then
          is_virt := 0;
      end if;
      
      if is_virt = 0 and (type_label_in = 'virtualization_host' or
                          type_label_in = 'virtualization_host_platform') then

        is_virt := 1;
      end if;

      if rhn_entitlements.can_entitle_server(server_id_in, 
                                             type_label_in) = 1 then
         sgid := rhn_entitlements.find_compatible_sg (server_id_in,
                                                      type_label_in);
         if sgid is not null then
            insert into rhnServerHistory ( id, server_id, summary, details )
            values ( nextval('rhn_event_id_seq'), server_id_in,
                     'added system entitlement ',
                      case type_label_in
                       when 'enterprise_entitled' then 'Management'
                       when 'sw_mgr_entitled' then 'Update'
                       when 'provisioning_entitled' then 'Provisioning'
                       when 'monitoring_entitled' then 'Monitoring'  
                       when 'virtualization_host' then 'Virtualization'
                       when 'virtualization_host_platform' then 
                            'Virtualization Platform' end  );

            perform rhn_server.insert_into_servergroup (server_id_in, sgid);

            if is_virt = 1 then
              perform rhn_entitlements.repoll_virt_guest_entitlements(server_id_in);
            end if;

         else
            perform rhn_exception.raise_exception ('no_available_server_group');
         end if;
      else
         perform rhn_exception.raise_exception ('invalid_entitlement');
      end if;
   end$$
language plpgsql;

    create or replace function remove_server_entitlement (
        server_id_in in numeric,
        type_label_in in varchar default 'sw_mgr_entitled',
        repoll_virt_guests in numeric default 1
    ) returns void
as $$
    declare
      group_id numeric;
      type_is_base char;
      is_virt numeric := 0;
    begin
      -- would be nice if there were a virt attribute of entitlement types, not have to specify 2 different ones...
        select 1 into is_virt
          from rhnServerEntitlementView
          where server_id = server_id_in
            and label in ('virtualization_host', 'virtualization_host_platform');
        if not found then
            is_virt := 0;
        end if;

        select  sg.id, sgt.is_base
        into group_id, type_is_base
        from    rhnServerGroupType sgt,
            rhnServerGroup sg,
                rhnServerGroupMembers sgm,
                rhnServer s
        where   s.id = server_id_in
            and s.id = sgm.server_id
            and sgm.server_group_id = sg.id
            and sg.org_id = s.org_id
            and sgt.label = type_label_in
            and sgt.id = sg.group_type;

        if not found then
          perform rhn_exception.raise_exception('invalid_server_group_member');
        end if;

      if ( type_is_base = 'Y' ) then
         -- unentitle_server should handle everything, don't really need to do anything else special here
         perform rhn_entitlements.unentitle_server ( server_id_in );
      else

         insert into rhnServerHistory ( id, server_id, summary, details )
         values ( nextval('rhn_event_id_seq'), server_id_in,
                  'removed system entitlement ',
                   case type_label_in
                    when 'enterprise_entitled' then 'Management'
                    when 'sw_mgr_entitled' then 'Update'
                    when 'provisioning_entitled' then 'Provisioning'
                    when 'monitoring_entitled' then 'Monitoring'
                    when 'virtualization_host' then 'Virtualization'
                    when 'virtualization_host_platform' then 
                         'Virtualization Platforrm' end  );

         perform rhn_server.delete_from_servergroup(server_id_in, group_id);

         if type_label_in = 'monitoring_entitled' then
           DELETE
             FROM rhn_probe
            WHERE recid IN (SELECT probe_id
                              FROM rhn_check_probe
                             WHERE host_id = server_id_in);
         end if;

         if is_virt = 1 and repoll_virt_guests = 1 then
           perform rhn_entitlements.repoll_virt_guest_entitlements(server_id_in);
         end if;
      end if;

    end$$
language plpgsql;

    create or replace function unentitle_server (
        server_id_in in numeric
    ) returns void
as $$
    declare
      servergroups cursor for
         select distinct sgt.label, sg.id server_group_id
         from  rhnServerGroupType sgt,
               rhnServerGroup sg,
               rhnServer s,
               rhnServerGroupMembers sgm
         where s.id = server_id_in
            and s.org_id = sg.org_id
            and sg.group_type = sgt.id
            and sgm.server_group_id = sg.id
            and sgm.server_id = s.id;
            
     is_virt numeric := 0;

   begin

      select 1 into is_virt
        from rhnServerEntitlementView
        where server_id = server_id_in
         and label in ('virtualization_host', 'virtualization_host_platform');

      if not found then
          is_virt := 0;
      end if;

      for servergroup in servergroups loop

         insert into rhnServerHistory ( id, server_id, summary, details )
         values ( nextval('rhn_event_id_seq'), server_id_in,
                  'removed system entitlement ',
                   case servergroup.label
                    when 'enterprise_entitled' then 'Management'
                    when 'sw_mgr_entitled' then 'Update'
                    when 'provisioning_entitled' then 'Provisioning'
                    when 'monitoring_entitled' then 'Monitoring'
                    when 'virtualization_host' then 'Virtualization'
                    when 'virtualization_host_platform' then 
                         'Virtualization Platform' end  );
  
         perform rhn_server.delete_from_servergroup(server_id_in, 
                                            servergroup.server_group_id );
      end loop;

      if is_virt = 1 then
        perform rhn_entitlements.repoll_virt_guest_entitlements(server_id_in);
      end if;

   end$$
language plpgsql;


    -- *******************************************************************
    -- PROCEDURE: repoll_virt_guest_entitlements
    --
    --   Whenever we add/remove a virtualization_host* entitlement from 
    --   a host, we can call this procedure to update what type of slots
    --   the guests are consuming.  
    -- 
    --   If you're removing the entitlement, it's 
    --   possible the guests will become unentitled if you don't have enough
    --   physical slots to cover them.
    --
    --   If you're adding the entitlement, you end up freeing up physical
    --   slots for other systems.
    --
    -- *******************************************************************
    create or replace function repoll_virt_guest_entitlements(
        server_id_in in numeric
    ) returns void
as $$
    declare
        -- All channel families associated with the guests of server_id_in
        families cursor for 
            select distinct cfs.channel_family_id
            from
                rhnChannelFamilyServers cfs,
                rhnVirtualInstance vi
            where
                vi.host_system_id = server_id_in
                and vi.virtual_system_id = cfs.server_id;
        
        -- All of server group types associated with the guests of
        -- server_id_in
        group_types cursor for
            select distinct sg.group_type, sgt.label, sg.org_id
            from
                rhnServerGroupType sgt,
                rhnServerGroup sg,
                rhnServerGroupMembers sgm,
                rhnVirtualInstance vi
            where
                vi.host_system_id = server_id_in
                and vi.virtual_system_id = sgm.server_id
                and sgm.server_group_id = sg.id
                and sg.group_type = sgt.id;

        -- Virtual servers from a certain family belonging to a specific
        -- host that are consuming physical channel slots over the limit.
        virt_servers_cfam cursor(family_id_in numeric, quantity_in numeric) for
                select vi.virtual_system_id
                from
                    rhnChannelFamilyMembers cfm,
                    rhnServerChannel sc,
                    rhnVirtualInstance vi
                where
                    vi.host_system_id = server_id_in
                    and vi.virtual_system_id = sc.server_id
                    and sc.channel_id = cfm.channel_id
                    and cfm.channel_family_id = family_id_in
                order by sc.modified desc
                limit quantity_in;                

        -- Virtual servers from a certain family belonging to a specific
        -- host that are consuming physical system slots over the limit.
        virt_servers_sgt cursor(group_type_in numeric, quantity_in numeric) for
                select vi.virtual_system_id
                from
                    rhnServerGroup sg,
                    rhnServerGroupMembers sgm,
                    rhnVirtualInstance vi
                where
                    vi.host_system_id = server_id_in
                    and vi.virtual_system_id = sgm.server_id
                    and sgm.server_group_id = sg.id
                    and sg.group_type = group_type_in
                order by sgm.modified desc
                limit quantity_in;                
        
        -- Get the orgs of Virtual guests
        -- Since they may belong to different orgs
        virt_guest_orgs cursor for
                select  distinct (s.org_id)
                from rhnServer s
                    inner join  rhnVirtualInstance vi on vi.virtual_system_id = s.id
                where
                    vi.host_system_id = server_id_in
                    and s.org_id <> (select s1.org_id from rhnServer s1 where s1.id = vi.host_system_id) ;

        org_id_val numeric;
        max_members_val numeric;
        max_flex_val numeric;
        current_members_calc numeric;
        sg_id numeric;
        is_virt numeric := 0;
        free_slots numeric := 0;
    begin
          select 1 into is_virt
                from rhnServerEntitlementView
           where server_id = server_id_in
                 and label in ('virtualization_host', 'virtualization_host_platform');

      if not found then
          is_virt := 0;
      end if;

        select org_id
        into org_id_val
        from rhnServer
        where id = server_id_in;

        -- deal w/ channel entitlements first ...
        for family in families loop
            if is_virt = 0 then
            -- if the host_server does not have virt
            --- find all possible flex slots
            -- and set each of the flex eligible guests to Y
                select sfc.max_members - sfc.current_members
                  into free_slots
                  from rhnServerFveCapable sfc
                 where sfc.channel_family_id = family.channel_family_id;
                UPDATE rhnServerChannel sc set is_fve = 'Y'
                where sc.server_id in (
                            select vi.virtual_system_id
                            from rhnServerFveCapable sfc
                                inner join rhnVirtualInstance vi on vi.virtual_system_id = sfc.server_id
                            where vi.host_system_id = server_id_in
                                  and sfc.channel_family_id = family.channel_family_id
                              order by vi.modified desc
                            limit free_slots
                );
            else
            -- if the host_server has virt
            -- set all its flex guests to N
                UPDATE rhnServerChannel sc set is_fve = 'N'
                where
                    sc.channel_id in (select cfm.channel_id from rhnChannelFamilyMembers cfm
                                      where cfm.CHANNEL_FAMILY_ID = family.channel_family_id)
                    and sc.is_fve = 'Y'
                    and sc.server_id in
                            (select vi.virtual_system_id  from rhnVirtualInstance vi
                                    where vi.host_system_id = server_id_in);
            end if;

            -- get the current (physical) members of the family
            current_members_calc := 
                rhn_channel.channel_family_current_members(family.channel_family_id,
                                                           org_id_val); -- fixed transposed args

            -- get the max members of the family
            select max_members
            into max_members_val
            from rhnPrivateChannelFamily
            where channel_family_id = family.channel_family_id
            and org_id = org_id_val;

            select fve_max_members
            into max_flex_val
            from rhnPrivateChannelFamily
            where channel_family_id = family.channel_family_id
            and org_id = org_id_val;

            if current_members_calc > max_members_val then
                -- A virtualization_host* ent must have been removed, so we'll
                -- unsubscribe guests from the host first.

                -- hm, i don't think max_members - current_members_calc yielding a negative number
                -- will work w/ rownum, swaping 'em in the body of this if...
                for virt_server in virt_servers_cfam(family.channel_family_id,
                                current_members_calc - max_members_val) loop 

                    perform rhn_channel.unsubscribe_server_from_family(
                                virt_server.virtual_system_id,
                                family.channel_family_id);
                end loop;                               

                -- if we're still over the limit, which would be odd,
                -- just prune the group to max_members
                --
                -- er... wouldn't we actually have to refresh the values of
                -- current_members_calc and max_members_val to actually ever
                -- *skip this??
                if current_members_calc > max_members_val then
                    -- argh, transposed again?!
                    perform rhn_entitlements.set_family_count(org_id_val,
                                     family.channel_family_id,
                                     max_members_val, max_flex_val);
                    --TODO calculate this correctly
                end if; 

           end if;

            -- update current_members for the family.  This will set the value
            -- to reflect adding/removing the entitlement.
            --
            -- what's the difference of doing this vs the unavoidable set_family_count above?
            perform rhn_channel.update_family_counts(family.channel_family_id,
                                             org_id_val);

            -- It is possible that the guests belong  to a different org than the host
            -- so we are going to update the family counts in the guests orgs also
            for org in virt_guest_orgs loop
                    perform rhn_channel.update_family_counts(family.channel_family_id,
                                             org.org_id);
            end loop;
        end loop;

        for a_group_type in group_types loop
          -- get the current *physical* members of the system entitlement type for the org...
          -- 
          -- unlike channel families, it appears the standard rhnServerGroup.max_members represents
          -- *physical* slots, vs physical+virt ... boy that's confusing...

          select max_members, id
            into max_members_val, sg_id
            from rhnServerGroup
            where group_type = a_group_type.group_type
            and org_id = a_group_type.org_id;


      select count(sep.server_id) into current_members_calc
            from rhnServerEntitlementPhysical sep
           where sep.server_group_id = sg_id
             and sep.server_group_type_id = a_group_type.group_type;
          
          if current_members_calc > max_members_val then
            -- A virtualization_host* ent must have been removed, and we're over the limit, so unsubscribe guests
            for virt_server in virt_servers_sgt(a_group_type.group_type,
                                                current_members_calc - max_members_val) loop
              perform rhn_entitlements.remove_server_entitlement(virt_server.virtual_system_id, a_group_type.label);

              -- decrement current_members_calc, we'll use it to reset current_members for the group at the end...
              current_members_calc := current_members_calc - 1;
            end loop;

          end if;

          update rhnServerGroup set current_members = current_members_calc
           where org_id = a_group_type.org_id
             and group_type = a_group_type.group_type;

          -- I think that's all the house-keeping we have to do...
        end loop;

    end$$
language plpgsql;

    create or replace function get_server_entitlement (
        server_id_in in numeric
    ) returns varchar[]
as $$
    declare
        server_groups cursor for
            select  sgt.label
            from    rhnServerGroupType      sgt,
                    rhnServerGroup          sg,
                    rhnServerGroupMembers   sgm
            where   1=1
                and sgm.server_id = server_id_in
                and sg.id = sgm.server_group_id
                and sgt.id = sg.group_type
                and sgt.label in (
                    'sw_mgr_entitled','enterprise_entitled',
                    'provisioning_entitled', 'nonlinux_entitled',
                    'monitoring_entitled', 'virtualization_host',
                                        'virtualization_host_platform'
                    );

         ent_array varchar[];

    begin
      
      ent_array := '{}';

      for sg in server_groups loop
         ent_array := ent_array || sg.label;
      end loop;

      return ent_array;

    end$$
language plpgsql;

    -- this desperately needs to be table driven.
    create or replace function modify_org_service (
        org_id_in in numeric,
        service_label_in in varchar,
        enable_in in char
    ) returns void
as $$
    declare
        roles_to_process varchar[];
        roles cursor(role_label_in varchar) for
            select  label, id
            from    rhnUserGroupType
            where   label = role_label_in;
        org_roles cursor(role_label_in varchar) for
            select  1
            from    rhnUserGroup ug,
                    rhnUserGroupType ugt
            where   ugt.label = role_label_in
                and ug.org_id = org_id_in
                and ugt.id = ug.group_type;
                
        ents_to_process varchar[];
        ents cursor(ent_label_in varchar) for
            select  label, id
            from    rhnOrgEntitlementType
            where   label = ent_label_in;
        org_ents cursor(ent_label_in varchar) for
            select  1
            from    rhnOrgEntitlements oe,
                    rhnOrgEntitlementType oet
            where   oet.label = ent_label_in
                and oe.org_id = org_id_in
                and oet.id = oe.entitlement_id;
        create_row char(1);
    begin
        ents_to_process := '{}';
        roles_to_process := '{}';
        -- a bit kludgy, but only for 3.4 really.  Certainly no
        -- worse than the old code...
        if service_label_in = 'enterprise' or 
           service_label_in = 'management' then
            ents_to_process := array_append(ents_to_process, 'sw_mgr_enterprise');

            roles_to_process := array_append(roles_to_process, 'org_admin');

            roles_to_process := array_append(roles_to_process, 'system_group_admin');

            roles_to_process := array_append(roles_to_process, 'activation_key_admin');
        elsif service_label_in = 'provisioning' then
            ents_to_process := array_append(ents_to_process, 'rhn_provisioning');

            roles_to_process := array_append(roles_to_process, 'system_group_admin');

            roles_to_process := array_append(roles_to_process, 'activation_key_admin');

            roles_to_process := array_append(roles_to_process, 'config_admin');
            -- another nasty special case...
            if enable_in = 'Y' then
                ents_to_process := array_append(ents_to_process, 'sw_mgr_enterprise');
            end if;
        elsif service_label_in = 'monitoring' then
            ents_to_process := array_append(ents_to_process, 'rhn_monitor');

            roles_to_process := array_append(roles_to_process, 'monitoring_admin');
        elsif service_label_in = 'virtualization' then
            ents_to_process := array_append(ents_to_process, 'rhn_virtualization');

            roles_to_process := array_append(roles_to_process, 'config_admin');
        elsif service_label_in = 'virtualization_platform' then
            ents_to_process := array_append(ents_to_process, 'rhn_virtualization_platform');
            roles_to_process := array_append(roles_to_process, 'config_admin');
    elsif service_label_in = 'nonlinux' then
            ents_to_process := array_append(ents_to_process, 'rhn_nonlinux');
            roles_to_process := array_append(roles_to_process, 'config_admin');
        end if;

        if enable_in = 'Y' then
            for i in 1..array_upper(ents_to_process, 1) loop
                for ent in ents(ents_to_process[i]) loop
                    create_row := 'Y';
                    for oe in org_ents(ent.label) loop
                        create_row := 'N';
                    end loop;
                    if create_row = 'Y' then
                        insert into rhnOrgEntitlements(org_id, entitlement_id)
                            values (org_id_in, ent.id);
                    end if;
                end loop;
            end loop;
            for i in 1..array_upper(roles_to_process, 1) loop
                for role in roles(roles_to_process[i]) loop
                    create_row := 'Y';
                    for o_r in org_roles(role.label) loop
                        create_row := 'N';
                    end loop;
                    if create_row = 'Y' then
                        insert into rhnUserGroup(
                                id, name, description, current_members,
                                group_type, org_id
                            ) (
                                select  nextval('rhn_user_group_id_seq'),
                                        ugt.name || 's',
                                        ugt.name || 's for Org ' ||
                                            o.name || ' ('|| o.id ||')',
                                        0, ugt.id, o.id
                                from    rhnUserGroupType ugt,
                                        web_customer o
                                where   o.id = org_id_in
                                    and ugt.id = role.id
                            );
                    end if;
                end loop;
            end loop;
        else
            for i in 1..coalesce(array_upper(ents_to_process, 1), 0) loop
                for ent in ents(ents_to_process[i]) loop
                    delete from rhnOrgEntitlements
                     where org_id = org_id_in
                       and entitlement_id = ent.id;
                end loop;
            end loop;
        end if;
    end$$
language plpgsql;

    create or replace function set_customer_enterprise (
        customer_id_in in numeric
    ) returns void
as $$
    begin
        perform rhn_entitlements.modify_org_service(customer_id_in, 'enterprise', 'Y');
    end$$
language plpgsql;

    create or replace function set_customer_provisioning (
        customer_id_in in numeric
    ) returns void
as $$
    begin
        perform rhn_entitlements.modify_org_service(customer_id_in, 'provisioning', 'Y');
    end$$
language plpgsql;

    create or replace function set_customer_monitoring (
        customer_id_in in numeric
    ) returns void
as $$
    begin
        perform rhn_entitlements.modify_org_service(customer_id_in, 'monitoring', 'Y');
    end$$
language plpgsql;

    create or replace function set_customer_nonlinux (
        customer_id_in in numeric
    ) returns void
as $$
    begin
        perform rhn_entitlements.modify_org_service(customer_id_in, 'nonlinux', 'Y');
    end$$
language plpgsql;

    create or replace function unset_customer_enterprise (
        customer_id_in in numeric
    ) returns void
as $$
    begin
        perform rhn_entitlements.modify_org_service(customer_id_in, 'enterprise', 'N');
    end$$
language plpgsql;

    create or replace function unset_customer_provisioning (
        customer_id_in in numeric
    ) returns void
as $$
    begin
        perform rhn_entitlements.modify_org_service(customer_id_in, 'provisioning', 'N');
    end$$
language plpgsql;

    create or replace function unset_customer_monitoring (
        customer_id_in in numeric
    ) returns void
as $$
    begin
        perform rhn_entitlements.modify_org_service(customer_id_in, 'monitoring', 'N');
    end$$
language plpgsql;

    create or replace function unset_customer_nonlinux (
        customer_id_in in numeric
    ) returns void
as $$
    begin
        perform rhn_entitlements.modify_org_service(customer_id_in, 'nonlinux', 'N');
    end$$
language plpgsql;

    -- *******************************************************************
    -- PROCEDURE: prune_group
    -- Unsubscribes servers consuming physical slots that over the org's
    --   limit.
    -- Called by: set_server_group_count, repoll_virt_guest_entitlements
    -- *******************************************************************
    create or replace function prune_group (
        group_id_in in numeric,
        quantity_in in numeric,
        update_family_countsYN in numeric default 1
    ) returns void
as $$
    declare
        sgrecord record;
      type_is_base char;
    begin
            update      rhnServerGroup
                set     max_members = quantity_in
                where   id = group_id_in;

            for sgrecord in (
		   select  server_id, server_group_id, sgt.id as group_type_id, sgt.label
		    from    rhnServerGroupType              sgt,
				    rhnServerGroup                  sg,
				    rhnServerGroupMembers   sgm
		    where   1=1
			    and sgm.server_group_id = group_id_in
			    and sgm.server_id in (
				    select  sep.server_id
				    from
					rhnServerEntitlementPhysical sep
				    where
					sep.server_group_id = group_id_in
				    order by sep.modified asc
				    offset quantity_in
				)
			    and sgm.server_group_id = sg.id
			    and sg.group_type = sgt.id
	    ) loop
                perform rhn_entitlements.remove_server_entitlement(sgrecord.server_id, sgrecord.label);
            
            select is_base 
            into type_is_base
            from rhnServerGroupType sgt
            where sgt.id = sgrecord.group_type_id;

            -- if we're removing a base ent, then be sure to
            -- remove the server's channel subscriptions.
            if ( type_is_base = 'Y' ) then
                   perform rhn_channel.clear_subscriptions(sgrecord.server_id, 0, update_family_countsYN);
            end if;

            end loop;
    end$$
language plpgsql;

    -- *******************************************************************
    -- PROCEDURE: assign_system_entitlement
    --
    -- Moves system entitlements from from_org_id_in to to_org_id_in.
    -- Can raise not_enough_entitlements_in_base_org if from_org_id_in
    -- does not have enough entitlements to cover the move.
    -- Takes care of unentitling systems if necessary by calling 
    -- set_server_group_count
    -- *******************************************************************
    create or replace function assign_system_entitlement(
        group_label_in in varchar,
        from_org_id_in in numeric,
        to_org_id_in in numeric,
        quantity_in in numeric
    ) returns void
as $$
    declare
        prev_ent_count numeric;
    to_org_prev_ent_count numeric;
        new_ent_count numeric;
    new_quantity numeric;
        group_type numeric;
    begin

            select max_members
            into prev_ent_count
            from rhnServerGroupType sgt,
                 rhnServerGroup sg
            where sg.org_id = from_org_id_in
              and sg.group_type = sgt.id
              and sgt.label = group_label_in;

            if not found then
                perform rhn_exception.raise_exception(
                              'not_enough_entitlements_in_base_org');
            end if;

            select max_members
            into to_org_prev_ent_count
            from rhnServerGroupType sgt,
                 rhnServerGroup sg
            where sg.org_id = to_org_id_in
              and sg.group_type = sgt.id
              and sgt.label = group_label_in;

            if not found then
                to_org_prev_ent_count := 0;
            end if;
    
            select id
            into group_type
            from rhnServerGroupType
            where label = group_label_in;

            if not found then
                perform rhn_exception.raise_exception(
                              'invalid_server_group');
            end if;

        new_ent_count := prev_ent_count - quantity_in;
    
        if prev_ent_count > new_ent_count then
            new_quantity := to_org_prev_ent_count + quantity_in;
        end if;
    
        if new_ent_count < 0 then
            perform rhn_exception.raise_exception(
                          'not_enough_entitlements_in_base_org');
        end if;


        perform rhn_entitlements.set_server_group_count(from_org_id_in,
                                         group_type,
                                         new_ent_count);

        perform rhn_entitlements.set_server_group_count(to_org_id_in,
                                         group_type,
                                         new_quantity);
        
        -- Create or delete the entries in rhnOrgEntitlementType
        if group_label_in = 'enterprise_entitled' then 
            if new_quantity > 0 then
                perform rhn_entitlements.set_customer_enterprise(to_org_id_in);
            else
                perform rhn_entitlements.unset_customer_enterprise(to_org_id_in);
            end if;
        end if;

        if group_label_in = 'provisioning_entitled' then
            if new_quantity > 0 then
                perform rhn_entitlements.set_customer_provisioning(to_org_id_in);
            else
                perform rhn_entitlements.unset_customer_provisioning(to_org_id_in);
            end if;
        end if;

        if group_label_in = 'monitoring_entitled' then
            if new_quantity > 0 then
                perform rhn_entitlements.set_customer_monitoring(to_org_id_in);
            else
                perform rhn_entitlements.unset_customer_monitoring(to_org_id_in);
            end if;
        end if;

    end$$
language plpgsql;

    -- *******************************************************************
    -- PROCEDURE: assign_channel_entitlement
    --
    -- Moves channel entitlements from from_org_id_in to to_org_id_in.
    -- Can raise not_enough_entitlements_in_base_org if from_org_id_in
    -- does not have enough entitlements to cover the move.
    -- Takes care of unentitling systems if necessary by calling 
    -- set_family_count
    -- *******************************************************************
    create or replace function assign_channel_entitlement(
        channel_family_label_in in varchar,
        from_org_id_in in numeric,
        to_org_id_in in numeric,
        quantity_in in numeric,
        flex_in in numeric
    ) returns void
as $$
    declare
        from_org_prev_ent_count numeric;
        from_org_prev_ent_count_flex numeric;
        new_ent_count numeric;
        new_ent_count_flex numeric;
        to_org_prev_ent_count numeric;
        to_org_prev_ent_count_flex numeric;
        new_quantity numeric;
        new_flex numeric;
        cfam_id       numeric;
    begin

            select max_members
            into from_org_prev_ent_count
            from rhnChannelFamily cf,
                 rhnPrivateChannelFamily pcf
            where pcf.org_id = from_org_id_in
              and pcf.channel_family_id = cf.id
              and cf.label = channel_family_label_in;

            if not found then
                perform rhn_exception.raise_exception(
                              'not_enough_entitlements_in_base_org');
            end if;
    
            select max_members
            into to_org_prev_ent_count
            from rhnChannelFamily cf,
                 rhnPrivateChannelFamily pcf
            where pcf.org_id = to_org_id_in
              and pcf.channel_family_id = cf.id
              and cf.label = channel_family_label_in;

            if not found then
                to_org_prev_ent_count := 0;
            end if;

            select fve_max_members
            into from_org_prev_ent_count_flex
            from rhnChannelFamily cf,
                rhnPrivateChannelFamily pcf
            where pcf.org_id = from_org_id_in
              and pcf.channel_family_id = cf.id
              and cf.label = channel_family_label_in;

            if not found then
                perform rhn_exception.raise_exception(
                              'not_enough_flex_entitlements_in_base_org');
            end if;

            select fve_max_members
            into to_org_prev_ent_count_flex
            from rhnChannelFamily cf,
                 rhnPrivateChannelFamily pcf
            where pcf.org_id = to_org_id_in
              and pcf.channel_family_id = cf.id
              and cf.label = channel_family_label_in;

            if not found then
                to_org_prev_ent_count_flex := 0;
            end if;

            select id
            into cfam_id
            from rhnChannelFamily
            where label = channel_family_label_in;

            if not found then
                perform rhn_exception.raise_exception(
                              'invalid_channel_family');
            end if;

        new_ent_count := from_org_prev_ent_count - quantity_in;
        new_ent_count_flex := from_org_prev_ent_count_flex - flex_in;
    
        if from_org_prev_ent_count >= new_ent_count then
            new_quantity := to_org_prev_ent_count + quantity_in;
        end if;

        if from_org_prev_ent_count_flex >= new_ent_count_flex then
            new_flex := to_org_prev_ent_count_flex + flex_in;
        end if;

        if new_ent_count < 0 then
            perform rhn_exception.raise_exception(
                          'not_enough_entitlements_in_base_org');
        end if;

        if new_ent_count_flex < 0 then
            perform rhn_exception.raise_exception(
                          'not_enough_flex_entitlements_in_base_org');
        end if;



        perform rhn_entitlements.set_family_count(from_org_id_in,
                                          cfam_id,
                                          new_ent_count,
                                          new_ent_count_flex);

        perform rhn_entitlements.set_family_count(to_org_id_in,
                                          cfam_id,
                                          new_quantity,
                                          new_flex);

    end$$
language plpgsql;

    -- *******************************************************************
    -- PROCEDURE: activate_system_entitlement
    --
    -- Sets the values in rhnServerGroup for a given rhnServerGroupType.
    -- 
    -- Calls: set_server_group_count to update, prune, or create the group.
    -- Called by: the code that activates a satellite cert. 
    --
    -- Raises not_enough_entitlements_in_base_org if all entitlements
    -- in the org are used so the free entitlements would not cover
    -- the difference when descreasing the number of entitlements.
    -- *******************************************************************
    create or replace function activate_system_entitlement(
        org_id_in in numeric,
        group_label_in in varchar,
        quantity_in in numeric
    ) returns void
as $$
    declare
        prev_ent_count numeric; 
        prev_ent_count_sum numeric; 
        group_type numeric;
    begin

        -- Fetch the current entitlement count for the org
        -- into prev_ent_count

            select current_members
            into prev_ent_count
            from rhnServerGroupType sgt,
                 rhnServerGroup sg
            where sg.group_type = sgt.id
              and sgt.label = group_label_in
              and sg.org_id = org_id_in;

            if not found then
                prev_ent_count := 0;
            end if;

            select id
            into group_type
            from rhnServerGroupType
            where label = group_label_in;

            if not found then
                perform rhn_exception.raise_exception(
                              'invalid_server_group');
            end if;

        -- If we're setting the total entitlemnt count to a lower value,
        -- and that value is less than the allocated count in this org,
        -- we need to raise an exception.
        if quantity_in < prev_ent_count then
            perform rhn_exception.raise_exception(
                          'not_enough_entitlements_in_base_org');
        else
            -- don't update family counts after every server
            -- will do bulk update afterwards
            perform rhn_entitlements.set_server_group_count(org_id_in,
                                             group_type,
                                             quantity_in,
                                             0);
            -- bulk update family counts
            perform rhn_channel.update_group_family_counts(group_label_in, org_id_in);
        end if;

    end$$
language plpgsql;

    -- *******************************************************************
    -- PROCEDURE: activate_channel_entitlement
    --
    -- Calls: set_family_count to update, prune, or create the family
    --        permission bucket.
    -- Called by: the code that activates a satellite cert. 
    --
    -- Raises not_enough_entitlements_in_base_org if there are not enough
    -- entitlements in the org to cover the difference when you are
    -- descreasing the number of entitlements.
    --
    -- The backend code in Python is expected to do whatever arithmetics
    -- is needed.
    -- *******************************************************************
    create or replace function activate_channel_entitlement(
        org_id_in in numeric,
        channel_family_label_in in varchar,
        quantity_in in numeric,
        flex_in in numeric
    ) returns void
as $$
    declare
        prev_ent_count numeric; 
        prev_flex_count numeric;
        prev_ent_count_sum numeric; 
        cfam_id numeric;
        reduce_quantity numeric;
        total_flex_capable numeric;
        to_convert_reg cursor (channel_family_id_val numeric, org_id_in numeric, quantity numeric) for
                     select SC.server_id
                     from rhnServerChannel SC inner join
                          rhnServer S on S.id = SC.server_id
                     where
                         is_fve = 'Y'
                         and S.org_id = org_id_in
                         and SC.channel_id in
                         (select cfm.channel_id from rhnChannelFamilyMembers cfm
                             where cfm.CHANNEL_FAMILY_ID = channel_family_id_val)
                         limit quantity;
         to_convert_flex cursor (channel_family_id_val numeric, org_id_in numeric, quantity numeric) for
                   select server_id
                   from rhnServerFveCapable
                       where SERVER_ORG_ID = org_id_in and
                             channel_family_id = cfam_id
                       limit quantity;

    begin

        -- Fetch the current entitlement count for the org
        -- into prev_ent_count
            select current_members
            into prev_ent_count
            from rhnChannelFamily cf,
                 rhnPrivateChannelFamily pcf
            where pcf.org_id = org_id_in
              and pcf.channel_family_id = cf.id
              and cf.label = channel_family_label_in;

            if not found then
                prev_ent_count := 0;
            end if;

            select pcf.fve_current_members
            into prev_flex_count
            from rhnChannelFamily cf,
                 rhnPrivateChannelFamily pcf
            where pcf.org_id = org_id_in
              and pcf.channel_family_id = cf.id
              and cf.label = channel_family_label_in;

            if not found then
                prev_flex_count := 0;
            end if;

            select id
            into cfam_id
            from rhnChannelFamily
            where label = channel_family_label_in;

            if not found then
                perform rhn_exception.raise_exception(
                              'invalid_channel_family');
            end if;

        -- if there are too few flex entitlements
        if flex_in < prev_flex_count then
            -- and if the extra we need is less than or equal to our extra regular entitlements
            if prev_flex_count - flex_in <= quantity_in - prev_ent_count then
                   reduce_quantity := prev_flex_count - flex_in;
                   -- We need to convert some systems from flex guest to regular
                   for system in to_convert_reg(cfam_id, org_id_in, reduce_quantity) loop
                      --rhn_channel.convert_to_regular(system.server_id, cfam_id);
                      UPDATE rhnServerChannel sc set is_fve = 'N'
                           where sc.server_id = system.server_id
                                 and sc.channel_id in (select cfm.channel_id
                                                          from rhnChannelFamilyMembers cfm
                                                          where cfm.channel_family_id = cfam_id);
                   end loop;

                   --reset previous counts
                   prev_ent_count := prev_ent_count + reduce_quantity;
                   prev_flex_count := prev_flex_count - reduce_quantity;
            else
                perform rhn_exception.raise_exception(
                          'not_enough_flex_entitlements_in_base_org');
            end if;
        end if;

        -- if there are too few regular entitlements, and extra flex entitlements
        if quantity_in < prev_ent_count and prev_flex_count < flex_in then
                -- how many flex-capable systems (that aren't using flex) do we have
                select count(*)
                   into total_flex_capable
                   from rhnServerFveCapable
                       where SERVER_ORG_ID = org_id_in and
                             channel_family_id = cfam_id;
                -- if we have enough flex capable machines that is at least
                --   as many as what we are over on
                if total_flex_capable >= prev_ent_count - quantity_in then
                    reduce_quantity := prev_ent_count - quantity_in;
                    for system in to_convert_flex(cfam_id, org_id_in, reduce_quantity) loop
--                          rhn_channel.convert_to_fve(system.server_id, cfam_id);
                        UPDATE rhnServerChannel sc set is_fve = 'Y'
                           where sc.server_id = system.server_id
                                 and sc.channel_id in (select cfm.channel_id
                                                          from rhnChannelFamilyMembers cfm
                                                          where cfm.channel_family_id = cfam_id);
                    end loop;
                    prev_ent_count := prev_ent_count - reduce_quantity;
                    prev_flex_count := prev_flex_count + reduce_quantity;
                end if;
        end if;

        -- If we're setting the total entitlemnt count to a lower value,
        -- and that value is less than the count in that one org,
        -- we need to raise an exception.
        if quantity_in < prev_ent_count then
            perform rhn_exception.raise_exception(
                          'not_enough_entitlements_in_base_org');
        else
            -- even if we've manually converted systems to/from flex above
            -- set_family_count should call update_family_counts, to reset
            -- current used slots
            perform rhn_entitlements.set_family_count(org_id_in, cfam_id,
                                              quantity_in, flex_in);
        end if;

    end$$
language plpgsql;

    create or replace function set_server_group_count (
        customer_id_in in numeric,  -- customer_id
        group_type_in in numeric,   -- rhn[User|Server]GroupType.id
        quantity_in in numeric,      -- quantity
                update_family_countsYN in numeric default 1
    ) returns void
as $$
    declare
        group_id numeric;
        quantity numeric;
        wasfound boolean;
    begin
        quantity := quantity_in;
        if quantity is not null and quantity < 0 then
            quantity := 0;
        end if;

        select  rsg.id
        into    group_id
        from    rhnServerGroup rsg
        where   1=1
            and rsg.org_id = customer_id_in
            and rsg.group_type = group_type_in;

        -- preserve the not found status across the rhn_entitlements.prune_group invocation
        wasfound := true;
        if not found then
            wasfound := false;
        end if;

        perform rhn_entitlements.prune_group(
            group_id,
            quantity,
                        update_family_countsYN
        );

        if not wasfound then
            insert into rhnServerGroup (
                    id, name, description, max_members, current_members,
                    group_type, org_id, created, modified
                ) (
                    select  nextval('rhn_server_group_id_seq'), name, name,
                            quantity, 0, id, customer_id_in,
                            current_timestamp, current_timestamp
                    from    rhnServerGroupType
                    where   id = group_type_in
            );
        end if;

    end$$
language plpgsql;

    -- *******************************************************************
    -- PROCEDURE: prune_family
    -- Unsubscribes servers consuming physical slots from the channel family 
    --   that are over the org's limit.
    -- Called by: set_family_count
    -- *******************************************************************
    create or replace function prune_family (
        customer_id_in in numeric,
        channel_family_id_in in numeric,
        quantity_in in numeric,
        flex_in in numeric
    ) returns void
as $$
    declare
        serverchannels cursor(tmp_quantity numeric, is_fve_in char) for
            select  sc.server_id,
                    sc.channel_id
            from    rhnServerChannel sc,
                    rhnChannelFamilyMembers cfm
            where   1=1
                and cfm.channel_family_id = channel_family_id_in
                and cfm.channel_id = sc.channel_id
                and server_id in (
                            select  rs.id as server_id
                            from    
                                    rhnServerChannel        rsc,
                                    rhnChannelFamilyMembers rcfm,
                                    rhnServer               rs
                            where   1=1
                                and rs.org_id = customer_id_in
                                and rs.id = rsc.server_id
                                and rsc.channel_id = rcfm.channel_id
                                and rcfm.channel_family_id =  channel_family_id_in
                                and rsc.is_fve = is_fve_in
                                -- we only want to grab servers consuming
                                -- physical slots.
                                and exists (
                                    select 1
                                    from rhnChannelFamilyServerPhysical cfsp
                                    where cfsp.server_id = rs.id
                                    and cfsp.channel_family_id = 
                                        channel_family_id_in
                                    )
                            order by rcfm.modified asc
                            offset quantity_in
                        );
    begin
        -- if we get a null customer_id, this is completely bogus.
        if customer_id_in is null then
            return;
        end if;

        for sc in serverchannels(quantity_in, 'N') loop
            perform rhn_channel.unsubscribe_server(sc.server_id, sc.channel_id,
                                                   1, 1, 0, 0);
        end loop;

        for sc in serverchannels(flex_in, 'Y') loop
            perform rhn_channel.unsubscribe_server(sc.server_id, sc.channel_id,
                                                   1, 1, 0, 0);
        end loop;

        perform rhn_channel.update_family_counts(channel_family_id_in, customer_id_in);
    end$$
language plpgsql;
        
    create or replace function set_family_count (
        customer_id_in in numeric,      -- customer_id
        channel_family_id_in in numeric,    -- 246
        quantity_in in numeric,          -- 3
        flex_in in numeric
    ) returns void
as $$
    declare
        privperms cursor for
            select  1
            from    rhnPrivateChannelFamily
            where   org_id = customer_id_in
                and channel_family_id = channel_family_id_in;
        pubperms cursor for
            select  o.id org_id
            from    web_customer o,
                    rhnPublicChannelFamily pcf
            where   pcf.channel_family_id = channel_family_id_in;
        quantity numeric;
        done numeric := 0;
        flex numeric;
    begin
        quantity := quantity_in;
        if quantity is not null and quantity < 0 then
            quantity := 0;
        end if;
        flex := flex_in;
        if flex is not null and flex < 0 then
            flex := 0;
        end if;

        if customer_id_in is not null then
            for perm in privperms loop
                perform rhn_entitlements.prune_family(
                    customer_id_in,
                    channel_family_id_in,
                    quantity,
                    flex
                );

                if quantity is null and flex is null then
                    delete from rhnPrivateChannelFamily
                        where org_id = customer_id_in
                            and channel_family_id = channel_family_id_in;
                 else
                    update rhnPrivateChannelFamily
                        set max_members = quantity
                        where org_id = customer_id_in
                            and channel_family_id = channel_family_id_in;

                   update rhnPrivateChannelFamily
                        set fve_max_members = flex
                        where org_id = customer_id_in
                            and channel_family_id = channel_family_id_in;
                end if;
                return;
            end loop;

            insert into rhnPrivateChannelFamily (
                    channel_family_id, org_id, max_members, current_members, fve_max_members, fve_current_members
                ) values (
                    channel_family_id_in, customer_id_in, quantity, 0, flex, 0 );
            return;
        end if;

        for perm in pubperms loop
            if quantity = 0 then
                perform rhn_entitlements.prune_family(
                    perm.org_id,
                    channel_family_id_in,
                    quantity,
                    flex
                );
                if done = 0 then
                    delete from rhnPublicChannelFamily
                        where channel_family_id = channel_family_id_in;
                end if;
            end if;
            done := 1;
        end loop;
        -- if done's not 1, then we don't have any entitlements
        if done != 1 then
            insert into rhnPublicChannelFamily (
                    channel_family_id
                ) values (
                    channel_family_id_in
                );
        end if;
    end$$
language plpgsql;

    -- this expects quantity_in to be the number of available slots, not the
    -- max_members of the server group.  If you give it too many, it'll fail
    -- and raise servergroup_max_members.
    -- We should NEVER run this unless we're SURE that we won't
    -- be violating the max.
    create or replace function entitle_last_modified_servers (
        customer_id_in in numeric,  -- customer_id
        type_label_in in varchar,   -- 'enterprise_entitled'
        quantity_in in numeric      -- 3
    ) returns void
as $$
    declare
        -- find the servers that aren't currently in slots
        servers cursor(cid_in numeric, quant_in numeric) for
                                    select  rs.id as server_id
                                    from    rhnServer rs
                                    where   1=1
                                        and rs.org_id = cid_in
                                        and not exists (
                                            select  1
                                            from    rhnServerGroup sg,
                                                    rhnServerGroupMembers rsgm
                                            where   rsgm.server_id = rs.id
                                                and rsgm.server_group_id = sg.id
                                                and sg.group_type is not null
                                        )
                                        and not exists (
                                            select 1
                                            from rhnVirtualInstance vi
                                            where vi.virtual_system_id =
                                                  rs.id
                                        )
                                    order by modified desc
                                    limit quant_in;
    begin
        for server in servers(customer_id_in, quantity_in) loop
            perform rhn_entitlements.entitle_server(server.server_id, type_label_in);
        end loop;
    end$$
language plpgsql;

    create or replace function subscribe_newest_servers (
        customer_id_in in numeric
    ) returns void
as $$
    declare
        -- find servers without base channels
        servers cursor(cid_in numeric) for
            select  s.id
            from    rhnServer           s
            where   1=1
                and s.org_id = cid_in
                and not exists (
                        select 1
                        from    rhnChannel          c,
                                rhnServerChannel    sc
                        where   sc.server_id = s.id
                            and sc.channel_id = c.id
                            and c.parent_channel is null
                    )
                and not exists (
                        select 1
                        from rhnVirtualInstance vi
                        where vi.virtual_system_id = s.id
                    )                        
            order by s.modified desc;
        channel_id numeric;
    begin
        for server in servers(customer_id_in) loop
            channel_id := rhn_channel.guess_server_base(server.id);
            if channel_id is not null then
                begin
                    perform rhn_channel.subscribe_server(server.id, channel_id);
                -- exception is really channel_family_no_subscriptions
                exception
                    when others then
                        null;
                end;
            end if;
        end loop;
    end$$
language plpgsql;


-- restore the original setting
update pg_settings set setting = overlay( setting placing '' from 1 for (length('rhn_entitlements')+1) ) where name = 'search_path';
   07070100000A4F000081B400000000000000000000000167AE111400000064000000000000000000000000000000000000006B00000000susemanager-schema/upgrade/susemanager-schema-1.7.57-to-susemanager-schema-2.1/4021-rhnKickstartScript.sql    update rhnkickstartscript set position = position * -1 where script_type = 'post' and chroot = 'N';
07070100000A50000081B400000000000000000000000167AE111400000108000000000000000000000000000000000000007800000000susemanager-schema/upgrade/susemanager-schema-1.7.57-to-susemanager-schema-2.1/4034-rhnServerNeededCache-channel_id.sql   

ALTER TABLE rhnServerNeededCache ADD
        channel_id NUMERIC
                CONSTRAINT rhn_sncp_cid_fk
                REFERENCES rhnChannel (id)
                ON DELETE CASCADE;

CREATE INDEX rhn_snc_cid_idx
    ON rhnServerNeededCache (channel_id)
    ;
07070100000A51000081B400000000000000000000000167AE111400000767000000000000000000000000000000000000006700000000susemanager-schema/upgrade/susemanager-schema-1.7.57-to-susemanager-schema-2.1/4035-rhn_server.pkb.sql    

update pg_settings set setting = 'rhn_server,' || setting where name = 'search_path';

    create or replace function update_needed_cache(
        server_id_in in numeric
	) returns void as $$
    begin
      delete from rhnServerNeededCache
        where server_id = server_id_in;
      insert into rhnServerNeededCache
             (server_id, errata_id, package_id, channel_id)
        (select distinct sp.server_id, x.errata_id, p.id, x.channel_id
           FROM (SELECT sp_sp.server_id, sp_sp.name_id,
		        sp_sp.package_arch_id, max(sp_pe.evr) AS max_evr
                   FROM rhnServerPackage sp_sp
                   join rhnPackageEvr sp_pe ON sp_pe.id = sp_sp.evr_id
                  GROUP BY sp_sp.server_id, sp_sp.name_id, sp_sp.package_arch_id) sp
           join rhnPackage p ON p.name_id = sp.name_id
           join rhnPackageEvr pe ON pe.id = p.evr_id AND sp.max_evr < pe.evr
           join rhnPackageUpgradeArchCompat puac
	            ON puac.package_arch_id = sp.package_arch_id
		    AND puac.package_upgrade_arch_id = p.package_arch_id
           join rhnServerChannel sc ON sc.server_id = sp.server_id
           join rhnChannelPackage cp ON cp.package_id = p.id
	            AND cp.channel_id = sc.channel_id
           left join (SELECT ep.errata_id, ce.channel_id, ep.package_id
                        FROM rhnChannelErrata ce
                        join rhnErrataPackage ep
			         ON ep.errata_id = ce.errata_id
			join rhnServerChannel sc_sc
			         ON sc_sc.channel_id = ce.channel_id
		       WHERE sc_sc.server_id = server_id_in) x
             ON x.channel_id = sc.channel_id AND x.package_id = cp.package_id
          where sp.server_id = server_id_in);
	end$$ language plpgsql;

-- restore the original setting
update pg_settings set setting = overlay( setting placing '' from 1 for (length('rhn_server')+1) ) where name = 'search_path';
 07070100000A52000081B400000000000000000000000167AE1114000019BA000000000000000000000000000000000000006000000000susemanager-schema/upgrade/susemanager-schema-1.7.57-to-susemanager-schema-2.1/4036-armv6hl.sql   insert into rhnCpuArch (id, label, name) select
sequence_nextval('rhn_cpu_arch_id_seq'), 'armv6hl', 'ARMv6hl' from dual
where not exists (select 1 from rhnCpuArch where label = 'armv6hl');


insert into rhnPackageArch (id, label, name, arch_type_id) select
sequence_nextval('rhn_package_arch_id_seq'), 'armv6hl', 'ARMv6hl', lookup_arch_type('rpm') from dual
where not exists (select 1 from rhnPackageArch where label = 'armv6hl');


insert into rhnServerArch (id, label, name, arch_type_id) select
sequence_nextval('rhn_server_arch_id_seq'), 'armv6hl-redhat-linux', 'armv6hl', lookup_arch_type('rpm') from dual
where not exists (select 1 from rhnServerArch where label = 'armv6hl-redhat-linux');


insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) select
LOOKUP_PACKAGE_ARCH('noarch'), LOOKUP_PACKAGE_ARCH('armv6hl'), current_timestamp, current_timestamp from dual
where not exists (select 1 from rhnPackageUpgradeArchCompat where package_arch_id = LOOKUP_PACKAGE_ARCH('noarch') and package_upgrade_arch_id = LOOKUP_PACKAGE_ARCH('armv6hl'));

insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) select
LOOKUP_PACKAGE_ARCH('armv6hl'), LOOKUP_PACKAGE_ARCH('armv6hl'), current_timestamp, current_timestamp from dual
where not exists (select 1 from rhnPackageUpgradeArchCompat where package_arch_id = LOOKUP_PACKAGE_ARCH('armv6hl') and package_upgrade_arch_id = LOOKUP_PACKAGE_ARCH('armv6hl'));

insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) select
LOOKUP_PACKAGE_ARCH('armv6hl'), LOOKUP_PACKAGE_ARCH('noarch'), current_timestamp, current_timestamp from dual
where not exists (select 1 from rhnPackageUpgradeArchCompat where package_arch_id = LOOKUP_PACKAGE_ARCH('armv6hl') and package_upgrade_arch_id = LOOKUP_PACKAGE_ARCH('noarch'));


insert into rhnChannelPackageArchCompat (channel_arch_id, package_arch_id) select
LOOKUP_CHANNEL_ARCH('channel-arm'), LOOKUP_PACKAGE_ARCH('armv6hl') from dual
where not exists (select 1 from rhnChannelPackageArchCompat where channel_arch_id = LOOKUP_CHANNEL_ARCH('channel-arm') and package_arch_id = LOOKUP_PACKAGE_ARCH('armv6hl'));


insert into rhnServerChannelArchCompat (server_arch_id, channel_arch_id) select
LOOKUP_SERVER_ARCH('armv6hl-redhat-linux'), LOOKUP_CHANNEL_ARCH('channel-arm') from dual
where not exists (select 1 from rhnServerChannelArchCompat where server_arch_id = LOOKUP_SERVER_ARCH('armv6hl-redhat-linux') and channel_arch_id = LOOKUP_CHANNEL_ARCH('channel-arm'));

insert into rhnServerPackageArchCompat (server_arch_id, package_arch_id, preference) select
LOOKUP_SERVER_ARCH('armv7l-redhat-linux'), LOOKUP_PACKAGE_ARCH('armv6hl'), 25 from dual
where not exists (select 1 from rhnServerPackageArchCompat where server_arch_id = LOOKUP_SERVER_ARCH('armv7l-redhat-linux') and package_arch_id = LOOKUP_PACKAGE_ARCH('armv6hl'));

insert into rhnServerPackageArchCompat (server_arch_id, package_arch_id, preference) select
LOOKUP_SERVER_ARCH('armv6hl-redhat-linux'), LOOKUP_PACKAGE_ARCH('armv6hl'), 0 from dual
where not exists (select 1 from rhnServerPackageArchCompat where server_arch_id = LOOKUP_SERVER_ARCH('armv6hl-redhat-linux'));

insert into rhnServerPackageArchCompat (server_arch_id, package_arch_id, preference) select
LOOKUP_SERVER_ARCH('armv6hl-redhat-linux'), LOOKUP_PACKAGE_ARCH('armv6l'), 10 from dual
where not exists (select 1 from rhnServerPackageArchCompat where server_arch_id = LOOKUP_SERVER_ARCH('armv6hl-redhat-linux') and package_arch_id = LOOKUP_PACKAGE_ARCH('armv6l'));

insert into rhnServerPackageArchCompat (server_arch_id, package_arch_id, preference) select
LOOKUP_SERVER_ARCH('armv6hl-redhat-linux'), LOOKUP_PACKAGE_ARCH('armv5tel'), 20 from dual
where not exists (select 1 from rhnServerPackageArchCompat where server_arch_id = LOOKUP_SERVER_ARCH('armv6hl-redhat-linux') and package_arch_id = LOOKUP_PACKAGE_ARCH('armv5tel'));

insert into rhnServerPackageArchCompat (server_arch_id, package_arch_id, preference) select
LOOKUP_SERVER_ARCH('armv6hl-redhat-linux'), LOOKUP_PACKAGE_ARCH('noarch'), 1000 from dual
where not exists (select 1 from rhnServerPackageArchCompat where server_arch_id = LOOKUP_SERVER_ARCH('armv6hl-redhat-linux') and package_arch_id = LOOKUP_PACKAGE_ARCH('noarch'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type ) select
lookup_server_arch('armv6hl-redhat-linux'), lookup_sg_type('sw_mgr_entitled') from dual
where not exists (select 1 from rhnServerServerGroupArchCompat where server_arch_id = lookup_server_arch('armv6hl-redhat-linux') and server_group_type = lookup_sg_type('sw_mgr_entitled'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type ) select
lookup_server_arch('armv6hl-redhat-linux'), lookup_sg_type('enterprise_entitled') from dual
where not exists (select 1 from rhnServerServerGroupArchCompat where server_arch_id = lookup_server_arch('armv6hl-redhat-linux') and server_group_type = lookup_sg_type('enterprise_entitled'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type ) select
lookup_server_arch('armv6hl-redhat-linux'), lookup_sg_type('provisioning_entitled') from dual
where not exists (select 1 from rhnServerServerGroupArchCompat where server_arch_id = lookup_server_arch('armv6hl-redhat-linux') and server_group_type = lookup_sg_type('provisioning_entitled'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type ) select
lookup_server_arch('armv6hl-redhat-linux'), lookup_sg_type('monitoring_entitled') from dual
where not exists (select 1 from rhnServerServerGroupArchCompat where server_arch_id = lookup_server_arch('armv6hl-redhat-linux') and server_group_type = lookup_sg_type('monitoring_entitled'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type ) select
lookup_server_arch('armv6hl-redhat-linux'), lookup_sg_type('virtualization_host') from dual
where not exists (select 1 from rhnServerServerGroupArchCompat where server_arch_id = lookup_server_arch('armv6hl-redhat-linux') and server_group_type = lookup_sg_type('virtualization_host'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type ) select
lookup_server_arch('armv6hl-redhat-linux'), lookup_sg_type('virtualization_host_platform') from dual
where not exists (select 1 from rhnServerServerGroupArchCompat where server_arch_id = lookup_server_arch('armv6hl-redhat-linux') and server_group_type = lookup_sg_type('virtualization_host_platform'));
  07070100000A53000081B400000000000000000000000167AE11140000003C000000000000000000000000000000000000006F00000000susemanager-schema/upgrade/susemanager-schema-1.7.57-to-susemanager-schema-2.1/4040-inc-length-rhnCVE-name.sql    
ALTER TABLE rhnCVE
    ALTER COLUMN name TYPE varchar(20);
07070100000A54000081B400000000000000000000000167AE11140000046F000000000000000000000000000000000000006900000000susemanager-schema/upgrade/susemanager-schema-1.7.57-to-susemanager-schema-2.1/4040-rhnConfiguration.sql  --
-- Copyright (c) 2014 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

CREATE TABLE rhnConfiguration
(
    key                     VARCHAR(64) NOT NULL
                                CONSTRAINT rhnConfig_key_pk PRIMARY KEY,
    description             VARCHAR(512) NOT NULL,
    value                   VARCHAR(512),
    default_value           VARCHAR(512),
    created                 TIMESTAMPTZ
                                DEFAULT (current_timestamp) NOT NULL,
    modified                TIMESTAMPTZ
                                DEFAULT (current_timestamp) NOT NULL
)

;
 07070100000A55000081B400000000000000000000000167AE11140000039C000000000000000000000000000000000000007100000000susemanager-schema/upgrade/susemanager-schema-1.7.57-to-susemanager-schema-2.1/4041-rhnConfiguration-trigger.sql  --
-- Copyright (c) 2014 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

create or replace function rhn_conf_mod_trig_fun() returns trigger as
$$
begin
        new.modified := current_timestamp;
        return new;
end;
$$ language plpgsql;

create trigger
rhn_conf_mod_trig
before insert or update on rhnConfiguration
for each row
execute procedure rhn_conf_mod_trig_fun();
07070100000A56000081B400000000000000000000000167AE111400000163000000000000000000000000000000000000006E00000000susemanager-schema/upgrade/susemanager-schema-1.7.57-to-susemanager-schema-2.1/4042-rhnConfiguration-data.sql INSERT INTO rhnConfiguration (key, description) VALUES ('extauth_default_orgid', 'Organization id, where externally authenticated users will be created.');
INSERT INTO rhnConfiguration (key, description, default_value) VALUES ('extauth_use_orgunit', 'Use Org. Unit IPA setting as organization name to create externally authenticated users in.', 'false');
 07070100000A57000081B400000000000000000000000167AE111400000449000000000000000000000000000000000000006800000000susemanager-schema/upgrade/susemanager-schema-1.7.57-to-susemanager-schema-2.1/4043-rhnUserExtGroup.sql   --
-- Copyright (c) 2014 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnUserExtGroup
(
    id        NUMERIC NOT NULL
                  CONSTRAINT rhn_userExtGroup_id_pk PRIMARY KEY
                  ,
    label     VARCHAR(512) NOT NULL,
    created   TIMESTAMPTZ
                  DEFAULT (current_timestamp) NOT NULL,
    modified  TIMESTAMPTZ
                  DEFAULT (current_timestamp) NOT NULL
)

;

CREATE UNIQUE INDEX rhn_userextgroup_label_uq
    ON rhnUserExtGroup (label)
    ;

CREATE SEQUENCE rhn_userextgroup_seq;
   07070100000A58000081B400000000000000000000000167AE1114000003AA000000000000000000000000000000000000007000000000susemanager-schema/upgrade/susemanager-schema-1.7.57-to-susemanager-schema-2.1/4044-rhnUserExtGroup-trigger.sql   --
-- Copyright (c) 2014 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

create or replace function rhn_userextgr_mod_trig_fun() returns trigger as
$$
begin
        new.modified := current_timestamp;
        return new;
end;
$$ language plpgsql;

create trigger
rhn_userextgr_mod_trig
before insert or update on rhnUserExtGroup
for each row
execute procedure rhn_userextgr_mod_trig_fun();
  07070100000A59000081B400000000000000000000000167AE1114000005C2000000000000000000000000000000000000006F00000000susemanager-schema/upgrade/susemanager-schema-1.7.57-to-susemanager-schema-2.1/4045-rhnUserExtGroupMapping.sql    --
-- Copyright (c) 2014 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnUserExtGroupMapping
(
    id        NUMERIC NOT NULL
                  CONSTRAINT rhn_userExtGroupMap_id_pk PRIMARY KEY
                  ,
    ext_group_id        NUMERIC NOT NULL
                  constraint rhn_userextgroupmap_e_fk
                  references rhnUserExtGroup(id)
                  on delete cascade,
    int_group_type_id        NUMERIC NOT NULL
                  constraint rhn_userextgroupmap_i_fk
                  references rhnUserGroupType(id)
                  on delete cascade,
    created   TIMESTAMPTZ
                  DEFAULT (current_timestamp) NOT NULL,
    modified  TIMESTAMPTZ
                  DEFAULT (current_timestamp) NOT NULL
)

;

CREATE UNIQUE INDEX rhn_userextgroupmap_ei_uq
    ON rhnUserExtGroupMapping (ext_group_id, int_group_type_id)
    ;

CREATE SEQUENCE rhn_userextgroupmap_seq;
  07070100000A5A000081B400000000000000000000000167AE111400000423000000000000000000000000000000000000007700000000susemanager-schema/upgrade/susemanager-schema-1.7.57-to-susemanager-schema-2.1/4046-rhnUserExtGroupMapping-trigger.sql    --
-- Copyright (c) 2014 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

create or replace function rhn_userextgrmap_mod_trig_fun() returns trigger as
$$
begin
        if new.id is null then
            new.id := nextval('rhn_userextgroupmap_seq');
        end if;
        new.modified := current_timestamp;
        return new;
end;
$$ language plpgsql;

create trigger
rhn_userextgrmap_mod_trig
before insert or update on rhnUserExtGroupMapping
for each row
execute procedure rhn_userextgrmap_mod_trig_fun();
 07070100000A5B000081B400000000000000000000000167AE1114000000DD000000000000000000000000000000000000006A00000000susemanager-schema/upgrade/susemanager-schema-1.7.57-to-susemanager-schema-2.1/4047-rhnPackageKey-f20.sql insert
  into rhnPackageKey (id, key_id, key_type_id, provider_id)
values (sequence_nextval('rhn_pkey_id_seq'),
       '2eb161fa246110c1',
       lookup_package_key_type('gpg'),
       lookup_package_provider('Fedora'));
   07070100000A5C000081B400000000000000000000000167AE11140000BBB8000000000000000000000000000000000000006800000000susemanager-schema/upgrade/susemanager-schema-1.7.57-to-susemanager-schema-2.1/4048-rhn_channel.pkb.sql   --
-- Copyright (c) 2008--2013 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--

-- create schema rhn_channel;

--update pg_setting
update pg_settings set setting = 'rhn_channel,' || setting where name = 'search_path';

    create or replace function obtain_read_lock(channel_family_id_in in numeric, org_id_in in numeric)
    returns void as $$
    declare
        read_lock timestamptz;
    begin
        select created into read_lock
          from rhnPrivateChannelFamily
         where channel_family_id = channel_family_id_in and org_id = org_id_in
           for update;
    end$$ language plpgsql;

    -- this "emulates" cursor server_base_subscriptions defined in oracle/rhn_channel.pks
    create or replace function server_base_subscriptions(server_id_in NUMERIC)
    returns boolean as $$
    begin
      return exists(SELECT C.id FROM rhnChannel C, rhnServerChannel SC
		    WHERE C.id = SC.channel_id
		      AND SC.server_id = server_id_in
		      AND C.parent_channel IS NULL);
    end$$ language plpgsql;

    -- this "emulates" cursor server_base_subscriptions defined in oracle/rhn_channel.pks
    create or replace function check_server_subscription(server_id_in NUMERIC, channel_id_in NUMERIC)
    returns boolean as $$
    begin
      return exists(SELECT channel_id FROM rhnServerChannel WHERE server_id = server_id_in AND channel_id = channel_id_in);
    end$$ language plpgsql;


    CREATE OR REPLACE FUNCTION subscribe_server(server_id_in IN NUMERIC, channel_id_in NUMERIC, immediate_in NUMERIC default 1, user_id_in in numeric default null, recalcfamily_in NUMERIC default 1) returns void
    AS $$
    declare
        channel_parent_val      rhnChannel.parent_channel%TYPE;
        parent_subscribed       BOOLEAN;
        server_has_base_chan    BOOLEAN;
        server_already_in_chan  BOOLEAN;
        channel_family_id_val   NUMERIC;
        server_org_id_val       NUMERIC;
        available_subscriptions NUMERIC;
        available_fve_subs      numeric;
        consenting_user         NUMERIC;
        allowed                 numeric;
        is_fve_char             char(1) := 'N';
    BEGIN
        if user_id_in is not null then
            allowed := rhn_channel.user_role_check(channel_id_in, user_id_in, 'subscribe');
        else
            allowed := 1;
        end if;

        if allowed = 0 then
            perform rhn_exception.raise_exception('no_subscribe_permissions');
        end if;


        SELECT parent_channel INTO channel_parent_val FROM rhnChannel WHERE id = channel_id_in;

        IF channel_parent_val IS NOT NULL
        THEN    
            -- child channel; if attempting to cross-subscribe a child to the wrong base, silently ignore
            parent_subscribed := rhn_channel.check_server_subscription(server_id_in, channel_parent_val);
        
            IF NOT parent_subscribed
            THEN
                RETURN;
            END IF;
        ELSE
            -- base channel
            server_has_base_chan := rhn_channel.server_base_subscriptions(server_id_in);
            
            IF server_has_base_chan
            THEN
                perform rhn_exception.raise_exception('channel_server_one_base');
            END IF;
        END IF;

        server_already_in_chan := rhn_channel.check_server_subscription(server_id_in, channel_id_in);
    
        IF server_already_in_chan
        THEN
            RETURN;
        END IF;
        
        channel_family_id_val := rhn_channel.family_for_channel(channel_id_in);
        IF channel_family_id_val IS NULL
        THEN
            perform rhn_exception.raise_exception('channel_subscribe_no_family');
        END IF;

        --
        -- Use the org_id of the server only if the org_id of the channel = NULL.
        -- This is required for subscribing to shared channels.
        --
        SELECT COALESCE(org_id, (SELECT org_id FROM rhnServer WHERE id = server_id_in))
          INTO server_org_id_val
          FROM rhnChannel
         WHERE id = channel_id_in;
         
        begin
            perform rhn_channel.obtain_read_lock(channel_family_id_val, server_org_id_val);
        exception
            when no_data_found then
                perform rhn_exception.raise_exception('channel_family_no_subscriptions');
        end;

        available_subscriptions := rhn_channel.available_family_subscriptions(channel_family_id_val, server_org_id_val);
        available_fve_subs := rhn_channel.available_fve_family_subs(channel_family_id_val, server_org_id_val);
        
        IF available_subscriptions IS NULL OR 
           available_subscriptions > 0 or
           rhn_channel.can_server_consume_virt_channl(server_id_in, channel_family_id_val) = 1 OR
           (available_fve_subs > 0 AND rhn_channel.can_server_consume_fve(server_id_in) = 1) OR
           rhn_channel.server_has_family_subscription(server_id_in, channel_family_id_val) > 0
        THEN
            if rhn_channel.can_server_consume_virt_channl(server_id_in, channel_family_id_val) = 0 AND available_fve_subs > 0 AND rhn_channel.can_server_consume_fve(server_id_in) = 1 THEN
                is_fve_char := 'Y';
            end if;

            insert into rhnServerHistory (id,server_id,summary,details) (
                select  nextval('rhn_event_id_seq'),
                        server_id_in,
                        'subscribed to channel ' || SUBSTR(c.label, 0, 106),
                        c.label
                from    rhnChannel c
                where   c.id = channel_id_in
            );

            INSERT INTO rhnServerChannel (server_id, channel_id, is_fve) VALUES (server_id_in, channel_id_in, is_fve_char);
			IF recalcfamily_in > 0
			THEN
                perform rhn_channel.update_family_counts(channel_family_id_val, server_org_id_val);
			END IF;

            perform queue_server(server_id_in, immediate_in);

            update rhnServer
               set channels_changed = current_timestamp
             where id = server_id_in;
        ELSE
            perform rhn_exception.raise_exception('channel_family_no_subscriptions');
        END IF;
            
    END$$ language plpgsql;



    create or replace function can_convert_to_fve(server_id_in IN NUMERIC, channel_family_id_val IN NUMERIC)
    RETURNS NUMERIC
    as $$
    declare
        fve_convertible_entries cursor for
        select 1  from
            rhnServerFveCapable cap
          where cap.server_id = server_id_in
                AND cap.channel_family_id = channel_family_id_val;
    BEGIN
        FOR entry IN fve_convertible_entries LOOP
            return 1;
        END LOOP;
        RETURN 0;
    END$$ language plpgsql;



    -- Converts server channel_family to use a flex entitlement
    create or replace function convert_to_fve(server_id_in IN NUMERIC, channel_family_id_val IN NUMERIC)
    returns void
    as $$
    declare
        available_fve_subs      NUMERIC;
        server_org_id_val       NUMERIC;
    BEGIN

        --
        -- Use the org_id of the server only if the org_id of the channel = NULL.
        -- This is required for subscribing to shared channels.
        --
        SELECT org_id
          INTO server_org_id_val
          FROM rhnServer
         WHERE id = server_id_in;


        perform rhn_channel.obtain_read_lock(channel_family_id_val, server_org_id_val);
        if not found then
                perform rhn_exception.raise_exception('channel_family_no_subscriptions');
        end if;
        IF (rhn_channel.can_convert_to_fve(server_id_in, channel_family_id_val ) = 0)
            THEN
                perform rhn_exception.raise_exception('server_cannot_convert_to_flex');
        END IF;

        available_fve_subs := rhn_channel.available_fve_family_subs(channel_family_id_val, server_org_id_val);

        IF (available_fve_subs > 0)
        THEN

            insert into rhnServerHistory (id,server_id,summary,details) (
                select  nextval('rhn_event_id_seq'),
                        server_id_in,
                        'converted to flex entitlement' || SUBSTR(cf.label, 0, 99),
                        cf.label
                from    rhnChannelFamily cf
                where   cf.id = channel_family_id_val
            );

            UPDATE rhnServerChannel sc set is_fve = 'Y'
                           where sc.server_id = server_id_in and
                                 sc.channel_id in
                                    (select cfm.channel_id from rhnChannelFamilyMembers cfm
                                                where cfm.CHANNEL_FAMILY_ID = channel_family_id_val);

            perform rhn_channel.update_family_counts(channel_family_id_val, server_org_id_val);
        ELSE
            perform rhn_exception.raise_exception('not_enough_flex_entitlements');
        END IF;

    END$$ language plpgsql;
    
    create or replace function can_server_consume_virt_channl(
        server_id_in in numeric,
        family_id_in in numeric )
    returns numeric
    as $$
    begin
      if exists(
            select 1
            from
                rhnChannelFamilyVirtSubLevel cfvsl,
                rhnSGTypeVirtSubLevel sgtvsl,
                rhnVirtualInstance vi
            where
                vi.virtual_system_id = server_id_in 
                and sgtvsl.virt_sub_level_id = cfvsl.virt_sub_level_id
                and cfvsl.channel_family_id = family_id_in
                and exists (
                    select 1
                    from rhnServerEntitlementView sev
                    where vi.host_system_id = sev.server_id
                    and sev.server_group_type_id = sgtvsl.server_group_type_id ))
      then
        return 1;
      else
        return 0;
      end if;
    end$$ language plpgsql;

    create or replace function can_server_consume_fve(server_id_in in numeric) returns numeric
    as $$
    declare
        vi_entries cursor for
            SELECT 1
              FROM rhnVirtualInstance vi
             WHERE vi.virtual_system_id = server_id_in;
        vi_count numeric;

    begin
        FOR vi_entry IN VI_ENTRIES LOOP
            return 1;
        END LOOP;
        RETURN 0;
    end$$ language plpgsql;

    create or replace function guess_server_base(
        server_id_in in numeric
    ) RETURNS numeric as $$
    declare
        server_cursor cursor for
            select s.server_arch_id, s.release, s.org_id
              from rhnServer s
             where s.id = server_id_in;
    -- Cursor that fetches all the possible base channels for a
    -- (server_arch_id, release, org_id) combination
        base_channel_cursor cursor(
                release_in varchar,
                server_arch_id_in numeric,
                org_id_in numeric
        ) for
                select distinct c.*
                from    rhnOrgDistChannelMap                       odcm,
                                rhnServerChannelArchCompat      scac,
                                rhnChannel                                      c
                where   c.parent_channel is null
                        and c.id = odcm.channel_id
                        and c.channel_arch_id = odcm.channel_arch_id
                        and odcm.release = release_in
                        and odcm.for_org_id = org_id_in
                        and scac.server_arch_id = server_arch_id_in
                        and scac.channel_arch_id = c.channel_arch_id;

    begin
        for s in server_cursor loop
            for channel in base_channel_cursor(s.release,
                s.server_arch_id, s.org_id) 
            loop
                return channel.id;
            end loop;
        end loop;
        -- Server not found, or no base channel applies to it
        return null;
    end$$ language plpgsql;

    -- Private function
    create or replace function normalize_server_arch(server_arch_in in varchar)
    returns varchar
    as $$
    declare
        suffix VARCHAR(128) := '-redhat-linux';
    begin
        if server_arch_in is NULL then
            return NULL;
        end if;
        if position('-' IN server_arch_in) > 0
        then
            -- Suffix already present
            return server_arch_in;
        end if;
        return server_arch_in || suffix;
    end$$ language plpgsql;

    --
    -- Raises: 
    --   server_arch_not_found
    --   no_subscribe_permissions
    create or replace function base_channel_for_release_arch(
        release_in in varchar,
        server_arch_in in varchar,
        org_id_in in numeric default -1,
        user_id_in in numeric default null
    ) returns numeric as $$
    declare
        server_arch varchar(256) := rhn_channel.normalize_server_arch(server_arch_in);
        server_arch_id numeric;
    begin
        -- Look up the server arch
            select id
              into server_arch_id
              from rhnServerArch
             where label = server_arch;
            if not found then
                perform rhn_exception.raise_exception('server_arch_not_found');
            end if;

        return rhn_channel.base_channel_rel_archid(release_in, server_arch_id,
            org_id_in, user_id_in);
    end$$ language plpgsql;

    create or replace function base_channel_rel_archid(
        release_in in varchar,
        server_arch_id_in in numeric,
        org_id_in in numeric default -1,
        user_id_in in numeric default null
    ) returns numeric as $$
    declare
        denied_channel_id numeric := null;
        valid_org_id numeric := org_id_in;
        valid_user_id numeric := user_id_in;
        channel_subscribable numeric;
    -- Cursor that fetches all the possible base channels for a
    -- (server_arch_id, release, org_id) combination
        base_channel_cursor cursor(
                release_in varchar,
                server_arch_id_in numeric,
                org_id_in numeric
        ) for
                select distinct c.*
                from    rhnOrgDistChannelMap                       odcm,
                                rhnServerChannelArchCompat      scac,
                                rhnChannel                                      c
                where   c.parent_channel is null
                        and c.id = odcm.channel_id
                        and c.channel_arch_id = odcm.channel_arch_id
                        and odcm.release = release_in
                        and odcm.for_org_id = org_id_in
                        and scac.server_arch_id = server_arch_id_in
                        and scac.channel_arch_id = c.channel_arch_id;

    begin
        if org_id_in = -1 and user_id_in is not null then
            -- Get the org id from the user id

                select org_id
                  into valid_org_id
                  from web_contact
                 where id = user_id_in;

                if not found then
                    -- User doesn't exist
                    -- XXX Only list public stuff for now
                    valid_user_id := null;
                    valid_org_id := -1;
                end if;
        end if;

        for c in base_channel_cursor(release_in, server_arch_id_in, valid_org_id)
        loop
            -- This row is a possible match
            if valid_user_id is null then
                -- User ID not specified, so no user to channel permissions to
                -- check
                return c.id;
            end if;

            -- Check user to channel permissions
            select rhn_channel.loose_user_role_check(c.id, user_id_in, 'subscribe')
              into channel_subscribable;

            if channel_subscribable = 1 then
                return c.id;
            end if;
                
            -- Base channel exists, but is not subscribable; keep trying
            denied_channel_id := c.id;
        end loop;
        
        if denied_channel_id is not null then
            perform rhn_exception.raise_exception('no_subscribe_permissions');
        end if;
        -- No base channel applies
        return NULL;
    end$$ language plpgsql;

    CREATE OR REPLACE FUNCTION clear_subscriptions(server_id_in IN NUMERIC, deleting_server IN NUMERIC default 0,
                                update_family_countsYN IN NUMERIC default 1 ) returns void
    AS $$
    declare
        server_channels cursor(server_id_in numeric) for
                select  s.org_id, sc.channel_id, cfm.channel_family_id
                from    rhnServer s,
                        rhnServerChannel sc,
                        rhnChannelFamilyMembers cfm
                where   s.id = server_id_in
                        and s.id = sc.server_id
                        and sc.channel_id = cfm.channel_id
                order by cfm.channel_family_id;
        last_channel_family_id rhnChannelFamilyMembers.channel_family_id%type := -1;
        last_channel_org_id    rhnServer.org_id%type := -1;
    BEGIN
        for channel in server_channels(server_id_in)
        loop
                perform rhn_channel.unsubscribe_server(server_id_in, channel.channel_id, 1, 1, deleting_server, 0);
                if update_family_countsYN > 0
                    and channel.channel_family_id != last_channel_family_id then
                    -- update family counts only once
                    -- after all channels with same family has been fetched
                    if last_channel_family_id != -1 then
                        perform rhn_channel.update_family_counts(channel.channel_family_id, channel.org_id);
                    end if;
                    last_channel_family_id := channel.channel_family_id;
                    last_channel_org_id    := channel.org_id;
                end if;
        end loop;
        if update_family_countsYN > 0 and last_channel_family_id != -1 then
            -- update the last family fetched
            perform rhn_channel.update_family_counts(last_channel_family_id, last_channel_org_id);
        end if;
    END$$ language plpgsql;

    CREATE OR REPLACE FUNCTION unsubscribe_server(server_id_in IN NUMERIC, channel_id_in NUMERIC, immediate_in NUMERIC default 1, unsubscribe_children_in numeric default 0,
                                 deleting_server in numeric default 0,
                                 update_family_countsYN in numeric default 1) returns void
    AS $$
    declare
        channel_family_id_val   NUMERIC;
        server_org_id_val       NUMERIC;
        available_subscriptions NUMERIC; 
        server_already_in_chan  BOOLEAN;
        channel_family_is_proxy cursor(channel_family_id_in numeric) for
                select  1
                from    rhnChannelFamily
                where   id = channel_family_id_in
                    and label = 'rhn-proxy';
        channel_family_is_satellite cursor(channel_family_id_in numeric) for
                select  1
                from    rhnChannelFamily
                where   id = channel_family_id_in
                    and label = 'rhn-satellite';
        child record;
    BEGIN
        -- In PostgreSQL recursion with opened cursors is not allowed so we use
        -- FOR IN SELECT form which is ok.
        FOR child IN select  c.id
                from    rhnChannel                      c,
                                rhnServerChannel        sc
                where   1=1
                        and c.parent_channel = channel_id_in
                        and c.id = sc.channel_id
                        and sc.server_id = server_id_in
        LOOP
            if unsubscribe_children_in = 1 then
                perform rhn_channel.unsubscribe_server(server_id_in,
                                                       child.id,
                                                       immediate_in,
                                                       unsubscribe_children_in,
                                                       deleting_server,
                                                       update_family_countsYN);
            else
                perform rhn_exception.raise_exception('channel_unsubscribe_child_exists');
            end if;
        END LOOP;
        
        server_already_in_chan := rhn_channel.check_server_subscription(server_id_in, channel_id_in);
    
        IF NOT server_already_in_chan
        THEN
            RETURN;
        END IF;
        
   if deleting_server = 0 then 
      insert into rhnServerHistory (id,server_id,summary,details) (
          select  nextval('rhn_event_id_seq'),
                server_id_in,
             'unsubscribed from channel ' || SUBSTR(c.label, 0, 106),
             c.label
          from    rhnChannel c
          where   c.id = channel_id_in
      );
   end if;
        
   DELETE FROM rhnServerChannel WHERE server_id = server_id_in AND channel_id = channel_id_in;

   if deleting_server = 0 then 
        perform queue_server(server_id_in, immediate_in);

        update rhnServer
           set channels_changed = current_timestamp
         where id = server_id_in;
   end if;

        channel_family_id_val := rhn_channel.family_for_channel(channel_id_in);
        IF channel_family_id_val IS NULL
        THEN
            perform rhn_exception.raise_exception('channel_unsubscribe_no_family');
        END IF;

        for ignore in channel_family_is_satellite(channel_family_id_val) loop
                delete from rhnSatelliteInfo where server_id = server_id_in;
        end loop;

        for ignore in channel_family_is_proxy(channel_family_id_val) loop
                delete from rhnProxyInfo where server_id = server_id_in;
        end loop;
        SELECT org_id INTO server_org_id_val
          FROM rhnServer
         WHERE id = server_id_in;
         
        if update_family_countsYN = 1 then
           perform rhn_channel.update_family_counts(channel_family_id_val, server_org_id_val);
        end if;
    END$$ language plpgsql;

    CREATE OR REPLACE FUNCTION family_for_channel(channel_id_in IN NUMERIC)
    RETURNS NUMERIC
    AS $$
    declare
        channel_family_id_val NUMERIC;
    BEGIN
        SELECT channel_family_id INTO channel_family_id_val
          FROM rhnChannelFamilyMembers
         WHERE channel_id = channel_id_in;

        IF NOT FOUND THEN
          RETURN NULL;
        END IF;
         
        RETURN channel_family_id_val;
    END$$ language plpgsql;

    CREATE OR REPLACE FUNCTION available_family_subscriptions(channel_family_id_in IN NUMERIC, org_id_in IN NUMERIC)
    RETURNS NUMERIC
    AS $$
    declare
        cfp record;
        current_members_val NUMERIC;
        max_members_val     NUMERIC;
        found               NUMERIC;
    BEGIN
        for cfp in SELECT * FROM rhnOrgChannelFamilyPermissions
	    WHERE channel_family_id = channel_family_id_in
	      AND org_id = org_id_in
        LOOP
            found := 1;
            current_members_val := cfp.current_members;
            max_members_val := cfp.max_members;
        END LOOP;

        -- not found: either the channel fam doesn't have an entry in cfp, or the org doesn't have access to it.
        -- either way, there are no available subscriptions

        IF found IS NULL
        THEN
            RETURN 0;
        END IF;

        -- null max members?  in that case, pass it on; NULL means infinite
        IF max_members_val IS NULL
        THEN
            RETURN NULL;
        END IF;

        -- otherwise, return the delta
        RETURN max_members_val - current_members_val;
    END$$ language plpgsql;

    CREATE OR REPLACE FUNCTION available_fve_family_subs(channel_family_id_in IN NUMERIC, org_id_in IN NUMERIC)
    RETURNS NUMERIC
    AS $$
    declare
        cfp record;
        fve_current_members_val NUMERIC;
        fve_max_members_val     NUMERIC;
        found               NUMERIC;
    BEGIN
        for cfp in SELECT * FROM rhnOrgChannelFamilyPermissions
	    WHERE channel_family_id = channel_family_id_in
	      AND org_id = org_id_in
        LOOP
            found := 1;
            fve_current_members_val := cfp.fve_current_members;
            fve_max_members_val := cfp.fve_max_members;
        END LOOP;

        -- not found: either the channel fam doesn't have an entry in cfp, or the org doesn't have access to it.
        -- either way, there are no available subscriptions
        
        IF found IS NULL
        THEN
            RETURN 0;
        END IF;

        -- null max members?  in that case, pass it on; NULL means infinite                     
        IF fve_max_members_val IS NULL
        THEN
            RETURN NULL;
        END IF;

        -- otherwise, return the delta  
        RETURN fve_max_members_val - fve_current_members_val;
    END$$ language plpgsql;
    
    -- *******************************************************************
    -- FUNCTION: channel_family_current_members
    -- Calculates and returns the actual count of systems consuming
    --   physical channel subscriptions.
    -- Called by: update_family_counts 
    --            rhn_entitlements.repoll_virt_guest_entitlements
    -- *******************************************************************
    create or replace function channel_family_current_members(channel_family_id_in IN NUMERIC,
                                            org_id_in IN NUMERIC)
    returns numeric
    as $$
    declare
        current_members_count numeric := 0;
    begin
        select  count(distinct server_id)
        into    current_members_count
          from  rhnChannelFamilyServerPhysical cfsp
         where  cfsp.channel_family_id = channel_family_id_in
           and  cfsp.customer_id = org_id_in;
        return current_members_count;
    end$$ language plpgsql;


    create or replace function cfam_curr_fve_members(
        channel_family_id_in IN NUMERIC,
        org_id_in IN NUMERIC)
    returns numeric
    as $$
    declare
        current_members_count numeric := 0;

    begin
        select count(sc.server_id)
          into current_members_count
          from rhnServerChannel sc,
               rhnChannelFamilyMembers cfm,
               rhnServer s
         where s.org_id = org_id_in
           and s.id = sc.server_id
           and cfm.channel_family_id = channel_family_id_in
           and cfm.channel_id = sc.channel_id
           and exists (
                select 1
                  from rhnChannelFamilyServerFve cfsp
                 where cfsp.CHANNEL_FAMILY_ID = channel_family_id_in
                   and cfsp.server_id = s.id
                );

        return current_members_count;
    end$$ language plpgsql;
    CREATE OR REPLACE FUNCTION update_family_counts(channel_family_id_in IN NUMERIC, 
                                   org_id_in IN NUMERIC) returns void
    AS $$
    BEGIN
        update rhnPrivateChannelFamily
           set current_members = rhn_channel.channel_family_current_members(channel_family_id_in, org_id_in),
               fve_current_members = rhn_channel.cfam_curr_fve_members(channel_family_id_in,org_id_in)
         where org_id = org_id_in
           and channel_family_id = channel_family_id_in;
    END$$ language plpgsql;
    
    create or replace function update_group_family_counts(group_label_in IN VARCHAR,
                                   org_id_in IN NUMERIC)
    returns void
    as $$
    declare
        i record;
    BEGIN
        FOR i IN (
                SELECT DISTINCT CFM.channel_family_id, SG.org_id
                 FROM rhnChannelFamilyMembers CFM
                 JOIN rhnServerChannel SC
                   ON SC.channel_id = CFM.channel_id
                 JOIN rhnServerGroupMembers SGM
                   ON SC.server_id = SGM.server_id
                 JOIN rhnServerGroup SG
                   ON SGM.server_group_id = SG.id
                 JOIN rhnServerGroupType SGT
                   ON SG.group_type = SGT.id
                WHERE SGT.label = group_label_in
                  AND SG.org_id = org_id_in
                  AND SGT.is_base = 'Y'
        ) LOOP
            perform rhn_channel.update_family_counts(i.channel_family_id, i.org_id);
        END LOOP;
    END$$ language plpgsql;

    CREATE OR REPLACE FUNCTION available_chan_subscriptions(channel_id_in IN NUMERIC, 
                                          org_id_in IN NUMERIC)
    RETURNS NUMERIC
    AS $$
    declare
            channel_family_id_val NUMERIC;
    BEGIN
        SELECT channel_family_id INTO STRICT channel_family_id_val
            FROM rhnChannelFamilyMembers
            WHERE channel_id = channel_id_in;
         
            RETURN rhn_channel.available_family_subscriptions(
                           channel_family_id_val, org_id_in);
    END$$ language plpgsql;

    CREATE OR REPLACE FUNCTION available_fve_chan_subs(channel_id_in IN NUMERIC,
                                          org_id_in IN NUMERIC)
    RETURNS NUMERIC
    AS $$
    declare
            channel_family_id_val NUMERIC;
    BEGIN
        SELECT channel_family_id INTO STRICT channel_family_id_val
            FROM rhnChannelFamilyMembers
            WHERE channel_id = channel_id_in;

            RETURN rhn_channel.available_fve_family_subs(
                           channel_family_id_val, org_id_in);
    END$$ language plpgsql;

    create or replace function unsubscribe_server_from_family(server_id_in in numeric, 
                                             channel_family_id_in in numeric)
    returns void
    as $$
    begin
        delete
        from    rhnServerChannel rsc
        where   rsc.server_id = server_id_in
            and channel_id in (
                select  rcfm.channel_id
                from    rhnChannelFamilyMembers rcfm
                where   rcfm.channel_family_id = channel_family_id_in);
    end$$ language plpgsql;

    create or replace function get_org_id(channel_id_in in numeric)
    returns numeric
    as $$
    declare
        org_id_out numeric;
    begin
        select org_id into strict org_id_out
            from rhnChannel
            where id = channel_id_in;
         
            return org_id_out;
    end$$ language plpgsql;
    
    create or replace function get_cfam_org_access(cfam_id_in in numeric, org_id_in in numeric)
    returns numeric
    as $$
    begin
      if exists(
                        select  1
                        from    rhnOrgChannelFamilyPermissions cfp
                        where   cfp.org_id = org_id_in
      ) then
                return 1;
      else
                return 0;
      end if;
    end$$ language plpgsql;

    create or replace function get_org_access(channel_id_in in numeric, org_id_in in numeric)
    returns integer
    as $$
    begin
        -- the idea: if we get past this query, 
        -- the org has access to the channel, else not
        if exists(
        select 1
          from rhnChannelFamilyMembers CFM,
               rhnOrgChannelFamilyPermissions CFP
         where cfp.org_id = org_id_in
           and CFM.channel_family_id = CFP.channel_family_id
           and CFM.channel_id = channel_id_in
           and (CFP.max_members > 0 or CFP.max_members is null or CFP.fve_max_members > 0 or CFP.fve_max_members is null or CFP.org_id = 1) )
        then
          return 1;
        else
          return 0;
        end if;
    end$$ language plpgsql;
    
    -- check if a user has a given role, or if such a role is inferrable
    -- returns NULL if OK, error message otherwise
    create or replace function user_role_check_debug(channel_id_in in numeric, 
                                   user_id_in in numeric, 
                                   role_in in varchar)
    returns varchar
    as $$
    declare
        org_id numeric;
    begin
        org_id := rhn_user.get_org_id(user_id_in);

        -- channel might be shared
        if role_in = 'subscribe' and
           rhn_channel.shared_user_role_check(channel_id_in, user_id_in, role_in) = 1 then
            return NULL;
        end if;
        
        if role_in = 'manage' and 
           COALESCE(rhn_channel.get_org_id(channel_id_in), -1) <> org_id then
               return 'channel_not_owned';
        end if;
        
        if role_in = 'subscribe' and 
           rhn_channel.get_org_access(channel_id_in, org_id) = 0 then
                return 'channel_not_available';
        end if;
        
        -- channel admins have all roles
        if rhn_user.check_role_implied(user_id_in, 'channel_admin') = 1 then
            return NULL;
        end if;

        -- the subscribe permission is inferred 
        -- UNLESS the not_globally_subscribable flag is set
        if role_in = 'subscribe'
        then
            if rhn_channel.org_channel_setting(channel_id_in, 
                       org_id,
                       'not_globally_subscribable') = 0 then
                return NULL;
            end if;
        end if;
        
        -- all other roles (manage right now) are explicitly granted    
        if rhn_channel.direct_user_role_check(channel_id_in,
                                              user_id_in, role_in) = 1 then
            return NULL;
        end if;
        return 'direct_permission';
    end$$ language plpgsql;
    
    -- same as above, but with 1/0 output; useful in views, etc
    create or replace function user_role_check(channel_id_in in numeric, user_id_in in numeric, role_in in varchar)
    returns numeric
    as $$
    begin
        if rhn_channel.user_role_check_debug(channel_id_in,
                                             user_id_in, role_in) is NULL then
            return 1;
        else
            return 0;
        end if;
    end$$ language plpgsql;

    --
    -- For multiorg phase II, this function simply checks to see if the user's
    -- has a trust relationship that includes this channel by id.
    --
    create or replace function shared_user_role_check(channel_id in numeric, user_id in numeric, role in varchar)
    returns numeric
    as $$
    declare
      n numeric;
      oid numeric;
    begin
      oid := rhn_user.get_org_id(user_id);
      select 1 into n
      from rhnSharedChannelView s
      where s.id = channel_id and s.org_trust_id = oid;

      if not found then
        return 0;
      end if;

      return 1;
    end$$ language plpgsql;

    -- same as above, but returns 1 if user_id_in is null
    -- This is useful in queries where user_id is not specified
    create or replace function loose_user_role_check(channel_id_in in numeric, user_id_in in numeric, role_in in varchar)
    returns numeric
    as $$
    begin
        if user_id_in is null then
            return 1;
        end if;
        return rhn_channel.user_role_check(channel_id_in, user_id_in, role_in);
    end$$ language plpgsql;
    
    -- directly checks the table, no inferred permissions
    create or replace function direct_user_role_check(channel_id_in in numeric, user_id_in in numeric, role_in in varchar)
    returns numeric
    as $$
    declare
        throwaway numeric;
    begin
        -- the idea: if we get past this query, the user has the role, else no
        select 1 into throwaway
          from rhnChannelPermissionRole CPR,
               rhnChannelPermission CP
         where CP.user_id = user_id_in
           and CP.channel_id = channel_id_in
           and CPR.label = role_in
           and CP.role_id = CPR.id;

      if not found then
        return 0;
      end if;
           
      return 1;
    end$$ language plpgsql;
    
    -- check if an org has a certain setting
    create or replace function org_channel_setting(channel_id_in in numeric, org_id_in in numeric, setting_in in varchar)
    returns numeric
    as $$
    declare
        throwaway numeric;
    begin
        -- the idea: if we get past this query, the org has the setting
        select 1 into throwaway
          from rhnOrgChannelSettingsType OCST,
               rhnOrgChannelSettings OCS
         where OCS.org_id = org_id_in
           and OCS.channel_id = channel_id_in
           and OCST.label = setting_in
           and OCS.setting_id = OCST.id;

      if not found then
        return 0;
      end if;

      return 1;
    end$$ language plpgsql;
    
    CREATE OR REPLACE FUNCTION channel_priority(channel_id_in IN numeric) 
    RETURNS numeric
    AS $$
    declare
         channel_name varchar(256);
         priority numeric;
         end_of_life_val timestamptz;
         org_id_val numeric;
    BEGIN

        select name, end_of_life, org_id
        into channel_name, end_of_life_val, org_id_val
        from rhnChannel
        where id = channel_id_in;

        if end_of_life_val is not null then
          return -400;
        end if;

        if channel_name like 'Red Hat Enterprise Linux%' or channel_name like 'RHEL%' then
          priority := 1000;
          if channel_name not like '%Beta%' then
            priority := priority + 1000;
          end if;

          priority := priority +
            case
              when channel_name like '%v. 5%' then 600
              when channel_name like '%v. 4%' then 500
              when channel_name like '%v. 3%' then 400
              when channel_name like '%v. 2%' then 300
              when channel_name like '%v. 1%' then 200
              else 0
            end;

          priority := priority +
            case
              when channel_name like 'Red Hat Enterprise Linux (v. 5%' then 60
              when (channel_name like '%AS%' and channel_name not like '%Extras%') then 50
              when (channel_name like '%ES%' and channel_name not like '%Extras%') then 40
              when (channel_name like '%WS%' and channel_name not like '%Extras%') then 30
              when (channel_name like '%Desktop%' and channel_name not like '%Extras%') then 20
              when channel_name like '%Extras%' then 10
              else 0
            end; 

          priority := priority +
            case
              when channel_name like '%)' then 5
              else 0
            end;

          priority := priority +
            case
              when channel_name like '%32-bit x86%' then 4
              when channel_name like '%64-bit Intel Itanium%' then 3
              when channel_name like '%64-bit AMD64/Intel EM64T%' then 2
              else 0
            end;
        elsif channel_name like 'Red Hat Desktop%' then
            priority := 900;

            if channel_name not like '%Beta%' then
               priority := priority + 50;
            end if;

          priority := priority +
            case
              when channel_name like '%v. 4%' then 40
              when channel_name like '%v. 3%' then 30
              when channel_name like '%v. 2%' then 20
              when channel_name like '%v. 1%' then 10
              else 0
            end;
            
          priority := priority +
            case
              when channel_name like '%32-bit x86%' then 4
              when channel_name like '%64-bit Intel Itanium%' then 3
              when channel_name like '%64-bit AMD64/Intel EM64T%' then 2
              else 0
            end;
         
        elsif org_id_val is not null then
          priority := 600;
        else
          priority := 500;
        end if;
      
      return -priority;

    end$$ language plpgsql;

    -- right now this only does the accounting changes; the cascade
    -- actually does the rhnServerChannel delete.
    create or replace function delete_server_channels(server_id_in in numeric) returns void
    as $$
    begin
        update  rhnPrivateChannelFamily
        set     current_members = current_members -1
        where   org_id in (
                        select  org_id
                        from    rhnServer
                        where   id = server_id_in
                )
                and channel_family_id in (
                        select  rcfm.channel_family_id
                        from    rhnChannelFamilyMembers rcfm,
                                rhnServerChannel rsc
                        where   rsc.server_id = server_id_in
                                and rsc.channel_id = rcfm.channel_id
                and not exists (
                    select 1
                    from
                        rhnChannelFamilyVirtSubLevel cfvsl,
                        rhnSGTypeVirtSubLevel sgtvsl,
                        rhnServerEntitlementView sev,
                        rhnVirtualInstance vi
                    where
                        -- system is a virtual instance
                        vi.virtual_system_id = server_id_in
                        and vi.host_system_id = sev.server_id
                        -- system's host has a virt ent
                        and sev.label in ('virtualization_host',
                                          'virtualization_host_platform')
                        and sev.server_group_type_id = 
                            sgtvsl.server_group_type_id
                        -- the host's virt ent grants a cf virt sub level
                        and sgtvsl.virt_sub_level_id = cfvsl.virt_sub_level_id
                        -- the cf is in that virt sub level
                        and cfvsl.channel_family_id = rcfm.channel_family_id
                    )
                );
    end$$ language plpgsql;

    -- this could certainly be optimized to do updates if needs be
    create or replace function refresh_newest_package(channel_id_in in numeric,
                                      caller_in in varchar default '(unknown)',
                                      package_name_id_in in numeric default null)
    returns void
    as $$
    -- procedure refreshes rows for name_id = package_name_id_in or
    -- all rows if package_name_id_in is null
    begin
        delete from rhnChannelNewestPackage
              where channel_id = channel_id_in
                and (package_name_id_in is null
                     or name_id = package_name_id_in);
        insert into rhnChannelNewestPackage
                (channel_id, name_id, evr_id, package_id, package_arch_id)
                (select channel_id,
                        name_id, evr_id,
                        package_id, package_arch_id
                   from rhnChannelNewestPackageView
                  where channel_id = channel_id_in
                    and (package_name_id_in is null
                         or name_id = package_name_id_in)
                );
        insert into rhnChannelNewestPackageAudit (channel_id, caller)
             values (channel_id_in, caller_in);
        update rhnChannel
           set last_modified = greatest(current_timestamp,
                                        last_modified + interval '1 second')
         where id = channel_id_in;
    end$$ language plpgsql;

   create or replace function update_channel ( channel_id_in in numeric, invalidate_ss in numeric default 0, 
                              date_to_use in timestamptz default current_timestamp ) returns void
   as $$
   declare
   channel_last_modified timestamptz;
   last_modified_value timestamptz;

   snapshots cursor for
   select  snapshot_id id
   from    rhnSnapshotChannel
   where   channel_id = channel_id_in;

   begin

      select last_modified
      into channel_last_modified
      from rhnChannel
      where id = channel_id_in;
  
      last_modified_value := date_to_use;

      if last_modified_value <= channel_last_modified then
          last_modified_value := last_modified_value + interval '1 second';
      end if;

      update rhnChannel set last_modified = last_modified_value
      where id = channel_id_in;

      if invalidate_ss = 1 then 
        for snapshot in snapshots loop
            update rhnSnapshot
            set invalid = lookup_snapshot_invalid_reason('channel_modified')
            where id = snapshot.id;
        end loop;
      end if;

   end$$ language plpgsql;

   create or replace function update_channels_by_package ( package_id_in in numeric, date_to_use in timestamptz default current_timestamp ) returns void
   as $$
   declare
   channels cursor for
   select channel_id
   from rhnChannelPackage
   where package_id = package_id_in
   order by channel_id;

   begin
      for channel in channels loop
         -- we want to invalidate the snapshot assocated with the channel when we
         -- do this b/c we know we've added or removed or packages
         perform rhn_channel.update_channel ( channel.channel_id, 1, date_to_use );
      end loop;
   end$$ language plpgsql;

   
   create or replace function update_channels_by_errata ( errata_id_in numeric, date_to_use in timestamptz default current_timestamp ) returns void
   as $$
   declare
   channels cursor for
   select channel_id
   from rhnChannelErrata
   where errata_id = errata_id_in
   order by channel_id;

   begin
      for channel in channels loop
         -- we won't invalidate snapshots, b/c just changing the errata associated with
         -- a channel shouldn't invalidate snapshots
         perform rhn_channel.update_channel ( channel.channel_id, 0, date_to_use );
      end loop;
   end$$ language plpgsql;

   create or replace function update_needed_cache(channel_id_in in numeric) returns void
   as $$
   declare
   server record;
   begin
      -- we intentionaly do a loop here instead of one huge select
      -- b/c we want to break update into smaller transaction to unblock other sessions
      -- querying rhnServerNeededCache
      for server in (
                select sc.server_id as id
                  from rhnServerChannel sc
                 where sc.channel_id = channel_id_in
                 order by id asc
      ) loop
         perform rhn_server.update_needed_cache(server.id);
      end loop;
   end$$ language plpgsql;

    create or replace function set_comps(channel_id_in in numeric, path_in in varchar, timestamp_in in varchar) returns void
    as $$
    declare
    row record;
    begin
        for row in (
            select relative_filename, last_modified
            from rhnChannelComps
            where channel_id = channel_id_in
            ) loop
            if row.relative_filename = path_in
                and row.last_modified = to_timestamp(timestamp_in, 'YYYYMMDDHH24MISS') then
                return;
            end if;
        end loop;
        delete from rhnChannelComps
        where channel_id = channel_id_in;
        insert into rhnChannelComps (id, channel_id, relative_filename, last_modified, created, modified)
        values (sequence_nextval('rhn_channelcomps_id_seq'), channel_id_in, path_in, to_timestamp(timestamp_in, 'YYYYMMDDHH24MISS'), current_timestamp, current_timestamp);
    end$$ language plpgsql;

CREATE OR REPLACE FUNCTION server_has_family_subscription(server_id_in DECIMAL, 
                                                          channel_family_id_in DECIMAL) 
          RETURNS INTEGER AS $$
  DECLARE
    fam_entry RECORD;

  BEGIN
    FOR fam_entry IN SELECT DISTINCT cfm.channel_family_id
                       FROM rhnchannelfamilymembers AS cfm
                       JOIN rhnserverchannel AS sc ON sc.channel_id = cfm.channel_id
                      WHERE sc.server_id = server_id_in
                        AND cfm.channel_family_id = channel_family_id_in
    LOOP
      return 1;
    END LOOP;
    RETURN 0;
  END;
$$ LANGUAGE plpgsql;

-- restore the original setting
update pg_settings set setting = overlay( setting placing '' from 1 for (length('rhn_channel')+1) ) where name = 'search_path';
07070100000A5D000081B400000000000000000000000167AE111400000162000000000000000000000000000000000000006900000000susemanager-schema/upgrade/susemanager-schema-1.7.57-to-susemanager-schema-2.1/4050-rhnTimezone-data.sql  insert into rhnTimezone (id, olson_name, display_name) (
    select sequence_nextval('rhn_timezone_id_seq'),
           'Asia/Riyadh',
           'Saudi Arabia'
      from dual
     where not exists (
           select 1
             from rhnTimezone
            where olson_name = 'Asia/Riyadh'
              and display_name = 'Saudi Arabia'
     )
);
  07070100000A5E000081B400000000000000000000000167AE111400000519000000000000000000000000000000000000007200000000susemanager-schema/upgrade/susemanager-schema-1.7.57-to-susemanager-schema-2.1/4051-rhnServerOutdatedPackages.sql --
-- Copyright (c) 2008 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--

DROP VIEW rhnServerOutdatedPackages;

CREATE OR REPLACE VIEW
rhnServerOutdatedPackages
(
    server_id,
    package_name_id,
    package_evr_id,    
    package_arch_id,
    package_nvre,
    errata_id,
    errata_advisory
)
AS
SELECT DISTINCT SNPC.server_id,
       P.name_id,
       P.evr_id,
       P.package_arch_id,
       PN.name || '-' || evr_t_as_vre_simple( PE.evr ),
       E.id,
       E.advisory
  FROM rhnPackageName PN,
       rhnPackageEVR PE,
       rhnPackage P,
       rhnServerNeededPackageCache SNPC
         left outer join
        rhnErrata E
          on SNPC.errata_id = E.id
 WHERE SNPC.package_id = P.id
   AND P.name_id = PN.id
   AND P.evr_id = PE.id;

   07070100000A5F000081B400000000000000000000000167AE1114000001FF000000000000000000000000000000000000006F00000000susemanager-schema/upgrade/susemanager-schema-1.7.57-to-susemanager-schema-2.1/4900-pxe-rhnServerGroupType.sql    --  bootstrap_entitled type ----------------------------------------------------

insert into rhnServerGroupType ( id, label, name, permanent, is_base) (
    select sequence_nextval('rhn_servergroup_type_seq'),
                            'bootstrap_entitled',
                            'Bootstrap Entitled Servers',
                            'N', 'Y'
      from dual
     where not exists (
           select 1
             from rhnServerGroupType
            where label = 'bootstrap_entitled'
     )
);

 07070100000A60000081B400000000000000000000000167AE111400000144000000000000000000000000000000000000007600000000susemanager-schema/upgrade/susemanager-schema-1.7.57-to-susemanager-schema-2.1/4901-pxe-rhnServerGroupTypeFeature.sql insert into rhnServerGroupTypeFeature (server_group_type_id, feature_id)
values (lookup_sg_type('bootstrap_entitled'), lookup_feature_type('ftr_kickstart'));

insert into rhnServerGroupTypeFeature (server_group_type_id, feature_id)
values (lookup_sg_type('bootstrap_entitled'), lookup_feature_type('ftr_system_grouping'));

07070100000A61000081B400000000000000000000000167AE111400001C55000000000000000000000000000000000000007B00000000susemanager-schema/upgrade/susemanager-schema-1.7.57-to-susemanager-schema-2.1/4902-pxe-rhnServerServerGroupArchCompat.sql    -- bootstrap entitlements

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
       values (lookup_server_arch('i386-redhat-linux'),
            lookup_sg_type('bootstrap_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
       values (lookup_server_arch('i386-debian-linux'),
            lookup_sg_type('bootstrap_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
       values (lookup_server_arch('i486-redhat-linux'),
            lookup_sg_type('bootstrap_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
       values (lookup_server_arch('i586-redhat-linux'),
            lookup_sg_type('bootstrap_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
       values (lookup_server_arch('i686-redhat-linux'),
            lookup_sg_type('bootstrap_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
       values (lookup_server_arch('athlon-redhat-linux'),
            lookup_sg_type('bootstrap_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
       values (lookup_server_arch('alpha-redhat-linux'),
            lookup_sg_type('bootstrap_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
       values (lookup_server_arch('alpha-debian-linux'),
            lookup_sg_type('bootstrap_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
       values (lookup_server_arch('alphaev6-redhat-linux'),
            lookup_sg_type('bootstrap_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
       values (lookup_server_arch('ia64-redhat-linux'),
            lookup_sg_type('bootstrap_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
       values (lookup_server_arch('ia64-debian-linux'),
            lookup_sg_type('bootstrap_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
       values (lookup_server_arch('sparc-redhat-linux'),
            lookup_sg_type('bootstrap_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
       values (lookup_server_arch('sparc-debian-linux'),
            lookup_sg_type('bootstrap_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
       values (lookup_server_arch('sparcv9-redhat-linux'),
            lookup_sg_type('bootstrap_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
       values (lookup_server_arch('sparc64-redhat-linux'),
            lookup_sg_type('bootstrap_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
       values (lookup_server_arch('s390-redhat-linux'),
            lookup_sg_type('bootstrap_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
        values (lookup_server_arch('armv7l-redhat-linux'),
            lookup_sg_type('bootstrap_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
        values (lookup_server_arch('armv5tejl-redhat-linux'),
            lookup_sg_type('bootstrap_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
        values (lookup_server_arch('armv6l-redhat-linux'),
            lookup_sg_type('bootstrap_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
       values (lookup_server_arch('s390-debian-linux'),
            lookup_sg_type('bootstrap_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
       values (lookup_server_arch('s390x-redhat-linux'),
            lookup_sg_type('bootstrap_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
       values (lookup_server_arch('ppc-redhat-linux'),
            lookup_sg_type('bootstrap_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
       values (lookup_server_arch('powerpc-debian-linux'),
            lookup_sg_type('bootstrap_entitled'));
insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
       values (lookup_server_arch('ppc64-redhat-linux'),
            lookup_sg_type('bootstrap_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
       values (lookup_server_arch('pSeries-redhat-linux'),
            lookup_sg_type('bootstrap_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
       values (lookup_server_arch('iSeries-redhat-linux'),
            lookup_sg_type('bootstrap_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
       values (lookup_server_arch('x86_64-redhat-linux'),
            lookup_sg_type('bootstrap_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
       values (lookup_server_arch('ia32e-redhat-linux'),
            lookup_sg_type('bootstrap_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
       values (lookup_server_arch('amd64-redhat-linux'),
            lookup_sg_type('bootstrap_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
       values (lookup_server_arch('amd64-debian-linux'),
            lookup_sg_type('bootstrap_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
       values (lookup_server_arch('ppc64iseries-redhat-linux'),
            lookup_sg_type('bootstrap_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
       values (lookup_server_arch('ppc64pseries-redhat-linux'),
            lookup_sg_type('bootstrap_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
       values (lookup_server_arch('arm-debian-linux'),
            lookup_sg_type('bootstrap_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
       values (lookup_server_arch('mips-debian-linux'),
            lookup_sg_type('bootstrap_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
   values (lookup_server_arch('sparc-sun4m-solaris'),
           lookup_sg_type('bootstrap_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
   values (lookup_server_arch('sparc-sun4u-solaris'),
           lookup_sg_type('bootstrap_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
   values (lookup_server_arch('sparc-sun4v-solaris'),
           lookup_sg_type('bootstrap_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
   values (lookup_server_arch('i386-i86pc-solaris'),
           lookup_sg_type('bootstrap_entitled'));

   07070100000A62000081B400000000000000000000000167AE11140001085B000000000000000000000000000000000000007100000000susemanager-schema/upgrade/susemanager-schema-1.7.57-to-susemanager-schema-2.1/4903-pxe-rhn_entitlements.pkb.sql  --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--

-- create schema rhn_entitlements;

-- setup search_path so that these functions are created in appropriate schema.
update pg_settings set setting = 'rhn_entitlements,' || setting where name = 'search_path';

   create or replace function find_compatible_sg (
      server_id_in in numeric,
      type_label_in in varchar
   )
   returns numeric
as $$
    declare
      servergroups cursor for
         select sg.id
           from rhnServerGroupType             sgt,
                rhnServerGroup                 sg,
                rhnServer                     s,
                rhnServerServerGroupArchCompat ssgac
          where s.id = server_id_in
            and s.org_id = sg.org_id
            and sgt.label = type_label_in
            and sg.group_type = sgt.id
            and ssgac.server_group_type = sgt.id
            and ssgac.server_arch_id = s.server_arch_id
            and not exists ( 
                     select 1
                      from rhnServerGroupMembers sgm
                     where sgm.server_group_id = sg.id 
                       and sgm.server_id = s.id);

         
   begin
      for servergroup in servergroups loop
         return servergroup.id;
      end loop;

      --no servergroup found
      return NULL;
   end$$
language plpgsql;

    -- *******************************************************************
    -- PROCEDURE: remove_org_entitlements
    --
    -- Removes both system entitlements and channel subscriptions
    -- that are currently assigned to an org and re-assigns to the
    -- master org (org_id = 1).
    --
    -- When we call this we expect everything to already be unentitled
    -- which shoul be handled by delete_org.
    --
    -- Called by: delete_org
    -- *******************************************************************
    create or replace function remove_org_entitlements (
        org_id_in numeric
    ) returns void
as $$
    declare
        system_ents cursor for
        select sg.id, sg.max_members, sg.group_type
        from rhnServerGroup sg
        where group_type is not null
          and org_id = org_id_in;

        channel_subs cursor for
        select pcf.channel_family_id, pcf.max_members
        from rhnChannelFamily cf,
             rhnPrivateChannelFamily pcf
        where pcf.org_id = org_id_in
          and pcf.channel_family_id = cf.id
          and cf.org_id is null;

    begin

        for system_ent in system_ents loop
            update rhnServerGroup
            set max_members = max_members + system_ent.max_members
            where org_id = 1
              and group_type = system_ent.group_type;
        end loop;

        update rhnServerGroup
        set max_members = 0
        where org_id = org_id_in;

        for channel_sub in channel_subs loop
            update rhnPrivateChannelFamily
            set max_members = max_members + channel_sub.max_members
            where org_id = 1
              and channel_family_id = channel_sub.channel_family_id;
        end loop;
        
        update rhnPrivateChannelFamily
        set max_members = 0
        where org_id = org_id_in;

    end$$
language plpgsql;

    create or replace function entitlement_grants_service (
        entitlement_in in varchar,
        service_level_in in varchar
    ) returns numeric
as $$
    begin
        if service_level_in = 'provisioning' then
            if entitlement_in = 'provisioning_entitled' then
                return 1;
            else
                return 0;
            end if;
        elsif service_level_in = 'management' then
            if entitlement_in = 'enterprise_entitled' then
                return 1;
            else
                return 0;
            end if;
        elsif service_level_in = 'monitoring' then
            if entitlement_in = 'monitoring_entitled' then
                return 1;
            end if;
        elsif service_level_in = 'updates' then
            return 1;           
        else
            return 0;
        end if;
    end$$
language plpgsql;

    create or replace function lookup_entitlement_group (
        org_id_in in numeric,
        type_label_in in varchar default 'sw_mgr_entitled'
    ) returns numeric
as $$
    declare
        server_groups cursor for
            select  sg.id               server_group_id
            from    rhnServerGroup      sg,
                    rhnServerGroupType  sgt
            where   sgt.label = type_label_in
                and sgt.id = sg.group_type
                and sg.org_id = org_id_in;
    begin
        for sg in server_groups loop
            return sg.server_group_id;
        end loop;
        return rhn_entitlements.create_entitlement_group(
                org_id_in, 
                type_label_in
            );
    end$$
language plpgsql;

    create or replace function create_entitlement_group (
        org_id_in in numeric,
        type_label_in in varchar default 'sw_mgr_entitled'
    ) returns numeric
as $$
    declare
        sg_id_val numeric;
    begin
        select  nextval('rhn_server_group_id_seq')
        into    sg_id_val;

        insert into rhnServerGroup (
                id, name, description, max_members, current_members,
                group_type, org_id
            ) (
                select  sg_id_val, sgt.label, sgt.label,
                        0, 0, sgt.id, org_id_in
                from    rhnServerGroupType sgt
                where   sgt.label = type_label_in
            );

        return sg_id_val;
    end$$
language plpgsql;

   create or replace function can_entitle_server ( 
      server_id_in   in numeric, 
      type_label_in  in varchar
   )
   returns numeric
as $$
    declare
      addon_servergroups cursor (base_label_in varchar, 
                                 addon_label_in varchar) for
         select
            addon_id
         from
            rhnSGTypeBaseAddonCompat
         where base_id = lookup_sg_type (base_label_in)
           and addon_id = lookup_sg_type (addon_label_in);

      previous_ent        varchar[];
      is_base_in          char   := 'N';
      is_base_current     char   := 'N';
      i                   numeric := 0;
      sgid                numeric := 0;

   begin

      previous_ent := rhn_entitlements.get_server_entitlement(server_id_in);

      select distinct is_base
      into is_base_in
      from rhnServerGroupType
      where label = type_label_in;

      if array_upper(previous_ent, 1) is null or array_upper(previous_ent, 1) = 0 then
         if is_base_in = 'Y' then
            sgid := rhn_entitlements.find_compatible_sg (server_id_in, type_label_in);
            if sgid is not null then
              -- rhn_server.insert_into_servergroup (server_id_in, sgid);
              return 1;
            else
              -- rhn_exception.raise_exception ('invalid_base_entitlement');
              return 0;
            end if;
         else
            -- rhn_exception.raise_exception ('invalid_base_entitlement');
            return 0;
         end if;

      -- there are previous ents, first make sure we're not trying to entitle a base ent
      elsif is_base_in = 'Y' then
         -- rhn_exception.raise_exception ('invalid_addon_entitlement');
         return 0;

      -- it must be an addon, so proceed with the entitlement
      else

         -- find the servers base ent
         is_base_current := 'N';
         i := 0;
         while is_base_current = 'N' and i < array_upper(previous_ent, 1)
         loop
            i := i + 1;
            select is_base
            into is_base_current
            from rhnServerGroupType
            where label = previous_ent[i];
         end loop;

         -- never found a base ent, that would be strange
         if is_base_current  = 'N' then
            -- rhn_exception.raise_exception ('invalid_base_entitlement');
            return 0;
         end if;

         -- this for loop verifies the validity of the addon path
         for addon_servergroup in addon_servergroups  (previous_ent[i], type_label_in) loop
            -- find an appropriate sgid for the addon and entitle the server
            sgid := rhn_entitlements.find_compatible_sg (server_id_in, type_label_in);
            if sgid is not null then
               -- rhn_server.insert_into_servergroup (server_id_in, sgid);
               return 1;
            else
               -- rhn_exception.raise_exception ('invalid_addon_entitlement');
               return 0;
            end if;
         end loop;

      end if;

      return 0;

   end$$
language plpgsql;

   create or replace function can_switch_base ( 
      server_id_in   in    integer, 
      type_label_in  in    varchar
   )
   returns numeric
as $$
   declare
      type_label_in_is_base   char(1);
      sgid                    numeric;

   begin

       select is_base into type_label_in_is_base
       from rhnServerGroupType
       where label = type_label_in;

       if not found then
          perform rhn_exception.raise_exception ( 'invalid_entitlement' );
       end if;

      if type_label_in_is_base = 'N' then
         perform rhn_exception.raise_exception ( 'invalid_entitlement' );
      else
         sgid := rhn_entitlements.find_compatible_sg ( server_id_in,
                                                       type_label_in );
         if sgid is not null then
           return 1;
         else
           return 0;
         end if;
      end if;

   end$$
language plpgsql;

    create or replace function entitle_server (
        server_id_in in numeric,
        type_label_in in varchar default 'sw_mgr_entitled'
    ) returns void
as $$
    declare
      sgid  numeric := 0;
      is_virt numeric := 0;

    begin

      select 1 into is_virt
        from rhnServerEntitlementView
        where server_id = server_id_in
          and label in ('virtualization_host', 'virtualization_host_platform');

      if not found then
          is_virt := 0;
      end if;
      
      if is_virt = 0 and (type_label_in = 'virtualization_host' or
                          type_label_in = 'virtualization_host_platform') then

        is_virt := 1;
      end if;

      if rhn_entitlements.can_entitle_server(server_id_in, 
                                             type_label_in) = 1 then
         sgid := rhn_entitlements.find_compatible_sg (server_id_in,
                                                      type_label_in);
         if sgid is not null then
            insert into rhnServerHistory ( id, server_id, summary, details )
            values ( nextval('rhn_event_id_seq'), server_id_in,
                     'added system entitlement ',
                      case type_label_in
                       when 'enterprise_entitled' then 'Management'
                       when 'bootstrap_entitled' then 'Bootstrap'
                       when 'sw_mgr_entitled' then 'Update'
                       when 'provisioning_entitled' then 'Provisioning'
                       when 'monitoring_entitled' then 'Monitoring'  
                       when 'virtualization_host' then 'Virtualization'
                       when 'virtualization_host_platform' then 
                            'Virtualization Platform' end  );

            perform rhn_server.insert_into_servergroup (server_id_in, sgid);

            if is_virt = 1 then
              perform rhn_entitlements.repoll_virt_guest_entitlements(server_id_in);
            end if;

         else
            perform rhn_exception.raise_exception ('no_available_server_group');
         end if;
      else
         perform rhn_exception.raise_exception ('invalid_entitlement');
      end if;
   end$$
language plpgsql;

    create or replace function remove_server_entitlement (
        server_id_in in numeric,
        type_label_in in varchar default 'sw_mgr_entitled',
        repoll_virt_guests in numeric default 1
    ) returns void
as $$
    declare
      group_id numeric;
      type_is_base char;
      is_virt numeric := 0;
    begin
      -- would be nice if there were a virt attribute of entitlement types, not have to specify 2 different ones...
        select 1 into is_virt
          from rhnServerEntitlementView
          where server_id = server_id_in
            and label in ('virtualization_host', 'virtualization_host_platform');
        if not found then
            is_virt := 0;
        end if;

        select  sg.id, sgt.is_base
        into group_id, type_is_base
        from    rhnServerGroupType sgt,
            rhnServerGroup sg,
                rhnServerGroupMembers sgm,
                rhnServer s
        where   s.id = server_id_in
            and s.id = sgm.server_id
            and sgm.server_group_id = sg.id
            and sg.org_id = s.org_id
            and sgt.label = type_label_in
            and sgt.id = sg.group_type;

        if not found then
          perform rhn_exception.raise_exception('invalid_server_group_member');
        end if;

      if ( type_is_base = 'Y' ) then
         -- unentitle_server should handle everything, don't really need to do anything else special here
         perform rhn_entitlements.unentitle_server ( server_id_in );
      else

         insert into rhnServerHistory ( id, server_id, summary, details )
         values ( nextval('rhn_event_id_seq'), server_id_in,
                  'removed system entitlement ',
                   case type_label_in
                    when 'enterprise_entitled' then 'Management'
                    when 'bootstrap_entitled' then 'Bootstrap'
                    when 'sw_mgr_entitled' then 'Update'
                    when 'provisioning_entitled' then 'Provisioning'
                    when 'monitoring_entitled' then 'Monitoring'
                    when 'virtualization_host' then 'Virtualization'
                    when 'virtualization_host_platform' then 
                         'Virtualization Platforrm' end  );

         perform rhn_server.delete_from_servergroup(server_id_in, group_id);

         if type_label_in = 'monitoring_entitled' then
           DELETE
             FROM rhn_probe
            WHERE recid IN (SELECT probe_id
                              FROM rhn_check_probe
                             WHERE host_id = server_id_in);
         end if;

         if is_virt = 1 and repoll_virt_guests = 1 then
           perform rhn_entitlements.repoll_virt_guest_entitlements(server_id_in);
         end if;
      end if;

    end$$
language plpgsql;

    create or replace function unentitle_server (
        server_id_in in numeric
    ) returns void
as $$
    declare
      servergroups cursor for
         select distinct sgt.label, sg.id server_group_id
         from  rhnServerGroupType sgt,
               rhnServerGroup sg,
               rhnServer s,
               rhnServerGroupMembers sgm
         where s.id = server_id_in
            and s.org_id = sg.org_id
            and sg.group_type = sgt.id
            and sgm.server_group_id = sg.id
            and sgm.server_id = s.id;
            
     is_virt numeric := 0;

   begin

      select 1 into is_virt
        from rhnServerEntitlementView
        where server_id = server_id_in
         and label in ('virtualization_host', 'virtualization_host_platform');

      if not found then
          is_virt := 0;
      end if;

      for servergroup in servergroups loop

         insert into rhnServerHistory ( id, server_id, summary, details )
         values ( nextval('rhn_event_id_seq'), server_id_in,
                  'removed system entitlement ',
                   case servergroup.label
                    when 'enterprise_entitled' then 'Management'
                    when 'bootstrap_entitled' then 'Bootstrap'
                    when 'sw_mgr_entitled' then 'Update'
                    when 'provisioning_entitled' then 'Provisioning'
                    when 'monitoring_entitled' then 'Monitoring'
                    when 'virtualization_host' then 'Virtualization'
                    when 'virtualization_host_platform' then 
                         'Virtualization Platform' end  );
  
         perform rhn_server.delete_from_servergroup(server_id_in, 
                                            servergroup.server_group_id );
      end loop;

      if is_virt = 1 then
        perform rhn_entitlements.repoll_virt_guest_entitlements(server_id_in);
      end if;

   end$$
language plpgsql;


    -- *******************************************************************
    -- PROCEDURE: repoll_virt_guest_entitlements
    --
    --   Whenever we add/remove a virtualization_host* entitlement from 
    --   a host, we can call this procedure to update what type of slots
    --   the guests are consuming.  
    -- 
    --   If you're removing the entitlement, it's 
    --   possible the guests will become unentitled if you don't have enough
    --   physical slots to cover them.
    --
    --   If you're adding the entitlement, you end up freeing up physical
    --   slots for other systems.
    --
    -- *******************************************************************
    create or replace function repoll_virt_guest_entitlements(
        server_id_in in numeric
    ) returns void
as $$
    declare
        -- All channel families associated with the guests of server_id_in
        families cursor for 
            select distinct cfs.channel_family_id
            from
                rhnChannelFamilyServers cfs,
                rhnVirtualInstance vi
            where
                vi.host_system_id = server_id_in
                and vi.virtual_system_id = cfs.server_id;
        
        -- All of server group types associated with the guests of
        -- server_id_in
        group_types cursor for
            select distinct sg.group_type, sgt.label, sg.org_id
            from
                rhnServerGroupType sgt,
                rhnServerGroup sg,
                rhnServerGroupMembers sgm,
                rhnVirtualInstance vi
            where
                vi.host_system_id = server_id_in
                and vi.virtual_system_id = sgm.server_id
                and sgm.server_group_id = sg.id
                and sg.group_type = sgt.id;

        -- Virtual servers from a certain family belonging to a specific
        -- host that are consuming physical channel slots over the limit.
        virt_servers_cfam cursor(family_id_in numeric, quantity_in numeric) for
                select vi.virtual_system_id
                from
                    rhnChannelFamilyMembers cfm,
                    rhnServerChannel sc,
                    rhnVirtualInstance vi
                where
                    vi.host_system_id = server_id_in
                    and vi.virtual_system_id = sc.server_id
                    and sc.channel_id = cfm.channel_id
                    and cfm.channel_family_id = family_id_in
                order by sc.modified desc
                limit quantity_in;                

        -- Virtual servers from a certain family belonging to a specific
        -- host that are consuming physical system slots over the limit.
        virt_servers_sgt cursor(group_type_in numeric, quantity_in numeric) for
                select vi.virtual_system_id
                from
                    rhnServerGroup sg,
                    rhnServerGroupMembers sgm,
                    rhnVirtualInstance vi
                where
                    vi.host_system_id = server_id_in
                    and vi.virtual_system_id = sgm.server_id
                    and sgm.server_group_id = sg.id
                    and sg.group_type = group_type_in
                order by sgm.modified desc
                limit quantity_in;                
        
        -- Get the orgs of Virtual guests
        -- Since they may belong to different orgs
        virt_guest_orgs cursor for
                select  distinct (s.org_id)
                from rhnServer s
                    inner join  rhnVirtualInstance vi on vi.virtual_system_id = s.id
                where
                    vi.host_system_id = server_id_in
                    and s.org_id <> (select s1.org_id from rhnServer s1 where s1.id = vi.host_system_id) ;

        org_id_val numeric;
        max_members_val numeric;
        max_flex_val numeric;
        current_members_calc numeric;
        sg_id numeric;
        is_virt numeric := 0;
        free_slots numeric := 0;
    begin
          select 1 into is_virt
                from rhnServerEntitlementView
           where server_id = server_id_in
                 and label in ('virtualization_host', 'virtualization_host_platform');

      if not found then
          is_virt := 0;
      end if;

        select org_id
        into org_id_val
        from rhnServer
        where id = server_id_in;

        -- deal w/ channel entitlements first ...
        for family in families loop
            if is_virt = 0 then
            -- if the host_server does not have virt
            --- find all possible flex slots
            -- and set each of the flex eligible guests to Y
                select sfc.max_members - sfc.current_members
                  into free_slots
                  from rhnServerFveCapable sfc
                 where sfc.channel_family_id = family.channel_family_id;
                UPDATE rhnServerChannel sc set is_fve = 'Y'
                where sc.server_id in (
                            select vi.virtual_system_id
                            from rhnServerFveCapable sfc
                                inner join rhnVirtualInstance vi on vi.virtual_system_id = sfc.server_id
                            where vi.host_system_id = server_id_in
                                  and sfc.channel_family_id = family.channel_family_id
                              order by vi.modified desc
                            limit free_slots
                );
            else
            -- if the host_server has virt
            -- set all its flex guests to N
                UPDATE rhnServerChannel sc set is_fve = 'N'
                where
                    sc.channel_id in (select cfm.channel_id from rhnChannelFamilyMembers cfm
                                      where cfm.CHANNEL_FAMILY_ID = family.channel_family_id)
                    and sc.is_fve = 'Y'
                    and sc.server_id in
                            (select vi.virtual_system_id  from rhnVirtualInstance vi
                                    where vi.host_system_id = server_id_in);
            end if;

            -- get the current (physical) members of the family
            current_members_calc := 
                rhn_channel.channel_family_current_members(family.channel_family_id,
                                                           org_id_val); -- fixed transposed args

            -- get the max members of the family
            select max_members
            into max_members_val
            from rhnPrivateChannelFamily
            where channel_family_id = family.channel_family_id
            and org_id = org_id_val;

            select fve_max_members
            into max_flex_val
            from rhnPrivateChannelFamily
            where channel_family_id = family.channel_family_id
            and org_id = org_id_val;

            if current_members_calc > max_members_val then
                -- A virtualization_host* ent must have been removed, so we'll
                -- unsubscribe guests from the host first.

                -- hm, i don't think max_members - current_members_calc yielding a negative number
                -- will work w/ rownum, swaping 'em in the body of this if...
                for virt_server in virt_servers_cfam(family.channel_family_id,
                                current_members_calc - max_members_val) loop 

                    perform rhn_channel.unsubscribe_server_from_family(
                                virt_server.virtual_system_id,
                                family.channel_family_id);
                end loop;                               

                -- if we're still over the limit, which would be odd,
                -- just prune the group to max_members
                --
                -- er... wouldn't we actually have to refresh the values of
                -- current_members_calc and max_members_val to actually ever
                -- *skip this??
                if current_members_calc > max_members_val then
                    -- argh, transposed again?!
                    perform rhn_entitlements.set_family_count(org_id_val,
                                     family.channel_family_id,
                                     max_members_val, max_flex_val);
                    --TODO calculate this correctly
                end if; 

           end if;

            -- update current_members for the family.  This will set the value
            -- to reflect adding/removing the entitlement.
            --
            -- what's the difference of doing this vs the unavoidable set_family_count above?
            perform rhn_channel.update_family_counts(family.channel_family_id,
                                             org_id_val);

            -- It is possible that the guests belong  to a different org than the host
            -- so we are going to update the family counts in the guests orgs also
            for org in virt_guest_orgs loop
                    perform rhn_channel.update_family_counts(family.channel_family_id,
                                             org.org_id);
            end loop;
        end loop;

        for a_group_type in group_types loop
          -- get the current *physical* members of the system entitlement type for the org...
          -- 
          -- unlike channel families, it appears the standard rhnServerGroup.max_members represents
          -- *physical* slots, vs physical+virt ... boy that's confusing...

          select max_members, id
            into max_members_val, sg_id
            from rhnServerGroup
            where group_type = a_group_type.group_type
            and org_id = a_group_type.org_id;


      select count(sep.server_id) into current_members_calc
            from rhnServerEntitlementPhysical sep
           where sep.server_group_id = sg_id
             and sep.server_group_type_id = a_group_type.group_type;
          
          if current_members_calc > max_members_val then
            -- A virtualization_host* ent must have been removed, and we're over the limit, so unsubscribe guests
            for virt_server in virt_servers_sgt(a_group_type.group_type,
                                                current_members_calc - max_members_val) loop
              perform rhn_entitlements.remove_server_entitlement(virt_server.virtual_system_id, a_group_type.label);

              -- decrement current_members_calc, we'll use it to reset current_members for the group at the end...
              current_members_calc := current_members_calc - 1;
            end loop;

          end if;

          update rhnServerGroup set current_members = current_members_calc
           where org_id = a_group_type.org_id
             and group_type = a_group_type.group_type;

          -- I think that's all the house-keeping we have to do...
        end loop;

    end$$
language plpgsql;

    create or replace function get_server_entitlement (
        server_id_in in numeric
    ) returns varchar[]
as $$
    declare
        server_groups cursor for
            select  sgt.label
            from    rhnServerGroupType      sgt,
                    rhnServerGroup          sg,
                    rhnServerGroupMembers   sgm
            where   1=1
                and sgm.server_id = server_id_in
                and sg.id = sgm.server_group_id
                and sgt.id = sg.group_type
                and sgt.label in (
                    'sw_mgr_entitled','enterprise_entitled', 'bootstrap_entitled',
                    'provisioning_entitled', 'nonlinux_entitled',
                    'monitoring_entitled', 'virtualization_host',
                                        'virtualization_host_platform'
                    );

         ent_array varchar[];

    begin
      
      ent_array := '{}';

      for sg in server_groups loop
         ent_array := ent_array || sg.label;
      end loop;

      return ent_array;

    end$$
language plpgsql;

    -- this desperately needs to be table driven.
    create or replace function modify_org_service (
        org_id_in in numeric,
        service_label_in in varchar,
        enable_in in char
    ) returns void
as $$
    declare
        roles_to_process varchar[];
        roles cursor(role_label_in varchar) for
            select  label, id
            from    rhnUserGroupType
            where   label = role_label_in;
        org_roles cursor(role_label_in varchar) for
            select  1
            from    rhnUserGroup ug,
                    rhnUserGroupType ugt
            where   ugt.label = role_label_in
                and ug.org_id = org_id_in
                and ugt.id = ug.group_type;
                
        ents_to_process varchar[];
        ents cursor(ent_label_in varchar) for
            select  label, id
            from    rhnOrgEntitlementType
            where   label = ent_label_in;
        org_ents cursor(ent_label_in varchar) for
            select  1
            from    rhnOrgEntitlements oe,
                    rhnOrgEntitlementType oet
            where   oet.label = ent_label_in
                and oe.org_id = org_id_in
                and oet.id = oe.entitlement_id;
        create_row char(1);
    begin
        ents_to_process := '{}';
        roles_to_process := '{}';
        -- a bit kludgy, but only for 3.4 really.  Certainly no
        -- worse than the old code...
        if service_label_in = 'enterprise' or 
           service_label_in = 'management' then
            ents_to_process := array_append(ents_to_process, 'sw_mgr_enterprise');

            roles_to_process := array_append(roles_to_process, 'org_admin');

            roles_to_process := array_append(roles_to_process, 'system_group_admin');

            roles_to_process := array_append(roles_to_process, 'activation_key_admin');
        elsif service_label_in = 'provisioning' then
            ents_to_process := array_append(ents_to_process, 'rhn_provisioning');

            roles_to_process := array_append(roles_to_process, 'system_group_admin');

            roles_to_process := array_append(roles_to_process, 'activation_key_admin');

            roles_to_process := array_append(roles_to_process, 'config_admin');
            -- another nasty special case...
            if enable_in = 'Y' then
                ents_to_process := array_append(ents_to_process, 'sw_mgr_enterprise');
            end if;
        elsif service_label_in = 'monitoring' then
            ents_to_process := array_append(ents_to_process, 'rhn_monitor');

            roles_to_process := array_append(roles_to_process, 'monitoring_admin');
        elsif service_label_in = 'virtualization' then
            ents_to_process := array_append(ents_to_process, 'rhn_virtualization');

            roles_to_process := array_append(roles_to_process, 'config_admin');
        elsif service_label_in = 'virtualization_platform' then
            ents_to_process := array_append(ents_to_process, 'rhn_virtualization_platform');
            roles_to_process := array_append(roles_to_process, 'config_admin');
    elsif service_label_in = 'nonlinux' then
            ents_to_process := array_append(ents_to_process, 'rhn_nonlinux');
            roles_to_process := array_append(roles_to_process, 'config_admin');
        end if;

        if enable_in = 'Y' then
            for i in 1..array_upper(ents_to_process, 1) loop
                for ent in ents(ents_to_process[i]) loop
                    create_row := 'Y';
                    for oe in org_ents(ent.label) loop
                        create_row := 'N';
                    end loop;
                    if create_row = 'Y' then
                        insert into rhnOrgEntitlements(org_id, entitlement_id)
                            values (org_id_in, ent.id);
                    end if;
                end loop;
            end loop;
            for i in 1..array_upper(roles_to_process, 1) loop
                for role in roles(roles_to_process[i]) loop
                    create_row := 'Y';
                    for o_r in org_roles(role.label) loop
                        create_row := 'N';
                    end loop;
                    if create_row = 'Y' then
                        insert into rhnUserGroup(
                                id, name, description, current_members,
                                group_type, org_id
                            ) (
                                select  nextval('rhn_user_group_id_seq'),
                                        ugt.name || 's',
                                        ugt.name || 's for Org ' ||
                                            o.name || ' ('|| o.id ||')',
                                        0, ugt.id, o.id
                                from    rhnUserGroupType ugt,
                                        web_customer o
                                where   o.id = org_id_in
                                    and ugt.id = role.id
                            );
                    end if;
                end loop;
            end loop;
        else
            for i in 1..coalesce(array_upper(ents_to_process, 1), 0) loop
                for ent in ents(ents_to_process[i]) loop
                    delete from rhnOrgEntitlements
                     where org_id = org_id_in
                       and entitlement_id = ent.id;
                end loop;
            end loop;
        end if;
    end$$
language plpgsql;

    create or replace function set_customer_enterprise (
        customer_id_in in numeric
    ) returns void
as $$
    begin
        perform rhn_entitlements.modify_org_service(customer_id_in, 'enterprise', 'Y');
    end$$
language plpgsql;

    create or replace function set_customer_provisioning (
        customer_id_in in numeric
    ) returns void
as $$
    begin
        perform rhn_entitlements.modify_org_service(customer_id_in, 'provisioning', 'Y');
    end$$
language plpgsql;

    create or replace function set_customer_monitoring (
        customer_id_in in numeric
    ) returns void
as $$
    begin
        perform rhn_entitlements.modify_org_service(customer_id_in, 'monitoring', 'Y');
    end$$
language plpgsql;

    create or replace function set_customer_nonlinux (
        customer_id_in in numeric
    ) returns void
as $$
    begin
        perform rhn_entitlements.modify_org_service(customer_id_in, 'nonlinux', 'Y');
    end$$
language plpgsql;

    create or replace function unset_customer_enterprise (
        customer_id_in in numeric
    ) returns void
as $$
    begin
        perform rhn_entitlements.modify_org_service(customer_id_in, 'enterprise', 'N');
    end$$
language plpgsql;

    create or replace function unset_customer_provisioning (
        customer_id_in in numeric
    ) returns void
as $$
    begin
        perform rhn_entitlements.modify_org_service(customer_id_in, 'provisioning', 'N');
    end$$
language plpgsql;

    create or replace function unset_customer_monitoring (
        customer_id_in in numeric
    ) returns void
as $$
    begin
        perform rhn_entitlements.modify_org_service(customer_id_in, 'monitoring', 'N');
    end$$
language plpgsql;

    create or replace function unset_customer_nonlinux (
        customer_id_in in numeric
    ) returns void
as $$
    begin
        perform rhn_entitlements.modify_org_service(customer_id_in, 'nonlinux', 'N');
    end$$
language plpgsql;

    -- *******************************************************************
    -- PROCEDURE: prune_group
    -- Unsubscribes servers consuming physical slots that over the org's
    --   limit.
    -- Called by: set_server_group_count, repoll_virt_guest_entitlements
    -- *******************************************************************
    create or replace function prune_group (
        group_id_in in numeric,
        quantity_in in numeric,
        update_family_countsYN in numeric default 1
    ) returns void
as $$
    declare
        sgrecord record;
      type_is_base char;
    begin
            update      rhnServerGroup
                set     max_members = quantity_in
                where   id = group_id_in;

            for sgrecord in (
		   select  server_id, server_group_id, sgt.id as group_type_id, sgt.label
		    from    rhnServerGroupType              sgt,
				    rhnServerGroup                  sg,
				    rhnServerGroupMembers   sgm
		    where   1=1
			    and sgm.server_group_id = group_id_in
			    and sgm.server_id in (
				    select  sep.server_id
				    from
					rhnServerEntitlementPhysical sep
				    where
					sep.server_group_id = group_id_in
				    order by sep.modified asc
				    offset quantity_in
				)
			    and sgm.server_group_id = sg.id
			    and sg.group_type = sgt.id
	    ) loop
                perform rhn_entitlements.remove_server_entitlement(sgrecord.server_id, sgrecord.label);
            
            select is_base 
            into type_is_base
            from rhnServerGroupType sgt
            where sgt.id = sgrecord.group_type_id;

            -- if we're removing a base ent, then be sure to
            -- remove the server's channel subscriptions.
            if ( type_is_base = 'Y' ) then
                   perform rhn_channel.clear_subscriptions(sgrecord.server_id, 0, update_family_countsYN);
            end if;

            end loop;
    end$$
language plpgsql;

    -- *******************************************************************
    -- PROCEDURE: assign_system_entitlement
    --
    -- Moves system entitlements from from_org_id_in to to_org_id_in.
    -- Can raise not_enough_entitlements_in_base_org if from_org_id_in
    -- does not have enough entitlements to cover the move.
    -- Takes care of unentitling systems if necessary by calling 
    -- set_server_group_count
    -- *******************************************************************
    create or replace function assign_system_entitlement(
        group_label_in in varchar,
        from_org_id_in in numeric,
        to_org_id_in in numeric,
        quantity_in in numeric
    ) returns void
as $$
    declare
        prev_ent_count numeric;
    to_org_prev_ent_count numeric;
        new_ent_count numeric;
    new_quantity numeric;
        group_type numeric;
    begin

            select max_members
            into prev_ent_count
            from rhnServerGroupType sgt,
                 rhnServerGroup sg
            where sg.org_id = from_org_id_in
              and sg.group_type = sgt.id
              and sgt.label = group_label_in;

            if not found then
                perform rhn_exception.raise_exception(
                              'not_enough_entitlements_in_base_org');
            end if;

            select max_members
            into to_org_prev_ent_count
            from rhnServerGroupType sgt,
                 rhnServerGroup sg
            where sg.org_id = to_org_id_in
              and sg.group_type = sgt.id
              and sgt.label = group_label_in;

            if not found then
                to_org_prev_ent_count := 0;
            end if;
    
            select id
            into group_type
            from rhnServerGroupType
            where label = group_label_in;

            if not found then
                perform rhn_exception.raise_exception(
                              'invalid_server_group');
            end if;

        new_ent_count := prev_ent_count - quantity_in;
    
        if prev_ent_count > new_ent_count then
            new_quantity := to_org_prev_ent_count + quantity_in;
        end if;
    
        if new_ent_count < 0 then
            perform rhn_exception.raise_exception(
                          'not_enough_entitlements_in_base_org');
        end if;


        perform rhn_entitlements.set_server_group_count(from_org_id_in,
                                         group_type,
                                         new_ent_count);

        perform rhn_entitlements.set_server_group_count(to_org_id_in,
                                         group_type,
                                         new_quantity);
        
        -- Create or delete the entries in rhnOrgEntitlementType
        if group_label_in = 'enterprise_entitled' then 
            if new_quantity > 0 then
                perform rhn_entitlements.set_customer_enterprise(to_org_id_in);
            else
                perform rhn_entitlements.unset_customer_enterprise(to_org_id_in);
            end if;
        end if;

        if group_label_in = 'provisioning_entitled' then
            if new_quantity > 0 then
                perform rhn_entitlements.set_customer_provisioning(to_org_id_in);
            else
                perform rhn_entitlements.unset_customer_provisioning(to_org_id_in);
            end if;
        end if;

        if group_label_in = 'monitoring_entitled' then
            if new_quantity > 0 then
                perform rhn_entitlements.set_customer_monitoring(to_org_id_in);
            else
                perform rhn_entitlements.unset_customer_monitoring(to_org_id_in);
            end if;
        end if;

    end$$
language plpgsql;

    -- *******************************************************************
    -- PROCEDURE: assign_channel_entitlement
    --
    -- Moves channel entitlements from from_org_id_in to to_org_id_in.
    -- Can raise not_enough_entitlements_in_base_org if from_org_id_in
    -- does not have enough entitlements to cover the move.
    -- Takes care of unentitling systems if necessary by calling 
    -- set_family_count
    -- *******************************************************************
    create or replace function assign_channel_entitlement(
        channel_family_label_in in varchar,
        from_org_id_in in numeric,
        to_org_id_in in numeric,
        quantity_in in numeric,
        flex_in in numeric
    ) returns void
as $$
    declare
        from_org_prev_ent_count numeric;
        from_org_prev_ent_count_flex numeric;
        new_ent_count numeric;
        new_ent_count_flex numeric;
        to_org_prev_ent_count numeric;
        to_org_prev_ent_count_flex numeric;
        new_quantity numeric;
        new_flex numeric;
        cfam_id       numeric;
    begin

            select max_members
            into from_org_prev_ent_count
            from rhnChannelFamily cf,
                 rhnPrivateChannelFamily pcf
            where pcf.org_id = from_org_id_in
              and pcf.channel_family_id = cf.id
              and cf.label = channel_family_label_in;

            if not found then
                perform rhn_exception.raise_exception(
                              'not_enough_entitlements_in_base_org');
            end if;
    
            select max_members
            into to_org_prev_ent_count
            from rhnChannelFamily cf,
                 rhnPrivateChannelFamily pcf
            where pcf.org_id = to_org_id_in
              and pcf.channel_family_id = cf.id
              and cf.label = channel_family_label_in;

            if not found then
                to_org_prev_ent_count := 0;
            end if;

            select fve_max_members
            into from_org_prev_ent_count_flex
            from rhnChannelFamily cf,
                rhnPrivateChannelFamily pcf
            where pcf.org_id = from_org_id_in
              and pcf.channel_family_id = cf.id
              and cf.label = channel_family_label_in;

            if not found then
                perform rhn_exception.raise_exception(
                              'not_enough_flex_entitlements_in_base_org');
            end if;

            select fve_max_members
            into to_org_prev_ent_count_flex
            from rhnChannelFamily cf,
                 rhnPrivateChannelFamily pcf
            where pcf.org_id = to_org_id_in
              and pcf.channel_family_id = cf.id
              and cf.label = channel_family_label_in;

            if not found then
                to_org_prev_ent_count_flex := 0;
            end if;

            select id
            into cfam_id
            from rhnChannelFamily
            where label = channel_family_label_in;

            if not found then
                perform rhn_exception.raise_exception(
                              'invalid_channel_family');
            end if;

        new_ent_count := from_org_prev_ent_count - quantity_in;
        new_ent_count_flex := from_org_prev_ent_count_flex - flex_in;
    
        if from_org_prev_ent_count >= new_ent_count then
            new_quantity := to_org_prev_ent_count + quantity_in;
        end if;

        if from_org_prev_ent_count_flex >= new_ent_count_flex then
            new_flex := to_org_prev_ent_count_flex + flex_in;
        end if;

        if new_ent_count < 0 then
            perform rhn_exception.raise_exception(
                          'not_enough_entitlements_in_base_org');
        end if;

        if new_ent_count_flex < 0 then
            perform rhn_exception.raise_exception(
                          'not_enough_flex_entitlements_in_base_org');
        end if;



        perform rhn_entitlements.set_family_count(from_org_id_in,
                                          cfam_id,
                                          new_ent_count,
                                          new_ent_count_flex);

        perform rhn_entitlements.set_family_count(to_org_id_in,
                                          cfam_id,
                                          new_quantity,
                                          new_flex);

    end$$
language plpgsql;

    -- *******************************************************************
    -- PROCEDURE: activate_system_entitlement
    --
    -- Sets the values in rhnServerGroup for a given rhnServerGroupType.
    -- 
    -- Calls: set_server_group_count to update, prune, or create the group.
    -- Called by: the code that activates a satellite cert. 
    --
    -- Raises not_enough_entitlements_in_base_org if all entitlements
    -- in the org are used so the free entitlements would not cover
    -- the difference when descreasing the number of entitlements.
    -- *******************************************************************
    create or replace function activate_system_entitlement(
        org_id_in in numeric,
        group_label_in in varchar,
        quantity_in in numeric
    ) returns void
as $$
    declare
        prev_ent_count numeric; 
        prev_ent_count_sum numeric; 
        group_type numeric;
    begin

        -- Fetch the current entitlement count for the org
        -- into prev_ent_count

            select current_members
            into prev_ent_count
            from rhnServerGroupType sgt,
                 rhnServerGroup sg
            where sg.group_type = sgt.id
              and sgt.label = group_label_in
              and sg.org_id = org_id_in;

            if not found then
                prev_ent_count := 0;
            end if;

            select id
            into group_type
            from rhnServerGroupType
            where label = group_label_in;

            if not found then
                perform rhn_exception.raise_exception(
                              'invalid_server_group');
            end if;

        -- If we're setting the total entitlemnt count to a lower value,
        -- and that value is less than the allocated count in this org,
        -- we need to raise an exception.
        if quantity_in < prev_ent_count then
            perform rhn_exception.raise_exception(
                          'not_enough_entitlements_in_base_org');
        else
            -- don't update family counts after every server
            -- will do bulk update afterwards
            perform rhn_entitlements.set_server_group_count(org_id_in,
                                             group_type,
                                             quantity_in,
                                             0);
            -- bulk update family counts
            perform rhn_channel.update_group_family_counts(group_label_in, org_id_in);
        end if;

    end$$
language plpgsql;

    -- *******************************************************************
    -- PROCEDURE: activate_channel_entitlement
    --
    -- Calls: set_family_count to update, prune, or create the family
    --        permission bucket.
    -- Called by: the code that activates a satellite cert. 
    --
    -- Raises not_enough_entitlements_in_base_org if there are not enough
    -- entitlements in the org to cover the difference when you are
    -- descreasing the number of entitlements.
    --
    -- The backend code in Python is expected to do whatever arithmetics
    -- is needed.
    -- *******************************************************************
    create or replace function activate_channel_entitlement(
        org_id_in in numeric,
        channel_family_label_in in varchar,
        quantity_in in numeric,
        flex_in in numeric
    ) returns void
as $$
    declare
        prev_ent_count numeric; 
        prev_flex_count numeric;
        prev_ent_count_sum numeric; 
        cfam_id numeric;
        reduce_quantity numeric;
        total_flex_capable numeric;
        to_convert_reg cursor (channel_family_id_val numeric, org_id_in numeric, quantity numeric) for
                     select SC.server_id
                     from rhnServerChannel SC inner join
                          rhnServer S on S.id = SC.server_id
                     where
                         is_fve = 'Y'
                         and S.org_id = org_id_in
                         and SC.channel_id in
                         (select cfm.channel_id from rhnChannelFamilyMembers cfm
                             where cfm.CHANNEL_FAMILY_ID = channel_family_id_val)
                         limit quantity;
         to_convert_flex cursor (channel_family_id_val numeric, org_id_in numeric, quantity numeric) for
                   select server_id
                   from rhnServerFveCapable
                       where SERVER_ORG_ID = org_id_in and
                             channel_family_id = cfam_id
                       limit quantity;

    begin

        -- Fetch the current entitlement count for the org
        -- into prev_ent_count
            select current_members
            into prev_ent_count
            from rhnChannelFamily cf,
                 rhnPrivateChannelFamily pcf
            where pcf.org_id = org_id_in
              and pcf.channel_family_id = cf.id
              and cf.label = channel_family_label_in;

            if not found then
                prev_ent_count := 0;
            end if;

            select pcf.fve_current_members
            into prev_flex_count
            from rhnChannelFamily cf,
                 rhnPrivateChannelFamily pcf
            where pcf.org_id = org_id_in
              and pcf.channel_family_id = cf.id
              and cf.label = channel_family_label_in;

            if not found then
                prev_flex_count := 0;
            end if;

            select id
            into cfam_id
            from rhnChannelFamily
            where label = channel_family_label_in;

            if not found then
                perform rhn_exception.raise_exception(
                              'invalid_channel_family');
            end if;

        -- if there are too few flex entitlements
        if flex_in < prev_flex_count then
            -- and if the extra we need is less than or equal to our extra regular entitlements
            if prev_flex_count - flex_in <= quantity_in - prev_ent_count then
                   reduce_quantity := prev_flex_count - flex_in;
                   -- We need to convert some systems from flex guest to regular
                   for system in to_convert_reg(cfam_id, org_id_in, reduce_quantity) loop
                      --rhn_channel.convert_to_regular(system.server_id, cfam_id);
                      UPDATE rhnServerChannel sc set is_fve = 'N'
                           where sc.server_id = system.server_id
                                 and sc.channel_id in (select cfm.channel_id
                                                          from rhnChannelFamilyMembers cfm
                                                          where cfm.channel_family_id = cfam_id);
                   end loop;

                   --reset previous counts
                   prev_ent_count := prev_ent_count + reduce_quantity;
                   prev_flex_count := prev_flex_count - reduce_quantity;
            else
                perform rhn_exception.raise_exception(
                          'not_enough_flex_entitlements_in_base_org');
            end if;
        end if;

        -- if there are too few regular entitlements, and extra flex entitlements
        if quantity_in < prev_ent_count and prev_flex_count < flex_in then
                -- how many flex-capable systems (that aren't using flex) do we have
                select count(*)
                   into total_flex_capable
                   from rhnServerFveCapable
                       where SERVER_ORG_ID = org_id_in and
                             channel_family_id = cfam_id;
                -- if we have enough flex capable machines that is at least
                --   as many as what we are over on
                if total_flex_capable >= prev_ent_count - quantity_in then
                    reduce_quantity := prev_ent_count - quantity_in;
                    for system in to_convert_flex(cfam_id, org_id_in, reduce_quantity) loop
--                          rhn_channel.convert_to_fve(system.server_id, cfam_id);
                        UPDATE rhnServerChannel sc set is_fve = 'Y'
                           where sc.server_id = system.server_id
                                 and sc.channel_id in (select cfm.channel_id
                                                          from rhnChannelFamilyMembers cfm
                                                          where cfm.channel_family_id = cfam_id);
                    end loop;
                    prev_ent_count := prev_ent_count - reduce_quantity;
                    prev_flex_count := prev_flex_count + reduce_quantity;
                end if;
        end if;

        -- If we're setting the total entitlemnt count to a lower value,
        -- and that value is less than the count in that one org,
        -- we need to raise an exception.
        if quantity_in < prev_ent_count then
            perform rhn_exception.raise_exception(
                          'not_enough_entitlements_in_base_org');
        else
            -- even if we've manually converted systems to/from flex above
            -- set_family_count should call update_family_counts, to reset
            -- current used slots
            perform rhn_entitlements.set_family_count(org_id_in, cfam_id,
                                              quantity_in, flex_in);
        end if;

    end$$
language plpgsql;

    create or replace function set_server_group_count (
        customer_id_in in numeric,  -- customer_id
        group_type_in in numeric,   -- rhn[User|Server]GroupType.id
        quantity_in in numeric,      -- quantity
                update_family_countsYN in numeric default 1
    ) returns void
as $$
    declare
        group_id numeric;
        quantity numeric;
        wasfound boolean;
    begin
        quantity := quantity_in;
        if quantity is not null and quantity < 0 then
            quantity := 0;
        end if;

        select  rsg.id
        into    group_id
        from    rhnServerGroup rsg
        where   1=1
            and rsg.org_id = customer_id_in
            and rsg.group_type = group_type_in;

        -- preserve the not found status across the rhn_entitlements.prune_group invocation
        wasfound := true;
        if not found then
            wasfound := false;
        end if;

        perform rhn_entitlements.prune_group(
            group_id,
            quantity,
                        update_family_countsYN
        );

        if not wasfound then
            insert into rhnServerGroup (
                    id, name, description, max_members, current_members,
                    group_type, org_id, created, modified
                ) (
                    select  nextval('rhn_server_group_id_seq'), name, name,
                            quantity, 0, id, customer_id_in,
                            current_timestamp, current_timestamp
                    from    rhnServerGroupType
                    where   id = group_type_in
            );
        end if;

    end$$
language plpgsql;

    -- *******************************************************************
    -- PROCEDURE: prune_family
    -- Unsubscribes servers consuming physical slots from the channel family 
    --   that are over the org's limit.
    -- Called by: set_family_count
    -- *******************************************************************
    create or replace function prune_family (
        customer_id_in in numeric,
        channel_family_id_in in numeric,
        quantity_in in numeric,
        flex_in in numeric
    ) returns void
as $$
    declare
        serverchannels cursor(tmp_quantity numeric, is_fve_in char) for
            select  sc.server_id,
                    sc.channel_id
            from    rhnServerChannel sc,
                    rhnChannelFamilyMembers cfm
            where   1=1
                and cfm.channel_family_id = channel_family_id_in
                and cfm.channel_id = sc.channel_id
                and server_id in (
                            select  rs.id as server_id
                            from    
                                    rhnServerChannel        rsc,
                                    rhnChannelFamilyMembers rcfm,
                                    rhnServer               rs
                            where   1=1
                                and rs.org_id = customer_id_in
                                and rs.id = rsc.server_id
                                and rsc.channel_id = rcfm.channel_id
                                and rcfm.channel_family_id =  channel_family_id_in
                                and rsc.is_fve = is_fve_in
                                -- we only want to grab servers consuming
                                -- physical slots.
                                and exists (
                                    select 1
                                    from rhnChannelFamilyServerPhysical cfsp
                                    where cfsp.server_id = rs.id
                                    and cfsp.channel_family_id = 
                                        channel_family_id_in
                                    )
                            order by rcfm.modified asc
                            offset quantity_in
                        );
    begin
        -- if we get a null customer_id, this is completely bogus.
        if customer_id_in is null then
            return;
        end if;

        for sc in serverchannels(quantity_in, 'N') loop
            perform rhn_channel.unsubscribe_server(sc.server_id, sc.channel_id,
                                                   1, 1, 0, 0);
        end loop;

        for sc in serverchannels(flex_in, 'Y') loop
            perform rhn_channel.unsubscribe_server(sc.server_id, sc.channel_id,
                                                   1, 1, 0, 0);
        end loop;

        perform rhn_channel.update_family_counts(channel_family_id_in, customer_id_in);
    end$$
language plpgsql;
        
    create or replace function set_family_count (
        customer_id_in in numeric,      -- customer_id
        channel_family_id_in in numeric,    -- 246
        quantity_in in numeric,          -- 3
        flex_in in numeric
    ) returns void
as $$
    declare
        privperms cursor for
            select  1
            from    rhnPrivateChannelFamily
            where   org_id = customer_id_in
                and channel_family_id = channel_family_id_in;
        pubperms cursor for
            select  o.id org_id
            from    web_customer o,
                    rhnPublicChannelFamily pcf
            where   pcf.channel_family_id = channel_family_id_in;
        quantity numeric;
        done numeric := 0;
        flex numeric;
    begin
        quantity := quantity_in;
        if quantity is not null and quantity < 0 then
            quantity := 0;
        end if;
        flex := flex_in;
        if flex is not null and flex < 0 then
            flex := 0;
        end if;

        if customer_id_in is not null then
            for perm in privperms loop
                perform rhn_entitlements.prune_family(
                    customer_id_in,
                    channel_family_id_in,
                    quantity,
                    flex
                );

                if quantity is null and flex is null then
                    delete from rhnPrivateChannelFamily
                        where org_id = customer_id_in
                            and channel_family_id = channel_family_id_in;
                 else
                    update rhnPrivateChannelFamily
                        set max_members = quantity
                        where org_id = customer_id_in
                            and channel_family_id = channel_family_id_in;

                   update rhnPrivateChannelFamily
                        set fve_max_members = flex
                        where org_id = customer_id_in
                            and channel_family_id = channel_family_id_in;
                end if;
                return;
            end loop;

            insert into rhnPrivateChannelFamily (
                    channel_family_id, org_id, max_members, current_members, fve_max_members, fve_current_members
                ) values (
                    channel_family_id_in, customer_id_in, quantity, 0, flex, 0 );
            return;
        end if;

        for perm in pubperms loop
            if quantity = 0 then
                perform rhn_entitlements.prune_family(
                    perm.org_id,
                    channel_family_id_in,
                    quantity,
                    flex
                );
                if done = 0 then
                    delete from rhnPublicChannelFamily
                        where channel_family_id = channel_family_id_in;
                end if;
            end if;
            done := 1;
        end loop;
        -- if done's not 1, then we don't have any entitlements
        if done != 1 then
            insert into rhnPublicChannelFamily (
                    channel_family_id
                ) values (
                    channel_family_id_in
                );
        end if;
    end$$
language plpgsql;

    -- this expects quantity_in to be the number of available slots, not the
    -- max_members of the server group.  If you give it too many, it'll fail
    -- and raise servergroup_max_members.
    -- We should NEVER run this unless we're SURE that we won't
    -- be violating the max.
    create or replace function entitle_last_modified_servers (
        customer_id_in in numeric,  -- customer_id
        type_label_in in varchar,   -- 'enterprise_entitled'
        quantity_in in numeric      -- 3
    ) returns void
as $$
    declare
        -- find the servers that aren't currently in slots
        servers cursor(cid_in numeric, quant_in numeric) for
                                    select  rs.id as server_id
                                    from    rhnServer rs
                                    where   1=1
                                        and rs.org_id = cid_in
                                        and not exists (
                                            select  1
                                            from    rhnServerGroup sg,
                                                    rhnServerGroupMembers rsgm
                                            where   rsgm.server_id = rs.id
                                                and rsgm.server_group_id = sg.id
                                                and sg.group_type is not null
                                        )
                                        and not exists (
                                            select 1
                                            from rhnVirtualInstance vi
                                            where vi.virtual_system_id =
                                                  rs.id
                                        )
                                    order by modified desc
                                    limit quant_in;
    begin
        for server in servers(customer_id_in, quantity_in) loop
            perform rhn_entitlements.entitle_server(server.server_id, type_label_in);
        end loop;
    end$$
language plpgsql;

    create or replace function subscribe_newest_servers (
        customer_id_in in numeric
    ) returns void
as $$
    declare
        -- find servers without base channels
        servers cursor(cid_in numeric) for
            select  s.id
            from    rhnServer           s
            where   1=1
                and s.org_id = cid_in
                and not exists (
                        select 1
                        from    rhnChannel          c,
                                rhnServerChannel    sc
                        where   sc.server_id = s.id
                            and sc.channel_id = c.id
                            and c.parent_channel is null
                    )
                and not exists (
                        select 1
                        from rhnVirtualInstance vi
                        where vi.virtual_system_id = s.id
                    )                        
            order by s.modified desc;
        channel_id numeric;
    begin
        for server in servers(customer_id_in) loop
            channel_id := rhn_channel.guess_server_base(server.id);
            if channel_id is not null then
                begin
                    perform rhn_channel.subscribe_server(server.id, channel_id);
                -- exception is really channel_family_no_subscriptions
                exception
                    when others then
                        null;
                end;
            end if;
        end loop;
    end$$
language plpgsql;


-- restore the original setting
update pg_settings set setting = overlay( setting placing '' from 1 for (length('rhn_entitlements')+1) ) where name = 'search_path';
 07070100000A63000081B400000000000000000000000167AE111400006154000000000000000000000000000000000000006B00000000susemanager-schema/upgrade/susemanager-schema-1.7.57-to-susemanager-schema-2.1/4904-pxe-rhn_server.pkb.sql    --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--

-- create schema rhn_server;

--update pg_setting
update pg_settings set setting = 'rhn_server,' || setting where name = 'search_path';

    create or replace function system_service_level(
    	server_id_in in numeric,
	service_level_in in varchar
    ) returns numeric as $$
    declare
    ents cursor is 
      select label from rhnServerEntitlementView
      where server_id = server_id_in;

    retval numeric := 0;

    begin
         for ent in ents loop
            retval := rhn_entitlements.entitlement_grants_service (ent.label, service_level_in);
            if retval = 1 then
               return retval;
            end if;
         end loop;

         return retval;

    end$$ language plpgsql;

        
    create or replace function can_change_base_channel(server_id_in IN NUMERIC)
    returns numeric
    as $$
    declare
    	throwaway numeric;
    begin
    	-- the idea: if we get past this query, the server is
	-- neither sat nor proxy, so base channel is changeable

	select 1 into throwaway
	  from rhnServer S
	 where S.id = server_id_in
	   and not exists (select 1 from rhnSatelliteInfo SI where SI.server_id = S.id)
	   and not exists (select 1 from rhnProxyInfo PI where PI.server_id = S.id);

        if not found then
	    return 0;
        end if;
	   
	return 1;
    end$$ language plpgsql;
	        
    create or replace function set_custom_value(
    	server_id_in in numeric,
	user_id_in in numeric,
	key_label_in in varchar,
	value_in in varchar
    ) returns void
    as $$
    declare
    	key_id_val numeric;
    begin
    	select CDK.id into strict key_id_val
	  from rhnCustomDataKey CDK,
	       rhnServer S
	 where S.id = server_id_in
	   and S.org_id = CDK.org_id
	   and CDK.label = key_label_in;
	   
	begin
	    insert into rhnServerCustomDataValue (server_id, key_id, value, created_by, last_modified_by)
	    values (server_id_in, key_id_val, value_in, user_id_in, user_id_in);
	exception
	    when UNIQUE_VIOLATION
	    	then
		update rhnServerCustomDataValue
		   set value = value_in,
		       last_modified_by = user_id_in
		 where server_id = server_id_in
		   and key_id = key_id_val;		   
	end;

    end$$ language plpgsql;
    
    create or replace function bulk_set_custom_value(
    	key_label_in in varchar,
	value_in in varchar,
	set_label_in in varchar,
	set_uid_in in numeric
    )
    returns integer
    as $$
    declare
        i integer;
        server record;
    begin
        i := 0;
        for server in (
           SELECT user_id, label, element, element_two
	     FROM rhnSet
	    WHERE label = set_label_in
	      AND user_id = set_uid_in
	) loop
	    if rhn_server.system_service_level(server.element, 'provisioning') = 1 then
	    	perform rhn_server.set_custom_value(server.element, set_uid_in, key_label_in, value_in);
            i := i + 1;
	    end if;
	end loop;
    return i;
    end$$ language plpgsql;

    create or replace function bulk_snapshot_tag(
    	org_id_in in numeric,
        tagname_in in varchar,
	set_label_in in varchar,
	set_uid_in in numeric
    ) returns void
    as $$
    declare
        server record;
    	snapshot_id numeric;
    begin
        for server in (
           SELECT user_id, label, element, element_two
	     FROM rhnSet
	    WHERE label = set_label_in
	      AND user_id = set_uid_in
	    ) loop
	    if rhn_server.system_service_level(server.element, 'provisioning') = 1 then
	    	    select max(id) into snapshot_id
	    	    from rhnSnapshot
	    	    where server_id = server.element;

	    	    if snapshot_id is null then
		    	perform rhn_server.snapshot_server(server.element, 'tagging system:  ' || tagname_in);
			
			select max(id) into snapshot_id
			from rhnSnapshot
			where server_id = server.element;
		    end if;
		 
		-- now have a snapshot_id to work with...
		begin
		    perform rhn_server.tag_snapshot(snapshot_id, org_id_in, tagname_in);
		exception
		    when UNIQUE_VIOLATION
		    	then
			-- do nothing, be forgiving...
			null;
		end;
	    end if;
	end loop;    
    end$$ language plpgsql;

    create or replace function tag_delete(
    	server_id_in in numeric,
	tag_id_in in numeric
    ) returns void
    as $$
    declare
    	snapshots cursor is
		select	snapshot_id
		from	rhnSnapshotTag
		where	tag_id = tag_id_in;
	tag_id_tmp numeric;
    begin
    	select	id into tag_id_tmp
	from	rhnTag
	where	id = tag_id_in
	for update;

	delete
		from	rhnSnapshotTag
		where	server_id = server_id_in
			and tag_id = tag_id_in;
	for snapshot in snapshots loop
		return;
	end loop;
	delete
		from rhnTag
		where id = tag_id_in;
    end$$ language plpgsql;

    create or replace function tag_snapshot(
        snapshot_id_in in numeric,
	org_id_in in numeric,
	tagname_in in varchar
    ) returns void
    as $$
    begin
    	insert into rhnSnapshotTag (snapshot_id, server_id, tag_id)
	select snapshot_id_in, server_id, lookup_tag(org_id_in, tagname_in)
	from rhnSnapshot
	where id = snapshot_id_in;
    end$$ language plpgsql;

    create or replace function bulk_snapshot(
    	reason_in in varchar,
	set_label_in in varchar,
	set_uid_in in numeric
    ) returns void
    as $$
    declare
        server record;
    begin
        for server in (
           SELECT user_id, label, element, element_two
	     FROM rhnSet
	    WHERE label = set_label_in
	      AND user_id = set_uid_in
	    ) loop
    	    if rhn_server.system_service_level(server.element, 'provisioning') = 1 then
	    	perform rhn_server.snapshot_server(server.element, reason_in);
	    end if;
	end loop;
    end$$ language plpgsql;

    create or replace function snapshot_server(
    	server_id_in in numeric,
	reason_in in varchar
    ) returns void
    as $$
    declare
    	snapshot_id_v numeric;
	revisions cursor is
		select distinct
			cr.id
		from	rhnConfigRevision	cr,
			rhnConfigFileName	cfn,
			rhnConfigFile		cf,
			rhnConfigChannel	cc,
			rhnServerConfigChannel	scc
		where	1=1
			and scc.server_id = server_id_in
			and scc.config_channel_id = cc.id
			and cc.id = cf.config_channel_id
			and cf.id = cr.config_file_id
			and cr.id = cf.latest_config_revision_id
			and cf.config_file_name_id = cfn.id
			and cf.id = lookup_first_matching_cf(scc.server_id, cfn.path);
	locked integer;
    begin
    	select nextval('rhn_snapshot_id_seq') into snapshot_id_v;

	insert into rhnSnapshot (id, org_id, server_id, reason) (
		select	snapshot_id_v,
			s.org_id,
			server_id_in,
			reason_in
		from	rhnServer s
		where	s.id = server_id_in
	);
	insert into rhnSnapshotChannel (snapshot_id, channel_id) (
		select	snapshot_id_v, sc.channel_id
		from	rhnServerChannel sc
		where	sc.server_id = server_id_in
	);
	insert into rhnSnapshotServerGroup (snapshot_id, server_group_id) (
		select	snapshot_id_v, sgm.server_group_id
		from	rhnServerGroupMembers sgm
		where	sgm.server_id = server_id_in
	);
        locked := 0;
        <<iloop>>
        while true loop
            begin
                insert into rhnPackageNEVRA (id, name_id, evr_id, package_arch_id)
                select nextval('rhn_pkgnevra_id_seq'), sp.name_id, sp.evr_id, sp.package_arch_id
                from rhnServerPackage sp
                where sp.server_id = server_id_in
                        and not exists
                        (select 1
                                from rhnPackageNEVRA nevra
                                where nevra.name_id = sp.name_id
                                        and nevra.evr_id = sp.evr_id
                                        and (nevra.package_arch_id = sp.package_arch_id
                                            or (nevra.package_arch_id is null
                                                and sp.package_arch_id is null)));
                exit iloop;
            exception when unique_violation then
                if locked = 1 then
                    raise;
                else
                    lock table rhnPackageNEVRA in exclusive mode;
                    locked := 1;
                end if;
            end;
        end loop;
	insert into rhnSnapshotPackage (snapshot_id, nevra_id) (
                select distinct snapshot_id_v, nevra.id
                from    rhnServerPackage sp, rhnPackageNEVRA nevra
                where   sp.server_id = server_id_in
                        and nevra.name_id = sp.name_id
                        and nevra.evr_id = sp.evr_id
                        and (nevra.package_arch_id = sp.package_arch_id
                            or (nevra.package_arch_id is null
                                and sp.package_arch_id is null))
	);

	insert into rhnSnapshotConfigChannel ( snapshot_id, config_channel_id ) (
		select	snapshot_id_v, scc.config_channel_id
		from	rhnServerConfigChannel scc
		where	server_id = server_id_in
	);

	for revision in revisions loop
		insert into rhnSnapshotConfigRevision (
				snapshot_id, config_revision_id
			) values (
				snapshot_id_v, revision.id
			);
	end loop;
    end$$ language plpgsql;

    create or replace function remove_action(
    	server_id_in in numeric,
	action_id_in in numeric
    ) returns void
    as $$
    declare
    	-- this really wants "nulls last", but 8.1.7.3.0 sucks ass.
	-- instead, we make a local table that holds our
	-- list of ids with null prereqs.  There's surely a better way
	-- (an array instead of a table maybe?  who knows...)
	-- but I've got code to do this handy that I can look at ;)
    	chained_actions cursor is
                with recursive r(id, prerequisite) as (
			select	id, prerequisite
			from	rhnAction
			where id = action_id_in
		union all
			select	r1.id, r1.prerequisite
			from	rhnAction r1, r
			where r.id = r1.prerequisite
		)
		select * from r
		order by prerequisite desc;
	sessions cursor is
		select	s.id
		from	rhnKickstartSession s
		where	server_id_in in (s.old_server_id, s.new_server_id)
			and s.action_id = action_id_in
			and not exists (
				select	1
				from	rhnKickstartSessionState ss
				where	ss.id = s.state_id
					and ss.label in ('failed','complete')
			);
	chain_ends numeric[];
	i numeric;
	prereq numeric := 1;
    begin
	select	prerequisite
	into	prereq
	from	rhnAction
	where	id = action_id_in;

	if prereq is not null then
		perform rhn_exception.raise_exception('action_is_child');
	end if;

        chain_ends := '{}';
	i := 1;
	for action in chained_actions loop
		if action.prerequisite is null then
			chain_ends[i] := action.id;
			i := i + 1;
		else
			delete from rhnServerAction
				where server_id = server_id_in
				and action_id = action.id;
		end if;
	end loop;

	delete from rhnServerAction
		where server_id = server_id_in
		and action_id = any(chain_ends);

	for s in sessions loop
		update rhnKickstartSession
			set 	state_id = (
					select	id
					from	rhnKickstartSessionState
					where	label = 'failed'
				),
				action_id = null
			where	id = s.id;
		perform set_ks_session_history_message(s.id, 'failed', 'Kickstart cancelled due to action removal');
	end loop;
    end$$ language plpgsql;
   
    create or replace function check_user_access(server_id_in in numeric, user_id_in in numeric)
    returns numeric
    as $$
    declare
    	has_access numeric;
    begin
    	-- first check; if this returns no rows, then the server/user are in different orgs, and we bail
        select 1 into has_access
	  from rhnServer S,
	       web_contact wc
	 where wc.org_id = s.org_id
	   and s.id = server_id_in
	   and wc.id = user_id_in;

        if not found then
          return 0;
        end if;

	-- okay, so they're in the same org.  if we have an org admin, they get a free pass
    	if rhn_user.check_role(user_id_in, 'org_admin') = 1
	then
	    return 1;
	end if;
		   
    	select 1 into has_access
	  from rhnServerGroupMembers SGM,
	       rhnUserServerGroupPerms USG
	 where SGM.server_group_id = USG.server_group_id
	   and SGM.server_id = server_id_in
	   and USG.user_id = user_id_in;

        if not found then
          return 0;
        end if;
	   
	return 1;
    end$$ language plpgsql;

    -- *******************************************************************
    -- FUNCTION: can_server_consume_virt_slot
    -- Returns 1 if the server id is eligible to consume a virtual slot,
    --   else returns 0.
    -- Called by: insert_into_servergroup, delete_from_servergroup
    -- *******************************************************************
    create or replace function can_server_consume_virt_slot(server_id_in in numeric,
                                           group_type_in in varchar)
    returns numeric                                           
    as $$
    declare
        server_virt_slots cursor is
            select vi.VIRTUAL_SYSTEM_ID
            from
                rhnVirtualInstance vi
            where
                -- server id is a virtual instance
                vi.VIRTUAL_SYSTEM_ID = server_id_in
                -- server id's host is virt entitled
                and exists ( select 1
                     from rhnServerEntitlementView sev
                 where vi.HOST_SYSTEM_ID = sev.server_id
                 and sev.label in ('virtualization_host',
                                   'virtualization_host_platform') )
                -- server id's host also has the ent we want
                and exists ( select 1
                     from rhnServerEntitlementView sev2
                 where vi.HOST_SYSTEM_ID = sev2.server_id
                 and sev2.label = group_type_in );

    begin
        for server_virt_slot in server_virt_slots loop
            return 1;
        end loop;
        return 0;
    end$$ language plpgsql;


    create or replace function insert_into_servergroup (
		server_id_in in numeric,
		server_group_id_in in numeric
    ) returns void
    as $$
    declare
		used_slots numeric;
		max_slots numeric;
		org_id numeric;
		mgmt_available numeric;
		mgmt_upgrade numeric;
		mgmt_sgid numeric;
		prov_available numeric;
		prov_upgrade numeric;
		prov_sgid numeric;
		group_label varchar;
		group_type numeric;
	begin
		-- first, group_type = null, because it's easy...

		-- this will rowlock the servergroup we're trying to change;
		-- we probably need to lock the other one, but I think the chances
		-- of it being a real issue are very small for now...
		select	sg.group_type, sg.org_id, sg.current_members, sg.max_members
		into	group_type, org_id, used_slots, max_slots
		from	rhnServerGroup sg
		where	sg.id = server_group_id_in
		for update of sg;

		if group_type is null then
			if used_slots >= max_slots then
				perform rhn_exception.raise_exception('servergroup_max_members');
			end if;

			insert into rhnServerGroupMembers(
					server_id, server_group_id
				) values (
					server_id_in, server_group_id_in
				);
			update rhnServerGroup
				set current_members = current_members + 1
				where id = server_group_id_in;

			perform rhn_cache.update_perms_for_server_group(server_group_id_in);
			return;
		end if;

		-- now for group_type != null
		-- 
		select	label
		into	group_label
		from	rhnServerGroupType	sgt
		where	sgt.id = group_type;

		-- the naive easy path that gets hit most often and has to be quickest.
		if group_label in ('sw_mgr_entitled',
                           'enterprise_entitled',
                           'bootstrap_entitled',
                           'monitoring_entitled',
                           'provisioning_entitled',
                           'virtualization_host',
                           'virtualization_host_platform') then
			if used_slots >= max_slots and 
               (rhn_server.can_server_consume_virt_slot(server_id_in, group_label) != 1) 
               then
				perform rhn_exception.raise_exception('servergroup_max_members');
			end if;

			insert into rhnServerGroupMembers(
					server_id, server_group_id
				) values (
					server_id_in, server_group_id_in
				);

            -- Only update current members if the system in consuming a 
            -- physical slot.
            if rhn_server.can_server_consume_virt_slot(server_id_in, group_label) = 0 then
                update rhnServerGroup
                set current_members = current_members + 1
                where id = server_group_id_in;
            end if;                

			return;
		end if;
	end$$ language plpgsql;

	create or replace function insert_into_servergroup_maybe (
		server_id_in in numeric,
		server_group_id_in in numeric
	) returns numeric as $$ 
    declare
		retval numeric := 0;
		servergroups cursor is
			select	s.id	server_id,
					sg.id	server_group_id
			from	rhnServerGroup	sg,
					rhnServer		s
			where	s.id = server_id_in
				and sg.id = server_group_id_in
				and s.org_id = sg.org_id
				and not exists (
					select	1
					from	rhnServerGroupMembers sgm
					where	sgm.server_id = s.id
						and sgm.server_group_id = sg.id
				);
	begin
		for sgm in servergroups loop
			perform rhn_server.insert_into_servergroup(sgm.server_id, sgm.server_group_id);
			retval := retval + 1;
		end loop;
		return retval;
	end$$ language plpgsql;

	create or replace function insert_set_into_servergroup (
		server_group_id_in in numeric,
		user_id_in in numeric,
		set_label_in in varchar
	) returns void
        as $$
    declare
		servers cursor is
			select	st.element	id
			from	rhnSet		st
			where	st.user_id = user_id_in
				and st.label = set_label_in
				and exists (
					select	1
					from	rhnUserManagedServerGroups umsg
					where	umsg.server_group_id = server_group_id_in
						and umsg.user_id = user_id_in
					)
				and not exists (
					select	1
					from	rhnServerGroupMembers sgm
					where	sgm.server_id = st.element
						and sgm.server_group_id = server_group_id_in
				);
	begin
		for s in servers loop
			perform rhn_server.insert_into_servergroup(s.id, server_group_id_in);
		end loop;
	end$$ language plpgsql;
		
    create or replace function delete_from_servergroup (
    	server_id_in in numeric,
		server_group_id_in in numeric
    ) returns void
    as $$
    declare
        server_virt_groups cursor is
            select 1
            from rhnServerEntitlementVirtual sev
            where sev.server_id = server_id_in
            and sev.server_group_id = server_group_id_in;

		oid numeric;
		mgmt_sgid numeric;
		label varchar;
		group_type numeric;
	begin
			select	sg.group_type, sg.org_id
			into	group_type,	oid
			from	rhnServerGroupMembers	sgm,
					rhnServerGroup			sg
			where	sg.id = server_group_id_in
				and sg.id = sgm.server_group_id
				and sgm.server_id = server_id_in
			for update of sg;

			if not found then
				perform rhn_exception.raise_exception('server_not_in_group');
			end if;

		-- do group_type is null first
		if group_type is null then
			delete from rhnServerGroupMembers
				where server_group_id = server_group_id_in
				and	server_id = server_id_in;
			update rhnServerGroup
				set current_members = current_members - 1
				where id = server_group_id_in;
			perform rhn_cache.update_perms_for_server_group(server_group_id_in);
			return;
		end if;

		select	sgt.label
		into	label
		from	rhnServerGroupType sgt
		where	sgt.id = group_type;

		if label in ('sw_mgr_entitled',
                     'enterprise_entitled', 
                     'bootstrap_entitled',
                     'provisioning_entitled', 
                     'monitoring_entitled',
                     'virtualization_host',
                     'virtualization_host_platform') then

            -- Only update current members if the system is consuming
            -- a physical slot.
            for server_virt_group in server_virt_groups loop                
                delete from rhnServerGroupMembers
                where server_group_id = server_group_id_in
                and	server_id = server_id_in;
                return;
            end loop;                

            delete from rhnServerGroupMembers
            where server_group_id = server_group_id_in
            and	server_id = server_id_in;

            update rhnServerGroup
            set current_members = current_members - 1
            where id = server_group_id_in;

		end if;
	end$$ language plpgsql;

	create or replace function delete_set_from_servergroup (
		server_group_id_in in numeric,
		user_id_in in numeric,
		set_label_in in varchar
	) returns void
        as $$	
        declare
		servergroups cursor is
			select	sgm.server_id, sgm.server_group_id
			from	rhnSet st,
					rhnServerGroupMembers sgm
			where	sgm.server_group_id = server_group_id_in
				and st.user_id = user_id_in
				and st.label = set_label_in
				and sgm.server_id = st.element
				and exists (
					select	1
					from	rhnUserManagedServerGroups usgp
					where	usgp.server_group_id = server_group_id_in
						and usgp.user_id = user_id_in
				);
	begin
		for sgm in servergroups loop
			perform rhn_server.delete_from_servergroup(sgm.server_id, server_group_id_in);
		end loop;
	end$$ language plpgsql;

	create or replace function clear_servergroup (
		server_group_id_in in numeric
	) returns void
        as $$
        declare
		servers cursor is
			select	sgm.server_id	id
			from	rhnServerGroupMembers sgm
			where	sgm.server_group_id = server_group_id_in;
	begin
		for s in servers loop
			perform rhn_server.delete_from_servergroup(s.id, server_group_id_in);
		end loop;
	end$$ language plpgsql;

	create or replace function delete_from_org_servergroups (
		server_id_in in numeric
	) returns void
        as $$
        declare
		servergroups cursor is
			select	sgm.server_group_id id
			from	rhnServerGroup sg,
					rhnServerGroupMembers sgm
			where	sgm.server_id = server_id_in
				and sgm.server_group_id = sg.id
				and sg.group_type is null;
	begin
		for sg in servergroups loop
			perform rhn_server.delete_from_servergroup(server_id_in, sg.id);
		end loop;
	end$$ language plpgsql;

	create or replace function get_ip_address (
		server_id_in in numeric
	) returns varchar as $$
        declare
		interfaces cursor is
			select	ni.name as name, na4.address as address
			from	rhnServerNetInterface ni,
			        rhnServerNetAddress4 na4
			where	server_id = server_id_in
                and ni.id = na4.interface_id
				and na4.address != '127.0.0.1';
		addresses cursor is
			select	ipaddr ip_addr
			from	rhnServerNetwork
			where	server_id = server_id_in
				and ipaddr != '127.0.0.1';
	begin
		for addr in addresses loop
			return addr.ip_addr;
		end loop;
		for iface in interfaces loop
			return iface.address;
		end loop;
		return NULL;
	end$$ language plpgsql;

    create or replace function update_needed_cache(
        server_id_in in numeric
	) returns void as $$
    begin
      delete from rhnServerNeededCache
        where server_id = server_id_in;
      insert into rhnServerNeededCache
             (server_id, errata_id, package_id, channel_id)
        (select distinct sp.server_id, x.errata_id, p.id, x.channel_id
           FROM (SELECT sp_sp.server_id, sp_sp.name_id,
		        sp_sp.package_arch_id, max(sp_pe.evr) AS max_evr
                   FROM rhnServerPackage sp_sp
                   join rhnPackageEvr sp_pe ON sp_pe.id = sp_sp.evr_id
                  GROUP BY sp_sp.server_id, sp_sp.name_id, sp_sp.package_arch_id) sp
           join rhnPackage p ON p.name_id = sp.name_id
           join rhnPackageEvr pe ON pe.id = p.evr_id AND sp.max_evr < pe.evr
           join rhnPackageUpgradeArchCompat puac
	            ON puac.package_arch_id = sp.package_arch_id
		    AND puac.package_upgrade_arch_id = p.package_arch_id
           join rhnServerChannel sc ON sc.server_id = sp.server_id
           join rhnChannelPackage cp ON cp.package_id = p.id
	            AND cp.channel_id = sc.channel_id
           left join (SELECT ep.errata_id, ce.channel_id, ep.package_id
                        FROM rhnChannelErrata ce
                        join rhnErrataPackage ep
			         ON ep.errata_id = ce.errata_id
			join rhnServerChannel sc_sc
			         ON sc_sc.channel_id = ce.channel_id
		       WHERE sc_sc.server_id = server_id_in) x
             ON x.channel_id = sc.channel_id AND x.package_id = cp.package_id
          where sp.server_id = server_id_in);
	end$$ language plpgsql;
-- restore the original setting
update pg_settings set setting = overlay( setting placing '' from 1 for (length('rhn_server')+1) ) where name = 'search_path';
07070100000A64000081B400000000000000000000000167AE1114000000B3000000000000000000000000000000000000007C00000000susemanager-schema/upgrade/susemanager-schema-1.7.57-to-susemanager-schema-2.1/4905-add-column-bootstrap-activation-key.sql   ALTER TABLE rhnactivationkey ADD bootstrap CHAR(1) DEFAULT ('N') NOT NULL;
ALTER TABLE rhnactivationkey ADD CONSTRAINT rhn_act_key_bootstrap_ck CHECK (bootstrap in ('Y', 'N'));


 07070100000A65000081B400000000000000000000000167AE111400000E45000000000000000000000000000000000000006D00000000susemanager-schema/upgrade/susemanager-schema-1.7.57-to-susemanager-schema-2.1/4906-pxe-create_first_org.sql  --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
-- This creates an org with ID of 1, and errors if there already is one
--

create or replace function
create_first_org
(
	name_in in varchar,
	password_in in varchar
)
returns void as
$$
declare
	ug_type			numeric;
	group_val		numeric;
begin
	insert into web_customer (
		id, name
	) values (
		1, name_in
	);

	select nextval( 'rhn_user_group_id_seq' ) into group_val from dual;

	select	id
	into	ug_type
	from	rhnUserGroupType
	where	label = 'org_admin';

	insert into rhnUserGroup (
		id, name,
		description,
		max_members, group_type, org_id
	) values (
		group_val, 'Organization Administrators',
		'Organization Administrators for Org ' || name_in || ' (1)',
		NULL, ug_type, 1
	);

	select nextval('rhn_user_group_id_seq') into group_val from dual;

	select	id
	into	ug_type
	from	rhnUserGroupType
	where	label = 'system_group_admin';

	insert into rhnUserGroup (
		id, name,
		description,
		max_members, group_type, org_id
	) values (
		group_val, 'System Group Administrators',
		'System Group Administrators for Org ' || name_in || ' (1)',
		NULL, ug_type, 1
	);


	select nextval('rhn_user_group_id_seq') into group_val from dual;

	select	id
	into	ug_type
	from	rhnUserGroupType
	where	label = 'activation_key_admin';

	insert into rhnUserGroup (
		id, name,
		description,
		max_members, group_type, org_id
	) values (
		group_val, 'Activation Key Administrators',
		'Activation Key Administrators for Org ' || name_in || ' (1)',
		NULL, ug_type, 1
	);

	-- config admin is special; it gets created in
	-- rhn_entitlements.set_customer_provisioning instead.

	select nextval('rhn_user_group_id_seq') into group_val from dual;

	select	id
	into	ug_type
	from	rhnUserGroupType
	where	label = 'channel_admin';

	insert into rhnUserGroup (
		id, name,
		description,
		max_members, group_type, org_id
	) values (
		group_val, 'Channel Administrators',
		'Channel Administrators for Org ' || name_in || ' (1)',
		NULL, ug_type, 1
	);

	select nextval('rhn_user_group_id_seq') into group_val from dual;

	select	id
	into	ug_type
	from	rhnUserGroupType
	where	label = 'satellite_admin';

	insert into rhnUserGroup (
		id, name,
		description,
		max_members, group_type, org_id
	) values (
		group_val, 'SUSE Manager Administrators',
		'SUSE Manager Administrators for Org ' || name_in || ' (1)',
		NULL, ug_type, 1
	);


	-- there aren't any users yet, so we don't need to update
	-- rhnUserServerPerms
        insert into rhnServerGroup 
		( id, name, description, max_members, group_type, org_id )
		select nextval('rhn_server_group_id_seq'), sgt.name, sgt.name, 
			0, sgt.id, 1
		from rhnServerGroupType sgt
		where sgt.label = 'sw_mgr_entitled';

        insert into rhnServerGroup
                ( id, name, description, max_members, group_type, org_id )
                select nextval('rhn_server_group_id_seq'), sgt.name, sgt.name,
                        200000, sgt.id, 1
                from rhnServerGroupType sgt
                where sgt.label = 'bootstrap_entitled';
		
end
$$ language plpgsql;

   07070100000A66000081B400000000000000000000000167AE1114000010A0000000000000000000000000000000000000006B00000000susemanager-schema/upgrade/susemanager-schema-1.7.57-to-susemanager-schema-2.1/4907-pxe-create_new_org.sql    --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--

create or replace function create_new_org
(
        name_in      in varchar,
        password_in  in varchar
        --org_id_out   out NUMERIC
) returns numeric
as
$$
declare
        ug_type                 numeric;
        group_val               numeric;
        new_org_id              numeric;
        org_id_out		numeric;
begin

        select nextval('web_customer_id_seq') into new_org_id;

        insert into web_customer (
                id, name
        ) values (
                new_org_id, name_in
        );

        select nextval('rhn_user_group_id_seq') into group_val;

        select  id
        into    ug_type
        from    rhnUserGroupType
        where   label = 'org_admin';

        insert into rhnUserGroup (
                id, name,
                description,
                max_members, group_type, org_id
        ) values (
                group_val, 'Organization Administrators',
                'Organization Administrators for Org ' || name_in,
                NULL, ug_type, new_org_id
        );

        select nextval('rhn_user_group_id_seq') into group_val;

        select  id
        into    ug_type
        from    rhnUserGroupType
        where   label = 'system_group_admin';

        insert into rhnUserGroup (
                id, name,
                description,
                max_members, group_type, org_id
        ) values (
                group_val, 'System Group Administrators',
                'System Group Administrators for Org ' || name_in,
                NULL, ug_type, new_org_id
        );


        select nextval('rhn_user_group_id_seq') into group_val;

        select  id
        into    ug_type
        from    rhnUserGroupType
        where   label = 'activation_key_admin';

        insert into rhnUserGroup (
                id, name,
                description,
                max_members, group_type, org_id
        ) values (
                group_val, 'Activation Key Administrators',
                'Activation Key Administrators for Org ' || name_in,
                NULL, ug_type, new_org_id
        );

        -- config admin is special; it gets created in
        -- rhn_entitlements.set_customer_provisioning instead.

        select nextval('rhn_user_group_id_seq') into group_val;

        select  id
        into    ug_type
        from    rhnUserGroupType
        where   label = 'channel_admin';

        insert into rhnUserGroup (
                id, name,
                description,
                max_members, group_type, org_id
        ) values (
                group_val, 'Channel Administrators',
                'Channel Administrators for Org ' || name_in,
                NULL, ug_type, new_org_id
        );

        -- there aren't any users yet, so we don't need to update
        -- rhnUserServerPerms
        insert into rhnServerGroup
                ( id, name, description, max_members, group_type, org_id )
                select nextval('rhn_server_group_id_seq'), sgt.name, sgt.name,
                        0, sgt.id, new_org_id
                from rhnServerGroupType sgt
                where sgt.label = 'sw_mgr_entitled';

        insert into rhnServerGroup
                ( id, name, description, max_members, group_type, org_id )
                select nextval('rhn_server_group_id_seq'), sgt.name, sgt.name,
                        200000, sgt.id, new_org_id
                from rhnServerGroupType sgt
                where sgt.label = 'bootstrap_entitled';

        org_id_out := new_org_id;

	-- Returning the value of OUT parameter
        return org_id_out;

end;
$$
language plpgsql;


07070100000A67000081B400000000000000000000000167AE11140000026F000000000000000000000000000000000000007C00000000susemanager-schema/upgrade/susemanager-schema-1.7.57-to-susemanager-schema-2.1/4908-pxe-bootstrap_ent-to-rhnServerGroup.sql   
select .clear_log_id() from dual;

insert into rhnServerGroup ( id, name, description, max_members, group_type, org_id )
  select nextval('rhn_server_group_id_seq'), sgt.name, sgt.name, 200000, sgt.id, X.org_id
  from rhnServerGroupType sgt,
     (select distinct msg.org_id
        from rhnServerGroup msg
       where msg.org_id not in (select org_id
                                  from rhnServerGroup sg
                                  join rhnServerGroupType sgt ON sgt.id = sg.group_type
                                 where sgt.label = 'bootstrap_entitled')
     ) X
  where sgt.label = 'bootstrap_entitled';
 07070100000A68000081B400000000000000000000000167AE11140000021D000000000000000000000000000000000000008500000000susemanager-schema/upgrade/susemanager-schema-1.7.57-to-susemanager-schema-2.1/4910-add-bootstrap-entitlement-rhnentitledservers.sql  create or replace view
rhnEntitledServers
as
select distinct
    S.id,
    S.org_id,
    S.digital_server_id,
    S.server_arch_id,
    S.os,
    S.release,
    S.name,
    S.description,
    S.info,
    S.secret
from
    rhnServerGroup SG,
    rhnServerGroupType SGT,
    rhnServerGroupMembers SGM,
    rhnServer S
where
    S.id = SGM.server_id
and SG.id = SGM.server_group_id
and SGT.label IN ('sw_mgr_entitled', 'enterprise_entitled', 'provisioning_entitled', 'bootstrap_entitled')
and SG.group_type = SGT.id
and SG.org_id = S.org_id
;

   07070100000A69000081B400000000000000000000000167AE11140000004D000000000000000000000000000000000000007F00000000susemanager-schema/upgrade/susemanager-schema-1.7.57-to-susemanager-schema-2.1/4911-add-succeeded-to-rhnssmoperationserver.sql    ALTER TABLE rhnSsmOperationServer
  ADD note VARCHAR(256)
    DEFAULT NULL
;
   07070100000A6A000081B400000000000000000000000167AE1114000003FE000000000000000000000000000000000000007700000000susemanager-schema/upgrade/susemanager-schema-1.7.57-to-susemanager-schema-2.1/4912-add-reboot-action-cleanup-task.sql    INSERT INTO rhnTaskoBunch (id, name, description, org_bunch)
    VALUES (sequence_nextval('rhn_tasko_bunch_id_seq'), 'reboot-action-cleanup-bunch', 'invalidate reboot actions which never finish', null);

-- Every hour

INSERT INTO rhnTaskoSchedule (id, job_label, bunch_id, active_from, cron_expr)
    VALUES(sequence_nextval('rhn_tasko_schedule_id_seq'), 'reboot-action-cleanup-default',
        (SELECT id FROM rhnTaskoBunch WHERE name='reboot-action-cleanup-bunch'),
        current_timestamp, '0 0 * * * ?');

INSERT INTO rhnTaskoTask (id, name, class)
    VALUES (sequence_nextval('rhn_tasko_task_id_seq'), 'reboot-action-cleanup', 'com.redhat.rhn.taskomatic.task.RebootActionCleanup');

INSERT INTO rhnTaskoTemplate (id, bunch_id, task_id, ordering, start_if)
    VALUES (sequence_nextval('rhn_tasko_template_id_seq'),
            (SELECT id FROM rhnTaskoBunch WHERE name='reboot-action-cleanup-bunch'),
            (SELECT id FROM rhnTaskoTask WHERE name='reboot-action-cleanup'),
            0,
            null);
  07070100000A6B000081B400000000000000000000000167AE11140000029C000000000000000000000000000000000000008500000000susemanager-schema/upgrade/susemanager-schema-1.7.57-to-susemanager-schema-2.1/4950-update_rhnActionPackage_parameter_constraint.sql  --
-- Copyright (c) 2013 Novell
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
--

ALTER TABLE rhnActionPackage DROP CONSTRAINT rhn_act_p_param_ck;

-- add the contraints
ALTER TABLE rhnActionPackage
    ADD CONSTRAINT rhn_act_p_param_ck
    CHECK (parameter IN ('upgrade', 'install', 'remove', 'downgrade', 'lock'));

07070100000A6C000081B400000000000000000000000167AE111400000210000000000000000000000000000000000000009100000000susemanager-schema/upgrade/susemanager-schema-1.7.57-to-susemanager-schema-2.1/4951-insert_packages_set_locks_action_type_into_rhnActionType.sql  --
-- Copyright (c) 2013 Novell
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
--

insert into rhnActionType values (502, 'packages.setLocks', 'Lock packages', 'N', 'N');
commit;
07070100000A6D000081B400000000000000000000000167AE111400000619000000000000000000000000000000000000007700000000susemanager-schema/upgrade/susemanager-schema-1.7.57-to-susemanager-schema-2.1/4952-create_rhnLockedPackages_table.sql    --
-- Copyright (c) 2013 SUSE.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnLockedPackages
(
    pkg_id           NUMERIC NOT NULL
                         REFERENCES rhnPackage (id)
                             ON DELETE CASCADE,
    server_id        NUMERIC NOT NULL
                         REFERENCES rhnServer (id)
                             ON DELETE CASCADE,
    name_id          NUMERIC NOT NULL
                         REFERENCES rhnPackageName (id),
    evr_id           NUMERIC NOT NULL
                         REFERENCES rhnPackageEVR (id),
    arch_id          NUMERIC
                         REFERENCES rhnPackageArch (id),
    pending          CHAR(1) DEFAULT ('L')
                         CONSTRAINT rhn_lockedpackages_pending_ck
                           CHECK (pending in ('L', 'U'))
)

;

CREATE UNIQUE INDEX rhn_lp_pkg_id_uq
    ON rhnLockedPackages (pkg_id)
    
    ;
CREATE UNIQUE INDEX rhn_lp_snep_uq
    ON rhnLockedPackages (server_id, name_id, evr_id, arch_id)
    
    ;
   07070100000A6E000081B400000000000000000000000167AE1114000003DC000000000000000000000000000000000000006700000000susemanager-schema/upgrade/susemanager-schema-1.7.57-to-susemanager-schema-2.1/4953-rhnActionChain.sql    --
-- Copyright (c) 2014 SUSE
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
--

CREATE TABLE rhnActionChain
(
    id          NUMERIC        NOT NULL
                    CONSTRAINT rhn_action_chain_id_pk PRIMARY KEY,
    label       VARCHAR(256) NOT NULL,
    user_id     NUMERIC        NOT NULL
                    CONSTRAINT rhn_actionchain_uid_fk
                        REFERENCES web_contact (id)
                        ON DELETE CASCADE,
    created     TIMESTAMPTZ          DEFAULT(CURRENT_TIMESTAMP) NOT NULL,
    modified    TIMESTAMPTZ          DEFAULT(CURRENT_TIMESTAMP) NOT NULL
)

;

CREATE SEQUENCE rhn_actionchain_id_seq;
07070100000A6F000081B400000000000000000000000167AE111400000517000000000000000000000000000000000000006C00000000susemanager-schema/upgrade/susemanager-schema-1.7.57-to-susemanager-schema-2.1/4954-rhnActionChainEntry.sql   --
-- Copyright (c) 2014 SUSE
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
--

CREATE TABLE rhnActionChainEntry
(
    actionchain_id NUMERIC NOT NULL
        CONSTRAINT rhn_actchainent_acid_fk
            REFERENCES rhnActionChain (id)
            ON DELETE CASCADE,
    action_id      NUMERIC
        CONSTRAINT rhn_actchainent_aid_fk
            REFERENCES rhnAction (id)
            ON DELETE CASCADE,
    server_id      NUMERIC NOT NULL
        CONSTRAINT rhn_actchainent_sid_fk
            REFERENCES rhnServer(id)
            ON DELETE CASCADE,
    sort_order     NUMERIC NOT NULL,
    created        TIMESTAMPTZ DEFAULT(CURRENT_TIMESTAMP) NOT NULL,
    modified       TIMESTAMPTZ DEFAULT(CURRENT_TIMESTAMP) NOT NULL,
    CONSTRAINT rhn_actchainent_cid_sid_so_uq UNIQUE 
        (actionchain_id, server_id, sort_order)
    DEFERRABLE INITIALLY DEFERRED
)

;

CREATE UNIQUE INDEX rhn_actchainent_aid_uq
    ON rhnActionChainEntry(action_id)
    ;
 07070100000A70000081B400000000000000000000000167AE111400000312000000000000000000000000000000000000006F00000000susemanager-schema/upgrade/susemanager-schema-1.7.57-to-susemanager-schema-2.1/4955-rhnActionChain-trigger.sql    --
-- Copyright (c) 2014 SUSE
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
--
CREATE OR REPLACE FUNCTION rhn_actionchain_mod_trig_fun() RETURNS TRIGGER
    AS
    $$
    BEGIN
        new.modified := current_timestamp;
        RETURN new;
    END;
    $$
    LANGUAGE PLPGSQL;

CREATE TRIGGER rhn_actionchain_mod_trig
    BEFORE INSERT OR UPDATE ON rhnActionChain
    FOR EACH ROW
    EXECUTE PROCEDURE rhn_actionchain_mod_trig_fun();
  07070100000A71000081B400000000000000000000000167AE111400000317000000000000000000000000000000000000007400000000susemanager-schema/upgrade/susemanager-schema-1.7.57-to-susemanager-schema-2.1/4956-rhnActionChainEntry-trigger.sql   --
-- Copyright (c) 2014 SUSE
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
--
CREATE OR REPLACE FUNCTION rhn_actchainent_mod_trig_fun() RETURNS TRIGGER
    AS
    $$
    BEGIN
        new.modified := current_timestamp;
        RETURN new;
    END;
    $$
    LANGUAGE PLPGSQL;

CREATE TRIGGER rhn_actchainent_mod_trig
    BEFORE INSERT OR UPDATE ON rhnActionChainEntry
    FOR EACH ROW
    EXECUTE PROCEDURE rhn_actchainent_mod_trig_fun();
 07070100000A72000081B400000000000000000000000167AE111400000041000000000000000000000000000000000000006900000000susemanager-schema/upgrade/susemanager-schema-1.7.57-to-susemanager-schema-2.1/5003-rhnTaskoSchedule.sql  
ALTER TABLE rhnTaskoSchedule ALTER cron_expr TYPE VARCHAR(120);
   07070100000A73000081B400000000000000000000000167AE1114000014B7000000000000000000000000000000000000007100000000susemanager-schema/upgrade/susemanager-schema-1.7.57-to-susemanager-schema-2.1/5004-web_contact-old_password.sql  
-- ## views

create or replace view
rhnUserReceiveNotifications
as
select
	0::numeric as org_id,
	0::numeric as user_id,
	0::numeric as server_id
from dual;

drop view rhnWebContactEnabled;
drop view rhnWebContactDisabled;

create or replace view
rhnWebContactDisabled
as
select
   wcon.id,
   wcon.org_id,
   wcon.login,
   wcon.login_uc,
   wcon.password,
   wcon.oracle_contact_id,
   wcon.created,
   wcon.modified,
   wcon.ignore_flag
from
   rhnWebContactChangeLog   wccl,
   rhnWebContactChangeState wccs,
   web_contact              wcon
where wccl.change_state_id = wccs.id
   and wccs.label = 'disabled'
   and wccl.web_contact_id = wcon.id
   and wccl.date_completed =
              (select max(wccl_exists.date_completed)
                 from rhnWebContactChangeLog   wccl_exists
                where wccl.web_contact_id = wccl_exists.web_contact_id);

create or replace view
rhnWebContactEnabled
as
select
   wcon.id,
   wcon.org_id,
   wcon.login,
   wcon.login_uc,
   wcon.password,
   wcon.oracle_contact_id,
   wcon.created,
   wcon.modified,
   wcon.ignore_flag
from
   web_contact wcon
where not exists (
     select 1 from rhnWebContactDisabled
     where wcon.id = rhnWebContactDisabled.id
   );

create or replace view rhnUserReceiveNotifications
as
    select wc.org_id, usp.user_id, usp.server_id
    from rhnUserServerPerms usp
    left join rhnWebContactDisabled wcd
        on usp.user_id = wcd.id
    join web_contact wc
        on usp.user_id = wc.id
    join rhnUserInfo ui
        on usp.user_id = ui.user_id
        and ui.email_notify = 1
    join web_user_personal_info upi
        on usp.user_id = upi.web_user_id
        and upi.email is not null
    left join rhnUserServerPrefs uspr
        on uspr.server_id = usp.server_id
        and usp.user_id = uspr.user_id
        and uspr.name = 'receive_notifications'
        and value='0'
    where uspr.server_id is null
    and wcd.id is null;

-- ## create_new_user

create or replace function
create_new_user
(
    org_id_in           in numeric,
    login_in            in varchar,
    password_in         in varchar,
    oracle_contact_id_in in varchar,
    prefix_in           in varchar,
    first_names_in      in varchar,
    last_name_in        in varchar,
    genqual_in          in varchar,
    parent_company_in   in varchar,
    company_in          in varchar,
    title_in            in varchar,
    phone_in            in varchar,
    fax_in              in varchar,
    email_in            in varchar,
    pin_in              in numeric,
    first_names_ol_in   in varchar,
    last_name_ol_in     in varchar,
    address1_in         in varchar,
    address2_in         in varchar,
    address3_in         in varchar,
    city_in             in varchar,
    state_in            in varchar,
    zip_in              in varchar,
    country_in          in varchar,
    alt_first_names_in  in varchar,
    alt_last_name_in    in varchar,
    contact_call_in     varchar,
    contact_mail_in     varchar,
    contact_email_in    varchar,
    contact_fax_in      varchar
)
returns numeric
AS
$$
declare
    user_id_tmp             numeric;


    -- Would be using the below variables instead of the last four parameters
    contact_call_in_tmp     varchar := 'N';
    contact_mail_in_tmp     varchar := 'N';
    contact_email_in_tmp    varchar := 'N';
    contact_fax_in_tmp      varchar := 'N';
begin
    select nextval('web_contact_id_seq') into user_id_tmp;

    insert into web_contact
        (id, org_id, login, login_uc, password, oracle_contact_id)
    values
        (user_id_tmp, org_id_in, login_in, upper(login_in), password_in, oracle_contact_id_in::numeric);

    insert into web_user_contact_permission
        (web_user_id, call, mail, email, fax)
    values
        (user_id_tmp, contact_call_in_tmp, contact_mail_in_tmp, contact_email_in_tmp, contact_fax_in_tmp);

    insert into web_user_personal_info
        (web_user_id, prefix, first_names, last_name, genqual,
        parent_company, company, title, phone, fax, email, pin,
        first_names_ol, last_name_ol)
    values
        (user_id_tmp, prefix_in, first_names_in, last_name_in, genqual_in,
        parent_company_in, company_in, title_in, phone_in, fax_in, email_in, pin_in :: numeric,
        first_names_ol_in, last_name_ol_in);

    if address1_in != '.' then
        insert into web_user_site_info
            (id, web_user_id, email,
            address1, address2, address3,
            city, state, zip, country, phone, fax, type,
            alt_first_names, alt_last_name)
        values
            (nextval('web_user_site_info_id_seq'), user_id_tmp, email_in,
            address1_in, address2_in, address3_in,
            city_in, state_in, zip_in, country_in, phone_in, fax_in, 'M',
            alt_first_names_in, alt_last_name_in);
    end if;

    insert into rhnUserInfo
        (user_id)
    values
        (user_id_tmp);

    return user_id_tmp;
end;
$$
language plpgsql;

-- ## web_contact triggers

create or replace function web_contact_upd_trig_fun() returns trigger
as
$$
begin
        new.modified := current_timestamp;
        new.login_uc := UPPER(new.login);

        return new;
end;
$$
language plpgsql;

-- ## drop web_contact.old_password

alter table web_contact drop column old_password;
 07070100000A74000081B400000000000000000000000167AE111400001516000000000000000000000000000000000000006C00000000susemanager-schema/upgrade/susemanager-schema-1.7.57-to-susemanager-schema-2.1/5005-support-for-aarch64.sql   insert into rhnChannelArch (id, label, name, arch_type_id) select
sequence_nextval('rhn_channel_arch_id_seq'), 'channel-aarch64', 'AArch64', lookup_arch_type('rpm') from dual
where not exists (select 1 from rhnChannelArch where label = 'channel-aarch64');

insert into rhnPackageArch (id, label, name, arch_type_id) select
sequence_nextval('rhn_package_arch_id_seq'), 'aarch64', 'AArch64', lookup_arch_type('rpm') from dual
where not exists (select 1 from rhnPackageArch where label ='aarch64');

insert into rhnChannelPackageArchCompat (channel_arch_id, package_arch_id) select
LOOKUP_CHANNEL_ARCH('channel-aarch64'), LOOKUP_PACKAGE_ARCH('aarch64') from dual
where not exists (select 1 from rhnChannelPackageArchCompat where channel_arch_id = LOOKUP_CHANNEL_ARCH('channel-aarch64') and package_arch_id = LOOKUP_PACKAGE_ARCH('aarch64'));
insert into rhnChannelPackageArchCompat (channel_arch_id, package_arch_id) select
LOOKUP_CHANNEL_ARCH('channel-aarch64'), LOOKUP_PACKAGE_ARCH('noarch') from dual
where not exists (select 1 from rhnChannelPackageArchCompat where channel_arch_id = LOOKUP_CHANNEL_ARCH('channel-aarch64') and package_arch_id = LOOKUP_PACKAGE_ARCH('noarch'));

insert into rhnServerArch (id, label, name, arch_type_id) select
sequence_nextval('rhn_server_arch_id_seq'), 'aarch64-redhat-linux', 'aarch64', lookup_arch_type('rpm') from dual
where not exists (select 1 from rhnServerArch where label = 'aarch64-redhat-linux');

insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) select
LOOKUP_PACKAGE_ARCH('noarch'), LOOKUP_PACKAGE_ARCH('aarch64'), current_timestamp, current_timestamp from dual
where not exists (select 1 from rhnPackageUpgradeArchCompat where package_arch_id = LOOKUP_PACKAGE_ARCH('noarch') and package_upgrade_arch_id = LOOKUP_PACKAGE_ARCH('aarch64'));
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) select
LOOKUP_PACKAGE_ARCH('aarch64'), LOOKUP_PACKAGE_ARCH('aarch64'), current_timestamp, current_timestamp from dual
where not exists (select 1 from rhnPackageUpgradeArchCompat where package_arch_id = LOOKUP_PACKAGE_ARCH('aarch64') and package_upgrade_arch_id = LOOKUP_PACKAGE_ARCH('aarch64'));
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) select
LOOKUP_PACKAGE_ARCH('aarch64'), LOOKUP_PACKAGE_ARCH('noarch'), current_timestamp, current_timestamp from dual
where not exists (select 1 from rhnPackageUpgradeArchCompat where package_arch_id = LOOKUP_PACKAGE_ARCH('aarch64') and package_upgrade_arch_id = LOOKUP_PACKAGE_ARCH('noarch'));

insert into rhnServerChannelArchCompat (server_arch_id, channel_arch_id) select
LOOKUP_SERVER_ARCH('aarch64-redhat-linux'), LOOKUP_CHANNEL_ARCH('channel-aarch64') from dual
where not exists (select 1 from rhnServerChannelArchCompat where server_arch_id = LOOKUP_SERVER_ARCH('aarch64-redhat-linux') and channel_arch_id = LOOKUP_CHANNEL_ARCH('channel-aarch64'));

insert into rhnServerPackageArchCompat (server_arch_id, package_arch_id, preference) select
LOOKUP_SERVER_ARCH('aarch64-redhat-linux'), LOOKUP_PACKAGE_ARCH('aarch64'), 0 from dual
where not exists (select 1 from rhnServerPackageArchCompat where server_arch_id = LOOKUP_SERVER_ARCH('aarch64-redhat-linux') and package_arch_id = LOOKUP_PACKAGE_ARCH('aarch64'));


insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type) select
LOOKUP_SERVER_ARCH('aarch64-redhat-linux'), LOOKUP_SG_TYPE('sw_mgr_entitled') from dual
where not exists (select 1 from rhnServerServerGroupArchCompat where server_arch_id = LOOKUP_SERVER_ARCH('aarch64-redhat-linux') and server_group_type = LOOKUP_SG_TYPE('sw_mgr_entitled'));
insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type) select
LOOKUP_SERVER_ARCH('aarch64-redhat-linux'), LOOKUP_SG_TYPE('enterprise_entitled') from dual
where not exists (select 1 from rhnServerServerGroupArchCompat where server_arch_id = LOOKUP_SERVER_ARCH('aarch64-redhat-linux') and server_group_type = LOOKUP_SG_TYPE('enterprise_entitled'));
insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type) select
LOOKUP_SERVER_ARCH('aarch64-redhat-linux'), LOOKUP_SG_TYPE('provisioning_entitled') from dual
where not exists (select 1 from rhnServerServerGroupArchCompat where server_arch_id = LOOKUP_SERVER_ARCH('aarch64-redhat-linux') and server_group_type = LOOKUP_SG_TYPE('provisioning_entitled'));
insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type) select
LOOKUP_SERVER_ARCH('aarch64-redhat-linux'), LOOKUP_SG_TYPE('monitoring_entitled') from dual
where not exists (select 1 from rhnServerServerGroupArchCompat where server_arch_id = LOOKUP_SERVER_ARCH('aarch64-redhat-linux') and server_group_type = LOOKUP_SG_TYPE('monitoring_entitled'));
insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type) select
LOOKUP_SERVER_ARCH('aarch64-redhat-linux'), LOOKUP_SG_TYPE('virtualization_host') from dual
where not exists (select 1 from rhnServerServerGroupArchCompat where server_arch_id = LOOKUP_SERVER_ARCH('aarch64-redhat-linux') and server_group_type = LOOKUP_SG_TYPE('virtualization_host'));

insert into rhnCpuArch (id, label, name) select
sequence_nextval('rhn_cpu_arch_id_seq'), 'aarch64', 'AArch64' from dual
where not exists (select 1 from rhnCpuArch where label = 'aarch64');
  07070100000A75000081B400000000000000000000000167AE111400000A06000000000000000000000000000000000000006D00000000susemanager-schema/upgrade/susemanager-schema-1.7.57-to-susemanager-schema-2.1/5006-web_contact-password.sql  
drop view rhnWebContactEnabled;
drop view rhnUserReceiveNotifications;
drop view rhnWebContactDisabled;
drop view rhn_contact_monitoring;

alter table web_contact alter password type varchar(110);

create or replace view
rhnWebContactDisabled
as
select
   wcon.id,
   wcon.org_id,
   wcon.login,
   wcon.login_uc,
   wcon.password,
   wcon.oracle_contact_id,
   wcon.created,
   wcon.modified,
   wcon.ignore_flag
from
   rhnWebContactChangeLog   wccl,
   rhnWebContactChangeState wccs,
   web_contact              wcon
where wccl.change_state_id = wccs.id
   and wccs.label = 'disabled'
   and wccl.web_contact_id = wcon.id
   and wccl.date_completed =
              (select max(wccl_exists.date_completed)
                 from rhnWebContactChangeLog   wccl_exists
                where wccl.web_contact_id = wccl_exists.web_contact_id);

create or replace view
rhnWebContactEnabled
as
select
   wcon.id,
   wcon.org_id,
   wcon.login,
   wcon.login_uc,
   wcon.password,
   wcon.oracle_contact_id,
   wcon.created,
   wcon.modified,
   wcon.ignore_flag
from
   web_contact wcon
where not exists (
     select 1 from rhnWebContactDisabled
     where wcon.id = rhnWebContactDisabled.id
   );

create or replace view rhnUserReceiveNotifications
as
    select wc.org_id, usp.user_id, usp.server_id
    from rhnUserServerPerms usp
    left join rhnWebContactDisabled wcd
        on usp.user_id = wcd.id
    join web_contact wc
        on usp.user_id = wc.id
    join rhnUserInfo ui
        on usp.user_id = ui.user_id
        and ui.email_notify = 1
    join web_user_personal_info upi
        on usp.user_id = upi.web_user_id
        and upi.email is not null
    left join rhnUserServerPrefs uspr
        on uspr.server_id = usp.server_id
        and usp.user_id = uspr.user_id
        and uspr.name = 'receive_notifications'
        and value='0'
    where uspr.server_id is null
    and wcd.id is null;

create or replace view rhn_contact_monitoring as
select  u.id                    as recid,
        u.org_id                as customer_id,
        wupi.last_name          as contact_last_name,
        wupi.first_names        as contact_first_name,
        wupi.email          as email_address,
        u.login                 as username,
        u.password              as password,
        1                       as schedule_id,
        'GMT' || ''                     as preferred_time_zone
from
        web_user_personal_info wupi,
        web_contact u
where   u.id = wupi.web_user_id
        --  and some logic here to check org id for entitlements?
;
  07070100000A76000081B400000000000000000000000167AE1114000000A0000000000000000000000000000000000000006800000000susemanager-schema/upgrade/susemanager-schema-1.7.57-to-susemanager-schema-2.1/5010-web_contact_log.sql   
alter table web_contact_log drop column old_password;

alter table web_contact_log alter password type varchar(110);

select .recreate_trigger('web_contact');
07070100000A77000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005100000000susemanager-schema/upgrade/susemanager-schema-2.1-to-susemanager-schema-2.1.50.3  07070100000A78000081B400000000000000000000000167AE111400000039000000000000000000000000000000000000005800000000susemanager-schema/upgrade/susemanager-schema-2.1-to-susemanager-schema-2.1.50.3/README   -- Schema upgrade scripts.
-- leave this directory empty
   07070100000A79000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005800000000susemanager-schema/upgrade/susemanager-schema-2.1.50.10-to-susemanager-schema-2.1.50.11   07070100000A7A000081B400000000000000000000000167AE1114000108A5000000000000000000000000000000000000007500000000susemanager-schema/upgrade/susemanager-schema-2.1.50.10-to-susemanager-schema-2.1.50.11/001-rhn_entitlements.pkb.sql  
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--

-- create schema rhn_entitlements;

-- setup search_path so that these functions are created in appropriate schema.
update pg_settings set setting = 'rhn_entitlements,' || setting where name = 'search_path';

   create or replace function find_compatible_sg (
      server_id_in in numeric,
      type_label_in in varchar
   )
   returns numeric
as $$
    declare
      servergroups cursor for
         select sg.id
           from rhnServerGroupType             sgt,
                rhnServerGroup                 sg,
                rhnServer                     s,
                rhnServerServerGroupArchCompat ssgac
          where s.id = server_id_in
            and s.org_id = sg.org_id
            and sgt.label = type_label_in
            and sg.group_type = sgt.id
            and ssgac.server_group_type = sgt.id
            and ssgac.server_arch_id = s.server_arch_id
            and not exists ( 
                     select 1
                      from rhnServerGroupMembers sgm
                     where sgm.server_group_id = sg.id 
                       and sgm.server_id = s.id);

         
   begin
      for servergroup in servergroups loop
         return servergroup.id;
      end loop;

      --no servergroup found
      return NULL;
   end$$
language plpgsql;

    -- *******************************************************************
    -- PROCEDURE: remove_org_entitlements
    --
    -- Removes both system entitlements and channel subscriptions
    -- that are currently assigned to an org and re-assigns to the
    -- master org (org_id = 1).
    --
    -- When we call this we expect everything to already be unentitled
    -- which shoul be handled by delete_org.
    --
    -- Called by: delete_org
    -- *******************************************************************
    create or replace function remove_org_entitlements (
        org_id_in numeric
    ) returns void
as $$
    declare
        system_ents cursor for
        select sg.id, sg.max_members, sg.group_type
        from rhnServerGroup sg
        where group_type is not null
          and org_id = org_id_in;

        channel_subs cursor for
        select pcf.channel_family_id, pcf.max_members
        from rhnChannelFamily cf,
             rhnPrivateChannelFamily pcf
        where pcf.org_id = org_id_in
          and pcf.channel_family_id = cf.id
          and cf.org_id is null;

    begin

        for system_ent in system_ents loop
            update rhnServerGroup
            set max_members = max_members + system_ent.max_members
            where org_id = 1
              and group_type = system_ent.group_type;
        end loop;

        update rhnServerGroup
        set max_members = 0
        where org_id = org_id_in;

        for channel_sub in channel_subs loop
            update rhnPrivateChannelFamily
            set max_members = max_members + channel_sub.max_members
            where org_id = 1
              and channel_family_id = channel_sub.channel_family_id;
        end loop;
        
        update rhnPrivateChannelFamily
        set max_members = 0
        where org_id = org_id_in;

    end$$
language plpgsql;

    create or replace function entitlement_grants_service (
        entitlement_in in varchar,
        service_level_in in varchar
    ) returns numeric
as $$
    begin
        if service_level_in = 'provisioning' then
            if entitlement_in = 'provisioning_entitled' then
                return 1;
            else
                return 0;
            end if;
        elsif service_level_in = 'management' then
            if entitlement_in = 'enterprise_entitled' then
                return 1;
            else
                return 0;
            end if;
        elsif service_level_in = 'monitoring' then
            if entitlement_in = 'monitoring_entitled' then
                return 1;
            end if;
        elsif service_level_in = 'updates' then
            return 1;           
        else
            return 0;
        end if;
    end$$
language plpgsql;

    create or replace function lookup_entitlement_group (
        org_id_in in numeric,
        type_label_in in varchar default 'sw_mgr_entitled'
    ) returns numeric
as $$
    declare
        server_groups cursor for
            select  sg.id               server_group_id
            from    rhnServerGroup      sg,
                    rhnServerGroupType  sgt
            where   sgt.label = type_label_in
                and sgt.id = sg.group_type
                and sg.org_id = org_id_in;
    begin
        for sg in server_groups loop
            return sg.server_group_id;
        end loop;
        return rhn_entitlements.create_entitlement_group(
                org_id_in, 
                type_label_in
            );
    end$$
language plpgsql;

    create or replace function create_entitlement_group (
        org_id_in in numeric,
        type_label_in in varchar default 'sw_mgr_entitled'
    ) returns numeric
as $$
    declare
        sg_id_val numeric;
    begin
        select  nextval('rhn_server_group_id_seq')
        into    sg_id_val;

        insert into rhnServerGroup (
                id, name, description, max_members, current_members,
                group_type, org_id
            ) (
                select  sg_id_val, sgt.label, sgt.label,
                        0, 0, sgt.id, org_id_in
                from    rhnServerGroupType sgt
                where   sgt.label = type_label_in
            );

        return sg_id_val;
    end$$
language plpgsql;

   create or replace function can_entitle_server ( 
      server_id_in   in numeric, 
      type_label_in  in varchar
   )
   returns numeric
as $$
    declare
      addon_servergroups cursor (base_label_in varchar, 
                                 addon_label_in varchar) for
         select
            addon_id
         from
            rhnSGTypeBaseAddonCompat
         where base_id = lookup_sg_type (base_label_in)
           and addon_id = lookup_sg_type (addon_label_in);

      previous_ent        varchar[];
      is_base_in          char   := 'N';
      is_base_current     char   := 'N';
      i                   numeric := 0;
      sgid                numeric := 0;

   begin

      previous_ent := rhn_entitlements.get_server_entitlement(server_id_in);

      select distinct is_base
      into is_base_in
      from rhnServerGroupType
      where label = type_label_in;

      if array_upper(previous_ent, 1) is null or array_upper(previous_ent, 1) = 0 then
         if is_base_in = 'Y' then
            sgid := rhn_entitlements.find_compatible_sg (server_id_in, type_label_in);
            if sgid is not null then
              -- rhn_server.insert_into_servergroup (server_id_in, sgid);
              return 1;
            else
              -- rhn_exception.raise_exception ('invalid_base_entitlement');
              return 0;
            end if;
         else
            -- rhn_exception.raise_exception ('invalid_base_entitlement');
            return 0;
         end if;

      -- there are previous ents, first make sure we're not trying to entitle a base ent
      elsif is_base_in = 'Y' then
         -- rhn_exception.raise_exception ('invalid_addon_entitlement');
         return 0;

      -- it must be an addon, so proceed with the entitlement
      else

         -- find the servers base ent
         is_base_current := 'N';
         i := 0;
         while is_base_current = 'N' and i < array_upper(previous_ent, 1)
         loop
            i := i + 1;
            select is_base
            into is_base_current
            from rhnServerGroupType
            where label = previous_ent[i];
         end loop;

         -- never found a base ent, that would be strange
         if is_base_current  = 'N' then
            -- rhn_exception.raise_exception ('invalid_base_entitlement');
            return 0;
         end if;

         -- this for loop verifies the validity of the addon path
         for addon_servergroup in addon_servergroups  (previous_ent[i], type_label_in) loop
            -- find an appropriate sgid for the addon and entitle the server
            sgid := rhn_entitlements.find_compatible_sg (server_id_in, type_label_in);
            if sgid is not null then
               -- rhn_server.insert_into_servergroup (server_id_in, sgid);
               return 1;
            else
               -- rhn_exception.raise_exception ('invalid_addon_entitlement');
               return 0;
            end if;
         end loop;

      end if;

      return 0;

   end$$
language plpgsql;

   create or replace function can_switch_base ( 
      server_id_in   in    integer, 
      type_label_in  in    varchar
   )
   returns numeric
as $$
   declare
      type_label_in_is_base   char(1);
      sgid                    numeric;

   begin

       select is_base into type_label_in_is_base
       from rhnServerGroupType
       where label = type_label_in;

       if not found then
          perform rhn_exception.raise_exception ( 'invalid_entitlement' );
       end if;

      if type_label_in_is_base = 'N' then
         perform rhn_exception.raise_exception ( 'invalid_entitlement' );
      else
         sgid := rhn_entitlements.find_compatible_sg ( server_id_in,
                                                       type_label_in );
         if sgid is not null then
           return 1;
         else
           return 0;
         end if;
      end if;

   end$$
language plpgsql;

    create or replace function entitle_server (
        server_id_in in numeric,
        type_label_in in varchar default 'sw_mgr_entitled'
    ) returns void
as $$
    declare
      sgid  numeric := 0;
      is_virt numeric := 0;

    begin

      select 1 into is_virt
        from rhnServerEntitlementView
        where server_id = server_id_in
          and label in ('virtualization_host', 'virtualization_host_platform');

      if not found then
          is_virt := 0;
      end if;
      
      if is_virt = 0 and (type_label_in = 'virtualization_host' or
                          type_label_in = 'virtualization_host_platform') then

        is_virt := 1;
      end if;

      if rhn_entitlements.can_entitle_server(server_id_in, 
                                             type_label_in) = 1 then
         sgid := rhn_entitlements.find_compatible_sg (server_id_in,
                                                      type_label_in);
         if sgid is not null then
            insert into rhnServerHistory ( id, server_id, summary, details )
            values ( nextval('rhn_event_id_seq'), server_id_in,
                     'added system entitlement ',
                      case type_label_in
                       when 'enterprise_entitled' then 'Management'
                       when 'bootstrap_entitled' then 'Bootstrap'
                       when 'sw_mgr_entitled' then 'Update'
                       when 'provisioning_entitled' then 'Provisioning'
                       when 'monitoring_entitled' then 'Monitoring'  
                       when 'virtualization_host' then 'Virtualization'
                       when 'virtualization_host_platform' then 
                            'Virtualization Platform' end  );

            perform rhn_server.insert_into_servergroup (server_id_in, sgid);

            if is_virt = 1 then
              perform rhn_entitlements.repoll_virt_guest_entitlements(server_id_in);
            end if;

         else
            perform rhn_exception.raise_exception ('no_available_server_group');
         end if;
      else
         perform rhn_exception.raise_exception ('invalid_entitlement');
      end if;
   end$$
language plpgsql;

    create or replace function remove_server_entitlement (
        server_id_in in numeric,
        type_label_in in varchar default 'sw_mgr_entitled',
        repoll_virt_guests in numeric default 1
    ) returns void
as $$
    declare
      group_id numeric;
      type_is_base char;
      is_virt numeric := 0;
    begin
      -- would be nice if there were a virt attribute of entitlement types, not have to specify 2 different ones...
        select 1 into is_virt
          from rhnServerEntitlementView
          where server_id = server_id_in
            and label in ('virtualization_host', 'virtualization_host_platform');
        if not found then
            is_virt := 0;
        end if;

        select  sg.id, sgt.is_base
        into group_id, type_is_base
        from    rhnServerGroupType sgt,
            rhnServerGroup sg,
                rhnServerGroupMembers sgm,
                rhnServer s
        where   s.id = server_id_in
            and s.id = sgm.server_id
            and sgm.server_group_id = sg.id
            and sg.org_id = s.org_id
            and sgt.label = type_label_in
            and sgt.id = sg.group_type;

        if not found then
          perform rhn_exception.raise_exception('invalid_server_group_member');
        end if;

      if ( type_is_base = 'Y' ) then
         -- unentitle_server should handle everything, don't really need to do anything else special here
         perform rhn_entitlements.unentitle_server ( server_id_in );
      else

         insert into rhnServerHistory ( id, server_id, summary, details )
         values ( nextval('rhn_event_id_seq'), server_id_in,
                  'removed system entitlement ',
                   case type_label_in
                    when 'enterprise_entitled' then 'Management'
                    when 'bootstrap_entitled' then 'Bootstrap'
                    when 'sw_mgr_entitled' then 'Update'
                    when 'provisioning_entitled' then 'Provisioning'
                    when 'monitoring_entitled' then 'Monitoring'
                    when 'virtualization_host' then 'Virtualization'
                    when 'virtualization_host_platform' then 
                         'Virtualization Platforrm' end  );

         perform rhn_server.delete_from_servergroup(server_id_in, group_id);

         if type_label_in = 'monitoring_entitled' then
           DELETE
             FROM rhn_probe
            WHERE recid IN (SELECT probe_id
                              FROM rhn_check_probe
                             WHERE host_id = server_id_in);
         end if;

         if is_virt = 1 and repoll_virt_guests = 1 then
           perform rhn_entitlements.repoll_virt_guest_entitlements(server_id_in);
         end if;
      end if;

    end$$
language plpgsql;

    create or replace function unentitle_server (
        server_id_in in numeric
    ) returns void
as $$
    declare
      servergroups cursor for
         select distinct sgt.label, sg.id server_group_id
         from  rhnServerGroupType sgt,
               rhnServerGroup sg,
               rhnServer s,
               rhnServerGroupMembers sgm
         where s.id = server_id_in
            and s.org_id = sg.org_id
            and sg.group_type = sgt.id
            and sgm.server_group_id = sg.id
            and sgm.server_id = s.id;
            
     is_virt numeric := 0;

   begin

      select 1 into is_virt
        from rhnServerEntitlementView
        where server_id = server_id_in
         and label in ('virtualization_host', 'virtualization_host_platform');

      if not found then
          is_virt := 0;
      end if;

      for servergroup in servergroups loop

         insert into rhnServerHistory ( id, server_id, summary, details )
         values ( nextval('rhn_event_id_seq'), server_id_in,
                  'removed system entitlement ',
                   case servergroup.label
                    when 'enterprise_entitled' then 'Management'
                    when 'bootstrap_entitled' then 'Bootstrap'
                    when 'sw_mgr_entitled' then 'Update'
                    when 'provisioning_entitled' then 'Provisioning'
                    when 'monitoring_entitled' then 'Monitoring'
                    when 'virtualization_host' then 'Virtualization'
                    when 'virtualization_host_platform' then 
                         'Virtualization Platform' end  );
  
         perform rhn_server.delete_from_servergroup(server_id_in, 
                                            servergroup.server_group_id );
      end loop;

      if is_virt = 1 then
        perform rhn_entitlements.repoll_virt_guest_entitlements(server_id_in);
      end if;

   end$$
language plpgsql;


    -- *******************************************************************
    -- PROCEDURE: repoll_virt_guest_entitlements
    --
    --   Whenever we add/remove a virtualization_host* entitlement from 
    --   a host, we can call this procedure to update what type of slots
    --   the guests are consuming.  
    -- 
    --   If you're removing the entitlement, it's 
    --   possible the guests will become unentitled if you don't have enough
    --   physical slots to cover them.
    --
    --   If you're adding the entitlement, you end up freeing up physical
    --   slots for other systems.
    --
    -- *******************************************************************
    create or replace function repoll_virt_guest_entitlements(
        server_id_in in numeric
    ) returns void
as $$
    declare
        -- All channel families associated with the guests of server_id_in
        families cursor for 
            select distinct cfs.channel_family_id
            from
                rhnChannelFamilyServers cfs,
                rhnVirtualInstance vi
            where
                vi.host_system_id = server_id_in
                and vi.virtual_system_id = cfs.server_id;
        
        -- All of server group types associated with the guests of
        -- server_id_in
        group_types cursor for
            select distinct sg.group_type, sgt.label, sg.org_id
            from
                rhnServerGroupType sgt,
                rhnServerGroup sg,
                rhnServerGroupMembers sgm,
                rhnVirtualInstance vi
            where
                vi.host_system_id = server_id_in
                and vi.virtual_system_id = sgm.server_id
                and sgm.server_group_id = sg.id
                and sg.group_type = sgt.id;

        -- Virtual servers from a certain family belonging to a specific
        -- host that are consuming physical channel slots over the limit.
        virt_servers_cfam cursor(family_id_in numeric, quantity_in numeric) for
                select vi.virtual_system_id
                from
                    rhnChannelFamilyMembers cfm,
                    rhnServerChannel sc,
                    rhnVirtualInstance vi
                where
                    vi.host_system_id = server_id_in
                    and vi.virtual_system_id = sc.server_id
                    and sc.channel_id = cfm.channel_id
                    and cfm.channel_family_id = family_id_in
                order by sc.modified desc
                limit quantity_in;                

        -- Virtual servers from a certain family belonging to a specific
        -- host that are consuming physical system slots over the limit.
        virt_servers_sgt cursor(group_type_in numeric, quantity_in numeric) for
                select vi.virtual_system_id
                from
                    rhnServerGroup sg,
                    rhnServerGroupMembers sgm,
                    rhnVirtualInstance vi
                where
                    vi.host_system_id = server_id_in
                    and vi.virtual_system_id = sgm.server_id
                    and sgm.server_group_id = sg.id
                    and sg.group_type = group_type_in
                order by sgm.modified desc
                limit quantity_in;                
        
        -- Get the orgs of Virtual guests
        -- Since they may belong to different orgs
        virt_guest_orgs cursor for
                select  distinct (s.org_id)
                from rhnServer s
                    inner join  rhnVirtualInstance vi on vi.virtual_system_id = s.id
                where
                    vi.host_system_id = server_id_in
                    and s.org_id <> (select s1.org_id from rhnServer s1 where s1.id = vi.host_system_id) ;

        org_id_val numeric;
        max_members_val numeric;
        max_flex_val numeric;
        current_members_calc numeric;
        sg_id numeric;
        is_virt numeric := 0;
        free_slots numeric := 0;
    begin
          select 1 into is_virt
                from rhnServerEntitlementView
           where server_id = server_id_in
                 and label in ('virtualization_host', 'virtualization_host_platform');

      if not found then
          is_virt := 0;
      end if;

        select org_id
        into org_id_val
        from rhnServer
        where id = server_id_in;

        -- deal w/ channel entitlements first ...
        for family in families loop
            if is_virt = 0 then
            -- if the host_server does not have virt
            --- find all possible flex slots
            -- and set each of the flex eligible guests to Y
                select sfc.max_members - sfc.current_members
                  into free_slots
                  from rhnServerFveCapable sfc
                 where sfc.channel_family_id = family.channel_family_id;
                UPDATE rhnServerChannel sc set is_fve = 'Y'
                where sc.server_id in (
                            select vi.virtual_system_id
                            from rhnServerFveCapable sfc
                                inner join rhnVirtualInstance vi on vi.virtual_system_id = sfc.server_id
                            where vi.host_system_id = server_id_in
                                  and sfc.channel_family_id = family.channel_family_id
                              order by vi.modified desc
                            limit free_slots
                );
            else
            -- if the host_server has virt
            -- set all its flex guests to N
                UPDATE rhnServerChannel sc set is_fve = 'N'
                where
                    sc.channel_id in (select cfm.channel_id from rhnChannelFamilyMembers cfm
                                      where cfm.CHANNEL_FAMILY_ID = family.channel_family_id)
                    and sc.is_fve = 'Y'
                    and sc.server_id in
                            (select vi.virtual_system_id  from rhnVirtualInstance vi
                                    where vi.host_system_id = server_id_in);
            end if;

            -- get the current (physical) members of the family
            current_members_calc := 
                rhn_channel.channel_family_current_members(family.channel_family_id,
                                                           org_id_val); -- fixed transposed args

            -- get the max members of the family
            select max_members
            into max_members_val
            from rhnPrivateChannelFamily
            where channel_family_id = family.channel_family_id
            and org_id = org_id_val;

            select fve_max_members
            into max_flex_val
            from rhnPrivateChannelFamily
            where channel_family_id = family.channel_family_id
            and org_id = org_id_val;

            if current_members_calc > max_members_val then
                -- A virtualization_host* ent must have been removed, so we'll
                -- unsubscribe guests from the host first.

                -- hm, i don't think max_members - current_members_calc yielding a negative number
                -- will work w/ rownum, swaping 'em in the body of this if...
                for virt_server in virt_servers_cfam(family.channel_family_id,
                                current_members_calc - max_members_val) loop 

                    perform rhn_channel.unsubscribe_server_from_family(
                                virt_server.virtual_system_id,
                                family.channel_family_id);
                end loop;                               

                -- if we're still over the limit, which would be odd,
                -- just prune the group to max_members
                --
                -- er... wouldn't we actually have to refresh the values of
                -- current_members_calc and max_members_val to actually ever
                -- *skip this??
                if current_members_calc > max_members_val then
                    -- argh, transposed again?!
                    perform rhn_entitlements.set_family_count(org_id_val,
                                     family.channel_family_id,
                                     max_members_val, max_flex_val);
                    --TODO calculate this correctly
                end if; 

           end if;

            -- update current_members for the family.  This will set the value
            -- to reflect adding/removing the entitlement.
            --
            -- what's the difference of doing this vs the unavoidable set_family_count above?
            perform rhn_channel.update_family_counts(family.channel_family_id,
                                             org_id_val);

            -- It is possible that the guests belong  to a different org than the host
            -- so we are going to update the family counts in the guests orgs also
            for org in virt_guest_orgs loop
                    perform rhn_channel.update_family_counts(family.channel_family_id,
                                             org.org_id);
            end loop;
        end loop;

        for a_group_type in group_types loop
          -- get the current *physical* members of the system entitlement type for the org...
          -- 
          -- unlike channel families, it appears the standard rhnServerGroup.max_members represents
          -- *physical* slots, vs physical+virt ... boy that's confusing...

          select max_members, id
            into max_members_val, sg_id
            from rhnServerGroup
            where group_type = a_group_type.group_type
            and org_id = a_group_type.org_id;


      select count(sep.server_id) into current_members_calc
            from rhnServerEntitlementPhysical sep
           where sep.server_group_id = sg_id
             and sep.server_group_type_id = a_group_type.group_type;
          
          if current_members_calc > max_members_val then
            -- A virtualization_host* ent must have been removed, and we're over the limit, so unsubscribe guests
            for virt_server in virt_servers_sgt(a_group_type.group_type,
                                                current_members_calc - max_members_val) loop
              perform rhn_entitlements.remove_server_entitlement(virt_server.virtual_system_id, a_group_type.label);

              -- decrement current_members_calc, we'll use it to reset current_members for the group at the end...
              current_members_calc := current_members_calc - 1;
            end loop;

          end if;

          update rhnServerGroup set current_members = current_members_calc
           where org_id = a_group_type.org_id
             and group_type = a_group_type.group_type;

          -- I think that's all the house-keeping we have to do...
        end loop;

    end$$
language plpgsql;

    create or replace function get_server_entitlement (
        server_id_in in numeric
    ) returns varchar[]
as $$
    declare
        server_groups cursor for
            select  sgt.label
            from    rhnServerGroupType      sgt,
                    rhnServerGroup          sg,
                    rhnServerGroupMembers   sgm
            where   1=1
                and sgm.server_id = server_id_in
                and sg.id = sgm.server_group_id
                and sgt.id = sg.group_type
                and sgt.label in (
                    'sw_mgr_entitled','enterprise_entitled', 'bootstrap_entitled',
                    'provisioning_entitled', 'nonlinux_entitled',
                    'monitoring_entitled', 'virtualization_host',
                                        'virtualization_host_platform'
                    );

         ent_array varchar[];

    begin
      
      ent_array := '{}';

      for sg in server_groups loop
         ent_array := ent_array || sg.label;
      end loop;

      return ent_array;

    end$$
language plpgsql;

    -- this desperately needs to be table driven.
    create or replace function modify_org_service (
        org_id_in in numeric,
        service_label_in in varchar,
        enable_in in char
    ) returns void
as $$
    declare
        roles_to_process varchar[];
        roles cursor(role_label_in varchar) for
            select  label, id
            from    rhnUserGroupType
            where   label = role_label_in;
        org_roles cursor(role_label_in varchar) for
            select  1
            from    rhnUserGroup ug,
                    rhnUserGroupType ugt
            where   ugt.label = role_label_in
                and ug.org_id = org_id_in
                and ugt.id = ug.group_type;
                
        ents_to_process varchar[];
        ents cursor(ent_label_in varchar) for
            select  label, id
            from    rhnOrgEntitlementType
            where   label = ent_label_in;
        org_ents cursor(ent_label_in varchar) for
            select  1
            from    rhnOrgEntitlements oe,
                    rhnOrgEntitlementType oet
            where   oet.label = ent_label_in
                and oe.org_id = org_id_in
                and oet.id = oe.entitlement_id;
        create_row char(1);
    begin
        ents_to_process := '{}';
        roles_to_process := '{}';
        -- a bit kludgy, but only for 3.4 really.  Certainly no
        -- worse than the old code...
        if service_label_in = 'enterprise' or 
           service_label_in = 'management' then
            ents_to_process := array_append(ents_to_process, 'sw_mgr_enterprise');

            roles_to_process := array_append(roles_to_process, 'org_admin');

            roles_to_process := array_append(roles_to_process, 'system_group_admin');

            roles_to_process := array_append(roles_to_process, 'activation_key_admin');
        elsif service_label_in = 'provisioning' then
            ents_to_process := array_append(ents_to_process, 'rhn_provisioning');

            roles_to_process := array_append(roles_to_process, 'system_group_admin');

            roles_to_process := array_append(roles_to_process, 'activation_key_admin');

            roles_to_process := array_append(roles_to_process, 'config_admin');
            -- another nasty special case...
            if enable_in = 'Y' then
                ents_to_process := array_append(ents_to_process, 'sw_mgr_enterprise');
            end if;
        elsif service_label_in = 'monitoring' then
            ents_to_process := array_append(ents_to_process, 'rhn_monitor');

            roles_to_process := array_append(roles_to_process, 'monitoring_admin');
        elsif service_label_in = 'virtualization' then
            ents_to_process := array_append(ents_to_process, 'rhn_virtualization');

            roles_to_process := array_append(roles_to_process, 'config_admin');
        elsif service_label_in = 'virtualization_platform' then
            ents_to_process := array_append(ents_to_process, 'rhn_virtualization_platform');
            roles_to_process := array_append(roles_to_process, 'config_admin');
    elsif service_label_in = 'nonlinux' then
            ents_to_process := array_append(ents_to_process, 'rhn_nonlinux');
            roles_to_process := array_append(roles_to_process, 'config_admin');
        end if;

        if enable_in = 'Y' then
            for i in 1..array_upper(ents_to_process, 1) loop
                for ent in ents(ents_to_process[i]) loop
                    create_row := 'Y';
                    for oe in org_ents(ent.label) loop
                        create_row := 'N';
                    end loop;
                    if create_row = 'Y' then
                        insert into rhnOrgEntitlements(org_id, entitlement_id)
                            values (org_id_in, ent.id);
                    end if;
                end loop;
            end loop;
            for i in 1..array_upper(roles_to_process, 1) loop
                for role in roles(roles_to_process[i]) loop
                    create_row := 'Y';
                    for o_r in org_roles(role.label) loop
                        create_row := 'N';
                    end loop;
                    if create_row = 'Y' then
                        insert into rhnUserGroup(
                                id, name, description, current_members,
                                group_type, org_id
                            ) (
                                select  nextval('rhn_user_group_id_seq'),
                                        ugt.name || 's',
                                        ugt.name || 's for Org ' ||
                                            o.name || ' ('|| o.id ||')',
                                        0, ugt.id, o.id
                                from    rhnUserGroupType ugt,
                                        web_customer o
                                where   o.id = org_id_in
                                    and ugt.id = role.id
                            );
                    end if;
                end loop;
            end loop;
        else
            for i in 1..coalesce(array_upper(ents_to_process, 1), 0) loop
                for ent in ents(ents_to_process[i]) loop
                    delete from rhnOrgEntitlements
                     where org_id = org_id_in
                       and entitlement_id = ent.id;
                end loop;
            end loop;
        end if;
    end$$
language plpgsql;

    create or replace function set_customer_enterprise (
        customer_id_in in numeric
    ) returns void
as $$
    begin
        perform rhn_entitlements.modify_org_service(customer_id_in, 'enterprise', 'Y');
    end$$
language plpgsql;

    create or replace function set_customer_provisioning (
        customer_id_in in numeric
    ) returns void
as $$
    begin
        perform rhn_entitlements.modify_org_service(customer_id_in, 'provisioning', 'Y');
    end$$
language plpgsql;

    create or replace function set_customer_monitoring (
        customer_id_in in numeric
    ) returns void
as $$
    begin
        perform rhn_entitlements.modify_org_service(customer_id_in, 'monitoring', 'Y');
    end$$
language plpgsql;

    create or replace function set_customer_nonlinux (
        customer_id_in in numeric
    ) returns void
as $$
    begin
        perform rhn_entitlements.modify_org_service(customer_id_in, 'nonlinux', 'Y');
    end$$
language plpgsql;

    create or replace function unset_customer_enterprise (
        customer_id_in in numeric
    ) returns void
as $$
    begin
        perform rhn_entitlements.modify_org_service(customer_id_in, 'enterprise', 'N');
    end$$
language plpgsql;

    create or replace function unset_customer_provisioning (
        customer_id_in in numeric
    ) returns void
as $$
    begin
        perform rhn_entitlements.modify_org_service(customer_id_in, 'provisioning', 'N');
    end$$
language plpgsql;

    create or replace function unset_customer_monitoring (
        customer_id_in in numeric
    ) returns void
as $$
    begin
        perform rhn_entitlements.modify_org_service(customer_id_in, 'monitoring', 'N');
    end$$
language plpgsql;

    create or replace function unset_customer_nonlinux (
        customer_id_in in numeric
    ) returns void
as $$
    begin
        perform rhn_entitlements.modify_org_service(customer_id_in, 'nonlinux', 'N');
    end$$
language plpgsql;

    -- *******************************************************************
    -- PROCEDURE: prune_group
    -- Unsubscribes servers consuming physical slots that over the org's
    --   limit.
    -- Called by: set_server_group_count, repoll_virt_guest_entitlements
    -- *******************************************************************
    create or replace function prune_group (
        group_id_in in numeric,
        quantity_in in numeric,
        update_family_countsYN in numeric default 1
    ) returns void
as $$
    declare
        sgrecord record;
      type_is_base char;
    begin
            update      rhnServerGroup
                set     max_members = quantity_in
                where   id = group_id_in;

            for sgrecord in (
		   select  server_id, server_group_id, sgt.id as group_type_id, sgt.label
		    from    rhnServerGroupType              sgt,
				    rhnServerGroup                  sg,
				    rhnServerGroupMembers   sgm
		    where   1=1
			    and sgm.server_group_id = group_id_in
			    and sgm.server_id in (
				    select  sep.server_id
				    from
					rhnServerEntitlementPhysical sep
				    where
					sep.server_group_id = group_id_in
				    order by sep.modified asc
				    offset quantity_in
				)
			    and sgm.server_group_id = sg.id
			    and sg.group_type = sgt.id
	    ) loop
                perform rhn_entitlements.remove_server_entitlement(sgrecord.server_id, sgrecord.label);
            
            select is_base 
            into type_is_base
            from rhnServerGroupType sgt
            where sgt.id = sgrecord.group_type_id;

            -- if we're removing a base ent, then be sure to
            -- remove the server's channel subscriptions.
            if ( type_is_base = 'Y' ) then
                   perform rhn_channel.clear_subscriptions(sgrecord.server_id, 0, update_family_countsYN);
            end if;

            end loop;
    end$$
language plpgsql;

    -- *******************************************************************
    -- PROCEDURE: assign_system_entitlement
    --
    -- Moves system entitlements from from_org_id_in to to_org_id_in.
    -- Can raise not_enough_entitlements_in_base_org if from_org_id_in
    -- does not have enough entitlements to cover the move.
    -- Takes care of unentitling systems if necessary by calling 
    -- set_server_group_count
    -- *******************************************************************
    create or replace function assign_system_entitlement(
        group_label_in in varchar,
        from_org_id_in in numeric,
        to_org_id_in in numeric,
        quantity_in in numeric
    ) returns void
as $$
    declare
        prev_ent_count numeric;
    to_org_prev_ent_count numeric;
        new_ent_count numeric;
    new_quantity numeric;
        group_type numeric;
    begin

            select max_members
            into prev_ent_count
            from rhnServerGroupType sgt,
                 rhnServerGroup sg
            where sg.org_id = from_org_id_in
              and sg.group_type = sgt.id
              and sgt.label = group_label_in;

            if not found then
                perform rhn_exception.raise_exception(
                              'not_enough_entitlements_in_base_org');
            end if;

            select max_members
            into to_org_prev_ent_count
            from rhnServerGroupType sgt,
                 rhnServerGroup sg
            where sg.org_id = to_org_id_in
              and sg.group_type = sgt.id
              and sgt.label = group_label_in;

            if not found then
                to_org_prev_ent_count := 0;
            end if;
    
            select id
            into group_type
            from rhnServerGroupType
            where label = group_label_in;

            if not found then
                perform rhn_exception.raise_exception(
                              'invalid_server_group');
            end if;

        new_ent_count := prev_ent_count - quantity_in;
    
        if prev_ent_count > new_ent_count then
            new_quantity := to_org_prev_ent_count + quantity_in;
        end if;
    
        if new_ent_count < 0 then
            perform rhn_exception.raise_exception(
                          'not_enough_entitlements_in_base_org');
        end if;


        perform rhn_entitlements.set_server_group_count(from_org_id_in,
                                         group_type,
                                         new_ent_count);

        perform rhn_entitlements.set_server_group_count(to_org_id_in,
                                         group_type,
                                         new_quantity);
        
        -- Create or delete the entries in rhnOrgEntitlementType
        if group_label_in = 'enterprise_entitled' then 
            if new_quantity > 0 then
                perform rhn_entitlements.set_customer_enterprise(to_org_id_in);
            else
                perform rhn_entitlements.unset_customer_enterprise(to_org_id_in);
            end if;
        end if;

        if group_label_in = 'provisioning_entitled' then
            if new_quantity > 0 then
                perform rhn_entitlements.set_customer_provisioning(to_org_id_in);
            else
                perform rhn_entitlements.unset_customer_provisioning(to_org_id_in);
            end if;
        end if;

        if group_label_in = 'monitoring_entitled' then
            if new_quantity > 0 then
                perform rhn_entitlements.set_customer_monitoring(to_org_id_in);
            else
                perform rhn_entitlements.unset_customer_monitoring(to_org_id_in);
            end if;
        end if;

    end$$
language plpgsql;

    -- *******************************************************************
    -- PROCEDURE: assign_channel_entitlement
    --
    -- Moves channel entitlements from from_org_id_in to to_org_id_in.
    -- Can raise not_enough_entitlements_in_base_org if from_org_id_in
    -- does not have enough entitlements to cover the move.
    -- Takes care of unentitling systems if necessary by calling 
    -- set_family_count
    -- *******************************************************************
    create or replace function assign_channel_entitlement(
        channel_family_label_in in varchar,
        from_org_id_in in numeric,
        to_org_id_in in numeric,
        quantity_in in numeric,
        flex_in in numeric
    ) returns void
as $$
    declare
        from_org_prev_ent_count numeric;
        from_org_prev_ent_count_flex numeric;
        new_ent_count numeric;
        new_ent_count_flex numeric;
        to_org_prev_ent_count numeric;
        to_org_prev_ent_count_flex numeric;
        new_quantity numeric;
        new_flex numeric;
        cfam_id       numeric;
    begin

            select max_members
            into from_org_prev_ent_count
            from rhnChannelFamily cf,
                 rhnPrivateChannelFamily pcf
            where pcf.org_id = from_org_id_in
              and pcf.channel_family_id = cf.id
              and cf.label = channel_family_label_in;

            if not found then
                perform rhn_exception.raise_exception(
                              'not_enough_entitlements_in_base_org');
            end if;
    
            select max_members
            into to_org_prev_ent_count
            from rhnChannelFamily cf,
                 rhnPrivateChannelFamily pcf
            where pcf.org_id = to_org_id_in
              and pcf.channel_family_id = cf.id
              and cf.label = channel_family_label_in;

            if not found then
                to_org_prev_ent_count := 0;
            end if;

            select fve_max_members
            into from_org_prev_ent_count_flex
            from rhnChannelFamily cf,
                rhnPrivateChannelFamily pcf
            where pcf.org_id = from_org_id_in
              and pcf.channel_family_id = cf.id
              and cf.label = channel_family_label_in;

            if not found then
                perform rhn_exception.raise_exception(
                              'not_enough_flex_entitlements_in_base_org');
            end if;

            select fve_max_members
            into to_org_prev_ent_count_flex
            from rhnChannelFamily cf,
                 rhnPrivateChannelFamily pcf
            where pcf.org_id = to_org_id_in
              and pcf.channel_family_id = cf.id
              and cf.label = channel_family_label_in;

            if not found then
                to_org_prev_ent_count_flex := 0;
            end if;

            select id
            into cfam_id
            from rhnChannelFamily
            where label = channel_family_label_in;

            if not found then
                perform rhn_exception.raise_exception(
                              'invalid_channel_family');
            end if;

        new_ent_count := from_org_prev_ent_count - quantity_in;
        new_ent_count_flex := from_org_prev_ent_count_flex - flex_in;
    
        if from_org_prev_ent_count >= new_ent_count then
            new_quantity := to_org_prev_ent_count + quantity_in;
        end if;

        if from_org_prev_ent_count_flex >= new_ent_count_flex then
            new_flex := to_org_prev_ent_count_flex + flex_in;
        end if;

        if new_ent_count < 0 then
            perform rhn_exception.raise_exception(
                          'not_enough_entitlements_in_base_org');
        end if;

        if new_ent_count_flex < 0 then
            perform rhn_exception.raise_exception(
                          'not_enough_flex_entitlements_in_base_org');
        end if;



        perform rhn_entitlements.set_family_count(from_org_id_in,
                                          cfam_id,
                                          new_ent_count,
                                          new_ent_count_flex);

        perform rhn_entitlements.set_family_count(to_org_id_in,
                                          cfam_id,
                                          new_quantity,
                                          new_flex);

    end$$
language plpgsql;

    -- *******************************************************************
    -- PROCEDURE: activate_system_entitlement
    --
    -- Sets the values in rhnServerGroup for a given rhnServerGroupType.
    -- 
    -- Calls: set_server_group_count to update, prune, or create the group.
    -- Called by: the code that activates a satellite cert. 
    --
    -- Raises not_enough_entitlements_in_base_org if all entitlements
    -- in the org are used so the free entitlements would not cover
    -- the difference when descreasing the number of entitlements.
    -- *******************************************************************
    create or replace function activate_system_entitlement(
        org_id_in in numeric,
        group_label_in in varchar,
        quantity_in in numeric
    ) returns void
as $$
    declare
        prev_ent_count numeric; 
        prev_ent_count_sum numeric; 
        group_type numeric;
    begin

        -- Fetch the current entitlement count for the org
        -- into prev_ent_count

            select current_members
            into prev_ent_count
            from rhnServerGroupType sgt,
                 rhnServerGroup sg
            where sg.group_type = sgt.id
              and sgt.label = group_label_in
              and sg.org_id = org_id_in;

            if not found then
                prev_ent_count := 0;
            end if;

            select id
            into group_type
            from rhnServerGroupType
            where label = group_label_in;

            if not found then
                perform rhn_exception.raise_exception(
                              'invalid_server_group');
            end if;

        -- If we're setting the total entitlemnt count to a lower value,
        -- and that value is less than the allocated count in this org,
        -- we need to raise an exception.
        if quantity_in < prev_ent_count then
            perform rhn_exception.raise_exception(
                          'not_enough_entitlements_in_base_org');
        else
            -- don't update family counts after every server
            -- will do bulk update afterwards
            perform rhn_entitlements.set_server_group_count(org_id_in,
                                             group_type,
                                             quantity_in,
                                             0);
            -- bulk update family counts
            perform rhn_channel.update_group_family_counts(group_label_in, org_id_in);
        end if;

    end$$
language plpgsql;

    -- *******************************************************************
    -- PROCEDURE: activate_channel_entitlement
    --
    -- Calls: set_family_count to update, prune, or create the family
    --        permission bucket.
    -- Called by: the code that activates a satellite cert. 
    --
    -- Raises not_enough_entitlements_in_base_org if there are not enough
    -- entitlements in the org to cover the difference when you are
    -- descreasing the number of entitlements.
    --
    -- The backend code in Python is expected to do whatever arithmetics
    -- is needed.
    -- *******************************************************************
    create or replace function activate_channel_entitlement(
        org_id_in in numeric,
        channel_family_label_in in varchar,
        quantity_in in numeric,
        flex_in in numeric
    ) returns void
as $$
    declare
        prev_ent_count numeric; 
        prev_flex_count numeric;
        prev_ent_count_sum numeric; 
        cfam_id numeric;
        reduce_quantity numeric;
        total_flex_capable numeric;
        to_convert_reg cursor (channel_family_id_val numeric, org_id_in numeric, quantity numeric) for
                     select SC.server_id
                     from rhnServerChannel SC inner join
                          rhnServer S on S.id = SC.server_id
                     where
                         is_fve = 'Y'
                         and S.org_id = org_id_in
                         and SC.channel_id in
                         (select cfm.channel_id from rhnChannelFamilyMembers cfm
                             where cfm.CHANNEL_FAMILY_ID = channel_family_id_val)
                         limit quantity;
         to_convert_flex cursor (channel_family_id_val numeric, org_id_in numeric, quantity numeric) for
                   select server_id
                   from rhnServerFveCapable
                       where SERVER_ORG_ID = org_id_in and
                             channel_family_id = cfam_id
                       limit quantity;

    begin

        -- Fetch the current entitlement count for the org
        -- into prev_ent_count
            select current_members
            into prev_ent_count
            from rhnChannelFamily cf,
                 rhnPrivateChannelFamily pcf
            where pcf.org_id = org_id_in
              and pcf.channel_family_id = cf.id
              and cf.label = channel_family_label_in;

            if not found then
                prev_ent_count := 0;
            end if;

            select pcf.fve_current_members
            into prev_flex_count
            from rhnChannelFamily cf,
                 rhnPrivateChannelFamily pcf
            where pcf.org_id = org_id_in
              and pcf.channel_family_id = cf.id
              and cf.label = channel_family_label_in;

            if not found then
                prev_flex_count := 0;
            end if;

            select id
            into cfam_id
            from rhnChannelFamily
            where label = channel_family_label_in;

            if not found then
                perform rhn_exception.raise_exception(
                              'invalid_channel_family');
            end if;

        -- if there are too few flex entitlements
        if flex_in < prev_flex_count then
            -- and if the extra we need is less than or equal to our extra regular entitlements
            if prev_flex_count - flex_in <= quantity_in - prev_ent_count then
                   reduce_quantity := prev_flex_count - flex_in;
                   -- We need to convert some systems from flex guest to regular
                   for system in to_convert_reg(cfam_id, org_id_in, reduce_quantity) loop
                      --rhn_channel.convert_to_regular(system.server_id, cfam_id);
                      UPDATE rhnServerChannel sc set is_fve = 'N'
                           where sc.server_id = system.server_id
                                 and sc.channel_id in (select cfm.channel_id
                                                          from rhnChannelFamilyMembers cfm
                                                          where cfm.channel_family_id = cfam_id);
                   end loop;

                   --reset previous counts
                   prev_ent_count := prev_ent_count + reduce_quantity;
                   prev_flex_count := prev_flex_count - reduce_quantity;
            else
                perform rhn_exception.raise_exception(
                          'not_enough_flex_entitlements_in_base_org');
            end if;
        end if;

        -- if there are too few regular entitlements, and extra flex entitlements
        if quantity_in < prev_ent_count and prev_flex_count < flex_in then
                -- how many flex-capable systems (that aren't using flex) do we have
                select count(*)
                   into total_flex_capable
                   from rhnServerFveCapable
                       where SERVER_ORG_ID = org_id_in and
                             channel_family_id = cfam_id;
                -- if we have enough flex capable machines that is at least
                --   as many as what we are over on
                if total_flex_capable >= prev_ent_count - quantity_in then
                    reduce_quantity := prev_ent_count - quantity_in;
                    for system in to_convert_flex(cfam_id, org_id_in, reduce_quantity) loop
--                          rhn_channel.convert_to_fve(system.server_id, cfam_id);
                        UPDATE rhnServerChannel sc set is_fve = 'Y'
                           where sc.server_id = system.server_id
                                 and sc.channel_id in (select cfm.channel_id
                                                          from rhnChannelFamilyMembers cfm
                                                          where cfm.channel_family_id = cfam_id);
                    end loop;
                    prev_ent_count := prev_ent_count - reduce_quantity;
                    prev_flex_count := prev_flex_count + reduce_quantity;
                end if;
        end if;

        -- If we're setting the total entitlemnt count to a lower value,
        -- and that value is less than the count in that one org,
        -- we need to raise an exception.
        if quantity_in < prev_ent_count then
            perform rhn_exception.raise_exception(
                          'not_enough_entitlements_in_base_org');
        else
            -- even if we've manually converted systems to/from flex above
            -- set_family_count should call update_family_counts, to reset
            -- current used slots
            perform rhn_entitlements.set_family_count(org_id_in, cfam_id,
                                              quantity_in, flex_in);
        end if;

    end$$
language plpgsql;

    create or replace function set_server_group_count (
        customer_id_in in numeric,  -- customer_id
        group_type_in in numeric,   -- rhn[User|Server]GroupType.id
        quantity_in in numeric,      -- quantity
                update_family_countsYN in numeric default 1
    ) returns void
as $$
    declare
        group_id numeric;
        quantity numeric;
        wasfound boolean;
    begin
        quantity := quantity_in;
        if quantity is not null and quantity < 0 then
            quantity := 0;
        end if;

        select  rsg.id
        into    group_id
        from    rhnServerGroup rsg
        where   1=1
            and rsg.org_id = customer_id_in
            and rsg.group_type = group_type_in;

        -- preserve the not found status across the rhn_entitlements.prune_group invocation
        wasfound := true;
        if not found then
            wasfound := false;
        end if;

        perform rhn_entitlements.prune_group(
            group_id,
            quantity,
                        update_family_countsYN
        );

        if not wasfound then
            insert into rhnServerGroup (
                    id, name, description, max_members, current_members,
                    group_type, org_id, created, modified
                ) (
                    select  nextval('rhn_server_group_id_seq'), name, name,
                            quantity, 0, id, customer_id_in,
                            current_timestamp, current_timestamp
                    from    rhnServerGroupType
                    where   id = group_type_in
            );
        end if;

    end$$
language plpgsql;

    -- *******************************************************************
    -- PROCEDURE: prune_family
    -- Unsubscribes servers consuming physical slots from the channel family 
    --   that are over the org's limit.
    -- Called by: set_family_count
    -- *******************************************************************
    create or replace function prune_family (
        customer_id_in in numeric,
        channel_family_id_in in numeric,
        quantity_in in numeric,
        flex_in in numeric
    ) returns void
as $$
    declare
        serverchannels cursor(tmp_quantity numeric, is_fve_in char) for
            select  sc.server_id,
                    sc.channel_id
            from    rhnServerChannel sc,
                    rhnChannelFamilyMembers cfm
            where   1=1
                and cfm.channel_family_id = channel_family_id_in
                and cfm.channel_id = sc.channel_id
                and server_id in (
                       select server_id from (
                            select  distinct rs.id as server_id
                            from    
                                    rhnServerChannel        rsc,
                                    rhnChannelFamilyMembers rcfm,
                                    rhnServer               rs
                            where   1=1
                                and rs.org_id = customer_id_in
                                and rs.id = rsc.server_id
                                and rsc.channel_id = rcfm.channel_id
                                and rcfm.channel_family_id =  channel_family_id_in
                                and rsc.is_fve = is_fve_in
                                -- we only want to grab servers consuming
                                -- physical slots.
                                and exists (
                                    select 1
                                    from rhnChannelFamilyServerPhysical cfsp
                                    where cfsp.server_id = rs.id
                                    and cfsp.channel_family_id = 
                                        channel_family_id_in
                                    )
                            ) Q
                        order by server_id asc
                        offset quantity_in
                        );
    begin
        -- if we get a null customer_id, this is completely bogus.
        if customer_id_in is null then
            return;
        end if;

        for sc in serverchannels(quantity_in, 'N') loop
            perform rhn_channel.unsubscribe_server(sc.server_id, sc.channel_id,
                                                   1, 1, 0, 0);
        end loop;

        for sc in serverchannels(flex_in, 'Y') loop
            perform rhn_channel.unsubscribe_server(sc.server_id, sc.channel_id,
                                                   1, 1, 0, 0);
        end loop;

        perform rhn_channel.update_family_counts(channel_family_id_in, customer_id_in);
    end$$
language plpgsql;
        
    create or replace function set_family_count (
        customer_id_in in numeric,      -- customer_id
        channel_family_id_in in numeric,    -- 246
        quantity_in in numeric,          -- 3
        flex_in in numeric
    ) returns void
as $$
    declare
        privperms cursor for
            select  1
            from    rhnPrivateChannelFamily
            where   org_id = customer_id_in
                and channel_family_id = channel_family_id_in;
        pubperms cursor for
            select  o.id org_id
            from    web_customer o,
                    rhnPublicChannelFamily pcf
            where   pcf.channel_family_id = channel_family_id_in;
        quantity numeric;
        done numeric := 0;
        flex numeric;
    begin
        quantity := quantity_in;
        if quantity is not null and quantity < 0 then
            quantity := 0;
        end if;
        flex := flex_in;
        if flex is not null and flex < 0 then
            flex := 0;
        end if;

        if customer_id_in is not null then
            for perm in privperms loop
                perform rhn_entitlements.prune_family(
                    customer_id_in,
                    channel_family_id_in,
                    quantity,
                    flex
                );

                if quantity is null and flex is null then
                    delete from rhnPrivateChannelFamily
                        where org_id = customer_id_in
                            and channel_family_id = channel_family_id_in;
                 else
                    update rhnPrivateChannelFamily
                        set max_members = quantity
                        where org_id = customer_id_in
                            and channel_family_id = channel_family_id_in;

                   update rhnPrivateChannelFamily
                        set fve_max_members = flex
                        where org_id = customer_id_in
                            and channel_family_id = channel_family_id_in;
                end if;
                return;
            end loop;

            insert into rhnPrivateChannelFamily (
                    channel_family_id, org_id, max_members, current_members, fve_max_members, fve_current_members
                ) values (
                    channel_family_id_in, customer_id_in, quantity, 0, flex, 0 );
            return;
        end if;

        for perm in pubperms loop
            if quantity = 0 then
                perform rhn_entitlements.prune_family(
                    perm.org_id,
                    channel_family_id_in,
                    quantity,
                    flex
                );
                if done = 0 then
                    delete from rhnPublicChannelFamily
                        where channel_family_id = channel_family_id_in;
                end if;
            end if;
            done := 1;
        end loop;
        -- if done's not 1, then we don't have any entitlements
        if done != 1 then
            insert into rhnPublicChannelFamily (
                    channel_family_id
                ) values (
                    channel_family_id_in
                );
        end if;
    end$$
language plpgsql;

    -- this expects quantity_in to be the number of available slots, not the
    -- max_members of the server group.  If you give it too many, it'll fail
    -- and raise servergroup_max_members.
    -- We should NEVER run this unless we're SURE that we won't
    -- be violating the max.
    create or replace function entitle_last_modified_servers (
        customer_id_in in numeric,  -- customer_id
        type_label_in in varchar,   -- 'enterprise_entitled'
        quantity_in in numeric      -- 3
    ) returns void
as $$
    declare
        -- find the servers that aren't currently in slots
        servers cursor(cid_in numeric, quant_in numeric) for
                                    select  rs.id as server_id
                                    from    rhnServer rs
                                    where   1=1
                                        and rs.org_id = cid_in
                                        and not exists (
                                            select  1
                                            from    rhnServerGroup sg,
                                                    rhnServerGroupMembers rsgm
                                            where   rsgm.server_id = rs.id
                                                and rsgm.server_group_id = sg.id
                                                and sg.group_type is not null
                                        )
                                        and not exists (
                                            select 1
                                            from rhnVirtualInstance vi
                                            where vi.virtual_system_id =
                                                  rs.id
                                        )
                                    order by modified desc
                                    limit quant_in;
    begin
        for server in servers(customer_id_in, quantity_in) loop
            perform rhn_entitlements.entitle_server(server.server_id, type_label_in);
        end loop;
    end$$
language plpgsql;

    create or replace function subscribe_newest_servers (
        customer_id_in in numeric
    ) returns void
as $$
    declare
        -- find servers without base channels
        servers cursor(cid_in numeric) for
            select  s.id
            from    rhnServer           s
            where   1=1
                and s.org_id = cid_in
                and not exists (
                        select 1
                        from    rhnChannel          c,
                                rhnServerChannel    sc
                        where   sc.server_id = s.id
                            and sc.channel_id = c.id
                            and c.parent_channel is null
                    )
                and not exists (
                        select 1
                        from rhnVirtualInstance vi
                        where vi.virtual_system_id = s.id
                    )                        
            order by s.modified desc;
        channel_id numeric;
    begin
        for server in servers(customer_id_in) loop
            channel_id := rhn_channel.guess_server_base(server.id);
            if channel_id is not null then
                begin
                    perform rhn_channel.subscribe_server(server.id, channel_id);
                -- exception is really channel_family_no_subscriptions
                exception
                    when others then
                        null;
                end;
            end if;
        end loop;
    end$$
language plpgsql;


-- restore the original setting
update pg_settings set setting = overlay( setting placing '' from 1 for (length('rhn_entitlements')+1) ) where name = 'search_path';
   07070100000A7B000081B400000000000000000000000167AE111400000029000000000000000000000000000000000000008400000000susemanager-schema/upgrade/susemanager-schema-2.1.50.10-to-susemanager-schema-2.1.50.11/002-pxe-bootstrap_ent-to-rhnServerGroup.sql   
-- this file is intentionally left blank   07070100000A7C000081B400000000000000000000000167AE1114000001D9000000000000000000000000000000000000007B00000000susemanager-schema/upgrade/susemanager-schema-2.1.50.10-to-susemanager-schema-2.1.50.11/003-suseSCCRepository-sequence.sql    --
-- Copyright (c) 2015 SUSE
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
--

CREATE SEQUENCE suse_sccrepository_id_seq;
   07070100000A7D000081B400000000000000000000000167AE1114000001E0000000000000000000000000000000000000008400000000susemanager-schema/upgrade/susemanager-schema-2.1.50.10-to-susemanager-schema-2.1.50.11/004-suseSCCRepository-add-scc-id-column.sql   --
-- Copyright (c) 2015 SUSE
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
--

ALTER TABLE suseSCCRepository ADD scc_id NUMERIC;
07070100000A7E000081B400000000000000000000000167AE111400000081000000000000000000000000000000000000008200000000susemanager-schema/upgrade/susemanager-schema-2.1.50.10-to-susemanager-schema-2.1.50.11/005-fix-max_members-in-rhnServerGroup.sql 
select .clear_log_id();

UPDATE rhnServerGroup
   SET max_members = 0
 WHERE max_members IS NULL
   AND group_type IS NOT NULL;
   07070100000A7F000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005800000000susemanager-schema/upgrade/susemanager-schema-2.1.50.11-to-susemanager-schema-2.1.50.12   07070100000A80000081B400000000000000000000000167AE1114000000F1000000000000000000000000000000000000007700000000susemanager-schema/upgrade/susemanager-schema-2.1.50.11-to-susemanager-schema-2.1.50.12/001-delete-cached-repodata.sql    delete from rhnPackageRepodata;

insert into rhnRepoRegenQueue (id, CHANNEL_LABEL, REASON, FORCE)
(select sequence_nextval('rhn_repo_regen_queue_id_seq'),
        C.label,
        'fix double XML quoting',
        'Y'
   from rhnChannel C);
   07070100000A81000081B400000000000000000000000167AE1114000061CF000000000000000000000000000000000000008A00000000susemanager-schema/upgrade/susemanager-schema-2.1.50.11-to-susemanager-schema-2.1.50.12/002-avoid_deadlock_update_server_needed_cache.sql --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--

-- create schema rhn_server;

--update pg_setting
update pg_settings set setting = 'rhn_server,' || setting where name = 'search_path';

    create or replace function system_service_level(
    	server_id_in in numeric,
	service_level_in in varchar
    ) returns numeric as $$
    declare
    ents cursor is 
      select label from rhnServerEntitlementView
      where server_id = server_id_in;

    retval numeric := 0;

    begin
         for ent in ents loop
            retval := rhn_entitlements.entitlement_grants_service (ent.label, service_level_in);
            if retval = 1 then
               return retval;
            end if;
         end loop;

         return retval;

    end$$ language plpgsql;

        
    create or replace function can_change_base_channel(server_id_in IN NUMERIC)
    returns numeric
    as $$
    declare
    	throwaway numeric;
    begin
    	-- the idea: if we get past this query, the server is
	-- neither sat nor proxy, so base channel is changeable

	select 1 into throwaway
	  from rhnServer S
	 where S.id = server_id_in
	   and not exists (select 1 from rhnSatelliteInfo SI where SI.server_id = S.id)
	   and not exists (select 1 from rhnProxyInfo PI where PI.server_id = S.id);

        if not found then
	    return 0;
        end if;
	   
	return 1;
    end$$ language plpgsql;
	        
    create or replace function set_custom_value(
    	server_id_in in numeric,
	user_id_in in numeric,
	key_label_in in varchar,
	value_in in varchar
    ) returns void
    as $$
    declare
    	key_id_val numeric;
    begin
    	select CDK.id into strict key_id_val
	  from rhnCustomDataKey CDK,
	       rhnServer S
	 where S.id = server_id_in
	   and S.org_id = CDK.org_id
	   and CDK.label = key_label_in;
	   
	begin
	    insert into rhnServerCustomDataValue (server_id, key_id, value, created_by, last_modified_by)
	    values (server_id_in, key_id_val, value_in, user_id_in, user_id_in);
	exception
	    when UNIQUE_VIOLATION
	    	then
		update rhnServerCustomDataValue
		   set value = value_in,
		       last_modified_by = user_id_in
		 where server_id = server_id_in
		   and key_id = key_id_val;		   
	end;

    end$$ language plpgsql;
    
    create or replace function bulk_set_custom_value(
    	key_label_in in varchar,
	value_in in varchar,
	set_label_in in varchar,
	set_uid_in in numeric
    )
    returns integer
    as $$
    declare
        i integer;
        server record;
    begin
        i := 0;
        for server in (
           SELECT user_id, label, element, element_two
	     FROM rhnSet
	    WHERE label = set_label_in
	      AND user_id = set_uid_in
	) loop
	    if rhn_server.system_service_level(server.element, 'provisioning') = 1 then
	    	perform rhn_server.set_custom_value(server.element, set_uid_in, key_label_in, value_in);
            i := i + 1;
	    end if;
	end loop;
    return i;
    end$$ language plpgsql;

    create or replace function bulk_snapshot_tag(
    	org_id_in in numeric,
        tagname_in in varchar,
	set_label_in in varchar,
	set_uid_in in numeric
    ) returns void
    as $$
    declare
        server record;
    	snapshot_id numeric;
    begin
        for server in (
           SELECT user_id, label, element, element_two
	     FROM rhnSet
	    WHERE label = set_label_in
	      AND user_id = set_uid_in
	    ) loop
	    if rhn_server.system_service_level(server.element, 'provisioning') = 1 then
	    	    select max(id) into snapshot_id
	    	    from rhnSnapshot
	    	    where server_id = server.element;

	    	    if snapshot_id is null then
		    	perform rhn_server.snapshot_server(server.element, 'tagging system:  ' || tagname_in);
			
			select max(id) into snapshot_id
			from rhnSnapshot
			where server_id = server.element;
		    end if;
		 
		-- now have a snapshot_id to work with...
		begin
		    perform rhn_server.tag_snapshot(snapshot_id, org_id_in, tagname_in);
		exception
		    when UNIQUE_VIOLATION
		    	then
			-- do nothing, be forgiving...
			null;
		end;
	    end if;
	end loop;    
    end$$ language plpgsql;

    create or replace function tag_delete(
    	server_id_in in numeric,
	tag_id_in in numeric
    ) returns void
    as $$
    declare
    	snapshots cursor is
		select	snapshot_id
		from	rhnSnapshotTag
		where	tag_id = tag_id_in;
	tag_id_tmp numeric;
    begin
    	select	id into tag_id_tmp
	from	rhnTag
	where	id = tag_id_in
	for update;

	delete
		from	rhnSnapshotTag
		where	server_id = server_id_in
			and tag_id = tag_id_in;
	for snapshot in snapshots loop
		return;
	end loop;
	delete
		from rhnTag
		where id = tag_id_in;
    end$$ language plpgsql;

    create or replace function tag_snapshot(
        snapshot_id_in in numeric,
	org_id_in in numeric,
	tagname_in in varchar
    ) returns void
    as $$
    begin
    	insert into rhnSnapshotTag (snapshot_id, server_id, tag_id)
	select snapshot_id_in, server_id, lookup_tag(org_id_in, tagname_in)
	from rhnSnapshot
	where id = snapshot_id_in;
    end$$ language plpgsql;

    create or replace function bulk_snapshot(
    	reason_in in varchar,
	set_label_in in varchar,
	set_uid_in in numeric
    ) returns void
    as $$
    declare
        server record;
    begin
        for server in (
           SELECT user_id, label, element, element_two
	     FROM rhnSet
	    WHERE label = set_label_in
	      AND user_id = set_uid_in
	    ) loop
    	    if rhn_server.system_service_level(server.element, 'provisioning') = 1 then
	    	perform rhn_server.snapshot_server(server.element, reason_in);
	    end if;
	end loop;
    end$$ language plpgsql;

    create or replace function snapshot_server(
    	server_id_in in numeric,
	reason_in in varchar
    ) returns void
    as $$
    declare
    	snapshot_id_v numeric;
	revisions cursor is
		select distinct
			cr.id
		from	rhnConfigRevision	cr,
			rhnConfigFileName	cfn,
			rhnConfigFile		cf,
			rhnConfigChannel	cc,
			rhnServerConfigChannel	scc
		where	1=1
			and scc.server_id = server_id_in
			and scc.config_channel_id = cc.id
			and cc.id = cf.config_channel_id
			and cf.id = cr.config_file_id
			and cr.id = cf.latest_config_revision_id
			and cf.config_file_name_id = cfn.id
			and cf.id = lookup_first_matching_cf(scc.server_id, cfn.path);
	locked integer;
    begin
    	select nextval('rhn_snapshot_id_seq') into snapshot_id_v;

	insert into rhnSnapshot (id, org_id, server_id, reason) (
		select	snapshot_id_v,
			s.org_id,
			server_id_in,
			reason_in
		from	rhnServer s
		where	s.id = server_id_in
	);
	insert into rhnSnapshotChannel (snapshot_id, channel_id) (
		select	snapshot_id_v, sc.channel_id
		from	rhnServerChannel sc
		where	sc.server_id = server_id_in
	);
	insert into rhnSnapshotServerGroup (snapshot_id, server_group_id) (
		select	snapshot_id_v, sgm.server_group_id
		from	rhnServerGroupMembers sgm
		where	sgm.server_id = server_id_in
	);
        locked := 0;
        <<iloop>>
        while true loop
            begin
                insert into rhnPackageNEVRA (id, name_id, evr_id, package_arch_id)
                select nextval('rhn_pkgnevra_id_seq'), sp.name_id, sp.evr_id, sp.package_arch_id
                from rhnServerPackage sp
                where sp.server_id = server_id_in
                        and not exists
                        (select 1
                                from rhnPackageNEVRA nevra
                                where nevra.name_id = sp.name_id
                                        and nevra.evr_id = sp.evr_id
                                        and (nevra.package_arch_id = sp.package_arch_id
                                            or (nevra.package_arch_id is null
                                                and sp.package_arch_id is null)));
                exit iloop;
            exception when unique_violation then
                if locked = 1 then
                    raise;
                else
                    lock table rhnPackageNEVRA in exclusive mode;
                    locked := 1;
                end if;
            end;
        end loop;
	insert into rhnSnapshotPackage (snapshot_id, nevra_id) (
                select distinct snapshot_id_v, nevra.id
                from    rhnServerPackage sp, rhnPackageNEVRA nevra
                where   sp.server_id = server_id_in
                        and nevra.name_id = sp.name_id
                        and nevra.evr_id = sp.evr_id
                        and (nevra.package_arch_id = sp.package_arch_id
                            or (nevra.package_arch_id is null
                                and sp.package_arch_id is null))
	);

	insert into rhnSnapshotConfigChannel ( snapshot_id, config_channel_id ) (
		select	snapshot_id_v, scc.config_channel_id
		from	rhnServerConfigChannel scc
		where	server_id = server_id_in
	);

	for revision in revisions loop
		insert into rhnSnapshotConfigRevision (
				snapshot_id, config_revision_id
			) values (
				snapshot_id_v, revision.id
			);
	end loop;
    end$$ language plpgsql;

    create or replace function remove_action(
    	server_id_in in numeric,
	action_id_in in numeric
    ) returns void
    as $$
    declare
    	-- this really wants "nulls last", but 8.1.7.3.0 sucks ass.
	-- instead, we make a local table that holds our
	-- list of ids with null prereqs.  There's surely a better way
	-- (an array instead of a table maybe?  who knows...)
	-- but I've got code to do this handy that I can look at ;)
    	chained_actions cursor is
                with recursive r(id, prerequisite) as (
			select	id, prerequisite
			from	rhnAction
			where id = action_id_in
		union all
			select	r1.id, r1.prerequisite
			from	rhnAction r1, r
			where r.id = r1.prerequisite
		)
		select * from r
		order by prerequisite desc;
	sessions cursor is
		select	s.id
		from	rhnKickstartSession s
		where	server_id_in in (s.old_server_id, s.new_server_id)
			and s.action_id = action_id_in
			and not exists (
				select	1
				from	rhnKickstartSessionState ss
				where	ss.id = s.state_id
					and ss.label in ('failed','complete')
			);
	chain_ends numeric[];
	i numeric;
	prereq numeric := 1;
    begin
	select	prerequisite
	into	prereq
	from	rhnAction
	where	id = action_id_in;

	if prereq is not null then
		perform rhn_exception.raise_exception('action_is_child');
	end if;

        chain_ends := '{}';
	i := 1;
	for action in chained_actions loop
		if action.prerequisite is null then
			chain_ends[i] := action.id;
			i := i + 1;
		else
			delete from rhnServerAction
				where server_id = server_id_in
				and action_id = action.id;
		end if;
	end loop;

	delete from rhnServerAction
		where server_id = server_id_in
		and action_id = any(chain_ends);

	for s in sessions loop
		update rhnKickstartSession
			set 	state_id = (
					select	id
					from	rhnKickstartSessionState
					where	label = 'failed'
				),
				action_id = null
			where	id = s.id;
		perform set_ks_session_history_message(s.id, 'failed', 'Kickstart cancelled due to action removal');
	end loop;
    end$$ language plpgsql;
   
    create or replace function check_user_access(server_id_in in numeric, user_id_in in numeric)
    returns numeric
    as $$
    declare
    	has_access numeric;
    begin
    	-- first check; if this returns no rows, then the server/user are in different orgs, and we bail
        select 1 into has_access
	  from rhnServer S,
	       web_contact wc
	 where wc.org_id = s.org_id
	   and s.id = server_id_in
	   and wc.id = user_id_in;

        if not found then
          return 0;
        end if;

	-- okay, so they're in the same org.  if we have an org admin, they get a free pass
    	if rhn_user.check_role(user_id_in, 'org_admin') = 1
	then
	    return 1;
	end if;
		   
    	select 1 into has_access
	  from rhnServerGroupMembers SGM,
	       rhnUserServerGroupPerms USG
	 where SGM.server_group_id = USG.server_group_id
	   and SGM.server_id = server_id_in
	   and USG.user_id = user_id_in;

        if not found then
          return 0;
        end if;
	   
	return 1;
    end$$ language plpgsql;

    -- *******************************************************************
    -- FUNCTION: can_server_consume_virt_slot
    -- Returns 1 if the server id is eligible to consume a virtual slot,
    --   else returns 0.
    -- Called by: insert_into_servergroup, delete_from_servergroup
    -- *******************************************************************
    create or replace function can_server_consume_virt_slot(server_id_in in numeric,
                                           group_type_in in varchar)
    returns numeric                                           
    as $$
    declare
        server_virt_slots cursor is
            select vi.VIRTUAL_SYSTEM_ID
            from
                rhnVirtualInstance vi
            where
                -- server id is a virtual instance
                vi.VIRTUAL_SYSTEM_ID = server_id_in
                -- server id's host is virt entitled
                and exists ( select 1
                     from rhnServerEntitlementView sev
                 where vi.HOST_SYSTEM_ID = sev.server_id
                 and sev.label in ('virtualization_host',
                                   'virtualization_host_platform') )
                -- server id's host also has the ent we want
                and exists ( select 1
                     from rhnServerEntitlementView sev2
                 where vi.HOST_SYSTEM_ID = sev2.server_id
                 and sev2.label = group_type_in );

    begin
        for server_virt_slot in server_virt_slots loop
            return 1;
        end loop;
        return 0;
    end$$ language plpgsql;


    create or replace function insert_into_servergroup (
		server_id_in in numeric,
		server_group_id_in in numeric
    ) returns void
    as $$
    declare
		used_slots numeric;
		max_slots numeric;
		org_id numeric;
		mgmt_available numeric;
		mgmt_upgrade numeric;
		mgmt_sgid numeric;
		prov_available numeric;
		prov_upgrade numeric;
		prov_sgid numeric;
		group_label varchar;
		group_type numeric;
	begin
		-- first, group_type = null, because it's easy...

		-- this will rowlock the servergroup we're trying to change;
		-- we probably need to lock the other one, but I think the chances
		-- of it being a real issue are very small for now...
		select	sg.group_type, sg.org_id, sg.current_members, sg.max_members
		into	group_type, org_id, used_slots, max_slots
		from	rhnServerGroup sg
		where	sg.id = server_group_id_in
		for update of sg;

		if group_type is null then
			if used_slots >= max_slots then
				perform rhn_exception.raise_exception('servergroup_max_members');
			end if;

			insert into rhnServerGroupMembers(
					server_id, server_group_id
				) values (
					server_id_in, server_group_id_in
				);
			update rhnServerGroup
				set current_members = current_members + 1
				where id = server_group_id_in;

			perform rhn_cache.update_perms_for_server_group(server_group_id_in);
			return;
		end if;

		-- now for group_type != null
		-- 
		select	label
		into	group_label
		from	rhnServerGroupType	sgt
		where	sgt.id = group_type;

		-- the naive easy path that gets hit most often and has to be quickest.
		if group_label in ('sw_mgr_entitled',
                           'enterprise_entitled',
                           'bootstrap_entitled',
                           'monitoring_entitled',
                           'provisioning_entitled',
                           'virtualization_host',
                           'virtualization_host_platform') then
			if used_slots >= max_slots and 
               (rhn_server.can_server_consume_virt_slot(server_id_in, group_label) != 1) 
               then
				perform rhn_exception.raise_exception('servergroup_max_members');
			end if;

			insert into rhnServerGroupMembers(
					server_id, server_group_id
				) values (
					server_id_in, server_group_id_in
				);

            -- Only update current members if the system in consuming a 
            -- physical slot.
            if rhn_server.can_server_consume_virt_slot(server_id_in, group_label) = 0 then
                update rhnServerGroup
                set current_members = current_members + 1
                where id = server_group_id_in;
            end if;                

			return;
		end if;
	end$$ language plpgsql;

	create or replace function insert_into_servergroup_maybe (
		server_id_in in numeric,
		server_group_id_in in numeric
	) returns numeric as $$ 
    declare
		retval numeric := 0;
		servergroups cursor is
			select	s.id	server_id,
					sg.id	server_group_id
			from	rhnServerGroup	sg,
					rhnServer		s
			where	s.id = server_id_in
				and sg.id = server_group_id_in
				and s.org_id = sg.org_id
				and not exists (
					select	1
					from	rhnServerGroupMembers sgm
					where	sgm.server_id = s.id
						and sgm.server_group_id = sg.id
				);
	begin
		for sgm in servergroups loop
			perform rhn_server.insert_into_servergroup(sgm.server_id, sgm.server_group_id);
			retval := retval + 1;
		end loop;
		return retval;
	end$$ language plpgsql;

	create or replace function insert_set_into_servergroup (
		server_group_id_in in numeric,
		user_id_in in numeric,
		set_label_in in varchar
	) returns void
        as $$
    declare
		servers cursor is
			select	st.element	id
			from	rhnSet		st
			where	st.user_id = user_id_in
				and st.label = set_label_in
				and exists (
					select	1
					from	rhnUserManagedServerGroups umsg
					where	umsg.server_group_id = server_group_id_in
						and umsg.user_id = user_id_in
					)
				and not exists (
					select	1
					from	rhnServerGroupMembers sgm
					where	sgm.server_id = st.element
						and sgm.server_group_id = server_group_id_in
				);
	begin
		for s in servers loop
			perform rhn_server.insert_into_servergroup(s.id, server_group_id_in);
		end loop;
	end$$ language plpgsql;
		
    create or replace function delete_from_servergroup (
    	server_id_in in numeric,
		server_group_id_in in numeric
    ) returns void
    as $$
    declare
        server_virt_groups cursor is
            select 1
            from rhnServerEntitlementVirtual sev
            where sev.server_id = server_id_in
            and sev.server_group_id = server_group_id_in;

		oid numeric;
		mgmt_sgid numeric;
		label varchar;
		group_type numeric;
	begin
			select	sg.group_type, sg.org_id
			into	group_type,	oid
			from	rhnServerGroupMembers	sgm,
					rhnServerGroup			sg
			where	sg.id = server_group_id_in
				and sg.id = sgm.server_group_id
				and sgm.server_id = server_id_in
			for update of sg;

			if not found then
				perform rhn_exception.raise_exception('server_not_in_group');
			end if;

		-- do group_type is null first
		if group_type is null then
			delete from rhnServerGroupMembers
				where server_group_id = server_group_id_in
				and	server_id = server_id_in;
			update rhnServerGroup
				set current_members = current_members - 1
				where id = server_group_id_in;
			perform rhn_cache.update_perms_for_server_group(server_group_id_in);
			return;
		end if;

		select	sgt.label
		into	label
		from	rhnServerGroupType sgt
		where	sgt.id = group_type;

		if label in ('sw_mgr_entitled',
                     'enterprise_entitled', 
                     'bootstrap_entitled',
                     'provisioning_entitled', 
                     'monitoring_entitled',
                     'virtualization_host',
                     'virtualization_host_platform') then

            -- Only update current members if the system is consuming
            -- a physical slot.
            for server_virt_group in server_virt_groups loop                
                delete from rhnServerGroupMembers
                where server_group_id = server_group_id_in
                and	server_id = server_id_in;
                return;
            end loop;                

            delete from rhnServerGroupMembers
            where server_group_id = server_group_id_in
            and	server_id = server_id_in;

            update rhnServerGroup
            set current_members = current_members - 1
            where id = server_group_id_in;

		end if;
	end$$ language plpgsql;

	create or replace function delete_set_from_servergroup (
		server_group_id_in in numeric,
		user_id_in in numeric,
		set_label_in in varchar
	) returns void
        as $$	
        declare
		servergroups cursor is
			select	sgm.server_id, sgm.server_group_id
			from	rhnSet st,
					rhnServerGroupMembers sgm
			where	sgm.server_group_id = server_group_id_in
				and st.user_id = user_id_in
				and st.label = set_label_in
				and sgm.server_id = st.element
				and exists (
					select	1
					from	rhnUserManagedServerGroups usgp
					where	usgp.server_group_id = server_group_id_in
						and usgp.user_id = user_id_in
				);
	begin
		for sgm in servergroups loop
			perform rhn_server.delete_from_servergroup(sgm.server_id, server_group_id_in);
		end loop;
	end$$ language plpgsql;

	create or replace function clear_servergroup (
		server_group_id_in in numeric
	) returns void
        as $$
        declare
		servers cursor is
			select	sgm.server_id	id
			from	rhnServerGroupMembers sgm
			where	sgm.server_group_id = server_group_id_in;
	begin
		for s in servers loop
			perform rhn_server.delete_from_servergroup(s.id, server_group_id_in);
		end loop;
	end$$ language plpgsql;

	create or replace function delete_from_org_servergroups (
		server_id_in in numeric
	) returns void
        as $$
        declare
		servergroups cursor is
			select	sgm.server_group_id id
			from	rhnServerGroup sg,
					rhnServerGroupMembers sgm
			where	sgm.server_id = server_id_in
				and sgm.server_group_id = sg.id
				and sg.group_type is null;
	begin
		for sg in servergroups loop
			perform rhn_server.delete_from_servergroup(server_id_in, sg.id);
		end loop;
	end$$ language plpgsql;

	create or replace function get_ip_address (
		server_id_in in numeric
	) returns varchar as $$
        declare
		interfaces cursor is
			select	ni.name as name, na4.address as address
			from	rhnServerNetInterface ni,
			        rhnServerNetAddress4 na4
			where	server_id = server_id_in
                and ni.id = na4.interface_id
				and na4.address != '127.0.0.1';
		addresses cursor is
			select	ipaddr ip_addr
			from	rhnServerNetwork
			where	server_id = server_id_in
				and ipaddr != '127.0.0.1';
	begin
		for addr in addresses loop
			return addr.ip_addr;
		end loop;
		for iface in interfaces loop
			return iface.address;
		end loop;
		return NULL;
	end$$ language plpgsql;

    create or replace function update_needed_cache(
        server_id_in in numeric
	) returns void as $$
    declare
      update_lock numeric;
    begin
      select id into update_lock from rhnServer where id = server_id_in for update;
      delete from rhnServerNeededCache
        where server_id = server_id_in;
      insert into rhnServerNeededCache
             (server_id, errata_id, package_id, channel_id)
        (select distinct sp.server_id, x.errata_id, p.id, x.channel_id
           FROM (SELECT sp_sp.server_id, sp_sp.name_id,
		        sp_sp.package_arch_id, max(sp_pe.evr) AS max_evr
                   FROM rhnServerPackage sp_sp
                   join rhnPackageEvr sp_pe ON sp_pe.id = sp_sp.evr_id
                  GROUP BY sp_sp.server_id, sp_sp.name_id, sp_sp.package_arch_id) sp
           join rhnPackage p ON p.name_id = sp.name_id
           join rhnPackageEvr pe ON pe.id = p.evr_id AND sp.max_evr < pe.evr
           join rhnPackageUpgradeArchCompat puac
	            ON puac.package_arch_id = sp.package_arch_id
		    AND puac.package_upgrade_arch_id = p.package_arch_id
           join rhnServerChannel sc ON sc.server_id = sp.server_id
           join rhnChannelPackage cp ON cp.package_id = p.id
	            AND cp.channel_id = sc.channel_id
           left join (SELECT ep.errata_id, ce.channel_id, ep.package_id
                        FROM rhnChannelErrata ce
                        join rhnErrataPackage ep
			         ON ep.errata_id = ce.errata_id
			join rhnServerChannel sc_sc
			         ON sc_sc.channel_id = ce.channel_id
		       WHERE sc_sc.server_id = server_id_in) x
             ON x.channel_id = sc.channel_id AND x.package_id = cp.package_id
          where sp.server_id = server_id_in);
	end$$ language plpgsql;
-- restore the original setting
update pg_settings set setting = overlay( setting placing '' from 1 for (length('rhn_server')+1) ) where name = 'search_path';
 07070100000A82000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005800000000susemanager-schema/upgrade/susemanager-schema-2.1.50.12-to-susemanager-schema-2.1.50.13   07070100000A83000081B400000000000000000000000167AE11140000169C000000000000000000000000000000000000007300000000susemanager-schema/upgrade/susemanager-schema-2.1.50.12-to-susemanager-schema-2.1.50.13/001-fix-vercmp-rpm.pkb.sql    -- create schema rpm;

--update pg_setting
update pg_settings set setting = 'rpm,' || setting where name = 'search_path';

create or replace function isdigit(ch CHAR)
    RETURNS BOOLEAN as $$
    BEGIN
        if ascii(ch) between ascii('0') and ascii('9')
        then
            return TRUE;
        end if;
        return FALSE;
    END ;
$$ language 'plpgsql';

    
    create or replace FUNCTION isalpha(ch CHAR)
    RETURNS BOOLEAN as $$
    BEGIN
        if ascii(ch) between ascii('a') and ascii('z') or 
            ascii(ch) between ascii('A') and ascii('Z')
        then
            return TRUE;
        end if;
        return FALSE;
    END;
$$ language 'plpgsql';


    create or replace FUNCTION isalphanum(ch CHAR)
    RETURNS BOOLEAN as $$ 
    BEGIN
        if ascii(ch) between ascii('a') and ascii('z') or 
            ascii(ch) between ascii('A') and ascii('Z') or
            ascii(ch) between ascii('0') and ascii('9')
        then
            return TRUE;
        end if;
        return FALSE;
    END;
    $$ language 'plpgsql';


    create or replace FUNCTION rpmstrcmp (string1 IN VARCHAR, string2 IN VARCHAR)
    RETURNS INTEGER as $$
    declare
        str1 VARCHAR := string1;
        str2 VARCHAR := string2;
        digits VARCHAR(10) := '0123456789';
        lc_alpha VARCHAR(27) := 'abcdefghijklmnopqrstuvwxyz';
        uc_alpha VARCHAR(27) := 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
        alpha VARCHAR(54) := lc_alpha || uc_alpha;
        one VARCHAR;
        two VARCHAR;
        isnum BOOLEAN;
    BEGIN
        if str1 is NULL or str2 is NULL
        then
            RAISE EXCEPTION 'VALUE_ERROR.';
        end if;
      
        if str1 = str2
        then
            return 0;
        end if;
        one := str1;
        two := str2;

        <<segment_loop>>
        while one <> '' or two <> ''
        loop
            declare
                segm1 VARCHAR;
                segm2 VARCHAR;
            begin
                --DBMS_OUTPUT.PUT_LINE('Params: ' || one || ',' || two);
                -- Throw out all non-alphanum characters
                -- 126 == ~
                while one <> '' and not rpm.isalphanum(one) and ascii(one) <> 126
                loop
                    one := substr(one, 2);
                end loop;
                while two <> '' and not rpm.isalphanum(two) and ascii(two) <> 126
                loop
                    two := substr(two, 2);
                end loop;
                if ascii(one) = 126 or ascii(two) = 126
                then
                    if one = '' or ascii(one) <> 126 then return 1; end if;
                    if two = '' or ascii(two) <> 126 then return -1; end if;
                    one := substr(one, 2);
                    two := substr(two, 2);
                    continue;
                end if;
                if one = '' or two = ''
                then
                    exit;
                end if;
                str1 := one;
                str2 := two;
                if rpm.isdigit(str1) or rpm.isdigit(str2)
                then
                    str1 := ltrim(str1, digits);
                    str2 := ltrim(str2, digits);
                    isnum := true;
                else
                    str1 := ltrim(str1, alpha);
                    str2 := ltrim(str2, alpha);
                    isnum := false;
                end if;
                if str1 <> ''
                then segm1 := substr(one, 1, length(one) - length(str1));
                else segm1 := one;
                end if;

                if str2 <> ''
                then segm2 := substr(two, 1, length(two) - length(str2));
                else segm2 := two;
                end if;

                if isnum
                then
                    if segm1 = '' then return -1; end if;
                    if segm2 = '' then return 1; end if;

                    segm1 := ltrim(segm1, '0');
                    segm2 := ltrim(segm2, '0');

                    if segm1 = '' and segm2 <> ''
                    then
                        return -1;
                    end if;
                    if segm1 <> '' and segm2 = ''
                    then
                        return 1;
                    end if;
                    if length(segm1) < length(segm2) then return -1; end if;
                    if length(segm1) > length(segm2) then return 1; end if;
                end if;
                if segm1 < segm2 then return -1; end if;
                if segm1 > segm2 then return 1; end if;
               one := str1;
                two := str2;
            end;
        end loop segment_loop;
        if one = '' and two = '' then return 0; end if;

        if one = '' then return -1; end if;
        return 1;
    END ;
$$ language 'plpgsql';



   create or replace FUNCTION vercmp(
        e1 VARCHAR, v1 VARCHAR, r1 VARCHAR, 
        e2 VARCHAR, v2 VARCHAR, r2 VARCHAR)
    RETURNS INTEGER as $$
    declare
        rc INTEGER;
          ep1 INTEGER;
          ep2 INTEGER;
          BEGIN
            if e1 is null or e1 = '' then
              ep1 := 0;
            else
              ep1 := e1::integer;
            end if;
            if e2 is null or e2 = '' then
              ep2 := 0;
            else
              ep2 := e2::integer;
            end if;
            -- Epochs are non-null; compare them
            if ep1 < ep2 then return -1; end if;
            if ep1 > ep2 then return 1; end if;
            rc := rpm.rpmstrcmp(v1, v2);
            if rc != 0 then return rc; end if;
           return rpm.rpmstrcmp(r1, r2);
         END;
         $$ language 'plpgsql';

-- restore the original setting
update pg_settings set setting = overlay( setting placing '' from 1 for (length('rpm')+1) ) where name = 'search_path';

07070100000A84000081B400000000000000000000000167AE111400000C79000000000000000000000000000000000000007E00000000susemanager-schema/upgrade/susemanager-schema-2.1.50.12-to-susemanager-schema-2.1.50.13/002-rhnServerGroupOverview-errata.sql --
-- Copyright (c) 2008--2015 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
CREATE OR REPLACE VIEW rhnServerGroupOverview (
         ORG_ID, SECURITY_ERRATA, BUG_ERRATA, ENHANCEMENT_ERRATA, GROUP_ID, GROUP_NAME, GROUP_ADMINS, SERVER_COUNT, MODIFIED, MAX_MEMBERS
)
AS
  SELECT SG.org_id,
         (SELECT COUNT(distinct E.id)
            FROM rhnErrata E,
                 rhnServerNeededErrataCache SNEC,
                 rhnServerGroupMembers SGM
           WHERE E.advisory_type = 'Security Advisory'
                 and SNEC.errata_id = e.id
                 and SNEC.server_id = sgm.server_id
                 and sgm.server_group_id = sg.id
                 AND EXISTS ( SELECT 1
                              FROM rhnServerFeaturesView SFV
                              WHERE SFV.server_id = SGM.server_id
                                    AND SFV.label = 'ftr_system_grouping')),
         (SELECT COUNT(distinct E.id)
            FROM rhnErrata E,
                 rhnServerNeededErrataCache SNEC,
                 rhnServerGroupMembers SGM
           WHERE E.advisory_type = 'Bug Fix Advisory'
                 and SNEC.errata_id = e.id
                 and SNEC.server_id = sgm.server_id
                 and sgm.server_group_id = sg.id
                 AND EXISTS ( SELECT 1
                              FROM rhnServerFeaturesView SFV
                              WHERE SFV.server_id = SGM.server_id
                                    AND SFV.label = 'ftr_system_grouping')),
         (SELECT COUNT(distinct E.id)
            FROM rhnErrata E,
                 rhnServerNeededErrataCache SNEC,
                 rhnServerGroupMembers SGM
           WHERE E.advisory_type = 'Product Enhancement Advisory'
                 and SNEC.errata_id = e.id
                 and SNEC.server_id = sgm.server_id
                 and sgm.server_group_id = sg.id
                 AND EXISTS ( SELECT 1
                              FROM rhnServerFeaturesView SFV
                              WHERE SFV.server_id = SGM.server_id
                                    AND SFV.label = 'ftr_system_grouping')),
         SG.id, SG.name,
         (SELECT COUNT(*) FROM rhnUserManagedServerGroups UMSG WHERE UMSG.server_group_id = SG.id),
         (SELECT COUNT(*) FROM rhnServerGroupMembers SGM WHERE SGM.server_group_id = SG.id
                 AND EXISTS ( SELECT 1
                              FROM rhnServerFeaturesView SFV
                              WHERE SFV.server_id = SGM.server_id
                                    AND SFV.label = 'ftr_system_grouping')),
         CURRENT_TIMESTAMP, MAX_MEMBERS
    FROM rhnServerGroup SG;

   07070100000A85000081B400000000000000000000000167AE1114000004EE000000000000000000000000000000000000008100000000susemanager-schema/upgrade/susemanager-schema-2.1.50.12-to-susemanager-schema-2.1.50.13/003-rhnServerOutdatedPackages-errata.sql  --
-- Copyright (c) 2008--2015 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--

CREATE OR REPLACE VIEW
rhnServerOutdatedPackages
(
    server_id,
    package_name_id,
    package_evr_id,    
    package_arch_id,
    package_nvre,
    errata_id,
    errata_advisory
)
AS
SELECT DISTINCT SNC.server_id,
       P.name_id,
       P.evr_id,
       P.package_arch_id,
       PN.name || '-' || evr_t_as_vre_simple( PE.evr ),
       E.id,
       E.advisory
  FROM rhnPackageName PN,
       rhnPackageEVR PE,
       rhnPackage P,
       rhnServerNeededCache SNC
         left outer join
        rhnErrata E
          on SNC.errata_id = E.id
 WHERE SNC.package_id = P.id
   AND P.name_id = PN.id
   AND P.evr_id = PE.id;

  07070100000A86000081B400000000000000000000000167AE1114000003F5000000000000000000000000000000000000007800000000susemanager-schema/upgrade/susemanager-schema-2.1.50.12-to-susemanager-schema-2.1.50.13/004-auto-errata-update-task.sql   INSERT INTO rhnTaskoBunch (id, name, description, org_bunch)
             VALUES (sequence_nextval('rhn_tasko_bunch_id_seq'), 'auto-errata-bunch', 'Schedule automatic errata update actions', null);


INSERT INTO rhnTaskoSchedule (id, job_label, bunch_id, active_from, cron_expr)
    VALUES(sequence_nextval('rhn_tasko_schedule_id_seq'), 'auto-errata-default',
        (SELECT id FROM rhnTaskoBunch WHERE name='auto-errata-bunch'),
        current_timestamp, '0 5/10 * * * ?');

INSERT INTO rhnTaskoTask (id, name, class)
         VALUES (sequence_nextval('rhn_tasko_task_id_seq'), 'auto-errata', 'com.redhat.rhn.taskomatic.task.AutoErrataTask');

INSERT INTO rhnTaskoTemplate (id, bunch_id, task_id, ordering, start_if)
             VALUES (sequence_nextval('rhn_tasko_template_id_seq'),
                        (SELECT id FROM rhnTaskoBunch WHERE name='auto-errata-bunch'),
                        (SELECT id FROM rhnTaskoTask WHERE name='auto-errata'),
                        0,
                        null);
   07070100000A87000081B400000000000000000000000167AE111400000044000000000000000000000000000000000000007700000000susemanager-schema/upgrade/susemanager-schema-2.1.50.12-to-susemanager-schema-2.1.50.13/005-rhnContentSource-label.sql    
ALTER TABLE rhnContentSource ALTER COLUMN label TYPE VARCHAR(128);
07070100000A88000081B400000000000000000000000167AE1114000006FF000000000000000000000000000000000000007B00000000susemanager-schema/upgrade/susemanager-schema-2.1.50.12-to-susemanager-schema-2.1.50.13/006-queue_server-no_duplicates.sql    -- retrieved from ./1241128047/984a347f2afbd47756e90584364799dd670b62db/schema/spacewalk/oracle/procs/queue_server.sql
--
-- Copyright (c) 2008--2013 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--

-- the next two views are basically the same.  the first, though, has an outer join to
-- the errata stuff, in case there are packages the server needs that haven't been
-- errata'd (ie, the fringe case)


CREATE OR REPLACE FUNCTION
queue_server(server_id_in IN NUMERIC, immediate_in IN NUMERIC DEFAULT 1)
RETURNS VOID
AS
$$
DECLARE
    org_id_tmp NUMERIC;
BEGIN
    IF immediate_in > 0
    THEN
          PERFORM rhn_server.update_needed_cache(server_id_in);
    ELSE
          SELECT org_id INTO STRICT org_id_tmp
          FROM rhnServer WHERE id = server_id_in;

          INSERT
            INTO rhnTaskQueue
                 (org_id, task_name, task_data)
          SELECT org_id_tmp,
                 'update_server_errata_cache',
                 server_id_in
          WHERE NOT EXISTS
            (SELECT 1 FROM rhnTaskQueue
               WHERE org_id = org_id_tmp
               AND task_name = 'update_server_errata_cache'
               AND task_data = server_id_in
            );
    END IF;
END;
$$ LANGUAGE plpgsql;
 07070100000A89000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005800000000susemanager-schema/upgrade/susemanager-schema-2.1.50.13-to-susemanager-schema-2.1.50.14   07070100000A8A000081B400000000000000000000000167AE111400000099000000000000000000000000000000000000007700000000susemanager-schema/upgrade/susemanager-schema-2.1.50.13-to-susemanager-schema-2.1.50.14/001-errata-cache-cron-expr.sql    UPDATE rhnTaskoSchedule SET cron_expr = '0 * * * * ?' WHERE job_label = 'errata-cache-default' AND active_till IS NULL AND cron_expr = '0 0/10 * * * ?';
   07070100000A8B000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005800000000susemanager-schema/upgrade/susemanager-schema-2.1.50.14-to-susemanager-schema-2.1.50.15   07070100000A8C000081B400000000000000000000000167AE1114000000C4000000000000000000000000000000000000008A00000000susemanager-schema/upgrade/susemanager-schema-2.1.50.14-to-susemanager-schema-2.1.50.15/001-add-missing-on-delete-cascade-sppf-pid-fk.sql ALTER TABLE susePackageProductFile DROP CONSTRAINT sppf_pid_fk;
ALTER TABLE susePackageProductFile ADD CONSTRAINT sppf_pid_fk FOREIGN KEY (package_id) REFERENCES rhnPackage(id) ON DELETE CASCADE;
07070100000A8D000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005800000000susemanager-schema/upgrade/susemanager-schema-2.1.50.15-to-susemanager-schema-2.1.50.16   07070100000A8E000081B400000000000000000000000167AE1114000002F7000000000000000000000000000000000000007100000000susemanager-schema/upgrade/susemanager-schema-2.1.50.15-to-susemanager-schema-2.1.50.16/001-rhnTimezone-data.sql  insert into rhnTimezone (id, olson_name, display_name) (
    select sequence_nextval('rhn_timezone_id_seq'),
           'America/Santiago',
           'Chile (Continental)'
      from dual
     where not exists (
           select 1
             from rhnTimezone
            where olson_name = 'America/Santiago'
              and display_name = 'Chile (Continental)'
     )
);

insert into rhnTimezone (id, olson_name, display_name) (
    select sequence_nextval('rhn_timezone_id_seq'),
           'Pacific/Easter',
           'Chile (Easter Island)'
      from dual
     where not exists (
           select 1
             from rhnTimezone
            where olson_name = 'Pacific/Easter'
              and display_name = 'Chile (Easter Island)'
     )
);


 07070100000A8F000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005500000000susemanager-schema/upgrade/susemanager-schema-2.1.50.15-to-susemanager-schema-2.1.51  07070100000A90000081B400000000000000000000000167AE11140000007C000000000000000000000000000000000000005C00000000susemanager-schema/upgrade/susemanager-schema-2.1.50.15-to-susemanager-schema-2.1.51/README   -- Schema upgrade scripts.
-- leave this directory empty, all upgrades from 2.1 to 3.0 are covered by 2.1.51 to 3.0 upgrade
07070100000A91000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005800000000susemanager-schema/upgrade/susemanager-schema-2.1.50.16-to-susemanager-schema-2.1.50.17   07070100000A92000081B400000000000000000000000167AE111400000954000000000000000000000000000000000000008400000000susemanager-schema/upgrade/susemanager-schema-2.1.50.16-to-susemanager-schema-2.1.50.17/001-deduplicate-rhnChannelContentSource.sql   UPDATE rhnChannelContentSource
  SET source_id = (
    -- first, construct a temporary view on duplicates
    -- that is, couples of ids of rhnCountentSource rows that only differ by the URL token
    WITH duplicates AS (
      SELECT c1.id AS new_id, c2.id AS old_id
        -- take a couple of rhnCountentSource rows
        FROM rhnContentSource c1, rhnContentSource c2
        -- making sure that c1 is the newest, or in case they are equally old, c1 has higher id
        WHERE (c1.modified > c2.modified OR (c1.modified = c2.modified AND c1.id > c2.id))
        -- make sure we are talking about SCC URLs
          AND c1.source_url LIKE 'https://updates.suse.com/%'
          AND c1.source_url LIKE 'https://updates.suse.com/%'
        -- make sure both have a URL with a token part
          AND instr(c1.source_url, '?') > 0
          AND instr(c2.source_url, '?') > 0
        -- finally, they have equal initial (non-token) part
          AND c1.source_url LIKE substr(c2.source_url, 0, instr(c2.source_url, '?') - 1) || '%'
    )
    -- second, the new source id is simply the new_id from the duplicates table
    SELECT duplicates.new_id
      FROM duplicates
      WHERE duplicates.old_id = rhnChannelContentSource.source_id
  )
  WHERE EXISTS (
    -- the update must only be executed on those rows that actually have a duplicate
    -- duplicate definition below is identical to the one above, it's copypasted because
    -- of cross-RDBMS syntax restrictions
    WITH duplicates AS (
      SELECT c1.id AS new_id, c2.id AS old_id
        FROM rhnContentSource c1, rhnContentSource c2
        WHERE (c1.modified > c2.modified OR (c1.modified = c2.modified AND c1.id > c2.id))
          AND c1.source_url LIKE 'https://updates.suse.com/%'
          AND c1.source_url LIKE 'https://updates.suse.com/%'
          AND instr(c1.source_url, '?') > 0
          AND instr(c2.source_url, '?') > 0
          AND c1.source_url LIKE substr(c2.source_url, 0, instr(c2.source_url, '?') - 1) || '%'
    )
    SELECT 1
      FROM duplicates
      WHERE duplicates.old_id = rhnChannelContentSource.source_id
  )
;

DELETE FROM rhncontentsourcefilter
  WHERE rhncontentsourcefilter.source_id NOT IN (
    SELECT source_id
      FROM rhnChannelContentSource
  );

DELETE FROM rhnContentSource
  WHERE rhnContentSource.id NOT IN (
    SELECT source_id
      FROM rhnChannelContentSource
  );

07070100000A93000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005500000000susemanager-schema/upgrade/susemanager-schema-2.1.50.16-to-susemanager-schema-2.1.51  07070100000A94000081B400000000000000000000000167AE11140000007C000000000000000000000000000000000000005C00000000susemanager-schema/upgrade/susemanager-schema-2.1.50.16-to-susemanager-schema-2.1.51/README   -- Schema upgrade scripts.
-- leave this directory empty, all upgrades from 2.1 to 3.0 are covered by 2.1.51 to 3.0 upgrade
07070100000A95000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005800000000susemanager-schema/upgrade/susemanager-schema-2.1.50.17-to-susemanager-schema-2.1.50.18   07070100000A96000081B400000000000000000000000167AE111400002D0E000000000000000000000000000000000000007D00000000susemanager-schema/upgrade/susemanager-schema-2.1.50.17-to-susemanager-schema-2.1.50.18/001-avoid_deadlock_delete_server.sql  --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
-- This deletes a server.  All codepaths which delete servers should hit this
-- or delete_server_bulk()

create or replace
function delete_server (
        server_id_in in numeric
) returns void 
as
$$
declare
         servergroups cursor for
                select  server_id, server_group_id
                from    rhnServerGroupMembers sgm
                where   sgm.server_id = server_id_in;

         configchannels cursor for
                select  cc.id
                from    rhnConfigChannel cc,
                        rhnConfigChannelType cct,
                        rhnServerConfigChannel scc
                where   1=1
                        and scc.server_id = server_id_in
                        and scc.config_channel_id = cc.id
                        -- these config channel types are reserved
                        -- for use by a single server, so we don't
                        -- need to check for other servers subscribed
                        and cct.label in
                                ('local_override','server_import')
                        and cct.id = cc.confchan_type_id;

    is_virt boolean;
    update_lock numeric;
begin
    -- lock the rhnServer row to prevent deadlocks
    -- we want rhnServer to be locked first, followed by tables that depend on it
    select id into update_lock from rhnServer where id = server_id_in for update;

        perform rhn_channel.delete_server_channels(server_id_in);
        -- rhn_channel.clear_subscriptions(server_id_in);

        -- filelists
        delete from rhnFileList where id in (
	select	spfl.file_list_id
	  from	rhnServerPreserveFileList spfl
	 where	spfl.server_id = server_id_in
			and not exists (
				select	1
				from	rhnServerPreserveFileList
				where	file_list_id = spfl.file_list_id
					and server_id != server_id_in
				union all
				select	1
				from	rhnKickstartPreserveFileList
				where	file_list_id = spfl.file_list_id
			)
        );

	for configchannel in configchannels loop
		perform rhn_config.delete_channel(configchannel.id);
	end loop;

      is_virt := exists (
       select 1
        from rhnServerEntitlementView
       where server_id = server_id_in
         and label in ('virtualization_host', 'virtualization_host_platform')
      );

	for sgm in servergroups loop
		perform rhn_server.delete_from_servergroup(
			sgm.server_id, sgm.server_group_id);
	end loop;

    if is_virt then
        perform rhn_entitlements.repoll_virt_guest_entitlements(server_id_in);
    end if;

        -- we're handling this instead of letting an "on delete
        -- set null" do it so that we don't run the risk
        -- of setting off the triggers and killing us with a
        -- mutating table

        -- this is merge of two single updates:
        --  update ... set old_server_id = null where old_server_id = server_id_in;
        --  update ... set new_server_id = null where new_server_id = server_id_in;
        -- so we scan rhnKickstartSession table only once
        update rhnKickstartSession
                set old_server_id = case when old_server_id = server_id_in then null else old_server_id end,
                    new_server_id = case when new_server_id = server_id_in then null else new_server_id end
                where old_server_id = server_id_in
                   or new_server_id = server_id_in;

        perform rhn_channel.clear_subscriptions(server_id_in, 1, 1);

        -- A little complicated here, but the goal is to
        -- delete records from rhnVirtualInstace only if we don't
        -- care about them anymore.  We don't care about records
        -- in rhnVirtualInstance if we are deleting the host
        -- system and the virtual system is already null, or
        -- vice-versa.  We *do* care about them if either the
        -- host or virtual system is still registered because we
        -- still want them to show up in the UI.
    -- If there's a newer row in rhnVirtualInstance with the same
    -- uuid, this guest must have been re-registered, so we can clean
    -- this data up.

        delete from rhnVirtualInstance vi
              where (host_system_id = server_id_in and virtual_system_id is null)
                 or (virtual_system_id = server_id_in and host_system_id is null)
                 or (vi.virtual_system_id = server_id_in and vi.modified < (select max(vi2.modified)
                    from rhnVirtualInstance vi2 where vi2.uuid = vi.uuid));

        -- this is merge of two single updates:
        --  update ... set host_system_id = null where host_system_id = server_id_in;
        --  update ... set virtual_system_id = null where virtual_system_id = server_id_in;
        -- so we scan rhnVirtualInstance table only once
        update rhnVirtualInstance
           set host_system_id = case when host_system_id = server_id_in then null else host_system_id end,
               virtual_system_id = case when virtual_system_id = server_id_in then null else virtual_system_id end
         where host_system_id = server_id_in
            or virtual_system_id = server_id_in;

        -- this is merge of two single updates:
        --  update ... set old_host_system_id = null when old_host_system_id = server_id_in;
        --  update ... set new_host_system_id = null when new_host_system_id = server_id_in;
        -- so we scan rhnVirtualInstanceEventLog table only once
        update rhnVirtualInstanceEventLog
           set old_host_system_id = case when old_host_system_id = server_id_in then null else old_host_system_id end,
               new_host_system_id = case when new_host_system_id = server_id_in then null else new_host_system_id end
         where old_host_system_id = server_id_in
            or new_host_system_id = server_id_in;

        -- We're deleting everything with a foreign key to rhnServer
        -- here, now.  I'm hoping this will help aleviate our deadlock
        -- problem.

        delete from rhnActionConfigChannel where server_id = server_id_in;
        delete from rhnActionConfigRevision where server_id = server_id_in;
        delete from rhnActionPackageRemovalFailure where server_id = server_id_in;
        delete from rhnClientCapability where server_id = server_id_in;
        delete from rhnCpu where server_id = server_id_in;
        -- there's still a cascade here, because the constraint keeps the
        -- table locked for too long to rebuild it.  Ugh...
        delete from rhnDevice where server_id = server_id_in;
        delete from rhnProxyInfo where server_id = server_id_in;
        delete from rhnRam where server_id = server_id_in;
        delete from rhnRegToken where server_id = server_id_in;
        delete from rhnSatelliteInfo where server_id = server_id_in;
        -- this cascades to rhnActionConfigChannel and rhnActionConfigFileName
        delete from rhnServerAction where server_id = server_id_in;
        delete from rhnServerActionPackageResult where server_id = server_id_in;
        delete from rhnServerActionScriptResult where server_id = server_id_in;
        delete from rhnServerActionVerifyResult where server_id = server_id_in;
        delete from rhnServerActionVerifyMissing where server_id = server_id_in;
        -- counts are handled above.  this should be a delete_ function.
        delete from rhnServerChannel where server_id = server_id_in;
        delete from rhnServerConfigChannel where server_id = server_id_in;
        delete from rhnServerCustomDataValue where server_id = server_id_in;
        delete from rhnServerDMI where server_id = server_id_in;
        delete from rhnServerEvent where server_id = server_id_in;
        delete from rhnServerHistory where server_id = server_id_in;
        delete from rhnServerInfo where server_id = server_id_in;
        delete from rhnServerInstallInfo where server_id = server_id_in;
        delete from rhnServerLocation where server_id = server_id_in;
        delete from rhnServerLock where server_id = server_id_in;
        delete from rhnServerNeededCache where server_id = server_id_in;
        delete from rhnServerNetwork where server_id = server_id_in;
        delete from rhnServerNotes where server_id = server_id_in;
        -- I'm not removing the foreign key from rhnServerPackage; that'll
        -- take forever.  Do the delete anyway.
        delete from rhnServerPackage where server_id = server_id_in;
        delete from rhnServerTokenRegs where server_id = server_id_in;
        delete from rhnSnapshotTag where server_id = server_id_in;
        -- this cascades to:
        --   rhnSnapshotChannel, rhnSnapshotConfigChannel, rhnSnapshotPackage,
        --   rhnSnapshotConfigRevision, rhnSnapshotServerGroup,
        --   rhnSnapshotTag.
        -- We may want to consider delete_snapshot() at some point, but
        --   I don't think we need to yet.
        delete from rhnSnapshot where server_id = server_id_in;
        delete from rhnUserServerPrefs where server_id = server_id_in;
        -- hrm, this one's interesting... we _probably_ should delete
        -- everything for the parent server_id when we delete the proxy,
        -- but we don't currently.
        delete from rhnServerPath where server_id_in in (server_id, proxy_server_id);
        delete from rhnUserServerPerms where server_id = server_id_in;

        delete from rhnServerNetInterface where server_id = server_id_in;
        delete from rhn_server_monitoring_info where recid = server_id_in;

        delete from rhnServerUuid where server_id = server_id_in;

    -- We delete all the probes running directly against this system
    -- and any probes that were using this Server as a Proxy Scout.
    DELETE FROM rhn_probe_state PS WHERE PS.probe_id IN (
     SELECT CP.probe_id
       FROM rhn_check_probe CP  
      WHERE CP.host_id = server_id_in
         OR CP.sat_cluster_id in
    (SELECT SN.sat_cluster_id
       FROM rhn_sat_node SN
      WHERE SN.server_id = server_id_in)
    );

    DELETE FROM rhn_probe P  WHERE P.recid IN (
     SELECT CP.probe_id
       FROM rhn_check_probe CP  
      WHERE CP.host_id = server_id_in
         OR CP.sat_cluster_id in
    (SELECT SN.sat_cluster_id
       FROM rhn_sat_node SN
      WHERE SN.server_id = server_id_in)
    );

        delete from rhn_check_probe where host_id = server_id_in;
        delete from rhn_host_probe where host_id = server_id_in;

    delete from rhn_sat_cluster where recid in
      ( select sat_cluster_id from rhn_sat_node where server_id = server_id_in );

        delete from rhn_sat_node where server_id = server_id_in;

        delete from rhnPushClient where server_id = server_id_in;

        -- now get rhnServer itself.
        delete
        from    rhnServer
                where id = server_id_in;

        delete
        from    rhnSet
        where   label = 'system_list'
                and element = server_id_in;
end;
$$
language plpgsql;

  07070100000A97000081B400000000000000000000000167AE1114000000A4000000000000000000000000000000000000008400000000susemanager-schema/upgrade/susemanager-schema-2.1.50.17-to-susemanager-schema-2.1.50.18/002-add-severity-column-to-rhnErrataTmp.sql   --
-- Adding the missing columnt 'severity_id' to rhnErrataTmp
-- table to be consistent with rhnErrata table

ALTER TABLE rhnerratatmp
   ADD severity_id NUMERIC;
07070100000A98000081B400000000000000000000000167AE11140000044F000000000000000000000000000000000000007500000000susemanager-schema/upgrade/susemanager-schema-2.1.50.17-to-susemanager-schema-2.1.50.18/003.suseProductExtension.sql  --
-- Copyright (c) 2016 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
--


create table
suseProductExtension
(
    base_pdid   NUMERIC not null
                  CONSTRAINT suse_prdext_bpid_fk
                  REFERENCES suseProducts (id)
                  ON DELETE CASCADE,
    ext_pdid   NUMERIC not null
                  CONSTRAINT suse_prdext_epid_fk
                  REFERENCES suseProducts (id)
                  ON DELETE CASCADE,
    created   TIMESTAMPTZ
                  DEFAULT (current_timestamp) NOT NULL,
    modified  TIMESTAMPTZ
                  DEFAULT (current_timestamp) NOT NULL
);

CREATE INDEX prdext_bpid_idx
ON suseProductExtension (base_pdid)
;

CREATE INDEX prdext_epid_idx
ON suseProductExtension (ext_pdid)
;
 07070100000A99000081B400000000000000000000000167AE1114000002E9000000000000000000000000000000000000007500000000susemanager-schema/upgrade/susemanager-schema-2.1.50.17-to-susemanager-schema-2.1.50.18/004-suseProductExtension.sql  --
-- Copyright (c) 2016 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
--
create or replace function suse_prdext_mod_trig_fun() returns trigger
as
$$
begin
        new.modified := current_timestamp;

        return new;
end;
$$
language plpgsql;


create trigger
prdext_mod_trig
before insert or update on suseProductExtension
for each row
execute procedure suse_prdext_mod_trig_fun();
   07070100000A9A000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005500000000susemanager-schema/upgrade/susemanager-schema-2.1.50.17-to-susemanager-schema-2.1.51  07070100000A9B000081B400000000000000000000000167AE11140000007C000000000000000000000000000000000000005C00000000susemanager-schema/upgrade/susemanager-schema-2.1.50.17-to-susemanager-schema-2.1.51/README   -- Schema upgrade scripts.
-- leave this directory empty, all upgrades from 2.1 to 3.0 are covered by 2.1.51 to 3.0 upgrade
07070100000A9C000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005500000000susemanager-schema/upgrade/susemanager-schema-2.1.50.18-to-susemanager-schema-2.1.51  07070100000A9D000081B400000000000000000000000167AE11140000007C000000000000000000000000000000000000005C00000000susemanager-schema/upgrade/susemanager-schema-2.1.50.18-to-susemanager-schema-2.1.51/README   -- Schema upgrade scripts.
-- leave this directory empty, all upgrades from 2.1 to 3.0 are covered by 2.1.51 to 3.0 upgrade
07070100000A9E000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005600000000susemanager-schema/upgrade/susemanager-schema-2.1.50.2-to-susemanager-schema-2.1.50.3 07070100000A9F000081B400000000000000000000000167AE111400000043000000000000000000000000000000000000007300000000susemanager-schema/upgrade/susemanager-schema-2.1.50.2-to-susemanager-schema-2.1.50.3/001-fix-foreign-key-name.sql    
ALTER INDEX rhnactionchain_pkey RENAME TO rhn_action_chain_id_pk;
 07070100000AA0000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005600000000susemanager-schema/upgrade/susemanager-schema-2.1.50.3-to-susemanager-schema-2.1.50.4 07070100000AA1000081B400000000000000000000000167AE111400000277000000000000000000000000000000000000007200000000susemanager-schema/upgrade/susemanager-schema-2.1.50.3-to-susemanager-schema-2.1.50.4/001-add-SLES12-GPG-keys.sql insert into rhnPackageKey (id, key_id, key_type_id, provider_id)
    (select sequence_nextval('rhn_pkey_id_seq'), '70af9e8139db7c82', lookup_package_key_type('gpg'), lookup_package_provider('SUSE LINUX Products GmbH') from dual
      where 1 not in (select 1 from rhnPackageKey where key_id = '70af9e8139db7c82'));

insert into rhnPackageKey (id, key_id, key_type_id, provider_id)
    (select sequence_nextval('rhn_pkey_id_seq'), '5eaf444450a3dd1c', lookup_package_key_type('gpg'), lookup_package_provider('SUSE LINUX Products GmbH') from dual
      where 1 not in (select 1 from rhnPackageKey where key_id = '5eaf444450a3dd1c'));
 07070100000AA2000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005600000000susemanager-schema/upgrade/susemanager-schema-2.1.50.4-to-susemanager-schema-2.1.50.5 07070100000AA3000081B400000000000000000000000167AE1114000002F9000000000000000000000000000000000000007400000000susemanager-schema/upgrade/susemanager-schema-2.1.50.4-to-susemanager-schema-2.1.50.5/001-create_suseEula_table.sql   --

-- Copyright (c) 2014 SUSE LINUX Products GmbH, Nuernberg, Germany.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--


CREATE TABLE suseEula
(
    id          NUMERIC NOT NULL
                    CONSTRAINT suse_eula_id_pk PRIMARY KEY,
    text        BYTEA,
    checksum    VARCHAR(64) NOT NULL
)

;

CREATE SEQUENCE suse_eula_id_seq;

CREATE UNIQUE INDEX suse_eula_checksum
    on suseEula (checksum)
    ;

   07070100000AA4000081B400000000000000000000000167AE11140000047B000000000000000000000000000000000000007B00000000susemanager-schema/upgrade/susemanager-schema-2.1.50.4-to-susemanager-schema-2.1.50.5/002-create_susePackageEula_table.sql    --
-- Copyright (c) 2014 SUSE LINUX Products GmbH, Nuernberg, Germany.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
--

CREATE TABLE
susePackageEula
(
    package_id        NUMERIC
                      CONSTRAINT susepackageeula_pkg_id_fk
                      REFERENCES rhnPackage (id)
                      On DELETE CASCADE,
    eula_id           NUMERIC
                      CONSTRAINT susepackageeula_id_fk
                      REFERENCES suseEula (id),
    created   TIMESTAMPTZ
                  DEFAULT (current_timestamp) NOT NULL,
    modified  TIMESTAMPTZ
                  DEFAULT (current_timestamp) NOT NULL
)

;

CREATE UNIQUE INDEX susepackageeula_pkg_eula_uq
ON susePackageEula (package_id, eula_id)
;

CREATE INDEX susepackageeula_pkg_idx
ON susePackageEula (package_id)
;

 07070100000AA5000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005600000000susemanager-schema/upgrade/susemanager-schema-2.1.50.5-to-susemanager-schema-2.1.50.6 07070100000AA6000081B400000000000000000000000167AE11140000004B000000000000000000000000000000000000008100000000susemanager-schema/upgrade/susemanager-schema-2.1.50.5-to-susemanager-schema-2.1.50.6/001-web_user_personal_info-userIdIndex.sql  CREATE INDEX wupi_user_id_idx
    ON web_user_personal_info (web_user_id);
 07070100000AA7000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005600000000susemanager-schema/upgrade/susemanager-schema-2.1.50.6-to-susemanager-schema-2.1.50.7 07070100000AA8000081B400000000000000000000000167AE111400000152000000000000000000000000000000000000006F00000000susemanager-schema/upgrade/susemanager-schema-2.1.50.6-to-susemanager-schema-2.1.50.7/002-rhnTimezone-data.sql    insert into rhnTimezone (id, olson_name, display_name) (
    select sequence_nextval('rhn_timezone_id_seq'),
           'Asia/Seoul',
           'Korea'
      from dual
     where not exists (
           select 1
             from rhnTimezone
            where olson_name = 'Asia/Seoul'
              and display_name = 'Korea'
     )
);
  07070100000AA9000081B400000000000000000000000167AE111400001684000000000000000000000000000000000000006A00000000susemanager-schema/upgrade/susemanager-schema-2.1.50.6-to-susemanager-schema-2.1.50.7/003-add-ppc64le.sql insert into rhnChannelArch (id, label, name, arch_type_id) select
sequence_nextval('rhn_channel_arch_id_seq'), 'channel-ppc64le', 'PPC64LE', lookup_arch_type('rpm') from dual
where not exists (select 1 from rhnChannelArch where label = 'channel-ppc64le');

insert into rhnChannelPackageArchCompat (channel_arch_id, package_arch_id) select
LOOKUP_CHANNEL_ARCH('channel-ppc64le'), LOOKUP_PACKAGE_ARCH('noarch') from dual
where not exists (select 1 from rhnChannelPackageArchCompat where channel_arch_id = LOOKUP_CHANNEL_ARCH('channel-ppc64le') and package_arch_id = LOOKUP_PACKAGE_ARCH('noarch'));

insert into rhnCpuArch (id, label, name) select
sequence_nextval('rhn_cpu_arch_id_seq'), 'ppc64le', 'ppc64le' from dual
where not exists (select 1 from rhnCpuArch where label = 'ppc64le');

insert into rhnPackageArch (id, label, name, arch_type_id) select
sequence_nextval('rhn_package_arch_id_seq'), 'ppc64le', 'ppc64le', lookup_arch_type('rpm') from dual
where not exists (select 1 from rhnPackageArch where label = 'ppc64le');

insert into rhnChannelPackageArchCompat (channel_arch_id, package_arch_id) select
LOOKUP_CHANNEL_ARCH('channel-ppc64le'), LOOKUP_PACKAGE_ARCH('ppc64le') from dual
where not exists (select 1 from rhnChannelPackageArchCompat where channel_arch_id = LOOKUP_CHANNEL_ARCH('channel-ppc64le') and package_arch_id = LOOKUP_PACKAGE_ARCH('ppc64le'));

insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) select
LOOKUP_PACKAGE_ARCH('noarch'), LOOKUP_PACKAGE_ARCH('ppc64le'), current_timestamp, current_timestamp from dual
where not exists (select 1 from rhnPackageUpgradeArchCompat where package_arch_id = LOOKUP_PACKAGE_ARCH('noarch') and package_upgrade_arch_id = LOOKUP_PACKAGE_ARCH('ppc64le'));
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) select
LOOKUP_PACKAGE_ARCH('ppc64le'), LOOKUP_PACKAGE_ARCH('ppc64le'), current_timestamp, current_timestamp from dual
where not exists (select 1 from rhnPackageUpgradeArchCompat where package_arch_id = LOOKUP_PACKAGE_ARCH('noarch') and package_upgrade_arch_id = LOOKUP_PACKAGE_ARCH('ppc64le'));
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) select
LOOKUP_PACKAGE_ARCH('ppc64le'), LOOKUP_PACKAGE_ARCH('noarch'), current_timestamp, current_timestamp from dual
where not exists (select 1 from rhnPackageUpgradeArchCompat where package_arch_id = LOOKUP_PACKAGE_ARCH('ppc64le') and package_upgrade_arch_id = LOOKUP_PACKAGE_ARCH('noarch'));

insert into rhnServerArch (id, label, name, arch_type_id) select
sequence_nextval('rhn_server_arch_id_seq'), 'ppc64le-redhat-linux', 'ppc64le', lookup_arch_type('rpm') from dual
where not exists (select 1 from rhnServerArch where label = 'ppc64le-redhat-linux');

insert into rhnServerChannelArchCompat (server_arch_id, channel_arch_id) select
LOOKUP_SERVER_ARCH('ppc64le-redhat-linux'), LOOKUP_CHANNEL_ARCH('channel-ppc64le') from dual
where not exists (select 1 from rhnServerChannelArchCompat where server_arch_id = LOOKUP_SERVER_ARCH('ppc64le-redhat-linux') and channel_arch_id = LOOKUP_CHANNEL_ARCH('channel-ppc64le'));

insert into rhnServerPackageArchCompat (server_arch_id, package_arch_id, preference) select
LOOKUP_SERVER_ARCH('ppc64le-redhat-linux'), LOOKUP_PACKAGE_ARCH('ppc64le'), 0 from dual
where not exists (select 1 from rhnServerPackageArchCompat where server_arch_id = LOOKUP_SERVER_ARCH('ppc64le-redhat-linux') and package_arch_id = LOOKUP_PACKAGE_ARCH('ppc64le'));

insert into rhnServerPackageArchCompat (server_arch_id, package_arch_id, preference) select
LOOKUP_SERVER_ARCH('ppc64le-redhat-linux'), LOOKUP_PACKAGE_ARCH('noarch'), 1000 from dual
where not exists (select 1 from rhnServerPackageArchCompat where server_arch_id = LOOKUP_SERVER_ARCH('ppc64le-redhat-linux') and package_arch_id = LOOKUP_PACKAGE_ARCH('noarch'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type) select
LOOKUP_SERVER_ARCH('ppc64le-redhat-linux'), LOOKUP_SG_TYPE('sw_mgr_entitled') from dual
where not exists (select 1 from rhnServerServerGroupArchCompat where server_arch_id = LOOKUP_SERVER_ARCH('ppc64le-redhat-linux') and server_group_type = LOOKUP_SG_TYPE('sw_mgr_entitled'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type) select
lookup_server_arch('ppc64le-redhat-linux'), lookup_sg_type('enterprise_entitled') from dual
where not exists (select 1 from rhnServerServerGroupArchCompat where server_arch_id = LOOKUP_SERVER_ARCH('ppc64le-redhat-linux') and server_group_type = LOOKUP_SG_TYPE('enterprise_entitled'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type) select
lookup_server_arch('ppc64le-redhat-linux'), lookup_sg_type('provisioning_entitled') from dual
where not exists (select 1 from rhnServerServerGroupArchCompat where server_arch_id = LOOKUP_SERVER_ARCH('ppc64le-redhat-linux') and server_group_type = LOOKUP_SG_TYPE('provisioning_entitled'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type) select
lookup_server_arch('ppc64le-redhat-linux'), lookup_sg_type('monitoring_entitled') from dual
where not exists (select 1 from rhnServerServerGroupArchCompat where server_arch_id = LOOKUP_SERVER_ARCH('ppc64le-redhat-linux') and server_group_type = LOOKUP_SG_TYPE('monitoring_entitled'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type) select
lookup_server_arch('ppc64le-redhat-linux'), lookup_sg_type('virtualization_host') from dual
where not exists (select 1 from rhnServerServerGroupArchCompat where server_arch_id = LOOKUP_SERVER_ARCH('ppc64le-redhat-linux') and server_group_type = LOOKUP_SG_TYPE('virtualization_host'));
07070100000AAA000081B400000000000000000000000167AE1114000004BF000000000000000000000000000000000000007B00000000susemanager-schema/upgrade/susemanager-schema-2.1.50.6-to-susemanager-schema-2.1.50.7/004-rhnKickstartableTree-trigger.sql    
create or replace function rhn_kstree_mod_trig_fun() returns trigger as
$$
begin
        if tg_op='UPDATE' then
                -- Basically if we're changing something other than cobbler_id,
                -- cobbler_xen_id, and last_modified - or if last_modified is
                -- explicity set to null. Gets complicated because we have
                -- to allow for the possibility of the ids being null
                if ((not old.cobbler_id is null and new.cobbler_id = old.cobbler_id)
                        or (old.cobbler_id is null and new.cobbler_id is null))
                    and ((not old.cobbler_xen_id is null and new.cobbler_xen_id = old.cobbler_xen_id)
                        or (old.cobbler_xen_id is null and new.cobbler_xen_id is null))
                    and new.last_modified = old.last_modified
                    or new.last_modified is null
                then
                    new.last_modified := current_timestamp;
                end if;
        elseif tg_op='INSERT' and new.last_modified is null then
                new.last_modified := current_timestamp;
        end if;

        new.modified := current_timestamp;

        return new;
end;
$$ language plpgsql;
 07070100000AAB000081B400000000000000000000000167AE111400000198000000000000000000000000000000000000007500000000susemanager-schema/upgrade/susemanager-schema-2.1.50.6-to-susemanager-schema-2.1.50.7/005-rhnPackageKey-CentOS-7.sql  update rhnPackageKey set provider_id = lookup_package_provider('CentOS')
 where key_id = '24c6a8a7f4a80eb5';

insert into rhnPackageKey (id, key_id, key_type_id, provider_id)
    (select sequence_nextval('rhn_pkey_id_seq'), '24c6a8a7f4a80eb5', lookup_package_key_type('gpg'), lookup_package_provider('CentOS') from dual
     where not exists (select 1 from rhnPackageKey where key_id = '24c6a8a7f4a80eb5'));
07070100000AAC000081B400000000000000000000000167AE1114000002E2000000000000000000000000000000000000007600000000susemanager-schema/upgrade/susemanager-schema-2.1.50.6-to-susemanager-schema-2.1.50.7/006-rhnPackageKey-Fedora-21.sql update rhnPackageKey set provider_id = lookup_package_provider('Fedora')
 where key_id = '89ad4e8795a43f54' or key_id = '636dea19a0a7badb';

insert into rhnPackageKey (id, key_id, key_type_id, provider_id)
    (select sequence_nextval('rhn_pkey_id_seq'), '89ad4e8795a43f54', lookup_package_key_type('gpg'), lookup_package_provider('Fedora') from dual
     where not exists (select 1 from rhnPackageKey where key_id = '89ad4e8795a43f54'));

insert into rhnPackageKey (id, key_id, key_type_id, provider_id)
    (select sequence_nextval('rhn_pkey_id_seq'), '636dea19a0a7badb', lookup_package_key_type('gpg'), lookup_package_provider('Fedora') from dual
     where not exists (select 1 from rhnPackageKey where key_id = '636dea19a0a7badb'));
  07070100000AAD000081B400000000000000000000000167AE111400000048000000000000000000000000000000000000007A00000000susemanager-schema/upgrade/susemanager-schema-2.1.50.6-to-susemanager-schema-2.1.50.7/007-alter-rhnChannel-update_tag.sql 
ALTER TABLE rhnChannel
    ALTER COLUMN update_tag TYPE varchar(128);

07070100000AAE000081B400000000000000000000000167AE111400001748000000000000000000000000000000000000007400000000susemanager-schema/upgrade/susemanager-schema-2.1.50.6-to-susemanager-schema-2.1.50.7/008-tilde-compare-rpm.pkb.sql   -- create schema rpm;

--update pg_setting
update pg_settings set setting = 'rpm,' || setting where name = 'search_path';

create or replace function isdigit(ch CHAR)
    RETURNS BOOLEAN as $$
    BEGIN
        if ascii(ch) between ascii('0') and ascii('9')
        then
            return TRUE;
        end if;
        return FALSE;
    END ;
$$ language 'plpgsql';

    
    create or replace FUNCTION isalpha(ch CHAR)
    RETURNS BOOLEAN as $$
    BEGIN
        if ascii(ch) between ascii('a') and ascii('z') or 
            ascii(ch) between ascii('A') and ascii('Z')
        then
            return TRUE;
        end if;
        return FALSE;
    END;
$$ language 'plpgsql';


    create or replace FUNCTION isalphanum(ch CHAR)
    RETURNS BOOLEAN as $$ 
    BEGIN
        if ascii(ch) between ascii('a') and ascii('z') or 
            ascii(ch) between ascii('A') and ascii('Z') or
            ascii(ch) between ascii('0') and ascii('9')
        then
            return TRUE;
        end if;
        return FALSE;
    END;
    $$ language 'plpgsql';


    create or replace FUNCTION rpmstrcmp (string1 IN VARCHAR, string2 IN VARCHAR)
    RETURNS INTEGER as $$
    declare
        str1 VARCHAR := string1;
        str2 VARCHAR := string2;
        digits VARCHAR(10) := '0123456789';
        lc_alpha VARCHAR(27) := 'abcdefghijklmnopqrstuvwxyz';
        uc_alpha VARCHAR(27) := 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
        alpha VARCHAR(54) := lc_alpha || uc_alpha;
        one VARCHAR;
        two VARCHAR;
        isnum BOOLEAN;
    BEGIN
        if str1 is NULL or str2 is NULL
        then
            RAISE EXCEPTION 'VALUE_ERROR.';
        end if;
      
        if str1 = str2
        then
            return 0;
        end if;
        one := str1;
        two := str2;

        <<segment_loop>>
        while one <> '' or two <> ''
        loop
            declare
                segm1 VARCHAR;
                segm2 VARCHAR;
            begin
                --DBMS_OUTPUT.PUT_LINE('Params: ' || one || ',' || two);
                -- Throw out all non-alphanum characters
                -- 126 == ~
                while one <> '' and not rpm.isalphanum(one) and ascii(one) <> 126
                loop
                    one := substr(one, 2);
                end loop;
                while two <> '' and not rpm.isalphanum(two) and ascii(two) <> 126
                loop
                    two := substr(two, 2);
                end loop;
                if ascii(one) = 126 or ascii(two) = 126
                then
                    if one is NULL or ascii(one) <> 126 then return 1; end if;
                    if two is NULL or ascii(two) <> 126 then return -1; end if;
                    one := substr(one, 2);
                    two := substr(two, 2);
                    continue;
                end if;
                str1 := one;
                str2 := two;
                if str1 <> '' and rpm.isdigit(str1)
                then
                    str1 := ltrim(str1, digits);
                    str2 := ltrim(str2, digits);
                    isnum := true;
                else
                    str1 := ltrim(str1, alpha);
                    str2 := ltrim(str2, alpha);
                    isnum := false;
                end if;
                if str1 <> ''
                then segm1 := substr(one, 1, length(one) - length(str1));
                else segm1 := one;
                end if;
                    
                if str2 <> ''
                then segm2 := substr(two, 1, length(two) - length(str2));
                else segm2 := two;
                end if;
                if segm1 = '' then return -1; end if; /* arbitrary */
                if segm2 = '' then
                                        if isnum then
                                                return 1;
                                        else
                                                return -1;
                                        end if;
                                end if;
                if isnum
                then
                   
                    segm1 := ltrim(segm1, '0');
                    segm2 := ltrim(segm2, '0');

                    if segm1 = '' and segm2 <> ''
                    then
                        return -1;
                    end if;
                    if segm1 <> '' and segm2 = ''
                    then
                        return 1;
                    end if;
                    if length(segm1) > length(segm2) then return 1; end if;
                    if length(segm2) > length(segm1) then return -1; end if;
                end if;
                  if segm1 < segm2 then return -1; end if;
                if segm1 > segm2 then return 1; end if;
               one := str1;
                two := str2;
            end;
        end loop segment_loop;
     
        if one = '' then return -1; end if;
        return 1;
    END ;
$$ language 'plpgsql';



   create or replace FUNCTION vercmp(
        e1 VARCHAR, v1 VARCHAR, r1 VARCHAR, 
        e2 VARCHAR, v2 VARCHAR, r2 VARCHAR)
    RETURNS INTEGER as $$
    declare
        rc INTEGER;
          ep1 INTEGER;
          ep2 INTEGER;
          BEGIN
            if e1 is null or e1 = '' then
              ep1 := 0;
            else
              ep1 := e1::integer;
            end if;
            if e2 is null or e2 = '' then
              ep2 := 0;
            else
              ep2 := e2::integer;
            end if;
            -- Epochs are non-null; compare them
            if ep1 < ep2 then return -1; end if;
            if ep1 > ep2 then return 1; end if;
            rc := rpm.rpmstrcmp(v1, v2);
            if rc != 0 then return rc; end if;
           return rpm.rpmstrcmp(r1, r2);
         END;
         $$ language 'plpgsql';

-- restore the original setting
update pg_settings set setting = overlay( setting placing '' from 1 for (length('rpm')+1) ) where name = 'search_path';

07070100000AAF000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005600000000susemanager-schema/upgrade/susemanager-schema-2.1.50.7-to-susemanager-schema-2.1.50.8 07070100000AB0000081B400000000000000000000000167AE111400000371000000000000000000000000000000000000006F00000000susemanager-schema/upgrade/susemanager-schema-2.1.50.7-to-susemanager-schema-2.1.50.8/001-add-scc-credtype.sql    --
-- Copyright (c) 2014 Novell
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

insert into suseCredentialsType (id, label, name) (
  select sequence_nextval('suse_credtype_id_seq'), 'scc', 'SUSE Customer Center'
    from dual
   where not exists (
           select 1
             from suseCredentialsType
            where label = 'scc'
  )
);
   07070100000AB1000081B400000000000000000000000167AE111400000041000000000000000000000000000000000000007F00000000susemanager-schema/upgrade/susemanager-schema-2.1.50.7-to-susemanager-schema-2.1.50.8/002-remove-not-null-userid-susecreds.sql    
alter table suseCredentials alter column user_id drop not null;
   07070100000AB2000081B400000000000000000000000167AE11140000014D000000000000000000000000000000000000007600000000susemanager-schema/upgrade/susemanager-schema-2.1.50.7-to-susemanager-schema-2.1.50.8/003-rhnDistChannelMap_index.sql 
alter table rhnDistChannelMap drop constraint rhn_dcm_release_caid_oid_uq;

create unique index rhn_dcm_rel_caid_oid_uq_idx
    on rhnDistChannelMap (release, channel_arch_id, org_id)
 where org_id is not null;

create unique index rhn_dcm_rel_caid_uq_idx
    on rhnDistChannelMap (release, channel_arch_id)
 where org_id is null;

   07070100000AB3000081B400000000000000000000000167AE11140000038D000000000000000000000000000000000000007800000000susemanager-schema/upgrade/susemanager-schema-2.1.50.7-to-susemanager-schema-2.1.50.8/004-lookup_package_capability.sql   
-- Note: intentionally not thread-safe! You must aquire a write lock on the
-- rhnPackageCapability tabel if you are going to use this proc!
create or replace function lookup_package_capability_fast(name_in in varchar, version_in in varchar default null)
returns numeric
as
$$
declare
    name_id numeric;
begin
    if version_in is null then
        select id
          into name_id
          from rhnpackagecapability
         where name = name_in and
               version is null;
    else
        select id
          into name_id
          from rhnpackagecapability
         where name = name_in and
               version = version_in;
    end if;

    if not found then
        name_id = nextval('rhn_pkg_capability_id_seq');
        insert into rhnPackageCapability(id, name, version) values (
               name_id, name_in, version_in);
    end if;

    return name_id;
end;
$$
language plpgsql;
   07070100000AB4000081B400000000000000000000000167AE11140000034C000000000000000000000000000000000000006E00000000susemanager-schema/upgrade/susemanager-schema-2.1.50.7-to-susemanager-schema-2.1.50.8/005-lookup_checksum.sql 
-- NOTE: This is intentionally not thread safe! You must lock rhnChecksum
-- if you are going to use this procedure!
create or replace function
lookup_checksum_fast(checksum_type_in in varchar, checksum_in in varchar)
returns numeric
as
$$
declare
    checksum_id     numeric;
begin
    if checksum_in is null then
        return null;
    end if;

    select c.id
      into checksum_id
      from rhnChecksumView c
     where c.checksum = checksum_in and
           c.checksum_type = checksum_type_in;

    if not found then
        checksum_id := nextval('rhnchecksum_seq');
        insert into rhnChecksum (id, checksum_type_id, checksum) values (
            checksum_id,
            (select id from rhnChecksumType where label = checksum_type_in),
            checksum_in);
    end if;

    return checksum_id;
end;
$$
language plpgsql;
07070100000AB5000081B400000000000000000000000167AE11140000004E000000000000000000000000000000000000008500000000susemanager-schema/upgrade/susemanager-schema-2.1.50.7-to-susemanager-schema-2.1.50.8/006-inc-length-rhnContentSource-source_url.sql  
ALTER TABLE rhnContentSource
    ALTER COLUMN source_url TYPE varchar(2048);
  07070100000AB6000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005600000000susemanager-schema/upgrade/susemanager-schema-2.1.50.8-to-susemanager-schema-2.1.50.9 07070100000AB7000081B400000000000000000000000167AE1114000000B0000000000000000000000000000000000000007900000000susemanager-schema/upgrade/susemanager-schema-2.1.50.8-to-susemanager-schema-2.1.50.9/001-rhnServerPackageArchCompat.sql  insert into rhnServerPackageArchCompat
(server_arch_id, package_arch_id, preference) values
(LOOKUP_SERVER_ARCH('aarch64-redhat-linux'), LOOKUP_PACKAGE_ARCH('noarch'), 1000);

07070100000AB8000081B400000000000000000000000167AE111400000540000000000000000000000000000000000000007000000000susemanager-schema/upgrade/susemanager-schema-2.1.50.8-to-susemanager-schema-2.1.50.9/002-suseSCCRepository.sql   --
-- Copyright (c) 2014 SUSE
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

CREATE TABLE suseSCCRepository
(
    id             NUMERIC NOT NULL PRIMARY KEY,
    credentials_id NUMERIC
                       CONSTRAINT suse_sccrepo_credsid_fk
                       REFERENCES suseCredentials (id)
                       ON DELETE CASCADE,
    autorefresh    CHAR(1) NOT NULL
                       CONSTRAINT suse_sccrepo_ck
                       CHECK (autorefresh in ('Y', 'N')),
    name           VARCHAR(256),
    distro_target  VARCHAR(256),
    description    VARCHAR(2048),
    url            VARCHAR(2048),
    created        TIMESTAMPTZ
                       DEFAULT (current_timestamp) NOT NULL,
    modified       TIMESTAMPTZ
                       DEFAULT (current_timestamp) NOT NULL
)

;

07070100000AB9000081B400000000000000000000000167AE111400000600000000000000000000000000000000000000007E00000000susemanager-schema/upgrade/susemanager-schema-2.1.50.8-to-susemanager-schema-2.1.50.9/003-mgr-sync-refresh-taskomatic-job.sql --
-- Copyright (c) 2014 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--

-- Insert task and map to the Java class
INSERT INTO rhnTaskoTask (id, name, class)
    VALUES (sequence_nextval('rhn_tasko_task_id_seq'), 'mgr-sync-refresh',
        'com.redhat.rhn.taskomatic.task.MgrSyncRefresh');

-- Insert bunch
INSERT INTO rhnTaskoBunch (id, name, description, org_bunch)
    VALUES (sequence_nextval('rhn_tasko_bunch_id_seq'), 'mgr-sync-refresh-bunch',
        'Refresh data about channels, products and subscriptions', null);

-- Insert template
INSERT INTO rhnTaskoTemplate (id, bunch_id, task_id, ordering, start_if)
    VALUES (sequence_nextval('rhn_tasko_template_id_seq'),
        (SELECT id FROM rhnTaskoBunch WHERE name='mgr-sync-refresh-bunch'),
        (SELECT id FROM rhnTaskoTask WHERE name='mgr-sync-refresh'),
        0, null);

-- Insert schedule for task (once a day at 11:00 PM)
INSERT INTO rhnTaskoSchedule (id, job_label, bunch_id, active_from, cron_expr)
    VALUES (sequence_nextval('rhn_tasko_schedule_id_seq'), 'mgr-sync-refresh-default',
        (SELECT id FROM rhnTaskoBunch WHERE name='mgr-sync-refresh-bunch'),
        current_timestamp, '0 0 0 ? * *');
07070100000ABA000081B400000000000000000000000167AE1114000003C0000000000000000000000000000000000000007700000000susemanager-schema/upgrade/susemanager-schema-2.1.50.8-to-susemanager-schema-2.1.50.9/004-randomize_bunch_schedule.sql    --
-- Copyright (c) 2014 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--

CREATE OR REPLACE FUNCTION
RANDOMIZE_BUNCH_SCHEDULE(label_in IN VARCHAR)
RETURNS void
AS
$$
DECLARE
        new_hour          NUMERIC;
        new_minute        NUMERIC;
BEGIN
        SELECT floor(random()*6)
          INTO new_hour
          FROM dual;

        SELECT floor(random()*59)
          INTO new_minute
          FROM dual;

        UPDATE rhnTaskoSchedule
           SET cron_expr = (select '0 ' || new_minute || ' ' || new_hour || ' ? * *' from dual)
         WHERE job_label = label_in;
END;
$$ LANGUAGE PLPGSQL;

07070100000ABB000081B400000000000000000000000167AE1114000001ED000000000000000000000000000000000000006900000000susemanager-schema/upgrade/susemanager-schema-2.1.50.8-to-susemanager-schema-2.1.50.9/005-reschedule.sql  --
-- Copyright (c) 2014 SUSE LLC.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--

select randomize_bunch_schedule('mgr-sync-refresh-default');
   07070100000ABC000081B400000000000000000000000167AE1114000001A5000000000000000000000000000000000000007E00000000susemanager-schema/upgrade/susemanager-schema-2.1.50.8-to-susemanager-schema-2.1.50.9/010-change_fk_on_suseProductChannel.sql ALTER TABLE suseProductChannel
  DROP constraint spc_pid_fk;

ALTER TABLE suseProductChannel
  ADD constraint spc_pid_fk
    foreign key (product_id)
    references suseProducts (id)
    ON DELETE CASCADE;

ALTER TABLE suseProductChannel
  DROP constraint spc_rhn_cid_fk;

ALTER TABLE suseProductChannel
  ADD constraint spc_rhn_cid_fk
    foreign key (channel_id)
    references rhnChannel (id)
    ON DELETE SET NULL;

   07070100000ABD000081B400000000000000000000000167AE111400000227000000000000000000000000000000000000007200000000susemanager-schema/upgrade/susemanager-schema-2.1.50.8-to-susemanager-schema-2.1.50.9/011-add-sle12-ostargets.sql insert into suseOSTarget (id, os, target, channel_arch_id) values
(sequence_nextval('suse_ostarget_id_seq'), 'sle-12-ppc64le', 'sle-12-ppc64le', LOOKUP_CHANNEL_ARCH('channel-ppc64le'));

insert into suseOSTarget (id, os, target, channel_arch_id) values
(sequence_nextval('suse_ostarget_id_seq'), 'sle-12-s390x', 'sle-12-s390x', LOOKUP_CHANNEL_ARCH('channel-s390x'));

insert into suseOSTarget (id, os, target, channel_arch_id) values
(sequence_nextval('suse_ostarget_id_seq'), 'sle-12-x86_64', 'sle-12-x86_64', LOOKUP_CHANNEL_ARCH('channel-x86_64'));
 07070100000ABE000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005700000000susemanager-schema/upgrade/susemanager-schema-2.1.50.9-to-susemanager-schema-2.1.50.10    07070100000ABF000081B400000000000000000000000167AE111400000038000000000000000000000000000000000000008900000000susemanager-schema/upgrade/susemanager-schema-2.1.50.9-to-susemanager-schema-2.1.50.10/001-suseProducts-drop-colum-channel_family_id.sql  alter table suseProducts drop column channel_family_id;
07070100000AC0000081B400000000000000000000000167AE111400000033000000000000000000000000000000000000008400000000susemanager-schema/upgrade/susemanager-schema-2.1.50.9-to-susemanager-schema-2.1.50.10/002-suseProducts-drop-colum-product_list.sql   alter table suseProducts drop column product_list;
 07070100000AC1000081B400000000000000000000000167AE11140000005E000000000000000000000000000000000000008900000000susemanager-schema/upgrade/susemanager-schema-2.1.50.9-to-susemanager-schema-2.1.50.10/003-rhnLockedPackages-drop-unique-index-pkgid.sql  drop index rhn_lp_pkg_id_uq;

create index rhn_lp_pkg_id_idx
  on rhnLockedPackages (pkg_id);
  07070100000AC2000081B400000000000000000000000167AE11140000030C000000000000000000000000000000000000009D00000000susemanager-schema/upgrade/susemanager-schema-2.1.50.9-to-susemanager-schema-2.1.50.10/004-rhnServerServerGroupArchCompat-missing-virt-platform-mappings.sql  insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type) select
LOOKUP_SERVER_ARCH('aarch64-redhat-linux'), LOOKUP_SG_TYPE('virtualization_host_platform') from dual
where not exists (select 1 from rhnServerServerGroupArchCompat where server_arch_id = LOOKUP_SERVER_ARCH('aarch64-redhat-linux') and server_group_type = LOOKUP_SG_TYPE('virtualization_host_platform'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type) select
LOOKUP_SERVER_ARCH('ppc64le-redhat-linux'), LOOKUP_SG_TYPE('virtualization_host_platform') from dual
where not exists (select 1 from rhnServerServerGroupArchCompat where server_arch_id = LOOKUP_SERVER_ARCH('ppc64le-redhat-linux') and server_group_type = LOOKUP_SG_TYPE('virtualization_host_platform'));

07070100000AC3000081B400000000000000000000000167AE111400006154000000000000000000000000000000000000007200000000susemanager-schema/upgrade/susemanager-schema-2.1.50.9-to-susemanager-schema-2.1.50.10/005-pxe-rhn_server.pkb.sql --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--

-- create schema rhn_server;

--update pg_setting
update pg_settings set setting = 'rhn_server,' || setting where name = 'search_path';

    create or replace function system_service_level(
    	server_id_in in numeric,
	service_level_in in varchar
    ) returns numeric as $$
    declare
    ents cursor is 
      select label from rhnServerEntitlementView
      where server_id = server_id_in;

    retval numeric := 0;

    begin
         for ent in ents loop
            retval := rhn_entitlements.entitlement_grants_service (ent.label, service_level_in);
            if retval = 1 then
               return retval;
            end if;
         end loop;

         return retval;

    end$$ language plpgsql;

        
    create or replace function can_change_base_channel(server_id_in IN NUMERIC)
    returns numeric
    as $$
    declare
    	throwaway numeric;
    begin
    	-- the idea: if we get past this query, the server is
	-- neither sat nor proxy, so base channel is changeable

	select 1 into throwaway
	  from rhnServer S
	 where S.id = server_id_in
	   and not exists (select 1 from rhnSatelliteInfo SI where SI.server_id = S.id)
	   and not exists (select 1 from rhnProxyInfo PI where PI.server_id = S.id);

        if not found then
	    return 0;
        end if;
	   
	return 1;
    end$$ language plpgsql;
	        
    create or replace function set_custom_value(
    	server_id_in in numeric,
	user_id_in in numeric,
	key_label_in in varchar,
	value_in in varchar
    ) returns void
    as $$
    declare
    	key_id_val numeric;
    begin
    	select CDK.id into strict key_id_val
	  from rhnCustomDataKey CDK,
	       rhnServer S
	 where S.id = server_id_in
	   and S.org_id = CDK.org_id
	   and CDK.label = key_label_in;
	   
	begin
	    insert into rhnServerCustomDataValue (server_id, key_id, value, created_by, last_modified_by)
	    values (server_id_in, key_id_val, value_in, user_id_in, user_id_in);
	exception
	    when UNIQUE_VIOLATION
	    	then
		update rhnServerCustomDataValue
		   set value = value_in,
		       last_modified_by = user_id_in
		 where server_id = server_id_in
		   and key_id = key_id_val;		   
	end;

    end$$ language plpgsql;
    
    create or replace function bulk_set_custom_value(
    	key_label_in in varchar,
	value_in in varchar,
	set_label_in in varchar,
	set_uid_in in numeric
    )
    returns integer
    as $$
    declare
        i integer;
        server record;
    begin
        i := 0;
        for server in (
           SELECT user_id, label, element, element_two
	     FROM rhnSet
	    WHERE label = set_label_in
	      AND user_id = set_uid_in
	) loop
	    if rhn_server.system_service_level(server.element, 'provisioning') = 1 then
	    	perform rhn_server.set_custom_value(server.element, set_uid_in, key_label_in, value_in);
            i := i + 1;
	    end if;
	end loop;
    return i;
    end$$ language plpgsql;

    create or replace function bulk_snapshot_tag(
    	org_id_in in numeric,
        tagname_in in varchar,
	set_label_in in varchar,
	set_uid_in in numeric
    ) returns void
    as $$
    declare
        server record;
    	snapshot_id numeric;
    begin
        for server in (
           SELECT user_id, label, element, element_two
	     FROM rhnSet
	    WHERE label = set_label_in
	      AND user_id = set_uid_in
	    ) loop
	    if rhn_server.system_service_level(server.element, 'provisioning') = 1 then
	    	    select max(id) into snapshot_id
	    	    from rhnSnapshot
	    	    where server_id = server.element;

	    	    if snapshot_id is null then
		    	perform rhn_server.snapshot_server(server.element, 'tagging system:  ' || tagname_in);
			
			select max(id) into snapshot_id
			from rhnSnapshot
			where server_id = server.element;
		    end if;
		 
		-- now have a snapshot_id to work with...
		begin
		    perform rhn_server.tag_snapshot(snapshot_id, org_id_in, tagname_in);
		exception
		    when UNIQUE_VIOLATION
		    	then
			-- do nothing, be forgiving...
			null;
		end;
	    end if;
	end loop;    
    end$$ language plpgsql;

    create or replace function tag_delete(
    	server_id_in in numeric,
	tag_id_in in numeric
    ) returns void
    as $$
    declare
    	snapshots cursor is
		select	snapshot_id
		from	rhnSnapshotTag
		where	tag_id = tag_id_in;
	tag_id_tmp numeric;
    begin
    	select	id into tag_id_tmp
	from	rhnTag
	where	id = tag_id_in
	for update;

	delete
		from	rhnSnapshotTag
		where	server_id = server_id_in
			and tag_id = tag_id_in;
	for snapshot in snapshots loop
		return;
	end loop;
	delete
		from rhnTag
		where id = tag_id_in;
    end$$ language plpgsql;

    create or replace function tag_snapshot(
        snapshot_id_in in numeric,
	org_id_in in numeric,
	tagname_in in varchar
    ) returns void
    as $$
    begin
    	insert into rhnSnapshotTag (snapshot_id, server_id, tag_id)
	select snapshot_id_in, server_id, lookup_tag(org_id_in, tagname_in)
	from rhnSnapshot
	where id = snapshot_id_in;
    end$$ language plpgsql;

    create or replace function bulk_snapshot(
    	reason_in in varchar,
	set_label_in in varchar,
	set_uid_in in numeric
    ) returns void
    as $$
    declare
        server record;
    begin
        for server in (
           SELECT user_id, label, element, element_two
	     FROM rhnSet
	    WHERE label = set_label_in
	      AND user_id = set_uid_in
	    ) loop
    	    if rhn_server.system_service_level(server.element, 'provisioning') = 1 then
	    	perform rhn_server.snapshot_server(server.element, reason_in);
	    end if;
	end loop;
    end$$ language plpgsql;

    create or replace function snapshot_server(
    	server_id_in in numeric,
	reason_in in varchar
    ) returns void
    as $$
    declare
    	snapshot_id_v numeric;
	revisions cursor is
		select distinct
			cr.id
		from	rhnConfigRevision	cr,
			rhnConfigFileName	cfn,
			rhnConfigFile		cf,
			rhnConfigChannel	cc,
			rhnServerConfigChannel	scc
		where	1=1
			and scc.server_id = server_id_in
			and scc.config_channel_id = cc.id
			and cc.id = cf.config_channel_id
			and cf.id = cr.config_file_id
			and cr.id = cf.latest_config_revision_id
			and cf.config_file_name_id = cfn.id
			and cf.id = lookup_first_matching_cf(scc.server_id, cfn.path);
	locked integer;
    begin
    	select nextval('rhn_snapshot_id_seq') into snapshot_id_v;

	insert into rhnSnapshot (id, org_id, server_id, reason) (
		select	snapshot_id_v,
			s.org_id,
			server_id_in,
			reason_in
		from	rhnServer s
		where	s.id = server_id_in
	);
	insert into rhnSnapshotChannel (snapshot_id, channel_id) (
		select	snapshot_id_v, sc.channel_id
		from	rhnServerChannel sc
		where	sc.server_id = server_id_in
	);
	insert into rhnSnapshotServerGroup (snapshot_id, server_group_id) (
		select	snapshot_id_v, sgm.server_group_id
		from	rhnServerGroupMembers sgm
		where	sgm.server_id = server_id_in
	);
        locked := 0;
        <<iloop>>
        while true loop
            begin
                insert into rhnPackageNEVRA (id, name_id, evr_id, package_arch_id)
                select nextval('rhn_pkgnevra_id_seq'), sp.name_id, sp.evr_id, sp.package_arch_id
                from rhnServerPackage sp
                where sp.server_id = server_id_in
                        and not exists
                        (select 1
                                from rhnPackageNEVRA nevra
                                where nevra.name_id = sp.name_id
                                        and nevra.evr_id = sp.evr_id
                                        and (nevra.package_arch_id = sp.package_arch_id
                                            or (nevra.package_arch_id is null
                                                and sp.package_arch_id is null)));
                exit iloop;
            exception when unique_violation then
                if locked = 1 then
                    raise;
                else
                    lock table rhnPackageNEVRA in exclusive mode;
                    locked := 1;
                end if;
            end;
        end loop;
	insert into rhnSnapshotPackage (snapshot_id, nevra_id) (
                select distinct snapshot_id_v, nevra.id
                from    rhnServerPackage sp, rhnPackageNEVRA nevra
                where   sp.server_id = server_id_in
                        and nevra.name_id = sp.name_id
                        and nevra.evr_id = sp.evr_id
                        and (nevra.package_arch_id = sp.package_arch_id
                            or (nevra.package_arch_id is null
                                and sp.package_arch_id is null))
	);

	insert into rhnSnapshotConfigChannel ( snapshot_id, config_channel_id ) (
		select	snapshot_id_v, scc.config_channel_id
		from	rhnServerConfigChannel scc
		where	server_id = server_id_in
	);

	for revision in revisions loop
		insert into rhnSnapshotConfigRevision (
				snapshot_id, config_revision_id
			) values (
				snapshot_id_v, revision.id
			);
	end loop;
    end$$ language plpgsql;

    create or replace function remove_action(
    	server_id_in in numeric,
	action_id_in in numeric
    ) returns void
    as $$
    declare
    	-- this really wants "nulls last", but 8.1.7.3.0 sucks ass.
	-- instead, we make a local table that holds our
	-- list of ids with null prereqs.  There's surely a better way
	-- (an array instead of a table maybe?  who knows...)
	-- but I've got code to do this handy that I can look at ;)
    	chained_actions cursor is
                with recursive r(id, prerequisite) as (
			select	id, prerequisite
			from	rhnAction
			where id = action_id_in
		union all
			select	r1.id, r1.prerequisite
			from	rhnAction r1, r
			where r.id = r1.prerequisite
		)
		select * from r
		order by prerequisite desc;
	sessions cursor is
		select	s.id
		from	rhnKickstartSession s
		where	server_id_in in (s.old_server_id, s.new_server_id)
			and s.action_id = action_id_in
			and not exists (
				select	1
				from	rhnKickstartSessionState ss
				where	ss.id = s.state_id
					and ss.label in ('failed','complete')
			);
	chain_ends numeric[];
	i numeric;
	prereq numeric := 1;
    begin
	select	prerequisite
	into	prereq
	from	rhnAction
	where	id = action_id_in;

	if prereq is not null then
		perform rhn_exception.raise_exception('action_is_child');
	end if;

        chain_ends := '{}';
	i := 1;
	for action in chained_actions loop
		if action.prerequisite is null then
			chain_ends[i] := action.id;
			i := i + 1;
		else
			delete from rhnServerAction
				where server_id = server_id_in
				and action_id = action.id;
		end if;
	end loop;

	delete from rhnServerAction
		where server_id = server_id_in
		and action_id = any(chain_ends);

	for s in sessions loop
		update rhnKickstartSession
			set 	state_id = (
					select	id
					from	rhnKickstartSessionState
					where	label = 'failed'
				),
				action_id = null
			where	id = s.id;
		perform set_ks_session_history_message(s.id, 'failed', 'Kickstart cancelled due to action removal');
	end loop;
    end$$ language plpgsql;
   
    create or replace function check_user_access(server_id_in in numeric, user_id_in in numeric)
    returns numeric
    as $$
    declare
    	has_access numeric;
    begin
    	-- first check; if this returns no rows, then the server/user are in different orgs, and we bail
        select 1 into has_access
	  from rhnServer S,
	       web_contact wc
	 where wc.org_id = s.org_id
	   and s.id = server_id_in
	   and wc.id = user_id_in;

        if not found then
          return 0;
        end if;

	-- okay, so they're in the same org.  if we have an org admin, they get a free pass
    	if rhn_user.check_role(user_id_in, 'org_admin') = 1
	then
	    return 1;
	end if;
		   
    	select 1 into has_access
	  from rhnServerGroupMembers SGM,
	       rhnUserServerGroupPerms USG
	 where SGM.server_group_id = USG.server_group_id
	   and SGM.server_id = server_id_in
	   and USG.user_id = user_id_in;

        if not found then
          return 0;
        end if;
	   
	return 1;
    end$$ language plpgsql;

    -- *******************************************************************
    -- FUNCTION: can_server_consume_virt_slot
    -- Returns 1 if the server id is eligible to consume a virtual slot,
    --   else returns 0.
    -- Called by: insert_into_servergroup, delete_from_servergroup
    -- *******************************************************************
    create or replace function can_server_consume_virt_slot(server_id_in in numeric,
                                           group_type_in in varchar)
    returns numeric                                           
    as $$
    declare
        server_virt_slots cursor is
            select vi.VIRTUAL_SYSTEM_ID
            from
                rhnVirtualInstance vi
            where
                -- server id is a virtual instance
                vi.VIRTUAL_SYSTEM_ID = server_id_in
                -- server id's host is virt entitled
                and exists ( select 1
                     from rhnServerEntitlementView sev
                 where vi.HOST_SYSTEM_ID = sev.server_id
                 and sev.label in ('virtualization_host',
                                   'virtualization_host_platform') )
                -- server id's host also has the ent we want
                and exists ( select 1
                     from rhnServerEntitlementView sev2
                 where vi.HOST_SYSTEM_ID = sev2.server_id
                 and sev2.label = group_type_in );

    begin
        for server_virt_slot in server_virt_slots loop
            return 1;
        end loop;
        return 0;
    end$$ language plpgsql;


    create or replace function insert_into_servergroup (
		server_id_in in numeric,
		server_group_id_in in numeric
    ) returns void
    as $$
    declare
		used_slots numeric;
		max_slots numeric;
		org_id numeric;
		mgmt_available numeric;
		mgmt_upgrade numeric;
		mgmt_sgid numeric;
		prov_available numeric;
		prov_upgrade numeric;
		prov_sgid numeric;
		group_label varchar;
		group_type numeric;
	begin
		-- first, group_type = null, because it's easy...

		-- this will rowlock the servergroup we're trying to change;
		-- we probably need to lock the other one, but I think the chances
		-- of it being a real issue are very small for now...
		select	sg.group_type, sg.org_id, sg.current_members, sg.max_members
		into	group_type, org_id, used_slots, max_slots
		from	rhnServerGroup sg
		where	sg.id = server_group_id_in
		for update of sg;

		if group_type is null then
			if used_slots >= max_slots then
				perform rhn_exception.raise_exception('servergroup_max_members');
			end if;

			insert into rhnServerGroupMembers(
					server_id, server_group_id
				) values (
					server_id_in, server_group_id_in
				);
			update rhnServerGroup
				set current_members = current_members + 1
				where id = server_group_id_in;

			perform rhn_cache.update_perms_for_server_group(server_group_id_in);
			return;
		end if;

		-- now for group_type != null
		-- 
		select	label
		into	group_label
		from	rhnServerGroupType	sgt
		where	sgt.id = group_type;

		-- the naive easy path that gets hit most often and has to be quickest.
		if group_label in ('sw_mgr_entitled',
                           'enterprise_entitled',
                           'bootstrap_entitled',
                           'monitoring_entitled',
                           'provisioning_entitled',
                           'virtualization_host',
                           'virtualization_host_platform') then
			if used_slots >= max_slots and 
               (rhn_server.can_server_consume_virt_slot(server_id_in, group_label) != 1) 
               then
				perform rhn_exception.raise_exception('servergroup_max_members');
			end if;

			insert into rhnServerGroupMembers(
					server_id, server_group_id
				) values (
					server_id_in, server_group_id_in
				);

            -- Only update current members if the system in consuming a 
            -- physical slot.
            if rhn_server.can_server_consume_virt_slot(server_id_in, group_label) = 0 then
                update rhnServerGroup
                set current_members = current_members + 1
                where id = server_group_id_in;
            end if;                

			return;
		end if;
	end$$ language plpgsql;

	create or replace function insert_into_servergroup_maybe (
		server_id_in in numeric,
		server_group_id_in in numeric
	) returns numeric as $$ 
    declare
		retval numeric := 0;
		servergroups cursor is
			select	s.id	server_id,
					sg.id	server_group_id
			from	rhnServerGroup	sg,
					rhnServer		s
			where	s.id = server_id_in
				and sg.id = server_group_id_in
				and s.org_id = sg.org_id
				and not exists (
					select	1
					from	rhnServerGroupMembers sgm
					where	sgm.server_id = s.id
						and sgm.server_group_id = sg.id
				);
	begin
		for sgm in servergroups loop
			perform rhn_server.insert_into_servergroup(sgm.server_id, sgm.server_group_id);
			retval := retval + 1;
		end loop;
		return retval;
	end$$ language plpgsql;

	create or replace function insert_set_into_servergroup (
		server_group_id_in in numeric,
		user_id_in in numeric,
		set_label_in in varchar
	) returns void
        as $$
    declare
		servers cursor is
			select	st.element	id
			from	rhnSet		st
			where	st.user_id = user_id_in
				and st.label = set_label_in
				and exists (
					select	1
					from	rhnUserManagedServerGroups umsg
					where	umsg.server_group_id = server_group_id_in
						and umsg.user_id = user_id_in
					)
				and not exists (
					select	1
					from	rhnServerGroupMembers sgm
					where	sgm.server_id = st.element
						and sgm.server_group_id = server_group_id_in
				);
	begin
		for s in servers loop
			perform rhn_server.insert_into_servergroup(s.id, server_group_id_in);
		end loop;
	end$$ language plpgsql;
		
    create or replace function delete_from_servergroup (
    	server_id_in in numeric,
		server_group_id_in in numeric
    ) returns void
    as $$
    declare
        server_virt_groups cursor is
            select 1
            from rhnServerEntitlementVirtual sev
            where sev.server_id = server_id_in
            and sev.server_group_id = server_group_id_in;

		oid numeric;
		mgmt_sgid numeric;
		label varchar;
		group_type numeric;
	begin
			select	sg.group_type, sg.org_id
			into	group_type,	oid
			from	rhnServerGroupMembers	sgm,
					rhnServerGroup			sg
			where	sg.id = server_group_id_in
				and sg.id = sgm.server_group_id
				and sgm.server_id = server_id_in
			for update of sg;

			if not found then
				perform rhn_exception.raise_exception('server_not_in_group');
			end if;

		-- do group_type is null first
		if group_type is null then
			delete from rhnServerGroupMembers
				where server_group_id = server_group_id_in
				and	server_id = server_id_in;
			update rhnServerGroup
				set current_members = current_members - 1
				where id = server_group_id_in;
			perform rhn_cache.update_perms_for_server_group(server_group_id_in);
			return;
		end if;

		select	sgt.label
		into	label
		from	rhnServerGroupType sgt
		where	sgt.id = group_type;

		if label in ('sw_mgr_entitled',
                     'enterprise_entitled', 
                     'bootstrap_entitled',
                     'provisioning_entitled', 
                     'monitoring_entitled',
                     'virtualization_host',
                     'virtualization_host_platform') then

            -- Only update current members if the system is consuming
            -- a physical slot.
            for server_virt_group in server_virt_groups loop                
                delete from rhnServerGroupMembers
                where server_group_id = server_group_id_in
                and	server_id = server_id_in;
                return;
            end loop;                

            delete from rhnServerGroupMembers
            where server_group_id = server_group_id_in
            and	server_id = server_id_in;

            update rhnServerGroup
            set current_members = current_members - 1
            where id = server_group_id_in;

		end if;
	end$$ language plpgsql;

	create or replace function delete_set_from_servergroup (
		server_group_id_in in numeric,
		user_id_in in numeric,
		set_label_in in varchar
	) returns void
        as $$	
        declare
		servergroups cursor is
			select	sgm.server_id, sgm.server_group_id
			from	rhnSet st,
					rhnServerGroupMembers sgm
			where	sgm.server_group_id = server_group_id_in
				and st.user_id = user_id_in
				and st.label = set_label_in
				and sgm.server_id = st.element
				and exists (
					select	1
					from	rhnUserManagedServerGroups usgp
					where	usgp.server_group_id = server_group_id_in
						and usgp.user_id = user_id_in
				);
	begin
		for sgm in servergroups loop
			perform rhn_server.delete_from_servergroup(sgm.server_id, server_group_id_in);
		end loop;
	end$$ language plpgsql;

	create or replace function clear_servergroup (
		server_group_id_in in numeric
	) returns void
        as $$
        declare
		servers cursor is
			select	sgm.server_id	id
			from	rhnServerGroupMembers sgm
			where	sgm.server_group_id = server_group_id_in;
	begin
		for s in servers loop
			perform rhn_server.delete_from_servergroup(s.id, server_group_id_in);
		end loop;
	end$$ language plpgsql;

	create or replace function delete_from_org_servergroups (
		server_id_in in numeric
	) returns void
        as $$
        declare
		servergroups cursor is
			select	sgm.server_group_id id
			from	rhnServerGroup sg,
					rhnServerGroupMembers sgm
			where	sgm.server_id = server_id_in
				and sgm.server_group_id = sg.id
				and sg.group_type is null;
	begin
		for sg in servergroups loop
			perform rhn_server.delete_from_servergroup(server_id_in, sg.id);
		end loop;
	end$$ language plpgsql;

	create or replace function get_ip_address (
		server_id_in in numeric
	) returns varchar as $$
        declare
		interfaces cursor is
			select	ni.name as name, na4.address as address
			from	rhnServerNetInterface ni,
			        rhnServerNetAddress4 na4
			where	server_id = server_id_in
                and ni.id = na4.interface_id
				and na4.address != '127.0.0.1';
		addresses cursor is
			select	ipaddr ip_addr
			from	rhnServerNetwork
			where	server_id = server_id_in
				and ipaddr != '127.0.0.1';
	begin
		for addr in addresses loop
			return addr.ip_addr;
		end loop;
		for iface in interfaces loop
			return iface.address;
		end loop;
		return NULL;
	end$$ language plpgsql;

    create or replace function update_needed_cache(
        server_id_in in numeric
	) returns void as $$
    begin
      delete from rhnServerNeededCache
        where server_id = server_id_in;
      insert into rhnServerNeededCache
             (server_id, errata_id, package_id, channel_id)
        (select distinct sp.server_id, x.errata_id, p.id, x.channel_id
           FROM (SELECT sp_sp.server_id, sp_sp.name_id,
		        sp_sp.package_arch_id, max(sp_pe.evr) AS max_evr
                   FROM rhnServerPackage sp_sp
                   join rhnPackageEvr sp_pe ON sp_pe.id = sp_sp.evr_id
                  GROUP BY sp_sp.server_id, sp_sp.name_id, sp_sp.package_arch_id) sp
           join rhnPackage p ON p.name_id = sp.name_id
           join rhnPackageEvr pe ON pe.id = p.evr_id AND sp.max_evr < pe.evr
           join rhnPackageUpgradeArchCompat puac
	            ON puac.package_arch_id = sp.package_arch_id
		    AND puac.package_upgrade_arch_id = p.package_arch_id
           join rhnServerChannel sc ON sc.server_id = sp.server_id
           join rhnChannelPackage cp ON cp.package_id = p.id
	            AND cp.channel_id = sc.channel_id
           left join (SELECT ep.errata_id, ce.channel_id, ep.package_id
                        FROM rhnChannelErrata ce
                        join rhnErrataPackage ep
			         ON ep.errata_id = ce.errata_id
			join rhnServerChannel sc_sc
			         ON sc_sc.channel_id = ce.channel_id
		       WHERE sc_sc.server_id = server_id_in) x
             ON x.channel_id = sc.channel_id AND x.package_id = cp.package_id
          where sp.server_id = server_id_in);
	end$$ language plpgsql;
-- restore the original setting
update pg_settings set setting = overlay( setting placing '' from 1 for (length('rhn_server')+1) ) where name = 'search_path';
07070100000AC4000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000004F00000000susemanager-schema/upgrade/susemanager-schema-2.1.51-to-susemanager-schema-3.0    07070100000AC5000081B400000000000000000000000167AE111400000132000000000000000000000000000000000000006C00000000susemanager-schema/upgrade/susemanager-schema-2.1.51-to-susemanager-schema-3.0/0001-rhnUserGroupMembers.sql   ALTER TABLE rhnUserGroupMembers ADD temporary CHAR(1) DEFAULT ('N') NOT NULL
    CONSTRAINT rhn_ugmembers_t_ck
        CHECK (temporary in ('Y', 'N'));

CREATE UNIQUE INDEX rhn_ugmembers_uid_ugid_temp_uq
    ON rhnUserGroupMembers (user_id, user_group_id, temporary);
DROP INDEX rhn_ugmembers_uid_ugid_uq;
  07070100000AC6000081B400000000000000000000000167AE1114000000DF000000000000000000000000000000000000006E00000000susemanager-schema/upgrade/susemanager-schema-2.1.51-to-susemanager-schema-3.0/0002-rhnConfiguration-data.sql INSERT INTO rhnConfiguration (key, description, default_value) VALUES ('extauth_keep_temproles', 'Keep temporary user roles granted due to the external authentication setup for subsequent logins using password.', 'false');
 07070100000AC7000081B400000000000000000000000167AE111400001516000000000000000000000000000000000000006C00000000susemanager-schema/upgrade/susemanager-schema-2.1.51-to-susemanager-schema-3.0/0005-support-for-aarch64.sql   insert into rhnChannelArch (id, label, name, arch_type_id) select
sequence_nextval('rhn_channel_arch_id_seq'), 'channel-aarch64', 'AArch64', lookup_arch_type('rpm') from dual
where not exists (select 1 from rhnChannelArch where label = 'channel-aarch64');

insert into rhnPackageArch (id, label, name, arch_type_id) select
sequence_nextval('rhn_package_arch_id_seq'), 'aarch64', 'AArch64', lookup_arch_type('rpm') from dual
where not exists (select 1 from rhnPackageArch where label ='aarch64');

insert into rhnChannelPackageArchCompat (channel_arch_id, package_arch_id) select
LOOKUP_CHANNEL_ARCH('channel-aarch64'), LOOKUP_PACKAGE_ARCH('aarch64') from dual
where not exists (select 1 from rhnChannelPackageArchCompat where channel_arch_id = LOOKUP_CHANNEL_ARCH('channel-aarch64') and package_arch_id = LOOKUP_PACKAGE_ARCH('aarch64'));
insert into rhnChannelPackageArchCompat (channel_arch_id, package_arch_id) select
LOOKUP_CHANNEL_ARCH('channel-aarch64'), LOOKUP_PACKAGE_ARCH('noarch') from dual
where not exists (select 1 from rhnChannelPackageArchCompat where channel_arch_id = LOOKUP_CHANNEL_ARCH('channel-aarch64') and package_arch_id = LOOKUP_PACKAGE_ARCH('noarch'));

insert into rhnServerArch (id, label, name, arch_type_id) select
sequence_nextval('rhn_server_arch_id_seq'), 'aarch64-redhat-linux', 'aarch64', lookup_arch_type('rpm') from dual
where not exists (select 1 from rhnServerArch where label = 'aarch64-redhat-linux');

insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) select
LOOKUP_PACKAGE_ARCH('noarch'), LOOKUP_PACKAGE_ARCH('aarch64'), current_timestamp, current_timestamp from dual
where not exists (select 1 from rhnPackageUpgradeArchCompat where package_arch_id = LOOKUP_PACKAGE_ARCH('noarch') and package_upgrade_arch_id = LOOKUP_PACKAGE_ARCH('aarch64'));
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) select
LOOKUP_PACKAGE_ARCH('aarch64'), LOOKUP_PACKAGE_ARCH('aarch64'), current_timestamp, current_timestamp from dual
where not exists (select 1 from rhnPackageUpgradeArchCompat where package_arch_id = LOOKUP_PACKAGE_ARCH('aarch64') and package_upgrade_arch_id = LOOKUP_PACKAGE_ARCH('aarch64'));
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) select
LOOKUP_PACKAGE_ARCH('aarch64'), LOOKUP_PACKAGE_ARCH('noarch'), current_timestamp, current_timestamp from dual
where not exists (select 1 from rhnPackageUpgradeArchCompat where package_arch_id = LOOKUP_PACKAGE_ARCH('aarch64') and package_upgrade_arch_id = LOOKUP_PACKAGE_ARCH('noarch'));

insert into rhnServerChannelArchCompat (server_arch_id, channel_arch_id) select
LOOKUP_SERVER_ARCH('aarch64-redhat-linux'), LOOKUP_CHANNEL_ARCH('channel-aarch64') from dual
where not exists (select 1 from rhnServerChannelArchCompat where server_arch_id = LOOKUP_SERVER_ARCH('aarch64-redhat-linux') and channel_arch_id = LOOKUP_CHANNEL_ARCH('channel-aarch64'));

insert into rhnServerPackageArchCompat (server_arch_id, package_arch_id, preference) select
LOOKUP_SERVER_ARCH('aarch64-redhat-linux'), LOOKUP_PACKAGE_ARCH('aarch64'), 0 from dual
where not exists (select 1 from rhnServerPackageArchCompat where server_arch_id = LOOKUP_SERVER_ARCH('aarch64-redhat-linux') and package_arch_id = LOOKUP_PACKAGE_ARCH('aarch64'));


insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type) select
LOOKUP_SERVER_ARCH('aarch64-redhat-linux'), LOOKUP_SG_TYPE('sw_mgr_entitled') from dual
where not exists (select 1 from rhnServerServerGroupArchCompat where server_arch_id = LOOKUP_SERVER_ARCH('aarch64-redhat-linux') and server_group_type = LOOKUP_SG_TYPE('sw_mgr_entitled'));
insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type) select
LOOKUP_SERVER_ARCH('aarch64-redhat-linux'), LOOKUP_SG_TYPE('enterprise_entitled') from dual
where not exists (select 1 from rhnServerServerGroupArchCompat where server_arch_id = LOOKUP_SERVER_ARCH('aarch64-redhat-linux') and server_group_type = LOOKUP_SG_TYPE('enterprise_entitled'));
insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type) select
LOOKUP_SERVER_ARCH('aarch64-redhat-linux'), LOOKUP_SG_TYPE('provisioning_entitled') from dual
where not exists (select 1 from rhnServerServerGroupArchCompat where server_arch_id = LOOKUP_SERVER_ARCH('aarch64-redhat-linux') and server_group_type = LOOKUP_SG_TYPE('provisioning_entitled'));
insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type) select
LOOKUP_SERVER_ARCH('aarch64-redhat-linux'), LOOKUP_SG_TYPE('monitoring_entitled') from dual
where not exists (select 1 from rhnServerServerGroupArchCompat where server_arch_id = LOOKUP_SERVER_ARCH('aarch64-redhat-linux') and server_group_type = LOOKUP_SG_TYPE('monitoring_entitled'));
insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type) select
LOOKUP_SERVER_ARCH('aarch64-redhat-linux'), LOOKUP_SG_TYPE('virtualization_host') from dual
where not exists (select 1 from rhnServerServerGroupArchCompat where server_arch_id = LOOKUP_SERVER_ARCH('aarch64-redhat-linux') and server_group_type = LOOKUP_SG_TYPE('virtualization_host'));

insert into rhnCpuArch (id, label, name) select
sequence_nextval('rhn_cpu_arch_id_seq'), 'aarch64', 'AArch64' from dual
where not exists (select 1 from rhnCpuArch where label = 'aarch64');
  07070100000AC8000081B400000000000000000000000167AE111400000125000000000000000000000000000000000000006800000000susemanager-schema/upgrade/susemanager-schema-2.1.51-to-susemanager-schema-3.0/0007-rhnUserExtGroup.sql   ALTER TABLE rhnUserExtGroup ADD org_id NUMERIC DEFAULT NULL
    CONSTRAINT rhn_userExtGroup_oid_fk
        REFERENCES web_customer (id)
        ON DELETE CASCADE;

CREATE UNIQUE INDEX rhn_userextgroup_label_oid_uq
    ON rhnUserExtGroup (label, org_id) ;
DROP INDEX rhn_userextgroup_label_uq;
   07070100000AC9000081B400000000000000000000000167AE1114000005B2000000000000000000000000000000000000006E00000000susemanager-schema/upgrade/susemanager-schema-2.1.51-to-susemanager-schema-3.0/0008-rhnOrgExtGroupMapping.sql --
-- Copyright (c) 2014 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnOrgExtGroupMapping
(
    id        NUMERIC NOT NULL
                  CONSTRAINT rhn_orgextgroupmap_id_pk PRIMARY KEY
                  ,
    ext_group_id       NUMERIC NOT NULL
                  constraint rhn_orgextgroupmap_eg_fk
                  references rhnUserExtGroup(id)
                  on delete cascade,
    server_group_id    NUMERIC NOT NULL
                  constraint rhn_orgextgroupmap_sg_fk
                  references rhnServerGroup(id)
                  on delete cascade,
    created   TIMESTAMPTZ
                  DEFAULT (current_timestamp) NOT NULL,
    modified  TIMESTAMPTZ
                  DEFAULT (current_timestamp) NOT NULL
)

;

CREATE UNIQUE INDEX rhn_orgextgroupmap_es_uq
    ON rhnOrgExtGroupMapping (ext_group_id, server_group_id)
    ;

CREATE SEQUENCE rhn_orgextgroupmap_seq;
  07070100000ACA000081B400000000000000000000000167AE1114000000AC000000000000000000000000000000000000006C00000000susemanager-schema/upgrade/susemanager-schema-2.1.51-to-susemanager-schema-3.0/0009-rhnOrgConfiguration.sql   ALTER TABLE rhnOrgConfiguration ADD create_default_sg CHAR(1)
    default('N') not null
    constraint rhn_org_cong_deforg_chk
    check (create_default_sg in ('Y', 'N'));
07070100000ACB000081B400000000000000000000000167AE11140000042A000000000000000000000000000000000000007300000000susemanager-schema/upgrade/susemanager-schema-2.1.51-to-susemanager-schema-3.0/0011-rhnOrgExtGroupMapping-trig.sql    --
-- Copyright (c) 2014 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

create or replace function rhn_userorgextgrmap_mod_trig_fun() returns trigger as
$$
begin
        if new.id is null then
            new.id := nextval('rhn_orgextgroupmap_seq');
        end if;
        new.modified := current_timestamp;
        return new;
end;
$$ language plpgsql;

create trigger
rhn_userorgextgrmap_mod_trig
before insert or update on rhnOrgExtGroupMapping
for each row
execute procedure rhn_userorgextgrmap_mod_trig_fun();
  07070100000ACC000081B400000000000000000000000167AE1114000002CC000000000000000000000000000000000000006900000000susemanager-schema/upgrade/susemanager-schema-2.1.51-to-susemanager-schema-3.0/0012-rhnServer-secret.sql  
drop view rhnentitledservers;

alter table rhnServer alter column secret type varchar(64);

create or replace view
rhnEntitledServers
as
select distinct
    S.id,
    S.org_id,
    S.digital_server_id,
    S.server_arch_id,
    S.os,
    S.release,
    S.name,
    S.description,
    S.info,
    S.secret
from
    rhnServerGroup SG,
    rhnServerGroupType SGT,
    rhnServerGroupMembers SGM,
    rhnServer S
where
    S.id = SGM.server_id
and SG.id = SGM.server_group_id
and SGT.label IN ('sw_mgr_entitled', 'enterprise_entitled', 'provisioning_entitled')
and SG.group_type = SGT.id
and SG.org_id = S.org_id
;

alter table rhnServer_log alter column secret type varchar(64);

select .recreate_trigger('rhnserver');
07070100000ACD000081B400000000000000000000000167AE111400000500000000000000000000000000000000000000006900000000susemanager-schema/upgrade/susemanager-schema-2.1.51-to-susemanager-schema-3.0/0018-rhnPackageBreaks.sql  --
-- Copyright (c) 2010 Novell
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
--


CREATE TABLE rhnPackageBreaks
(
    package_id     NUMERIC NOT NULL
                       CONSTRAINT rhn_pkg_brks_package_fk
                           REFERENCES rhnPackage (id)
                           ON DELETE CASCADE,
    capability_id  NUMERIC NOT NULL
                       CONSTRAINT rhn_pkg_brks_capability_fk
                           REFERENCES rhnPackageCapability (id),
    sense          NUMERIC
                       DEFAULT (0) NOT NULL,
    created        TIMESTAMPTZ
                       DEFAULT (current_timestamp) NOT NULL,
    modified       TIMESTAMPTZ
                       DEFAULT (current_timestamp) NOT NULL
)

;

CREATE UNIQUE INDEX rhn_pkg_brks_pid_cid_s_uq
    ON rhnPackageBreaks (package_id, capability_id, sense)
    ;

CREATE INDEX rhn_pkg_brks_cid_idx
    ON rhnPackageBreaks (capability_id)
    
    ;

07070100000ACE000081B400000000000000000000000167AE11140000050C000000000000000000000000000000000000006D00000000susemanager-schema/upgrade/susemanager-schema-2.1.51-to-susemanager-schema-3.0/0019-rhnPackagePredepends.sql  --
-- Copyright (c) 2010 Novell
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
--


CREATE TABLE rhnPackagePredepends
(
    package_id     NUMERIC NOT NULL
                       CONSTRAINT rhn_pkg_pdep_package_fk
                           REFERENCES rhnPackage (id)
                           ON DELETE CASCADE,
    capability_id  NUMERIC NOT NULL
                       CONSTRAINT rhn_pkg_pdep_capability_fk
                           REFERENCES rhnPackageCapability (id),
    sense          NUMERIC
                       DEFAULT (0) NOT NULL,
    created        TIMESTAMPTZ
                       DEFAULT (current_timestamp) NOT NULL,
    modified       TIMESTAMPTZ
                       DEFAULT (current_timestamp) NOT NULL
)

;

CREATE UNIQUE INDEX rhn_pkg_pdep_pid_cid_s_uq
    ON rhnPackagePredepends (package_id, capability_id, sense)
    ;

CREATE INDEX rhn_pkg_pdep_cid_idx
    ON rhnPackagePredepends (capability_id)
    
    ;

07070100000ACF000081B400000000000000000000000167AE1114000002E4000000000000000000000000000000000000007100000000susemanager-schema/upgrade/susemanager-schema-2.1.51-to-susemanager-schema-3.0/0020-rhnPackageBreaks-trigger.sql  --
-- Copyright (c) 2010 Novell, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
--

create or replace function rhn_pkg_brks_mod_trig_fun() returns trigger as
$$
begin
	new.modified := current_timestamp;

	return new;
end;
$$ language plpgsql;

create trigger
rhn_pkg_brks_mod_trig
before insert or update on rhnPackageBreaks
for each row
execute procedure rhn_pkg_brks_mod_trig_fun();

07070100000AD0000081B400000000000000000000000167AE1114000002E8000000000000000000000000000000000000007500000000susemanager-schema/upgrade/susemanager-schema-2.1.51-to-susemanager-schema-3.0/0020-rhnPackagePredepends-trigger.sql  --
-- Copyright (c) 2010 Novell, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
--

create or replace function rhn_pkg_pdep_mod_trig_fun() returns trigger as
$$
begin
	new.modified := current_timestamp;

	return new;
end;
$$ language plpgsql;

create trigger
rhn_pkg_pdep_mod_trig
before insert or update on rhnPackagePredepends
for each row
execute procedure rhn_pkg_pdep_mod_trig_fun();

07070100000AD1000081B400000000000000000000000167AE111400000071000000000000000000000000000000000000007100000000susemanager-schema/upgrade/susemanager-schema-2.1.51-to-susemanager-schema-3.0/0021-rhnActionType-clientcert.sql  insert
  into rhnActionType
values (51, 'clientcert.update_client_cert', 'Update Client Certificate', 'N', 'Y');
   07070100000AD2000081B400000000000000000000000167AE1114000004BF000000000000000000000000000000000000007500000000susemanager-schema/upgrade/susemanager-schema-2.1.51-to-susemanager-schema-3.0/0024-rhnKickstartableTree-trigger.sql  
create or replace function rhn_kstree_mod_trig_fun() returns trigger as
$$
begin
        if tg_op='UPDATE' then
                -- Basically if we're changing something other than cobbler_id,
                -- cobbler_xen_id, and last_modified - or if last_modified is
                -- explicity set to null. Gets complicated because we have
                -- to allow for the possibility of the ids being null
                if ((not old.cobbler_id is null and new.cobbler_id = old.cobbler_id)
                        or (old.cobbler_id is null and new.cobbler_id is null))
                    and ((not old.cobbler_xen_id is null and new.cobbler_xen_id = old.cobbler_xen_id)
                        or (old.cobbler_xen_id is null and new.cobbler_xen_id is null))
                    and new.last_modified = old.last_modified
                    or new.last_modified is null
                then
                    new.last_modified := current_timestamp;
                end if;
        elseif tg_op='INSERT' and new.last_modified is null then
                new.last_modified := current_timestamp;
        end if;

        new.modified := current_timestamp;

        return new;
end;
$$ language plpgsql;
 07070100000AD3000081B400000000000000000000000167AE111400000114000000000000000000000000000000000000008100000000susemanager-schema/upgrade/susemanager-schema-2.1.51-to-susemanager-schema-3.0/0025-rhnKickstartableTree-touch-last_modified.sql  -- Update last_modified on every kickstart tree.
-- This will force a re-sync to cobbler the next time
-- something on cobbler changes or taskomatic is restarted.
-- The re-sync will correct the cobbler arch.
update rhnKickstartableTree set last_modified = current_timestamp;
07070100000AD4000081B400000000000000000000000167AE11140000098F000000000000000000000000000000000000007400000000susemanager-schema/upgrade/susemanager-schema-2.1.51-to-susemanager-schema-3.0/0026-support-for-armhf-on-debian.sql   
insert into rhnPackageArch (id, label, name, arch_type_id) values
        (sequence_nextval('rhn_package_arch_id_seq'), 'armhf-deb', 'armhf-deb', lookup_arch_type('deb'));

insert into rhnChannelPackageArchCompat (channel_arch_id, package_arch_id)
        values (LOOKUP_CHANNEL_ARCH('channel-arm-deb'), LOOKUP_PACKAGE_ARCH('armhf-deb'));

insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('armhf-deb'), LOOKUP_PACKAGE_ARCH('all-deb'), current_timestamp, current_timestamp);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('all-deb'), LOOKUP_PACKAGE_ARCH('armhf-deb'), current_timestamp, current_timestamp);
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) values (LOOKUP_PACKAGE_ARCH('armhf-deb'), LOOKUP_PACKAGE_ARCH('armhf-deb'), current_timestamp, current_timestamp);

insert into rhnServerArch (id, label, name, arch_type_id) values
(sequence_nextval('rhn_server_arch_id_seq'), 'armv6l-debian-linux', 'arm Debian', lookup_arch_type('deb'));

insert into rhnServerChannelArchCompat (server_arch_id, channel_arch_id) values
(LOOKUP_SERVER_ARCH('armv6l-debian-linux'), LOOKUP_CHANNEL_ARCH('channel-arm-deb'));

insert into rhnServerPackageArchCompat
(server_arch_id, package_arch_id, preference) values
(LOOKUP_SERVER_ARCH('armv6l-debian-linux'), LOOKUP_PACKAGE_ARCH('armhf-deb'), 0);
insert into rhnServerPackageArchCompat
(server_arch_id, package_arch_id, preference) values
(LOOKUP_SERVER_ARCH('armv6l-debian-linux'), LOOKUP_PACKAGE_ARCH('all-deb'), 1000);


insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
        values (lookup_server_arch('armv6l-debian-linux'),
            lookup_sg_type('sw_mgr_entitled'));
insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
        values (lookup_server_arch('armv6l-debian-linux'),
            lookup_sg_type('enterprise_entitled'));
insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
        values (lookup_server_arch('armv6l-debian-linux'),
            lookup_sg_type('provisioning_entitled'));
insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
        values (lookup_server_arch('armv6l-debian-linux'),
            lookup_sg_type('monitoring_entitled'));

 07070100000AD5000081B400000000000000000000000167AE111400000198000000000000000000000000000000000000006F00000000susemanager-schema/upgrade/susemanager-schema-2.1.51-to-susemanager-schema-3.0/0027-rhnPackageKey-CentOS-7.sql    update rhnPackageKey set provider_id = lookup_package_provider('CentOS')
 where key_id = '24c6a8a7f4a80eb5';

insert into rhnPackageKey (id, key_id, key_type_id, provider_id)
    (select sequence_nextval('rhn_pkey_id_seq'), '24c6a8a7f4a80eb5', lookup_package_key_type('gpg'), lookup_package_provider('CentOS') from dual
     where not exists (select 1 from rhnPackageKey where key_id = '24c6a8a7f4a80eb5'));
07070100000AD6000081B400000000000000000000000167AE11140000038D000000000000000000000000000000000000007200000000susemanager-schema/upgrade/susemanager-schema-2.1.51-to-susemanager-schema-3.0/1001-lookup_package_capability.sql 
-- Note: intentionally not thread-safe! You must aquire a write lock on the
-- rhnPackageCapability tabel if you are going to use this proc!
create or replace function lookup_package_capability_fast(name_in in varchar, version_in in varchar default null)
returns numeric
as
$$
declare
    name_id numeric;
begin
    if version_in is null then
        select id
          into name_id
          from rhnpackagecapability
         where name = name_in and
               version is null;
    else
        select id
          into name_id
          from rhnpackagecapability
         where name = name_in and
               version = version_in;
    end if;

    if not found then
        name_id = nextval('rhn_pkg_capability_id_seq');
        insert into rhnPackageCapability(id, name, version) values (
               name_id, name_in, version_in);
    end if;

    return name_id;
end;
$$
language plpgsql;
   07070100000AD7000081B400000000000000000000000167AE1114000002E2000000000000000000000000000000000000007000000000susemanager-schema/upgrade/susemanager-schema-2.1.51-to-susemanager-schema-3.0/1001-rhnPackageKey-Fedora-21.sql   update rhnPackageKey set provider_id = lookup_package_provider('Fedora')
 where key_id = '89ad4e8795a43f54' or key_id = '636dea19a0a7badb';

insert into rhnPackageKey (id, key_id, key_type_id, provider_id)
    (select sequence_nextval('rhn_pkey_id_seq'), '89ad4e8795a43f54', lookup_package_key_type('gpg'), lookup_package_provider('Fedora') from dual
     where not exists (select 1 from rhnPackageKey where key_id = '89ad4e8795a43f54'));

insert into rhnPackageKey (id, key_id, key_type_id, provider_id)
    (select sequence_nextval('rhn_pkey_id_seq'), '636dea19a0a7badb', lookup_package_key_type('gpg'), lookup_package_provider('Fedora') from dual
     where not exists (select 1 from rhnPackageKey where key_id = '636dea19a0a7badb'));
  07070100000AD8000081B400000000000000000000000167AE11140000034C000000000000000000000000000000000000006800000000susemanager-schema/upgrade/susemanager-schema-2.1.51-to-susemanager-schema-3.0/1002-lookup_checksum.sql   
-- NOTE: This is intentionally not thread safe! You must lock rhnChecksum
-- if you are going to use this procedure!
create or replace function
lookup_checksum_fast(checksum_type_in in varchar, checksum_in in varchar)
returns numeric
as
$$
declare
    checksum_id     numeric;
begin
    if checksum_in is null then
        return null;
    end if;

    select c.id
      into checksum_id
      from rhnChecksumView c
     where c.checksum = checksum_in and
           c.checksum_type = checksum_type_in;

    if not found then
        checksum_id := nextval('rhnchecksum_seq');
        insert into rhnChecksum (id, checksum_type_id, checksum) values (
            checksum_id,
            (select id from rhnChecksumType where label = checksum_type_in),
            checksum_in);
    end if;

    return checksum_id;
end;
$$
language plpgsql;
07070100000AD9000081B400000000000000000000000167AE11140000006A000000000000000000000000000000000000007200000000susemanager-schema/upgrade/susemanager-schema-2.1.51-to-susemanager-schema-3.0/1003-rhnServerGroupTypeFeature.sql delete from rhnServerGroupTypeFeature where server_group_type_id = lookup_sg_type('monitoring_entitled');
  07070100000ADA000081B400000000000000000000000167AE11140000047E000000000000000000000000000000000000007900000000susemanager-schema/upgrade/susemanager-schema-2.1.51-to-susemanager-schema-3.0/1004-rhnConfigRevision-delete-trigger.sql  --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--


create or replace function rhn_confrevision_del_trig_fun() returns trigger 
as
$$
declare
        cr_removed numeric := lookup_snapshot_invalid_reason('cr_removed');
begin
        update rhnSnapshot as s
           set invalid = cr_removed
          from rhnSnapshotConfigRevision as scr
         where s.id = scr.snapshot_id
           and scr.config_revision_id = old.id;
        delete from rhnSnapshotConfigRevision
         where config_revision_id = old.id;
        return old;
end;
$$ language plpgsql;
  07070100000ADB000081B400000000000000000000000167AE111400000152000000000000000000000000000000000000006900000000susemanager-schema/upgrade/susemanager-schema-2.1.51-to-susemanager-schema-3.0/1005-rhnTimezone-data.sql  insert into rhnTimezone (id, olson_name, display_name) (
    select sequence_nextval('rhn_timezone_id_seq'),
           'Asia/Seoul',
           'Korea'
      from dual
     where not exists (
           select 1
             from rhnTimezone
            where olson_name = 'Asia/Seoul'
              and display_name = 'Korea'
     )
);
  07070100000ADC000081B400000000000000000000000167AE111400000060000000000000000000000000000000000000007A00000000susemanager-schema/upgrade/susemanager-schema-2.1.51-to-susemanager-schema-3.0/1006-rhnTaskoSchedule-update-cron_expr.sql update rhnTaskoSchedule set cron_expr = '0 * * * * ?' where job_label = 'errata-cache-default';
07070100000ADD000081B400000000000000000000000167AE11140000BBC1000000000000000000000000000000000000006800000000susemanager-schema/upgrade/susemanager-schema-2.1.51-to-susemanager-schema-3.0/1007-rhn_channel.pkb.sql   --
-- Copyright (c) 2008--2014 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--

-- create schema rhn_channel;

--update pg_setting
update pg_settings set setting = 'rhn_channel,' || setting where name = 'search_path';

    create or replace function obtain_read_lock(channel_family_id_in in numeric, org_id_in in numeric)
    returns void as $$
    declare
        read_lock timestamptz;
    begin
        select created into read_lock
          from rhnPrivateChannelFamily
         where channel_family_id = channel_family_id_in and org_id = org_id_in
           for update;
    end$$ language plpgsql;

    -- this "emulates" cursor server_base_subscriptions defined in oracle/rhn_channel.pks
    create or replace function server_base_subscriptions(server_id_in NUMERIC)
    returns boolean as $$
    begin
      return exists(SELECT C.id FROM rhnChannel C, rhnServerChannel SC
		    WHERE C.id = SC.channel_id
		      AND SC.server_id = server_id_in
		      AND C.parent_channel IS NULL);
    end$$ language plpgsql;

    -- this "emulates" cursor server_base_subscriptions defined in oracle/rhn_channel.pks
    create or replace function check_server_subscription(server_id_in NUMERIC, channel_id_in NUMERIC)
    returns boolean as $$
    begin
      return exists(SELECT channel_id FROM rhnServerChannel WHERE server_id = server_id_in AND channel_id = channel_id_in);
    end$$ language plpgsql;


    CREATE OR REPLACE FUNCTION subscribe_server(server_id_in IN NUMERIC, channel_id_in NUMERIC, immediate_in NUMERIC default 1, user_id_in in numeric default null, recalcfamily_in NUMERIC default 1) returns void
    AS $$
    declare
        channel_parent_val      rhnChannel.parent_channel%TYPE;
        parent_subscribed       BOOLEAN;
        server_has_base_chan    BOOLEAN;
        server_already_in_chan  BOOLEAN;
        channel_family_id_val   NUMERIC;
        server_org_id_val       NUMERIC;
        available_subscriptions NUMERIC;
        available_fve_subs      numeric;
        consenting_user         NUMERIC;
        allowed                 numeric;
        is_fve_char             char(1) := 'N';
    BEGIN
        if user_id_in is not null then
            allowed := rhn_channel.user_role_check(channel_id_in, user_id_in, 'subscribe');
        else
            allowed := 1;
        end if;

        if allowed = 0 then
            perform rhn_exception.raise_exception('no_subscribe_permissions');
        end if;


        SELECT parent_channel INTO channel_parent_val FROM rhnChannel WHERE id = channel_id_in;

        IF channel_parent_val IS NOT NULL
        THEN    
            -- child channel; if attempting to cross-subscribe a child to the wrong base, silently ignore
            parent_subscribed := rhn_channel.check_server_subscription(server_id_in, channel_parent_val);
        
            IF NOT parent_subscribed
            THEN
                RETURN;
            END IF;
        ELSE
            -- base channel
            server_has_base_chan := rhn_channel.server_base_subscriptions(server_id_in);
            
            IF server_has_base_chan
            THEN
                perform rhn_exception.raise_exception('channel_server_one_base');
            END IF;
        END IF;

        server_already_in_chan := rhn_channel.check_server_subscription(server_id_in, channel_id_in);
    
        IF server_already_in_chan
        THEN
            RETURN;
        END IF;
        
        channel_family_id_val := rhn_channel.family_for_channel(channel_id_in);
        IF channel_family_id_val IS NULL
        THEN
            perform rhn_exception.raise_exception('channel_subscribe_no_family');
        END IF;

        --
        -- Use the org_id of the server only if the org_id of the channel = NULL.
        -- This is required for subscribing to shared channels.
        --
        SELECT COALESCE(org_id, (SELECT org_id FROM rhnServer WHERE id = server_id_in))
          INTO server_org_id_val
          FROM rhnChannel
         WHERE id = channel_id_in;
         
        begin
            perform rhn_channel.obtain_read_lock(channel_family_id_val, server_org_id_val);
        exception
            when no_data_found then
                perform rhn_exception.raise_exception('channel_family_no_subscriptions');
        end;

        available_subscriptions := rhn_channel.available_family_subscriptions(channel_family_id_val, server_org_id_val);
        available_fve_subs := rhn_channel.available_fve_family_subs(channel_family_id_val, server_org_id_val);
        
        IF available_subscriptions IS NULL OR 
           available_subscriptions > 0 or
           rhn_channel.can_server_consume_virt_channl(server_id_in, channel_family_id_val) = 1 OR
           (available_fve_subs > 0 AND rhn_channel.can_server_consume_fve(server_id_in) = 1) OR
           rhn_channel.server_has_family_subscription(server_id_in, channel_family_id_val) > 0
        THEN
            if rhn_channel.can_server_consume_virt_channl(server_id_in, channel_family_id_val) = 0 AND available_fve_subs > 0 AND rhn_channel.can_server_consume_fve(server_id_in) = 1 THEN
                is_fve_char := 'Y';
            end if;

            insert into rhnServerHistory (id,server_id,summary,details) (
                select  nextval('rhn_event_id_seq'),
                        server_id_in,
                        'subscribed to channel ' || SUBSTR(c.label, 0, 106),
                        c.label
                from    rhnChannel c
                where   c.id = channel_id_in
            );

            INSERT INTO rhnServerChannel (server_id, channel_id, is_fve) VALUES (server_id_in, channel_id_in, is_fve_char);
			IF recalcfamily_in > 0
			THEN
                perform rhn_channel.update_family_counts(channel_family_id_val, server_org_id_val);
			END IF;

            perform queue_server(server_id_in, immediate_in);

            update rhnServer
               set channels_changed = current_timestamp
             where id = server_id_in;
        ELSE
            perform rhn_exception.raise_exception('channel_family_no_subscriptions');
        END IF;
            
    END$$ language plpgsql;



    create or replace function can_convert_to_fve(server_id_in IN NUMERIC, channel_family_id_val IN NUMERIC)
    RETURNS NUMERIC
    as $$
    declare
        fve_convertible_entries cursor for
        select 1  from
            rhnServerFveCapable cap
          where cap.server_id = server_id_in
                AND cap.channel_family_id = channel_family_id_val;
    BEGIN
        FOR entry IN fve_convertible_entries LOOP
            return 1;
        END LOOP;
        RETURN 0;
    END$$ language plpgsql;



    -- Converts server channel_family to use a flex entitlement
    create or replace function convert_to_fve(server_id_in IN NUMERIC, channel_family_id_val IN NUMERIC)
    returns void
    as $$
    declare
        available_fve_subs      NUMERIC;
        server_org_id_val       NUMERIC;
    BEGIN

        --
        -- Use the org_id of the server only if the org_id of the channel = NULL.
        -- This is required for subscribing to shared channels.
        --
        SELECT org_id
          INTO server_org_id_val
          FROM rhnServer
         WHERE id = server_id_in;


        perform rhn_channel.obtain_read_lock(channel_family_id_val, server_org_id_val);
        if not found then
                perform rhn_exception.raise_exception('channel_family_no_subscriptions');
        end if;
        IF (rhn_channel.can_convert_to_fve(server_id_in, channel_family_id_val ) = 0)
            THEN
                perform rhn_exception.raise_exception('server_cannot_convert_to_flex');
        END IF;

        available_fve_subs := rhn_channel.available_fve_family_subs(channel_family_id_val, server_org_id_val);

        IF (available_fve_subs > 0)
        THEN

            insert into rhnServerHistory (id,server_id,summary,details) (
                select  nextval('rhn_event_id_seq'),
                        server_id_in,
                        'converted to flex entitlement' || SUBSTR(cf.label, 0, 99),
                        cf.label
                from    rhnChannelFamily cf
                where   cf.id = channel_family_id_val
            );

            UPDATE rhnServerChannel sc set is_fve = 'Y'
                           where sc.server_id = server_id_in and
                                 sc.channel_id in
                                    (select cfm.channel_id from rhnChannelFamilyMembers cfm
                                                where cfm.CHANNEL_FAMILY_ID = channel_family_id_val);

            perform rhn_channel.update_family_counts(channel_family_id_val, server_org_id_val);
        ELSE
            perform rhn_exception.raise_exception('not_enough_flex_entitlements');
        END IF;

    END$$ language plpgsql;
    
    create or replace function can_server_consume_virt_channl(
        server_id_in in numeric,
        family_id_in in numeric )
    returns numeric
    as $$
    begin
      if exists(
            select 1
            from
                rhnChannelFamilyVirtSubLevel cfvsl,
                rhnSGTypeVirtSubLevel sgtvsl,
                rhnVirtualInstance vi
            where
                vi.virtual_system_id = server_id_in 
                and sgtvsl.virt_sub_level_id = cfvsl.virt_sub_level_id
                and cfvsl.channel_family_id = family_id_in
                and exists (
                    select 1
                    from rhnServerEntitlementView sev
                    where vi.host_system_id = sev.server_id
                    and sev.server_group_type_id = sgtvsl.server_group_type_id ))
      then
        return 1;
      else
        return 0;
      end if;
    end$$ language plpgsql;

    create or replace function can_server_consume_fve(server_id_in in numeric) returns numeric
    as $$
    declare
        vi_entries cursor for
            SELECT 1
              FROM rhnVirtualInstance vi
             WHERE vi.virtual_system_id = server_id_in;
        vi_count numeric;

    begin
        FOR vi_entry IN VI_ENTRIES LOOP
            return 1;
        END LOOP;
        RETURN 0;
    end$$ language plpgsql;

    create or replace function guess_server_base(
        server_id_in in numeric
    ) RETURNS numeric as $$
    declare
        server_cursor cursor for
            select s.server_arch_id, s.release, s.org_id
              from rhnServer s
             where s.id = server_id_in;
    -- Cursor that fetches all the possible base channels for a
    -- (server_arch_id, release, org_id) combination
        base_channel_cursor cursor(
                release_in varchar,
                server_arch_id_in numeric,
                org_id_in numeric
        ) for
                select distinct c.*
                from    rhnOrgDistChannelMap                       odcm,
                                rhnServerChannelArchCompat      scac,
                                rhnChannel                                      c
                where   c.parent_channel is null
                        and c.id = odcm.channel_id
                        and c.channel_arch_id = odcm.channel_arch_id
                        and odcm.release = release_in
                        and odcm.for_org_id = org_id_in
                        and scac.server_arch_id = server_arch_id_in
                        and scac.channel_arch_id = c.channel_arch_id;

    begin
        for s in server_cursor loop
            for channel in base_channel_cursor(s.release,
                s.server_arch_id, s.org_id) 
            loop
                return channel.id;
            end loop;
        end loop;
        -- Server not found, or no base channel applies to it
        return null;
    end$$ language plpgsql;

    -- Private function
    create or replace function normalize_server_arch(server_arch_in in varchar)
    returns varchar
    as $$
    declare
        suffix VARCHAR(128) := '-redhat-linux';
    begin
        if server_arch_in is NULL then
            return NULL;
        end if;
        if position('-' IN server_arch_in) > 0
        then
            -- Suffix already present
            return server_arch_in;
        end if;
        return server_arch_in || suffix;
    end$$ language plpgsql;

    --
    -- Raises: 
    --   server_arch_not_found
    --   no_subscribe_permissions
    create or replace function base_channel_for_release_arch(
        release_in in varchar,
        server_arch_in in varchar,
        org_id_in in numeric default -1,
        user_id_in in numeric default null
    ) returns numeric as $$
    declare
        server_arch varchar(256) := rhn_channel.normalize_server_arch(server_arch_in);
        server_arch_id numeric;
    begin
        -- Look up the server arch
            select id
              into server_arch_id
              from rhnServerArch
             where label = server_arch;
            if not found then
                perform rhn_exception.raise_exception('server_arch_not_found');
            end if;

        return rhn_channel.base_channel_rel_archid(release_in, server_arch_id,
            org_id_in, user_id_in);
    end$$ language plpgsql;

    create or replace function base_channel_rel_archid(
        release_in in varchar,
        server_arch_id_in in numeric,
        org_id_in in numeric default -1,
        user_id_in in numeric default null
    ) returns numeric as $$
    declare
        denied_channel_id numeric := null;
        valid_org_id numeric := org_id_in;
        valid_user_id numeric := user_id_in;
        channel_subscribable numeric;
    -- Cursor that fetches all the possible base channels for a
    -- (server_arch_id, release, org_id) combination
        base_channel_cursor cursor(
                release_in varchar,
                server_arch_id_in numeric,
                org_id_in numeric
        ) for
                select distinct c.*
                from    rhnOrgDistChannelMap                       odcm,
                                rhnServerChannelArchCompat      scac,
                                rhnChannel                                      c
                where   c.parent_channel is null
                        and c.id = odcm.channel_id
                        and c.channel_arch_id = odcm.channel_arch_id
                        and odcm.release = release_in
                        and odcm.for_org_id = org_id_in
                        and scac.server_arch_id = server_arch_id_in
                        and scac.channel_arch_id = c.channel_arch_id;

    begin
        if org_id_in = -1 and user_id_in is not null then
            -- Get the org id from the user id

                select org_id
                  into valid_org_id
                  from web_contact
                 where id = user_id_in;

                if not found then
                    -- User doesn't exist
                    -- XXX Only list public stuff for now
                    valid_user_id := null;
                    valid_org_id := -1;
                end if;
        end if;

        for c in base_channel_cursor(release_in, server_arch_id_in, valid_org_id)
        loop
            -- This row is a possible match
            if valid_user_id is null then
                -- User ID not specified, so no user to channel permissions to
                -- check
                return c.id;
            end if;

            -- Check user to channel permissions
            select rhn_channel.loose_user_role_check(c.id, user_id_in, 'subscribe')
              into channel_subscribable;

            if channel_subscribable = 1 then
                return c.id;
            end if;
                
            -- Base channel exists, but is not subscribable; keep trying
            denied_channel_id := c.id;
        end loop;
        
        if denied_channel_id is not null then
            perform rhn_exception.raise_exception('no_subscribe_permissions');
        end if;
        -- No base channel applies
        return NULL;
    end$$ language plpgsql;

    CREATE OR REPLACE FUNCTION clear_subscriptions(server_id_in IN NUMERIC, deleting_server IN NUMERIC default 0,
                                update_family_countsYN IN NUMERIC default 1 ) returns void
    AS $$
    declare
        server_channels cursor(server_id_in numeric) for
                select  s.org_id, sc.channel_id, cfm.channel_family_id
                from    rhnServer s,
                        rhnServerChannel sc,
                        rhnChannelFamilyMembers cfm
                where   s.id = server_id_in
                        and s.id = sc.server_id
                        and sc.channel_id = cfm.channel_id
                order by cfm.channel_family_id;
        last_channel_family_id rhnChannelFamilyMembers.channel_family_id%type := -1;
        last_channel_org_id    rhnServer.org_id%type := -1;
    BEGIN
        for channel in server_channels(server_id_in)
        loop
                perform rhn_channel.unsubscribe_server(server_id_in, channel.channel_id, 1, 1, deleting_server, 0);
                if update_family_countsYN > 0
                    and channel.channel_family_id != last_channel_family_id then
                    -- update family counts only once
                    -- after all channels with same family has been fetched
                    if last_channel_family_id != -1 then
                        perform rhn_channel.update_family_counts(channel.channel_family_id, channel.org_id);
                    end if;
                    last_channel_family_id := channel.channel_family_id;
                    last_channel_org_id    := channel.org_id;
                end if;
        end loop;
        if update_family_countsYN > 0 and last_channel_family_id != -1 then
            -- update the last family fetched
            perform rhn_channel.update_family_counts(last_channel_family_id, last_channel_org_id);
        end if;
    END$$ language plpgsql;

    CREATE OR REPLACE FUNCTION unsubscribe_server(server_id_in IN NUMERIC, channel_id_in NUMERIC, immediate_in NUMERIC default 1, unsubscribe_children_in numeric default 0,
                                 deleting_server in numeric default 0,
                                 update_family_countsYN in numeric default 1) returns void
    AS $$
    declare
        channel_family_id_val   NUMERIC;
        server_org_id_val       NUMERIC;
        available_subscriptions NUMERIC; 
        server_already_in_chan  BOOLEAN;
        channel_family_is_proxy cursor(channel_family_id_in numeric) for
                select  1
                from    rhnChannelFamily
                where   id = channel_family_id_in
                    and label = 'rhn-proxy';
        channel_family_is_satellite cursor(channel_family_id_in numeric) for
                select  1
                from    rhnChannelFamily
                where   id = channel_family_id_in
                    and label = 'rhn-satellite';
        child record;
    BEGIN
        -- In PostgreSQL recursion with opened cursors is not allowed so we use
        -- FOR IN SELECT form which is ok.
        FOR child IN select  c.id
                from    rhnChannel                      c,
                                rhnServerChannel        sc
                where   1=1
                        and c.parent_channel = channel_id_in
                        and c.id = sc.channel_id
                        and sc.server_id = server_id_in
        LOOP
            if unsubscribe_children_in = 1 then
                perform rhn_channel.unsubscribe_server(server_id_in,
                                                       child.id,
                                                       immediate_in,
                                                       unsubscribe_children_in,
                                                       deleting_server,
                                                       update_family_countsYN);
            else
                perform rhn_exception.raise_exception('channel_unsubscribe_child_exists');
            end if;
        END LOOP;
        
        server_already_in_chan := rhn_channel.check_server_subscription(server_id_in, channel_id_in);
    
        IF NOT server_already_in_chan
        THEN
            RETURN;
        END IF;
        
   if deleting_server = 0 then 
      insert into rhnServerHistory (id,server_id,summary,details) (
          select  nextval('rhn_event_id_seq'),
                server_id_in,
             'unsubscribed from channel ' || SUBSTR(c.label, 0, 106),
             c.label
          from    rhnChannel c
          where   c.id = channel_id_in
      );
   end if;
        
   DELETE FROM rhnServerChannel WHERE server_id = server_id_in AND channel_id = channel_id_in;

   if deleting_server = 0 then 
        perform queue_server(server_id_in, immediate_in);

        update rhnServer
           set channels_changed = current_timestamp
         where id = server_id_in;
   end if;

        channel_family_id_val := rhn_channel.family_for_channel(channel_id_in);
        IF channel_family_id_val IS NULL
        THEN
            perform rhn_exception.raise_exception('channel_unsubscribe_no_family');
        END IF;

        for ignore in channel_family_is_satellite(channel_family_id_val) loop
                delete from rhnSatelliteInfo where server_id = server_id_in;
        end loop;

        for ignore in channel_family_is_proxy(channel_family_id_val) loop
                delete from rhnProxyInfo where server_id = server_id_in;
        end loop;
        SELECT org_id INTO server_org_id_val
          FROM rhnServer
         WHERE id = server_id_in;
         
        if update_family_countsYN = 1 then
           perform rhn_channel.update_family_counts(channel_family_id_val, server_org_id_val);
        end if;
    END$$ language plpgsql;

    CREATE OR REPLACE FUNCTION family_for_channel(channel_id_in IN NUMERIC)
    RETURNS NUMERIC
    AS $$
    declare
        channel_family_id_val NUMERIC;
    BEGIN
        SELECT channel_family_id INTO channel_family_id_val
          FROM rhnChannelFamilyMembers
         WHERE channel_id = channel_id_in;

        IF NOT FOUND THEN
          RETURN NULL;
        END IF;
         
        RETURN channel_family_id_val;
    END$$ language plpgsql;

    CREATE OR REPLACE FUNCTION available_family_subscriptions(channel_family_id_in IN NUMERIC, org_id_in IN NUMERIC)
    RETURNS NUMERIC
    AS $$
    declare
        cfp record;
        current_members_val NUMERIC;
        max_members_val     NUMERIC;
        found               NUMERIC;
    BEGIN
        for cfp in SELECT * FROM rhnOrgChannelFamilyPermissions
	    WHERE channel_family_id = channel_family_id_in
	      AND org_id = org_id_in
        LOOP
            found := 1;
            current_members_val := cfp.current_members;
            max_members_val := cfp.max_members;
        END LOOP;

        -- not found: either the channel fam doesn't have an entry in cfp, or the org doesn't have access to it.
        -- either way, there are no available subscriptions

        IF found IS NULL
        THEN
            RETURN 0;
        END IF;

        -- null max members?  in that case, pass it on; NULL means infinite
        IF max_members_val IS NULL
        THEN
            RETURN NULL;
        END IF;

        -- otherwise, return the delta
        RETURN max_members_val - current_members_val;
    END$$ language plpgsql;

    CREATE OR REPLACE FUNCTION available_fve_family_subs(channel_family_id_in IN NUMERIC, org_id_in IN NUMERIC)
    RETURNS NUMERIC
    AS $$
    declare
        cfp record;
        fve_current_members_val NUMERIC;
        fve_max_members_val     NUMERIC;
        found               NUMERIC;
    BEGIN
        for cfp in SELECT * FROM rhnOrgChannelFamilyPermissions
	    WHERE channel_family_id = channel_family_id_in
	      AND org_id = org_id_in
        LOOP
            found := 1;
            fve_current_members_val := cfp.fve_current_members;
            fve_max_members_val := cfp.fve_max_members;
        END LOOP;

        -- not found: either the channel fam doesn't have an entry in cfp, or the org doesn't have access to it.
        -- either way, there are no available subscriptions
        
        IF found IS NULL
        THEN
            RETURN 0;
        END IF;

        -- null max members?  in that case, pass it on; NULL means infinite                     
        IF fve_max_members_val IS NULL
        THEN
            RETURN NULL;
        END IF;

        -- otherwise, return the delta  
        RETURN fve_max_members_val - fve_current_members_val;
    END$$ language plpgsql;
    
    -- *******************************************************************
    -- FUNCTION: channel_family_current_members
    -- Calculates and returns the actual count of systems consuming
    --   physical channel subscriptions.
    -- Called by: update_family_counts 
    --            rhn_entitlements.repoll_virt_guest_entitlements
    -- *******************************************************************
    create or replace function channel_family_current_members(channel_family_id_in IN NUMERIC,
                                            org_id_in IN NUMERIC)
    returns numeric
    as $$
    declare
        current_members_count numeric := 0;
    begin
        select  count(distinct server_id)
        into    current_members_count
          from  rhnChannelFamilyServerPhysical cfsp
         where  cfsp.channel_family_id = channel_family_id_in
           and  cfsp.customer_id = org_id_in;
        return current_members_count;
    end$$ language plpgsql;


    create or replace function cfam_curr_fve_members(
        channel_family_id_in IN NUMERIC,
        org_id_in IN NUMERIC)
    returns numeric
    as $$
    declare
        current_members_count numeric := 0;

    begin
        select count(distinct sc.server_id)
          into current_members_count
          from rhnServerChannel sc,
               rhnChannelFamilyMembers cfm,
               rhnServer s
         where s.org_id = org_id_in
           and s.id = sc.server_id
           and cfm.channel_family_id = channel_family_id_in
           and cfm.channel_id = sc.channel_id
           and exists (
                select 1
                  from rhnChannelFamilyServerFve cfsp
                 where cfsp.CHANNEL_FAMILY_ID = channel_family_id_in
                   and cfsp.server_id = s.id
                );

        return current_members_count;
    end$$ language plpgsql;
    CREATE OR REPLACE FUNCTION update_family_counts(channel_family_id_in IN NUMERIC, 
                                   org_id_in IN NUMERIC) returns void
    AS $$
    BEGIN
        update rhnPrivateChannelFamily
           set current_members = rhn_channel.channel_family_current_members(channel_family_id_in, org_id_in),
               fve_current_members = rhn_channel.cfam_curr_fve_members(channel_family_id_in,org_id_in)
         where org_id = org_id_in
           and channel_family_id = channel_family_id_in;
    END$$ language plpgsql;
    
    create or replace function update_group_family_counts(group_label_in IN VARCHAR,
                                   org_id_in IN NUMERIC)
    returns void
    as $$
    declare
        i record;
    BEGIN
        FOR i IN (
                SELECT DISTINCT CFM.channel_family_id, SG.org_id
                 FROM rhnChannelFamilyMembers CFM
                 JOIN rhnServerChannel SC
                   ON SC.channel_id = CFM.channel_id
                 JOIN rhnServerGroupMembers SGM
                   ON SC.server_id = SGM.server_id
                 JOIN rhnServerGroup SG
                   ON SGM.server_group_id = SG.id
                 JOIN rhnServerGroupType SGT
                   ON SG.group_type = SGT.id
                WHERE SGT.label = group_label_in
                  AND SG.org_id = org_id_in
                  AND SGT.is_base = 'Y'
        ) LOOP
            perform rhn_channel.update_family_counts(i.channel_family_id, i.org_id);
        END LOOP;
    END$$ language plpgsql;

    CREATE OR REPLACE FUNCTION available_chan_subscriptions(channel_id_in IN NUMERIC, 
                                          org_id_in IN NUMERIC)
    RETURNS NUMERIC
    AS $$
    declare
            channel_family_id_val NUMERIC;
    BEGIN
        SELECT channel_family_id INTO STRICT channel_family_id_val
            FROM rhnChannelFamilyMembers
            WHERE channel_id = channel_id_in;
         
            RETURN rhn_channel.available_family_subscriptions(
                           channel_family_id_val, org_id_in);
    END$$ language plpgsql;

    CREATE OR REPLACE FUNCTION available_fve_chan_subs(channel_id_in IN NUMERIC,
                                          org_id_in IN NUMERIC)
    RETURNS NUMERIC
    AS $$
    declare
            channel_family_id_val NUMERIC;
    BEGIN
        SELECT channel_family_id INTO STRICT channel_family_id_val
            FROM rhnChannelFamilyMembers
            WHERE channel_id = channel_id_in;

            RETURN rhn_channel.available_fve_family_subs(
                           channel_family_id_val, org_id_in);
    END$$ language plpgsql;

    create or replace function unsubscribe_server_from_family(server_id_in in numeric, 
                                             channel_family_id_in in numeric)
    returns void
    as $$
    begin
        delete
        from    rhnServerChannel rsc
        where   rsc.server_id = server_id_in
            and channel_id in (
                select  rcfm.channel_id
                from    rhnChannelFamilyMembers rcfm
                where   rcfm.channel_family_id = channel_family_id_in);
    end$$ language plpgsql;

    create or replace function get_org_id(channel_id_in in numeric)
    returns numeric
    as $$
    declare
        org_id_out numeric;
    begin
        select org_id into strict org_id_out
            from rhnChannel
            where id = channel_id_in;
         
            return org_id_out;
    end$$ language plpgsql;
    
    create or replace function get_cfam_org_access(cfam_id_in in numeric, org_id_in in numeric)
    returns numeric
    as $$
    begin
      if exists(
                        select  1
                        from    rhnOrgChannelFamilyPermissions cfp
                        where   cfp.org_id = org_id_in
      ) then
                return 1;
      else
                return 0;
      end if;
    end$$ language plpgsql;

    create or replace function get_org_access(channel_id_in in numeric, org_id_in in numeric)
    returns integer
    as $$
    begin
        -- the idea: if we get past this query, 
        -- the org has access to the channel, else not
        if exists(
        select 1
          from rhnChannelFamilyMembers CFM,
               rhnOrgChannelFamilyPermissions CFP
         where cfp.org_id = org_id_in
           and CFM.channel_family_id = CFP.channel_family_id
           and CFM.channel_id = channel_id_in
           and (CFP.max_members > 0 or CFP.max_members is null or CFP.fve_max_members > 0 or CFP.fve_max_members is null or CFP.org_id = 1) )
        then
          return 1;
        else
          return 0;
        end if;
    end$$ language plpgsql;
    
    -- check if a user has a given role, or if such a role is inferrable
    -- returns NULL if OK, error message otherwise
    create or replace function user_role_check_debug(channel_id_in in numeric, 
                                   user_id_in in numeric, 
                                   role_in in varchar)
    returns varchar
    as $$
    declare
        org_id numeric;
    begin
        org_id := rhn_user.get_org_id(user_id_in);

        -- channel might be shared
        if role_in = 'subscribe' and
           rhn_channel.shared_user_role_check(channel_id_in, user_id_in, role_in) = 1 then
            return NULL;
        end if;
        
        if role_in = 'manage' and 
           COALESCE(rhn_channel.get_org_id(channel_id_in), -1) <> org_id then
               return 'channel_not_owned';
        end if;
        
        if role_in = 'subscribe' and 
           rhn_channel.get_org_access(channel_id_in, org_id) = 0 then
                return 'channel_not_available';
        end if;
        
        -- channel admins have all roles
        if rhn_user.check_role_implied(user_id_in, 'channel_admin') = 1 then
            return NULL;
        end if;

        -- the subscribe permission is inferred 
        -- UNLESS the not_globally_subscribable flag is set
        if role_in = 'subscribe'
        then
            if rhn_channel.org_channel_setting(channel_id_in, 
                       org_id,
                       'not_globally_subscribable') = 0 then
                return NULL;
            end if;
        end if;
        
        -- all other roles (manage right now) are explicitly granted    
        if rhn_channel.direct_user_role_check(channel_id_in,
                                              user_id_in, role_in) = 1 then
            return NULL;
        end if;
        return 'direct_permission';
    end$$ language plpgsql;
    
    -- same as above, but with 1/0 output; useful in views, etc
    create or replace function user_role_check(channel_id_in in numeric, user_id_in in numeric, role_in in varchar)
    returns numeric
    as $$
    begin
        if rhn_channel.user_role_check_debug(channel_id_in,
                                             user_id_in, role_in) is NULL then
            return 1;
        else
            return 0;
        end if;
    end$$ language plpgsql;

    --
    -- For multiorg phase II, this function simply checks to see if the user's
    -- has a trust relationship that includes this channel by id.
    --
    create or replace function shared_user_role_check(channel_id in numeric, user_id in numeric, role in varchar)
    returns numeric
    as $$
    declare
      n numeric;
      oid numeric;
    begin
      oid := rhn_user.get_org_id(user_id);
      select 1 into n
      from rhnSharedChannelView s
      where s.id = channel_id and s.org_trust_id = oid;

      if not found then
        return 0;
      end if;

      return 1;
    end$$ language plpgsql;

    -- same as above, but returns 1 if user_id_in is null
    -- This is useful in queries where user_id is not specified
    create or replace function loose_user_role_check(channel_id_in in numeric, user_id_in in numeric, role_in in varchar)
    returns numeric
    as $$
    begin
        if user_id_in is null then
            return 1;
        end if;
        return rhn_channel.user_role_check(channel_id_in, user_id_in, role_in);
    end$$ language plpgsql;
    
    -- directly checks the table, no inferred permissions
    create or replace function direct_user_role_check(channel_id_in in numeric, user_id_in in numeric, role_in in varchar)
    returns numeric
    as $$
    declare
        throwaway numeric;
    begin
        -- the idea: if we get past this query, the user has the role, else no
        select 1 into throwaway
          from rhnChannelPermissionRole CPR,
               rhnChannelPermission CP
         where CP.user_id = user_id_in
           and CP.channel_id = channel_id_in
           and CPR.label = role_in
           and CP.role_id = CPR.id;

      if not found then
        return 0;
      end if;
           
      return 1;
    end$$ language plpgsql;
    
    -- check if an org has a certain setting
    create or replace function org_channel_setting(channel_id_in in numeric, org_id_in in numeric, setting_in in varchar)
    returns numeric
    as $$
    declare
        throwaway numeric;
    begin
        -- the idea: if we get past this query, the org has the setting
        select 1 into throwaway
          from rhnOrgChannelSettingsType OCST,
               rhnOrgChannelSettings OCS
         where OCS.org_id = org_id_in
           and OCS.channel_id = channel_id_in
           and OCST.label = setting_in
           and OCS.setting_id = OCST.id;

      if not found then
        return 0;
      end if;

      return 1;
    end$$ language plpgsql;
    
    CREATE OR REPLACE FUNCTION channel_priority(channel_id_in IN numeric) 
    RETURNS numeric
    AS $$
    declare
         channel_name varchar(256);
         priority numeric;
         end_of_life_val timestamptz;
         org_id_val numeric;
    BEGIN

        select name, end_of_life, org_id
        into channel_name, end_of_life_val, org_id_val
        from rhnChannel
        where id = channel_id_in;

        if end_of_life_val is not null then
          return -400;
        end if;

        if channel_name like 'Red Hat Enterprise Linux%' or channel_name like 'RHEL%' then
          priority := 1000;
          if channel_name not like '%Beta%' then
            priority := priority + 1000;
          end if;

          priority := priority +
            case
              when channel_name like '%v. 5%' then 600
              when channel_name like '%v. 4%' then 500
              when channel_name like '%v. 3%' then 400
              when channel_name like '%v. 2%' then 300
              when channel_name like '%v. 1%' then 200
              else 0
            end;

          priority := priority +
            case
              when channel_name like 'Red Hat Enterprise Linux (v. 5%' then 60
              when (channel_name like '%AS%' and channel_name not like '%Extras%') then 50
              when (channel_name like '%ES%' and channel_name not like '%Extras%') then 40
              when (channel_name like '%WS%' and channel_name not like '%Extras%') then 30
              when (channel_name like '%Desktop%' and channel_name not like '%Extras%') then 20
              when channel_name like '%Extras%' then 10
              else 0
            end; 

          priority := priority +
            case
              when channel_name like '%)' then 5
              else 0
            end;

          priority := priority +
            case
              when channel_name like '%32-bit x86%' then 4
              when channel_name like '%64-bit Intel Itanium%' then 3
              when channel_name like '%64-bit AMD64/Intel EM64T%' then 2
              else 0
            end;
        elsif channel_name like 'Red Hat Desktop%' then
            priority := 900;

            if channel_name not like '%Beta%' then
               priority := priority + 50;
            end if;

          priority := priority +
            case
              when channel_name like '%v. 4%' then 40
              when channel_name like '%v. 3%' then 30
              when channel_name like '%v. 2%' then 20
              when channel_name like '%v. 1%' then 10
              else 0
            end;
            
          priority := priority +
            case
              when channel_name like '%32-bit x86%' then 4
              when channel_name like '%64-bit Intel Itanium%' then 3
              when channel_name like '%64-bit AMD64/Intel EM64T%' then 2
              else 0
            end;
         
        elsif org_id_val is not null then
          priority := 600;
        else
          priority := 500;
        end if;
      
      return -priority;

    end$$ language plpgsql;

    -- right now this only does the accounting changes; the cascade
    -- actually does the rhnServerChannel delete.
    create or replace function delete_server_channels(server_id_in in numeric) returns void
    as $$
    begin
        update  rhnPrivateChannelFamily
        set     current_members = current_members -1
        where   org_id in (
                        select  org_id
                        from    rhnServer
                        where   id = server_id_in
                )
                and channel_family_id in (
                        select  rcfm.channel_family_id
                        from    rhnChannelFamilyMembers rcfm,
                                rhnServerChannel rsc
                        where   rsc.server_id = server_id_in
                                and rsc.channel_id = rcfm.channel_id
                and not exists (
                    select 1
                    from
                        rhnChannelFamilyVirtSubLevel cfvsl,
                        rhnSGTypeVirtSubLevel sgtvsl,
                        rhnServerEntitlementView sev,
                        rhnVirtualInstance vi
                    where
                        -- system is a virtual instance
                        vi.virtual_system_id = server_id_in
                        and vi.host_system_id = sev.server_id
                        -- system's host has a virt ent
                        and sev.label in ('virtualization_host',
                                          'virtualization_host_platform')
                        and sev.server_group_type_id = 
                            sgtvsl.server_group_type_id
                        -- the host's virt ent grants a cf virt sub level
                        and sgtvsl.virt_sub_level_id = cfvsl.virt_sub_level_id
                        -- the cf is in that virt sub level
                        and cfvsl.channel_family_id = rcfm.channel_family_id
                    )
                );
    end$$ language plpgsql;

    -- this could certainly be optimized to do updates if needs be
    create or replace function refresh_newest_package(channel_id_in in numeric,
                                      caller_in in varchar default '(unknown)',
                                      package_name_id_in in numeric default null)
    returns void
    as $$
    -- procedure refreshes rows for name_id = package_name_id_in or
    -- all rows if package_name_id_in is null
    begin
        delete from rhnChannelNewestPackage
              where channel_id = channel_id_in
                and (package_name_id_in is null
                     or name_id = package_name_id_in);
        insert into rhnChannelNewestPackage
                (channel_id, name_id, evr_id, package_id, package_arch_id)
                (select channel_id,
                        name_id, evr_id,
                        package_id, package_arch_id
                   from rhnChannelNewestPackageView
                  where channel_id = channel_id_in
                    and (package_name_id_in is null
                         or name_id = package_name_id_in)
                );
        insert into rhnChannelNewestPackageAudit (channel_id, caller)
             values (channel_id_in, caller_in);
        update rhnChannel
           set last_modified = greatest(current_timestamp,
                                        last_modified + interval '1 second')
         where id = channel_id_in;
    end$$ language plpgsql;

   create or replace function update_channel ( channel_id_in in numeric, invalidate_ss in numeric default 0, 
                              date_to_use in timestamptz default current_timestamp ) returns void
   as $$
   declare
   channel_last_modified timestamptz;
   last_modified_value timestamptz;

   snapshots cursor for
   select  snapshot_id id
   from    rhnSnapshotChannel
   where   channel_id = channel_id_in;

   begin

      select last_modified
      into channel_last_modified
      from rhnChannel
      where id = channel_id_in;
  
      last_modified_value := date_to_use;

      if last_modified_value <= channel_last_modified then
          last_modified_value := last_modified_value + interval '1 second';
      end if;

      update rhnChannel set last_modified = last_modified_value
      where id = channel_id_in;

      if invalidate_ss = 1 then 
        for snapshot in snapshots loop
            update rhnSnapshot
            set invalid = lookup_snapshot_invalid_reason('channel_modified')
            where id = snapshot.id;
        end loop;
      end if;

   end$$ language plpgsql;

   create or replace function update_channels_by_package ( package_id_in in numeric, date_to_use in timestamptz default current_timestamp ) returns void
   as $$
   declare
   channels cursor for
   select channel_id
   from rhnChannelPackage
   where package_id = package_id_in
   order by channel_id;

   begin
      for channel in channels loop
         -- we want to invalidate the snapshot assocated with the channel when we
         -- do this b/c we know we've added or removed or packages
         perform rhn_channel.update_channel ( channel.channel_id, 1, date_to_use );
      end loop;
   end$$ language plpgsql;

   
   create or replace function update_channels_by_errata ( errata_id_in numeric, date_to_use in timestamptz default current_timestamp ) returns void
   as $$
   declare
   channels cursor for
   select channel_id
   from rhnChannelErrata
   where errata_id = errata_id_in
   order by channel_id;

   begin
      for channel in channels loop
         -- we won't invalidate snapshots, b/c just changing the errata associated with
         -- a channel shouldn't invalidate snapshots
         perform rhn_channel.update_channel ( channel.channel_id, 0, date_to_use );
      end loop;
   end$$ language plpgsql;

   create or replace function update_needed_cache(channel_id_in in numeric) returns void
   as $$
   declare
   server record;
   begin
      -- we intentionaly do a loop here instead of one huge select
      -- b/c we want to break update into smaller transaction to unblock other sessions
      -- querying rhnServerNeededCache
      for server in (
                select sc.server_id as id
                  from rhnServerChannel sc
                 where sc.channel_id = channel_id_in
                 order by id asc
      ) loop
         perform rhn_server.update_needed_cache(server.id);
      end loop;
   end$$ language plpgsql;

    create or replace function set_comps(channel_id_in in numeric, path_in in varchar, timestamp_in in varchar) returns void
    as $$
    declare
    row record;
    begin
        for row in (
            select relative_filename, last_modified
            from rhnChannelComps
            where channel_id = channel_id_in
            ) loop
            if row.relative_filename = path_in
                and row.last_modified = to_timestamp(timestamp_in, 'YYYYMMDDHH24MISS') then
                return;
            end if;
        end loop;
        delete from rhnChannelComps
        where channel_id = channel_id_in;
        insert into rhnChannelComps (id, channel_id, relative_filename, last_modified, created, modified)
        values (sequence_nextval('rhn_channelcomps_id_seq'), channel_id_in, path_in, to_timestamp(timestamp_in, 'YYYYMMDDHH24MISS'), current_timestamp, current_timestamp);
    end$$ language plpgsql;

CREATE OR REPLACE FUNCTION server_has_family_subscription(server_id_in DECIMAL, 
                                                          channel_family_id_in DECIMAL) 
          RETURNS INTEGER AS $$
  DECLARE
    fam_entry RECORD;

  BEGIN
    FOR fam_entry IN SELECT DISTINCT cfm.channel_family_id
                       FROM rhnchannelfamilymembers AS cfm
                       JOIN rhnserverchannel AS sc ON sc.channel_id = cfm.channel_id
                      WHERE sc.server_id = server_id_in
                        AND cfm.channel_family_id = channel_family_id_in
    LOOP
      return 1;
    END LOOP;
    RETURN 0;
  END;
$$ LANGUAGE plpgsql;

-- restore the original setting
update pg_settings set setting = overlay( setting placing '' from 1 for (length('rhn_channel')+1) ) where name = 'search_path';
   07070100000ADE000081B400000000000000000000000167AE11140000007A000000000000000000000000000000000000006A00000000susemanager-schema/upgrade/susemanager-schema-2.1.51-to-susemanager-schema-3.0/1008-update_fve_counts.sql update rhnPrivateChannelFamily
   set fve_current_members = rhn_channel.cfam_curr_fve_members(channel_family_id,org_id);

  07070100000ADF000081B400000000000000000000000167AE111400001C48000000000000000000000000000000000000007200000000susemanager-schema/upgrade/susemanager-schema-2.1.51-to-susemanager-schema-3.0/1009-rhnChildChannelArchCompat.sql --
-- Copyright (c) 2014 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--

CREATE TABLE rhnChildChannelArchCompat
(
    parent_arch_id  NUMERIC NOT NULL
                         CONSTRAINT rhn_ccac_paid_fk
                             REFERENCES rhnChannelArch (id),
    child_arch_id  NUMERIC NOT NULL
                         CONSTRAINT rhn_ccac_caid_fk
                             REFERENCES rhnChannelArch (id),
    created          TIMESTAMPTZ
                         DEFAULT (current_timestamp) NOT NULL,
    modified         TIMESTAMPTZ
                         DEFAULT (current_timestamp) NOT NULL
)

;

CREATE INDEX rhn_ccac_paid_caid
    ON rhnChildChannelArchCompat (parent_arch_id, child_arch_id)
    ;

ALTER TABLE rhnChildChannelArchCompat
    ADD CONSTRAINT rhn_ccac_paid_caid_uq UNIQUE (parent_arch_id, child_arch_id);


insert into rhnChildChannelArchCompat (parent_arch_id, child_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-ia32'), LOOKUP_CHANNEL_ARCH('channel-ia32'));

insert into rhnChildChannelArchCompat (parent_arch_id, child_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-ia64'), LOOKUP_CHANNEL_ARCH('channel-ia32'));

insert into rhnChildChannelArchCompat (parent_arch_id, child_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-ia64'), LOOKUP_CHANNEL_ARCH('channel-ia64'));

insert into rhnChildChannelArchCompat (parent_arch_id, child_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-ia32-deb'), LOOKUP_CHANNEL_ARCH('channel-ia32-deb'));

insert into rhnChildChannelArchCompat (parent_arch_id, child_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-ia64-deb'), LOOKUP_CHANNEL_ARCH('channel-ia32-deb'));

insert into rhnChildChannelArchCompat (parent_arch_id, child_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-ia64-deb'), LOOKUP_CHANNEL_ARCH('channel-ia64-deb'));

insert into rhnChildChannelArchCompat (parent_arch_id, child_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-sparc'), LOOKUP_CHANNEL_ARCH('channel-sparc'));

insert into rhnChildChannelArchCompat (parent_arch_id, child_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-sparc'), LOOKUP_CHANNEL_ARCH('channel-sparc-sun-solaris'));

insert into rhnChildChannelArchCompat (parent_arch_id, child_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-sparc'), LOOKUP_CHANNEL_ARCH('channel-i386-sun-solaris'));

insert into rhnChildChannelArchCompat (parent_arch_id, child_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-sparc-deb'), LOOKUP_CHANNEL_ARCH('channel-sparc-deb'));

insert into rhnChildChannelArchCompat (parent_arch_id, child_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-alpha'), LOOKUP_CHANNEL_ARCH('channel-alpha'));

insert into rhnChildChannelArchCompat (parent_arch_id, child_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-alpha-deb'), LOOKUP_CHANNEL_ARCH('channel-alpha-deb'));

insert into rhnChildChannelArchCompat (parent_arch_id, child_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-s390'), LOOKUP_CHANNEL_ARCH('channel-s390'));

insert into rhnChildChannelArchCompat (parent_arch_id, child_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-s390-deb'), LOOKUP_CHANNEL_ARCH('channel-s390-deb'));

insert into rhnChildChannelArchCompat (parent_arch_id, child_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-s390x'), LOOKUP_CHANNEL_ARCH('channel-s390'));

insert into rhnChildChannelArchCompat (parent_arch_id, child_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-s390x'), LOOKUP_CHANNEL_ARCH('channel-s390x'));

insert into rhnChildChannelArchCompat (parent_arch_id, child_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-iSeries'), LOOKUP_CHANNEL_ARCH('channel-iSeries'));

insert into rhnChildChannelArchCompat (parent_arch_id, child_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-pSeries'), LOOKUP_CHANNEL_ARCH('channel-pSeries'));

insert into rhnChildChannelArchCompat (parent_arch_id, child_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-x86_64'), LOOKUP_CHANNEL_ARCH('channel-ia32'));

insert into rhnChildChannelArchCompat (parent_arch_id, child_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-x86_64'), LOOKUP_CHANNEL_ARCH('channel-x86_64'));

insert into rhnChildChannelArchCompat (parent_arch_id, child_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-amd64-deb'), LOOKUP_CHANNEL_ARCH('channel-ia32-deb'));

insert into rhnChildChannelArchCompat (parent_arch_id, child_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-amd64-deb'), LOOKUP_CHANNEL_ARCH('channel-amd64-deb'));

insert into rhnChildChannelArchCompat (parent_arch_id, child_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-ppc'), LOOKUP_CHANNEL_ARCH('channel-ppc'));

insert into rhnChildChannelArchCompat (parent_arch_id, child_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-powerpc-deb'), LOOKUP_CHANNEL_ARCH('channel-powerpc-deb'));

insert into rhnChildChannelArchCompat (parent_arch_id, child_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-arm'), LOOKUP_CHANNEL_ARCH('channel-arm'));

insert into rhnChildChannelArchCompat (parent_arch_id, child_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-armhfp'), LOOKUP_CHANNEL_ARCH('channel-armhfp'));

insert into rhnChildChannelArchCompat (parent_arch_id, child_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-arm-deb'), LOOKUP_CHANNEL_ARCH('channel-arm-deb'));

insert into rhnChildChannelArchCompat (parent_arch_id, child_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-mips-deb'), LOOKUP_CHANNEL_ARCH('channel-mips-deb'));

insert into rhnChildChannelArchCompat (parent_arch_id, child_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-sparc-sun-solaris'), LOOKUP_CHANNEL_ARCH('channel-sparc'));

insert into rhnChildChannelArchCompat (parent_arch_id, child_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-sparc-sun-solaris'), LOOKUP_CHANNEL_ARCH('channel-sparc-sun-solaris'));

insert into rhnChildChannelArchCompat (parent_arch_id, child_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-sparc-sun-solaris'), LOOKUP_CHANNEL_ARCH('channel-i386-sun-solaris'));

insert into rhnChildChannelArchCompat (parent_arch_id, child_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-i386-sun-solaris'), LOOKUP_CHANNEL_ARCH('channel-sparc'));

insert into rhnChildChannelArchCompat (parent_arch_id, child_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-i386-sun-solaris'), LOOKUP_CHANNEL_ARCH('channel-sparc-sun-solaris'));

insert into rhnChildChannelArchCompat (parent_arch_id, child_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-i386-sun-solaris'), LOOKUP_CHANNEL_ARCH('channel-i386-sun-solaris'));

insert into rhnChildChannelArchCompat (parent_arch_id, child_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-aarch64'), LOOKUP_CHANNEL_ARCH('channel-aarch64'));

insert into rhnChildChannelArchCompat (parent_arch_id, child_arch_id)
values (LOOKUP_CHANNEL_ARCH('channel-ppc64le'), LOOKUP_CHANNEL_ARCH('channel-ppc64le'));

commit;

07070100000AE0000081B400000000000000000000000167AE1114000003CE000000000000000000000000000000000000006D00000000susemanager-schema/upgrade/susemanager-schema-2.1.51-to-susemanager-schema-3.0/1011-rhnWebContactEnabled.sql  --
-- Copyright (c) 2008--2014 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

create or replace view
rhnWebContactEnabled
as
select
   wcon.id,
   wcon.org_id,
   wcon.login,
   wcon.login_uc,
   wcon.password,
   wcon.oracle_contact_id,
   wcon.created,
   wcon.modified,
   wcon.ignore_flag,
   wcon.read_only
from
   web_contact wcon left join rhnWebContactDisabled wcond on wcond.id = wcon.id
   where wcond.id is null;
  07070100000AE1000081B400000000000000000000000167AE111400000047000000000000000000000000000000000000006E00000000susemanager-schema/upgrade/susemanager-schema-2.1.51-to-susemanager-schema-3.0/1013-rhnKSInstallType-data.sql UPDATE rhnKSInstallType SET label = 'fedora18' WHERE label = 'fedora';
 07070100000AE2000081B400000000000000000000000167AE11140000004E000000000000000000000000000000000000007F00000000susemanager-schema/upgrade/susemanager-schema-2.1.51-to-susemanager-schema-3.0/1014-inc-length-rhnContentSource-source_url.sql    
ALTER TABLE rhnContentSource
    ALTER COLUMN source_url TYPE varchar(2048);
  07070100000AE3000081B400000000000000000000000167AE11140000030C000000000000000000000000000000000000009600000000susemanager-schema/upgrade/susemanager-schema-2.1.51-to-susemanager-schema-3.0/1015-rhnServerServerGroupArchCompat-missing-virt-platform-mappings.sql insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type) select
LOOKUP_SERVER_ARCH('aarch64-redhat-linux'), LOOKUP_SG_TYPE('virtualization_host_platform') from dual
where not exists (select 1 from rhnServerServerGroupArchCompat where server_arch_id = LOOKUP_SERVER_ARCH('aarch64-redhat-linux') and server_group_type = LOOKUP_SG_TYPE('virtualization_host_platform'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type) select
LOOKUP_SERVER_ARCH('ppc64le-redhat-linux'), LOOKUP_SG_TYPE('virtualization_host_platform') from dual
where not exists (select 1 from rhnServerServerGroupArchCompat where server_arch_id = LOOKUP_SERVER_ARCH('ppc64le-redhat-linux') and server_group_type = LOOKUP_SG_TYPE('virtualization_host_platform'));

07070100000AE4000081B400000000000000000000000167AE1114000028FE000000000000000000000000000000000000006600000000susemanager-schema/upgrade/susemanager-schema-2.1.51-to-susemanager-schema-3.0/1016-delete_server.sql --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
-- This deletes a server.  All codepaths which delete servers should hit this
-- or delete_server_bulk()

create or replace
function delete_server (
        server_id_in in numeric
) returns void 
as
$$
declare
         servergroups cursor for
                select  server_id, server_group_id
                from    rhnServerGroupMembers sgm
                where   sgm.server_id = server_id_in;

         configchannels cursor for
                select  cc.id
                from    rhnConfigChannel cc,
                        rhnConfigChannelType cct,
                        rhnServerConfigChannel scc
                where   1=1
                        and scc.server_id = server_id_in
                        and scc.config_channel_id = cc.id
                        -- these config channel types are reserved
                        -- for use by a single server, so we don't
                        -- need to check for other servers subscribed
                        and cct.label in
                                ('local_override','server_import')
                        and cct.id = cc.confchan_type_id;

    is_virt boolean;
begin
        perform rhn_channel.delete_server_channels(server_id_in);
        -- rhn_channel.clear_subscriptions(server_id_in);

        -- filelists
        delete from rhnFileList where id in (
	select	spfl.file_list_id
	  from	rhnServerPreserveFileList spfl
	 where	spfl.server_id = server_id_in
			and not exists (
				select	1
				from	rhnServerPreserveFileList
				where	file_list_id = spfl.file_list_id
					and server_id != server_id_in
				union all
				select	1
				from	rhnKickstartPreserveFileList
				where	file_list_id = spfl.file_list_id
			)
        );

	for configchannel in configchannels loop
		perform rhn_config.delete_channel(configchannel.id);
	end loop;

      is_virt := exists (
       select 1
        from rhnServerEntitlementView
       where server_id = server_id_in
         and label in ('virtualization_host', 'virtualization_host_platform')
      );

	for sgm in servergroups loop
		perform rhn_server.delete_from_servergroup(
			sgm.server_id, sgm.server_group_id);
	end loop;

    if is_virt then
        perform rhn_entitlements.repoll_virt_guest_entitlements(server_id_in);
    end if;

        -- we're handling this instead of letting an "on delete
        -- set null" do it so that we don't run the risk
        -- of setting off the triggers and killing us with a
        -- mutating table

        -- this is merge of two single updates:
        --  update ... set old_server_id = null where old_server_id = server_id_in;
        --  update ... set new_server_id = null where new_server_id = server_id_in;
        -- so we scan rhnKickstartSession table only once
        update rhnKickstartSession
                set old_server_id = case when old_server_id = server_id_in then null else old_server_id end,
                    new_server_id = case when new_server_id = server_id_in then null else new_server_id end
                where old_server_id = server_id_in
                   or new_server_id = server_id_in;

        perform rhn_channel.clear_subscriptions(server_id_in, 1, 1);

        -- A little complicated here, but the goal is to
        -- delete records from rhnVirtualInstace only if we don't
        -- care about them anymore.  We don't care about records
        -- in rhnVirtualInstance if we are deleting the host
        -- system and the virtual system is already null, or
        -- vice-versa.  We *do* care about them if either the
        -- host or virtual system is still registered because we
        -- still want them to show up in the UI.
    -- If there's a newer row in rhnVirtualInstance with the same
    -- uuid, this guest must have been re-registered, so we can clean
    -- this data up.

        delete from rhnVirtualInstance vi
              where (host_system_id = server_id_in and virtual_system_id is null)
                 or (virtual_system_id = server_id_in and host_system_id is null)
                 or (vi.virtual_system_id = server_id_in and vi.modified < (select max(vi2.modified)
                    from rhnVirtualInstance vi2 where vi2.uuid = vi.uuid));

        -- this is merge of two single updates:
        --  update ... set host_system_id = null where host_system_id = server_id_in;
        --  update ... set virtual_system_id = null where virtual_system_id = server_id_in;
        -- so we scan rhnVirtualInstance table only once
        update rhnVirtualInstance
           set host_system_id = case when host_system_id = server_id_in then null else host_system_id end,
               virtual_system_id = case when virtual_system_id = server_id_in then null else virtual_system_id end
         where host_system_id = server_id_in
            or virtual_system_id = server_id_in;

        -- this is merge of two single updates:
        --  update ... set old_host_system_id = null when old_host_system_id = server_id_in;
        --  update ... set new_host_system_id = null when new_host_system_id = server_id_in;
        -- so we scan rhnVirtualInstanceEventLog table only once
        update rhnVirtualInstanceEventLog
           set old_host_system_id = case when old_host_system_id = server_id_in then null else old_host_system_id end,
               new_host_system_id = case when new_host_system_id = server_id_in then null else new_host_system_id end
         where old_host_system_id = server_id_in
            or new_host_system_id = server_id_in;

        -- We're deleting everything with a foreign key to rhnServer
        -- here, now.  I'm hoping this will help aleviate our deadlock
        -- problem.

        delete from rhnActionConfigChannel where server_id = server_id_in;
        delete from rhnActionConfigRevision where server_id = server_id_in;
        delete from rhnActionPackageRemovalFailure where server_id = server_id_in;
        delete from rhnClientCapability where server_id = server_id_in;
        delete from rhnCpu where server_id = server_id_in;
        -- there's still a cascade here, because the constraint keeps the
        -- table locked for too long to rebuild it.  Ugh...
        delete from rhnDevice where server_id = server_id_in;
        delete from rhnProxyInfo where server_id = server_id_in;
        delete from rhnRam where server_id = server_id_in;
        delete from rhnRegToken where server_id = server_id_in;
        delete from rhnSatelliteInfo where server_id = server_id_in;
        -- this cascades to rhnActionConfigChannel and rhnActionConfigFileName
        delete from rhnServerAction where server_id = server_id_in;
        delete from rhnServerActionPackageResult where server_id = server_id_in;
        delete from rhnServerActionScriptResult where server_id = server_id_in;
        delete from rhnServerActionVerifyResult where server_id = server_id_in;
        delete from rhnServerActionVerifyMissing where server_id = server_id_in;
        -- counts are handled above.  this should be a delete_ function.
        delete from rhnServerChannel where server_id = server_id_in;
        delete from rhnServerConfigChannel where server_id = server_id_in;
        delete from rhnServerCustomDataValue where server_id = server_id_in;
        delete from rhnServerDMI where server_id = server_id_in;
        delete from rhnServerEvent where server_id = server_id_in;
        delete from rhnServerHistory where server_id = server_id_in;
        delete from rhnServerInfo where server_id = server_id_in;
        delete from rhnServerInstallInfo where server_id = server_id_in;
        delete from rhnServerLocation where server_id = server_id_in;
        delete from rhnServerLock where server_id = server_id_in;
        delete from rhnServerNeededCache where server_id = server_id_in;
        delete from rhnServerNetwork where server_id = server_id_in;
        delete from rhnServerNotes where server_id = server_id_in;
        -- I'm not removing the foreign key from rhnServerPackage; that'll
        -- take forever.  Do the delete anyway.
        delete from rhnServerPackage where server_id = server_id_in;
        delete from rhnServerTokenRegs where server_id = server_id_in;
        delete from rhnSnapshotTag where server_id = server_id_in;
        -- this cascades to:
        --   rhnSnapshotChannel, rhnSnapshotConfigChannel, rhnSnapshotPackage,
        --   rhnSnapshotConfigRevision, rhnSnapshotServerGroup,
        --   rhnSnapshotTag.
        -- We may want to consider delete_snapshot() at some point, but
        --   I don't think we need to yet.
        delete from rhnSnapshot where server_id = server_id_in;
        delete from rhnUserServerPrefs where server_id = server_id_in;
        -- hrm, this one's interesting... we _probably_ should delete
        -- everything for the parent server_id when we delete the proxy,
        -- but we don't currently.
        delete from rhnServerPath where server_id_in in (server_id, proxy_server_id);
        delete from rhnUserServerPerms where server_id = server_id_in;

        delete from rhnServerNetInterface where server_id = server_id_in;

        delete from rhnServerUuid where server_id = server_id_in;

        delete from rhnPushClient where server_id = server_id_in;

        -- now get rhnServer itself.
        delete
        from    rhnServer
                where id = server_id_in;

        delete
        from    rhnSet
        where   1=1
                and user_id in (
                        select  wc.id
                        from    rhnServer rs,
                                web_contact wc
                        where   rs.id = server_id_in
                                and rs.org_id = wc.org_id
                )
                and label = 'system_list'
                and element = server_id_in;
end;
$$
language plpgsql;

  07070100000AE5000081B400000000000000000000000167AE111400000053000000000000000000000000000000000000006400000000susemanager-schema/upgrade/susemanager-schema-2.1.51-to-susemanager-schema-3.0/1016-rhnFeatures.sql   delete from rhnFeature where label = 'ftr_schedule_probe' or label = 'ftr_probes';
 07070100000AE6000081B400000000000000000000000167AE111400010795000000000000000000000000000000000000006D00000000susemanager-schema/upgrade/susemanager-schema-2.1.51-to-susemanager-schema-3.0/1016-rhn_entitlements.pkb.sql  --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--

-- create schema rhn_entitlements;

-- setup search_path so that these functions are created in appropriate schema.
update pg_settings set setting = 'rhn_entitlements,' || setting where name = 'search_path';

   create or replace function find_compatible_sg (
      server_id_in in numeric,
      type_label_in in varchar
   )
   returns numeric
as $$
    declare
      servergroups cursor for
         select sg.id
           from rhnServerGroupType             sgt,
                rhnServerGroup                 sg,
                rhnServer                     s,
                rhnServerServerGroupArchCompat ssgac
          where s.id = server_id_in
            and s.org_id = sg.org_id
            and sgt.label = type_label_in
            and sg.group_type = sgt.id
            and ssgac.server_group_type = sgt.id
            and ssgac.server_arch_id = s.server_arch_id
            and not exists ( 
                     select 1
                      from rhnServerGroupMembers sgm
                     where sgm.server_group_id = sg.id 
                       and sgm.server_id = s.id);

         
   begin
      for servergroup in servergroups loop
         return servergroup.id;
      end loop;

      --no servergroup found
      return NULL;
   end$$
language plpgsql;

    -- *******************************************************************
    -- PROCEDURE: remove_org_entitlements
    --
    -- Removes both system entitlements and channel subscriptions
    -- that are currently assigned to an org and re-assigns to the
    -- master org (org_id = 1).
    --
    -- When we call this we expect everything to already be unentitled
    -- which shoul be handled by delete_org.
    --
    -- Called by: delete_org
    -- *******************************************************************
    create or replace function remove_org_entitlements (
        org_id_in numeric
    ) returns void
as $$
    declare
        system_ents cursor for
        select sg.id, sg.max_members, sg.group_type
        from rhnServerGroup sg
        where group_type is not null
          and org_id = org_id_in;

        channel_subs cursor for
        select pcf.channel_family_id, pcf.max_members
        from rhnChannelFamily cf,
             rhnPrivateChannelFamily pcf
        where pcf.org_id = org_id_in
          and pcf.channel_family_id = cf.id
          and cf.org_id is null;

    begin

        for system_ent in system_ents loop
            update rhnServerGroup
            set max_members = max_members + system_ent.max_members
            where org_id = 1
              and group_type = system_ent.group_type;
        end loop;

        update rhnServerGroup
        set max_members = 0
        where org_id = org_id_in;

        for channel_sub in channel_subs loop
            update rhnPrivateChannelFamily
            set max_members = max_members + channel_sub.max_members
            where org_id = 1
              and channel_family_id = channel_sub.channel_family_id;
        end loop;
        
        update rhnPrivateChannelFamily
        set max_members = 0
        where org_id = org_id_in;

    end$$
language plpgsql;

    create or replace function entitlement_grants_service (
        entitlement_in in varchar,
        service_level_in in varchar
    ) returns numeric
as $$
    begin
        if service_level_in = 'provisioning' then
            if entitlement_in = 'provisioning_entitled' then
                return 1;
            else
                return 0;
            end if;
        elsif service_level_in = 'management' then
            if entitlement_in = 'enterprise_entitled' then
                return 1;
            else
                return 0;
            end if;
        elsif service_level_in = 'monitoring' then
            if entitlement_in = 'monitoring_entitled' then
                return 1;
            end if;
        elsif service_level_in = 'updates' then
            return 1;           
        else
            return 0;
        end if;
    end$$
language plpgsql;

    create or replace function lookup_entitlement_group (
        org_id_in in numeric,
        type_label_in in varchar default 'sw_mgr_entitled'
    ) returns numeric
as $$
    declare
        server_groups cursor for
            select  sg.id               server_group_id
            from    rhnServerGroup      sg,
                    rhnServerGroupType  sgt
            where   sgt.label = type_label_in
                and sgt.id = sg.group_type
                and sg.org_id = org_id_in;
    begin
        for sg in server_groups loop
            return sg.server_group_id;
        end loop;
        return rhn_entitlements.create_entitlement_group(
                org_id_in, 
                type_label_in
            );
    end$$
language plpgsql;

    create or replace function create_entitlement_group (
        org_id_in in numeric,
        type_label_in in varchar default 'sw_mgr_entitled'
    ) returns numeric
as $$
    declare
        sg_id_val numeric;
    begin
        select  nextval('rhn_server_group_id_seq')
        into    sg_id_val;

        insert into rhnServerGroup (
                id, name, description, max_members, current_members,
                group_type, org_id
            ) (
                select  sg_id_val, sgt.label, sgt.label,
                        0, 0, sgt.id, org_id_in
                from    rhnServerGroupType sgt
                where   sgt.label = type_label_in
            );

        return sg_id_val;
    end$$
language plpgsql;

   create or replace function can_entitle_server ( 
      server_id_in   in numeric, 
      type_label_in  in varchar
   )
   returns numeric
as $$
    declare
      addon_servergroups cursor (base_label_in varchar, 
                                 addon_label_in varchar) for
         select
            addon_id
         from
            rhnSGTypeBaseAddonCompat
         where base_id = lookup_sg_type (base_label_in)
           and addon_id = lookup_sg_type (addon_label_in);

      previous_ent        varchar[];
      is_base_in          char   := 'N';
      is_base_current     char   := 'N';
      i                   numeric := 0;
      sgid                numeric := 0;

   begin

      previous_ent := rhn_entitlements.get_server_entitlement(server_id_in);

      select distinct is_base
      into is_base_in
      from rhnServerGroupType
      where label = type_label_in;

      if array_upper(previous_ent, 1) is null or array_upper(previous_ent, 1) = 0 then
         if is_base_in = 'Y' then
            sgid := rhn_entitlements.find_compatible_sg (server_id_in, type_label_in);
            if sgid is not null then
              -- rhn_server.insert_into_servergroup (server_id_in, sgid);
              return 1;
            else
              -- rhn_exception.raise_exception ('invalid_base_entitlement');
              return 0;
            end if;
         else
            -- rhn_exception.raise_exception ('invalid_base_entitlement');
            return 0;
         end if;

      -- there are previous ents, first make sure we're not trying to entitle a base ent
      elsif is_base_in = 'Y' then
         -- rhn_exception.raise_exception ('invalid_addon_entitlement');
         return 0;

      -- it must be an addon, so proceed with the entitlement
      else

         -- find the servers base ent
         is_base_current := 'N';
         i := 0;
         while is_base_current = 'N' and i < array_upper(previous_ent, 1)
         loop
            i := i + 1;
            select is_base
            into is_base_current
            from rhnServerGroupType
            where label = previous_ent[i];
         end loop;

         -- never found a base ent, that would be strange
         if is_base_current  = 'N' then
            -- rhn_exception.raise_exception ('invalid_base_entitlement');
            return 0;
         end if;

         -- this for loop verifies the validity of the addon path
         for addon_servergroup in addon_servergroups  (previous_ent[i], type_label_in) loop
            -- find an appropriate sgid for the addon and entitle the server
            sgid := rhn_entitlements.find_compatible_sg (server_id_in, type_label_in);
            if sgid is not null then
               -- rhn_server.insert_into_servergroup (server_id_in, sgid);
               return 1;
            else
               -- rhn_exception.raise_exception ('invalid_addon_entitlement');
               return 0;
            end if;
         end loop;

      end if;

      return 0;

   end$$
language plpgsql;

   create or replace function can_switch_base ( 
      server_id_in   in    integer, 
      type_label_in  in    varchar
   )
   returns numeric
as $$
   declare
      type_label_in_is_base   char(1);
      sgid                    numeric;

   begin

       select is_base into type_label_in_is_base
       from rhnServerGroupType
       where label = type_label_in;

       if not found then
          perform rhn_exception.raise_exception ( 'invalid_entitlement' );
       end if;

      if type_label_in_is_base = 'N' then
         perform rhn_exception.raise_exception ( 'invalid_entitlement' );
      else
         sgid := rhn_entitlements.find_compatible_sg ( server_id_in,
                                                       type_label_in );
         if sgid is not null then
           return 1;
         else
           return 0;
         end if;
      end if;

   end$$
language plpgsql;

    create or replace function entitle_server (
        server_id_in in numeric,
        type_label_in in varchar default 'sw_mgr_entitled'
    ) returns void
as $$
    declare
      sgid  numeric := 0;
      is_virt numeric := 0;

    begin

      select 1 into is_virt
        from rhnServerEntitlementView
        where server_id = server_id_in
          and label in ('virtualization_host', 'virtualization_host_platform');

      if not found then
          is_virt := 0;
      end if;
      
      if is_virt = 0 and (type_label_in = 'virtualization_host' or
                          type_label_in = 'virtualization_host_platform') then

        is_virt := 1;
      end if;

      if rhn_entitlements.can_entitle_server(server_id_in, 
                                             type_label_in) = 1 then
         sgid := rhn_entitlements.find_compatible_sg (server_id_in,
                                                      type_label_in);
         if sgid is not null then
            insert into rhnServerHistory ( id, server_id, summary, details )
            values ( nextval('rhn_event_id_seq'), server_id_in,
                     'added system entitlement ',
                      case type_label_in
                       when 'enterprise_entitled' then 'Management'
                       when 'bootstrap_entitled' then 'Bootstrap'
                       when 'sw_mgr_entitled' then 'Update'
                       when 'provisioning_entitled' then 'Provisioning'
                       when 'monitoring_entitled' then 'Monitoring'  
                       when 'virtualization_host' then 'Virtualization'
                       when 'virtualization_host_platform' then 
                            'Virtualization Platform' end  );

            perform rhn_server.insert_into_servergroup (server_id_in, sgid);

            if is_virt = 1 then
              perform rhn_entitlements.repoll_virt_guest_entitlements(server_id_in);
            end if;

         else
            perform rhn_exception.raise_exception ('no_available_server_group');
         end if;
      else
         perform rhn_exception.raise_exception ('invalid_entitlement');
      end if;
   end$$
language plpgsql;

    create or replace function remove_server_entitlement (
        server_id_in in numeric,
        type_label_in in varchar default 'sw_mgr_entitled',
        repoll_virt_guests in numeric default 1
    ) returns void
as $$
    declare
      group_id numeric;
      type_is_base char;
      is_virt numeric := 0;
    begin
      -- would be nice if there were a virt attribute of entitlement types, not have to specify 2 different ones...
        select 1 into is_virt
          from rhnServerEntitlementView
          where server_id = server_id_in
            and label in ('virtualization_host', 'virtualization_host_platform');
        if not found then
            is_virt := 0;
        end if;

        select  sg.id, sgt.is_base
        into group_id, type_is_base
        from    rhnServerGroupType sgt,
            rhnServerGroup sg,
                rhnServerGroupMembers sgm,
                rhnServer s
        where   s.id = server_id_in
            and s.id = sgm.server_id
            and sgm.server_group_id = sg.id
            and sg.org_id = s.org_id
            and sgt.label = type_label_in
            and sgt.id = sg.group_type;

        if not found then
          perform rhn_exception.raise_exception('invalid_server_group_member');
        end if;

      if ( type_is_base = 'Y' ) then
         -- unentitle_server should handle everything, don't really need to do anything else special here
         perform rhn_entitlements.unentitle_server ( server_id_in );
      else

         insert into rhnServerHistory ( id, server_id, summary, details )
         values ( nextval('rhn_event_id_seq'), server_id_in,
                  'removed system entitlement ',
                   case type_label_in
                    when 'enterprise_entitled' then 'Management'
                    when 'bootstrap_entitled' then 'Bootstrap'
                    when 'sw_mgr_entitled' then 'Update'
                    when 'provisioning_entitled' then 'Provisioning'
                    when 'monitoring_entitled' then 'Monitoring'
                    when 'virtualization_host' then 'Virtualization'
                    when 'virtualization_host_platform' then 
                         'Virtualization Platforrm' end  );

         perform rhn_server.delete_from_servergroup(server_id_in, group_id);

         if is_virt = 1 and repoll_virt_guests = 1 then
           perform rhn_entitlements.repoll_virt_guest_entitlements(server_id_in);
         end if;
      end if;

    end$$
language plpgsql;

    create or replace function unentitle_server (
        server_id_in in numeric
    ) returns void
as $$
    declare
      servergroups cursor for
         select distinct sgt.label, sg.id server_group_id
         from  rhnServerGroupType sgt,
               rhnServerGroup sg,
               rhnServer s,
               rhnServerGroupMembers sgm
         where s.id = server_id_in
            and s.org_id = sg.org_id
            and sg.group_type = sgt.id
            and sgm.server_group_id = sg.id
            and sgm.server_id = s.id;
            
     is_virt numeric := 0;

   begin

      select 1 into is_virt
        from rhnServerEntitlementView
        where server_id = server_id_in
         and label in ('virtualization_host', 'virtualization_host_platform');

      if not found then
          is_virt := 0;
      end if;

      for servergroup in servergroups loop

         insert into rhnServerHistory ( id, server_id, summary, details )
         values ( nextval('rhn_event_id_seq'), server_id_in,
                  'removed system entitlement ',
                   case servergroup.label
                    when 'enterprise_entitled' then 'Management'
                    when 'bootstrap_entitled' then 'Bootstrap'
                    when 'sw_mgr_entitled' then 'Update'
                    when 'provisioning_entitled' then 'Provisioning'
                    when 'monitoring_entitled' then 'Monitoring'
                    when 'virtualization_host' then 'Virtualization'
                    when 'virtualization_host_platform' then 
                         'Virtualization Platform' end  );
  
         perform rhn_server.delete_from_servergroup(server_id_in, 
                                            servergroup.server_group_id );
      end loop;

      if is_virt = 1 then
        perform rhn_entitlements.repoll_virt_guest_entitlements(server_id_in);
      end if;

   end$$
language plpgsql;


    -- *******************************************************************
    -- PROCEDURE: repoll_virt_guest_entitlements
    --
    --   Whenever we add/remove a virtualization_host* entitlement from 
    --   a host, we can call this procedure to update what type of slots
    --   the guests are consuming.  
    -- 
    --   If you're removing the entitlement, it's 
    --   possible the guests will become unentitled if you don't have enough
    --   physical slots to cover them.
    --
    --   If you're adding the entitlement, you end up freeing up physical
    --   slots for other systems.
    --
    -- *******************************************************************
    create or replace function repoll_virt_guest_entitlements(
        server_id_in in numeric
    ) returns void
as $$
    declare
        -- All channel families associated with the guests of server_id_in
        families cursor for 
            select distinct cfs.channel_family_id
            from
                rhnChannelFamilyServers cfs,
                rhnVirtualInstance vi
            where
                vi.host_system_id = server_id_in
                and vi.virtual_system_id = cfs.server_id;
        
        -- All of server group types associated with the guests of
        -- server_id_in
        group_types cursor for
            select distinct sg.group_type, sgt.label, sg.org_id
            from
                rhnServerGroupType sgt,
                rhnServerGroup sg,
                rhnServerGroupMembers sgm,
                rhnVirtualInstance vi
            where
                vi.host_system_id = server_id_in
                and vi.virtual_system_id = sgm.server_id
                and sgm.server_group_id = sg.id
                and sg.group_type = sgt.id;

        -- Virtual servers from a certain family belonging to a specific
        -- host that are consuming physical channel slots over the limit.
        virt_servers_cfam cursor(family_id_in numeric, quantity_in numeric) for
                select vi.virtual_system_id
                from
                    rhnChannelFamilyMembers cfm,
                    rhnServerChannel sc,
                    rhnVirtualInstance vi
                where
                    vi.host_system_id = server_id_in
                    and vi.virtual_system_id = sc.server_id
                    and sc.channel_id = cfm.channel_id
                    and cfm.channel_family_id = family_id_in
                order by sc.modified desc
                limit quantity_in;                

        -- Virtual servers from a certain family belonging to a specific
        -- host that are consuming physical system slots over the limit.
        virt_servers_sgt cursor(group_type_in numeric, quantity_in numeric) for
                select vi.virtual_system_id
                from
                    rhnServerGroup sg,
                    rhnServerGroupMembers sgm,
                    rhnVirtualInstance vi
                where
                    vi.host_system_id = server_id_in
                    and vi.virtual_system_id = sgm.server_id
                    and sgm.server_group_id = sg.id
                    and sg.group_type = group_type_in
                order by sgm.modified desc
                limit quantity_in;                
        
        -- Get the orgs of Virtual guests
        -- Since they may belong to different orgs
        virt_guest_orgs cursor for
                select  distinct (s.org_id)
                from rhnServer s
                    inner join  rhnVirtualInstance vi on vi.virtual_system_id = s.id
                where
                    vi.host_system_id = server_id_in
                    and s.org_id <> (select s1.org_id from rhnServer s1 where s1.id = vi.host_system_id) ;

        org_id_val numeric;
        max_members_val numeric;
        max_flex_val numeric;
        current_members_calc numeric;
        sg_id numeric;
        is_virt numeric := 0;
        free_slots numeric := 0;
    begin
          select 1 into is_virt
                from rhnServerEntitlementView
           where server_id = server_id_in
                 and label in ('virtualization_host', 'virtualization_host_platform');

      if not found then
          is_virt := 0;
      end if;

        select org_id
        into org_id_val
        from rhnServer
        where id = server_id_in;

        -- deal w/ channel entitlements first ...
        for family in families loop
            if is_virt = 0 then
            -- if the host_server does not have virt
            --- find all possible flex slots
            -- and set each of the flex eligible guests to Y
                select sfc.max_members - sfc.current_members
                  into free_slots
                  from rhnServerFveCapable sfc
                 where sfc.channel_family_id = family.channel_family_id;
                UPDATE rhnServerChannel sc set is_fve = 'Y'
                where sc.server_id in (
                            select vi.virtual_system_id
                            from rhnServerFveCapable sfc
                                inner join rhnVirtualInstance vi on vi.virtual_system_id = sfc.server_id
                            where vi.host_system_id = server_id_in
                                  and sfc.channel_family_id = family.channel_family_id
                              order by vi.modified desc
                            limit free_slots
                );
            else
            -- if the host_server has virt
            -- set all its flex guests to N
                UPDATE rhnServerChannel sc set is_fve = 'N'
                where
                    sc.channel_id in (select cfm.channel_id from rhnChannelFamilyMembers cfm
                                      where cfm.CHANNEL_FAMILY_ID = family.channel_family_id)
                    and sc.is_fve = 'Y'
                    and sc.server_id in
                            (select vi.virtual_system_id  from rhnVirtualInstance vi
                                    where vi.host_system_id = server_id_in);
            end if;

            -- get the current (physical) members of the family
            current_members_calc := 
                rhn_channel.channel_family_current_members(family.channel_family_id,
                                                           org_id_val); -- fixed transposed args

            -- get the max members of the family
            select max_members
            into max_members_val
            from rhnPrivateChannelFamily
            where channel_family_id = family.channel_family_id
            and org_id = org_id_val;

            select fve_max_members
            into max_flex_val
            from rhnPrivateChannelFamily
            where channel_family_id = family.channel_family_id
            and org_id = org_id_val;

            if current_members_calc > max_members_val then
                -- A virtualization_host* ent must have been removed, so we'll
                -- unsubscribe guests from the host first.

                -- hm, i don't think max_members - current_members_calc yielding a negative number
                -- will work w/ rownum, swaping 'em in the body of this if...
                for virt_server in virt_servers_cfam(family.channel_family_id,
                                current_members_calc - max_members_val) loop 

                    perform rhn_channel.unsubscribe_server_from_family(
                                virt_server.virtual_system_id,
                                family.channel_family_id);
                end loop;                               

                -- if we're still over the limit, which would be odd,
                -- just prune the group to max_members
                --
                -- er... wouldn't we actually have to refresh the values of
                -- current_members_calc and max_members_val to actually ever
                -- *skip this??
                if current_members_calc > max_members_val then
                    -- argh, transposed again?!
                    perform rhn_entitlements.set_family_count(org_id_val,
                                     family.channel_family_id,
                                     max_members_val, max_flex_val);
                    --TODO calculate this correctly
                end if; 

           end if;

            -- update current_members for the family.  This will set the value
            -- to reflect adding/removing the entitlement.
            --
            -- what's the difference of doing this vs the unavoidable set_family_count above?
            perform rhn_channel.update_family_counts(family.channel_family_id,
                                             org_id_val);

            -- It is possible that the guests belong  to a different org than the host
            -- so we are going to update the family counts in the guests orgs also
            for org in virt_guest_orgs loop
                    perform rhn_channel.update_family_counts(family.channel_family_id,
                                             org.org_id);
            end loop;
        end loop;

        for a_group_type in group_types loop
          -- get the current *physical* members of the system entitlement type for the org...
          -- 
          -- unlike channel families, it appears the standard rhnServerGroup.max_members represents
          -- *physical* slots, vs physical+virt ... boy that's confusing...

          select max_members, id
            into max_members_val, sg_id
            from rhnServerGroup
            where group_type = a_group_type.group_type
            and org_id = a_group_type.org_id;


      select count(sep.server_id) into current_members_calc
            from rhnServerEntitlementPhysical sep
           where sep.server_group_id = sg_id
             and sep.server_group_type_id = a_group_type.group_type;
          
          if current_members_calc > max_members_val then
            -- A virtualization_host* ent must have been removed, and we're over the limit, so unsubscribe guests
            for virt_server in virt_servers_sgt(a_group_type.group_type,
                                                current_members_calc - max_members_val) loop
              perform rhn_entitlements.remove_server_entitlement(virt_server.virtual_system_id, a_group_type.label);

              -- decrement current_members_calc, we'll use it to reset current_members for the group at the end...
              current_members_calc := current_members_calc - 1;
            end loop;

          end if;

          update rhnServerGroup set current_members = current_members_calc
           where org_id = a_group_type.org_id
             and group_type = a_group_type.group_type;

          -- I think that's all the house-keeping we have to do...
        end loop;

    end$$
language plpgsql;

    create or replace function get_server_entitlement (
        server_id_in in numeric
    ) returns varchar[]
as $$
    declare
        server_groups cursor for
            select  sgt.label
            from    rhnServerGroupType      sgt,
                    rhnServerGroup          sg,
                    rhnServerGroupMembers   sgm
            where   1=1
                and sgm.server_id = server_id_in
                and sg.id = sgm.server_group_id
                and sgt.id = sg.group_type
                and sgt.label in (
                    'sw_mgr_entitled','enterprise_entitled', 'bootstrap_entitled',
                    'provisioning_entitled', 'nonlinux_entitled',
                    'monitoring_entitled', 'virtualization_host',
                                        'virtualization_host_platform'
                    );

         ent_array varchar[];

    begin
      
      ent_array := '{}';

      for sg in server_groups loop
         ent_array := ent_array || sg.label;
      end loop;

      return ent_array;

    end$$
language plpgsql;

    -- this desperately needs to be table driven.
    create or replace function modify_org_service (
        org_id_in in numeric,
        service_label_in in varchar,
        enable_in in char
    ) returns void
as $$
    declare
        roles_to_process varchar[];
        roles cursor(role_label_in varchar) for
            select  label, id
            from    rhnUserGroupType
            where   label = role_label_in;
        org_roles cursor(role_label_in varchar) for
            select  1
            from    rhnUserGroup ug,
                    rhnUserGroupType ugt
            where   ugt.label = role_label_in
                and ug.org_id = org_id_in
                and ugt.id = ug.group_type;
                
        ents_to_process varchar[];
        ents cursor(ent_label_in varchar) for
            select  label, id
            from    rhnOrgEntitlementType
            where   label = ent_label_in;
        org_ents cursor(ent_label_in varchar) for
            select  1
            from    rhnOrgEntitlements oe,
                    rhnOrgEntitlementType oet
            where   oet.label = ent_label_in
                and oe.org_id = org_id_in
                and oet.id = oe.entitlement_id;
        create_row char(1);
    begin
        ents_to_process := '{}';
        roles_to_process := '{}';
        -- a bit kludgy, but only for 3.4 really.  Certainly no
        -- worse than the old code...
        if service_label_in = 'enterprise' or 
           service_label_in = 'management' then
            ents_to_process := array_append(ents_to_process, 'sw_mgr_enterprise');

            roles_to_process := array_append(roles_to_process, 'org_admin');

            roles_to_process := array_append(roles_to_process, 'system_group_admin');

            roles_to_process := array_append(roles_to_process, 'activation_key_admin');
        elsif service_label_in = 'provisioning' then
            ents_to_process := array_append(ents_to_process, 'rhn_provisioning');

            roles_to_process := array_append(roles_to_process, 'system_group_admin');

            roles_to_process := array_append(roles_to_process, 'activation_key_admin');

            roles_to_process := array_append(roles_to_process, 'config_admin');
            -- another nasty special case...
            if enable_in = 'Y' then
                ents_to_process := array_append(ents_to_process, 'sw_mgr_enterprise');
            end if;
        elsif service_label_in = 'monitoring' then
            ents_to_process := array_append(ents_to_process, 'rhn_monitor');

            roles_to_process := array_append(roles_to_process, 'monitoring_admin');
        elsif service_label_in = 'virtualization' then
            ents_to_process := array_append(ents_to_process, 'rhn_virtualization');

            roles_to_process := array_append(roles_to_process, 'config_admin');
        elsif service_label_in = 'virtualization_platform' then
            ents_to_process := array_append(ents_to_process, 'rhn_virtualization_platform');
            roles_to_process := array_append(roles_to_process, 'config_admin');
    elsif service_label_in = 'nonlinux' then
            ents_to_process := array_append(ents_to_process, 'rhn_nonlinux');
            roles_to_process := array_append(roles_to_process, 'config_admin');
        end if;

        if enable_in = 'Y' then
            for i in 1..array_upper(ents_to_process, 1) loop
                for ent in ents(ents_to_process[i]) loop
                    create_row := 'Y';
                    for oe in org_ents(ent.label) loop
                        create_row := 'N';
                    end loop;
                    if create_row = 'Y' then
                        insert into rhnOrgEntitlements(org_id, entitlement_id)
                            values (org_id_in, ent.id);
                    end if;
                end loop;
            end loop;
            for i in 1..array_upper(roles_to_process, 1) loop
                for role in roles(roles_to_process[i]) loop
                    create_row := 'Y';
                    for o_r in org_roles(role.label) loop
                        create_row := 'N';
                    end loop;
                    if create_row = 'Y' then
                        insert into rhnUserGroup(
                                id, name, description, current_members,
                                group_type, org_id
                            ) (
                                select  nextval('rhn_user_group_id_seq'),
                                        ugt.name || 's',
                                        ugt.name || 's for Org ' ||
                                            o.name || ' ('|| o.id ||')',
                                        0, ugt.id, o.id
                                from    rhnUserGroupType ugt,
                                        web_customer o
                                where   o.id = org_id_in
                                    and ugt.id = role.id
                            );
                    end if;
                end loop;
            end loop;
        else
            for i in 1..coalesce(array_upper(ents_to_process, 1), 0) loop
                for ent in ents(ents_to_process[i]) loop
                    delete from rhnOrgEntitlements
                     where org_id = org_id_in
                       and entitlement_id = ent.id;
                end loop;
            end loop;
        end if;
    end$$
language plpgsql;

    create or replace function set_customer_enterprise (
        customer_id_in in numeric
    ) returns void
as $$
    begin
        perform rhn_entitlements.modify_org_service(customer_id_in, 'enterprise', 'Y');
    end$$
language plpgsql;

    create or replace function set_customer_provisioning (
        customer_id_in in numeric
    ) returns void
as $$
    begin
        perform rhn_entitlements.modify_org_service(customer_id_in, 'provisioning', 'Y');
    end$$
language plpgsql;

    create or replace function set_customer_monitoring (
        customer_id_in in numeric
    ) returns void
as $$
    begin
        perform rhn_entitlements.modify_org_service(customer_id_in, 'monitoring', 'Y');
    end$$
language plpgsql;

    create or replace function set_customer_nonlinux (
        customer_id_in in numeric
    ) returns void
as $$
    begin
        perform rhn_entitlements.modify_org_service(customer_id_in, 'nonlinux', 'Y');
    end$$
language plpgsql;

    create or replace function unset_customer_enterprise (
        customer_id_in in numeric
    ) returns void
as $$
    begin
        perform rhn_entitlements.modify_org_service(customer_id_in, 'enterprise', 'N');
    end$$
language plpgsql;

    create or replace function unset_customer_provisioning (
        customer_id_in in numeric
    ) returns void
as $$
    begin
        perform rhn_entitlements.modify_org_service(customer_id_in, 'provisioning', 'N');
    end$$
language plpgsql;

    create or replace function unset_customer_monitoring (
        customer_id_in in numeric
    ) returns void
as $$
    begin
        perform rhn_entitlements.modify_org_service(customer_id_in, 'monitoring', 'N');
    end$$
language plpgsql;

    create or replace function unset_customer_nonlinux (
        customer_id_in in numeric
    ) returns void
as $$
    begin
        perform rhn_entitlements.modify_org_service(customer_id_in, 'nonlinux', 'N');
    end$$
language plpgsql;

    -- *******************************************************************
    -- PROCEDURE: prune_group
    -- Unsubscribes servers consuming physical slots that over the org's
    --   limit.
    -- Called by: set_server_group_count, repoll_virt_guest_entitlements
    -- *******************************************************************
    create or replace function prune_group (
        group_id_in in numeric,
        quantity_in in numeric,
        update_family_countsYN in numeric default 1
    ) returns void
as $$
    declare
        sgrecord record;
      type_is_base char;
    begin
            update      rhnServerGroup
                set     max_members = quantity_in
                where   id = group_id_in;

            for sgrecord in (
		   select  server_id, server_group_id, sgt.id as group_type_id, sgt.label
		    from    rhnServerGroupType              sgt,
				    rhnServerGroup                  sg,
				    rhnServerGroupMembers   sgm
		    where   1=1
			    and sgm.server_group_id = group_id_in
			    and sgm.server_id in (
				    select  sep.server_id
				    from
					rhnServerEntitlementPhysical sep
				    where
					sep.server_group_id = group_id_in
				    order by sep.modified asc
				    offset quantity_in
				)
			    and sgm.server_group_id = sg.id
			    and sg.group_type = sgt.id
	    ) loop
                perform rhn_entitlements.remove_server_entitlement(sgrecord.server_id, sgrecord.label);
            
            select is_base 
            into type_is_base
            from rhnServerGroupType sgt
            where sgt.id = sgrecord.group_type_id;

            -- if we're removing a base ent, then be sure to
            -- remove the server's channel subscriptions.
            if ( type_is_base = 'Y' ) then
                   perform rhn_channel.clear_subscriptions(sgrecord.server_id, 0, update_family_countsYN);
            end if;

            end loop;
    end$$
language plpgsql;

    -- *******************************************************************
    -- PROCEDURE: assign_system_entitlement
    --
    -- Moves system entitlements from from_org_id_in to to_org_id_in.
    -- Can raise not_enough_entitlements_in_base_org if from_org_id_in
    -- does not have enough entitlements to cover the move.
    -- Takes care of unentitling systems if necessary by calling 
    -- set_server_group_count
    -- *******************************************************************
    create or replace function assign_system_entitlement(
        group_label_in in varchar,
        from_org_id_in in numeric,
        to_org_id_in in numeric,
        quantity_in in numeric
    ) returns void
as $$
    declare
        prev_ent_count numeric;
    to_org_prev_ent_count numeric;
        new_ent_count numeric;
    new_quantity numeric;
        group_type numeric;
    begin

            select max_members
            into prev_ent_count
            from rhnServerGroupType sgt,
                 rhnServerGroup sg
            where sg.org_id = from_org_id_in
              and sg.group_type = sgt.id
              and sgt.label = group_label_in;

            if not found then
                perform rhn_exception.raise_exception(
                              'not_enough_entitlements_in_base_org');
            end if;

            select max_members
            into to_org_prev_ent_count
            from rhnServerGroupType sgt,
                 rhnServerGroup sg
            where sg.org_id = to_org_id_in
              and sg.group_type = sgt.id
              and sgt.label = group_label_in;

            if not found then
                to_org_prev_ent_count := 0;
            end if;
    
            select id
            into group_type
            from rhnServerGroupType
            where label = group_label_in;

            if not found then
                perform rhn_exception.raise_exception(
                              'invalid_server_group');
            end if;

        new_ent_count := prev_ent_count - quantity_in;
    
        if prev_ent_count > new_ent_count then
            new_quantity := to_org_prev_ent_count + quantity_in;
        end if;
    
        if new_ent_count < 0 then
            perform rhn_exception.raise_exception(
                          'not_enough_entitlements_in_base_org');
        end if;


        perform rhn_entitlements.set_server_group_count(from_org_id_in,
                                         group_type,
                                         new_ent_count);

        perform rhn_entitlements.set_server_group_count(to_org_id_in,
                                         group_type,
                                         new_quantity);
        
        -- Create or delete the entries in rhnOrgEntitlementType
        if group_label_in = 'enterprise_entitled' then 
            if new_quantity > 0 then
                perform rhn_entitlements.set_customer_enterprise(to_org_id_in);
            else
                perform rhn_entitlements.unset_customer_enterprise(to_org_id_in);
            end if;
        end if;

        if group_label_in = 'provisioning_entitled' then
            if new_quantity > 0 then
                perform rhn_entitlements.set_customer_provisioning(to_org_id_in);
            else
                perform rhn_entitlements.unset_customer_provisioning(to_org_id_in);
            end if;
        end if;

        if group_label_in = 'monitoring_entitled' then
            if new_quantity > 0 then
                perform rhn_entitlements.set_customer_monitoring(to_org_id_in);
            else
                perform rhn_entitlements.unset_customer_monitoring(to_org_id_in);
            end if;
        end if;

    end$$
language plpgsql;

    -- *******************************************************************
    -- PROCEDURE: assign_channel_entitlement
    --
    -- Moves channel entitlements from from_org_id_in to to_org_id_in.
    -- Can raise not_enough_entitlements_in_base_org if from_org_id_in
    -- does not have enough entitlements to cover the move.
    -- Takes care of unentitling systems if necessary by calling 
    -- set_family_count
    -- *******************************************************************
    create or replace function assign_channel_entitlement(
        channel_family_label_in in varchar,
        from_org_id_in in numeric,
        to_org_id_in in numeric,
        quantity_in in numeric,
        flex_in in numeric
    ) returns void
as $$
    declare
        from_org_prev_ent_count numeric;
        from_org_prev_ent_count_flex numeric;
        new_ent_count numeric;
        new_ent_count_flex numeric;
        to_org_prev_ent_count numeric;
        to_org_prev_ent_count_flex numeric;
        new_quantity numeric;
        new_flex numeric;
        cfam_id       numeric;
    begin

            select max_members
            into from_org_prev_ent_count
            from rhnChannelFamily cf,
                 rhnPrivateChannelFamily pcf
            where pcf.org_id = from_org_id_in
              and pcf.channel_family_id = cf.id
              and cf.label = channel_family_label_in;

            if not found then
                perform rhn_exception.raise_exception(
                              'not_enough_entitlements_in_base_org');
            end if;
    
            select max_members
            into to_org_prev_ent_count
            from rhnChannelFamily cf,
                 rhnPrivateChannelFamily pcf
            where pcf.org_id = to_org_id_in
              and pcf.channel_family_id = cf.id
              and cf.label = channel_family_label_in;

            if not found then
                to_org_prev_ent_count := 0;
            end if;

            select fve_max_members
            into from_org_prev_ent_count_flex
            from rhnChannelFamily cf,
                rhnPrivateChannelFamily pcf
            where pcf.org_id = from_org_id_in
              and pcf.channel_family_id = cf.id
              and cf.label = channel_family_label_in;

            if not found then
                perform rhn_exception.raise_exception(
                              'not_enough_flex_entitlements_in_base_org');
            end if;

            select fve_max_members
            into to_org_prev_ent_count_flex
            from rhnChannelFamily cf,
                 rhnPrivateChannelFamily pcf
            where pcf.org_id = to_org_id_in
              and pcf.channel_family_id = cf.id
              and cf.label = channel_family_label_in;

            if not found then
                to_org_prev_ent_count_flex := 0;
            end if;

            select id
            into cfam_id
            from rhnChannelFamily
            where label = channel_family_label_in;

            if not found then
                perform rhn_exception.raise_exception(
                              'invalid_channel_family');
            end if;

        new_ent_count := from_org_prev_ent_count - quantity_in;
        new_ent_count_flex := from_org_prev_ent_count_flex - flex_in;
    
        if from_org_prev_ent_count >= new_ent_count then
            new_quantity := to_org_prev_ent_count + quantity_in;
        end if;

        if from_org_prev_ent_count_flex >= new_ent_count_flex then
            new_flex := to_org_prev_ent_count_flex + flex_in;
        end if;

        if new_ent_count < 0 then
            perform rhn_exception.raise_exception(
                          'not_enough_entitlements_in_base_org');
        end if;

        if new_ent_count_flex < 0 then
            perform rhn_exception.raise_exception(
                          'not_enough_flex_entitlements_in_base_org');
        end if;



        perform rhn_entitlements.set_family_count(from_org_id_in,
                                          cfam_id,
                                          new_ent_count,
                                          new_ent_count_flex);

        perform rhn_entitlements.set_family_count(to_org_id_in,
                                          cfam_id,
                                          new_quantity,
                                          new_flex);

    end$$
language plpgsql;

    -- *******************************************************************
    -- PROCEDURE: activate_system_entitlement
    --
    -- Sets the values in rhnServerGroup for a given rhnServerGroupType.
    -- 
    -- Calls: set_server_group_count to update, prune, or create the group.
    -- Called by: the code that activates a satellite cert. 
    --
    -- Raises not_enough_entitlements_in_base_org if all entitlements
    -- in the org are used so the free entitlements would not cover
    -- the difference when descreasing the number of entitlements.
    -- *******************************************************************
    create or replace function activate_system_entitlement(
        org_id_in in numeric,
        group_label_in in varchar,
        quantity_in in numeric
    ) returns void
as $$
    declare
        prev_ent_count numeric; 
        prev_ent_count_sum numeric; 
        group_type numeric;
    begin

        -- Fetch the current entitlement count for the org
        -- into prev_ent_count

            select current_members
            into prev_ent_count
            from rhnServerGroupType sgt,
                 rhnServerGroup sg
            where sg.group_type = sgt.id
              and sgt.label = group_label_in
              and sg.org_id = org_id_in;

            if not found then
                prev_ent_count := 0;
            end if;

            select id
            into group_type
            from rhnServerGroupType
            where label = group_label_in;

            if not found then
                perform rhn_exception.raise_exception(
                              'invalid_server_group');
            end if;

        -- If we're setting the total entitlemnt count to a lower value,
        -- and that value is less than the allocated count in this org,
        -- we need to raise an exception.
        if quantity_in < prev_ent_count then
            perform rhn_exception.raise_exception(
                          'not_enough_entitlements_in_base_org');
        else
            -- don't update family counts after every server
            -- will do bulk update afterwards
            perform rhn_entitlements.set_server_group_count(org_id_in,
                                             group_type,
                                             quantity_in,
                                             0);
            -- bulk update family counts
            perform rhn_channel.update_group_family_counts(group_label_in, org_id_in);
        end if;

    end$$
language plpgsql;

    -- *******************************************************************
    -- PROCEDURE: activate_channel_entitlement
    --
    -- Calls: set_family_count to update, prune, or create the family
    --        permission bucket.
    -- Called by: the code that activates a satellite cert. 
    --
    -- Raises not_enough_entitlements_in_base_org if there are not enough
    -- entitlements in the org to cover the difference when you are
    -- descreasing the number of entitlements.
    --
    -- The backend code in Python is expected to do whatever arithmetics
    -- is needed.
    -- *******************************************************************
    create or replace function activate_channel_entitlement(
        org_id_in in numeric,
        channel_family_label_in in varchar,
        quantity_in in numeric,
        flex_in in numeric
    ) returns void
as $$
    declare
        prev_ent_count numeric; 
        prev_flex_count numeric;
        prev_ent_count_sum numeric; 
        cfam_id numeric;
        reduce_quantity numeric;
        total_flex_capable numeric;
        to_convert_reg cursor (channel_family_id_val numeric, org_id_in numeric, quantity numeric) for
                     select SC.server_id
                     from rhnServerChannel SC inner join
                          rhnServer S on S.id = SC.server_id
                     where
                         is_fve = 'Y'
                         and S.org_id = org_id_in
                         and SC.channel_id in
                         (select cfm.channel_id from rhnChannelFamilyMembers cfm
                             where cfm.CHANNEL_FAMILY_ID = channel_family_id_val)
                         limit quantity;
         to_convert_flex cursor (channel_family_id_val numeric, org_id_in numeric, quantity numeric) for
                   select server_id
                   from rhnServerFveCapable
                       where SERVER_ORG_ID = org_id_in and
                             channel_family_id = cfam_id
                       limit quantity;

    begin

        -- Fetch the current entitlement count for the org
        -- into prev_ent_count
            select current_members
            into prev_ent_count
            from rhnChannelFamily cf,
                 rhnPrivateChannelFamily pcf
            where pcf.org_id = org_id_in
              and pcf.channel_family_id = cf.id
              and cf.label = channel_family_label_in;

            if not found then
                prev_ent_count := 0;
            end if;

            select pcf.fve_current_members
            into prev_flex_count
            from rhnChannelFamily cf,
                 rhnPrivateChannelFamily pcf
            where pcf.org_id = org_id_in
              and pcf.channel_family_id = cf.id
              and cf.label = channel_family_label_in;

            if not found then
                prev_flex_count := 0;
            end if;

            select id
            into cfam_id
            from rhnChannelFamily
            where label = channel_family_label_in;

            if not found then
                perform rhn_exception.raise_exception(
                              'invalid_channel_family');
            end if;

        -- if there are too few flex entitlements
        if flex_in < prev_flex_count then
            -- and if the extra we need is less than or equal to our extra regular entitlements
            if prev_flex_count - flex_in <= quantity_in - prev_ent_count then
                   reduce_quantity := prev_flex_count - flex_in;
                   -- We need to convert some systems from flex guest to regular
                   for system in to_convert_reg(cfam_id, org_id_in, reduce_quantity) loop
                      --rhn_channel.convert_to_regular(system.server_id, cfam_id);
                      UPDATE rhnServerChannel sc set is_fve = 'N'
                           where sc.server_id = system.server_id
                                 and sc.channel_id in (select cfm.channel_id
                                                          from rhnChannelFamilyMembers cfm
                                                          where cfm.channel_family_id = cfam_id);
                   end loop;

                   --reset previous counts
                   prev_ent_count := prev_ent_count + reduce_quantity;
                   prev_flex_count := prev_flex_count - reduce_quantity;
            else
                perform rhn_exception.raise_exception(
                          'not_enough_flex_entitlements_in_base_org');
            end if;
        end if;

        -- if there are too few regular entitlements, and extra flex entitlements
        if quantity_in < prev_ent_count and prev_flex_count < flex_in then
                -- how many flex-capable systems (that aren't using flex) do we have
                select count(*)
                   into total_flex_capable
                   from rhnServerFveCapable
                       where SERVER_ORG_ID = org_id_in and
                             channel_family_id = cfam_id;
                -- if we have enough flex capable machines that is at least
                --   as many as what we are over on
                if total_flex_capable >= prev_ent_count - quantity_in then
                    reduce_quantity := prev_ent_count - quantity_in;
                    for system in to_convert_flex(cfam_id, org_id_in, reduce_quantity) loop
--                          rhn_channel.convert_to_fve(system.server_id, cfam_id);
                        UPDATE rhnServerChannel sc set is_fve = 'Y'
                           where sc.server_id = system.server_id
                                 and sc.channel_id in (select cfm.channel_id
                                                          from rhnChannelFamilyMembers cfm
                                                          where cfm.channel_family_id = cfam_id);
                    end loop;
                    prev_ent_count := prev_ent_count - reduce_quantity;
                    prev_flex_count := prev_flex_count + reduce_quantity;
                end if;
        end if;

        -- If we're setting the total entitlemnt count to a lower value,
        -- and that value is less than the count in that one org,
        -- we need to raise an exception.
        if quantity_in < prev_ent_count then
            perform rhn_exception.raise_exception(
                          'not_enough_entitlements_in_base_org');
        else
            -- even if we've manually converted systems to/from flex above
            -- set_family_count should call update_family_counts, to reset
            -- current used slots
            perform rhn_entitlements.set_family_count(org_id_in, cfam_id,
                                              quantity_in, flex_in);
        end if;

    end$$
language plpgsql;

    create or replace function set_server_group_count (
        customer_id_in in numeric,  -- customer_id
        group_type_in in numeric,   -- rhn[User|Server]GroupType.id
        quantity_in in numeric,      -- quantity
                update_family_countsYN in numeric default 1
    ) returns void
as $$
    declare
        group_id numeric;
        quantity numeric;
        wasfound boolean;
    begin
        quantity := quantity_in;
        if quantity is not null and quantity < 0 then
            quantity := 0;
        end if;

        select  rsg.id
        into    group_id
        from    rhnServerGroup rsg
        where   1=1
            and rsg.org_id = customer_id_in
            and rsg.group_type = group_type_in;

        -- preserve the not found status across the rhn_entitlements.prune_group invocation
        wasfound := true;
        if not found then
            wasfound := false;
        end if;

        perform rhn_entitlements.prune_group(
            group_id,
            quantity,
                        update_family_countsYN
        );

        if not wasfound then
            insert into rhnServerGroup (
                    id, name, description, max_members, current_members,
                    group_type, org_id, created, modified
                ) (
                    select  nextval('rhn_server_group_id_seq'), name, name,
                            quantity, 0, id, customer_id_in,
                            current_timestamp, current_timestamp
                    from    rhnServerGroupType
                    where   id = group_type_in
            );
        end if;

    end$$
language plpgsql;

    -- *******************************************************************
    -- PROCEDURE: prune_family
    -- Unsubscribes servers consuming physical slots from the channel family 
    --   that are over the org's limit.
    -- Called by: set_family_count
    -- *******************************************************************
    create or replace function prune_family (
        customer_id_in in numeric,
        channel_family_id_in in numeric,
        quantity_in in numeric,
        flex_in in numeric
    ) returns void
as $$
    declare
        serverchannels cursor(tmp_quantity numeric, is_fve_in char) for
            select  sc.server_id,
                    sc.channel_id
            from    rhnServerChannel sc,
                    rhnChannelFamilyMembers cfm
            where   1=1
                and cfm.channel_family_id = channel_family_id_in
                and cfm.channel_id = sc.channel_id
                and server_id in (
                       select server_id from (
                            select  distinct rs.id as server_id
                            from    
                                    rhnServerChannel        rsc,
                                    rhnChannelFamilyMembers rcfm,
                                    rhnServer               rs
                            where   1=1
                                and rs.org_id = customer_id_in
                                and rs.id = rsc.server_id
                                and rsc.channel_id = rcfm.channel_id
                                and rcfm.channel_family_id =  channel_family_id_in
                                and rsc.is_fve = is_fve_in
                                -- we only want to grab servers consuming
                                -- physical slots.
                                and exists (
                                    select 1
                                    from rhnChannelFamilyServerPhysical cfsp
                                    where cfsp.server_id = rs.id
                                    and cfsp.channel_family_id = 
                                        channel_family_id_in
                                    )
                            ) Q
                        order by server_id asc
                        offset quantity_in
                        );
    begin
        -- if we get a null customer_id, this is completely bogus.
        if customer_id_in is null then
            return;
        end if;

        for sc in serverchannels(quantity_in, 'N') loop
            perform rhn_channel.unsubscribe_server(sc.server_id, sc.channel_id,
                                                   1, 1, 0, 0);
        end loop;

        for sc in serverchannels(flex_in, 'Y') loop
            perform rhn_channel.unsubscribe_server(sc.server_id, sc.channel_id,
                                                   1, 1, 0, 0);
        end loop;

        perform rhn_channel.update_family_counts(channel_family_id_in, customer_id_in);
    end$$
language plpgsql;
        
    create or replace function set_family_count (
        customer_id_in in numeric,      -- customer_id
        channel_family_id_in in numeric,    -- 246
        quantity_in in numeric,          -- 3
        flex_in in numeric
    ) returns void
as $$
    declare
        privperms cursor for
            select  1
            from    rhnPrivateChannelFamily
            where   org_id = customer_id_in
                and channel_family_id = channel_family_id_in;
        pubperms cursor for
            select  o.id org_id
            from    web_customer o,
                    rhnPublicChannelFamily pcf
            where   pcf.channel_family_id = channel_family_id_in;
        quantity numeric;
        done numeric := 0;
        flex numeric;
    begin
        quantity := quantity_in;
        if quantity is not null and quantity < 0 then
            quantity := 0;
        end if;
        flex := flex_in;
        if flex is not null and flex < 0 then
            flex := 0;
        end if;

        if customer_id_in is not null then
            for perm in privperms loop
                perform rhn_entitlements.prune_family(
                    customer_id_in,
                    channel_family_id_in,
                    quantity,
                    flex
                );

                if quantity is null and flex is null then
                    delete from rhnPrivateChannelFamily
                        where org_id = customer_id_in
                            and channel_family_id = channel_family_id_in;
                 else
                    update rhnPrivateChannelFamily
                        set max_members = quantity
                        where org_id = customer_id_in
                            and channel_family_id = channel_family_id_in;

                   update rhnPrivateChannelFamily
                        set fve_max_members = flex
                        where org_id = customer_id_in
                            and channel_family_id = channel_family_id_in;
                end if;
                return;
            end loop;

            insert into rhnPrivateChannelFamily (
                    channel_family_id, org_id, max_members, current_members, fve_max_members, fve_current_members
                ) values (
                    channel_family_id_in, customer_id_in, quantity, 0, flex, 0 );
            return;
        end if;

        for perm in pubperms loop
            if quantity = 0 then
                perform rhn_entitlements.prune_family(
                    perm.org_id,
                    channel_family_id_in,
                    quantity,
                    flex
                );
                if done = 0 then
                    delete from rhnPublicChannelFamily
                        where channel_family_id = channel_family_id_in;
                end if;
            end if;
            done := 1;
        end loop;
        -- if done's not 1, then we don't have any entitlements
        if done != 1 then
            insert into rhnPublicChannelFamily (
                    channel_family_id
                ) values (
                    channel_family_id_in
                );
        end if;
    end$$
language plpgsql;

    -- this expects quantity_in to be the number of available slots, not the
    -- max_members of the server group.  If you give it too many, it'll fail
    -- and raise servergroup_max_members.
    -- We should NEVER run this unless we're SURE that we won't
    -- be violating the max.
    create or replace function entitle_last_modified_servers (
        customer_id_in in numeric,  -- customer_id
        type_label_in in varchar,   -- 'enterprise_entitled'
        quantity_in in numeric      -- 3
    ) returns void
as $$
    declare
        -- find the servers that aren't currently in slots
        servers cursor(cid_in numeric, quant_in numeric) for
                                    select  rs.id as server_id
                                    from    rhnServer rs
                                    where   1=1
                                        and rs.org_id = cid_in
                                        and not exists (
                                            select  1
                                            from    rhnServerGroup sg,
                                                    rhnServerGroupMembers rsgm
                                            where   rsgm.server_id = rs.id
                                                and rsgm.server_group_id = sg.id
                                                and sg.group_type is not null
                                        )
                                        and not exists (
                                            select 1
                                            from rhnVirtualInstance vi
                                            where vi.virtual_system_id =
                                                  rs.id
                                        )
                                    order by modified desc
                                    limit quant_in;
    begin
        for server in servers(customer_id_in, quantity_in) loop
            perform rhn_entitlements.entitle_server(server.server_id, type_label_in);
        end loop;
    end$$
language plpgsql;

    create or replace function subscribe_newest_servers (
        customer_id_in in numeric
    ) returns void
as $$
    declare
        -- find servers without base channels
        servers cursor(cid_in numeric) for
            select  s.id
            from    rhnServer           s
            where   1=1
                and s.org_id = cid_in
                and not exists (
                        select 1
                        from    rhnChannel          c,
                                rhnServerChannel    sc
                        where   sc.server_id = s.id
                            and sc.channel_id = c.id
                            and c.parent_channel is null
                    )
                and not exists (
                        select 1
                        from rhnVirtualInstance vi
                        where vi.virtual_system_id = s.id
                    )                        
            order by s.modified desc;
        channel_id numeric;
    begin
        for server in servers(customer_id_in) loop
            channel_id := rhn_channel.guess_server_base(server.id);
            if channel_id is not null then
                begin
                    perform rhn_channel.subscribe_server(server.id, channel_id);
                -- exception is really channel_family_no_subscriptions
                exception
                    when others then
                        null;
                end;
            end if;
        end loop;
    end$$
language plpgsql;


-- restore the original setting
update pg_settings set setting = overlay( setting placing '' from 1 for (length('rhn_entitlements')+1) ) where name = 'search_path';
   07070100000AE7000081B400000000000000000000000167AE111400001CB4000000000000000000000000000000000000006000000000susemanager-schema/upgrade/susemanager-schema-2.1.51-to-susemanager-schema-3.0/1016-rhn_org.sql   --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--

-- create schema rhn_org;

-- setup search_path so that these functions are created in appropriate schema.
update pg_settings set setting = 'rhn_org,' || setting where name = 'search_path';


create or replace function delete_org (
        org_id_in in numeric
    ) returns void
    as
    $$
    declare
        users cursor for
        select id
        from web_contact
        where org_id = org_id_in;

        servers cursor (org_id_in numeric) for
        select  id
        from    rhnServer
        where   org_id = org_id_in;

        config_channels cursor for
        select id
        from rhnConfigChannel
        where org_id = org_id_in;

        custom_channels cursor for
        select  id
        from    rhnChannel
        where   org_id = org_id_in;

        errata cursor for
        select  id
        from    rhnErrata
        where   org_id = org_id_in;

    begin

        if org_id_in = 1 then
            perform rhn_exception.raise_exception('cannot_delete_base_org');
        end if;

        -- Delete all users.
        for u in users loop
            perform rhn_org.delete_user(u.id, 1);
        end loop;

        -- Delete all servers.
        for s in servers(org_id_in) loop
            perform delete_server(s.id);
        end loop;

        -- Delete all config channels.
        for c in config_channels loop
            perform rhn_config.delete_channel(c.id);
        end loop;

        -- Delete all custom channels.
        for cc in custom_channels loop
          delete from rhnServerChannel where channel_id = cc.id;
          delete from rhnServerProfilePackage where server_profile_id in (
            select id from rhnServerProfile where base_channel = cc.id
          );
          delete from rhnServerProfile where base_channel = cc.id;
        end loop;

        -- Delete all errata packages 
        for e in errata loop
            delete from rhnErrataPackage where errata_id = e.id;
        end loop;

        -- Give the org's entitlements back to the main org.
        perform rhn_entitlements.remove_org_entitlements(org_id_in);

        -- Clean up tables where we don't have a cascading delete.
        delete from rhnChannel where org_id = org_id_in;
        delete from rhnDailySummaryQueue where org_id = org_id_in;
        delete from rhnFileList where org_id = org_id_in;
        delete from rhnServerGroup where org_id = org_id_in;
        delete from rhnContentSource where org_id = org_id_in;

        -- Delete the org.
        delete from web_customer where id = org_id_in;

    end;
    $$
    language plpgsql;

create or replace function delete_user(user_id_in in numeric, deleting_org in numeric default 0) returns void 
    as
    $$
    declare
    servergroups_needing_admins cursor for
            select    usgp.server_group_id    server_group_id
            from    rhnUserServerGroupPerms    usgp
            where    1=1
                and usgp.user_id = user_id_in
                and not exists (
                    select    1
                    from    rhnUserServerGroupPerms    sq_usgp
                    where    1=1
                        and sq_usgp.server_group_id = usgp.server_group_id
                        and    sq_usgp.user_id != user_id_in
                );
        users            numeric;
        our_org_id        numeric;
        other_users        numeric;
        other_org_admin    numeric;
        other_user_id  numeric;
        is_admin       numeric;
    begin
        select    wc.org_id
        into    our_org_id
        from    web_contact wc
        where    id = user_id_in;

        -- find any other users
        begin
            select    id, 1
            into    other_user_id, other_users
            from    web_contact
            where    1=1
                and org_id = our_org_id
                and id != user_id_in
                limit 1;
        exception
            when no_data_found then
                other_users := 0;
        end;

        -- now do org admin stuff
        if other_users != 0 then
            -- is user admin?
            select  count(1)
             into   is_admin
            from    rhnUserGroupType    ugt,
                    rhnUserGroup        ug,
                    rhnUserGroupMembers    ugm
            where    ugm.user_id = user_id_in
                and ugm.user_group_id = ug.id
                and ug.group_type = ugt.id
                and ugt.label = 'org_admin';
            if is_admin > 0 then
                begin
                    select    new_ugm.user_id
                    into    other_org_admin
                    from    rhnUserGroupMembers    new_ugm,
                            rhnUserGroupType    ugt,
                            rhnUserGroup        ug,
                            rhnUserGroupMembers    ugm
                    where    ugm.user_id = user_id_in
                        and ugm.user_group_id = ug.id
                        and ug.group_type = ugt.id
                        and ugt.label = 'org_admin'
                        and ug.id = new_ugm.user_group_id
                        and new_ugm.user_id != user_id_in
                        limit 1;
                exception
                    when no_data_found then
                        -- If we're deleting the org, we don't want to raise
                        -- the exception.
                        if deleting_org = 0 then
                           perform rhn_exception.raise_exception('cannot_delete_user');
                        end if;
                end;

                for sg in servergroups_needing_admins loop
                   perform rhn_user.add_servergroup_perm(other_org_admin,
                        sg.server_group_id);
                end loop;
            end if;
        end if;

        -- and now things for every user
        delete from rhnUserServerPerms where user_id = user_id_in;
        update rhnConfigRevision
           set changed_by_id = NULL
         where changed_by_id = user_id_in;
        if other_users != 0 then
            update        rhnRegToken
                set        user_id = coalesce(other_org_admin, other_user_id)
                where    org_id = our_org_id
                    and user_id = user_id_in;
        end if;

        begin
            delete from web_contact where id = user_id_in;
        exception
            when others then
               perform rhn_exception.raise_exception('cannot_delete_user');
        end;
        return;

        end;
        $$
        language plpgsql;


-- restore the original setting
update pg_settings set setting = overlay( setting placing '' from 1 for (length('rhn_org')+1) ) where name = 'search_path';
07070100000AE8000081B400000000000000000000000167AE1114000008C3000000000000000000000000000000000000006F00000000susemanager-schema/upgrade/susemanager-schema-2.1.51-to-susemanager-schema-3.0/1017-drop_monitoring_tables.sql    
drop function rhn_install_org_satellites(numeric, numeric, character varying);
drop function rhn_prepare_install(character varying, numeric);
drop function rhn_install_satellite(numeric, numeric);
drop function rhn_synch_probe_state();
drop table rhn_probe_param_value;
drop table rhn_command_parameter;
drop view time_series;
drop table time_series_data;
drop table time_series_purge;
drop table rhn_check_probe;
drop table rhn_host_probe;
drop table rhn_sat_cluster_probe;
drop table rhn_url_probe_step;
drop table rhn_url_probe;
drop table rhn_service_probe_origins;
drop table rhn_probe;
drop table rhn_os_commands_xref;
drop table rhn_command_param_threshold;
drop table rhn_command;
drop table rhn_command_groups;
drop table rhn_metrics;
drop table rhn_command_class;
drop table rhn_command_requirements;
drop table rhn_command_queue_execs;
drop table rhn_command_queue_params;
drop table rhn_command_queue_instances;
drop table rhn_command_queue_commands;
drop table rhn_threshold_type;
drop table rhn_units;
drop table rhn_quanta;
drop table rhn_server_monitoring_info;
drop table rhn_os;
drop table rhn_deployed_probe;
drop table rhn_current_state_summaries;
drop table rhn_probe_types;
drop table rhn_probe_state;
drop table rhn_widget;
drop table rhn_check_suite_probe;
drop table rhn_check_suites;
drop table rhn_ll_netsaint;
drop table rhn_snmp_alert;
drop table rhn_redirect_method_targets;
drop table rhn_redirect_group_targets;
drop table rhn_redirect_email_targets;
drop table rhn_redirect_criteria;
drop table rhn_redirects;
drop table rhn_contact_group_members;
drop table rhn_contact_groups;
drop table rhn_contact_methods;
drop table rhn_method_types;
drop table rhn_pager_types;
drop table rhn_notification_formats;
drop table rhn_strategies;
drop table rhn_redirect_match_types;
drop table rhn_redirect_types;
drop table rhn_notifservers;
drop table rhn_semantic_data_type;
drop table rhn_sat_node;
drop table rhn_sat_cluster;
drop table rhn_command_target;
drop table rhn_physical_location;
drop table rhn_multi_scout_threshold;
drop table rhn_satellite_state;
drop table rhn_schedule_days;
drop table rhn_schedule_weeks;
drop table rhn_schedules;
drop table rhn_schedule_types;
drop table rhn_command_queue_sessions;
 07070100000AE9000081B400000000000000000000000167AE1114000000E8000000000000000000000000000000000000006C00000000susemanager-schema/upgrade/susemanager-schema-2.1.51-to-susemanager-schema-3.0/1018-drop_solaris_tables.sql   drop table rhnSolarisPatchSet;
drop table rhnSolarisPatch;
drop table rhnSolarisPatchType;
drop table rhnSolarisPatchedPackage;
drop table rhnSolarisPackage;
drop table rhnSolarisPatchSetMembers;
drop table rhnSolarisPatchPackages;
07070100000AEA000081B400000000000000000000000167AE111400000359000000000000000000000000000000000000006B00000000susemanager-schema/upgrade/susemanager-schema-2.1.51-to-susemanager-schema-3.0/1019-rhnServerGroupType.sql    
delete from rhnServerGroupMembers where server_group_id in
       (select sg.id
          from rhnServerGroup sg,
               rhnServerGroupType sgt
         where sg.group_type = sgt.id
           and sgt.label = 'monitoring_entitled');
alter table rhnServerGroup disable trigger rhnservergroup_log_trig;
delete from rhnServerGroup where group_type in
       (select id from rhnServerGroupType where label = 'monitoring_entitled');
alter table rhnServerGroup enable trigger rhnservergroup_log_trig;
delete from rhnSgTypeBaseAddOnCompat where addon_id in
       (select id from rhnServerGroupType where label = 'monitoring_entitled');
delete from rhnServerServerGroupArchCompat where server_group_type in
       (select id from rhnServerGroupType where label = 'monitoring_entitled');
delete from rhnServerGroupType where label = 'monitoring_entitled';
   07070100000AEB000081B400000000000000000000000167AE111400000035000000000000000000000000000000000000006400000000susemanager-schema/upgrade/susemanager-schema-2.1.51-to-susemanager-schema-3.0/1020-rhnInfoPane.sql   delete from rhnInfoPane where label like '%-probes';
   07070100000AEC000081B400000000000000000000000167AE1114000000EE000000000000000000000000000000000000007100000000susemanager-schema/upgrade/susemanager-schema-2.1.51-to-susemanager-schema-3.0/1021-rhnServerNetwork-trigger.sql  
drop trigger if exists rhn_servnet_ipaddr_mon_trig on rhnServerNetwork;

create or replace function rhn_servernetwork_mod_trig_fun() returns trigger as
$$
begin
	new.modified := current_timestamp;
 	return new;
end;
$$ language plpgsql;
  07070100000AED000081B400000000000000000000000167AE111400000407000000000000000000000000000000000000006B00000000susemanager-schema/upgrade/susemanager-schema-2.1.51-to-susemanager-schema-3.0/1022-armv7l-debian-arch.sql    insert into rhnServerArch (id, label, name, arch_type_id) values (sequence_nextval('rhn_server_arch_id_seq'), 'armv7l-debian-linux', 'arm Debian', lookup_arch_type('deb'));

insert into rhnServerChannelArchCompat (server_arch_id, channel_arch_id) values (LOOKUP_SERVER_ARCH('armv7l-debian-linux'), LOOKUP_CHANNEL_ARCH('channel-arm-deb'));

insert into rhnServerPackageArchCompat (server_arch_id, package_arch_id, preference) values (LOOKUP_SERVER_ARCH('armv7l-debian-linux'), LOOKUP_PACKAGE_ARCH('armhf-deb'), 0);

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type ) values (lookup_server_arch('armv7l-debian-linux'), lookup_sg_type('sw_mgr_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type ) values (lookup_server_arch('armv7l-debian-linux'), lookup_sg_type('enterprise_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type ) values (lookup_server_arch('armv7l-debian-linux'), lookup_sg_type('provisioning_entitled'));
 07070100000AEE000081B400000000000000000000000167AE1114000000A1000000000000000000000000000000000000006400000000susemanager-schema/upgrade/susemanager-schema-2.1.51-to-susemanager-schema-3.0/1023-rhnUserInfo.sql   ALTER TABLE rhnUserInfo ADD tasko_notify CHAR(1)
      DEFAULT('Y') NOT NULL
      CONSTRAINT rhn_user_info_tasko_ck
        CHECK (tasko_notify in ('Y', 'N'));
   07070100000AEF000081B400000000000000000000000167AE1114000061CF000000000000000000000000000000000000008200000000susemanager-schema/upgrade/susemanager-schema-2.1.51-to-susemanager-schema-3.0/1024-avoid_deadlock_update_server_needed_cache.sql --
-- Copyright (c) 2008--2014 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--

-- create schema rhn_server;

--update pg_setting
update pg_settings set setting = 'rhn_server,' || setting where name = 'search_path';

    create or replace function system_service_level(
    	server_id_in in numeric,
	service_level_in in varchar
    ) returns numeric as $$
    declare
    ents cursor is 
      select label from rhnServerEntitlementView
      where server_id = server_id_in;

    retval numeric := 0;

    begin
         for ent in ents loop
            retval := rhn_entitlements.entitlement_grants_service (ent.label, service_level_in);
            if retval = 1 then
               return retval;
            end if;
         end loop;

         return retval;

    end$$ language plpgsql;

        
    create or replace function can_change_base_channel(server_id_in IN NUMERIC)
    returns numeric
    as $$
    declare
    	throwaway numeric;
    begin
    	-- the idea: if we get past this query, the server is
	-- neither sat nor proxy, so base channel is changeable

	select 1 into throwaway
	  from rhnServer S
	 where S.id = server_id_in
	   and not exists (select 1 from rhnSatelliteInfo SI where SI.server_id = S.id)
	   and not exists (select 1 from rhnProxyInfo PI where PI.server_id = S.id);

        if not found then
	    return 0;
        end if;
	   
	return 1;
    end$$ language plpgsql;
	        
    create or replace function set_custom_value(
    	server_id_in in numeric,
	user_id_in in numeric,
	key_label_in in varchar,
	value_in in varchar
    ) returns void
    as $$
    declare
    	key_id_val numeric;
    begin
    	select CDK.id into strict key_id_val
	  from rhnCustomDataKey CDK,
	       rhnServer S
	 where S.id = server_id_in
	   and S.org_id = CDK.org_id
	   and CDK.label = key_label_in;
	   
	begin
	    insert into rhnServerCustomDataValue (server_id, key_id, value, created_by, last_modified_by)
	    values (server_id_in, key_id_val, value_in, user_id_in, user_id_in);
	exception
	    when UNIQUE_VIOLATION
	    	then
		update rhnServerCustomDataValue
		   set value = value_in,
		       last_modified_by = user_id_in
		 where server_id = server_id_in
		   and key_id = key_id_val;		   
	end;

    end$$ language plpgsql;
    
    create or replace function bulk_set_custom_value(
    	key_label_in in varchar,
	value_in in varchar,
	set_label_in in varchar,
	set_uid_in in numeric
    )
    returns integer
    as $$
    declare
        i integer;
        server record;
    begin
        i := 0;
        for server in (
           SELECT user_id, label, element, element_two
	     FROM rhnSet
	    WHERE label = set_label_in
	      AND user_id = set_uid_in
	) loop
	    if rhn_server.system_service_level(server.element, 'provisioning') = 1 then
	    	perform rhn_server.set_custom_value(server.element, set_uid_in, key_label_in, value_in);
            i := i + 1;
	    end if;
	end loop;
    return i;
    end$$ language plpgsql;

    create or replace function bulk_snapshot_tag(
    	org_id_in in numeric,
        tagname_in in varchar,
	set_label_in in varchar,
	set_uid_in in numeric
    ) returns void
    as $$
    declare
        server record;
    	snapshot_id numeric;
    begin
        for server in (
           SELECT user_id, label, element, element_two
	     FROM rhnSet
	    WHERE label = set_label_in
	      AND user_id = set_uid_in
	    ) loop
	    if rhn_server.system_service_level(server.element, 'provisioning') = 1 then
	    	    select max(id) into snapshot_id
	    	    from rhnSnapshot
	    	    where server_id = server.element;

	    	    if snapshot_id is null then
		    	perform rhn_server.snapshot_server(server.element, 'tagging system:  ' || tagname_in);
			
			select max(id) into snapshot_id
			from rhnSnapshot
			where server_id = server.element;
		    end if;
		 
		-- now have a snapshot_id to work with...
		begin
		    perform rhn_server.tag_snapshot(snapshot_id, org_id_in, tagname_in);
		exception
		    when UNIQUE_VIOLATION
		    	then
			-- do nothing, be forgiving...
			null;
		end;
	    end if;
	end loop;    
    end$$ language plpgsql;

    create or replace function tag_delete(
    	server_id_in in numeric,
	tag_id_in in numeric
    ) returns void
    as $$
    declare
    	snapshots cursor is
		select	snapshot_id
		from	rhnSnapshotTag
		where	tag_id = tag_id_in;
	tag_id_tmp numeric;
    begin
    	select	id into tag_id_tmp
	from	rhnTag
	where	id = tag_id_in
	for update;

	delete
		from	rhnSnapshotTag
		where	server_id = server_id_in
			and tag_id = tag_id_in;
	for snapshot in snapshots loop
		return;
	end loop;
	delete
		from rhnTag
		where id = tag_id_in;
    end$$ language plpgsql;

    create or replace function tag_snapshot(
        snapshot_id_in in numeric,
	org_id_in in numeric,
	tagname_in in varchar
    ) returns void
    as $$
    begin
    	insert into rhnSnapshotTag (snapshot_id, server_id, tag_id)
	select snapshot_id_in, server_id, lookup_tag(org_id_in, tagname_in)
	from rhnSnapshot
	where id = snapshot_id_in;
    end$$ language plpgsql;

    create or replace function bulk_snapshot(
    	reason_in in varchar,
	set_label_in in varchar,
	set_uid_in in numeric
    ) returns void
    as $$
    declare
        server record;
    begin
        for server in (
           SELECT user_id, label, element, element_two
	     FROM rhnSet
	    WHERE label = set_label_in
	      AND user_id = set_uid_in
	    ) loop
    	    if rhn_server.system_service_level(server.element, 'provisioning') = 1 then
	    	perform rhn_server.snapshot_server(server.element, reason_in);
	    end if;
	end loop;
    end$$ language plpgsql;

    create or replace function snapshot_server(
    	server_id_in in numeric,
	reason_in in varchar
    ) returns void
    as $$
    declare
    	snapshot_id_v numeric;
	revisions cursor is
		select distinct
			cr.id
		from	rhnConfigRevision	cr,
			rhnConfigFileName	cfn,
			rhnConfigFile		cf,
			rhnConfigChannel	cc,
			rhnServerConfigChannel	scc
		where	1=1
			and scc.server_id = server_id_in
			and scc.config_channel_id = cc.id
			and cc.id = cf.config_channel_id
			and cf.id = cr.config_file_id
			and cr.id = cf.latest_config_revision_id
			and cf.config_file_name_id = cfn.id
			and cf.id = lookup_first_matching_cf(scc.server_id, cfn.path);
	locked integer;
    begin
    	select nextval('rhn_snapshot_id_seq') into snapshot_id_v;

	insert into rhnSnapshot (id, org_id, server_id, reason) (
		select	snapshot_id_v,
			s.org_id,
			server_id_in,
			reason_in
		from	rhnServer s
		where	s.id = server_id_in
	);
	insert into rhnSnapshotChannel (snapshot_id, channel_id) (
		select	snapshot_id_v, sc.channel_id
		from	rhnServerChannel sc
		where	sc.server_id = server_id_in
	);
	insert into rhnSnapshotServerGroup (snapshot_id, server_group_id) (
		select	snapshot_id_v, sgm.server_group_id
		from	rhnServerGroupMembers sgm
		where	sgm.server_id = server_id_in
	);
        locked := 0;
        <<iloop>>
        while true loop
            begin
                insert into rhnPackageNEVRA (id, name_id, evr_id, package_arch_id)
                select nextval('rhn_pkgnevra_id_seq'), sp.name_id, sp.evr_id, sp.package_arch_id
                from rhnServerPackage sp
                where sp.server_id = server_id_in
                        and not exists
                        (select 1
                                from rhnPackageNEVRA nevra
                                where nevra.name_id = sp.name_id
                                        and nevra.evr_id = sp.evr_id
                                        and (nevra.package_arch_id = sp.package_arch_id
                                            or (nevra.package_arch_id is null
                                                and sp.package_arch_id is null)));
                exit iloop;
            exception when unique_violation then
                if locked = 1 then
                    raise;
                else
                    lock table rhnPackageNEVRA in exclusive mode;
                    locked := 1;
                end if;
            end;
        end loop;
	insert into rhnSnapshotPackage (snapshot_id, nevra_id) (
                select distinct snapshot_id_v, nevra.id
                from    rhnServerPackage sp, rhnPackageNEVRA nevra
                where   sp.server_id = server_id_in
                        and nevra.name_id = sp.name_id
                        and nevra.evr_id = sp.evr_id
                        and (nevra.package_arch_id = sp.package_arch_id
                            or (nevra.package_arch_id is null
                                and sp.package_arch_id is null))
	);

	insert into rhnSnapshotConfigChannel ( snapshot_id, config_channel_id ) (
		select	snapshot_id_v, scc.config_channel_id
		from	rhnServerConfigChannel scc
		where	server_id = server_id_in
	);

	for revision in revisions loop
		insert into rhnSnapshotConfigRevision (
				snapshot_id, config_revision_id
			) values (
				snapshot_id_v, revision.id
			);
	end loop;
    end$$ language plpgsql;

    create or replace function remove_action(
    	server_id_in in numeric,
	action_id_in in numeric
    ) returns void
    as $$
    declare
    	-- this really wants "nulls last", but 8.1.7.3.0 sucks ass.
	-- instead, we make a local table that holds our
	-- list of ids with null prereqs.  There's surely a better way
	-- (an array instead of a table maybe?  who knows...)
	-- but I've got code to do this handy that I can look at ;)
    	chained_actions cursor is
                with recursive r(id, prerequisite) as (
			select	id, prerequisite
			from	rhnAction
			where id = action_id_in
		union all
			select	r1.id, r1.prerequisite
			from	rhnAction r1, r
			where r.id = r1.prerequisite
		)
		select * from r
		order by prerequisite desc;
	sessions cursor is
		select	s.id
		from	rhnKickstartSession s
		where	server_id_in in (s.old_server_id, s.new_server_id)
			and s.action_id = action_id_in
			and not exists (
				select	1
				from	rhnKickstartSessionState ss
				where	ss.id = s.state_id
					and ss.label in ('failed','complete')
			);
	chain_ends numeric[];
	i numeric;
	prereq numeric := 1;
    begin
	select	prerequisite
	into	prereq
	from	rhnAction
	where	id = action_id_in;

	if prereq is not null then
		perform rhn_exception.raise_exception('action_is_child');
	end if;

        chain_ends := '{}';
	i := 1;
	for action in chained_actions loop
		if action.prerequisite is null then
			chain_ends[i] := action.id;
			i := i + 1;
		else
			delete from rhnServerAction
				where server_id = server_id_in
				and action_id = action.id;
		end if;
	end loop;

	delete from rhnServerAction
		where server_id = server_id_in
		and action_id = any(chain_ends);

	for s in sessions loop
		update rhnKickstartSession
			set 	state_id = (
					select	id
					from	rhnKickstartSessionState
					where	label = 'failed'
				),
				action_id = null
			where	id = s.id;
		perform set_ks_session_history_message(s.id, 'failed', 'Kickstart cancelled due to action removal');
	end loop;
    end$$ language plpgsql;
   
    create or replace function check_user_access(server_id_in in numeric, user_id_in in numeric)
    returns numeric
    as $$
    declare
    	has_access numeric;
    begin
    	-- first check; if this returns no rows, then the server/user are in different orgs, and we bail
        select 1 into has_access
	  from rhnServer S,
	       web_contact wc
	 where wc.org_id = s.org_id
	   and s.id = server_id_in
	   and wc.id = user_id_in;

        if not found then
          return 0;
        end if;

	-- okay, so they're in the same org.  if we have an org admin, they get a free pass
    	if rhn_user.check_role(user_id_in, 'org_admin') = 1
	then
	    return 1;
	end if;
		   
    	select 1 into has_access
	  from rhnServerGroupMembers SGM,
	       rhnUserServerGroupPerms USG
	 where SGM.server_group_id = USG.server_group_id
	   and SGM.server_id = server_id_in
	   and USG.user_id = user_id_in;

        if not found then
          return 0;
        end if;
	   
	return 1;
    end$$ language plpgsql;

    -- *******************************************************************
    -- FUNCTION: can_server_consume_virt_slot
    -- Returns 1 if the server id is eligible to consume a virtual slot,
    --   else returns 0.
    -- Called by: insert_into_servergroup, delete_from_servergroup
    -- *******************************************************************
    create or replace function can_server_consume_virt_slot(server_id_in in numeric,
                                           group_type_in in varchar)
    returns numeric                                           
    as $$
    declare
        server_virt_slots cursor is
            select vi.VIRTUAL_SYSTEM_ID
            from
                rhnVirtualInstance vi
            where
                -- server id is a virtual instance
                vi.VIRTUAL_SYSTEM_ID = server_id_in
                -- server id's host is virt entitled
                and exists ( select 1
                     from rhnServerEntitlementView sev
                 where vi.HOST_SYSTEM_ID = sev.server_id
                 and sev.label in ('virtualization_host',
                                   'virtualization_host_platform') )
                -- server id's host also has the ent we want
                and exists ( select 1
                     from rhnServerEntitlementView sev2
                 where vi.HOST_SYSTEM_ID = sev2.server_id
                 and sev2.label = group_type_in );

    begin
        for server_virt_slot in server_virt_slots loop
            return 1;
        end loop;
        return 0;
    end$$ language plpgsql;


    create or replace function insert_into_servergroup (
		server_id_in in numeric,
		server_group_id_in in numeric
    ) returns void
    as $$
    declare
		used_slots numeric;
		max_slots numeric;
		org_id numeric;
		mgmt_available numeric;
		mgmt_upgrade numeric;
		mgmt_sgid numeric;
		prov_available numeric;
		prov_upgrade numeric;
		prov_sgid numeric;
		group_label varchar;
		group_type numeric;
	begin
		-- first, group_type = null, because it's easy...

		-- this will rowlock the servergroup we're trying to change;
		-- we probably need to lock the other one, but I think the chances
		-- of it being a real issue are very small for now...
		select	sg.group_type, sg.org_id, sg.current_members, sg.max_members
		into	group_type, org_id, used_slots, max_slots
		from	rhnServerGroup sg
		where	sg.id = server_group_id_in
		for update of sg;

		if group_type is null then
			if used_slots >= max_slots then
				perform rhn_exception.raise_exception('servergroup_max_members');
			end if;

			insert into rhnServerGroupMembers(
					server_id, server_group_id
				) values (
					server_id_in, server_group_id_in
				);
			update rhnServerGroup
				set current_members = current_members + 1
				where id = server_group_id_in;

			perform rhn_cache.update_perms_for_server_group(server_group_id_in);
			return;
		end if;

		-- now for group_type != null
		-- 
		select	label
		into	group_label
		from	rhnServerGroupType	sgt
		where	sgt.id = group_type;

		-- the naive easy path that gets hit most often and has to be quickest.
		if group_label in ('sw_mgr_entitled',
                           'enterprise_entitled',
                           'bootstrap_entitled',
                           'monitoring_entitled',
                           'provisioning_entitled',
                           'virtualization_host',
                           'virtualization_host_platform') then
			if used_slots >= max_slots and 
               (rhn_server.can_server_consume_virt_slot(server_id_in, group_label) != 1) 
               then
				perform rhn_exception.raise_exception('servergroup_max_members');
			end if;

			insert into rhnServerGroupMembers(
					server_id, server_group_id
				) values (
					server_id_in, server_group_id_in
				);

            -- Only update current members if the system in consuming a 
            -- physical slot.
            if rhn_server.can_server_consume_virt_slot(server_id_in, group_label) = 0 then
                update rhnServerGroup
                set current_members = current_members + 1
                where id = server_group_id_in;
            end if;                

			return;
		end if;
	end$$ language plpgsql;

	create or replace function insert_into_servergroup_maybe (
		server_id_in in numeric,
		server_group_id_in in numeric
	) returns numeric as $$ 
    declare
		retval numeric := 0;
		servergroups cursor is
			select	s.id	server_id,
					sg.id	server_group_id
			from	rhnServerGroup	sg,
					rhnServer		s
			where	s.id = server_id_in
				and sg.id = server_group_id_in
				and s.org_id = sg.org_id
				and not exists (
					select	1
					from	rhnServerGroupMembers sgm
					where	sgm.server_id = s.id
						and sgm.server_group_id = sg.id
				);
	begin
		for sgm in servergroups loop
			perform rhn_server.insert_into_servergroup(sgm.server_id, sgm.server_group_id);
			retval := retval + 1;
		end loop;
		return retval;
	end$$ language plpgsql;

	create or replace function insert_set_into_servergroup (
		server_group_id_in in numeric,
		user_id_in in numeric,
		set_label_in in varchar
	) returns void
        as $$
    declare
		servers cursor is
			select	st.element	id
			from	rhnSet		st
			where	st.user_id = user_id_in
				and st.label = set_label_in
				and exists (
					select	1
					from	rhnUserManagedServerGroups umsg
					where	umsg.server_group_id = server_group_id_in
						and umsg.user_id = user_id_in
					)
				and not exists (
					select	1
					from	rhnServerGroupMembers sgm
					where	sgm.server_id = st.element
						and sgm.server_group_id = server_group_id_in
				);
	begin
		for s in servers loop
			perform rhn_server.insert_into_servergroup(s.id, server_group_id_in);
		end loop;
	end$$ language plpgsql;
		
    create or replace function delete_from_servergroup (
    	server_id_in in numeric,
		server_group_id_in in numeric
    ) returns void
    as $$
    declare
        server_virt_groups cursor is
            select 1
            from rhnServerEntitlementVirtual sev
            where sev.server_id = server_id_in
            and sev.server_group_id = server_group_id_in;

		oid numeric;
		mgmt_sgid numeric;
		label varchar;
		group_type numeric;
	begin
			select	sg.group_type, sg.org_id
			into	group_type,	oid
			from	rhnServerGroupMembers	sgm,
					rhnServerGroup			sg
			where	sg.id = server_group_id_in
				and sg.id = sgm.server_group_id
				and sgm.server_id = server_id_in
			for update of sg;

			if not found then
				perform rhn_exception.raise_exception('server_not_in_group');
			end if;

		-- do group_type is null first
		if group_type is null then
			delete from rhnServerGroupMembers
				where server_group_id = server_group_id_in
				and	server_id = server_id_in;
			update rhnServerGroup
				set current_members = current_members - 1
				where id = server_group_id_in;
			perform rhn_cache.update_perms_for_server_group(server_group_id_in);
			return;
		end if;

		select	sgt.label
		into	label
		from	rhnServerGroupType sgt
		where	sgt.id = group_type;

		if label in ('sw_mgr_entitled',
                     'enterprise_entitled', 
                     'bootstrap_entitled',
                     'provisioning_entitled', 
                     'monitoring_entitled',
                     'virtualization_host',
                     'virtualization_host_platform') then

            -- Only update current members if the system is consuming
            -- a physical slot.
            for server_virt_group in server_virt_groups loop                
                delete from rhnServerGroupMembers
                where server_group_id = server_group_id_in
                and	server_id = server_id_in;
                return;
            end loop;                

            delete from rhnServerGroupMembers
            where server_group_id = server_group_id_in
            and	server_id = server_id_in;

            update rhnServerGroup
            set current_members = current_members - 1
            where id = server_group_id_in;

		end if;
	end$$ language plpgsql;

	create or replace function delete_set_from_servergroup (
		server_group_id_in in numeric,
		user_id_in in numeric,
		set_label_in in varchar
	) returns void
        as $$	
        declare
		servergroups cursor is
			select	sgm.server_id, sgm.server_group_id
			from	rhnSet st,
					rhnServerGroupMembers sgm
			where	sgm.server_group_id = server_group_id_in
				and st.user_id = user_id_in
				and st.label = set_label_in
				and sgm.server_id = st.element
				and exists (
					select	1
					from	rhnUserManagedServerGroups usgp
					where	usgp.server_group_id = server_group_id_in
						and usgp.user_id = user_id_in
				);
	begin
		for sgm in servergroups loop
			perform rhn_server.delete_from_servergroup(sgm.server_id, server_group_id_in);
		end loop;
	end$$ language plpgsql;

	create or replace function clear_servergroup (
		server_group_id_in in numeric
	) returns void
        as $$
        declare
		servers cursor is
			select	sgm.server_id	id
			from	rhnServerGroupMembers sgm
			where	sgm.server_group_id = server_group_id_in;
	begin
		for s in servers loop
			perform rhn_server.delete_from_servergroup(s.id, server_group_id_in);
		end loop;
	end$$ language plpgsql;

	create or replace function delete_from_org_servergroups (
		server_id_in in numeric
	) returns void
        as $$
        declare
		servergroups cursor is
			select	sgm.server_group_id id
			from	rhnServerGroup sg,
					rhnServerGroupMembers sgm
			where	sgm.server_id = server_id_in
				and sgm.server_group_id = sg.id
				and sg.group_type is null;
	begin
		for sg in servergroups loop
			perform rhn_server.delete_from_servergroup(server_id_in, sg.id);
		end loop;
	end$$ language plpgsql;

	create or replace function get_ip_address (
		server_id_in in numeric
	) returns varchar as $$
        declare
		interfaces cursor is
			select	ni.name as name, na4.address as address
			from	rhnServerNetInterface ni,
			        rhnServerNetAddress4 na4
			where	server_id = server_id_in
                and ni.id = na4.interface_id
				and na4.address != '127.0.0.1';
		addresses cursor is
			select	ipaddr ip_addr
			from	rhnServerNetwork
			where	server_id = server_id_in
				and ipaddr != '127.0.0.1';
	begin
		for addr in addresses loop
			return addr.ip_addr;
		end loop;
		for iface in interfaces loop
			return iface.address;
		end loop;
		return NULL;
	end$$ language plpgsql;

    create or replace function update_needed_cache(
        server_id_in in numeric
	) returns void as $$
    declare
      update_lock numeric;
    begin
      select id into update_lock from rhnServer where id = server_id_in for update;
      delete from rhnServerNeededCache
        where server_id = server_id_in;
      insert into rhnServerNeededCache
             (server_id, errata_id, package_id, channel_id)
        (select distinct sp.server_id, x.errata_id, p.id, x.channel_id
           FROM (SELECT sp_sp.server_id, sp_sp.name_id,
		        sp_sp.package_arch_id, max(sp_pe.evr) AS max_evr
                   FROM rhnServerPackage sp_sp
                   join rhnPackageEvr sp_pe ON sp_pe.id = sp_sp.evr_id
                  GROUP BY sp_sp.server_id, sp_sp.name_id, sp_sp.package_arch_id) sp
           join rhnPackage p ON p.name_id = sp.name_id
           join rhnPackageEvr pe ON pe.id = p.evr_id AND sp.max_evr < pe.evr
           join rhnPackageUpgradeArchCompat puac
	            ON puac.package_arch_id = sp.package_arch_id
		    AND puac.package_upgrade_arch_id = p.package_arch_id
           join rhnServerChannel sc ON sc.server_id = sp.server_id
           join rhnChannelPackage cp ON cp.package_id = p.id
	            AND cp.channel_id = sc.channel_id
           left join (SELECT ep.errata_id, ce.channel_id, ep.package_id
                        FROM rhnChannelErrata ce
                        join rhnErrataPackage ep
			         ON ep.errata_id = ce.errata_id
			join rhnServerChannel sc_sc
			         ON sc_sc.channel_id = ce.channel_id
		       WHERE sc_sc.server_id = server_id_in) x
             ON x.channel_id = sc.channel_id AND x.package_id = cp.package_id
          where sp.server_id = server_id_in);
	end$$ language plpgsql;
-- restore the original setting
update pg_settings set setting = overlay( setting placing '' from 1 for (length('rhn_server')+1) ) where name = 'search_path';
 07070100000AF0000081B400000000000000000000000167AE11140000019C000000000000000000000000000000000000006D00000000susemanager-schema/upgrade/susemanager-schema-2.1.51-to-susemanager-schema-3.0/1025-rhnPackageKey-EPEL-7.sql  -- EPEL 7
update rhnPackageKey set provider_id = lookup_package_provider('EPEL')
 where key_id = '6a2faea2352c64e5';

insert into rhnPackageKey (id, key_id, key_type_id, provider_id)
    (select sequence_nextval('rhn_pkey_id_seq'), '6a2faea2352c64e5', lookup_package_key_type('gpg'), lookup_package_provider('EPEL') from dual
     where 1 not in (select 1 from rhnPackageKey where key_id = '6a2faea2352c64e5'));
07070100000AF1000081B400000000000000000000000167AE11140000066F000000000000000000000000000000000000007500000000susemanager-schema/upgrade/susemanager-schema-2.1.51-to-susemanager-schema-3.0/2001-rhnPackageKey-Spacewalk-2014.sql  update rhnPackageKey set provider_id = lookup_package_provider('Spacewalk')
 where key_id = '41605346066e5810';

insert into rhnPackageKey (id, key_id, key_type_id, provider_id)
    (select sequence_nextval('rhn_pkey_id_seq'), '41605346066e5810', lookup_package_key_type('gpg'), lookup_package_provider('Spacewalk') from dual
     where not exists (select 1 from rhnPackageKey where key_id = '41605346066e5810'));

update rhnPackageKey set provider_id = lookup_package_provider('Fedora')
 where key_id = '32474cf834ec9cba';

insert into rhnPackageKey (id, key_id, key_type_id, provider_id)
    (select sequence_nextval('rhn_pkey_id_seq'), '32474cf834ec9cba', lookup_package_key_type('gpg'), lookup_package_provider('Fedora') from dual
     where not exists (select 1 from rhnPackageKey where key_id = '32474cf834ec9cba'));

update rhnPackageKey set provider_id = lookup_package_provider('Fedora')
 where key_id = 'b4bb871c873529b8';

insert into rhnPackageKey (id, key_id, key_type_id, provider_id)
    (select sequence_nextval('rhn_pkey_id_seq'), 'b4bb871c873529b8', lookup_package_key_type('gpg'), lookup_package_provider('Fedora') from dual
     where not exists (select 1 from rhnPackageKey where key_id = 'b4bb871c873529b8'));

update rhnPackageKey set provider_id = lookup_package_provider('Spacewalk')
 where key_id = 'dcc981cdb8002de1';

insert into rhnPackageKey (id, key_id, key_type_id, provider_id)
    (select sequence_nextval('rhn_pkey_id_seq'), 'dcc981cdb8002de1', lookup_package_key_type('gpg'), lookup_package_provider('Spacewalk') from dual
     where not exists (select 1 from rhnPackageKey where key_id = 'dcc981cdb8002de1'));
 07070100000AF2000081B400000000000000000000000167AE111400000C79000000000000000000000000000000000000007600000000susemanager-schema/upgrade/susemanager-schema-2.1.51-to-susemanager-schema-3.0/2001-rhnServerGroupOverview-errata.sql --
-- Copyright (c) 2008--2015 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
CREATE OR REPLACE VIEW rhnServerGroupOverview (
         ORG_ID, SECURITY_ERRATA, BUG_ERRATA, ENHANCEMENT_ERRATA, GROUP_ID, GROUP_NAME, GROUP_ADMINS, SERVER_COUNT, MODIFIED, MAX_MEMBERS
)
AS
  SELECT SG.org_id,
         (SELECT COUNT(distinct E.id)
            FROM rhnErrata E,
                 rhnServerNeededErrataCache SNEC,
                 rhnServerGroupMembers SGM
           WHERE E.advisory_type = 'Security Advisory'
                 and SNEC.errata_id = e.id
                 and SNEC.server_id = sgm.server_id
                 and sgm.server_group_id = sg.id
                 AND EXISTS ( SELECT 1
                              FROM rhnServerFeaturesView SFV
                              WHERE SFV.server_id = SGM.server_id
                                    AND SFV.label = 'ftr_system_grouping')),
         (SELECT COUNT(distinct E.id)
            FROM rhnErrata E,
                 rhnServerNeededErrataCache SNEC,
                 rhnServerGroupMembers SGM
           WHERE E.advisory_type = 'Bug Fix Advisory'
                 and SNEC.errata_id = e.id
                 and SNEC.server_id = sgm.server_id
                 and sgm.server_group_id = sg.id
                 AND EXISTS ( SELECT 1
                              FROM rhnServerFeaturesView SFV
                              WHERE SFV.server_id = SGM.server_id
                                    AND SFV.label = 'ftr_system_grouping')),
         (SELECT COUNT(distinct E.id)
            FROM rhnErrata E,
                 rhnServerNeededErrataCache SNEC,
                 rhnServerGroupMembers SGM
           WHERE E.advisory_type = 'Product Enhancement Advisory'
                 and SNEC.errata_id = e.id
                 and SNEC.server_id = sgm.server_id
                 and sgm.server_group_id = sg.id
                 AND EXISTS ( SELECT 1
                              FROM rhnServerFeaturesView SFV
                              WHERE SFV.server_id = SGM.server_id
                                    AND SFV.label = 'ftr_system_grouping')),
         SG.id, SG.name,
         (SELECT COUNT(*) FROM rhnUserManagedServerGroups UMSG WHERE UMSG.server_group_id = SG.id),
         (SELECT COUNT(*) FROM rhnServerGroupMembers SGM WHERE SGM.server_group_id = SG.id
                 AND EXISTS ( SELECT 1
                              FROM rhnServerFeaturesView SFV
                              WHERE SFV.server_id = SGM.server_id
                                    AND SFV.label = 'ftr_system_grouping')),
         CURRENT_TIMESTAMP, MAX_MEMBERS
    FROM rhnServerGroup SG;

   07070100000AF3000081B400000000000000000000000167AE1114000004EE000000000000000000000000000000000000007900000000susemanager-schema/upgrade/susemanager-schema-2.1.51-to-susemanager-schema-3.0/2001-rhnServerOutdatedPackages-errata.sql  --
-- Copyright (c) 2008--2015 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--

CREATE OR REPLACE VIEW
rhnServerOutdatedPackages
(
    server_id,
    package_name_id,
    package_evr_id,    
    package_arch_id,
    package_nvre,
    errata_id,
    errata_advisory
)
AS
SELECT DISTINCT SNC.server_id,
       P.name_id,
       P.evr_id,
       P.package_arch_id,
       PN.name || '-' || evr_t_as_vre_simple( PE.evr ),
       E.id,
       E.advisory
  FROM rhnPackageName PN,
       rhnPackageEVR PE,
       rhnPackage P,
       rhnServerNeededCache SNC
         left outer join
        rhnErrata E
          on SNC.errata_id = E.id
 WHERE SNC.package_id = P.id
   AND P.name_id = PN.id
   AND P.evr_id = PE.id;

  07070100000AF4000081B400000000000000000000000167AE111400000030000000000000000000000000000000000000007400000000susemanager-schema/upgrade/susemanager-schema-2.1.51-to-susemanager-schema-3.0/2002-rhnPushDispatcher-drop-port.sql   ALTER TABLE rhnPushDispatcher DROP COLUMN port;
07070100000AF5000081B400000000000000000000000167AE11140001068E000000000000000000000000000000000000006D00000000susemanager-schema/upgrade/susemanager-schema-2.1.51-to-susemanager-schema-3.0/2003-rhn_entitlements.pkb.sql  --
-- Copyright (c) 2008--2015 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

-- create schema rhn_entitlements;

-- setup search_path so that these functions are created in appropriate schema.
update pg_settings set setting = 'rhn_entitlements,' || setting where name = 'search_path';

   create or replace function find_compatible_sg (
      server_id_in in numeric,
      type_label_in in varchar
   )
   returns numeric
as $$
    declare
      servergroups cursor for
         select sg.id
           from rhnServerGroupType             sgt,
                rhnServerGroup                 sg,
                rhnServer                     s,
                rhnServerServerGroupArchCompat ssgac
          where s.id = server_id_in
            and s.org_id = sg.org_id
            and sgt.label = type_label_in
            and sg.group_type = sgt.id
            and ssgac.server_group_type = sgt.id
            and ssgac.server_arch_id = s.server_arch_id
            and not exists (
                     select 1
                      from rhnServerGroupMembers sgm
                     where sgm.server_group_id = sg.id
                       and sgm.server_id = s.id);


   begin
      for servergroup in servergroups loop
         return servergroup.id;
      end loop;

      --no servergroup found
      return NULL;
   end$$
language plpgsql;

    -- *******************************************************************
    -- PROCEDURE: remove_org_entitlements
    --
    -- Removes both system entitlements and channel subscriptions
    -- that are currently assigned to an org and re-assigns to the
    -- master org (org_id = 1).
    --
    -- When we call this we expect everything to already be unentitled
    -- which shoul be handled by delete_org.
    --
    -- Called by: delete_org
    -- *******************************************************************
    create or replace function remove_org_entitlements (
        org_id_in numeric
    ) returns void
as $$
    declare
        system_ents cursor for
        select sg.id, sg.max_members, sg.group_type
        from rhnServerGroup sg
        where group_type is not null
          and org_id = org_id_in;

        channel_subs cursor for
        select pcf.channel_family_id, pcf.max_members
        from rhnChannelFamily cf,
             rhnPrivateChannelFamily pcf
        where pcf.org_id = org_id_in
          and pcf.channel_family_id = cf.id
          and cf.org_id is null;

    begin

        for system_ent in system_ents loop
            update rhnServerGroup
            set max_members = max_members + system_ent.max_members
            where org_id = 1
              and group_type = system_ent.group_type;
        end loop;

        update rhnServerGroup
        set max_members = 0
        where org_id = org_id_in;

        for channel_sub in channel_subs loop
            update rhnPrivateChannelFamily
            set max_members = max_members + channel_sub.max_members
            where org_id = 1
              and channel_family_id = channel_sub.channel_family_id;
        end loop;

        update rhnPrivateChannelFamily
        set max_members = 0
        where org_id = org_id_in;

    end$$
language plpgsql;

    create or replace function entitlement_grants_service (
        entitlement_in in varchar,
        service_level_in in varchar
    ) returns numeric
as $$
    begin
        if service_level_in = 'provisioning' then
            if entitlement_in = 'provisioning_entitled' then
                return 1;
            else
                return 0;
            end if;
        elsif service_level_in = 'management' then
            if entitlement_in = 'enterprise_entitled' then
                return 1;
            else
                return 0;
            end if;
        elsif service_level_in = 'monitoring' then
            if entitlement_in = 'monitoring_entitled' then
                return 1;
            end if;
        elsif service_level_in = 'updates' then
            return 1;
        else
            return 0;
        end if;
    end$$
language plpgsql;

    create or replace function lookup_entitlement_group (
        org_id_in in numeric,
        type_label_in in varchar default 'sw_mgr_entitled'
    ) returns numeric
as $$
    declare
        server_groups cursor for
            select  sg.id               server_group_id
            from    rhnServerGroup      sg,
                    rhnServerGroupType  sgt
            where   sgt.label = type_label_in
                and sgt.id = sg.group_type
                and sg.org_id = org_id_in;
    begin
        for sg in server_groups loop
            return sg.server_group_id;
        end loop;
        return rhn_entitlements.create_entitlement_group(
                org_id_in,
                type_label_in
            );
    end$$
language plpgsql;

    create or replace function create_entitlement_group (
        org_id_in in numeric,
        type_label_in in varchar default 'sw_mgr_entitled'
    ) returns numeric
as $$
    declare
        sg_id_val numeric;
    begin
        select  nextval('rhn_server_group_id_seq')
        into    sg_id_val;

        insert into rhnServerGroup (
                id, name, description, max_members, current_members,
                group_type, org_id
            ) (
                select  sg_id_val, sgt.label, sgt.label,
                        0, 0, sgt.id, org_id_in
                from    rhnServerGroupType sgt
                where   sgt.label = type_label_in
            );

        return sg_id_val;
    end$$
language plpgsql;

   create or replace function can_entitle_server (
      server_id_in   in numeric,
      type_label_in  in varchar
   )
   returns numeric
as $$
    declare
      addon_servergroups cursor (base_label_in varchar,
                                 addon_label_in varchar) for
         select
            addon_id
         from
            rhnSGTypeBaseAddonCompat
         where base_id = lookup_sg_type (base_label_in)
           and addon_id = lookup_sg_type (addon_label_in);

      previous_ent        varchar[];
      is_base_in          char   := 'N';
      is_base_current     char   := 'N';
      i                   numeric := 0;
      sgid                numeric := 0;

   begin

      previous_ent := rhn_entitlements.get_server_entitlement(server_id_in);

      select distinct is_base
      into is_base_in
      from rhnServerGroupType
      where label = type_label_in;

      if array_upper(previous_ent, 1) is null or array_upper(previous_ent, 1) = 0 then
         if is_base_in = 'Y' then
            sgid := rhn_entitlements.find_compatible_sg (server_id_in, type_label_in);
            if sgid is not null then
              -- rhn_server.insert_into_servergroup (server_id_in, sgid);
              return 1;
            else
              -- rhn_exception.raise_exception ('invalid_base_entitlement');
              return 0;
            end if;
         else
            -- rhn_exception.raise_exception ('invalid_base_entitlement');
            return 0;
         end if;

      -- there are previous ents, first make sure we're not trying to entitle a base ent
      elsif is_base_in = 'Y' then
         -- rhn_exception.raise_exception ('invalid_addon_entitlement');
         return 0;

      -- it must be an addon, so proceed with the entitlement
      else

         -- find the servers base ent
         is_base_current := 'N';
         i := 0;
         while is_base_current = 'N' and i < array_upper(previous_ent, 1)
         loop
            i := i + 1;
            select is_base
            into is_base_current
            from rhnServerGroupType
            where label = previous_ent[i];
         end loop;

         -- never found a base ent, that would be strange
         if is_base_current  = 'N' then
            -- rhn_exception.raise_exception ('invalid_base_entitlement');
            return 0;
         end if;

         -- this for loop verifies the validity of the addon path
         for addon_servergroup in addon_servergroups  (previous_ent[i], type_label_in) loop
            -- find an appropriate sgid for the addon and entitle the server
            sgid := rhn_entitlements.find_compatible_sg (server_id_in, type_label_in);
            if sgid is not null then
               -- rhn_server.insert_into_servergroup (server_id_in, sgid);
               return 1;
            else
               -- rhn_exception.raise_exception ('invalid_addon_entitlement');
               return 0;
            end if;
         end loop;

      end if;

      return 0;

   end$$
language plpgsql;

   create or replace function can_switch_base (
      server_id_in   in    integer,
      type_label_in  in    varchar
   )
   returns numeric
as $$
   declare
      type_label_in_is_base   char(1);
      sgid                    numeric;

   begin

       select is_base into type_label_in_is_base
       from rhnServerGroupType
       where label = type_label_in;

       if not found then
          perform rhn_exception.raise_exception ( 'invalid_entitlement' );
       end if;

      if type_label_in_is_base = 'N' then
         perform rhn_exception.raise_exception ( 'invalid_entitlement' );
      else
         sgid := rhn_entitlements.find_compatible_sg ( server_id_in,
                                                       type_label_in );
         if sgid is not null then
           return 1;
         else
           return 0;
         end if;
      end if;

   end$$
language plpgsql;

    create or replace function entitle_server (
        server_id_in in numeric,
        type_label_in in varchar default 'sw_mgr_entitled'
    ) returns void
as $$
    declare
      sgid  numeric := 0;
      is_virt numeric := 0;

    begin

      select 1 into is_virt
        from rhnServerEntitlementView
        where server_id = server_id_in
          and label in ('virtualization_host', 'virtualization_host_platform');

      if not found then
          is_virt := 0;
      end if;

      if is_virt = 0 and (type_label_in = 'virtualization_host' or
                          type_label_in = 'virtualization_host_platform') then

        is_virt := 1;
      end if;

      if rhn_entitlements.can_entitle_server(server_id_in,
                                             type_label_in) = 1 then
         sgid := rhn_entitlements.find_compatible_sg (server_id_in,
                                                      type_label_in);
         if sgid is not null then
            insert into rhnServerHistory ( id, server_id, summary, details )
            values ( nextval('rhn_event_id_seq'), server_id_in,
                     'added system entitlement ',
                      case type_label_in
                       when 'enterprise_entitled' then 'Management'
                       when 'bootstrap_entitled' then 'Bootstrap'
                       when 'sw_mgr_entitled' then 'Update'
                       when 'provisioning_entitled' then 'Provisioning'
                       when 'monitoring_entitled' then 'Monitoring'
                       when 'virtualization_host' then 'Virtualization'
                       when 'virtualization_host_platform' then
                            'Virtualization Platform' end  );

            perform rhn_server.insert_into_servergroup (server_id_in, sgid);

            if is_virt = 1 then
              perform rhn_entitlements.repoll_virt_guest_entitlements(server_id_in);
            end if;

         else
            perform rhn_exception.raise_exception ('no_available_server_group');
         end if;
      else
         perform rhn_exception.raise_exception ('invalid_entitlement');
      end if;
   end$$
language plpgsql;

    create or replace function remove_server_entitlement (
        server_id_in in numeric,
        type_label_in in varchar default 'sw_mgr_entitled',
        repoll_virt_guests in numeric default 1
    ) returns void
as $$
    declare
      group_id numeric;
      type_is_base char;
      is_virt numeric := 0;
    begin
      -- would be nice if there were a virt attribute of entitlement types, not have to specify 2 different ones...
        select 1 into is_virt
          from rhnServerEntitlementView
          where server_id = server_id_in
            and label in ('virtualization_host', 'virtualization_host_platform');
        if not found then
            is_virt := 0;
        end if;

        select  sg.id, sgt.is_base
        into group_id, type_is_base
        from    rhnServerGroupType sgt,
            rhnServerGroup sg,
                rhnServerGroupMembers sgm,
                rhnServer s
        where   s.id = server_id_in
            and s.id = sgm.server_id
            and sgm.server_group_id = sg.id
            and sg.org_id = s.org_id
            and sgt.label = type_label_in
            and sgt.id = sg.group_type;

        if not found then
          perform rhn_exception.raise_exception('invalid_server_group_member');
        end if;

      if ( type_is_base = 'Y' ) then
         -- unentitle_server should handle everything, don't really need to do anything else special here
         perform rhn_entitlements.unentitle_server ( server_id_in );
      else

         insert into rhnServerHistory ( id, server_id, summary, details )
         values ( nextval('rhn_event_id_seq'), server_id_in,
                  'removed system entitlement ',
                   case type_label_in
                    when 'enterprise_entitled' then 'Management'
                    when 'bootstrap_entitled' then 'Bootstrap'
                    when 'sw_mgr_entitled' then 'Update'
                    when 'provisioning_entitled' then 'Provisioning'
                    when 'monitoring_entitled' then 'Monitoring'
                    when 'virtualization_host' then 'Virtualization'
                    when 'virtualization_host_platform' then
                         'Virtualization Platforrm' end  );

         perform rhn_server.delete_from_servergroup(server_id_in, group_id);

         if is_virt = 1 and repoll_virt_guests = 1 then
           perform rhn_entitlements.repoll_virt_guest_entitlements(server_id_in);
         end if;
      end if;

    end$$
language plpgsql;

    create or replace function unentitle_server (
        server_id_in in numeric
    ) returns void
as $$
    declare
      servergroups cursor for
         select distinct sgt.label, sg.id server_group_id
         from  rhnServerGroupType sgt,
               rhnServerGroup sg,
               rhnServer s,
               rhnServerGroupMembers sgm
         where s.id = server_id_in
            and s.org_id = sg.org_id
            and sg.group_type = sgt.id
            and sgm.server_group_id = sg.id
            and sgm.server_id = s.id;

     is_virt numeric := 0;

   begin

      select 1 into is_virt
        from rhnServerEntitlementView
        where server_id = server_id_in
         and label in ('virtualization_host', 'virtualization_host_platform');

      if not found then
          is_virt := 0;
      end if;

      for servergroup in servergroups loop

         insert into rhnServerHistory ( id, server_id, summary, details )
         values ( nextval('rhn_event_id_seq'), server_id_in,
                  'removed system entitlement ',
                   case servergroup.label
                    when 'enterprise_entitled' then 'Management'
                    when 'bootstrap_entitled' then 'Bootstrap'
                    when 'sw_mgr_entitled' then 'Update'
                    when 'provisioning_entitled' then 'Provisioning'
                    when 'monitoring_entitled' then 'Monitoring'
                    when 'virtualization_host' then 'Virtualization'
                    when 'virtualization_host_platform' then
                         'Virtualization Platform' end  );

         perform rhn_server.delete_from_servergroup(server_id_in,
                                            servergroup.server_group_id );
      end loop;

      if is_virt = 1 then
        perform rhn_entitlements.repoll_virt_guest_entitlements(server_id_in);
      end if;

   end$$
language plpgsql;


    -- *******************************************************************
    -- PROCEDURE: repoll_virt_guest_entitlements
    --
    --   Whenever we add/remove a virtualization_host* entitlement from
    --   a host, we can call this procedure to update what type of slots
    --   the guests are consuming.
    --
    --   If you're removing the entitlement, it's
    --   possible the guests will become unentitled if you don't have enough
    --   physical slots to cover them.
    --
    --   If you're adding the entitlement, you end up freeing up physical
    --   slots for other systems.
    --
    -- *******************************************************************
    create or replace function repoll_virt_guest_entitlements(
        server_id_in in numeric
    ) returns void
as $$
    declare
        -- All channel families associated with the guests of server_id_in
        families cursor for
            select distinct cfs.channel_family_id
            from
                rhnChannelFamilyServers cfs,
                rhnVirtualInstance vi
            where
                vi.host_system_id = server_id_in
                and vi.virtual_system_id = cfs.server_id;

        -- All of server group types associated with the guests of
        -- server_id_in
        group_types cursor for
            select distinct sg.group_type, sgt.label, sg.org_id
            from
                rhnServerGroupType sgt,
                rhnServerGroup sg,
                rhnServerGroupMembers sgm,
                rhnVirtualInstance vi
            where
                vi.host_system_id = server_id_in
                and vi.virtual_system_id = sgm.server_id
                and sgm.server_group_id = sg.id
                and sg.group_type = sgt.id;

        -- Virtual servers from a certain family belonging to a specific
        -- host that are consuming physical channel slots over the limit.
        virt_servers_cfam cursor(family_id_in numeric, quantity_in numeric) for
                select vi.virtual_system_id
                from
                    rhnChannelFamilyMembers cfm,
                    rhnServerChannel sc,
                    rhnVirtualInstance vi
                where
                    vi.host_system_id = server_id_in
                    and vi.virtual_system_id = sc.server_id
                    and sc.channel_id = cfm.channel_id
                    and cfm.channel_family_id = family_id_in
                order by sc.modified desc
                limit quantity_in;

        -- Virtual servers from a certain family belonging to a specific
        -- host that are consuming physical system slots over the limit.
        virt_servers_sgt cursor(group_type_in numeric, quantity_in numeric) for
                select vi.virtual_system_id
                from
                    rhnServerGroup sg,
                    rhnServerGroupMembers sgm,
                    rhnVirtualInstance vi
                where
                    vi.host_system_id = server_id_in
                    and vi.virtual_system_id = sgm.server_id
                    and sgm.server_group_id = sg.id
                    and sg.group_type = group_type_in
                order by sgm.modified desc
                limit quantity_in;

        -- Get the orgs of Virtual guests
        -- Since they may belong to different orgs
        virt_guest_orgs cursor for
                select  distinct (s.org_id)
                from rhnServer s
                    inner join  rhnVirtualInstance vi on vi.virtual_system_id = s.id
                where
                    vi.host_system_id = server_id_in
                    and s.org_id <> (select s1.org_id from rhnServer s1 where s1.id = vi.host_system_id) ;

        org_id_val numeric;
        max_members_val numeric;
        max_flex_val numeric;
        current_members_calc numeric;
        sg_id numeric;
        is_virt numeric := 0;
        free_slots numeric := 0;
    begin
          select 1 into is_virt
                from rhnServerEntitlementView
           where server_id = server_id_in
                 and label in ('virtualization_host', 'virtualization_host_platform');

      if not found then
          is_virt := 0;
      end if;

        select org_id
        into org_id_val
        from rhnServer
        where id = server_id_in;

        -- deal w/ channel entitlements first ...
        for family in families loop
            if is_virt = 0 then
            -- if the host_server does not have virt
            --- find all possible flex slots
            -- and set each of the flex eligible guests to Y
                select GREATEST(sfc.max_members - sfc.current_members, 0)
                  into free_slots
                  from rhnServerFveCapable sfc
                 where sfc.channel_family_id = family.channel_family_id;
                UPDATE rhnServerChannel sc set is_fve = 'Y'
                where sc.server_id in (
                            select vi.virtual_system_id
                            from rhnServerFveCapable sfc
                                inner join rhnVirtualInstance vi on vi.virtual_system_id = sfc.server_id
                            where vi.host_system_id = server_id_in
                                  and sfc.channel_family_id = family.channel_family_id
                              order by vi.modified desc
                            limit free_slots
                );
            else
            -- if the host_server has virt
            -- set all its flex guests to N
                UPDATE rhnServerChannel sc set is_fve = 'N'
                where
                    sc.channel_id in (select cfm.channel_id from rhnChannelFamilyMembers cfm
                                      where cfm.CHANNEL_FAMILY_ID = family.channel_family_id)
                    and sc.is_fve = 'Y'
                    and sc.server_id in
                            (select vi.virtual_system_id  from rhnVirtualInstance vi
                                    where vi.host_system_id = server_id_in);
            end if;

            -- get the current (physical) members of the family
            current_members_calc :=
                rhn_channel.channel_family_current_members(family.channel_family_id,
                                                           org_id_val); -- fixed transposed args

            -- get the max members of the family
            select max_members
            into max_members_val
            from rhnPrivateChannelFamily
            where channel_family_id = family.channel_family_id
            and org_id = org_id_val;

            select fve_max_members
            into max_flex_val
            from rhnPrivateChannelFamily
            where channel_family_id = family.channel_family_id
            and org_id = org_id_val;

            if current_members_calc > max_members_val then
                -- A virtualization_host* ent must have been removed, so we'll
                -- unsubscribe guests from the host first.

                -- hm, i don't think max_members - current_members_calc yielding a negative number
                -- will work w/ rownum, swaping 'em in the body of this if...
                for virt_server in virt_servers_cfam(family.channel_family_id,
                                current_members_calc - max_members_val) loop

                    perform rhn_channel.unsubscribe_server_from_family(
                                virt_server.virtual_system_id,
                                family.channel_family_id);
                end loop;

                -- if we're still over the limit, which would be odd,
                -- just prune the group to max_members
                --
                -- er... wouldn't we actually have to refresh the values of
                -- current_members_calc and max_members_val to actually ever
                -- *skip this??
                if current_members_calc > max_members_val then
                    -- argh, transposed again?!
                    perform rhn_entitlements.set_family_count(org_id_val,
                                     family.channel_family_id,
                                     max_members_val, max_flex_val);
                    --TODO calculate this correctly
                end if;

           end if;

            -- update current_members for the family.  This will set the value
            -- to reflect adding/removing the entitlement.
            --
            -- what's the difference of doing this vs the unavoidable set_family_count above?
            perform rhn_channel.update_family_counts(family.channel_family_id,
                                             org_id_val);

            -- It is possible that the guests belong  to a different org than the host
            -- so we are going to update the family counts in the guests orgs also
            for org in virt_guest_orgs loop
                    perform rhn_channel.update_family_counts(family.channel_family_id,
                                             org.org_id);
            end loop;
        end loop;

        for a_group_type in group_types loop
          -- get the current *physical* members of the system entitlement type for the org...
          --
          -- unlike channel families, it appears the standard rhnServerGroup.max_members represents
          -- *physical* slots, vs physical+virt ... boy that's confusing...

          select max_members, id
            into max_members_val, sg_id
            from rhnServerGroup
            where group_type = a_group_type.group_type
            and org_id = a_group_type.org_id;


      select count(sep.server_id) into current_members_calc
            from rhnServerEntitlementPhysical sep
           where sep.server_group_id = sg_id
             and sep.server_group_type_id = a_group_type.group_type;

          if current_members_calc > max_members_val then
            -- A virtualization_host* ent must have been removed, and we're over the limit, so unsubscribe guests
            for virt_server in virt_servers_sgt(a_group_type.group_type,
                                                current_members_calc - max_members_val) loop
              perform rhn_entitlements.remove_server_entitlement(virt_server.virtual_system_id, a_group_type.label);

              -- decrement current_members_calc, we'll use it to reset current_members for the group at the end...
              current_members_calc := current_members_calc - 1;
            end loop;

          end if;

          update rhnServerGroup set current_members = current_members_calc
           where org_id = a_group_type.org_id
             and group_type = a_group_type.group_type;

          -- I think that's all the house-keeping we have to do...
        end loop;

    end$$
language plpgsql;

    create or replace function get_server_entitlement (
        server_id_in in numeric
    ) returns varchar[]
as $$
    declare
        server_groups cursor for
            select  sgt.label
            from    rhnServerGroupType      sgt,
                    rhnServerGroup          sg,
                    rhnServerGroupMembers   sgm
            where   1=1
                and sgm.server_id = server_id_in
                and sg.id = sgm.server_group_id
                and sgt.id = sg.group_type
                and sgt.label in (
                    'sw_mgr_entitled','enterprise_entitled', 'bootstrap_entitled',
                    'provisioning_entitled', 'nonlinux_entitled',
                    'monitoring_entitled', 'virtualization_host',
                                        'virtualization_host_platform'
                    );

         ent_array varchar[];

    begin

      ent_array := '{}';

      for sg in server_groups loop
         ent_array := ent_array || sg.label;
      end loop;

      return ent_array;

    end$$
language plpgsql;

    -- this desperately needs to be table driven.
    create or replace function modify_org_service (
        org_id_in in numeric,
        service_label_in in varchar,
        enable_in in char
    ) returns void
as $$
    declare
        roles_to_process varchar[];
        roles cursor(role_label_in varchar) for
            select  label, id
            from    rhnUserGroupType
            where   label = role_label_in;
        org_roles cursor(role_label_in varchar) for
            select  1
            from    rhnUserGroup ug,
                    rhnUserGroupType ugt
            where   ugt.label = role_label_in
                and ug.org_id = org_id_in
                and ugt.id = ug.group_type;

        ents_to_process varchar[];
        ents cursor(ent_label_in varchar) for
            select  label, id
            from    rhnOrgEntitlementType
            where   label = ent_label_in;
        org_ents cursor(ent_label_in varchar) for
            select  1
            from    rhnOrgEntitlements oe,
                    rhnOrgEntitlementType oet
            where   oet.label = ent_label_in
                and oe.org_id = org_id_in
                and oet.id = oe.entitlement_id;
        create_row char(1);
    begin
        ents_to_process := '{}';
        roles_to_process := '{}';
        -- a bit kludgy, but only for 3.4 really.  Certainly no
        -- worse than the old code...
        if service_label_in = 'enterprise' or
           service_label_in = 'management' then
            ents_to_process := array_append(ents_to_process, 'sw_mgr_enterprise');

            roles_to_process := array_append(roles_to_process, 'org_admin');

            roles_to_process := array_append(roles_to_process, 'system_group_admin');

            roles_to_process := array_append(roles_to_process, 'activation_key_admin');
        elsif service_label_in = 'provisioning' then
            ents_to_process := array_append(ents_to_process, 'rhn_provisioning');

            roles_to_process := array_append(roles_to_process, 'system_group_admin');

            roles_to_process := array_append(roles_to_process, 'activation_key_admin');

            roles_to_process := array_append(roles_to_process, 'config_admin');
            -- another nasty special case...
            if enable_in = 'Y' then
                ents_to_process := array_append(ents_to_process, 'sw_mgr_enterprise');
            end if;
        elsif service_label_in = 'monitoring' then
            ents_to_process := array_append(ents_to_process, 'rhn_monitor');

            roles_to_process := array_append(roles_to_process, 'monitoring_admin');
        elsif service_label_in = 'virtualization' then
            ents_to_process := array_append(ents_to_process, 'rhn_virtualization');

            roles_to_process := array_append(roles_to_process, 'config_admin');
        elsif service_label_in = 'virtualization_platform' then
            ents_to_process := array_append(ents_to_process, 'rhn_virtualization_platform');
            roles_to_process := array_append(roles_to_process, 'config_admin');
    elsif service_label_in = 'nonlinux' then
            ents_to_process := array_append(ents_to_process, 'rhn_nonlinux');
            roles_to_process := array_append(roles_to_process, 'config_admin');
        end if;

        if enable_in = 'Y' then
            for i in 1..array_upper(ents_to_process, 1) loop
                for ent in ents(ents_to_process[i]) loop
                    create_row := 'Y';
                    for oe in org_ents(ent.label) loop
                        create_row := 'N';
                    end loop;
                    if create_row = 'Y' then
                        insert into rhnOrgEntitlements(org_id, entitlement_id)
                            values (org_id_in, ent.id);
                    end if;
                end loop;
            end loop;
            for i in 1..array_upper(roles_to_process, 1) loop
                for role in roles(roles_to_process[i]) loop
                    create_row := 'Y';
                    for o_r in org_roles(role.label) loop
                        create_row := 'N';
                    end loop;
                    if create_row = 'Y' then
                        insert into rhnUserGroup(
                                id, name, description, current_members,
                                group_type, org_id
                            ) (
                                select  nextval('rhn_user_group_id_seq'),
                                        ugt.name || 's',
                                        ugt.name || 's for Org ' ||
                                            o.name || ' ('|| o.id ||')',
                                        0, ugt.id, o.id
                                from    rhnUserGroupType ugt,
                                        web_customer o
                                where   o.id = org_id_in
                                    and ugt.id = role.id
                            );
                    end if;
                end loop;
            end loop;
        else
            for i in 1..coalesce(array_upper(ents_to_process, 1), 0) loop
                for ent in ents(ents_to_process[i]) loop
                    delete from rhnOrgEntitlements
                     where org_id = org_id_in
                       and entitlement_id = ent.id;
                end loop;
            end loop;
        end if;
    end$$
language plpgsql;

    create or replace function set_customer_enterprise (
        customer_id_in in numeric
    ) returns void
as $$
    begin
        perform rhn_entitlements.modify_org_service(customer_id_in, 'enterprise', 'Y');
    end$$
language plpgsql;

    create or replace function set_customer_provisioning (
        customer_id_in in numeric
    ) returns void
as $$
    begin
        perform rhn_entitlements.modify_org_service(customer_id_in, 'provisioning', 'Y');
    end$$
language plpgsql;

    create or replace function set_customer_monitoring (
        customer_id_in in numeric
    ) returns void
as $$
    begin
        perform rhn_entitlements.modify_org_service(customer_id_in, 'monitoring', 'Y');
    end$$
language plpgsql;

    create or replace function set_customer_nonlinux (
        customer_id_in in numeric
    ) returns void
as $$
    begin
        perform rhn_entitlements.modify_org_service(customer_id_in, 'nonlinux', 'Y');
    end$$
language plpgsql;

    create or replace function unset_customer_enterprise (
        customer_id_in in numeric
    ) returns void
as $$
    begin
        perform rhn_entitlements.modify_org_service(customer_id_in, 'enterprise', 'N');
    end$$
language plpgsql;

    create or replace function unset_customer_provisioning (
        customer_id_in in numeric
    ) returns void
as $$
    begin
        perform rhn_entitlements.modify_org_service(customer_id_in, 'provisioning', 'N');
    end$$
language plpgsql;

    create or replace function unset_customer_monitoring (
        customer_id_in in numeric
    ) returns void
as $$
    begin
        perform rhn_entitlements.modify_org_service(customer_id_in, 'monitoring', 'N');
    end$$
language plpgsql;

    create or replace function unset_customer_nonlinux (
        customer_id_in in numeric
    ) returns void
as $$
    begin
        perform rhn_entitlements.modify_org_service(customer_id_in, 'nonlinux', 'N');
    end$$
language plpgsql;

    -- *******************************************************************
    -- PROCEDURE: prune_group
    -- Unsubscribes servers consuming physical slots that over the org's
    --   limit.
    -- Called by: set_server_group_count, repoll_virt_guest_entitlements
    -- *******************************************************************
    create or replace function prune_group (
        group_id_in in numeric,
        quantity_in in numeric,
        update_family_countsYN in numeric default 1
    ) returns void
as $$
    declare
        sgrecord record;
      type_is_base char;
    begin
            update      rhnServerGroup
                set     max_members = quantity_in
                where   id = group_id_in;

            for sgrecord in (
		   select  server_id, server_group_id, sgt.id as group_type_id, sgt.label
		    from    rhnServerGroupType              sgt,
				    rhnServerGroup                  sg,
				    rhnServerGroupMembers   sgm
		    where   1=1
			    and sgm.server_group_id = group_id_in
			    and sgm.server_id in (
				    select  sep.server_id
				    from
					rhnServerEntitlementPhysical sep
				    where
					sep.server_group_id = group_id_in
				    order by sep.modified asc
				    offset quantity_in
				)
			    and sgm.server_group_id = sg.id
			    and sg.group_type = sgt.id
	    ) loop
                perform rhn_entitlements.remove_server_entitlement(sgrecord.server_id, sgrecord.label);

            select is_base
            into type_is_base
            from rhnServerGroupType sgt
            where sgt.id = sgrecord.group_type_id;

            -- if we're removing a base ent, then be sure to
            -- remove the server's channel subscriptions.
            if ( type_is_base = 'Y' ) then
                   perform rhn_channel.clear_subscriptions(sgrecord.server_id, 0, update_family_countsYN);
            end if;

            end loop;
    end$$
language plpgsql;

    -- *******************************************************************
    -- PROCEDURE: assign_system_entitlement
    --
    -- Moves system entitlements from from_org_id_in to to_org_id_in.
    -- Can raise not_enough_entitlements_in_base_org if from_org_id_in
    -- does not have enough entitlements to cover the move.
    -- Takes care of unentitling systems if necessary by calling
    -- set_server_group_count
    -- *******************************************************************
    create or replace function assign_system_entitlement(
        group_label_in in varchar,
        from_org_id_in in numeric,
        to_org_id_in in numeric,
        quantity_in in numeric
    ) returns void
as $$
    declare
        prev_ent_count numeric;
    to_org_prev_ent_count numeric;
        new_ent_count numeric;
    new_quantity numeric;
        group_type numeric;
    begin

            select max_members
            into prev_ent_count
            from rhnServerGroupType sgt,
                 rhnServerGroup sg
            where sg.org_id = from_org_id_in
              and sg.group_type = sgt.id
              and sgt.label = group_label_in;

            if not found then
                perform rhn_exception.raise_exception(
                              'not_enough_entitlements_in_base_org');
            end if;

            select max_members
            into to_org_prev_ent_count
            from rhnServerGroupType sgt,
                 rhnServerGroup sg
            where sg.org_id = to_org_id_in
              and sg.group_type = sgt.id
              and sgt.label = group_label_in;

            if not found then
                to_org_prev_ent_count := 0;
            end if;

            select id
            into group_type
            from rhnServerGroupType
            where label = group_label_in;

            if not found then
                perform rhn_exception.raise_exception(
                              'invalid_server_group');
            end if;

        new_ent_count := prev_ent_count - quantity_in;

        if prev_ent_count > new_ent_count then
            new_quantity := to_org_prev_ent_count + quantity_in;
        end if;

        if new_ent_count < 0 then
            perform rhn_exception.raise_exception(
                          'not_enough_entitlements_in_base_org');
        end if;


        perform rhn_entitlements.set_server_group_count(from_org_id_in,
                                         group_type,
                                         new_ent_count);

        perform rhn_entitlements.set_server_group_count(to_org_id_in,
                                         group_type,
                                         new_quantity);

        -- Create or delete the entries in rhnOrgEntitlementType
        if group_label_in = 'enterprise_entitled' then
            if new_quantity > 0 then
                perform rhn_entitlements.set_customer_enterprise(to_org_id_in);
            else
                perform rhn_entitlements.unset_customer_enterprise(to_org_id_in);
            end if;
        end if;

        if group_label_in = 'provisioning_entitled' then
            if new_quantity > 0 then
                perform rhn_entitlements.set_customer_provisioning(to_org_id_in);
            else
                perform rhn_entitlements.unset_customer_provisioning(to_org_id_in);
            end if;
        end if;

        if group_label_in = 'monitoring_entitled' then
            if new_quantity > 0 then
                perform rhn_entitlements.set_customer_monitoring(to_org_id_in);
            else
                perform rhn_entitlements.unset_customer_monitoring(to_org_id_in);
            end if;
        end if;

    end$$
language plpgsql;

    -- *******************************************************************
    -- PROCEDURE: assign_channel_entitlement
    --
    -- Moves channel entitlements from from_org_id_in to to_org_id_in.
    -- Can raise not_enough_entitlements_in_base_org if from_org_id_in
    -- does not have enough entitlements to cover the move.
    -- Takes care of unentitling systems if necessary by calling
    -- set_family_count
    -- *******************************************************************
    create or replace function assign_channel_entitlement(
        channel_family_label_in in varchar,
        from_org_id_in in numeric,
        to_org_id_in in numeric,
        quantity_in in numeric,
        flex_in in numeric
    ) returns void
as $$
    declare
        from_org_prev_ent_count numeric;
        from_org_prev_ent_count_flex numeric;
        new_ent_count numeric;
        new_ent_count_flex numeric;
        to_org_prev_ent_count numeric;
        to_org_prev_ent_count_flex numeric;
        new_quantity numeric;
        new_flex numeric;
        cfam_id       numeric;
    begin

            select max_members
            into from_org_prev_ent_count
            from rhnChannelFamily cf,
                 rhnPrivateChannelFamily pcf
            where pcf.org_id = from_org_id_in
              and pcf.channel_family_id = cf.id
              and cf.label = channel_family_label_in;

            if not found then
                perform rhn_exception.raise_exception(
                              'not_enough_entitlements_in_base_org');
            end if;

            select max_members
            into to_org_prev_ent_count
            from rhnChannelFamily cf,
                 rhnPrivateChannelFamily pcf
            where pcf.org_id = to_org_id_in
              and pcf.channel_family_id = cf.id
              and cf.label = channel_family_label_in;

            if not found then
                to_org_prev_ent_count := 0;
            end if;

            select fve_max_members
            into from_org_prev_ent_count_flex
            from rhnChannelFamily cf,
                rhnPrivateChannelFamily pcf
            where pcf.org_id = from_org_id_in
              and pcf.channel_family_id = cf.id
              and cf.label = channel_family_label_in;

            if not found then
                perform rhn_exception.raise_exception(
                              'not_enough_flex_entitlements_in_base_org');
            end if;

            select fve_max_members
            into to_org_prev_ent_count_flex
            from rhnChannelFamily cf,
                 rhnPrivateChannelFamily pcf
            where pcf.org_id = to_org_id_in
              and pcf.channel_family_id = cf.id
              and cf.label = channel_family_label_in;

            if not found then
                to_org_prev_ent_count_flex := 0;
            end if;

            select id
            into cfam_id
            from rhnChannelFamily
            where label = channel_family_label_in;

            if not found then
                perform rhn_exception.raise_exception(
                              'invalid_channel_family');
            end if;

        new_ent_count := from_org_prev_ent_count - quantity_in;
        new_ent_count_flex := from_org_prev_ent_count_flex - flex_in;

        if from_org_prev_ent_count >= new_ent_count then
            new_quantity := to_org_prev_ent_count + quantity_in;
        end if;

        if from_org_prev_ent_count_flex >= new_ent_count_flex then
            new_flex := to_org_prev_ent_count_flex + flex_in;
        end if;

        if new_ent_count < 0 then
            perform rhn_exception.raise_exception(
                          'not_enough_entitlements_in_base_org');
        end if;

        if new_ent_count_flex < 0 then
            perform rhn_exception.raise_exception(
                          'not_enough_flex_entitlements_in_base_org');
        end if;



        perform rhn_entitlements.set_family_count(from_org_id_in,
                                          cfam_id,
                                          new_ent_count,
                                          new_ent_count_flex);

        perform rhn_entitlements.set_family_count(to_org_id_in,
                                          cfam_id,
                                          new_quantity,
                                          new_flex);

    end$$
language plpgsql;

    -- *******************************************************************
    -- PROCEDURE: activate_system_entitlement
    --
    -- Sets the values in rhnServerGroup for a given rhnServerGroupType.
    --
    -- Calls: set_server_group_count to update, prune, or create the group.
    -- Called by: the code that activates a satellite cert.
    --
    -- Raises not_enough_entitlements_in_base_org if all entitlements
    -- in the org are used so the free entitlements would not cover
    -- the difference when descreasing the number of entitlements.
    -- *******************************************************************
    create or replace function activate_system_entitlement(
        org_id_in in numeric,
        group_label_in in varchar,
        quantity_in in numeric
    ) returns void
as $$
    declare
        prev_ent_count numeric;
        prev_ent_count_sum numeric;
        group_type numeric;
    begin

        -- Fetch the current entitlement count for the org
        -- into prev_ent_count

            select current_members
            into prev_ent_count
            from rhnServerGroupType sgt,
                 rhnServerGroup sg
            where sg.group_type = sgt.id
              and sgt.label = group_label_in
              and sg.org_id = org_id_in;

            if not found then
                prev_ent_count := 0;
            end if;

            select id
            into group_type
            from rhnServerGroupType
            where label = group_label_in;

            if not found then
                perform rhn_exception.raise_exception(
                              'invalid_server_group');
            end if;

        -- If we're setting the total entitlemnt count to a lower value,
        -- and that value is less than the allocated count in this org,
        -- we need to raise an exception.
        if quantity_in < prev_ent_count then
            perform rhn_exception.raise_exception(
                          'not_enough_entitlements_in_base_org');
        else
            -- don't update family counts after every server
            -- will do bulk update afterwards
            perform rhn_entitlements.set_server_group_count(org_id_in,
                                             group_type,
                                             quantity_in,
                                             0);
            -- bulk update family counts
            perform rhn_channel.update_group_family_counts(group_label_in, org_id_in);
        end if;

    end$$
language plpgsql;

    -- *******************************************************************
    -- PROCEDURE: activate_channel_entitlement
    --
    -- Calls: set_family_count to update, prune, or create the family
    --        permission bucket.
    -- Called by: the code that activates a satellite cert.
    --
    -- Raises not_enough_entitlements_in_base_org if there are not enough
    -- entitlements in the org to cover the difference when you are
    -- descreasing the number of entitlements.
    --
    -- The backend code in Python is expected to do whatever arithmetics
    -- is needed.
    -- *******************************************************************
    create or replace function activate_channel_entitlement(
        org_id_in in numeric,
        channel_family_label_in in varchar,
        quantity_in in numeric,
        flex_in in numeric
    ) returns void
as $$
    declare
        prev_ent_count numeric;
        prev_flex_count numeric;
        prev_ent_count_sum numeric;
        cfam_id numeric;
        reduce_quantity numeric;
        total_flex_capable numeric;
        to_convert_reg cursor (channel_family_id_val numeric, org_id_in numeric, quantity numeric) for
                     select SC.server_id
                     from rhnServerChannel SC inner join
                          rhnServer S on S.id = SC.server_id
                     where
                         is_fve = 'Y'
                         and S.org_id = org_id_in
                         and SC.channel_id in
                         (select cfm.channel_id from rhnChannelFamilyMembers cfm
                             where cfm.CHANNEL_FAMILY_ID = channel_family_id_val)
                         limit quantity;
         to_convert_flex cursor (channel_family_id_val numeric, org_id_in numeric, quantity numeric) for
                   select server_id
                   from rhnServerFveCapable
                       where SERVER_ORG_ID = org_id_in and
                             channel_family_id = cfam_id
                       limit quantity;

    begin

        -- Fetch the current entitlement count for the org
        -- into prev_ent_count
            select current_members
            into prev_ent_count
            from rhnChannelFamily cf,
                 rhnPrivateChannelFamily pcf
            where pcf.org_id = org_id_in
              and pcf.channel_family_id = cf.id
              and cf.label = channel_family_label_in;

            if not found then
                prev_ent_count := 0;
            end if;

            select pcf.fve_current_members
            into prev_flex_count
            from rhnChannelFamily cf,
                 rhnPrivateChannelFamily pcf
            where pcf.org_id = org_id_in
              and pcf.channel_family_id = cf.id
              and cf.label = channel_family_label_in;

            if not found then
                prev_flex_count := 0;
            end if;

            select id
            into cfam_id
            from rhnChannelFamily
            where label = channel_family_label_in;

            if not found then
                perform rhn_exception.raise_exception(
                              'invalid_channel_family');
            end if;

        -- if there are too few flex entitlements
        if flex_in < prev_flex_count then
            -- and if the extra we need is less than or equal to our extra regular entitlements
            if prev_flex_count - flex_in <= quantity_in - prev_ent_count then
                   reduce_quantity := prev_flex_count - flex_in;
                   -- We need to convert some systems from flex guest to regular
                   for system in to_convert_reg(cfam_id, org_id_in, reduce_quantity) loop
                      --rhn_channel.convert_to_regular(system.server_id, cfam_id);
                      UPDATE rhnServerChannel sc set is_fve = 'N'
                           where sc.server_id = system.server_id
                                 and sc.channel_id in (select cfm.channel_id
                                                          from rhnChannelFamilyMembers cfm
                                                          where cfm.channel_family_id = cfam_id);
                   end loop;

                   --reset previous counts
                   prev_ent_count := prev_ent_count + reduce_quantity;
                   prev_flex_count := prev_flex_count - reduce_quantity;
            else
                perform rhn_exception.raise_exception(
                          'not_enough_flex_entitlements_in_base_org');
            end if;
        end if;

        -- if there are too few regular entitlements, and extra flex entitlements
        if quantity_in < prev_ent_count and prev_flex_count < flex_in then
                -- how many flex-capable systems (that aren't using flex) do we have
                select count(*)
                   into total_flex_capable
                   from rhnServerFveCapable
                       where SERVER_ORG_ID = org_id_in and
                             channel_family_id = cfam_id;
                -- if we have enough flex capable machines that is at least
                --   as many as what we are over on
                if total_flex_capable >= prev_ent_count - quantity_in then
                    reduce_quantity := prev_ent_count - quantity_in;
                    for system in to_convert_flex(cfam_id, org_id_in, reduce_quantity) loop
--                          rhn_channel.convert_to_fve(system.server_id, cfam_id);
                        UPDATE rhnServerChannel sc set is_fve = 'Y'
                           where sc.server_id = system.server_id
                                 and sc.channel_id in (select cfm.channel_id
                                                          from rhnChannelFamilyMembers cfm
                                                          where cfm.channel_family_id = cfam_id);
                    end loop;
                    prev_ent_count := prev_ent_count - reduce_quantity;
                    prev_flex_count := prev_flex_count + reduce_quantity;
                end if;
        end if;

        -- If we're setting the total entitlemnt count to a lower value,
        -- and that value is less than the count in that one org,
        -- we need to raise an exception.
        if quantity_in < prev_ent_count then
            perform rhn_exception.raise_exception(
                          'not_enough_entitlements_in_base_org');
        else
            -- even if we've manually converted systems to/from flex above
            -- set_family_count should call update_family_counts, to reset
            -- current used slots
            perform rhn_entitlements.set_family_count(org_id_in, cfam_id,
                                              quantity_in, flex_in);
        end if;

    end$$
language plpgsql;

    create or replace function set_server_group_count (
        customer_id_in in numeric,  -- customer_id
        group_type_in in numeric,   -- rhn[User|Server]GroupType.id
        quantity_in in numeric,      -- quantity
                update_family_countsYN in numeric default 1
    ) returns void
as $$
    declare
        group_id numeric;
        quantity numeric;
        wasfound boolean;
    begin
        quantity := quantity_in;
        if quantity is not null and quantity < 0 then
            quantity := 0;
        end if;

        select  rsg.id
        into    group_id
        from    rhnServerGroup rsg
        where   1=1
            and rsg.org_id = customer_id_in
            and rsg.group_type = group_type_in;

        -- preserve the not found status across the rhn_entitlements.prune_group invocation
        wasfound := true;
        if not found then
            wasfound := false;
        end if;

        perform rhn_entitlements.prune_group(
            group_id,
            quantity,
                        update_family_countsYN
        );

        if not wasfound then
            insert into rhnServerGroup (
                    id, name, description, max_members, current_members,
                    group_type, org_id, created, modified
                ) (
                    select  nextval('rhn_server_group_id_seq'), name, name,
                            quantity, 0, id, customer_id_in,
                            current_timestamp, current_timestamp
                    from    rhnServerGroupType
                    where   id = group_type_in
            );
        end if;

    end$$
language plpgsql;

    -- *******************************************************************
    -- PROCEDURE: prune_family
    -- Unsubscribes servers consuming physical slots from the channel family
    --   that are over the org's limit.
    -- Called by: set_family_count
    -- *******************************************************************
    create or replace function prune_family (
        customer_id_in in numeric,
        channel_family_id_in in numeric,
        quantity_in in numeric,
        flex_in in numeric
    ) returns void
as $$
    declare
        serverchannels cursor(tmp_quantity numeric, is_fve_in char) for
            select  sc.server_id,
                    sc.channel_id
            from    rhnServerChannel sc,
                    rhnChannelFamilyMembers cfm
            where   1=1
                and cfm.channel_family_id = channel_family_id_in
                and cfm.channel_id = sc.channel_id
                and server_id in (
                       select server_id from (
                            select  distinct rs.id as server_id
                            from
                                    rhnServerChannel        rsc,
                                    rhnChannelFamilyMembers rcfm,
                                    rhnServer               rs
                            where   1=1
                                and rs.org_id = customer_id_in
                                and rs.id = rsc.server_id
                                and rsc.channel_id = rcfm.channel_id
                                and rcfm.channel_family_id =  channel_family_id_in
                                and rsc.is_fve = is_fve_in
                                -- we only want to grab servers consuming
                                -- physical slots.
                                and exists (
                                    select 1
                                    from rhnChannelFamilyServerPhysical cfsp
                                    where cfsp.server_id = rs.id
                                    and cfsp.channel_family_id =
                                        channel_family_id_in
                                    )
                            ) Q
                        order by server_id asc
                        offset quantity_in
                        );
    begin
        -- if we get a null customer_id, this is completely bogus.
        if customer_id_in is null then
            return;
        end if;

        for sc in serverchannels(quantity_in, 'N') loop
            perform rhn_channel.unsubscribe_server(sc.server_id, sc.channel_id,
                                                   1, 1, 0, 0);
        end loop;

        for sc in serverchannels(flex_in, 'Y') loop
            perform rhn_channel.unsubscribe_server(sc.server_id, sc.channel_id,
                                                   1, 1, 0, 0);
        end loop;

        perform rhn_channel.update_family_counts(channel_family_id_in, customer_id_in);
    end$$
language plpgsql;

    create or replace function set_family_count (
        customer_id_in in numeric,      -- customer_id
        channel_family_id_in in numeric,    -- 246
        quantity_in in numeric,          -- 3
        flex_in in numeric
    ) returns void
as $$
    declare
        privperms cursor for
            select  1
            from    rhnPrivateChannelFamily
            where   org_id = customer_id_in
                and channel_family_id = channel_family_id_in;
        pubperms cursor for
            select  o.id org_id
            from    web_customer o,
                    rhnPublicChannelFamily pcf
            where   pcf.channel_family_id = channel_family_id_in;
        quantity numeric;
        done numeric := 0;
        flex numeric;
    begin
        quantity := quantity_in;
        if quantity is not null and quantity < 0 then
            quantity := 0;
        end if;
        flex := flex_in;
        if flex is not null and flex < 0 then
            flex := 0;
        end if;

        if customer_id_in is not null then
            for perm in privperms loop
                perform rhn_entitlements.prune_family(
                    customer_id_in,
                    channel_family_id_in,
                    quantity,
                    flex
                );

                if quantity is null and flex is null then
                    delete from rhnPrivateChannelFamily
                        where org_id = customer_id_in
                            and channel_family_id = channel_family_id_in;
                 else
                    update rhnPrivateChannelFamily
                        set max_members = quantity
                        where org_id = customer_id_in
                            and channel_family_id = channel_family_id_in;

                   update rhnPrivateChannelFamily
                        set fve_max_members = flex
                        where org_id = customer_id_in
                            and channel_family_id = channel_family_id_in;
                end if;
                return;
            end loop;

            insert into rhnPrivateChannelFamily (
                    channel_family_id, org_id, max_members, current_members, fve_max_members, fve_current_members
                ) values (
                    channel_family_id_in, customer_id_in, quantity, 0, flex, 0 );
            return;
        end if;

        for perm in pubperms loop
            if quantity = 0 then
                perform rhn_entitlements.prune_family(
                    perm.org_id,
                    channel_family_id_in,
                    quantity,
                    flex
                );
                if done = 0 then
                    delete from rhnPublicChannelFamily
                        where channel_family_id = channel_family_id_in;
                end if;
            end if;
            done := 1;
        end loop;
        -- if done's not 1, then we don't have any entitlements
        if done != 1 then
            insert into rhnPublicChannelFamily (
                    channel_family_id
                ) values (
                    channel_family_id_in
                );
        end if;
    end$$
language plpgsql;

    -- this expects quantity_in to be the number of available slots, not the
    -- max_members of the server group.  If you give it too many, it'll fail
    -- and raise servergroup_max_members.
    -- We should NEVER run this unless we're SURE that we won't
    -- be violating the max.
    create or replace function entitle_last_modified_servers (
        customer_id_in in numeric,  -- customer_id
        type_label_in in varchar,   -- 'enterprise_entitled'
        quantity_in in numeric      -- 3
    ) returns void
as $$
    declare
        -- find the servers that aren't currently in slots
        servers cursor(cid_in numeric, quant_in numeric) for
                                    select  rs.id as server_id
                                    from    rhnServer rs
                                    where   1=1
                                        and rs.org_id = cid_in
                                        and not exists (
                                            select  1
                                            from    rhnServerGroup sg,
                                                    rhnServerGroupMembers rsgm
                                            where   rsgm.server_id = rs.id
                                                and rsgm.server_group_id = sg.id
                                                and sg.group_type is not null
                                        )
                                        and not exists (
                                            select 1
                                            from rhnVirtualInstance vi
                                            where vi.virtual_system_id =
                                                  rs.id
                                        )
                                    order by modified desc
                                    limit quant_in;
    begin
        for server in servers(customer_id_in, quantity_in) loop
            perform rhn_entitlements.entitle_server(server.server_id, type_label_in);
        end loop;
    end$$
language plpgsql;

    create or replace function subscribe_newest_servers (
        customer_id_in in numeric
    ) returns void
as $$
    declare
        -- find servers without base channels
        servers cursor(cid_in numeric) for
            select  s.id
            from    rhnServer           s
            where   1=1
                and s.org_id = cid_in
                and not exists (
                        select 1
                        from    rhnChannel          c,
                                rhnServerChannel    sc
                        where   sc.server_id = s.id
                            and sc.channel_id = c.id
                            and c.parent_channel is null
                    )
                and not exists (
                        select 1
                        from rhnVirtualInstance vi
                        where vi.virtual_system_id = s.id
                    )
            order by s.modified desc;
        channel_id numeric;
    begin
        for server in servers(customer_id_in) loop
            channel_id := rhn_channel.guess_server_base(server.id);
            if channel_id is not null then
                begin
                    perform rhn_channel.subscribe_server(server.id, channel_id);
                -- exception is really channel_family_no_subscriptions
                exception
                    when others then
                        null;
                end;
            end if;
        end loop;
    end$$
language plpgsql;


-- restore the original setting
update pg_settings set setting = overlay( setting placing '' from 1 for (length('rhn_entitlements')+1) ) where name = 'search_path';
  07070100000AF6000081B400000000000000000000000167AE111400000258000000000000000000000000000000000000007B00000000susemanager-schema/upgrade/susemanager-schema-2.1.51-to-susemanager-schema-3.0/2004-remove_monitoring_taskomatic_tasks.sql    delete from rhnTaskoRun where template_id in
       (select ttemp.id
	  from rhnTaskoTemplate ttemp,
	       rhnTaskoTask ttask
	 where ttemp.task_id = ttask.id
	   and ttask.name = 'cleanup-timeseries-data');

delete from rhnTaskoTemplate where task_id in (SELECT id FROM rhnTaskoTask WHERE name='cleanup-timeseries-data');
update rhnTaskoTemplate set ordering=0 where bunch_id in (SELECT id FROM rhnTaskoBunch WHERE name='cleanup-data-bunch') and task_id in (SELECT id FROM rhnTaskoTask WHERE name='cleanup-packagechangelog-data');

delete from rhnTaskoTask where name = 'cleanup-timeseries-data';
07070100000AF7000081B400000000000000000000000167AE111400000044000000000000000000000000000000000000006F00000000susemanager-schema/upgrade/susemanager-schema-2.1.51-to-susemanager-schema-3.0/2005-rhnContentSource-label.sql    
ALTER TABLE rhnContentSource ALTER COLUMN label TYPE VARCHAR(128);
07070100000AF8000081B400000000000000000000000167AE1114000006FF000000000000000000000000000000000000007300000000susemanager-schema/upgrade/susemanager-schema-2.1.51-to-susemanager-schema-3.0/2006-queue_server-no_duplicates.sql    -- retrieved from ./1241128047/984a347f2afbd47756e90584364799dd670b62db/schema/spacewalk/oracle/procs/queue_server.sql
--
-- Copyright (c) 2008--2015 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--

-- the next two views are basically the same.  the first, though, has an outer join to
-- the errata stuff, in case there are packages the server needs that haven't been
-- errata'd (ie, the fringe case)


CREATE OR REPLACE FUNCTION
queue_server(server_id_in IN NUMERIC, immediate_in IN NUMERIC DEFAULT 1)
RETURNS VOID
AS
$$
DECLARE
    org_id_tmp NUMERIC;
BEGIN
    IF immediate_in > 0
    THEN
          PERFORM rhn_server.update_needed_cache(server_id_in);
    ELSE
          SELECT org_id INTO STRICT org_id_tmp
          FROM rhnServer WHERE id = server_id_in;

          INSERT
            INTO rhnTaskQueue
                 (org_id, task_name, task_data)
          SELECT org_id_tmp,
                 'update_server_errata_cache',
                 server_id_in
          WHERE NOT EXISTS
            (SELECT 1 FROM rhnTaskQueue
               WHERE org_id = org_id_tmp
               AND task_name = 'update_server_errata_cache'
               AND task_data = server_id_in
            );
    END IF;
END;
$$ LANGUAGE plpgsql;
 07070100000AF9000081B400000000000000000000000167AE11140000BBC3000000000000000000000000000000000000007E00000000susemanager-schema/upgrade/susemanager-schema-2.1.51-to-susemanager-schema-3.0/2007-rhn_channel-update_needed_cache-async.sql --
-- Copyright (c) 2008--2015 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--

-- create schema rhn_channel;

--update pg_setting
update pg_settings set setting = 'rhn_channel,' || setting where name = 'search_path';

    create or replace function obtain_read_lock(channel_family_id_in in numeric, org_id_in in numeric)
    returns void as $$
    declare
        read_lock timestamptz;
    begin
        select created into read_lock
          from rhnPrivateChannelFamily
         where channel_family_id = channel_family_id_in and org_id = org_id_in
           for update;
    end$$ language plpgsql;

    -- this "emulates" cursor server_base_subscriptions defined in oracle/rhn_channel.pks
    create or replace function server_base_subscriptions(server_id_in NUMERIC)
    returns boolean as $$
    begin
      return exists(SELECT C.id FROM rhnChannel C, rhnServerChannel SC
		    WHERE C.id = SC.channel_id
		      AND SC.server_id = server_id_in
		      AND C.parent_channel IS NULL);
    end$$ language plpgsql;

    -- this "emulates" cursor server_base_subscriptions defined in oracle/rhn_channel.pks
    create or replace function check_server_subscription(server_id_in NUMERIC, channel_id_in NUMERIC)
    returns boolean as $$
    begin
      return exists(SELECT channel_id FROM rhnServerChannel WHERE server_id = server_id_in AND channel_id = channel_id_in);
    end$$ language plpgsql;


    CREATE OR REPLACE FUNCTION subscribe_server(server_id_in IN NUMERIC, channel_id_in NUMERIC, immediate_in NUMERIC default 1, user_id_in in numeric default null, recalcfamily_in NUMERIC default 1) returns void
    AS $$
    declare
        channel_parent_val      rhnChannel.parent_channel%TYPE;
        parent_subscribed       BOOLEAN;
        server_has_base_chan    BOOLEAN;
        server_already_in_chan  BOOLEAN;
        channel_family_id_val   NUMERIC;
        server_org_id_val       NUMERIC;
        available_subscriptions NUMERIC;
        available_fve_subs      numeric;
        consenting_user         NUMERIC;
        allowed                 numeric;
        is_fve_char             char(1) := 'N';
    BEGIN
        if user_id_in is not null then
            allowed := rhn_channel.user_role_check(channel_id_in, user_id_in, 'subscribe');
        else
            allowed := 1;
        end if;

        if allowed = 0 then
            perform rhn_exception.raise_exception('no_subscribe_permissions');
        end if;


        SELECT parent_channel INTO channel_parent_val FROM rhnChannel WHERE id = channel_id_in;

        IF channel_parent_val IS NOT NULL
        THEN    
            -- child channel; if attempting to cross-subscribe a child to the wrong base, silently ignore
            parent_subscribed := rhn_channel.check_server_subscription(server_id_in, channel_parent_val);
        
            IF NOT parent_subscribed
            THEN
                RETURN;
            END IF;
        ELSE
            -- base channel
            server_has_base_chan := rhn_channel.server_base_subscriptions(server_id_in);
            
            IF server_has_base_chan
            THEN
                perform rhn_exception.raise_exception('channel_server_one_base');
            END IF;
        END IF;

        server_already_in_chan := rhn_channel.check_server_subscription(server_id_in, channel_id_in);
    
        IF server_already_in_chan
        THEN
            RETURN;
        END IF;
        
        channel_family_id_val := rhn_channel.family_for_channel(channel_id_in);
        IF channel_family_id_val IS NULL
        THEN
            perform rhn_exception.raise_exception('channel_subscribe_no_family');
        END IF;

        --
        -- Use the org_id of the server only if the org_id of the channel = NULL.
        -- This is required for subscribing to shared channels.
        --
        SELECT COALESCE(org_id, (SELECT org_id FROM rhnServer WHERE id = server_id_in))
          INTO server_org_id_val
          FROM rhnChannel
         WHERE id = channel_id_in;
         
        begin
            perform rhn_channel.obtain_read_lock(channel_family_id_val, server_org_id_val);
        exception
            when no_data_found then
                perform rhn_exception.raise_exception('channel_family_no_subscriptions');
        end;

        available_subscriptions := rhn_channel.available_family_subscriptions(channel_family_id_val, server_org_id_val);
        available_fve_subs := rhn_channel.available_fve_family_subs(channel_family_id_val, server_org_id_val);
        
        IF available_subscriptions IS NULL OR 
           available_subscriptions > 0 or
           rhn_channel.can_server_consume_virt_channl(server_id_in, channel_family_id_val) = 1 OR
           (available_fve_subs > 0 AND rhn_channel.can_server_consume_fve(server_id_in) = 1) OR
           rhn_channel.server_has_family_subscription(server_id_in, channel_family_id_val) > 0
        THEN
            if rhn_channel.can_server_consume_virt_channl(server_id_in, channel_family_id_val) = 0 AND available_fve_subs > 0 AND rhn_channel.can_server_consume_fve(server_id_in) = 1 THEN
                is_fve_char := 'Y';
            end if;

            insert into rhnServerHistory (id,server_id,summary,details) (
                select  nextval('rhn_event_id_seq'),
                        server_id_in,
                        'subscribed to channel ' || SUBSTR(c.label, 0, 106),
                        c.label
                from    rhnChannel c
                where   c.id = channel_id_in
            );

            INSERT INTO rhnServerChannel (server_id, channel_id, is_fve) VALUES (server_id_in, channel_id_in, is_fve_char);
			IF recalcfamily_in > 0
			THEN
                perform rhn_channel.update_family_counts(channel_family_id_val, server_org_id_val);
			END IF;

            perform queue_server(server_id_in, immediate_in);

            update rhnServer
               set channels_changed = current_timestamp
             where id = server_id_in;
        ELSE
            perform rhn_exception.raise_exception('channel_family_no_subscriptions');
        END IF;
            
    END$$ language plpgsql;



    create or replace function can_convert_to_fve(server_id_in IN NUMERIC, channel_family_id_val IN NUMERIC)
    RETURNS NUMERIC
    as $$
    declare
        fve_convertible_entries cursor for
        select 1  from
            rhnServerFveCapable cap
          where cap.server_id = server_id_in
                AND cap.channel_family_id = channel_family_id_val;
    BEGIN
        FOR entry IN fve_convertible_entries LOOP
            return 1;
        END LOOP;
        RETURN 0;
    END$$ language plpgsql;



    -- Converts server channel_family to use a flex entitlement
    create or replace function convert_to_fve(server_id_in IN NUMERIC, channel_family_id_val IN NUMERIC)
    returns void
    as $$
    declare
        available_fve_subs      NUMERIC;
        server_org_id_val       NUMERIC;
    BEGIN

        --
        -- Use the org_id of the server only if the org_id of the channel = NULL.
        -- This is required for subscribing to shared channels.
        --
        SELECT org_id
          INTO server_org_id_val
          FROM rhnServer
         WHERE id = server_id_in;


        perform rhn_channel.obtain_read_lock(channel_family_id_val, server_org_id_val);
        if not found then
                perform rhn_exception.raise_exception('channel_family_no_subscriptions');
        end if;
        IF (rhn_channel.can_convert_to_fve(server_id_in, channel_family_id_val ) = 0)
            THEN
                perform rhn_exception.raise_exception('server_cannot_convert_to_flex');
        END IF;

        available_fve_subs := rhn_channel.available_fve_family_subs(channel_family_id_val, server_org_id_val);

        IF (available_fve_subs > 0)
        THEN

            insert into rhnServerHistory (id,server_id,summary,details) (
                select  nextval('rhn_event_id_seq'),
                        server_id_in,
                        'converted to flex entitlement' || SUBSTR(cf.label, 0, 99),
                        cf.label
                from    rhnChannelFamily cf
                where   cf.id = channel_family_id_val
            );

            UPDATE rhnServerChannel sc set is_fve = 'Y'
                           where sc.server_id = server_id_in and
                                 sc.channel_id in
                                    (select cfm.channel_id from rhnChannelFamilyMembers cfm
                                                where cfm.CHANNEL_FAMILY_ID = channel_family_id_val);

            perform rhn_channel.update_family_counts(channel_family_id_val, server_org_id_val);
        ELSE
            perform rhn_exception.raise_exception('not_enough_flex_entitlements');
        END IF;

    END$$ language plpgsql;
    
    create or replace function can_server_consume_virt_channl(
        server_id_in in numeric,
        family_id_in in numeric )
    returns numeric
    as $$
    begin
      if exists(
            select 1
            from
                rhnChannelFamilyVirtSubLevel cfvsl,
                rhnSGTypeVirtSubLevel sgtvsl,
                rhnVirtualInstance vi
            where
                vi.virtual_system_id = server_id_in 
                and sgtvsl.virt_sub_level_id = cfvsl.virt_sub_level_id
                and cfvsl.channel_family_id = family_id_in
                and exists (
                    select 1
                    from rhnServerEntitlementView sev
                    where vi.host_system_id = sev.server_id
                    and sev.server_group_type_id = sgtvsl.server_group_type_id ))
      then
        return 1;
      else
        return 0;
      end if;
    end$$ language plpgsql;

    create or replace function can_server_consume_fve(server_id_in in numeric) returns numeric
    as $$
    declare
        vi_entries cursor for
            SELECT 1
              FROM rhnVirtualInstance vi
             WHERE vi.virtual_system_id = server_id_in;
        vi_count numeric;

    begin
        FOR vi_entry IN VI_ENTRIES LOOP
            return 1;
        END LOOP;
        RETURN 0;
    end$$ language plpgsql;

    create or replace function guess_server_base(
        server_id_in in numeric
    ) RETURNS numeric as $$
    declare
        server_cursor cursor for
            select s.server_arch_id, s.release, s.org_id
              from rhnServer s
             where s.id = server_id_in;
    -- Cursor that fetches all the possible base channels for a
    -- (server_arch_id, release, org_id) combination
        base_channel_cursor cursor(
                release_in varchar,
                server_arch_id_in numeric,
                org_id_in numeric
        ) for
                select distinct c.*
                from    rhnOrgDistChannelMap                       odcm,
                                rhnServerChannelArchCompat      scac,
                                rhnChannel                                      c
                where   c.parent_channel is null
                        and c.id = odcm.channel_id
                        and c.channel_arch_id = odcm.channel_arch_id
                        and odcm.release = release_in
                        and odcm.for_org_id = org_id_in
                        and scac.server_arch_id = server_arch_id_in
                        and scac.channel_arch_id = c.channel_arch_id;

    begin
        for s in server_cursor loop
            for channel in base_channel_cursor(s.release,
                s.server_arch_id, s.org_id) 
            loop
                return channel.id;
            end loop;
        end loop;
        -- Server not found, or no base channel applies to it
        return null;
    end$$ language plpgsql;

    -- Private function
    create or replace function normalize_server_arch(server_arch_in in varchar)
    returns varchar
    as $$
    declare
        suffix VARCHAR(128) := '-redhat-linux';
    begin
        if server_arch_in is NULL then
            return NULL;
        end if;
        if position('-' IN server_arch_in) > 0
        then
            -- Suffix already present
            return server_arch_in;
        end if;
        return server_arch_in || suffix;
    end$$ language plpgsql;

    --
    -- Raises: 
    --   server_arch_not_found
    --   no_subscribe_permissions
    create or replace function base_channel_for_release_arch(
        release_in in varchar,
        server_arch_in in varchar,
        org_id_in in numeric default -1,
        user_id_in in numeric default null
    ) returns numeric as $$
    declare
        server_arch varchar(256) := rhn_channel.normalize_server_arch(server_arch_in);
        server_arch_id numeric;
    begin
        -- Look up the server arch
            select id
              into server_arch_id
              from rhnServerArch
             where label = server_arch;
            if not found then
                perform rhn_exception.raise_exception('server_arch_not_found');
            end if;

        return rhn_channel.base_channel_rel_archid(release_in, server_arch_id,
            org_id_in, user_id_in);
    end$$ language plpgsql;

    create or replace function base_channel_rel_archid(
        release_in in varchar,
        server_arch_id_in in numeric,
        org_id_in in numeric default -1,
        user_id_in in numeric default null
    ) returns numeric as $$
    declare
        denied_channel_id numeric := null;
        valid_org_id numeric := org_id_in;
        valid_user_id numeric := user_id_in;
        channel_subscribable numeric;
    -- Cursor that fetches all the possible base channels for a
    -- (server_arch_id, release, org_id) combination
        base_channel_cursor cursor(
                release_in varchar,
                server_arch_id_in numeric,
                org_id_in numeric
        ) for
                select distinct c.*
                from    rhnOrgDistChannelMap                       odcm,
                                rhnServerChannelArchCompat      scac,
                                rhnChannel                                      c
                where   c.parent_channel is null
                        and c.id = odcm.channel_id
                        and c.channel_arch_id = odcm.channel_arch_id
                        and odcm.release = release_in
                        and odcm.for_org_id = org_id_in
                        and scac.server_arch_id = server_arch_id_in
                        and scac.channel_arch_id = c.channel_arch_id;

    begin
        if org_id_in = -1 and user_id_in is not null then
            -- Get the org id from the user id

                select org_id
                  into valid_org_id
                  from web_contact
                 where id = user_id_in;

                if not found then
                    -- User doesn't exist
                    -- XXX Only list public stuff for now
                    valid_user_id := null;
                    valid_org_id := -1;
                end if;
        end if;

        for c in base_channel_cursor(release_in, server_arch_id_in, valid_org_id)
        loop
            -- This row is a possible match
            if valid_user_id is null then
                -- User ID not specified, so no user to channel permissions to
                -- check
                return c.id;
            end if;

            -- Check user to channel permissions
            select rhn_channel.loose_user_role_check(c.id, user_id_in, 'subscribe')
              into channel_subscribable;

            if channel_subscribable = 1 then
                return c.id;
            end if;
                
            -- Base channel exists, but is not subscribable; keep trying
            denied_channel_id := c.id;
        end loop;
        
        if denied_channel_id is not null then
            perform rhn_exception.raise_exception('no_subscribe_permissions');
        end if;
        -- No base channel applies
        return NULL;
    end$$ language plpgsql;

    CREATE OR REPLACE FUNCTION clear_subscriptions(server_id_in IN NUMERIC, deleting_server IN NUMERIC default 0,
                                update_family_countsYN IN NUMERIC default 1 ) returns void
    AS $$
    declare
        server_channels cursor(server_id_in numeric) for
                select  s.org_id, sc.channel_id, cfm.channel_family_id
                from    rhnServer s,
                        rhnServerChannel sc,
                        rhnChannelFamilyMembers cfm
                where   s.id = server_id_in
                        and s.id = sc.server_id
                        and sc.channel_id = cfm.channel_id
                order by cfm.channel_family_id;
        last_channel_family_id rhnChannelFamilyMembers.channel_family_id%type := -1;
        last_channel_org_id    rhnServer.org_id%type := -1;
    BEGIN
        for channel in server_channels(server_id_in)
        loop
                perform rhn_channel.unsubscribe_server(server_id_in, channel.channel_id, 1, 1, deleting_server, 0);
                if update_family_countsYN > 0
                    and channel.channel_family_id != last_channel_family_id then
                    -- update family counts only once
                    -- after all channels with same family has been fetched
                    if last_channel_family_id != -1 then
                        perform rhn_channel.update_family_counts(channel.channel_family_id, channel.org_id);
                    end if;
                    last_channel_family_id := channel.channel_family_id;
                    last_channel_org_id    := channel.org_id;
                end if;
        end loop;
        if update_family_countsYN > 0 and last_channel_family_id != -1 then
            -- update the last family fetched
            perform rhn_channel.update_family_counts(last_channel_family_id, last_channel_org_id);
        end if;
    END$$ language plpgsql;

    CREATE OR REPLACE FUNCTION unsubscribe_server(server_id_in IN NUMERIC, channel_id_in NUMERIC, immediate_in NUMERIC default 1, unsubscribe_children_in numeric default 0,
                                 deleting_server in numeric default 0,
                                 update_family_countsYN in numeric default 1) returns void
    AS $$
    declare
        channel_family_id_val   NUMERIC;
        server_org_id_val       NUMERIC;
        available_subscriptions NUMERIC; 
        server_already_in_chan  BOOLEAN;
        channel_family_is_proxy cursor(channel_family_id_in numeric) for
                select  1
                from    rhnChannelFamily
                where   id = channel_family_id_in
                    and label = 'rhn-proxy';
        channel_family_is_satellite cursor(channel_family_id_in numeric) for
                select  1
                from    rhnChannelFamily
                where   id = channel_family_id_in
                    and label = 'rhn-satellite';
        child record;
    BEGIN
        -- In PostgreSQL recursion with opened cursors is not allowed so we use
        -- FOR IN SELECT form which is ok.
        FOR child IN select  c.id
                from    rhnChannel                      c,
                                rhnServerChannel        sc
                where   1=1
                        and c.parent_channel = channel_id_in
                        and c.id = sc.channel_id
                        and sc.server_id = server_id_in
        LOOP
            if unsubscribe_children_in = 1 then
                perform rhn_channel.unsubscribe_server(server_id_in,
                                                       child.id,
                                                       immediate_in,
                                                       unsubscribe_children_in,
                                                       deleting_server,
                                                       update_family_countsYN);
            else
                perform rhn_exception.raise_exception('channel_unsubscribe_child_exists');
            end if;
        END LOOP;
        
        server_already_in_chan := rhn_channel.check_server_subscription(server_id_in, channel_id_in);
    
        IF NOT server_already_in_chan
        THEN
            RETURN;
        END IF;
        
   if deleting_server = 0 then 
      insert into rhnServerHistory (id,server_id,summary,details) (
          select  nextval('rhn_event_id_seq'),
                server_id_in,
             'unsubscribed from channel ' || SUBSTR(c.label, 0, 106),
             c.label
          from    rhnChannel c
          where   c.id = channel_id_in
      );
   end if;
        
   DELETE FROM rhnServerChannel WHERE server_id = server_id_in AND channel_id = channel_id_in;

   if deleting_server = 0 then 
        perform queue_server(server_id_in, immediate_in);

        update rhnServer
           set channels_changed = current_timestamp
         where id = server_id_in;
   end if;

        channel_family_id_val := rhn_channel.family_for_channel(channel_id_in);
        IF channel_family_id_val IS NULL
        THEN
            perform rhn_exception.raise_exception('channel_unsubscribe_no_family');
        END IF;

        for ignore in channel_family_is_satellite(channel_family_id_val) loop
                delete from rhnSatelliteInfo where server_id = server_id_in;
        end loop;

        for ignore in channel_family_is_proxy(channel_family_id_val) loop
                delete from rhnProxyInfo where server_id = server_id_in;
        end loop;
        SELECT org_id INTO server_org_id_val
          FROM rhnServer
         WHERE id = server_id_in;
         
        if update_family_countsYN = 1 then
           perform rhn_channel.update_family_counts(channel_family_id_val, server_org_id_val);
        end if;
    END$$ language plpgsql;

    CREATE OR REPLACE FUNCTION family_for_channel(channel_id_in IN NUMERIC)
    RETURNS NUMERIC
    AS $$
    declare
        channel_family_id_val NUMERIC;
    BEGIN
        SELECT channel_family_id INTO channel_family_id_val
          FROM rhnChannelFamilyMembers
         WHERE channel_id = channel_id_in;

        IF NOT FOUND THEN
          RETURN NULL;
        END IF;
         
        RETURN channel_family_id_val;
    END$$ language plpgsql;

    CREATE OR REPLACE FUNCTION available_family_subscriptions(channel_family_id_in IN NUMERIC, org_id_in IN NUMERIC)
    RETURNS NUMERIC
    AS $$
    declare
        cfp record;
        current_members_val NUMERIC;
        max_members_val     NUMERIC;
        found               NUMERIC;
    BEGIN
        for cfp in SELECT * FROM rhnOrgChannelFamilyPermissions
	    WHERE channel_family_id = channel_family_id_in
	      AND org_id = org_id_in
        LOOP
            found := 1;
            current_members_val := cfp.current_members;
            max_members_val := cfp.max_members;
        END LOOP;

        -- not found: either the channel fam doesn't have an entry in cfp, or the org doesn't have access to it.
        -- either way, there are no available subscriptions

        IF found IS NULL
        THEN
            RETURN 0;
        END IF;

        -- null max members?  in that case, pass it on; NULL means infinite
        IF max_members_val IS NULL
        THEN
            RETURN NULL;
        END IF;

        -- otherwise, return the delta
        RETURN max_members_val - current_members_val;
    END$$ language plpgsql;

    CREATE OR REPLACE FUNCTION available_fve_family_subs(channel_family_id_in IN NUMERIC, org_id_in IN NUMERIC)
    RETURNS NUMERIC
    AS $$
    declare
        cfp record;
        fve_current_members_val NUMERIC;
        fve_max_members_val     NUMERIC;
        found               NUMERIC;
    BEGIN
        for cfp in SELECT * FROM rhnOrgChannelFamilyPermissions
	    WHERE channel_family_id = channel_family_id_in
	      AND org_id = org_id_in
        LOOP
            found := 1;
            fve_current_members_val := cfp.fve_current_members;
            fve_max_members_val := cfp.fve_max_members;
        END LOOP;

        -- not found: either the channel fam doesn't have an entry in cfp, or the org doesn't have access to it.
        -- either way, there are no available subscriptions
        
        IF found IS NULL
        THEN
            RETURN 0;
        END IF;

        -- null max members?  in that case, pass it on; NULL means infinite                     
        IF fve_max_members_val IS NULL
        THEN
            RETURN NULL;
        END IF;

        -- otherwise, return the delta  
        RETURN fve_max_members_val - fve_current_members_val;
    END$$ language plpgsql;
    
    -- *******************************************************************
    -- FUNCTION: channel_family_current_members
    -- Calculates and returns the actual count of systems consuming
    --   physical channel subscriptions.
    -- Called by: update_family_counts 
    --            rhn_entitlements.repoll_virt_guest_entitlements
    -- *******************************************************************
    create or replace function channel_family_current_members(channel_family_id_in IN NUMERIC,
                                            org_id_in IN NUMERIC)
    returns numeric
    as $$
    declare
        current_members_count numeric := 0;
    begin
        select  count(distinct server_id)
        into    current_members_count
          from  rhnChannelFamilyServerPhysical cfsp
         where  cfsp.channel_family_id = channel_family_id_in
           and  cfsp.customer_id = org_id_in;
        return current_members_count;
    end$$ language plpgsql;


    create or replace function cfam_curr_fve_members(
        channel_family_id_in IN NUMERIC,
        org_id_in IN NUMERIC)
    returns numeric
    as $$
    declare
        current_members_count numeric := 0;

    begin
        select count(distinct sc.server_id)
          into current_members_count
          from rhnServerChannel sc,
               rhnChannelFamilyMembers cfm,
               rhnServer s
         where s.org_id = org_id_in
           and s.id = sc.server_id
           and cfm.channel_family_id = channel_family_id_in
           and cfm.channel_id = sc.channel_id
           and exists (
                select 1
                  from rhnChannelFamilyServerFve cfsp
                 where cfsp.CHANNEL_FAMILY_ID = channel_family_id_in
                   and cfsp.server_id = s.id
                );

        return current_members_count;
    end$$ language plpgsql;
    CREATE OR REPLACE FUNCTION update_family_counts(channel_family_id_in IN NUMERIC, 
                                   org_id_in IN NUMERIC) returns void
    AS $$
    BEGIN
        update rhnPrivateChannelFamily
           set current_members = rhn_channel.channel_family_current_members(channel_family_id_in, org_id_in),
               fve_current_members = rhn_channel.cfam_curr_fve_members(channel_family_id_in,org_id_in)
         where org_id = org_id_in
           and channel_family_id = channel_family_id_in;
    END$$ language plpgsql;
    
    create or replace function update_group_family_counts(group_label_in IN VARCHAR,
                                   org_id_in IN NUMERIC)
    returns void
    as $$
    declare
        i record;
    BEGIN
        FOR i IN (
                SELECT DISTINCT CFM.channel_family_id, SG.org_id
                 FROM rhnChannelFamilyMembers CFM
                 JOIN rhnServerChannel SC
                   ON SC.channel_id = CFM.channel_id
                 JOIN rhnServerGroupMembers SGM
                   ON SC.server_id = SGM.server_id
                 JOIN rhnServerGroup SG
                   ON SGM.server_group_id = SG.id
                 JOIN rhnServerGroupType SGT
                   ON SG.group_type = SGT.id
                WHERE SGT.label = group_label_in
                  AND SG.org_id = org_id_in
                  AND SGT.is_base = 'Y'
        ) LOOP
            perform rhn_channel.update_family_counts(i.channel_family_id, i.org_id);
        END LOOP;
    END$$ language plpgsql;

    CREATE OR REPLACE FUNCTION available_chan_subscriptions(channel_id_in IN NUMERIC, 
                                          org_id_in IN NUMERIC)
    RETURNS NUMERIC
    AS $$
    declare
            channel_family_id_val NUMERIC;
    BEGIN
        SELECT channel_family_id INTO STRICT channel_family_id_val
            FROM rhnChannelFamilyMembers
            WHERE channel_id = channel_id_in;
         
            RETURN rhn_channel.available_family_subscriptions(
                           channel_family_id_val, org_id_in);
    END$$ language plpgsql;

    CREATE OR REPLACE FUNCTION available_fve_chan_subs(channel_id_in IN NUMERIC,
                                          org_id_in IN NUMERIC)
    RETURNS NUMERIC
    AS $$
    declare
            channel_family_id_val NUMERIC;
    BEGIN
        SELECT channel_family_id INTO STRICT channel_family_id_val
            FROM rhnChannelFamilyMembers
            WHERE channel_id = channel_id_in;

            RETURN rhn_channel.available_fve_family_subs(
                           channel_family_id_val, org_id_in);
    END$$ language plpgsql;

    create or replace function unsubscribe_server_from_family(server_id_in in numeric, 
                                             channel_family_id_in in numeric)
    returns void
    as $$
    begin
        delete
        from    rhnServerChannel rsc
        where   rsc.server_id = server_id_in
            and channel_id in (
                select  rcfm.channel_id
                from    rhnChannelFamilyMembers rcfm
                where   rcfm.channel_family_id = channel_family_id_in);
    end$$ language plpgsql;

    create or replace function get_org_id(channel_id_in in numeric)
    returns numeric
    as $$
    declare
        org_id_out numeric;
    begin
        select org_id into strict org_id_out
            from rhnChannel
            where id = channel_id_in;
         
            return org_id_out;
    end$$ language plpgsql;
    
    create or replace function get_cfam_org_access(cfam_id_in in numeric, org_id_in in numeric)
    returns numeric
    as $$
    begin
      if exists(
                        select  1
                        from    rhnOrgChannelFamilyPermissions cfp
                        where   cfp.org_id = org_id_in
      ) then
                return 1;
      else
                return 0;
      end if;
    end$$ language plpgsql;

    create or replace function get_org_access(channel_id_in in numeric, org_id_in in numeric)
    returns integer
    as $$
    begin
        -- the idea: if we get past this query, 
        -- the org has access to the channel, else not
        if exists(
        select 1
          from rhnChannelFamilyMembers CFM,
               rhnOrgChannelFamilyPermissions CFP
         where cfp.org_id = org_id_in
           and CFM.channel_family_id = CFP.channel_family_id
           and CFM.channel_id = channel_id_in
           and (CFP.max_members > 0 or CFP.max_members is null or CFP.fve_max_members > 0 or CFP.fve_max_members is null or CFP.org_id = 1) )
        then
          return 1;
        else
          return 0;
        end if;
    end$$ language plpgsql;
    
    -- check if a user has a given role, or if such a role is inferrable
    -- returns NULL if OK, error message otherwise
    create or replace function user_role_check_debug(channel_id_in in numeric, 
                                   user_id_in in numeric, 
                                   role_in in varchar)
    returns varchar
    as $$
    declare
        org_id numeric;
    begin
        org_id := rhn_user.get_org_id(user_id_in);

        -- channel might be shared
        if role_in = 'subscribe' and
           rhn_channel.shared_user_role_check(channel_id_in, user_id_in, role_in) = 1 then
            return NULL;
        end if;
        
        if role_in = 'manage' and 
           COALESCE(rhn_channel.get_org_id(channel_id_in), -1) <> org_id then
               return 'channel_not_owned';
        end if;
        
        if role_in = 'subscribe' and 
           rhn_channel.get_org_access(channel_id_in, org_id) = 0 then
                return 'channel_not_available';
        end if;
        
        -- channel admins have all roles
        if rhn_user.check_role_implied(user_id_in, 'channel_admin') = 1 then
            return NULL;
        end if;

        -- the subscribe permission is inferred 
        -- UNLESS the not_globally_subscribable flag is set
        if role_in = 'subscribe'
        then
            if rhn_channel.org_channel_setting(channel_id_in, 
                       org_id,
                       'not_globally_subscribable') = 0 then
                return NULL;
            end if;
        end if;
        
        -- all other roles (manage right now) are explicitly granted    
        if rhn_channel.direct_user_role_check(channel_id_in,
                                              user_id_in, role_in) = 1 then
            return NULL;
        end if;
        return 'direct_permission';
    end$$ language plpgsql;
    
    -- same as above, but with 1/0 output; useful in views, etc
    create or replace function user_role_check(channel_id_in in numeric, user_id_in in numeric, role_in in varchar)
    returns numeric
    as $$
    begin
        if rhn_channel.user_role_check_debug(channel_id_in,
                                             user_id_in, role_in) is NULL then
            return 1;
        else
            return 0;
        end if;
    end$$ language plpgsql;

    --
    -- For multiorg phase II, this function simply checks to see if the user's
    -- has a trust relationship that includes this channel by id.
    --
    create or replace function shared_user_role_check(channel_id in numeric, user_id in numeric, role in varchar)
    returns numeric
    as $$
    declare
      n numeric;
      oid numeric;
    begin
      oid := rhn_user.get_org_id(user_id);
      select 1 into n
      from rhnSharedChannelView s
      where s.id = channel_id and s.org_trust_id = oid;

      if not found then
        return 0;
      end if;

      return 1;
    end$$ language plpgsql;

    -- same as above, but returns 1 if user_id_in is null
    -- This is useful in queries where user_id is not specified
    create or replace function loose_user_role_check(channel_id_in in numeric, user_id_in in numeric, role_in in varchar)
    returns numeric
    as $$
    begin
        if user_id_in is null then
            return 1;
        end if;
        return rhn_channel.user_role_check(channel_id_in, user_id_in, role_in);
    end$$ language plpgsql;
    
    -- directly checks the table, no inferred permissions
    create or replace function direct_user_role_check(channel_id_in in numeric, user_id_in in numeric, role_in in varchar)
    returns numeric
    as $$
    declare
        throwaway numeric;
    begin
        -- the idea: if we get past this query, the user has the role, else no
        select 1 into throwaway
          from rhnChannelPermissionRole CPR,
               rhnChannelPermission CP
         where CP.user_id = user_id_in
           and CP.channel_id = channel_id_in
           and CPR.label = role_in
           and CP.role_id = CPR.id;

      if not found then
        return 0;
      end if;
           
      return 1;
    end$$ language plpgsql;
    
    -- check if an org has a certain setting
    create or replace function org_channel_setting(channel_id_in in numeric, org_id_in in numeric, setting_in in varchar)
    returns numeric
    as $$
    declare
        throwaway numeric;
    begin
        -- the idea: if we get past this query, the org has the setting
        select 1 into throwaway
          from rhnOrgChannelSettingsType OCST,
               rhnOrgChannelSettings OCS
         where OCS.org_id = org_id_in
           and OCS.channel_id = channel_id_in
           and OCST.label = setting_in
           and OCS.setting_id = OCST.id;

      if not found then
        return 0;
      end if;

      return 1;
    end$$ language plpgsql;
    
    CREATE OR REPLACE FUNCTION channel_priority(channel_id_in IN numeric) 
    RETURNS numeric
    AS $$
    declare
         channel_name varchar(256);
         priority numeric;
         end_of_life_val timestamptz;
         org_id_val numeric;
    BEGIN

        select name, end_of_life, org_id
        into channel_name, end_of_life_val, org_id_val
        from rhnChannel
        where id = channel_id_in;

        if end_of_life_val is not null then
          return -400;
        end if;

        if channel_name like 'Red Hat Enterprise Linux%' or channel_name like 'RHEL%' then
          priority := 1000;
          if channel_name not like '%Beta%' then
            priority := priority + 1000;
          end if;

          priority := priority +
            case
              when channel_name like '%v. 5%' then 600
              when channel_name like '%v. 4%' then 500
              when channel_name like '%v. 3%' then 400
              when channel_name like '%v. 2%' then 300
              when channel_name like '%v. 1%' then 200
              else 0
            end;

          priority := priority +
            case
              when channel_name like 'Red Hat Enterprise Linux (v. 5%' then 60
              when (channel_name like '%AS%' and channel_name not like '%Extras%') then 50
              when (channel_name like '%ES%' and channel_name not like '%Extras%') then 40
              when (channel_name like '%WS%' and channel_name not like '%Extras%') then 30
              when (channel_name like '%Desktop%' and channel_name not like '%Extras%') then 20
              when channel_name like '%Extras%' then 10
              else 0
            end; 

          priority := priority +
            case
              when channel_name like '%)' then 5
              else 0
            end;

          priority := priority +
            case
              when channel_name like '%32-bit x86%' then 4
              when channel_name like '%64-bit Intel Itanium%' then 3
              when channel_name like '%64-bit AMD64/Intel EM64T%' then 2
              else 0
            end;
        elsif channel_name like 'Red Hat Desktop%' then
            priority := 900;

            if channel_name not like '%Beta%' then
               priority := priority + 50;
            end if;

          priority := priority +
            case
              when channel_name like '%v. 4%' then 40
              when channel_name like '%v. 3%' then 30
              when channel_name like '%v. 2%' then 20
              when channel_name like '%v. 1%' then 10
              else 0
            end;
            
          priority := priority +
            case
              when channel_name like '%32-bit x86%' then 4
              when channel_name like '%64-bit Intel Itanium%' then 3
              when channel_name like '%64-bit AMD64/Intel EM64T%' then 2
              else 0
            end;
         
        elsif org_id_val is not null then
          priority := 600;
        else
          priority := 500;
        end if;
      
      return -priority;

    end$$ language plpgsql;

    -- right now this only does the accounting changes; the cascade
    -- actually does the rhnServerChannel delete.
    create or replace function delete_server_channels(server_id_in in numeric) returns void
    as $$
    begin
        update  rhnPrivateChannelFamily
        set     current_members = current_members -1
        where   org_id in (
                        select  org_id
                        from    rhnServer
                        where   id = server_id_in
                )
                and channel_family_id in (
                        select  rcfm.channel_family_id
                        from    rhnChannelFamilyMembers rcfm,
                                rhnServerChannel rsc
                        where   rsc.server_id = server_id_in
                                and rsc.channel_id = rcfm.channel_id
                and not exists (
                    select 1
                    from
                        rhnChannelFamilyVirtSubLevel cfvsl,
                        rhnSGTypeVirtSubLevel sgtvsl,
                        rhnServerEntitlementView sev,
                        rhnVirtualInstance vi
                    where
                        -- system is a virtual instance
                        vi.virtual_system_id = server_id_in
                        and vi.host_system_id = sev.server_id
                        -- system's host has a virt ent
                        and sev.label in ('virtualization_host',
                                          'virtualization_host_platform')
                        and sev.server_group_type_id = 
                            sgtvsl.server_group_type_id
                        -- the host's virt ent grants a cf virt sub level
                        and sgtvsl.virt_sub_level_id = cfvsl.virt_sub_level_id
                        -- the cf is in that virt sub level
                        and cfvsl.channel_family_id = rcfm.channel_family_id
                    )
                );
    end$$ language plpgsql;

    -- this could certainly be optimized to do updates if needs be
    create or replace function refresh_newest_package(channel_id_in in numeric,
                                      caller_in in varchar default '(unknown)',
                                      package_name_id_in in numeric default null)
    returns void
    as $$
    -- procedure refreshes rows for name_id = package_name_id_in or
    -- all rows if package_name_id_in is null
    begin
        delete from rhnChannelNewestPackage
              where channel_id = channel_id_in
                and (package_name_id_in is null
                     or name_id = package_name_id_in);
        insert into rhnChannelNewestPackage
                (channel_id, name_id, evr_id, package_id, package_arch_id)
                (select channel_id,
                        name_id, evr_id,
                        package_id, package_arch_id
                   from rhnChannelNewestPackageView
                  where channel_id = channel_id_in
                    and (package_name_id_in is null
                         or name_id = package_name_id_in)
                );
        insert into rhnChannelNewestPackageAudit (channel_id, caller)
             values (channel_id_in, caller_in);
        update rhnChannel
           set last_modified = greatest(current_timestamp,
                                        last_modified + interval '1 second')
         where id = channel_id_in;
    end$$ language plpgsql;

   create or replace function update_channel ( channel_id_in in numeric, invalidate_ss in numeric default 0, 
                              date_to_use in timestamptz default current_timestamp ) returns void
   as $$
   declare
   channel_last_modified timestamptz;
   last_modified_value timestamptz;

   snapshots cursor for
   select  snapshot_id id
   from    rhnSnapshotChannel
   where   channel_id = channel_id_in;

   begin

      select last_modified
      into channel_last_modified
      from rhnChannel
      where id = channel_id_in;
  
      last_modified_value := date_to_use;

      if last_modified_value <= channel_last_modified then
          last_modified_value := last_modified_value + interval '1 second';
      end if;

      update rhnChannel set last_modified = last_modified_value
      where id = channel_id_in;

      if invalidate_ss = 1 then 
        for snapshot in snapshots loop
            update rhnSnapshot
            set invalid = lookup_snapshot_invalid_reason('channel_modified')
            where id = snapshot.id;
        end loop;
      end if;

   end$$ language plpgsql;

   create or replace function update_channels_by_package ( package_id_in in numeric, date_to_use in timestamptz default current_timestamp ) returns void
   as $$
   declare
   channels cursor for
   select channel_id
   from rhnChannelPackage
   where package_id = package_id_in
   order by channel_id;

   begin
      for channel in channels loop
         -- we want to invalidate the snapshot assocated with the channel when we
         -- do this b/c we know we've added or removed or packages
         perform rhn_channel.update_channel ( channel.channel_id, 1, date_to_use );
      end loop;
   end$$ language plpgsql;

   
   create or replace function update_channels_by_errata ( errata_id_in numeric, date_to_use in timestamptz default current_timestamp ) returns void
   as $$
   declare
   channels cursor for
   select channel_id
   from rhnChannelErrata
   where errata_id = errata_id_in
   order by channel_id;

   begin
      for channel in channels loop
         -- we won't invalidate snapshots, b/c just changing the errata associated with
         -- a channel shouldn't invalidate snapshots
         perform rhn_channel.update_channel ( channel.channel_id, 0, date_to_use );
      end loop;
   end$$ language plpgsql;

   create or replace function update_needed_cache(channel_id_in in numeric) returns void
   as $$
   declare
   server record;
   begin
      -- we intentionaly do a loop here instead of one huge select
      -- b/c we want to break update into smaller transaction to unblock other sessions
      -- querying rhnServerNeededCache
      for server in (
                select sc.server_id as id
                  from rhnServerChannel sc
                 where sc.channel_id = channel_id_in
                 order by id asc
      ) loop
         perform queue_server(server.id, 0); -- NOT IMMEDIATE
      end loop;
   end$$ language plpgsql;

    create or replace function set_comps(channel_id_in in numeric, path_in in varchar, timestamp_in in varchar) returns void
    as $$
    declare
    row record;
    begin
        for row in (
            select relative_filename, last_modified
            from rhnChannelComps
            where channel_id = channel_id_in
            ) loop
            if row.relative_filename = path_in
                and row.last_modified = to_timestamp(timestamp_in, 'YYYYMMDDHH24MISS') then
                return;
            end if;
        end loop;
        delete from rhnChannelComps
        where channel_id = channel_id_in;
        insert into rhnChannelComps (id, channel_id, relative_filename, last_modified, created, modified)
        values (sequence_nextval('rhn_channelcomps_id_seq'), channel_id_in, path_in, to_timestamp(timestamp_in, 'YYYYMMDDHH24MISS'), current_timestamp, current_timestamp);
    end$$ language plpgsql;

CREATE OR REPLACE FUNCTION server_has_family_subscription(server_id_in DECIMAL, 
                                                          channel_family_id_in DECIMAL) 
          RETURNS INTEGER AS $$
  DECLARE
    fam_entry RECORD;

  BEGIN
    FOR fam_entry IN SELECT DISTINCT cfm.channel_family_id
                       FROM rhnchannelfamilymembers AS cfm
                       JOIN rhnserverchannel AS sc ON sc.channel_id = cfm.channel_id
                      WHERE sc.server_id = server_id_in
                        AND cfm.channel_family_id = channel_family_id_in
    LOOP
      return 1;
    END LOOP;
    RETURN 0;
  END;
$$ LANGUAGE plpgsql;

-- restore the original setting
update pg_settings set setting = overlay( setting placing '' from 1 for (length('rhn_channel')+1) ) where name = 'search_path';
 07070100000AFA000081B400000000000000000000000167AE1114000000BB000000000000000000000000000000000000008200000000susemanager-schema/upgrade/susemanager-schema-2.1.51-to-susemanager-schema-3.0/2008-rhnOrgConfiguration-errata_emails_enabled.sql ALTER TABLE rhnOrgConfiguration ADD errata_emails_enabled CHAR(1)
    DEFAULT('Y') NOT NULL
    CONSTRAINT rhn_org_conf_errata_emails_chk
    CHECK (errata_emails_enabled in ('Y', 'N'));
 07070100000AFB000081B400000000000000000000000167AE111400000596000000000000000000000000000000000000006E00000000susemanager-schema/upgrade/susemanager-schema-2.1.51-to-susemanager-schema-3.0/2009-rhnOrgAdminManagement.sql --
-- Copyright (c) 2015 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

CREATE TABLE rhnOrgAdminManagement
(
    org_id                  NUMERIC NOT NULL
                                CONSTRAINT rhn_orgadm_mngt_fk
                                    REFERENCES web_customer (id)
                                    ON DELETE CASCADE,
    enabled                 CHAR(1)
                                DEFAULT ('Y') NOT NULL
                                CONSTRAINT rhn_orgadm_mngt_enabled_ck
                                    CHECK (enabled in ('Y', 'N')),
    created                 TIMESTAMPTZ
                                DEFAULT (current_timestamp) NOT NULL,
    modified                TIMESTAMPTZ
                                DEFAULT (current_timestamp) NOT NULL
)

;

CREATE UNIQUE INDEX rhn_orgadm_mngt_org_id
    on rhnOrgAdminManagement (org_id)
        ;
  07070100000AFC000081B400000000000000000000000167AE11140000004A000000000000000000000000000000000000007300000000susemanager-schema/upgrade/susemanager-schema-2.1.51-to-susemanager-schema-3.0/2010-rhnOrgAdminManagement-data.sql    INSERT INTO rhnOrgAdminManagement (org_id) (SELECT id FROM web_customer);
  07070100000AFD000081B400000000000000000000000167AE1114000000FE000000000000000000000000000000000000006D00000000susemanager-schema/upgrade/susemanager-schema-2.1.51-to-susemanager-schema-3.0/2011-web_customer-trigger.sql  
create or replace function web_customer_insert_trig_fun() returns trigger
as
$$
begin
	insert into rhnOrgConfiguration (org_id) values (new.id);
	insert into rhnOrgAdminManagement (org_id) values (new.id);

        return new;
end;
$$
language plpgsql;
  07070100000AFE000081B400000000000000000000000167AE11140000053E000000000000000000000000000000000000006900000000susemanager-schema/upgrade/susemanager-schema-2.1.51-to-susemanager-schema-3.0/2013-rhnResetPassword.sql  --
-- Copyright (c) 2015 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnResetPassword
(
    id            NUMERIC NOT NULL
                      CONSTRAINT rhn_rstpwd_id_pk primary key,
    user_id       NUMERIC NOT NULL
                      CONSTRAINT rhn_rstpwd_uid_fk REFERENCES web_contact (id)
                      ON DELETE CASCADE,
    token         VARCHAR(64) NOT NULL
                      CONSTRAINT rhn_rstpwd_token_uq UNIQUE,
    is_valid      char(1) DEFAULT ('Y') NOT NULL
                      CONSTRAINT rhn_rstpwd_is_valid_ck CHECK (is_valid IN ('Y', 'N')),
    created       TIMESTAMPTZ DEFAULT (current_timestamp) NOT NULL,
    modified      TIMESTAMPTZ DEFAULT (current_timestamp) NOT NULL
);

CREATE SEQUENCE rhn_reset_password_id_seq START WITH 500;
  07070100000AFF000081B400000000000000000000000167AE111400000135000000000000000000000000000000000000007100000000susemanager-schema/upgrade/susemanager-schema-2.1.51-to-susemanager-schema-3.0/2014-rhnResetPassword-trigger.sql  
create or replace function rhn_rstpwd_mod_trig_fun() returns trigger as
$$
begin
        new.modified := current_timestamp;
        return new;
end;
$$ language plpgsql;

create trigger
rhn_rstpwd_mod_trig
before insert or update on rhnResetPassword
for each row
execute procedure rhn_rstpwd_mod_trig_fun();
   07070100000B00000081B400000000000000000000000167AE11140000003E000000000000000000000000000000000000007500000000susemanager-schema/upgrade/susemanager-schema-2.1.51-to-susemanager-schema-3.0/3200-rhnCryptoKey-enable-org-null.sql  
ALTER TABLE rhnCryptoKey ALTER COLUMN org_id DROP NOT NULL;

  07070100000B01000081B400000000000000000000000167AE1114000002DF000000000000000000000000000000000000006B00000000susemanager-schema/upgrade/susemanager-schema-2.1.51-to-susemanager-schema-3.0/3201-rhnVirtualInstance.sql    
delete from rhnVirtualInstance where virtual_system_id is NULL and host_system_id is not NULL and uuid in (select uuid from rhnVirtualInstance group by uuid having count(uuid) > 1);
delete from rhnVirtualInstance where virtual_system_id is NULL and host_system_id is NULL and uuid is not NULL;

create or replace function rhn_virtinst_del_trig_fun() returns trigger
as
$$
begin
  delete from rhnVirtualInstance where virtual_system_id is NULL and host_system_id is NULL and uuid is not NULL;
  return null;
end;
$$
language plpgsql;

drop trigger if exists rhn_virtinst_del_trig on rhnVirtualInstance;
create trigger
rhn_virtinst_del_trig
after update on rhnVirtualInstance
for each row
execute procedure rhn_virtinst_del_trig_fun();
 07070100000B02000081B400000000000000000000000167AE1114000002E1000000000000000000000000000000000000007C00000000susemanager-schema/upgrade/susemanager-schema-2.1.51-to-susemanager-schema-3.0/9000-rhnKSInstallType-add-generic-distro.sql   insert into rhnKSInstallType (id, label, name)
    (select sequence_nextval('rhn_ksinstalltype_id_seq'), 'sles10generic','SUSE Enterprise Linux 10' from dual
     where not exists (select 1 from rhnKSInstallType where label = 'sles10generic'));

insert into rhnKSInstallType (id, label, name)
    (select sequence_nextval('rhn_ksinstalltype_id_seq'), 'sles11generic','SUSE Enterprise Linux 11' from dual
     where not exists (select 1 from rhnKSInstallType where label = 'sles11generic'));

insert into rhnKSInstallType (id, label, name)
    (select sequence_nextval('rhn_ksinstalltype_id_seq'), 'sles12generic','SUSE Enterprise Linux 12' from dual
     where not exists (select 1 from rhnKSInstallType where label = 'sles12generic'));
   07070100000B03000081B400000000000000000000000167AE111400000146000000000000000000000000000000000000007500000000susemanager-schema/upgrade/susemanager-schema-2.1.51-to-susemanager-schema-3.0/9001-add_pk_to_suseProductChannel.sql  
CREATE SEQUENCE suse_product_channel_id_seq;

ALTER TABLE suseProductChannel ADD id NUMERIC;

UPDATE suseProductChannel SET id = sequence_nextval('suse_product_channel_id_seq');

ALTER TABLE suseProductChannel ADD CONSTRAINT suse_product_channel_id_pk PRIMARY KEY (id);

ALTER TABLE suseProductChannel ALTER id SET NOT NULL;
  07070100000B04000081B400000000000000000000000167AE111400000098000000000000000000000000000000000000007B00000000susemanager-schema/upgrade/susemanager-schema-2.1.51-to-susemanager-schema-3.0/9002-rhnKickstartableTree-kernelOptions.sql    ALTER TABLE rhnKickstartableTree
    ADD kernel_options       VARCHAR(256);
ALTER TABLE rhnKickstartableTree
    ADD kernel_options_post  VARCHAR(256);
07070100000B05000081B400000000000000000000000167AE11140000007F000000000000000000000000000000000000008A00000000susemanager-schema/upgrade/susemanager-schema-2.1.51-to-susemanager-schema-3.0/9003-rhnOrgEntitlements-delete_monitoring_entitlements.sql DELETE FROM rhnOrgEntitlements
WHERE entitlement_id IN
    (SELECT id FROM rhnOrgEntitlementType WHERE label = 'rhn_monitor');
 07070100000B06000081B400000000000000000000000167AE11140000003F000000000000000000000000000000000000009100000000susemanager-schema/upgrade/susemanager-schema-2.1.51-to-susemanager-schema-3.0/9004-rhnOrgEntitlementType-delete_monitoring_entitlement_type.sql  DELETE FROM rhnOrgEntitlementType
WHERE label = 'rhn_monitor';
 07070100000B07000081B400000000000000000000000167AE1114000004F5000000000000000000000000000000000000006F00000000susemanager-schema/upgrade/susemanager-schema-2.1.51-to-susemanager-schema-3.0/9005-suseVirtualHostManager.sql    --
-- Copyright (c) 2015 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--

CREATE TABLE suseVirtualHostManager
(
    id          NUMERIC NOT NULL
                    CONSTRAINT suse_vhms_id_pk PRIMARY KEY,
    org_id      NUMERIC NOT NULL
                    CONSTRAINT suse_vhms_oid_fk
                    REFERENCES web_customer (id)
                    ON DELETE CASCADE,
    label       VARCHAR(128) NOT NULL,
    gatherer_module     VARCHAR(50) NOT NULL,
    cred_id     NUMERIC
                    CONSTRAINT suse_vhms_creds_fk
                    REFERENCES suseCredentials (id)
                    ON DELETE SET NULL,
    created     TIMESTAMPTZ
                    DEFAULT (current_timestamp) NOT NULL,
    modified    TIMESTAMPTZ
                    DEFAULT (current_timestamp) NOT NULL
)

;

CREATE UNIQUE INDEX suse_vhm_label_uq
ON suseVirtualHostManager (label)
;

CREATE SEQUENCE suse_vhms_id_seq;

   07070100000B08000081B400000000000000000000000167AE111400000300000000000000000000000000000000000000007700000000susemanager-schema/upgrade/susemanager-schema-2.1.51-to-susemanager-schema-3.0/9006-suseVirtualHostManager-trigger.sql    --
-- Copyright (c) 2015 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- triggers for suseVirtualHostManager

create or replace function suse_vhms_mod_trig_fun() returns trigger as
$$
begin
	new.modified := current_timestamp;
	return new;
end;
$$ language plpgsql;

create trigger
suse_vhms_mod_trig
before insert or update on suseVirtualHostManager
for each row
execute procedure suse_vhms_mod_trig_fun();

07070100000B09000081B400000000000000000000000167AE1114000003B6000000000000000000000000000000000000007500000000susemanager-schema/upgrade/susemanager-schema-2.1.51-to-susemanager-schema-3.0/9007-suseServerVirtualHostManager.sql  --
-- Copyright (c) 2015 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--

CREATE TABLE suseServerVirtualHostManager
(
    server_id     NUMERIC NOT NULL
                    CONSTRAINT suse_server_vhms_sid_fk
                    REFERENCES rhnServer (id)
                    ON DELETE CASCADE,
    vhmserver_id  NUMERIC NOT NULL
                    CONSTRAINT suse_server_vhms_vhmsid_fk
                    REFERENCES suseVirtualHostManager (id)
                    ON DELETE CASCADE
)

;

CREATE UNIQUE INDEX suse_svhm_sid_vhmid_uq
ON suseServerVirtualHostManager (server_id, vhmserver_id)
;

  07070100000B0A000081B400000000000000000000000167AE1114000003C2000000000000000000000000000000000000006600000000susemanager-schema/upgrade/susemanager-schema-2.1.51-to-susemanager-schema-3.0/9008-suseVHMConfig.sql --
-- Copyright (c) 2015 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--

CREATE TABLE suseVHMConfig
(
    id          NUMERIC NOT NULL
                CONSTRAINT suse_vhm_config_id_pk PRIMARY KEY,
    virtual_host_manager_id NUMERIC NOT NULL
                    CONSTRAINT suse_vhmc_vhms_fk
                    REFERENCES suseVirtualHostManager (id)
                    ON DELETE CASCADE,
    parameter   VARCHAR(1024) NOT NULL,
    value       VARCHAR(1024)
)

;

CREATE UNIQUE INDEX suse_vhmc_id_para_uq
ON suseVHMConfig (virtual_host_manager_id, parameter)
;

CREATE SEQUENCE suse_vhm_config_id_seq;

  07070100000B0B000081B400000000000000000000000167AE1114000002B9000000000000000000000000000000000000006F00000000susemanager-schema/upgrade/susemanager-schema-2.1.51-to-susemanager-schema-3.0/9009-add-gatherer-cred-type.sql    --
-- Copyright (c) 2015 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--

insert into suseCredentialsType (id, label, name) (
  select sequence_nextval('suse_credtype_id_seq'), 'vhm', 'Virtual Host Manager'
    from dual
   where not exists (
           select 1
             from suseCredentialsType
            where label = 'vhm'
  )
);
   07070100000B0C000081B400000000000000000000000167AE111400007A8D000000000000000000000000000000000000006800000000susemanager-schema/upgrade/susemanager-schema-2.1.51-to-susemanager-schema-3.0/9011-rhn_channel.pkb.sql   --
-- Copyright (c) 2008--2014 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--
--
--
--

-- create schema rhn_channel;

--update pg_setting
update pg_settings set setting = 'rhn_channel,' || setting where name = 'search_path';

    create or replace function obtain_read_lock(channel_family_id_in in numeric, org_id_in in numeric)
    returns void as $$
    declare
        read_lock timestamptz;
    begin
        select created into read_lock
          from rhnPrivateChannelFamily
         where channel_family_id = channel_family_id_in and org_id = org_id_in
           for update;
    end$$ language plpgsql;

    -- this "emulates" cursor server_base_subscriptions defined in oracle/rhn_channel.pks
    create or replace function server_base_subscriptions(server_id_in NUMERIC)
    returns boolean as $$
    begin
      return exists(SELECT C.id FROM rhnChannel C, rhnServerChannel SC
		    WHERE C.id = SC.channel_id
		      AND SC.server_id = server_id_in
		      AND C.parent_channel IS NULL);
    end$$ language plpgsql;

    -- this "emulates" cursor server_base_subscriptions defined in oracle/rhn_channel.pks
    create or replace function check_server_subscription(server_id_in NUMERIC, channel_id_in NUMERIC)
    returns boolean as $$
    begin
      return exists(SELECT channel_id FROM rhnServerChannel WHERE server_id = server_id_in AND channel_id = channel_id_in);
    end$$ language plpgsql;


    CREATE OR REPLACE FUNCTION subscribe_server(server_id_in IN NUMERIC, channel_id_in NUMERIC, immediate_in NUMERIC default 1, user_id_in in numeric default null) returns void
    AS $$
    declare
        channel_parent_val      rhnChannel.parent_channel%TYPE;
        parent_subscribed       BOOLEAN;
        server_has_base_chan    BOOLEAN;
        server_already_in_chan  BOOLEAN;
        channel_family_id_val   NUMERIC;
        server_org_id_val       NUMERIC;
        allowed                 numeric;
    BEGIN
        if user_id_in is not null then
            allowed := rhn_channel.user_role_check(channel_id_in, user_id_in, 'subscribe');
        else
            allowed := 1;
        end if;

        if allowed = 0 then
            perform rhn_exception.raise_exception('no_subscribe_permissions');
        end if;


        SELECT parent_channel INTO channel_parent_val FROM rhnChannel WHERE id = channel_id_in;

        IF channel_parent_val IS NOT NULL
        THEN
            -- child channel; if attempting to cross-subscribe a child to the wrong base, silently ignore
            parent_subscribed := rhn_channel.check_server_subscription(server_id_in, channel_parent_val);

            IF NOT parent_subscribed
            THEN
                RETURN;
            END IF;
        ELSE
            -- base channel
            server_has_base_chan := rhn_channel.server_base_subscriptions(server_id_in);

            IF server_has_base_chan
            THEN
                perform rhn_exception.raise_exception('channel_server_one_base');
            END IF;
        END IF;

        server_already_in_chan := rhn_channel.check_server_subscription(server_id_in, channel_id_in);

        IF server_already_in_chan
        THEN
            RETURN;
        END IF;

        channel_family_id_val := rhn_channel.family_for_channel(channel_id_in);
        IF channel_family_id_val IS NULL
        THEN
            perform rhn_exception.raise_exception('channel_subscribe_no_family');
        END IF;

        --
        -- Use the org_id of the server only if the org_id of the channel = NULL.
        -- This is required for subscribing to shared channels.
        --
        SELECT COALESCE(org_id, (SELECT org_id FROM rhnServer WHERE id = server_id_in))
          INTO server_org_id_val
          FROM rhnChannel
         WHERE id = channel_id_in;

        begin
            perform rhn_channel.obtain_read_lock(channel_family_id_val, server_org_id_val);
        exception
            when no_data_found then
                perform rhn_exception.raise_exception('channel_subscribe_no_family');
        end;

        insert into rhnServerHistory (id,server_id,summary,details) (
            select  nextval('rhn_event_id_seq'),
                    server_id_in,
                    'subscribed to channel ' || SUBSTR(c.label, 0, 106),
                    c.label
            from    rhnChannel c
            where   c.id = channel_id_in
        );

        INSERT INTO rhnServerChannel (server_id, channel_id) VALUES (server_id_in, channel_id_in);

        perform queue_server(server_id_in, immediate_in);

        update rhnServer
           set channels_changed = current_timestamp
         where id = server_id_in;
    END$$ language plpgsql;

    create or replace function guess_server_base(
        server_id_in in numeric
    ) RETURNS numeric as $$
    declare
        server_cursor cursor for
            select s.server_arch_id, s.release, s.org_id
              from rhnServer s
             where s.id = server_id_in;
    -- Cursor that fetches all the possible base channels for a
    -- (server_arch_id, release, org_id) combination
        base_channel_cursor cursor(
                release_in varchar,
                server_arch_id_in numeric,
                org_id_in numeric
        ) for
                select distinct c.*
                from    rhnOrgDistChannelMap                       odcm,
                                rhnServerChannelArchCompat      scac,
                                rhnChannel                                      c
                where   c.parent_channel is null
                        and c.id = odcm.channel_id
                        and c.channel_arch_id = odcm.channel_arch_id
                        and odcm.release = release_in
                        and odcm.for_org_id = org_id_in
                        and scac.server_arch_id = server_arch_id_in
                        and scac.channel_arch_id = c.channel_arch_id;

    begin
        for s in server_cursor loop
            for channel in base_channel_cursor(s.release,
                s.server_arch_id, s.org_id)
            loop
                return channel.id;
            end loop;
        end loop;
        -- Server not found, or no base channel applies to it
        return null;
    end$$ language plpgsql;

    -- Private function
    create or replace function normalize_server_arch(server_arch_in in varchar)
    returns varchar
    as $$
    declare
        suffix VARCHAR(128) := '-redhat-linux';
    begin
        if server_arch_in is NULL then
            return NULL;
        end if;
        if position('-' IN server_arch_in) > 0
        then
            -- Suffix already present
            return server_arch_in;
        end if;
        return server_arch_in || suffix;
    end$$ language plpgsql;

    --
    -- Raises:
    --   server_arch_not_found
    --   no_subscribe_permissions
    create or replace function base_channel_for_release_arch(
        release_in in varchar,
        server_arch_in in varchar,
        org_id_in in numeric default -1,
        user_id_in in numeric default null
    ) returns numeric as $$
    declare
        server_arch varchar(256) := rhn_channel.normalize_server_arch(server_arch_in);
        server_arch_id numeric;
    begin
        -- Look up the server arch
            select id
              into server_arch_id
              from rhnServerArch
             where label = server_arch;
            if not found then
                perform rhn_exception.raise_exception('server_arch_not_found');
            end if;

        return rhn_channel.base_channel_rel_archid(release_in, server_arch_id,
            org_id_in, user_id_in);
    end$$ language plpgsql;

    create or replace function base_channel_rel_archid(
        release_in in varchar,
        server_arch_id_in in numeric,
        org_id_in in numeric default -1,
        user_id_in in numeric default null
    ) returns numeric as $$
    declare
        denied_channel_id numeric := null;
        valid_org_id numeric := org_id_in;
        valid_user_id numeric := user_id_in;
        channel_subscribable numeric;
    -- Cursor that fetches all the possible base channels for a
    -- (server_arch_id, release, org_id) combination
        base_channel_cursor cursor(
                release_in varchar,
                server_arch_id_in numeric,
                org_id_in numeric
        ) for
                select distinct c.*
                from    rhnOrgDistChannelMap                       odcm,
                                rhnServerChannelArchCompat      scac,
                                rhnChannel                                      c
                where   c.parent_channel is null
                        and c.id = odcm.channel_id
                        and c.channel_arch_id = odcm.channel_arch_id
                        and odcm.release = release_in
                        and odcm.for_org_id = org_id_in
                        and scac.server_arch_id = server_arch_id_in
                        and scac.channel_arch_id = c.channel_arch_id;

    begin
        if org_id_in = -1 and user_id_in is not null then
            -- Get the org id from the user id

                select org_id
                  into valid_org_id
                  from web_contact
                 where id = user_id_in;

                if not found then
                    -- User doesn't exist
                    -- XXX Only list public stuff for now
                    valid_user_id := null;
                    valid_org_id := -1;
                end if;
        end if;

        for c in base_channel_cursor(release_in, server_arch_id_in, valid_org_id)
        loop
            -- This row is a possible match
            if valid_user_id is null then
                -- User ID not specified, so no user to channel permissions to
                -- check
                return c.id;
            end if;

            -- Check user to channel permissions
            select rhn_channel.loose_user_role_check(c.id, user_id_in, 'subscribe')
              into channel_subscribable;

            if channel_subscribable = 1 then
                return c.id;
            end if;

            -- Base channel exists, but is not subscribable; keep trying
            denied_channel_id := c.id;
        end loop;

        if denied_channel_id is not null then
            perform rhn_exception.raise_exception('no_subscribe_permissions');
        end if;
        -- No base channel applies
        return NULL;
    end$$ language plpgsql;

    CREATE OR REPLACE FUNCTION clear_subscriptions(server_id_in IN NUMERIC, deleting_server IN NUMERIC default 0) returns void
    AS $$
    declare
        server_channels cursor(server_id_in numeric) for
                select  s.org_id, sc.channel_id, cfm.channel_family_id
                from    rhnServer s,
                        rhnServerChannel sc,
                        rhnChannelFamilyMembers cfm
                where   s.id = server_id_in
                        and s.id = sc.server_id
                        and sc.channel_id = cfm.channel_id
                order by cfm.channel_family_id;
        last_channel_family_id rhnChannelFamilyMembers.channel_family_id%type := -1;
        last_channel_org_id    rhnServer.org_id%type := -1;
    BEGIN
        for channel in server_channels(server_id_in)
        loop
                perform rhn_channel.unsubscribe_server(server_id_in, channel.channel_id, 1, 1, deleting_server);
        end loop;
    END$$ language plpgsql;

    CREATE OR REPLACE FUNCTION unsubscribe_server(server_id_in IN NUMERIC, channel_id_in NUMERIC, immediate_in NUMERIC default 1, unsubscribe_children_in numeric default 0,
                                 deleting_server in numeric default 0) returns void
    AS $$
    declare
        channel_family_id_val   NUMERIC;
        server_org_id_val       NUMERIC;
        server_already_in_chan  BOOLEAN;
        channel_family_is_proxy cursor(channel_family_id_in numeric) for
                select  1
                from    rhnChannelFamily
                where   id = channel_family_id_in
                    and label = 'rhn-proxy';
        channel_family_is_satellite cursor(channel_family_id_in numeric) for
                select  1
                from    rhnChannelFamily
                where   id = channel_family_id_in
                    and label = 'rhn-satellite';
        child record;
    BEGIN
        -- In PostgreSQL recursion with opened cursors is not allowed so we use
        -- FOR IN SELECT form which is ok.
        FOR child IN select  c.id
                from    rhnChannel                      c,
                                rhnServerChannel        sc
                where   1=1
                        and c.parent_channel = channel_id_in
                        and c.id = sc.channel_id
                        and sc.server_id = server_id_in
        LOOP
            if unsubscribe_children_in = 1 then
                perform rhn_channel.unsubscribe_server(server_id_in,
                                                       child.id,
                                                       immediate_in,
                                                       unsubscribe_children_in,
                                                       deleting_server);
            else
                perform rhn_exception.raise_exception('channel_unsubscribe_child_exists');
            end if;
        END LOOP;

        server_already_in_chan := rhn_channel.check_server_subscription(server_id_in, channel_id_in);

        IF NOT server_already_in_chan
        THEN
            RETURN;
        END IF;

   if deleting_server = 0 then
      insert into rhnServerHistory (id,server_id,summary,details) (
          select  nextval('rhn_event_id_seq'),
                server_id_in,
             'unsubscribed from channel ' || SUBSTR(c.label, 0, 106),
             c.label
          from    rhnChannel c
          where   c.id = channel_id_in
      );
   end if;

   DELETE FROM rhnServerChannel WHERE server_id = server_id_in AND channel_id = channel_id_in;

   if deleting_server = 0 then
        perform queue_server(server_id_in, immediate_in);

        update rhnServer
           set channels_changed = current_timestamp
         where id = server_id_in;
   end if;

        channel_family_id_val := rhn_channel.family_for_channel(channel_id_in);
        IF channel_family_id_val IS NULL
        THEN
            perform rhn_exception.raise_exception('channel_unsubscribe_no_family');
        END IF;

        for ignore in channel_family_is_satellite(channel_family_id_val) loop
                delete from rhnSatelliteInfo where server_id = server_id_in;
        end loop;

        for ignore in channel_family_is_proxy(channel_family_id_val) loop
                delete from rhnProxyInfo where server_id = server_id_in;
        end loop;
        SELECT org_id INTO server_org_id_val
          FROM rhnServer
         WHERE id = server_id_in;

    END$$ language plpgsql;

    CREATE OR REPLACE FUNCTION family_for_channel(channel_id_in IN NUMERIC)
    RETURNS NUMERIC
    AS $$
    declare
        channel_family_id_val NUMERIC;
    BEGIN
        SELECT channel_family_id INTO channel_family_id_val
          FROM rhnChannelFamilyMembers
         WHERE channel_id = channel_id_in;

        IF NOT FOUND THEN
          RETURN NULL;
        END IF;

        RETURN channel_family_id_val;
    END$$ language plpgsql;

    create or replace function unsubscribe_server_from_family(server_id_in in numeric,
                                             channel_family_id_in in numeric)
    returns void
    as $$
    begin
        delete
        from    rhnServerChannel rsc
        where   rsc.server_id = server_id_in
            and channel_id in (
                select  rcfm.channel_id
                from    rhnChannelFamilyMembers rcfm
                where   rcfm.channel_family_id = channel_family_id_in);
    end$$ language plpgsql;

    create or replace function get_org_id(channel_id_in in numeric)
    returns numeric
    as $$
    declare
        org_id_out numeric;
    begin
        select org_id into strict org_id_out
            from rhnChannel
            where id = channel_id_in;

            return org_id_out;
    end$$ language plpgsql;

    create or replace function get_cfam_org_access(cfam_id_in in numeric, org_id_in in numeric)
    returns numeric
    as $$
    begin
      if exists(
                        select  1
                        from    rhnOrgChannelFamilyPermissions cfp
                        where   cfp.org_id = org_id_in
      ) then
                return 1;
      else
                return 0;
      end if;
    end$$ language plpgsql;

    create or replace function get_org_access(channel_id_in in numeric, org_id_in in numeric)
    returns integer
    as $$
    begin
        -- the idea: if we get past this query,
        -- the org has access to the channel, else not
        if exists(
        select 1
          from rhnChannelFamilyMembers CFM,
               rhnOrgChannelFamilyPermissions CFP
         where cfp.org_id = org_id_in
           and CFM.channel_family_id = CFP.channel_family_id
           and CFM.channel_id = channel_id_in)
        then
          return 1;
        else
          return 0;
        end if;
    end$$ language plpgsql;

    -- check if a user has a given role, or if such a role is inferrable
    -- returns NULL if OK, error message otherwise
    create or replace function user_role_check_debug(channel_id_in in numeric,
                                   user_id_in in numeric,
                                   role_in in varchar)
    returns varchar
    as $$
    declare
        org_id numeric;
    begin
        org_id := rhn_user.get_org_id(user_id_in);

        -- channel might be shared
        if role_in = 'subscribe' and
           rhn_channel.shared_user_role_check(channel_id_in, user_id_in, role_in) = 1 then
            return NULL;
        end if;

        if role_in = 'manage' and
           COALESCE(rhn_channel.get_org_id(channel_id_in), -1) <> org_id then
               return 'channel_not_owned';
        end if;

        if role_in = 'subscribe' and
           rhn_channel.get_org_access(channel_id_in, org_id) = 0 then
                return 'channel_not_available';
        end if;

        -- channel admins have all roles
        if rhn_user.check_role_implied(user_id_in, 'channel_admin') = 1 then
            return NULL;
        end if;

        -- the subscribe permission is inferred
        -- UNLESS the not_globally_subscribable flag is set
        if role_in = 'subscribe'
        then
            if rhn_channel.org_channel_setting(channel_id_in,
                       org_id,
                       'not_globally_subscribable') = 0 then
                return NULL;
            end if;
        end if;

        -- all other roles (manage right now) are explicitly granted
        if rhn_channel.direct_user_role_check(channel_id_in,
                                              user_id_in, role_in) = 1 then
            return NULL;
        end if;
        return 'direct_permission';
    end$$ language plpgsql;

    -- same as above, but with 1/0 output; useful in views, etc
    create or replace function user_role_check(channel_id_in in numeric, user_id_in in numeric, role_in in varchar)
    returns numeric
    as $$
    begin
        if rhn_channel.user_role_check_debug(channel_id_in,
                                             user_id_in, role_in) is NULL then
            return 1;
        else
            return 0;
        end if;
    end$$ language plpgsql;

    --
    -- For multiorg phase II, this function simply checks to see if the user's
    -- has a trust relationship that includes this channel by id.
    --
    create or replace function shared_user_role_check(channel_id in numeric, user_id in numeric, role in varchar)
    returns numeric
    as $$
    declare
      n numeric;
      oid numeric;
    begin
      oid := rhn_user.get_org_id(user_id);
      select 1 into n
      from rhnSharedChannelView s
      where s.id = channel_id and s.org_trust_id = oid;

      if not found then
        return 0;
      end if;

      return 1;
    end$$ language plpgsql;

    -- same as above, but returns 1 if user_id_in is null
    -- This is useful in queries where user_id is not specified
    create or replace function loose_user_role_check(channel_id_in in numeric, user_id_in in numeric, role_in in varchar)
    returns numeric
    as $$
    begin
        if user_id_in is null then
            return 1;
        end if;
        return rhn_channel.user_role_check(channel_id_in, user_id_in, role_in);
    end$$ language plpgsql;

    -- directly checks the table, no inferred permissions
    create or replace function direct_user_role_check(channel_id_in in numeric, user_id_in in numeric, role_in in varchar)
    returns numeric
    as $$
    declare
        throwaway numeric;
    begin
        -- the idea: if we get past this query, the user has the role, else no
        select 1 into throwaway
          from rhnChannelPermissionRole CPR,
               rhnChannelPermission CP
         where CP.user_id = user_id_in
           and CP.channel_id = channel_id_in
           and CPR.label = role_in
           and CP.role_id = CPR.id;

      if not found then
        return 0;
      end if;

      return 1;
    end$$ language plpgsql;

    -- check if an org has a certain setting
    create or replace function org_channel_setting(channel_id_in in numeric, org_id_in in numeric, setting_in in varchar)
    returns numeric
    as $$
    declare
        throwaway numeric;
    begin
        -- the idea: if we get past this query, the org has the setting
        select 1 into throwaway
          from rhnOrgChannelSettingsType OCST,
               rhnOrgChannelSettings OCS
         where OCS.org_id = org_id_in
           and OCS.channel_id = channel_id_in
           and OCST.label = setting_in
           and OCS.setting_id = OCST.id;

      if not found then
        return 0;
      end if;

      return 1;
    end$$ language plpgsql;

    CREATE OR REPLACE FUNCTION channel_priority(channel_id_in IN numeric)
    RETURNS numeric
    AS $$
    declare
         channel_name varchar(256);
         priority numeric;
         end_of_life_val timestamptz;
         org_id_val numeric;
    BEGIN

        select name, end_of_life, org_id
        into channel_name, end_of_life_val, org_id_val
        from rhnChannel
        where id = channel_id_in;

        if end_of_life_val is not null then
          return -400;
        end if;

        if channel_name like 'Red Hat Enterprise Linux%' or channel_name like 'RHEL%' then
          priority := 1000;
          if channel_name not like '%Beta%' then
            priority := priority + 1000;
          end if;

          priority := priority +
            case
              when channel_name like '%v. 5%' then 600
              when channel_name like '%v. 4%' then 500
              when channel_name like '%v. 3%' then 400
              when channel_name like '%v. 2%' then 300
              when channel_name like '%v. 1%' then 200
              else 0
            end;

          priority := priority +
            case
              when channel_name like 'Red Hat Enterprise Linux (v. 5%' then 60
              when (channel_name like '%AS%' and channel_name not like '%Extras%') then 50
              when (channel_name like '%ES%' and channel_name not like '%Extras%') then 40
              when (channel_name like '%WS%' and channel_name not like '%Extras%') then 30
              when (channel_name like '%Desktop%' and channel_name not like '%Extras%') then 20
              when channel_name like '%Extras%' then 10
              else 0
            end;

          priority := priority +
            case
              when channel_name like '%)' then 5
              else 0
            end;

          priority := priority +
            case
              when channel_name like '%32-bit x86%' then 4
              when channel_name like '%64-bit Intel Itanium%' then 3
              when channel_name like '%64-bit AMD64/Intel EM64T%' then 2
              else 0
            end;
        elsif channel_name like 'Red Hat Desktop%' then
            priority := 900;

            if channel_name not like '%Beta%' then
               priority := priority + 50;
            end if;

          priority := priority +
            case
              when channel_name like '%v. 4%' then 40
              when channel_name like '%v. 3%' then 30
              when channel_name like '%v. 2%' then 20
              when channel_name like '%v. 1%' then 10
              else 0
            end;

          priority := priority +
            case
              when channel_name like '%32-bit x86%' then 4
              when channel_name like '%64-bit Intel Itanium%' then 3
              when channel_name like '%64-bit AMD64/Intel EM64T%' then 2
              else 0
            end;

        elsif org_id_val is not null then
          priority := 600;
        else
          priority := 500;
        end if;

      return -priority;

    end$$ language plpgsql;

    -- this could certainly be optimized to do updates if needs be
    create or replace function refresh_newest_package(channel_id_in in numeric,
                                      caller_in in varchar default '(unknown)',
                                      package_name_id_in in numeric default null)
    returns void
    as $$
    -- procedure refreshes rows for name_id = package_name_id_in or
    -- all rows if package_name_id_in is null
    begin
        delete from rhnChannelNewestPackage
              where channel_id = channel_id_in
                and (package_name_id_in is null
                     or name_id = package_name_id_in);
        insert into rhnChannelNewestPackage
                (channel_id, name_id, evr_id, package_id, package_arch_id)
                (select channel_id,
                        name_id, evr_id,
                        package_id, package_arch_id
                   from rhnChannelNewestPackageView
                  where channel_id = channel_id_in
                    and (package_name_id_in is null
                         or name_id = package_name_id_in)
                );
        insert into rhnChannelNewestPackageAudit (channel_id, caller)
             values (channel_id_in, caller_in);
        update rhnChannel
           set last_modified = greatest(current_timestamp,
                                        last_modified + interval '1 second')
         where id = channel_id_in;
    end$$ language plpgsql;

   create or replace function update_channel ( channel_id_in in numeric, invalidate_ss in numeric default 0,
                              date_to_use in timestamptz default current_timestamp ) returns void
   as $$
   declare
   channel_last_modified timestamptz;
   last_modified_value timestamptz;

   snapshots cursor for
   select  snapshot_id id
   from    rhnSnapshotChannel
   where   channel_id = channel_id_in;

   begin

      select last_modified
      into channel_last_modified
      from rhnChannel
      where id = channel_id_in;

      last_modified_value := date_to_use;

      if last_modified_value <= channel_last_modified then
          last_modified_value := last_modified_value + interval '1 second';
      end if;

      update rhnChannel set last_modified = last_modified_value
      where id = channel_id_in;

      if invalidate_ss = 1 then
        for snapshot in snapshots loop
            update rhnSnapshot
            set invalid = lookup_snapshot_invalid_reason('channel_modified')
            where id = snapshot.id;
        end loop;
      end if;

   end$$ language plpgsql;

   create or replace function update_channels_by_package ( package_id_in in numeric, date_to_use in timestamptz default current_timestamp ) returns void
   as $$
   declare
   channels cursor for
   select channel_id
   from rhnChannelPackage
   where package_id = package_id_in
   order by channel_id;

   begin
      for channel in channels loop
         -- we want to invalidate the snapshot assocated with the channel when we
         -- do this b/c we know we've added or removed or packages
         perform rhn_channel.update_channel ( channel.channel_id, 1, date_to_use );
      end loop;
   end$$ language plpgsql;


   create or replace function update_channels_by_errata ( errata_id_in numeric, date_to_use in timestamptz default current_timestamp ) returns void
   as $$
   declare
   channels cursor for
   select channel_id
   from rhnChannelErrata
   where errata_id = errata_id_in
   order by channel_id;

   begin
      for channel in channels loop
         -- we won't invalidate snapshots, b/c just changing the errata associated with
         -- a channel shouldn't invalidate snapshots
         perform rhn_channel.update_channel ( channel.channel_id, 0, date_to_use );
      end loop;
   end$$ language plpgsql;

   create or replace function update_needed_cache(channel_id_in in numeric) returns void
   as $$
   declare
   server record;
   begin
      -- we intentionaly do a loop here instead of one huge select
      -- b/c we want to break update into smaller transaction to unblock other sessions
      -- querying rhnServerNeededCache
      for server in (
                select sc.server_id as id
                  from rhnServerChannel sc
                 where sc.channel_id = channel_id_in
                 order by id asc
      ) loop
         perform queue_server(server.id, 0); -- NOT IMMEDIATE
      end loop;
   end$$ language plpgsql;

    create or replace function set_comps(channel_id_in in numeric, path_in in varchar, timestamp_in in varchar) returns void
    as $$
    declare
    row record;
    begin
        for row in (
            select relative_filename, last_modified
            from rhnChannelComps
            where channel_id = channel_id_in
            ) loop
            if row.relative_filename = path_in
                and row.last_modified = to_timestamp(timestamp_in, 'YYYYMMDDHH24MISS') then
                return;
            end if;
        end loop;
        delete from rhnChannelComps
        where channel_id = channel_id_in;
        insert into rhnChannelComps (id, channel_id, relative_filename, last_modified, created, modified)
        values (sequence_nextval('rhn_channelcomps_id_seq'), channel_id_in, path_in, to_timestamp(timestamp_in, 'YYYYMMDDHH24MISS'), current_timestamp, current_timestamp);
    end$$ language plpgsql;

-- restore the original setting
update pg_settings set setting = overlay( setting placing '' from 1 for (length('rhn_channel')+1) ) where name = 'search_path';
   07070100000B0D000081B400000000000000000000000167AE1114000099B6000000000000000000000000000000000000006D00000000susemanager-schema/upgrade/susemanager-schema-2.1.51-to-susemanager-schema-3.0/9013-rhn_entitlements.pkb.sql  --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

-- create schema rhn_entitlements;

-- setup search_path so that these functions are created in appropriate schema.
update pg_settings set setting = 'rhn_entitlements,' || setting where name = 'search_path';

   create or replace function find_compatible_sg (
      server_id_in in numeric,
      type_label_in in varchar
   )
   returns numeric
as $$
    declare
      servergroups cursor for
         select sg.id
           from rhnServerGroupType             sgt,
                rhnServerGroup                 sg,
                rhnServer                     s,
                rhnServerServerGroupArchCompat ssgac
          where s.id = server_id_in
            and s.org_id = sg.org_id
            and sgt.label = type_label_in
            and sg.group_type = sgt.id
            and ssgac.server_group_type = sgt.id
            and ssgac.server_arch_id = s.server_arch_id
            and not exists (
                     select 1
                      from rhnServerGroupMembers sgm
                     where sgm.server_group_id = sg.id
                       and sgm.server_id = s.id);


   begin
      for servergroup in servergroups loop
         return servergroup.id;
      end loop;

      --no servergroup found
      return NULL;
   end$$
language plpgsql;

    -- *******************************************************************
    -- PROCEDURE: remove_org_entitlements
    --
    -- Removes both system entitlements and channel subscriptions
    -- that are currently assigned to an org and re-assigns to the
    -- master org (org_id = 1).
    --
    -- When we call this we expect everything to already be unentitled
    -- which shoul be handled by delete_org.
    --
    -- Called by: delete_org
    -- *******************************************************************
    create or replace function remove_org_entitlements (
        org_id_in numeric
    ) returns void
as $$
    declare
        system_ents cursor for
        select sg.id, sg.max_members, sg.group_type
        from rhnServerGroup sg
        where group_type is not null
          and org_id = org_id_in;

    begin

        for system_ent in system_ents loop
            update rhnServerGroup
            set max_members = max_members + system_ent.max_members
            where org_id = 1
              and group_type = system_ent.group_type;
        end loop;

        update rhnServerGroup
        set max_members = 0
        where org_id = org_id_in;

    end$$
language plpgsql;

    create or replace function entitlement_grants_service (
        entitlement_in in varchar,
        service_level_in in varchar
    ) returns numeric
as $$
    begin
        if service_level_in = 'provisioning' then
            if entitlement_in = 'provisioning_entitled' then
                return 1;
            else
                return 0;
            end if;
        elsif service_level_in = 'management' then
            if entitlement_in = 'enterprise_entitled' then
                return 1;
            else
                return 0;
            end if;
        elsif service_level_in = 'updates' then
            return 1;
        else
            return 0;
        end if;
    end$$
language plpgsql;

    create or replace function lookup_entitlement_group (
        org_id_in in numeric,
        type_label_in in varchar default 'sw_mgr_entitled'
    ) returns numeric
as $$
    declare
        server_groups cursor for
            select  sg.id               server_group_id
            from    rhnServerGroup      sg,
                    rhnServerGroupType  sgt
            where   sgt.label = type_label_in
                and sgt.id = sg.group_type
                and sg.org_id = org_id_in;
    begin
        for sg in server_groups loop
            return sg.server_group_id;
        end loop;
        return rhn_entitlements.create_entitlement_group(
                org_id_in,
                type_label_in
            );
    end$$
language plpgsql;

    create or replace function create_entitlement_group (
        org_id_in in numeric,
        type_label_in in varchar default 'sw_mgr_entitled'
    ) returns numeric
as $$
    declare
        sg_id_val numeric;
    begin
        select  nextval('rhn_server_group_id_seq')
        into    sg_id_val;

        insert into rhnServerGroup (
                id, name, description, max_members, current_members,
                group_type, org_id
            ) (
                select  sg_id_val, sgt.label, sgt.label,
                        0, 0, sgt.id, org_id_in
                from    rhnServerGroupType sgt
                where   sgt.label = type_label_in
            );

        return sg_id_val;
    end$$
language plpgsql;

   create or replace function can_entitle_server (
      server_id_in   in numeric,
      type_label_in  in varchar
   )
   returns numeric
as $$
    declare
      addon_servergroups cursor (base_label_in varchar,
                                 addon_label_in varchar) for
         select
            addon_id
         from
            rhnSGTypeBaseAddonCompat
         where base_id = lookup_sg_type (base_label_in)
           and addon_id = lookup_sg_type (addon_label_in);

      previous_ent        varchar[];
      is_base_in          char   := 'N';
      is_base_current     char   := 'N';
      i                   numeric := 0;
      sgid                numeric := 0;

   begin

      previous_ent := rhn_entitlements.get_server_entitlement(server_id_in);

      select distinct is_base
      into is_base_in
      from rhnServerGroupType
      where label = type_label_in;

      if array_upper(previous_ent, 1) is null or array_upper(previous_ent, 1) = 0 then
         if is_base_in = 'Y' then
            sgid := rhn_entitlements.find_compatible_sg (server_id_in, type_label_in);
            if sgid is not null then
              -- rhn_server.insert_into_servergroup (server_id_in, sgid);
              return 1;
            else
              -- rhn_exception.raise_exception ('invalid_base_entitlement');
              return 0;
            end if;
         else
            -- rhn_exception.raise_exception ('invalid_base_entitlement');
            return 0;
         end if;

      -- there are previous ents, first make sure we're not trying to entitle a base ent
      elsif is_base_in = 'Y' then
         -- rhn_exception.raise_exception ('invalid_addon_entitlement');
         return 0;

      -- it must be an addon, so proceed with the entitlement
      else

         -- find the servers base ent
         is_base_current := 'N';
         i := 0;
         while is_base_current = 'N' and i < array_upper(previous_ent, 1)
         loop
            i := i + 1;
            select is_base
            into is_base_current
            from rhnServerGroupType
            where label = previous_ent[i];
         end loop;

         -- never found a base ent, that would be strange
         if is_base_current  = 'N' then
            -- rhn_exception.raise_exception ('invalid_base_entitlement');
            return 0;
         end if;

         -- this for loop verifies the validity of the addon path
         for addon_servergroup in addon_servergroups  (previous_ent[i], type_label_in) loop
            -- find an appropriate sgid for the addon and entitle the server
            sgid := rhn_entitlements.find_compatible_sg (server_id_in, type_label_in);
            if sgid is not null then
               -- rhn_server.insert_into_servergroup (server_id_in, sgid);
               return 1;
            else
               -- rhn_exception.raise_exception ('invalid_addon_entitlement');
               return 0;
            end if;
         end loop;

      end if;

      return 0;

   end$$
language plpgsql;

   create or replace function can_switch_base (
      server_id_in   in    integer,
      type_label_in  in    varchar
   )
   returns numeric
as $$
   declare
      type_label_in_is_base   char(1);
      sgid                    numeric;

   begin

       select is_base into type_label_in_is_base
       from rhnServerGroupType
       where label = type_label_in;

       if not found then
          perform rhn_exception.raise_exception ( 'invalid_entitlement' );
       end if;

      if type_label_in_is_base = 'N' then
         perform rhn_exception.raise_exception ( 'invalid_entitlement' );
      else
         sgid := rhn_entitlements.find_compatible_sg ( server_id_in,
                                                       type_label_in );
         if sgid is not null then
           return 1;
         else
           return 0;
         end if;
      end if;

   end$$
language plpgsql;

    create or replace function entitle_server (
        server_id_in in numeric,
        type_label_in in varchar default 'sw_mgr_entitled'
    ) returns void
as $$
    declare
      sgid  numeric := 0;
      is_virt numeric := 0;

    begin

      select 1 into is_virt
        from rhnServerEntitlementView
        where server_id = server_id_in
          and label in ('virtualization_host', 'virtualization_host_platform');

      if not found then
          is_virt := 0;
      end if;

      if is_virt = 0 and (type_label_in = 'virtualization_host' or
                          type_label_in = 'virtualization_host_platform') then

        is_virt := 1;
      end if;

      if rhn_entitlements.can_entitle_server(server_id_in,
                                             type_label_in) = 1 then
         sgid := rhn_entitlements.find_compatible_sg (server_id_in,
                                                      type_label_in);
         if sgid is not null then
            insert into rhnServerHistory ( id, server_id, summary, details )
            values ( nextval('rhn_event_id_seq'), server_id_in,
                     'added system entitlement ',
                      case type_label_in
                       when 'enterprise_entitled' then 'Management'
                       when 'bootstrap_entitled' then 'Bootstrap'
                       when 'sw_mgr_entitled' then 'Update'
                       when 'provisioning_entitled' then 'Provisioning'
                       when 'virtualization_host' then 'Virtualization'
                       when 'virtualization_host_platform' then
                            'Virtualization Platform' end  );

            perform rhn_server.insert_into_servergroup (server_id_in, sgid);

            if is_virt = 1 then
              perform rhn_entitlements.repoll_virt_guest_entitlements(server_id_in);
            end if;

         else
            perform rhn_exception.raise_exception ('no_available_server_group');
         end if;
      else
         perform rhn_exception.raise_exception ('invalid_entitlement');
      end if;
   end$$
language plpgsql;

    create or replace function remove_server_entitlement (
        server_id_in in numeric,
        type_label_in in varchar default 'sw_mgr_entitled',
        repoll_virt_guests in numeric default 1
    ) returns void
as $$
    declare
      group_id numeric;
      type_is_base char;
      is_virt numeric := 0;
    begin
      -- would be nice if there were a virt attribute of entitlement types, not have to specify 2 different ones...
        select 1 into is_virt
          from rhnServerEntitlementView
          where server_id = server_id_in
            and label in ('virtualization_host', 'virtualization_host_platform');
        if not found then
            is_virt := 0;
        end if;

        select  sg.id, sgt.is_base
        into group_id, type_is_base
        from    rhnServerGroupType sgt,
            rhnServerGroup sg,
                rhnServerGroupMembers sgm,
                rhnServer s
        where   s.id = server_id_in
            and s.id = sgm.server_id
            and sgm.server_group_id = sg.id
            and sg.org_id = s.org_id
            and sgt.label = type_label_in
            and sgt.id = sg.group_type;

        if not found then
          perform rhn_exception.raise_exception('invalid_server_group_member');
        end if;

      if ( type_is_base = 'Y' ) then
         -- unentitle_server should handle everything, don't really need to do anything else special here
         perform rhn_entitlements.unentitle_server ( server_id_in );
      else

         insert into rhnServerHistory ( id, server_id, summary, details )
         values ( nextval('rhn_event_id_seq'), server_id_in,
                  'removed system entitlement ',
                   case type_label_in
                    when 'enterprise_entitled' then 'Management'
                    when 'bootstrap_entitled' then 'Bootstrap'
                    when 'sw_mgr_entitled' then 'Update'
                    when 'provisioning_entitled' then 'Provisioning'
                    when 'virtualization_host' then 'Virtualization'
                    when 'virtualization_host_platform' then
                         'Virtualization Platforrm' end  );

         perform rhn_server.delete_from_servergroup(server_id_in, group_id);

         if is_virt = 1 and repoll_virt_guests = 1 then
           perform rhn_entitlements.repoll_virt_guest_entitlements(server_id_in);
         end if;
      end if;

    end$$
language plpgsql;

    create or replace function unentitle_server (
        server_id_in in numeric
    ) returns void
as $$
    declare
      servergroups cursor for
         select distinct sgt.label, sg.id server_group_id
         from  rhnServerGroupType sgt,
               rhnServerGroup sg,
               rhnServer s,
               rhnServerGroupMembers sgm
         where s.id = server_id_in
            and s.org_id = sg.org_id
            and sg.group_type = sgt.id
            and sgm.server_group_id = sg.id
            and sgm.server_id = s.id;

     is_virt numeric := 0;

   begin

      select 1 into is_virt
        from rhnServerEntitlementView
        where server_id = server_id_in
         and label in ('virtualization_host', 'virtualization_host_platform');

      if not found then
          is_virt := 0;
      end if;

      for servergroup in servergroups loop

         insert into rhnServerHistory ( id, server_id, summary, details )
         values ( nextval('rhn_event_id_seq'), server_id_in,
                  'removed system entitlement ',
                   case servergroup.label
                    when 'enterprise_entitled' then 'Management'
                    when 'bootstrap_entitled' then 'Bootstrap'
                    when 'sw_mgr_entitled' then 'Update'
                    when 'provisioning_entitled' then 'Provisioning'
                    when 'virtualization_host' then 'Virtualization'
                    when 'virtualization_host_platform' then
                         'Virtualization Platform' end  );

         perform rhn_server.delete_from_servergroup(server_id_in,
                                            servergroup.server_group_id );
      end loop;

      if is_virt = 1 then
        perform rhn_entitlements.repoll_virt_guest_entitlements(server_id_in);
      end if;

   end$$
language plpgsql;


    -- *******************************************************************
    -- PROCEDURE: repoll_virt_guest_entitlements
    --
    --   Whenever we add/remove a virtualization_host* entitlement from
    --   a host, we can call this procedure to update what type of slots
    --   the guests are consuming.
    --
    --   If you're removing the entitlement, it's
    --   possible the guests will become unentitled if you don't have enough
    --   physical slots to cover them.
    --
    --   If you're adding the entitlement, you end up freeing up physical
    --   slots for other systems.
    --
    -- *******************************************************************
    create or replace function repoll_virt_guest_entitlements(
        server_id_in in numeric
    ) returns void
as $$
    declare
        -- All of server group types associated with the guests of
        -- server_id_in
        group_types cursor for
            select distinct sg.group_type, sgt.label, sg.org_id
            from
                rhnServerGroupType sgt,
                rhnServerGroup sg,
                rhnServerGroupMembers sgm,
                rhnVirtualInstance vi
            where
                vi.host_system_id = server_id_in
                and vi.virtual_system_id = sgm.server_id
                and sgm.server_group_id = sg.id
                and sg.group_type = sgt.id;

        -- Virtual servers from a certain family belonging to a specific
        -- host that are consuming physical system slots over the limit.
        virt_servers_sgt cursor(group_type_in numeric, quantity_in numeric) for
                select vi.virtual_system_id
                from
                    rhnServerGroup sg,
                    rhnServerGroupMembers sgm,
                    rhnVirtualInstance vi
                where
                    vi.host_system_id = server_id_in
                    and vi.virtual_system_id = sgm.server_id
                    and sgm.server_group_id = sg.id
                    and sg.group_type = group_type_in
                order by sgm.modified desc
                limit quantity_in;

        org_id_val numeric;
        max_members_val numeric;
        max_flex_val numeric;
        current_members_calc numeric;
        sg_id numeric;
        is_virt numeric := 0;
        free_slots numeric := 0;
    begin
          select 1 into is_virt
                from rhnServerEntitlementView
           where server_id = server_id_in
                 and label in ('virtualization_host', 'virtualization_host_platform');

      if not found then
          is_virt := 0;
      end if;

        select org_id
        into org_id_val
        from rhnServer
        where id = server_id_in;

        for a_group_type in group_types loop
          -- get the current *physical* members of the system entitlement type for the org...
          --
          -- unlike channel families, it appears the standard rhnServerGroup.max_members represents
          -- *physical* slots, vs physical+virt ... boy that's confusing...

          select max_members, id
            into max_members_val, sg_id
            from rhnServerGroup
            where group_type = a_group_type.group_type
            and org_id = a_group_type.org_id;


      select count(sep.server_id) into current_members_calc
            from rhnServerEntitlementPhysical sep
           where sep.server_group_id = sg_id
             and sep.server_group_type_id = a_group_type.group_type;

          if current_members_calc > max_members_val then
            -- A virtualization_host* ent must have been removed, and we're over the limit, so unsubscribe guests
            for virt_server in virt_servers_sgt(a_group_type.group_type,
                                                current_members_calc - max_members_val) loop
              perform rhn_entitlements.remove_server_entitlement(virt_server.virtual_system_id, a_group_type.label);

              -- decrement current_members_calc, we'll use it to reset current_members for the group at the end...
              current_members_calc := current_members_calc - 1;
            end loop;

          end if;

          update rhnServerGroup set current_members = current_members_calc
           where org_id = a_group_type.org_id
             and group_type = a_group_type.group_type;

          -- I think that's all the house-keeping we have to do...
        end loop;

    end$$
language plpgsql;

    create or replace function get_server_entitlement (
        server_id_in in numeric
    ) returns varchar[]
as $$
    declare
        server_groups cursor for
            select  sgt.label
            from    rhnServerGroupType      sgt,
                    rhnServerGroup          sg,
                    rhnServerGroupMembers   sgm
            where   1=1
                and sgm.server_id = server_id_in
                and sg.id = sgm.server_group_id
                and sgt.id = sg.group_type
                and sgt.label in (
                    'sw_mgr_entitled','enterprise_entitled', 'bootstrap_entitled',
                    'provisioning_entitled', 'nonlinux_entitled',
                    'virtualization_host', 'virtualization_host_platform'
                    );

         ent_array varchar[];

    begin

      ent_array := '{}';

      for sg in server_groups loop
         ent_array := ent_array || sg.label;
      end loop;

      return ent_array;

    end$$
language plpgsql;

    -- this desperately needs to be table driven.
    create or replace function modify_org_service (
        org_id_in in numeric,
        service_label_in in varchar,
        enable_in in char
    ) returns void
as $$
    declare
        roles_to_process varchar[];
        roles cursor(role_label_in varchar) for
            select  label, id
            from    rhnUserGroupType
            where   label = role_label_in;
        org_roles cursor(role_label_in varchar) for
            select  1
            from    rhnUserGroup ug,
                    rhnUserGroupType ugt
            where   ugt.label = role_label_in
                and ug.org_id = org_id_in
                and ugt.id = ug.group_type;

        ents_to_process varchar[];
        ents cursor(ent_label_in varchar) for
            select  label, id
            from    rhnOrgEntitlementType
            where   label = ent_label_in;
        org_ents cursor(ent_label_in varchar) for
            select  1
            from    rhnOrgEntitlements oe,
                    rhnOrgEntitlementType oet
            where   oet.label = ent_label_in
                and oe.org_id = org_id_in
                and oet.id = oe.entitlement_id;
        create_row char(1);
    begin
        ents_to_process := '{}';
        roles_to_process := '{}';
        -- a bit kludgy, but only for 3.4 really.  Certainly no
        -- worse than the old code...
        if service_label_in = 'enterprise' or
           service_label_in = 'management' then
            ents_to_process := array_append(ents_to_process, 'sw_mgr_enterprise');

            roles_to_process := array_append(roles_to_process, 'org_admin');

            roles_to_process := array_append(roles_to_process, 'system_group_admin');

            roles_to_process := array_append(roles_to_process, 'activation_key_admin');
        elsif service_label_in = 'provisioning' then
            ents_to_process := array_append(ents_to_process, 'rhn_provisioning');

            roles_to_process := array_append(roles_to_process, 'system_group_admin');

            roles_to_process := array_append(roles_to_process, 'activation_key_admin');

            roles_to_process := array_append(roles_to_process, 'config_admin');
            -- another nasty special case...
            if enable_in = 'Y' then
                ents_to_process := array_append(ents_to_process, 'sw_mgr_enterprise');
            end if;
        elsif service_label_in = 'virtualization' then
            ents_to_process := array_append(ents_to_process, 'rhn_virtualization');

            roles_to_process := array_append(roles_to_process, 'config_admin');
        elsif service_label_in = 'virtualization_platform' then
            ents_to_process := array_append(ents_to_process, 'rhn_virtualization_platform');
            roles_to_process := array_append(roles_to_process, 'config_admin');
    elsif service_label_in = 'nonlinux' then
            ents_to_process := array_append(ents_to_process, 'rhn_nonlinux');
            roles_to_process := array_append(roles_to_process, 'config_admin');
        end if;

        if enable_in = 'Y' then
            for i in 1..array_upper(ents_to_process, 1) loop
                for ent in ents(ents_to_process[i]) loop
                    create_row := 'Y';
                    for oe in org_ents(ent.label) loop
                        create_row := 'N';
                    end loop;
                    if create_row = 'Y' then
                        insert into rhnOrgEntitlements(org_id, entitlement_id)
                            values (org_id_in, ent.id);
                    end if;
                end loop;
            end loop;
            for i in 1..array_upper(roles_to_process, 1) loop
                for role in roles(roles_to_process[i]) loop
                    create_row := 'Y';
                    for o_r in org_roles(role.label) loop
                        create_row := 'N';
                    end loop;
                    if create_row = 'Y' then
                        insert into rhnUserGroup(
                                id, name, description, current_members,
                                group_type, org_id
                            ) (
                                select  nextval('rhn_user_group_id_seq'),
                                        ugt.name || 's',
                                        ugt.name || 's for Org ' ||
                                            o.name || ' ('|| o.id ||')',
                                        0, ugt.id, o.id
                                from    rhnUserGroupType ugt,
                                        web_customer o
                                where   o.id = org_id_in
                                    and ugt.id = role.id
                            );
                    end if;
                end loop;
            end loop;
        else
            for i in 1..coalesce(array_upper(ents_to_process, 1), 0) loop
                for ent in ents(ents_to_process[i]) loop
                    delete from rhnOrgEntitlements
                     where org_id = org_id_in
                       and entitlement_id = ent.id;
                end loop;
            end loop;
        end if;
    end$$
language plpgsql;

    create or replace function set_customer_enterprise (
        customer_id_in in numeric
    ) returns void
as $$
    begin
        perform rhn_entitlements.modify_org_service(customer_id_in, 'enterprise', 'Y');
    end$$
language plpgsql;

    create or replace function set_customer_provisioning (
        customer_id_in in numeric
    ) returns void
as $$
    begin
        perform rhn_entitlements.modify_org_service(customer_id_in, 'provisioning', 'Y');
    end$$
language plpgsql;

    create or replace function set_customer_nonlinux (
        customer_id_in in numeric
    ) returns void
as $$
    begin
        perform rhn_entitlements.modify_org_service(customer_id_in, 'nonlinux', 'Y');
    end$$
language plpgsql;

    create or replace function unset_customer_enterprise (
        customer_id_in in numeric
    ) returns void
as $$
    begin
        perform rhn_entitlements.modify_org_service(customer_id_in, 'enterprise', 'N');
    end$$
language plpgsql;

    create or replace function unset_customer_provisioning (
        customer_id_in in numeric
    ) returns void
as $$
    begin
        perform rhn_entitlements.modify_org_service(customer_id_in, 'provisioning', 'N');
    end$$
language plpgsql;

    create or replace function unset_customer_nonlinux (
        customer_id_in in numeric
    ) returns void
as $$
    begin
        perform rhn_entitlements.modify_org_service(customer_id_in, 'nonlinux', 'N');
    end$$
language plpgsql;

    -- *******************************************************************
    -- PROCEDURE: prune_group
    -- Unsubscribes servers consuming physical slots that over the org's
    --   limit.
    -- Called by: set_server_group_count, repoll_virt_guest_entitlements
    -- *******************************************************************
    create or replace function prune_group (
        group_id_in in numeric,
        quantity_in in numeric
    ) returns void
as $$
    declare
        sgrecord record;
      type_is_base char;
    begin
            update      rhnServerGroup
                set     max_members = quantity_in
                where   id = group_id_in;

            for sgrecord in (
		   select  server_id, server_group_id, sgt.id as group_type_id, sgt.label
		    from    rhnServerGroupType              sgt,
				    rhnServerGroup                  sg,
				    rhnServerGroupMembers   sgm
		    where   1=1
			    and sgm.server_group_id = group_id_in
			    and sgm.server_id in (
				    select  sep.server_id
				    from
					rhnServerEntitlementPhysical sep
				    where
					sep.server_group_id = group_id_in
				    order by sep.modified asc
				    offset quantity_in
				)
			    and sgm.server_group_id = sg.id
			    and sg.group_type = sgt.id
	    ) loop
                perform rhn_entitlements.remove_server_entitlement(sgrecord.server_id, sgrecord.label);

            select is_base
            into type_is_base
            from rhnServerGroupType sgt
            where sgt.id = sgrecord.group_type_id;

            -- if we're removing a base ent, then be sure to
            -- remove the server's channel subscriptions.
            if ( type_is_base = 'Y' ) then
                   perform rhn_channel.clear_subscriptions(sgrecord.server_id, 0);
            end if;

            end loop;
    end$$
language plpgsql;

    -- *******************************************************************
    -- PROCEDURE: assign_system_entitlement
    --
    -- Moves system entitlements from from_org_id_in to to_org_id_in.
    -- Can raise not_enough_entitlements_in_base_org if from_org_id_in
    -- does not have enough entitlements to cover the move.
    -- Takes care of unentitling systems if necessary by calling
    -- set_server_group_count
    -- *******************************************************************
    create or replace function assign_system_entitlement(
        group_label_in in varchar,
        from_org_id_in in numeric,
        to_org_id_in in numeric,
        quantity_in in numeric
    ) returns void
as $$
    declare
        prev_ent_count numeric;
    to_org_prev_ent_count numeric;
        new_ent_count numeric;
    new_quantity numeric;
        group_type numeric;
    begin

            select max_members
            into prev_ent_count
            from rhnServerGroupType sgt,
                 rhnServerGroup sg
            where sg.org_id = from_org_id_in
              and sg.group_type = sgt.id
              and sgt.label = group_label_in;

            if not found then
                perform rhn_exception.raise_exception(
                              'not_enough_entitlements_in_base_org');
            end if;

            select max_members
            into to_org_prev_ent_count
            from rhnServerGroupType sgt,
                 rhnServerGroup sg
            where sg.org_id = to_org_id_in
              and sg.group_type = sgt.id
              and sgt.label = group_label_in;

            if not found then
                to_org_prev_ent_count := 0;
            end if;

            select id
            into group_type
            from rhnServerGroupType
            where label = group_label_in;

            if not found then
                perform rhn_exception.raise_exception(
                              'invalid_server_group');
            end if;

        new_ent_count := prev_ent_count - quantity_in;

        if prev_ent_count > new_ent_count then
            new_quantity := to_org_prev_ent_count + quantity_in;
        end if;

        if new_ent_count < 0 then
            perform rhn_exception.raise_exception(
                          'not_enough_entitlements_in_base_org');
        end if;


        perform rhn_entitlements.set_server_group_count(from_org_id_in,
                                         group_type,
                                         new_ent_count);

        perform rhn_entitlements.set_server_group_count(to_org_id_in,
                                         group_type,
                                         new_quantity);

        -- Create or delete the entries in rhnOrgEntitlementType
        if group_label_in = 'enterprise_entitled' then
            if new_quantity > 0 then
                perform rhn_entitlements.set_customer_enterprise(to_org_id_in);
            else
                perform rhn_entitlements.unset_customer_enterprise(to_org_id_in);
            end if;
        end if;

        if group_label_in = 'provisioning_entitled' then
            if new_quantity > 0 then
                perform rhn_entitlements.set_customer_provisioning(to_org_id_in);
            else
                perform rhn_entitlements.unset_customer_provisioning(to_org_id_in);
            end if;
        end if;

    end$$
language plpgsql;

    -- *******************************************************************
    -- PROCEDURE: activate_system_entitlement
    --
    -- Sets the values in rhnServerGroup for a given rhnServerGroupType.
    --
    -- Calls: set_server_group_count to update, prune, or create the group.
    -- Called by: the code that activates a satellite cert.
    --
    -- Raises not_enough_entitlements_in_base_org if all entitlements
    -- in the org are used so the free entitlements would not cover
    -- the difference when descreasing the number of entitlements.
    -- *******************************************************************
    create or replace function activate_system_entitlement(
        org_id_in in numeric,
        group_label_in in varchar,
        quantity_in in numeric
    ) returns void
as $$
    declare
        prev_ent_count numeric;
        prev_ent_count_sum numeric;
        group_type numeric;
    begin

        -- Fetch the current entitlement count for the org
        -- into prev_ent_count

            select current_members
            into prev_ent_count
            from rhnServerGroupType sgt,
                 rhnServerGroup sg
            where sg.group_type = sgt.id
              and sgt.label = group_label_in
              and sg.org_id = org_id_in;

            if not found then
                prev_ent_count := 0;
            end if;

            select id
            into group_type
            from rhnServerGroupType
            where label = group_label_in;

            if not found then
                perform rhn_exception.raise_exception(
                              'invalid_server_group');
            end if;

        -- If we're setting the total entitlemnt count to a lower value,
        -- and that value is less than the allocated count in this org,
        -- we need to raise an exception.
        if quantity_in < prev_ent_count then
            perform rhn_exception.raise_exception(
                          'not_enough_entitlements_in_base_org');
        else
            -- don't update family counts after every server
            -- will do bulk update afterwards
            perform rhn_entitlements.set_server_group_count(org_id_in,
                                             group_type,
                                             quantity_in);
        end if;

    end$$
language plpgsql;


    create or replace function set_server_group_count (
        customer_id_in in numeric,  -- customer_id
        group_type_in in numeric,   -- rhn[User|Server]GroupType.id
        quantity_in in numeric      -- quantity
    ) returns void
as $$
    declare
        group_id numeric;
        quantity numeric;
        wasfound boolean;
    begin
        quantity := quantity_in;
        if quantity is not null and quantity < 0 then
            quantity := 0;
        end if;

        select  rsg.id
        into    group_id
        from    rhnServerGroup rsg
        where   1=1
            and rsg.org_id = customer_id_in
            and rsg.group_type = group_type_in;

        -- preserve the not found status across the rhn_entitlements.prune_group invocation
        wasfound := true;
        if not found then
            wasfound := false;
        end if;

        perform rhn_entitlements.prune_group(
            group_id,
            quantity
        );

        if not wasfound then
            insert into rhnServerGroup (
                    id, name, description, max_members, current_members,
                    group_type, org_id, created, modified
                ) (
                    select  nextval('rhn_server_group_id_seq'), name, name,
                            quantity, 0, id, customer_id_in,
                            current_timestamp, current_timestamp
                    from    rhnServerGroupType
                    where   id = group_type_in
            );
        end if;

    end$$
language plpgsql;

    -- this expects quantity_in to be the number of available slots, not the
    -- max_members of the server group.  If you give it too many, it'll fail
    -- and raise servergroup_max_members.
    -- We should NEVER run this unless we're SURE that we won't
    -- be violating the max.
    create or replace function entitle_last_modified_servers (
        customer_id_in in numeric,  -- customer_id
        type_label_in in varchar,   -- 'enterprise_entitled'
        quantity_in in numeric      -- 3
    ) returns void
as $$
    declare
        -- find the servers that aren't currently in slots
        servers cursor(cid_in numeric, quant_in numeric) for
                                    select  rs.id as server_id
                                    from    rhnServer rs
                                    where   1=1
                                        and rs.org_id = cid_in
                                        and not exists (
                                            select  1
                                            from    rhnServerGroup sg,
                                                    rhnServerGroupMembers rsgm
                                            where   rsgm.server_id = rs.id
                                                and rsgm.server_group_id = sg.id
                                                and sg.group_type is not null
                                        )
                                        and not exists (
                                            select 1
                                            from rhnVirtualInstance vi
                                            where vi.virtual_system_id =
                                                  rs.id
                                        )
                                    order by modified desc
                                    limit quant_in;
    begin
        for server in servers(customer_id_in, quantity_in) loop
            perform rhn_entitlements.entitle_server(server.server_id, type_label_in);
        end loop;
    end$$
language plpgsql;

-- restore the original setting
update pg_settings set setting = overlay( setting placing '' from 1 for (length('rhn_entitlements')+1) ) where name = 'search_path';
  07070100000B0E000081B400000000000000000000000167AE1114000006F5000000000000000000000000000000000000007900000000susemanager-schema/upgrade/susemanager-schema-2.1.51-to-susemanager-schema-3.0/9015-modify-rhnAvailableChannels-view.sql  --
-- Copyright (c) 2008--2010 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
-- tricky view.  it explodes to a full cartesian product when
-- not queried via org_id, so DO NOT DO THAT :)

drop view rhnOrgErrata;
drop view rhnAvailableChannels;

create or replace view
rhnAvailableChannels
(
    	org_id,
	channel_id,
	channel_depth,
	channel_name,
	channel_arch_id,
	padded_name,
        last_modified,
        channel_label,
	parent_or_self_label,
	parent_or_self_id 
)
as
select
     ct.org_id,
     ct.id,
     CT.depth,
     CT.name,
     CT.channel_arch_id,
     CT.padded_name,
     CT.last_modified,
     CT.label,
     CT.parent_or_self_label,
     CT.parent_or_self_id
from
     rhnOrgChannelTreeView CT
UNION ALL
select
     ct.org_id,
     ct.id,
     CT.depth,
     CT.name,
     CT.channel_arch_id,
     CT.padded_name,
     CT.last_modified,
     CT.label,
     CT.parent_or_self_label,
     CT.parent_or_self_id
from
     rhnSharedChannelTreeView CT
;

create or replace view
rhnOrgErrata
(
        org_id,
        errata_id,
        channel_id
)
as
select
    ac.org_id,
    ce.errata_id,
    ac.channel_id
from
    rhnChannelErrata ce,
    rhnAvailableChannels ac
where
    ce.channel_id = ac.channel_id
;
   07070100000B0F000081B400000000000000000000000167AE111400000024000000000000000000000000000000000000007B00000000susemanager-schema/upgrade/susemanager-schema-2.1.51-to-susemanager-schema-3.0/9016-drop-rhnUserAvailableChannels-view.sql    drop view rhnUserAvailableChannels;
07070100000B10000081B400000000000000000000000167AE11140000001F000000000000000000000000000000000000007600000000susemanager-schema/upgrade/susemanager-schema-2.1.51-to-susemanager-schema-3.0/9017-drop-rhnServerFveCapable-view.sql drop view rhnServerFveCapable;
 07070100000B11000081B400000000000000000000000167AE111400000051000000000000000000000000000000000000008200000000susemanager-schema/upgrade/susemanager-schema-2.1.51-to-susemanager-schema-3.0/9018-channel_family_no_subscriptions-exception.sql -- 'channel_family_no_subscriptions'
delete from rhnException where id = -20235;
   07070100000B12000081B400000000000000000000000167AE111400000024000000000000000000000000000000000000007B00000000susemanager-schema/upgrade/susemanager-schema-2.1.51-to-susemanager-schema-3.0/9019-drop-rhnChannelFamilyOverview-view.sql    drop view rhnChannelFamilyOverview;
07070100000B13000081B400000000000000000000000167AE111400000025000000000000000000000000000000000000007C00000000susemanager-schema/upgrade/susemanager-schema-2.1.51-to-susemanager-schema-3.0/9020-drop-rhnChannelFamilyServerFve-view.sql   drop view rhnChannelFamilyServerFve;
   07070100000B14000081B400000000000000000000000167AE111400000023000000000000000000000000000000000000007A00000000susemanager-schema/upgrade/susemanager-schema-2.1.51-to-susemanager-schema-3.0/9021-drop-rhnChannelFamilyServers-view.sql drop view rhnChannelFamilyServers;
 07070100000B15000081B400000000000000000000000167AE111400000029000000000000000000000000000000000000008000000000susemanager-schema/upgrade/susemanager-schema-2.1.51-to-susemanager-schema-3.0/9022-drop-rhnChannelFamilyServerVirtual-view.sql   drop view rhnChannelFamilyServerVirtual;
   07070100000B16000081B400000000000000000000000167AE1114000010AF000000000000000000000000000000000000008300000000susemanager-schema/upgrade/susemanager-schema-2.1.51-to-susemanager-schema-3.0/9023-modify-rhnOrgChannelFamilyPermissions-view.sql    --
-- Copyright (c) 2008--2010 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--

drop view rhnOrgErrata;
drop view rhnAvailableChannels;
drop view rhnOrgChannelTreeView;
drop view rhnOrgChannelFamilyPermissions;

create or replace view rhnOrgChannelFamilyPermissions as
	select	pcf.channel_family_id,
		u.org_id as org_id,
		pcf.created,
		pcf.modified
	from	rhnPublicChannelFamily pcf,
		web_contact u
	union
	select	channel_family_id,
		org_id,
		created,
		modified
	from	rhnPrivateChannelFamily;

CREATE OR REPLACE VIEW rhnOrgChannelTreeView
(
        org_id,
        id,
        depth,
        name,
        padded_name,
        channel_arch_id,
        last_modified,
        label,
        parent_or_self_label,
        parent_or_self_id,
        end_of_life
)
AS
select * from (
        select  cfp.org_id              as org_id,
                c.id                    as id,
                1                       as depth,
                c.name                  as name,
                '  ' || c.name          as padded_name,
                c.channel_arch_id       as channel_arch_id,
                c.last_modified         as last_modified,
                c.label                 as label,
                c.label                 as parent_or_self_label,
                c.id                    as parent_or_self_id,
                c.end_of_life           as end_of_life
        from    rhnChannel              c,
                rhnChannelFamilyMembers cfm,
                rhnOrgChannelFamilyPermissions cfp
        where   cfp.channel_family_id = cfm.channel_family_id
                and cfm.channel_id = c.id
                and c.parent_channel is null
        union
        select  cfp.org_id              as org_id,
                c.id                    as id,
                2                       as depth,
                c.name                  as name,
                '' || c.name            as padded_name,
                c.channel_arch_id       as channel_arch_id,
                c.last_modified         as last_modified,
                c.label                 as label,
                pc.label                as parent_or_self_label,
                pc.id                   as parent_or_self_id,
                c.end_of_life           as end_of_life
         from    rhnChannel              pc,
                rhnChannel              c,
                rhnChannelFamilyMembers cfm,
                rhnOrgChannelFamilyPermissions cfp
        where   cfp.channel_family_id = cfm.channel_family_id
                and cfm.channel_id = c.id
                and c.parent_channel = pc.id
) s order by parent_or_self_label, parent_or_self_id;

create or replace view
rhnAvailableChannels
(
        org_id,
        channel_id,
        channel_depth,
        channel_name,
        channel_arch_id,
        padded_name,
        last_modified,
        channel_label,
        parent_or_self_label,
        parent_or_self_id
)
as
select
     ct.org_id,
     ct.id,
     CT.depth,
     CT.name,
     CT.channel_arch_id,
     CT.padded_name,
     CT.last_modified,
     CT.label,
     CT.parent_or_self_label,
     CT.parent_or_self_id
from
     rhnOrgChannelTreeView CT
UNION ALL
select
     ct.org_id,
     ct.id,
     CT.depth,
     CT.name,
     CT.channel_arch_id,
     CT.padded_name,
     CT.last_modified,
     CT.label,
     CT.parent_or_self_label,
     CT.parent_or_self_id
from
     rhnSharedChannelTreeView CT
;

create or replace view
rhnOrgErrata
(
        org_id,
        errata_id,
        channel_id
)
as
select
    ac.org_id,
    ce.errata_id,
    ac.channel_id
from
    rhnChannelErrata ce,
    rhnAvailableChannels ac
where
    ce.channel_id = ac.channel_id
;

 07070100000B17000081B400000000000000000000000167AE1114000010AD000000000000000000000000000000000000008200000000susemanager-schema/upgrade/susemanager-schema-2.1.51-to-susemanager-schema-3.0/9024-modify-rhnUserChannelFamilyPerms.sql-view.sql --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--

drop view rhnUserChannel;
drop view rhnUserChannelTreeView;
drop view rhnUserChannelFamilyPerms;

create or replace view rhnUserChannelFamilyPerms as
	select	pcf.channel_family_id,
		u.org_id as org_id,
		u.id as user_id,
		pcf.created,
		pcf.modified
	from	rhnPublicChannelFamily pcf,
		web_contact u
	union
	select	pcf.channel_family_id,
		u.org_id,
		u.id as user_id,
		pcf.created,
		pcf.modified
	from	rhnPrivateChannelFamily pcf,
		web_contact u
	where	u.org_id = pcf.org_id;

CREATE OR REPLACE VIEW rhnUserChannelTreeView
(
        user_id,
        org_id,
        id,
        depth,
        name,
        padded_name,
        channel_arch_id,
        last_modified,
        label,
        parent_or_self_label,
        parent_or_self_id,
        end_of_life
)
AS
select * from (
        select  cfp.user_id             as user_id,
                cfp.org_id              as org_id,
                c.id                    as id,
                1                       as depth,
                c.name                  as name,
                '  ' || c.name          as padded_name,
                c.channel_arch_id       as channel_arch_id,
                c.last_modified         as last_modified,
                c.label                 as label,
                c.label                 as parent_or_self_label,
                c.id                    as parent_or_self_id,
                c.end_of_life           as end_of_life
        from    rhnChannel              c,
                rhnChannelFamilyMembers cfm,
                rhnUserChannelFamilyPerms cfp
        where   cfp.channel_family_id = cfm.channel_family_id
                and cfm.channel_id = c.id
                and c.parent_channel is null
        union
        select  cfp.user_id             as user_id,
                cfp.org_id              as org_id,
                c.id                    as id,
                2                       as depth,
                c.name                  as name,
                '' || c.name            as padded_name,
                c.channel_arch_id       as channel_arch_id,
                c.last_modified         as last_modified,
                c.label                 as label,
                pc.label                as parent_or_self_label,
                pc.id                   as parent_or_self_id,
                c.end_of_life           as end_of_life
        from    rhnChannel              pc,
                rhnChannel              c,
                rhnChannelFamilyMembers cfm,
                rhnUserChannelFamilyPerms cfp
        where   cfp.channel_family_id = cfm.channel_family_id
                and cfm.channel_id = c.id
                and c.parent_channel = pc.id
) S order by parent_or_self_label, parent_or_self_id;

create or replace view rhnUserChannel
as
select
   cfp.user_id,
   cfp.org_id,
   cfm.channel_id,
   'manage' as role
from rhnChannelFamilyMembers cfm,
      rhnUserChannelFamilyPerms cfp
where
   cfp.channel_family_id = cfm.channel_family_id and
   rhn_channel.user_role_check(cfm.channel_id, cfp.user_id, 'manage') = 1
union all
select
   cfp.user_id,
   cfp.org_id,
   cfm.channel_id,
   'subscribe' as role
from rhnChannelFamilyMembers cfm,
      rhnUserChannelFamilyPerms cfp
where
   cfp.channel_family_id = cfm.channel_family_id and
   rhn_channel.user_role_check(cfm.channel_id, cfp.user_id, 'subscribe') = 1
union all
select
   w.id as user_id,
   w.org_id,
   s.id as channel_id,
   'subscribe' as role
from rhnSharedChannelView s,
      web_contact w
where
   w.org_id = s.org_trust_id and
   rhn_channel.user_role_check(s.id, w.id, 'subscribe') = 1;

   07070100000B18000081B400000000000000000000000167AE1114000003B0000000000000000000000000000000000000008000000000susemanager-schema/upgrade/susemanager-schema-2.1.51-to-susemanager-schema-3.0/9025-modify-rhnChannelFamilyPermissions-view.sql   --
-- Copyright (c) 2008--2010 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--

drop view rhnChannelFamilyPermissions;

create or replace view rhnChannelFamilyPermissions as
	select	channel_family_id,
		to_number(null, null) as org_id,
		created,
		modified
	from	rhnPublicChannelFamily
	union
	select	channel_family_id,
		org_id,
		created,
		modified
	from	rhnPrivateChannelFamily;

07070100000B19000081B400000000000000000000000167AE111400000104000000000000000000000000000000000000007D00000000susemanager-schema/upgrade/susemanager-schema-2.1.51-to-susemanager-schema-3.0/9026-drop-columns-rhnPrivateChannelFamily.sql  alter table rhnPrivateChannelFamily drop column max_members;
alter table rhnPrivateChannelFamily drop column current_members;
alter table rhnPrivateChannelFamily drop column fve_max_members;
alter table rhnPrivateChannelFamily drop column fve_current_members;
07070100000B1A000081B400000000000000000000000167AE11140000002A000000000000000000000000000000000000008100000000susemanager-schema/upgrade/susemanager-schema-2.1.51-to-susemanager-schema-3.0/9027-drop-rhnChannelFamilyServerPhysical-view.sql  drop view rhnChannelFamilyServerPhysical;
  07070100000B1B000081B400000000000000000000000167AE11140000007D000000000000000000000000000000000000007A00000000susemanager-schema/upgrade/susemanager-schema-2.1.51-to-susemanager-schema-3.0/9028-drop-is_fve-from-rhnServerChannel.sql ALTER TABLE rhnServerChannel DROP CONSTRAINT rhn_server_channel_is_fve_ck;
ALTER TABLE rhnServerChannel DROP COLUMN is_fve;

   07070100000B1C000081B400000000000000000000000167AE111400000048000000000000000000000000000000000000007E00000000susemanager-schema/upgrade/susemanager-schema-2.1.51-to-susemanager-schema-3.0/9029-drop-invalid_channel_family-exception.sql -- 'invalid_channel_family'
delete from rhnException where id = -20250;
07070100000B1D000081B400000000000000000000000167AE11140000004F000000000000000000000000000000000000008500000000susemanager-schema/upgrade/susemanager-schema-2.1.51-to-susemanager-schema-3.0/9030-drop-server_cannot_convert_to_flex-exception.sql  -- 'server_cannot_convert_to_flex'
delete from rhnException where id = -20295;
 07070100000B1E000081B400000000000000000000000167AE11140000005A000000000000000000000000000000000000009000000000susemanager-schema/upgrade/susemanager-schema-2.1.51-to-susemanager-schema-3.0/9031-drop-not_enough_flex_entitlements_in_base_org-exception.sql   -- 'not_enough_flex_entitlements_in_base_org'
delete from rhnException where id = -20294;
  07070100000B1F000081B400000000000000000000000167AE11140000004E000000000000000000000000000000000000008400000000susemanager-schema/upgrade/susemanager-schema-2.1.51-to-susemanager-schema-3.0/9032-drop-not_enough_flex_entitlements-exception.sql   -- 'not_enough_flex_entitlements'
delete from rhnException where id = -20296;
  07070100000B20000081B400000000000000000000000167AE11140000001D000000000000000000000000000000000000006E00000000susemanager-schema/upgrade/susemanager-schema-2.1.51-to-susemanager-schema-3.0/9051-drop_rhn_config_macro.sql DROP TABLE rhn_config_macro;
   07070100000B21000081B400000000000000000000000167AE1114000009F4000000000000000000000000000000000000007200000000susemanager-schema/upgrade/susemanager-schema-2.1.51-to-susemanager-schema-3.0/9052-delete_rhnServerGroupType.sql 
-- rhnServerGroup and dependencies

SELECT .clear_log_id();

DELETE FROM rhnOrgExtGroupMapping
  WHERE server_group_id in (
    SELECT id
      FROM rhnServerGroup
      WHERE group_type = (
        SELECT id
          FROM rhnServerGroupType
          WHERE label = 'provisioning_entitled'
      )
  );

DELETE FROM rhnRegTokenGroups
  WHERE server_group_id in (
    SELECT id
      FROM rhnServerGroup
      WHERE group_type = (
        SELECT id
          FROM rhnServerGroupType
          WHERE label = 'provisioning_entitled'
      )
  );

DELETE FROM rhnServerGroupMembers
  WHERE server_group_id in (
    SELECT id
      FROM rhnServerGroup
      WHERE group_type = (
        SELECT id
          FROM rhnServerGroupType
          WHERE label = 'provisioning_entitled'
      )
  );

DELETE FROM rhnSnapshotServerGroup
  WHERE server_group_id in (
    SELECT id
      FROM rhnServerGroup
      WHERE group_type = (
        SELECT id
          FROM rhnServerGroupType
          WHERE label = 'provisioning_entitled'
      )
  );

DELETE FROM rhnUserDefaultSystemGroups
  WHERE system_group_id in (
    SELECT id
      FROM rhnServerGroup
      WHERE group_type = (
        SELECT id
          FROM rhnServerGroupType
          WHERE label = 'provisioning_entitled'
      )
  );

DELETE FROM rhnUserServerGroupPerms
  WHERE server_group_id in (
    SELECT id
      FROM rhnServerGroup
      WHERE group_type = (
        SELECT id
          FROM rhnServerGroupType
          WHERE label = 'provisioning_entitled'
      )
  );

DELETE FROM rhnServerGroup
  WHERE group_type = (
    SELECT id
      FROM rhnServerGroupType
      WHERE label = 'provisioning_entitled'
  );

-- rhnServerGroupType and dependencies

DELETE FROM rhnRegTokenEntitlement
  WHERE server_group_type_id = (
    SELECT id
      FROM rhnServerGroupType
      WHERE label = 'provisioning_entitled'
  );

UPDATE rhnServerGroupTypeFeature
  SET server_group_type_id = (
    SELECT id
      FROM rhnServerGroupType
      WHERE label = 'enterprise_entitled'
  )
  WHERE server_group_type_id = (
    SELECT id
      FROM rhnServerGroupType
      WHERE label = 'provisioning_entitled'
  );

DELETE FROM rhnServerServerGroupArchCompat
  WHERE server_group_type = (
    SELECT id
      FROM rhnServerGroupType
      WHERE label = 'provisioning_entitled'
  );

DELETE FROM rhnSGTypeBaseAddonCompat
  WHERE addon_id = (
    SELECT id
      FROM rhnServerGroupType
      WHERE label = 'provisioning_entitled'
  );

DELETE FROM rhnServerGroupType
  WHERE label = 'provisioning_entitled';
07070100000B22000081B400000000000000000000000167AE111400000118000000000000000000000000000000000000007900000000susemanager-schema/upgrade/susemanager-schema-2.1.51-to-susemanager-schema-3.0/9053-update_rhnServerGroupTypeFeature.sql  UPDATE rhnServerGroupTypeFeature
  SET server_group_type_id = (
    SELECT id
      FROM rhnServerGroupType
      WHERE label = 'enterprise_entitled'
  )
  WHERE server_group_type_id = (
    SELECT id
      FROM rhnServerGroupType
      WHERE label = 'provisioning_entitled'
  );
07070100000B23000081B400000000000000000000000167AE1114000000D1000000000000000000000000000000000000007500000000susemanager-schema/upgrade/susemanager-schema-2.1.51-to-susemanager-schema-3.0/9054-update_rhnOrgEntitlementType.sql  DELETE FROM rhnOrgEntitlements
  WHERE entitlement_id IN (
    SELECT id FROM rhnOrgEntitlementType WHERE label = 'rhn_provisioning'
  );

DELETE FROM rhnOrgEntitlementType
  WHERE label = 'rhn_provisioning';
   07070100000B24000081B400000000000000000000000167AE111400009291000000000000000000000000000000000000008400000000susemanager-schema/upgrade/susemanager-schema-2.1.51-to-susemanager-schema-3.0/9055-drop-provisioning-from-rhn_entitlements_pkb.sql   --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

-- create schema rhn_entitlements;

-- setup search_path so that these functions are created in appropriate schema.
update pg_settings set setting = 'rhn_entitlements,' || setting where name = 'search_path';

   create or replace function find_compatible_sg (
      server_id_in in numeric,
      type_label_in in varchar
   )
   returns numeric
as $$
    declare
      servergroups cursor for
         select sg.id
           from rhnServerGroupType             sgt,
                rhnServerGroup                 sg,
                rhnServer                     s,
                rhnServerServerGroupArchCompat ssgac
          where s.id = server_id_in
            and s.org_id = sg.org_id
            and sgt.label = type_label_in
            and sg.group_type = sgt.id
            and ssgac.server_group_type = sgt.id
            and ssgac.server_arch_id = s.server_arch_id
            and not exists (
                     select 1
                      from rhnServerGroupMembers sgm
                     where sgm.server_group_id = sg.id
                       and sgm.server_id = s.id);


   begin
      for servergroup in servergroups loop
         return servergroup.id;
      end loop;

      --no servergroup found
      return NULL;
   end$$
language plpgsql;

    -- *******************************************************************
    -- PROCEDURE: remove_org_entitlements
    --
    -- Removes both system entitlements and channel subscriptions
    -- that are currently assigned to an org and re-assigns to the
    -- master org (org_id = 1).
    --
    -- When we call this we expect everything to already be unentitled
    -- which shoul be handled by delete_org.
    --
    -- Called by: delete_org
    -- *******************************************************************
    create or replace function remove_org_entitlements (
        org_id_in numeric
    ) returns void
as $$
    declare
        system_ents cursor for
        select sg.id, sg.max_members, sg.group_type
        from rhnServerGroup sg
        where group_type is not null
          and org_id = org_id_in;

    begin

        for system_ent in system_ents loop
            update rhnServerGroup
            set max_members = max_members + system_ent.max_members
            where org_id = 1
              and group_type = system_ent.group_type;
        end loop;

        update rhnServerGroup
        set max_members = 0
        where org_id = org_id_in;

    end$$
language plpgsql;

    create or replace function entitlement_grants_service (
        entitlement_in in varchar,
        service_level_in in varchar
    ) returns numeric
as $$
    begin
        if service_level_in = 'management' then
            if entitlement_in = 'enterprise_entitled' then
                return 1;
            else
                return 0;
            end if;
        elsif service_level_in = 'updates' then
            return 1;
        else
            return 0;
        end if;
    end$$
language plpgsql;

    create or replace function lookup_entitlement_group (
        org_id_in in numeric,
        type_label_in in varchar default 'sw_mgr_entitled'
    ) returns numeric
as $$
    declare
        server_groups cursor for
            select  sg.id               server_group_id
            from    rhnServerGroup      sg,
                    rhnServerGroupType  sgt
            where   sgt.label = type_label_in
                and sgt.id = sg.group_type
                and sg.org_id = org_id_in;
    begin
        for sg in server_groups loop
            return sg.server_group_id;
        end loop;
        return rhn_entitlements.create_entitlement_group(
                org_id_in,
                type_label_in
            );
    end$$
language plpgsql;

    create or replace function create_entitlement_group (
        org_id_in in numeric,
        type_label_in in varchar default 'sw_mgr_entitled'
    ) returns numeric
as $$
    declare
        sg_id_val numeric;
    begin
        select  nextval('rhn_server_group_id_seq')
        into    sg_id_val;

        insert into rhnServerGroup (
                id, name, description, max_members, current_members,
                group_type, org_id
            ) (
                select  sg_id_val, sgt.label, sgt.label,
                        0, 0, sgt.id, org_id_in
                from    rhnServerGroupType sgt
                where   sgt.label = type_label_in
            );

        return sg_id_val;
    end$$
language plpgsql;

   create or replace function can_entitle_server (
      server_id_in   in numeric,
      type_label_in  in varchar
   )
   returns numeric
as $$
    declare
      addon_servergroups cursor (base_label_in varchar,
                                 addon_label_in varchar) for
         select
            addon_id
         from
            rhnSGTypeBaseAddonCompat
         where base_id = lookup_sg_type (base_label_in)
           and addon_id = lookup_sg_type (addon_label_in);

      previous_ent        varchar[];
      is_base_in          char   := 'N';
      is_base_current     char   := 'N';
      i                   numeric := 0;
      sgid                numeric := 0;

   begin

      previous_ent := rhn_entitlements.get_server_entitlement(server_id_in);

      select distinct is_base
      into is_base_in
      from rhnServerGroupType
      where label = type_label_in;

      if array_upper(previous_ent, 1) is null or array_upper(previous_ent, 1) = 0 then
         if is_base_in = 'Y' then
            sgid := rhn_entitlements.find_compatible_sg (server_id_in, type_label_in);
            if sgid is not null then
              -- rhn_server.insert_into_servergroup (server_id_in, sgid);
              return 1;
            else
              -- rhn_exception.raise_exception ('invalid_base_entitlement');
              return 0;
            end if;
         else
            -- rhn_exception.raise_exception ('invalid_base_entitlement');
            return 0;
         end if;

      -- there are previous ents, first make sure we're not trying to entitle a base ent
      elsif is_base_in = 'Y' then
         -- rhn_exception.raise_exception ('invalid_addon_entitlement');
         return 0;

      -- it must be an addon, so proceed with the entitlement
      else

         -- find the servers base ent
         is_base_current := 'N';
         i := 0;
         while is_base_current = 'N' and i < array_upper(previous_ent, 1)
         loop
            i := i + 1;
            select is_base
            into is_base_current
            from rhnServerGroupType
            where label = previous_ent[i];
         end loop;

         -- never found a base ent, that would be strange
         if is_base_current  = 'N' then
            -- rhn_exception.raise_exception ('invalid_base_entitlement');
            return 0;
         end if;

         -- this for loop verifies the validity of the addon path
         for addon_servergroup in addon_servergroups  (previous_ent[i], type_label_in) loop
            -- find an appropriate sgid for the addon and entitle the server
            sgid := rhn_entitlements.find_compatible_sg (server_id_in, type_label_in);
            if sgid is not null then
               -- rhn_server.insert_into_servergroup (server_id_in, sgid);
               return 1;
            else
               -- rhn_exception.raise_exception ('invalid_addon_entitlement');
               return 0;
            end if;
         end loop;

      end if;

      return 0;

   end$$
language plpgsql;

   create or replace function can_switch_base (
      server_id_in   in    integer,
      type_label_in  in    varchar
   )
   returns numeric
as $$
   declare
      type_label_in_is_base   char(1);
      sgid                    numeric;

   begin

       select is_base into type_label_in_is_base
       from rhnServerGroupType
       where label = type_label_in;

       if not found then
          perform rhn_exception.raise_exception ( 'invalid_entitlement' );
       end if;

      if type_label_in_is_base = 'N' then
         perform rhn_exception.raise_exception ( 'invalid_entitlement' );
      else
         sgid := rhn_entitlements.find_compatible_sg ( server_id_in,
                                                       type_label_in );
         if sgid is not null then
           return 1;
         else
           return 0;
         end if;
      end if;

   end$$
language plpgsql;

    create or replace function entitle_server (
        server_id_in in numeric,
        type_label_in in varchar default 'sw_mgr_entitled'
    ) returns void
as $$
    declare
      sgid  numeric := 0;
      is_virt numeric := 0;

    begin

      select 1 into is_virt
        from rhnServerEntitlementView
        where server_id = server_id_in
          and label in ('virtualization_host', 'virtualization_host_platform');

      if not found then
          is_virt := 0;
      end if;

      if is_virt = 0 and (type_label_in = 'virtualization_host' or
                          type_label_in = 'virtualization_host_platform') then

        is_virt := 1;
      end if;

      if rhn_entitlements.can_entitle_server(server_id_in,
                                             type_label_in) = 1 then
         sgid := rhn_entitlements.find_compatible_sg (server_id_in,
                                                      type_label_in);
         if sgid is not null then
            insert into rhnServerHistory ( id, server_id, summary, details )
            values ( nextval('rhn_event_id_seq'), server_id_in,
                     'added system entitlement ',
                      case type_label_in
                       when 'enterprise_entitled' then 'Management'
                       when 'bootstrap_entitled' then 'Bootstrap'
                       when 'sw_mgr_entitled' then 'Update'
                       when 'virtualization_host' then 'Virtualization'
                       when 'virtualization_host_platform' then
                            'Virtualization Platform' end  );

            perform rhn_server.insert_into_servergroup (server_id_in, sgid);

            if is_virt = 1 then
              perform rhn_entitlements.repoll_virt_guest_entitlements(server_id_in);
            end if;

         else
            perform rhn_exception.raise_exception ('no_available_server_group');
         end if;
      else
         perform rhn_exception.raise_exception ('invalid_entitlement');
      end if;
   end$$
language plpgsql;

    create or replace function remove_server_entitlement (
        server_id_in in numeric,
        type_label_in in varchar default 'sw_mgr_entitled',
        repoll_virt_guests in numeric default 1
    ) returns void
as $$
    declare
      group_id numeric;
      type_is_base char;
      is_virt numeric := 0;
    begin
      -- would be nice if there were a virt attribute of entitlement types, not have to specify 2 different ones...
        select 1 into is_virt
          from rhnServerEntitlementView
          where server_id = server_id_in
            and label in ('virtualization_host', 'virtualization_host_platform');
        if not found then
            is_virt := 0;
        end if;

        select  sg.id, sgt.is_base
        into group_id, type_is_base
        from    rhnServerGroupType sgt,
            rhnServerGroup sg,
                rhnServerGroupMembers sgm,
                rhnServer s
        where   s.id = server_id_in
            and s.id = sgm.server_id
            and sgm.server_group_id = sg.id
            and sg.org_id = s.org_id
            and sgt.label = type_label_in
            and sgt.id = sg.group_type;

        if not found then
          perform rhn_exception.raise_exception('invalid_server_group_member');
        end if;

      if ( type_is_base = 'Y' ) then
         -- unentitle_server should handle everything, don't really need to do anything else special here
         perform rhn_entitlements.unentitle_server ( server_id_in );
      else

         insert into rhnServerHistory ( id, server_id, summary, details )
         values ( nextval('rhn_event_id_seq'), server_id_in,
                  'removed system entitlement ',
                   case type_label_in
                    when 'enterprise_entitled' then 'Management'
                    when 'bootstrap_entitled' then 'Bootstrap'
                    when 'sw_mgr_entitled' then 'Update'
                    when 'virtualization_host' then 'Virtualization'
                    when 'virtualization_host_platform' then
                         'Virtualization Platforrm' end  );

         perform rhn_server.delete_from_servergroup(server_id_in, group_id);

         if is_virt = 1 and repoll_virt_guests = 1 then
           perform rhn_entitlements.repoll_virt_guest_entitlements(server_id_in);
         end if;
      end if;

    end$$
language plpgsql;

    create or replace function unentitle_server (
        server_id_in in numeric
    ) returns void
as $$
    declare
      servergroups cursor for
         select distinct sgt.label, sg.id server_group_id
         from  rhnServerGroupType sgt,
               rhnServerGroup sg,
               rhnServer s,
               rhnServerGroupMembers sgm
         where s.id = server_id_in
            and s.org_id = sg.org_id
            and sg.group_type = sgt.id
            and sgm.server_group_id = sg.id
            and sgm.server_id = s.id;

     is_virt numeric := 0;

   begin

      select 1 into is_virt
        from rhnServerEntitlementView
        where server_id = server_id_in
         and label in ('virtualization_host', 'virtualization_host_platform');

      if not found then
          is_virt := 0;
      end if;

      for servergroup in servergroups loop

         insert into rhnServerHistory ( id, server_id, summary, details )
         values ( nextval('rhn_event_id_seq'), server_id_in,
                  'removed system entitlement ',
                   case servergroup.label
                    when 'enterprise_entitled' then 'Management'
                    when 'bootstrap_entitled' then 'Bootstrap'
                    when 'sw_mgr_entitled' then 'Update'
                    when 'virtualization_host' then 'Virtualization'
                    when 'virtualization_host_platform' then
                         'Virtualization Platform' end  );

         perform rhn_server.delete_from_servergroup(server_id_in,
                                            servergroup.server_group_id );
      end loop;

      if is_virt = 1 then
        perform rhn_entitlements.repoll_virt_guest_entitlements(server_id_in);
      end if;

   end$$
language plpgsql;


    -- *******************************************************************
    -- PROCEDURE: repoll_virt_guest_entitlements
    --
    --   Whenever we add/remove a virtualization_host* entitlement from
    --   a host, we can call this procedure to update what type of slots
    --   the guests are consuming.
    --
    --   If you're removing the entitlement, it's
    --   possible the guests will become unentitled if you don't have enough
    --   physical slots to cover them.
    --
    --   If you're adding the entitlement, you end up freeing up physical
    --   slots for other systems.
    --
    -- *******************************************************************
    create or replace function repoll_virt_guest_entitlements(
        server_id_in in numeric
    ) returns void
as $$
    declare
        -- All of server group types associated with the guests of
        -- server_id_in
        group_types cursor for
            select distinct sg.group_type, sgt.label, sg.org_id
            from
                rhnServerGroupType sgt,
                rhnServerGroup sg,
                rhnServerGroupMembers sgm,
                rhnVirtualInstance vi
            where
                vi.host_system_id = server_id_in
                and vi.virtual_system_id = sgm.server_id
                and sgm.server_group_id = sg.id
                and sg.group_type = sgt.id;

        -- Virtual servers from a certain family belonging to a specific
        -- host that are consuming physical system slots over the limit.
        virt_servers_sgt cursor(group_type_in numeric, quantity_in numeric) for
                select vi.virtual_system_id
                from
                    rhnServerGroup sg,
                    rhnServerGroupMembers sgm,
                    rhnVirtualInstance vi
                where
                    vi.host_system_id = server_id_in
                    and vi.virtual_system_id = sgm.server_id
                    and sgm.server_group_id = sg.id
                    and sg.group_type = group_type_in
                order by sgm.modified desc
                limit quantity_in;

        org_id_val numeric;
        max_members_val numeric;
        max_flex_val numeric;
        current_members_calc numeric;
        sg_id numeric;
        is_virt numeric := 0;
        free_slots numeric := 0;
    begin
          select 1 into is_virt
                from rhnServerEntitlementView
           where server_id = server_id_in
                 and label in ('virtualization_host', 'virtualization_host_platform');

      if not found then
          is_virt := 0;
      end if;

        select org_id
        into org_id_val
        from rhnServer
        where id = server_id_in;

        for a_group_type in group_types loop
          -- get the current *physical* members of the system entitlement type for the org...
          --
          -- unlike channel families, it appears the standard rhnServerGroup.max_members represents
          -- *physical* slots, vs physical+virt ... boy that's confusing...

          select max_members, id
            into max_members_val, sg_id
            from rhnServerGroup
            where group_type = a_group_type.group_type
            and org_id = a_group_type.org_id;


      select count(sep.server_id) into current_members_calc
            from rhnServerEntitlementPhysical sep
           where sep.server_group_id = sg_id
             and sep.server_group_type_id = a_group_type.group_type;

          if current_members_calc > max_members_val then
            -- A virtualization_host* ent must have been removed, and we're over the limit, so unsubscribe guests
            for virt_server in virt_servers_sgt(a_group_type.group_type,
                                                current_members_calc - max_members_val) loop
              perform rhn_entitlements.remove_server_entitlement(virt_server.virtual_system_id, a_group_type.label);

              -- decrement current_members_calc, we'll use it to reset current_members for the group at the end...
              current_members_calc := current_members_calc - 1;
            end loop;

          end if;

          update rhnServerGroup set current_members = current_members_calc
           where org_id = a_group_type.org_id
             and group_type = a_group_type.group_type;

          -- I think that's all the house-keeping we have to do...
        end loop;

    end$$
language plpgsql;

    create or replace function get_server_entitlement (
        server_id_in in numeric
    ) returns varchar[]
as $$
    declare
        server_groups cursor for
            select  sgt.label
            from    rhnServerGroupType      sgt,
                    rhnServerGroup          sg,
                    rhnServerGroupMembers   sgm
            where   1=1
                and sgm.server_id = server_id_in
                and sg.id = sgm.server_group_id
                and sgt.id = sg.group_type
                and sgt.label in (
                    'sw_mgr_entitled','enterprise_entitled', 'bootstrap_entitled',
                    'nonlinux_entitled','virtualization_host',
                    'virtualization_host_platform'
                    );

         ent_array varchar[];

    begin

      ent_array := '{}';

      for sg in server_groups loop
         ent_array := ent_array || sg.label;
      end loop;

      return ent_array;

    end$$
language plpgsql;

    -- this desperately needs to be table driven.
    create or replace function modify_org_service (
        org_id_in in numeric,
        service_label_in in varchar,
        enable_in in char
    ) returns void
as $$
    declare
        roles_to_process varchar[];
        roles cursor(role_label_in varchar) for
            select  label, id
            from    rhnUserGroupType
            where   label = role_label_in;
        org_roles cursor(role_label_in varchar) for
            select  1
            from    rhnUserGroup ug,
                    rhnUserGroupType ugt
            where   ugt.label = role_label_in
                and ug.org_id = org_id_in
                and ugt.id = ug.group_type;

        ents_to_process varchar[];
        ents cursor(ent_label_in varchar) for
            select  label, id
            from    rhnOrgEntitlementType
            where   label = ent_label_in;
        org_ents cursor(ent_label_in varchar) for
            select  1
            from    rhnOrgEntitlements oe,
                    rhnOrgEntitlementType oet
            where   oet.label = ent_label_in
                and oe.org_id = org_id_in
                and oet.id = oe.entitlement_id;
        create_row char(1);
    begin
        ents_to_process := '{}';
        roles_to_process := '{}';
        -- a bit kludgy, but only for 3.4 really.  Certainly no
        -- worse than the old code...
        if service_label_in = 'enterprise' or
           service_label_in = 'management' then
            ents_to_process := array_append(ents_to_process, 'sw_mgr_enterprise');

            roles_to_process := array_append(roles_to_process, 'org_admin');

            roles_to_process := array_append(roles_to_process, 'system_group_admin');

            roles_to_process := array_append(roles_to_process, 'activation_key_admin');
        elsif service_label_in = 'virtualization' then
            ents_to_process := array_append(ents_to_process, 'rhn_virtualization');

            roles_to_process := array_append(roles_to_process, 'config_admin');
        elsif service_label_in = 'virtualization_platform' then
            ents_to_process := array_append(ents_to_process, 'rhn_virtualization_platform');
            roles_to_process := array_append(roles_to_process, 'config_admin');
    elsif service_label_in = 'nonlinux' then
            ents_to_process := array_append(ents_to_process, 'rhn_nonlinux');
            roles_to_process := array_append(roles_to_process, 'config_admin');
        end if;

        if enable_in = 'Y' then
            for i in 1..array_upper(ents_to_process, 1) loop
                for ent in ents(ents_to_process[i]) loop
                    create_row := 'Y';
                    for oe in org_ents(ent.label) loop
                        create_row := 'N';
                    end loop;
                    if create_row = 'Y' then
                        insert into rhnOrgEntitlements(org_id, entitlement_id)
                            values (org_id_in, ent.id);
                    end if;
                end loop;
            end loop;
            for i in 1..array_upper(roles_to_process, 1) loop
                for role in roles(roles_to_process[i]) loop
                    create_row := 'Y';
                    for o_r in org_roles(role.label) loop
                        create_row := 'N';
                    end loop;
                    if create_row = 'Y' then
                        insert into rhnUserGroup(
                                id, name, description, current_members,
                                group_type, org_id
                            ) (
                                select  nextval('rhn_user_group_id_seq'),
                                        ugt.name || 's',
                                        ugt.name || 's for Org ' ||
                                            o.name || ' ('|| o.id ||')',
                                        0, ugt.id, o.id
                                from    rhnUserGroupType ugt,
                                        web_customer o
                                where   o.id = org_id_in
                                    and ugt.id = role.id
                            );
                    end if;
                end loop;
            end loop;
        else
            for i in 1..coalesce(array_upper(ents_to_process, 1), 0) loop
                for ent in ents(ents_to_process[i]) loop
                    delete from rhnOrgEntitlements
                     where org_id = org_id_in
                       and entitlement_id = ent.id;
                end loop;
            end loop;
        end if;
    end$$
language plpgsql;

    create or replace function set_customer_enterprise (
        customer_id_in in numeric
    ) returns void
as $$
    begin
        perform rhn_entitlements.modify_org_service(customer_id_in, 'enterprise', 'Y');
    end$$
language plpgsql;

    create or replace function set_customer_nonlinux (
        customer_id_in in numeric
    ) returns void
as $$
    begin
        perform rhn_entitlements.modify_org_service(customer_id_in, 'nonlinux', 'Y');
    end$$
language plpgsql;

    create or replace function unset_customer_enterprise (
        customer_id_in in numeric
    ) returns void
as $$
    begin
        perform rhn_entitlements.modify_org_service(customer_id_in, 'enterprise', 'N');
    end$$
language plpgsql;

    create or replace function unset_customer_nonlinux (
        customer_id_in in numeric
    ) returns void
as $$
    begin
        perform rhn_entitlements.modify_org_service(customer_id_in, 'nonlinux', 'N');
    end$$
language plpgsql;

    -- *******************************************************************
    -- PROCEDURE: prune_group
    -- Unsubscribes servers consuming physical slots that over the org's
    --   limit.
    -- Called by: set_server_group_count, repoll_virt_guest_entitlements
    -- *******************************************************************
    create or replace function prune_group (
        group_id_in in numeric,
        quantity_in in numeric
    ) returns void
as $$
    declare
        sgrecord record;
      type_is_base char;
    begin
            update      rhnServerGroup
                set     max_members = quantity_in
                where   id = group_id_in;

            for sgrecord in (
		   select  server_id, server_group_id, sgt.id as group_type_id, sgt.label
		    from    rhnServerGroupType              sgt,
				    rhnServerGroup                  sg,
				    rhnServerGroupMembers   sgm
		    where   1=1
			    and sgm.server_group_id = group_id_in
			    and sgm.server_id in (
				    select  sep.server_id
				    from
					rhnServerEntitlementPhysical sep
				    where
					sep.server_group_id = group_id_in
				    order by sep.modified asc
				    offset quantity_in
				)
			    and sgm.server_group_id = sg.id
			    and sg.group_type = sgt.id
	    ) loop
                perform rhn_entitlements.remove_server_entitlement(sgrecord.server_id, sgrecord.label);

            select is_base
            into type_is_base
            from rhnServerGroupType sgt
            where sgt.id = sgrecord.group_type_id;

            -- if we're removing a base ent, then be sure to
            -- remove the server's channel subscriptions.
            if ( type_is_base = 'Y' ) then
                   perform rhn_channel.clear_subscriptions(sgrecord.server_id, 0);
            end if;

            end loop;
    end$$
language plpgsql;

    -- *******************************************************************
    -- PROCEDURE: assign_system_entitlement
    --
    -- Moves system entitlements from from_org_id_in to to_org_id_in.
    -- Can raise not_enough_entitlements_in_base_org if from_org_id_in
    -- does not have enough entitlements to cover the move.
    -- Takes care of unentitling systems if necessary by calling
    -- set_server_group_count
    -- *******************************************************************
    create or replace function assign_system_entitlement(
        group_label_in in varchar,
        from_org_id_in in numeric,
        to_org_id_in in numeric,
        quantity_in in numeric
    ) returns void
as $$
    declare
        prev_ent_count numeric;
    to_org_prev_ent_count numeric;
        new_ent_count numeric;
    new_quantity numeric;
        group_type numeric;
    begin

            select max_members
            into prev_ent_count
            from rhnServerGroupType sgt,
                 rhnServerGroup sg
            where sg.org_id = from_org_id_in
              and sg.group_type = sgt.id
              and sgt.label = group_label_in;

            if not found then
                perform rhn_exception.raise_exception(
                              'not_enough_entitlements_in_base_org');
            end if;

            select max_members
            into to_org_prev_ent_count
            from rhnServerGroupType sgt,
                 rhnServerGroup sg
            where sg.org_id = to_org_id_in
              and sg.group_type = sgt.id
              and sgt.label = group_label_in;

            if not found then
                to_org_prev_ent_count := 0;
            end if;

            select id
            into group_type
            from rhnServerGroupType
            where label = group_label_in;

            if not found then
                perform rhn_exception.raise_exception(
                              'invalid_server_group');
            end if;

        new_ent_count := prev_ent_count - quantity_in;

        if prev_ent_count > new_ent_count then
            new_quantity := to_org_prev_ent_count + quantity_in;
        end if;

        if new_ent_count < 0 then
            perform rhn_exception.raise_exception(
                          'not_enough_entitlements_in_base_org');
        end if;


        perform rhn_entitlements.set_server_group_count(from_org_id_in,
                                         group_type,
                                         new_ent_count);

        perform rhn_entitlements.set_server_group_count(to_org_id_in,
                                         group_type,
                                         new_quantity);

        -- Create or delete the entries in rhnOrgEntitlementType
        if group_label_in = 'enterprise_entitled' then
            if new_quantity > 0 then
                perform rhn_entitlements.set_customer_enterprise(to_org_id_in);
            else
                perform rhn_entitlements.unset_customer_enterprise(to_org_id_in);
            end if;
        end if;

    end$$
language plpgsql;

    -- *******************************************************************
    -- PROCEDURE: activate_system_entitlement
    --
    -- Sets the values in rhnServerGroup for a given rhnServerGroupType.
    --
    -- Calls: set_server_group_count to update, prune, or create the group.
    -- Called by: the code that activates a satellite cert.
    --
    -- Raises not_enough_entitlements_in_base_org if all entitlements
    -- in the org are used so the free entitlements would not cover
    -- the difference when descreasing the number of entitlements.
    -- *******************************************************************
    create or replace function activate_system_entitlement(
        org_id_in in numeric,
        group_label_in in varchar,
        quantity_in in numeric
    ) returns void
as $$
    declare
        prev_ent_count numeric;
        prev_ent_count_sum numeric;
        group_type numeric;
    begin

        -- Fetch the current entitlement count for the org
        -- into prev_ent_count

            select current_members
            into prev_ent_count
            from rhnServerGroupType sgt,
                 rhnServerGroup sg
            where sg.group_type = sgt.id
              and sgt.label = group_label_in
              and sg.org_id = org_id_in;

            if not found then
                prev_ent_count := 0;
            end if;

            select id
            into group_type
            from rhnServerGroupType
            where label = group_label_in;

            if not found then
                perform rhn_exception.raise_exception(
                              'invalid_server_group');
            end if;

        -- If we're setting the total entitlemnt count to a lower value,
        -- and that value is less than the allocated count in this org,
        -- we need to raise an exception.
        if quantity_in < prev_ent_count then
            perform rhn_exception.raise_exception(
                          'not_enough_entitlements_in_base_org');
        else
            -- don't update family counts after every server
            -- will do bulk update afterwards
            perform rhn_entitlements.set_server_group_count(org_id_in,
                                             group_type,
                                             quantity_in);
        end if;

    end$$
language plpgsql;


    create or replace function set_server_group_count (
        customer_id_in in numeric,  -- customer_id
        group_type_in in numeric,   -- rhn[User|Server]GroupType.id
        quantity_in in numeric      -- quantity
    ) returns void
as $$
    declare
        group_id numeric;
        quantity numeric;
        wasfound boolean;
    begin
        quantity := quantity_in;
        if quantity is not null and quantity < 0 then
            quantity := 0;
        end if;

        select  rsg.id
        into    group_id
        from    rhnServerGroup rsg
        where   1=1
            and rsg.org_id = customer_id_in
            and rsg.group_type = group_type_in;

        -- preserve the not found status across the rhn_entitlements.prune_group invocation
        wasfound := true;
        if not found then
            wasfound := false;
        end if;

        perform rhn_entitlements.prune_group(
            group_id,
            quantity
        );

        if not wasfound then
            insert into rhnServerGroup (
                    id, name, description, max_members, current_members,
                    group_type, org_id, created, modified
                ) (
                    select  nextval('rhn_server_group_id_seq'), name, name,
                            quantity, 0, id, customer_id_in,
                            current_timestamp, current_timestamp
                    from    rhnServerGroupType
                    where   id = group_type_in
            );
        end if;

    end$$
language plpgsql;

    -- this expects quantity_in to be the number of available slots, not the
    -- max_members of the server group.  If you give it too many, it'll fail
    -- and raise servergroup_max_members.
    -- We should NEVER run this unless we're SURE that we won't
    -- be violating the max.
    create or replace function entitle_last_modified_servers (
        customer_id_in in numeric,  -- customer_id
        type_label_in in varchar,   -- 'enterprise_entitled'
        quantity_in in numeric      -- 3
    ) returns void
as $$
    declare
        -- find the servers that aren't currently in slots
        servers cursor(cid_in numeric, quant_in numeric) for
                                    select  rs.id as server_id
                                    from    rhnServer rs
                                    where   1=1
                                        and rs.org_id = cid_in
                                        and not exists (
                                            select  1
                                            from    rhnServerGroup sg,
                                                    rhnServerGroupMembers rsgm
                                            where   rsgm.server_id = rs.id
                                                and rsgm.server_group_id = sg.id
                                                and sg.group_type is not null
                                        )
                                        and not exists (
                                            select 1
                                            from rhnVirtualInstance vi
                                            where vi.virtual_system_id =
                                                  rs.id
                                        )
                                    order by modified desc
                                    limit quant_in;
    begin
        for server in servers(customer_id_in, quantity_in) loop
            perform rhn_entitlements.entitle_server(server.server_id, type_label_in);
        end loop;
    end$$
language plpgsql;

-- restore the original setting
update pg_settings set setting = overlay( setting placing '' from 1 for (length('rhn_entitlements')+1) ) where name = 'search_path';
   07070100000B25000081B400000000000000000000000167AE1114000002C2000000000000000000000000000000000000006900000000susemanager-schema/upgrade/susemanager-schema-2.1.51-to-susemanager-schema-3.0/9057-create_first_org.sql  --
-- Copyright (c) 2015 SUSE LLC.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--

drop function if exists create_first_org(name_in in varchar, password_in in varchar);
  07070100000B26000081B400000000000000000000000167AE111400006104000000000000000000000000000000000000007E00000000susemanager-schema/upgrade/susemanager-schema-2.1.51-to-susemanager-schema-3.0/9059-drop-provisioning-from-rhn_server_pkb.sql --
-- Copyright (c) 2008--2014 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--

-- create schema rhn_server;

--update pg_setting
update pg_settings set setting = 'rhn_server,' || setting where name = 'search_path';

    create or replace function system_service_level(
    	server_id_in in numeric,
	service_level_in in varchar
    ) returns numeric as $$
    declare
    ents cursor is 
      select label from rhnServerEntitlementView
      where server_id = server_id_in;

    retval numeric := 0;

    begin
         for ent in ents loop
            retval := rhn_entitlements.entitlement_grants_service (ent.label, service_level_in);
            if retval = 1 then
               return retval;
            end if;
         end loop;

         return retval;

    end$$ language plpgsql;

        
    create or replace function can_change_base_channel(server_id_in IN NUMERIC)
    returns numeric
    as $$
    declare
    	throwaway numeric;
    begin
    	-- the idea: if we get past this query, the server is
	-- neither sat nor proxy, so base channel is changeable

	select 1 into throwaway
	  from rhnServer S
	 where S.id = server_id_in
	   and not exists (select 1 from rhnSatelliteInfo SI where SI.server_id = S.id)
	   and not exists (select 1 from rhnProxyInfo PI where PI.server_id = S.id);

        if not found then
	    return 0;
        end if;
	   
	return 1;
    end$$ language plpgsql;
	        
    create or replace function set_custom_value(
    	server_id_in in numeric,
	user_id_in in numeric,
	key_label_in in varchar,
	value_in in varchar
    ) returns void
    as $$
    declare
    	key_id_val numeric;
    begin
    	select CDK.id into strict key_id_val
	  from rhnCustomDataKey CDK,
	       rhnServer S
	 where S.id = server_id_in
	   and S.org_id = CDK.org_id
	   and CDK.label = key_label_in;
	   
	begin
	    insert into rhnServerCustomDataValue (server_id, key_id, value, created_by, last_modified_by)
	    values (server_id_in, key_id_val, value_in, user_id_in, user_id_in);
	exception
	    when UNIQUE_VIOLATION
	    	then
		update rhnServerCustomDataValue
		   set value = value_in,
		       last_modified_by = user_id_in
		 where server_id = server_id_in
		   and key_id = key_id_val;		   
	end;

    end$$ language plpgsql;
    
    create or replace function bulk_set_custom_value(
    	key_label_in in varchar,
	value_in in varchar,
	set_label_in in varchar,
	set_uid_in in numeric
    )
    returns integer
    as $$
    declare
        i integer;
        server record;
    begin
        i := 0;
        for server in (
           SELECT user_id, label, element, element_two
	     FROM rhnSet
	    WHERE label = set_label_in
	      AND user_id = set_uid_in
	) loop
	    if rhn_server.system_service_level(server.element, 'management') = 1 then
	    	perform rhn_server.set_custom_value(server.element, set_uid_in, key_label_in, value_in);
            i := i + 1;
	    end if;
	end loop;
    return i;
    end$$ language plpgsql;

    create or replace function bulk_snapshot_tag(
    	org_id_in in numeric,
        tagname_in in varchar,
	set_label_in in varchar,
	set_uid_in in numeric
    ) returns void
    as $$
    declare
        server record;
    	snapshot_id numeric;
    begin
        for server in (
           SELECT user_id, label, element, element_two
	     FROM rhnSet
	    WHERE label = set_label_in
	      AND user_id = set_uid_in
	    ) loop
	    if rhn_server.system_service_level(server.element, 'management') = 1 then
	    	    select max(id) into snapshot_id
	    	    from rhnSnapshot
	    	    where server_id = server.element;

	    	    if snapshot_id is null then
		    	perform rhn_server.snapshot_server(server.element, 'tagging system:  ' || tagname_in);
			
			select max(id) into snapshot_id
			from rhnSnapshot
			where server_id = server.element;
		    end if;
		 
		-- now have a snapshot_id to work with...
		begin
		    perform rhn_server.tag_snapshot(snapshot_id, org_id_in, tagname_in);
		exception
		    when UNIQUE_VIOLATION
		    	then
			-- do nothing, be forgiving...
			null;
		end;
	    end if;
	end loop;    
    end$$ language plpgsql;

    create or replace function tag_delete(
    	server_id_in in numeric,
	tag_id_in in numeric
    ) returns void
    as $$
    declare
    	snapshots cursor is
		select	snapshot_id
		from	rhnSnapshotTag
		where	tag_id = tag_id_in;
	tag_id_tmp numeric;
    begin
    	select	id into tag_id_tmp
	from	rhnTag
	where	id = tag_id_in
	for update;

	delete
		from	rhnSnapshotTag
		where	server_id = server_id_in
			and tag_id = tag_id_in;
	for snapshot in snapshots loop
		return;
	end loop;
	delete
		from rhnTag
		where id = tag_id_in;
    end$$ language plpgsql;

    create or replace function tag_snapshot(
        snapshot_id_in in numeric,
	org_id_in in numeric,
	tagname_in in varchar
    ) returns void
    as $$
    begin
    	insert into rhnSnapshotTag (snapshot_id, server_id, tag_id)
	select snapshot_id_in, server_id, lookup_tag(org_id_in, tagname_in)
	from rhnSnapshot
	where id = snapshot_id_in;
    end$$ language plpgsql;

    create or replace function bulk_snapshot(
    	reason_in in varchar,
	set_label_in in varchar,
	set_uid_in in numeric
    ) returns void
    as $$
    declare
        server record;
    begin
        for server in (
           SELECT user_id, label, element, element_two
	     FROM rhnSet
	    WHERE label = set_label_in
	      AND user_id = set_uid_in
	    ) loop
	    if rhn_server.system_service_level(server.element, 'management') = 1 then
	    	perform rhn_server.snapshot_server(server.element, reason_in);
	    end if;
	end loop;
    end$$ language plpgsql;

    create or replace function snapshot_server(
    	server_id_in in numeric,
	reason_in in varchar
    ) returns void
    as $$
    declare
    	snapshot_id_v numeric;
	revisions cursor is
		select distinct
			cr.id
		from	rhnConfigRevision	cr,
			rhnConfigFileName	cfn,
			rhnConfigFile		cf,
			rhnConfigChannel	cc,
			rhnServerConfigChannel	scc
		where	1=1
			and scc.server_id = server_id_in
			and scc.config_channel_id = cc.id
			and cc.id = cf.config_channel_id
			and cf.id = cr.config_file_id
			and cr.id = cf.latest_config_revision_id
			and cf.config_file_name_id = cfn.id
			and cf.id = lookup_first_matching_cf(scc.server_id, cfn.path);
	locked integer;
    begin
    	select nextval('rhn_snapshot_id_seq') into snapshot_id_v;

	insert into rhnSnapshot (id, org_id, server_id, reason) (
		select	snapshot_id_v,
			s.org_id,
			server_id_in,
			reason_in
		from	rhnServer s
		where	s.id = server_id_in
	);
	insert into rhnSnapshotChannel (snapshot_id, channel_id) (
		select	snapshot_id_v, sc.channel_id
		from	rhnServerChannel sc
		where	sc.server_id = server_id_in
	);
	insert into rhnSnapshotServerGroup (snapshot_id, server_group_id) (
		select	snapshot_id_v, sgm.server_group_id
		from	rhnServerGroupMembers sgm
		where	sgm.server_id = server_id_in
	);
        locked := 0;
        <<iloop>>
        while true loop
            begin
                insert into rhnPackageNEVRA (id, name_id, evr_id, package_arch_id)
                select nextval('rhn_pkgnevra_id_seq'), sp.name_id, sp.evr_id, sp.package_arch_id
                from rhnServerPackage sp
                where sp.server_id = server_id_in
                        and not exists
                        (select 1
                                from rhnPackageNEVRA nevra
                                where nevra.name_id = sp.name_id
                                        and nevra.evr_id = sp.evr_id
                                        and (nevra.package_arch_id = sp.package_arch_id
                                            or (nevra.package_arch_id is null
                                                and sp.package_arch_id is null)));
                exit iloop;
            exception when unique_violation then
                if locked = 1 then
                    raise;
                else
                    lock table rhnPackageNEVRA in exclusive mode;
                    locked := 1;
                end if;
            end;
        end loop;
	insert into rhnSnapshotPackage (snapshot_id, nevra_id) (
                select distinct snapshot_id_v, nevra.id
                from    rhnServerPackage sp, rhnPackageNEVRA nevra
                where   sp.server_id = server_id_in
                        and nevra.name_id = sp.name_id
                        and nevra.evr_id = sp.evr_id
                        and (nevra.package_arch_id = sp.package_arch_id
                            or (nevra.package_arch_id is null
                                and sp.package_arch_id is null))
	);

	insert into rhnSnapshotConfigChannel ( snapshot_id, config_channel_id ) (
		select	snapshot_id_v, scc.config_channel_id
		from	rhnServerConfigChannel scc
		where	server_id = server_id_in
	);

	for revision in revisions loop
		insert into rhnSnapshotConfigRevision (
				snapshot_id, config_revision_id
			) values (
				snapshot_id_v, revision.id
			);
	end loop;
    end$$ language plpgsql;

    create or replace function remove_action(
    	server_id_in in numeric,
	action_id_in in numeric
    ) returns void
    as $$
    declare
    	-- this really wants "nulls last", but 8.1.7.3.0 sucks ass.
	-- instead, we make a local table that holds our
	-- list of ids with null prereqs.  There's surely a better way
	-- (an array instead of a table maybe?  who knows...)
	-- but I've got code to do this handy that I can look at ;)
    	chained_actions cursor is
                with recursive r(id, prerequisite) as (
			select	id, prerequisite
			from	rhnAction
			where id = action_id_in
		union all
			select	r1.id, r1.prerequisite
			from	rhnAction r1, r
			where r.id = r1.prerequisite
		)
		select * from r
		order by prerequisite desc;
	sessions cursor is
		select	s.id
		from	rhnKickstartSession s
		where	server_id_in in (s.old_server_id, s.new_server_id)
			and s.action_id = action_id_in
			and not exists (
				select	1
				from	rhnKickstartSessionState ss
				where	ss.id = s.state_id
					and ss.label in ('failed','complete')
			);
	chain_ends numeric[];
	i numeric;
	prereq numeric := 1;
    begin
	select	prerequisite
	into	prereq
	from	rhnAction
	where	id = action_id_in;

	if prereq is not null then
		perform rhn_exception.raise_exception('action_is_child');
	end if;

        chain_ends := '{}';
	i := 1;
	for action in chained_actions loop
		if action.prerequisite is null then
			chain_ends[i] := action.id;
			i := i + 1;
		else
			delete from rhnServerAction
				where server_id = server_id_in
				and action_id = action.id;
		end if;
	end loop;

	delete from rhnServerAction
		where server_id = server_id_in
		and action_id = any(chain_ends);

	for s in sessions loop
		update rhnKickstartSession
			set 	state_id = (
					select	id
					from	rhnKickstartSessionState
					where	label = 'failed'
				),
				action_id = null
			where	id = s.id;
		perform set_ks_session_history_message(s.id, 'failed', 'Kickstart cancelled due to action removal');
	end loop;
    end$$ language plpgsql;
   
    create or replace function check_user_access(server_id_in in numeric, user_id_in in numeric)
    returns numeric
    as $$
    declare
    	has_access numeric;
    begin
    	-- first check; if this returns no rows, then the server/user are in different orgs, and we bail
        select 1 into has_access
	  from rhnServer S,
	       web_contact wc
	 where wc.org_id = s.org_id
	   and s.id = server_id_in
	   and wc.id = user_id_in;

        if not found then
          return 0;
        end if;

	-- okay, so they're in the same org.  if we have an org admin, they get a free pass
    	if rhn_user.check_role(user_id_in, 'org_admin') = 1
	then
	    return 1;
	end if;
		   
    	select 1 into has_access
	  from rhnServerGroupMembers SGM,
	       rhnUserServerGroupPerms USG
	 where SGM.server_group_id = USG.server_group_id
	   and SGM.server_id = server_id_in
	   and USG.user_id = user_id_in;

        if not found then
          return 0;
        end if;
	   
	return 1;
    end$$ language plpgsql;

    -- *******************************************************************
    -- FUNCTION: can_server_consume_virt_slot
    -- Returns 1 if the server id is eligible to consume a virtual slot,
    --   else returns 0.
    -- Called by: insert_into_servergroup, delete_from_servergroup
    -- *******************************************************************
    create or replace function can_server_consume_virt_slot(server_id_in in numeric,
                                           group_type_in in varchar)
    returns numeric                                           
    as $$
    declare
        server_virt_slots cursor is
            select vi.VIRTUAL_SYSTEM_ID
            from
                rhnVirtualInstance vi
            where
                -- server id is a virtual instance
                vi.VIRTUAL_SYSTEM_ID = server_id_in
                -- server id's host is virt entitled
                and exists ( select 1
                     from rhnServerEntitlementView sev
                 where vi.HOST_SYSTEM_ID = sev.server_id
                 and sev.label in ('virtualization_host',
                                   'virtualization_host_platform') )
                -- server id's host also has the ent we want
                and exists ( select 1
                     from rhnServerEntitlementView sev2
                 where vi.HOST_SYSTEM_ID = sev2.server_id
                 and sev2.label = group_type_in );

    begin
        for server_virt_slot in server_virt_slots loop
            return 1;
        end loop;
        return 0;
    end$$ language plpgsql;


    create or replace function insert_into_servergroup (
		server_id_in in numeric,
		server_group_id_in in numeric
    ) returns void
    as $$
    declare
		used_slots numeric;
		max_slots numeric;
		org_id numeric;
		mgmt_available numeric;
		mgmt_upgrade numeric;
		mgmt_sgid numeric;
		prov_available numeric;
		prov_upgrade numeric;
		prov_sgid numeric;
		group_label varchar;
		group_type numeric;
	begin
		-- first, group_type = null, because it's easy...

		-- this will rowlock the servergroup we're trying to change;
		-- we probably need to lock the other one, but I think the chances
		-- of it being a real issue are very small for now...
		select	sg.group_type, sg.org_id, sg.current_members, sg.max_members
		into	group_type, org_id, used_slots, max_slots
		from	rhnServerGroup sg
		where	sg.id = server_group_id_in
		for update of sg;

		if group_type is null then
			if used_slots >= max_slots then
				perform rhn_exception.raise_exception('servergroup_max_members');
			end if;

			insert into rhnServerGroupMembers(
					server_id, server_group_id
				) values (
					server_id_in, server_group_id_in
				);
			update rhnServerGroup
				set current_members = current_members + 1
				where id = server_group_id_in;

			perform rhn_cache.update_perms_for_server_group(server_group_id_in);
			return;
		end if;

		-- now for group_type != null
		-- 
		select	label
		into	group_label
		from	rhnServerGroupType	sgt
		where	sgt.id = group_type;

		-- the naive easy path that gets hit most often and has to be quickest.
		if group_label in ('sw_mgr_entitled',
                           'enterprise_entitled',
                           'bootstrap_entitled',
                           'virtualization_host',
                           'virtualization_host_platform') then
			if used_slots >= max_slots and 
               (rhn_server.can_server_consume_virt_slot(server_id_in, group_label) != 1) 
               then
				perform rhn_exception.raise_exception('servergroup_max_members');
			end if;

			insert into rhnServerGroupMembers(
					server_id, server_group_id
				) values (
					server_id_in, server_group_id_in
				);

            -- Only update current members if the system in consuming a 
            -- physical slot.
            if rhn_server.can_server_consume_virt_slot(server_id_in, group_label) = 0 then
                update rhnServerGroup
                set current_members = current_members + 1
                where id = server_group_id_in;
            end if;                

			return;
		end if;
	end$$ language plpgsql;

	create or replace function insert_into_servergroup_maybe (
		server_id_in in numeric,
		server_group_id_in in numeric
	) returns numeric as $$ 
    declare
		retval numeric := 0;
		servergroups cursor is
			select	s.id	server_id,
					sg.id	server_group_id
			from	rhnServerGroup	sg,
					rhnServer		s
			where	s.id = server_id_in
				and sg.id = server_group_id_in
				and s.org_id = sg.org_id
				and not exists (
					select	1
					from	rhnServerGroupMembers sgm
					where	sgm.server_id = s.id
						and sgm.server_group_id = sg.id
				);
	begin
		for sgm in servergroups loop
			perform rhn_server.insert_into_servergroup(sgm.server_id, sgm.server_group_id);
			retval := retval + 1;
		end loop;
		return retval;
	end$$ language plpgsql;

	create or replace function insert_set_into_servergroup (
		server_group_id_in in numeric,
		user_id_in in numeric,
		set_label_in in varchar
	) returns void
        as $$
    declare
		servers cursor is
			select	st.element	id
			from	rhnSet		st
			where	st.user_id = user_id_in
				and st.label = set_label_in
				and exists (
					select	1
					from	rhnUserManagedServerGroups umsg
					where	umsg.server_group_id = server_group_id_in
						and umsg.user_id = user_id_in
					)
				and not exists (
					select	1
					from	rhnServerGroupMembers sgm
					where	sgm.server_id = st.element
						and sgm.server_group_id = server_group_id_in
				);
	begin
		for s in servers loop
			perform rhn_server.insert_into_servergroup(s.id, server_group_id_in);
		end loop;
	end$$ language plpgsql;
		
    create or replace function delete_from_servergroup (
    	server_id_in in numeric,
		server_group_id_in in numeric
    ) returns void
    as $$
    declare
        server_virt_groups cursor is
            select 1
            from rhnServerEntitlementVirtual sev
            where sev.server_id = server_id_in
            and sev.server_group_id = server_group_id_in;

		oid numeric;
		mgmt_sgid numeric;
		label varchar;
		group_type numeric;
	begin
			select	sg.group_type, sg.org_id
			into	group_type,	oid
			from	rhnServerGroupMembers	sgm,
					rhnServerGroup			sg
			where	sg.id = server_group_id_in
				and sg.id = sgm.server_group_id
				and sgm.server_id = server_id_in
			for update of sg;

			if not found then
				perform rhn_exception.raise_exception('server_not_in_group');
			end if;

		-- do group_type is null first
		if group_type is null then
			delete from rhnServerGroupMembers
				where server_group_id = server_group_id_in
				and	server_id = server_id_in;
			update rhnServerGroup
				set current_members = current_members - 1
				where id = server_group_id_in;
			perform rhn_cache.update_perms_for_server_group(server_group_id_in);
			return;
		end if;

		select	sgt.label
		into	label
		from	rhnServerGroupType sgt
		where	sgt.id = group_type;

		if label in ('sw_mgr_entitled',
                     'enterprise_entitled', 
                     'bootstrap_entitled',
                     'virtualization_host',
                     'virtualization_host_platform') then

            -- Only update current members if the system is consuming
            -- a physical slot.
            for server_virt_group in server_virt_groups loop                
                delete from rhnServerGroupMembers
                where server_group_id = server_group_id_in
                and	server_id = server_id_in;
                return;
            end loop;                

            delete from rhnServerGroupMembers
            where server_group_id = server_group_id_in
            and	server_id = server_id_in;

            update rhnServerGroup
            set current_members = current_members - 1
            where id = server_group_id_in;

		end if;
	end$$ language plpgsql;

	create or replace function delete_set_from_servergroup (
		server_group_id_in in numeric,
		user_id_in in numeric,
		set_label_in in varchar
	) returns void
        as $$	
        declare
		servergroups cursor is
			select	sgm.server_id, sgm.server_group_id
			from	rhnSet st,
					rhnServerGroupMembers sgm
			where	sgm.server_group_id = server_group_id_in
				and st.user_id = user_id_in
				and st.label = set_label_in
				and sgm.server_id = st.element
				and exists (
					select	1
					from	rhnUserManagedServerGroups usgp
					where	usgp.server_group_id = server_group_id_in
						and usgp.user_id = user_id_in
				);
	begin
		for sgm in servergroups loop
			perform rhn_server.delete_from_servergroup(sgm.server_id, server_group_id_in);
		end loop;
	end$$ language plpgsql;

	create or replace function clear_servergroup (
		server_group_id_in in numeric
	) returns void
        as $$
        declare
		servers cursor is
			select	sgm.server_id	id
			from	rhnServerGroupMembers sgm
			where	sgm.server_group_id = server_group_id_in;
	begin
		for s in servers loop
			perform rhn_server.delete_from_servergroup(s.id, server_group_id_in);
		end loop;
	end$$ language plpgsql;

	create or replace function delete_from_org_servergroups (
		server_id_in in numeric
	) returns void
        as $$
        declare
		servergroups cursor is
			select	sgm.server_group_id id
			from	rhnServerGroup sg,
					rhnServerGroupMembers sgm
			where	sgm.server_id = server_id_in
				and sgm.server_group_id = sg.id
				and sg.group_type is null;
	begin
		for sg in servergroups loop
			perform rhn_server.delete_from_servergroup(server_id_in, sg.id);
		end loop;
	end$$ language plpgsql;

	create or replace function get_ip_address (
		server_id_in in numeric
	) returns varchar as $$
        declare
		interfaces cursor is
			select	ni.name as name, na4.address as address
			from	rhnServerNetInterface ni,
			        rhnServerNetAddress4 na4
			where	server_id = server_id_in
                and ni.id = na4.interface_id
				and na4.address != '127.0.0.1';
		addresses cursor is
			select	ipaddr ip_addr
			from	rhnServerNetwork
			where	server_id = server_id_in
				and ipaddr != '127.0.0.1';
	begin
		for addr in addresses loop
			return addr.ip_addr;
		end loop;
		for iface in interfaces loop
			return iface.address;
		end loop;
		return NULL;
	end$$ language plpgsql;

    create or replace function update_needed_cache(
        server_id_in in numeric
	) returns void as $$
    declare
      update_lock numeric;
    begin
      select id into update_lock from rhnServer where id = server_id_in for update;
      delete from rhnServerNeededCache
        where server_id = server_id_in;
      insert into rhnServerNeededCache
             (server_id, errata_id, package_id, channel_id)
        (select distinct sp.server_id, x.errata_id, p.id, x.channel_id
           FROM (SELECT sp_sp.server_id, sp_sp.name_id,
		        sp_sp.package_arch_id, max(sp_pe.evr) AS max_evr
                   FROM rhnServerPackage sp_sp
                   join rhnPackageEvr sp_pe ON sp_pe.id = sp_sp.evr_id
                  GROUP BY sp_sp.server_id, sp_sp.name_id, sp_sp.package_arch_id) sp
           join rhnPackage p ON p.name_id = sp.name_id
           join rhnPackageEvr pe ON pe.id = p.evr_id AND sp.max_evr < pe.evr
           join rhnPackageUpgradeArchCompat puac
	            ON puac.package_arch_id = sp.package_arch_id
		    AND puac.package_upgrade_arch_id = p.package_arch_id
           join rhnServerChannel sc ON sc.server_id = sp.server_id
           join rhnChannelPackage cp ON cp.package_id = p.id
	            AND cp.channel_id = sc.channel_id
           left join (SELECT ep.errata_id, ce.channel_id, ep.package_id
                        FROM rhnChannelErrata ce
                        join rhnErrataPackage ep
			         ON ep.errata_id = ce.errata_id
			join rhnServerChannel sc_sc
			         ON sc_sc.channel_id = ce.channel_id
		       WHERE sc_sc.server_id = server_id_in) x
             ON x.channel_id = sc.channel_id AND x.package_id = cp.package_id
          where sp.server_id = server_id_in);
	end$$ language plpgsql;
-- restore the original setting
update pg_settings set setting = overlay( setting placing '' from 1 for (length('rhn_server')+1) ) where name = 'search_path';
07070100000B27000081B400000000000000000000000167AE111400000161000000000000000000000000000000000000007000000000susemanager-schema/upgrade/susemanager-schema-2.1.51-to-susemanager-schema-3.0/9060-delete_monitoring_admin.sql   DELETE FROM rhnUserGroupMembers WHERE user_group_id IN (SELECT g.id from rhnUserGroup g JOIN rhnUserGroupType gt ON g.group_type = gt.id WHERE gt.label = 'monitoring_admin');

DELETE FROM rhnUserGroup WHERE group_type IN (SELECT id FROM rhnUserGroupType WHERE label = 'monitoring_admin');

DELETE FROM rhnUserGroupType WHERE label = 'monitoring_admin';
   07070100000B28000081B400000000000000000000000167AE11140000047D000000000000000000000000000000000000008200000000susemanager-schema/upgrade/susemanager-schema-2.1.51-to-susemanager-schema-3.0/9060-drop-provisioning-from-rhnEntitledServers.sql --
-- Copyright (c) 2008 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--

create or replace view
rhnEntitledServers
as
select distinct
    S.id,
    S.org_id,
    S.digital_server_id,
    S.server_arch_id,
    S.os,
    S.release,
    S.name,
    S.description,
    S.info,
    S.secret
from
    rhnServerGroup SG,
    rhnServerGroupType SGT,
    rhnServerGroupMembers SGM,
    rhnServer S
where
    S.id = SGM.server_id
and SG.id = SGM.server_group_id
and SGT.label IN ('sw_mgr_entitled', 'enterprise_entitled', 'bootstrap_entitled')
and SG.group_type = SGT.id
and SG.org_id = S.org_id
;

   07070100000B29000081B400000000000000000000000167AE111400000022000000000000000000000000000000000000007400000000susemanager-schema/upgrade/susemanager-schema-2.1.51-to-susemanager-schema-3.0/9071-drop_rhn_contact_monitoring.sql   DROP VIEW rhn_contact_monitoring;
  07070100000B2A000081B400000000000000000000000167AE111400000023000000000000000000000000000000000000007500000000susemanager-schema/upgrade/susemanager-schema-2.1.51-to-susemanager-schema-3.0/9081-drop_rhn_customer_monitoring.sql  DROP VIEW rhn_customer_monitoring;
 07070100000B2B000081B400000000000000000000000167AE11140000001F000000000000000000000000000000000000007100000000susemanager-schema/upgrade/susemanager-schema-2.1.51-to-susemanager-schema-3.0/9091-drop_rhn_host_monitoring.sql  DROP VIEW rhn_host_monitoring;
 07070100000B2C000081B400000000000000000000000167AE11140000881D000000000000000000000000000000000000006D00000000susemanager-schema/upgrade/susemanager-schema-2.1.51-to-susemanager-schema-3.0/9095-rhn_entitlements.pkb.sql  --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

-- create schema rhn_entitlements;

-- setup search_path so that these functions are created in appropriate schema.
update pg_settings set setting = 'rhn_entitlements,' || setting where name = 'search_path';

   create or replace function find_compatible_sg (
      server_id_in in numeric,
      type_label_in in varchar
   )
   returns numeric
as $$
    declare
      servergroups cursor for
         select sg.id
           from rhnServerGroupType             sgt,
                rhnServerGroup                 sg,
                rhnServer                     s,
                rhnServerServerGroupArchCompat ssgac
          where s.id = server_id_in
            and s.org_id = sg.org_id
            and sgt.label = type_label_in
            and sg.group_type = sgt.id
            and ssgac.server_group_type = sgt.id
            and ssgac.server_arch_id = s.server_arch_id
            and not exists (
                     select 1
                      from rhnServerGroupMembers sgm
                     where sgm.server_group_id = sg.id
                       and sgm.server_id = s.id);


   begin
      for servergroup in servergroups loop
         return servergroup.id;
      end loop;

      --no servergroup found
      return NULL;
   end$$
language plpgsql;

    -- *******************************************************************
    -- PROCEDURE: remove_org_entitlements
    --
    -- Removes both system entitlements and channel subscriptions
    -- that are currently assigned to an org and re-assigns to the
    -- master org (org_id = 1).
    --
    -- When we call this we expect everything to already be unentitled
    -- which shoul be handled by delete_org.
    --
    -- Called by: delete_org
    -- *******************************************************************
    create or replace function remove_org_entitlements (
        org_id_in numeric
    ) returns void
as $$
    declare
        system_ents cursor for
        select sg.id, sg.max_members, sg.group_type
        from rhnServerGroup sg
        where group_type is not null
          and org_id = org_id_in;

    begin

        for system_ent in system_ents loop
            update rhnServerGroup
            set max_members = max_members + system_ent.max_members
            where org_id = 1
              and group_type = system_ent.group_type;
        end loop;

        update rhnServerGroup
        set max_members = 0
        where org_id = org_id_in;

    end$$
language plpgsql;

    create or replace function entitlement_grants_service (
        entitlement_in in varchar,
        service_level_in in varchar
    ) returns numeric
as $$
    begin
        if service_level_in = 'management' then
            if entitlement_in = 'enterprise_entitled' then
                return 1;
            else
                return 0;
            end if;
        elsif service_level_in = 'updates' then
            return 1;
        else
            return 0;
        end if;
    end$$
language plpgsql;

   create or replace function can_entitle_server (
      server_id_in   in numeric,
      type_label_in  in varchar
   )
   returns numeric
as $$
    declare
      addon_servergroups cursor (base_label_in varchar,
                                 addon_label_in varchar) for
         select
            addon_id
         from
            rhnSGTypeBaseAddonCompat
         where base_id = lookup_sg_type (base_label_in)
           and addon_id = lookup_sg_type (addon_label_in);

      previous_ent        varchar[];
      is_base_in          char   := 'N';
      is_base_current     char   := 'N';
      i                   numeric := 0;
      sgid                numeric := 0;

   begin

      previous_ent := rhn_entitlements.get_server_entitlement(server_id_in);

      select distinct is_base
      into is_base_in
      from rhnServerGroupType
      where label = type_label_in;

      if array_upper(previous_ent, 1) is null or array_upper(previous_ent, 1) = 0 then
         if is_base_in = 'Y' then
            sgid := rhn_entitlements.find_compatible_sg (server_id_in, type_label_in);
            if sgid is not null then
              -- rhn_server.insert_into_servergroup (server_id_in, sgid);
              return 1;
            else
              -- rhn_exception.raise_exception ('invalid_base_entitlement');
              return 0;
            end if;
         else
            -- rhn_exception.raise_exception ('invalid_base_entitlement');
            return 0;
         end if;

      -- there are previous ents, first make sure we're not trying to entitle a base ent
      elsif is_base_in = 'Y' then
         -- rhn_exception.raise_exception ('invalid_addon_entitlement');
         return 0;

      -- it must be an addon, so proceed with the entitlement
      else

         -- find the servers base ent
         is_base_current := 'N';
         i := 0;
         while is_base_current = 'N' and i < array_upper(previous_ent, 1)
         loop
            i := i + 1;
            select is_base
            into is_base_current
            from rhnServerGroupType
            where label = previous_ent[i];
         end loop;

         -- never found a base ent, that would be strange
         if is_base_current  = 'N' then
            -- rhn_exception.raise_exception ('invalid_base_entitlement');
            return 0;
         end if;

         -- this for loop verifies the validity of the addon path
         for addon_servergroup in addon_servergroups  (previous_ent[i], type_label_in) loop
            -- find an appropriate sgid for the addon and entitle the server
            sgid := rhn_entitlements.find_compatible_sg (server_id_in, type_label_in);
            if sgid is not null then
               -- rhn_server.insert_into_servergroup (server_id_in, sgid);
               return 1;
            else
               -- rhn_exception.raise_exception ('invalid_addon_entitlement');
               return 0;
            end if;
         end loop;

      end if;

      return 0;

   end$$
language plpgsql;

   create or replace function can_switch_base (
      server_id_in   in    integer,
      type_label_in  in    varchar
   )
   returns numeric
as $$
   declare
      type_label_in_is_base   char(1);
      sgid                    numeric;

   begin

       select is_base into type_label_in_is_base
       from rhnServerGroupType
       where label = type_label_in;

       if not found then
          perform rhn_exception.raise_exception ( 'invalid_entitlement' );
       end if;

      if type_label_in_is_base = 'N' then
         perform rhn_exception.raise_exception ( 'invalid_entitlement' );
      else
         sgid := rhn_entitlements.find_compatible_sg ( server_id_in,
                                                       type_label_in );
         if sgid is not null then
           return 1;
         else
           return 0;
         end if;
      end if;

   end$$
language plpgsql;
    
    -- workaround: dropping the function - in past default arg. values were
    -- changed and postgres doesn't like it (ERROR: cannot remove parameter
    -- defaults from existing function)
    drop function if exists entitle_server(numeric, varchar);

    create or replace function entitle_server (
        server_id_in in numeric,
        type_label_in in varchar
    ) returns void
as $$
    declare
      sgid  numeric := 0;
      is_virt numeric := 0;

    begin

      select 1 into is_virt
        from rhnServerEntitlementView
        where server_id = server_id_in
          and label = 'virtualization_host';

      if not found then
          is_virt := 0;
      end if;

      if is_virt = 0 and type_label_in = 'virtualization_host' then
        is_virt := 1;
      end if;

      if rhn_entitlements.can_entitle_server(server_id_in,
                                             type_label_in) = 1 then
         sgid := rhn_entitlements.find_compatible_sg (server_id_in,
                                                      type_label_in);
         if sgid is not null then
            insert into rhnServerHistory ( id, server_id, summary, details )
            values ( nextval('rhn_event_id_seq'), server_id_in,
                     'added system entitlement ',
                      case type_label_in
                       when 'enterprise_entitled' then 'Management'
                       when 'bootstrap_entitled' then 'Bootstrap'
                       when 'virtualization_host' then 'Virtualization'
                      end  );

            perform rhn_server.insert_into_servergroup (server_id_in, sgid);

            if is_virt = 1 then
              perform rhn_entitlements.repoll_virt_guest_entitlements(server_id_in);
            end if;

         else
            perform rhn_exception.raise_exception ('no_available_server_group');
         end if;
      else
         perform rhn_exception.raise_exception ('invalid_entitlement');
      end if;
   end$$
language plpgsql;

    -- workaround: dropping the function - in past default arg. values were
    -- changed and postgres doesn't like it (ERROR: cannot remove parameter
    -- defaults from existing function)
    drop function if exists remove_server_entitlement(numeric, varchar, numeric);

    create or replace function remove_server_entitlement (
        server_id_in in numeric,
        type_label_in in varchar,
        repoll_virt_guests in numeric default 1
    ) returns void
as $$
    declare
      group_id numeric;
      type_is_base char;
      is_virt numeric := 0;
    begin
      -- would be nice if there were a virt attribute of entitlement types, not have to specify 2 different ones...
        select 1 into is_virt
          from rhnServerEntitlementView
          where server_id = server_id_in
            and label = 'virtualization_host';
        if not found then
            is_virt := 0;
        end if;

        select  sg.id, sgt.is_base
        into group_id, type_is_base
        from    rhnServerGroupType sgt,
            rhnServerGroup sg,
                rhnServerGroupMembers sgm,
                rhnServer s
        where   s.id = server_id_in
            and s.id = sgm.server_id
            and sgm.server_group_id = sg.id
            and sg.org_id = s.org_id
            and sgt.label = type_label_in
            and sgt.id = sg.group_type;

        if not found then
          perform rhn_exception.raise_exception('invalid_server_group_member');
        end if;

      if ( type_is_base = 'Y' ) then
         -- unentitle_server should handle everything, don't really need to do anything else special here
         perform rhn_entitlements.unentitle_server ( server_id_in );
      else

         insert into rhnServerHistory ( id, server_id, summary, details )
         values ( nextval('rhn_event_id_seq'), server_id_in,
                  'removed system entitlement ',
                   case type_label_in
                    when 'enterprise_entitled' then 'Management'
                    when 'bootstrap_entitled' then 'Bootstrap'
                    when 'virtualization_host' then 'Virtualization'
                   end  );

         perform rhn_server.delete_from_servergroup(server_id_in, group_id);

         if is_virt = 1 and repoll_virt_guests = 1 then
           perform rhn_entitlements.repoll_virt_guest_entitlements(server_id_in);
         end if;
      end if;

    end$$
language plpgsql;

    create or replace function unentitle_server (
        server_id_in in numeric
    ) returns void
as $$
    declare
      servergroups cursor for
         select distinct sgt.label, sg.id server_group_id
         from  rhnServerGroupType sgt,
               rhnServerGroup sg,
               rhnServer s,
               rhnServerGroupMembers sgm
         where s.id = server_id_in
            and s.org_id = sg.org_id
            and sg.group_type = sgt.id
            and sgm.server_group_id = sg.id
            and sgm.server_id = s.id;

     is_virt numeric := 0;

   begin

      select 1 into is_virt
        from rhnServerEntitlementView
        where server_id = server_id_in
         and label = 'virtualization_host';

      if not found then
          is_virt := 0;
      end if;

      for servergroup in servergroups loop

         insert into rhnServerHistory ( id, server_id, summary, details )
         values ( nextval('rhn_event_id_seq'), server_id_in,
                  'removed system entitlement ',
                   case servergroup.label
                    when 'enterprise_entitled' then 'Management'
                    when 'bootstrap_entitled' then 'Bootstrap'
                    when 'virtualization_host' then 'Virtualization'
                   end  );

         perform rhn_server.delete_from_servergroup(server_id_in,
                                            servergroup.server_group_id );
      end loop;

      if is_virt = 1 then
        perform rhn_entitlements.repoll_virt_guest_entitlements(server_id_in);
      end if;

   end$$
language plpgsql;


    -- *******************************************************************
    -- PROCEDURE: repoll_virt_guest_entitlements
    --
    --   Whenever we add/remove a virtualization_host* entitlement from
    --   a host, we can call this procedure to update what type of slots
    --   the guests are consuming.
    --
    --   If you're removing the entitlement, it's
    --   possible the guests will become unentitled if you don't have enough
    --   physical slots to cover them.
    --
    --   If you're adding the entitlement, you end up freeing up physical
    --   slots for other systems.
    --
    -- *******************************************************************
    create or replace function repoll_virt_guest_entitlements(
        server_id_in in numeric
    ) returns void
as $$
    declare
        -- All of server group types associated with the guests of
        -- server_id_in
        group_types cursor for
            select distinct sg.group_type, sgt.label, sg.org_id
            from
                rhnServerGroupType sgt,
                rhnServerGroup sg,
                rhnServerGroupMembers sgm,
                rhnVirtualInstance vi
            where
                vi.host_system_id = server_id_in
                and vi.virtual_system_id = sgm.server_id
                and sgm.server_group_id = sg.id
                and sg.group_type = sgt.id;

        -- Virtual servers from a certain family belonging to a specific
        -- host that are consuming physical system slots over the limit.
        virt_servers_sgt cursor(group_type_in numeric, quantity_in numeric) for
                select vi.virtual_system_id
                from
                    rhnServerGroup sg,
                    rhnServerGroupMembers sgm,
                    rhnVirtualInstance vi
                where
                    vi.host_system_id = server_id_in
                    and vi.virtual_system_id = sgm.server_id
                    and sgm.server_group_id = sg.id
                    and sg.group_type = group_type_in
                order by sgm.modified desc
                limit quantity_in;

        org_id_val numeric;
        max_members_val numeric;
        max_flex_val numeric;
        current_members_calc numeric;
        sg_id numeric;
        is_virt numeric := 0;
        free_slots numeric := 0;
    begin
          select 1 into is_virt
                from rhnServerEntitlementView
           where server_id = server_id_in
                 and label = 'virtualization_host';

      if not found then
          is_virt := 0;
      end if;

        select org_id
        into org_id_val
        from rhnServer
        where id = server_id_in;

        for a_group_type in group_types loop
          -- get the current *physical* members of the system entitlement type for the org...
          --
          -- unlike channel families, it appears the standard rhnServerGroup.max_members represents
          -- *physical* slots, vs physical+virt ... boy that's confusing...

          select max_members, id
            into max_members_val, sg_id
            from rhnServerGroup
            where group_type = a_group_type.group_type
            and org_id = a_group_type.org_id;


      select count(sep.server_id) into current_members_calc
            from rhnServerEntitlementPhysical sep
           where sep.server_group_id = sg_id
             and sep.server_group_type_id = a_group_type.group_type;

          if current_members_calc > max_members_val then
            -- A virtualization_host* ent must have been removed, and we're over the limit, so unsubscribe guests
            for virt_server in virt_servers_sgt(a_group_type.group_type,
                                                current_members_calc - max_members_val) loop
              perform rhn_entitlements.remove_server_entitlement(virt_server.virtual_system_id, a_group_type.label);

              -- decrement current_members_calc, we'll use it to reset current_members for the group at the end...
              current_members_calc := current_members_calc - 1;
            end loop;

          end if;

          update rhnServerGroup set current_members = current_members_calc
           where org_id = a_group_type.org_id
             and group_type = a_group_type.group_type;

          -- I think that's all the house-keeping we have to do...
        end loop;

    end$$
language plpgsql;

    create or replace function get_server_entitlement (
        server_id_in in numeric
    ) returns varchar[]
as $$
    declare
        server_groups cursor for
            select  sgt.label
            from    rhnServerGroupType      sgt,
                    rhnServerGroup          sg,
                    rhnServerGroupMembers   sgm
            where   1=1
                and sgm.server_id = server_id_in
                and sg.id = sgm.server_group_id
                and sgt.id = sg.group_type
                and sgt.label in (
                    'enterprise_entitled',
                    'bootstrap_entitled',
                    'virtualization_host'
                    );

         ent_array varchar[];

    begin

      ent_array := '{}';

      for sg in server_groups loop
         ent_array := ent_array || sg.label;
      end loop;

      return ent_array;

    end$$
language plpgsql;

    -- this desperately needs to be table driven.
    create or replace function modify_org_service (
        org_id_in in numeric,
        service_label_in in varchar,
        enable_in in char
    ) returns void
as $$
    declare
        roles_to_process varchar[];
        roles cursor(role_label_in varchar) for
            select  label, id
            from    rhnUserGroupType
            where   label = role_label_in;
        org_roles cursor(role_label_in varchar) for
            select  1
            from    rhnUserGroup ug,
                    rhnUserGroupType ugt
            where   ugt.label = role_label_in
                and ug.org_id = org_id_in
                and ugt.id = ug.group_type;

        ents_to_process varchar[];
        ents cursor(ent_label_in varchar) for
            select  label, id
            from    rhnOrgEntitlementType
            where   label = ent_label_in;
        org_ents cursor(ent_label_in varchar) for
            select  1
            from    rhnOrgEntitlements oe,
                    rhnOrgEntitlementType oet
            where   oet.label = ent_label_in
                and oe.org_id = org_id_in
                and oet.id = oe.entitlement_id;
        create_row char(1);
    begin
        ents_to_process := '{}';
        roles_to_process := '{}';
        -- a bit kludgy, but only for 3.4 really.  Certainly no
        -- worse than the old code...
        if service_label_in = 'enterprise' or
           service_label_in = 'management' then
            ents_to_process := array_append(ents_to_process, 'sw_mgr_enterprise');

            roles_to_process := array_append(roles_to_process, 'org_admin');

            roles_to_process := array_append(roles_to_process, 'system_group_admin');

            roles_to_process := array_append(roles_to_process, 'activation_key_admin');
        elsif service_label_in = 'virtualization' then
            ents_to_process := array_append(ents_to_process, 'rhn_virtualization');

            roles_to_process := array_append(roles_to_process, 'config_admin');
        end if;

        if enable_in = 'Y' then
            for i in 1..array_upper(ents_to_process, 1) loop
                for ent in ents(ents_to_process[i]) loop
                    create_row := 'Y';
                    for oe in org_ents(ent.label) loop
                        create_row := 'N';
                    end loop;
                    if create_row = 'Y' then
                        insert into rhnOrgEntitlements(org_id, entitlement_id)
                            values (org_id_in, ent.id);
                    end if;
                end loop;
            end loop;
            for i in 1..array_upper(roles_to_process, 1) loop
                for role in roles(roles_to_process[i]) loop
                    create_row := 'Y';
                    for o_r in org_roles(role.label) loop
                        create_row := 'N';
                    end loop;
                    if create_row = 'Y' then
                        insert into rhnUserGroup(
                                id, name, description, current_members,
                                group_type, org_id
                            ) (
                                select  nextval('rhn_user_group_id_seq'),
                                        ugt.name || 's',
                                        ugt.name || 's for Org ' ||
                                            o.name || ' ('|| o.id ||')',
                                        0, ugt.id, o.id
                                from    rhnUserGroupType ugt,
                                        web_customer o
                                where   o.id = org_id_in
                                    and ugt.id = role.id
                            );
                    end if;
                end loop;
            end loop;
        else
            for i in 1..coalesce(array_upper(ents_to_process, 1), 0) loop
                for ent in ents(ents_to_process[i]) loop
                    delete from rhnOrgEntitlements
                     where org_id = org_id_in
                       and entitlement_id = ent.id;
                end loop;
            end loop;
        end if;
    end$$
language plpgsql;

    create or replace function set_customer_enterprise (
        customer_id_in in numeric
    ) returns void
as $$
    begin
        perform rhn_entitlements.modify_org_service(customer_id_in, 'enterprise', 'Y');
    end$$
language plpgsql;

    create or replace function unset_customer_enterprise (
        customer_id_in in numeric
    ) returns void
as $$
    begin
        perform rhn_entitlements.modify_org_service(customer_id_in, 'enterprise', 'N');
    end$$
language plpgsql;

    -- *******************************************************************
    -- PROCEDURE: prune_group
    -- Unsubscribes servers consuming physical slots that over the org's
    --   limit.
    -- Called by: set_server_group_count, repoll_virt_guest_entitlements
    -- *******************************************************************
    create or replace function prune_group (
        group_id_in in numeric,
        quantity_in in numeric
    ) returns void
as $$
    declare
        sgrecord record;
      type_is_base char;
    begin
            update      rhnServerGroup
                set     max_members = quantity_in
                where   id = group_id_in;

            for sgrecord in (
		   select  server_id, server_group_id, sgt.id as group_type_id, sgt.label
		    from    rhnServerGroupType              sgt,
				    rhnServerGroup                  sg,
				    rhnServerGroupMembers   sgm
		    where   1=1
			    and sgm.server_group_id = group_id_in
			    and sgm.server_id in (
				    select  sep.server_id
				    from
					rhnServerEntitlementPhysical sep
				    where
					sep.server_group_id = group_id_in
				    order by sep.modified asc
				    offset quantity_in
				)
			    and sgm.server_group_id = sg.id
			    and sg.group_type = sgt.id
	    ) loop
                perform rhn_entitlements.remove_server_entitlement(sgrecord.server_id, sgrecord.label);

            select is_base
            into type_is_base
            from rhnServerGroupType sgt
            where sgt.id = sgrecord.group_type_id;

            -- if we're removing a base ent, then be sure to
            -- remove the server's channel subscriptions.
            if ( type_is_base = 'Y' ) then
                   perform rhn_channel.clear_subscriptions(sgrecord.server_id, 0);
            end if;

            end loop;
    end$$
language plpgsql;

    -- *******************************************************************
    -- PROCEDURE: assign_system_entitlement
    --
    -- Moves system entitlements from from_org_id_in to to_org_id_in.
    -- Can raise not_enough_entitlements_in_base_org if from_org_id_in
    -- does not have enough entitlements to cover the move.
    -- Takes care of unentitling systems if necessary by calling
    -- set_server_group_count
    -- *******************************************************************
    create or replace function assign_system_entitlement(
        group_label_in in varchar,
        from_org_id_in in numeric,
        to_org_id_in in numeric,
        quantity_in in numeric
    ) returns void
as $$
    declare
        prev_ent_count numeric;
    to_org_prev_ent_count numeric;
        new_ent_count numeric;
    new_quantity numeric;
        group_type numeric;
    begin

            select max_members
            into prev_ent_count
            from rhnServerGroupType sgt,
                 rhnServerGroup sg
            where sg.org_id = from_org_id_in
              and sg.group_type = sgt.id
              and sgt.label = group_label_in;

            if not found then
                perform rhn_exception.raise_exception(
                              'not_enough_entitlements_in_base_org');
            end if;

            select max_members
            into to_org_prev_ent_count
            from rhnServerGroupType sgt,
                 rhnServerGroup sg
            where sg.org_id = to_org_id_in
              and sg.group_type = sgt.id
              and sgt.label = group_label_in;

            if not found then
                to_org_prev_ent_count := 0;
            end if;

            select id
            into group_type
            from rhnServerGroupType
            where label = group_label_in;

            if not found then
                perform rhn_exception.raise_exception(
                              'invalid_server_group');
            end if;

        new_ent_count := prev_ent_count - quantity_in;

        if prev_ent_count > new_ent_count then
            new_quantity := to_org_prev_ent_count + quantity_in;
        end if;

        if new_ent_count < 0 then
            perform rhn_exception.raise_exception(
                          'not_enough_entitlements_in_base_org');
        end if;


        perform rhn_entitlements.set_server_group_count(from_org_id_in,
                                         group_type,
                                         new_ent_count);

        perform rhn_entitlements.set_server_group_count(to_org_id_in,
                                         group_type,
                                         new_quantity);

        -- Create or delete the entries in rhnOrgEntitlementType
        if group_label_in = 'enterprise_entitled' then
            if new_quantity > 0 then
                perform rhn_entitlements.set_customer_enterprise(to_org_id_in);
            else
                perform rhn_entitlements.unset_customer_enterprise(to_org_id_in);
            end if;
        end if;

    end$$
language plpgsql;

    -- *******************************************************************
    -- PROCEDURE: activate_system_entitlement
    --
    -- Sets the values in rhnServerGroup for a given rhnServerGroupType.
    --
    -- Calls: set_server_group_count to update, prune, or create the group.
    -- Called by: the code that activates a satellite cert.
    --
    -- Raises not_enough_entitlements_in_base_org if all entitlements
    -- in the org are used so the free entitlements would not cover
    -- the difference when descreasing the number of entitlements.
    -- *******************************************************************
    create or replace function activate_system_entitlement(
        org_id_in in numeric,
        group_label_in in varchar,
        quantity_in in numeric
    ) returns void
as $$
    declare
        prev_ent_count numeric;
        prev_ent_count_sum numeric;
        group_type numeric;
    begin

        -- Fetch the current entitlement count for the org
        -- into prev_ent_count

            select current_members
            into prev_ent_count
            from rhnServerGroupType sgt,
                 rhnServerGroup sg
            where sg.group_type = sgt.id
              and sgt.label = group_label_in
              and sg.org_id = org_id_in;

            if not found then
                prev_ent_count := 0;
            end if;

            select id
            into group_type
            from rhnServerGroupType
            where label = group_label_in;

            if not found then
                perform rhn_exception.raise_exception(
                              'invalid_server_group');
            end if;

        -- If we're setting the total entitlemnt count to a lower value,
        -- and that value is less than the allocated count in this org,
        -- we need to raise an exception.
        if quantity_in < prev_ent_count then
            perform rhn_exception.raise_exception(
                          'not_enough_entitlements_in_base_org');
        else
            -- don't update family counts after every server
            -- will do bulk update afterwards
            perform rhn_entitlements.set_server_group_count(org_id_in,
                                             group_type,
                                             quantity_in);
        end if;

    end$$
language plpgsql;


    create or replace function set_server_group_count (
        customer_id_in in numeric,  -- customer_id
        group_type_in in numeric,   -- rhn[User|Server]GroupType.id
        quantity_in in numeric      -- quantity
    ) returns void
as $$
    declare
        group_id numeric;
        quantity numeric;
        wasfound boolean;
    begin
        quantity := quantity_in;
        if quantity is not null and quantity < 0 then
            quantity := 0;
        end if;

        select  rsg.id
        into    group_id
        from    rhnServerGroup rsg
        where   1=1
            and rsg.org_id = customer_id_in
            and rsg.group_type = group_type_in;

        -- preserve the not found status across the rhn_entitlements.prune_group invocation
        wasfound := true;
        if not found then
            wasfound := false;
        end if;

        perform rhn_entitlements.prune_group(
            group_id,
            quantity
        );

        if not wasfound then
            insert into rhnServerGroup (
                    id, name, description, max_members, current_members,
                    group_type, org_id, created, modified
                ) (
                    select  nextval('rhn_server_group_id_seq'), name, name,
                            quantity, 0, id, customer_id_in,
                            current_timestamp, current_timestamp
                    from    rhnServerGroupType
                    where   id = group_type_in
            );
        end if;

    end$$
language plpgsql;

    -- this expects quantity_in to be the number of available slots, not the
    -- max_members of the server group.  If you give it too many, it'll fail
    -- and raise servergroup_max_members.
    -- We should NEVER run this unless we're SURE that we won't
    -- be violating the max.
    create or replace function entitle_last_modified_servers (
        customer_id_in in numeric,  -- customer_id
        type_label_in in varchar,   -- 'enterprise_entitled'
        quantity_in in numeric      -- 3
    ) returns void
as $$
    declare
        -- find the servers that aren't currently in slots
        servers cursor(cid_in numeric, quant_in numeric) for
                                    select  rs.id as server_id
                                    from    rhnServer rs
                                    where   1=1
                                        and rs.org_id = cid_in
                                        and not exists (
                                            select  1
                                            from    rhnServerGroup sg,
                                                    rhnServerGroupMembers rsgm
                                            where   rsgm.server_id = rs.id
                                                and rsgm.server_group_id = sg.id
                                                and sg.group_type is not null
                                        )
                                        and not exists (
                                            select 1
                                            from rhnVirtualInstance vi
                                            where vi.virtual_system_id =
                                                  rs.id
                                        )
                                    order by modified desc
                                    limit quant_in;
    begin
        for server in servers(customer_id_in, quantity_in) loop
            perform rhn_entitlements.entitle_server(server.server_id, type_label_in);
        end loop;
    end$$
language plpgsql;

-- restore the original setting
update pg_settings set setting = overlay( setting placing '' from 1 for (length('rhn_entitlements')+1) ) where name = 'search_path';
   07070100000B2D000081B400000000000000000000000167AE111400006052000000000000000000000000000000000000006700000000susemanager-schema/upgrade/susemanager-schema-2.1.51-to-susemanager-schema-3.0/9096-rhn_server.pkb.sql    --
-- Copyright (c) 2008--2014 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--

-- create schema rhn_server;

--update pg_setting
update pg_settings set setting = 'rhn_server,' || setting where name = 'search_path';

    create or replace function system_service_level(
    	server_id_in in numeric,
	service_level_in in varchar
    ) returns numeric as $$
    declare
    ents cursor is 
      select label from rhnServerEntitlementView
      where server_id = server_id_in;

    retval numeric := 0;

    begin
         for ent in ents loop
            retval := rhn_entitlements.entitlement_grants_service (ent.label, service_level_in);
            if retval = 1 then
               return retval;
            end if;
         end loop;

         return retval;

    end$$ language plpgsql;

        
    create or replace function can_change_base_channel(server_id_in IN NUMERIC)
    returns numeric
    as $$
    declare
    	throwaway numeric;
    begin
    	-- the idea: if we get past this query, the server is
	-- neither sat nor proxy, so base channel is changeable

	select 1 into throwaway
	  from rhnServer S
	 where S.id = server_id_in
	   and not exists (select 1 from rhnSatelliteInfo SI where SI.server_id = S.id)
	   and not exists (select 1 from rhnProxyInfo PI where PI.server_id = S.id);

        if not found then
	    return 0;
        end if;
	   
	return 1;
    end$$ language plpgsql;
	        
    create or replace function set_custom_value(
    	server_id_in in numeric,
	user_id_in in numeric,
	key_label_in in varchar,
	value_in in varchar
    ) returns void
    as $$
    declare
    	key_id_val numeric;
    begin
    	select CDK.id into strict key_id_val
	  from rhnCustomDataKey CDK,
	       rhnServer S
	 where S.id = server_id_in
	   and S.org_id = CDK.org_id
	   and CDK.label = key_label_in;
	   
	begin
	    insert into rhnServerCustomDataValue (server_id, key_id, value, created_by, last_modified_by)
	    values (server_id_in, key_id_val, value_in, user_id_in, user_id_in);
	exception
	    when UNIQUE_VIOLATION
	    	then
		update rhnServerCustomDataValue
		   set value = value_in,
		       last_modified_by = user_id_in
		 where server_id = server_id_in
		   and key_id = key_id_val;		   
	end;

    end$$ language plpgsql;
    
    create or replace function bulk_set_custom_value(
    	key_label_in in varchar,
	value_in in varchar,
	set_label_in in varchar,
	set_uid_in in numeric
    )
    returns integer
    as $$
    declare
        i integer;
        server record;
    begin
        i := 0;
        for server in (
           SELECT user_id, label, element, element_two
	     FROM rhnSet
	    WHERE label = set_label_in
	      AND user_id = set_uid_in
	) loop
	    if rhn_server.system_service_level(server.element, 'management') = 1 then
	    	perform rhn_server.set_custom_value(server.element, set_uid_in, key_label_in, value_in);
            i := i + 1;
	    end if;
	end loop;
    return i;
    end$$ language plpgsql;

    create or replace function bulk_snapshot_tag(
    	org_id_in in numeric,
        tagname_in in varchar,
	set_label_in in varchar,
	set_uid_in in numeric
    ) returns void
    as $$
    declare
        server record;
    	snapshot_id numeric;
    begin
        for server in (
           SELECT user_id, label, element, element_two
	     FROM rhnSet
	    WHERE label = set_label_in
	      AND user_id = set_uid_in
	    ) loop
	    if rhn_server.system_service_level(server.element, 'management') = 1 then
	    	    select max(id) into snapshot_id
	    	    from rhnSnapshot
	    	    where server_id = server.element;

	    	    if snapshot_id is null then
		    	perform rhn_server.snapshot_server(server.element, 'tagging system:  ' || tagname_in);
			
			select max(id) into snapshot_id
			from rhnSnapshot
			where server_id = server.element;
		    end if;
		 
		-- now have a snapshot_id to work with...
		begin
		    perform rhn_server.tag_snapshot(snapshot_id, org_id_in, tagname_in);
		exception
		    when UNIQUE_VIOLATION
		    	then
			-- do nothing, be forgiving...
			null;
		end;
	    end if;
	end loop;    
    end$$ language plpgsql;

    create or replace function tag_delete(
    	server_id_in in numeric,
	tag_id_in in numeric
    ) returns void
    as $$
    declare
    	snapshots cursor is
		select	snapshot_id
		from	rhnSnapshotTag
		where	tag_id = tag_id_in;
	tag_id_tmp numeric;
    begin
    	select	id into tag_id_tmp
	from	rhnTag
	where	id = tag_id_in
	for update;

	delete
		from	rhnSnapshotTag
		where	server_id = server_id_in
			and tag_id = tag_id_in;
	for snapshot in snapshots loop
		return;
	end loop;
	delete
		from rhnTag
		where id = tag_id_in;
    end$$ language plpgsql;

    create or replace function tag_snapshot(
        snapshot_id_in in numeric,
	org_id_in in numeric,
	tagname_in in varchar
    ) returns void
    as $$
    begin
    	insert into rhnSnapshotTag (snapshot_id, server_id, tag_id)
	select snapshot_id_in, server_id, lookup_tag(org_id_in, tagname_in)
	from rhnSnapshot
	where id = snapshot_id_in;
    end$$ language plpgsql;

    create or replace function bulk_snapshot(
    	reason_in in varchar,
	set_label_in in varchar,
	set_uid_in in numeric
    ) returns void
    as $$
    declare
        server record;
    begin
        for server in (
           SELECT user_id, label, element, element_two
	     FROM rhnSet
	    WHERE label = set_label_in
	      AND user_id = set_uid_in
	    ) loop
	    if rhn_server.system_service_level(server.element, 'management') = 1 then
	    	perform rhn_server.snapshot_server(server.element, reason_in);
	    end if;
	end loop;
    end$$ language plpgsql;

    create or replace function snapshot_server(
    	server_id_in in numeric,
	reason_in in varchar
    ) returns void
    as $$
    declare
    	snapshot_id_v numeric;
	revisions cursor is
		select distinct
			cr.id
		from	rhnConfigRevision	cr,
			rhnConfigFileName	cfn,
			rhnConfigFile		cf,
			rhnConfigChannel	cc,
			rhnServerConfigChannel	scc
		where	1=1
			and scc.server_id = server_id_in
			and scc.config_channel_id = cc.id
			and cc.id = cf.config_channel_id
			and cf.id = cr.config_file_id
			and cr.id = cf.latest_config_revision_id
			and cf.config_file_name_id = cfn.id
			and cf.id = lookup_first_matching_cf(scc.server_id, cfn.path);
	locked integer;
    begin
    	select nextval('rhn_snapshot_id_seq') into snapshot_id_v;

	insert into rhnSnapshot (id, org_id, server_id, reason) (
		select	snapshot_id_v,
			s.org_id,
			server_id_in,
			reason_in
		from	rhnServer s
		where	s.id = server_id_in
	);
	insert into rhnSnapshotChannel (snapshot_id, channel_id) (
		select	snapshot_id_v, sc.channel_id
		from	rhnServerChannel sc
		where	sc.server_id = server_id_in
	);
	insert into rhnSnapshotServerGroup (snapshot_id, server_group_id) (
		select	snapshot_id_v, sgm.server_group_id
		from	rhnServerGroupMembers sgm
		where	sgm.server_id = server_id_in
	);
        locked := 0;
        <<iloop>>
        while true loop
            begin
                insert into rhnPackageNEVRA (id, name_id, evr_id, package_arch_id)
                select nextval('rhn_pkgnevra_id_seq'), sp.name_id, sp.evr_id, sp.package_arch_id
                from rhnServerPackage sp
                where sp.server_id = server_id_in
                        and not exists
                        (select 1
                                from rhnPackageNEVRA nevra
                                where nevra.name_id = sp.name_id
                                        and nevra.evr_id = sp.evr_id
                                        and (nevra.package_arch_id = sp.package_arch_id
                                            or (nevra.package_arch_id is null
                                                and sp.package_arch_id is null)));
                exit iloop;
            exception when unique_violation then
                if locked = 1 then
                    raise;
                else
                    lock table rhnPackageNEVRA in exclusive mode;
                    locked := 1;
                end if;
            end;
        end loop;
	insert into rhnSnapshotPackage (snapshot_id, nevra_id) (
                select distinct snapshot_id_v, nevra.id
                from    rhnServerPackage sp, rhnPackageNEVRA nevra
                where   sp.server_id = server_id_in
                        and nevra.name_id = sp.name_id
                        and nevra.evr_id = sp.evr_id
                        and (nevra.package_arch_id = sp.package_arch_id
                            or (nevra.package_arch_id is null
                                and sp.package_arch_id is null))
	);

	insert into rhnSnapshotConfigChannel ( snapshot_id, config_channel_id ) (
		select	snapshot_id_v, scc.config_channel_id
		from	rhnServerConfigChannel scc
		where	server_id = server_id_in
	);

	for revision in revisions loop
		insert into rhnSnapshotConfigRevision (
				snapshot_id, config_revision_id
			) values (
				snapshot_id_v, revision.id
			);
	end loop;
    end$$ language plpgsql;

    create or replace function remove_action(
    	server_id_in in numeric,
	action_id_in in numeric
    ) returns void
    as $$
    declare
    	-- this really wants "nulls last", but 8.1.7.3.0 sucks ass.
	-- instead, we make a local table that holds our
	-- list of ids with null prereqs.  There's surely a better way
	-- (an array instead of a table maybe?  who knows...)
	-- but I've got code to do this handy that I can look at ;)
    	chained_actions cursor is
                with recursive r(id, prerequisite) as (
			select	id, prerequisite
			from	rhnAction
			where id = action_id_in
		union all
			select	r1.id, r1.prerequisite
			from	rhnAction r1, r
			where r.id = r1.prerequisite
		)
		select * from r
		order by prerequisite desc;
	sessions cursor is
		select	s.id
		from	rhnKickstartSession s
		where	server_id_in in (s.old_server_id, s.new_server_id)
			and s.action_id = action_id_in
			and not exists (
				select	1
				from	rhnKickstartSessionState ss
				where	ss.id = s.state_id
					and ss.label in ('failed','complete')
			);
	chain_ends numeric[];
	i numeric;
	prereq numeric := 1;
    begin
	select	prerequisite
	into	prereq
	from	rhnAction
	where	id = action_id_in;

	if prereq is not null then
		perform rhn_exception.raise_exception('action_is_child');
	end if;

        chain_ends := '{}';
	i := 1;
	for action in chained_actions loop
		if action.prerequisite is null then
			chain_ends[i] := action.id;
			i := i + 1;
		else
			delete from rhnServerAction
				where server_id = server_id_in
				and action_id = action.id;
		end if;
	end loop;

	delete from rhnServerAction
		where server_id = server_id_in
		and action_id = any(chain_ends);

	for s in sessions loop
		update rhnKickstartSession
			set 	state_id = (
					select	id
					from	rhnKickstartSessionState
					where	label = 'failed'
				),
				action_id = null
			where	id = s.id;
		perform set_ks_session_history_message(s.id, 'failed', 'Kickstart cancelled due to action removal');
	end loop;
    end$$ language plpgsql;
   
    create or replace function check_user_access(server_id_in in numeric, user_id_in in numeric)
    returns numeric
    as $$
    declare
    	has_access numeric;
    begin
    	-- first check; if this returns no rows, then the server/user are in different orgs, and we bail
        select 1 into has_access
	  from rhnServer S,
	       web_contact wc
	 where wc.org_id = s.org_id
	   and s.id = server_id_in
	   and wc.id = user_id_in;

        if not found then
          return 0;
        end if;

	-- okay, so they're in the same org.  if we have an org admin, they get a free pass
    	if rhn_user.check_role(user_id_in, 'org_admin') = 1
	then
	    return 1;
	end if;
		   
    	select 1 into has_access
	  from rhnServerGroupMembers SGM,
	       rhnUserServerGroupPerms USG
	 where SGM.server_group_id = USG.server_group_id
	   and SGM.server_id = server_id_in
	   and USG.user_id = user_id_in;

        if not found then
          return 0;
        end if;
	   
	return 1;
    end$$ language plpgsql;

    -- *******************************************************************
    -- FUNCTION: can_server_consume_virt_slot
    -- Returns 1 if the server id is eligible to consume a virtual slot,
    --   else returns 0.
    -- Called by: insert_into_servergroup, delete_from_servergroup
    -- *******************************************************************
    create or replace function can_server_consume_virt_slot(server_id_in in numeric,
                                           group_type_in in varchar)
    returns numeric                                           
    as $$
    declare
        server_virt_slots cursor is
            select vi.VIRTUAL_SYSTEM_ID
            from
                rhnVirtualInstance vi
            where
                -- server id is a virtual instance
                vi.VIRTUAL_SYSTEM_ID = server_id_in
                -- server id's host is virt entitled
                and exists ( select 1
                     from rhnServerEntitlementView sev
                 where vi.HOST_SYSTEM_ID = sev.server_id
                 and sev.label = 'virtualization_host' )
                -- server id's host also has the ent we want
                and exists ( select 1
                     from rhnServerEntitlementView sev2
                 where vi.HOST_SYSTEM_ID = sev2.server_id
                 and sev2.label = group_type_in );

    begin
        for server_virt_slot in server_virt_slots loop
            return 1;
        end loop;
        return 0;
    end$$ language plpgsql;


    create or replace function insert_into_servergroup (
		server_id_in in numeric,
		server_group_id_in in numeric
    ) returns void
    as $$
    declare
		used_slots numeric;
		max_slots numeric;
		org_id numeric;
		mgmt_available numeric;
		mgmt_upgrade numeric;
		mgmt_sgid numeric;
		prov_available numeric;
		prov_upgrade numeric;
		prov_sgid numeric;
		group_label varchar;
		group_type numeric;
	begin
		-- first, group_type = null, because it's easy...

		-- this will rowlock the servergroup we're trying to change;
		-- we probably need to lock the other one, but I think the chances
		-- of it being a real issue are very small for now...
		select	sg.group_type, sg.org_id, sg.current_members, sg.max_members
		into	group_type, org_id, used_slots, max_slots
		from	rhnServerGroup sg
		where	sg.id = server_group_id_in
		for update of sg;

		if group_type is null then
			if used_slots >= max_slots then
				perform rhn_exception.raise_exception('servergroup_max_members');
			end if;

			insert into rhnServerGroupMembers(
					server_id, server_group_id
				) values (
					server_id_in, server_group_id_in
				);
			update rhnServerGroup
				set current_members = current_members + 1
				where id = server_group_id_in;

			perform rhn_cache.update_perms_for_server_group(server_group_id_in);
			return;
		end if;

		-- now for group_type != null
		-- 
		select	label
		into	group_label
		from	rhnServerGroupType	sgt
		where	sgt.id = group_type;

		-- the naive easy path that gets hit most often and has to be quickest.
		if group_label in (
                           'enterprise_entitled',
                           'bootstrap_entitled',
                           'virtualization_host'
                      ) then
			if used_slots >= max_slots and 
               (rhn_server.can_server_consume_virt_slot(server_id_in, group_label) != 1) 
               then
				perform rhn_exception.raise_exception('servergroup_max_members');
			end if;

			insert into rhnServerGroupMembers(
					server_id, server_group_id
				) values (
					server_id_in, server_group_id_in
				);

            -- Only update current members if the system in consuming a 
            -- physical slot.
            if rhn_server.can_server_consume_virt_slot(server_id_in, group_label) = 0 then
                update rhnServerGroup
                set current_members = current_members + 1
                where id = server_group_id_in;
            end if;                

			return;
		end if;
	end$$ language plpgsql;

	create or replace function insert_into_servergroup_maybe (
		server_id_in in numeric,
		server_group_id_in in numeric
	) returns numeric as $$ 
    declare
		retval numeric := 0;
		servergroups cursor is
			select	s.id	server_id,
					sg.id	server_group_id
			from	rhnServerGroup	sg,
					rhnServer		s
			where	s.id = server_id_in
				and sg.id = server_group_id_in
				and s.org_id = sg.org_id
				and not exists (
					select	1
					from	rhnServerGroupMembers sgm
					where	sgm.server_id = s.id
						and sgm.server_group_id = sg.id
				);
	begin
		for sgm in servergroups loop
			perform rhn_server.insert_into_servergroup(sgm.server_id, sgm.server_group_id);
			retval := retval + 1;
		end loop;
		return retval;
	end$$ language plpgsql;

	create or replace function insert_set_into_servergroup (
		server_group_id_in in numeric,
		user_id_in in numeric,
		set_label_in in varchar
	) returns void
        as $$
    declare
		servers cursor is
			select	st.element	id
			from	rhnSet		st
			where	st.user_id = user_id_in
				and st.label = set_label_in
				and exists (
					select	1
					from	rhnUserManagedServerGroups umsg
					where	umsg.server_group_id = server_group_id_in
						and umsg.user_id = user_id_in
					)
				and not exists (
					select	1
					from	rhnServerGroupMembers sgm
					where	sgm.server_id = st.element
						and sgm.server_group_id = server_group_id_in
				);
	begin
		for s in servers loop
			perform rhn_server.insert_into_servergroup(s.id, server_group_id_in);
		end loop;
	end$$ language plpgsql;
		
    create or replace function delete_from_servergroup (
    	server_id_in in numeric,
		server_group_id_in in numeric
    ) returns void
    as $$
    declare
        server_virt_groups cursor is
            select 1
            from rhnServerEntitlementVirtual sev
            where sev.server_id = server_id_in
            and sev.server_group_id = server_group_id_in;

		oid numeric;
		mgmt_sgid numeric;
		label varchar;
		group_type numeric;
	begin
			select	sg.group_type, sg.org_id
			into	group_type,	oid
			from	rhnServerGroupMembers	sgm,
					rhnServerGroup			sg
			where	sg.id = server_group_id_in
				and sg.id = sgm.server_group_id
				and sgm.server_id = server_id_in
			for update of sg;

			if not found then
				perform rhn_exception.raise_exception('server_not_in_group');
			end if;

		-- do group_type is null first
		if group_type is null then
			delete from rhnServerGroupMembers
				where server_group_id = server_group_id_in
				and	server_id = server_id_in;
			update rhnServerGroup
				set current_members = current_members - 1
				where id = server_group_id_in;
			perform rhn_cache.update_perms_for_server_group(server_group_id_in);
			return;
		end if;

		select	sgt.label
		into	label
		from	rhnServerGroupType sgt
		where	sgt.id = group_type;

		if label in (
                     'enterprise_entitled', 
                     'bootstrap_entitled',
                     'virtualization_host'
                ) then

            -- Only update current members if the system is consuming
            -- a physical slot.
            for server_virt_group in server_virt_groups loop                
                delete from rhnServerGroupMembers
                where server_group_id = server_group_id_in
                and	server_id = server_id_in;
                return;
            end loop;                

            delete from rhnServerGroupMembers
            where server_group_id = server_group_id_in
            and	server_id = server_id_in;

            update rhnServerGroup
            set current_members = current_members - 1
            where id = server_group_id_in;

		end if;
	end$$ language plpgsql;

	create or replace function delete_set_from_servergroup (
		server_group_id_in in numeric,
		user_id_in in numeric,
		set_label_in in varchar
	) returns void
        as $$	
        declare
		servergroups cursor is
			select	sgm.server_id, sgm.server_group_id
			from	rhnSet st,
					rhnServerGroupMembers sgm
			where	sgm.server_group_id = server_group_id_in
				and st.user_id = user_id_in
				and st.label = set_label_in
				and sgm.server_id = st.element
				and exists (
					select	1
					from	rhnUserManagedServerGroups usgp
					where	usgp.server_group_id = server_group_id_in
						and usgp.user_id = user_id_in
				);
	begin
		for sgm in servergroups loop
			perform rhn_server.delete_from_servergroup(sgm.server_id, server_group_id_in);
		end loop;
	end$$ language plpgsql;

	create or replace function clear_servergroup (
		server_group_id_in in numeric
	) returns void
        as $$
        declare
		servers cursor is
			select	sgm.server_id	id
			from	rhnServerGroupMembers sgm
			where	sgm.server_group_id = server_group_id_in;
	begin
		for s in servers loop
			perform rhn_server.delete_from_servergroup(s.id, server_group_id_in);
		end loop;
	end$$ language plpgsql;

	create or replace function delete_from_org_servergroups (
		server_id_in in numeric
	) returns void
        as $$
        declare
		servergroups cursor is
			select	sgm.server_group_id id
			from	rhnServerGroup sg,
					rhnServerGroupMembers sgm
			where	sgm.server_id = server_id_in
				and sgm.server_group_id = sg.id
				and sg.group_type is null;
	begin
		for sg in servergroups loop
			perform rhn_server.delete_from_servergroup(server_id_in, sg.id);
		end loop;
	end$$ language plpgsql;

	create or replace function get_ip_address (
		server_id_in in numeric
	) returns varchar as $$
        declare
		interfaces cursor is
			select	ni.name as name, na4.address as address
			from	rhnServerNetInterface ni,
			        rhnServerNetAddress4 na4
			where	server_id = server_id_in
                and ni.id = na4.interface_id
				and na4.address != '127.0.0.1';
		addresses cursor is
			select	ipaddr ip_addr
			from	rhnServerNetwork
			where	server_id = server_id_in
				and ipaddr != '127.0.0.1';
	begin
		for addr in addresses loop
			return addr.ip_addr;
		end loop;
		for iface in interfaces loop
			return iface.address;
		end loop;
		return NULL;
	end$$ language plpgsql;

    create or replace function update_needed_cache(
        server_id_in in numeric
	) returns void as $$
    declare
      update_lock numeric;
    begin
      select id into update_lock from rhnServer where id = server_id_in for update;
      delete from rhnServerNeededCache
        where server_id = server_id_in;
      insert into rhnServerNeededCache
             (server_id, errata_id, package_id, channel_id)
        (select distinct sp.server_id, x.errata_id, p.id, x.channel_id
           FROM (SELECT sp_sp.server_id, sp_sp.name_id,
		        sp_sp.package_arch_id, max(sp_pe.evr) AS max_evr
                   FROM rhnServerPackage sp_sp
                   join rhnPackageEvr sp_pe ON sp_pe.id = sp_sp.evr_id
                  GROUP BY sp_sp.server_id, sp_sp.name_id, sp_sp.package_arch_id) sp
           join rhnPackage p ON p.name_id = sp.name_id
           join rhnPackageEvr pe ON pe.id = p.evr_id AND sp.max_evr < pe.evr
           join rhnPackageUpgradeArchCompat puac
	            ON puac.package_arch_id = sp.package_arch_id
		    AND puac.package_upgrade_arch_id = p.package_arch_id
           join rhnServerChannel sc ON sc.server_id = sp.server_id
           join rhnChannelPackage cp ON cp.package_id = p.id
	            AND cp.channel_id = sc.channel_id
           left join (SELECT ep.errata_id, ce.channel_id, ep.package_id
                        FROM rhnChannelErrata ce
                        join rhnErrataPackage ep
			         ON ep.errata_id = ce.errata_id
			join rhnServerChannel sc_sc
			         ON sc_sc.channel_id = ce.channel_id
		       WHERE sc_sc.server_id = server_id_in) x
             ON x.channel_id = sc.channel_id AND x.package_id = cp.package_id
          where sp.server_id = server_id_in);
	end$$ language plpgsql;
-- restore the original setting
update pg_settings set setting = overlay( setting placing '' from 1 for (length('rhn_server')+1) ) where name = 'search_path';
  07070100000B2E000081B400000000000000000000000167AE111400000F3A000000000000000000000000000000000000007500000000susemanager-schema/upgrade/susemanager-schema-2.1.51-to-susemanager-schema-3.0/9097-delete_update_ent_references.sql  
-- rhnServerGroup and dependencies

SELECT .clear_log_id();

DELETE FROM rhnOrgExtGroupMapping
  WHERE server_group_id in (
    SELECT id
      FROM rhnServerGroup
      WHERE group_type = (
        SELECT id
          FROM rhnServerGroupType
          WHERE label = 'sw_mgr_entitled'
      )
  );

DELETE FROM rhnRegTokenGroups
  WHERE server_group_id in (
    SELECT id
      FROM rhnServerGroup
      WHERE group_type = (
        SELECT id
          FROM rhnServerGroupType
          WHERE label = 'sw_mgr_entitled'
      )
  );

-- create server group for 'enterprise_entitled' everywhere
insert into rhnServerGroup ( id, name, description, group_type, org_id )
  select nextval('rhn_server_group_id_seq'), sgt.name, sgt.name, sgt.id, X.org_id
  from rhnServerGroupType sgt,
     (select distinct msg.org_id
        from rhnServerGroup msg
       where msg.org_id not in (select org_id
                                  from rhnServerGroup sg
                                  join rhnServerGroupType sgt ON sgt.id = sg.group_type
                                 where sgt.label = 'enterprise_entitled')
     ) X
  where sgt.label = 'enterprise_entitled';

-- add membership to 'enterprise_entitled' for all server which
-- are currently in the group 'sw_mgr_entitled'
  insert into rhnServerGroupMembers (server_id, server_group_id)
    select * from (
      select sgm.server_id,
        (select nsg.id
           from rhnServerGroup nsg
           join rhnServerGroupType nsgt on nsg.group_type = nsgt.id
          where nsgt.label = 'enterprise_entitled'
            and nsg.org_id = sg.org_id) new_group_id
        from rhnServerGroupMembers sgm
        join rhnServerGroup sg on sgm.server_group_id = sg.id
        join rhnServerGroupType sgt on sg.group_type = sgt.id
       where sgt.label = 'sw_mgr_entitled'
    ) X
    where not exists (select 1
                       from rhnServerGroupMembers csgm
                      where csgm.server_id = X.server_id
                        and csgm.server_group_id = X.new_group_id);

-- remove 'sw_mgr_entitled'
DELETE FROM rhnServerGroupMembers
  WHERE server_group_id in (
    SELECT id
      FROM rhnServerGroup
      WHERE group_type = (
        SELECT id
          FROM rhnServerGroupType
          WHERE label = 'sw_mgr_entitled'
      )
  );


DELETE FROM rhnSnapshotServerGroup
  WHERE server_group_id in (
    SELECT id
      FROM rhnServerGroup
      WHERE group_type = (
        SELECT id
          FROM rhnServerGroupType
          WHERE label = 'sw_mgr_entitled'
      )
  );

DELETE FROM rhnUserDefaultSystemGroups
  WHERE system_group_id in (
    SELECT id
      FROM rhnServerGroup
      WHERE group_type = (
        SELECT id
          FROM rhnServerGroupType
          WHERE label = 'sw_mgr_entitled'
      )
  );

DELETE FROM rhnUserServerGroupPerms
  WHERE server_group_id in (
    SELECT id
      FROM rhnServerGroup
      WHERE group_type = (
        SELECT id
          FROM rhnServerGroupType
          WHERE label = 'sw_mgr_entitled'
      )
  );

DELETE FROM rhnServerGroup
  WHERE group_type = (
    SELECT id
      FROM rhnServerGroupType
      WHERE label = 'sw_mgr_entitled'
  );

-- rhnServerGroupType and dependencies

DELETE FROM rhnRegTokenEntitlement
  WHERE server_group_type_id = (
    SELECT id
      FROM rhnServerGroupType
      WHERE label = 'sw_mgr_entitled'
  );

DELETE FROM rhnServerGroupTypeFeature
  WHERE server_group_type_id = (
    SELECT id
      FROM rhnServerGroupType
      WHERE label = 'sw_mgr_entitled'
  );

DELETE FROM rhnServerServerGroupArchCompat
  WHERE server_group_type = (
    SELECT id
      FROM rhnServerGroupType
      WHERE label = 'sw_mgr_entitled'
  );

DELETE FROM rhnSGTypeBaseAddonCompat
  WHERE base_id = (
    SELECT id
      FROM rhnServerGroupType
      WHERE label = 'sw_mgr_entitled'
  );

DELETE FROM rhnServerGroupType
  WHERE label = 'sw_mgr_entitled';
  07070100000B2F000081B400000000000000000000000167AE1114000004A1000000000000000000000000000000000000006B00000000susemanager-schema/upgrade/susemanager-schema-2.1.51-to-susemanager-schema-3.0/9098-rhnEntitledServers.sql    --
-- Copyright (c) 2008 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--

create or replace view
rhnEntitledServers
as
select distinct
    S.id,
    S.org_id,
    S.digital_server_id,
    S.server_arch_id,
    S.os,
    S.release,
    S.name,
    S.description,
    S.info,
    S.secret
from
    rhnServerGroup SG,
    rhnServerGroupType SGT,
    rhnServerGroupMembers SGM,
    rhnServer S
where
    S.id = SGM.server_id
and SG.id = SGM.server_group_id
and SGT.label IN ('enterprise_entitled', 'bootstrap_entitled',
                  'salt_entitled', 'foreign_entitled')
and SG.group_type = SGT.id
and SG.org_id = S.org_id
;

   07070100000B30000081B400000000000000000000000167AE111400000A8D000000000000000000000000000000000000007400000000susemanager-schema/upgrade/susemanager-schema-2.1.51-to-susemanager-schema-3.0/9099-remove_non_linux_references.sql   
-- rhnServerGroup and dependencies

SELECT .clear_log_id();

DELETE FROM rhnOrgExtGroupMapping
  WHERE server_group_id in (
    SELECT id
      FROM rhnServerGroup
      WHERE group_type = (
        SELECT id
          FROM rhnServerGroupType
          WHERE label = 'nonlinux_entitled'
      )
  );

DELETE FROM rhnRegTokenGroups
  WHERE server_group_id in (
    SELECT id
      FROM rhnServerGroup
      WHERE group_type = (
        SELECT id
          FROM rhnServerGroupType
          WHERE label = 'nonlinux_entitled'
      )
  );

DELETE FROM rhnServerGroupMembers
  WHERE server_group_id in (
    SELECT id
      FROM rhnServerGroup
      WHERE group_type = (
        SELECT id
          FROM rhnServerGroupType
          WHERE label = 'nonlinux_entitled'
      )
  );

DELETE FROM rhnSnapshotServerGroup
  WHERE server_group_id in (
    SELECT id
      FROM rhnServerGroup
      WHERE group_type = (
        SELECT id
          FROM rhnServerGroupType
          WHERE label = 'nonlinux_entitled'
      )
  );

DELETE FROM rhnUserDefaultSystemGroups
  WHERE system_group_id in (
    SELECT id
      FROM rhnServerGroup
      WHERE group_type = (
        SELECT id
          FROM rhnServerGroupType
          WHERE label = 'nonlinux_entitled'
      )
  );

DELETE FROM rhnUserServerGroupPerms
  WHERE server_group_id in (
    SELECT id
      FROM rhnServerGroup
      WHERE group_type = (
        SELECT id
          FROM rhnServerGroupType
          WHERE label = 'nonlinux_entitled'
      )
  );

DELETE FROM rhnServerGroup
  WHERE group_type = (
    SELECT id
      FROM rhnServerGroupType
      WHERE label = 'nonlinux_entitled'
  );

-- rhnServerGroupType and dependencies

DELETE FROM rhnRegTokenEntitlement
  WHERE server_group_type_id = (
    SELECT id
      FROM rhnServerGroupType
      WHERE label = 'nonlinux_entitled'
  );

DELETE FROM rhnServerGroupTypeFeature
  WHERE server_group_type_id = (
    SELECT id
      FROM rhnServerGroupType
      WHERE label = 'nonlinux_entitled'
  );

DELETE FROM rhnServerServerGroupArchCompat
  WHERE server_group_type = (
    SELECT id
      FROM rhnServerGroupType
      WHERE label = 'nonlinux_entitled'
  );

DELETE FROM rhnSGTypeBaseAddonCompat
  WHERE base_id = (
    SELECT id
      FROM rhnServerGroupType
      WHERE label = 'nonlinux_entitled'
  );

DELETE FROM rhnServerGroupType
  WHERE label = 'nonlinux_entitled';

-- rhnOrgEntitlementType

DELETE FROM rhnOrgEntitlements
  WHERE entitlement_id = (
    SELECT id
      FROM rhnOrgEntitlementType
      WHERE label = 'rhn_nonlinux'
  );

DELETE FROM rhnOrgEntitlementType
  WHERE label = 'rhn_nonlinux';

-- rhnFeature

DELETE FROM rhnFeature
  WHERE label = 'ftr_nonlinux_support';
   07070100000B31000081B400000000000000000000000167AE11140000285B000000000000000000000000000000000000006600000000susemanager-schema/upgrade/susemanager-schema-2.1.51-to-susemanager-schema-3.0/9100-delete_server.sql --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
-- This deletes a server.  All codepaths which delete servers should hit this
-- or delete_server_bulk()

create or replace
function delete_server (
        server_id_in in numeric
) returns void 
as
$$
declare
         servergroups cursor for
                select  server_id, server_group_id
                from    rhnServerGroupMembers sgm
                where   sgm.server_id = server_id_in;

         configchannels cursor for
                select  cc.id
                from    rhnConfigChannel cc,
                        rhnConfigChannelType cct,
                        rhnServerConfigChannel scc
                where   1=1
                        and scc.server_id = server_id_in
                        and scc.config_channel_id = cc.id
                        -- these config channel types are reserved
                        -- for use by a single server, so we don't
                        -- need to check for other servers subscribed
                        and cct.label in
                                ('local_override','server_import')
                        and cct.id = cc.confchan_type_id;

    is_virt boolean;
begin
        -- filelists
        delete from rhnFileList where id in (
	select	spfl.file_list_id
	  from	rhnServerPreserveFileList spfl
	 where	spfl.server_id = server_id_in
			and not exists (
				select	1
				from	rhnServerPreserveFileList
				where	file_list_id = spfl.file_list_id
					and server_id != server_id_in
				union all
				select	1
				from	rhnKickstartPreserveFileList
				where	file_list_id = spfl.file_list_id
			)
        );

	for configchannel in configchannels loop
		perform rhn_config.delete_channel(configchannel.id);
	end loop;

      is_virt := exists (
       select 1
        from rhnServerEntitlementView
       where server_id = server_id_in
         and label = 'virtualization_host'
      );

	for sgm in servergroups loop
		perform rhn_server.delete_from_servergroup(
			sgm.server_id, sgm.server_group_id);
	end loop;

    if is_virt then
        perform rhn_entitlements.repoll_virt_guest_entitlements(server_id_in);
    end if;

        -- we're handling this instead of letting an "on delete
        -- set null" do it so that we don't run the risk
        -- of setting off the triggers and killing us with a
        -- mutating table

        -- this is merge of two single updates:
        --  update ... set old_server_id = null where old_server_id = server_id_in;
        --  update ... set new_server_id = null where new_server_id = server_id_in;
        -- so we scan rhnKickstartSession table only once
        update rhnKickstartSession
                set old_server_id = case when old_server_id = server_id_in then null else old_server_id end,
                    new_server_id = case when new_server_id = server_id_in then null else new_server_id end
                where old_server_id = server_id_in
                   or new_server_id = server_id_in;

        perform rhn_channel.clear_subscriptions(server_id_in, 1);

        -- A little complicated here, but the goal is to
        -- delete records from rhnVirtualInstace only if we don't
        -- care about them anymore.  We don't care about records
        -- in rhnVirtualInstance if we are deleting the host
        -- system and the virtual system is already null, or
        -- vice-versa.  We *do* care about them if either the
        -- host or virtual system is still registered because we
        -- still want them to show up in the UI.
    -- If there's a newer row in rhnVirtualInstance with the same
    -- uuid, this guest must have been re-registered, so we can clean
    -- this data up.

        delete from rhnVirtualInstance vi
              where (host_system_id = server_id_in and virtual_system_id is null)
                 or (virtual_system_id = server_id_in and host_system_id is null)
                 or (vi.virtual_system_id = server_id_in and vi.modified < (select max(vi2.modified)
                    from rhnVirtualInstance vi2 where vi2.uuid = vi.uuid));

        -- this is merge of two single updates:
        --  update ... set host_system_id = null where host_system_id = server_id_in;
        --  update ... set virtual_system_id = null where virtual_system_id = server_id_in;
        -- so we scan rhnVirtualInstance table only once
        update rhnVirtualInstance
           set host_system_id = case when host_system_id = server_id_in then null else host_system_id end,
               virtual_system_id = case when virtual_system_id = server_id_in then null else virtual_system_id end
         where host_system_id = server_id_in
            or virtual_system_id = server_id_in;

        -- this is merge of two single updates:
        --  update ... set old_host_system_id = null when old_host_system_id = server_id_in;
        --  update ... set new_host_system_id = null when new_host_system_id = server_id_in;
        -- so we scan rhnVirtualInstanceEventLog table only once
        update rhnVirtualInstanceEventLog
           set old_host_system_id = case when old_host_system_id = server_id_in then null else old_host_system_id end,
               new_host_system_id = case when new_host_system_id = server_id_in then null else new_host_system_id end
         where old_host_system_id = server_id_in
            or new_host_system_id = server_id_in;

        -- We're deleting everything with a foreign key to rhnServer
        -- here, now.  I'm hoping this will help aleviate our deadlock
        -- problem.

        delete from rhnActionConfigChannel where server_id = server_id_in;
        delete from rhnActionConfigRevision where server_id = server_id_in;
        delete from rhnActionPackageRemovalFailure where server_id = server_id_in;
        delete from rhnClientCapability where server_id = server_id_in;
        delete from rhnCpu where server_id = server_id_in;
        -- there's still a cascade here, because the constraint keeps the
        -- table locked for too long to rebuild it.  Ugh...
        delete from rhnDevice where server_id = server_id_in;
        delete from rhnProxyInfo where server_id = server_id_in;
        delete from rhnRam where server_id = server_id_in;
        delete from rhnRegToken where server_id = server_id_in;
        delete from rhnSatelliteInfo where server_id = server_id_in;
        -- this cascades to rhnActionConfigChannel and rhnActionConfigFileName
        delete from rhnServerAction where server_id = server_id_in;
        delete from rhnServerActionPackageResult where server_id = server_id_in;
        delete from rhnServerActionScriptResult where server_id = server_id_in;
        delete from rhnServerActionVerifyResult where server_id = server_id_in;
        delete from rhnServerActionVerifyMissing where server_id = server_id_in;
        -- counts are handled above.  this should be a delete_ function.
        delete from rhnServerChannel where server_id = server_id_in;
        delete from rhnServerConfigChannel where server_id = server_id_in;
        delete from rhnServerCustomDataValue where server_id = server_id_in;
        delete from rhnServerDMI where server_id = server_id_in;
        delete from rhnServerEvent where server_id = server_id_in;
        delete from rhnServerHistory where server_id = server_id_in;
        delete from rhnServerInfo where server_id = server_id_in;
        delete from rhnServerInstallInfo where server_id = server_id_in;
        delete from rhnServerLocation where server_id = server_id_in;
        delete from rhnServerLock where server_id = server_id_in;
        delete from rhnServerNeededCache where server_id = server_id_in;
        delete from rhnServerNetwork where server_id = server_id_in;
        delete from rhnServerNotes where server_id = server_id_in;
        -- I'm not removing the foreign key from rhnServerPackage; that'll
        -- take forever.  Do the delete anyway.
        delete from rhnServerPackage where server_id = server_id_in;
        delete from rhnServerTokenRegs where server_id = server_id_in;
        delete from rhnSnapshotTag where server_id = server_id_in;
        -- this cascades to:
        --   rhnSnapshotChannel, rhnSnapshotConfigChannel, rhnSnapshotPackage,
        --   rhnSnapshotConfigRevision, rhnSnapshotServerGroup,
        --   rhnSnapshotTag.
        -- We may want to consider delete_snapshot() at some point, but
        --   I don't think we need to yet.
        delete from rhnSnapshot where server_id = server_id_in;
        delete from rhnUserServerPrefs where server_id = server_id_in;
        -- hrm, this one's interesting... we _probably_ should delete
        -- everything for the parent server_id when we delete the proxy,
        -- but we don't currently.
        delete from rhnServerPath where server_id_in in (server_id, proxy_server_id);
        delete from rhnUserServerPerms where server_id = server_id_in;

        delete from rhnServerNetInterface where server_id = server_id_in;

        delete from rhnServerUuid where server_id = server_id_in;

        delete from rhnPushClient where server_id = server_id_in;

        -- now get rhnServer itself.
        delete
        from    rhnServer
                where id = server_id_in;

        delete
        from    rhnSet
        where   1=1
                and user_id in (
                        select  wc.id
                        from    rhnServer rs,
                                web_contact wc
                        where   rs.id = server_id_in
                                and rs.org_id = wc.org_id
                )
                and label = 'system_list'
                and element = server_id_in;
end;
$$
language plpgsql;

 07070100000B32000081B400000000000000000000000167AE111400001225000000000000000000000000000000000000008100000000susemanager-schema/upgrade/susemanager-schema-2.1.51-to-susemanager-schema-3.0/9101-remove_virtualization_host_platform_refs.sql  
SELECT .clear_log_id();

-- rhnServerGroup and dependencies

DELETE FROM rhnOrgExtGroupMapping
  WHERE server_group_id in (
    SELECT id
      FROM rhnServerGroup
      WHERE group_type = (
        SELECT id
          FROM rhnServerGroupType
          WHERE label = 'virtualization_host_platform'
      )
  );

DELETE FROM rhnRegTokenGroups
  WHERE server_group_id in (
    SELECT id
      FROM rhnServerGroup
      WHERE group_type = (
        SELECT id
          FROM rhnServerGroupType
          WHERE label = 'virtualization_host_platform'
      )
  );

-- create server group for 'virtualization_host' everywhere
insert into rhnServerGroup ( id, name, description, group_type, org_id )
  select nextval('rhn_server_group_id_seq'), sgt.name, sgt.name, sgt.id, X.org_id
  from rhnServerGroupType sgt,
     (select distinct msg.org_id
        from rhnServerGroup msg
       where msg.org_id not in (select org_id
                                  from rhnServerGroup sg
                                  join rhnServerGroupType sgt ON sgt.id = sg.group_type
                                 where sgt.label = 'virtualization_host')
     ) X
  where sgt.label = 'virtualization_host';

-- add membership to 'virtualization_host' for all server which
-- are currently in the group 'virtualization_host_platform'
  insert into rhnServerGroupMembers (server_id, server_group_id)
    select * from (
      select sgm.server_id,
        (select nsg.id
           from rhnServerGroup nsg
           join rhnServerGroupType nsgt on nsg.group_type = nsgt.id
          where nsgt.label = 'virtualization_host'
            and nsg.org_id = sg.org_id) new_group_id
        from rhnServerGroupMembers sgm
        join rhnServerGroup sg on sgm.server_group_id = sg.id
        join rhnServerGroupType sgt on sg.group_type = sgt.id
       where sgt.label = 'virtualization_host_platform'
    ) X
    where not exists (select 1
                       from rhnServerGroupMembers csgm
                      where csgm.server_id = X.server_id
                        and csgm.server_group_id = X.new_group_id);

-- remove 'virtualization_host_platform'
DELETE FROM rhnServerGroupMembers
  WHERE server_group_id in (
    SELECT id
      FROM rhnServerGroup
      WHERE group_type = (
        SELECT id
          FROM rhnServerGroupType
          WHERE label = 'virtualization_host_platform'
      )
  );

DELETE FROM rhnSnapshotServerGroup
  WHERE server_group_id in (
    SELECT id
      FROM rhnServerGroup
      WHERE group_type = (
        SELECT id
          FROM rhnServerGroupType
          WHERE label = 'virtualization_host_platform'
      )
  );

DELETE FROM rhnUserDefaultSystemGroups
  WHERE system_group_id in (
    SELECT id
      FROM rhnServerGroup
      WHERE group_type = (
        SELECT id
          FROM rhnServerGroupType
          WHERE label = 'virtualization_host_platform'
      )
  );

DELETE FROM rhnUserServerGroupPerms
  WHERE server_group_id in (
    SELECT id
      FROM rhnServerGroup
      WHERE group_type = (
        SELECT id
          FROM rhnServerGroupType
          WHERE label = 'virtualization_host_platform'
      )
  );

DELETE FROM rhnServerGroup
  WHERE group_type = (
    SELECT id
      FROM rhnServerGroupType
      WHERE label = 'virtualization_host_platform'
  );

-- rhnServerGroupType and dependencies

UPDATE rhnRegTokenEntitlement
  SET server_group_type_id = (
    SELECT id
      FROM rhnServerGroupType
      WHERE label = 'virtualization_host'
  )
  WHERE server_group_type_id = (
    SELECT id
      FROM rhnServerGroupType
      WHERE label = 'virtualization_host_platform'
  );

DELETE FROM rhnServerGroupTypeFeature
  WHERE server_group_type_id = (
    SELECT id
      FROM rhnServerGroupType
      WHERE label = 'virtualization_host_platform'
  );

DELETE FROM rhnServerServerGroupArchCompat
  WHERE server_group_type = (
    SELECT id
      FROM rhnServerGroupType
      WHERE label = 'virtualization_host_platform'
  );

DELETE FROM rhnSGTypeBaseAddonCompat
  WHERE addon_id = (
    SELECT id
      FROM rhnServerGroupType
      WHERE label = 'virtualization_host_platform'
  );

DELETE FROM rhnSGTypeVirtSublevel
  WHERE server_group_type_id = (
    SELECT id
      FROM rhnServerGroupType
      WHERE label = 'virtualization_host_platform'
  );

DELETE FROM rhnServerGroupType
  WHERE label = 'virtualization_host_platform';

--rhnOrgEntitlementType

DELETE FROM rhnOrgEntitlements
  WHERE entitlement_id = (
    SELECT id
      FROM rhnOrgEntitlementType
      WHERE label = 'rhn_virtualization_platform'
  );

DELETE FROM rhnOrgEntitlementType
  WHERE label = 'rhn_virtualization_platform';
   07070100000B33000081B400000000000000000000000167AE111400000133000000000000000000000000000000000000007300000000susemanager-schema/upgrade/susemanager-schema-2.1.51-to-susemanager-schema-3.0/9102-remove_virt_sub_level_refs.sql    DELETE FROM rhnException
WHERE label = 'invalid_virt_sub_level';

delete from rhnChannelFamilyVirtSubLevel;
delete from rhnSGTypeVirtSubLevel;
delete from rhnVirtSubLevel;

DROP TABLE rhnChannelFamilyVirtSubLevel;
DROP TABLE rhnSGTypeVirtSubLevel;
DROP TABLE rhnVirtSubLevel;
DROP SEQUENCE rhn_virt_sl_seq;
 07070100000B34000081B400000000000000000000000167AE111400000052000000000000000000000000000000000000007800000000susemanager-schema/upgrade/susemanager-schema-2.1.51-to-susemanager-schema-3.0/9103-remove_virt_sub_level_functions.sql   DROP FUNCTION lookup_virt_sub_level(varchar); -- TODO really 'character varying'?
  07070100000B35000081B400000000000000000000000167AE111400000265000000000000000000000000000000000000006E00000000susemanager-schema/upgrade/susemanager-schema-2.1.51-to-susemanager-schema-3.0/9104-remove_sat_check_task.sql DELETE FROM rhnTaskoRun
  WHERE template_id IN (
    SELECT id
      FROM rhnTaskoTemplate
      WHERE task_id IN (
        SELECT id
          FROM rhnTaskoTask
          WHERE name = 'sat-cert-check'
      )
  );

DELETE FROM rhnTaskoTemplate
  WHERE bunch_id IN (
    SELECT id
      FROM rhnTaskoBunch
      WHERE name = 'satcert-check-bunch'
  );

DELETE FROM rhnTaskoTask
  WHERE name = 'sat-cert-check';

DELETE FROM rhnTaskoSchedule
  WHERE bunch_id IN (
    SELECT id
      FROM rhnTaskoBunch
      WHERE name = 'satcert-check-bunch'
  );

DELETE FROM rhnTaskoBunch
  WHERE name = 'satcert-check-bunch';
   07070100000B36000081B400000000000000000000000167AE11140000001D000000000000000000000000000000000000006E00000000susemanager-schema/upgrade/susemanager-schema-2.1.51-to-susemanager-schema-3.0/9105-drop_rhnSatelliteCert.sql DROP TABLE rhnSatelliteCert;
   07070100000B37000081B400000000000000000000000167AE111400002DC7000000000000000000000000000000000000006D00000000susemanager-schema/upgrade/susemanager-schema-2.1.51-to-susemanager-schema-3.0/9109-rhn_entitlements.pkb.sql  --
-- Copyright (c) 2008--2015 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

-- create schema rhn_entitlements;

-- setup search_path so that these functions are created in appropriate schema.
update pg_settings set setting = 'rhn_entitlements,' || setting where name = 'search_path';

   create or replace function find_compatible_sg (
      server_id_in in numeric,
      type_label_in in varchar
   )
   returns numeric
as $$
    declare
      servergroups cursor for
         select sg.id
           from rhnServerGroupType             sgt,
                rhnServerGroup                 sg,
                rhnServer                     s,
                rhnServerServerGroupArchCompat ssgac
          where s.id = server_id_in
            and s.org_id = sg.org_id
            and sgt.label = type_label_in
            and sg.group_type = sgt.id
            and ssgac.server_group_type = sgt.id
            and ssgac.server_arch_id = s.server_arch_id
            and not exists (
                     select 1
                      from rhnServerGroupMembers sgm
                     where sgm.server_group_id = sg.id
                       and sgm.server_id = s.id);


   begin
      for servergroup in servergroups loop
         return servergroup.id;
      end loop;

      --no servergroup found
      return NULL;
   end$$
language plpgsql;


    create or replace function entitlement_grants_service (
        entitlement_in in varchar,
        service_level_in in varchar
    ) returns numeric
as $$
    begin
        if service_level_in = 'management' then
            if entitlement_in = 'enterprise_entitled' or entitlement_in = 'salt_entitled' then
                return 1;
            else
                return 0;
            end if;
        elsif service_level_in = 'updates' then
            return 1;
        else
            return 0;
        end if;
    end$$
language plpgsql;

   create or replace function can_entitle_server (
      server_id_in   in numeric,
      type_label_in  in varchar
   )
   returns numeric
as $$
    declare
      addon_servergroups cursor (base_label_in varchar,
                                 addon_label_in varchar) for
         select
            addon_id
         from
            rhnSGTypeBaseAddonCompat
         where base_id = lookup_sg_type (base_label_in)
           and addon_id = lookup_sg_type (addon_label_in);

      previous_ent        varchar[];
      is_base_in          char   := 'N';
      is_base_current     char   := 'N';
      i                   numeric := 0;
      sgid                numeric := 0;

   begin

      previous_ent := rhn_entitlements.get_server_entitlement(server_id_in);

      select distinct is_base
      into is_base_in
      from rhnServerGroupType
      where label = type_label_in;

      if array_upper(previous_ent, 1) is null or array_upper(previous_ent, 1) = 0 then
         if is_base_in = 'Y' then
            sgid := rhn_entitlements.find_compatible_sg (server_id_in, type_label_in);
            if sgid is not null then
              -- rhn_server.insert_into_servergroup (server_id_in, sgid);
              return 1;
            else
              -- rhn_exception.raise_exception ('invalid_base_entitlement');
              return 0;
            end if;
         else
            -- rhn_exception.raise_exception ('invalid_base_entitlement');
            return 0;
         end if;

      -- there are previous ents, first make sure we're not trying to entitle a base ent
      elsif is_base_in = 'Y' then
         -- rhn_exception.raise_exception ('invalid_addon_entitlement');
         return 0;

      -- it must be an addon, so proceed with the entitlement
      else

         -- find the servers base ent
         is_base_current := 'N';
         i := 0;
         while is_base_current = 'N' and i < array_upper(previous_ent, 1)
         loop
            i := i + 1;
            select is_base
            into is_base_current
            from rhnServerGroupType
            where label = previous_ent[i];
         end loop;

         -- never found a base ent, that would be strange
         if is_base_current  = 'N' then
            -- rhn_exception.raise_exception ('invalid_base_entitlement');
            return 0;
         end if;

         -- this for loop verifies the validity of the addon path
         for addon_servergroup in addon_servergroups  (previous_ent[i], type_label_in) loop
            -- find an appropriate sgid for the addon and entitle the server
            sgid := rhn_entitlements.find_compatible_sg (server_id_in, type_label_in);
            if sgid is not null then
               -- rhn_server.insert_into_servergroup (server_id_in, sgid);
               return 1;
            else
               -- rhn_exception.raise_exception ('invalid_addon_entitlement');
               return 0;
            end if;
         end loop;

      end if;

      return 0;

   end$$
language plpgsql;

   create or replace function can_switch_base (
      server_id_in   in    integer,
      type_label_in  in    varchar
   )
   returns numeric
as $$
   declare
      type_label_in_is_base   char(1);
      sgid                    numeric;

   begin

       select is_base into type_label_in_is_base
       from rhnServerGroupType
       where label = type_label_in;

       if not found then
          perform rhn_exception.raise_exception ( 'invalid_entitlement' );
       end if;

      if type_label_in_is_base = 'N' then
         perform rhn_exception.raise_exception ( 'invalid_entitlement' );
      else
         sgid := rhn_entitlements.find_compatible_sg ( server_id_in,
                                                       type_label_in );
         if sgid is not null then
           return 1;
         else
           return 0;
         end if;
      end if;

   end$$
language plpgsql;

    create or replace function entitle_server (
        server_id_in in numeric,
        type_label_in in varchar
    ) returns void
as $$
    declare
      sgid  numeric := 0;

    begin

      if rhn_entitlements.can_entitle_server(server_id_in,
                                             type_label_in) = 1 then
         sgid := rhn_entitlements.find_compatible_sg (server_id_in,
                                                      type_label_in);
         if sgid is not null then
            insert into rhnServerHistory ( id, server_id, summary, details )
            values ( nextval('rhn_event_id_seq'), server_id_in,
                     'added system entitlement ',
                      case type_label_in
                       when 'enterprise_entitled' then 'Management'
                       when 'bootstrap_entitled' then 'Bootstrap'
                       when 'salt_entitled' then 'Salt'
                       when 'foreign_entitled' then 'Foreign'
                       when 'virtualization_host' then 'Virtualization'
                      end  );

            perform rhn_server.insert_into_servergroup (server_id_in, sgid);

         else
            perform rhn_exception.raise_exception ('no_available_server_group');
         end if;
      else
         perform rhn_exception.raise_exception ('invalid_entitlement');
      end if;
   end$$
language plpgsql;

    create or replace function remove_server_entitlement (
        server_id_in in numeric,
        type_label_in in varchar
    ) returns void
as $$
    declare
      group_id numeric;
      type_is_base char;
    begin

        select  sg.id, sgt.is_base
        into group_id, type_is_base
        from    rhnServerGroupType sgt,
            rhnServerGroup sg,
                rhnServerGroupMembers sgm,
                rhnServer s
        where   s.id = server_id_in
            and s.id = sgm.server_id
            and sgm.server_group_id = sg.id
            and sg.org_id = s.org_id
            and sgt.label = type_label_in
            and sgt.id = sg.group_type;

        if not found then
          perform rhn_exception.raise_exception('invalid_server_group_member');
        end if;

      if ( type_is_base = 'Y' ) then
         -- unentitle_server should handle everything, don't really need to do anything else special here
         perform rhn_entitlements.unentitle_server ( server_id_in );
      else

         insert into rhnServerHistory ( id, server_id, summary, details )
         values ( nextval('rhn_event_id_seq'), server_id_in,
                  'removed system entitlement ',
                   case type_label_in
                    when 'enterprise_entitled' then 'Management'
                    when 'bootstrap_entitled' then 'Bootstrap'
                    when 'salt_entitled' then 'Salt'
                    when 'foreign_entitled' then 'Foreign'
                    when 'virtualization_host' then 'Virtualization'
                   end  );

         perform rhn_server.delete_from_servergroup(server_id_in, group_id);

      end if;

    end$$
language plpgsql;

    create or replace function unentitle_server (
        server_id_in in numeric
    ) returns void
as $$
    declare
      servergroups cursor for
         select distinct sgt.label, sg.id server_group_id
         from  rhnServerGroupType sgt,
               rhnServerGroup sg,
               rhnServer s,
               rhnServerGroupMembers sgm
         where s.id = server_id_in
            and s.org_id = sg.org_id
            and sg.group_type = sgt.id
            and sgm.server_group_id = sg.id
            and sgm.server_id = s.id;

   begin

      for servergroup in servergroups loop

         insert into rhnServerHistory ( id, server_id, summary, details )
         values ( nextval('rhn_event_id_seq'), server_id_in,
                  'removed system entitlement ',
                   case servergroup.label
                    when 'enterprise_entitled' then 'Management'
                    when 'bootstrap_entitled' then 'Bootstrap'
                    when 'salt_entitled' then 'Salt'
                    when 'foreign_entitled' then 'Foreign'
                    when 'virtualization_host' then 'Virtualization'
                   end  );

         perform rhn_server.delete_from_servergroup(server_id_in,
                                            servergroup.server_group_id );
      end loop;

   end$$
language plpgsql;


    create or replace function get_server_entitlement (
        server_id_in in numeric
    ) returns varchar[]
as $$
    declare
        server_groups cursor for
            select  sgt.label
            from    rhnServerGroupType      sgt,
                    rhnServerGroup          sg,
                    rhnServerGroupMembers   sgm
            where   1=1
                and sgm.server_id = server_id_in
                and sg.id = sgm.server_group_id
                and sgt.id = sg.group_type;

         ent_array varchar[];

    begin

      ent_array := '{}';

      for sg in server_groups loop
         ent_array := ent_array || sg.label;
      end loop;

      return ent_array;

    end$$
language plpgsql;

-- restore the original setting
update pg_settings set setting = overlay( setting placing '' from 1 for (length('rhn_entitlements')+1) ) where name = 'search_path';
 07070100000B38000081B400000000000000000000000167AE111400001C31000000000000000000000000000000000000006400000000susemanager-schema/upgrade/susemanager-schema-2.1.51-to-susemanager-schema-3.0/9110-rhn_org.pkb.sql   --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--

-- create schema rhn_org;

-- setup search_path so that these functions are created in appropriate schema.
update pg_settings set setting = 'rhn_org,' || setting where name = 'search_path';


create or replace function delete_org (
        org_id_in in numeric
    ) returns void
    as
    $$
    declare
        users cursor for
        select id
        from web_contact
        where org_id = org_id_in;

        servers cursor (org_id_in numeric) for
        select  id
        from    rhnServer
        where   org_id = org_id_in;

        config_channels cursor for
        select id
        from rhnConfigChannel
        where org_id = org_id_in;

        custom_channels cursor for
        select  id
        from    rhnChannel
        where   org_id = org_id_in;

        errata cursor for
        select  id
        from    rhnErrata
        where   org_id = org_id_in;

    begin

        if org_id_in = 1 then
            perform rhn_exception.raise_exception('cannot_delete_base_org');
        end if;

        -- Delete all users.
        for u in users loop
            perform rhn_org.delete_user(u.id, 1);
        end loop;

        -- Delete all servers.
        for s in servers(org_id_in) loop
            perform delete_server(s.id);
        end loop;

        -- Delete all config channels.
        for c in config_channels loop
            perform rhn_config.delete_channel(c.id);
        end loop;

        -- Delete all custom channels.
        for cc in custom_channels loop
          delete from rhnServerChannel where channel_id = cc.id;
          delete from rhnServerProfilePackage where server_profile_id in (
            select id from rhnServerProfile where base_channel = cc.id
          );
          delete from rhnServerProfile where base_channel = cc.id;
        end loop;

        -- Delete all errata packages 
        for e in errata loop
            delete from rhnErrataPackage where errata_id = e.id;
        end loop;

        -- Clean up tables where we don't have a cascading delete.
        delete from rhnChannel where org_id = org_id_in;
        delete from rhnDailySummaryQueue where org_id = org_id_in;
        delete from rhnFileList where org_id = org_id_in;
        delete from rhnServerGroup where org_id = org_id_in;
        delete from rhnContentSource where org_id = org_id_in;

        -- Delete the org.
        delete from web_customer where id = org_id_in;

    end;
    $$
    language plpgsql;

create or replace function delete_user(user_id_in in numeric, deleting_org in numeric default 0) returns void 
    as
    $$
    declare
    servergroups_needing_admins cursor for
            select    usgp.server_group_id    server_group_id
            from    rhnUserServerGroupPerms    usgp
            where    1=1
                and usgp.user_id = user_id_in
                and not exists (
                    select    1
                    from    rhnUserServerGroupPerms    sq_usgp
                    where    1=1
                        and sq_usgp.server_group_id = usgp.server_group_id
                        and    sq_usgp.user_id != user_id_in
                );
        users            numeric;
        our_org_id        numeric;
        other_users        numeric;
        other_org_admin    numeric;
        other_user_id  numeric;
        is_admin       numeric;
    begin
        select    wc.org_id
        into    our_org_id
        from    web_contact wc
        where    id = user_id_in;

        -- find any other users
        begin
            select    id, 1
            into    other_user_id, other_users
            from    web_contact
            where    1=1
                and org_id = our_org_id
                and id != user_id_in
                limit 1;
        exception
            when no_data_found then
                other_users := 0;
        end;

        -- now do org admin stuff
        if other_users != 0 then
            -- is user admin?
            select  count(1)
             into   is_admin
            from    rhnUserGroupType    ugt,
                    rhnUserGroup        ug,
                    rhnUserGroupMembers    ugm
            where    ugm.user_id = user_id_in
                and ugm.user_group_id = ug.id
                and ug.group_type = ugt.id
                and ugt.label = 'org_admin';
            if is_admin > 0 then
                begin
                    select    new_ugm.user_id
                    into    other_org_admin
                    from    rhnUserGroupMembers    new_ugm,
                            rhnUserGroupType    ugt,
                            rhnUserGroup        ug,
                            rhnUserGroupMembers    ugm
                    where    ugm.user_id = user_id_in
                        and ugm.user_group_id = ug.id
                        and ug.group_type = ugt.id
                        and ugt.label = 'org_admin'
                        and ug.id = new_ugm.user_group_id
                        and new_ugm.user_id != user_id_in
                        limit 1;
                exception
                    when no_data_found then
                        -- If we're deleting the org, we don't want to raise
                        -- the exception.
                        if deleting_org = 0 then
                           perform rhn_exception.raise_exception('cannot_delete_user');
                        end if;
                end;

                for sg in servergroups_needing_admins loop
                   perform rhn_user.add_servergroup_perm(other_org_admin,
                        sg.server_group_id);
                end loop;
            end if;
        end if;

        -- and now things for every user
        delete from rhnUserServerPerms where user_id = user_id_in;
        update rhnConfigRevision
           set changed_by_id = NULL
         where changed_by_id = user_id_in;
        if other_users != 0 then
            update        rhnRegToken
                set        user_id = coalesce(other_org_admin, other_user_id)
                where    org_id = our_org_id
                    and user_id = user_id_in;
        end if;

        begin
            delete from web_contact where id = user_id_in;
        exception
            when others then
               perform rhn_exception.raise_exception('cannot_delete_user');
        end;
        return;

        end;
        $$
        language plpgsql;


-- restore the original setting
update pg_settings set setting = overlay( setting placing '' from 1 for (length('rhn_org')+1) ) where name = 'search_path';
   07070100000B39000081B400000000000000000000000167AE111400004F22000000000000000000000000000000000000006700000000susemanager-schema/upgrade/susemanager-schema-2.1.51-to-susemanager-schema-3.0/9112-rhn_server.pkb.sql    --
-- Copyright (c) 2008--2014 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--

-- create schema rhn_server;

--update pg_setting
update pg_settings set setting = 'rhn_server,' || setting where name = 'search_path';

    create or replace function system_service_level(
    	server_id_in in numeric,
	service_level_in in varchar
    ) returns numeric as $$
    declare
    ents cursor is 
      select label from rhnServerEntitlementView
      where server_id = server_id_in;

    retval numeric := 0;

    begin
         for ent in ents loop
            retval := rhn_entitlements.entitlement_grants_service (ent.label, service_level_in);
            if retval = 1 then
               return retval;
            end if;
         end loop;

         return retval;

    end$$ language plpgsql;

        
    create or replace function can_change_base_channel(server_id_in IN NUMERIC)
    returns numeric
    as $$
    declare
    	throwaway numeric;
    begin
    	-- the idea: if we get past this query, the server is
	-- neither sat nor proxy, so base channel is changeable

	select 1 into throwaway
	  from rhnServer S
	 where S.id = server_id_in
	   and not exists (select 1 from rhnSatelliteInfo SI where SI.server_id = S.id)
	   and not exists (select 1 from rhnProxyInfo PI where PI.server_id = S.id);

        if not found then
	    return 0;
        end if;
	   
	return 1;
    end$$ language plpgsql;
	        
    create or replace function set_custom_value(
    	server_id_in in numeric,
	user_id_in in numeric,
	key_label_in in varchar,
	value_in in varchar
    ) returns void
    as $$
    declare
    	key_id_val numeric;
    begin
    	select CDK.id into strict key_id_val
	  from rhnCustomDataKey CDK,
	       rhnServer S
	 where S.id = server_id_in
	   and S.org_id = CDK.org_id
	   and CDK.label = key_label_in;
	   
	begin
	    insert into rhnServerCustomDataValue (server_id, key_id, value, created_by, last_modified_by)
	    values (server_id_in, key_id_val, value_in, user_id_in, user_id_in);
	exception
	    when UNIQUE_VIOLATION
	    	then
		update rhnServerCustomDataValue
		   set value = value_in,
		       last_modified_by = user_id_in
		 where server_id = server_id_in
		   and key_id = key_id_val;		   
	end;

    end$$ language plpgsql;
    
    create or replace function bulk_set_custom_value(
    	key_label_in in varchar,
	value_in in varchar,
	set_label_in in varchar,
	set_uid_in in numeric
    )
    returns integer
    as $$
    declare
        i integer;
        server record;
    begin
        i := 0;
        for server in (
           SELECT user_id, label, element, element_two
	     FROM rhnSet
	    WHERE label = set_label_in
	      AND user_id = set_uid_in
	) loop
	    if rhn_server.system_service_level(server.element, 'management') = 1 then
	    	perform rhn_server.set_custom_value(server.element, set_uid_in, key_label_in, value_in);
            i := i + 1;
	    end if;
	end loop;
    return i;
    end$$ language plpgsql;

    create or replace function bulk_snapshot_tag(
    	org_id_in in numeric,
        tagname_in in varchar,
	set_label_in in varchar,
	set_uid_in in numeric
    ) returns void
    as $$
    declare
        server record;
    	snapshot_id numeric;
    begin
        for server in (
           SELECT user_id, label, element, element_two
	     FROM rhnSet
	    WHERE label = set_label_in
	      AND user_id = set_uid_in
	    ) loop
	    if rhn_server.system_service_level(server.element, 'management') = 1 then
	    	    select max(id) into snapshot_id
	    	    from rhnSnapshot
	    	    where server_id = server.element;

	    	    if snapshot_id is null then
		    	perform rhn_server.snapshot_server(server.element, 'tagging system:  ' || tagname_in);
			
			select max(id) into snapshot_id
			from rhnSnapshot
			where server_id = server.element;
		    end if;
		 
		-- now have a snapshot_id to work with...
		begin
		    perform rhn_server.tag_snapshot(snapshot_id, org_id_in, tagname_in);
		exception
		    when UNIQUE_VIOLATION
		    	then
			-- do nothing, be forgiving...
			null;
		end;
	    end if;
	end loop;    
    end$$ language plpgsql;

    create or replace function tag_delete(
    	server_id_in in numeric,
	tag_id_in in numeric
    ) returns void
    as $$
    declare
    	snapshots cursor is
		select	snapshot_id
		from	rhnSnapshotTag
		where	tag_id = tag_id_in;
	tag_id_tmp numeric;
    begin
    	select	id into tag_id_tmp
	from	rhnTag
	where	id = tag_id_in
	for update;

	delete
		from	rhnSnapshotTag
		where	server_id = server_id_in
			and tag_id = tag_id_in;
	for snapshot in snapshots loop
		return;
	end loop;
	delete
		from rhnTag
		where id = tag_id_in;
    end$$ language plpgsql;

    create or replace function tag_snapshot(
        snapshot_id_in in numeric,
	org_id_in in numeric,
	tagname_in in varchar
    ) returns void
    as $$
    begin
    	insert into rhnSnapshotTag (snapshot_id, server_id, tag_id)
	select snapshot_id_in, server_id, lookup_tag(org_id_in, tagname_in)
	from rhnSnapshot
	where id = snapshot_id_in;
    end$$ language plpgsql;

    create or replace function bulk_snapshot(
    	reason_in in varchar,
	set_label_in in varchar,
	set_uid_in in numeric
    ) returns void
    as $$
    declare
        server record;
    begin
        for server in (
           SELECT user_id, label, element, element_two
	     FROM rhnSet
	    WHERE label = set_label_in
	      AND user_id = set_uid_in
	    ) loop
	    if rhn_server.system_service_level(server.element, 'management') = 1 then
	    	perform rhn_server.snapshot_server(server.element, reason_in);
	    end if;
	end loop;
    end$$ language plpgsql;

    create or replace function snapshot_server(
    	server_id_in in numeric,
	reason_in in varchar
    ) returns void
    as $$
    declare
    	snapshot_id_v numeric;
	revisions cursor is
		select distinct
			cr.id
		from	rhnConfigRevision	cr,
			rhnConfigFileName	cfn,
			rhnConfigFile		cf,
			rhnConfigChannel	cc,
			rhnServerConfigChannel	scc
		where	1=1
			and scc.server_id = server_id_in
			and scc.config_channel_id = cc.id
			and cc.id = cf.config_channel_id
			and cf.id = cr.config_file_id
			and cr.id = cf.latest_config_revision_id
			and cf.config_file_name_id = cfn.id
			and cf.id = lookup_first_matching_cf(scc.server_id, cfn.path);
	locked integer;
    begin
    	select nextval('rhn_snapshot_id_seq') into snapshot_id_v;

	insert into rhnSnapshot (id, org_id, server_id, reason) (
		select	snapshot_id_v,
			s.org_id,
			server_id_in,
			reason_in
		from	rhnServer s
		where	s.id = server_id_in
	);
	insert into rhnSnapshotChannel (snapshot_id, channel_id) (
		select	snapshot_id_v, sc.channel_id
		from	rhnServerChannel sc
		where	sc.server_id = server_id_in
	);
	insert into rhnSnapshotServerGroup (snapshot_id, server_group_id) (
		select	snapshot_id_v, sgm.server_group_id
		from	rhnServerGroupMembers sgm
		where	sgm.server_id = server_id_in
	);
        locked := 0;
        <<iloop>>
        while true loop
            begin
                insert into rhnPackageNEVRA (id, name_id, evr_id, package_arch_id)
                select nextval('rhn_pkgnevra_id_seq'), sp.name_id, sp.evr_id, sp.package_arch_id
                from rhnServerPackage sp
                where sp.server_id = server_id_in
                        and not exists
                        (select 1
                                from rhnPackageNEVRA nevra
                                where nevra.name_id = sp.name_id
                                        and nevra.evr_id = sp.evr_id
                                        and (nevra.package_arch_id = sp.package_arch_id
                                            or (nevra.package_arch_id is null
                                                and sp.package_arch_id is null)));
                exit iloop;
            exception when unique_violation then
                if locked = 1 then
                    raise;
                else
                    lock table rhnPackageNEVRA in exclusive mode;
                    locked := 1;
                end if;
            end;
        end loop;
	insert into rhnSnapshotPackage (snapshot_id, nevra_id) (
                select distinct snapshot_id_v, nevra.id
                from    rhnServerPackage sp, rhnPackageNEVRA nevra
                where   sp.server_id = server_id_in
                        and nevra.name_id = sp.name_id
                        and nevra.evr_id = sp.evr_id
                        and (nevra.package_arch_id = sp.package_arch_id
                            or (nevra.package_arch_id is null
                                and sp.package_arch_id is null))
	);

	insert into rhnSnapshotConfigChannel ( snapshot_id, config_channel_id ) (
		select	snapshot_id_v, scc.config_channel_id
		from	rhnServerConfigChannel scc
		where	server_id = server_id_in
	);

	for revision in revisions loop
		insert into rhnSnapshotConfigRevision (
				snapshot_id, config_revision_id
			) values (
				snapshot_id_v, revision.id
			);
	end loop;
    end$$ language plpgsql;

    create or replace function remove_action(
    	server_id_in in numeric,
	action_id_in in numeric
    ) returns void
    as $$
    declare
    	-- this really wants "nulls last", but 8.1.7.3.0 sucks ass.
	-- instead, we make a local table that holds our
	-- list of ids with null prereqs.  There's surely a better way
	-- (an array instead of a table maybe?  who knows...)
	-- but I've got code to do this handy that I can look at ;)
    	chained_actions cursor is
                with recursive r(id, prerequisite) as (
			select	id, prerequisite
			from	rhnAction
			where id = action_id_in
		union all
			select	r1.id, r1.prerequisite
			from	rhnAction r1, r
			where r.id = r1.prerequisite
		)
		select * from r
		order by prerequisite desc;
	sessions cursor is
		select	s.id
		from	rhnKickstartSession s
		where	server_id_in in (s.old_server_id, s.new_server_id)
			and s.action_id = action_id_in
			and not exists (
				select	1
				from	rhnKickstartSessionState ss
				where	ss.id = s.state_id
					and ss.label in ('failed','complete')
			);
	chain_ends numeric[];
	i numeric;
	prereq numeric := 1;
    begin
	select	prerequisite
	into	prereq
	from	rhnAction
	where	id = action_id_in;

	if prereq is not null then
		perform rhn_exception.raise_exception('action_is_child');
	end if;

        chain_ends := '{}';
	i := 1;
	for action in chained_actions loop
		if action.prerequisite is null then
			chain_ends[i] := action.id;
			i := i + 1;
		else
			delete from rhnServerAction
				where server_id = server_id_in
				and action_id = action.id;
		end if;
	end loop;

	delete from rhnServerAction
		where server_id = server_id_in
		and action_id = any(chain_ends);

	for s in sessions loop
		update rhnKickstartSession
			set 	state_id = (
					select	id
					from	rhnKickstartSessionState
					where	label = 'failed'
				),
				action_id = null
			where	id = s.id;
		perform set_ks_session_history_message(s.id, 'failed', 'Kickstart cancelled due to action removal');
	end loop;
    end$$ language plpgsql;
   
    create or replace function check_user_access(server_id_in in numeric, user_id_in in numeric)
    returns numeric
    as $$
    declare
    	has_access numeric;
    begin
    	-- first check; if this returns no rows, then the server/user are in different orgs, and we bail
        select 1 into has_access
	  from rhnServer S,
	       web_contact wc
	 where wc.org_id = s.org_id
	   and s.id = server_id_in
	   and wc.id = user_id_in;

        if not found then
          return 0;
        end if;

	-- okay, so they're in the same org.  if we have an org admin, they get a free pass
    	if rhn_user.check_role(user_id_in, 'org_admin') = 1
	then
	    return 1;
	end if;
		   
    	select 1 into has_access
	  from rhnServerGroupMembers SGM,
	       rhnUserServerGroupPerms USG
	 where SGM.server_group_id = USG.server_group_id
	   and SGM.server_id = server_id_in
	   and USG.user_id = user_id_in;

        if not found then
          return 0;
        end if;
	   
	return 1;
    end$$ language plpgsql;

    create or replace function insert_into_servergroup (
		server_id_in in numeric,
		server_group_id_in in numeric
    ) returns void
    as $$
    declare
		group_type numeric;
	begin
		-- this will rowlock the servergroup we're trying to change;
		-- we probably need to lock the other one, but I think the chances
		-- of it being a real issue are very small for now...
		select	sg.group_type
		into	group_type
		from	rhnServerGroup sg
		where	sg.id = server_group_id_in
		for update of sg;

		insert into rhnServerGroupMembers(server_id, server_group_id)
		values (server_id_in, server_group_id_in);

		update rhnServerGroup
		set current_members = current_members + 1
		where id = server_group_id_in;

		if group_type is null then
			perform rhn_cache.update_perms_for_server_group(server_group_id_in);
		end if;

		return;
	end$$ language plpgsql;

	create or replace function insert_into_servergroup_maybe (
		server_id_in in numeric,
		server_group_id_in in numeric
	) returns numeric as $$ 
    declare
		retval numeric := 0;
		servergroups cursor is
			select	s.id	server_id,
					sg.id	server_group_id
			from	rhnServerGroup	sg,
					rhnServer		s
			where	s.id = server_id_in
				and sg.id = server_group_id_in
				and s.org_id = sg.org_id
				and not exists (
					select	1
					from	rhnServerGroupMembers sgm
					where	sgm.server_id = s.id
						and sgm.server_group_id = sg.id
				);
	begin
		for sgm in servergroups loop
			perform rhn_server.insert_into_servergroup(sgm.server_id, sgm.server_group_id);
			retval := retval + 1;
		end loop;
		return retval;
	end$$ language plpgsql;

	create or replace function insert_set_into_servergroup (
		server_group_id_in in numeric,
		user_id_in in numeric,
		set_label_in in varchar
	) returns void
        as $$
    declare
		servers cursor is
			select	st.element	id
			from	rhnSet		st
			where	st.user_id = user_id_in
				and st.label = set_label_in
				and exists (
					select	1
					from	rhnUserManagedServerGroups umsg
					where	umsg.server_group_id = server_group_id_in
						and umsg.user_id = user_id_in
					)
				and not exists (
					select	1
					from	rhnServerGroupMembers sgm
					where	sgm.server_id = st.element
						and sgm.server_group_id = server_group_id_in
				);
	begin
		for s in servers loop
			perform rhn_server.insert_into_servergroup(s.id, server_group_id_in);
		end loop;
	end$$ language plpgsql;
		
    create or replace function delete_from_servergroup (
    	server_id_in in numeric,
	server_group_id_in in numeric
    ) returns void
    as $$
    declare

		oid numeric;
		label varchar;
		group_type numeric;
	begin
		select	sg.group_type, sg.org_id
		into	group_type,	oid
		from	rhnServerGroupMembers	sgm,
			rhnServerGroup		sg
		where	sg.id = server_group_id_in
		and 	sg.id = sgm.server_group_id
		and 	sgm.server_id = server_id_in
		for update of sg;

		if not found then
			perform rhn_exception.raise_exception('server_not_in_group');
		end if;

		delete from rhnServerGroupMembers
		where server_group_id = server_group_id_in
		and	server_id = server_id_in;

		update rhnServerGroup
		set current_members = current_members - 1
		where id = server_group_id_in;

		-- do group_type is null first
		if group_type is null then
			perform rhn_cache.update_perms_for_server_group(server_group_id_in);
		end if;

	end$$ language plpgsql;

	create or replace function delete_set_from_servergroup (
		server_group_id_in in numeric,
		user_id_in in numeric,
		set_label_in in varchar
	) returns void
        as $$	
        declare
		servergroups cursor is
			select	sgm.server_id, sgm.server_group_id
			from	rhnSet st,
					rhnServerGroupMembers sgm
			where	sgm.server_group_id = server_group_id_in
				and st.user_id = user_id_in
				and st.label = set_label_in
				and sgm.server_id = st.element
				and exists (
					select	1
					from	rhnUserManagedServerGroups usgp
					where	usgp.server_group_id = server_group_id_in
						and usgp.user_id = user_id_in
				);
	begin
		for sgm in servergroups loop
			perform rhn_server.delete_from_servergroup(sgm.server_id, server_group_id_in);
		end loop;
	end$$ language plpgsql;

	create or replace function clear_servergroup (
		server_group_id_in in numeric
	) returns void
        as $$
        declare
		servers cursor is
			select	sgm.server_id	id
			from	rhnServerGroupMembers sgm
			where	sgm.server_group_id = server_group_id_in;
	begin
		for s in servers loop
			perform rhn_server.delete_from_servergroup(s.id, server_group_id_in);
		end loop;
	end$$ language plpgsql;

	create or replace function delete_from_org_servergroups (
		server_id_in in numeric
	) returns void
        as $$
        declare
		servergroups cursor is
			select	sgm.server_group_id id
			from	rhnServerGroup sg,
					rhnServerGroupMembers sgm
			where	sgm.server_id = server_id_in
				and sgm.server_group_id = sg.id
				and sg.group_type is null;
	begin
		for sg in servergroups loop
			perform rhn_server.delete_from_servergroup(server_id_in, sg.id);
		end loop;
	end$$ language plpgsql;

	create or replace function get_ip_address (
		server_id_in in numeric
	) returns varchar as $$
        declare
		interfaces cursor is
			select	ni.name as name, na4.address as address
			from	rhnServerNetInterface ni,
			        rhnServerNetAddress4 na4
			where	server_id = server_id_in
                and ni.id = na4.interface_id
				and na4.address != '127.0.0.1';
		addresses cursor is
			select	ipaddr ip_addr
			from	rhnServerNetwork
			where	server_id = server_id_in
				and ipaddr != '127.0.0.1';
	begin
		for addr in addresses loop
			return addr.ip_addr;
		end loop;
		for iface in interfaces loop
			return iface.address;
		end loop;
		return NULL;
	end$$ language plpgsql;

    create or replace function update_needed_cache(
        server_id_in in numeric
	) returns void as $$
    declare
      update_lock numeric;
    begin
      select id into update_lock from rhnServer where id = server_id_in for update;
      delete from rhnServerNeededCache
        where server_id = server_id_in;
      insert into rhnServerNeededCache
             (server_id, errata_id, package_id, channel_id)
        (select distinct sp.server_id, x.errata_id, p.id, x.channel_id
           FROM (SELECT sp_sp.server_id, sp_sp.name_id,
		        sp_sp.package_arch_id, max(sp_pe.evr) AS max_evr
                   FROM rhnServerPackage sp_sp
                   join rhnPackageEvr sp_pe ON sp_pe.id = sp_sp.evr_id
                  GROUP BY sp_sp.server_id, sp_sp.name_id, sp_sp.package_arch_id) sp
           join rhnPackage p ON p.name_id = sp.name_id
           join rhnPackageEvr pe ON pe.id = p.evr_id AND sp.max_evr < pe.evr
           join rhnPackageUpgradeArchCompat puac
	            ON puac.package_arch_id = sp.package_arch_id
		    AND puac.package_upgrade_arch_id = p.package_arch_id
           join rhnServerChannel sc ON sc.server_id = sp.server_id
           join rhnChannelPackage cp ON cp.package_id = p.id
	            AND cp.channel_id = sc.channel_id
           left join (SELECT ep.errata_id, ce.channel_id, ep.package_id
                        FROM rhnChannelErrata ce
                        join rhnErrataPackage ep
			         ON ep.errata_id = ce.errata_id
			join rhnServerChannel sc_sc
			         ON sc_sc.channel_id = ce.channel_id
		       WHERE sc_sc.server_id = server_id_in) x
             ON x.channel_id = sc.channel_id AND x.package_id = cp.package_id
          where sp.server_id = server_id_in);
	end$$ language plpgsql;
-- restore the original setting
update pg_settings set setting = overlay( setting placing '' from 1 for (length('rhn_server')+1) ) where name = 'search_path';
  07070100000B3A000081B400000000000000000000000167AE111400000058000000000000000000000000000000000000006500000000susemanager-schema/upgrade/susemanager-schema-2.1.51-to-susemanager-schema-3.0/9113-rhnexception.sql  DELETE FROM rhnException WHERE id = -20220;
DELETE FROM rhnException WHERE id = -20290;
07070100000B3B000081B400000000000000000000000167AE111400000DD1000000000000000000000000000000000000005E00000000susemanager-schema/upgrade/susemanager-schema-2.1.51-to-susemanager-schema-3.0/9114-views.sql DROP VIEW rhnServerGroupMembership;

CREATE OR REPLACE VIEW rhnServerGroupMembership (
         ORG_ID, SERVER_ID, GROUP_ID, GROUP_NAME, GROUP_TYPE, CURRENT_MEMBERS
)
AS
SELECT   SG.org_id, SGM.server_id, SG.id, SG.name, SGT.label, SG.current_members
  FROM
	 rhnServerGroupMembers SGM
             right join
    	 rhnServerGroup SG on (SG.id = SGM.server_group_id)
             left join
         rhnServerGroupType SGT on (SG.group_type = SGT.id)
;

DROP VIEW rhnVisServerGroupMembership;

CREATE OR REPLACE VIEW rhnVisServerGroupMembership (
         ORG_ID, SERVER_ID, GROUP_ID, GROUP_NAME, GROUP_TYPE, CURRENT_MEMBERS
)
AS
SELECT   SG.org_id, SGM.server_id, SG.id, SG.name, SGT.label, SG.current_members
  FROM
	 rhnServerGroupMembers SGM
            right outer join
    	 rhnVisibleServerGroup SG on (SG.id = SGM.server_group_id)
            left outer join
         rhnServerGroupType SGT on (SG.group_type = SGT.id)
;

DROP VIEW rhnVisServerGroupOverviewLite;

DROP VIEW rhnServerGroupOverview;

CREATE OR REPLACE VIEW rhnServerGroupOverview (
         ORG_ID, SECURITY_ERRATA, BUG_ERRATA, ENHANCEMENT_ERRATA, GROUP_ID, GROUP_NAME, GROUP_ADMINS, SERVER_COUNT, MODIFIED
)
AS
  SELECT SG.org_id,
         (SELECT COUNT(distinct E.id)
            FROM rhnErrata E,
                 rhnServerNeededErrataCache SNEC,
                 rhnServerGroupMembers SGM
           WHERE E.advisory_type = 'Security Advisory'
                 and SNEC.errata_id = e.id
                 and SNEC.server_id = sgm.server_id
                 and sgm.server_group_id = sg.id
                 AND EXISTS ( SELECT 1
                              FROM rhnServerFeaturesView SFV
                              WHERE SFV.server_id = SGM.server_id
                                    AND SFV.label = 'ftr_system_grouping')),
         (SELECT COUNT(distinct E.id)
            FROM rhnErrata E,
                 rhnServerNeededErrataCache SNEC,
                 rhnServerGroupMembers SGM
           WHERE E.advisory_type = 'Bug Fix Advisory'
                 and SNEC.errata_id = e.id
                 and SNEC.server_id = sgm.server_id
                 and sgm.server_group_id = sg.id
                 AND EXISTS ( SELECT 1
                              FROM rhnServerFeaturesView SFV
                              WHERE SFV.server_id = SGM.server_id
                                    AND SFV.label = 'ftr_system_grouping')),
         (SELECT COUNT(distinct E.id)
            FROM rhnErrata E,
                 rhnServerNeededErrataCache SNEC,
                 rhnServerGroupMembers SGM
           WHERE E.advisory_type = 'Product Enhancement Advisory'
                 and SNEC.errata_id = e.id
                 and SNEC.server_id = sgm.server_id
                 and sgm.server_group_id = sg.id
                 AND EXISTS ( SELECT 1
                              FROM rhnServerFeaturesView SFV
                              WHERE SFV.server_id = SGM.server_id
                                    AND SFV.label = 'ftr_system_grouping')),
         SG.id, SG.name,
         (SELECT COUNT(*) FROM rhnUserManagedServerGroups UMSG WHERE UMSG.server_group_id = SG.id),
         (SELECT COUNT(*) FROM rhnServerGroupMembers SGM WHERE SGM.server_group_id = SG.id
                 AND EXISTS ( SELECT 1
                              FROM rhnServerFeaturesView SFV
                              WHERE SFV.server_id = SGM.server_id
                                    AND SFV.label = 'ftr_system_grouping')),
         CURRENT_TIMESTAMP
    FROM rhnServerGroup SG;
   07070100000B3C000081B400000000000000000000000167AE11140000272C000000000000000000000000000000000000006600000000susemanager-schema/upgrade/susemanager-schema-2.1.51-to-susemanager-schema-3.0/9115-delete_server.sql --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
-- This deletes a server.  All codepaths which delete servers should hit this
-- or delete_server_bulk()

create or replace
function delete_server (
        server_id_in in numeric
) returns void 
as
$$
declare
         servergroups cursor for
                select  server_id, server_group_id
                from    rhnServerGroupMembers sgm
                where   sgm.server_id = server_id_in;

         configchannels cursor for
                select  cc.id
                from    rhnConfigChannel cc,
                        rhnConfigChannelType cct,
                        rhnServerConfigChannel scc
                where   1=1
                        and scc.server_id = server_id_in
                        and scc.config_channel_id = cc.id
                        -- these config channel types are reserved
                        -- for use by a single server, so we don't
                        -- need to check for other servers subscribed
                        and cct.label in
                                ('local_override','server_import')
                        and cct.id = cc.confchan_type_id;

begin
        -- filelists
        delete from rhnFileList where id in (
	select	spfl.file_list_id
	  from	rhnServerPreserveFileList spfl
	 where	spfl.server_id = server_id_in
			and not exists (
				select	1
				from	rhnServerPreserveFileList
				where	file_list_id = spfl.file_list_id
					and server_id != server_id_in
				union all
				select	1
				from	rhnKickstartPreserveFileList
				where	file_list_id = spfl.file_list_id
			)
        );

	for configchannel in configchannels loop
		perform rhn_config.delete_channel(configchannel.id);
	end loop;

	for sgm in servergroups loop
		perform rhn_server.delete_from_servergroup(
			sgm.server_id, sgm.server_group_id);
	end loop;


        -- we're handling this instead of letting an "on delete
        -- set null" do it so that we don't run the risk
        -- of setting off the triggers and killing us with a
        -- mutating table

        -- this is merge of two single updates:
        --  update ... set old_server_id = null where old_server_id = server_id_in;
        --  update ... set new_server_id = null where new_server_id = server_id_in;
        -- so we scan rhnKickstartSession table only once
        update rhnKickstartSession
                set old_server_id = case when old_server_id = server_id_in then null else old_server_id end,
                    new_server_id = case when new_server_id = server_id_in then null else new_server_id end
                where old_server_id = server_id_in
                   or new_server_id = server_id_in;

        perform rhn_channel.clear_subscriptions(server_id_in, 1);

        -- A little complicated here, but the goal is to
        -- delete records from rhnVirtualInstace only if we don't
        -- care about them anymore.  We don't care about records
        -- in rhnVirtualInstance if we are deleting the host
        -- system and the virtual system is already null, or
        -- vice-versa.  We *do* care about them if either the
        -- host or virtual system is still registered because we
        -- still want them to show up in the UI.
    -- If there's a newer row in rhnVirtualInstance with the same
    -- uuid, this guest must have been re-registered, so we can clean
    -- this data up.

        delete from rhnVirtualInstance vi
              where (host_system_id = server_id_in and virtual_system_id is null)
                 or (virtual_system_id = server_id_in and host_system_id is null)
                 or (vi.virtual_system_id = server_id_in and vi.modified < (select max(vi2.modified)
                    from rhnVirtualInstance vi2 where vi2.uuid = vi.uuid));

        -- this is merge of two single updates:
        --  update ... set host_system_id = null where host_system_id = server_id_in;
        --  update ... set virtual_system_id = null where virtual_system_id = server_id_in;
        -- so we scan rhnVirtualInstance table only once
        update rhnVirtualInstance
           set host_system_id = case when host_system_id = server_id_in then null else host_system_id end,
               virtual_system_id = case when virtual_system_id = server_id_in then null else virtual_system_id end
         where host_system_id = server_id_in
            or virtual_system_id = server_id_in;

        -- this is merge of two single updates:
        --  update ... set old_host_system_id = null when old_host_system_id = server_id_in;
        --  update ... set new_host_system_id = null when new_host_system_id = server_id_in;
        -- so we scan rhnVirtualInstanceEventLog table only once
        update rhnVirtualInstanceEventLog
           set old_host_system_id = case when old_host_system_id = server_id_in then null else old_host_system_id end,
               new_host_system_id = case when new_host_system_id = server_id_in then null else new_host_system_id end
         where old_host_system_id = server_id_in
            or new_host_system_id = server_id_in;

        -- We're deleting everything with a foreign key to rhnServer
        -- here, now.  I'm hoping this will help aleviate our deadlock
        -- problem.

        delete from rhnActionConfigChannel where server_id = server_id_in;
        delete from rhnActionConfigRevision where server_id = server_id_in;
        delete from rhnActionPackageRemovalFailure where server_id = server_id_in;
        delete from rhnClientCapability where server_id = server_id_in;
        delete from rhnCpu where server_id = server_id_in;
        -- there's still a cascade here, because the constraint keeps the
        -- table locked for too long to rebuild it.  Ugh...
        delete from rhnDevice where server_id = server_id_in;
        delete from rhnProxyInfo where server_id = server_id_in;
        delete from rhnRam where server_id = server_id_in;
        delete from rhnRegToken where server_id = server_id_in;
        delete from rhnSatelliteInfo where server_id = server_id_in;
        -- this cascades to rhnActionConfigChannel and rhnActionConfigFileName
        delete from rhnServerAction where server_id = server_id_in;
        delete from rhnServerActionPackageResult where server_id = server_id_in;
        delete from rhnServerActionScriptResult where server_id = server_id_in;
        delete from rhnServerActionVerifyResult where server_id = server_id_in;
        delete from rhnServerActionVerifyMissing where server_id = server_id_in;
        -- counts are handled above.  this should be a delete_ function.
        delete from rhnServerChannel where server_id = server_id_in;
        delete from rhnServerConfigChannel where server_id = server_id_in;
        delete from rhnServerCustomDataValue where server_id = server_id_in;
        delete from rhnServerDMI where server_id = server_id_in;
        delete from rhnServerEvent where server_id = server_id_in;
        delete from rhnServerHistory where server_id = server_id_in;
        delete from rhnServerInfo where server_id = server_id_in;
        delete from rhnServerInstallInfo where server_id = server_id_in;
        delete from rhnServerLocation where server_id = server_id_in;
        delete from rhnServerLock where server_id = server_id_in;
        delete from rhnServerNeededCache where server_id = server_id_in;
        delete from rhnServerNetwork where server_id = server_id_in;
        delete from rhnServerNotes where server_id = server_id_in;
        -- I'm not removing the foreign key from rhnServerPackage; that'll
        -- take forever.  Do the delete anyway.
        delete from rhnServerPackage where server_id = server_id_in;
        delete from rhnServerTokenRegs where server_id = server_id_in;
        delete from rhnSnapshotTag where server_id = server_id_in;
        -- this cascades to:
        --   rhnSnapshotChannel, rhnSnapshotConfigChannel, rhnSnapshotPackage,
        --   rhnSnapshotConfigRevision, rhnSnapshotServerGroup,
        --   rhnSnapshotTag.
        -- We may want to consider delete_snapshot() at some point, but
        --   I don't think we need to yet.
        delete from rhnSnapshot where server_id = server_id_in;
        delete from rhnUserServerPrefs where server_id = server_id_in;
        -- hrm, this one's interesting... we _probably_ should delete
        -- everything for the parent server_id when we delete the proxy,
        -- but we don't currently.
        delete from rhnServerPath where server_id_in in (server_id, proxy_server_id);
        delete from rhnUserServerPerms where server_id = server_id_in;

        delete from rhnServerNetInterface where server_id = server_id_in;

        delete from rhnServerUuid where server_id = server_id_in;

        delete from rhnPushClient where server_id = server_id_in;

        -- now get rhnServer itself.
        delete
        from    rhnServer
                where id = server_id_in;

        delete
        from    rhnSet
        where   1=1
                and user_id in (
                        select  wc.id
                        from    rhnServer rs,
                                web_contact wc
                        where   rs.id = server_id_in
                                and rs.org_id = wc.org_id
                )
                and label = 'system_list'
                and element = server_id_in;
end;
$$
language plpgsql;

07070100000B3D000081B400000000000000000000000167AE111400000625000000000000000000000000000000000000006900000000susemanager-schema/upgrade/susemanager-schema-2.1.51-to-susemanager-schema-3.0/9116-drop_max_members.sql  
DROP VIEW rhnVisServerGroupMembership;
DROP VIEW rhnUsersInOrgOverview;
DROP VIEW rhnVisibleServerGroup;

ALTER TABLE rhnServerGroup DROP COLUMN max_members;
SELECT .recreate_trigger('rhnservergroup');

CREATE OR REPLACE VIEW
rhnVisibleServerGroup
AS
  SELECT *
    FROM rhnServerGroup SG
   WHERE SG.group_type IS NULL;

create or replace view rhnUsersInOrgOverview as
select    
  u.org_id          as org_id,
  u.id            as user_id,
  u.login           as user_login,
  pi.first_names          as user_first_name,
  pi.last_name          as user_last_name,
  u.modified          as user_modified,
      ( select  count(server_id)
    from  rhnUserServerPerms sp
    where sp.user_id = u.id)
              as server_count,
  ( select  count(server_group_id)
    from  rhnUserManagedServerGroups umsg
    where umsg.user_id = u.id and exists (
      select  1
      from  rhnVisibleServerGroup sg
      where sg.id = umsg.server_group_id))
              as server_group_count,
  coalesce(rhn_user.role_names(u.id), '(normal user)') as role_names
from  web_user_personal_info pi, 
  web_contact u 
where
  u.id = pi.web_user_id;

CREATE OR REPLACE VIEW rhnVisServerGroupMembership (
         ORG_ID, SERVER_ID, GROUP_ID, GROUP_NAME, GROUP_TYPE, CURRENT_MEMBERS
)
AS
SELECT   SG.org_id, SGM.server_id, SG.id, SG.name, SGT.label, SG.current_members
  FROM
   rhnServerGroupMembers SGM
            right outer join
       rhnVisibleServerGroup SG on (SG.id = SGM.server_group_id)
            left outer join
         rhnServerGroupType SGT on (SG.group_type = SGT.id)
;   07070100000B3E000081B400000000000000000000000167AE11140000187A000000000000000000000000000000000000006700000000susemanager-schema/upgrade/susemanager-schema-2.1.51-to-susemanager-schema-3.0/9118-create_new_org.sql    --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--

create or replace function create_new_org
(
        name_in      in varchar,
        password_in  in varchar
        --org_id_out   out NUMERIC
) returns numeric
as
$$
declare
        ug_type                 numeric;
        group_val               numeric;
        new_org_id              numeric;
        org_id_out		numeric;
begin

        select nextval('web_customer_id_seq') into new_org_id from dual;

        insert into web_customer (
                id, name
        ) values (
                new_org_id, name_in
        );

        select nextval('rhn_user_group_id_seq') into group_val from dual;

        select  id
        into    ug_type
        from    rhnUserGroupType
        where   label = 'org_admin';

        insert into rhnUserGroup (
                id, name,
                description,
                max_members, group_type, org_id
        ) values (
                group_val, 'Organization Administrators',
                'Organization Administrators for Org ' || name_in,
                NULL, ug_type, new_org_id
        );

        select nextval('rhn_user_group_id_seq') into group_val from dual;

        select  id
        into    ug_type
        from    rhnUserGroupType
        where   label = 'system_group_admin';

        insert into rhnUserGroup (
                id, name,
                description,
                max_members, group_type, org_id
        ) values (
                group_val, 'System Group Administrators',
                'System Group Administrators for Org ' || name_in,
                NULL, ug_type, new_org_id
        );


        select nextval('rhn_user_group_id_seq') into group_val from dual;

        select  id
        into    ug_type
        from    rhnUserGroupType
        where   label = 'activation_key_admin';

        insert into rhnUserGroup (
                id, name,
                description,
                max_members, group_type, org_id
        ) values (
                group_val, 'Activation Key Administrators',
                'Activation Key Administrators for Org ' || name_in,
                NULL, ug_type, new_org_id
        );

        select nextval('rhn_user_group_id_seq') into group_val from dual;

        select  id
        into    ug_type
        from    rhnUserGroupType
        where   label = 'channel_admin';

        insert into rhnUserGroup (
                id, name,
                description,
                max_members, group_type, org_id
        ) values (
                group_val, 'Channel Administrators',
                'Channel Administrators for Org ' || name_in,
                NULL, ug_type, new_org_id
        );

	if new_org_id = 1 then
            select nextval('rhn_user_group_id_seq') into group_val from dual;

            select  id
            into    ug_type
            from    rhnUserGroupType
            where   label = 'satellite_admin';

            insert into rhnUserGroup (
                    id, name,
                    description,
                    max_members, group_type, org_id
            ) values (
                    group_val, 'SUSE Manager Administrators',
                    'SUSE Manager Administrators for Org ' || name_in,
                    NULL, ug_type, new_org_id
            );
        end if;

        select nextval('rhn_user_group_id_seq') into group_val from dual;

        select  id
        into    ug_type
        from    rhnUserGroupType
        where   label = 'config_admin';

        insert into rhnUserGroup (
                id, name,
                description,
                max_members, group_type, org_id
        ) values (
                group_val, 'Configuration Administrators',
                'Configuration Administrators for Org ' || name_in,
                NULL, ug_type, new_org_id
        );

        -- there aren't any users yet, so we don't need to update
        -- rhnUserServerPerms

        insert into rhnServerGroup
                ( id, name, description, group_type, org_id )
                select nextval('rhn_server_group_id_seq'), sgt.name, sgt.name,
                        sgt.id, new_org_id
                from rhnServerGroupType sgt
                where sgt.label = 'bootstrap_entitled';

        insert into rhnServerGroup
                ( id, name, description, group_type, org_id )
                select nextval('rhn_server_group_id_seq'), sgt.name, sgt.name,
                        sgt.id, new_org_id
                from rhnServerGroupType sgt
                where sgt.label = 'enterprise_entitled';

        insert into rhnServerGroup
                ( id, name, description, group_type, org_id )
                select nextval('rhn_server_group_id_seq'), sgt.name, sgt.name,
                        sgt.id, new_org_id
                from rhnServerGroupType sgt
                where sgt.label = 'salt_entitled';

        insert into rhnServerGroup
                ( id, name, description, group_type, org_id )
                select nextval('rhn_server_group_id_seq'), sgt.name, sgt.name,
                        sgt.id, new_org_id
                from rhnServerGroupType sgt
                where sgt.label = 'foreign_entitled';

        insert into rhnServerGroup
                ( id, name, description, group_type, org_id )
                select nextval('rhn_server_group_id_seq'), sgt.name, sgt.name,
                        sgt.id, new_org_id
                from rhnServerGroupType sgt
                where sgt.label = 'virtualization_host';

        org_id_out := new_org_id;

	-- Returning the value of OUT parameter
        return org_id_out;

end;
$$
language plpgsql;


  07070100000B3F000081B400000000000000000000000167AE111400000041000000000000000000000000000000000000008A00000000susemanager-schema/upgrade/susemanager-schema-2.1.51-to-susemanager-schema-3.0/9119-drop-rhnOrgEntitlements-and-rhnOrgEntitlementType.sql DROP TABLE rhnOrgEntitlements;
DROP TABLE rhnOrgEntitlementType;
   07070100000B40000081B400000000000000000000000167AE111400000048000000000000000000000000000000000000006F00000000susemanager-schema/upgrade/susemanager-schema-2.1.51-to-susemanager-schema-3.0/9120-update-rhnInfoPane-acl.sql    UPDATE rhnInfoPane SET acl = NULL where label = 'system-groups-widget';
07070100000B41000081B400000000000000000000000167AE1114000021DB000000000000000000000000000000000000007100000000susemanager-schema/upgrade/susemanager-schema-2.1.51-to-susemanager-schema-3.0/9121-salt-entitlement-inserts.sql  -- rhnServerGroupType

insert into rhnServerGroupType (id, label, name, permanent, is_base)
   values (sequence_nextval('rhn_servergroup_type_seq'),
      'salt_entitled', 'Salt Management Entitled Servers',
      'N', 'Y'
   );

-- rhnServerGroupTypeFeature

insert into rhnServerGroupTypeFeature (server_group_type_id, feature_id,
                                       created, modified)
values (lookup_sg_type('salt_entitled'), lookup_feature_type('ftr_errata_updates'),
        current_timestamp,current_timestamp);

insert into rhnServerGroupTypeFeature (server_group_type_id, feature_id,
                                       created, modified)
values (lookup_sg_type('salt_entitled'), lookup_feature_type('ftr_daily_summary'),
        current_timestamp,current_timestamp);

insert into rhnServerGroupTypeFeature (server_group_type_id, feature_id,
                                       created, modified)
values (lookup_sg_type('salt_entitled'), lookup_feature_type('ftr_custom_info'),
        current_timestamp,current_timestamp);

-- rhnServerServerGroupArchCompat

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('i386-redhat-linux'),
            lookup_sg_type('salt_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('i386-debian-linux'),
            lookup_sg_type('salt_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('i486-redhat-linux'),
            lookup_sg_type('salt_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('i586-redhat-linux'),
            lookup_sg_type('salt_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('i686-redhat-linux'),
            lookup_sg_type('salt_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('athlon-redhat-linux'),
            lookup_sg_type('salt_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('alpha-redhat-linux'),
            lookup_sg_type('salt_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('alpha-debian-linux'),
            lookup_sg_type('salt_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('alphaev6-redhat-linux'),
            lookup_sg_type('salt_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('ia64-redhat-linux'),
            lookup_sg_type('salt_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('ia64-debian-linux'),
            lookup_sg_type('salt_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('sparc-redhat-linux'),
            lookup_sg_type('salt_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('sparc-debian-linux'),
            lookup_sg_type('salt_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('sparcv9-redhat-linux'),
            lookup_sg_type('salt_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('sparc64-redhat-linux'),
            lookup_sg_type('salt_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('s390-redhat-linux'),
            lookup_sg_type('salt_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
        values (lookup_server_arch('aarch64-redhat-linux'),
            lookup_sg_type('salt_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
        values (lookup_server_arch('armv7l-redhat-linux'),
            lookup_sg_type('salt_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
        values (lookup_server_arch('armv5tejl-redhat-linux'),
            lookup_sg_type('salt_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
        values (lookup_server_arch('armv6l-redhat-linux'),
            lookup_sg_type('salt_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
        values (lookup_server_arch('armv6hl-redhat-linux'),
            lookup_sg_type('salt_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('s390-debian-linux'),
            lookup_sg_type('salt_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('s390x-redhat-linux'),
            lookup_sg_type('salt_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('ppc-redhat-linux'),
            lookup_sg_type('salt_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('powerpc-debian-linux'),
            lookup_sg_type('salt_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('ppc64-redhat-linux'),
            lookup_sg_type('salt_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
    values (lookup_server_arch('ppc64le-redhat-linux'),
            lookup_sg_type('salt_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('pSeries-redhat-linux'),
            lookup_sg_type('salt_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('iSeries-redhat-linux'),
            lookup_sg_type('salt_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('x86_64-redhat-linux'),
            lookup_sg_type('salt_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('ia32e-redhat-linux'),
            lookup_sg_type('salt_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('amd64-redhat-linux'),
            lookup_sg_type('salt_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('amd64-debian-linux'),
            lookup_sg_type('salt_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('ppc64iseries-redhat-linux'),
            lookup_sg_type('salt_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('ppc64pseries-redhat-linux'),
            lookup_sg_type('salt_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('arm-debian-linux'),
            lookup_sg_type('salt_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('armv6l-debian-linux'),
            lookup_sg_type('salt_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
	values (lookup_server_arch('mips-debian-linux'),
            lookup_sg_type('salt_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
   values (lookup_server_arch('sparc-sun4m-solaris'),
           lookup_sg_type('salt_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
   values (lookup_server_arch('sparc-sun4u-solaris'),
           lookup_sg_type('salt_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
   values (lookup_server_arch('sparc-sun4v-solaris'),
           lookup_sg_type('salt_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
   values (lookup_server_arch('i386-i86pc-solaris'),
           lookup_sg_type('salt_entitled'));
 07070100000B42000081B400000000000000000000000167AE111400002044000000000000000000000000000000000000007300000000susemanager-schema/upgrade/susemanager-schema-2.1.51-to-susemanager-schema-3.0/9122-foreign-entitlement-insert.sql    -- foreign_entitled type ---------------------------------------------------------

insert into rhnServerGroupType ( id, label, name, permanent, is_base)
   values ( sequence_nextval('rhn_servergroup_type_seq'),
      'foreign_entitled', 'Foreign Entitled Servers',
      'Y', 'Y'
   );

-- foreign system entitlement

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
        values (lookup_server_arch('i386-redhat-linux'),
            lookup_sg_type('foreign_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
        values (lookup_server_arch('i386-debian-linux'),
            lookup_sg_type('foreign_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
        values (lookup_server_arch('i486-redhat-linux'),
            lookup_sg_type('foreign_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
        values (lookup_server_arch('i586-redhat-linux'),
            lookup_sg_type('foreign_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
        values (lookup_server_arch('i686-redhat-linux'),
            lookup_sg_type('foreign_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
        values (lookup_server_arch('athlon-redhat-linux'),
            lookup_sg_type('foreign_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
        values (lookup_server_arch('alpha-redhat-linux'),
            lookup_sg_type('foreign_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
        values (lookup_server_arch('alpha-debian-linux'),
            lookup_sg_type('foreign_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
        values (lookup_server_arch('alphaev6-redhat-linux'),
            lookup_sg_type('foreign_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
        values (lookup_server_arch('ia64-redhat-linux'),
            lookup_sg_type('foreign_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
        values (lookup_server_arch('ia64-debian-linux'),
            lookup_sg_type('foreign_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
        values (lookup_server_arch('sparc-redhat-linux'),
            lookup_sg_type('foreign_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
        values (lookup_server_arch('sparc-debian-linux'),
            lookup_sg_type('foreign_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
        values (lookup_server_arch('sparcv9-redhat-linux'),
            lookup_sg_type('foreign_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
        values (lookup_server_arch('sparc64-redhat-linux'),
            lookup_sg_type('foreign_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
        values (lookup_server_arch('s390-redhat-linux'),
            lookup_sg_type('foreign_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
        values (lookup_server_arch('aarch64-redhat-linux'),
            lookup_sg_type('foreign_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
        values (lookup_server_arch('armv7l-redhat-linux'),
            lookup_sg_type('foreign_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
        values (lookup_server_arch('armv5tejl-redhat-linux'),
            lookup_sg_type('foreign_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
        values (lookup_server_arch('armv6l-redhat-linux'),
            lookup_sg_type('foreign_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
        values (lookup_server_arch('armv6hl-redhat-linux'),
            lookup_sg_type('foreign_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
        values (lookup_server_arch('s390-debian-linux'),
            lookup_sg_type('foreign_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
        values (lookup_server_arch('s390x-redhat-linux'),
            lookup_sg_type('foreign_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
        values (lookup_server_arch('ppc-redhat-linux'),
            lookup_sg_type('foreign_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
        values (lookup_server_arch('powerpc-debian-linux'),
            lookup_sg_type('foreign_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
        values (lookup_server_arch('ppc64-redhat-linux'),
            lookup_sg_type('foreign_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
    values (lookup_server_arch('ppc64le-redhat-linux'),
            lookup_sg_type('foreign_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
        values (lookup_server_arch('pSeries-redhat-linux'),
            lookup_sg_type('foreign_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
        values (lookup_server_arch('iSeries-redhat-linux'),
            lookup_sg_type('foreign_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
        values (lookup_server_arch('x86_64-redhat-linux'),
            lookup_sg_type('foreign_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
        values (lookup_server_arch('ia32e-redhat-linux'),
            lookup_sg_type('foreign_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
        values (lookup_server_arch('amd64-redhat-linux'),
            lookup_sg_type('foreign_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
        values (lookup_server_arch('amd64-debian-linux'),
            lookup_sg_type('foreign_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
        values (lookup_server_arch('ppc64iseries-redhat-linux'),
            lookup_sg_type('foreign_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
        values (lookup_server_arch('ppc64pseries-redhat-linux'),
            lookup_sg_type('foreign_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
        values (lookup_server_arch('arm-debian-linux'),
            lookup_sg_type('foreign_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
        values (lookup_server_arch('armv6l-debian-linux'),
            lookup_sg_type('foreign_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
        values (lookup_server_arch('mips-debian-linux'),
            lookup_sg_type('foreign_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
   values (lookup_server_arch('sparc-sun4m-solaris'),
           lookup_sg_type('foreign_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
   values (lookup_server_arch('sparc-sun4u-solaris'),
           lookup_sg_type('foreign_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
   values (lookup_server_arch('sparc-sun4v-solaris'),
           lookup_sg_type('foreign_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
   values (lookup_server_arch('i386-i86pc-solaris'),
           lookup_sg_type('foreign_entitled'));

07070100000B43000081B400000000000000000000000167AE1114000003D8000000000000000000000000000000000000007400000000susemanager-schema/upgrade/susemanager-schema-2.1.51-to-susemanager-schema-3.0/9123-add-gatherer-taskomatic-job.sql   INSERT INTO rhnTaskoBunch (id, name, description, org_bunch)
             VALUES (sequence_nextval('rhn_tasko_bunch_id_seq'), 'gatherer-bunch', 'Schedule running gatherer', null);

INSERT INTO rhnTaskoSchedule (id, job_label, bunch_id, active_from, cron_expr)
    VALUES (sequence_nextval('rhn_tasko_schedule_id_seq'), 'gatherer-default',
        (SELECT id FROM rhnTaskoBunch WHERE name='gatherer-bunch'),
        current_timestamp, '0 0 0 ? * *');

INSERT INTO rhnTaskoTask (id, name, class)
         VALUES (sequence_nextval('rhn_tasko_task_id_seq'), 'gatherer', 'com.redhat.rhn.taskomatic.task.gatherer.GathererJob');

INSERT INTO rhnTaskoTemplate (id, bunch_id, task_id, ordering, start_if)
             VALUES (sequence_nextval('rhn_tasko_template_id_seq'),
                        (SELECT id FROM rhnTaskoBunch WHERE name='gatherer-bunch'),
                        (SELECT id FROM rhnTaskoTask WHERE name='gatherer'),
                        0,
                        null);

07070100000B44000081B400000000000000000000000167AE1114000005DF000000000000000000000000000000000000007200000000susemanager-schema/upgrade/susemanager-schema-2.1.51-to-susemanager-schema-3.0/9124-enlarge_digital_server_id.sql --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--
--

-- Before altering the size of the column, we must drop views referring to this
-- column. Then we need to recreate them again.
DROP VIEW rhnentitledservers;

-- Enlarge the size of digital_server_id to 1024.
ALTER TABLE rhnServer
ALTER COLUMN digital_server_id type varchar(1024);

-- Re-create rhnentitledservers view
create or replace view
rhnEntitledServers
as
select distinct
    S.id,
    S.org_id,
    S.digital_server_id,
    S.server_arch_id,
    S.os,
    S.release,
    S.name,
    S.description,
    S.info,
    S.secret
from
    rhnServerGroup SG,
    rhnServerGroupType SGT,
    rhnServerGroupMembers SGM,
    rhnServer S
where
    S.id = SGM.server_id
and SG.id = SGM.server_group_id
and SGT.label IN ('enterprise_entitled', 'bootstrap_entitled',
                  'salt_entitled', 'foreign_entitled')
and SG.group_type = SGT.id
and SG.org_id = S.org_id
;

 07070100000B45000081B400000000000000000000000167AE11140000024E000000000000000000000000000000000000007A00000000susemanager-schema/upgrade/susemanager-schema-2.1.51-to-susemanager-schema-3.0/9125-add-foreign_ent-to-rhnServerGroup.sql 
 SELECT .clear_log_id();

 insert into rhnServerGroup ( id, name, description, group_type, org_id )
  select nextval('rhn_server_group_id_seq'), sgt.name, sgt.name, sgt.id, X.org_id
  from rhnServerGroupType sgt,
     (select distinct msg.org_id
        from rhnServerGroup msg
       where msg.org_id not in (select org_id
                                  from rhnServerGroup sg
                                  join rhnServerGroupType sgt ON sgt.id = sg.group_type
                                 where sgt.label = 'foreign_entitled')
     ) X
  where sgt.label = 'foreign_entitled';
  07070100000B46000081B400000000000000000000000167AE111400000248000000000000000000000000000000000000007C00000000susemanager-schema/upgrade/susemanager-schema-2.1.51-to-susemanager-schema-3.0/9126-add-saltstack_ent-to-rhnServerGroup.sql   
 SELECT .clear_log_id();

 insert into rhnServerGroup ( id, name, description, group_type, org_id )
  select nextval('rhn_server_group_id_seq'), sgt.name, sgt.name, sgt.id, X.org_id
  from rhnServerGroupType sgt,
     (select distinct msg.org_id
        from rhnServerGroup msg
       where msg.org_id not in (select org_id
                                  from rhnServerGroup sg
                                  join rhnServerGroupType sgt ON sgt.id = sg.group_type
                                 where sgt.label = 'salt_entitled')
     ) X
  where sgt.label = 'salt_entitled';
07070100000B47000081B400000000000000000000000167AE1114000025EF000000000000000000000000000000000000006600000000susemanager-schema/upgrade/susemanager-schema-2.1.51-to-susemanager-schema-3.0/9127-delete_server.sql --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
-- This deletes a server.  All codepaths which delete servers should hit this
-- or delete_server_bulk()

create or replace
function delete_server (
        server_id_in in numeric
) returns void 
as
$$
declare
         servergroups cursor for
                select  server_id, server_group_id
                from    rhnServerGroupMembers sgm
                where   sgm.server_id = server_id_in;

         configchannels cursor for
                select  cc.id
                from    rhnConfigChannel cc,
                        rhnConfigChannelType cct,
                        rhnServerConfigChannel scc
                where   1=1
                        and scc.server_id = server_id_in
                        and scc.config_channel_id = cc.id
                        -- these config channel types are reserved
                        -- for use by a single server, so we don't
                        -- need to check for other servers subscribed
                        and cct.label in
                                ('local_override','server_import')
                        and cct.id = cc.confchan_type_id;

begin
        -- filelists
        delete from rhnFileList where id in (
	select	spfl.file_list_id
	  from	rhnServerPreserveFileList spfl
	 where	spfl.server_id = server_id_in
			and not exists (
				select	1
				from	rhnServerPreserveFileList
				where	file_list_id = spfl.file_list_id
					and server_id != server_id_in
				union all
				select	1
				from	rhnKickstartPreserveFileList
				where	file_list_id = spfl.file_list_id
			)
        );

	for configchannel in configchannels loop
		perform rhn_config.delete_channel(configchannel.id);
	end loop;

	for sgm in servergroups loop
		perform rhn_server.delete_from_servergroup(
			sgm.server_id, sgm.server_group_id);
	end loop;


        -- we're handling this instead of letting an "on delete
        -- set null" do it so that we don't run the risk
        -- of setting off the triggers and killing us with a
        -- mutating table

        -- this is merge of two single updates:
        --  update ... set old_server_id = null where old_server_id = server_id_in;
        --  update ... set new_server_id = null where new_server_id = server_id_in;
        -- so we scan rhnKickstartSession table only once
        update rhnKickstartSession
                set old_server_id = case when old_server_id = server_id_in then null else old_server_id end,
                    new_server_id = case when new_server_id = server_id_in then null else new_server_id end
                where old_server_id = server_id_in
                   or new_server_id = server_id_in;

        perform rhn_channel.clear_subscriptions(server_id_in, 1);

        -- A little complicated here, but the goal is to
        -- delete records from rhnVirtualInstace only if we don't
        -- care about them anymore.  We don't care about records
        -- in rhnVirtualInstance if we are deleting the host
        -- system and the virtual system is already null, or
        -- vice-versa.  We *do* care about them if either the
        -- host or virtual system is still registered because we
        -- still want them to show up in the UI.
    -- If there's a newer row in rhnVirtualInstance with the same
    -- uuid, this guest must have been re-registered, so we can clean
    -- this data up.

        delete from rhnVirtualInstance vi
              where (host_system_id = server_id_in and virtual_system_id is null)
                 or (virtual_system_id = server_id_in and host_system_id is null)
                 or (vi.virtual_system_id = server_id_in and vi.modified < (select max(vi2.modified)
                    from rhnVirtualInstance vi2 where vi2.uuid = vi.uuid));

        -- this is merge of two single updates:
        --  update ... set host_system_id = null where host_system_id = server_id_in;
        --  update ... set virtual_system_id = null where virtual_system_id = server_id_in;
        -- so we scan rhnVirtualInstance table only once
        update rhnVirtualInstance
           set host_system_id = case when host_system_id = server_id_in then null else host_system_id end,
               virtual_system_id = case when virtual_system_id = server_id_in then null else virtual_system_id end
         where host_system_id = server_id_in
            or virtual_system_id = server_id_in;

        -- this is merge of two single updates:
        --  update ... set old_host_system_id = null when old_host_system_id = server_id_in;
        --  update ... set new_host_system_id = null when new_host_system_id = server_id_in;
        -- so we scan rhnVirtualInstanceEventLog table only once
        update rhnVirtualInstanceEventLog
           set old_host_system_id = case when old_host_system_id = server_id_in then null else old_host_system_id end,
               new_host_system_id = case when new_host_system_id = server_id_in then null else new_host_system_id end
         where old_host_system_id = server_id_in
            or new_host_system_id = server_id_in;

        -- We're deleting everything with a foreign key to rhnServer
        -- here, now.  I'm hoping this will help aleviate our deadlock
        -- problem.

        delete from rhnActionConfigChannel where server_id = server_id_in;
        delete from rhnActionConfigRevision where server_id = server_id_in;
        delete from rhnActionPackageRemovalFailure where server_id = server_id_in;
        delete from rhnClientCapability where server_id = server_id_in;
        delete from rhnCpu where server_id = server_id_in;
        -- there's still a cascade here, because the constraint keeps the
        -- table locked for too long to rebuild it.  Ugh...
        delete from rhnDevice where server_id = server_id_in;
        delete from rhnProxyInfo where server_id = server_id_in;
        delete from rhnRam where server_id = server_id_in;
        delete from rhnRegToken where server_id = server_id_in;
        delete from rhnSatelliteInfo where server_id = server_id_in;
        -- this cascades to rhnActionConfigChannel and rhnActionConfigFileName
        delete from rhnServerAction where server_id = server_id_in;
        delete from rhnServerActionPackageResult where server_id = server_id_in;
        delete from rhnServerActionScriptResult where server_id = server_id_in;
        delete from rhnServerActionVerifyResult where server_id = server_id_in;
        delete from rhnServerActionVerifyMissing where server_id = server_id_in;
        -- counts are handled above.  this should be a delete_ function.
        delete from rhnServerChannel where server_id = server_id_in;
        delete from rhnServerConfigChannel where server_id = server_id_in;
        delete from rhnServerCustomDataValue where server_id = server_id_in;
        delete from rhnServerDMI where server_id = server_id_in;
        delete from rhnServerEvent where server_id = server_id_in;
        delete from rhnServerHistory where server_id = server_id_in;
        delete from rhnServerInfo where server_id = server_id_in;
        delete from rhnServerInstallInfo where server_id = server_id_in;
        delete from rhnServerLocation where server_id = server_id_in;
        delete from rhnServerLock where server_id = server_id_in;
        delete from rhnServerNeededCache where server_id = server_id_in;
        delete from rhnServerNetwork where server_id = server_id_in;
        delete from rhnServerNotes where server_id = server_id_in;
        -- I'm not removing the foreign key from rhnServerPackage; that'll
        -- take forever.  Do the delete anyway.
        delete from rhnServerPackage where server_id = server_id_in;
        delete from rhnServerTokenRegs where server_id = server_id_in;
        delete from rhnSnapshotTag where server_id = server_id_in;
        -- this cascades to:
        --   rhnSnapshotChannel, rhnSnapshotConfigChannel, rhnSnapshotPackage,
        --   rhnSnapshotConfigRevision, rhnSnapshotServerGroup,
        --   rhnSnapshotTag.
        -- We may want to consider delete_snapshot() at some point, but
        --   I don't think we need to yet.
        delete from rhnSnapshot where server_id = server_id_in;
        delete from rhnUserServerPrefs where server_id = server_id_in;
        -- hrm, this one's interesting... we _probably_ should delete
        -- everything for the parent server_id when we delete the proxy,
        -- but we don't currently.
        delete from rhnServerPath where server_id_in in (server_id, proxy_server_id);
        delete from rhnUserServerPerms where server_id = server_id_in;

        delete from rhnServerNetInterface where server_id = server_id_in;

        delete from rhnServerUuid where server_id = server_id_in;

        delete from rhnPushClient where server_id = server_id_in;

        -- now get rhnServer itself.
        delete
        from    rhnServer
                where id = server_id_in;

        delete
        from    rhnSet
        where   label = 'system_list'
                and element = server_id_in;
end;
$$
language plpgsql;

 07070100000B48000081B400000000000000000000000167AE111400001727000000000000000000000000000000000000006E00000000susemanager-schema/upgrade/susemanager-schema-2.1.51-to-susemanager-schema-3.0/9133-drop-unused-functions.sql 
drop function if exists rhn_channel.available_chan_subscriptions(channel_id_in IN NUMERIC, org_id_in IN NUMERIC);
drop function if exists rhn_channel.available_family_subscriptions(channel_family_id_in IN NUMERIC, org_id_in IN NUMERIC);
drop function if exists rhn_channel.available_fve_chan_subs(channel_id_in IN NUMERIC, org_id_in IN NUMERIC);
drop function if exists rhn_channel.available_fve_family_subs(channel_family_id_in IN NUMERIC, org_id_in IN NUMERIC);
drop function if exists rhn_channel.can_convert_to_fve(server_id_in IN NUMERIC, channel_family_id_val IN NUMERIC);
drop function if exists rhn_channel.can_server_consume_fve(server_id_in in numeric);
drop function if exists rhn_channel.can_server_consume_virt_channl(server_id_in in numeric, family_id_in in numeric );
drop function if exists rhn_channel.cfam_curr_fve_members(channel_family_id_in IN NUMERIC, org_id_in IN NUMERIC);
drop function if exists rhn_channel.channel_family_current_members(channel_family_id_in IN NUMERIC, org_id_in IN NUMERIC);
drop function if exists rhn_channel.clear_subscriptions(server_id_in numeric, deleting_server numeric, update_family_countsyn numeric);
drop function if exists rhn_channel.convert_to_fve(server_id_in IN NUMERIC, channel_family_id_val IN NUMERIC);
drop function if exists rhn_channel.delete_server_channels(server_id_in in numeric);
drop function if exists rhn_channel.server_has_family_subscription(server_id_in DECIMAL, channel_family_id_in DECIMAL);
drop function if exists rhn_channel.subscribe_server(server_id_in numeric, channel_id_in numeric, immediate_in numeric, user_id_in numeric, recalcfamily_in numeric);
drop function if exists rhn_channel.unsubscribe_server(server_id_in numeric, channel_id_in numeric, immediate_in numeric, unsubscribe_children_in numeric, deleting_server numeric, update_family_countsyn numeric);
drop function if exists rhn_channel.update_family_counts(channel_family_id_in IN NUMERIC, org_id_in IN NUMERIC);
drop function if exists rhn_channel.update_group_family_counts(group_label_in IN VARCHAR, org_id_in IN NUMERIC);

drop function if exists rhn_entitlements.activate_channel_entitlement(org_id_in in numeric, channel_family_label_in in varchar, quantity_in in numeric, flex_in in numeric);
drop function if exists rhn_entitlements.activate_system_entitlement(org_id_in numeric, group_label_in character varying, quantity_in numeric);
drop function if exists rhn_entitlements.assign_channel_entitlement(channel_family_label_in in varchar, from_org_id_in in numeric, to_org_id_in in numeric, quantity_in in numeric, flex_in in numeric);
drop function if exists rhn_entitlements.assign_system_entitlement(group_label_in character varying, from_org_id_in numeric, to_org_id_in numeric, quantity_in numeric);
drop function if exists rhn_entitlements.create_entitlement_group(org_id_in numeric, type_label_in character varying);
drop function if exists rhn_entitlements.entitle_last_modified_servers(customer_id_in numeric, type_label_in character varying, quantity_in numeric);
drop function if exists rhn_entitlements.lookup_entitlement_group(org_id_in numeric, type_label_in character varying);
drop function if exists rhn_entitlements.modify_org_service(org_id_in numeric, service_label_in character varying, enable_in character);
drop function if exists rhn_entitlements.prune_family(customer_id_in in numeric, channel_family_id_in in numeric, quantity_in in numeric, flex_in in numeric);
drop function if exists rhn_entitlements.prune_group(group_id_in in numeric, quantity_in in numeric, update_family_countsYN in numeric);
drop function if exists rhn_entitlements.prune_group(group_id_in numeric, quantity_in numeric);
drop function if exists rhn_entitlements.remove_org_entitlements(org_id_in numeric);
drop function if exists rhn_entitlements.remove_server_entitlement(server_id_in numeric, type_label_in character varying, repoll_virt_guests numeric);
drop function if exists rhn_entitlements.repoll_virt_guest_entitlements(server_id_in numeric);
drop function if exists rhn_entitlements.set_customer_enterprise(customer_id_in numeric);
drop function if exists rhn_entitlements.set_customer_monitoring(customer_id_in in numeric);
drop function if exists rhn_entitlements.set_customer_nonlinux(customer_id_in numeric);
drop function if exists rhn_entitlements.set_customer_provisioning(customer_id_in in numeric);
drop function if exists rhn_entitlements.set_family_count(customer_id_in in numeric, channel_family_id_in in numeric, quantity_in in numeric, flex_in in numeric);
drop function if exists rhn_entitlements.set_server_group_count(customer_id_in in numeric, group_type_in in numeric, quantity_in in numeric, update_family_countsYN in numeric);
drop function if exists rhn_entitlements.set_server_group_count(customer_id_in numeric, group_type_in numeric, quantity_in numeric);
drop function if exists rhn_entitlements.subscribe_newest_servers(customer_id_in in numeric);
drop function if exists rhn_entitlements.unset_customer_enterprise(customer_id_in numeric);
drop function if exists rhn_entitlements.unset_customer_monitoring(customer_id_in in numeric);
drop function if exists rhn_entitlements.unset_customer_nonlinux(customer_id_in numeric);
drop function if exists rhn_entitlements.unset_customer_provisioning(customer_id_in in numeric);

drop function if exists rhn_cmeth_val_trig_fun();
drop function if exists rhn_org_ent_mod_trig_fun();
drop function if exists rhn_org_ent_type_mod_trig_fun();
drop function if exists rhn_probe_delete_trigger_fun();
drop function if exists rhn_probe_insert_trigger_fun();
drop function if exists rhn_satcert_mod_trig_fun();
drop function if exists rhn_servnet_ipaddr_mon_trig_fun();
drop function if exists rhn_solaris_p_mod_trig_fun();
drop function if exists rhn_solaris_ps_mod_trig_fun();
drop function if exists rhn_solaris_psm_mod_trig_fun();
drop function if exists time_series_purge_mod_trig_fun();
 07070100000B49000081B400000000000000000000000167AE111400000316000000000000000000000000000000000000006D00000000susemanager-schema/upgrade/susemanager-schema-2.1.51-to-susemanager-schema-3.0/9134-susePackageStateType.sql  --
-- Copyright (c) 2015 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

CREATE TABLE susePackageStateType
(
    id        NUMERIC NOT NULL
                  CONSTRAINT suse_pkgstatetype_id_pk PRIMARY KEY,
    label     VARCHAR(32) NOT NULL
)

;
  07070100000B4A000081B400000000000000000000000167AE11140000033E000000000000000000000000000000000000007200000000susemanager-schema/upgrade/susemanager-schema-2.1.51-to-susemanager-schema-3.0/9135-susePackageStateType-data.sql --
-- Copyright (c) 2015 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

insert into susePackageStateType (id, label) values (0, 'installed');
insert into susePackageStateType (id, label) values (1, 'removed');
insert into susePackageStateType (id, label) values (2, 'purged');
commit;
  07070100000B4B000081B400000000000000000000000167AE11140000031C000000000000000000000000000000000000007200000000susemanager-schema/upgrade/susemanager-schema-2.1.51-to-susemanager-schema-3.0/9136-suseVersionConstraintType.sql --
-- Copyright (c) 2015 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

CREATE TABLE suseVersionConstraintType
(
    id        NUMERIC NOT NULL
                  CONSTRAINT suse_verconstrtype_id_pk PRIMARY KEY,
    label     VARCHAR(32) NOT NULL
)

;
07070100000B4C000081B400000000000000000000000167AE1114000002FE000000000000000000000000000000000000007700000000susemanager-schema/upgrade/susemanager-schema-2.1.51-to-susemanager-schema-3.0/9137-suseVersionConstraintType-data.sql    --
-- Copyright (c) 2015 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

insert into suseVersionConstraintType (id, label) values (0, 'latest');
insert into suseVersionConstraintType (id, label) values (1, 'any');
commit;
  07070100000B4D000081B400000000000000000000000167AE111400000452000000000000000000000000000000000000006A00000000susemanager-schema/upgrade/susemanager-schema-2.1.51-to-susemanager-schema-3.0/9138-suseStateRevision.sql --
-- Copyright (c) 2015 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

CREATE TABLE suseStateRevision
(
    id               NUMERIC NOT NULL
                         CONSTRAINT suse_state_revision_id_pk PRIMARY KEY,
    creator_id       NUMERIC
                         CONSTRAINT suse_state_revision_cid_fk
                             REFERENCES web_contact (id)
                             ON DELETE SET NULL,
    created          TIMESTAMPTZ
                         DEFAULT (current_timestamp) NOT NULL
)

;

CREATE SEQUENCE suse_state_revision_id_seq;
  07070100000B4E000081B400000000000000000000000167AE111400000542000000000000000000000000000000000000007000000000susemanager-schema/upgrade/susemanager-schema-2.1.51-to-susemanager-schema-3.0/9139-suseServerStateRevision.sql   --
-- Copyright (c) 2015 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--
-- CONSTRAINT names are different in the oracle version
-- pg names will be aligned again with 3.0.13/010-shorten-constraints-names

CREATE TABLE suseServerStateRevision
(
    server_id         NUMERIC NOT NULL
                          CONSTRAINT suse_server_state_rev_sid_fk
                              REFERENCES rhnServer (id)
                              ON DELETE CASCADE,
    state_revision_id NUMERIC NOT NULL
                          CONSTRAINT suse_server_state_rev_id_fk
                              REFERENCES suseStateRevision (id)
                              ON DELETE CASCADE
)

;

ALTER TABLE suseServerStateRevision
    ADD CONSTRAINT suse_server_state_rev_id_sid_uq UNIQUE (server_id, state_revision_id);
  07070100000B4F000081B400000000000000000000000167AE1114000007AA000000000000000000000000000000000000006900000000susemanager-schema/upgrade/susemanager-schema-2.1.51-to-susemanager-schema-3.0/9140-susePackageState.sql  --
-- Copyright (c) 2015 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

CREATE TABLE susePackageState
(
    id                    NUMERIC NOT NULL
                              CONSTRAINT suse_pkg_state_id_pk PRIMARY KEY,
    name_id               NUMERIC NOT NULL
                              CONSTRAINT suse_pkg_state_nid_fk
                                  REFERENCES rhnPackageName (id),
    evr_id                NUMERIC
                              CONSTRAINT suse_pkg_state_eid_fk
                                  REFERENCES rhnPackageEVR (id),
    package_arch_id       NUMERIC
                              CONSTRAINT suse_pkg_state_paid_fk
                                  REFERENCES rhnPackageArch (id),
    state_revision_id     NUMERIC NOT NULL
                              CONSTRAINT suse_pkg_state_srid_fk
                                  REFERENCES suseStateRevision (id),
    package_state_type_id NUMERIC NOT NULL
                              CONSTRAINT suse_pkg_state_pstid_fk
                                  REFERENCES susePackageStateType (id),
    version_constraint_id NUMERIC NOT NULL
                              CONSTRAINT suse_pkg_state_vcid_fk
                                  REFERENCES suseVersionConstraintType (id)
)

;

CREATE SEQUENCE suse_pkg_state_id_seq;

ALTER TABLE susePackageState
    ADD CONSTRAINT suse_pkg_state_nid_srid_uq UNIQUE (name_id, state_revision_id);
  07070100000B50000081B400000000000000000000000167AE111400000457000000000000000000000000000000000000006F00000000susemanager-schema/upgrade/susemanager-schema-2.1.51-to-susemanager-schema-3.0/9141-susePinnedSubscription.sql    --
-- Copyright (c) 2015 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

CREATE TABLE susePinnedSubscription
(
    id               NUMERIC NOT NULL
                       CONSTRAINT suse_pinsub_id_pk PRIMARY KEY
                       ,
    server_id        NUMERIC NOT NULL
                       CONSTRAINT suse_pinsub_sid_fk
                         REFERENCES rhnServer (id),
    orderitem_id     NUMERIC NOT NULL
)

;

CREATE UNIQUE INDEX suse_pinsub_sid_oid_uq
    ON susePinnedSubscription (server_id, orderitem_id)
    ;

CREATE SEQUENCE suse_pinsub_id_seq;
 07070100000B51000081B400000000000000000000000167AE1114000006B4000000000000000000000000000000000000006C00000000susemanager-schema/upgrade/susemanager-schema-2.1.51-to-susemanager-schema-3.0/9142-suseSCCSubscription.sql   --
-- Copyright (c) 2015 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

CREATE TABLE suseSCCSubscription
(
    id             NUMERIC NOT NULL
                     CONSTRAINT suse_sccsub_id_pk
                     PRIMARY KEY,
    scc_id         NUMERIC NOT NULL,
    credentials_id NUMERIC
                       CONSTRAINT suse_sccsub_credsid_fk
                       REFERENCES suseCredentials (id)
                       ON DELETE CASCADE,
    name           VARCHAR(256),
    starts_at      TIMESTAMPTZ,
    expires_at     TIMESTAMPTZ,
    status         VARCHAR(20),
    regcode        VARCHAR(256) NOT NULL,
    subtype        VARCHAR(20) NOT NULL,
    system_limit   NUMERIC DEFAULT(0) NOT NULL,
    created        TIMESTAMPTZ
                       DEFAULT (current_timestamp) NOT NULL,
    modified       TIMESTAMPTZ
                       DEFAULT (current_timestamp) NOT NULL
)

;

CREATE UNIQUE INDEX suse_sccsub_sccid_uq
    ON suseSCCSubscription (scc_id);

CREATE INDEX suse_sccsub_starts_at_idx
    ON suseSCCSubscription (starts_at);

CREATE INDEX suse_sccsub_expires_at_idx
    ON suseSCCSubscription (expires_at);

CREATE SEQUENCE suse_sccsub_id_seq;
07070100000B52000081B400000000000000000000000167AE111400000411000000000000000000000000000000000000007300000000susemanager-schema/upgrade/susemanager-schema-2.1.51-to-susemanager-schema-3.0/9143-suseSCCSubscriptionProduct.sql    --
-- Copyright (c) 2015 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

CREATE TABLE suseSCCSubscriptionProduct
(
    subscription_id  NUMERIC NOT NULL
                     CONSTRAINT suse_sccsubprod_subid_fk
                     REFERENCES suseSCCSubscription (id)
                     ON DELETE CASCADE,
    product_id       NUMERIC NOT NULL
                     CONSTRAINT suse_sccsubprod_prdid_fk
                     REFERENCES suseProducts (id)
                     ON DELETE CASCADE
)

;

   07070100000B53000081B400000000000000000000000167AE11140000060F000000000000000000000000000000000000006900000000susemanager-schema/upgrade/susemanager-schema-2.1.51-to-susemanager-schema-3.0/9144-suseSCCOrderItem.sql  --
-- Copyright (c) 2015 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

CREATE TABLE suseSCCOrderItem
(
    id             NUMERIC NOT NULL
                     CONSTRAINT suse_sccorder_id_pk
                     PRIMARY KEY,
    scc_id         NUMERIC NOT NULL,
    credentials_id NUMERIC
                       CONSTRAINT suse_sccorder_credsid_fk
                       REFERENCES suseCredentials (id)
                       ON DELETE CASCADE,
    sku            VARCHAR(256),
    start_date     TIMESTAMPTZ,
    end_date       TIMESTAMPTZ,
    quantity       NUMERIC DEFAULT(0),
    subscription_id NUMERIC NOT NULL,
    created        TIMESTAMPTZ
                       DEFAULT (current_timestamp) NOT NULL,
    modified       TIMESTAMPTZ
                       DEFAULT (current_timestamp) NOT NULL
)

;

CREATE UNIQUE INDEX suse_sccorder_sccid_uq
    ON suseSCCOrderItem (scc_id);

CREATE INDEX suse_sccorder_subid_idx
    ON suseSCCOrderItem (subscription_id);

CREATE SEQUENCE suse_sccorder_id_seq;
 07070100000B54000081B400000000000000000000000167AE11140000019E000000000000000000000000000000000000006E00000000susemanager-schema/upgrade/susemanager-schema-2.1.51-to-susemanager-schema-3.0/9145-rename-gatherer-bunch.sql -- Rename gatherer data in taskomatic bunch and schedule

-- gatherer-bunch becomes gatherer-matcher-bunch
UPDATE rhnTaskoBunch
SET name = 'gatherer-matcher-bunch',
    description = 'Schedule running gatherer and matcher'
WHERE name = 'gatherer-bunch';

-- gatherer-matcher-default matcher gatherer-default
UPDATE rhnTaskoSchedule
SET job_label = 'gatherer-matcher-default'
WHERE job_label = 'gatherer-default';

  07070100000B55000081B400000000000000000000000167AE1114000002CE000000000000000000000000000000000000007400000000susemanager-schema/upgrade/susemanager-schema-2.1.51-to-susemanager-schema-3.0/9146-add-matcher-taskomatic-task.sql   -- Add a new taskomatic task for running subscription matcher.
INSERT INTO rhnTaskoTask (id, name, class)
         VALUES (sequence_nextval('rhn_tasko_task_id_seq'), 'matcher', 'com.redhat.rhn.taskomatic.task.matcher.MatcherJob');

-- Add this task to the same bunch with the gatherer task. The matcher task will be run AFTER the gatherer one.
INSERT INTO rhnTaskoTemplate (id, bunch_id, task_id, ordering, start_if)
             VALUES (sequence_nextval('rhn_tasko_template_id_seq'),
                        (SELECT id FROM rhnTaskoBunch WHERE name='gatherer-matcher-bunch'),
                        (SELECT id FROM rhnTaskoTask WHERE name='matcher'),
                        1,
                        'FINISHED');

  07070100000B56000081B400000000000000000000000167AE1114000001D7000000000000000000000000000000000000008400000000susemanager-schema/upgrade/susemanager-schema-2.1.51-to-susemanager-schema-3.0/9147-move-suse-channels-to-public-channel-family.sql   INSERT INTO rhnPublicChannelFamily(channel_family_id)
  SELECT channel_family_id
    FROM rhnPrivateChannelFamily
    WHERE org_id = 1
      AND channel_family_id IN (
        SELECT id
          FROM rhnChannelFamily
          WHERE label NOT LIKE 'private-channel-family-%'
      );

DELETE FROM rhnPrivateChannelFamily
  WHERE org_id = 1
  AND channel_family_id IN (
    SELECT id
      FROM rhnChannelFamily
      WHERE label NOT LIKE 'private-channel-family-%'
  );
 07070100000B57000081B400000000000000000000000167AE1114000002F7000000000000000000000000000000000000006900000000susemanager-schema/upgrade/susemanager-schema-2.1.51-to-susemanager-schema-3.0/9148-rhnTimezone-data.sql  insert into rhnTimezone (id, olson_name, display_name) (
    select sequence_nextval('rhn_timezone_id_seq'),
           'America/Santiago',
           'Chile (Continental)'
      from dual
     where not exists (
           select 1
             from rhnTimezone
            where olson_name = 'America/Santiago'
              and display_name = 'Chile (Continental)'
     )
);

insert into rhnTimezone (id, olson_name, display_name) (
    select sequence_nextval('rhn_timezone_id_seq'),
           'Pacific/Easter',
           'Chile (Easter Island)'
      from dual
     where not exists (
           select 1
             from rhnTimezone
            where olson_name = 'Pacific/Easter'
              and display_name = 'Chile (Easter Island)'
     )
);


 07070100000B58000081B400000000000000000000000167AE111400000042000000000000000000000000000000000000007100000000susemanager-schema/upgrade/susemanager-schema-2.1.51-to-susemanager-schema-3.0/9149-add-free-flag-to-product.sql  ALTER TABLE suseProducts
ADD free CHAR(1) DEFAULT ('N') NOT NULL;
  07070100000B59000081B400000000000000000000000167AE111400000518000000000000000000000000000000000000006700000000susemanager-schema/upgrade/susemanager-schema-2.1.51-to-susemanager-schema-3.0/9150-suseMinionInfo.sql    --
-- Copyright (c) 2016 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

CREATE TABLE suseMinionInfo
(
    server_id          NUMERIC NOT NULL
                           CONSTRAINT suse_minion_info_sid_fk
                               REFERENCES rhnServer (id)
                               ON DELETE CASCADE,
    minion_id          VARCHAR(256) NOT NULL,
    machine_id         VARCHAR(256) NOT NULL
)

;

CREATE INDEX suse_minion_info_sid_idx
    ON suseMinionInfo (server_id)
    ;

ALTER TABLE suseMinionInfo
    ADD CONSTRAINT rhn_minion_info_sid_uq UNIQUE (server_id);

ALTER TABLE suseMinionInfo
    ADD CONSTRAINT rhn_minion_info_miid_uq UNIQUE (minion_id);

ALTER TABLE suseMinionInfo
    ADD CONSTRAINT rhn_minion_info_maid_uq UNIQUE (machine_id);
07070100000B5A000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000004F00000000susemanager-schema/upgrade/susemanager-schema-3.0-to-susemanager-schema-3.0.10    07070100000B5B000081B400000000000000000000000167AE111400000155000000000000000000000000000000000000006B00000000susemanager-schema/upgrade/susemanager-schema-3.0-to-susemanager-schema-3.0.10/0001-suseMatcherRunData.sql    CREATE TABLE suseMatcherRunData (
    id             NUMERIC NOT NULL
                   CONSTRAINT suse_matcher_run_data_pk PRIMARY KEY,
    inputBinary BYTEA,
    outputBinary BYTEA,
    subscriptionReportBinary BYTEA,
    messageReportBinary BYTEA,
    unmatchedSystemReportBinary BYTEA
);

CREATE SEQUENCE suse_matcher_run_data_id_seq;

   07070100000B5C000081B400000000000000000000000167AE11140000767E000000000000000000000000000000000000007000000000susemanager-schema/upgrade/susemanager-schema-3.0-to-susemanager-schema-3.0.10/0202-no-lock-rhn_channel.pkb.sql   --
-- Copyright (c) 2008--2015 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--
--
--
--

-- create schema rhn_channel;

--update pg_setting
update pg_settings set setting = 'rhn_channel,' || setting where name = 'search_path';

    -- this "emulates" cursor server_base_subscriptions defined in oracle/rhn_channel.pks
    create or replace function server_base_subscriptions(server_id_in NUMERIC)
    returns boolean as $$
    begin
      return exists(SELECT C.id FROM rhnChannel C, rhnServerChannel SC
		    WHERE C.id = SC.channel_id
		      AND SC.server_id = server_id_in
		      AND C.parent_channel IS NULL);
    end$$ language plpgsql;

    -- this "emulates" cursor server_base_subscriptions defined in oracle/rhn_channel.pks
    create or replace function check_server_subscription(server_id_in NUMERIC, channel_id_in NUMERIC)
    returns boolean as $$
    begin
      return exists(SELECT channel_id FROM rhnServerChannel WHERE server_id = server_id_in AND channel_id = channel_id_in);
    end$$ language plpgsql;


    CREATE OR REPLACE FUNCTION subscribe_server(server_id_in IN NUMERIC, channel_id_in NUMERIC, immediate_in NUMERIC default 1, user_id_in in numeric default null) returns void
    AS $$
    declare
        channel_parent_val      rhnChannel.parent_channel%TYPE;
        parent_subscribed       BOOLEAN;
        server_has_base_chan    BOOLEAN;
        server_already_in_chan  BOOLEAN;
        channel_family_id_val   NUMERIC;
        allowed                 numeric;
    BEGIN
        if user_id_in is not null then
            allowed := rhn_channel.user_role_check(channel_id_in, user_id_in, 'subscribe');
        else
            allowed := 1;
        end if;

        if allowed = 0 then
            perform rhn_exception.raise_exception('no_subscribe_permissions');
        end if;


        SELECT parent_channel INTO channel_parent_val FROM rhnChannel WHERE id = channel_id_in;

        IF channel_parent_val IS NOT NULL
        THEN
            -- child channel; if attempting to cross-subscribe a child to the wrong base, silently ignore
            parent_subscribed := rhn_channel.check_server_subscription(server_id_in, channel_parent_val);

            IF NOT parent_subscribed
            THEN
                RETURN;
            END IF;
        ELSE
            -- base channel
            server_has_base_chan := rhn_channel.server_base_subscriptions(server_id_in);

            IF server_has_base_chan
            THEN
                perform rhn_exception.raise_exception('channel_server_one_base');
            END IF;
        END IF;

        server_already_in_chan := rhn_channel.check_server_subscription(server_id_in, channel_id_in);

        IF server_already_in_chan
        THEN
            RETURN;
        END IF;

        channel_family_id_val := rhn_channel.family_for_channel(channel_id_in);
        IF channel_family_id_val IS NULL
        THEN
            perform rhn_exception.raise_exception('channel_subscribe_no_family');
        END IF;

        insert into rhnServerHistory (id,server_id,summary,details) (
            select  nextval('rhn_event_id_seq'),
                    server_id_in,
                    'subscribed to channel ' || SUBSTR(c.label, 0, 106),
                    c.label
            from    rhnChannel c
            where   c.id = channel_id_in
        );

        INSERT INTO rhnServerChannel (server_id, channel_id) VALUES (server_id_in, channel_id_in);

        perform queue_server(server_id_in, immediate_in);

        update rhnServer
           set channels_changed = current_timestamp
         where id = server_id_in;
    END$$ language plpgsql;

    create or replace function guess_server_base(
        server_id_in in numeric
    ) RETURNS numeric as $$
    declare
        server_cursor cursor for
            select s.server_arch_id, s.release, s.org_id
              from rhnServer s
             where s.id = server_id_in;
    -- Cursor that fetches all the possible base channels for a
    -- (server_arch_id, release, org_id) combination
        base_channel_cursor cursor(
                release_in varchar,
                server_arch_id_in numeric,
                org_id_in numeric
        ) for
                select distinct c.*
                from    rhnOrgDistChannelMap                       odcm,
                                rhnServerChannelArchCompat      scac,
                                rhnChannel                                      c
                where   c.parent_channel is null
                        and c.id = odcm.channel_id
                        and c.channel_arch_id = odcm.channel_arch_id
                        and odcm.release = release_in
                        and odcm.for_org_id = org_id_in
                        and scac.server_arch_id = server_arch_id_in
                        and scac.channel_arch_id = c.channel_arch_id;

    begin
        for s in server_cursor loop
            for channel in base_channel_cursor(s.release,
                s.server_arch_id, s.org_id)
            loop
                return channel.id;
            end loop;
        end loop;
        -- Server not found, or no base channel applies to it
        return null;
    end$$ language plpgsql;

    -- Private function
    create or replace function normalize_server_arch(server_arch_in in varchar)
    returns varchar
    as $$
    declare
        suffix VARCHAR(128) := '-redhat-linux';
    begin
        if server_arch_in is NULL then
            return NULL;
        end if;
        if position('-' IN server_arch_in) > 0
        then
            -- Suffix already present
            return server_arch_in;
        end if;
        return server_arch_in || suffix;
    end$$ language plpgsql;

    --
    -- Raises:
    --   server_arch_not_found
    --   no_subscribe_permissions
    create or replace function base_channel_for_release_arch(
        release_in in varchar,
        server_arch_in in varchar,
        org_id_in in numeric default -1,
        user_id_in in numeric default null
    ) returns numeric as $$
    declare
        server_arch varchar(256) := rhn_channel.normalize_server_arch(server_arch_in);
        server_arch_id numeric;
    begin
        -- Look up the server arch
            select id
              into server_arch_id
              from rhnServerArch
             where label = server_arch;
            if not found then
                perform rhn_exception.raise_exception('server_arch_not_found');
            end if;

        return rhn_channel.base_channel_rel_archid(release_in, server_arch_id,
            org_id_in, user_id_in);
    end$$ language plpgsql;

    create or replace function base_channel_rel_archid(
        release_in in varchar,
        server_arch_id_in in numeric,
        org_id_in in numeric default -1,
        user_id_in in numeric default null
    ) returns numeric as $$
    declare
        denied_channel_id numeric := null;
        valid_org_id numeric := org_id_in;
        valid_user_id numeric := user_id_in;
        channel_subscribable numeric;
    -- Cursor that fetches all the possible base channels for a
    -- (server_arch_id, release, org_id) combination
        base_channel_cursor cursor(
                release_in varchar,
                server_arch_id_in numeric,
                org_id_in numeric
        ) for
                select distinct c.*
                from    rhnOrgDistChannelMap                       odcm,
                                rhnServerChannelArchCompat      scac,
                                rhnChannel                                      c
                where   c.parent_channel is null
                        and c.id = odcm.channel_id
                        and c.channel_arch_id = odcm.channel_arch_id
                        and odcm.release = release_in
                        and odcm.for_org_id = org_id_in
                        and scac.server_arch_id = server_arch_id_in
                        and scac.channel_arch_id = c.channel_arch_id;

    begin
        if org_id_in = -1 and user_id_in is not null then
            -- Get the org id from the user id

                select org_id
                  into valid_org_id
                  from web_contact
                 where id = user_id_in;

                if not found then
                    -- User doesn't exist
                    -- XXX Only list public stuff for now
                    valid_user_id := null;
                    valid_org_id := -1;
                end if;
        end if;

        for c in base_channel_cursor(release_in, server_arch_id_in, valid_org_id)
        loop
            -- This row is a possible match
            if valid_user_id is null then
                -- User ID not specified, so no user to channel permissions to
                -- check
                return c.id;
            end if;

            -- Check user to channel permissions
            select rhn_channel.loose_user_role_check(c.id, user_id_in, 'subscribe')
              into channel_subscribable;

            if channel_subscribable = 1 then
                return c.id;
            end if;

            -- Base channel exists, but is not subscribable; keep trying
            denied_channel_id := c.id;
        end loop;

        if denied_channel_id is not null then
            perform rhn_exception.raise_exception('no_subscribe_permissions');
        end if;
        -- No base channel applies
        return NULL;
    end$$ language plpgsql;

    CREATE OR REPLACE FUNCTION clear_subscriptions(server_id_in IN NUMERIC, deleting_server IN NUMERIC default 0) returns void
    AS $$
    declare
        server_channels cursor(server_id_in numeric) for
                select  s.org_id, sc.channel_id, cfm.channel_family_id
                from    rhnServer s,
                        rhnServerChannel sc,
                        rhnChannelFamilyMembers cfm
                where   s.id = server_id_in
                        and s.id = sc.server_id
                        and sc.channel_id = cfm.channel_id
                order by cfm.channel_family_id;
        last_channel_family_id rhnChannelFamilyMembers.channel_family_id%type := -1;
        last_channel_org_id    rhnServer.org_id%type := -1;
    BEGIN
        for channel in server_channels(server_id_in)
        loop
                perform rhn_channel.unsubscribe_server(server_id_in, channel.channel_id, 1, 1, deleting_server);
        end loop;
    END$$ language plpgsql;

    CREATE OR REPLACE FUNCTION unsubscribe_server(server_id_in IN NUMERIC, channel_id_in NUMERIC, immediate_in NUMERIC default 1, unsubscribe_children_in numeric default 0,
                                 deleting_server in numeric default 0) returns void
    AS $$
    declare
        channel_family_id_val   NUMERIC;
        server_org_id_val       NUMERIC;
        server_already_in_chan  BOOLEAN;
        channel_family_is_proxy cursor(channel_family_id_in numeric) for
                select  1
                from    rhnChannelFamily
                where   id = channel_family_id_in
                    and label = 'rhn-proxy';
        channel_family_is_satellite cursor(channel_family_id_in numeric) for
                select  1
                from    rhnChannelFamily
                where   id = channel_family_id_in
                    and label = 'rhn-satellite';
        child record;
    BEGIN
        -- In PostgreSQL recursion with opened cursors is not allowed so we use
        -- FOR IN SELECT form which is ok.
        FOR child IN select  c.id
                from    rhnChannel                      c,
                                rhnServerChannel        sc
                where   1=1
                        and c.parent_channel = channel_id_in
                        and c.id = sc.channel_id
                        and sc.server_id = server_id_in
        LOOP
            if unsubscribe_children_in = 1 then
                perform rhn_channel.unsubscribe_server(server_id_in,
                                                       child.id,
                                                       immediate_in,
                                                       unsubscribe_children_in,
                                                       deleting_server);
            else
                perform rhn_exception.raise_exception('channel_unsubscribe_child_exists');
            end if;
        END LOOP;

        server_already_in_chan := rhn_channel.check_server_subscription(server_id_in, channel_id_in);

        IF NOT server_already_in_chan
        THEN
            RETURN;
        END IF;

   if deleting_server = 0 then
      insert into rhnServerHistory (id,server_id,summary,details) (
          select  nextval('rhn_event_id_seq'),
                server_id_in,
             'unsubscribed from channel ' || SUBSTR(c.label, 0, 106),
             c.label
          from    rhnChannel c
          where   c.id = channel_id_in
      );
   end if;

   DELETE FROM rhnServerChannel WHERE server_id = server_id_in AND channel_id = channel_id_in;

   if deleting_server = 0 then
        perform queue_server(server_id_in, immediate_in);

        update rhnServer
           set channels_changed = current_timestamp
         where id = server_id_in;
   end if;

        channel_family_id_val := rhn_channel.family_for_channel(channel_id_in);
        IF channel_family_id_val IS NULL
        THEN
            perform rhn_exception.raise_exception('channel_unsubscribe_no_family');
        END IF;

        for ignore in channel_family_is_satellite(channel_family_id_val) loop
                delete from rhnSatelliteInfo where server_id = server_id_in;
        end loop;

        for ignore in channel_family_is_proxy(channel_family_id_val) loop
                delete from rhnProxyInfo where server_id = server_id_in;
        end loop;
        SELECT org_id INTO server_org_id_val
          FROM rhnServer
         WHERE id = server_id_in;

    END$$ language plpgsql;

    CREATE OR REPLACE FUNCTION family_for_channel(channel_id_in IN NUMERIC)
    RETURNS NUMERIC
    AS $$
    declare
        channel_family_id_val NUMERIC;
    BEGIN
        SELECT channel_family_id INTO channel_family_id_val
          FROM rhnChannelFamilyMembers
         WHERE channel_id = channel_id_in;

        IF NOT FOUND THEN
          RETURN NULL;
        END IF;

        RETURN channel_family_id_val;
    END$$ language plpgsql;

    create or replace function unsubscribe_server_from_family(server_id_in in numeric,
                                             channel_family_id_in in numeric)
    returns void
    as $$
    begin
        delete
        from    rhnServerChannel rsc
        where   rsc.server_id = server_id_in
            and channel_id in (
                select  rcfm.channel_id
                from    rhnChannelFamilyMembers rcfm
                where   rcfm.channel_family_id = channel_family_id_in);
    end$$ language plpgsql;

    create or replace function get_org_id(channel_id_in in numeric)
    returns numeric
    as $$
    declare
        org_id_out numeric;
    begin
        select org_id into strict org_id_out
            from rhnChannel
            where id = channel_id_in;

            return org_id_out;
    end$$ language plpgsql;

    create or replace function get_cfam_org_access(cfam_id_in in numeric, org_id_in in numeric)
    returns numeric
    as $$
    begin
      if exists(
                        select  1
                        from    rhnOrgChannelFamilyPermissions cfp
                        where   cfp.org_id = org_id_in
      ) then
                return 1;
      else
                return 0;
      end if;
    end$$ language plpgsql;

    create or replace function get_org_access(channel_id_in in numeric, org_id_in in numeric)
    returns integer
    as $$
    begin
        -- the idea: if we get past this query,
        -- the org has access to the channel, else not
        if exists(
        select 1
          from rhnChannelFamilyMembers CFM,
               rhnOrgChannelFamilyPermissions CFP
         where cfp.org_id = org_id_in
           and CFM.channel_family_id = CFP.channel_family_id
           and CFM.channel_id = channel_id_in)
        then
          return 1;
        else
          return 0;
        end if;
    end$$ language plpgsql;

    -- check if a user has a given role, or if such a role is inferrable
    -- returns NULL if OK, error message otherwise
    create or replace function user_role_check_debug(channel_id_in in numeric,
                                   user_id_in in numeric,
                                   role_in in varchar)
    returns varchar
    as $$
    declare
        org_id numeric;
    begin
        org_id := rhn_user.get_org_id(user_id_in);

        -- channel might be shared
        if role_in = 'subscribe' and
           rhn_channel.shared_user_role_check(channel_id_in, user_id_in, role_in) = 1 then
            return NULL;
        end if;

        if role_in = 'manage' and
           COALESCE(rhn_channel.get_org_id(channel_id_in), -1) <> org_id then
               return 'channel_not_owned';
        end if;

        if role_in = 'subscribe' and
           rhn_channel.get_org_access(channel_id_in, org_id) = 0 then
                return 'channel_not_available';
        end if;

        -- channel admins have all roles
        if rhn_user.check_role_implied(user_id_in, 'channel_admin') = 1 then
            return NULL;
        end if;

        -- the subscribe permission is inferred
        -- UNLESS the not_globally_subscribable flag is set
        if role_in = 'subscribe'
        then
            if rhn_channel.org_channel_setting(channel_id_in,
                       org_id,
                       'not_globally_subscribable') = 0 then
                return NULL;
            end if;
        end if;

        -- all other roles (manage right now) are explicitly granted
        if rhn_channel.direct_user_role_check(channel_id_in,
                                              user_id_in, role_in) = 1 then
            return NULL;
        end if;
        return 'direct_permission';
    end$$ language plpgsql;

    -- same as above, but with 1/0 output; useful in views, etc
    create or replace function user_role_check(channel_id_in in numeric, user_id_in in numeric, role_in in varchar)
    returns numeric
    as $$
    begin
        if rhn_channel.user_role_check_debug(channel_id_in,
                                             user_id_in, role_in) is NULL then
            return 1;
        else
            return 0;
        end if;
    end$$ language plpgsql;

    --
    -- For multiorg phase II, this function simply checks to see if the user's
    -- has a trust relationship that includes this channel by id.
    --
    create or replace function shared_user_role_check(channel_id in numeric, user_id in numeric, role in varchar)
    returns numeric
    as $$
    declare
      n numeric;
      oid numeric;
    begin
      oid := rhn_user.get_org_id(user_id);
      select 1 into n
      from rhnSharedChannelView s
      where s.id = channel_id and s.org_trust_id = oid;

      if not found then
        return 0;
      end if;

      return 1;
    end$$ language plpgsql;

    -- same as above, but returns 1 if user_id_in is null
    -- This is useful in queries where user_id is not specified
    create or replace function loose_user_role_check(channel_id_in in numeric, user_id_in in numeric, role_in in varchar)
    returns numeric
    as $$
    begin
        if user_id_in is null then
            return 1;
        end if;
        return rhn_channel.user_role_check(channel_id_in, user_id_in, role_in);
    end$$ language plpgsql;

    -- directly checks the table, no inferred permissions
    create or replace function direct_user_role_check(channel_id_in in numeric, user_id_in in numeric, role_in in varchar)
    returns numeric
    as $$
    declare
        throwaway numeric;
    begin
        -- the idea: if we get past this query, the user has the role, else no
        select 1 into throwaway
          from rhnChannelPermissionRole CPR,
               rhnChannelPermission CP
         where CP.user_id = user_id_in
           and CP.channel_id = channel_id_in
           and CPR.label = role_in
           and CP.role_id = CPR.id;

      if not found then
        return 0;
      end if;

      return 1;
    end$$ language plpgsql;

    -- check if an org has a certain setting
    create or replace function org_channel_setting(channel_id_in in numeric, org_id_in in numeric, setting_in in varchar)
    returns numeric
    as $$
    declare
        throwaway numeric;
    begin
        -- the idea: if we get past this query, the org has the setting
        select 1 into throwaway
          from rhnOrgChannelSettingsType OCST,
               rhnOrgChannelSettings OCS
         where OCS.org_id = org_id_in
           and OCS.channel_id = channel_id_in
           and OCST.label = setting_in
           and OCS.setting_id = OCST.id;

      if not found then
        return 0;
      end if;

      return 1;
    end$$ language plpgsql;

    CREATE OR REPLACE FUNCTION channel_priority(channel_id_in IN numeric)
    RETURNS numeric
    AS $$
    declare
         channel_name varchar(256);
         priority numeric;
         end_of_life_val timestamptz;
         org_id_val numeric;
    BEGIN

        select name, end_of_life, org_id
        into channel_name, end_of_life_val, org_id_val
        from rhnChannel
        where id = channel_id_in;

        if end_of_life_val is not null then
          return -400;
        end if;

        if channel_name like 'Red Hat Enterprise Linux%' or channel_name like 'RHEL%' then
          priority := 1000;
          if channel_name not like '%Beta%' then
            priority := priority + 1000;
          end if;

          priority := priority +
            case
              when channel_name like '%v. 5%' then 600
              when channel_name like '%v. 4%' then 500
              when channel_name like '%v. 3%' then 400
              when channel_name like '%v. 2%' then 300
              when channel_name like '%v. 1%' then 200
              else 0
            end;

          priority := priority +
            case
              when channel_name like 'Red Hat Enterprise Linux (v. 5%' then 60
              when (channel_name like '%AS%' and channel_name not like '%Extras%') then 50
              when (channel_name like '%ES%' and channel_name not like '%Extras%') then 40
              when (channel_name like '%WS%' and channel_name not like '%Extras%') then 30
              when (channel_name like '%Desktop%' and channel_name not like '%Extras%') then 20
              when channel_name like '%Extras%' then 10
              else 0
            end;

          priority := priority +
            case
              when channel_name like '%)' then 5
              else 0
            end;

          priority := priority +
            case
              when channel_name like '%32-bit x86%' then 4
              when channel_name like '%64-bit Intel Itanium%' then 3
              when channel_name like '%64-bit AMD64/Intel EM64T%' then 2
              else 0
            end;
        elsif channel_name like 'Red Hat Desktop%' then
            priority := 900;

            if channel_name not like '%Beta%' then
               priority := priority + 50;
            end if;

          priority := priority +
            case
              when channel_name like '%v. 4%' then 40
              when channel_name like '%v. 3%' then 30
              when channel_name like '%v. 2%' then 20
              when channel_name like '%v. 1%' then 10
              else 0
            end;

          priority := priority +
            case
              when channel_name like '%32-bit x86%' then 4
              when channel_name like '%64-bit Intel Itanium%' then 3
              when channel_name like '%64-bit AMD64/Intel EM64T%' then 2
              else 0
            end;

        elsif org_id_val is not null then
          priority := 600;
        else
          priority := 500;
        end if;

      return -priority;

    end$$ language plpgsql;

    -- this could certainly be optimized to do updates if needs be
    create or replace function refresh_newest_package(channel_id_in in numeric,
                                      caller_in in varchar default '(unknown)',
                                      package_name_id_in in numeric default null)
    returns void
    as $$
    -- procedure refreshes rows for name_id = package_name_id_in or
    -- all rows if package_name_id_in is null
    begin
        delete from rhnChannelNewestPackage
              where channel_id = channel_id_in
                and (package_name_id_in is null
                     or name_id = package_name_id_in);
        insert into rhnChannelNewestPackage
                (channel_id, name_id, evr_id, package_id, package_arch_id)
                (select channel_id,
                        name_id, evr_id,
                        package_id, package_arch_id
                   from rhnChannelNewestPackageView
                  where channel_id = channel_id_in
                    and (package_name_id_in is null
                         or name_id = package_name_id_in)
                );
        insert into rhnChannelNewestPackageAudit (channel_id, caller)
             values (channel_id_in, caller_in);
        update rhnChannel
           set last_modified = greatest(current_timestamp,
                                        last_modified + interval '1 second')
         where id = channel_id_in;
    end$$ language plpgsql;

   create or replace function update_channel ( channel_id_in in numeric, invalidate_ss in numeric default 0,
                              date_to_use in timestamptz default current_timestamp ) returns void
   as $$
   declare
   channel_last_modified timestamptz;
   last_modified_value timestamptz;

   snapshots cursor for
   select  snapshot_id id
   from    rhnSnapshotChannel
   where   channel_id = channel_id_in;

   begin

      select last_modified
      into channel_last_modified
      from rhnChannel
      where id = channel_id_in;

      last_modified_value := date_to_use;

      if last_modified_value <= channel_last_modified then
          last_modified_value := last_modified_value + interval '1 second';
      end if;

      update rhnChannel set last_modified = last_modified_value
      where id = channel_id_in;

      if invalidate_ss = 1 then
        for snapshot in snapshots loop
            update rhnSnapshot
            set invalid = lookup_snapshot_invalid_reason('channel_modified')
            where id = snapshot.id;
        end loop;
      end if;

   end$$ language plpgsql;

   create or replace function update_channels_by_package ( package_id_in in numeric, date_to_use in timestamptz default current_timestamp ) returns void
   as $$
   declare
   channels cursor for
   select channel_id
   from rhnChannelPackage
   where package_id = package_id_in
   order by channel_id;

   begin
      for channel in channels loop
         -- we want to invalidate the snapshot assocated with the channel when we
         -- do this b/c we know we've added or removed or packages
         perform rhn_channel.update_channel ( channel.channel_id, 1, date_to_use );
      end loop;
   end$$ language plpgsql;


   create or replace function update_channels_by_errata ( errata_id_in numeric, date_to_use in timestamptz default current_timestamp ) returns void
   as $$
   declare
   channels cursor for
   select channel_id
   from rhnChannelErrata
   where errata_id = errata_id_in
   order by channel_id;

   begin
      for channel in channels loop
         -- we won't invalidate snapshots, b/c just changing the errata associated with
         -- a channel shouldn't invalidate snapshots
         perform rhn_channel.update_channel ( channel.channel_id, 0, date_to_use );
      end loop;
   end$$ language plpgsql;

   create or replace function update_needed_cache(channel_id_in in numeric) returns void
   as $$
   declare
   server record;
   begin
      -- we intentionaly do a loop here instead of one huge select
      -- b/c we want to break update into smaller transaction to unblock other sessions
      -- querying rhnServerNeededCache
      for server in (
                select sc.server_id as id
                  from rhnServerChannel sc
                 where sc.channel_id = channel_id_in
                 order by id asc
      ) loop
         perform queue_server(server.id, 0); -- NOT IMMEDIATE
      end loop;
   end$$ language plpgsql;

    create or replace function set_comps(channel_id_in in numeric, path_in in varchar, timestamp_in in varchar) returns void
    as $$
    declare
    row record;
    begin
        for row in (
            select relative_filename, last_modified
            from rhnChannelComps
            where channel_id = channel_id_in
            ) loop
            if row.relative_filename = path_in
                and row.last_modified = to_timestamp(timestamp_in, 'YYYYMMDDHH24MISS') then
                return;
            end if;
        end loop;
        delete from rhnChannelComps
        where channel_id = channel_id_in;
        insert into rhnChannelComps (id, channel_id, relative_filename, last_modified, created, modified)
        values (sequence_nextval('rhn_channelcomps_id_seq'), channel_id_in, path_in, to_timestamp(timestamp_in, 'YYYYMMDDHH24MISS'), current_timestamp, current_timestamp);
    end$$ language plpgsql;

-- restore the original setting
update pg_settings set setting = overlay( setting placing '' from 1 for (length('rhn_channel')+1) ) where name = 'search_path';
  07070100000B5D000081B400000000000000000000000167AE1114000002F5000000000000000000000000000000000000006900000000susemanager-schema/upgrade/susemanager-schema-3.0-to-susemanager-schema-3.0.10/0202-rhnTimezone-data.sql  insert into rhnTimezone (id, olson_name, display_name) (
    select sequence_nextval('rhn_timezone_id_seq'),
           'America/Santiago',
           'Chile (Continental)'
      from dual
     where not exists (
           select 1
             from rhnTimezone
            where olson_name = 'America/Santiago'
              and display_name = 'Chile (Continental)'
     )
);

insert into rhnTimezone (id, olson_name, display_name) (
    select sequence_nextval('rhn_timezone_id_seq'),
           'Pacific/Easter',
           'Chile (Easter Island)'
      from dual
     where not exists (
           select 1
             from rhnTimezone
            where olson_name = 'Pacific/Easter'
              and display_name = 'Chile (Easter Island)'
     )
);
   07070100000B5E000081B400000000000000000000000167AE11140000263E000000000000000000000000000000000000006600000000susemanager-schema/upgrade/susemanager-schema-3.0-to-susemanager-schema-3.0.10/0205-delete_server.sql --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
-- This deletes a server.  All codepaths which delete servers should hit this
-- or delete_server_bulk()

create or replace
function delete_server (
        server_id_in in numeric
) returns void 
as
$$
declare
         servergroups cursor for
                select  server_id, server_group_id
                from    rhnServerGroupMembers sgm
                where   sgm.server_id = server_id_in;

         configchannels cursor for
                select  cc.id
                from    rhnConfigChannel cc,
                        rhnConfigChannelType cct,
                        rhnServerConfigChannel scc
                where   1=1
                        and scc.server_id = server_id_in
                        and scc.config_channel_id = cc.id
                        -- these config channel types are reserved
                        -- for use by a single server, so we don't
                        -- need to check for other servers subscribed
                        and cct.label in
                                ('local_override','server_import')
                        and cct.id = cc.confchan_type_id;

begin
        -- filelists
        delete from rhnFileList where id in (
	select	spfl.file_list_id
	  from	rhnServerPreserveFileList spfl
	 where	spfl.server_id = server_id_in
			and not exists (
				select	1
				from	rhnServerPreserveFileList
				where	file_list_id = spfl.file_list_id
					and server_id != server_id_in
				union all
				select	1
				from	rhnKickstartPreserveFileList
				where	file_list_id = spfl.file_list_id
			)
        );

	for configchannel in configchannels loop
		perform rhn_config.delete_channel(configchannel.id);
	end loop;

	for sgm in servergroups loop
		perform rhn_server.delete_from_servergroup(
			sgm.server_id, sgm.server_group_id);
	end loop;


        -- we're handling this instead of letting an "on delete
        -- set null" do it so that we don't run the risk
        -- of setting off the triggers and killing us with a
        -- mutating table

        -- this is merge of two single updates:
        --  update ... set old_server_id = null where old_server_id = server_id_in;
        --  update ... set new_server_id = null where new_server_id = server_id_in;
        -- so we scan rhnKickstartSession table only once
        update rhnKickstartSession
                set old_server_id = case when old_server_id = server_id_in then null else old_server_id end,
                    new_server_id = case when new_server_id = server_id_in then null else new_server_id end
                where old_server_id = server_id_in
                   or new_server_id = server_id_in;

        perform rhn_channel.clear_subscriptions(server_id_in, 1);

        -- A little complicated here, but the goal is to
        -- delete records from rhnVirtualInstace only if we don't
        -- care about them anymore.  We don't care about records
        -- in rhnVirtualInstance if we are deleting the host
        -- system and the virtual system is already null, or
        -- vice-versa.  We *do* care about them if either the
        -- host or virtual system is still registered because we
        -- still want them to show up in the UI.
    -- If there's a newer row in rhnVirtualInstance with the same
    -- uuid, this guest must have been re-registered, so we can clean
    -- this data up.

        delete from rhnVirtualInstance vi
              where (host_system_id = server_id_in and virtual_system_id is null)
                 or (virtual_system_id = server_id_in and host_system_id is null)
                 or (vi.virtual_system_id = server_id_in and vi.modified < (select max(vi2.modified)
                    from rhnVirtualInstance vi2 where vi2.uuid = vi.uuid));

        -- this is merge of two single updates:
        --  update ... set host_system_id = null where host_system_id = server_id_in;
        --  update ... set virtual_system_id = null where virtual_system_id = server_id_in;
        -- so we scan rhnVirtualInstance table only once
        update rhnVirtualInstance
           set host_system_id = case when host_system_id = server_id_in then null else host_system_id end,
               virtual_system_id = case when virtual_system_id = server_id_in then null else virtual_system_id end
         where host_system_id = server_id_in
            or virtual_system_id = server_id_in;

        -- this is merge of two single updates:
        --  update ... set old_host_system_id = null when old_host_system_id = server_id_in;
        --  update ... set new_host_system_id = null when new_host_system_id = server_id_in;
        -- so we scan rhnVirtualInstanceEventLog table only once
        update rhnVirtualInstanceEventLog
           set old_host_system_id = case when old_host_system_id = server_id_in then null else old_host_system_id end,
               new_host_system_id = case when new_host_system_id = server_id_in then null else new_host_system_id end
         where old_host_system_id = server_id_in
            or new_host_system_id = server_id_in;

        -- We're deleting everything with a foreign key to rhnServer
        -- here, now.  I'm hoping this will help aleviate our deadlock
        -- problem.

        delete from rhnActionApplyStatesResult where server_id = server_id_in;
        delete from rhnActionConfigChannel where server_id = server_id_in;
        delete from rhnActionConfigRevision where server_id = server_id_in;
        delete from rhnActionPackageRemovalFailure where server_id = server_id_in;
        delete from rhnClientCapability where server_id = server_id_in;
        delete from rhnCpu where server_id = server_id_in;
        -- there's still a cascade here, because the constraint keeps the
        -- table locked for too long to rebuild it.  Ugh...
        delete from rhnDevice where server_id = server_id_in;
        delete from rhnProxyInfo where server_id = server_id_in;
        delete from rhnRam where server_id = server_id_in;
        delete from rhnRegToken where server_id = server_id_in;
        delete from rhnSatelliteInfo where server_id = server_id_in;
        -- this cascades to rhnActionConfigChannel and rhnActionConfigFileName
        delete from rhnServerAction where server_id = server_id_in;
        delete from rhnServerActionPackageResult where server_id = server_id_in;
        delete from rhnServerActionScriptResult where server_id = server_id_in;
        delete from rhnServerActionVerifyResult where server_id = server_id_in;
        delete from rhnServerActionVerifyMissing where server_id = server_id_in;
        -- counts are handled above.  this should be a delete_ function.
        delete from rhnServerChannel where server_id = server_id_in;
        delete from rhnServerConfigChannel where server_id = server_id_in;
        delete from rhnServerCustomDataValue where server_id = server_id_in;
        delete from rhnServerDMI where server_id = server_id_in;
        delete from rhnServerEvent where server_id = server_id_in;
        delete from rhnServerHistory where server_id = server_id_in;
        delete from rhnServerInfo where server_id = server_id_in;
        delete from rhnServerInstallInfo where server_id = server_id_in;
        delete from rhnServerLocation where server_id = server_id_in;
        delete from rhnServerLock where server_id = server_id_in;
        delete from rhnServerNeededCache where server_id = server_id_in;
        delete from rhnServerNetwork where server_id = server_id_in;
        delete from rhnServerNotes where server_id = server_id_in;
        -- I'm not removing the foreign key from rhnServerPackage; that'll
        -- take forever.  Do the delete anyway.
        delete from rhnServerPackage where server_id = server_id_in;
        delete from rhnServerTokenRegs where server_id = server_id_in;
        delete from rhnSnapshotTag where server_id = server_id_in;
        -- this cascades to:
        --   rhnSnapshotChannel, rhnSnapshotConfigChannel, rhnSnapshotPackage,
        --   rhnSnapshotConfigRevision, rhnSnapshotServerGroup,
        --   rhnSnapshotTag.
        -- We may want to consider delete_snapshot() at some point, but
        --   I don't think we need to yet.
        delete from rhnSnapshot where server_id = server_id_in;
        delete from rhnUserServerPrefs where server_id = server_id_in;
        -- hrm, this one's interesting... we _probably_ should delete
        -- everything for the parent server_id when we delete the proxy,
        -- but we don't currently.
        delete from rhnServerPath where server_id_in in (server_id, proxy_server_id);
        delete from rhnUserServerPerms where server_id = server_id_in;

        delete from rhnServerNetInterface where server_id = server_id_in;

        delete from rhnServerUuid where server_id = server_id_in;

        delete from rhnPushClient where server_id = server_id_in;

        -- now get rhnServer itself.
        delete
        from    rhnServer
                where id = server_id_in;

        delete
        from    rhnSet
        where   label = 'system_list'
                and element = server_id_in;
end;
$$
language plpgsql;

  07070100000B5F000081B400000000000000000000000167AE111400000106000000000000000000000000000000000000007400000000susemanager-schema/upgrade/susemanager-schema-3.0-to-susemanager-schema-3.0.10/0206-system-grouping-salt-insert.sql   insert into rhnServerGroupTypeFeature (server_group_type_id, feature_id,
                                       created, modified)
values (lookup_sg_type('salt_entitled'), lookup_feature_type('ftr_system_grouping'),
        current_timestamp,current_timestamp);
  07070100000B60000081B400000000000000000000000167AE111400000203000000000000000000000000000000000000008000000000susemanager-schema/upgrade/susemanager-schema-3.0-to-susemanager-schema-3.0.10/0207-enable-reboot-and-remote-cmd-on-minions.sql   insert into rhnServerGroupTypeFeature (server_group_type_id, feature_id,
                                       created, modified)
values (lookup_sg_type('salt_entitled'), lookup_feature_type('ftr_reboot'),
        current_timestamp,current_timestamp);

insert into rhnServerGroupTypeFeature (server_group_type_id, feature_id,
                                       created, modified)
values (lookup_sg_type('salt_entitled'), lookup_feature_type('ftr_remote_command'),
        current_timestamp,current_timestamp);
 07070100000B61000081B400000000000000000000000167AE111400000053000000000000000000000000000000000000008700000000susemanager-schema/upgrade/susemanager-schema-3.0-to-susemanager-schema-3.0.10/0210-rename-orderitem-to-subscription-in-pinnedsubs.sql    ALTER TABLE susePinnedSubscription RENAME COLUMN orderitem_id to subscription_id;

 07070100000B62000081B400000000000000000000000167AE1114000000C0000000000000000000000000000000000000007800000000susemanager-schema/upgrade/susemanager-schema-3.0-to-susemanager-schema-3.0.10/0211-pinned-subscription-adjustments.sql   -- rename the column
ALTER TABLE susePinnedSubscription RENAME COLUMN server_id to system_id;

-- drop the fk constraint
ALTER TABLE susePinnedSubscription DROP CONSTRAINT suse_pinsub_sid_fk;
07070100000B63000081B400000000000000000000000167AE11140000006B000000000000000000000000000000000000007100000000susemanager-schema/upgrade/susemanager-schema-3.0-to-susemanager-schema-3.0.10/0220-rename-unmatched-systems.sql  ALTER TABLE suseMatcherRunData
RENAME COLUMN unmatchedSystemReportBinary TO unmatchedProductReportBinary;

 07070100000B64000081B400000000000000000000000167AE111400000052000000000000000000000000000000000000007800000000susemanager-schema/upgrade/susemanager-schema-3.0-to-susemanager-schema-3.0.10/0230-insert-action-type-states-apply.sql   insert into rhnActionType values (503, 'states.apply', 'Apply states', 'N', 'N');
  07070100000B65000081B400000000000000000000000167AE111400000543000000000000000000000000000000000000007A00000000susemanager-schema/upgrade/susemanager-schema-3.0-to-susemanager-schema-3.0.10/0231-create-table-rhnActionApplyStates.sql --
-- Copyright (c) 2016 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

CREATE TABLE rhnActionApplyStates
(
    id               NUMERIC NOT NULL
                         CONSTRAINT rhn_act_apply_states_id_pk PRIMARY KEY,
    action_id        NUMERIC NOT NULL
                         CONSTRAINT rhn_act_apply_states_act_fk
                             REFERENCES rhnAction (id)
                             ON DELETE CASCADE,
    states           VARCHAR(1024),
    created          TIMESTAMPTZ
                         DEFAULT (current_timestamp) NOT NULL,
    modified         TIMESTAMPTZ
                         DEFAULT (current_timestamp) NOT NULL
)

;

CREATE UNIQUE INDEX rhn_act_apply_states_aid_idx
    ON rhnActionApplyStates (action_id)
    ;

CREATE SEQUENCE rhn_act_apply_states_id_seq;

 07070100000B66000081B400000000000000000000000167AE111400000635000000000000000000000000000000000000008000000000susemanager-schema/upgrade/susemanager-schema-3.0-to-susemanager-schema-3.0.10/0232-create-table-rhnActionApplyStatesResult.sql   --
-- Copyright (c) 2016 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--
-- CONSTRAINT names are different in the oracle version
-- pg names will be aligned again with 3.0.13/010-shorten-constraints-names

CREATE TABLE rhnActionApplyStatesResult
(
    server_id              NUMERIC NOT NULL
                               CONSTRAINT rhn_apply_states_result_sid_fk
                                   REFERENCES rhnServer (id)
                                   ON DELETE CASCADE,
    action_apply_states_id NUMERIC NOT NULL
                               CONSTRAINT rhn_apply_states_result_aasid_fk
                                   REFERENCES rhnActionApplyStates (id)
                                   ON DELETE CASCADE,
    output                 BYTEA,
    return_code            NUMERIC NOT NULL
)

;

CREATE UNIQUE INDEX rhn_apply_states_result_saas_uq
    ON rhnActionApplyStatesResult (server_id, action_apply_states_id);

CREATE INDEX rhn_apply_states_result_aasid_idx
    ON rhnActionApplyStatesResult (action_apply_states_id)
    ;

   07070100000B67000081B400000000000000000000000167AE111400000149000000000000000000000000000000000000007500000000susemanager-schema/upgrade/susemanager-schema-3.0-to-susemanager-schema-3.0.10/0233-trigger-rhnActionApplyStates.sql  
create or replace function rhn_act_apply_states_mod_trig_fun() returns trigger as
$$
begin
	new.modified := current_timestamp;
	return new;
end;
$$ language plpgsql;

create trigger
rhn_act_apply_states_mod_trig
before insert or update on rhnActionApplyStates
for each row
execute procedure rhn_act_apply_states_mod_trig_fun();
   07070100000B68000081B400000000000000000000000167AE11140000054F000000000000000000000000000000000000007500000000susemanager-schema/upgrade/susemanager-schema-3.0-to-susemanager-schema-3.0.10/0240-create-table-suseCustomState.sql  --
-- Copyright (c) 2016 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

CREATE TABLE suseCustomState
(
    id               NUMERIC NOT NULL
                         CONSTRAINT suse_custom_state_id_pk PRIMARY KEY,
    org_id           NUMERIC NOT NULL
                         CONSTRAINT suse_custom_state_org_id_fk
                            REFERENCES web_customer (id)
                            ON DELETE CASCADE,
    state_name       VARCHAR(256) NOT NULL,
    state_deleted    char(1)
                           default ('N') not null
                           constraint suse_custom_state_deleted_chk
                           check (state_deleted in ('Y', 'N'))
)

;
CREATE UNIQUE INDEX suse_custom_state_name_org_uq
ON suseCustomState (org_id, state_name)
;

CREATE SEQUENCE suse_custom_state_id_seq;
 07070100000B69000081B400000000000000000000000167AE11140000053F000000000000000000000000000000000000008200000000susemanager-schema/upgrade/susemanager-schema-3.0-to-susemanager-schema-3.0.10/0241-create-table-suseStateRevisionCustomState.sql --
-- Copyright (c) 2016 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--
-- CONSTRAINT names are different in the oracle version
-- pg names will be aligned again with 3.0.13/010-shorten-constraints-names

CREATE TABLE suseStateRevisionCustomState
(
    state_revision_id NUMERIC NOT NULL
                          CONSTRAINT suse_server_state_rev_id_fk
                              REFERENCES suseStateRevision (id)
                              ON DELETE CASCADE,
    state_id NUMERIC NOT NULL
                          CONSTRAINT suse_salt_state_id_fk
                              REFERENCES suseCustomState (id)
                              ON DELETE CASCADE
)

;

ALTER TABLE suseStateRevisionCustomState
    ADD CONSTRAINT suse_state_rev_id_state_id_uq UNIQUE (state_revision_id, state_id);
 07070100000B6A000081B400000000000000000000000167AE111400000117000000000000000000000000000000000000007500000000susemanager-schema/upgrade/susemanager-schema-3.0-to-susemanager-schema-3.0.10/0250-fix-SLES-KSInstallType-names.sql  update rhnKSInstallType set name = 'SUSE Linux Enterprise 10' where label = 'sles10generic';
update rhnKSInstallType set name = 'SUSE Linux Enterprise 11' where label = 'sles11generic';
update rhnKSInstallType set name = 'SUSE Linux Enterprise 12' where label = 'sles12generic';
 07070100000B6B000081B400000000000000000000000167AE111400000068000000000000000000000000000000000000007400000000susemanager-schema/upgrade/susemanager-schema-3.0-to-susemanager-schema-3.0.10/0251-make-entitlements-permanent.sql   UPDATE rhnServerGroupType SET permanent = 'Y' WHERE label IN ('enterprise_entitled', 'salt_entitled');

07070100000B6C000081B400000000000000000000000167AE11140000054F000000000000000000000000000000000000008200000000susemanager-schema/upgrade/susemanager-schema-3.0-to-susemanager-schema-3.0.10/0252-create-table-suseServerGroupStateRevision.sql --
-- Copyright (c) 2016 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--
-- CONSTRAINT names are different in the oracle version
-- pg names will be aligned again with 3.0.13/010-shorten-constraints-names

CREATE TABLE suseServerGroupStateRevision
(
    group_id         NUMERIC NOT NULL
                          CONSTRAINT suse_server_group_rev_sid_fk
                              REFERENCES rhnServerGroup (id)
                              ON DELETE CASCADE,
    state_revision_id NUMERIC NOT NULL
                          CONSTRAINT suse_server_group_rev_id_fk
                              REFERENCES suseStateRevision (id)
                              ON DELETE CASCADE
)

;

ALTER TABLE suseServerGroupStateRevision
    ADD CONSTRAINT suse_server_group_rev_id_sid_uq UNIQUE (group_id, state_revision_id);
 07070100000B6D000081B400000000000000000000000167AE1114000004B3000000000000000000000000000000000000007A00000000susemanager-schema/upgrade/susemanager-schema-3.0-to-susemanager-schema-3.0.10/0253-create-table-suseOrgStateRevision.sql --
-- Copyright (c) 2016 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

CREATE TABLE suseOrgStateRevision
(
    org_id         NUMERIC NOT NULL
                          CONSTRAINT suse_server_group_rev_sid_fk
                              REFERENCES web_customer (id)
                              ON DELETE CASCADE,
    state_revision_id NUMERIC NOT NULL
                          CONSTRAINT suse_server_group_rev_id_fk
                              REFERENCES suseStateRevision (id)
                              ON DELETE CASCADE
)

;

ALTER TABLE suseOrgStateRevision
    ADD CONSTRAINT suse_server_org_rev_id_sid_uq UNIQUE (org_id, state_revision_id);
 07070100000B6E000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005200000000susemanager-schema/upgrade/susemanager-schema-3.0.10-to-susemanager-schema-3.0.11 07070100000B6F000081B400000000000000000000000167AE11140000020D000000000000000000000000000000000000007900000000susemanager-schema/upgrade/susemanager-schema-3.0.10-to-susemanager-schema-3.0.11/0001-enable-pkg-actions-on-minions.sql  insert into rhnServerGroupTypeFeature (server_group_type_id, feature_id,
                                       created, modified)
values (lookup_sg_type('salt_entitled'), lookup_feature_type('ftr_package_updates'),
        current_timestamp,current_timestamp);

insert into rhnServerGroupTypeFeature (server_group_type_id, feature_id,
                                       created, modified)
values (lookup_sg_type('salt_entitled'), lookup_feature_type('ftr_package_remove'),
        current_timestamp,current_timestamp);

   07070100000B70000081B400000000000000000000000167AE11140000073D000000000000000000000000000000000000007600000000susemanager-schema/upgrade/susemanager-schema-3.0.10-to-susemanager-schema-3.0.11/0015-fixing-not-upgraded-schema.sql 
-- Dropping tables
drop table if exists rhn_command_queue_sessions;

-- Dropping PostgreSQL only functions
drop function if exists rhn_cmeth_val_trig_fun();
drop function if exists rhn_probe_delete_trigger_fun();
drop function if exists rhn_probe_insert_trigger_fun();
drop function if exists rhn_servnet_ipaddr_mon_trig_fun();
drop function if exists rhn_solaris_p_mod_trig_fun();
drop function if exists rhn_solaris_psm_mod_trig_fun();
drop function if exists rhn_solaris_ps_mod_trig_fun();
drop function if exists time_series_purge_mod_trig_fun();

-- Dropping sequences
drop sequence if exists rhn_check_suites_recid_seq;
drop sequence if exists rhn_command_q_comm_recid_seq;
drop sequence if exists rhn_command_q_inst_recid_seq;
drop sequence if exists rhn_commands_recid_seq;
drop sequence if exists rhn_command_target_recid_seq;
drop sequence if exists rhn_contact_groups_recid_seq;
drop sequence if exists rhn_contact_methods_recid_seq;
drop sequence if exists rhn_host_probes_recid_seq;
drop sequence if exists rhn_ntfmt_recid_seq;
drop sequence if exists rhn_pager_types_recid_seq;
drop sequence if exists rhn_physical_loc_recid_seq;
drop sequence if exists rhn_probes_recid_seq;
drop sequence if exists rhn_redirect_crit_recid_seq;
drop sequence if exists rhn_redirects_recid_seq;
drop sequence if exists rhn_redirect_types_recid_seq;
drop sequence if exists rhn_schedule_days_recid_seq;
drop sequence if exists rhn_schedules_recid_seq;
drop sequence if exists rhn_schedule_types_recid_seq;
drop sequence if exists rhn_schedule_weeks_recid_seq;
drop sequence if exists rhn_snmp_alert_recid_seq;
drop sequence if exists rhn_solaris_ps_seq;
drop sequence if exists rhn_solaris_pt_seq;
drop sequence if exists rhn_strategies_recid_seq;
drop sequence if exists rhn_url_probe_step_recid_seq;
drop sequence if exists rhn_org_entitlement_type_seq;
   07070100000B71000081B400000000000000000000000167AE1114000006A7000000000000000000000000000000000000007400000000susemanager-schema/upgrade/susemanager-schema-3.0.10-to-susemanager-schema-3.0.11/0016-fixing-not-upgraded-data.sql   -- Inserting into rhnPackageKey
update rhnPackageKey set provider_id = lookup_package_provider('Fedora')
 where key_id = '11adc0948e1431d5';

insert into rhnPackageKey (id, key_id, key_type_id, provider_id)
    (select sequence_nextval('rhn_pkey_id_seq'), '11adc0948e1431d5', lookup_package_key_type('gpg'), lookup_package_provider('Fedora') from dual
     where not exists (select 1 from rhnPackageKey where key_id = '11adc0948e1431d5'));

update rhnPackageKey set provider_id = lookup_package_provider('Fedora')
 where key_id = 'd8d1fa8ca29cb19c';

insert into rhnPackageKey (id, key_id, key_type_id, provider_id)
    (select sequence_nextval('rhn_pkey_id_seq'), 'd8d1fa8ca29cb19c', lookup_package_key_type('gpg'), lookup_package_provider('Fedora') from dual
     where not exists (select 1 from rhnPackageKey where key_id = 'd8d1fa8ca29cb19c'));

update rhnPackageKey set provider_id = lookup_package_provider('Fedora')
 where key_id = 'dbeae2e4efe550f5';

insert into rhnPackageKey (id, key_id, key_type_id, provider_id)
    (select sequence_nextval('rhn_pkey_id_seq'), 'dbeae2e4efe550f5', lookup_package_key_type('gpg'), lookup_package_provider('Fedora') from dual
     where not exists (select 1 from rhnPackageKey where key_id = 'dbeae2e4efe550f5'));

-- Inserting into rhnPackageUpgradeArchCompat
insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) select
LOOKUP_PACKAGE_ARCH('ppc64le'), LOOKUP_PACKAGE_ARCH('ppc64le'), current_timestamp, current_timestamp from dual
where not exists (select 1 from rhnPackageUpgradeArchCompat where package_arch_id = LOOKUP_PACKAGE_ARCH('ppc64le') and package_upgrade_arch_id = LOOKUP_PACKAGE_ARCH('ppc64le'));
 07070100000B72000081B400000000000000000000000167AE11140000005C000000000000000000000000000000000000007100000000susemanager-schema/upgrade/susemanager-schema-3.0.10-to-susemanager-schema-3.0.11/0017-drop-missing-function.sql  
drop function if exists obtain_read_lock(channel_family_id_in numeric, org_id_in numeric);
07070100000B73000081B400000000000000000000000167AE11140000004E000000000000000000000000000000000000007100000000susemanager-schema/upgrade/susemanager-schema-3.0.10-to-susemanager-schema-3.0.11/0019-remove-unused-feature.sql  -- rhnFeature

DELETE FROM rhnFeature
  WHERE label = 'ftr_nonlinux_support';
  07070100000B74000081B400000000000000000000000167AE111400000260000000000000000000000000000000000000007200000000susemanager-schema/upgrade/susemanager-schema-3.0.10-to-susemanager-schema-3.0.11/0207-remove-sync-probe-task.sql DELETE FROM rhnTaskoRun
  WHERE template_id IN (
    SELECT id
      FROM rhnTaskoTemplate
      WHERE task_id IN (
        SELECT id
          FROM rhnTaskoTask
          WHERE name = 'sync-probe-state'
      )
  );

DELETE FROM rhnTaskoTemplate
  WHERE bunch_id IN (
    SELECT id
      FROM rhnTaskoBunch
      WHERE name = 'sync-probe-bunch'
  );

DELETE FROM rhnTaskoTask
  WHERE name = 'sync-probe-state';

DELETE FROM rhnTaskoSchedule
  WHERE bunch_id IN (
    SELECT id
      FROM rhnTaskoBunch
      WHERE name = 'sync-probe-bunch'
  );

DELETE FROM rhnTaskoBunch
  WHERE name = 'sync-probe-bunch';
07070100000B75000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005200000000susemanager-schema/upgrade/susemanager-schema-3.0.11-to-susemanager-schema-3.0.12 07070100000B76000081B400000000000000000000000167AE1114000000D6000000000000000000000000000000000000007100000000susemanager-schema/upgrade/susemanager-schema-3.0.11-to-susemanager-schema-3.0.12/001-regen-channel-metadata.sql  insert into rhnRepoRegenQueue (id, CHANNEL_LABEL, REASON, FORCE)
(select sequence_nextval('rhn_repo_regen_queue_id_seq'),
        C.label,
        'fix names for cloned patches',
        'Y'
   from rhnChannel C);
  07070100000B77000081B400000000000000000000000167AE111400000108000000000000000000000000000000000000007D00000000susemanager-schema/upgrade/susemanager-schema-3.0.11-to-susemanager-schema-3.0.12/002-enable-refresh-hardware-on-minions.sql  insert into rhnServerGroupTypeFeature (server_group_type_id, feature_id,
                                       created, modified)
values (lookup_sg_type('salt_entitled'), lookup_feature_type('ftr_hardware_refresh'),
        current_timestamp, current_timestamp);
07070100000B78000081B400000000000000000000000167AE11140000009E000000000000000000000000000000000000007F00000000susemanager-schema/upgrade/susemanager-schema-3.0.11-to-susemanager-schema-3.0.12/003-change-customstate-unique-constraint.sql    drop index suse_custom_state_name_org_uq;

CREATE UNIQUE INDEX suse_custom_state_name_org_uq
ON suseCustomState (org_id, state_name)
WHERE state_deleted='N';
  07070100000B79000081B400000000000000000000000167AE111400000107000000000000000000000000000000000000008400000000susemanager-schema/upgrade/susemanager-schema-3.0.11-to-susemanager-schema-3.0.12/004-enable-package-profile-refresh-on-minions.sql   insert into rhnServerGroupTypeFeature (server_group_type_id, feature_id,
                                       created, modified)
values (lookup_sg_type('salt_entitled'), lookup_feature_type('ftr_package_refresh'),
        current_timestamp,current_timestamp);

 07070100000B7A000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005200000000susemanager-schema/upgrade/susemanager-schema-3.0.12-to-susemanager-schema-3.0.13 07070100000B7B000081B400000000000000000000000167AE1114000001A5000000000000000000000000000000000000007A00000000susemanager-schema/upgrade/susemanager-schema-3.0.12-to-susemanager-schema-3.0.13/001-migrate-machine_id-to-rhnserver.sql -- function index for rhnServer
alter table rhnServer add column machine_id VARCHAR(256);

CREATE UNIQUE INDEX rhn_server_maid_uq
  ON rhnServer
  (machine_id) where machine_id is not null;

update rhnServer s set machine_id=(select machine_id from suseMinionInfo m where m.server_id=s.id);

alter table suseMinionInfo drop constraint if exists rhn_minion_info_miid_uq;
alter table suseMinionInfo drop column machine_id;
   07070100000B7C000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005200000000susemanager-schema/upgrade/susemanager-schema-3.0.13-to-susemanager-schema-3.0.14 07070100000B7D000081B400000000000000000000000167AE1114000008F3000000000000000000000000000000000000007E00000000susemanager-schema/upgrade/susemanager-schema-3.0.13-to-susemanager-schema-3.0.14/001-deduplicate-rhnChannelContentSource.sql UPDATE rhnChannelContentSource
  SET source_id = (
    -- first, construct a temporary view on duplicates
    -- that is, couples of ids of rhnCountentSource rows that only differ by the URL token
    WITH duplicates AS (
      SELECT c1.id AS new_id, c2.id AS old_id
        -- take a couple of rhnCountentSource rows
        FROM rhnContentSource c1, rhnContentSource c2
        -- making sure that c1 is the newest, or in case they are equally old, c1 has higher id
        WHERE (c1.modified > c2.modified OR (c1.modified = c2.modified AND c1.id > c2.id))
        -- make sure we are talking about SCC URLs
          AND c1.source_url LIKE 'https://updates.suse.com/%'
          AND c2.source_url LIKE 'https://updates.suse.com/%'
        -- make sure both have a URL with a token part
          AND instr(c1.source_url, '?') > 0
          AND instr(c2.source_url, '?') > 0
        -- finally, they have equal initial (non-token) part
        -- but include the ? in the compare
          AND c1.source_url LIKE substr(c2.source_url, 0, instr(c2.source_url, '?')) || '%'
    )
    -- second, the new source id is simply the new_id from the duplicates table
    SELECT max(duplicates.new_id)
      FROM duplicates
      WHERE duplicates.old_id = rhnChannelContentSource.source_id
  )
  WHERE EXISTS (
    -- the update must only be executed on those rows that actually have a duplicate
    -- duplicate definition below is identical to the one above, it's copypasted because
    -- of cross-RDBMS syntax restrictions
    WITH duplicates AS (
      SELECT c1.id AS new_id, c2.id AS old_id
        FROM rhnContentSource c1, rhnContentSource c2
        WHERE (c1.modified > c2.modified OR (c1.modified = c2.modified AND c1.id > c2.id))
          AND c1.source_url LIKE 'https://updates.suse.com/%'
          AND c2.source_url LIKE 'https://updates.suse.com/%'
          AND instr(c1.source_url, '?') > 0
          AND instr(c2.source_url, '?') > 0
          AND c1.source_url LIKE substr(c2.source_url, 0, instr(c2.source_url, '?')) || '%'
    )
    SELECT distinct 1
      FROM duplicates
      WHERE duplicates.old_id = rhnChannelContentSource.source_id
  )
;

DELETE FROM rhnContentSource
  WHERE rhnContentSource.id NOT IN (
    SELECT source_id
      FROM rhnChannelContentSource
  );

 07070100000B7E000081B400000000000000000000000167AE111400000426000000000000000000000000000000000000007E00000000susemanager-schema/upgrade/susemanager-schema-3.0.13-to-susemanager-schema-3.0.14/002-add-minion-action-cleanup-tasko-job.sql INSERT INTO rhnTaskoBunch (id, name, description, org_bunch)
             VALUES (sequence_nextval('rhn_tasko_bunch_id_seq'), 'minion-action-cleanup-bunch', 'Cleanup actions for Minions', null);

INSERT INTO rhnTaskoSchedule (id, job_label, bunch_id, active_from, cron_expr)
    VALUES (sequence_nextval('rhn_tasko_schedule_id_seq'), 'minion-action-cleanup-default',
        (SELECT id FROM rhnTaskoBunch WHERE name='minion-action-cleanup-bunch'),
        current_timestamp, '0 0 * * * ?');

INSERT INTO rhnTaskoTask (id, name, class)
         VALUES (sequence_nextval('rhn_tasko_task_id_seq'), 'minion-action-cleanup', 'com.redhat.rhn.taskomatic.task.MinionActionCleanup');

INSERT INTO rhnTaskoTemplate (id, bunch_id, task_id, ordering, start_if)
             VALUES (sequence_nextval('rhn_tasko_template_id_seq'),
                        (SELECT id FROM rhnTaskoBunch WHERE name='minion-action-cleanup-bunch'),
                        (SELECT id FROM rhnTaskoTask WHERE name='minion-action-cleanup'),
                        0,
                        null);
  07070100000B7F000081B400000000000000000000000167AE1114000006E8000000000000000000000000000000000000007400000000susemanager-schema/upgrade/susemanager-schema-3.0.13-to-susemanager-schema-3.0.14/010-shorten-constraints-names.sql   
ALTER TABLE rhnActionApplyStatesResult DROP CONSTRAINT rhn_apply_states_result_aasid_fk;
ALTER TABLE rhnActionApplyStatesResult ADD CONSTRAINT rhn_apply_states_result_aid_fk FOREIGN KEY (action_apply_states_id) REFERENCES rhnActionApplyStates (id) ON DELETE CASCADE;

DROP INDEX rhn_apply_states_result_saas_uq;
CREATE UNIQUE INDEX rhn_apply_states_result_sa_uq
    ON rhnActionApplyStatesResult (server_id, action_apply_states_id);

DROP INDEX rhn_apply_states_result_aasid_idx;
CREATE INDEX rhn_apply_states_result_ad_idx
    ON rhnActionApplyStatesResult (action_apply_states_id);

ALTER TABLE suseServerGroupStateRevision DROP CONSTRAINT suse_server_group_rev_sid_fk;
ALTER TABLE suseServerGroupStateRevision ADD CONSTRAINT suse_server_group_gr_id_fk FOREIGN KEY (group_id) REFERENCES rhnServerGroup (id) ON DELETE CASCADE;

ALTER TABLE suseServerGroupStateRevision DROP CONSTRAINT suse_server_group_rev_id_fk;
ALTER TABLE suseServerGroupStateRevision ADD CONSTRAINT suse_server_group_sr_id_fk FOREIGN KEY (state_revision_id) REFERENCES suseStateRevision (id) ON DELETE CASCADE;

ALTER TABLE suseServerGroupStateRevision DROP CONSTRAINT suse_server_group_rev_id_sid_uq;
ALTER TABLE suseServerGroupStateRevision
    ADD CONSTRAINT suse_server_group_rev_grid_uq UNIQUE (group_id, state_revision_id);

ALTER TABLE suseServerStateRevision DROP CONSTRAINT suse_server_state_rev_id_sid_uq;
ALTER TABLE suseServerStateRevision
    ADD CONSTRAINT suse_server_state_rev_srev_uq UNIQUE (server_id, state_revision_id);

ALTER TABLE suseStateRevisionCustomState DROP CONSTRAINT suse_server_state_rev_id_fk;
ALTER TABLE suseStateRevisionCustomState ADD CONSTRAINT suse_salt_state_rev_id_fk FOREIGN KEY (state_revision_id) REFERENCES suseStateRevision (id) ON DELETE CASCADE;

07070100000B80000081B400000000000000000000000167AE11140000011C000000000000000000000000000000000000007300000000susemanager-schema/upgrade/susemanager-schema-3.0.13-to-susemanager-schema-3.0.14/100-remove-duplicate-minions.sql    DELETE FROM 
  rhnServerNetwork
    WHERE id IN
    (
        SELECT DISTINCT(a.id)
        FROM rhnServerNetwork a, rhnServerNetwork b, suseMinionInfo c
        WHERE
            a.server_id = b.server_id
            AND a.id < b.id
            AND a.server_id = c.server_id
    )
;
07070100000B81000081B400000000000000000000000167AE1114000001A2000000000000000000000000000000000000006D00000000susemanager-schema/upgrade/susemanager-schema-3.0.13-to-susemanager-schema-3.0.14/201-rhnVirtualInstance.sql  
delete from rhnVirtualInstance where virtual_system_id is NULL and host_system_id is not NULL and uuid in (select uuid from rhnVirtualInstance group by uuid having count(uuid) > 1);
delete from rhnVirtualInstance where virtual_system_id is NULL and host_system_id is NULL and uuid is not NULL;

DROP TRIGGER IF EXISTS rhn_virtinst_del_trig ON rhnvirtualinstance;
DROP FUNCTION IF EXISTS rhn_virtinst_del_trig_fun();

  07070100000B82000081B400000000000000000000000167AE111400000560000000000000000000000000000000000000006700000000susemanager-schema/upgrade/susemanager-schema-3.0.13-to-susemanager-schema-3.0.14/206-uuid-cleanup.sql    INSERT INTO rhnTaskoBunch (id, name, description, org_bunch)
    select sequence_nextval('rhn_tasko_bunch_id_seq'), 'uuid-cleanup-bunch', 'purge orphaned uuid records', null from dual
        where not exists (select 1 from rhnTaskoBunch where name = 'uuid-cleanup-bunch');

-- Every hour

INSERT INTO rhnTaskoSchedule (id, job_label, bunch_id, active_from, cron_expr)
    select sequence_nextval('rhn_tasko_schedule_id_seq'), 'uuid-cleanup-default',
        (SELECT id FROM rhnTaskoBunch WHERE name='uuid-cleanup-bunch'),
        current_timestamp, '0 0 * * * ?' from dual
        where not exists (select 1 from rhnTaskoSchedule where job_label = 'uuid-cleanup-default');

INSERT INTO rhnTaskoTask (id, name, class)
    select sequence_nextval('rhn_tasko_task_id_seq'), 'uuid-cleanup', 'com.redhat.rhn.taskomatic.task.UuidCleanup' from dual
where not exists (select 1 from rhnTaskoTask where name = 'uuid-cleanup');

INSERT INTO rhnTaskoTemplate (id, bunch_id, task_id, ordering, start_if)
    select sequence_nextval('rhn_tasko_template_id_seq'),
            (SELECT id FROM rhnTaskoBunch WHERE name='uuid-cleanup-bunch'),
            (SELECT id FROM rhnTaskoTask WHERE name='uuid-cleanup'),
            0,
            null from dual
        where not exists (select 1 from rhnTaskoTemplate where bunch_id = (SELECT id FROM rhnTaskoBunch WHERE name='uuid-cleanup-bunch'));
07070100000B83000081B400000000000000000000000167AE111400000156000000000000000000000000000000000000006700000000susemanager-schema/upgrade/susemanager-schema-3.0.13-to-susemanager-schema-3.0.14/207-drop-logging.sql    
DROP TRIGGER if exists web_contact_log_trig ON web_contact;
DROP FUNCTION if exists web_contact_log_trig_fun();

DROP TRIGGER if exists rhnserver_log_trig ON rhnserver;
DROP FUNCTION if exists rhnserver_log_trig_fun();

DROP TRIGGER if exists rhnservergroup_log_trig ON rhnservergroup;
DROP FUNCTION if exists rhnservergroup_log_trig_fun();
  07070100000B84000081B400000000000000000000000167AE111400000B52000000000000000000000000000000000000007500000000susemanager-schema/upgrade/susemanager-schema-3.0.13-to-susemanager-schema-3.0.14/9001-add-ssm-detailed-features.sql  insert into rhnFeature (id, label, name, created, modified)
select sequence_nextval('rhn_feature_seq'), 'ftr_channel_membership', 'Channel Memberships',
        current_timestamp, current_timestamp from dual
where not exists (select 1 from rhnFeature where label = 'ftr_channel_membership');
insert into rhnFeature (id, label, name, created, modified)
select sequence_nextval('rhn_feature_seq'), 'ftr_channel_config_subscription', 'Config Channel Subscriptions',
        current_timestamp, current_timestamp from dual
where not exists (select 1 from rhnFeature where label = 'ftr_channel_config_subscription');
insert into rhnFeature (id, label, name, created, modified)
select sequence_nextval('rhn_feature_seq'), 'ftr_channel_deploy_diff', 'Deploy/Diff Config Channel',
        current_timestamp, current_timestamp from dual
where not exists (select 1 from rhnFeature where label = 'ftr_channel_deploy_diff');
insert into rhnFeature (id, label, name, created, modified)
select sequence_nextval('rhn_feature_seq'), 'ftr_tag_system', 'Tag System',
        current_timestamp, current_timestamp from dual
where not exists (select 1 from rhnFeature where label = 'ftr_tag_system');
insert into rhnFeature (id, label, name, created, modified)
select sequence_nextval('rhn_feature_seq'), 'ftr_power_management', 'Power Management Operations',
        current_timestamp, current_timestamp from dual
where not exists (select 1 from rhnFeature where label = 'ftr_power_management');
insert into rhnFeature (id, label, name, created, modified)
select sequence_nextval('rhn_feature_seq'), 'ftr_system_preferences', 'System Preferences',
        current_timestamp, current_timestamp from dual
where not exists (select 1 from rhnFeature where label = 'ftr_system_preferences');
insert into rhnFeature (id, label, name, created, modified)
select sequence_nextval('rhn_feature_seq'), 'ftr_system_custom_values', 'System Custom Values',
        current_timestamp, current_timestamp from dual
where not exists (select 1 from rhnFeature where label = 'ftr_system_custom_values');
insert into rhnFeature (id, label, name, created, modified)
select sequence_nextval('rhn_feature_seq'), 'ftr_add_rm_addon_type', 'Add/Remove Addon Type',
        current_timestamp, current_timestamp from dual
where not exists (select 1 from rhnFeature where label = 'ftr_add_rm_addon_type');
insert into rhnFeature (id, label, name, created, modified)
select sequence_nextval('rhn_feature_seq'), 'ftr_system_lock', 'Lock System',
        current_timestamp, current_timestamp from dual
where not exists (select 1 from rhnFeature where label = 'ftr_system_lock');
insert into rhnFeature (id, label, name, created, modified)
select sequence_nextval('rhn_feature_seq'), 'ftr_system_audit', 'Audit System',
        current_timestamp, current_timestamp from dual
where not exists (select 1 from rhnFeature where label = 'ftr_system_audit');
  07070100000B85000081B400000000000000000000000167AE11140000183B000000000000000000000000000000000000007F00000000susemanager-schema/upgrade/susemanager-schema-3.0.13-to-susemanager-schema-3.0.14/9002-enable-entitlements-on-new-features.sql    
insert into rhnServerGroupTypeFeature (server_group_type_id, feature_id,
                                       created, modified)
select lookup_sg_type('enterprise_entitled'), lookup_feature_type('ftr_channel_membership'),
        current_timestamp,current_timestamp from dual
where not exists ( select 1 from rhnServerGroupTypeFeature
    where server_group_type_id = lookup_sg_type('enterprise_entitled')
      and feature_id = lookup_feature_type('ftr_channel_membership') );

insert into rhnServerGroupTypeFeature (server_group_type_id, feature_id,
                                       created, modified)
select lookup_sg_type('enterprise_entitled'), lookup_feature_type('ftr_channel_config_subscription'),
        current_timestamp,current_timestamp from dual
where not exists ( select 1 from rhnServerGroupTypeFeature
    where server_group_type_id = lookup_sg_type('enterprise_entitled')
      and feature_id = lookup_feature_type('ftr_channel_config_subscription') );

insert into rhnServerGroupTypeFeature (server_group_type_id, feature_id,
                                       created, modified)
select lookup_sg_type('enterprise_entitled'), lookup_feature_type('ftr_channel_deploy_diff'),
        current_timestamp,current_timestamp from dual
where not exists ( select 1 from rhnServerGroupTypeFeature
    where server_group_type_id = lookup_sg_type('enterprise_entitled')
      and feature_id = lookup_feature_type('ftr_channel_deploy_diff') );

insert into rhnServerGroupTypeFeature (server_group_type_id, feature_id,
                                       created, modified)
select lookup_sg_type('enterprise_entitled'), lookup_feature_type('ftr_tag_system'),
        current_timestamp,current_timestamp from dual
where not exists ( select 1 from rhnServerGroupTypeFeature
    where server_group_type_id = lookup_sg_type('enterprise_entitled')
      and feature_id = lookup_feature_type('ftr_tag_system') );

insert into rhnServerGroupTypeFeature (server_group_type_id, feature_id,
                                       created, modified)
select lookup_sg_type('enterprise_entitled'), lookup_feature_type('ftr_power_management'),
        current_timestamp,current_timestamp from dual
where not exists ( select 1 from rhnServerGroupTypeFeature
    where server_group_type_id = lookup_sg_type('enterprise_entitled')
      and feature_id = lookup_feature_type('ftr_power_management') );

insert into rhnServerGroupTypeFeature (server_group_type_id, feature_id,
                                       created, modified)
select lookup_sg_type('enterprise_entitled'), lookup_feature_type('ftr_system_preferences'),
        current_timestamp,current_timestamp from dual
where not exists ( select 1 from rhnServerGroupTypeFeature
    where server_group_type_id = lookup_sg_type('enterprise_entitled')
      and feature_id = lookup_feature_type('ftr_system_preferences') );

insert into rhnServerGroupTypeFeature (server_group_type_id, feature_id,
                                       created, modified)
select lookup_sg_type('enterprise_entitled'), lookup_feature_type('ftr_system_custom_values'),
        current_timestamp,current_timestamp from dual
where not exists ( select 1 from rhnServerGroupTypeFeature
    where server_group_type_id = lookup_sg_type('enterprise_entitled')
      and feature_id = lookup_feature_type('ftr_system_custom_values') );

insert into rhnServerGroupTypeFeature (server_group_type_id, feature_id,
                                       created, modified)
select lookup_sg_type('enterprise_entitled'), lookup_feature_type('ftr_add_rm_addon_type'),
        current_timestamp,current_timestamp from dual
where not exists ( select 1 from rhnServerGroupTypeFeature
    where server_group_type_id = lookup_sg_type('enterprise_entitled')
      and feature_id = lookup_feature_type('ftr_add_rm_addon_type') );

insert into rhnServerGroupTypeFeature (server_group_type_id, feature_id,
                                       created, modified)
select lookup_sg_type('enterprise_entitled'), lookup_feature_type('ftr_system_lock'),
        current_timestamp,current_timestamp from dual
where not exists ( select 1 from rhnServerGroupTypeFeature
    where server_group_type_id = lookup_sg_type('enterprise_entitled')
      and feature_id = lookup_feature_type('ftr_system_lock') );

insert into rhnServerGroupTypeFeature (server_group_type_id, feature_id,
                                       created, modified)
select lookup_sg_type('enterprise_entitled'), lookup_feature_type('ftr_system_audit'),
        current_timestamp,current_timestamp from dual
where not exists ( select 1 from rhnServerGroupTypeFeature
    where server_group_type_id = lookup_sg_type('enterprise_entitled')
      and feature_id = lookup_feature_type('ftr_system_audit') );

insert into rhnServerGroupTypeFeature (server_group_type_id, feature_id,
                                       created, modified)
select lookup_sg_type('salt_entitled'), lookup_feature_type('ftr_channel_membership'),
        current_timestamp,current_timestamp from dual
where not exists ( select 1 from rhnServerGroupTypeFeature
    where server_group_type_id = lookup_sg_type('salt_entitled')
      and feature_id = lookup_feature_type('ftr_channel_membership') );

insert into rhnServerGroupTypeFeature (server_group_type_id, feature_id,
                                       created, modified)
select lookup_sg_type('salt_entitled'), lookup_feature_type('ftr_system_custom_values'),
        current_timestamp,current_timestamp from dual
where not exists ( select 1 from rhnServerGroupTypeFeature
    where server_group_type_id = lookup_sg_type('salt_entitled')
      and feature_id = lookup_feature_type('ftr_system_custom_values') );

insert into rhnServerGroupTypeFeature (server_group_type_id, feature_id,
                                       created, modified)
select lookup_sg_type('bootstrap_entitled'), lookup_feature_type('ftr_power_management'),
        current_timestamp,current_timestamp from dual
where not exists ( select 1 from rhnServerGroupTypeFeature
    where server_group_type_id = lookup_sg_type('bootstrap_entitled')
      and feature_id = lookup_feature_type('ftr_power_management') );
 07070100000B86000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005200000000susemanager-schema/upgrade/susemanager-schema-3.0.14-to-susemanager-schema-3.0.15 07070100000B87000081B400000000000000000000000167AE11140000272F000000000000000000000000000000000000007700000000susemanager-schema/upgrade/susemanager-schema-3.0.14-to-susemanager-schema-3.0.15/001-avoid_deadlock_delete_server.sql    --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
-- This deletes a server.  All codepaths which delete servers should hit this
-- or delete_server_bulk()

create or replace
function delete_server (
        server_id_in in numeric
) returns void 
as
$$
declare
         servergroups cursor for
                select  server_id, server_group_id
                from    rhnServerGroupMembers sgm
                where   sgm.server_id = server_id_in;

         configchannels cursor for
                select  cc.id
                from    rhnConfigChannel cc,
                        rhnConfigChannelType cct,
                        rhnServerConfigChannel scc
                where   1=1
                        and scc.server_id = server_id_in
                        and scc.config_channel_id = cc.id
                        -- these config channel types are reserved
                        -- for use by a single server, so we don't
                        -- need to check for other servers subscribed
                        and cct.label in
                                ('local_override','server_import')
                        and cct.id = cc.confchan_type_id;

    update_lock numeric;
begin
    -- lock the rhnServer row to prevent deadlocks
    -- we want rhnServer to be locked first, followed by tables that depend on it
    select id into update_lock from rhnServer where id = server_id_in for update;

        -- filelists
        delete from rhnFileList where id in (
	select	spfl.file_list_id
	  from	rhnServerPreserveFileList spfl
	 where	spfl.server_id = server_id_in
			and not exists (
				select	1
				from	rhnServerPreserveFileList
				where	file_list_id = spfl.file_list_id
					and server_id != server_id_in
				union all
				select	1
				from	rhnKickstartPreserveFileList
				where	file_list_id = spfl.file_list_id
			)
        );

	for configchannel in configchannels loop
		perform rhn_config.delete_channel(configchannel.id);
	end loop;

	for sgm in servergroups loop
		perform rhn_server.delete_from_servergroup(
			sgm.server_id, sgm.server_group_id);
	end loop;


        -- we're handling this instead of letting an "on delete
        -- set null" do it so that we don't run the risk
        -- of setting off the triggers and killing us with a
        -- mutating table

        -- this is merge of two single updates:
        --  update ... set old_server_id = null where old_server_id = server_id_in;
        --  update ... set new_server_id = null where new_server_id = server_id_in;
        -- so we scan rhnKickstartSession table only once
        update rhnKickstartSession
                set old_server_id = case when old_server_id = server_id_in then null else old_server_id end,
                    new_server_id = case when new_server_id = server_id_in then null else new_server_id end
                where old_server_id = server_id_in
                   or new_server_id = server_id_in;

        perform rhn_channel.clear_subscriptions(server_id_in, 1);

        -- A little complicated here, but the goal is to
        -- delete records from rhnVirtualInstace only if we don't
        -- care about them anymore.  We don't care about records
        -- in rhnVirtualInstance if we are deleting the host
        -- system and the virtual system is already null, or
        -- vice-versa.  We *do* care about them if either the
        -- host or virtual system is still registered because we
        -- still want them to show up in the UI.
    -- If there's a newer row in rhnVirtualInstance with the same
    -- uuid, this guest must have been re-registered, so we can clean
    -- this data up.

        delete from rhnVirtualInstance vi
              where (host_system_id = server_id_in and virtual_system_id is null)
                 or (virtual_system_id = server_id_in and host_system_id is null)
                 or (vi.virtual_system_id = server_id_in and vi.modified < (select max(vi2.modified)
                    from rhnVirtualInstance vi2 where vi2.uuid = vi.uuid));

        -- this is merge of two single updates:
        --  update ... set host_system_id = null where host_system_id = server_id_in;
        --  update ... set virtual_system_id = null where virtual_system_id = server_id_in;
        -- so we scan rhnVirtualInstance table only once
        update rhnVirtualInstance
           set host_system_id = case when host_system_id = server_id_in then null else host_system_id end,
               virtual_system_id = case when virtual_system_id = server_id_in then null else virtual_system_id end
         where host_system_id = server_id_in
            or virtual_system_id = server_id_in;

        -- this is merge of two single updates:
        --  update ... set old_host_system_id = null when old_host_system_id = server_id_in;
        --  update ... set new_host_system_id = null when new_host_system_id = server_id_in;
        -- so we scan rhnVirtualInstanceEventLog table only once
        update rhnVirtualInstanceEventLog
           set old_host_system_id = case when old_host_system_id = server_id_in then null else old_host_system_id end,
               new_host_system_id = case when new_host_system_id = server_id_in then null else new_host_system_id end
         where old_host_system_id = server_id_in
            or new_host_system_id = server_id_in;

        -- We're deleting everything with a foreign key to rhnServer
        -- here, now.  I'm hoping this will help aleviate our deadlock
        -- problem.

        delete from rhnActionApplyStatesResult where server_id = server_id_in;
        delete from rhnActionConfigChannel where server_id = server_id_in;
        delete from rhnActionConfigRevision where server_id = server_id_in;
        delete from rhnActionPackageRemovalFailure where server_id = server_id_in;
        delete from rhnClientCapability where server_id = server_id_in;
        delete from rhnCpu where server_id = server_id_in;
        -- there's still a cascade here, because the constraint keeps the
        -- table locked for too long to rebuild it.  Ugh...
        delete from rhnDevice where server_id = server_id_in;
        delete from rhnProxyInfo where server_id = server_id_in;
        delete from rhnRam where server_id = server_id_in;
        delete from rhnRegToken where server_id = server_id_in;
        delete from rhnSatelliteInfo where server_id = server_id_in;
        -- this cascades to rhnActionConfigChannel and rhnActionConfigFileName
        delete from rhnServerAction where server_id = server_id_in;
        delete from rhnServerActionPackageResult where server_id = server_id_in;
        delete from rhnServerActionScriptResult where server_id = server_id_in;
        delete from rhnServerActionVerifyResult where server_id = server_id_in;
        delete from rhnServerActionVerifyMissing where server_id = server_id_in;
        -- counts are handled above.  this should be a delete_ function.
        delete from rhnServerChannel where server_id = server_id_in;
        delete from rhnServerConfigChannel where server_id = server_id_in;
        delete from rhnServerCustomDataValue where server_id = server_id_in;
        delete from rhnServerDMI where server_id = server_id_in;
        delete from rhnServerEvent where server_id = server_id_in;
        delete from rhnServerHistory where server_id = server_id_in;
        delete from rhnServerInfo where server_id = server_id_in;
        delete from rhnServerInstallInfo where server_id = server_id_in;
        delete from rhnServerLocation where server_id = server_id_in;
        delete from rhnServerLock where server_id = server_id_in;
        delete from rhnServerNeededCache where server_id = server_id_in;
        delete from rhnServerNetwork where server_id = server_id_in;
        delete from rhnServerNotes where server_id = server_id_in;
        -- I'm not removing the foreign key from rhnServerPackage; that'll
        -- take forever.  Do the delete anyway.
        delete from rhnServerPackage where server_id = server_id_in;
        delete from rhnServerTokenRegs where server_id = server_id_in;
        delete from rhnSnapshotTag where server_id = server_id_in;
        -- this cascades to:
        --   rhnSnapshotChannel, rhnSnapshotConfigChannel, rhnSnapshotPackage,
        --   rhnSnapshotConfigRevision, rhnSnapshotServerGroup,
        --   rhnSnapshotTag.
        -- We may want to consider delete_snapshot() at some point, but
        --   I don't think we need to yet.
        delete from rhnSnapshot where server_id = server_id_in;
        delete from rhnUserServerPrefs where server_id = server_id_in;
        -- hrm, this one's interesting... we _probably_ should delete
        -- everything for the parent server_id when we delete the proxy,
        -- but we don't currently.
        delete from rhnServerPath where server_id_in in (server_id, proxy_server_id);
        delete from rhnUserServerPerms where server_id = server_id_in;

        delete from rhnServerNetInterface where server_id = server_id_in;

        delete from rhnServerUuid where server_id = server_id_in;

        delete from rhnPushClient where server_id = server_id_in;

        -- now get rhnServer itself.
        delete
        from    rhnServer
                where id = server_id_in;

        delete
        from    rhnSet
        where   label = 'system_list'
                and element = server_id_in;
end;
$$
language plpgsql;

 07070100000B88000081B400000000000000000000000167AE111400000168000000000000000000000000000000000000007E00000000susemanager-schema/upgrade/susemanager-schema-3.0.14-to-susemanager-schema-3.0.15/002-add-severity-column-to-rhnErrataTmp.sql --
-- Adding the missing columnt 'severity_id' to rhnErrataTmp
-- table to be consistent with rhnErrata table

DO $$
    BEGIN
        BEGIN
            ALTER TABLE rhnerratatmp ADD COLUMN severity_id NUMERIC;
        EXCEPTION
            WHEN duplicate_column THEN RAISE NOTICE 'column severity_id already exists in rhnerratatmp.';
        END;
    END;
$$;
07070100000B89000081B400000000000000000000000167AE111400000504000000000000000000000000000000000000007C00000000susemanager-schema/upgrade/susemanager-schema-3.0.14-to-susemanager-schema-3.0.15/003-create-suseProductExtension-tabel.sql   --
-- Copyright (c) 2016 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
--


create table if not exists
suseProductExtension
(
    base_pdid   NUMERIC not null
                  CONSTRAINT suse_prdext_bpid_fk
                  REFERENCES suseProducts (id)
                  ON DELETE CASCADE,
    ext_pdid   NUMERIC not null
                  CONSTRAINT suse_prdext_epid_fk
                  REFERENCES suseProducts (id)
                  ON DELETE CASCADE,
    created   TIMESTAMPTZ
                  DEFAULT (current_timestamp) NOT NULL,
    modified  TIMESTAMPTZ
                  DEFAULT (current_timestamp) NOT NULL
);

DO $$
  BEGIN
    BEGIN
      CREATE INDEX prdext_bpid_idx
      ON suseProductExtension (base_pdid);

      CREATE INDEX prdext_epid_idx
      ON suseProductExtension (ext_pdid);
    EXCEPTION
      WHEN duplicate_table
      THEN RAISE NOTICE 'indexes already exists, skipping';
    END;
  END;
$$;
07070100000B8A000081B400000000000000000000000167AE111400000329000000000000000000000000000000000000006F00000000susemanager-schema/upgrade/susemanager-schema-3.0.14-to-susemanager-schema-3.0.15/004-suseProductExtension.sql    --
-- Copyright (c) 2016 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
--
create or replace function suse_prdext_mod_trig_fun() returns trigger
as
$$
begin
        new.modified := current_timestamp;

        return new;
end;
$$
language plpgsql;

drop trigger if exists prdext_mod_trig on suseProductExtension;

create trigger
prdext_mod_trig
before insert or update on suseProductExtension
for each row
execute procedure suse_prdext_mod_trig_fun();
   07070100000B8B000081B400000000000000000000000167AE11140000003E000000000000000000000000000000000000007800000000susemanager-schema/upgrade/susemanager-schema-3.0.14-to-susemanager-schema-3.0.15/010-add-os-family-to-minionserver.sql   
ALTER TABLE suseMinionInfo ADD COLUMN os_family VARCHAR(32);
  07070100000B8C000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005200000000susemanager-schema/upgrade/susemanager-schema-3.0.15-to-susemanager-schema-3.0.16 07070100000B8D000081B400000000000000000000000167AE11140000005B000000000000000000000000000000000000005900000000susemanager-schema/upgrade/susemanager-schema-3.0.15-to-susemanager-schema-3.0.16/README  -- Schema upgrade scripts.
-- Intentionally left empty. Please leave this directory empty.
 07070100000B8E000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005200000000susemanager-schema/upgrade/susemanager-schema-3.0.16-to-susemanager-schema-3.0.17 07070100000B8F000081B400000000000000000000000167AE111400000096000000000000000000000000000000000000007800000000susemanager-schema/upgrade/susemanager-schema-3.0.16-to-susemanager-schema-3.0.17/001-add-virthost-for-salt-systems.sql   insert into rhnSGTypeBaseAddonCompat (base_id, addon_id)
values (lookup_sg_type('salt_entitled'),
            lookup_sg_type('virtualization_host'));
  07070100000B90000081B400000000000000000000000167AE111400000115000000000000000000000000000000000000007600000000susemanager-schema/upgrade/susemanager-schema-3.0.16-to-susemanager-schema-3.0.17/002-fix-unique-indexes-with-org.sql 
drop index if exists rhn_cs_label_uq;
CREATE UNIQUE INDEX rhn_cs_label_uq
    ON rhnContentSource(COALESCE(org_id, 0), label)
    ;
drop index if exists rhn_cs_repo_uq;
CREATE UNIQUE INDEX rhn_cs_repo_uq
    ON rhnContentSource(COALESCE(org_id, 0), type_id, source_url)
    ;
   07070100000B91000081B400000000000000000000000167AE111400000041000000000000000000000000000000000000006F00000000susemanager-schema/upgrade/susemanager-schema-3.0.16-to-susemanager-schema-3.0.17/003-kernel-live-patching.sql    ALTER TABLE suseMinionInfo ADD kernel_live_version VARCHAR(255);
   07070100000B92000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005200000000susemanager-schema/upgrade/susemanager-schema-3.0.17-to-susemanager-schema-3.0.18 07070100000B93000081B400000000000000000000000167AE1114000003F3000000000000000000000000000000000000006D00000000susemanager-schema/upgrade/susemanager-schema-3.0.17-to-susemanager-schema-3.0.18/001-token-cleanup-task.sql  INSERT INTO rhnTaskoBunch (id, name, description, org_bunch)
             VALUES (sequence_nextval('rhn_tasko_bunch_id_seq'), 'token-cleanup-bunch', 'Cleanup expired channel tokens', null);

INSERT INTO rhnTaskoSchedule (id, job_label, bunch_id, active_from, cron_expr)
    VALUES (sequence_nextval('rhn_tasko_schedule_id_seq'), 'token-cleanup-default',
        (SELECT id FROM rhnTaskoBunch WHERE name='token-cleanup-bunch'),
        current_timestamp, '0 0 0 ? * *');

INSERT INTO rhnTaskoTask (id, name, class)
         VALUES (sequence_nextval('rhn_tasko_task_id_seq'), 'token-cleanup', 'com.redhat.rhn.taskomatic.task.TokenCleanup');

INSERT INTO rhnTaskoTemplate (id, bunch_id, task_id, ordering, start_if)
             VALUES (sequence_nextval('rhn_tasko_template_id_seq'),
                        (SELECT id FROM rhnTaskoBunch WHERE name='token-cleanup-bunch'),
                        (SELECT id FROM rhnTaskoTask WHERE name='token-cleanup'),
                        0,
                        null);

 07070100000B94000081B400000000000000000000000167AE111400000580000000000000000000000000000000000000006E00000000susemanager-schema/upgrade/susemanager-schema-3.0.17-to-susemanager-schema-3.0.18/002-create-token-tables.sql CREATE TABLE suseChannelAccessToken
(
    id               NUMERIC NOT NULL
                         CONSTRAINT suse_chan_access_token_id_pk PRIMARY KEY,
    minion_id        NUMERIC
                         CONSTRAINT suse_chan_access_token_mid_fk
                             REFERENCES suseMinionInfo (server_id)
                             ON DELETE SET NULL,
    token            VARCHAR(4000) NOT NULL,
    created          TIMESTAMPTZ NOT NULL,
    expiration       TIMESTAMPTZ NOT NULL,
    valid            CHAR(1) DEFAULT ('N') NOT NULL CHECK (valid in ('Y', 'N'))
)

;

CREATE SEQUENCE suse_chan_access_token_id_seq;

CREATE UNIQUE INDEX suse_accesstoken_token_uq
    ON suseChannelAccessToken (token);

CREATE TABLE suseChannelAccessTokenChannel
(
    token_id    NUMERIC NOT NULL
                    CONSTRAINT suse_catc_tid_fk
                        REFERENCES suseChannelAccessToken (id)
                        ON DELETE CASCADE,
    channel_id  NUMERIC NOT NULL
                    CONSTRAINT suse_catc_cid_fk
                        REFERENCES rhnChannel (id)
                        ON DELETE CASCADE,
    created     TIMESTAMPTZ
                    DEFAULT (current_timestamp) NOT NULL,
    modified    TIMESTAMPTZ
                    DEFAULT (current_timestamp) NOT NULL
)

;

CREATE UNIQUE INDEX suse_catc_tid_cid_uq
    ON suseChannelAccessTokenChannel (token_id, channel_id)
    ;

07070100000B95000081B400000000000000000000000167AE1114000000D6000000000000000000000000000000000000007100000000susemanager-schema/upgrade/susemanager-schema-3.0.17-to-susemanager-schema-3.0.18/999-regen-channel-metadata.sql  insert into rhnRepoRegenQueue (id, CHANNEL_LABEL, REASON, FORCE)
(select sequence_nextval('rhn_repo_regen_queue_id_seq'),
        C.label,
        'fix names for cloned patches',
        'Y'
   from rhnChannel C);
  07070100000B96000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005200000000susemanager-schema/upgrade/susemanager-schema-3.0.18-to-susemanager-schema-3.0.19 07070100000B97000081B400000000000000000000000167AE111400001A6A000000000000000000000000000000000000007700000000susemanager-schema/upgrade/susemanager-schema-3.0.18-to-susemanager-schema-3.0.19/001-disable-legacy-audit-logging.sql    --
-- Copyright (c) 2013 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

-- create schema ;

update pg_settings set setting = ',' || setting where name = 'search_path';

create or replace function clear_log_id()
returns void
as
$$
begin
    return;
end;
$$ language plpgsql set search_path from current;

create or replace function _set_log_auth(user_id in numeric, stamp in varchar)
returns void
as
$$
begin
    return;
end;
$$ language plpgsql set search_path from current;

create or replace function set_log_auth(user_id in numeric)
returns void
as
$$
begin
    return;
end;
$$ language plpgsql set search_path from current;

create or replace function _get_log_auth()
returns numeric
as
$$
begin
    return 0;
end;
$$ language plpgsql set search_path from current;

create or replace function _get_log_stamp()
returns varchar
as
$$
begin
    return '';
end;
$$ language plpgsql set search_path from current;

create or replace function _get_log_id()
returns numeric
as
$$
begin
    return 0;
end;
$$ language plpgsql set search_path from current;

create or replace function _set_log_id(log_id in numeric)
returns void
as
$$
begin
    return;
end;
$$ language plpgsql set search_path from current;

create or replace function get_log_id()
returns numeric
as
$$
declare
    the_log_id numeric;
    the_user_id numeric;
    the_stamp varchar;
begin
    the_log_id := _get_log_id();
    if the_log_id is not null and the_log_id > 0 then return the_log_id ; end if;
    the_log_id := nextval('log_seq');
    the_user_id := _get_log_auth();
    the_stamp := _get_log_stamp();
    insert into public.log (id, stamp, user_id)
    values (the_log_id,
        case when the_stamp = '' then current_timestamp else the_stamp::timestamp with time zone end,
        case when the_user_id = '0' then null else the_user_id::numeric end);
    perform _set_log_id(the_log_id);
    return the_log_id;
end;
$$ language plpgsql set search_path from current;

create or replace function _get_primary_key_column(table_name_in in varchar)
returns varchar
as
$$
declare
    pk_column varchar;
begin
    select constraint_column_usage.column_name into strict pk_column
    from information_schema.table_constraints, information_schema.constraint_column_usage
    where constraint_column_usage.table_catalog = current_catalog
        and constraint_column_usage.table_schema = 'public'
        and constraint_column_usage.table_name = lower(table_name_in)
        and constraint_column_usage.constraint_catalog = current_catalog
        and constraint_column_usage.constraint_schema = 'public'
        and constraint_column_usage.table_catalog = table_constraints.constraint_catalog
        and constraint_column_usage.table_catalog = table_constraints.table_catalog
        and constraint_column_usage.table_schema = table_constraints.constraint_schema
        and constraint_column_usage.table_schema = table_constraints.table_schema
        and constraint_column_usage.constraint_catalog = table_constraints.constraint_catalog
        and constraint_column_usage.constraint_name = table_constraints.constraint_name
        and table_constraints.constraint_type = 'PRIMARY KEY';
    return pk_column;
end;
$$
language plpgsql set search_path from current;

create or replace function _get_ddl_columns(table_name_in in varchar, pk_column_in in varchar)
returns varchar
as
$$
declare
    ddl_columns varchar;
    rec record;
begin
    ddl_columns := '';
    for rec in (
        select column_name
        from information_schema.columns
        where table_catalog = current_catalog
            and table_schema = 'public'
            and table_name = lower(table_name_in)
            and column_name not in (pk_column_in, 'created', 'modified' )
    ) loop
        ddl_columns := ddl_columns || ', ' || rec.column_name;
    end loop;
    return ddl_columns;
end;
$$
language plpgsql set search_path from current;


create or replace function recreate_trigger(table_name_in in varchar)
returns void
as
$$
declare
    pk_column varchar;
    ddl_columns varchar;
    the_insert varchar;
begin
    pk_column := _get_primary_key_column(table_name_in);
    ddl_columns := _get_ddl_columns(table_name_in, pk_column);
    the_insert := 'insert into public.' || table_name_in || '_log (log_id, action, ' || pk_column || ddl_columns ||')
                values (log_id_v, substr(tg_op, 1, 1)' || replace(', ' || pk_column || ddl_columns, ', ', ', old.') || ');';
    execute 'create or replace function public.' || table_name_in || '_log_trig_fun() returns trigger as
        ''
        begin
            return new;
        end;
        ''
        language plpgsql;';

    execute 'drop trigger if exists ' || table_name_in || '_log_trig' || ' on ' || table_name_in;
    execute 'create trigger ' || table_name_in || '_log_trig
        after insert or update or delete on public.' || table_name_in || '
        for each row
        execute procedure ' || table_name_in || '_log_trig_fun()';

end;
$$
language plpgsql set search_path from current;

create or replace function enable_(table_name_in in varchar)
returns void
as
$$
declare
    pk_column varchar;
    ddl_columns varchar;
begin
    pk_column := _get_primary_key_column(table_name_in);
    ddl_columns := _get_ddl_columns(table_name_in, pk_column);

    execute 'create table public.' || table_name_in || '_log
        as select ' || pk_column || ', .get_log_id()::numeric as log_id, ''A''::char as action' || ddl_columns
        || ' from ' || table_name_in;
    execute 'alter table public.' || table_name_in || '_log alter ' || pk_column || ' set not null';
    execute 'create index ' || table_name_in || '_log_idx on public.' || table_name_in || '_log(' || pk_column || ')';
    execute 'alter table public.' || table_name_in || '_log alter log_id set not null';
    execute 'alter table public.' || table_name_in || '_log add foreign key (log_id) references log(id)';
    execute 'alter table public.' || table_name_in || '_log alter action set not null';
    perform recreate_trigger(table_name_in);
end;
$$
language plpgsql set search_path from current;

update pg_settings set setting = overlay( setting placing '' from 1 for (length('')+1) ) where name = 'search_path';
  07070100000B98000081B400000000000000000000000167AE1114000001C6000000000000000000000000000000000000007700000000susemanager-schema/upgrade/susemanager-schema-3.0.18-to-susemanager-schema-3.0.19/001-give-minions-scap-capability.sql    select lookup_client_capability('scap.xccdf_eval') from dual;

INSERT INTO rhnClientCapability(server_id, capability_name_id, version) SELECT s.id, (SELECT id FROM rhnClientCapabilityName WHERE name='scap.xccdf_eval'), 1 FROM rhnServer s, suseminioninfo mi WHERE s.id=mi.server_id AND NOT EXISTS (select 1 from rhnClientCapability c where c.capability_name_id=(SELECT id FROM rhnClientCapabilityName WHERE name='scap.xccdf_eval') and c.server_id=s.id);

  07070100000B99000081B400000000000000000000000167AE111400000094000000000000000000000000000000000000007700000000susemanager-schema/upgrade/susemanager-schema-3.0.18-to-susemanager-schema-3.0.19/002-cleanup-legacy-audit-logging.sql    
SELECT .recreate_trigger('rhnserver');
SELECT .recreate_trigger('rhnservergroup');
SELECT .recreate_trigger('web_contact');

TRUNCATE log CASCADE;
07070100000B9A000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005200000000susemanager-schema/upgrade/susemanager-schema-3.0.19-to-susemanager-schema-3.0.20 07070100000B9B000081B400000000000000000000000167AE111400002FD6000000000000000000000000000000000000006F00000000susemanager-schema/upgrade/susemanager-schema-3.0.19-to-susemanager-schema-3.0.20/001-rhn_entitlements.pkb.sql    --
-- Copyright (c) 2008--2015 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

-- create schema rhn_entitlements;

-- setup search_path so that these functions are created in appropriate schema.
update pg_settings set setting = 'rhn_entitlements,' || setting where name = 'search_path';

   create or replace function find_compatible_sg (
      server_id_in in numeric,
      type_label_in in varchar
   )
   returns numeric
as $$
    declare
      servergroups cursor for
         select sg.id
           from rhnServerGroupType             sgt,
                rhnServerGroup                 sg,
                rhnServer                     s,
                rhnServerServerGroupArchCompat ssgac
          where s.id = server_id_in
            and s.org_id = sg.org_id
            and sgt.label = type_label_in
            and sg.group_type = sgt.id
            and ssgac.server_group_type = sgt.id
            and ssgac.server_arch_id = s.server_arch_id
            and not exists (
                     select 1
                      from rhnServerGroupMembers sgm
                     where sgm.server_group_id = sg.id
                       and sgm.server_id = s.id);


   begin
      for servergroup in servergroups loop
         return servergroup.id;
      end loop;

      --no servergroup found
      return NULL;
   end$$
language plpgsql;


    create or replace function entitlement_grants_service (
        entitlement_in in varchar,
        service_level_in in varchar
    ) returns numeric
as $$
    begin
        if service_level_in = 'management' then
            if entitlement_in = 'enterprise_entitled' or entitlement_in = 'salt_entitled' then
                return 1;
            else
                return 0;
            end if;
        elsif service_level_in = 'updates' then
            return 1;
        else
            return 0;
        end if;
    end$$
language plpgsql;

   create or replace function can_entitle_server (
      server_id_in   in numeric,
      type_label_in  in varchar
   )
   returns numeric
as $$
    declare
      addon_servergroups cursor (base_label_in varchar,
                                 addon_label_in varchar) for
         select
            addon_id
         from
            rhnSGTypeBaseAddonCompat
         where base_id = lookup_sg_type (base_label_in)
           and addon_id = lookup_sg_type (addon_label_in);

      previous_ent        varchar[];
      is_base_in          char   := 'N';
      is_base_current     char   := 'N';
      i                   numeric := 0;
      sgid                numeric := 0;

   begin

      previous_ent := rhn_entitlements.get_server_entitlement(server_id_in);
      RAISE NOTICE 'can_entitle_server - % - % prev ents: %', server_id_in, type_label_in, previous_ent;

      select distinct is_base
      into is_base_in
      from rhnServerGroupType
      where label = type_label_in;

      if array_upper(previous_ent, 1) is null or array_upper(previous_ent, 1) = 0 then
         if is_base_in = 'Y' then
            sgid := rhn_entitlements.find_compatible_sg (server_id_in, type_label_in);
            if sgid is not null then
              -- rhn_server.insert_into_servergroup (server_id_in, sgid);
              return 1;
            else
              -- rhn_exception.raise_exception ('invalid_base_entitlement');
              RAISE NOTICE 'invalid_base_entitlement - no compatible server group';
              return 0;
            end if;
         else
            -- rhn_exception.raise_exception ('invalid_base_entitlement');
            RAISE NOTICE 'invalid_base_entitlement - not a base entitlement';
            return 0;
         end if;

      -- there are previous ents, first make sure we're not trying to entitle a base ent
      elsif is_base_in = 'Y' then
         -- rhn_exception.raise_exception ('invalid_addon_entitlement');
         RAISE NOTICE 'invalid_addon_entitlement - found another base';
         return 0;

      -- it must be an addon, so proceed with the entitlement
      else

         -- find the servers base ent
         is_base_current := 'N';
         i := 0;
         while is_base_current = 'N' and i < array_upper(previous_ent, 1)
         loop
            i := i + 1;
            select is_base
            into is_base_current
            from rhnServerGroupType
            where label = previous_ent[i];
         end loop;

         -- never found a base ent, that would be strange
         if is_base_current  = 'N' then
            -- rhn_exception.raise_exception ('invalid_base_entitlement');
            RAISE NOTICE 'invalid_base_entitlement - never found a base';
            return 0;
         end if;

         -- this for loop verifies the validity of the addon path
         for addon_servergroup in addon_servergroups  (previous_ent[i], type_label_in) loop
            -- find an appropriate sgid for the addon and entitle the server
            sgid := rhn_entitlements.find_compatible_sg (server_id_in, type_label_in);
            if sgid is not null then
               -- rhn_server.insert_into_servergroup (server_id_in, sgid);
               return 1;
            else
               -- rhn_exception.raise_exception ('invalid_addon_entitlement');
               RAISE NOTICE 'invalid_addon_entitlement - no server group found';
               return 0;
            end if;
         end loop;

      end if;
      RAISE NOTICE 'final error';
      return 0;

   end$$
language plpgsql;

   create or replace function can_switch_base (
      server_id_in   in    integer,
      type_label_in  in    varchar
   )
   returns numeric
as $$
   declare
      type_label_in_is_base   char(1);
      sgid                    numeric;

   begin

       select is_base into type_label_in_is_base
       from rhnServerGroupType
       where label = type_label_in;

       if not found then
          perform rhn_exception.raise_exception ( 'invalid_entitlement' );
       end if;

      if type_label_in_is_base = 'N' then
         perform rhn_exception.raise_exception ( 'invalid_entitlement' );
      else
         sgid := rhn_entitlements.find_compatible_sg ( server_id_in,
                                                       type_label_in );
         if sgid is not null then
           return 1;
         else
           return 0;
         end if;
      end if;

   end$$
language plpgsql;

    create or replace function entitle_server (
        server_id_in in numeric,
        type_label_in in varchar
    ) returns void
as $$
    declare
      sgid  numeric := 0;

    begin

      if rhn_entitlements.can_entitle_server(server_id_in,
                                             type_label_in) = 1 then
         sgid := rhn_entitlements.find_compatible_sg (server_id_in,
                                                      type_label_in);
         if sgid is not null then
            insert into rhnServerHistory ( id, server_id, summary, details )
            values ( nextval('rhn_event_id_seq'), server_id_in,
                     'added system entitlement ',
                      case type_label_in
                       when 'enterprise_entitled' then 'Management'
                       when 'bootstrap_entitled' then 'Bootstrap'
                       when 'salt_entitled' then 'Salt'
                       when 'foreign_entitled' then 'Foreign'
                       when 'virtualization_host' then 'Virtualization'
                      end  );

            perform rhn_server.insert_into_servergroup (server_id_in, sgid);

         else
            perform rhn_exception.raise_exception ('no_available_server_group');
         end if;
      else
         perform rhn_exception.raise_exception ('invalid_entitlement');
      end if;
   end$$
language plpgsql;

    create or replace function remove_server_entitlement (
        server_id_in in numeric,
        type_label_in in varchar
    ) returns void
as $$
    declare
      group_id numeric;
      type_is_base char;
    begin

        select  sg.id, sgt.is_base
        into group_id, type_is_base
        from    rhnServerGroupType sgt,
            rhnServerGroup sg,
                rhnServerGroupMembers sgm,
                rhnServer s
        where   s.id = server_id_in
            and s.id = sgm.server_id
            and sgm.server_group_id = sg.id
            and sg.org_id = s.org_id
            and sgt.label = type_label_in
            and sgt.id = sg.group_type;

        if not found then
          perform rhn_exception.raise_exception('invalid_server_group_member');
        end if;

      if ( type_is_base = 'Y' ) then
         -- unentitle_server should handle everything, don't really need to do anything else special here
         perform rhn_entitlements.unentitle_server ( server_id_in );
      else

         insert into rhnServerHistory ( id, server_id, summary, details )
         values ( nextval('rhn_event_id_seq'), server_id_in,
                  'removed system entitlement ',
                   case type_label_in
                    when 'enterprise_entitled' then 'Management'
                    when 'bootstrap_entitled' then 'Bootstrap'
                    when 'salt_entitled' then 'Salt'
                    when 'foreign_entitled' then 'Foreign'
                    when 'virtualization_host' then 'Virtualization'
                   end  );

         perform rhn_server.delete_from_servergroup(server_id_in, group_id);

      end if;

    end$$
language plpgsql;

    create or replace function unentitle_server (
        server_id_in in numeric
    ) returns void
as $$
    declare
      servergroups cursor for
         select distinct sgt.label, sg.id server_group_id
         from  rhnServerGroupType sgt,
               rhnServerGroup sg,
               rhnServer s,
               rhnServerGroupMembers sgm
         where s.id = server_id_in
            and s.org_id = sg.org_id
            and sg.group_type = sgt.id
            and sgm.server_group_id = sg.id
            and sgm.server_id = s.id;

   begin

      for servergroup in servergroups loop

         insert into rhnServerHistory ( id, server_id, summary, details )
         values ( nextval('rhn_event_id_seq'), server_id_in,
                  'removed system entitlement ',
                   case servergroup.label
                    when 'enterprise_entitled' then 'Management'
                    when 'bootstrap_entitled' then 'Bootstrap'
                    when 'salt_entitled' then 'Salt'
                    when 'foreign_entitled' then 'Foreign'
                    when 'virtualization_host' then 'Virtualization'
                   end  );

         perform rhn_server.delete_from_servergroup(server_id_in,
                                            servergroup.server_group_id );
      end loop;

   end$$
language plpgsql;


    create or replace function get_server_entitlement (
        server_id_in in numeric
    ) returns varchar[]
as $$
    declare
        server_groups cursor for
            select  sgt.label
            from    rhnServerGroupType      sgt,
                    rhnServerGroup          sg,
                    rhnServerGroupMembers   sgm
            where   1=1
                and sgm.server_id = server_id_in
                and sg.id = sgm.server_group_id
                and sgt.id = sg.group_type;

         ent_array varchar[];

    begin

      ent_array := '{}';

      for sg in server_groups loop
         ent_array := ent_array || sg.label;
      end loop;

      return ent_array;

    end$$
language plpgsql;

-- restore the original setting
update pg_settings set setting = overlay( setting placing '' from 1 for (length('rhn_entitlements')+1) ) where name = 'search_path';
  07070100000B9C000081B400000000000000000000000167AE1114000134B2000000000000000000000000000000000000007D00000000susemanager-schema/upgrade/susemanager-schema-3.0.19-to-susemanager-schema-3.0.20/002-fix-rhnServerServerGroupArchCompat.sql  insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type)
  select LOOKUP_SERVER_ARCH('alpha-debian-linux'), LOOKUP_SG_TYPE('bootstrap_entitled') from dual
   where not exists (select 1 from rhnServerServerGroupArchCompat
                      where server_arch_id = LOOKUP_SERVER_ARCH('alpha-debian-linux')
                        and server_group_type = LOOKUP_SG_TYPE('bootstrap_entitled'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type)
  select LOOKUP_SERVER_ARCH('alphaev6-redhat-linux'), LOOKUP_SG_TYPE('bootstrap_entitled') from dual
   where not exists (select 1 from rhnServerServerGroupArchCompat
                      where server_arch_id = LOOKUP_SERVER_ARCH('alphaev6-redhat-linux')
                        and server_group_type = LOOKUP_SG_TYPE('bootstrap_entitled'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type)
  select LOOKUP_SERVER_ARCH('alpha-redhat-linux'), LOOKUP_SG_TYPE('bootstrap_entitled') from dual
   where not exists (select 1 from rhnServerServerGroupArchCompat
                      where server_arch_id = LOOKUP_SERVER_ARCH('alpha-redhat-linux')
                        and server_group_type = LOOKUP_SG_TYPE('bootstrap_entitled'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type)
  select LOOKUP_SERVER_ARCH('amd64-debian-linux'), LOOKUP_SG_TYPE('bootstrap_entitled') from dual
   where not exists (select 1 from rhnServerServerGroupArchCompat
                      where server_arch_id = LOOKUP_SERVER_ARCH('amd64-debian-linux')
                        and server_group_type = LOOKUP_SG_TYPE('bootstrap_entitled'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type)
  select LOOKUP_SERVER_ARCH('amd64-redhat-linux'), LOOKUP_SG_TYPE('bootstrap_entitled') from dual
   where not exists (select 1 from rhnServerServerGroupArchCompat
                      where server_arch_id = LOOKUP_SERVER_ARCH('amd64-redhat-linux')
                        and server_group_type = LOOKUP_SG_TYPE('bootstrap_entitled'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type)
  select LOOKUP_SERVER_ARCH('arm-debian-linux'), LOOKUP_SG_TYPE('bootstrap_entitled') from dual
   where not exists (select 1 from rhnServerServerGroupArchCompat
                      where server_arch_id = LOOKUP_SERVER_ARCH('arm-debian-linux')
                        and server_group_type = LOOKUP_SG_TYPE('bootstrap_entitled'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type)
  select LOOKUP_SERVER_ARCH('armv5tejl-redhat-linux'), LOOKUP_SG_TYPE('bootstrap_entitled') from dual
   where not exists (select 1 from rhnServerServerGroupArchCompat
                      where server_arch_id = LOOKUP_SERVER_ARCH('armv5tejl-redhat-linux')
                        and server_group_type = LOOKUP_SG_TYPE('bootstrap_entitled'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type)
  select LOOKUP_SERVER_ARCH('armv6l-redhat-linux'), LOOKUP_SG_TYPE('bootstrap_entitled') from dual
   where not exists (select 1 from rhnServerServerGroupArchCompat
                      where server_arch_id = LOOKUP_SERVER_ARCH('armv6l-redhat-linux')
                        and server_group_type = LOOKUP_SG_TYPE('bootstrap_entitled'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type)
  select LOOKUP_SERVER_ARCH('armv7l-redhat-linux'), LOOKUP_SG_TYPE('bootstrap_entitled') from dual
   where not exists (select 1 from rhnServerServerGroupArchCompat
                      where server_arch_id = LOOKUP_SERVER_ARCH('armv7l-redhat-linux')
                        and server_group_type = LOOKUP_SG_TYPE('bootstrap_entitled'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type)
  select LOOKUP_SERVER_ARCH('athlon-redhat-linux'), LOOKUP_SG_TYPE('bootstrap_entitled') from dual
   where not exists (select 1 from rhnServerServerGroupArchCompat
                      where server_arch_id = LOOKUP_SERVER_ARCH('athlon-redhat-linux')
                        and server_group_type = LOOKUP_SG_TYPE('bootstrap_entitled'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type)
  select LOOKUP_SERVER_ARCH('i386-debian-linux'), LOOKUP_SG_TYPE('bootstrap_entitled') from dual
   where not exists (select 1 from rhnServerServerGroupArchCompat
                      where server_arch_id = LOOKUP_SERVER_ARCH('i386-debian-linux')
                        and server_group_type = LOOKUP_SG_TYPE('bootstrap_entitled'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type)
  select LOOKUP_SERVER_ARCH('i386-i86pc-solaris'), LOOKUP_SG_TYPE('bootstrap_entitled') from dual
   where not exists (select 1 from rhnServerServerGroupArchCompat
                      where server_arch_id = LOOKUP_SERVER_ARCH('i386-i86pc-solaris')
                        and server_group_type = LOOKUP_SG_TYPE('bootstrap_entitled'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type)
  select LOOKUP_SERVER_ARCH('i386-redhat-linux'), LOOKUP_SG_TYPE('bootstrap_entitled') from dual
   where not exists (select 1 from rhnServerServerGroupArchCompat
                      where server_arch_id = LOOKUP_SERVER_ARCH('i386-redhat-linux')
                        and server_group_type = LOOKUP_SG_TYPE('bootstrap_entitled'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type)
  select LOOKUP_SERVER_ARCH('i486-redhat-linux'), LOOKUP_SG_TYPE('bootstrap_entitled') from dual
   where not exists (select 1 from rhnServerServerGroupArchCompat
                      where server_arch_id = LOOKUP_SERVER_ARCH('i486-redhat-linux')
                        and server_group_type = LOOKUP_SG_TYPE('bootstrap_entitled'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type)
  select LOOKUP_SERVER_ARCH('i586-redhat-linux'), LOOKUP_SG_TYPE('bootstrap_entitled') from dual
   where not exists (select 1 from rhnServerServerGroupArchCompat
                      where server_arch_id = LOOKUP_SERVER_ARCH('i586-redhat-linux')
                        and server_group_type = LOOKUP_SG_TYPE('bootstrap_entitled'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type)
  select LOOKUP_SERVER_ARCH('i686-redhat-linux'), LOOKUP_SG_TYPE('bootstrap_entitled') from dual
   where not exists (select 1 from rhnServerServerGroupArchCompat
                      where server_arch_id = LOOKUP_SERVER_ARCH('i686-redhat-linux')
                        and server_group_type = LOOKUP_SG_TYPE('bootstrap_entitled'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type)
  select LOOKUP_SERVER_ARCH('ia32e-redhat-linux'), LOOKUP_SG_TYPE('bootstrap_entitled') from dual
   where not exists (select 1 from rhnServerServerGroupArchCompat
                      where server_arch_id = LOOKUP_SERVER_ARCH('ia32e-redhat-linux')
                        and server_group_type = LOOKUP_SG_TYPE('bootstrap_entitled'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type)
  select LOOKUP_SERVER_ARCH('ia64-debian-linux'), LOOKUP_SG_TYPE('bootstrap_entitled') from dual
   where not exists (select 1 from rhnServerServerGroupArchCompat
                      where server_arch_id = LOOKUP_SERVER_ARCH('ia64-debian-linux')
                        and server_group_type = LOOKUP_SG_TYPE('bootstrap_entitled'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type)
  select LOOKUP_SERVER_ARCH('ia64-redhat-linux'), LOOKUP_SG_TYPE('bootstrap_entitled') from dual
   where not exists (select 1 from rhnServerServerGroupArchCompat
                      where server_arch_id = LOOKUP_SERVER_ARCH('ia64-redhat-linux')
                        and server_group_type = LOOKUP_SG_TYPE('bootstrap_entitled'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type)
  select LOOKUP_SERVER_ARCH('iSeries-redhat-linux'), LOOKUP_SG_TYPE('bootstrap_entitled') from dual
   where not exists (select 1 from rhnServerServerGroupArchCompat
                      where server_arch_id = LOOKUP_SERVER_ARCH('iSeries-redhat-linux')
                        and server_group_type = LOOKUP_SG_TYPE('bootstrap_entitled'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type)
  select LOOKUP_SERVER_ARCH('mips-debian-linux'), LOOKUP_SG_TYPE('bootstrap_entitled') from dual
   where not exists (select 1 from rhnServerServerGroupArchCompat
                      where server_arch_id = LOOKUP_SERVER_ARCH('mips-debian-linux')
                        and server_group_type = LOOKUP_SG_TYPE('bootstrap_entitled'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type)
  select LOOKUP_SERVER_ARCH('powerpc-debian-linux'), LOOKUP_SG_TYPE('bootstrap_entitled') from dual
   where not exists (select 1 from rhnServerServerGroupArchCompat
                      where server_arch_id = LOOKUP_SERVER_ARCH('powerpc-debian-linux')
                        and server_group_type = LOOKUP_SG_TYPE('bootstrap_entitled'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type)
  select LOOKUP_SERVER_ARCH('ppc64iseries-redhat-linux'), LOOKUP_SG_TYPE('bootstrap_entitled') from dual
   where not exists (select 1 from rhnServerServerGroupArchCompat
                      where server_arch_id = LOOKUP_SERVER_ARCH('ppc64iseries-redhat-linux')
                        and server_group_type = LOOKUP_SG_TYPE('bootstrap_entitled'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type)
  select LOOKUP_SERVER_ARCH('ppc64le-redhat-linux'), LOOKUP_SG_TYPE('bootstrap_entitled') from dual
   where not exists (select 1 from rhnServerServerGroupArchCompat
                      where server_arch_id = LOOKUP_SERVER_ARCH('ppc64le-redhat-linux')
                        and server_group_type = LOOKUP_SG_TYPE('bootstrap_entitled'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type)
  select LOOKUP_SERVER_ARCH('ppc64pseries-redhat-linux'), LOOKUP_SG_TYPE('bootstrap_entitled') from dual
   where not exists (select 1 from rhnServerServerGroupArchCompat
                      where server_arch_id = LOOKUP_SERVER_ARCH('ppc64pseries-redhat-linux')
                        and server_group_type = LOOKUP_SG_TYPE('bootstrap_entitled'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type)
  select LOOKUP_SERVER_ARCH('ppc64-redhat-linux'), LOOKUP_SG_TYPE('bootstrap_entitled') from dual
   where not exists (select 1 from rhnServerServerGroupArchCompat
                      where server_arch_id = LOOKUP_SERVER_ARCH('ppc64-redhat-linux')
                        and server_group_type = LOOKUP_SG_TYPE('bootstrap_entitled'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type)
  select LOOKUP_SERVER_ARCH('ppc-redhat-linux'), LOOKUP_SG_TYPE('bootstrap_entitled') from dual
   where not exists (select 1 from rhnServerServerGroupArchCompat
                      where server_arch_id = LOOKUP_SERVER_ARCH('ppc-redhat-linux')
                        and server_group_type = LOOKUP_SG_TYPE('bootstrap_entitled'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type)
  select LOOKUP_SERVER_ARCH('pSeries-redhat-linux'), LOOKUP_SG_TYPE('bootstrap_entitled') from dual
   where not exists (select 1 from rhnServerServerGroupArchCompat
                      where server_arch_id = LOOKUP_SERVER_ARCH('pSeries-redhat-linux')
                        and server_group_type = LOOKUP_SG_TYPE('bootstrap_entitled'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type)
  select LOOKUP_SERVER_ARCH('s390-debian-linux'), LOOKUP_SG_TYPE('bootstrap_entitled') from dual
   where not exists (select 1 from rhnServerServerGroupArchCompat
                      where server_arch_id = LOOKUP_SERVER_ARCH('s390-debian-linux')
                        and server_group_type = LOOKUP_SG_TYPE('bootstrap_entitled'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type)
  select LOOKUP_SERVER_ARCH('s390-redhat-linux'), LOOKUP_SG_TYPE('bootstrap_entitled') from dual
   where not exists (select 1 from rhnServerServerGroupArchCompat
                      where server_arch_id = LOOKUP_SERVER_ARCH('s390-redhat-linux')
                        and server_group_type = LOOKUP_SG_TYPE('bootstrap_entitled'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type)
  select LOOKUP_SERVER_ARCH('s390x-redhat-linux'), LOOKUP_SG_TYPE('bootstrap_entitled') from dual
   where not exists (select 1 from rhnServerServerGroupArchCompat
                      where server_arch_id = LOOKUP_SERVER_ARCH('s390x-redhat-linux')
                        and server_group_type = LOOKUP_SG_TYPE('bootstrap_entitled'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type)
  select LOOKUP_SERVER_ARCH('sparc64-redhat-linux'), LOOKUP_SG_TYPE('bootstrap_entitled') from dual
   where not exists (select 1 from rhnServerServerGroupArchCompat
                      where server_arch_id = LOOKUP_SERVER_ARCH('sparc64-redhat-linux')
                        and server_group_type = LOOKUP_SG_TYPE('bootstrap_entitled'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type)
  select LOOKUP_SERVER_ARCH('sparc-debian-linux'), LOOKUP_SG_TYPE('bootstrap_entitled') from dual
   where not exists (select 1 from rhnServerServerGroupArchCompat
                      where server_arch_id = LOOKUP_SERVER_ARCH('sparc-debian-linux')
                        and server_group_type = LOOKUP_SG_TYPE('bootstrap_entitled'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type)
  select LOOKUP_SERVER_ARCH('sparc-redhat-linux'), LOOKUP_SG_TYPE('bootstrap_entitled') from dual
   where not exists (select 1 from rhnServerServerGroupArchCompat
                      where server_arch_id = LOOKUP_SERVER_ARCH('sparc-redhat-linux')
                        and server_group_type = LOOKUP_SG_TYPE('bootstrap_entitled'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type)
  select LOOKUP_SERVER_ARCH('sparc-sun4m-solaris'), LOOKUP_SG_TYPE('bootstrap_entitled') from dual
   where not exists (select 1 from rhnServerServerGroupArchCompat
                      where server_arch_id = LOOKUP_SERVER_ARCH('sparc-sun4m-solaris')
                        and server_group_type = LOOKUP_SG_TYPE('bootstrap_entitled'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type)
  select LOOKUP_SERVER_ARCH('sparc-sun4u-solaris'), LOOKUP_SG_TYPE('bootstrap_entitled') from dual
   where not exists (select 1 from rhnServerServerGroupArchCompat
                      where server_arch_id = LOOKUP_SERVER_ARCH('sparc-sun4u-solaris')
                        and server_group_type = LOOKUP_SG_TYPE('bootstrap_entitled'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type)
  select LOOKUP_SERVER_ARCH('sparc-sun4v-solaris'), LOOKUP_SG_TYPE('bootstrap_entitled') from dual
   where not exists (select 1 from rhnServerServerGroupArchCompat
                      where server_arch_id = LOOKUP_SERVER_ARCH('sparc-sun4v-solaris')
                        and server_group_type = LOOKUP_SG_TYPE('bootstrap_entitled'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type)
  select LOOKUP_SERVER_ARCH('sparcv9-redhat-linux'), LOOKUP_SG_TYPE('bootstrap_entitled') from dual
   where not exists (select 1 from rhnServerServerGroupArchCompat
                      where server_arch_id = LOOKUP_SERVER_ARCH('sparcv9-redhat-linux')
                        and server_group_type = LOOKUP_SG_TYPE('bootstrap_entitled'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type)
  select LOOKUP_SERVER_ARCH('x86_64-redhat-linux'), LOOKUP_SG_TYPE('bootstrap_entitled') from dual
   where not exists (select 1 from rhnServerServerGroupArchCompat
                      where server_arch_id = LOOKUP_SERVER_ARCH('x86_64-redhat-linux')
                        and server_group_type = LOOKUP_SG_TYPE('bootstrap_entitled'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type)
  select LOOKUP_SERVER_ARCH('aarch64-redhat-linux'), LOOKUP_SG_TYPE('enterprise_entitled') from dual
   where not exists (select 1 from rhnServerServerGroupArchCompat
                      where server_arch_id = LOOKUP_SERVER_ARCH('aarch64-redhat-linux')
                        and server_group_type = LOOKUP_SG_TYPE('enterprise_entitled'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type)
  select LOOKUP_SERVER_ARCH('alpha-debian-linux'), LOOKUP_SG_TYPE('enterprise_entitled') from dual
   where not exists (select 1 from rhnServerServerGroupArchCompat
                      where server_arch_id = LOOKUP_SERVER_ARCH('alpha-debian-linux')
                        and server_group_type = LOOKUP_SG_TYPE('enterprise_entitled'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type)
  select LOOKUP_SERVER_ARCH('alphaev6-redhat-linux'), LOOKUP_SG_TYPE('enterprise_entitled') from dual
   where not exists (select 1 from rhnServerServerGroupArchCompat
                      where server_arch_id = LOOKUP_SERVER_ARCH('alphaev6-redhat-linux')
                        and server_group_type = LOOKUP_SG_TYPE('enterprise_entitled'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type)
  select LOOKUP_SERVER_ARCH('alpha-redhat-linux'), LOOKUP_SG_TYPE('enterprise_entitled') from dual
   where not exists (select 1 from rhnServerServerGroupArchCompat
                      where server_arch_id = LOOKUP_SERVER_ARCH('alpha-redhat-linux')
                        and server_group_type = LOOKUP_SG_TYPE('enterprise_entitled'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type)
  select LOOKUP_SERVER_ARCH('amd64-debian-linux'), LOOKUP_SG_TYPE('enterprise_entitled') from dual
   where not exists (select 1 from rhnServerServerGroupArchCompat
                      where server_arch_id = LOOKUP_SERVER_ARCH('amd64-debian-linux')
                        and server_group_type = LOOKUP_SG_TYPE('enterprise_entitled'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type)
  select LOOKUP_SERVER_ARCH('amd64-redhat-linux'), LOOKUP_SG_TYPE('enterprise_entitled') from dual
   where not exists (select 1 from rhnServerServerGroupArchCompat
                      where server_arch_id = LOOKUP_SERVER_ARCH('amd64-redhat-linux')
                        and server_group_type = LOOKUP_SG_TYPE('enterprise_entitled'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type)
  select LOOKUP_SERVER_ARCH('arm-debian-linux'), LOOKUP_SG_TYPE('enterprise_entitled') from dual
   where not exists (select 1 from rhnServerServerGroupArchCompat
                      where server_arch_id = LOOKUP_SERVER_ARCH('arm-debian-linux')
                        and server_group_type = LOOKUP_SG_TYPE('enterprise_entitled'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type)
  select LOOKUP_SERVER_ARCH('armv5tejl-redhat-linux'), LOOKUP_SG_TYPE('enterprise_entitled') from dual
   where not exists (select 1 from rhnServerServerGroupArchCompat
                      where server_arch_id = LOOKUP_SERVER_ARCH('armv5tejl-redhat-linux')
                        and server_group_type = LOOKUP_SG_TYPE('enterprise_entitled'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type)
  select LOOKUP_SERVER_ARCH('armv6hl-redhat-linux'), LOOKUP_SG_TYPE('enterprise_entitled') from dual
   where not exists (select 1 from rhnServerServerGroupArchCompat
                      where server_arch_id = LOOKUP_SERVER_ARCH('armv6hl-redhat-linux')
                        and server_group_type = LOOKUP_SG_TYPE('enterprise_entitled'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type)
  select LOOKUP_SERVER_ARCH('armv6l-debian-linux'), LOOKUP_SG_TYPE('enterprise_entitled') from dual
   where not exists (select 1 from rhnServerServerGroupArchCompat
                      where server_arch_id = LOOKUP_SERVER_ARCH('armv6l-debian-linux')
                        and server_group_type = LOOKUP_SG_TYPE('enterprise_entitled'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type)
  select LOOKUP_SERVER_ARCH('armv6l-redhat-linux'), LOOKUP_SG_TYPE('enterprise_entitled') from dual
   where not exists (select 1 from rhnServerServerGroupArchCompat
                      where server_arch_id = LOOKUP_SERVER_ARCH('armv6l-redhat-linux')
                        and server_group_type = LOOKUP_SG_TYPE('enterprise_entitled'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type)
  select LOOKUP_SERVER_ARCH('armv7l-debian-linux'), LOOKUP_SG_TYPE('enterprise_entitled') from dual
   where not exists (select 1 from rhnServerServerGroupArchCompat
                      where server_arch_id = LOOKUP_SERVER_ARCH('armv7l-debian-linux')
                        and server_group_type = LOOKUP_SG_TYPE('enterprise_entitled'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type)
  select LOOKUP_SERVER_ARCH('armv7l-redhat-linux'), LOOKUP_SG_TYPE('enterprise_entitled') from dual
   where not exists (select 1 from rhnServerServerGroupArchCompat
                      where server_arch_id = LOOKUP_SERVER_ARCH('armv7l-redhat-linux')
                        and server_group_type = LOOKUP_SG_TYPE('enterprise_entitled'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type)
  select LOOKUP_SERVER_ARCH('athlon-redhat-linux'), LOOKUP_SG_TYPE('enterprise_entitled') from dual
   where not exists (select 1 from rhnServerServerGroupArchCompat
                      where server_arch_id = LOOKUP_SERVER_ARCH('athlon-redhat-linux')
                        and server_group_type = LOOKUP_SG_TYPE('enterprise_entitled'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type)
  select LOOKUP_SERVER_ARCH('i386-debian-linux'), LOOKUP_SG_TYPE('enterprise_entitled') from dual
   where not exists (select 1 from rhnServerServerGroupArchCompat
                      where server_arch_id = LOOKUP_SERVER_ARCH('i386-debian-linux')
                        and server_group_type = LOOKUP_SG_TYPE('enterprise_entitled'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type)
  select LOOKUP_SERVER_ARCH('i386-i86pc-solaris'), LOOKUP_SG_TYPE('enterprise_entitled') from dual
   where not exists (select 1 from rhnServerServerGroupArchCompat
                      where server_arch_id = LOOKUP_SERVER_ARCH('i386-i86pc-solaris')
                        and server_group_type = LOOKUP_SG_TYPE('enterprise_entitled'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type)
  select LOOKUP_SERVER_ARCH('i386-redhat-linux'), LOOKUP_SG_TYPE('enterprise_entitled') from dual
   where not exists (select 1 from rhnServerServerGroupArchCompat
                      where server_arch_id = LOOKUP_SERVER_ARCH('i386-redhat-linux')
                        and server_group_type = LOOKUP_SG_TYPE('enterprise_entitled'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type)
  select LOOKUP_SERVER_ARCH('i486-redhat-linux'), LOOKUP_SG_TYPE('enterprise_entitled') from dual
   where not exists (select 1 from rhnServerServerGroupArchCompat
                      where server_arch_id = LOOKUP_SERVER_ARCH('i486-redhat-linux')
                        and server_group_type = LOOKUP_SG_TYPE('enterprise_entitled'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type)
  select LOOKUP_SERVER_ARCH('i586-redhat-linux'), LOOKUP_SG_TYPE('enterprise_entitled') from dual
   where not exists (select 1 from rhnServerServerGroupArchCompat
                      where server_arch_id = LOOKUP_SERVER_ARCH('i586-redhat-linux')
                        and server_group_type = LOOKUP_SG_TYPE('enterprise_entitled'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type)
  select LOOKUP_SERVER_ARCH('i686-redhat-linux'), LOOKUP_SG_TYPE('enterprise_entitled') from dual
   where not exists (select 1 from rhnServerServerGroupArchCompat
                      where server_arch_id = LOOKUP_SERVER_ARCH('i686-redhat-linux')
                        and server_group_type = LOOKUP_SG_TYPE('enterprise_entitled'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type)
  select LOOKUP_SERVER_ARCH('ia32e-redhat-linux'), LOOKUP_SG_TYPE('enterprise_entitled') from dual
   where not exists (select 1 from rhnServerServerGroupArchCompat
                      where server_arch_id = LOOKUP_SERVER_ARCH('ia32e-redhat-linux')
                        and server_group_type = LOOKUP_SG_TYPE('enterprise_entitled'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type)
  select LOOKUP_SERVER_ARCH('ia64-debian-linux'), LOOKUP_SG_TYPE('enterprise_entitled') from dual
   where not exists (select 1 from rhnServerServerGroupArchCompat
                      where server_arch_id = LOOKUP_SERVER_ARCH('ia64-debian-linux')
                        and server_group_type = LOOKUP_SG_TYPE('enterprise_entitled'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type)
  select LOOKUP_SERVER_ARCH('ia64-redhat-linux'), LOOKUP_SG_TYPE('enterprise_entitled') from dual
   where not exists (select 1 from rhnServerServerGroupArchCompat
                      where server_arch_id = LOOKUP_SERVER_ARCH('ia64-redhat-linux')
                        and server_group_type = LOOKUP_SG_TYPE('enterprise_entitled'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type)
  select LOOKUP_SERVER_ARCH('iSeries-redhat-linux'), LOOKUP_SG_TYPE('enterprise_entitled') from dual
   where not exists (select 1 from rhnServerServerGroupArchCompat
                      where server_arch_id = LOOKUP_SERVER_ARCH('iSeries-redhat-linux')
                        and server_group_type = LOOKUP_SG_TYPE('enterprise_entitled'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type)
  select LOOKUP_SERVER_ARCH('mips-debian-linux'), LOOKUP_SG_TYPE('enterprise_entitled') from dual
   where not exists (select 1 from rhnServerServerGroupArchCompat
                      where server_arch_id = LOOKUP_SERVER_ARCH('mips-debian-linux')
                        and server_group_type = LOOKUP_SG_TYPE('enterprise_entitled'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type)
  select LOOKUP_SERVER_ARCH('powerpc-debian-linux'), LOOKUP_SG_TYPE('enterprise_entitled') from dual
   where not exists (select 1 from rhnServerServerGroupArchCompat
                      where server_arch_id = LOOKUP_SERVER_ARCH('powerpc-debian-linux')
                        and server_group_type = LOOKUP_SG_TYPE('enterprise_entitled'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type)
  select LOOKUP_SERVER_ARCH('ppc64iseries-redhat-linux'), LOOKUP_SG_TYPE('enterprise_entitled') from dual
   where not exists (select 1 from rhnServerServerGroupArchCompat
                      where server_arch_id = LOOKUP_SERVER_ARCH('ppc64iseries-redhat-linux')
                        and server_group_type = LOOKUP_SG_TYPE('enterprise_entitled'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type)
  select LOOKUP_SERVER_ARCH('ppc64le-redhat-linux'), LOOKUP_SG_TYPE('enterprise_entitled') from dual
   where not exists (select 1 from rhnServerServerGroupArchCompat
                      where server_arch_id = LOOKUP_SERVER_ARCH('ppc64le-redhat-linux')
                        and server_group_type = LOOKUP_SG_TYPE('enterprise_entitled'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type)
  select LOOKUP_SERVER_ARCH('ppc64pseries-redhat-linux'), LOOKUP_SG_TYPE('enterprise_entitled') from dual
   where not exists (select 1 from rhnServerServerGroupArchCompat
                      where server_arch_id = LOOKUP_SERVER_ARCH('ppc64pseries-redhat-linux')
                        and server_group_type = LOOKUP_SG_TYPE('enterprise_entitled'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type)
  select LOOKUP_SERVER_ARCH('ppc64-redhat-linux'), LOOKUP_SG_TYPE('enterprise_entitled') from dual
   where not exists (select 1 from rhnServerServerGroupArchCompat
                      where server_arch_id = LOOKUP_SERVER_ARCH('ppc64-redhat-linux')
                        and server_group_type = LOOKUP_SG_TYPE('enterprise_entitled'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type)
  select LOOKUP_SERVER_ARCH('ppc-redhat-linux'), LOOKUP_SG_TYPE('enterprise_entitled') from dual
   where not exists (select 1 from rhnServerServerGroupArchCompat
                      where server_arch_id = LOOKUP_SERVER_ARCH('ppc-redhat-linux')
                        and server_group_type = LOOKUP_SG_TYPE('enterprise_entitled'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type)
  select LOOKUP_SERVER_ARCH('pSeries-redhat-linux'), LOOKUP_SG_TYPE('enterprise_entitled') from dual
   where not exists (select 1 from rhnServerServerGroupArchCompat
                      where server_arch_id = LOOKUP_SERVER_ARCH('pSeries-redhat-linux')
                        and server_group_type = LOOKUP_SG_TYPE('enterprise_entitled'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type)
  select LOOKUP_SERVER_ARCH('s390-debian-linux'), LOOKUP_SG_TYPE('enterprise_entitled') from dual
   where not exists (select 1 from rhnServerServerGroupArchCompat
                      where server_arch_id = LOOKUP_SERVER_ARCH('s390-debian-linux')
                        and server_group_type = LOOKUP_SG_TYPE('enterprise_entitled'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type)
  select LOOKUP_SERVER_ARCH('s390-redhat-linux'), LOOKUP_SG_TYPE('enterprise_entitled') from dual
   where not exists (select 1 from rhnServerServerGroupArchCompat
                      where server_arch_id = LOOKUP_SERVER_ARCH('s390-redhat-linux')
                        and server_group_type = LOOKUP_SG_TYPE('enterprise_entitled'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type)
  select LOOKUP_SERVER_ARCH('s390x-redhat-linux'), LOOKUP_SG_TYPE('enterprise_entitled') from dual
   where not exists (select 1 from rhnServerServerGroupArchCompat
                      where server_arch_id = LOOKUP_SERVER_ARCH('s390x-redhat-linux')
                        and server_group_type = LOOKUP_SG_TYPE('enterprise_entitled'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type)
  select LOOKUP_SERVER_ARCH('sparc64-redhat-linux'), LOOKUP_SG_TYPE('enterprise_entitled') from dual
   where not exists (select 1 from rhnServerServerGroupArchCompat
                      where server_arch_id = LOOKUP_SERVER_ARCH('sparc64-redhat-linux')
                        and server_group_type = LOOKUP_SG_TYPE('enterprise_entitled'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type)
  select LOOKUP_SERVER_ARCH('sparc-debian-linux'), LOOKUP_SG_TYPE('enterprise_entitled') from dual
   where not exists (select 1 from rhnServerServerGroupArchCompat
                      where server_arch_id = LOOKUP_SERVER_ARCH('sparc-debian-linux')
                        and server_group_type = LOOKUP_SG_TYPE('enterprise_entitled'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type)
  select LOOKUP_SERVER_ARCH('sparc-redhat-linux'), LOOKUP_SG_TYPE('enterprise_entitled') from dual
   where not exists (select 1 from rhnServerServerGroupArchCompat
                      where server_arch_id = LOOKUP_SERVER_ARCH('sparc-redhat-linux')
                        and server_group_type = LOOKUP_SG_TYPE('enterprise_entitled'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type)
  select LOOKUP_SERVER_ARCH('sparc-sun4m-solaris'), LOOKUP_SG_TYPE('enterprise_entitled') from dual
   where not exists (select 1 from rhnServerServerGroupArchCompat
                      where server_arch_id = LOOKUP_SERVER_ARCH('sparc-sun4m-solaris')
                        and server_group_type = LOOKUP_SG_TYPE('enterprise_entitled'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type)
  select LOOKUP_SERVER_ARCH('sparc-sun4u-solaris'), LOOKUP_SG_TYPE('enterprise_entitled') from dual
   where not exists (select 1 from rhnServerServerGroupArchCompat
                      where server_arch_id = LOOKUP_SERVER_ARCH('sparc-sun4u-solaris')
                        and server_group_type = LOOKUP_SG_TYPE('enterprise_entitled'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type)
  select LOOKUP_SERVER_ARCH('sparc-sun4v-solaris'), LOOKUP_SG_TYPE('enterprise_entitled') from dual
   where not exists (select 1 from rhnServerServerGroupArchCompat
                      where server_arch_id = LOOKUP_SERVER_ARCH('sparc-sun4v-solaris')
                        and server_group_type = LOOKUP_SG_TYPE('enterprise_entitled'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type)
  select LOOKUP_SERVER_ARCH('sparcv9-redhat-linux'), LOOKUP_SG_TYPE('enterprise_entitled') from dual
   where not exists (select 1 from rhnServerServerGroupArchCompat
                      where server_arch_id = LOOKUP_SERVER_ARCH('sparcv9-redhat-linux')
                        and server_group_type = LOOKUP_SG_TYPE('enterprise_entitled'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type)
  select LOOKUP_SERVER_ARCH('x86_64-redhat-linux'), LOOKUP_SG_TYPE('enterprise_entitled') from dual
   where not exists (select 1 from rhnServerServerGroupArchCompat
                      where server_arch_id = LOOKUP_SERVER_ARCH('x86_64-redhat-linux')
                        and server_group_type = LOOKUP_SG_TYPE('enterprise_entitled'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type)
  select LOOKUP_SERVER_ARCH('aarch64-redhat-linux'), LOOKUP_SG_TYPE('foreign_entitled') from dual
   where not exists (select 1 from rhnServerServerGroupArchCompat
                      where server_arch_id = LOOKUP_SERVER_ARCH('aarch64-redhat-linux')
                        and server_group_type = LOOKUP_SG_TYPE('foreign_entitled'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type)
  select LOOKUP_SERVER_ARCH('alpha-debian-linux'), LOOKUP_SG_TYPE('foreign_entitled') from dual
   where not exists (select 1 from rhnServerServerGroupArchCompat
                      where server_arch_id = LOOKUP_SERVER_ARCH('alpha-debian-linux')
                        and server_group_type = LOOKUP_SG_TYPE('foreign_entitled'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type)
  select LOOKUP_SERVER_ARCH('alphaev6-redhat-linux'), LOOKUP_SG_TYPE('foreign_entitled') from dual
   where not exists (select 1 from rhnServerServerGroupArchCompat
                      where server_arch_id = LOOKUP_SERVER_ARCH('alphaev6-redhat-linux')
                        and server_group_type = LOOKUP_SG_TYPE('foreign_entitled'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type)
  select LOOKUP_SERVER_ARCH('alpha-redhat-linux'), LOOKUP_SG_TYPE('foreign_entitled') from dual
   where not exists (select 1 from rhnServerServerGroupArchCompat
                      where server_arch_id = LOOKUP_SERVER_ARCH('alpha-redhat-linux')
                        and server_group_type = LOOKUP_SG_TYPE('foreign_entitled'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type)
  select LOOKUP_SERVER_ARCH('amd64-debian-linux'), LOOKUP_SG_TYPE('foreign_entitled') from dual
   where not exists (select 1 from rhnServerServerGroupArchCompat
                      where server_arch_id = LOOKUP_SERVER_ARCH('amd64-debian-linux')
                        and server_group_type = LOOKUP_SG_TYPE('foreign_entitled'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type)
  select LOOKUP_SERVER_ARCH('amd64-redhat-linux'), LOOKUP_SG_TYPE('foreign_entitled') from dual
   where not exists (select 1 from rhnServerServerGroupArchCompat
                      where server_arch_id = LOOKUP_SERVER_ARCH('amd64-redhat-linux')
                        and server_group_type = LOOKUP_SG_TYPE('foreign_entitled'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type)
  select LOOKUP_SERVER_ARCH('arm-debian-linux'), LOOKUP_SG_TYPE('foreign_entitled') from dual
   where not exists (select 1 from rhnServerServerGroupArchCompat
                      where server_arch_id = LOOKUP_SERVER_ARCH('arm-debian-linux')
                        and server_group_type = LOOKUP_SG_TYPE('foreign_entitled'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type)
  select LOOKUP_SERVER_ARCH('armv5tejl-redhat-linux'), LOOKUP_SG_TYPE('foreign_entitled') from dual
   where not exists (select 1 from rhnServerServerGroupArchCompat
                      where server_arch_id = LOOKUP_SERVER_ARCH('armv5tejl-redhat-linux')
                        and server_group_type = LOOKUP_SG_TYPE('foreign_entitled'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type)
  select LOOKUP_SERVER_ARCH('armv6hl-redhat-linux'), LOOKUP_SG_TYPE('foreign_entitled') from dual
   where not exists (select 1 from rhnServerServerGroupArchCompat
                      where server_arch_id = LOOKUP_SERVER_ARCH('armv6hl-redhat-linux')
                        and server_group_type = LOOKUP_SG_TYPE('foreign_entitled'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type)
  select LOOKUP_SERVER_ARCH('armv6l-debian-linux'), LOOKUP_SG_TYPE('foreign_entitled') from dual
   where not exists (select 1 from rhnServerServerGroupArchCompat
                      where server_arch_id = LOOKUP_SERVER_ARCH('armv6l-debian-linux')
                        and server_group_type = LOOKUP_SG_TYPE('foreign_entitled'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type)
  select LOOKUP_SERVER_ARCH('armv6l-redhat-linux'), LOOKUP_SG_TYPE('foreign_entitled') from dual
   where not exists (select 1 from rhnServerServerGroupArchCompat
                      where server_arch_id = LOOKUP_SERVER_ARCH('armv6l-redhat-linux')
                        and server_group_type = LOOKUP_SG_TYPE('foreign_entitled'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type)
  select LOOKUP_SERVER_ARCH('armv7l-redhat-linux'), LOOKUP_SG_TYPE('foreign_entitled') from dual
   where not exists (select 1 from rhnServerServerGroupArchCompat
                      where server_arch_id = LOOKUP_SERVER_ARCH('armv7l-redhat-linux')
                        and server_group_type = LOOKUP_SG_TYPE('foreign_entitled'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type)
  select LOOKUP_SERVER_ARCH('athlon-redhat-linux'), LOOKUP_SG_TYPE('foreign_entitled') from dual
   where not exists (select 1 from rhnServerServerGroupArchCompat
                      where server_arch_id = LOOKUP_SERVER_ARCH('athlon-redhat-linux')
                        and server_group_type = LOOKUP_SG_TYPE('foreign_entitled'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type)
  select LOOKUP_SERVER_ARCH('i386-debian-linux'), LOOKUP_SG_TYPE('foreign_entitled') from dual
   where not exists (select 1 from rhnServerServerGroupArchCompat
                      where server_arch_id = LOOKUP_SERVER_ARCH('i386-debian-linux')
                        and server_group_type = LOOKUP_SG_TYPE('foreign_entitled'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type)
  select LOOKUP_SERVER_ARCH('i386-i86pc-solaris'), LOOKUP_SG_TYPE('foreign_entitled') from dual
   where not exists (select 1 from rhnServerServerGroupArchCompat
                      where server_arch_id = LOOKUP_SERVER_ARCH('i386-i86pc-solaris')
                        and server_group_type = LOOKUP_SG_TYPE('foreign_entitled'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type)
  select LOOKUP_SERVER_ARCH('i386-redhat-linux'), LOOKUP_SG_TYPE('foreign_entitled') from dual
   where not exists (select 1 from rhnServerServerGroupArchCompat
                      where server_arch_id = LOOKUP_SERVER_ARCH('i386-redhat-linux')
                        and server_group_type = LOOKUP_SG_TYPE('foreign_entitled'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type)
  select LOOKUP_SERVER_ARCH('i486-redhat-linux'), LOOKUP_SG_TYPE('foreign_entitled') from dual
   where not exists (select 1 from rhnServerServerGroupArchCompat
                      where server_arch_id = LOOKUP_SERVER_ARCH('i486-redhat-linux')
                        and server_group_type = LOOKUP_SG_TYPE('foreign_entitled'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type)
  select LOOKUP_SERVER_ARCH('i586-redhat-linux'), LOOKUP_SG_TYPE('foreign_entitled') from dual
   where not exists (select 1 from rhnServerServerGroupArchCompat
                      where server_arch_id = LOOKUP_SERVER_ARCH('i586-redhat-linux')
                        and server_group_type = LOOKUP_SG_TYPE('foreign_entitled'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type)
  select LOOKUP_SERVER_ARCH('i686-redhat-linux'), LOOKUP_SG_TYPE('foreign_entitled') from dual
   where not exists (select 1 from rhnServerServerGroupArchCompat
                      where server_arch_id = LOOKUP_SERVER_ARCH('i686-redhat-linux')
                        and server_group_type = LOOKUP_SG_TYPE('foreign_entitled'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type)
  select LOOKUP_SERVER_ARCH('ia32e-redhat-linux'), LOOKUP_SG_TYPE('foreign_entitled') from dual
   where not exists (select 1 from rhnServerServerGroupArchCompat
                      where server_arch_id = LOOKUP_SERVER_ARCH('ia32e-redhat-linux')
                        and server_group_type = LOOKUP_SG_TYPE('foreign_entitled'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type)
  select LOOKUP_SERVER_ARCH('ia64-debian-linux'), LOOKUP_SG_TYPE('foreign_entitled') from dual
   where not exists (select 1 from rhnServerServerGroupArchCompat
                      where server_arch_id = LOOKUP_SERVER_ARCH('ia64-debian-linux')
                        and server_group_type = LOOKUP_SG_TYPE('foreign_entitled'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type)
  select LOOKUP_SERVER_ARCH('ia64-redhat-linux'), LOOKUP_SG_TYPE('foreign_entitled') from dual
   where not exists (select 1 from rhnServerServerGroupArchCompat
                      where server_arch_id = LOOKUP_SERVER_ARCH('ia64-redhat-linux')
                        and server_group_type = LOOKUP_SG_TYPE('foreign_entitled'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type)
  select LOOKUP_SERVER_ARCH('iSeries-redhat-linux'), LOOKUP_SG_TYPE('foreign_entitled') from dual
   where not exists (select 1 from rhnServerServerGroupArchCompat
                      where server_arch_id = LOOKUP_SERVER_ARCH('iSeries-redhat-linux')
                        and server_group_type = LOOKUP_SG_TYPE('foreign_entitled'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type)
  select LOOKUP_SERVER_ARCH('mips-debian-linux'), LOOKUP_SG_TYPE('foreign_entitled') from dual
   where not exists (select 1 from rhnServerServerGroupArchCompat
                      where server_arch_id = LOOKUP_SERVER_ARCH('mips-debian-linux')
                        and server_group_type = LOOKUP_SG_TYPE('foreign_entitled'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type)
  select LOOKUP_SERVER_ARCH('powerpc-debian-linux'), LOOKUP_SG_TYPE('foreign_entitled') from dual
   where not exists (select 1 from rhnServerServerGroupArchCompat
                      where server_arch_id = LOOKUP_SERVER_ARCH('powerpc-debian-linux')
                        and server_group_type = LOOKUP_SG_TYPE('foreign_entitled'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type)
  select LOOKUP_SERVER_ARCH('ppc64iseries-redhat-linux'), LOOKUP_SG_TYPE('foreign_entitled') from dual
   where not exists (select 1 from rhnServerServerGroupArchCompat
                      where server_arch_id = LOOKUP_SERVER_ARCH('ppc64iseries-redhat-linux')
                        and server_group_type = LOOKUP_SG_TYPE('foreign_entitled'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type)
  select LOOKUP_SERVER_ARCH('ppc64le-redhat-linux'), LOOKUP_SG_TYPE('foreign_entitled') from dual
   where not exists (select 1 from rhnServerServerGroupArchCompat
                      where server_arch_id = LOOKUP_SERVER_ARCH('ppc64le-redhat-linux')
                        and server_group_type = LOOKUP_SG_TYPE('foreign_entitled'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type)
  select LOOKUP_SERVER_ARCH('ppc64pseries-redhat-linux'), LOOKUP_SG_TYPE('foreign_entitled') from dual
   where not exists (select 1 from rhnServerServerGroupArchCompat
                      where server_arch_id = LOOKUP_SERVER_ARCH('ppc64pseries-redhat-linux')
                        and server_group_type = LOOKUP_SG_TYPE('foreign_entitled'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type)
  select LOOKUP_SERVER_ARCH('ppc64-redhat-linux'), LOOKUP_SG_TYPE('foreign_entitled') from dual
   where not exists (select 1 from rhnServerServerGroupArchCompat
                      where server_arch_id = LOOKUP_SERVER_ARCH('ppc64-redhat-linux')
                        and server_group_type = LOOKUP_SG_TYPE('foreign_entitled'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type)
  select LOOKUP_SERVER_ARCH('ppc-redhat-linux'), LOOKUP_SG_TYPE('foreign_entitled') from dual
   where not exists (select 1 from rhnServerServerGroupArchCompat
                      where server_arch_id = LOOKUP_SERVER_ARCH('ppc-redhat-linux')
                        and server_group_type = LOOKUP_SG_TYPE('foreign_entitled'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type)
  select LOOKUP_SERVER_ARCH('pSeries-redhat-linux'), LOOKUP_SG_TYPE('foreign_entitled') from dual
   where not exists (select 1 from rhnServerServerGroupArchCompat
                      where server_arch_id = LOOKUP_SERVER_ARCH('pSeries-redhat-linux')
                        and server_group_type = LOOKUP_SG_TYPE('foreign_entitled'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type)
  select LOOKUP_SERVER_ARCH('s390-debian-linux'), LOOKUP_SG_TYPE('foreign_entitled') from dual
   where not exists (select 1 from rhnServerServerGroupArchCompat
                      where server_arch_id = LOOKUP_SERVER_ARCH('s390-debian-linux')
                        and server_group_type = LOOKUP_SG_TYPE('foreign_entitled'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type)
  select LOOKUP_SERVER_ARCH('s390-redhat-linux'), LOOKUP_SG_TYPE('foreign_entitled') from dual
   where not exists (select 1 from rhnServerServerGroupArchCompat
                      where server_arch_id = LOOKUP_SERVER_ARCH('s390-redhat-linux')
                        and server_group_type = LOOKUP_SG_TYPE('foreign_entitled'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type)
  select LOOKUP_SERVER_ARCH('s390x-redhat-linux'), LOOKUP_SG_TYPE('foreign_entitled') from dual
   where not exists (select 1 from rhnServerServerGroupArchCompat
                      where server_arch_id = LOOKUP_SERVER_ARCH('s390x-redhat-linux')
                        and server_group_type = LOOKUP_SG_TYPE('foreign_entitled'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type)
  select LOOKUP_SERVER_ARCH('sparc64-redhat-linux'), LOOKUP_SG_TYPE('foreign_entitled') from dual
   where not exists (select 1 from rhnServerServerGroupArchCompat
                      where server_arch_id = LOOKUP_SERVER_ARCH('sparc64-redhat-linux')
                        and server_group_type = LOOKUP_SG_TYPE('foreign_entitled'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type)
  select LOOKUP_SERVER_ARCH('sparc-debian-linux'), LOOKUP_SG_TYPE('foreign_entitled') from dual
   where not exists (select 1 from rhnServerServerGroupArchCompat
                      where server_arch_id = LOOKUP_SERVER_ARCH('sparc-debian-linux')
                        and server_group_type = LOOKUP_SG_TYPE('foreign_entitled'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type)
  select LOOKUP_SERVER_ARCH('sparc-redhat-linux'), LOOKUP_SG_TYPE('foreign_entitled') from dual
   where not exists (select 1 from rhnServerServerGroupArchCompat
                      where server_arch_id = LOOKUP_SERVER_ARCH('sparc-redhat-linux')
                        and server_group_type = LOOKUP_SG_TYPE('foreign_entitled'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type)
  select LOOKUP_SERVER_ARCH('sparc-sun4m-solaris'), LOOKUP_SG_TYPE('foreign_entitled') from dual
   where not exists (select 1 from rhnServerServerGroupArchCompat
                      where server_arch_id = LOOKUP_SERVER_ARCH('sparc-sun4m-solaris')
                        and server_group_type = LOOKUP_SG_TYPE('foreign_entitled'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type)
  select LOOKUP_SERVER_ARCH('sparc-sun4u-solaris'), LOOKUP_SG_TYPE('foreign_entitled') from dual
   where not exists (select 1 from rhnServerServerGroupArchCompat
                      where server_arch_id = LOOKUP_SERVER_ARCH('sparc-sun4u-solaris')
                        and server_group_type = LOOKUP_SG_TYPE('foreign_entitled'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type)
  select LOOKUP_SERVER_ARCH('sparc-sun4v-solaris'), LOOKUP_SG_TYPE('foreign_entitled') from dual
   where not exists (select 1 from rhnServerServerGroupArchCompat
                      where server_arch_id = LOOKUP_SERVER_ARCH('sparc-sun4v-solaris')
                        and server_group_type = LOOKUP_SG_TYPE('foreign_entitled'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type)
  select LOOKUP_SERVER_ARCH('sparcv9-redhat-linux'), LOOKUP_SG_TYPE('foreign_entitled') from dual
   where not exists (select 1 from rhnServerServerGroupArchCompat
                      where server_arch_id = LOOKUP_SERVER_ARCH('sparcv9-redhat-linux')
                        and server_group_type = LOOKUP_SG_TYPE('foreign_entitled'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type)
  select LOOKUP_SERVER_ARCH('x86_64-redhat-linux'), LOOKUP_SG_TYPE('foreign_entitled') from dual
   where not exists (select 1 from rhnServerServerGroupArchCompat
                      where server_arch_id = LOOKUP_SERVER_ARCH('x86_64-redhat-linux')
                        and server_group_type = LOOKUP_SG_TYPE('foreign_entitled'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type)
  select LOOKUP_SERVER_ARCH('aarch64-redhat-linux'), LOOKUP_SG_TYPE('salt_entitled') from dual
   where not exists (select 1 from rhnServerServerGroupArchCompat
                      where server_arch_id = LOOKUP_SERVER_ARCH('aarch64-redhat-linux')
                        and server_group_type = LOOKUP_SG_TYPE('salt_entitled'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type)
  select LOOKUP_SERVER_ARCH('alpha-debian-linux'), LOOKUP_SG_TYPE('salt_entitled') from dual
   where not exists (select 1 from rhnServerServerGroupArchCompat
                      where server_arch_id = LOOKUP_SERVER_ARCH('alpha-debian-linux')
                        and server_group_type = LOOKUP_SG_TYPE('salt_entitled'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type)
  select LOOKUP_SERVER_ARCH('alphaev6-redhat-linux'), LOOKUP_SG_TYPE('salt_entitled') from dual
   where not exists (select 1 from rhnServerServerGroupArchCompat
                      where server_arch_id = LOOKUP_SERVER_ARCH('alphaev6-redhat-linux')
                        and server_group_type = LOOKUP_SG_TYPE('salt_entitled'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type)
  select LOOKUP_SERVER_ARCH('alpha-redhat-linux'), LOOKUP_SG_TYPE('salt_entitled') from dual
   where not exists (select 1 from rhnServerServerGroupArchCompat
                      where server_arch_id = LOOKUP_SERVER_ARCH('alpha-redhat-linux')
                        and server_group_type = LOOKUP_SG_TYPE('salt_entitled'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type)
  select LOOKUP_SERVER_ARCH('amd64-debian-linux'), LOOKUP_SG_TYPE('salt_entitled') from dual
   where not exists (select 1 from rhnServerServerGroupArchCompat
                      where server_arch_id = LOOKUP_SERVER_ARCH('amd64-debian-linux')
                        and server_group_type = LOOKUP_SG_TYPE('salt_entitled'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type)
  select LOOKUP_SERVER_ARCH('amd64-redhat-linux'), LOOKUP_SG_TYPE('salt_entitled') from dual
   where not exists (select 1 from rhnServerServerGroupArchCompat
                      where server_arch_id = LOOKUP_SERVER_ARCH('amd64-redhat-linux')
                        and server_group_type = LOOKUP_SG_TYPE('salt_entitled'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type)
  select LOOKUP_SERVER_ARCH('arm-debian-linux'), LOOKUP_SG_TYPE('salt_entitled') from dual
   where not exists (select 1 from rhnServerServerGroupArchCompat
                      where server_arch_id = LOOKUP_SERVER_ARCH('arm-debian-linux')
                        and server_group_type = LOOKUP_SG_TYPE('salt_entitled'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type)
  select LOOKUP_SERVER_ARCH('armv5tejl-redhat-linux'), LOOKUP_SG_TYPE('salt_entitled') from dual
   where not exists (select 1 from rhnServerServerGroupArchCompat
                      where server_arch_id = LOOKUP_SERVER_ARCH('armv5tejl-redhat-linux')
                        and server_group_type = LOOKUP_SG_TYPE('salt_entitled'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type)
  select LOOKUP_SERVER_ARCH('armv6hl-redhat-linux'), LOOKUP_SG_TYPE('salt_entitled') from dual
   where not exists (select 1 from rhnServerServerGroupArchCompat
                      where server_arch_id = LOOKUP_SERVER_ARCH('armv6hl-redhat-linux')
                        and server_group_type = LOOKUP_SG_TYPE('salt_entitled'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type)
  select LOOKUP_SERVER_ARCH('armv6l-debian-linux'), LOOKUP_SG_TYPE('salt_entitled') from dual
   where not exists (select 1 from rhnServerServerGroupArchCompat
                      where server_arch_id = LOOKUP_SERVER_ARCH('armv6l-debian-linux')
                        and server_group_type = LOOKUP_SG_TYPE('salt_entitled'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type)
  select LOOKUP_SERVER_ARCH('armv6l-redhat-linux'), LOOKUP_SG_TYPE('salt_entitled') from dual
   where not exists (select 1 from rhnServerServerGroupArchCompat
                      where server_arch_id = LOOKUP_SERVER_ARCH('armv6l-redhat-linux')
                        and server_group_type = LOOKUP_SG_TYPE('salt_entitled'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type)
  select LOOKUP_SERVER_ARCH('armv7l-redhat-linux'), LOOKUP_SG_TYPE('salt_entitled') from dual
   where not exists (select 1 from rhnServerServerGroupArchCompat
                      where server_arch_id = LOOKUP_SERVER_ARCH('armv7l-redhat-linux')
                        and server_group_type = LOOKUP_SG_TYPE('salt_entitled'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type)
  select LOOKUP_SERVER_ARCH('athlon-redhat-linux'), LOOKUP_SG_TYPE('salt_entitled') from dual
   where not exists (select 1 from rhnServerServerGroupArchCompat
                      where server_arch_id = LOOKUP_SERVER_ARCH('athlon-redhat-linux')
                        and server_group_type = LOOKUP_SG_TYPE('salt_entitled'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type)
  select LOOKUP_SERVER_ARCH('i386-debian-linux'), LOOKUP_SG_TYPE('salt_entitled') from dual
   where not exists (select 1 from rhnServerServerGroupArchCompat
                      where server_arch_id = LOOKUP_SERVER_ARCH('i386-debian-linux')
                        and server_group_type = LOOKUP_SG_TYPE('salt_entitled'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type)
  select LOOKUP_SERVER_ARCH('i386-i86pc-solaris'), LOOKUP_SG_TYPE('salt_entitled') from dual
   where not exists (select 1 from rhnServerServerGroupArchCompat
                      where server_arch_id = LOOKUP_SERVER_ARCH('i386-i86pc-solaris')
                        and server_group_type = LOOKUP_SG_TYPE('salt_entitled'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type)
  select LOOKUP_SERVER_ARCH('i386-redhat-linux'), LOOKUP_SG_TYPE('salt_entitled') from dual
   where not exists (select 1 from rhnServerServerGroupArchCompat
                      where server_arch_id = LOOKUP_SERVER_ARCH('i386-redhat-linux')
                        and server_group_type = LOOKUP_SG_TYPE('salt_entitled'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type)
  select LOOKUP_SERVER_ARCH('i486-redhat-linux'), LOOKUP_SG_TYPE('salt_entitled') from dual
   where not exists (select 1 from rhnServerServerGroupArchCompat
                      where server_arch_id = LOOKUP_SERVER_ARCH('i486-redhat-linux')
                        and server_group_type = LOOKUP_SG_TYPE('salt_entitled'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type)
  select LOOKUP_SERVER_ARCH('i586-redhat-linux'), LOOKUP_SG_TYPE('salt_entitled') from dual
   where not exists (select 1 from rhnServerServerGroupArchCompat
                      where server_arch_id = LOOKUP_SERVER_ARCH('i586-redhat-linux')
                        and server_group_type = LOOKUP_SG_TYPE('salt_entitled'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type)
  select LOOKUP_SERVER_ARCH('i686-redhat-linux'), LOOKUP_SG_TYPE('salt_entitled') from dual
   where not exists (select 1 from rhnServerServerGroupArchCompat
                      where server_arch_id = LOOKUP_SERVER_ARCH('i686-redhat-linux')
                        and server_group_type = LOOKUP_SG_TYPE('salt_entitled'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type)
  select LOOKUP_SERVER_ARCH('ia32e-redhat-linux'), LOOKUP_SG_TYPE('salt_entitled') from dual
   where not exists (select 1 from rhnServerServerGroupArchCompat
                      where server_arch_id = LOOKUP_SERVER_ARCH('ia32e-redhat-linux')
                        and server_group_type = LOOKUP_SG_TYPE('salt_entitled'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type)
  select LOOKUP_SERVER_ARCH('ia64-debian-linux'), LOOKUP_SG_TYPE('salt_entitled') from dual
   where not exists (select 1 from rhnServerServerGroupArchCompat
                      where server_arch_id = LOOKUP_SERVER_ARCH('ia64-debian-linux')
                        and server_group_type = LOOKUP_SG_TYPE('salt_entitled'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type)
  select LOOKUP_SERVER_ARCH('ia64-redhat-linux'), LOOKUP_SG_TYPE('salt_entitled') from dual
   where not exists (select 1 from rhnServerServerGroupArchCompat
                      where server_arch_id = LOOKUP_SERVER_ARCH('ia64-redhat-linux')
                        and server_group_type = LOOKUP_SG_TYPE('salt_entitled'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type)
  select LOOKUP_SERVER_ARCH('iSeries-redhat-linux'), LOOKUP_SG_TYPE('salt_entitled') from dual
   where not exists (select 1 from rhnServerServerGroupArchCompat
                      where server_arch_id = LOOKUP_SERVER_ARCH('iSeries-redhat-linux')
                        and server_group_type = LOOKUP_SG_TYPE('salt_entitled'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type)
  select LOOKUP_SERVER_ARCH('mips-debian-linux'), LOOKUP_SG_TYPE('salt_entitled') from dual
   where not exists (select 1 from rhnServerServerGroupArchCompat
                      where server_arch_id = LOOKUP_SERVER_ARCH('mips-debian-linux')
                        and server_group_type = LOOKUP_SG_TYPE('salt_entitled'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type)
  select LOOKUP_SERVER_ARCH('powerpc-debian-linux'), LOOKUP_SG_TYPE('salt_entitled') from dual
   where not exists (select 1 from rhnServerServerGroupArchCompat
                      where server_arch_id = LOOKUP_SERVER_ARCH('powerpc-debian-linux')
                        and server_group_type = LOOKUP_SG_TYPE('salt_entitled'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type)
  select LOOKUP_SERVER_ARCH('ppc64iseries-redhat-linux'), LOOKUP_SG_TYPE('salt_entitled') from dual
   where not exists (select 1 from rhnServerServerGroupArchCompat
                      where server_arch_id = LOOKUP_SERVER_ARCH('ppc64iseries-redhat-linux')
                        and server_group_type = LOOKUP_SG_TYPE('salt_entitled'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type)
  select LOOKUP_SERVER_ARCH('ppc64le-redhat-linux'), LOOKUP_SG_TYPE('salt_entitled') from dual
   where not exists (select 1 from rhnServerServerGroupArchCompat
                      where server_arch_id = LOOKUP_SERVER_ARCH('ppc64le-redhat-linux')
                        and server_group_type = LOOKUP_SG_TYPE('salt_entitled'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type)
  select LOOKUP_SERVER_ARCH('ppc64pseries-redhat-linux'), LOOKUP_SG_TYPE('salt_entitled') from dual
   where not exists (select 1 from rhnServerServerGroupArchCompat
                      where server_arch_id = LOOKUP_SERVER_ARCH('ppc64pseries-redhat-linux')
                        and server_group_type = LOOKUP_SG_TYPE('salt_entitled'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type)
  select LOOKUP_SERVER_ARCH('ppc64-redhat-linux'), LOOKUP_SG_TYPE('salt_entitled') from dual
   where not exists (select 1 from rhnServerServerGroupArchCompat
                      where server_arch_id = LOOKUP_SERVER_ARCH('ppc64-redhat-linux')
                        and server_group_type = LOOKUP_SG_TYPE('salt_entitled'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type)
  select LOOKUP_SERVER_ARCH('ppc-redhat-linux'), LOOKUP_SG_TYPE('salt_entitled') from dual
   where not exists (select 1 from rhnServerServerGroupArchCompat
                      where server_arch_id = LOOKUP_SERVER_ARCH('ppc-redhat-linux')
                        and server_group_type = LOOKUP_SG_TYPE('salt_entitled'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type)
  select LOOKUP_SERVER_ARCH('pSeries-redhat-linux'), LOOKUP_SG_TYPE('salt_entitled') from dual
   where not exists (select 1 from rhnServerServerGroupArchCompat
                      where server_arch_id = LOOKUP_SERVER_ARCH('pSeries-redhat-linux')
                        and server_group_type = LOOKUP_SG_TYPE('salt_entitled'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type)
  select LOOKUP_SERVER_ARCH('s390-debian-linux'), LOOKUP_SG_TYPE('salt_entitled') from dual
   where not exists (select 1 from rhnServerServerGroupArchCompat
                      where server_arch_id = LOOKUP_SERVER_ARCH('s390-debian-linux')
                        and server_group_type = LOOKUP_SG_TYPE('salt_entitled'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type)
  select LOOKUP_SERVER_ARCH('s390-redhat-linux'), LOOKUP_SG_TYPE('salt_entitled') from dual
   where not exists (select 1 from rhnServerServerGroupArchCompat
                      where server_arch_id = LOOKUP_SERVER_ARCH('s390-redhat-linux')
                        and server_group_type = LOOKUP_SG_TYPE('salt_entitled'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type)
  select LOOKUP_SERVER_ARCH('s390x-redhat-linux'), LOOKUP_SG_TYPE('salt_entitled') from dual
   where not exists (select 1 from rhnServerServerGroupArchCompat
                      where server_arch_id = LOOKUP_SERVER_ARCH('s390x-redhat-linux')
                        and server_group_type = LOOKUP_SG_TYPE('salt_entitled'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type)
  select LOOKUP_SERVER_ARCH('sparc64-redhat-linux'), LOOKUP_SG_TYPE('salt_entitled') from dual
   where not exists (select 1 from rhnServerServerGroupArchCompat
                      where server_arch_id = LOOKUP_SERVER_ARCH('sparc64-redhat-linux')
                        and server_group_type = LOOKUP_SG_TYPE('salt_entitled'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type)
  select LOOKUP_SERVER_ARCH('sparc-debian-linux'), LOOKUP_SG_TYPE('salt_entitled') from dual
   where not exists (select 1 from rhnServerServerGroupArchCompat
                      where server_arch_id = LOOKUP_SERVER_ARCH('sparc-debian-linux')
                        and server_group_type = LOOKUP_SG_TYPE('salt_entitled'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type)
  select LOOKUP_SERVER_ARCH('sparc-redhat-linux'), LOOKUP_SG_TYPE('salt_entitled') from dual
   where not exists (select 1 from rhnServerServerGroupArchCompat
                      where server_arch_id = LOOKUP_SERVER_ARCH('sparc-redhat-linux')
                        and server_group_type = LOOKUP_SG_TYPE('salt_entitled'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type)
  select LOOKUP_SERVER_ARCH('sparc-sun4m-solaris'), LOOKUP_SG_TYPE('salt_entitled') from dual
   where not exists (select 1 from rhnServerServerGroupArchCompat
                      where server_arch_id = LOOKUP_SERVER_ARCH('sparc-sun4m-solaris')
                        and server_group_type = LOOKUP_SG_TYPE('salt_entitled'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type)
  select LOOKUP_SERVER_ARCH('sparc-sun4u-solaris'), LOOKUP_SG_TYPE('salt_entitled') from dual
   where not exists (select 1 from rhnServerServerGroupArchCompat
                      where server_arch_id = LOOKUP_SERVER_ARCH('sparc-sun4u-solaris')
                        and server_group_type = LOOKUP_SG_TYPE('salt_entitled'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type)
  select LOOKUP_SERVER_ARCH('sparc-sun4v-solaris'), LOOKUP_SG_TYPE('salt_entitled') from dual
   where not exists (select 1 from rhnServerServerGroupArchCompat
                      where server_arch_id = LOOKUP_SERVER_ARCH('sparc-sun4v-solaris')
                        and server_group_type = LOOKUP_SG_TYPE('salt_entitled'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type)
  select LOOKUP_SERVER_ARCH('sparcv9-redhat-linux'), LOOKUP_SG_TYPE('salt_entitled') from dual
   where not exists (select 1 from rhnServerServerGroupArchCompat
                      where server_arch_id = LOOKUP_SERVER_ARCH('sparcv9-redhat-linux')
                        and server_group_type = LOOKUP_SG_TYPE('salt_entitled'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type)
  select LOOKUP_SERVER_ARCH('x86_64-redhat-linux'), LOOKUP_SG_TYPE('salt_entitled') from dual
   where not exists (select 1 from rhnServerServerGroupArchCompat
                      where server_arch_id = LOOKUP_SERVER_ARCH('x86_64-redhat-linux')
                        and server_group_type = LOOKUP_SG_TYPE('salt_entitled'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type)
  select LOOKUP_SERVER_ARCH('aarch64-redhat-linux'), LOOKUP_SG_TYPE('virtualization_host') from dual
   where not exists (select 1 from rhnServerServerGroupArchCompat
                      where server_arch_id = LOOKUP_SERVER_ARCH('aarch64-redhat-linux')
                        and server_group_type = LOOKUP_SG_TYPE('virtualization_host'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type)
  select LOOKUP_SERVER_ARCH('amd64-debian-linux'), LOOKUP_SG_TYPE('virtualization_host') from dual
   where not exists (select 1 from rhnServerServerGroupArchCompat
                      where server_arch_id = LOOKUP_SERVER_ARCH('amd64-debian-linux')
                        and server_group_type = LOOKUP_SG_TYPE('virtualization_host'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type)
  select LOOKUP_SERVER_ARCH('amd64-redhat-linux'), LOOKUP_SG_TYPE('virtualization_host') from dual
   where not exists (select 1 from rhnServerServerGroupArchCompat
                      where server_arch_id = LOOKUP_SERVER_ARCH('amd64-redhat-linux')
                        and server_group_type = LOOKUP_SG_TYPE('virtualization_host'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type)
  select LOOKUP_SERVER_ARCH('armv5tejl-redhat-linux'), LOOKUP_SG_TYPE('virtualization_host') from dual
   where not exists (select 1 from rhnServerServerGroupArchCompat
                      where server_arch_id = LOOKUP_SERVER_ARCH('armv5tejl-redhat-linux')
                        and server_group_type = LOOKUP_SG_TYPE('virtualization_host'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type)
  select LOOKUP_SERVER_ARCH('armv6hl-redhat-linux'), LOOKUP_SG_TYPE('virtualization_host') from dual
   where not exists (select 1 from rhnServerServerGroupArchCompat
                      where server_arch_id = LOOKUP_SERVER_ARCH('armv6hl-redhat-linux')
                        and server_group_type = LOOKUP_SG_TYPE('virtualization_host'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type)
  select LOOKUP_SERVER_ARCH('armv6l-redhat-linux'), LOOKUP_SG_TYPE('virtualization_host') from dual
   where not exists (select 1 from rhnServerServerGroupArchCompat
                      where server_arch_id = LOOKUP_SERVER_ARCH('armv6l-redhat-linux')
                        and server_group_type = LOOKUP_SG_TYPE('virtualization_host'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type)
  select LOOKUP_SERVER_ARCH('armv7l-redhat-linux'), LOOKUP_SG_TYPE('virtualization_host') from dual
   where not exists (select 1 from rhnServerServerGroupArchCompat
                      where server_arch_id = LOOKUP_SERVER_ARCH('armv7l-redhat-linux')
                        and server_group_type = LOOKUP_SG_TYPE('virtualization_host'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type)
  select LOOKUP_SERVER_ARCH('athlon-redhat-linux'), LOOKUP_SG_TYPE('virtualization_host') from dual
   where not exists (select 1 from rhnServerServerGroupArchCompat
                      where server_arch_id = LOOKUP_SERVER_ARCH('athlon-redhat-linux')
                        and server_group_type = LOOKUP_SG_TYPE('virtualization_host'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type)
  select LOOKUP_SERVER_ARCH('i386-debian-linux'), LOOKUP_SG_TYPE('virtualization_host') from dual
   where not exists (select 1 from rhnServerServerGroupArchCompat
                      where server_arch_id = LOOKUP_SERVER_ARCH('i386-debian-linux')
                        and server_group_type = LOOKUP_SG_TYPE('virtualization_host'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type)
  select LOOKUP_SERVER_ARCH('i386-redhat-linux'), LOOKUP_SG_TYPE('virtualization_host') from dual
   where not exists (select 1 from rhnServerServerGroupArchCompat
                      where server_arch_id = LOOKUP_SERVER_ARCH('i386-redhat-linux')
                        and server_group_type = LOOKUP_SG_TYPE('virtualization_host'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type)
  select LOOKUP_SERVER_ARCH('i486-redhat-linux'), LOOKUP_SG_TYPE('virtualization_host') from dual
   where not exists (select 1 from rhnServerServerGroupArchCompat
                      where server_arch_id = LOOKUP_SERVER_ARCH('i486-redhat-linux')
                        and server_group_type = LOOKUP_SG_TYPE('virtualization_host'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type)
  select LOOKUP_SERVER_ARCH('i586-redhat-linux'), LOOKUP_SG_TYPE('virtualization_host') from dual
   where not exists (select 1 from rhnServerServerGroupArchCompat
                      where server_arch_id = LOOKUP_SERVER_ARCH('i586-redhat-linux')
                        and server_group_type = LOOKUP_SG_TYPE('virtualization_host'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type)
  select LOOKUP_SERVER_ARCH('i686-redhat-linux'), LOOKUP_SG_TYPE('virtualization_host') from dual
   where not exists (select 1 from rhnServerServerGroupArchCompat
                      where server_arch_id = LOOKUP_SERVER_ARCH('i686-redhat-linux')
                        and server_group_type = LOOKUP_SG_TYPE('virtualization_host'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type)
  select LOOKUP_SERVER_ARCH('ia32e-redhat-linux'), LOOKUP_SG_TYPE('virtualization_host') from dual
   where not exists (select 1 from rhnServerServerGroupArchCompat
                      where server_arch_id = LOOKUP_SERVER_ARCH('ia32e-redhat-linux')
                        and server_group_type = LOOKUP_SG_TYPE('virtualization_host'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type)
  select LOOKUP_SERVER_ARCH('ia64-debian-linux'), LOOKUP_SG_TYPE('virtualization_host') from dual
   where not exists (select 1 from rhnServerServerGroupArchCompat
                      where server_arch_id = LOOKUP_SERVER_ARCH('ia64-debian-linux')
                        and server_group_type = LOOKUP_SG_TYPE('virtualization_host'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type)
  select LOOKUP_SERVER_ARCH('ia64-redhat-linux'), LOOKUP_SG_TYPE('virtualization_host') from dual
   where not exists (select 1 from rhnServerServerGroupArchCompat
                      where server_arch_id = LOOKUP_SERVER_ARCH('ia64-redhat-linux')
                        and server_group_type = LOOKUP_SG_TYPE('virtualization_host'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type)
  select LOOKUP_SERVER_ARCH('powerpc-debian-linux'), LOOKUP_SG_TYPE('virtualization_host') from dual
   where not exists (select 1 from rhnServerServerGroupArchCompat
                      where server_arch_id = LOOKUP_SERVER_ARCH('powerpc-debian-linux')
                        and server_group_type = LOOKUP_SG_TYPE('virtualization_host'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type)
  select LOOKUP_SERVER_ARCH('ppc64le-redhat-linux'), LOOKUP_SG_TYPE('virtualization_host') from dual
   where not exists (select 1 from rhnServerServerGroupArchCompat
                      where server_arch_id = LOOKUP_SERVER_ARCH('ppc64le-redhat-linux')
                        and server_group_type = LOOKUP_SG_TYPE('virtualization_host'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type)
  select LOOKUP_SERVER_ARCH('ppc64-redhat-linux'), LOOKUP_SG_TYPE('virtualization_host') from dual
   where not exists (select 1 from rhnServerServerGroupArchCompat
                      where server_arch_id = LOOKUP_SERVER_ARCH('ppc64-redhat-linux')
                        and server_group_type = LOOKUP_SG_TYPE('virtualization_host'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type)
  select LOOKUP_SERVER_ARCH('ppc-redhat-linux'), LOOKUP_SG_TYPE('virtualization_host') from dual
   where not exists (select 1 from rhnServerServerGroupArchCompat
                      where server_arch_id = LOOKUP_SERVER_ARCH('ppc-redhat-linux')
                        and server_group_type = LOOKUP_SG_TYPE('virtualization_host'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type)
  select LOOKUP_SERVER_ARCH('s390-debian-linux'), LOOKUP_SG_TYPE('virtualization_host') from dual
   where not exists (select 1 from rhnServerServerGroupArchCompat
                      where server_arch_id = LOOKUP_SERVER_ARCH('s390-debian-linux')
                        and server_group_type = LOOKUP_SG_TYPE('virtualization_host'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type)
  select LOOKUP_SERVER_ARCH('s390-redhat-linux'), LOOKUP_SG_TYPE('virtualization_host') from dual
   where not exists (select 1 from rhnServerServerGroupArchCompat
                      where server_arch_id = LOOKUP_SERVER_ARCH('s390-redhat-linux')
                        and server_group_type = LOOKUP_SG_TYPE('virtualization_host'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type)
  select LOOKUP_SERVER_ARCH('s390x-redhat-linux'), LOOKUP_SG_TYPE('virtualization_host') from dual
   where not exists (select 1 from rhnServerServerGroupArchCompat
                      where server_arch_id = LOOKUP_SERVER_ARCH('s390x-redhat-linux')
                        and server_group_type = LOOKUP_SG_TYPE('virtualization_host'));

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type)
  select LOOKUP_SERVER_ARCH('x86_64-redhat-linux'), LOOKUP_SG_TYPE('virtualization_host') from dual
   where not exists (select 1 from rhnServerServerGroupArchCompat
                      where server_arch_id = LOOKUP_SERVER_ARCH('x86_64-redhat-linux')
                        and server_group_type = LOOKUP_SG_TYPE('virtualization_host'));

  07070100000B9D000081B400000000000000000000000167AE111400000099000000000000000000000000000000000000007D00000000susemanager-schema/upgrade/susemanager-schema-3.0.19-to-susemanager-schema-3.0.20/004-suseProducts-add-channel_family_id.sql  ALTER TABLE suseProducts ADD channel_family_id NUMERIC
    CONSTRAINT suse_products_cfid_fk
    REFERENCES rhnChannelFamily (id)
    ON DELETE SET NULL;
   07070100000B9E000081B400000000000000000000000167AE111400000042000000000000000000000000000000000000007000000000susemanager-schema/upgrade/susemanager-schema-3.0.19-to-susemanager-schema-3.0.20/005-suseProducts-add-base.sql   ALTER TABLE suseProducts ADD base CHAR(1) DEFAULT ('N') NOT NULL;
  07070100000B9F000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005100000000susemanager-schema/upgrade/susemanager-schema-3.0.19-to-susemanager-schema-3.1.0  07070100000BA0000081B400000000000000000000000167AE11140000005B000000000000000000000000000000000000005800000000susemanager-schema/upgrade/susemanager-schema-3.0.19-to-susemanager-schema-3.1.0/README   -- Schema upgrade scripts.
-- Intentionally left empty. Please leave this directory empty.
 07070100000BA1000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005200000000susemanager-schema/upgrade/susemanager-schema-3.0.20-to-susemanager-schema-3.0.21 07070100000BA2000081B400000000000000000000000167AE11140000016E000000000000000000000000000000000000007600000000susemanager-schema/upgrade/susemanager-schema-3.0.20-to-susemanager-schema-3.0.21/001-add-channel-gpgcheck-column.sql -- Adding the column 'gpg_check' to rhnChannel

DO $$
    BEGIN
        BEGIN
            ALTER TABLE rhnChannel ADD gpg_check CHAR(1) DEFAULT ('Y') NOT NULL CONSTRAINT rhn_channel_gc_ck CHECK (gpg_check in ('Y', 'N'));
        EXCEPTION
            WHEN duplicate_column THEN RAISE NOTICE 'column rhnChannel already exists in rhnChannel';
        END;
    END;
$$;
  07070100000BA3000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005100000000susemanager-schema/upgrade/susemanager-schema-3.0.20-to-susemanager-schema-3.1.0  07070100000BA4000081B400000000000000000000000167AE11140000005B000000000000000000000000000000000000005800000000susemanager-schema/upgrade/susemanager-schema-3.0.20-to-susemanager-schema-3.1.0/README   -- Schema upgrade scripts.
-- Intentionally left empty. Please leave this directory empty.
 07070100000BA5000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005200000000susemanager-schema/upgrade/susemanager-schema-3.0.21-to-susemanager-schema-3.0.22 07070100000BA6000081B400000000000000000000000167AE111400000266000000000000000000000000000000000000006F00000000susemanager-schema/upgrade/susemanager-schema-3.0.21-to-susemanager-schema-3.0.22/001-fix-unique-minion-id.sql    
-- provide info about possible duplicate minion ids
select 'DUPLICATE MINION IDs FOUND:' || X.minion_id || ' Manual cleanup required!' message
from (select minion_id, count(server_id) dup
        from suseMinionInfo
       group by minion_id) X
where X.dup > 1;

select m.minion_id, s.name, s.id, s.org_id, s.os
  from rhnServer s
  join suseMinionInfo m on s.id = m.server_id
order by m.minion_id, s.name;

alter table suseMinionInfo drop CONSTRAINT IF EXISTS rhn_minion_info_miid_uq;

drop index if exists rhn_minion_info_miid_uq;

create unique index rhn_minion_info_miid_uq
    on suseMinionInfo (minion_id);
  07070100000BA7000081B400000000000000000000000167AE111400000049000000000000000000000000000000000000007000000000susemanager-schema/upgrade/susemanager-schema-3.0.21-to-susemanager-schema-3.0.22/003-increase-hw_addr-size.sql   ALTER TABLE rhnServerNetInterface ALTER COLUMN hw_addr TYPE VARCHAR(96);
   07070100000BA8000081B400000000000000000000000167AE1114000001D0000000000000000000000000000000000000007D00000000susemanager-schema/upgrade/susemanager-schema-3.0.21-to-susemanager-schema-3.0.22/004-enable-provision-for-salt-entitled.sql  insert into rhnServerGroupTypeFeature (server_group_type_id, feature_id,
                                       created, modified)
select lookup_sg_type('salt_entitled'), lookup_feature_type('ftr_power_management'),
        current_timestamp,current_timestamp from dual
where not exists ( select 1 from rhnServerGroupTypeFeature
    where server_group_type_id = lookup_sg_type('salt_entitled')
      and feature_id = lookup_feature_type('ftr_power_management') );
07070100000BA9000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005100000000susemanager-schema/upgrade/susemanager-schema-3.0.21-to-susemanager-schema-3.1.0  07070100000BAA000081B400000000000000000000000167AE11140000005B000000000000000000000000000000000000005800000000susemanager-schema/upgrade/susemanager-schema-3.0.21-to-susemanager-schema-3.1.0/README   -- Schema upgrade scripts.
-- Intentionally left empty. Please leave this directory empty.
 07070100000BAB000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005200000000susemanager-schema/upgrade/susemanager-schema-3.0.22-to-susemanager-schema-3.0.23 07070100000BAC000081B400000000000000000000000167AE1114000011C1000000000000000000000000000000000000007C00000000susemanager-schema/upgrade/susemanager-schema-3.0.22-to-susemanager-schema-3.0.23/001-may_take_long-fix-rhn_pe_v_r_e_uq.sql   
drop index if exists rhn_pe_v_r_e_uq;
drop index if exists rhn_pe_v_r_uq;

create or replace function fix_rhn_pe_v_r_e_uq()
returns void as
$$
declare original record;
declare duplicate record;
declare nevra_orig record;
declare nevra_dup record;
declare snapshotitem record;
declare serverpackage record;
begin
  for original in select min(id) as id
          from rhnpackageevr
      group by version, release, epoch
        having count(*) > 1 loop
    for duplicate in select evr2.id
             from rhnpackageevr evr1, rhnpackageevr evr2
            where evr1.version = evr2.version
              and evr1.release = evr2.release
              and (evr1.epoch = evr2.epoch
               or (evr1.epoch is NULL and evr2.epoch is NULL))
              and evr1.id != evr2.id
              and evr1.id = original.id loop
      update rhnactionpackage set evr_id = original.id where evr_id = duplicate.id;
      update rhnactionpackageremovalfailure set evr_id = original.id where evr_id = duplicate.id;
      update rhnLockedPackages set evr_id = original.id where evr_id = duplicate.id;
      update rhnchannelnewestpackage set evr_id = original.id where evr_id = duplicate.id;
      update rhnpackage set evr_id = original.id where evr_id = duplicate.id;
      select id into nevra_orig from rhnpackagenevra where evr_id = original.id;
      if NOT FOUND then
        update rhnpackagenevra set evr_id = original.id where evr_id = duplicate.id;
      else
        for nevra_dup in select id
                           from rhnpackagenevra
                          where evr_id = duplicate.id loop
          for snapshotitem in select snapshot_id
                                from rhnsnapshotpackage
                               where nevra_id = nevra_dup.id loop
            begin
              update rhnsnapshotpackage set nevra_id = nevra_orig.id where nevra_id = nevra_dup.id and snapshot_id = snapshotitem.snapshot_id;
            exception when unique_violation then
              delete from rhnsnapshotpackage where nevra_id = nevra_dup.id and snapshot_id = snapshotitem.snapshot_id;
            end;
          end loop;
        end loop;
        delete from rhnpackagenevra where evr_id = duplicate.id;
      end if;
      update rhnproxyinfo set proxy_evr_id = original.id where proxy_evr_id = duplicate.id;
      update rhnserveractionverifymissing set package_evr_id = original.id where package_evr_id = duplicate.id;
      update rhnserveractionverifyresult set package_evr_id = original.id where package_evr_id = duplicate.id;
      update rhnsatelliteinfo set evr_id = original.id where evr_id = duplicate.id;
      update rhnservercrash set package_evr_id = original.id where package_evr_id = duplicate.id;
      update rhnserverprofilepackage set evr_id = original.id where evr_id = duplicate.id;
      update rhntransactionpackage set evr_id = original.id where evr_id = duplicate.id;
      update rhnversioninfo set evr_id = original.id where evr_id = duplicate.id;

      for serverpackage in select * from rhnserverpackage where evr_id = duplicate.id loop
          begin
            update rhnserverpackage set evr_id = original.id where evr_id = duplicate.id and
                server_id = serverpackage.server_id and
                name_id = serverpackage.name_id and
                evr_id = serverpackage.evr_id and
                package_arch_id = serverpackage.package_arch_id;
          exception when unique_violation then
            delete from rhnserverpackage where evr_id = duplicate.id and
                server_id = serverpackage.server_id and
                name_id = serverpackage.name_id and
                evr_id = serverpackage.evr_id and
                package_arch_id = serverpackage.package_arch_id;
          end;
      end loop;

      update susePackageState set evr_id = original.id where evr_id = duplicate.id;
      update suseproductfile set evr_id = original.id where evr_id = duplicate.id;
      delete from rhnpackageevr where id = duplicate.id;
    end loop;
  end loop;
end;
$$ language plpgsql;

drop trigger if exists rhn_pack_evr_no_updel_trig on rhnpackageevr;

select fix_rhn_pe_v_r_e_uq();

drop function fix_rhn_pe_v_r_e_uq();

create trigger
rhn_pack_evr_no_updel_trig
before update or delete on rhnpackageevr
execute procedure no_operation_trig_fun();

create unique index rhn_pe_v_r_e_uq
    on rhnpackageevr (version, release, epoch)
 where epoch is not null;

create unique index rhn_pe_v_r_uq
    on rhnpackageevr (version, release)
 where epoch is null;
   07070100000BAD000081B400000000000000000000000167AE1114000010B4000000000000000000000000000000000000008800000000susemanager-schema/upgrade/susemanager-schema-3.0.22-to-susemanager-schema-3.0.23/002-may_take_long-fix-rhn_pkg_cap_name_version_uq.sql   
drop index if exists rhn_pkg_cap_name_version_uq;
drop index if exists rhn_pkg_cap_name_uq;

create or replace function fix_rhn_pkg_cap_name_version_uq()
returns void as
$$
declare original record;
declare duplicate record;
begin
  for original in select min(id) as id
          from rhnPackageCapability
      group by name, version
        having count(*) > 1 loop
    for duplicate in select cap2.id
             from rhnPackageCapability cap1, rhnPackageCapability cap2
            where
                  cap1.name = cap2.name
              and (cap1.version = cap2.version
               or (cap1.version is NULL and cap2.version is NULL))
              and cap1.id != cap2.id
              and cap1.id = original.id loop
      update rhnactionpackageremovalfailure set capability_id = original.id where capability_id = duplicate.id;
      begin
        update rhnPackageBreaks set capability_id = original.id where capability_id = duplicate.id;
      exception when unique_violation then
        -- do nothing as data already exists
        null;
      end;
      begin
        update rhnPackageConflicts set capability_id = original.id where capability_id = duplicate.id;
      exception when unique_violation then
        -- do nothing as data already exists
        null;
      end;
      begin
        update rhnPackageEnhances set capability_id = original.id where capability_id = duplicate.id;
      exception when unique_violation then
        -- do nothing as data already exists
        null;
      end;
      begin
        update rhnPackageFile set capability_id = original.id where capability_id = duplicate.id;
      exception when unique_violation then
        -- do nothing as data already exists
        null;
      end;
      begin
        update rhnPackageObsoletes set capability_id = original.id where capability_id = duplicate.id;
      exception when unique_violation then
        -- do nothing as data already exists
        null;
      end;
      begin
        update rhnPackagePredepends set capability_id = original.id where capability_id = duplicate.id;
      exception when unique_violation then
        -- do nothing as data already exists
        null;
      end;
      begin
        update rhnPackageProvides set capability_id = original.id where capability_id = duplicate.id;
      exception when unique_violation then
        -- do nothing as data already exists
        null;
      end;
      begin
        update rhnPackageRecommends set capability_id = original.id where capability_id = duplicate.id;
      exception when unique_violation then
        -- do nothing as data already exists
        null;
      end;
      begin
        update rhnPackageRequires set capability_id = original.id where capability_id = duplicate.id;
      exception when unique_violation then
        -- do nothing as data already exists
        null;
      end;
      begin
        update rhnPackageSuggests set capability_id = original.id where capability_id = duplicate.id;
      exception when unique_violation then
        -- do nothing as data already exists
        null;
      end;
      begin
        update rhnPackageSupplements set capability_id = original.id where capability_id = duplicate.id;
      exception when unique_violation then
        -- do nothing as data already exists
        null;
      end;
      begin
        update rhnServerActionVerifyMissing set package_capability_id = original.id where package_capability_id = duplicate.id;
      exception when unique_violation then
        -- do nothing as data already exists
        null;
      end;
      begin
        update rhnServerActionVerifyResult set package_capability_id = original.id where package_capability_id = duplicate.id;
      exception when unique_violation then
        -- do nothing as data already exists
        null;
      end;
      delete from rhnPackageCapability where id = duplicate.id;
    end loop;
  end loop;
end;
$$ language plpgsql;

select fix_rhn_pkg_cap_name_version_uq();

drop function fix_rhn_pkg_cap_name_version_uq();

CREATE UNIQUE INDEX rhn_pkg_cap_name_version_uq
    ON rhnPackageCapability (name, version)
 where version is not null;

create unique index rhn_pkg_cap_name_uq
    on rhnPackageCapability (name)
 where version is null;
07070100000BAE000081B400000000000000000000000167AE111400000190000000000000000000000000000000000000006C00000000susemanager-schema/upgrade/susemanager-schema-3.0.22-to-susemanager-schema-3.0.23/003-Adelaide-Timezone.sql   insert into rhnTimezone (id, olson_name, display_name) (
    select sequence_nextval('rhn_timezone_id_seq'),
           'Australia/Adelaide',
           'Australia Central (Adelaide)'
      from dual
     where not exists (
           select 1
             from rhnTimezone
            where olson_name = 'Australia/Adelaide'
              and display_name = 'Australia Central (Adelaide)'
     )
);
07070100000BAF000081B400000000000000000000000167AE111400000485000000000000000000000000000000000000007400000000susemanager-schema/upgrade/susemanager-schema-3.0.22-to-susemanager-schema-3.0.23/250-rhnUserChannelFamilyPerms.sql   --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

create or replace view rhnUserChannelFamilyPerms as
	select	pcf.channel_family_id,
		u.org_id as org_id,
		u.id as user_id,
		pcf.created,
		pcf.modified
	from	rhnPublicChannelFamily pcf,
		web_contact u
	where	pcf.channel_family_id not in (
			select priv.channel_family_id
			from rhnPrivateChannelFamily priv
			where u.org_id = priv.org_id
		)
	union
	select	pcf.channel_family_id,
		u.org_id,
		u.id as user_id,
		pcf.created,
		pcf.modified
	from	rhnPrivateChannelFamily pcf,
		web_contact u
	where	u.org_id = pcf.org_id;

   07070100000BB0000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005100000000susemanager-schema/upgrade/susemanager-schema-3.0.22-to-susemanager-schema-3.1.0  07070100000BB1000081B400000000000000000000000167AE11140000005B000000000000000000000000000000000000005800000000susemanager-schema/upgrade/susemanager-schema-3.0.22-to-susemanager-schema-3.1.0/README   -- Schema upgrade scripts.
-- Intentionally left empty. Please leave this directory empty.
 07070100000BB2000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005100000000susemanager-schema/upgrade/susemanager-schema-3.0.23-to-susemanager-schema-3.1.0  07070100000BB3000081B400000000000000000000000167AE11140000005B000000000000000000000000000000000000005800000000susemanager-schema/upgrade/susemanager-schema-3.0.23-to-susemanager-schema-3.1.0/README   -- Schema upgrade scripts.
-- Intentionally left empty. Please leave this directory empty.
 07070100000BB4000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005100000000susemanager-schema/upgrade/susemanager-schema-3.0.24-to-susemanager-schema-3.1.0  07070100000BB5000081B400000000000000000000000167AE11140000005B000000000000000000000000000000000000005800000000susemanager-schema/upgrade/susemanager-schema-3.0.24-to-susemanager-schema-3.1.0/README   -- Schema upgrade scripts.
-- Intentionally left empty. Please leave this directory empty.
 07070100000BB6000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005100000000susemanager-schema/upgrade/susemanager-schema-3.0.25-to-susemanager-schema-3.1.0  07070100000BB7000081B400000000000000000000000167AE11140000005B000000000000000000000000000000000000005800000000susemanager-schema/upgrade/susemanager-schema-3.0.25-to-susemanager-schema-3.1.0/README   -- Schema upgrade scripts.
-- Intentionally left empty. Please leave this directory empty.
 07070100000BB8000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000004E00000000susemanager-schema/upgrade/susemanager-schema-3.0.9-to-susemanager-schema-3.0 07070100000BB9000081B400000000000000000000000167AE111400000064000000000000000000000000000000000000005500000000susemanager-schema/upgrade/susemanager-schema-3.0.9-to-susemanager-schema-3.0/README  -- Schema upgrade scripts.
-- leave this directory empty. It reflects SUSE Manager 3 Beta 2 version
07070100000BBA000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005000000000susemanager-schema/upgrade/susemanager-schema-3.1.0-to-susemanager-schema-3.1.1   07070100000BBB000081B400000000000000000000000167AE11140000007A000000000000000000000000000000000000006600000000susemanager-schema/upgrade/susemanager-schema-3.1.0-to-susemanager-schema-3.1.1/0001-drop-trigger.sql 
drop trigger if exists rhn_virtinst_del_trig on rhnVirtualInstance;
drop function if exists rhn_virtinst_del_trig_fun();
  07070100000BBC000081B400000000000000000000000167AE111400000560000000000000000000000000000000000000006600000000susemanager-schema/upgrade/susemanager-schema-3.1.0-to-susemanager-schema-3.1.1/0206-uuid-cleanup.sql INSERT INTO rhnTaskoBunch (id, name, description, org_bunch)
    select sequence_nextval('rhn_tasko_bunch_id_seq'), 'uuid-cleanup-bunch', 'purge orphaned uuid records', null from dual
        where not exists (select 1 from rhnTaskoBunch where name = 'uuid-cleanup-bunch');

-- Every hour

INSERT INTO rhnTaskoSchedule (id, job_label, bunch_id, active_from, cron_expr)
    select sequence_nextval('rhn_tasko_schedule_id_seq'), 'uuid-cleanup-default',
        (SELECT id FROM rhnTaskoBunch WHERE name='uuid-cleanup-bunch'),
        current_timestamp, '0 0 * * * ?' from dual
        where not exists (select 1 from rhnTaskoSchedule where job_label = 'uuid-cleanup-default');

INSERT INTO rhnTaskoTask (id, name, class)
    select sequence_nextval('rhn_tasko_task_id_seq'), 'uuid-cleanup', 'com.redhat.rhn.taskomatic.task.UuidCleanup' from dual
where not exists (select 1 from rhnTaskoTask where name = 'uuid-cleanup');

INSERT INTO rhnTaskoTemplate (id, bunch_id, task_id, ordering, start_if)
    select sequence_nextval('rhn_tasko_template_id_seq'),
            (SELECT id FROM rhnTaskoBunch WHERE name='uuid-cleanup-bunch'),
            (SELECT id FROM rhnTaskoTask WHERE name='uuid-cleanup'),
            0,
            null from dual
        where not exists (select 1 from rhnTaskoTemplate where bunch_id = (SELECT id FROM rhnTaskoBunch WHERE name='uuid-cleanup-bunch'));
07070100000BBD000081B400000000000000000000000167AE111400000260000000000000000000000000000000000000007000000000susemanager-schema/upgrade/susemanager-schema-3.1.0-to-susemanager-schema-3.1.1/0207-remove-sync-probe-task.sql   DELETE FROM rhnTaskoRun
  WHERE template_id IN (
    SELECT id
      FROM rhnTaskoTemplate
      WHERE task_id IN (
        SELECT id
          FROM rhnTaskoTask
          WHERE name = 'sync-probe-state'
      )
  );

DELETE FROM rhnTaskoTemplate
  WHERE bunch_id IN (
    SELECT id
      FROM rhnTaskoBunch
      WHERE name = 'sync-probe-bunch'
  );

DELETE FROM rhnTaskoTask
  WHERE name = 'sync-probe-state';

DELETE FROM rhnTaskoSchedule
  WHERE bunch_id IN (
    SELECT id
      FROM rhnTaskoBunch
      WHERE name = 'sync-probe-bunch'
  );

DELETE FROM rhnTaskoBunch
  WHERE name = 'sync-probe-bunch';
07070100000BBE000081B400000000000000000000000167AE111400000350000000000000000000000000000000000000007C00000000susemanager-schema/upgrade/susemanager-schema-3.1.0-to-susemanager-schema-3.1.1/1001-drop-rhnContentSourceSsl-move-data.sql   -- Add columns
alter table rhnContentSource add ssl_ca_cert_id NUMERIC constraint rhn_cs_cacertid_fk references rhnCryptoKey(id) on delete set null;
alter table rhnContentSource add ssl_client_cert_id NUMERIC constraint rhn_cs_clcertid_fk references rhnCryptoKey(id) on delete set null;
alter table rhnContentSource add ssl_client_key_id NUMERIC constraint rhn_cs_clkeyid_fk references rhnCryptoKey(id) on delete set null;

-- Copy values
update rhnContentSource cs set
    ssl_ca_cert_id = (select csssl.ssl_ca_cert_id from rhnContentSourceSsl csssl where csssl.content_source_id = cs.id),
    ssl_client_cert_id = (select csssl.ssl_client_cert_id from rhnContentSourceSsl csssl where csssl.content_source_id = cs.id),
    ssl_client_key_id = (select csssl.ssl_client_key_id from rhnContentSourceSsl csssl where csssl.content_source_id = cs.id);

07070100000BBF000081B400000000000000000000000167AE1114000000D5000000000000000000000000000000000000007A00000000susemanager-schema/upgrade/susemanager-schema-3.1.0-to-susemanager-schema-3.1.1/1002-drop-rhnContentSourceSsl-cleanup.sql -- Drop old stuff
delete from rhnContentSourceSsl;
drop table rhnContentSourceSsl;
drop function rhn_csssl_ins_trig_fun();
drop function rhn_cont_source_ssl_mod_trig_fun();
drop sequence rhn_contentsourcessl_seq;
   07070100000BC0000081B400000000000000000000000167AE111400000071000000000000000000000000000000000000007100000000susemanager-schema/upgrade/susemanager-schema-3.1.0-to-susemanager-schema-3.1.1/1002-uln-content-source-type.sql  insert into rhnContentSourceType (id, label) values
(sequence_nextval('rhn_content_source_type_id_seq'), 'uln');
   07070100000BC1000081B400000000000000000000000167AE111400000071000000000000000000000000000000000000007100000000susemanager-schema/upgrade/susemanager-schema-3.1.0-to-susemanager-schema-3.1.1/1003-deb-content-source-type.sql  insert into rhnContentSourceType (id, label) values
(sequence_nextval('rhn_content_source_type_id_seq'), 'deb');
   07070100000BC2000081B400000000000000000000000167AE111400000418000000000000000000000000000000000000007600000000susemanager-schema/upgrade/susemanager-schema-3.1.0-to-susemanager-schema-3.1.1/1004-rhnChannelPackage-autovacuum.sql -- oracle equivalent source none
--
-- Copyright (c) 2016 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

-- Set some postgres-specific parameters that can strongly affect performance
-- when cloning channels
ALTER TABLE rhnChannelPackage SET (autovacuum_vacuum_scale_factor = 0.0);
ALTER TABLE rhnChannelPackage SET (autovacuum_vacuum_threshold = 15);
ALTER TABLE rhnChannelPackage SET (autovacuum_analyze_scale_factor = 0.0);
ALTER TABLE rhnChannelPackage SET (autovacuum_analyze_threshold = 15);
07070100000BC3000081B400000000000000000000000167AE111400000240000000000000000000000000000000000000006B00000000susemanager-schema/upgrade/susemanager-schema-3.1.0-to-susemanager-schema-3.1.1/1006-add-fedora24-keys.sql    insert into rhnPackageKey (id, key_id, key_type_id, provider_id) select sequence_nextval('rhn_pkey_id_seq'), '73bde98381b46521', lookup_package_key_type('gpg'), lookup_package_provider('Fedora') from dual where not exists (select 1 from rhnPackageKey where key_id = '73bde98381b46521');

insert into rhnPackageKey (id, key_id, key_type_id, provider_id) select sequence_nextval('rhn_pkey_id_seq'), 'b8635eeb030d5aed', lookup_package_key_type('gpg'), lookup_package_provider('Fedora') from dual where not exists (select 1 from rhnPackageKey where key_id = 'b8635eeb030d5aed');

07070100000BC4000081B400000000000000000000000167AE111400002BCC000000000000000000000000000000000000006D00000000susemanager-schema/upgrade/susemanager-schema-3.1.0-to-susemanager-schema-3.1.1/1007-remove-solaris-arch.sql  
create or replace
function delete_server_tmp (
  arch_in varchar
)
returns void as
$$
declare
  rec record;
begin
  for rec in select server.id as id
      from rhnServer server
      where server_arch_id = LOOKUP_SERVER_ARCH(arch_in) loop
    perform .clear_log_id();
    perform delete_server(rec.id);
  end loop;
end;
$$ language plpgsql;

select delete_server_tmp('sparc-sun4m-solaris');
select delete_server_tmp('sparc-sun4u-solaris');
select delete_server_tmp('sparc-sun4v-solaris');
select delete_server_tmp('i386-i86pc-solaris');

drop function delete_server_tmp(varchar);

create or replace
function delete_channel_tmp (
  arch_in varchar
)
returns void as
$$
declare
  rec record;
begin
  for rec in select channel.id as id
      from rhnChannel channel
      where channel_arch_id = LOOKUP_CHANNEL_ARCH(arch_in) loop
    perform delete_channel(rec.id);
  end loop;
end;
$$ language plpgsql;

create or replace
function delete_channel_tmp_child (
  arch_in varchar
)
returns void as
$$
declare
  rec record;
begin
  for rec in select channel.id as id
      from rhnChannel channel
      where channel.parent_channel in
        (select id from rhnChannel c2
          where c2.channel_arch_id = LOOKUP_CHANNEL_ARCH(arch_in))
    loop
    perform delete_channel(rec.id);
  end loop;
end;
$$ language plpgsql;

select delete_channel_tmp_child('channel-sparc-sun-solaris');
select delete_channel_tmp_child('channel-i386-sun-solaris');
select delete_channel_tmp('channel-sparc-sun-solaris');
select delete_channel_tmp('channel-i386-sun-solaris');

drop function delete_channel_tmp(varchar);
drop function delete_channel_tmp_child(varchar);

delete from rhnChannelPackageArchCompat where channel_arch_id = LOOKUP_CHANNEL_ARCH('channel-sparc-sun-solaris');
delete from rhnChannelPackageArchCompat where channel_arch_id = LOOKUP_CHANNEL_ARCH('channel-i386-sun-solaris');

delete from rhnServerChannelArchCompat where channel_arch_id = LOOKUP_CHANNEL_ARCH('channel-sparc-sun-solaris');
delete from rhnServerChannelArchCompat where channel_arch_id = LOOKUP_CHANNEL_ARCH('channel-i386-sun-solaris');

delete from rhnChildChannelArchCompat where parent_arch_id = LOOKUP_CHANNEL_ARCH('channel-sparc-sun-solaris');
delete from rhnChildChannelArchCompat where parent_arch_id = LOOKUP_CHANNEL_ARCH('channel-i386-sun-solaris');
delete from rhnChildChannelArchCompat where child_arch_id = LOOKUP_CHANNEL_ARCH('channel-sparc-sun-solaris');
delete from rhnChildChannelArchCompat where child_arch_id = LOOKUP_CHANNEL_ARCH('channel-i386-sun-solaris');

delete from rhnChannelArch where label = 'channel-sparc-sun-solaris';
delete from rhnChannelArch where label = 'channel-i386-sun-solaris';

delete from rhnPackageUpgradeArchCompat where package_arch_id = LOOKUP_PACKAGE_ARCH('sparc-solaris');
delete from rhnPackageUpgradeArchCompat where package_arch_id = LOOKUP_PACKAGE_ARCH('sparc.sun4u-solaris');
delete from rhnPackageUpgradeArchCompat where package_arch_id = LOOKUP_PACKAGE_ARCH('sparc.sun4v-solaris');
delete from rhnPackageUpgradeArchCompat where package_arch_id = LOOKUP_PACKAGE_ARCH('i386-solaris');
delete from rhnPackageUpgradeArchCompat where package_arch_id = LOOKUP_PACKAGE_ARCH('sparc-solaris-patch');
delete from rhnPackageUpgradeArchCompat where package_arch_id = LOOKUP_PACKAGE_ARCH('i386-solaris-patch');
delete from rhnPackageUpgradeArchCompat where package_arch_id = LOOKUP_PACKAGE_ARCH('sparc-solaris-patch-cluster');
delete from rhnPackageUpgradeArchCompat where package_arch_id = LOOKUP_PACKAGE_ARCH('i386-solaris-patch-cluster');
delete from rhnPackageUpgradeArchCompat where package_arch_id = LOOKUP_PACKAGE_ARCH('noarch-solaris');
delete from rhnPackageUpgradeArchCompat where package_arch_id = LOOKUP_PACKAGE_ARCH('noarch-solaris-patch');
delete from rhnPackageUpgradeArchCompat where package_arch_id = LOOKUP_PACKAGE_ARCH('noarch-solaris-patch-cluster');

delete from rhnPackageUpgradeArchCompat where package_upgrade_arch_id = LOOKUP_PACKAGE_ARCH('sparc-solaris');
delete from rhnPackageUpgradeArchCompat where package_upgrade_arch_id = LOOKUP_PACKAGE_ARCH('sparc.sun4u-solaris');
delete from rhnPackageUpgradeArchCompat where package_upgrade_arch_id = LOOKUP_PACKAGE_ARCH('sparc.sun4v-solaris');
delete from rhnPackageUpgradeArchCompat where package_upgrade_arch_id = LOOKUP_PACKAGE_ARCH('i386-solaris');
delete from rhnPackageUpgradeArchCompat where package_upgrade_arch_id = LOOKUP_PACKAGE_ARCH('sparc-solaris-patch');
delete from rhnPackageUpgradeArchCompat where package_upgrade_arch_id = LOOKUP_PACKAGE_ARCH('i386-solaris-patch');
delete from rhnPackageUpgradeArchCompat where package_upgrade_arch_id = LOOKUP_PACKAGE_ARCH('sparc-solaris-patch-cluster');
delete from rhnPackageUpgradeArchCompat where package_upgrade_arch_id = LOOKUP_PACKAGE_ARCH('i386-solaris-patch-cluster');
delete from rhnPackageUpgradeArchCompat where package_upgrade_arch_id = LOOKUP_PACKAGE_ARCH('noarch-solaris');
delete from rhnPackageUpgradeArchCompat where package_upgrade_arch_id = LOOKUP_PACKAGE_ARCH('noarch-solaris-patch');
delete from rhnPackageUpgradeArchCompat where package_upgrade_arch_id = LOOKUP_PACKAGE_ARCH('noarch-solaris-patch-cluster');

delete from rhnServerPackageArchCompat where package_arch_id = LOOKUP_PACKAGE_ARCH('sparc-solaris');
delete from rhnServerPackageArchCompat where package_arch_id = LOOKUP_PACKAGE_ARCH('sparc.sun4u-solaris');
delete from rhnServerPackageArchCompat where package_arch_id = LOOKUP_PACKAGE_ARCH('sparc.sun4v-solaris');
delete from rhnServerPackageArchCompat where package_arch_id = LOOKUP_PACKAGE_ARCH('i386-solaris');
delete from rhnServerPackageArchCompat where package_arch_id = LOOKUP_PACKAGE_ARCH('sparc-solaris-patch');
delete from rhnServerPackageArchCompat where package_arch_id = LOOKUP_PACKAGE_ARCH('i386-solaris-patch');
delete from rhnServerPackageArchCompat where package_arch_id = LOOKUP_PACKAGE_ARCH('sparc-solaris-patch-cluster');
delete from rhnServerPackageArchCompat where package_arch_id = LOOKUP_PACKAGE_ARCH('i386-solaris-patch-cluster');
delete from rhnServerPackageArchCompat where package_arch_id = LOOKUP_PACKAGE_ARCH('noarch-solaris');
delete from rhnServerPackageArchCompat where package_arch_id = LOOKUP_PACKAGE_ARCH('noarch-solaris-patch');
delete from rhnServerPackageArchCompat where package_arch_id = LOOKUP_PACKAGE_ARCH('noarch-solaris-patch-cluster');

delete from rhnPackage where package_arch_id = (select id from rhnPackageArch where label = 'sparc-solaris');
delete from rhnPackage where package_arch_id = (select id from rhnPackageArch where label = 'sparc.sun4u-solaris');
delete from rhnPackage where package_arch_id = (select id from rhnPackageArch where label = 'sparc.sun4v-solaris');
delete from rhnPackage where package_arch_id = (select id from rhnPackageArch where label = 'i386-solaris');
delete from rhnPackage where package_arch_id = (select id from rhnPackageArch where label = 'sparc-solaris-patch');
delete from rhnPackage where package_arch_id = (select id from rhnPackageArch where label = 'i386-solaris-patch');
delete from rhnPackage where package_arch_id = (select id from rhnPackageArch where label = 'sparc-solaris-patch-cluster');
delete from rhnPackage where package_arch_id = (select id from rhnPackageArch where label = 'i386-solaris-patch-cluster');
delete from rhnPackage where package_arch_id = (select id from rhnPackageArch where label = 'noarch-solaris');
delete from rhnPackage where package_arch_id = (select id from rhnPackageArch where label = 'noarch-solaris-patch');
delete from rhnPackage where package_arch_id = (select id from rhnPackageArch where label = 'noarch-solaris-patch-cluster');

delete from rhnPackageNEVRA where package_arch_id = (select id from rhnPackageArch where label = 'sparc-solaris');
delete from rhnPackageNEVRA where package_arch_id = (select id from rhnPackageArch where label = 'sparc.sun4u-solaris');
delete from rhnPackageNEVRA where package_arch_id = (select id from rhnPackageArch where label = 'sparc.sun4v-solaris');
delete from rhnPackageNEVRA where package_arch_id = (select id from rhnPackageArch where label = 'i386-solaris');
delete from rhnPackageNEVRA where package_arch_id = (select id from rhnPackageArch where label = 'sparc-solaris-patch');
delete from rhnPackageNEVRA where package_arch_id = (select id from rhnPackageArch where label = 'i386-solaris-patch');
delete from rhnPackageNEVRA where package_arch_id = (select id from rhnPackageArch where label = 'sparc-solaris-patch-cluster');
delete from rhnPackageNEVRA where package_arch_id = (select id from rhnPackageArch where label = 'i386-solaris-patch-cluster');
delete from rhnPackageNEVRA where package_arch_id = (select id from rhnPackageArch where label = 'noarch-solaris');
delete from rhnPackageNEVRA where package_arch_id = (select id from rhnPackageArch where label = 'noarch-solaris-patch');
delete from rhnPackageNEVRA where package_arch_id = (select id from rhnPackageArch where label = 'noarch-solaris-patch-cluster');

delete from rhnPackageArch where label = 'sparc-solaris';
delete from rhnPackageArch where label = 'sparc.sun4u-solaris';
delete from rhnPackageArch where label = 'sparc.sun4v-solaris';
delete from rhnPackageArch where label = 'i386-solaris';
delete from rhnPackageArch where label = 'sparc-solaris-patch';
delete from rhnPackageArch where label = 'i386-solaris-patch';
delete from rhnPackageArch where label = 'sparc-solaris-patch-cluster';
delete from rhnPackageArch where label = 'i386-solaris-patch-cluster';
delete from rhnPackageArch where label = 'noarch-solaris';
delete from rhnPackageArch where label = 'noarch-solaris-patch';
delete from rhnPackageArch where label = 'noarch-solaris-patch-cluster';

delete from rhnPackageArch where arch_type_id = (select id from rhnArchType where label = 'solaris-patch');
delete from rhnPackageArch where arch_type_id = (select id from rhnArchType where label = 'solaris-patch-cluster');
delete from rhnPackageArch where arch_type_id = (select id from rhnArchType where label = 'sysv-solaris');

delete from rhnServerServerGroupArchCompat where server_arch_id = LOOKUP_SERVER_ARCH('sparc-sun4m-solaris');
delete from rhnServerServerGroupArchCompat where server_arch_id = LOOKUP_SERVER_ARCH('sparc-sun4u-solaris');
delete from rhnServerServerGroupArchCompat where server_arch_id = LOOKUP_SERVER_ARCH('sparc-sun4v-solaris');
delete from rhnServerServerGroupArchCompat where server_arch_id = LOOKUP_SERVER_ARCH('i386-i86pc-solaris');

delete from rhnServerArch where label = 'sparc-sun4m-solaris';
delete from rhnServerArch where label = 'sparc-sun4u-solaris';
delete from rhnServerArch where label = 'sparc-sun4v-solaris';
delete from rhnServerArch where label = 'i386-i86pc-solaris';

delete from rhnArchTypeActions where arch_type_id = (select id from rhnArchType where label = 'solaris-patch');
delete from rhnArchTypeActions where arch_type_id = (select id from rhnArchType where label = 'solaris-patch-cluster');
delete from rhnArchTypeActions where arch_type_id = (select id from rhnArchType where label = 'sysv-solaris');

delete from rhnArchType where label = 'solaris-patch';
delete from rhnArchType where label = 'solaris-patch-cluster';
delete from rhnArchType where label = 'sysv-solaris';
07070100000BC5000081B400000000000000000000000167AE11140000003D000000000000000000000000000000000000007D00000000susemanager-schema/upgrade/susemanager-schema-3.1.0-to-susemanager-schema-3.1.1/2002-rhnKickstartCommand-custom-position.sql  ALTER TABLE rhnKickstartCommand ADD custom_position NUMERIC;
   07070100000BC6000081B400000000000000000000000167AE111400000583000000000000000000000000000000000000007A00000000susemanager-schema/upgrade/susemanager-schema-3.1.0-to-susemanager-schema-3.1.1/2003-rhnContentSourceSsl-create-table.sql --
-- Copyright (c) 2017 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE rhnContentSourceSsl
(
	content_source_id NUMERIC not null
		constraint rhn_csssl_csid_fk references rhnContentSource(id) on delete cascade,
	ssl_ca_cert_id NUMERIC not null
		constraint rhn_csssl_cacertid_fk references rhnCryptoKey(id) on delete cascade,
	ssl_client_cert_id NUMERIC
		constraint rhn_csssl_clcertid_fk references rhnCryptoKey(id) on delete cascade,
	ssl_client_key_id NUMERIC
		constraint rhn_csssl_clkeyid_fk references rhnCryptoKey(id) on delete cascade,
	constraint rhn_csssl_client_chk check(ssl_client_key_id is null or ssl_client_cert_id is not null),
	created TIMESTAMPTZ default(current_timestamp) not null,
	modified TIMESTAMPTZ default(current_timestamp) not null
)

;

CREATE INDEX rhn_csssl_cs
    ON rhnContentSourceSsl (content_source_id)
    ;
 07070100000BC7000081B400000000000000000000000167AE1114000004BA000000000000000000000000000000000000007C00000000susemanager-schema/upgrade/susemanager-schema-3.1.0-to-susemanager-schema-3.1.1/2004-rhnContentSourceSsl-create-indexes.sql   --
-- Copyright (c) 2017 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

CREATE UNIQUE INDEX rhn_csssl_ca_uq
    ON rhnContentSourceSsl (content_source_id, ssl_ca_cert_id)
    WHERE ssl_client_cert_id IS NULL AND ssl_client_key_id IS NULL;

CREATE UNIQUE INDEX rhn_csssl_ca_cert_uq
    ON rhnContentSourceSsl (content_source_id, ssl_ca_cert_id, ssl_client_cert_id)
    WHERE ssl_client_cert_id IS NOT NULL AND ssl_client_key_id IS NULL;

CREATE UNIQUE INDEX rhn_csssl_ca_cert_key_uq
    ON rhnContentSourceSsl (content_source_id, ssl_ca_cert_id, ssl_client_cert_id, ssl_client_key_id)
    WHERE ssl_client_cert_id IS NOT NULL AND ssl_client_key_id IS NOT NULL;
  07070100000BC8000081B400000000000000000000000167AE1114000003B3000000000000000000000000000000000000007D00000000susemanager-schema/upgrade/susemanager-schema-3.1.0-to-susemanager-schema-3.1.1/2004-rhnContentSourceSsl-create-triggers.sql  --
-- Copyright (c) 2017 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


create or replace function rhn_cont_source_ssl_mod_trig_fun() returns trigger as
$$
begin
	new.modified := current_timestamp;
	return new;
end;
$$ language plpgsql;

create trigger
rhn_cont_source_ssl_mod_trig
before insert or update on rhnContentSourceSsl
for each row
execute procedure rhn_cont_source_ssl_mod_trig_fun();
 07070100000BC9000081B400000000000000000000000167AE1114000001E1000000000000000000000000000000000000007700000000susemanager-schema/upgrade/susemanager-schema-3.1.0-to-susemanager-schema-3.1.1/2005-rhnContentSourceSsl-move-data.sql    insert into rhnContentSourceSsl
  (content_source_id, ssl_ca_cert_id, ssl_client_cert_id, ssl_client_key_id)
select id, ssl_ca_cert_id, ssl_client_cert_id, ssl_client_key_id
  from rhnContentSource where
  ssl_ca_cert_id is not null and
  (ssl_client_key_id is null or ssl_client_cert_id is not null);

alter table rhnContentSource drop column ssl_ca_cert_id;
alter table rhnContentSource drop column ssl_client_cert_id;
alter table rhnContentSource drop column ssl_client_key_id;
   07070100000BCA000081B400000000000000000000000167AE1114000000B0000000000000000000000000000000000000007300000000susemanager-schema/upgrade/susemanager-schema-3.1.0-to-susemanager-schema-3.1.1/3001-drop-legacy-audit-logging.sql    
DROP TABLE IF EXISTS rhnserver_log;
DROP TABLE IF EXISTS rhnservergroup_log;
DROP TABLE IF EXISTS web_contact_log;

DROP SCHEMA IF EXISTS  CASCADE;

DROP TABLE IF EXISTS log;
07070100000BCB000081B400000000000000000000000167AE111400000156000000000000000000000000000000000000006600000000susemanager-schema/upgrade/susemanager-schema-3.1.0-to-susemanager-schema-3.1.1/3002-drop-logging.sql 
DROP TRIGGER if exists web_contact_log_trig ON web_contact;
DROP FUNCTION if exists web_contact_log_trig_fun();

DROP TRIGGER if exists rhnserver_log_trig ON rhnserver;
DROP FUNCTION if exists rhnserver_log_trig_fun();

DROP TRIGGER if exists rhnservergroup_log_trig ON rhnservergroup;
DROP FUNCTION if exists rhnservergroup_log_trig_fun();
  07070100000BCC000081B400000000000000000000000167AE111400000B52000000000000000000000000000000000000007300000000susemanager-schema/upgrade/susemanager-schema-3.1.0-to-susemanager-schema-3.1.1/9001-add-ssm-detailed-features.sql    insert into rhnFeature (id, label, name, created, modified)
select sequence_nextval('rhn_feature_seq'), 'ftr_channel_membership', 'Channel Memberships',
        current_timestamp, current_timestamp from dual
where not exists (select 1 from rhnFeature where label = 'ftr_channel_membership');
insert into rhnFeature (id, label, name, created, modified)
select sequence_nextval('rhn_feature_seq'), 'ftr_channel_config_subscription', 'Config Channel Subscriptions',
        current_timestamp, current_timestamp from dual
where not exists (select 1 from rhnFeature where label = 'ftr_channel_config_subscription');
insert into rhnFeature (id, label, name, created, modified)
select sequence_nextval('rhn_feature_seq'), 'ftr_channel_deploy_diff', 'Deploy/Diff Config Channel',
        current_timestamp, current_timestamp from dual
where not exists (select 1 from rhnFeature where label = 'ftr_channel_deploy_diff');
insert into rhnFeature (id, label, name, created, modified)
select sequence_nextval('rhn_feature_seq'), 'ftr_tag_system', 'Tag System',
        current_timestamp, current_timestamp from dual
where not exists (select 1 from rhnFeature where label = 'ftr_tag_system');
insert into rhnFeature (id, label, name, created, modified)
select sequence_nextval('rhn_feature_seq'), 'ftr_power_management', 'Power Management Operations',
        current_timestamp, current_timestamp from dual
where not exists (select 1 from rhnFeature where label = 'ftr_power_management');
insert into rhnFeature (id, label, name, created, modified)
select sequence_nextval('rhn_feature_seq'), 'ftr_system_preferences', 'System Preferences',
        current_timestamp, current_timestamp from dual
where not exists (select 1 from rhnFeature where label = 'ftr_system_preferences');
insert into rhnFeature (id, label, name, created, modified)
select sequence_nextval('rhn_feature_seq'), 'ftr_system_custom_values', 'System Custom Values',
        current_timestamp, current_timestamp from dual
where not exists (select 1 from rhnFeature where label = 'ftr_system_custom_values');
insert into rhnFeature (id, label, name, created, modified)
select sequence_nextval('rhn_feature_seq'), 'ftr_add_rm_addon_type', 'Add/Remove Addon Type',
        current_timestamp, current_timestamp from dual
where not exists (select 1 from rhnFeature where label = 'ftr_add_rm_addon_type');
insert into rhnFeature (id, label, name, created, modified)
select sequence_nextval('rhn_feature_seq'), 'ftr_system_lock', 'Lock System',
        current_timestamp, current_timestamp from dual
where not exists (select 1 from rhnFeature where label = 'ftr_system_lock');
insert into rhnFeature (id, label, name, created, modified)
select sequence_nextval('rhn_feature_seq'), 'ftr_system_audit', 'Audit System',
        current_timestamp, current_timestamp from dual
where not exists (select 1 from rhnFeature where label = 'ftr_system_audit');
  07070100000BCD000081B400000000000000000000000167AE11140000183B000000000000000000000000000000000000007D00000000susemanager-schema/upgrade/susemanager-schema-3.1.0-to-susemanager-schema-3.1.1/9002-enable-entitlements-on-new-features.sql  
insert into rhnServerGroupTypeFeature (server_group_type_id, feature_id,
                                       created, modified)
select lookup_sg_type('enterprise_entitled'), lookup_feature_type('ftr_channel_membership'),
        current_timestamp,current_timestamp from dual
where not exists ( select 1 from rhnServerGroupTypeFeature
    where server_group_type_id = lookup_sg_type('enterprise_entitled')
      and feature_id = lookup_feature_type('ftr_channel_membership') );

insert into rhnServerGroupTypeFeature (server_group_type_id, feature_id,
                                       created, modified)
select lookup_sg_type('enterprise_entitled'), lookup_feature_type('ftr_channel_config_subscription'),
        current_timestamp,current_timestamp from dual
where not exists ( select 1 from rhnServerGroupTypeFeature
    where server_group_type_id = lookup_sg_type('enterprise_entitled')
      and feature_id = lookup_feature_type('ftr_channel_config_subscription') );

insert into rhnServerGroupTypeFeature (server_group_type_id, feature_id,
                                       created, modified)
select lookup_sg_type('enterprise_entitled'), lookup_feature_type('ftr_channel_deploy_diff'),
        current_timestamp,current_timestamp from dual
where not exists ( select 1 from rhnServerGroupTypeFeature
    where server_group_type_id = lookup_sg_type('enterprise_entitled')
      and feature_id = lookup_feature_type('ftr_channel_deploy_diff') );

insert into rhnServerGroupTypeFeature (server_group_type_id, feature_id,
                                       created, modified)
select lookup_sg_type('enterprise_entitled'), lookup_feature_type('ftr_tag_system'),
        current_timestamp,current_timestamp from dual
where not exists ( select 1 from rhnServerGroupTypeFeature
    where server_group_type_id = lookup_sg_type('enterprise_entitled')
      and feature_id = lookup_feature_type('ftr_tag_system') );

insert into rhnServerGroupTypeFeature (server_group_type_id, feature_id,
                                       created, modified)
select lookup_sg_type('enterprise_entitled'), lookup_feature_type('ftr_power_management'),
        current_timestamp,current_timestamp from dual
where not exists ( select 1 from rhnServerGroupTypeFeature
    where server_group_type_id = lookup_sg_type('enterprise_entitled')
      and feature_id = lookup_feature_type('ftr_power_management') );

insert into rhnServerGroupTypeFeature (server_group_type_id, feature_id,
                                       created, modified)
select lookup_sg_type('enterprise_entitled'), lookup_feature_type('ftr_system_preferences'),
        current_timestamp,current_timestamp from dual
where not exists ( select 1 from rhnServerGroupTypeFeature
    where server_group_type_id = lookup_sg_type('enterprise_entitled')
      and feature_id = lookup_feature_type('ftr_system_preferences') );

insert into rhnServerGroupTypeFeature (server_group_type_id, feature_id,
                                       created, modified)
select lookup_sg_type('enterprise_entitled'), lookup_feature_type('ftr_system_custom_values'),
        current_timestamp,current_timestamp from dual
where not exists ( select 1 from rhnServerGroupTypeFeature
    where server_group_type_id = lookup_sg_type('enterprise_entitled')
      and feature_id = lookup_feature_type('ftr_system_custom_values') );

insert into rhnServerGroupTypeFeature (server_group_type_id, feature_id,
                                       created, modified)
select lookup_sg_type('enterprise_entitled'), lookup_feature_type('ftr_add_rm_addon_type'),
        current_timestamp,current_timestamp from dual
where not exists ( select 1 from rhnServerGroupTypeFeature
    where server_group_type_id = lookup_sg_type('enterprise_entitled')
      and feature_id = lookup_feature_type('ftr_add_rm_addon_type') );

insert into rhnServerGroupTypeFeature (server_group_type_id, feature_id,
                                       created, modified)
select lookup_sg_type('enterprise_entitled'), lookup_feature_type('ftr_system_lock'),
        current_timestamp,current_timestamp from dual
where not exists ( select 1 from rhnServerGroupTypeFeature
    where server_group_type_id = lookup_sg_type('enterprise_entitled')
      and feature_id = lookup_feature_type('ftr_system_lock') );

insert into rhnServerGroupTypeFeature (server_group_type_id, feature_id,
                                       created, modified)
select lookup_sg_type('enterprise_entitled'), lookup_feature_type('ftr_system_audit'),
        current_timestamp,current_timestamp from dual
where not exists ( select 1 from rhnServerGroupTypeFeature
    where server_group_type_id = lookup_sg_type('enterprise_entitled')
      and feature_id = lookup_feature_type('ftr_system_audit') );

insert into rhnServerGroupTypeFeature (server_group_type_id, feature_id,
                                       created, modified)
select lookup_sg_type('salt_entitled'), lookup_feature_type('ftr_channel_membership'),
        current_timestamp,current_timestamp from dual
where not exists ( select 1 from rhnServerGroupTypeFeature
    where server_group_type_id = lookup_sg_type('salt_entitled')
      and feature_id = lookup_feature_type('ftr_channel_membership') );

insert into rhnServerGroupTypeFeature (server_group_type_id, feature_id,
                                       created, modified)
select lookup_sg_type('salt_entitled'), lookup_feature_type('ftr_system_custom_values'),
        current_timestamp,current_timestamp from dual
where not exists ( select 1 from rhnServerGroupTypeFeature
    where server_group_type_id = lookup_sg_type('salt_entitled')
      and feature_id = lookup_feature_type('ftr_system_custom_values') );

insert into rhnServerGroupTypeFeature (server_group_type_id, feature_id,
                                       created, modified)
select lookup_sg_type('bootstrap_entitled'), lookup_feature_type('ftr_power_management'),
        current_timestamp,current_timestamp from dual
where not exists ( select 1 from rhnServerGroupTypeFeature
    where server_group_type_id = lookup_sg_type('bootstrap_entitled')
      and feature_id = lookup_feature_type('ftr_power_management') );
 07070100000BCE000081B400000000000000000000000167AE111400000FEC000000000000000000000000000000000000007B00000000susemanager-schema/upgrade/susemanager-schema-3.1.0-to-susemanager-schema-3.1.1/9004-add-docker_build_host-system_type.sql    -- container_build_host type ----------------------------------------------------

insert into rhnServerGroupType ( id, label, name, permanent, is_base)
   values ( sequence_nextval('rhn_servergroup_type_seq'),
      'container_build_host', 'Container Build Host',
      'N', 'N'
   );


-- container_build_host* compatibilities --

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type)
    values (lookup_server_arch('i386-redhat-linux'),
            lookup_sg_type('container_build_host'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type)
    values (lookup_server_arch('i386-debian-linux'),
            lookup_sg_type('container_build_host'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type)
    values (lookup_server_arch('i486-redhat-linux'),
            lookup_sg_type('container_build_host'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type)
    values (lookup_server_arch('i586-redhat-linux'),
            lookup_sg_type('container_build_host'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type)
    values (lookup_server_arch('i686-redhat-linux'),
            lookup_sg_type('container_build_host'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type)
    values (lookup_server_arch('athlon-redhat-linux'),
            lookup_sg_type('container_build_host'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type)
    values (lookup_server_arch('amd64-redhat-linux'),
            lookup_sg_type('container_build_host'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type)
    values (lookup_server_arch('amd64-debian-linux'),
            lookup_sg_type('container_build_host'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type)
    values (lookup_server_arch('ia64-redhat-linux'),
            lookup_sg_type('container_build_host'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type)
    values (lookup_server_arch('ia64-debian-linux'),
            lookup_sg_type('container_build_host'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type)
    values (lookup_server_arch('ia32e-redhat-linux'),
            lookup_sg_type('container_build_host'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type)
    values (lookup_server_arch('s390-redhat-linux'),
            lookup_sg_type('container_build_host'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type)
    values (lookup_server_arch('s390-debian-linux'),
            lookup_sg_type('container_build_host'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type)
    values (lookup_server_arch('s390x-redhat-linux'),
            lookup_sg_type('container_build_host'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type)
    values (lookup_server_arch('ppc-redhat-linux'),
            lookup_sg_type('container_build_host'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type)
    values (lookup_server_arch('powerpc-debian-linux'),
            lookup_sg_type('container_build_host'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type)
    values (lookup_server_arch('ppc64-redhat-linux'),
            lookup_sg_type('container_build_host'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type)
    values (lookup_server_arch('ppc64le-redhat-linux'),
            lookup_sg_type('container_build_host'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type)
    values (lookup_server_arch('x86_64-redhat-linux'),
            lookup_sg_type('container_build_host'));

-- rhnSGTypeBaseAddonCompat

insert into rhnSGTypeBaseAddonCompat (base_id, addon_id)
values (lookup_sg_type('salt_entitled'),
        lookup_sg_type('container_build_host'));
07070100000BCF000081B400000000000000000000000167AE111400000280000000000000000000000000000000000000007100000000susemanager-schema/upgrade/susemanager-schema-3.1.0-to-susemanager-schema-3.1.1/9005-add-system_type-to-orgs.sql  -- create server group for 'container_build_host' everywhere
insert into rhnServerGroup ( id, name, description, group_type, org_id )
  select sequence_nextval('rhn_server_group_id_seq'), sgt.name, sgt.name, sgt.id, X.org_id
  from rhnServerGroupType sgt,
     (select distinct msg.org_id
        from rhnServerGroup msg
       where msg.org_id not in (select org_id
                                  from rhnServerGroup sg
                                  join rhnServerGroupType sgt ON sgt.id = sg.group_type
                                 where sgt.label = 'container_build_host')
     ) X
  where sgt.label = 'container_build_host';
07070100000BD0000081B400000000000000000000000167AE1114000019BC000000000000000000000000000000000000006C00000000susemanager-schema/upgrade/susemanager-schema-3.1.0-to-susemanager-schema-3.1.1/9006-mod-create_new_org.sql   --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--

create or replace function create_new_org
(
        name_in      in varchar,
        password_in  in varchar
        --org_id_out   out NUMERIC
) returns numeric
as
$$
declare
        ug_type                 numeric;
        group_val               numeric;
        new_org_id              numeric;
        org_id_out		numeric;
begin

        select nextval('web_customer_id_seq') into new_org_id from dual;

        insert into web_customer (
                id, name
        ) values (
                new_org_id, name_in
        );

        select nextval('rhn_user_group_id_seq') into group_val from dual;

        select  id
        into    ug_type
        from    rhnUserGroupType
        where   label = 'org_admin';

        insert into rhnUserGroup (
                id, name,
                description,
                max_members, group_type, org_id
        ) values (
                group_val, 'Organization Administrators',
                'Organization Administrators for Org ' || name_in,
                NULL, ug_type, new_org_id
        );

        select nextval('rhn_user_group_id_seq') into group_val from dual;

        select  id
        into    ug_type
        from    rhnUserGroupType
        where   label = 'system_group_admin';

        insert into rhnUserGroup (
                id, name,
                description,
                max_members, group_type, org_id
        ) values (
                group_val, 'System Group Administrators',
                'System Group Administrators for Org ' || name_in,
                NULL, ug_type, new_org_id
        );


        select nextval('rhn_user_group_id_seq') into group_val from dual;

        select  id
        into    ug_type
        from    rhnUserGroupType
        where   label = 'activation_key_admin';

        insert into rhnUserGroup (
                id, name,
                description,
                max_members, group_type, org_id
        ) values (
                group_val, 'Activation Key Administrators',
                'Activation Key Administrators for Org ' || name_in,
                NULL, ug_type, new_org_id
        );

        select nextval('rhn_user_group_id_seq') into group_val from dual;

        select  id
        into    ug_type
        from    rhnUserGroupType
        where   label = 'channel_admin';

        insert into rhnUserGroup (
                id, name,
                description,
                max_members, group_type, org_id
        ) values (
                group_val, 'Channel Administrators',
                'Channel Administrators for Org ' || name_in,
                NULL, ug_type, new_org_id
        );

	if new_org_id = 1 then
            select nextval('rhn_user_group_id_seq') into group_val from dual;

            select  id
            into    ug_type
            from    rhnUserGroupType
            where   label = 'satellite_admin';

            insert into rhnUserGroup (
                    id, name,
                    description,
                    max_members, group_type, org_id
            ) values (
                    group_val, 'SUSE Manager Administrators',
                    'SUSE Manager Administrators for Org ' || name_in,
                    NULL, ug_type, new_org_id
            );
        end if;

        select nextval('rhn_user_group_id_seq') into group_val from dual;

        select  id
        into    ug_type
        from    rhnUserGroupType
        where   label = 'config_admin';

        insert into rhnUserGroup (
                id, name,
                description,
                max_members, group_type, org_id
        ) values (
                group_val, 'Configuration Administrators',
                'Configuration Administrators for Org ' || name_in,
                NULL, ug_type, new_org_id
        );

        -- there aren't any users yet, so we don't need to update
        -- rhnUserServerPerms

        insert into rhnServerGroup
                ( id, name, description, group_type, org_id )
                select nextval('rhn_server_group_id_seq'), sgt.name, sgt.name,
                        sgt.id, new_org_id
                from rhnServerGroupType sgt
                where sgt.label = 'bootstrap_entitled';

        insert into rhnServerGroup
                ( id, name, description, group_type, org_id )
                select nextval('rhn_server_group_id_seq'), sgt.name, sgt.name,
                        sgt.id, new_org_id
                from rhnServerGroupType sgt
                where sgt.label = 'enterprise_entitled';

        insert into rhnServerGroup
                ( id, name, description, group_type, org_id )
                select nextval('rhn_server_group_id_seq'), sgt.name, sgt.name,
                        sgt.id, new_org_id
                from rhnServerGroupType sgt
                where sgt.label = 'salt_entitled';

        insert into rhnServerGroup
                ( id, name, description, group_type, org_id )
                select nextval('rhn_server_group_id_seq'), sgt.name, sgt.name,
                        sgt.id, new_org_id
                from rhnServerGroupType sgt
                where sgt.label = 'foreign_entitled';

        insert into rhnServerGroup
                ( id, name, description, group_type, org_id )
                select nextval('rhn_server_group_id_seq'), sgt.name, sgt.name,
                        sgt.id, new_org_id
                from rhnServerGroupType sgt
                where sgt.label = 'virtualization_host';

        insert into rhnServerGroup
                ( id, name, description, group_type, org_id )
                select nextval('rhn_server_group_id_seq'), sgt.name, sgt.name,
                        sgt.id, new_org_id
                from rhnServerGroupType sgt
                where sgt.label = 'container_build_host';

        org_id_out := new_org_id;

	-- Returning the value of OUT parameter
        return org_id_out;

end;
$$
language plpgsql;


07070100000BD1000081B400000000000000000000000167AE111400002E8D000000000000000000000000000000000000006E00000000susemanager-schema/upgrade/susemanager-schema-3.1.0-to-susemanager-schema-3.1.1/9007-mod-rhn_entitlements.sql --
-- Copyright (c) 2008--2015 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

-- create schema rhn_entitlements;

-- setup search_path so that these functions are created in appropriate schema.
update pg_settings set setting = 'rhn_entitlements,' || setting where name = 'search_path';

   create or replace function find_compatible_sg (
      server_id_in in numeric,
      type_label_in in varchar
   )
   returns numeric
as $$
    declare
      servergroups cursor for
         select sg.id
           from rhnServerGroupType             sgt,
                rhnServerGroup                 sg,
                rhnServer                     s,
                rhnServerServerGroupArchCompat ssgac
          where s.id = server_id_in
            and s.org_id = sg.org_id
            and sgt.label = type_label_in
            and sg.group_type = sgt.id
            and ssgac.server_group_type = sgt.id
            and ssgac.server_arch_id = s.server_arch_id
            and not exists (
                     select 1
                      from rhnServerGroupMembers sgm
                     where sgm.server_group_id = sg.id
                       and sgm.server_id = s.id);


   begin
      for servergroup in servergroups loop
         return servergroup.id;
      end loop;

      --no servergroup found
      return NULL;
   end$$
language plpgsql;


    create or replace function entitlement_grants_service (
        entitlement_in in varchar,
        service_level_in in varchar
    ) returns numeric
as $$
    begin
        if service_level_in = 'management' then
            if entitlement_in = 'enterprise_entitled' or entitlement_in = 'salt_entitled' then
                return 1;
            else
                return 0;
            end if;
        elsif service_level_in = 'updates' then
            return 1;
        else
            return 0;
        end if;
    end$$
language plpgsql;

   create or replace function can_entitle_server (
      server_id_in   in numeric,
      type_label_in  in varchar
   )
   returns numeric
as $$
    declare
      addon_servergroups cursor (base_label_in varchar,
                                 addon_label_in varchar) for
         select
            addon_id
         from
            rhnSGTypeBaseAddonCompat
         where base_id = lookup_sg_type (base_label_in)
           and addon_id = lookup_sg_type (addon_label_in);

      previous_ent        varchar[];
      is_base_in          char   := 'N';
      is_base_current     char   := 'N';
      i                   numeric := 0;
      sgid                numeric := 0;

   begin

      previous_ent := rhn_entitlements.get_server_entitlement(server_id_in);

      select distinct is_base
      into is_base_in
      from rhnServerGroupType
      where label = type_label_in;

      if array_upper(previous_ent, 1) is null or array_upper(previous_ent, 1) = 0 then
         if is_base_in = 'Y' then
            sgid := rhn_entitlements.find_compatible_sg (server_id_in, type_label_in);
            if sgid is not null then
              -- rhn_server.insert_into_servergroup (server_id_in, sgid);
              return 1;
            else
              -- rhn_exception.raise_exception ('invalid_base_entitlement');
              return 0;
            end if;
         else
            -- rhn_exception.raise_exception ('invalid_base_entitlement');
            return 0;
         end if;

      -- there are previous ents, first make sure we're not trying to entitle a base ent
      elsif is_base_in = 'Y' then
         -- rhn_exception.raise_exception ('invalid_addon_entitlement');
         return 0;

      -- it must be an addon, so proceed with the entitlement
      else

         -- find the servers base ent
         is_base_current := 'N';
         i := 0;
         while is_base_current = 'N' and i < array_upper(previous_ent, 1)
         loop
            i := i + 1;
            select is_base
            into is_base_current
            from rhnServerGroupType
            where label = previous_ent[i];
         end loop;

         -- never found a base ent, that would be strange
         if is_base_current  = 'N' then
            -- rhn_exception.raise_exception ('invalid_base_entitlement');
            return 0;
         end if;

         -- this for loop verifies the validity of the addon path
         for addon_servergroup in addon_servergroups  (previous_ent[i], type_label_in) loop
            -- find an appropriate sgid for the addon and entitle the server
            sgid := rhn_entitlements.find_compatible_sg (server_id_in, type_label_in);
            if sgid is not null then
               -- rhn_server.insert_into_servergroup (server_id_in, sgid);
               return 1;
            else
               -- rhn_exception.raise_exception ('invalid_addon_entitlement');
               return 0;
            end if;
         end loop;

      end if;

      return 0;

   end$$
language plpgsql;

   create or replace function can_switch_base (
      server_id_in   in    integer,
      type_label_in  in    varchar
   )
   returns numeric
as $$
   declare
      type_label_in_is_base   char(1);
      sgid                    numeric;

   begin

       select is_base into type_label_in_is_base
       from rhnServerGroupType
       where label = type_label_in;

       if not found then
          perform rhn_exception.raise_exception ( 'invalid_entitlement' );
       end if;

      if type_label_in_is_base = 'N' then
         perform rhn_exception.raise_exception ( 'invalid_entitlement' );
      else
         sgid := rhn_entitlements.find_compatible_sg ( server_id_in,
                                                       type_label_in );
         if sgid is not null then
           return 1;
         else
           return 0;
         end if;
      end if;

   end$$
language plpgsql;

    create or replace function entitle_server (
        server_id_in in numeric,
        type_label_in in varchar
    ) returns void
as $$
    declare
      sgid  numeric := 0;

    begin

      if rhn_entitlements.can_entitle_server(server_id_in,
                                             type_label_in) = 1 then
         sgid := rhn_entitlements.find_compatible_sg (server_id_in,
                                                      type_label_in);
         if sgid is not null then
            insert into rhnServerHistory ( id, server_id, summary, details )
            values ( nextval('rhn_event_id_seq'), server_id_in,
                     'added system entitlement ',
                      case type_label_in
                       when 'enterprise_entitled' then 'Management'
                       when 'bootstrap_entitled' then 'Bootstrap'
                       when 'salt_entitled' then 'Salt'
                       when 'foreign_entitled' then 'Foreign'
                       when 'virtualization_host' then 'Virtualization'
                       when 'container_build_host' then 'Container'
                      end  );

            perform rhn_server.insert_into_servergroup (server_id_in, sgid);

         else
            perform rhn_exception.raise_exception ('no_available_server_group');
         end if;
      else
         perform rhn_exception.raise_exception ('invalid_entitlement');
      end if;
   end$$
language plpgsql;

    create or replace function remove_server_entitlement (
        server_id_in in numeric,
        type_label_in in varchar
    ) returns void
as $$
    declare
      group_id numeric;
      type_is_base char;
    begin

        select  sg.id, sgt.is_base
        into group_id, type_is_base
        from    rhnServerGroupType sgt,
            rhnServerGroup sg,
                rhnServerGroupMembers sgm,
                rhnServer s
        where   s.id = server_id_in
            and s.id = sgm.server_id
            and sgm.server_group_id = sg.id
            and sg.org_id = s.org_id
            and sgt.label = type_label_in
            and sgt.id = sg.group_type;

        if not found then
          perform rhn_exception.raise_exception('invalid_server_group_member');
        end if;

      if ( type_is_base = 'Y' ) then
         -- unentitle_server should handle everything, don't really need to do anything else special here
         perform rhn_entitlements.unentitle_server ( server_id_in );
      else

         insert into rhnServerHistory ( id, server_id, summary, details )
         values ( nextval('rhn_event_id_seq'), server_id_in,
                  'removed system entitlement ',
                   case type_label_in
                    when 'enterprise_entitled' then 'Management'
                    when 'bootstrap_entitled' then 'Bootstrap'
                    when 'salt_entitled' then 'Salt'
                    when 'foreign_entitled' then 'Foreign'
                    when 'virtualization_host' then 'Virtualization'
                    when 'container_build_host' then 'Container'
                   end  );

         perform rhn_server.delete_from_servergroup(server_id_in, group_id);

      end if;

    end$$
language plpgsql;

    create or replace function unentitle_server (
        server_id_in in numeric
    ) returns void
as $$
    declare
      servergroups cursor for
         select distinct sgt.label, sg.id server_group_id
         from  rhnServerGroupType sgt,
               rhnServerGroup sg,
               rhnServer s,
               rhnServerGroupMembers sgm
         where s.id = server_id_in
            and s.org_id = sg.org_id
            and sg.group_type = sgt.id
            and sgm.server_group_id = sg.id
            and sgm.server_id = s.id;

   begin

      for servergroup in servergroups loop

         insert into rhnServerHistory ( id, server_id, summary, details )
         values ( nextval('rhn_event_id_seq'), server_id_in,
                  'removed system entitlement ',
                   case servergroup.label
                    when 'enterprise_entitled' then 'Management'
                    when 'bootstrap_entitled' then 'Bootstrap'
                    when 'salt_entitled' then 'Salt'
                    when 'foreign_entitled' then 'Foreign'
                    when 'virtualization_host' then 'Virtualization'
                    when 'container_build_host' then 'Container'
                   end  );

         perform rhn_server.delete_from_servergroup(server_id_in,
                                            servergroup.server_group_id );
      end loop;

   end$$
language plpgsql;


    create or replace function get_server_entitlement (
        server_id_in in numeric
    ) returns varchar[]
as $$
    declare
        server_groups cursor for
            select  sgt.label
            from    rhnServerGroupType      sgt,
                    rhnServerGroup          sg,
                    rhnServerGroupMembers   sgm
            where   1=1
                and sgm.server_id = server_id_in
                and sg.id = sgm.server_group_id
                and sgt.id = sg.group_type;

         ent_array varchar[];

    begin

      ent_array := '{}';

      for sg in server_groups loop
         ent_array := ent_array || sg.label;
      end loop;

      return ent_array;

    end$$
language plpgsql;

-- restore the original setting
update pg_settings set setting = overlay( setting placing '' from 1 for (length('rhn_entitlements')+1) ) where name = 'search_path';
   07070100000BD2000081B400000000000000000000000167AE111400000952000000000000000000000000000000000000006800000000susemanager-schema/upgrade/susemanager-schema-3.1.0-to-susemanager-schema-3.1.1/9008-suseImageStore.sql   --
-- Copyright (c) 2017 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

CREATE TABLE suseImageStoreType
(
    id     NUMERIC NOT NULL
                 CONSTRAINT suse_imgstore_type_id_pk PRIMARY KEY,
    label  VARCHAR(128) NOT NULL,
    name   VARCHAR(128) NOT NULL
)

;

CREATE UNIQUE INDEX suse_imgstore_type_label_uq
    ON suseImageStoreType (label)
        ;

CREATE UNIQUE INDEX suse_imgstore_type_name_uq
    ON suseImageStoreType (name)
        ;

CREATE SEQUENCE suse_imgstore_type_id_seq;

-----------------------------------------------------------------

CREATE TABLE suseImageStore
(
    id             NUMERIC NOT NULL
                     CONSTRAINT suse_imgstore_id_pk PRIMARY KEY,
    label          VARCHAR(128) NOT NULL,
    uri            VARCHAR(512) NOT NULL,
    store_type_id  NUMERIC NOT NULL
                     CONSTRAINT suse_imgstore_type_fk
                       REFERENCES suseImageStoreType (id)
                       ON DELETE CASCADE,
    org_id         NUMERIC NOT NULL
                     CONSTRAINT suse_imgstore_oid_fk
                       REFERENCES web_customer (id)
                       ON DELETE CASCADE,
    creds_id       NUMERIC
                     CONSTRAINT suse_imgstore_creds_fk
                       REFERENCES suseCredentials (id)
                       ON DELETE SET NULL,
    created        TIMESTAMPTZ
                     DEFAULT (current_timestamp) NOT NULL,
    modified       TIMESTAMPTZ
                     DEFAULT (current_timestamp) NOT NULL
)

;

CREATE UNIQUE INDEX suse_imgstore_label_uq
    ON suseImageStore (label)
        ;

CREATE SEQUENCE suse_imgstore_id_seq;

-----------------------------------------------------------------

insert into suseImageStoreType (id, label, name) values
	(sequence_nextval('suse_imgstore_type_id_seq'), 'registry', 'Registry');
  07070100000BD3000081B400000000000000000000000167AE1114000002FB000000000000000000000000000000000000007000000000susemanager-schema/upgrade/susemanager-schema-3.1.0-to-susemanager-schema-3.1.1/9010-suseImageStore-trigger.sql   --
-- Copyright (c) 2017 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- triggers for suseImageStore

create or replace function suse_imgstore_mod_trig_fun() returns trigger as
$$
begin
	new.modified := current_timestamp;
	return new;
end;
$$ language plpgsql;

create trigger
suse_imgstore_mod_trig
before insert or update on suseImageStore
for each row
execute procedure suse_imgstore_mod_trig_fun();
 07070100000BD4000081B400000000000000000000000167AE111400000698000000000000000000000000000000000000006E00000000susemanager-schema/upgrade/susemanager-schema-3.1.0-to-susemanager-schema-3.1.1/9011-add-suseImageProfile.sql --
-- Copyright (c) 2017 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

CREATE TABLE suseImageProfile
(
    profile_id     NUMERIC NOT NULL
                     CONSTRAINT suse_imgprof_prid_pk PRIMARY KEY,
    label          VARCHAR(128) NOT NULL,
    org_id         NUMERIC NOT NULL
                     CONSTRAINT suse_imgprof_oid_fk
                       REFERENCES web_customer (id)
                       ON DELETE CASCADE,
    token_id       NUMERIC
                     CONSTRAINT suse_imgprof_tk_fk
                       REFERENCES rhnRegToken (id)
                       ON DELETE SET NULL,
    image_type     VARCHAR(32) NOT NULL,
    target_store_id NUMERIC NOT NULL
                      CONSTRAINT suse_imgprof_tsid_fk
                         REFERENCES suseImageStore (id)
                         ON DELETE CASCADE,
    created        TIMESTAMPTZ
                     DEFAULT (current_timestamp) NOT NULL,
    modified       TIMESTAMPTZ
                     DEFAULT (current_timestamp) NOT NULL
)

;

CREATE UNIQUE INDEX suse_imgprof_label_uq
    ON suseImageProfile (label)
        ;

CREATE SEQUENCE suse_imgprof_prid_seq;
07070100000BD5000081B400000000000000000000000167AE111400000378000000000000000000000000000000000000007300000000susemanager-schema/upgrade/susemanager-schema-3.1.0-to-susemanager-schema-3.1.1/9012-add-suseDockerfileProfile.sql    --
-- Copyright (c) 2017 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

CREATE TABLE suseDockerfileProfile
(
    profile_id  NUMERIC NOT NULL
                  CONSTRAINT suse_dockfileprof_prid_fk
                     REFERENCES suseImageProfile (profile_id)
                     ON DELETE CASCADE,
    path        VARCHAR(1024) NOT NULL
)

;
07070100000BD6000081B400000000000000000000000167AE11140000077D000000000000000000000000000000000000007800000000susemanager-schema/upgrade/susemanager-schema-3.1.0-to-susemanager-schema-3.1.1/9013-add-suseProfileCustomDataValue.sql   --
-- Copyright (c) 2017 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

CREATE TABLE suseProfileCustomDataValue
(
    id                NUMERIC NOT NULL
                          CONSTRAINT suse_pcdv_id_pk PRIMARY KEY,
    profile_id        NUMERIC NOT NULL
                          CONSTRAINT suse_pcdv_prid_fk
                              REFERENCES suseImageProfile (profile_id),
    key_id            NUMERIC NOT NULL
                          CONSTRAINT suse_pcdv_kid_fk
                              REFERENCES rhnCustomDataKey (id),
    value             VARCHAR(4000),
    created_by        NUMERIC
                          CONSTRAINT suse_pcdv_cb_fk
                              REFERENCES web_contact (id)
                              ON DELETE SET NULL,
    last_modified_by  NUMERIC
                          CONSTRAINT suse_pcdv_lmb_fk
                              REFERENCES web_contact (id)
                              ON DELETE SET NULL,
    created           TIMESTAMPTZ
                          DEFAULT (current_timestamp) NOT NULL,
    modified          TIMESTAMPTZ
                          DEFAULT (current_timestamp) NOT NULL
)

;

CREATE UNIQUE INDEX suse_pcdv_prid_kid_uq
    ON suseProfileCustomDataValue (profile_id, key_id);

CREATE INDEX suse_pcdv_kid_idx
    ON suseProfileCustomDataValue (key_id);

CREATE SEQUENCE suse_pcdv_id_seq;
   07070100000BD7000081B400000000000000000000000167AE1114000002FC000000000000000000000000000000000000007200000000susemanager-schema/upgrade/susemanager-schema-3.1.0-to-susemanager-schema-3.1.1/9014-suseImageProfile-trigger.sql --
-- Copyright (c) 2017 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- triggers for suseImageProfile

create or replace function suse_imgprof_mod_trig_fun() returns trigger as
$$
begin
	new.modified := current_timestamp;
	return new;
end;
$$ language plpgsql;

create trigger
suse_imgprof_mod_trig
before insert or update on suseImageProfile
for each row
execute procedure suse_imgprof_mod_trig_fun();
07070100000BD8000081B400000000000000000000000167AE111400000130000000000000000000000000000000000000007C00000000susemanager-schema/upgrade/susemanager-schema-3.1.0-to-susemanager-schema-3.1.1/9015-suseProfileCustomDataValue-trigger.sql   
create or replace function suse_pcdv_mod_trig_fun() returns trigger as
$$
begin
	new.modified := current_timestamp;
 	return new;
end;
$$ language plpgsql;

create trigger
suse_pcdv_mod_trig
before insert or update on suseProfileCustomDataValue
for each row
execute procedure suse_pcdv_mod_trig_fun();

07070100000BD9000081B400000000000000000000000167AE111400000356000000000000000000000000000000000000007700000000susemanager-schema/upgrade/susemanager-schema-3.1.0-to-susemanager-schema-3.1.1/9016-add-image_admin-UserGroupType.sql    insert into rhnUserGroupType (id, label, name) values (
	sequence_nextval('rhn_usergroup_type_seq'),
	'image_admin',
	'Image Administrator'
);

-- create image_admin role to existing orgs
insert into rhnUserGroup ( id, name, description, max_members, group_type, org_id )
  select sequence_nextval('rhn_user_group_id_seq'), 'Image Administrators',
         'Image Administrators for Org ' || wc.name, NULL,
         (select id from rhnUserGroupType where label = 'image_admin'), wc.id
  from web_customer wc,
       (select distinct ug.org_id
        from rhnUserGroup ug
        where ug.org_id not in (select org_id
                                from rhnUserGroup xug
                                join rhnUserGroupType xugt ON xugt.id = xug.group_type
                                where xugt.label = 'image_admin')) X
  where X.org_id = wc.id;
  07070100000BDA000081B400000000000000000000000167AE111400001714000000000000000000000000000000000000006600000000susemanager-schema/upgrade/susemanager-schema-3.1.0-to-susemanager-schema-3.1.1/9017-rhn_user.pkb.sql --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--

-- create schema rhn_user;

-- setup search_path so that these functions are created in appropriate schema.
update pg_settings set setting = 'rhn_user,' || setting where name = 'search_path';

create or replace function
check_role(user_id_in in numeric, role_in in varchar)
    returns numeric as $$
    declare
    	throwaway numeric;
    begin
    	-- the idea: if we get past this query, the org has the setting, else catch the exception and return 0
	select 1 into throwaway
	  from rhnUserGroupType UGT,
	       rhnUserGroup UG,
	       rhnUserGroupMembers UGM
	 where UGM.user_id = user_id_in
	   and UGM.user_group_id = UG.id
	   and UG.group_type = UGT.id
	   and UGT.label = role_in;

        if not found then
            return 0;
        end if;

	return 1;
    end;
$$ language plpgsql;

create or replace
    function check_role_implied(user_id_in in numeric, role_in in varchar)
    returns numeric as $$
    declare
    	throwaway numeric;
    begin
    	-- if the user directly has the role, they win
    	if rhn_user.check_role(user_id_in, role_in) = 1
	then
	    return 1;
    	end if;

	-- config_admin and channel_admin are automatically implied for org admins	
	if role_in = 'config_admin' and rhn_user.check_role(user_id_in, 'org_admin') = 1
	then
	    return 1;
	end if;

	if role_in = 'channel_admin' and rhn_user.check_role(user_id_in, 'org_admin') = 1
	then
	    return 1;
	end if;

	if role_in = 'image_admin' and rhn_user.check_role(user_id_in, 'org_admin') = 1
	then
	    return 1;
	end if;

	return 0;	
    end;
$$ language plpgsql;

create or replace
    function get_org_id(user_id_in in numeric)
    returns numeric as $$
    declare
    	org_id_out numeric;
    begin
    	select org_id into org_id_out
	  from web_contact
	 where id = user_id_in;
	 
	return org_id_out;
    end;
$$ language plpgsql;

create or replace
	function add_servergroup_perm(
		user_id_in in numeric,
		server_group_id_in in numeric
	) returns void as $$
        declare
            okay record;
	begin
		for okay in
			select	1
			from	rhnServerGroup sg,
					web_contact u
			where	u.id = user_id_in
				and sg.id = server_group_id_in
				and sg.org_id = u.org_id
                loop
		insert into rhnUserServerGroupPerms(user_id, server_group_id)
				values (user_id_in, server_group_id_in);
			perform rhn_cache.update_perms_for_user(user_id_in);
			return;
		end loop;
		perform rhn_exception.raise_exception('usgp_different_orgs');
	exception when UNIQUE_VIOLATION then
		perform rhn_exception.raise_exception('usgp_already_allowed');
	end;
$$ language plpgsql;

create or replace
	function remove_servergroup_perm(
		user_id_in in numeric,
		server_group_id_in in numeric
	) returns void as $$
        declare
            perm record;
	begin
		for perm in
			select	1
			from	rhnUserServerGroupPerms
			where	user_id = user_id_in
				and server_group_id = server_group_id_in
                loop
		delete from rhnUserServerGroupPerms
				where	user_id = user_id_in
					and server_group_id = server_group_id_in;
			perform rhn_cache.update_perms_for_user(user_id_in);
			return;
		end loop;
		perform rhn_exception.raise_exception('usgp_not_allowed');
	end;
$$ language plpgsql;

create or replace
	function add_to_usergroup(
		user_id_in in numeric,
		user_group_id_in in numeric
	) returns void as $$
        declare
            ugr record;
	begin
		insert into rhnUserGroupMembers(user_id, user_group_id)
			values (user_id_in, user_group_id_in);

		for ugr in
			select	user_group_id_in
			from	rhnUserGroup		ug,
					rhnUserGroupType	ugt
			where	ugt.label in ('org_admin') -- and server_group_admin ?
				and ugr.id = user_group_id_in
				and ugr.group_type = ugt.id
                 loop
			perform rhn_cache.update_perms_for_user(user_id_in);
			return;
		end loop;
	end;
$$ language plpgsql;

create or replace
	function remove_from_usergroup(
		user_id_in in numeric,
		user_group_id_in in numeric
	) returns void as $$
        declare
            ugr record;
	begin
		-- we only do anything if you're really in the group, because
		-- testing is significantly cheaper than rebuilding the user's
		-- cache for no reason.
		for ugr in
			select	label
			from	rhnUserGroupType	ugt,
					rhnUserGroupMembers	ugm,
					rhnUserGroup		ug
			where	1=1
				and ug.id = user_group_id_in
				and ugm.user_group_id = user_group_id_in
				and ug.group_type = ugt.id
				and ugm.user_id = user_id_in
                 loop
			delete from rhnUserGroupMembers
				where	user_id = user_id_in
					and user_group_id = user_group_id_in;
			if ugr.label in ('org_admin') then
				perform rhn_cache.update_perms_for_user(user_id_in);
			end if;
		end loop;
	end;
$$ language plpgsql;

create or replace
        function role_names (user_id_in in numeric)
	returns varchar
	as
$$
	declare
		rec record;
		tmp varchar(4000);
	begin
		for rec in (
			select type_name
			from rhnUserTypeBase
			where user_id = user_id_in
			order by type_id
			) loop
			if tmp is null then
				tmp := rec.type_name;
			else
				tmp := tmp || ', ' || rec.type_name;
			end if;
		end loop;
		return tmp;
	end;
$$ language plpgsql;

-- restore the original setting
update pg_settings set setting = overlay( setting placing '' from 1 for (length('rhn_user')+1) ) where name = 'search_path';
07070100000BDB000081B400000000000000000000000167AE111400001BBD000000000000000000000000000000000000006800000000susemanager-schema/upgrade/susemanager-schema-3.1.0-to-susemanager-schema-3.1.1/9018-create_new_org.sql   --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--

create or replace function create_new_org
(
        name_in      in varchar,
        password_in  in varchar
        --org_id_out   out NUMERIC
) returns numeric
as
$$
declare
        ug_type                 numeric;
        group_val               numeric;
        new_org_id              numeric;
        org_id_out		numeric;
begin

        select nextval('web_customer_id_seq') into new_org_id from dual;

        insert into web_customer (
                id, name
        ) values (
                new_org_id, name_in
        );

        select nextval('rhn_user_group_id_seq') into group_val from dual;

        select  id
        into    ug_type
        from    rhnUserGroupType
        where   label = 'org_admin';

        insert into rhnUserGroup (
                id, name,
                description,
                max_members, group_type, org_id
        ) values (
                group_val, 'Organization Administrators',
                'Organization Administrators for Org ' || name_in,
                NULL, ug_type, new_org_id
        );

        select nextval('rhn_user_group_id_seq') into group_val from dual;

        select  id
        into    ug_type
        from    rhnUserGroupType
        where   label = 'system_group_admin';

        insert into rhnUserGroup (
                id, name,
                description,
                max_members, group_type, org_id
        ) values (
                group_val, 'System Group Administrators',
                'System Group Administrators for Org ' || name_in,
                NULL, ug_type, new_org_id
        );


        select nextval('rhn_user_group_id_seq') into group_val from dual;

        select  id
        into    ug_type
        from    rhnUserGroupType
        where   label = 'activation_key_admin';

        insert into rhnUserGroup (
                id, name,
                description,
                max_members, group_type, org_id
        ) values (
                group_val, 'Activation Key Administrators',
                'Activation Key Administrators for Org ' || name_in,
                NULL, ug_type, new_org_id
        );

        select nextval('rhn_user_group_id_seq') into group_val from dual;

        select  id
        into    ug_type
        from    rhnUserGroupType
        where   label = 'channel_admin';

        insert into rhnUserGroup (
                id, name,
                description,
                max_members, group_type, org_id
        ) values (
                group_val, 'Channel Administrators',
                'Channel Administrators for Org ' || name_in,
                NULL, ug_type, new_org_id
        );

	if new_org_id = 1 then
            select nextval('rhn_user_group_id_seq') into group_val from dual;

            select  id
            into    ug_type
            from    rhnUserGroupType
            where   label = 'satellite_admin';

            insert into rhnUserGroup (
                    id, name,
                    description,
                    max_members, group_type, org_id
            ) values (
                    group_val, 'SUSE Manager Administrators',
                    'SUSE Manager Administrators for Org ' || name_in,
                    NULL, ug_type, new_org_id
            );
        end if;

        select nextval('rhn_user_group_id_seq') into group_val from dual;

        select  id
        into    ug_type
        from    rhnUserGroupType
        where   label = 'config_admin';

        insert into rhnUserGroup (
                id, name,
                description,
                max_members, group_type, org_id
        ) values (
                group_val, 'Configuration Administrators',
                'Configuration Administrators for Org ' || name_in,
                NULL, ug_type, new_org_id
        );

        select nextval('rhn_user_group_id_seq') into group_val from dual;

        select  id
        into    ug_type
        from    rhnUserGroupType
        where   label = 'image_admin';

        insert into rhnUserGroup (
                id, name,
                description,
                max_members, group_type, org_id
        ) values (
                group_val, 'Image Administrators',
                'Image Administrators for Org ' || name_in,
                NULL, ug_type, new_org_id
        );

        -- there aren't any users yet, so we don't need to update
        -- rhnUserServerPerms

        insert into rhnServerGroup
                ( id, name, description, group_type, org_id )
                select nextval('rhn_server_group_id_seq'), sgt.name, sgt.name,
                        sgt.id, new_org_id
                from rhnServerGroupType sgt
                where sgt.label = 'bootstrap_entitled';

        insert into rhnServerGroup
                ( id, name, description, group_type, org_id )
                select nextval('rhn_server_group_id_seq'), sgt.name, sgt.name,
                        sgt.id, new_org_id
                from rhnServerGroupType sgt
                where sgt.label = 'enterprise_entitled';

        insert into rhnServerGroup
                ( id, name, description, group_type, org_id )
                select nextval('rhn_server_group_id_seq'), sgt.name, sgt.name,
                        sgt.id, new_org_id
                from rhnServerGroupType sgt
                where sgt.label = 'salt_entitled';

        insert into rhnServerGroup
                ( id, name, description, group_type, org_id )
                select nextval('rhn_server_group_id_seq'), sgt.name, sgt.name,
                        sgt.id, new_org_id
                from rhnServerGroupType sgt
                where sgt.label = 'foreign_entitled';

        insert into rhnServerGroup
                ( id, name, description, group_type, org_id )
                select nextval('rhn_server_group_id_seq'), sgt.name, sgt.name,
                        sgt.id, new_org_id
                from rhnServerGroupType sgt
                where sgt.label = 'virtualization_host';

        insert into rhnServerGroup
                ( id, name, description, group_type, org_id )
                select nextval('rhn_server_group_id_seq'), sgt.name, sgt.name,
                        sgt.id, new_org_id
                from rhnServerGroupType sgt
                where sgt.label = 'container_build_host';

        org_id_out := new_org_id;

	-- Returning the value of OUT parameter
        return org_id_out;

end;
$$
language plpgsql;


   07070100000BDC000081B400000000000000000000000167AE111400000957000000000000000000000000000000000000007000000000susemanager-schema/upgrade/susemanager-schema-3.1.0-to-susemanager-schema-3.1.1/9019-add-image-build-action.sql   --
-- Copyright (c) 2016 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

CREATE TABLE rhnActionImageBuild
(
    id               NUMERIC NOT NULL
                         CONSTRAINT rhn_act_image_build_id_pk PRIMARY KEY,
    action_id        NUMERIC NOT NULL
                         CONSTRAINT rhn_act_image_build_act_fk
                             REFERENCES rhnAction (id)
                             ON DELETE CASCADE,
    image_profile_id NUMERIC NOT NULL
                         CONSTRAINT rhn_act_image_build_ip_fk
                             REFERENCES suseImageProfile (profile_id)
                             ON DELETE CASCADE,
    tag              VARCHAR(30),
    created          TIMESTAMPTZ
                         DEFAULT (current_timestamp) NOT NULL,
    modified         TIMESTAMPTZ
                         DEFAULT (current_timestamp) NOT NULL
)

;

CREATE UNIQUE INDEX rhn_act_image_build_aid_idx
    ON rhnActionImageBuild (action_id)
    ;

CREATE SEQUENCE rhn_act_image_build_id_seq;

CREATE TABLE rhnActionImageBuildResult
(
    server_id              NUMERIC NOT NULL
                               CONSTRAINT rhn_image_build_result_sid_fk
                                   REFERENCES rhnServer (id)
                                   ON DELETE CASCADE,
    action_image_build_id NUMERIC NOT NULL
                               CONSTRAINT rhn_image_build_result_aid_fk
                                   REFERENCES rhnActionImageBuild (id)
                                   ON DELETE CASCADE
)

;

CREATE UNIQUE INDEX rhn_image_build_result_sa_uq
    ON rhnActionImageBuildResult (server_id, action_image_build_id);

CREATE INDEX rhn_image_build_result_ad_idx
    ON rhnActionImageBuildResult (action_image_build_id)
    ;

insert into rhnActionType values (504, 'image.build', 'Build an Image Profile', 'N', 'N');
 07070100000BDD000081B400000000000000000000000167AE111400001215000000000000000000000000000000000000006800000000susemanager-schema/upgrade/susemanager-schema-3.1.0-to-susemanager-schema-3.1.1/9020-add-image-info.sql   --
-- Copyright (c) 2017 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--
CREATE TABLE suseImageInfo
(
    id             NUMERIC NOT NULL
                     CONSTRAINT suse_imginfo_imgid_pk PRIMARY KEY,
    name           VARCHAR(128) NOT NULL,
    version        VARCHAR(128) NOT NULL,
    checksum       VARCHAR(128),
    image_arch_id  NUMERIC NOT NULL
                       CONSTRAINT rhn_imginfo_said_fk
                           REFERENCES rhnServerArch (id),
    org_id         NUMERIC NOT NULL
                     CONSTRAINT suse_imginfo_oid_fk
                       REFERENCES web_customer (id)
                       ON DELETE CASCADE,
    action_id      NUMERIC,
    profile_id     NUMERIC
                     CONSTRAINT suse_imginfo_pid_fk
                       REFERENCES suseImageProfile (profile_id)
                       ON DELETE CASCADE,
    store_id       NUMERIC NOT NULL
                      CONSTRAINT suse_imginfo_sid_fk
                         REFERENCES suseImageStore (id)
                         ON DELETE CASCADE,
    build_server_id  NUMERIC
                      CONSTRAINT suse_imginfo_bsid_fk
                         REFERENCES suseMinionInfo (server_id)
                         ON DELETE CASCADE,
    created        TIMESTAMPTZ
                     DEFAULT (current_timestamp) NOT NULL,
    modified       TIMESTAMPTZ
                     DEFAULT (current_timestamp) NOT NULL,
    CONSTRAINT suse_imginfo_aid_fk FOREIGN KEY (action_id, build_server_id)
        REFERENCES rhnServerAction (action_id, server_id) ON DELETE SET NULL
)

;

CREATE SEQUENCE suse_imginfo_imgid_seq;

CREATE TABLE suseImageCustomDataValue
(
    id                NUMERIC NOT NULL
                          CONSTRAINT suse_icdv_id_pk PRIMARY KEY,
    image_info_id     NUMERIC NOT NULL
                          CONSTRAINT suse_icdv_prid_fk
                              REFERENCES suseImageInfo (id),
    key_id            NUMERIC NOT NULL
                          CONSTRAINT suse_icdv_kid_fk
                              REFERENCES rhnCustomDataKey (id),
    value             VARCHAR(4000),
    created_by        NUMERIC
                          CONSTRAINT suse_icdv_cb_fk
                              REFERENCES web_contact (id)
                              ON DELETE SET NULL,
    last_modified_by  NUMERIC
                          CONSTRAINT suse_icdv_lmb_fk
                              REFERENCES web_contact (id)
                              ON DELETE SET NULL,
    created           TIMESTAMPTZ
                          DEFAULT (current_timestamp) NOT NULL,
    modified          TIMESTAMPTZ
                          DEFAULT (current_timestamp) NOT NULL
)

;

CREATE UNIQUE INDEX suse_icdv_imgid_kid_uq
    ON suseImageCustomDataValue (image_info_id, key_id);

CREATE INDEX suse_icdv_kid_idx
    ON suseImageCustomDataValue (key_id);

CREATE SEQUENCE suse_icdv_id_seq;

CREATE TABlE suseImageInfoChannel (
    channel_id      NUMERIC NOT NULL
                        CONSTRAINT suse_imginfoc_cid_fk
                        REFERENCES rhnChannel (id)
                        ON DELETE CASCADE,
    image_info_id   NUMERIC NOT NULL
                        CONSTRAINT suse_imginfoc_iiid_fk
                        REFERENCES suseImageInfo (id)
                        ON DELETE CASCADE
);

CREATE TABLE suseImageInfoPackage
(
    image_info_id    NUMERIC NOT NULL
                         REFERENCES suseImageInfo (id)
                             ON DELETE CASCADE,
    name_id          NUMERIC NOT NULL
                         REFERENCES rhnPackageName (id),
    evr_id           NUMERIC NOT NULL
                         REFERENCES rhnPackageEVR (id),
    package_arch_id  NUMERIC
                         REFERENCES rhnPackageArch (id),
    created          TIMESTAMPTZ
                         DEFAULT (current_timestamp) NOT NULL,
    installtime      TIMESTAMPTZ
)


;

CREATE UNIQUE INDEX suse_ip_inep_uq
    ON suseImageInfoPackage (image_info_id, name_id, evr_id, package_arch_id)
    
    ;

CREATE SEQUENCE suse_image_package_id_seq;
   07070100000BDE000081B400000000000000000000000167AE1114000005E3000000000000000000000000000000000000006D00000000susemanager-schema/upgrade/susemanager-schema-3.1.0-to-susemanager-schema-3.1.1/9021-rhnImageNeededCache.sql  --
-- Copyright (c) 2017 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
--

CREATE TABLE rhnImageNeededCache
(
    image_id    NUMERIC NOT NULL
                    CONSTRAINT rhn_inc_iid_fk
                        REFERENCES suseImageInfo (id)
                        ON DELETE CASCADE,
    errata_id   NUMERIC
                    CONSTRAINT rhn_inc_eid_fk
                        REFERENCES rhnErrata (id)
                        ON DELETE CASCADE,
    package_id  NUMERIC NOT NULL
                    CONSTRAINT rhn_inc_pid_fk
                        REFERENCES rhnPackage (id)
                        ON DELETE CASCADE,
    channel_id   NUMERIC
                    CONSTRAINT rhn_inc_cid_fk
                        REFERENCES rhnChannel (id)
                        ON DELETE CASCADE
)


;

CREATE INDEX rhn_inc_pid_idx
    ON rhnImageNeededCache (package_id)
    
    
    ;

CREATE INDEX rhn_inc_eid_idx
    ON rhnImageNeededCache (errata_id)
    
    ;

CREATE INDEX rhn_inc_cid_idx
    ON rhnImageNeededCache (channel_id)
    
    ;

CREATE INDEX rhn_inc_ipeid_idx
    ON rhnImageNeededCache (image_id, package_id, errata_id)
    
    
    ;
 07070100000BDF000081B400000000000000000000000167AE111400000452000000000000000000000000000000000000006900000000susemanager-schema/upgrade/susemanager-schema-3.1.0-to-susemanager-schema-3.1.1/9022-ImageCacheViews.sql  --
-- Copyright (c) 2017 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
--
create or replace view
rhnImageNeededPackageCache
(
    image_id,
    package_id,
    errata_id
)
as
select
	image_id,
	package_id,
	max(errata_id) as errata_id
	from rhnImageNeededCache
	group by image_id, package_id;

create or replace view
rhnImageNeededErrataCache
(
    image_id,
    errata_id
)
as
select
   distinct image_id, errata_id
   from rhnImageNeededCache;


CREATE OR REPLACE VIEW rhnImageErrataTypeView
(
    	image_id,
	errata_id,
	errata_type
)
AS
SELECT
    	INEC.image_id,
	INEC.errata_id,
	E.advisory_type
FROM    rhnErrata E,
    	rhnImageNeededErrataCache INEC
WHERE   E.id = INEC.errata_id
GROUP BY INEC.image_id, INEC.errata_id, E.advisory_type
;
  07070100000BE0000081B400000000000000000000000167AE111400000647000000000000000000000000000000000000006B00000000susemanager-schema/upgrade/susemanager-schema-3.1.0-to-susemanager-schema-3.1.1/9023-suseImageOverview.sql    --
-- Copyright (c) 2017 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--

create or replace view
suseImageOverview
(
    org_id,
    image_id,
    image_name,
    image_version,
    image_checksum,
    modified,
    image_arch_name,
    action_id,
    profile_id,
    store_id,
    build_server_id,
    security_errata,
    bug_errata,
    enhancement_errata,
    outdated_packages
)
as
select
    i.org_id, i.id, i.name, i.version, i.checksum, i.modified,
    ( select name from rhnServerArch where id = i.image_arch_id),
    i.action_id, i.profile_id, i.store_id, i.build_server_id,
    ( select count(*) from rhnImageErrataTypeView ietv
      where
            ietv.image_id = i.id
        and ietv.errata_type = 'Security Advisory'),
    ( select count(*) from rhnImageErrataTypeView ietv
      where
            ietv.image_id = i.id
        and ietv.errata_type = 'Bug Fix Advisory'),
    ( select count(*) from rhnImageErrataTypeView ietv
      where
            ietv.image_id = i.id
        and ietv.errata_type = 'Product Enhancement Advisory'),
    ( select count(distinct p.name_id) from rhnPackage p, rhnImageNeededPackageCache inpc
      where
             inpc.image_id = i.id
	 and p.id = inpc.package_id
	 )
from
    suseImageInfo i
;
 07070100000BE1000081B400000000000000000000000167AE1114000008CD000000000000000000000000000000000000007300000000susemanager-schema/upgrade/susemanager-schema-3.1.0-to-susemanager-schema-3.1.1/9024-update_image_needed_cache.sql    --
-- Copyright (c) 2017 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--

create or replace function
update_image_needed_cache(image_id_in in numeric)
returns void as $$
declare
  update_lock numeric;
begin
  select id into update_lock from suseImageInfo where id = image_id_in for update;
  delete from rhnImageNeededCache
   where image_id = image_id_in;
  insert into rhnImageNeededCache
         (image_id, errata_id, package_id, channel_id)
    (select distinct ip.image_info_id, x.errata_id, p.id, x.channel_id
       FROM (SELECT ip_ip.image_info_id, ip_ip.name_id,
                    ip_ip.package_arch_id, max(ip_pe.evr) AS max_evr
               FROM suseImageInfoPackage ip_ip
               join rhnPackageEvr ip_pe ON ip_pe.id = ip_ip.evr_id
              GROUP BY ip_ip.image_info_id, ip_ip.name_id, ip_ip.package_arch_id) ip
       join rhnPackage p ON p.name_id = ip.name_id
       join rhnPackageEvr pe ON pe.id = p.evr_id
                AND ip.max_evr < pe.evr
       join rhnPackageUpgradeArchCompat puac
                ON puac.package_arch_id = ip.package_arch_id
                AND puac.package_upgrade_arch_id = p.package_arch_id
       join suseImageInfoChannel ic ON ic.image_info_id = ip.image_info_id
       join rhnChannelPackage cp ON cp.package_id = p.id
                AND cp.channel_id = ic.channel_id
       left join (SELECT ep.errata_id, ce.channel_id, ep.package_id
                    FROM rhnChannelErrata ce
                    join rhnErrataPackage ep
                             ON ep.errata_id = ce.errata_id
                    join suseImageInfoChannel ic_ic
                             ON ic_ic.channel_id = ce.channel_id
                   WHERE ic_ic.image_info_id = image_id_in) x
         ON x.channel_id = ic.channel_id
                AND x.package_id = cp.package_id
      where ip.image_info_id = image_id_in);
end;
$$
language plpgsql;
   07070100000BE2000081B400000000000000000000000167AE1114000004DA000000000000000000000000000000000000006500000000susemanager-schema/upgrade/susemanager-schema-3.1.0-to-susemanager-schema-3.1.1/9025-queue_image.sql  --
-- Copyright (c) 2017 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
--

CREATE OR REPLACE FUNCTION
queue_image(image_id_in IN NUMERIC, immediate_in IN NUMERIC DEFAULT 1)
RETURNS VOID
AS
$$
DECLARE
    org_id_tmp NUMERIC;
BEGIN
    IF immediate_in > 0
    THEN
          PERFORM update_image_needed_cache(image_id_in);
    ELSE
          SELECT org_id INTO STRICT org_id_tmp FROM suseImageInfo WHERE id = image_id_in;

          INSERT
            INTO rhnTaskQueue
                 (org_id, task_name, task_data)
          SELECT org_id_tmp,
                 'update_image_errata_cache',
                 image_id_in
          WHERE NOT EXISTS
            (SELECT 1 FROM rhnTaskQueue
               WHERE org_id = org_id_tmp
               AND task_name = 'update_image_errata_cache'
               AND task_data = image_id_in
            );
    END IF;
END;
$$ LANGUAGE plpgsql;
  07070100000BE3000081B400000000000000000000000167AE11140000777E000000000000000000000000000000000000006900000000susemanager-schema/upgrade/susemanager-schema-3.1.0-to-susemanager-schema-3.1.1/9026-rhn_channel.pkb.sql  --
-- Copyright (c) 2008--2016 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--
--
--
--

-- create schema rhn_channel;

--update pg_setting
update pg_settings set setting = 'rhn_channel,' || setting where name = 'search_path';

    -- this "emulates" cursor server_base_subscriptions defined in oracle/rhn_channel.pks
    create or replace function server_base_subscriptions(server_id_in NUMERIC)
    returns boolean as $$
    begin
      return exists(SELECT C.id FROM rhnChannel C, rhnServerChannel SC
		    WHERE C.id = SC.channel_id
		      AND SC.server_id = server_id_in
		      AND C.parent_channel IS NULL);
    end$$ language plpgsql;

    -- this "emulates" cursor server_base_subscriptions defined in oracle/rhn_channel.pks
    create or replace function check_server_subscription(server_id_in NUMERIC, channel_id_in NUMERIC)
    returns boolean as $$
    begin
      return exists(SELECT channel_id FROM rhnServerChannel WHERE server_id = server_id_in AND channel_id = channel_id_in);
    end$$ language plpgsql;


    CREATE OR REPLACE FUNCTION subscribe_server(server_id_in IN NUMERIC, channel_id_in NUMERIC, immediate_in NUMERIC default 1, user_id_in in numeric default null) returns void
    AS $$
    declare
        channel_parent_val      rhnChannel.parent_channel%TYPE;
        parent_subscribed       BOOLEAN;
        server_has_base_chan    BOOLEAN;
        server_already_in_chan  BOOLEAN;
        channel_family_id_val   NUMERIC;
        allowed                 numeric;
    BEGIN
        if user_id_in is not null then
            allowed := rhn_channel.user_role_check(channel_id_in, user_id_in, 'subscribe');
        else
            allowed := 1;
        end if;

        if allowed = 0 then
            perform rhn_exception.raise_exception('no_subscribe_permissions');
        end if;


        SELECT parent_channel INTO channel_parent_val FROM rhnChannel WHERE id = channel_id_in;

        IF channel_parent_val IS NOT NULL
        THEN
            -- child channel; if attempting to cross-subscribe a child to the wrong base, silently ignore
            parent_subscribed := rhn_channel.check_server_subscription(server_id_in, channel_parent_val);

            IF NOT parent_subscribed
            THEN
                RETURN;
            END IF;
        ELSE
            -- base channel
            server_has_base_chan := rhn_channel.server_base_subscriptions(server_id_in);

            IF server_has_base_chan
            THEN
                perform rhn_exception.raise_exception('channel_server_one_base');
            END IF;
        END IF;

        server_already_in_chan := rhn_channel.check_server_subscription(server_id_in, channel_id_in);

        IF server_already_in_chan
        THEN
            RETURN;
        END IF;

        channel_family_id_val := rhn_channel.family_for_channel(channel_id_in);
        IF channel_family_id_val IS NULL
        THEN
            perform rhn_exception.raise_exception('channel_subscribe_no_family');
        END IF;

        insert into rhnServerHistory (id,server_id,summary,details) (
            select  nextval('rhn_event_id_seq'),
                    server_id_in,
                    'subscribed to channel ' || SUBSTR(c.label, 0, 106),
                    c.label
            from    rhnChannel c
            where   c.id = channel_id_in
        );

        INSERT INTO rhnServerChannel (server_id, channel_id) VALUES (server_id_in, channel_id_in);

        perform queue_server(server_id_in, immediate_in);

        update rhnServer
           set channels_changed = current_timestamp
         where id = server_id_in;
    END$$ language plpgsql;

    create or replace function guess_server_base(
        server_id_in in numeric
    ) RETURNS numeric as $$
    declare
        server_cursor cursor for
            select s.server_arch_id, s.release, s.org_id
              from rhnServer s
             where s.id = server_id_in;
    -- Cursor that fetches all the possible base channels for a
    -- (server_arch_id, release, org_id) combination
        base_channel_cursor cursor(
                release_in varchar,
                server_arch_id_in numeric,
                org_id_in numeric
        ) for
                select distinct c.*
                from    rhnOrgDistChannelMap                       odcm,
                                rhnServerChannelArchCompat      scac,
                                rhnChannel                                      c
                where   c.parent_channel is null
                        and c.id = odcm.channel_id
                        and c.channel_arch_id = odcm.channel_arch_id
                        and odcm.release = release_in
                        and odcm.for_org_id = org_id_in
                        and scac.server_arch_id = server_arch_id_in
                        and scac.channel_arch_id = c.channel_arch_id;

    begin
        for s in server_cursor loop
            for channel in base_channel_cursor(s.release,
                s.server_arch_id, s.org_id)
            loop
                return channel.id;
            end loop;
        end loop;
        -- Server not found, or no base channel applies to it
        return null;
    end$$ language plpgsql;

    -- Private function
    create or replace function normalize_server_arch(server_arch_in in varchar)
    returns varchar
    as $$
    declare
        suffix VARCHAR(128) := '-redhat-linux';
    begin
        if server_arch_in is NULL then
            return NULL;
        end if;
        if position('-' IN server_arch_in) > 0
        then
            -- Suffix already present
            return server_arch_in;
        end if;
        return server_arch_in || suffix;
    end$$ language plpgsql;

    --
    -- Raises:
    --   server_arch_not_found
    --   no_subscribe_permissions
    create or replace function base_channel_for_release_arch(
        release_in in varchar,
        server_arch_in in varchar,
        org_id_in in numeric default -1,
        user_id_in in numeric default null
    ) returns numeric as $$
    declare
        server_arch varchar(256) := rhn_channel.normalize_server_arch(server_arch_in);
        server_arch_id numeric;
    begin
        -- Look up the server arch
            select id
              into server_arch_id
              from rhnServerArch
             where label = server_arch;
            if not found then
                perform rhn_exception.raise_exception('server_arch_not_found');
            end if;

        return rhn_channel.base_channel_rel_archid(release_in, server_arch_id,
            org_id_in, user_id_in);
    end$$ language plpgsql;

    create or replace function base_channel_rel_archid(
        release_in in varchar,
        server_arch_id_in in numeric,
        org_id_in in numeric default -1,
        user_id_in in numeric default null
    ) returns numeric as $$
    declare
        denied_channel_id numeric := null;
        valid_org_id numeric := org_id_in;
        valid_user_id numeric := user_id_in;
        channel_subscribable numeric;
    -- Cursor that fetches all the possible base channels for a
    -- (server_arch_id, release, org_id) combination
        base_channel_cursor cursor(
                release_in varchar,
                server_arch_id_in numeric,
                org_id_in numeric
        ) for
                select distinct c.*
                from    rhnOrgDistChannelMap                       odcm,
                                rhnServerChannelArchCompat      scac,
                                rhnChannel                                      c
                where   c.parent_channel is null
                        and c.id = odcm.channel_id
                        and c.channel_arch_id = odcm.channel_arch_id
                        and odcm.release = release_in
                        and odcm.for_org_id = org_id_in
                        and scac.server_arch_id = server_arch_id_in
                        and scac.channel_arch_id = c.channel_arch_id;

    begin
        if org_id_in = -1 and user_id_in is not null then
            -- Get the org id from the user id

                select org_id
                  into valid_org_id
                  from web_contact
                 where id = user_id_in;

                if not found then
                    -- User doesn't exist
                    -- XXX Only list public stuff for now
                    valid_user_id := null;
                    valid_org_id := -1;
                end if;
        end if;

        for c in base_channel_cursor(release_in, server_arch_id_in, valid_org_id)
        loop
            -- This row is a possible match
            if valid_user_id is null then
                -- User ID not specified, so no user to channel permissions to
                -- check
                return c.id;
            end if;

            -- Check user to channel permissions
            select rhn_channel.loose_user_role_check(c.id, user_id_in, 'subscribe')
              into channel_subscribable;

            if channel_subscribable = 1 then
                return c.id;
            end if;

            -- Base channel exists, but is not subscribable; keep trying
            denied_channel_id := c.id;
        end loop;

        if denied_channel_id is not null then
            perform rhn_exception.raise_exception('no_subscribe_permissions');
        end if;
        -- No base channel applies
        return NULL;
    end$$ language plpgsql;

    CREATE OR REPLACE FUNCTION clear_subscriptions(server_id_in IN NUMERIC, deleting_server IN NUMERIC default 0) returns void
    AS $$
    declare
        server_channels cursor(server_id_in numeric) for
                select  s.org_id, sc.channel_id, cfm.channel_family_id
                from    rhnServer s,
                        rhnServerChannel sc,
                        rhnChannelFamilyMembers cfm
                where   s.id = server_id_in
                        and s.id = sc.server_id
                        and sc.channel_id = cfm.channel_id
                order by cfm.channel_family_id;
        last_channel_family_id rhnChannelFamilyMembers.channel_family_id%type := -1;
        last_channel_org_id    rhnServer.org_id%type := -1;
    BEGIN
        for channel in server_channels(server_id_in)
        loop
                perform rhn_channel.unsubscribe_server(server_id_in, channel.channel_id, 1, 1, deleting_server);
        end loop;
    END$$ language plpgsql;

    CREATE OR REPLACE FUNCTION unsubscribe_server(server_id_in IN NUMERIC, channel_id_in NUMERIC, immediate_in NUMERIC default 1, unsubscribe_children_in numeric default 0,
                                 deleting_server in numeric default 0) returns void
    AS $$
    declare
        channel_family_id_val   NUMERIC;
        server_org_id_val       NUMERIC;
        server_already_in_chan  BOOLEAN;
        channel_family_is_proxy cursor(channel_family_id_in numeric) for
                select  1
                from    rhnChannelFamily
                where   id = channel_family_id_in
                    and label = 'rhn-proxy';
        channel_family_is_satellite cursor(channel_family_id_in numeric) for
                select  1
                from    rhnChannelFamily
                where   id = channel_family_id_in
                    and label = 'rhn-satellite';
        child record;
    BEGIN
        -- In PostgreSQL recursion with opened cursors is not allowed so we use
        -- FOR IN SELECT form which is ok.
        FOR child IN select  c.id
                from    rhnChannel                      c,
                                rhnServerChannel        sc
                where   1=1
                        and c.parent_channel = channel_id_in
                        and c.id = sc.channel_id
                        and sc.server_id = server_id_in
        LOOP
            if unsubscribe_children_in = 1 then
                perform rhn_channel.unsubscribe_server(server_id_in,
                                                       child.id,
                                                       immediate_in,
                                                       unsubscribe_children_in,
                                                       deleting_server);
            else
                perform rhn_exception.raise_exception('channel_unsubscribe_child_exists');
            end if;
        END LOOP;

        server_already_in_chan := rhn_channel.check_server_subscription(server_id_in, channel_id_in);

        IF NOT server_already_in_chan
        THEN
            RETURN;
        END IF;

   if deleting_server = 0 then
      insert into rhnServerHistory (id,server_id,summary,details) (
          select  nextval('rhn_event_id_seq'),
                server_id_in,
             'unsubscribed from channel ' || SUBSTR(c.label, 0, 106),
             c.label
          from    rhnChannel c
          where   c.id = channel_id_in
      );
   end if;

   DELETE FROM rhnServerChannel WHERE server_id = server_id_in AND channel_id = channel_id_in;

   if deleting_server = 0 then
        perform queue_server(server_id_in, immediate_in);

        update rhnServer
           set channels_changed = current_timestamp
         where id = server_id_in;
   end if;

        channel_family_id_val := rhn_channel.family_for_channel(channel_id_in);
        IF channel_family_id_val IS NULL
        THEN
            perform rhn_exception.raise_exception('channel_unsubscribe_no_family');
        END IF;

        for ignore in channel_family_is_satellite(channel_family_id_val) loop
                delete from rhnSatelliteInfo where server_id = server_id_in;
        end loop;

        for ignore in channel_family_is_proxy(channel_family_id_val) loop
                delete from rhnProxyInfo where server_id = server_id_in;
        end loop;
        SELECT org_id INTO server_org_id_val
          FROM rhnServer
         WHERE id = server_id_in;

    END$$ language plpgsql;

    CREATE OR REPLACE FUNCTION family_for_channel(channel_id_in IN NUMERIC)
    RETURNS NUMERIC
    AS $$
    declare
        channel_family_id_val NUMERIC;
    BEGIN
        SELECT channel_family_id INTO channel_family_id_val
          FROM rhnChannelFamilyMembers
         WHERE channel_id = channel_id_in;

        IF NOT FOUND THEN
          RETURN NULL;
        END IF;

        RETURN channel_family_id_val;
    END$$ language plpgsql;

    create or replace function unsubscribe_server_from_family(server_id_in in numeric,
                                             channel_family_id_in in numeric)
    returns void
    as $$
    begin
        delete
        from    rhnServerChannel rsc
        where   rsc.server_id = server_id_in
            and channel_id in (
                select  rcfm.channel_id
                from    rhnChannelFamilyMembers rcfm
                where   rcfm.channel_family_id = channel_family_id_in);
    end$$ language plpgsql;

    create or replace function get_org_id(channel_id_in in numeric)
    returns numeric
    as $$
    declare
        org_id_out numeric;
    begin
        select org_id into strict org_id_out
            from rhnChannel
            where id = channel_id_in;

            return org_id_out;
    end$$ language plpgsql;

    create or replace function get_cfam_org_access(cfam_id_in in numeric, org_id_in in numeric)
    returns numeric
    as $$
    begin
      if exists(
                        select  1
                        from    rhnOrgChannelFamilyPermissions cfp
                        where   cfp.org_id = org_id_in
      ) then
                return 1;
      else
                return 0;
      end if;
    end$$ language plpgsql;

    create or replace function get_org_access(channel_id_in in numeric, org_id_in in numeric)
    returns integer
    as $$
    begin
        -- the idea: if we get past this query,
        -- the org has access to the channel, else not
        if exists(
        select 1
          from rhnChannelFamilyMembers CFM,
               rhnOrgChannelFamilyPermissions CFP
         where cfp.org_id = org_id_in
           and CFM.channel_family_id = CFP.channel_family_id
           and CFM.channel_id = channel_id_in)
        then
          return 1;
        else
          return 0;
        end if;
    end$$ language plpgsql;

    -- check if a user has a given role, or if such a role is inferrable
    -- returns NULL if OK, error message otherwise
    create or replace function user_role_check_debug(channel_id_in in numeric,
                                   user_id_in in numeric,
                                   role_in in varchar)
    returns varchar
    as $$
    declare
        org_id numeric;
    begin
        org_id := rhn_user.get_org_id(user_id_in);

        -- channel might be shared
        if role_in = 'subscribe' and
           rhn_channel.shared_user_role_check(channel_id_in, user_id_in, role_in) = 1 then
            return NULL;
        end if;

        if role_in = 'manage' and
           COALESCE(rhn_channel.get_org_id(channel_id_in), -1) <> org_id then
               return 'channel_not_owned';
        end if;

        if role_in = 'subscribe' and
           rhn_channel.get_org_access(channel_id_in, org_id) = 0 then
                return 'channel_not_available';
        end if;

        -- channel admins have all roles
        if rhn_user.check_role_implied(user_id_in, 'channel_admin') = 1 then
            return NULL;
        end if;

        -- the subscribe permission is inferred
        -- UNLESS the not_globally_subscribable flag is set
        if role_in = 'subscribe'
        then
            if rhn_channel.org_channel_setting(channel_id_in,
                       org_id,
                       'not_globally_subscribable') = 0 then
                return NULL;
            end if;
        end if;

        -- all other roles (manage right now) are explicitly granted
        if rhn_channel.direct_user_role_check(channel_id_in,
                                              user_id_in, role_in) = 1 then
            return NULL;
        end if;
        return 'direct_permission';
    end$$ language plpgsql;

    -- same as above, but with 1/0 output; useful in views, etc
    create or replace function user_role_check(channel_id_in in numeric, user_id_in in numeric, role_in in varchar)
    returns numeric
    as $$
    begin
        if rhn_channel.user_role_check_debug(channel_id_in,
                                             user_id_in, role_in) is NULL then
            return 1;
        else
            return 0;
        end if;
    end$$ language plpgsql;

    --
    -- For multiorg phase II, this function simply checks to see if the user's
    -- has a trust relationship that includes this channel by id.
    --
    create or replace function shared_user_role_check(channel_id in numeric, user_id in numeric, role in varchar)
    returns numeric
    as $$
    declare
      n numeric;
      oid numeric;
    begin
      oid := rhn_user.get_org_id(user_id);
      select 1 into n
      from rhnSharedChannelView s
      where s.id = channel_id and s.org_trust_id = oid;

      if not found then
        return 0;
      end if;

      return 1;
    end$$ language plpgsql;

    -- same as above, but returns 1 if user_id_in is null
    -- This is useful in queries where user_id is not specified
    create or replace function loose_user_role_check(channel_id_in in numeric, user_id_in in numeric, role_in in varchar)
    returns numeric
    as $$
    begin
        if user_id_in is null then
            return 1;
        end if;
        return rhn_channel.user_role_check(channel_id_in, user_id_in, role_in);
    end$$ language plpgsql;

    -- directly checks the table, no inferred permissions
    create or replace function direct_user_role_check(channel_id_in in numeric, user_id_in in numeric, role_in in varchar)
    returns numeric
    as $$
    declare
        throwaway numeric;
    begin
        -- the idea: if we get past this query, the user has the role, else no
        select 1 into throwaway
          from rhnChannelPermissionRole CPR,
               rhnChannelPermission CP
         where CP.user_id = user_id_in
           and CP.channel_id = channel_id_in
           and CPR.label = role_in
           and CP.role_id = CPR.id;

      if not found then
        return 0;
      end if;

      return 1;
    end$$ language plpgsql;

    -- check if an org has a certain setting
    create or replace function org_channel_setting(channel_id_in in numeric, org_id_in in numeric, setting_in in varchar)
    returns numeric
    as $$
    declare
        throwaway numeric;
    begin
        -- the idea: if we get past this query, the org has the setting
        select 1 into throwaway
          from rhnOrgChannelSettingsType OCST,
               rhnOrgChannelSettings OCS
         where OCS.org_id = org_id_in
           and OCS.channel_id = channel_id_in
           and OCST.label = setting_in
           and OCS.setting_id = OCST.id;

      if not found then
        return 0;
      end if;

      return 1;
    end$$ language plpgsql;

    CREATE OR REPLACE FUNCTION channel_priority(channel_id_in IN numeric)
    RETURNS numeric
    AS $$
    declare
         channel_name varchar(256);
         priority numeric;
         end_of_life_val timestamptz;
         org_id_val numeric;
    BEGIN

        select name, end_of_life, org_id
        into channel_name, end_of_life_val, org_id_val
        from rhnChannel
        where id = channel_id_in;

        if end_of_life_val is not null then
          return -400;
        end if;

        if channel_name like 'Red Hat Enterprise Linux%' or channel_name like 'RHEL%' then
          priority := 1000;
          if channel_name not like '%Beta%' then
            priority := priority + 1000;
          end if;

          priority := priority +
            case
              when channel_name like '%v. 5%' then 600
              when channel_name like '%v. 4%' then 500
              when channel_name like '%v. 3%' then 400
              when channel_name like '%v. 2%' then 300
              when channel_name like '%v. 1%' then 200
              else 0
            end;

          priority := priority +
            case
              when channel_name like 'Red Hat Enterprise Linux (v. 5%' then 60
              when (channel_name like '%AS%' and channel_name not like '%Extras%') then 50
              when (channel_name like '%ES%' and channel_name not like '%Extras%') then 40
              when (channel_name like '%WS%' and channel_name not like '%Extras%') then 30
              when (channel_name like '%Desktop%' and channel_name not like '%Extras%') then 20
              when channel_name like '%Extras%' then 10
              else 0
            end;

          priority := priority +
            case
              when channel_name like '%)' then 5
              else 0
            end;

          priority := priority +
            case
              when channel_name like '%32-bit x86%' then 4
              when channel_name like '%64-bit Intel Itanium%' then 3
              when channel_name like '%64-bit AMD64/Intel EM64T%' then 2
              else 0
            end;
        elsif channel_name like 'Red Hat Desktop%' then
            priority := 900;

            if channel_name not like '%Beta%' then
               priority := priority + 50;
            end if;

          priority := priority +
            case
              when channel_name like '%v. 4%' then 40
              when channel_name like '%v. 3%' then 30
              when channel_name like '%v. 2%' then 20
              when channel_name like '%v. 1%' then 10
              else 0
            end;

          priority := priority +
            case
              when channel_name like '%32-bit x86%' then 4
              when channel_name like '%64-bit Intel Itanium%' then 3
              when channel_name like '%64-bit AMD64/Intel EM64T%' then 2
              else 0
            end;

        elsif org_id_val is not null then
          priority := 600;
        else
          priority := 500;
        end if;

      return -priority;

    end$$ language plpgsql;

    -- this could certainly be optimized to do updates if needs be
    create or replace function refresh_newest_package(channel_id_in in numeric,
                                      caller_in in varchar default '(unknown)',
                                      package_name_id_in in numeric default null)
    returns void
    as $$
    -- procedure refreshes rows for name_id = package_name_id_in or
    -- all rows if package_name_id_in is null
    begin
        delete from rhnChannelNewestPackage
              where channel_id = channel_id_in
                and (package_name_id_in is null
                     or name_id = package_name_id_in);
        insert into rhnChannelNewestPackage
                (channel_id, name_id, evr_id, package_id, package_arch_id)
                (select channel_id,
                        name_id, evr_id,
                        package_id, package_arch_id
                   from rhnChannelNewestPackageView
                  where channel_id = channel_id_in
                    and (package_name_id_in is null
                         or name_id = package_name_id_in)
                );
        insert into rhnChannelNewestPackageAudit (channel_id, caller)
             values (channel_id_in, caller_in);
        update rhnChannel
           set last_modified = greatest(current_timestamp,
                                        last_modified + interval '1 second')
         where id = channel_id_in;
    end$$ language plpgsql;

   create or replace function update_channel ( channel_id_in in numeric, invalidate_ss in numeric default 0,
                              date_to_use in timestamptz default current_timestamp ) returns void
   as $$
   declare
   channel_last_modified timestamptz;
   last_modified_value timestamptz;

   snapshots cursor for
   select  snapshot_id id
   from    rhnSnapshotChannel
   where   channel_id = channel_id_in;

   begin

      select last_modified
      into channel_last_modified
      from rhnChannel
      where id = channel_id_in;

      last_modified_value := date_to_use;

      if last_modified_value <= channel_last_modified then
          last_modified_value := last_modified_value + interval '1 second';
      end if;

      update rhnChannel set last_modified = last_modified_value
      where id = channel_id_in;

      if invalidate_ss = 1 then
        for snapshot in snapshots loop
            update rhnSnapshot
            set invalid = lookup_snapshot_invalid_reason('channel_modified')
            where id = snapshot.id;
        end loop;
      end if;

   end$$ language plpgsql;

   create or replace function update_channels_by_package ( package_id_in in numeric, date_to_use in timestamptz default current_timestamp ) returns void
   as $$
   declare
   channels cursor for
   select channel_id
   from rhnChannelPackage
   where package_id = package_id_in
   order by channel_id;

   begin
      for channel in channels loop
         -- we want to invalidate the snapshot assocated with the channel when we
         -- do this b/c we know we've added or removed or packages
         perform rhn_channel.update_channel ( channel.channel_id, 1, date_to_use );
      end loop;
   end$$ language plpgsql;


   create or replace function update_channels_by_errata ( errata_id_in numeric, date_to_use in timestamptz default current_timestamp ) returns void
   as $$
   declare
   channels cursor for
   select channel_id
   from rhnChannelErrata
   where errata_id = errata_id_in
   order by channel_id;

   begin
      for channel in channels loop
         -- we won't invalidate snapshots, b/c just changing the errata associated with
         -- a channel shouldn't invalidate snapshots
         perform rhn_channel.update_channel ( channel.channel_id, 0, date_to_use );
      end loop;
   end$$ language plpgsql;

   create or replace function update_needed_cache(channel_id_in in numeric) returns void
   as $$
   declare
   server record;
   image record;
   begin
      -- we intentionaly do a loop here instead of one huge select
      -- b/c we want to break update into smaller transaction to unblock other sessions
      -- querying rhnServerNeededCache
      for server in (
                select sc.server_id as id
                  from rhnServerChannel sc
                 where sc.channel_id = channel_id_in
                 order by id asc
      ) loop
         perform queue_server(server.id, 0); -- NOT IMMEDIATE
      end loop;
      for image in (
        select ic.image_info_id as id
          from suseImageInfoChannel ic
         where ic.channel_id = channel_id_in
        order by id asc
      ) loop
         perform queue_image(image.id, 0);
      end loop;
   end$$ language plpgsql;

    create or replace function set_comps(channel_id_in in numeric, path_in in varchar, timestamp_in in varchar) returns void
    as $$
    declare
    row record;
    begin
        for row in (
            select relative_filename, last_modified
            from rhnChannelComps
            where channel_id = channel_id_in
            ) loop
            if row.relative_filename = path_in
                and row.last_modified = to_timestamp(timestamp_in, 'YYYYMMDDHH24MISS') then
                return;
            end if;
        end loop;
        delete from rhnChannelComps
        where channel_id = channel_id_in;
        insert into rhnChannelComps (id, channel_id, relative_filename, last_modified, created, modified)
        values (sequence_nextval('rhn_channelcomps_id_seq'), channel_id_in, path_in, to_timestamp(timestamp_in, 'YYYYMMDDHH24MISS'), current_timestamp, current_timestamp);
    end$$ language plpgsql;

-- restore the original setting
update pg_settings set setting = overlay( setting placing '' from 1 for (length('rhn_channel')+1) ) where name = 'search_path';
  07070100000BE4000081B400000000000000000000000167AE111400000988000000000000000000000000000000000000007200000000susemanager-schema/upgrade/susemanager-schema-3.1.0-to-susemanager-schema-3.1.1/9027-add-image-inspect-action.sql --
-- Copyright (c) 2017 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

CREATE TABLE rhnActionImageInspect
(
    id               NUMERIC NOT NULL
                         CONSTRAINT rhn_act_image_inspect_id_pk PRIMARY KEY,
    action_id        NUMERIC NOT NULL
                         CONSTRAINT rhn_act_image_inspect_act_fk
                             REFERENCES rhnAction (id)
                             ON DELETE CASCADE,
    image_store_id NUMERIC NOT NULL
                         CONSTRAINT rhn_act_image_inspect_is_fk
                             REFERENCES suseImageStore (id)
                             ON DELETE CASCADE,
    tag              VARCHAR(128),
    name             VARCHAR(128),
    created          TIMESTAMPTZ
                         DEFAULT (current_timestamp) NOT NULL,
    modified         TIMESTAMPTZ
                         DEFAULT (current_timestamp) NOT NULL
)

;

CREATE UNIQUE INDEX rhn_act_image_inspect_aid_idx
    ON rhnActionImageInspect (action_id)
    ;

CREATE SEQUENCE rhn_act_image_inspect_id_seq;


CREATE TABLE rhnActionImageInspectResult
(
    server_id              NUMERIC NOT NULL
                               CONSTRAINT rhn_image_inspect_res_sid_fk
                                   REFERENCES rhnServer (id)
                                   ON DELETE CASCADE,
    action_image_inspect_id NUMERIC NOT NULL
                               CONSTRAINT rhn_image_inspect_res_aid_fk
                                   REFERENCES rhnActionImageInspect (id)
                                   ON DELETE CASCADE
)

;

CREATE UNIQUE INDEX rhn_image_inspect_result_sa_uq
    ON rhnActionImageInspectResult (server_id, action_image_inspect_id);

CREATE INDEX rhn_image_inspect_res_ad_idx
    ON rhnActionImageInspectResult (action_image_inspect_id)
    ;

insert into rhnActionType values (505, 'image.inspect', 'Inspect an Image', 'N', 'N');

07070100000BE5000081B400000000000000000000000167AE111400000408000000000000000000000000000000000000007B00000000susemanager-schema/upgrade/susemanager-schema-3.1.0-to-susemanager-schema-3.1.1/9028-add-suseImageInfoInstalledProduct.sql    --
-- Copyright (c) 2017 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
--

create table
suseImageInfoInstalledProduct
(
    image_info_id         NUMERIC
                            CONSTRAINT suse_iiip_ii_id_fk
                            REFERENCES suseImageInfo (id)
                            ON DELETE CASCADE
                            not null,
    installed_product_id  NUMERIC
                            CONSTRAINT suse_iiip_ip_id_fk
                            REFERENCES suseInstalledProduct (id)
                            not null
);

CREATE UNIQUE INDEX suse_iiip_inprod_uq
    ON suseImageInfoInstalledProduct (image_info_id, installed_product_id)
    ;
07070100000BE6000081B400000000000000000000000167AE1114000002F6000000000000000000000000000000000000006C00000000susemanager-schema/upgrade/susemanager-schema-3.1.0-to-susemanager-schema-3.1.1/9029-suseImageInfo-trig.sql   --
-- Copyright (c) 2017 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- triggers for suseImageInfo

create or replace function suse_imginfo_mod_trig_fun() returns trigger as
$$
begin
	new.modified := current_timestamp;
	return new;
end;
$$ language plpgsql;

create trigger
suse_imginfo_mod_trig
before insert or update on suseImageInfo
for each row
execute procedure suse_imginfo_mod_trig_fun();
  07070100000BE7000081B400000000000000000000000167AE111400000187000000000000000000000000000000000000007600000000susemanager-schema/upgrade/susemanager-schema-3.1.0-to-susemanager-schema-3.1.1/9031-give-minions-scap-capability.sql INSERT INTO rhnClientCapability(server_id, capability_name_id, version) SELECT s.id, (SELECT id FROM rhnClientCapabilityName WHERE name='scap.xccdf_eval'), 1 FROM rhnServer s, suseminioninfo mi WHERE s.id=mi.server_id AND NOT EXISTS (select 1 from rhnClientCapability c where c.capability_name_id=(SELECT id FROM rhnClientCapabilityName WHERE name='scap.xccdf_eval') and c.server_id=s.id);

 07070100000BE8000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005000000000susemanager-schema/upgrade/susemanager-schema-3.1.1-to-susemanager-schema-3.1.4   07070100000BE9000081B400000000000000000000000167AE11140000005B000000000000000000000000000000000000005700000000susemanager-schema/upgrade/susemanager-schema-3.1.1-to-susemanager-schema-3.1.4/README    -- Schema upgrade scripts.
-- Intentionally left empty. Please leave this directory empty.
 07070100000BEA000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005200000000susemanager-schema/upgrade/susemanager-schema-3.1.10-to-susemanager-schema-3.1.11 07070100000BEB000081B400000000000000000000000167AE11140000009A000000000000000000000000000000000000007400000000susemanager-schema/upgrade/susemanager-schema-3.1.10-to-susemanager-schema-3.1.11/201-suseImageInfo-revisionNum.sql   ALTER TABLE suseImageInfo ADD COLUMN curr_revision_num NUMERIC NOT NULL DEFAULT 1;
ALTER TABLE suseImageInfo ALTER COLUMN curr_revision_num DROP DEFAULT;
  07070100000BEC000081B400000000000000000000000167AE111400000261000000000000000000000000000000000000007000000000susemanager-schema/upgrade/susemanager-schema-3.1.10-to-susemanager-schema-3.1.11/202-suseImageBuildHistory.sql   CREATE TABLE suseImageBuildHistory (
    id              NUMERIC NOT NULL
                        CONSTRAINT suse_bldhst_id_pk PRIMARY KEY,
    image_info_id   NUMERIC NOT NULL
                        CONSTRAINT suse_bldhst_imginfo_fk
                        REFERENCES suseImageInfo (id)
                        ON DELETE CASCADE,
    revision_num    NUMERIC NOT NULL,
    created         TIMESTAMPTZ
                        DEFAULT (CURRENT_TIMESTAMP) NOT NULL,
    modified        TIMESTAMPTZ
                        DEFAULT (CURRENT_TIMESTAMP) NOT NULL
)

;

CREATE SEQUENCE suse_img_buildhistory_id_seq;
   07070100000BED000081B400000000000000000000000167AE1114000002F7000000000000000000000000000000000000006E00000000susemanager-schema/upgrade/susemanager-schema-3.1.10-to-susemanager-schema-3.1.11/203-suseImageRepoDigest.sql CREATE TABLE suseImageRepoDigest (
    id                  NUMERIC NOT NULL
                            CONSTRAINT suse_rdigest_id_pk PRIMARY KEY,
    image_history_id    NUMERIC NOT NULL
                            CONSTRAINT suse_rdigest_bldhst_fk
                            REFERENCES suseImageBuildHistory (id)
                            ON DELETE CASCADE,
    repo_digest         VARCHAR(255) NOT NULL,
    created             TIMESTAMPTZ
                            DEFAULT (CURRENT_TIMESTAMP) NOT NULL,
    modified            TIMESTAMPTZ
                            DEFAULT (CURRENT_TIMESTAMP) NOT NULL
)

;

CREATE UNIQUE INDEX suse_img_repodigest_idx
    ON suseImageRepoDigest(repo_digest)
    
    ;

CREATE SEQUENCE suse_img_repodigest_id_seq;
 07070100000BEE000081B400000000000000000000000167AE1114000002E1000000000000000000000000000000000000007900000000susemanager-schema/upgrade/susemanager-schema-3.1.10-to-susemanager-schema-3.1.11/204-suseVirtualHostManagerNodeInfo.sql  CREATE TABLE suseVirtualHostManagerNodeInfo
(
    id            NUMERIC NOT NULL
                    CONSTRAINT suse_vhmnode_id_pk PRIMARY KEY,
    identifier    VARCHAR(1024) NOT NULL,
    name          VARCHAR(128),
    node_arch_id  NUMERIC
                    CONSTRAINT rhn_vhmnodeinf_said_fk
                    REFERENCES rhnServerArch (id),
    cpu_sockets   NUMERIC,
    cpu_cores     NUMERIC,
    ram           NUMERIC,
    os            VARCHAR(64) NOT NULL,
    os_version    VARCHAR(64) NOT NULL,
    created       TIMESTAMPTZ
                      DEFAULT (current_timestamp) NOT NULL,
    modified      TIMESTAMPTZ
                      DEFAULT (current_timestamp) NOT NULL
)

;

CREATE SEQUENCE suse_vhm_nodeinfo_id_seq;
   07070100000BEF000081B400000000000000000000000167AE111400000214000000000000000000000000000000000000007E00000000susemanager-schema/upgrade/susemanager-schema-3.1.10-to-susemanager-schema-3.1.11/205-suseServerVirtualHostManager-nodeId.sql ALTER TABLE suseServerVirtualHostManager ALTER COLUMN
    server_id DROP NOT NULL;

ALTER TABLE suseServerVirtualHostManager ADD COLUMN
    node_id NUMERIC CONSTRAINT suse_svhm_nodeinfo_fk
                    REFERENCES suseVirtualHostManagerNodeInfo (id)
                    ON DELETE SET NULL;

ALTER TABLE suseServerVirtualHostManager DROP CONSTRAINT suse_server_vhms_sid_fk;

ALTER TABLE suseServerVirtualHostManager ADD CONSTRAINT suse_server_vhms_sid_fk
    FOREIGN KEY(server_id) REFERENCES rhnServer(id) ON DELETE SET NULL;
07070100000BF0000081B400000000000000000000000167AE111400000098000000000000000000000000000000000000007B00000000susemanager-schema/upgrade/susemanager-schema-3.1.10-to-susemanager-schema-3.1.11/206-suseVHMConfig-deferredConstraint.sql    drop index suse_vhmc_id_para_uq;
alter table suseVHMConfig add constraint suse_vhmc_id_para_uq unique (virtual_host_manager_id, parameter) DEFERRABLE;

07070100000BF1000081B400000000000000000000000167AE1114000005C3000000000000000000000000000000000000007800000000susemanager-schema/upgrade/susemanager-schema-3.1.10-to-susemanager-schema-3.1.11/207-suseImageOverview-revisionNum.sql   drop view suseImageOverview;

create or replace view
suseImageOverview
(
    org_id,
    image_id,
    image_name,
    image_version,
    checksum_id,
    modified,
    image_arch_name,
    build_action_id,
    inspect_action_id,
    profile_id,
    store_id,
    build_server_id,
    curr_revision_num,
    external_image,
    security_errata,
    bug_errata,
    enhancement_errata,
    outdated_packages,
    installed_packages
)
as
select
    i.org_id, i.id, i.name, i.version, i.checksum_id, i.modified,
    ( select name from rhnServerArch where id = i.image_arch_id), i.build_action_id,
    i.inspect_action_id, i.profile_id, i.store_id, i.build_server_id, i.curr_revision_num,
    i.external_image,
    ( select count(*) from rhnImageErrataTypeView ietv
      where
            ietv.image_id = i.id
        and ietv.errata_type = 'Security Advisory'),
    ( select count(*) from rhnImageErrataTypeView ietv
      where
            ietv.image_id = i.id
        and ietv.errata_type = 'Bug Fix Advisory'),
    ( select count(*) from rhnImageErrataTypeView ietv
      where
            ietv.image_id = i.id
        and ietv.errata_type = 'Product Enhancement Advisory'),
    ( select count(distinct p.name_id) from rhnPackage p, rhnImageNeededPackageCache inpc
      where
            inpc.image_id = i.id
        and p.id = inpc.package_id),
    (select count(*) from suseImageInfoPackage iip
     where
            iip.image_info_id = i.id)
from
    suseImageInfo i
;
 07070100000BF2000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005200000000susemanager-schema/upgrade/susemanager-schema-3.1.11-to-susemanager-schema-3.1.12 07070100000BF3000081B400000000000000000000000167AE11140000005B000000000000000000000000000000000000005900000000susemanager-schema/upgrade/susemanager-schema-3.1.11-to-susemanager-schema-3.1.12/README  -- Schema upgrade scripts.
-- Intentionally left empty. Please leave this directory empty.
 07070100000BF4000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005200000000susemanager-schema/upgrade/susemanager-schema-3.1.12-to-susemanager-schema-3.1.13 07070100000BF5000081B400000000000000000000000167AE1114000000DA000000000000000000000000000000000000007700000000susemanager-schema/upgrade/susemanager-schema-3.1.12-to-susemanager-schema-3.1.13/001-enable-package-profiles-salt.sql    insert into rhnServerGroupTypeFeature (server_group_type_id, feature_id, created, modified)
  values (lookup_sg_type('salt_entitled'), lookup_feature_type('ftr_profile_compare'), current_timestamp, current_timestamp);
  07070100000BF6000081B400000000000000000000000167AE111400000266000000000000000000000000000000000000006F00000000susemanager-schema/upgrade/susemanager-schema-3.1.12-to-susemanager-schema-3.1.13/002-fix-unique-minion-id.sql    
-- provide info about possible duplicate minion ids
select 'DUPLICATE MINION IDs FOUND:' || X.minion_id || ' Manual cleanup required!' message
from (select minion_id, count(server_id) dup
        from suseMinionInfo
       group by minion_id) X
where X.dup > 1;

select m.minion_id, s.name, s.id, s.org_id, s.os
  from rhnServer s
  join suseMinionInfo m on s.id = m.server_id
order by m.minion_id, s.name;

alter table suseMinionInfo drop CONSTRAINT IF EXISTS rhn_minion_info_miid_uq;

drop index if exists rhn_minion_info_miid_uq;

create unique index rhn_minion_info_miid_uq
    on suseMinionInfo (minion_id);
  07070100000BF7000081B400000000000000000000000167AE111400000049000000000000000000000000000000000000007000000000susemanager-schema/upgrade/susemanager-schema-3.1.12-to-susemanager-schema-3.1.13/003-increase-hw_addr-size.sql   ALTER TABLE rhnServerNetInterface ALTER COLUMN hw_addr TYPE VARCHAR(96);
   07070100000BF8000081B400000000000000000000000167AE1114000001D0000000000000000000000000000000000000008400000000susemanager-schema/upgrade/susemanager-schema-3.1.12-to-susemanager-schema-3.1.13/004-enable-power-management-for-salt-entitled.sql   insert into rhnServerGroupTypeFeature (server_group_type_id, feature_id,
                                       created, modified)
select lookup_sg_type('salt_entitled'), lookup_feature_type('ftr_power_management'),
        current_timestamp,current_timestamp from dual
where not exists ( select 1 from rhnServerGroupTypeFeature
    where server_group_type_id = lookup_sg_type('salt_entitled')
      and feature_id = lookup_feature_type('ftr_power_management') );
07070100000BF9000081B400000000000000000000000167AE111400001219000000000000000000000000000000000000007C00000000susemanager-schema/upgrade/susemanager-schema-3.1.12-to-susemanager-schema-3.1.13/010-may_take_long-fix-rhn_pe_v_r_e_uq.sql   
drop index if exists rhn_pe_v_r_e_uq;
drop index if exists rhn_pe_v_r_uq;

create or replace function fix_rhn_pe_v_r_e_uq()
returns void as
$$
declare original record;
declare duplicate record;
declare nevra_orig record;
declare nevra_dup record;
declare snapshotitem record;
declare serverpackage record;
begin
  for original in select min(id) as id
          from rhnpackageevr
      group by version, release, epoch
        having count(*) > 1 loop
    for duplicate in select evr2.id
             from rhnpackageevr evr1, rhnpackageevr evr2
            where evr1.version = evr2.version
              and evr1.release = evr2.release
              and (evr1.epoch = evr2.epoch
               or (evr1.epoch is NULL and evr2.epoch is NULL))
              and evr1.id != evr2.id
              and evr1.id = original.id loop
      update rhnactionpackage set evr_id = original.id where evr_id = duplicate.id;
      update rhnactionpackageremovalfailure set evr_id = original.id where evr_id = duplicate.id;
      update rhnLockedPackages set evr_id = original.id where evr_id = duplicate.id;
      update rhnchannelnewestpackage set evr_id = original.id where evr_id = duplicate.id;
      update rhnpackage set evr_id = original.id where evr_id = duplicate.id;
      select id into nevra_orig from rhnpackagenevra where evr_id = original.id;
      if NOT FOUND then
        update rhnpackagenevra set evr_id = original.id where evr_id = duplicate.id;
      else
        for nevra_dup in select id
                           from rhnpackagenevra
                          where evr_id = duplicate.id loop
          for snapshotitem in select snapshot_id
                                from rhnsnapshotpackage
                               where nevra_id = nevra_dup.id loop
            begin
              update rhnsnapshotpackage set nevra_id = nevra_orig.id where nevra_id = nevra_dup.id and snapshot_id = snapshotitem.snapshot_id;
            exception when unique_violation then
              delete from rhnsnapshotpackage where nevra_id = nevra_dup.id and snapshot_id = snapshotitem.snapshot_id;
            end;
          end loop;
        end loop;
        delete from rhnpackagenevra where evr_id = duplicate.id;
      end if;
      update rhnproxyinfo set proxy_evr_id = original.id where proxy_evr_id = duplicate.id;
      update rhnserveractionverifymissing set package_evr_id = original.id where package_evr_id = duplicate.id;
      update rhnserveractionverifyresult set package_evr_id = original.id where package_evr_id = duplicate.id;
      update rhnsatelliteinfo set evr_id = original.id where evr_id = duplicate.id;
      update rhnservercrash set package_evr_id = original.id where package_evr_id = duplicate.id;
      update rhnserverprofilepackage set evr_id = original.id where evr_id = duplicate.id;
      update rhntransactionpackage set evr_id = original.id where evr_id = duplicate.id;
      update rhnversioninfo set evr_id = original.id where evr_id = duplicate.id;

      for serverpackage in select * from rhnserverpackage where evr_id = duplicate.id loop
          begin
            update rhnserverpackage set evr_id = original.id where evr_id = duplicate.id and
                server_id = serverpackage.server_id and
                name_id = serverpackage.name_id and
                evr_id = serverpackage.evr_id and
                package_arch_id = serverpackage.package_arch_id;
          exception when unique_violation then
            delete from rhnserverpackage where evr_id = duplicate.id and
                server_id = serverpackage.server_id and
                name_id = serverpackage.name_id and
                evr_id = serverpackage.evr_id and
                package_arch_id = serverpackage.package_arch_id;
          end;
      end loop;

      update suseImageInfoPackage set evr_id = original.id where evr_id = duplicate.id;
      update susePackageState set evr_id = original.id where evr_id = duplicate.id;
      update suseproductfile set evr_id = original.id where evr_id = duplicate.id;
      delete from rhnpackageevr where id = duplicate.id;
    end loop;
  end loop;
end;
$$ language plpgsql;

drop trigger if exists rhn_pack_evr_no_updel_trig on rhnpackageevr;

select fix_rhn_pe_v_r_e_uq();

drop function fix_rhn_pe_v_r_e_uq();

create trigger
rhn_pack_evr_no_updel_trig
before update or delete on rhnpackageevr
execute procedure no_operation_trig_fun();

create unique index rhn_pe_v_r_e_uq
    on rhnpackageevr (version, release, epoch)
 where epoch is not null;

create unique index rhn_pe_v_r_uq
    on rhnpackageevr (version, release)
 where epoch is null;
   07070100000BFA000081B400000000000000000000000167AE1114000010B4000000000000000000000000000000000000008800000000susemanager-schema/upgrade/susemanager-schema-3.1.12-to-susemanager-schema-3.1.13/011-may_take_long-fix-rhn_pkg_cap_name_version_uq.sql   
drop index if exists rhn_pkg_cap_name_version_uq;
drop index if exists rhn_pkg_cap_name_uq;

create or replace function fix_rhn_pkg_cap_name_version_uq()
returns void as
$$
declare original record;
declare duplicate record;
begin
  for original in select min(id) as id
          from rhnPackageCapability
      group by name, version
        having count(*) > 1 loop
    for duplicate in select cap2.id
             from rhnPackageCapability cap1, rhnPackageCapability cap2
            where
                  cap1.name = cap2.name
              and (cap1.version = cap2.version
               or (cap1.version is NULL and cap2.version is NULL))
              and cap1.id != cap2.id
              and cap1.id = original.id loop
      update rhnactionpackageremovalfailure set capability_id = original.id where capability_id = duplicate.id;
      begin
        update rhnPackageBreaks set capability_id = original.id where capability_id = duplicate.id;
      exception when unique_violation then
        -- do nothing as data already exists
        null;
      end;
      begin
        update rhnPackageConflicts set capability_id = original.id where capability_id = duplicate.id;
      exception when unique_violation then
        -- do nothing as data already exists
        null;
      end;
      begin
        update rhnPackageEnhances set capability_id = original.id where capability_id = duplicate.id;
      exception when unique_violation then
        -- do nothing as data already exists
        null;
      end;
      begin
        update rhnPackageFile set capability_id = original.id where capability_id = duplicate.id;
      exception when unique_violation then
        -- do nothing as data already exists
        null;
      end;
      begin
        update rhnPackageObsoletes set capability_id = original.id where capability_id = duplicate.id;
      exception when unique_violation then
        -- do nothing as data already exists
        null;
      end;
      begin
        update rhnPackagePredepends set capability_id = original.id where capability_id = duplicate.id;
      exception when unique_violation then
        -- do nothing as data already exists
        null;
      end;
      begin
        update rhnPackageProvides set capability_id = original.id where capability_id = duplicate.id;
      exception when unique_violation then
        -- do nothing as data already exists
        null;
      end;
      begin
        update rhnPackageRecommends set capability_id = original.id where capability_id = duplicate.id;
      exception when unique_violation then
        -- do nothing as data already exists
        null;
      end;
      begin
        update rhnPackageRequires set capability_id = original.id where capability_id = duplicate.id;
      exception when unique_violation then
        -- do nothing as data already exists
        null;
      end;
      begin
        update rhnPackageSuggests set capability_id = original.id where capability_id = duplicate.id;
      exception when unique_violation then
        -- do nothing as data already exists
        null;
      end;
      begin
        update rhnPackageSupplements set capability_id = original.id where capability_id = duplicate.id;
      exception when unique_violation then
        -- do nothing as data already exists
        null;
      end;
      begin
        update rhnServerActionVerifyMissing set package_capability_id = original.id where package_capability_id = duplicate.id;
      exception when unique_violation then
        -- do nothing as data already exists
        null;
      end;
      begin
        update rhnServerActionVerifyResult set package_capability_id = original.id where package_capability_id = duplicate.id;
      exception when unique_violation then
        -- do nothing as data already exists
        null;
      end;
      delete from rhnPackageCapability where id = duplicate.id;
    end loop;
  end loop;
end;
$$ language plpgsql;

select fix_rhn_pkg_cap_name_version_uq();

drop function fix_rhn_pkg_cap_name_version_uq();

CREATE UNIQUE INDEX rhn_pkg_cap_name_version_uq
    ON rhnPackageCapability (name, version)
 where version is not null;

create unique index rhn_pkg_cap_name_uq
    on rhnPackageCapability (name)
 where version is null;
07070100000BFB000081B400000000000000000000000167AE1114000004A3000000000000000000000000000000000000007200000000susemanager-schema/upgrade/susemanager-schema-3.1.12-to-susemanager-schema-3.1.13/100-rhnserver-move-hostname.sql 
DO $$
BEGIN
IF EXISTS (SELECT * FROM pg_tables WHERE tablename='rhnservernetwork')
THEN
  BEGIN
    BEGIN
      ALTER TABLE rhnServer ADD COLUMN hostname VARCHAR(128);
      UPDATE rhnServer
        SET hostname = (
          SELECT rhnServerNetwork.hostname
            FROM rhnServerNetwork
            WHERE rhnServerNetwork.id = (
              SELECT rhnServerNetwork.id
                FROM rhnServerNetwork
                WHERE server_id = rhnServer.id
                  AND id <= ALL (
                    SELECT rhnServerNetwork.id
                      FROM rhnServerNetwork
                      WHERE server_id = rhnServer.id
                  )
            )
        );
    EXCEPTION
      WHEN duplicate_column THEN RAISE NOTICE 'column hostname already exists in rhnServer. Safe to ignore';
    END;

    ALTER TABLE rhnServerNetwork DROP COLUMN IF EXISTS hostname;
    IF NOT EXISTS (
        SELECT 1
        FROM   pg_class c
        JOIN   pg_namespace n ON n.oid = c.relnamespace
        WHERE  c.relname = 'rhn_server_hostname_idx'
        ) THEN

        CREATE INDEX rhn_server_hostname_idx
        ON rhnServer (hostname);
    END IF;
  END;
  END IF;
END $$;

 07070100000BFC000081B400000000000000000000000167AE11140000018E000000000000000000000000000000000000007500000000susemanager-schema/upgrade/susemanager-schema-3.1.12-to-susemanager-schema-3.1.13/200-insert-feature_config-salt.sql  INSERT INTO rhnServerGroupTypeFeature (server_group_type_id, feature_id, created, modified)
SELECT lookup_sg_type('salt_entitled'), lookup_feature_type('ftr_config'),  current_timestamp,current_timestamp FROM dual
WHERE NOT EXISTS ( SELECT 1 FROM rhnServerGroupTypeFeature   WHERE server_group_type_id = lookup_sg_type('salt_entitled')   AND feature_id = lookup_feature_type('ftr_config') );






  07070100000BFD000081B400000000000000000000000167AE111400000928000000000000000000000000000000000000008000000000susemanager-schema/upgrade/susemanager-schema-3.1.12-to-susemanager-schema-3.1.13/201-give-minions-configfiles-capabilities.sql   
SELECT lookup_client_capability('configfiles.base64_enc') FROM dual;
INSERT INTO rhnClientCapability(server_id, capability_name_id, version) SELECT s.id, (SELECT id FROM rhnClientCapabilityName 
WHERE name='configfiles.base64_enc'), 1 FROM rhnServer s, suseminioninfo mi WHERE s.id=mi.server_id AND NOT EXISTS 
(select 1 from rhnClientCapability c where c.capability_name_id=(SELECT id FROM rhnClientCapabilityName WHERE name='configfiles.base64_enc') and c.server_id=s.id);

SELECT lookup_client_capability('configfiles.deploy') FROM dual;
INSERT INTO rhnClientCapability(server_id, capability_name_id, version) SELECT s.id, (SELECT id FROM rhnClientCapabilityName 
WHERE name='configfiles.deploy'), 1 FROM rhnServer s, suseminioninfo mi WHERE s.id=mi.server_id AND NOT EXISTS 
(select 1 from rhnClientCapability c where c.capability_name_id=(SELECT id FROM rhnClientCapabilityName WHERE name='configfiles.deploy') and c.server_id=s.id);

SELECT lookup_client_capability('configfiles.mtime_upload') FROM dual;
INSERT INTO rhnClientCapability(server_id, capability_name_id, version) SELECT s.id, (SELECT id FROM rhnClientCapabilityName 
WHERE name='configfiles.mtime_upload'), 1 FROM rhnServer s, suseminioninfo mi WHERE s.id=mi.server_id AND NOT EXISTS 
(select 1 from rhnClientCapability c where c.capability_name_id=(SELECT id FROM rhnClientCapabilityName WHERE name='configfiles.mtime_upload') and c.server_id=s.id);

SELECT lookup_client_capability('configfiles.diff') FROM dual;
INSERT INTO rhnClientCapability(server_id, capability_name_id, version) SELECT s.id, (SELECT id FROM rhnClientCapabilityName 
WHERE name='configfiles.diff'), 1 FROM rhnServer s, suseminioninfo mi WHERE s.id=mi.server_id AND NOT EXISTS 
(select 1 from rhnClientCapability c where c.capability_name_id=(SELECT id FROM rhnClientCapabilityName WHERE name='configfiles.diff') and c.server_id=s.id);

SELECT lookup_client_capability('configfiles.upload') FROM dual;
INSERT INTO rhnClientCapability(server_id, capability_name_id, version) SELECT s.id, (SELECT id FROM rhnClientCapabilityName 
WHERE name='configfiles.upload'), 1 FROM rhnServer s, suseminioninfo mi WHERE s.id=mi.server_id AND NOT EXISTS 
(select 1 from rhnClientCapability c where c.capability_name_id=(SELECT id FROM rhnClientCapabilityName WHERE name='configfiles.upload') and c.server_id=s.id);
07070100000BFE000081B400000000000000000000000167AE111400000108000000000000000000000000000000000000007F00000000susemanager-schema/upgrade/susemanager-schema-3.1.12-to-susemanager-schema-3.1.13/202-add-state-configuration-channel-type.sql     INSERT INTO rhnConfigChannelType (id, label, name, priority) 
 SELECT sequence_nextval('rhn_confchantype_id_seq'), 'state', 'Configuration channel based on SALT state', 1 from DUAL
 WHERE NOT EXISTS ( SELECT 1 FROM rhnConfigChannelType   WHERE label = 'state');

07070100000BFF000081B400000000000000000000000167AE1114000000D7000000000000000000000000000000000000007A00000000susemanager-schema/upgrade/susemanager-schema-3.1.12-to-susemanager-schema-3.1.13/203-add-sls-configuration-file-type.sql  INSERT INTO rhnConfigFileType(id, label, name, created, modified)
 SELECT 4, 'sls', 'SLS', current_timestamp, current_timestamp FROM DUAL
 WHERE NOT EXISTS ( SELECT 1 FROM rhnConfigFileType   WHERE label = 'sls');
 07070100000C00000081B400000000000000000000000167AE1114000004A9000000000000000000000000000000000000007900000000susemanager-schema/upgrade/susemanager-schema-3.1.12-to-susemanager-schema-3.1.13/204-suseStateRevisionConfigChannel.sql  --
-- Copyright (c) 2016 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

CREATE TABLE suseStateRevisionConfigChannel
(
    state_revision_id NUMERIC NOT NULL
                          CONSTRAINT suse_cfgchn_state_rev_id_fk
                              REFERENCES suseStateRevision (id)
                              ON DELETE CASCADE,
    config_channel_id NUMERIC NOT NULL
                          CONSTRAINT suse_state_rev_cfgchn_id_fk
                              REFERENCES rhnConfigChannel (id)
                              ON DELETE CASCADE,
    CONSTRAINT suse_state_rev_id_cfgchn_id_uq UNIQUE (state_revision_id, config_channel_id)
)

;
   07070100000C01000081B400000000000000000000000167AE111400000355000000000000000000000000000000000000008A00000000susemanager-schema/upgrade/susemanager-schema-3.1.12-to-susemanager-schema-3.1.13/205-feature_channel-config-sub-and-deploy-diff-salt.sql INSERT INTO rhnServerGroupTypeFeature (server_group_type_id, feature_id, created, modified)
SELECT lookup_sg_type('salt_entitled'), lookup_feature_type('ftr_channel_config_subscription'),  current_timestamp,current_timestamp FROM dual
WHERE NOT EXISTS ( SELECT 1 FROM rhnServerGroupTypeFeature   WHERE server_group_type_id = lookup_sg_type('salt_entitled')   AND feature_id = lookup_feature_type('ftr_channel_config_subscription') );

INSERT INTO rhnServerGroupTypeFeature (server_group_type_id, feature_id, created, modified)
SELECT lookup_sg_type('salt_entitled'), lookup_feature_type('ftr_channel_deploy_diff'),  current_timestamp,current_timestamp FROM dual
WHERE NOT EXISTS ( SELECT 1 FROM rhnServerGroupTypeFeature   WHERE server_group_type_id = lookup_sg_type('salt_entitled')   AND feature_id = lookup_feature_type('ftr_channel_deploy_diff') );
   07070100000C02000081B400000000000000000000000167AE1114000000D3000000000000000000000000000000000000007400000000susemanager-schema/upgrade/susemanager-schema-3.1.12-to-susemanager-schema-3.1.13/300-susevhmconfig-uq-deferred.sql   
ALTER TABLE suseVHMConfig DROP CONSTRAINT suse_vhmc_id_para_uq;

ALTER TABLE suseVHMConfig ADD CONSTRAINT suse_vhmc_id_para_uq UNIQUE (virtual_host_manager_id, parameter)
        DEFERRABLE INITIALLY DEFERRED;
 07070100000C03000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005200000000susemanager-schema/upgrade/susemanager-schema-3.1.13-to-susemanager-schema-3.1.14 07070100000C04000081B400000000000000000000000167AE111400000063000000000000000000000000000000000000008500000000susemanager-schema/upgrade/susemanager-schema-3.1.13-to-susemanager-schema-3.1.14/001-rhnserverlock-remove-locks-against-minions.sql  DELETE FROM rhnserverlock sl
	WHERE sl.server_id IN (SELECT sm.server_id FROM suseminioninfo sm);

 07070100000C05000081B400000000000000000000000167AE11140000008E000000000000000000000000000000000000007800000000susemanager-schema/upgrade/susemanager-schema-3.1.13-to-susemanager-schema-3.1.14/002-rhnactionapplystates-add-test.sql   ALTER TABLE rhnActionApplyStates ADD test CHAR(1) DEFAULT ('N') NOT NULL CONSTRAINT rhn_act_apply_states_test_ck CHECK (test in ('Y', 'N'));

  07070100000C06000081B400000000000000000000000167AE11140000040E000000000000000000000000000000000000007500000000susemanager-schema/upgrade/susemanager-schema-3.1.13-to-susemanager-schema-3.1.14/003-create-notification-tables.sql  CREATE TABLE suseNotificationMessage
(
  id                NUMERIC NOT NULL
                        CONSTRAINT suse_notifmess_pk PRIMARY KEY,
  type              VARCHAR(32) NOT NULL,
  data              VARCHAR(1024) NOT NULL,
  created           TIMESTAMPTZ default(current_timestamp) NOT NULL
);

CREATE SEQUENCE suse_notif_message_id_seq;

CREATE TABLE suseUserNotification
(
    id              NUMERIC NOT NULL
                        CONSTRAINT suse_user_notif_pk PRIMARY KEY,
    user_id         NUMERIC NOT NULL
                        CONSTRAINT suse_user_notif_uid_fk
                        REFERENCES web_contact (id)
                        ON DELETE CASCADE,
    message_id      NUMERIC NOT NULL
                        CONSTRAINT suse_user_notif_mid_fk
                        REFERENCES suseNotificationMessage (id)
                        ON DELETE CASCADE,
    read            CHAR(1) DEFAULT ('N') NOT NULL,
    CONSTRAINT suse_notif_uid_mid_uq UNIQUE (user_id, message_id)
);

CREATE SEQUENCE suse_user_notif_id_seq;
  07070100000C07000081B400000000000000000000000167AE111400000190000000000000000000000000000000000000006C00000000susemanager-schema/upgrade/susemanager-schema-3.1.13-to-susemanager-schema-3.1.14/004-Adelaide-Timezone.sql   insert into rhnTimezone (id, olson_name, display_name) (
    select sequence_nextval('rhn_timezone_id_seq'),
           'Australia/Adelaide',
           'Australia Central (Adelaide)'
      from dual
     where not exists (
           select 1
             from rhnTimezone
            where olson_name = 'Australia/Adelaide'
              and display_name = 'Australia Central (Adelaide)'
     )
);
07070100000C08000081B400000000000000000000000167AE111400007741000000000000000000000000000000000000007700000000susemanager-schema/upgrade/susemanager-schema-3.1.13-to-susemanager-schema-3.1.14/202-remove-rhnservernetwork-proc.sql    
DROP SEQUENCE IF EXISTS rhn_server_net_id_seq;
DROP TRIGGER IF EXISTS rhn_servernetwork_mod_trig ON rhnServerNetwork;
DROP FUNCTION IF EXISTS rhn_servernetwork_mod_trig_fun();

-- delete_server.sql

--
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--
--
--
-- This deletes a server.  All codepaths which delete servers should hit this
-- or delete_server_bulk()

create or replace
function delete_server (
        server_id_in in numeric
) returns void
as
$$
declare
         servergroups cursor for
                select  server_id, server_group_id
                from    rhnServerGroupMembers sgm
                where   sgm.server_id = server_id_in;

         configchannels cursor for
                select  cc.id
                from    rhnConfigChannel cc,
                        rhnConfigChannelType cct,
                        rhnServerConfigChannel scc
                where   1=1
                        and scc.server_id = server_id_in
                        and scc.config_channel_id = cc.id
                        -- these config channel types are reserved
                        -- for use by a single server, so we don't
                        -- need to check for other servers subscribed
                        and cct.label in
                                ('local_override','server_import')
                        and cct.id = cc.confchan_type_id;

    update_lock numeric;
begin
    -- lock the rhnServer row to prevent deadlocks
    -- we want rhnServer to be locked first, followed by tables that depend on it
    select id into update_lock from rhnServer where id = server_id_in for update;

        -- filelists
        delete from rhnFileList where id in (
	select	spfl.file_list_id
	  from	rhnServerPreserveFileList spfl
	 where	spfl.server_id = server_id_in
			and not exists (
				select	1
				from	rhnServerPreserveFileList
				where	file_list_id = spfl.file_list_id
					and server_id != server_id_in
				union all
				select	1
				from	rhnKickstartPreserveFileList
				where	file_list_id = spfl.file_list_id
			)
        );

	for configchannel in configchannels loop
		perform rhn_config.delete_channel(configchannel.id);
	end loop;

	for sgm in servergroups loop
		perform rhn_server.delete_from_servergroup(
			sgm.server_id, sgm.server_group_id);
	end loop;


        -- we're handling this instead of letting an "on delete
        -- set null" do it so that we don't run the risk
        -- of setting off the triggers and killing us with a
        -- mutating table

        -- this is merge of two single updates:
        --  update ... set old_server_id = null where old_server_id = server_id_in;
        --  update ... set new_server_id = null where new_server_id = server_id_in;
        -- so we scan rhnKickstartSession table only once
        update rhnKickstartSession
                set old_server_id = case when old_server_id = server_id_in then null else old_server_id end,
                    new_server_id = case when new_server_id = server_id_in then null else new_server_id end
                where old_server_id = server_id_in
                   or new_server_id = server_id_in;

        perform rhn_channel.clear_subscriptions(server_id_in, 1);

        -- A little complicated here, but the goal is to
        -- delete records from rhnVirtualInstace only if we don't
        -- care about them anymore.  We don't care about records
        -- in rhnVirtualInstance if we are deleting the host
        -- system and the virtual system is already null, or
        -- vice-versa.  We *do* care about them if either the
        -- host or virtual system is still registered because we
        -- still want them to show up in the UI.
    -- If there's a newer row in rhnVirtualInstance with the same
    -- uuid, this guest must have been re-registered, so we can clean
    -- this data up.

        delete from rhnVirtualInstance vi
              where (host_system_id = server_id_in and virtual_system_id is null)
                 or (virtual_system_id = server_id_in and host_system_id is null)
                 or (vi.virtual_system_id = server_id_in and vi.modified < (select max(vi2.modified)
                    from rhnVirtualInstance vi2 where vi2.uuid = vi.uuid));

        -- this is merge of two single updates:
        --  update ... set host_system_id = null where host_system_id = server_id_in;
        --  update ... set virtual_system_id = null where virtual_system_id = server_id_in;
        -- so we scan rhnVirtualInstance table only once
        update rhnVirtualInstance
           set host_system_id = case when host_system_id = server_id_in then null else host_system_id end,
               virtual_system_id = case when virtual_system_id = server_id_in then null else virtual_system_id end
         where host_system_id = server_id_in
            or virtual_system_id = server_id_in;

        -- this is merge of two single updates:
        --  update ... set old_host_system_id = null when old_host_system_id = server_id_in;
        --  update ... set new_host_system_id = null when new_host_system_id = server_id_in;
        -- so we scan rhnVirtualInstanceEventLog table only once
        update rhnVirtualInstanceEventLog
           set old_host_system_id = case when old_host_system_id = server_id_in then null else old_host_system_id end,
               new_host_system_id = case when new_host_system_id = server_id_in then null else new_host_system_id end
         where old_host_system_id = server_id_in
            or new_host_system_id = server_id_in;

        -- We're deleting everything with a foreign key to rhnServer
        -- here, now.  I'm hoping this will help aleviate our deadlock
        -- problem.

        delete from rhnActionApplyStatesResult where server_id = server_id_in;
        delete from rhnActionConfigChannel where server_id = server_id_in;
        delete from rhnActionConfigRevision where server_id = server_id_in;
        delete from rhnActionPackageRemovalFailure where server_id = server_id_in;
        delete from rhnClientCapability where server_id = server_id_in;
        delete from rhnCpu where server_id = server_id_in;
        -- there's still a cascade here, because the constraint keeps the
        -- table locked for too long to rebuild it.  Ugh...
        delete from rhnDevice where server_id = server_id_in;
        delete from rhnProxyInfo where server_id = server_id_in;
        delete from rhnRam where server_id = server_id_in;
        delete from rhnRegToken where server_id = server_id_in;
        delete from rhnSatelliteInfo where server_id = server_id_in;
        -- this cascades to rhnActionConfigChannel and rhnActionConfigFileName
        delete from rhnServerAction where server_id = server_id_in;
        delete from rhnServerActionPackageResult where server_id = server_id_in;
        delete from rhnServerActionScriptResult where server_id = server_id_in;
        delete from rhnServerActionVerifyResult where server_id = server_id_in;
        delete from rhnServerActionVerifyMissing where server_id = server_id_in;
        -- counts are handled above.  this should be a delete_ function.
        delete from rhnServerChannel where server_id = server_id_in;
        delete from rhnServerConfigChannel where server_id = server_id_in;
        delete from rhnServerCustomDataValue where server_id = server_id_in;
        delete from rhnServerDMI where server_id = server_id_in;
        delete from rhnServerEvent where server_id = server_id_in;
        delete from rhnServerHistory where server_id = server_id_in;
        delete from rhnServerInfo where server_id = server_id_in;
        delete from rhnServerInstallInfo where server_id = server_id_in;
        delete from rhnServerLocation where server_id = server_id_in;
        delete from rhnServerLock where server_id = server_id_in;
        delete from rhnServerNeededCache where server_id = server_id_in;
        delete from rhnServerNotes where server_id = server_id_in;
        -- I'm not removing the foreign key from rhnServerPackage; that'll
        -- take forever.  Do the delete anyway.
        delete from rhnServerPackage where server_id = server_id_in;
        delete from rhnServerTokenRegs where server_id = server_id_in;
        delete from rhnSnapshotTag where server_id = server_id_in;
        -- this cascades to:
        --   rhnSnapshotChannel, rhnSnapshotConfigChannel, rhnSnapshotPackage,
        --   rhnSnapshotConfigRevision, rhnSnapshotServerGroup,
        --   rhnSnapshotTag.
        -- We may want to consider delete_snapshot() at some point, but
        --   I don't think we need to yet.
        delete from rhnSnapshot where server_id = server_id_in;
        delete from rhnUserServerPrefs where server_id = server_id_in;
        -- hrm, this one's interesting... we _probably_ should delete
        -- everything for the parent server_id when we delete the proxy,
        -- but we don't currently.
        delete from rhnServerPath where server_id_in in (server_id, proxy_server_id);
        delete from rhnUserServerPerms where server_id = server_id_in;

        delete from rhnServerNetInterface where server_id = server_id_in;

        delete from rhnServerUuid where server_id = server_id_in;

        delete from rhnPushClient where server_id = server_id_in;

        -- now get rhnServer itself.
        delete
        from    rhnServer
                where id = server_id_in;

        delete
        from    rhnSet
        where   label = 'system_list'
                and element = server_id_in;
end;
$$
language plpgsql;

--
-- Copyright (c) 2008--2014 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--
--
--
--

-- create schema rhn_server;

--update pg_setting
update pg_settings set setting = 'rhn_server,' || setting where name = 'search_path';

    create or replace function system_service_level(
    	server_id_in in numeric,
	service_level_in in varchar
    ) returns numeric as $$
    declare
    ents cursor is
      select label from rhnServerEntitlementView
      where server_id = server_id_in;

    retval numeric := 0;

    begin
         for ent in ents loop
            retval := rhn_entitlements.entitlement_grants_service (ent.label, service_level_in);
            if retval = 1 then
               return retval;
            end if;
         end loop;

         return retval;

    end$$ language plpgsql;


    create or replace function can_change_base_channel(server_id_in IN NUMERIC)
    returns numeric
    as $$
    declare
    	throwaway numeric;
    begin
    	-- the idea: if we get past this query, the server is
	-- neither sat nor proxy, so base channel is changeable

	select 1 into throwaway
	  from rhnServer S
	 where S.id = server_id_in
	   and not exists (select 1 from rhnSatelliteInfo SI where SI.server_id = S.id)
	   and not exists (select 1 from rhnProxyInfo PI where PI.server_id = S.id);

        if not found then
	    return 0;
        end if;

	return 1;
    end$$ language plpgsql;

    create or replace function set_custom_value(
    	server_id_in in numeric,
	user_id_in in numeric,
	key_label_in in varchar,
	value_in in varchar
    ) returns void
    as $$
    declare
    	key_id_val numeric;
    begin
    	select CDK.id into strict key_id_val
	  from rhnCustomDataKey CDK,
	       rhnServer S
	 where S.id = server_id_in
	   and S.org_id = CDK.org_id
	   and CDK.label = key_label_in;

	begin
	    insert into rhnServerCustomDataValue (server_id, key_id, value, created_by, last_modified_by)
	    values (server_id_in, key_id_val, value_in, user_id_in, user_id_in);
	exception
	    when UNIQUE_VIOLATION
	    	then
		update rhnServerCustomDataValue
		   set value = value_in,
		       last_modified_by = user_id_in
		 where server_id = server_id_in
		   and key_id = key_id_val;
	end;

    end$$ language plpgsql;

    create or replace function bulk_set_custom_value(
    	key_label_in in varchar,
	value_in in varchar,
	set_label_in in varchar,
	set_uid_in in numeric
    )
    returns integer
    as $$
    declare
        i integer;
        server record;
    begin
        i := 0;
        for server in (
           SELECT user_id, label, element, element_two
	     FROM rhnSet
	    WHERE label = set_label_in
	      AND user_id = set_uid_in
	) loop
	    if rhn_server.system_service_level(server.element, 'management') = 1 then
	    	perform rhn_server.set_custom_value(server.element, set_uid_in, key_label_in, value_in);
            i := i + 1;
	    end if;
	end loop;
    return i;
    end$$ language plpgsql;

    create or replace function bulk_snapshot_tag(
    	org_id_in in numeric,
        tagname_in in varchar,
	set_label_in in varchar,
	set_uid_in in numeric
    ) returns void
    as $$
    declare
        server record;
    	snapshot_id numeric;
    begin
        for server in (
           SELECT user_id, label, element, element_two
	     FROM rhnSet
	    WHERE label = set_label_in
	      AND user_id = set_uid_in
	    ) loop
	    if rhn_server.system_service_level(server.element, 'management') = 1 then
	    	    select max(id) into snapshot_id
	    	    from rhnSnapshot
	    	    where server_id = server.element;

	    	    if snapshot_id is null then
		    	perform rhn_server.snapshot_server(server.element, 'tagging system:  ' || tagname_in);

			select max(id) into snapshot_id
			from rhnSnapshot
			where server_id = server.element;
		    end if;

		-- now have a snapshot_id to work with...
		begin
		    perform rhn_server.tag_snapshot(snapshot_id, org_id_in, tagname_in);
		exception
		    when UNIQUE_VIOLATION
		    	then
			-- do nothing, be forgiving...
			null;
		end;
	    end if;
	end loop;
    end$$ language plpgsql;

    create or replace function tag_delete(
    	server_id_in in numeric,
	tag_id_in in numeric
    ) returns void
    as $$
    declare
    	snapshots cursor is
		select	snapshot_id
		from	rhnSnapshotTag
		where	tag_id = tag_id_in;
	tag_id_tmp numeric;
    begin
    	select	id into tag_id_tmp
	from	rhnTag
	where	id = tag_id_in
	for update;

	delete
		from	rhnSnapshotTag
		where	server_id = server_id_in
			and tag_id = tag_id_in;
	for snapshot in snapshots loop
		return;
	end loop;
	delete
		from rhnTag
		where id = tag_id_in;
    end$$ language plpgsql;

    create or replace function tag_snapshot(
        snapshot_id_in in numeric,
	org_id_in in numeric,
	tagname_in in varchar
    ) returns void
    as $$
    begin
    	insert into rhnSnapshotTag (snapshot_id, server_id, tag_id)
	select snapshot_id_in, server_id, lookup_tag(org_id_in, tagname_in)
	from rhnSnapshot
	where id = snapshot_id_in;
    end$$ language plpgsql;

    create or replace function bulk_snapshot(
    	reason_in in varchar,
	set_label_in in varchar,
	set_uid_in in numeric
    ) returns void
    as $$
    declare
        server record;
    begin
        for server in (
           SELECT user_id, label, element, element_two
	     FROM rhnSet
	    WHERE label = set_label_in
	      AND user_id = set_uid_in
	    ) loop
	    if rhn_server.system_service_level(server.element, 'management') = 1 then
	    	perform rhn_server.snapshot_server(server.element, reason_in);
	    end if;
	end loop;
    end$$ language plpgsql;

    create or replace function snapshot_server(
    	server_id_in in numeric,
	reason_in in varchar
    ) returns void
    as $$
    declare
    	snapshot_id_v numeric;
	revisions cursor is
		select distinct
			cr.id
		from	rhnConfigRevision	cr,
			rhnConfigFileName	cfn,
			rhnConfigFile		cf,
			rhnConfigChannel	cc,
			rhnServerConfigChannel	scc
		where	1=1
			and scc.server_id = server_id_in
			and scc.config_channel_id = cc.id
			and cc.id = cf.config_channel_id
			and cf.id = cr.config_file_id
			and cr.id = cf.latest_config_revision_id
			and cf.config_file_name_id = cfn.id
			and cf.id = lookup_first_matching_cf(scc.server_id, cfn.path);
	locked integer;
    begin
    	select nextval('rhn_snapshot_id_seq') into snapshot_id_v;

	insert into rhnSnapshot (id, org_id, server_id, reason) (
		select	snapshot_id_v,
			s.org_id,
			server_id_in,
			reason_in
		from	rhnServer s
		where	s.id = server_id_in
	);
	insert into rhnSnapshotChannel (snapshot_id, channel_id) (
		select	snapshot_id_v, sc.channel_id
		from	rhnServerChannel sc
		where	sc.server_id = server_id_in
	);
	insert into rhnSnapshotServerGroup (snapshot_id, server_group_id) (
		select	snapshot_id_v, sgm.server_group_id
		from	rhnServerGroupMembers sgm
		where	sgm.server_id = server_id_in
	);
        locked := 0;
        <<iloop>>
        while true loop
            begin
                insert into rhnPackageNEVRA (id, name_id, evr_id, package_arch_id)
                select nextval('rhn_pkgnevra_id_seq'), sp.name_id, sp.evr_id, sp.package_arch_id
                from rhnServerPackage sp
                where sp.server_id = server_id_in
                        and not exists
                        (select 1
                                from rhnPackageNEVRA nevra
                                where nevra.name_id = sp.name_id
                                        and nevra.evr_id = sp.evr_id
                                        and (nevra.package_arch_id = sp.package_arch_id
                                            or (nevra.package_arch_id is null
                                                and sp.package_arch_id is null)));
                exit iloop;
            exception when unique_violation then
                if locked = 1 then
                    raise;
                else
                    lock table rhnPackageNEVRA in exclusive mode;
                    locked := 1;
                end if;
            end;
        end loop;
	insert into rhnSnapshotPackage (snapshot_id, nevra_id) (
                select distinct snapshot_id_v, nevra.id
                from    rhnServerPackage sp, rhnPackageNEVRA nevra
                where   sp.server_id = server_id_in
                        and nevra.name_id = sp.name_id
                        and nevra.evr_id = sp.evr_id
                        and (nevra.package_arch_id = sp.package_arch_id
                            or (nevra.package_arch_id is null
                                and sp.package_arch_id is null))
	);

	insert into rhnSnapshotConfigChannel ( snapshot_id, config_channel_id ) (
		select	snapshot_id_v, scc.config_channel_id
		from	rhnServerConfigChannel scc
		where	server_id = server_id_in
	);

	for revision in revisions loop
		insert into rhnSnapshotConfigRevision (
				snapshot_id, config_revision_id
			) values (
				snapshot_id_v, revision.id
			);
	end loop;
    end$$ language plpgsql;

    create or replace function remove_action(
    	server_id_in in numeric,
	action_id_in in numeric
    ) returns void
    as $$
    declare
    	-- this really wants "nulls last", but 8.1.7.3.0 sucks ass.
	-- instead, we make a local table that holds our
	-- list of ids with null prereqs.  There's surely a better way
	-- (an array instead of a table maybe?  who knows...)
	-- but I've got code to do this handy that I can look at ;)
    	chained_actions cursor is
                with recursive r(id, prerequisite) as (
			select	id, prerequisite
			from	rhnAction
			where id = action_id_in
		union all
			select	r1.id, r1.prerequisite
			from	rhnAction r1, r
			where r.id = r1.prerequisite
		)
		select * from r
		order by prerequisite desc;
	sessions cursor is
		select	s.id
		from	rhnKickstartSession s
		where	server_id_in in (s.old_server_id, s.new_server_id)
			and s.action_id = action_id_in
			and not exists (
				select	1
				from	rhnKickstartSessionState ss
				where	ss.id = s.state_id
					and ss.label in ('failed','complete')
			);
	chain_ends numeric[];
	i numeric;
	prereq numeric := 1;
    begin
	select	prerequisite
	into	prereq
	from	rhnAction
	where	id = action_id_in;

	if prereq is not null then
		perform rhn_exception.raise_exception('action_is_child');
	end if;

        chain_ends := '{}';
	i := 1;
	for action in chained_actions loop
		if action.prerequisite is null then
			chain_ends[i] := action.id;
			i := i + 1;
		else
			delete from rhnServerAction
				where server_id = server_id_in
				and action_id = action.id;
		end if;
	end loop;

	delete from rhnServerAction
		where server_id = server_id_in
		and action_id = any(chain_ends);

	for s in sessions loop
		update rhnKickstartSession
			set 	state_id = (
					select	id
					from	rhnKickstartSessionState
					where	label = 'failed'
				),
				action_id = null
			where	id = s.id;
		perform set_ks_session_history_message(s.id, 'failed', 'Kickstart cancelled due to action removal');
	end loop;
    end$$ language plpgsql;

    create or replace function check_user_access(server_id_in in numeric, user_id_in in numeric)
    returns numeric
    as $$
    declare
    	has_access numeric;
    begin
    	-- first check; if this returns no rows, then the server/user are in different orgs, and we bail
        select 1 into has_access
	  from rhnServer S,
	       web_contact wc
	 where wc.org_id = s.org_id
	   and s.id = server_id_in
	   and wc.id = user_id_in;

        if not found then
          return 0;
        end if;

	-- okay, so they're in the same org.  if we have an org admin, they get a free pass
    	if rhn_user.check_role(user_id_in, 'org_admin') = 1
	then
	    return 1;
	end if;

    	select 1 into has_access
	  from rhnServerGroupMembers SGM,
	       rhnUserServerGroupPerms USG
	 where SGM.server_group_id = USG.server_group_id
	   and SGM.server_id = server_id_in
	   and USG.user_id = user_id_in;

        if not found then
          return 0;
        end if;

	return 1;
    end$$ language plpgsql;

    create or replace function insert_into_servergroup (
		server_id_in in numeric,
		server_group_id_in in numeric
    ) returns void
    as $$
    declare
		group_type numeric;
	begin
		-- this will rowlock the servergroup we're trying to change;
		-- we probably need to lock the other one, but I think the chances
		-- of it being a real issue are very small for now...
		select	sg.group_type
		into	group_type
		from	rhnServerGroup sg
		where	sg.id = server_group_id_in
		for update of sg;

		insert into rhnServerGroupMembers(server_id, server_group_id)
		values (server_id_in, server_group_id_in);

		update rhnServerGroup
		set current_members = current_members + 1
		where id = server_group_id_in;

		if group_type is null then
			perform rhn_cache.update_perms_for_server_group(server_group_id_in);
		end if;

		return;
	end$$ language plpgsql;

	create or replace function insert_into_servergroup_maybe (
		server_id_in in numeric,
		server_group_id_in in numeric
	) returns numeric as $$
    declare
		retval numeric := 0;
		servergroups cursor is
			select	s.id	server_id,
					sg.id	server_group_id
			from	rhnServerGroup	sg,
					rhnServer		s
			where	s.id = server_id_in
				and sg.id = server_group_id_in
				and s.org_id = sg.org_id
				and not exists (
					select	1
					from	rhnServerGroupMembers sgm
					where	sgm.server_id = s.id
						and sgm.server_group_id = sg.id
				);
	begin
		for sgm in servergroups loop
			perform rhn_server.insert_into_servergroup(sgm.server_id, sgm.server_group_id);
			retval := retval + 1;
		end loop;
		return retval;
	end$$ language plpgsql;

	create or replace function insert_set_into_servergroup (
		server_group_id_in in numeric,
		user_id_in in numeric,
		set_label_in in varchar
	) returns void
        as $$
    declare
		servers cursor is
			select	st.element	id
			from	rhnSet		st
			where	st.user_id = user_id_in
				and st.label = set_label_in
				and exists (
					select	1
					from	rhnUserManagedServerGroups umsg
					where	umsg.server_group_id = server_group_id_in
						and umsg.user_id = user_id_in
					)
				and not exists (
					select	1
					from	rhnServerGroupMembers sgm
					where	sgm.server_id = st.element
						and sgm.server_group_id = server_group_id_in
				);
	begin
		for s in servers loop
			perform rhn_server.insert_into_servergroup(s.id, server_group_id_in);
		end loop;
	end$$ language plpgsql;

    create or replace function delete_from_servergroup (
    	server_id_in in numeric,
	server_group_id_in in numeric
    ) returns void
    as $$
    declare

		oid numeric;
		label varchar;
		group_type numeric;
	begin
		select	sg.group_type, sg.org_id
		into	group_type,	oid
		from	rhnServerGroupMembers	sgm,
			rhnServerGroup		sg
		where	sg.id = server_group_id_in
		and 	sg.id = sgm.server_group_id
		and 	sgm.server_id = server_id_in
		for update of sg;

		if not found then
			perform rhn_exception.raise_exception('server_not_in_group');
		end if;

		delete from rhnServerGroupMembers
		where server_group_id = server_group_id_in
		and	server_id = server_id_in;

		update rhnServerGroup
		set current_members = current_members - 1
		where id = server_group_id_in;

		-- do group_type is null first
		if group_type is null then
			perform rhn_cache.update_perms_for_server_group(server_group_id_in);
		end if;

	end$$ language plpgsql;

	create or replace function delete_set_from_servergroup (
		server_group_id_in in numeric,
		user_id_in in numeric,
		set_label_in in varchar
	) returns void
        as $$
        declare
		servergroups cursor is
			select	sgm.server_id, sgm.server_group_id
			from	rhnSet st,
					rhnServerGroupMembers sgm
			where	sgm.server_group_id = server_group_id_in
				and st.user_id = user_id_in
				and st.label = set_label_in
				and sgm.server_id = st.element
				and exists (
					select	1
					from	rhnUserManagedServerGroups usgp
					where	usgp.server_group_id = server_group_id_in
						and usgp.user_id = user_id_in
				);
	begin
		for sgm in servergroups loop
			perform rhn_server.delete_from_servergroup(sgm.server_id, server_group_id_in);
		end loop;
	end$$ language plpgsql;

	create or replace function clear_servergroup (
		server_group_id_in in numeric
	) returns void
        as $$
        declare
		servers cursor is
			select	sgm.server_id	id
			from	rhnServerGroupMembers sgm
			where	sgm.server_group_id = server_group_id_in;
	begin
		for s in servers loop
			perform rhn_server.delete_from_servergroup(s.id, server_group_id_in);
		end loop;
	end$$ language plpgsql;

	create or replace function delete_from_org_servergroups (
		server_id_in in numeric
	) returns void
        as $$
        declare
		servergroups cursor is
			select	sgm.server_group_id id
			from	rhnServerGroup sg,
					rhnServerGroupMembers sgm
			where	sgm.server_id = server_id_in
				and sgm.server_group_id = sg.id
				and sg.group_type is null;
	begin
		for sg in servergroups loop
			perform rhn_server.delete_from_servergroup(server_id_in, sg.id);
		end loop;
	end$$ language plpgsql;

	create or replace function get_ip_address (
		server_id_in in numeric
	) returns varchar as $$
        declare
		interfaces cursor is
			select	ni.name as name, na4.address as address
			from	rhnServerNetInterface ni,
			        rhnServerNetAddress4 na4
			where	server_id = server_id_in
		                and ni.id = na4.interface_id
				and na4.address != '127.0.0.1';
		addresses cursor is
			select	address ip_addr
			from	rhnServerNetInterface
			left join rhnServerNetAddress4
			on rhnServerNetInterface.id = rhnServerNetAddress4.interface_id
			where	server_id = server_id_in
				and address != '127.0.0.1'
				and is_primary = 'Y';
	begin
		for addr in addresses loop
			return addr.ip_addr;
		end loop;
		for iface in interfaces loop
			return iface.address;
		end loop;
		return NULL;
	end$$ language plpgsql;

    create or replace function update_needed_cache(
        server_id_in in numeric
	) returns void as $$
    declare
      update_lock numeric;
    begin
      select id into update_lock from rhnServer where id = server_id_in for update;
      delete from rhnServerNeededCache
        where server_id = server_id_in;
      insert into rhnServerNeededCache
             (server_id, errata_id, package_id, channel_id)
        (select distinct sp.server_id, x.errata_id, p.id, x.channel_id
           FROM (SELECT sp_sp.server_id, sp_sp.name_id,
		        sp_sp.package_arch_id, max(sp_pe.evr) AS max_evr
                   FROM rhnServerPackage sp_sp
                   join rhnPackageEvr sp_pe ON sp_pe.id = sp_sp.evr_id
                  GROUP BY sp_sp.server_id, sp_sp.name_id, sp_sp.package_arch_id) sp
           join rhnPackage p ON p.name_id = sp.name_id
           join rhnPackageEvr pe ON pe.id = p.evr_id AND sp.max_evr < pe.evr
           join rhnPackageUpgradeArchCompat puac
	            ON puac.package_arch_id = sp.package_arch_id
		    AND puac.package_upgrade_arch_id = p.package_arch_id
           join rhnServerChannel sc ON sc.server_id = sp.server_id
           join rhnChannelPackage cp ON cp.package_id = p.id
	            AND cp.channel_id = sc.channel_id
           left join (SELECT ep.errata_id, ce.channel_id, ep.package_id
                        FROM rhnChannelErrata ce
                        join rhnErrataPackage ep
			         ON ep.errata_id = ce.errata_id
			join rhnServerChannel sc_sc
			         ON sc_sc.channel_id = ce.channel_id
		       WHERE sc_sc.server_id = server_id_in) x
             ON x.channel_id = sc.channel_id AND x.package_id = cp.package_id
          where sp.server_id = server_id_in);
	end$$ language plpgsql;
-- restore the original setting
update pg_settings set setting = overlay( setting placing '' from 1 for (length('rhn_server')+1) ) where name = 'search_path';

DROP TABLE IF EXISTS rhnServerNetwork;
   07070100000C09000081B400000000000000000000000167AE111400000485000000000000000000000000000000000000007400000000susemanager-schema/upgrade/susemanager-schema-3.1.13-to-susemanager-schema-3.1.14/250-rhnUserChannelFamilyPerms.sql   --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

create or replace view rhnUserChannelFamilyPerms as
	select	pcf.channel_family_id,
		u.org_id as org_id,
		u.id as user_id,
		pcf.created,
		pcf.modified
	from	rhnPublicChannelFamily pcf,
		web_contact u
	where	pcf.channel_family_id not in (
			select priv.channel_family_id
			from rhnPrivateChannelFamily priv
			where u.org_id = priv.org_id
		)
	union
	select	pcf.channel_family_id,
		u.org_id,
		u.id as user_id,
		pcf.created,
		pcf.modified
	from	rhnPrivateChannelFamily pcf,
		web_contact u
	where	u.org_id = pcf.org_id;

   07070100000C0A000081B400000000000000000000000167AE111400000026000000000000000000000000000000000000007A00000000susemanager-schema/upgrade/susemanager-schema-3.1.13-to-susemanager-schema-3.1.14/300-drop-rhnServerGroupOVLiteHelper.sql DROP VIEW rhnServerGroupOVLiteHelper;
  07070100000C0B000081B400000000000000000000000167AE111400000F1B000000000000000000000000000000000000007300000000susemanager-schema/upgrade/susemanager-schema-3.1.13-to-susemanager-schema-3.1.14/301-update-rhnServerOverview.sql    --
-- Copyright (c) 2008--2013 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--
--
--

create or replace view
rhnServerOverview
(
    org_id,
    server_id,
    server_name,
    modified,
    server_admins,
    group_count,
    channel_id,
    channel_labels,
    history_count,
    security_errata,
    bug_errata,
    enhancement_errata,
    outdated_packages,
	config_files_with_differences,
    unique_crash_count,
    total_crash_count,
    last_checkin_days_ago,
    last_checkin,
    pending_updates,
    os,
    release,
    server_arch_name,
    locked
)
as
select
    s.org_id, s.id, s.name, s.modified,
    ( select count(user_id) from rhnUserServerPerms ap
      where server_id = s.id ),
    ( select count(server_group_id) from rhnVisibleServerGroupMembers
      where server_id = s.id ),
    ( select C.id
        from rhnChannel C,
	     rhnServerChannel SC
       where SC.server_id = S.id
         and SC.channel_id = C.id
	 and C.parent_channel IS NULL),
    coalesce(( select C.name
        from rhnChannel C,
	     rhnServerChannel SC
       where SC.server_id = S.id
         and SC.channel_id = C.id
	 and C.parent_channel IS NULL), '(none)'),
    ( select count(id) from rhnServerHistory
      where
            server_id = S.id),
    ( select count(*) from rhnServerErrataTypeView setv
      where
            setv.server_id = s.id
        and setv.errata_type = 'Security Advisory'),
    ( select count(*) from rhnServerErrataTypeView setv
      where
            setv.server_id = s.id
        and setv.errata_type = 'Bug Fix Advisory'),
    ( select count(*) from rhnServerErrataTypeView setv
      where
            setv.server_id = s.id
        and setv.errata_type = 'Product Enhancement Advisory'),
    ( select count(distinct p.name_id) from rhnPackage p, rhnServerNeededCache snc
      where
             snc.server_id = S.id
	 and p.id = snc.package_id
	 ),
    ( select count(*)
        from rhnActionConfigRevision ACR
             INNER JOIN rhnActionConfigRevisionResult ACRR on ACR.id = ACRR.action_config_revision_id
       where ACR.server_id = S.id
         and ACR.action_id = (
              select MAX(rA.id)
                from rhnAction rA
                     INNER JOIN rhnServerAction rSA on rSA.action_id = rA.id
                     INNER JOIN rhnActionStatus rAS on rAS.id = rSA.status
                     INNER JOIN rhnActionType rAT on rAT.id = rA.action_type
               where rSA.server_id = S.id
                 and rAS.name in ('Completed', 'Failed')
                 and rAT.label = 'configfiles.diff'
         )
         and ACR.failure_id is null
         and ACRR.result is not null
        ),
    ( select unique_count from rhnServerCrashCount where server_id = S.id ),
    ( select total_count from rhnServerCrashCount where server_id = S.id ),
    ( select date_diff_in_days(checkin, current_timestamp) from rhnServerInfo where server_id = S.id ),
    ( select TO_CHAR(checkin, 'YYYY-MM-DD HH24:MI:SS') from rhnServerInfo where server_id = S.id ),
    ( select count(1)
        from rhnServerAction
       where server_id = S.id
         and status in (0, 1)),
    os,
    release,
    ( select name from rhnServerArch where id = s.server_arch_id),
    coalesce((select 1 from rhnServerLock SL WHERE SL.server_id = S.id), 0)
from
    rhnServer S
;
 07070100000C0C000081B400000000000000000000000167AE111400000027000000000000000000000000000000000000007B00000000susemanager-schema/upgrade/susemanager-schema-3.1.13-to-susemanager-schema-3.1.14/302-drop-rhnServerNeededPackageCache.sql    DROP VIEW rhnServerNeededPackageCache;
 07070100000C0D000081B400000000000000000000000167AE111400007509000000000000000000000000000000000000006A00000000susemanager-schema/upgrade/susemanager-schema-3.1.13-to-susemanager-schema-3.1.14/303-rhn_channel.pkb.sql 
-- create schema rhn_channel;

--update pg_setting
update pg_settings set setting = 'rhn_channel,' || setting where name = 'search_path';

    -- this "emulates" cursor server_base_subscriptions defined in oracle/rhn_channel.pks
    create or replace function server_base_subscriptions(server_id_in NUMERIC)
    returns boolean as $$
    begin
      return exists(SELECT C.id FROM rhnChannel C, rhnServerChannel SC
		    WHERE C.id = SC.channel_id
		      AND SC.server_id = server_id_in
		      AND C.parent_channel IS NULL);
    end$$ language plpgsql;

    -- this "emulates" cursor server_base_subscriptions defined in oracle/rhn_channel.pks
    create or replace function check_server_subscription(server_id_in NUMERIC, channel_id_in NUMERIC)
    returns boolean as $$
    begin
      return exists(SELECT channel_id FROM rhnServerChannel WHERE server_id = server_id_in AND channel_id = channel_id_in);
    end$$ language plpgsql;


    CREATE OR REPLACE FUNCTION subscribe_server(server_id_in IN NUMERIC, channel_id_in NUMERIC, immediate_in NUMERIC default 1, user_id_in in numeric default null) returns void
    AS $$
    declare
        channel_parent_val      rhnChannel.parent_channel%TYPE;
        parent_subscribed       BOOLEAN;
        server_has_base_chan    BOOLEAN;
        server_already_in_chan  BOOLEAN;
        channel_family_id_val   NUMERIC;
        allowed                 numeric;
    BEGIN
        if user_id_in is not null then
            allowed := rhn_channel.user_role_check(channel_id_in, user_id_in, 'subscribe');
        else
            allowed := 1;
        end if;

        if allowed = 0 then
            perform rhn_exception.raise_exception('no_subscribe_permissions');
        end if;
        
        server_already_in_chan := rhn_channel.check_server_subscription(server_id_in, channel_id_in);

        IF server_already_in_chan
        THEN
            RETURN;
        END IF;

        SELECT parent_channel INTO channel_parent_val FROM rhnChannel WHERE id = channel_id_in;

        IF channel_parent_val IS NOT NULL
        THEN
            -- child channel; if attempting to cross-subscribe a child to the wrong base, silently ignore
            parent_subscribed := rhn_channel.check_server_subscription(server_id_in, channel_parent_val);

            IF NOT parent_subscribed
            THEN
                RETURN;
            END IF;
        ELSE
            -- base channel
            server_has_base_chan := rhn_channel.server_base_subscriptions(server_id_in);

            IF server_has_base_chan
            THEN
                perform rhn_exception.raise_exception('channel_server_one_base');
            END IF;
        END IF;

        channel_family_id_val := rhn_channel.family_for_channel(channel_id_in);
        IF channel_family_id_val IS NULL
        THEN
            perform rhn_exception.raise_exception('channel_subscribe_no_family');
        END IF;

        insert into rhnServerHistory (id,server_id,summary,details) (
            select  nextval('rhn_event_id_seq'),
                    server_id_in,
                    'subscribed to channel ' || SUBSTR(c.label, 0, 106),
                    c.label
            from    rhnChannel c
            where   c.id = channel_id_in
        );

        INSERT INTO rhnServerChannel (server_id, channel_id) VALUES (server_id_in, channel_id_in);

        perform queue_server(server_id_in, immediate_in);

        update rhnServer
           set channels_changed = current_timestamp
         where id = server_id_in;
    END$$ language plpgsql;

    create or replace function guess_server_base(
        server_id_in in numeric
    ) RETURNS numeric as $$
    declare
        server_cursor cursor for
            select s.server_arch_id, s.release, s.org_id
              from rhnServer s
             where s.id = server_id_in;
    -- Cursor that fetches all the possible base channels for a
    -- (server_arch_id, release, org_id) combination
        base_channel_cursor cursor(
                release_in varchar,
                server_arch_id_in numeric,
                org_id_in numeric
        ) for
                select distinct c.*
                from    rhnOrgDistChannelMap                       odcm,
                                rhnServerChannelArchCompat      scac,
                                rhnChannel                                      c
                where   c.parent_channel is null
                        and c.id = odcm.channel_id
                        and c.channel_arch_id = odcm.channel_arch_id
                        and odcm.release = release_in
                        and odcm.for_org_id = org_id_in
                        and scac.server_arch_id = server_arch_id_in
                        and scac.channel_arch_id = c.channel_arch_id;

    begin
        for s in server_cursor loop
            for channel in base_channel_cursor(s.release,
                s.server_arch_id, s.org_id)
            loop
                return channel.id;
            end loop;
        end loop;
        -- Server not found, or no base channel applies to it
        return null;
    end$$ language plpgsql;

    -- Private function
    create or replace function normalize_server_arch(server_arch_in in varchar)
    returns varchar
    as $$
    declare
        suffix VARCHAR(128) := '-redhat-linux';
    begin
        if server_arch_in is NULL then
            return NULL;
        end if;
        if position('-' IN server_arch_in) > 0
        then
            -- Suffix already present
            return server_arch_in;
        end if;
        return server_arch_in || suffix;
    end$$ language plpgsql;

    --
    -- Raises:
    --   server_arch_not_found
    --   no_subscribe_permissions
    create or replace function base_channel_for_release_arch(
        release_in in varchar,
        server_arch_in in varchar,
        org_id_in in numeric default -1,
        user_id_in in numeric default null
    ) returns numeric as $$
    declare
        server_arch varchar(256) := rhn_channel.normalize_server_arch(server_arch_in);
        server_arch_id numeric;
    begin
        -- Look up the server arch
            select id
              into server_arch_id
              from rhnServerArch
             where label = server_arch;
            if not found then
                perform rhn_exception.raise_exception('server_arch_not_found');
            end if;

        return rhn_channel.base_channel_rel_archid(release_in, server_arch_id,
            org_id_in, user_id_in);
    end$$ language plpgsql;

    create or replace function base_channel_rel_archid(
        release_in in varchar,
        server_arch_id_in in numeric,
        org_id_in in numeric default -1,
        user_id_in in numeric default null
    ) returns numeric as $$
    declare
        denied_channel_id numeric := null;
        valid_org_id numeric := org_id_in;
        valid_user_id numeric := user_id_in;
        channel_subscribable numeric;
    -- Cursor that fetches all the possible base channels for a
    -- (server_arch_id, release, org_id) combination
        base_channel_cursor cursor(
                release_in varchar,
                server_arch_id_in numeric,
                org_id_in numeric
        ) for
                select distinct c.*
                from    rhnOrgDistChannelMap                       odcm,
                                rhnServerChannelArchCompat      scac,
                                rhnChannel                                      c
                where   c.parent_channel is null
                        and c.id = odcm.channel_id
                        and c.channel_arch_id = odcm.channel_arch_id
                        and odcm.release = release_in
                        and odcm.for_org_id = org_id_in
                        and scac.server_arch_id = server_arch_id_in
                        and scac.channel_arch_id = c.channel_arch_id;

    begin
        if org_id_in = -1 and user_id_in is not null then
            -- Get the org id from the user id

                select org_id
                  into valid_org_id
                  from web_contact
                 where id = user_id_in;

                if not found then
                    -- User doesn't exist
                    -- XXX Only list public stuff for now
                    valid_user_id := null;
                    valid_org_id := -1;
                end if;
        end if;

        for c in base_channel_cursor(release_in, server_arch_id_in, valid_org_id)
        loop
            -- This row is a possible match
            if valid_user_id is null then
                -- User ID not specified, so no user to channel permissions to
                -- check
                return c.id;
            end if;

            -- Check user to channel permissions
            select rhn_channel.loose_user_role_check(c.id, user_id_in, 'subscribe')
              into channel_subscribable;

            if channel_subscribable = 1 then
                return c.id;
            end if;

            -- Base channel exists, but is not subscribable; keep trying
            denied_channel_id := c.id;
        end loop;

        if denied_channel_id is not null then
            perform rhn_exception.raise_exception('no_subscribe_permissions');
        end if;
        -- No base channel applies
        return NULL;
    end$$ language plpgsql;

    CREATE OR REPLACE FUNCTION clear_subscriptions(server_id_in IN NUMERIC, deleting_server IN NUMERIC default 0) returns void
    AS $$
    declare
        server_channels cursor(server_id_in numeric) for
                select  s.org_id, sc.channel_id, cfm.channel_family_id
                from    rhnServer s,
                        rhnServerChannel sc,
                        rhnChannelFamilyMembers cfm
                where   s.id = server_id_in
                        and s.id = sc.server_id
                        and sc.channel_id = cfm.channel_id
                order by cfm.channel_family_id;
        last_channel_family_id rhnChannelFamilyMembers.channel_family_id%type := -1;
        last_channel_org_id    rhnServer.org_id%type := -1;
    BEGIN
        for channel in server_channels(server_id_in)
        loop
                perform rhn_channel.unsubscribe_server(server_id_in, channel.channel_id, 1, 1, deleting_server);
        end loop;
    END$$ language plpgsql;

    CREATE OR REPLACE FUNCTION unsubscribe_server(server_id_in IN NUMERIC, channel_id_in NUMERIC, immediate_in NUMERIC default 1, unsubscribe_children_in numeric default 0,
                                 deleting_server in numeric default 0) returns void
    AS $$
    declare
        channel_family_id_val   NUMERIC;
        server_org_id_val       NUMERIC;
        server_already_in_chan  BOOLEAN;
        channel_family_is_proxy cursor(channel_family_id_in numeric) for
                select  1
                from    rhnChannelFamily
                where   id = channel_family_id_in
                    and label = 'rhn-proxy';
        channel_family_is_satellite cursor(channel_family_id_in numeric) for
                select  1
                from    rhnChannelFamily
                where   id = channel_family_id_in
                    and label = 'rhn-satellite';
        child record;
    BEGIN
        -- In PostgreSQL recursion with opened cursors is not allowed so we use
        -- FOR IN SELECT form which is ok.
        FOR child IN select  c.id
                from    rhnChannel                      c,
                                rhnServerChannel        sc
                where   1=1
                        and c.parent_channel = channel_id_in
                        and c.id = sc.channel_id
                        and sc.server_id = server_id_in
        LOOP
            if unsubscribe_children_in = 1 then
                perform rhn_channel.unsubscribe_server(server_id_in,
                                                       child.id,
                                                       immediate_in,
                                                       unsubscribe_children_in,
                                                       deleting_server);
            else
                perform rhn_exception.raise_exception('channel_unsubscribe_child_exists');
            end if;
        END LOOP;

        server_already_in_chan := rhn_channel.check_server_subscription(server_id_in, channel_id_in);

        IF NOT server_already_in_chan
        THEN
            RETURN;
        END IF;

   if deleting_server = 0 then
      insert into rhnServerHistory (id,server_id,summary,details) (
          select  nextval('rhn_event_id_seq'),
                server_id_in,
             'unsubscribed from channel ' || SUBSTR(c.label, 0, 106),
             c.label
          from    rhnChannel c
          where   c.id = channel_id_in
      );
   end if;

   DELETE FROM rhnServerChannel WHERE server_id = server_id_in AND channel_id = channel_id_in;

   if deleting_server = 0 then
        perform queue_server(server_id_in, immediate_in);

        update rhnServer
           set channels_changed = current_timestamp
         where id = server_id_in;
   end if;

        channel_family_id_val := rhn_channel.family_for_channel(channel_id_in);
        IF channel_family_id_val IS NULL
        THEN
            perform rhn_exception.raise_exception('channel_unsubscribe_no_family');
        END IF;

        for ignore in channel_family_is_satellite(channel_family_id_val) loop
                delete from rhnSatelliteInfo where server_id = server_id_in;
        end loop;

        for ignore in channel_family_is_proxy(channel_family_id_val) loop
                delete from rhnProxyInfo where server_id = server_id_in;
        end loop;
        SELECT org_id INTO server_org_id_val
          FROM rhnServer
         WHERE id = server_id_in;

    END$$ language plpgsql;

    CREATE OR REPLACE FUNCTION family_for_channel(channel_id_in IN NUMERIC)
    RETURNS NUMERIC
    AS $$
    declare
        channel_family_id_val NUMERIC;
    BEGIN
        SELECT channel_family_id INTO channel_family_id_val
          FROM rhnChannelFamilyMembers
         WHERE channel_id = channel_id_in;

        IF NOT FOUND THEN
          RETURN NULL;
        END IF;

        RETURN channel_family_id_val;
    END$$ language plpgsql;

    create or replace function unsubscribe_server_from_family(server_id_in in numeric,
                                             channel_family_id_in in numeric)
    returns void
    as $$
    begin
        delete
        from    rhnServerChannel rsc
        where   rsc.server_id = server_id_in
            and channel_id in (
                select  rcfm.channel_id
                from    rhnChannelFamilyMembers rcfm
                where   rcfm.channel_family_id = channel_family_id_in);
    end$$ language plpgsql;

    create or replace function get_org_id(channel_id_in in numeric)
    returns numeric
    as $$
    declare
        org_id_out numeric;
    begin
        select org_id into strict org_id_out
            from rhnChannel
            where id = channel_id_in;

            return org_id_out;
    end$$ language plpgsql;

    create or replace function get_cfam_org_access(cfam_id_in in numeric, org_id_in in numeric)
    returns numeric
    as $$
    begin
      if exists(
                        select  1
                        from    rhnOrgChannelFamilyPermissions cfp
                        where   cfp.org_id = org_id_in
      ) then
                return 1;
      else
                return 0;
      end if;
    end$$ language plpgsql;

    create or replace function get_org_access(channel_id_in in numeric, org_id_in in numeric)
    returns integer
    as $$
    begin
        -- the idea: if we get past this query,
        -- the org has access to the channel, else not
        if exists(
        select 1
          from rhnChannelFamilyMembers CFM,
               rhnOrgChannelFamilyPermissions CFP
         where cfp.org_id = org_id_in
           and CFM.channel_family_id = CFP.channel_family_id
           and CFM.channel_id = channel_id_in)
        then
          return 1;
        else
          return 0;
        end if;
    end$$ language plpgsql;

    -- check if a user has a given role, or if such a role is inferrable
    -- returns NULL if OK, error message otherwise
    create or replace function user_role_check_debug(channel_id_in in numeric,
                                   user_id_in in numeric,
                                   role_in in varchar)
    returns varchar
    as $$
    declare
        org_id numeric;
    begin
        org_id := rhn_user.get_org_id(user_id_in);

        -- channel might be shared
        if role_in = 'subscribe' and
           rhn_channel.shared_user_role_check(channel_id_in, user_id_in, role_in) = 1 then
            return NULL;
        end if;

        if role_in = 'manage' and
           COALESCE(rhn_channel.get_org_id(channel_id_in), -1) <> org_id then
               return 'channel_not_owned';
        end if;

        if role_in = 'subscribe' and
           rhn_channel.get_org_access(channel_id_in, org_id) = 0 then
                return 'channel_not_available';
        end if;

        -- channel admins have all roles
        if rhn_user.check_role_implied(user_id_in, 'channel_admin') = 1 then
            return NULL;
        end if;

        -- the subscribe permission is inferred
        -- UNLESS the not_globally_subscribable flag is set
        if role_in = 'subscribe'
        then
            if rhn_channel.org_channel_setting(channel_id_in,
                       org_id,
                       'not_globally_subscribable') = 0 then
                return NULL;
            end if;
        end if;

        -- all other roles (manage right now) are explicitly granted
        if rhn_channel.direct_user_role_check(channel_id_in,
                                              user_id_in, role_in) = 1 then
            return NULL;
        end if;
        return 'direct_permission';
    end$$ language plpgsql;

    -- same as above, but with 1/0 output; useful in views, etc
    create or replace function user_role_check(channel_id_in in numeric, user_id_in in numeric, role_in in varchar)
    returns numeric
    as $$
    begin
        if rhn_channel.user_role_check_debug(channel_id_in,
                                             user_id_in, role_in) is NULL then
            return 1;
        else
            return 0;
        end if;
    end$$ language plpgsql;

    --
    -- For multiorg phase II, this function simply checks to see if the user's
    -- has a trust relationship that includes this channel by id.
    --
    create or replace function shared_user_role_check(channel_id in numeric, user_id in numeric, role in varchar)
    returns numeric
    as $$
    declare
      n numeric;
      oid numeric;
    begin
      oid := rhn_user.get_org_id(user_id);
      select 1 into n
      from rhnSharedChannelView s
      where s.id = channel_id and s.org_trust_id = oid;

      if not found then
        return 0;
      end if;

      return 1;
    end$$ language plpgsql;

    -- same as above, but returns 1 if user_id_in is null
    -- This is useful in queries where user_id is not specified
    create or replace function loose_user_role_check(channel_id_in in numeric, user_id_in in numeric, role_in in varchar)
    returns numeric
    as $$
    begin
        if user_id_in is null then
            return 1;
        end if;
        return rhn_channel.user_role_check(channel_id_in, user_id_in, role_in);
    end$$ language plpgsql;

    -- directly checks the table, no inferred permissions
    create or replace function direct_user_role_check(channel_id_in in numeric, user_id_in in numeric, role_in in varchar)
    returns numeric
    as $$
    declare
        throwaway numeric;
    begin
        -- the idea: if we get past this query, the user has the role, else no
        select 1 into throwaway
          from rhnChannelPermissionRole CPR,
               rhnChannelPermission CP
         where CP.user_id = user_id_in
           and CP.channel_id = channel_id_in
           and CPR.label = role_in
           and CP.role_id = CPR.id;

      if not found then
        return 0;
      end if;

      return 1;
    end$$ language plpgsql;

    -- check if an org has a certain setting
    create or replace function org_channel_setting(channel_id_in in numeric, org_id_in in numeric, setting_in in varchar)
    returns numeric
    as $$
    declare
        throwaway numeric;
    begin
        -- the idea: if we get past this query, the org has the setting
        select 1 into throwaway
          from rhnOrgChannelSettingsType OCST,
               rhnOrgChannelSettings OCS
         where OCS.org_id = org_id_in
           and OCS.channel_id = channel_id_in
           and OCST.label = setting_in
           and OCS.setting_id = OCST.id;

      if not found then
        return 0;
      end if;

      return 1;
    end$$ language plpgsql;

    CREATE OR REPLACE FUNCTION channel_priority(channel_id_in IN numeric)
    RETURNS numeric
    AS $$
    declare
         channel_name varchar(256);
         priority numeric;
         end_of_life_val timestamptz;
         org_id_val numeric;
    BEGIN

        select name, end_of_life, org_id
        into channel_name, end_of_life_val, org_id_val
        from rhnChannel
        where id = channel_id_in;

        if end_of_life_val is not null then
          return -400;
        end if;

        if channel_name like 'Red Hat Enterprise Linux%' or channel_name like 'RHEL%' then
          priority := 1000;
          if channel_name not like '%Beta%' then
            priority := priority + 1000;
          end if;

          priority := priority +
            case
              when channel_name like '%v. 5%' then 600
              when channel_name like '%v. 4%' then 500
              when channel_name like '%v. 3%' then 400
              when channel_name like '%v. 2%' then 300
              when channel_name like '%v. 1%' then 200
              else 0
            end;

          priority := priority +
            case
              when channel_name like 'Red Hat Enterprise Linux (v. 5%' then 60
              when (channel_name like '%AS%' and channel_name not like '%Extras%') then 50
              when (channel_name like '%ES%' and channel_name not like '%Extras%') then 40
              when (channel_name like '%WS%' and channel_name not like '%Extras%') then 30
              when (channel_name like '%Desktop%' and channel_name not like '%Extras%') then 20
              when channel_name like '%Extras%' then 10
              else 0
            end;

          priority := priority +
            case
              when channel_name like '%)' then 5
              else 0
            end;

          priority := priority +
            case
              when channel_name like '%32-bit x86%' then 4
              when channel_name like '%64-bit Intel Itanium%' then 3
              when channel_name like '%64-bit AMD64/Intel EM64T%' then 2
              else 0
            end;
        elsif channel_name like 'Red Hat Desktop%' then
            priority := 900;

            if channel_name not like '%Beta%' then
               priority := priority + 50;
            end if;

          priority := priority +
            case
              when channel_name like '%v. 4%' then 40
              when channel_name like '%v. 3%' then 30
              when channel_name like '%v. 2%' then 20
              when channel_name like '%v. 1%' then 10
              else 0
            end;

          priority := priority +
            case
              when channel_name like '%32-bit x86%' then 4
              when channel_name like '%64-bit Intel Itanium%' then 3
              when channel_name like '%64-bit AMD64/Intel EM64T%' then 2
              else 0
            end;

        elsif org_id_val is not null then
          priority := 600;
        else
          priority := 500;
        end if;

      return -priority;

    end$$ language plpgsql;

    -- this could certainly be optimized to do updates if needs be
    create or replace function refresh_newest_package(channel_id_in in numeric,
                                      caller_in in varchar default '(unknown)',
                                      package_name_id_in in numeric default null)
    returns void
    as $$
    -- procedure refreshes rows for name_id = package_name_id_in or
    -- all rows if package_name_id_in is null
    begin
        delete from rhnChannelNewestPackage
              where channel_id = channel_id_in
                and (package_name_id_in is null
                     or name_id = package_name_id_in);
        insert into rhnChannelNewestPackage
                (channel_id, name_id, evr_id, package_id, package_arch_id)
                (select channel_id,
                        name_id, evr_id,
                        package_id, package_arch_id
                   from rhnChannelNewestPackageView
                  where channel_id = channel_id_in
                    and (package_name_id_in is null
                         or name_id = package_name_id_in)
                );
        insert into rhnChannelNewestPackageAudit (channel_id, caller)
             values (channel_id_in, caller_in);
        update rhnChannel
           set last_modified = greatest(current_timestamp,
                                        last_modified + interval '1 second')
         where id = channel_id_in;
    end$$ language plpgsql;

   create or replace function update_channel ( channel_id_in in numeric, invalidate_ss in numeric default 0,
                              date_to_use in timestamptz default current_timestamp ) returns void
   as $$
   declare
   channel_last_modified timestamptz;
   last_modified_value timestamptz;

   snapshots cursor for
   select  snapshot_id id
   from    rhnSnapshotChannel
   where   channel_id = channel_id_in;

   begin

      select last_modified
      into channel_last_modified
      from rhnChannel
      where id = channel_id_in;

      last_modified_value := date_to_use;

      if last_modified_value <= channel_last_modified then
          last_modified_value := last_modified_value + interval '1 second';
      end if;

      update rhnChannel set last_modified = last_modified_value
      where id = channel_id_in;

      if invalidate_ss = 1 then
        for snapshot in snapshots loop
            update rhnSnapshot
            set invalid = lookup_snapshot_invalid_reason('channel_modified')
            where id = snapshot.id;
        end loop;
      end if;

   end$$ language plpgsql;

   create or replace function update_channels_by_package ( package_id_in in numeric, date_to_use in timestamptz default current_timestamp ) returns void
   as $$
   declare
   channels cursor for
   select channel_id
   from rhnChannelPackage
   where package_id = package_id_in
   order by channel_id;

   begin
      for channel in channels loop
         -- we want to invalidate the snapshot assocated with the channel when we
         -- do this b/c we know we've added or removed or packages
         perform rhn_channel.update_channel ( channel.channel_id, 1, date_to_use );
      end loop;
   end$$ language plpgsql;


   create or replace function update_channels_by_errata ( errata_id_in numeric, date_to_use in timestamptz default current_timestamp ) returns void
   as $$
   declare
   channels cursor for
   select channel_id
   from rhnChannelErrata
   where errata_id = errata_id_in
   order by channel_id;

   begin
      for channel in channels loop
         -- we won't invalidate snapshots, b/c just changing the errata associated with
         -- a channel shouldn't invalidate snapshots
         perform rhn_channel.update_channel ( channel.channel_id, 0, date_to_use );
      end loop;
   end$$ language plpgsql;

   create or replace function update_needed_cache(channel_id_in in numeric) returns void
   as $$
   declare
   server record;
   image record;
   begin
      -- we intentionaly do a loop here instead of one huge select
      -- b/c we want to break update into smaller transaction to unblock other sessions
      -- querying rhnServerNeededCache
      for server in (
                select sc.server_id as id
                  from rhnServerChannel sc
                 where sc.channel_id = channel_id_in
                 order by id asc
      ) loop
         perform queue_server(server.id, 0); -- NOT IMMEDIATE
      end loop;
      for image in (
        select ic.image_info_id as id
          from suseImageInfoChannel ic
         where ic.channel_id = channel_id_in
        order by id asc
      ) loop
         perform queue_image(image.id, 0);
      end loop;
   end$$ language plpgsql;

    create or replace function set_comps(channel_id_in in numeric, path_in in varchar, timestamp_in in varchar) returns void
    as $$
    declare
    row record;
    begin
        for row in (
            select relative_filename, last_modified
            from rhnChannelComps
            where channel_id = channel_id_in
            ) loop
            if row.relative_filename = path_in
                and row.last_modified = to_timestamp(timestamp_in, 'YYYYMMDDHH24MISS') then
                return;
            end if;
        end loop;
        delete from rhnChannelComps
        where channel_id = channel_id_in;
        insert into rhnChannelComps (id, channel_id, relative_filename, last_modified, created, modified)
        values (sequence_nextval('rhn_channelcomps_id_seq'), channel_id_in, path_in, to_timestamp(timestamp_in, 'YYYYMMDDHH24MISS'), current_timestamp, current_timestamp);
    end$$ language plpgsql;

-- restore the original setting
update pg_settings set setting = overlay( setting placing '' from 1 for (length('rhn_channel')+1) ) where name = 'search_path';
   07070100000C0E000081B400000000000000000000000167AE1114000004DB000000000000000000000000000000000000006800000000susemanager-schema/upgrade/susemanager-schema-3.1.13-to-susemanager-schema-3.1.14/400-rhnserverfqdn.sql   --
-- Copyright (c) 2017 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.

CREATE TABLE rhnServerFQDN
(
    id         NUMERIC NOT NULL
                   CONSTRAINT rhn_serverfqdn_id_pk PRIMARY KEY
                   ,
    name       VARCHAR(253) NOT NULL,
    server_id  NUMERIC NOT NULL
                   CONSTRAINT rhn_serverfqdn_sid_fk
                       REFERENCES rhnServer (id),
    created    TIMESTAMPTZ
                   DEFAULT (current_timestamp) NOT NULL,
    modified   TIMESTAMPTZ
                   DEFAULT (current_timestamp) NOT NULL
)

;

CREATE SEQUENCE rhn_serverfqdn_id_seq;

CREATE UNIQUE INDEX rhn_server_fqdn_name_id_idx
    ON rhnServerFQDN (name, server_id)
    
    ;

 07070100000C0F000081B400000000000000000000000167AE111400002728000000000000000000000000000000000000006D00000000susemanager-schema/upgrade/susemanager-schema-3.1.13-to-susemanager-schema-3.1.14/401-rhnserverfqdn-proc.sql  --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--
--
--
-- This deletes a server.  All codepaths which delete servers should hit this
-- or delete_server_bulk()

create or replace
function delete_server (
        server_id_in in numeric
) returns void
as
$$
declare
         servergroups cursor for
                select  server_id, server_group_id
                from    rhnServerGroupMembers sgm
                where   sgm.server_id = server_id_in;

         configchannels cursor for
                select  cc.id
                from    rhnConfigChannel cc,
                        rhnConfigChannelType cct,
                        rhnServerConfigChannel scc
                where   1=1
                        and scc.server_id = server_id_in
                        and scc.config_channel_id = cc.id
                        -- these config channel types are reserved
                        -- for use by a single server, so we don't
                        -- need to check for other servers subscribed
                        and cct.label in
                                ('local_override','server_import')
                        and cct.id = cc.confchan_type_id;

    update_lock numeric;
begin
    -- lock the rhnServer row to prevent deadlocks
    -- we want rhnServer to be locked first, followed by tables that depend on it
    select id into update_lock from rhnServer where id = server_id_in for update;

        -- filelists
        delete from rhnFileList where id in (
	select	spfl.file_list_id
	  from	rhnServerPreserveFileList spfl
	 where	spfl.server_id = server_id_in
			and not exists (
				select	1
				from	rhnServerPreserveFileList
				where	file_list_id = spfl.file_list_id
					and server_id != server_id_in
				union all
				select	1
				from	rhnKickstartPreserveFileList
				where	file_list_id = spfl.file_list_id
			)
        );

	for configchannel in configchannels loop
		perform rhn_config.delete_channel(configchannel.id);
	end loop;

	for sgm in servergroups loop
		perform rhn_server.delete_from_servergroup(
			sgm.server_id, sgm.server_group_id);
	end loop;


        -- we're handling this instead of letting an "on delete
        -- set null" do it so that we don't run the risk
        -- of setting off the triggers and killing us with a
        -- mutating table

        -- this is merge of two single updates:
        --  update ... set old_server_id = null where old_server_id = server_id_in;
        --  update ... set new_server_id = null where new_server_id = server_id_in;
        -- so we scan rhnKickstartSession table only once
        update rhnKickstartSession
                set old_server_id = case when old_server_id = server_id_in then null else old_server_id end,
                    new_server_id = case when new_server_id = server_id_in then null else new_server_id end
                where old_server_id = server_id_in
                   or new_server_id = server_id_in;

        perform rhn_channel.clear_subscriptions(server_id_in, 1);

        -- A little complicated here, but the goal is to
        -- delete records from rhnVirtualInstace only if we don't
        -- care about them anymore.  We don't care about records
        -- in rhnVirtualInstance if we are deleting the host
        -- system and the virtual system is already null, or
        -- vice-versa.  We *do* care about them if either the
        -- host or virtual system is still registered because we
        -- still want them to show up in the UI.
    -- If there's a newer row in rhnVirtualInstance with the same
    -- uuid, this guest must have been re-registered, so we can clean
    -- this data up.

        delete from rhnVirtualInstance vi
              where (host_system_id = server_id_in and virtual_system_id is null)
                 or (virtual_system_id = server_id_in and host_system_id is null)
                 or (vi.virtual_system_id = server_id_in and vi.modified < (select max(vi2.modified)
                    from rhnVirtualInstance vi2 where vi2.uuid = vi.uuid));

        -- this is merge of two single updates:
        --  update ... set host_system_id = null where host_system_id = server_id_in;
        --  update ... set virtual_system_id = null where virtual_system_id = server_id_in;
        -- so we scan rhnVirtualInstance table only once
        update rhnVirtualInstance
           set host_system_id = case when host_system_id = server_id_in then null else host_system_id end,
               virtual_system_id = case when virtual_system_id = server_id_in then null else virtual_system_id end
         where host_system_id = server_id_in
            or virtual_system_id = server_id_in;

        -- this is merge of two single updates:
        --  update ... set old_host_system_id = null when old_host_system_id = server_id_in;
        --  update ... set new_host_system_id = null when new_host_system_id = server_id_in;
        -- so we scan rhnVirtualInstanceEventLog table only once
        update rhnVirtualInstanceEventLog
           set old_host_system_id = case when old_host_system_id = server_id_in then null else old_host_system_id end,
               new_host_system_id = case when new_host_system_id = server_id_in then null else new_host_system_id end
         where old_host_system_id = server_id_in
            or new_host_system_id = server_id_in;

        -- We're deleting everything with a foreign key to rhnServer
        -- here, now.  I'm hoping this will help aleviate our deadlock
        -- problem.

        delete from rhnActionApplyStatesResult where server_id = server_id_in;
        delete from rhnActionConfigChannel where server_id = server_id_in;
        delete from rhnActionConfigRevision where server_id = server_id_in;
        delete from rhnActionPackageRemovalFailure where server_id = server_id_in;
        delete from rhnClientCapability where server_id = server_id_in;
        delete from rhnCpu where server_id = server_id_in;
        -- there's still a cascade here, because the constraint keeps the
        -- table locked for too long to rebuild it.  Ugh...
        delete from rhnDevice where server_id = server_id_in;
        delete from rhnProxyInfo where server_id = server_id_in;
        delete from rhnRam where server_id = server_id_in;
        delete from rhnRegToken where server_id = server_id_in;
        delete from rhnSatelliteInfo where server_id = server_id_in;
        -- this cascades to rhnActionConfigChannel and rhnActionConfigFileName
        delete from rhnServerAction where server_id = server_id_in;
        delete from rhnServerActionPackageResult where server_id = server_id_in;
        delete from rhnServerActionScriptResult where server_id = server_id_in;
        delete from rhnServerActionVerifyResult where server_id = server_id_in;
        delete from rhnServerActionVerifyMissing where server_id = server_id_in;
        -- counts are handled above.  this should be a delete_ function.
        delete from rhnServerChannel where server_id = server_id_in;
        delete from rhnServerConfigChannel where server_id = server_id_in;
        delete from rhnServerCustomDataValue where server_id = server_id_in;
        delete from rhnServerDMI where server_id = server_id_in;
        delete from rhnServerEvent where server_id = server_id_in;
        delete from rhnServerFQDN where server_id = server_id_in;
        delete from rhnServerHistory where server_id = server_id_in;
        delete from rhnServerInfo where server_id = server_id_in;
        delete from rhnServerInstallInfo where server_id = server_id_in;
        delete from rhnServerLocation where server_id = server_id_in;
        delete from rhnServerLock where server_id = server_id_in;
        delete from rhnServerNeededCache where server_id = server_id_in;
        delete from rhnServerNotes where server_id = server_id_in;
        -- I'm not removing the foreign key from rhnServerPackage; that'll
        -- take forever.  Do the delete anyway.
        delete from rhnServerPackage where server_id = server_id_in;
        delete from rhnServerTokenRegs where server_id = server_id_in;
        delete from rhnSnapshotTag where server_id = server_id_in;
        -- this cascades to:
        --   rhnSnapshotChannel, rhnSnapshotConfigChannel, rhnSnapshotPackage,
        --   rhnSnapshotConfigRevision, rhnSnapshotServerGroup,
        --   rhnSnapshotTag.
        -- We may want to consider delete_snapshot() at some point, but
        --   I don't think we need to yet.
        delete from rhnSnapshot where server_id = server_id_in;
        delete from rhnUserServerPrefs where server_id = server_id_in;
        -- hrm, this one's interesting... we _probably_ should delete
        -- everything for the parent server_id when we delete the proxy,
        -- but we don't currently.
        delete from rhnServerPath where server_id_in in (server_id, proxy_server_id);
        delete from rhnUserServerPerms where server_id = server_id_in;

        delete from rhnServerNetInterface where server_id = server_id_in;

        delete from rhnServerUuid where server_id = server_id_in;

        delete from rhnPushClient where server_id = server_id_in;

        -- now get rhnServer itself.
        delete
        from    rhnServer
                where id = server_id_in;

        delete
        from    rhnSet
        where   label = 'system_list'
                and element = server_id_in;
end;
$$
language plpgsql;
07070100000C10000081B400000000000000000000000167AE111400000390000000000000000000000000000000000000007100000000susemanager-schema/upgrade/susemanager-schema-3.1.13-to-susemanager-schema-3.1.14/402-rhnserverfqdn-triggers.sql  

--
-- Copyright (c) 2018 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

create or replace function rhn_sfqdn_mod_trig_fun() returns trigger as
$$
begin
    new.modified := current_timestamp;
    return new;
end;
$$ language plpgsql;

create trigger rhn_fqdn_mod_trig
before insert or update
on rhnServerFQDN
for each row
execute procedure rhn_sfqdn_mod_trig_fun();
07070100000C11000081B400000000000000000000000167AE11140000122B000000000000000000000000000000000000007100000000susemanager-schema/upgrade/susemanager-schema-3.1.13-to-susemanager-schema-3.1.14/450-rhn_config_channel.pkb.sql  
-- setup search_path so that these functions are created in appropriate schema.
update pg_settings set setting = 'rhn_config_channel,' || setting where name = 'search_path';  

CREATE OR REPLACE FUNCTION action_diff_revision_status(action_config_revision_id_in numeric)
RETURNS VARCHAR
        -- result_is_null obviously wants NVL2, but stupid 8.1.7.3.0 doesn't
        -- have that.  Or case.  So we're using union, instead.
   AS $$
   DECLARE
   failure_reason  VARCHAR(4000);
   result_is_null  numeric;
   result_exists  numeric;
BEGIN
   select extant,is_null,reason
   into   result_exists,result_is_null,failure_reason
   from(SELECT ACRR.ACTION_CONFIG_REVISION_ID AS EXTANT,1 AS IS_NULL, -- NVL2(ACRR.result, 0, 1),
                       CFF.NAME AS REASON
      FROM RHNACTIONCONFIGREVISION ACR LEFT OUTER JOIN RHNACTIONCONFIGREVISIONRESULT ACRR ON ACR.ID = ACRR.ACTION_CONFIG_REVISION_ID  LEFT OUTER JOIN RHNCONFIGFILEFAILURE CFF ON ACR.FAILURE_ID = CFF.ID 
      WHERE ACR.ID = action_config_revision_id_in AND ACRR.RESULT is null
      union all
      SELECT ACRR.ACTION_CONFIG_REVISION_ID AS EXTANT,0 AS IS_NULL, -- NVL2(ACRR.result, 0, 1),
                       CFF.NAME AS REASON
      FROM RHNACTIONCONFIGREVISION ACR LEFT OUTER JOIN RHNACTIONCONFIGREVISIONRESULT ACRR ON ACR.ID = ACRR.ACTION_CONFIG_REVISION_ID  LEFT OUTER JOIN RHNCONFIGFILEFAILURE CFF ON ACR.FAILURE_ID = CFF.ID 
      WHERE ACR.ID = action_config_revision_id_in AND ACRR.RESULT is not null) AS SWT_TABAL;
   IF failure_reason IS NOT NULL
   THEN
      RETURN failure_reason;
   END IF;

   IF result_exists IS NOT NULL
   THEN
      IF result_is_null = 1
      THEN
         RETURN 'No differences';
      END IF;
      RETURN 'Differences exist';
   END IF;

   RETURN NULL;
END; 
$$ LANGUAGE plpgsql;

CREATE OR REPLACE FUNCTION get_user_chan_access(config_channel_id_in IN NUMERIC, user_id_in IN NUMERIC)
    RETURNS NUMERIC as $$
    Declare
        server_id NUMERIC;
        org_matches NUMERIC;
        global_channel VARCHAR(30);
        any_visible_servers_subscribed NUMERIC;
    BEGIN

          SELECT 1 INTO org_matches
            FROM rhnConfigChannel CC,
                 web_contact WC
           WHERE WC.id = user_id_in
             AND CC.id = config_channel_id_in
             AND WC.org_id = CC.org_id;

          IF NOT FOUND THEN
            RETURN 0;
          END IF;

        global_channel := 'unknown';
        SELECT CCT.label INTO global_channel
          FROM rhnConfigChannel CC,
               rhnConfigChannelType CCT
         WHERE CC.id = config_channel_id_in
           AND CCT.id = CC.confchan_type_id;

        IF (rhn_user.check_role_implied(user_id_in, 'config_admin') = 1) AND (global_channel IN ('normal', 'state'))
        THEN
            RETURN 1;
        END IF;

          SELECT 1 INTO any_visible_servers_subscribed
            FROM DUAL
           WHERE EXISTS (
             SELECT SCC.server_id
               FROM rhnServerConfigChannel SCC,
                    rhnUserServerPermsDupes USPD
              WHERE USPD.user_id = user_id_in
                AND USPD.server_id = SCC.server_id
                AND SCC.config_channel_id = config_channel_id_in
           );

          IF NOT FOUND 
            THEN RETURN 0;
          END IF;

        RETURN any_visible_servers_subscribed;

    END ;
   $$ language 'plpgsql';

CREATE OR REPLACE FUNCTION get_user_revision_access(config_revision_id_in IN NUMERIC, user_id_in IN NUMERIC)
    RETURNS NUMERIC AS $$
    DECLARE
        config_channel_id NUMERIC;
     BEGIN

        SELECT CF.config_channel_id INTO config_channel_id
          FROM rhnConfigFile CF,
               rhnConfigRevision CR
         WHERE CF.id = CR.config_file_id
           AND CR.id = config_revision_id_in;

          if not found then
           RETURN 0;
          end if;

        RETURN rhn_config_channel.get_user_chan_access(config_channel_id, user_id_in);
    END;
    $$ language 'plpgsql';


    CREATE OR REPLACE FUNCTION get_user_file_access(config_file_id_in IN NUMERIC, user_id_in IN NUMERIC)
    RETURNS NUMERIC as $$
    declare
        config_channel_id NUMERIC;
    BEGIN

        SELECT CF.config_channel_id INTO config_channel_id
          FROM rhnConfigFile CF
         WHERE CF.id = config_file_id_in;

        IF NOT FOUND THEN
          RETURN 0;
        END IF;

        RETURN rhn_config_channel.get_user_chan_access(config_channel_id, user_id_in);
    END ;
    $$ language 'plpgsql';


-- restore the original setting
update pg_settings set setting = overlay( setting placing '' from 1 for (length('rhn_config_channel')+1) ) where name = 'search_path';
 07070100000C12000081B400000000000000000000000167AE111400000178000000000000000000000000000000000000007400000000susemanager-schema/upgrade/susemanager-schema-3.1.13-to-susemanager-schema-3.1.14/500-rename-conflicting-states.sql   -- Pre-task: we need to make sure there are no custom states with name equal to
-- some existing configuration channel label. We'll relabel the conflicting
-- channels  by appending a random suffix to them.

UPDATE rhnConfigChannel
SET label = label || '-' || (SELECT cast(trunc(random() * 1000000) AS TEXT) FROM DUAL)
WHERE label IN (SELECT state_name FROM suseCustomState);
07070100000C13000081B400000000000000000000000167AE111400000042000000000000000000000000000000000000008900000000susemanager-schema/upgrade/susemanager-schema-3.1.13-to-susemanager-schema-3.1.14/501-add-position-to-susestaterevisionconfigchannel.sql  ALTER TABLE suseStateRevisionConfigChannel
ADD position NUMERIC;

  07070100000C14000081B400000000000000000000000167AE111400000CB7000000000000000000000000000000000000008200000000susemanager-schema/upgrade/susemanager-schema-3.1.13-to-susemanager-schema-3.1.14/502-create-state-channel-from-custom-states.sql -------------------------------------------------------------------------------
-- CONFIG CHANNEL -------------------------------------------------------------
-------------------------------------------------------------------------------
INSERT INTO rhnConfigChannel(
    id,
    org_id,
    confchan_type_id,
    name,
    label,
    description)
SELECT
   sequence_nextval('rhn_confchan_id_seq'),
   org_id,
   (SELECT id FROM rhnConfigChannelType WHERE label = 'state'),
   state_name,
   state_name,
   state_name
FROM suseCustomState
WHERE
    state_deleted = 'N';

-------------------------------------------------------------------------------
-- CONFIG FILE ----------------------------------------------------------------
-------------------------------------------------------------------------------
-- NAME
INSERT INTO rhnConfigFileName(
    id,
    path)
SELECT
    sequence_nextval('rhn_cfname_id_seq'),
    '/init.sls'
FROM DUAL
WHERE NOT EXISTS (SELECT id FROM rhnConfigFileName WHERE path = '/init.sls');


-- FILE
-- (latest_config_revision_id will be updated after the revision is created)
INSERT INTO rhnConfigFile(
    id,
    config_channel_id,
    config_file_name_id,
    state_id
)
SELECT
    sequence_nextval('rhn_conffile_id_seq'),
    cc.id,
    (SELECT id FROM rhnConfigFileName WHERE path = '/init.sls'),
    (SELECT id from rhnConfigFileState WHERE label = 'alive')
FROM rhnConfigChannel cc
WHERE
    cc.confchan_type_id IN (SELECT id from rhnConfigChannelType WHERE label = 'state');

-------------------------------------------------------------------------------
-- CONFIG REVISION ------------------------------------------------------------
-------------------------------------------------------------------------------
-- CONTENT
-- initial version is empty
SELECT lookup_checksum('md5', 'd41d8cd98f00b204e9800998ecf8427e') FROM DUAL;

INSERT INTO rhnConfigContent(
    id,
    contents,
    file_size,
    checksum_id,
    is_binary,
    delim_start,
    delim_end)
SELECT
    sequence_nextval('rhn_confcontent_id_seq'),
    '',
    0,
    lookup_checksum('md5', 'd41d8cd98f00b204e9800998ecf8427e'), -- empty content
    'N',
    '{|',
    '|}'
FROM DUAL;

-- REVISION
SELECT lookup_config_info('root', 'root', 644, null, null) FROM dual;
INSERT INTO rhnConfigRevision(
    id,
    revision,
    config_file_id,
    config_content_id,
    config_info_id,
    config_file_type_id
)
SELECT
    sequence_nextval('rhn_confrevision_id_seq'),
    1,
    cf.id,
    (SELECT MAX(id) FROM rhnConfigContent WHERE checksum_id = lookup_checksum('md5', 'd41d8cd98f00b204e9800998ecf8427e')),
    lookup_config_info('root', 'root', 644, null, null),
    (SELECT id FROM rhnConfigFileType WHERE label = 'sls')
FROM rhnConfigFile cf
WHERE
    config_file_name_id = (SELECT id FROM rhnConfigFileName WHERE path = '/init.sls') AND
    NOT EXISTS (SELECT id FROM rhnConfigRevision WHERE config_file_id = cf.id);


-- update latest_config_revision_id in rhnConfigFile
UPDATE rhnConfigFile cf
SET latest_config_revision_id = (SELECT MAX(id) FROM rhnConfigRevision WHERE config_file_id = cf.id)
WHERE
    cf.config_file_name_id IN (SELECT id FROM rhnConfigFileName WHERE path = '/init.sls') AND
    cf.latest_config_revision_id IS NULL;
 07070100000C15000081B400000000000000000000000167AE11140000065E000000000000000000000000000000000000008600000000susemanager-schema/upgrade/susemanager-schema-3.1.13-to-susemanager-schema-3.1.14/503-create-revisions-for-servers-with-conf-channels -- oracle equivalent source sha1 df6188637d4b993e47fc2105624d515e452f18a5
-- Temporary procedure
--
-- For each minion server associated with a configuration channel but not
-- associated with any state revision create a revision and associate the
-- server with it.
--
-- This is needed as we need to upgrade the association of server's state
-- revision to configuration channel (based on rhnServerConfigChannel) in the
-- following steps. For this, the revision and it's association to the server
-- must exist.
--

CREATE OR REPLACE FUNCTION suse_create_revision_for_servers_with_conf_channel()
RETURNS VOID AS
$$
DECLARE
    new_rev_id numeric := 0;
    sid numeric := 0;
BEGIN
    FOR sid IN SELECT DISTINCT serverChannel.server_id
               FROM rhnServerConfigChannel serverChannel INNER JOIN suseMinionInfo minionInfo
               ON serverChannel.server_id = minionInfo.server_id
               WHERE NOT EXISTS (SELECT 1 FROM suseServerStateRevision WHERE server_id = serverChannel.server_id)
    LOOP
        SELECT sequence_nextval('suse_state_revision_id_seq') INTO new_rev_id FROM DUAL;
        raise notice 'INSERTING NEW STATE REVISION: %', new_rev_id;
        EXECUTE 'INSERT INTO suseStateRevision(id) VALUES (' || new_rev_id || ');';
        raise notice 'LINKING IT TO SERVER: %', sid;
        EXECUTE 'INSERT INTO suseServerStateRevision(server_id, state_revision_id) VALUES (' || sid || ', ' || new_rev_id || ');';
    END LOOP;
END
$$
LANGUAGE plpgsql;
SELECT 1 FROM suse_create_revision_for_servers_with_conf_channel();
DROP FUNCTION IF EXISTS suse_create_revision_for_servers_with_conf_channel();
  07070100000C16000081B400000000000000000000000167AE111400001A2A000000000000000000000000000000000000007E00000000susemanager-schema/upgrade/susemanager-schema-3.1.13-to-susemanager-schema-3.1.14/504-custom-states-assignments-migration.sql -------------------------------------------------------------------------------
-- CHANNEL ASSIGNMENT ---------------------------------------------------------
-------------------------------------------------------------------------------
-- OLD STYLE SYSTEM-CHANNEL ASSIGNMENT (via rhnServerConfigChannel)
-- we need to add new assignments based on 'server - custom states' assignments
INSERT INTO rhnServerConfigChannel(
    server_id,
    config_channel_id,
    position)
SELECT
    serverRev.server_id,
    configChannel.id,
    -- generate the position for the new assignments
    rank() OVER (PARTITION BY server_id ORDER BY configChannel.id) + COALESCE((SELECT max(position) FROM rhnServerConfigChannel WHERE server_id = serverRev.server_id), 0)
FROM
    suseCustomState customState
    INNER JOIN suseStateRevisionCustomState revCustomState ON customState.id = revCustomState.state_id
    INNER JOIN suseStateRevision rev ON revCustomState.state_revision_id = rev.id
    INNER JOIN suseServerStateRevision serverRev ON rev.id = serverRev.state_revision_id
    INNER JOIN rhnConfigChannel configChannel ON configChannel.label = customState.state_name
WHERE
    customState.state_deleted = 'N' AND
    -- we only want the latest revision
    rev.id = (SELECT max(state_revision_id) FROM suseServerStateRevision WHERE server_id = serverRev.server_id) AND
    NOT EXISTS (SELECT server_id
                FROM rhnServerConfigChannel
                WHERE server_id = serverRev.server_id
                      AND config_channel_id = configChannel.id);

-- NEW STYLE SYSTEM-CHANNEL ASSIGNMENT (via suseStateRevisionConfigChannel)
-- (suseStateRevisionConfigChannel duplicates the information from rhnServerConfigChannel)
-- Here we insert new 'revision - config channel' association based on
-- 'server - config channel' assignment.
-- We only update the latest revision as the revisions from the past as we
-- can't reconstruct the history of the assignments from the information in
-- rhnServerConfigChannel.
INSERT INTO suseStateRevisionConfigChannel(
    state_revision_id,
    config_channel_id,
    position
)
SELECT
    state_revision_id,
    serverConfigChannel.config_channel_id,
    serverConfigChannel.position
FROM
    suseServerStateRevision serverStateRevision
    INNER JOIN rhnServerConfigChannel serverConfigChannel ON serverStateRevision.server_id = serverConfigChannel.server_id
WHERE
    serverStateRevision.state_revision_id = (SELECT max(state_revision_id)
                                             FROM suseServerStateRevision
                                             WHERE server_id = serverConfigChannel.server_id)
    AND NOT EXISTS (SELECT *
                    FROM suseStateRevisionConfigChannel
                    WHERE state_revision_id = serverStateRevision.state_revision_id
                        AND config_channel_id = serverConfigChannel.config_channel_id);

-- SUSE REVISION ASSIGNMENT
-- Converting the revision-custom state assignment to revision-config channel
-- assignment for servers, server groups and organizations.
INSERT INTO suseStateRevisionConfigChannel(
    state_revision_id,
    config_channel_id)
SELECT DISTINCT
    rev.id, channel.id
FROM suseCustomState state
    INNER JOIN suseStateRevisionCustomState revState on state.id = revState.state_id
    INNER JOIN suseStateRevision rev ON rev.id = revState.state_revision_id
    INNER JOIN rhnConfigChannel channel ON channel.label = state.state_name
WHERE
    state.state_deleted = 'N'
    AND NOT EXISTS (SELECT state_revision_id
                    FROM suseStateRevisionConfigChannel
                    WHERE state_revision_id = rev.id
                          AND config_channel_id = channel.id);

-- GENERATE POSITION
-- STATE-SERVER assignments
-- position of the latest revision for servers is determined by rhnServerConfigChannel
UPDATE suseStateRevisionConfigChannel rev
SET position = (SELECT position
                FROM rhnServerConfigChannel serverChannel
                    INNER JOIN suseServerStateRevision serverStateRev ON serverChannel.server_id = serverStateRev.server_id
                WHERE
                    serverStateRev.state_revision_id = rev.state_revision_id
                    AND serverChannel.config_channel_id = rev.config_channel_id)
WHERE
    position IS NULL
    AND rev.state_revision_id IN (SELECT max(state_revision_id) FROM suseServerStateRevision GROUP BY server_id);
    -- and is a server revision, not org/grp


-- STATE-ORGANIZATION assignments
-- We generate initial ranking.
UPDATE suseStateRevisionConfigChannel
SET position = (SELECT rank
                      -- the inner SELECT gives us ranking of channels in form of: (channel ID, revision ID, position in ranking)
                      -- this is an initial ranking and we determine it based on channel id
                FROM (SELECT config_channel_id, revConfigChannel.state_revision_id, (rank() OVER (PARTITION BY orgRev.state_revision_id ORDER BY config_channel_id)) rank
                      FROM suseStateRevisionConfigChannel revConfigChannel
                          INNER JOIN suseOrgStateRevision orgRev
                          ON revConfigChannel.state_revision_id = orgRev.state_revision_id) RANKING
                WHERE config_channel_id = suseStateRevisionConfigChannel.config_channel_id
                    AND state_revision_id = suseStateRevisionConfigChannel.state_revision_id)
WHERE position IS NULL
    AND state_revision_id in (SELECT state_revision_id from suseOrgStateRevision);

-- STATE-SERVER GROUP assignments
-- We generate initial ranking.
UPDATE suseStateRevisionConfigChannel
SET position = (SELECT rank
                      -- the inner SELECT gives us ranking of channels in form of: (channel ID, revision ID, position in ranking)
                      -- this is an initial ranking and we determine it based on channel id
                FROM (SELECT config_channel_id, revConfigChannel.state_revision_id, (rank() OVER (PARTITION BY grpRev.state_revision_id ORDER BY config_channel_id)) rank
                      FROM suseStateRevisionConfigChannel revConfigChannel
                          INNER JOIN suseServerGroupStateRevision grpRev
                          ON revConfigChannel.state_revision_id = grpRev.state_revision_id) RANKING
                WHERE config_channel_id = suseStateRevisionConfigChannel.config_channel_id
                    AND state_revision_id = suseStateRevisionConfigChannel.state_revision_id)
WHERE position IS NULL
    AND state_revision_id in (SELECT state_revision_id from suseServerGroupStateRevision);

-- DROP OLD STATES
DROP TABLE suseStateRevisionCustomState;
DROP TABLE suseCustomState;
  07070100000C17000081B400000000000000000000000167AE111400000089000000000000000000000000000000000000007900000000susemanager-schema/upgrade/susemanager-schema-3.1.13-to-susemanager-schema-3.1.14/505-enable-custom-states-migration.sql  INSERT INTO rhnTaskQueue (org_id, task_name, task_data)
SELECT id, 'upgrade_satellite_custom_states', 0
FROM web_customer
WHERE id = 1;

   07070100000C18000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005200000000susemanager-schema/upgrade/susemanager-schema-3.1.14-to-susemanager-schema-3.1.15 07070100000C19000081B400000000000000000000000167AE111400000000000000000000000000000000000000000000005B00000000susemanager-schema/upgrade/susemanager-schema-3.1.14-to-susemanager-schema-3.1.15/.gitkeep    07070100000C1A000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005200000000susemanager-schema/upgrade/susemanager-schema-3.1.15-to-susemanager-schema-3.1.16 07070100000C1B000081B400000000000000000000000167AE11140000078D000000000000000000000000000000000000007400000000susemanager-schema/upgrade/susemanager-schema-3.1.15-to-susemanager-schema-3.1.16/005-subscribe-channels-action.sql   CREATE TABLE rhnActionSubChannels (
    id                  NUMERIC NOT NULL
                            CONSTRAINT rhn_actionsubscrch_id_pk PRIMARY KEY,
    action_id           NUMERIC NOT NULL
                            CONSTRAINT rhn_actionsubscrch_aid_fk
                            REFERENCES rhnAction (id)
                            ON DELETE CASCADE,
    base_channel_id     NUMERIC
                            CONSTRAINT rhn_actionsubscrch_base_ch_fk
                            REFERENCES rhnChannel (id)
                            ON DELETE CASCADE,
    created             TIMESTAMPTZ
                            DEFAULT (CURRENT_TIMESTAMP) NOT NULL,
    modified            TIMESTAMPTZ
                            DEFAULT (CURRENT_TIMESTAMP) NOT NULL
)

;

CREATE SEQUENCE RHN_ACT_SUBSCR_CHNLS_ID_SEQ;

CREATE TABLE rhnActionSubChannelsList (
    subscribe_channels_id
                        NUMERIC NOT NULL
                            CONSTRAINT rhn_actionsubscrchls_det_fk
                            REFERENCES rhnActionSubChannels (id)
                            ON DELETE CASCADE,
    channel_id          NUMERIC NOT NULL
                            CONSTRAINT rhn_actionsubscrchls_ch_fk
                            REFERENCES rhnChannel (id)
                            ON DELETE CASCADE
)

;

CREATE TABLE rhnActionSubChannelsTokens (
    subscribe_channels_id
                        NUMERIC NOT NULL
                            CONSTRAINT rhn_actionsubscrchtok_det_fk
                            REFERENCES rhnActionSubChannels (id)
                            ON DELETE CASCADE,
    token_id            NUMERIC NOT NULL
                            CONSTRAINT rhn_actionsubscrchtok_tok_fk
                            REFERENCES suseChannelAccessToken (id)
                            ON DELETE CASCADE
)

;

insert into rhnActionType values (506, 'channels.subscribe', 'Subscribe to channels', 'N', 'N');
   07070100000C1C000081B400000000000000000000000167AE1114000002F3000000000000000000000000000000000000006F00000000susemanager-schema/upgrade/susemanager-schema-3.1.15-to-susemanager-schema-3.1.16/006-rhnActionSubChannels.sql    
--
-- Copyright (c) 2018 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
--

create or replace function rhn_actionsbscrch_mod_trig_fun() returns trigger as
$$
begin
	new.modified := current_timestamp;
	return new;
end;
$$ language plpgsql;

create trigger
rhn_actionsbscrch_mod_trig
before insert or update on rhnActionSubChannels
for each row
execute procedure rhn_actionsbscrch_mod_trig_fun();

 07070100000C1D000081B400000000000000000000000167AE11140000072F000000000000000000000000000000000000007D00000000susemanager-schema/upgrade/susemanager-schema-3.1.15-to-susemanager-schema-3.1.16/007-add-minionactionchainexecutor-task.sql  --
-- Copyright (c) 2018 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

INSERT INTO rhnTaskoBunch (id, name, description, org_bunch)
  SELECT sequence_nextval('rhn_tasko_bunch_id_seq'), 'minion-action-chain-executor-bunch', 'Execute action chains on Minions', null from dual
   where not exists (select 1 from rhnTaskoBunch where name = 'minion-action-chain-executor-bunch');

INSERT INTO rhnTaskoTask (id, name, class)
    SELECT sequence_nextval('rhn_tasko_task_id_seq'), 'minion-action-chain-executor', 'com.redhat.rhn.taskomatic.task.MinionActionChainExecutor' from dual
     where not exists (select 1 from rhnTaskoTask where name = 'minion-action-chain-executor');

INSERT INTO rhnTaskoTemplate (id, bunch_id, task_id, ordering, start_if)
    SELECT sequence_nextval('rhn_tasko_template_id_seq'),
        (SELECT id FROM rhnTaskoBunch WHERE name='minion-action-chain-executor-bunch'),
        (SELECT id FROM rhnTaskoTask WHERE name='minion-action-chain-executor'),
        0,
        null from dual
     where not exists (select 1 from rhnTaskoTemplate
                        where bunch_id = (SELECT id FROM rhnTaskoBunch WHERE name='minion-action-chain-executor-bunch')
                          and task_id = (SELECT id FROM rhnTaskoTask WHERE name='minion-action-chain-executor'));
 07070100000C1E000081B400000000000000000000000167AE1114000006CE000000000000000000000000000000000000008400000000susemanager-schema/upgrade/susemanager-schema-3.1.15-to-susemanager-schema-3.1.16/008-add-minion-action-chain-cleanup-tasko-job.sql   INSERT INTO rhnTaskoBunch (id, name, description, org_bunch)
    SELECT sequence_nextval('rhn_tasko_bunch_id_seq'), 'minion-action-chain-cleanup-bunch', 'Cleanup actions chains for Minions', null
    FROM dual WHERE NOT EXISTS (
        SELECT 1 FROM rhnTaskoBunch WHERE
        name='minion-action-chain-cleanup-bunch'
    );

INSERT INTO rhnTaskoSchedule (id, job_label, bunch_id, active_from, cron_expr)
    SELECT sequence_nextval('rhn_tasko_schedule_id_seq'), 'minion-action-chain-cleanup-default',
        (SELECT id FROM rhnTaskoBunch WHERE name='minion-action-chain-cleanup-bunch'),
        current_timestamp, '0 0 * * * ?'
    FROM dual WHERE NOT EXISTS (
        SELECT 1 FROM rhnTaskoSchedule WHERE
        job_label='minion-action-chain-cleanup-default'
    );

INSERT INTO rhnTaskoTask (id, name, class)
    SELECT sequence_nextval('rhn_tasko_task_id_seq'), 'minion-action-chain-cleanup', 'com.redhat.rhn.taskomatic.task.MinionActionChainCleanup'
    FROM dual WHERE NOT EXISTS (
        SELECT 1 FROM rhnTaskoTask WHERE
        name='minion-action-chain-cleanup'
    );

INSERT INTO rhnTaskoTemplate (id, bunch_id, task_id, ordering, start_if)
    SELECT sequence_nextval('rhn_tasko_template_id_seq'),
                        (SELECT id FROM rhnTaskoBunch WHERE name='minion-action-chain-cleanup-bunch'),
                        (SELECT id FROM rhnTaskoTask WHERE name='minion-action-chain-cleanup'),
                        0,
                        null
    FROM dual WHERE NOT EXISTS (
        SELECT 1 FROM rhnTaskoTemplate WHERE
        bunch_id=(SELECT id FROM rhnTaskoBunch WHERE name='minion-action-chain-cleanup-bunch') AND
        task_id=(SELECT id FROM rhnTaskoTask WHERE name='minion-action-chain-cleanup')
    );
  07070100000C1F000081B400000000000000000000000167AE111400000A9C000000000000000000000000000000000000007400000000susemanager-schema/upgrade/susemanager-schema-3.1.15-to-susemanager-schema-3.1.16/100-lookup_package_capability.sql   --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 

create or replace function lookup_package_capability(name_in in varchar, version_in in varchar default null)
returns numeric
as
$$
declare
    name_id numeric;
begin
    if version_in is null then
        select id
          into name_id
          from rhnpackagecapability
         where name = name_in and
               version is null;
    else
        select id
          into name_id
          from rhnpackagecapability
         where name = name_in and
               version = version_in;
    end if;

    if not found then
        name_id = nextval('rhn_pkg_capability_id_seq');

        insert into rhnPackageCapability(id, name, version)
            values (name_id, name_in, version_in)
            on conflict do nothing;

        if version_in is null then
            select id
                into strict name_id
                from rhnpackagecapability
                where name = name_in and version is null;
        else
            select id
                into strict name_id
                from rhnpackagecapability
                where name = name_in and version = version_in;
        end if;
    end if;

    return name_id;
end;
$$ language plpgsql;

-- Note: intentionally not thread-safe! You must aquire a write lock on the
-- rhnPackageCapability tabel if you are going to use this proc!
create or replace function lookup_package_capability_fast(name_in in varchar, version_in in varchar default null)
returns numeric
as
$$
declare
    name_id numeric;
begin
    if version_in is null then
        select id
          into name_id
          from rhnpackagecapability
         where name = name_in and
               version is null;
    else
        select id
          into name_id
          from rhnpackagecapability
         where name = name_in and
               version = version_in;
    end if;

    if not found then
        name_id = nextval('rhn_pkg_capability_id_seq');
        insert into rhnPackageCapability(id, name, version) values (
               name_id, name_in, version_in);
    end if;

    return name_id;
end;
$$
language plpgsql;
07070100000C20000081B400000000000000000000000167AE111400000998000000000000000000000000000000000000006A00000000susemanager-schema/upgrade/susemanager-schema-3.1.15-to-susemanager-schema-3.1.16/101-lookup_checksum.sql --
-- Copyright (c) 2010 - 2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

create or replace function
lookup_checksum(checksum_type_in in varchar, checksum_in in varchar)
returns numeric
as
$$
declare
    checksum_id     numeric;
begin
    if checksum_in is null then
        return null;
    end if;

    select c.id
      into checksum_id
      from rhnChecksumView c
     where c.checksum = checksum_in and
           c.checksum_type = checksum_type_in;

    if not found then
        checksum_id := nextval('rhnchecksum_seq');

        insert into rhnChecksum (id, checksum_type_id, checksum)
          values (
              checksum_id,
              (select id from rhnChecksumType where label = checksum_type_in),
              checksum_in
          )
          on conflict do nothing;

          select c.id
              into strict checksum_id
              from rhnChecksumView c
              where c.checksum = checksum_in and
                  c.checksum_type = checksum_type_in;
    end if;

    return checksum_id;
end;
$$ language plpgsql;

-- NOTE: This is intentionally not thread safe! You must lock rhnChecksum
-- if you are going to use this procedure!
create or replace function
lookup_checksum_fast(checksum_type_in in varchar, checksum_in in varchar)
returns numeric
as
$$
declare
    checksum_id     numeric;
begin
    if checksum_in is null then
        return null;
    end if;

    select c.id
      into checksum_id
      from rhnChecksumView c
     where c.checksum = checksum_in and
           c.checksum_type = checksum_type_in;

    if not found then
        checksum_id := nextval('rhnchecksum_seq');
        insert into rhnChecksum (id, checksum_type_id, checksum) values (
            checksum_id,
            (select id from rhnChecksumType where label = checksum_type_in),
            checksum_in);
    end if;

    return checksum_id;
end;
$$
language plpgsql;
07070100000C21000081B400000000000000000000000167AE1114000004F9000000000000000000000000000000000000007300000000susemanager-schema/upgrade/susemanager-schema-3.1.15-to-susemanager-schema-3.1.16/102-lookup_client_capability.sql    --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 

create or replace function
lookup_client_capability(name_in in varchar)
returns numeric
as $$
declare
    cap_name_id     numeric;
begin
    select id
      into cap_name_id
      from rhnclientcapabilityname
     where name = name_in;

    if not found then
        cap_name_id := nextval('rhn_client_capname_id_seq');

        insert into rhnClientCapabilityName(id, name)
            values (cap_name_id, name_in)
            on conflict do nothing;

        select id
            into strict cap_name_id
            from rhnclientcapabilityname
            where name = name_in;
    end if;

    return cap_name_id;
end;
$$ language plpgsql;
   07070100000C22000081B400000000000000000000000167AE1114000004C4000000000000000000000000000000000000007100000000susemanager-schema/upgrade/susemanager-schema-3.1.15-to-susemanager-schema-3.1.16/103-lookup_config_filename.sql  --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.

create or replace function
lookup_config_filename(name_in in varchar)
returns numeric as
$$
declare
    name_id     numeric;
begin
    select id
      into name_id
      from rhnconfigfilename
     where path = name_in;

    if not found then
        name_id := nextval('rhn_cfname_id_seq');

        insert into rhnConfigFileName (id, path)
            values (name_id, name_in)
            on conflict do nothing;

        select id
            into strict name_id
            from rhnconfigfilename
            where path = name_in;
    end if;

    return name_id;
end;
$$ language plpgsql;
07070100000C23000081B400000000000000000000000167AE1114000007FC000000000000000000000000000000000000006D00000000susemanager-schema/upgrade/susemanager-schema-3.1.15-to-susemanager-schema-3.1.16/104-lookup_config_info.sql  --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

create or replace function
lookup_config_info
(
    username_in     in varchar,
    groupname_in    in varchar,
    filemode_in     in numeric,
    selinux_ctx_in  in varchar,
    symlink_target_id in numeric
)
returns numeric
as
$$
declare
    r numeric;
    v_id    numeric;
    lookup_cursor cursor  for
        select id
          from rhnConfigInfo
         where 1=1
           and (username = username_in or (username is null and username_in is null))
           and (groupname = groupname_in or (groupname is null and groupname_in is null))
           and (filemode = filemode_in or (filemode is null and filemode_in is null))
           and (selinux_ctx = selinux_ctx_in or
               (selinux_ctx is null and selinux_ctx_in is null))
           and (symlink_target_filename_id = symlink_target_id or
               (symlink_target_filename_id is null and symlink_target_id is null))
        ;
begin
    for r in lookup_cursor loop
        return r.id;
    end loop;
    -- If we got here, we don't have the id
    v_id := nextval('rhn_confinfo_id_seq');

    insert into rhnConfigInfo (id, username, groupname, filemode, selinux_ctx, symlink_target_filename_id)
        values (v_id, username_in, groupname_in, filemode_in, selinux_ctx_in, symlink_target_id)
        on conflict do nothing;

    for r in lookup_cursor loop
        return r.id;
    end loop;
    return v_id;
end;
$$ language plpgsql;
07070100000C24000081B400000000000000000000000167AE111400000494000000000000000000000000000000000000006500000000susemanager-schema/upgrade/susemanager-schema-3.1.15-to-susemanager-schema-3.1.16/105-lookup_cve.sql  --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.

create or replace function
lookup_cve(name_in in varchar)
returns numeric
as $$
declare
    name_id     numeric;
begin
    select id
      into name_id
      from rhnCVE
     where name = name_in;

    if not found then
        name_id := nextval('rhn_cve_id_seq');

        insert into rhnCVE (id, name)
            values (name_id, name_in)
            on conflict do nothing;

        select id
            into strict name_id
            from rhnCVE
            where name = name_in;
    end if;

    return name_id;
end;
$$ language plpgsql;
07070100000C25000081B400000000000000000000000167AE1114000005B6000000000000000000000000000000000000006500000000susemanager-schema/upgrade/susemanager-schema-3.1.15-to-susemanager-schema-3.1.16/106-lookup_evr.sql  --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.

create or replace function
lookup_evr(e_in in varchar, v_in in varchar, r_in in varchar)
returns numeric
as
$$
declare
    evr_id  numeric;
begin
    select id
      into evr_id
      from rhnPackageEVR
     where ((epoch is null and e_in is null) or (epoch = e_in)) and
           version = v_in and
           release = r_in;

    if not found then
        evr_id := nextval('rhn_pkg_evr_seq');

        insert into rhnPackageEVR(id, epoch, version, release, evr)
            values (evr_id, e_in, v_in, r_in, evr_t(e_in, v_in, r_in))
            on conflict do nothing;

        select id
            into strict evr_id
            from rhnPackageEVR
            where ((epoch is null and e_in is null) or (epoch = e_in)) and
               version = v_in and release = r_in;
    end if;

    return evr_id;
end;
$$ language plpgsql;
  07070100000C26000081B400000000000000000000000167AE111400000419000000000000000000000000000000000000006C00000000susemanager-schema/upgrade/susemanager-schema-3.1.15-to-susemanager-schema-3.1.16/107-lookup_md_keyword.sql   --
-- Copyright (c) 2012 Novell
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--

create or replace function
lookup_md_keyword(label_in in varchar)
returns numeric
as
$$
declare
    md_keyword_id numeric;
begin
    select id
      into md_keyword_id
      from suseMdKeyword
     where label = label_in;
    if not found then
        md_keyword_id := nextval('suse_mdkeyword_id_seq');

        insert into suseMdKeyword (id, label)
            values (md_keyword_id, label_in)
            on conflict do nothing;

        select id
            into strict md_keyword_id
            from suseMdKeyword
            where label = label_in;
    end if;

    return md_keyword_id;
end;
$$ language plpgsql;
   07070100000C27000081B400000000000000000000000167AE1114000004BA000000000000000000000000000000000000006F00000000susemanager-schema/upgrade/susemanager-schema-3.1.15-to-susemanager-schema-3.1.16/108-lookup_package_delta.sql    --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 

create or replace function lookup_package_delta(n_in in varchar)
returns numeric
as
$$
declare
    name_id     numeric;
begin
    select id
      into name_id
      from rhnPackageDelta
     where label = n_in;

    if not found then
        name_id := nextval('rhn_packagedelta_id_seq');

        insert into rhnPackageDelta(id, label)
            values (name_id, n_in)
            on conflict do nothing;

        select id
            into strict name_id
            from rhnpackagedelta
            where label = n_in;
    end if;

    return name_id;
end;
$$ language plpgsql;
  07070100000C28000081B400000000000000000000000167AE1114000004D4000000000000000000000000000000000000006F00000000susemanager-schema/upgrade/susemanager-schema-3.1.15-to-susemanager-schema-3.1.16/109-lookup_package_group.sql    --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 

create or replace function
lookup_package_group(name_in in varchar)
returns numeric
as
$$
declare
    package_id   numeric;
begin
    select id
      into package_id
      from rhnPackageGroup
     where name = name_in;

    if not found then
        package_id := nextval('rhn_package_group_id_seq');

        insert into rhnPackageGroup(id, name)
            values (package_id, name_in)
            on conflict do nothing;

        select id
            into strict package_id
            from rhnPackageGroup
            where name = name_in;
    end if;

    return package_id;
end;
$$ language plpgsql;
07070100000C29000081B400000000000000000000000167AE11140000052C000000000000000000000000000000000000006E00000000susemanager-schema/upgrade/susemanager-schema-3.1.15-to-susemanager-schema-3.1.16/110-lookup_package_name.sql --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 

create or replace function
lookup_package_name(name_in in varchar, ignore_null in numeric default 0)
returns numeric
as
$$
declare
    name_id     numeric;
begin
    if ignore_null = 1 and name_in is null then
        return null;
    end if;

    select id
      into name_id
      from rhnPackageName
     where name = name_in;

    if not found then
        name_id := nextval('rhn_pkg_name_seq');

        insert into rhnPackageName(id, name)
            values (name_id, name_in)
            on conflict do nothing;

        select id
            into strict name_id
            from rhnPackageName
            where name = name_in;
    end if;

    return name_id;
end;
$$ language plpgsql;
07070100000C2A000081B400000000000000000000000167AE111400000724000000000000000000000000000000000000006F00000000susemanager-schema/upgrade/susemanager-schema-3.1.15-to-susemanager-schema-3.1.16/111-lookup_package_nevra.sql    --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 

create or replace function
lookup_package_nevra(
        name_id_in in numeric,
        evr_id_in in numeric,
        package_arch_id_in in numeric,
        ignore_null_name in numeric default 0
) returns numeric
as
$$
declare
    nevra_id numeric;
begin
    if ignore_null_name = 1 and name_id_in is null then
        return null;
    end if;

    select id
      into nevra_id
      from rhnPackageNEVRA
     where name_id = name_id_in and
           evr_id = evr_id_in and
           (package_arch_id = package_arch_id_in or
            (package_arch_id is null and package_arch_id_in is null));

    if not found then
        nevra_id := nextval('rhn_pkgnevra_id_seq');

        insert into rhnPackageNEVRA(id, name_id, evr_id, package_arch_id)
            values (nevra_id, name_id_in, evr_id_in, package_arch_id_in)
            on conflict do nothing;

        select id
            into strict nevra_id
            from rhnPackageNEVRA
            where name_id = name_id_in and evr_id = evr_id_in and
                (package_arch_id = package_arch_id_in or
                (package_arch_id is null and package_arch_id_in is null));
    end if;

    return nevra_id;
end;
$$ language plpgsql;
07070100000C2B000081B400000000000000000000000167AE1114000004BF000000000000000000000000000000000000006D00000000susemanager-schema/upgrade/susemanager-schema-3.1.15-to-susemanager-schema-3.1.16/112-lookup_source_name.sql  --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 

create or replace function
lookup_source_name(name_in in varchar)
returns numeric
as
$$
declare
    source_id   numeric;
begin
    select id
      into source_id
      from rhnSourceRPM
     where name = name_in;

    if not found then
        source_id := nextval('rhn_sourcerpm_id_seq');

        insert into rhnSourceRPM(id, name)
            values (source_id, name_in)
            on conflict do nothing;

        select id
            into strict source_id
            from rhnSourceRPM
            where name = name_in;
    end if;

    return source_id;
end;
$$ language plpgsql;
 07070100000C2C000081B400000000000000000000000167AE111400000567000000000000000000000000000000000000006500000000susemanager-schema/upgrade/susemanager-schema-3.1.15-to-susemanager-schema-3.1.16/113-lookup_tag.sql  --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 

create or replace function
lookup_tag(org_id_in in numeric, name_in in varchar)
returns numeric
as $$
declare
    tag_id  numeric;
    tag_name_id numeric;
begin
    tag_name_id := lookup_tag_name(name_in);

    select id
      into tag_id
      from rhnTag
     where org_id = org_id_in and
           name_id = tag_name_id;

    if not found then
        tag_id := nextval('rhn_tag_id_seq');

        insert into rhnTag(id, org_id, name_id)
            values (tag_id, org_id_in, tag_name_id)
            on conflict do nothing;

        select id
            into strict tag_id
            from rhnTag
            where org_id = org_id_in and
                name_id = lookup_tag_name(name_in);
    end if;

    return tag_id;
end;
$$ language plpgsql;
 07070100000C2D000081B400000000000000000000000167AE1114000004A6000000000000000000000000000000000000006A00000000susemanager-schema/upgrade/susemanager-schema-3.1.15-to-susemanager-schema-3.1.16/114-lookup_tag_name.sql --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 

create or replace function
lookup_tag_name(name_in in varchar)
returns numeric
as
$$
declare
    name_id numeric;
begin
    select id
      into name_id
      from rhnTagName
     where name = name_in;

    if not found then
        name_id := nextval('rhn_tagname_id_seq');

        insert into rhnTagName(id, name)
            values (name_id, name_in)
            on conflict do nothing;

        select id
            into strict name_id
            from rhnTagName
            where name = name_in;
    end if;

    return name_id;
end;
$$ language plpgsql;
  07070100000C2E000081B400000000000000000000000167AE11140000088B000000000000000000000000000000000000007500000000susemanager-schema/upgrade/susemanager-schema-3.1.15-to-susemanager-schema-3.1.16/115-lookup_transaction_package.sql  --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 

create or replace function
lookup_transaction_package(
    o_in in varchar,
    n_in in varchar,
    e_in in varchar,
    v_in in varchar,
    r_in in varchar,
    a_in in varchar)
returns numeric
as
$$
declare
    o_id        numeric;
    n_id        numeric;
    e_id        numeric;
    p_arch_id   numeric;
    tp_id       numeric;
begin
    select id
      into o_id
      from rhnTransactionOperation
     where label = o_in;

    if not found then
        perform rhn_exception.raise_exception('invalid_transaction_operation');
    end if;

    n_id := lookup_package_name(n_in);
    e_id := lookup_evr(e_in, v_in, r_in);
    p_arch_id := null;

    if a_in is not null then
        p_arch_id := lookup_package_arch(a_in);
    end if;

    select id
      into tp_id
      from rhnTransactionPackage
     where operation = o_id and
           name_id = n_id and
           evr_id = e_id and
           (package_arch_id = p_arch_id or (p_arch_id is null and package_arch_id is null));

    if not found then
        tp_id := nextval('rhn_transpack_id_seq');

        insert into rhnTransactionPackage (id, operation, name_id, evr_id, package_arch_id)
            values (tp_id, o_id, n_id, e_id, p_arch_id)
            on conflict do nothing;

        select id
            into strict tp_id
            from rhnTransactionPackage
         where operation = o_id and name_id = n_id and evr_id = e_id and
            (package_arch_id = p_arch_id or (p_arch_id is null and package_arch_id is null));
    end if;
    return tp_id;
end;
$$ language plpgsql;
 07070100000C2F000081B400000000000000000000000167AE11140000056C000000000000000000000000000000000000007100000000susemanager-schema/upgrade/susemanager-schema-3.1.15-to-susemanager-schema-3.1.16/116-lookup_xccdf_benchmark.sql  --
-- Copyright (c) 2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

create or replace function
lookup_xccdf_benchmark(identifier_in in varchar, version_in in varchar)
returns numeric
as
$$
declare
    benchmark_id numeric;
begin
    select id
      into benchmark_id
      from rhnXccdfBenchmark
     where identifier = identifier_in and version = version_in;

    if not found then
        benchmark_id := nextval('rhn_xccdf_benchmark_id_seq');

        insert into rhnXccdfBenchmark (id, identifier, version)
            values (benchmark_id, identifier_in, version_in)
            on conflict do nothing;

        select id
            into strict benchmark_id
            from rhnXccdfBenchmark
            where identifier = identifier_in and version = version_in;
    end if;

    return benchmark_id;
end;
$$ language plpgsql;
07070100000C30000081B400000000000000000000000167AE111400000764000000000000000000000000000000000000006D00000000susemanager-schema/upgrade/susemanager-schema-3.1.15-to-susemanager-schema-3.1.16/117-lookup_xccdf_ident.sql  --
-- Copyright (c) 2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.

create or replace function
lookup_xccdf_ident(system_in in varchar, identifier_in in varchar)
returns numeric
as
$$
declare
    xccdf_ident_id numeric;
    ident_sys_id numeric;
begin
    select id
      into ident_sys_id
      from rhnXccdfIdentSystem
     where system = system_in;
    if not found then
        ident_sys_id := nextval('rhn_xccdf_identsytem_id_seq');

        insert into rhnXccdfIdentSystem (id, system)
            values (ident_sys_id, system_in)
            on conflict do nothing;

        select id
            into strict ident_sys_id
            from rhnXccdfIdentSystem
            where system = system_in;
    end if;

    select id
      into xccdf_ident_id
      from rhnXccdfIdent
     where identsystem_id = ident_sys_id and identifier = identifier_in;
    if not found then
        xccdf_ident_id := nextval('rhn_xccdf_ident_id_seq');

        insert into rhnXccdfIdent (id, identsystem_id, identifier)
            values (xccdf_ident_id, ident_sys_id, identifier_in)
            on conflict do nothing;

        select id
            into strict xccdf_ident_id
            from rhnXccdfIdent
            where identsystem_id = ident_sys_id and identifier = identifier_in;
    end if;
    return xccdf_ident_id;
end;
$$ language plpgsql;
07070100000C31000081B400000000000000000000000167AE111400000541000000000000000000000000000000000000006F00000000susemanager-schema/upgrade/susemanager-schema-3.1.15-to-susemanager-schema-3.1.16/118-lookup_xccdf_profile.sql    --
-- Copyright (c) 2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

create or replace function
lookup_xccdf_profile(identifier_in in varchar, title_in in varchar)
returns numeric
as
$$
declare
    profile_id numeric;
begin
    select id
      into profile_id
      from rhnXccdfProfile
     where identifier = identifier_in and title = title_in;

    if not found then
        profile_id := nextval('rhn_xccdf_profile_id_seq');

        insert into rhnXccdfProfile (id, identifier, title)
            values (profile_id, identifier_in, title_in)
            on conflict do nothing;

        select id
            into profile_id
            from rhnXccdfProfile
            where identifier = identifier_in and title = title_in;
    end if;

    return profile_id;
end;
$$ language plpgsql;
   07070100000C32000081B400000000000000000000000167AE111400000521000000000000000000000000000000000000006D00000000susemanager-schema/upgrade/susemanager-schema-3.1.15-to-susemanager-schema-3.1.16/119-create_pxt_session.sql  -- retrieved from ./1241042199/53fa26df463811901487b608eecc3f77ca7783a1/schema/spacewalk/oracle/procs/create_pxt_session.sql
--
-- Copyright (c) 2008--2015 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--

create or replace function
create_pxt_session(p_web_user_id in numeric, p_expires in numeric, p_value in varchar)
returns numeric as $$
declare
	l_id numeric;
begin
    l_id := nextval( 'pxt_id_seq' );

    insert into PXTSessions (id, value, expires, web_user_id)
        values (l_id, p_value, p_expires, p_web_user_id)
        on conflict do nothing;

    select id
        into strict l_id
        from PXTSessions
        where value = p_value and expires = p_expires and web_user_id = p_web_user_id;

	  return l_id;
end;
$$ language plpgsql;
   07070100000C33000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005200000000susemanager-schema/upgrade/susemanager-schema-3.1.16-to-susemanager-schema-3.1.17 07070100000C34000081B400000000000000000000000167AE111400000561000000000000000000000000000000000000007100000000susemanager-schema/upgrade/susemanager-schema-3.1.16-to-susemanager-schema-3.1.17/001-define-sle15-ostargets.sql  insert into suseOSTarget (id, os, target, channel_arch_id)
  select sequence_nextval('suse_ostarget_id_seq'), 'sle-15-x86_64', 'sle-15-x86_64', LOOKUP_CHANNEL_ARCH('channel-x86_64') from dual
   where not exists (select 1 from suseOSTarget where target = 'sle-15-x86_64');

insert into suseOSTarget (id, os, target, channel_arch_id)
  select sequence_nextval('suse_ostarget_id_seq'), 'sle-15-s390x', 'sle-15-s390x', LOOKUP_CHANNEL_ARCH('channel-s390x') from dual
   where not exists (select 1 from suseOSTarget where target = 'sle-15-s390x');

insert into suseOSTarget (id, os, target, channel_arch_id)
  select sequence_nextval('suse_ostarget_id_seq'), 'sle-15-ppc64le', 'sle-15-ppc64le', LOOKUP_CHANNEL_ARCH('channel-ppc64le') from dual
   where not exists (select 1 from suseOSTarget where target = 'sle-15-ppc64le');

insert into suseOSTarget (id, os, target, channel_arch_id)
  select sequence_nextval('suse_ostarget_id_seq'), 'sle-15-aarch64', 'sle-15-aarch64', LOOKUP_CHANNEL_ARCH('channel-aarch64') from dual
   where not exists (select 1 from suseOSTarget where target = 'sle-15-aarch64');

insert into suseOSTarget (id, os, target, channel_arch_id)
  select sequence_nextval('suse_ostarget_id_seq'), 'sle-12-aarch64', 'sle-12-aarch64', LOOKUP_CHANNEL_ARCH('channel-aarch64') from dual
   where not exists (select 1 from suseOSTarget where target = 'sle-12-aarch64');
   07070100000C35000081B400000000000000000000000167AE1114000000EE000000000000000000000000000000000000007300000000susemanager-schema/upgrade/susemanager-schema-3.1.16-to-susemanager-schema-3.1.17/003-add-sles15-KSInstallType.sql    insert into rhnKSInstallType (id, label, name)
(select sequence_nextval('rhn_ksinstalltype_id_seq'), 'sles15generic','SUSE Enterprise Linux 15' from dual
  where not exists (select 1 from rhnKSInstallType where label = 'sles15generic'));
  07070100000C36000081B400000000000000000000000167AE11140000029C000000000000000000000000000000000000008100000000susemanager-schema/upgrade/susemanager-schema-3.1.16-to-susemanager-schema-3.1.17/201-add-root_pdid-to-suseProductExtensions.sql  
DO $$
  BEGIN
    alter table suseProductExtension add root_pdid numeric CONSTRAINT suse_prdext_rootid_fk REFERENCES suseProducts (id) ON DELETE CASCADE;
    update suseProductExtension set root_pdid = base_pdid;
    alter table suseProductExtension ALTER COLUMN root_pdid SET NOT NULL;

    CREATE UNIQUE INDEX prdext_ber_id_uq
    ON suseProductExtension (base_pdid, ext_pdid, root_pdid);

    alter table suseProductExtension add recommended CHAR(1) DEFAULT ('N') NOT NULL CONSTRAINT suse_prdext_rec_ck CHECK (recommended in ('Y', 'N'));
  EXCEPTION
    WHEN duplicate_column THEN RAISE NOTICE 'column root_pdid already exists in suseProductExtension';
  END;
$$;
07070100000C37000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005200000000susemanager-schema/upgrade/susemanager-schema-3.1.17-to-susemanager-schema-3.1.18 07070100000C38000081B400000000000000000000000167AE111400000096000000000000000000000000000000000000007600000000susemanager-schema/upgrade/susemanager-schema-3.1.17-to-susemanager-schema-3.1.18/000-fix-suse_img_repodigest_idx.sql DROP INDEX suse_img_repodigest_idx;

CREATE UNIQUE INDEX suse_img_repodigest_idx
    ON suseImageRepoDigest(repo_digest, image_history_id)
    
    ;
  07070100000C39000081B400000000000000000000000167AE111400000168000000000000000000000000000000000000007700000000susemanager-schema/upgrade/susemanager-schema-3.1.17-to-susemanager-schema-3.1.18/001-fix-truncated-action-results.sql    
DO $$
  declare
    result_msg_data_type text;
  BEGIN
    SELECT data_type INTO result_msg_data_type
    FROM information_schema.columns
    WHERE table_name = 'rhnserveraction' and column_name = 'result_msg';

    IF (result_msg_data_type='character varying') THEN
      ALTER TABLE rhnserveraction ALTER COLUMN result_msg TYPE text;
    END IF;
  END;
$$;
07070100000C3A000081B400000000000000000000000167AE1114000006A6000000000000000000000000000000000000008B00000000susemanager-schema/upgrade/susemanager-schema-3.1.17-to-susemanager-schema-3.1.18/100-fix-inconsistent-config-state-channel-assignment.sql    -- Remove inconsistent config channel state revisions where config channel org is
-- not equal to staterevision org.
DELETE FROM suseStateRevisionConfigChannel scc WHERE
NOT EXISTS (SELECT 1
            FROM rhnConfigChannel cc, suseStateRevision sr, web_contact wc
            WHERE cc.id = scc.config_channel_id
            AND scc.state_revision_id = sr.id
            AND sr.creator_id = wc.id
            AND wc.org_id = cc.org_id);

DELETE from rhnServerConfigChannel sscc WHERE
NOT EXISTS (SELECT 1
            FROM rhnConfigChannel cc, rhnserver s
            WHERE cc.id = sscc.config_channel_id
            AND sscc.server_id = s.id
            AND s.org_id = cc.org_id);

-- Recalculate positions for entries after removing some of them on the previous step.
-- These SQL queries will keep the actual position ordering but ensuring there is no missing position.
UPDATE suseStateRevisionConfigChannel
SET position = (
    SELECT rank
    FROM (
        SELECT state_revision_id, config_channel_id, position, (row_number() OVER (PARTITION BY state_revision_id ORDER BY position ASC)) rank
        FROM suseStateRevisionConfigChannel scc
    ) ranking
    WHERE config_channel_id = suseStateRevisionConfigChannel.config_channel_id
    AND state_revision_id = suseStateRevisionConfigChannel.state_revision_id);


UPDATE rhnServerConfigChannel
SET position = (
    select rank
    from (
        SELECT server_id, config_channel_id, position, (row_number() OVER (PARTITION BY server_id ORDER BY position ASC)) rank
        FROM rhnServerConfigChannel sscc
    ) ranking
    WHERE config_channel_id = rhnServerConfigChannel.config_channel_id
    AND server_id = rhnServerConfigChannel.server_id);
  07070100000C3B000081B400000000000000000000000167AE111400000093000000000000000000000000000000000000007C00000000susemanager-schema/upgrade/susemanager-schema-3.1.17-to-susemanager-schema-3.1.18/101-run-refresh-custom-sls-files-task.sql   INSERT INTO rhnTaskQueue (org_id, task_name, task_data)
SELECT id, 'upgrade_satellite_refresh_custom_sls_files', 0
FROM web_customer
WHERE id = 1;
 07070100000C3C000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005100000000susemanager-schema/upgrade/susemanager-schema-3.1.17-to-susemanager-schema-3.2.0  07070100000C3D000081B400000000000000000000000167AE111400000000000000000000000000000000000000000000005A00000000susemanager-schema/upgrade/susemanager-schema-3.1.17-to-susemanager-schema-3.2.0/.gitkeep 07070100000C3E000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005100000000susemanager-schema/upgrade/susemanager-schema-3.1.18-to-susemanager-schema-3.2.0  07070100000C3F000081B400000000000000000000000167AE111400000000000000000000000000000000000000000000005A00000000susemanager-schema/upgrade/susemanager-schema-3.1.18-to-susemanager-schema-3.2.0/.gitkeep 07070100000C40000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005100000000susemanager-schema/upgrade/susemanager-schema-3.1.19-to-susemanager-schema-3.2.0  07070100000C41000081B400000000000000000000000167AE11140000005B000000000000000000000000000000000000005800000000susemanager-schema/upgrade/susemanager-schema-3.1.19-to-susemanager-schema-3.2.0/README   -- Schema upgrade scripts.
-- Intentionally left empty. Please leave this directory empty.
 07070100000C42000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005100000000susemanager-schema/upgrade/susemanager-schema-3.1.20-to-susemanager-schema-3.2.0  07070100000C43000081B400000000000000000000000167AE11140000005B000000000000000000000000000000000000005800000000susemanager-schema/upgrade/susemanager-schema-3.1.20-to-susemanager-schema-3.2.0/README   -- Schema upgrade scripts.
-- Intentionally left empty. Please leave this directory empty.
 07070100000C44000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005000000000susemanager-schema/upgrade/susemanager-schema-3.1.4-to-susemanager-schema-3.1.5   07070100000C45000081B400000000000000000000000167AE111400000514000000000000000000000000000000000000007300000000susemanager-schema/upgrade/susemanager-schema-3.1.4-to-susemanager-schema-3.1.5/001-scheduling-with-taskomatic.sql    --
-- Copyright (c) 2017 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

INSERT INTO rhnTaskoBunch (id, name, description, org_bunch)
    VALUES (sequence_nextval('rhn_tasko_bunch_id_seq'), 'minion-action-executor-bunch', 'Execute actions on Minions', null);

INSERT INTO rhnTaskoTask (id, name, class)
    VALUES (sequence_nextval('rhn_tasko_task_id_seq'), 'minion-action-executor', 'com.redhat.rhn.taskomatic.task.MinionActionExecutor');

INSERT INTO rhnTaskoTemplate (id, bunch_id, task_id, ordering, start_if)
    VALUES (sequence_nextval('rhn_tasko_template_id_seq'),
        (SELECT id FROM rhnTaskoBunch WHERE name='minion-action-executor-bunch'),
        (SELECT id FROM rhnTaskoTask WHERE name='minion-action-executor'),
        0,
        null);
07070100000C46000081B400000000000000000000000167AE111400000112000000000000000000000000000000000000007600000000susemanager-schema/upgrade/susemanager-schema-3.1.4-to-susemanager-schema-3.1.5/010-insert-credentials-store-type.sql insert into suseCredentialsType (id, label, name) (
  select sequence_nextval('suse_credtype_id_seq'), 'registrycreds', 'Registry'
    from dual
   where not exists (
           select 1
             from suseCredentialsType
            where label = 'registrycreds'
  )
);
  07070100000C47000081B400000000000000000000000167AE1114000005E7000000000000000000000000000000000000007200000000susemanager-schema/upgrade/susemanager-schema-3.1.4-to-susemanager-schema-3.1.5/011-suseImageInfo-checksum_id.sql drop view suseimageoverview;

alter table suseImageInfo add checksum_id NUMERIC
        CONSTRAINT suse_imginfo_chsum_fk
        REFERENCES rhnChecksum (id);

alter table suseImageInfo drop column checksum;

create or replace view
suseImageOverview
(
    org_id,
    image_id,
    image_name,
    image_version,
    checksum_id,
    modified,
    image_arch_name,
    action_id,
    profile_id,
    store_id,
    build_server_id,
    security_errata,
    bug_errata,
    enhancement_errata,
    outdated_packages,
    installed_packages
)
as
select
    i.org_id, i.id, i.name, i.version, i.checksum_id, i.modified,
    ( select name from rhnServerArch where id = i.image_arch_id),
    i.action_id, i.profile_id, i.store_id, i.build_server_id,
    ( select count(*) from rhnImageErrataTypeView ietv
      where
            ietv.image_id = i.id
        and ietv.errata_type = 'Security Advisory'),
    ( select count(*) from rhnImageErrataTypeView ietv
      where
            ietv.image_id = i.id
        and ietv.errata_type = 'Bug Fix Advisory'),
    ( select count(*) from rhnImageErrataTypeView ietv
      where
            ietv.image_id = i.id
        and ietv.errata_type = 'Product Enhancement Advisory'),
    ( select count(distinct p.name_id) from rhnPackage p, rhnImageNeededPackageCache inpc
      where
            inpc.image_id = i.id
        and p.id = inpc.package_id),
    (select count(*) from suseImageInfoPackage iip
     where
            iip.image_info_id = i.id)
from
    suseImageInfo i
;
 07070100000C48000081B400000000000000000000000167AE111400000040000000000000000000000000000000000000007300000000susemanager-schema/upgrade/susemanager-schema-3.1.4-to-susemanager-schema-3.1.5/012-fix-suseImageInfo-store_id.sql    
ALTER TABLE suseImageInfo ALTER COLUMN store_id DROP NOT NULL;
07070100000C49000081B400000000000000000000000167AE111400000430000000000000000000000000000000000000006900000000susemanager-schema/upgrade/susemanager-schema-3.1.4-to-susemanager-schema-3.1.5/013-fix-foreign-keys.sql  ALTER TABLE suseImageCustomDataValue DROP CONSTRAINT suse_icdv_prid_fk;
ALTER TABLE suseImageCustomDataValue ADD CONSTRAINT  suse_icdv_prid_fk FOREIGN KEY (image_info_id) REFERENCES suseImageInfo (id) ON DELETE CASCADE;

ALTER TABLE suseImageCustomDataValue DROP CONSTRAINT suse_icdv_kid_fk;
ALTER TABLE suseImageCustomDataValue ADD CONSTRAINT  suse_icdv_kid_fk FOREIGN KEY (key_id) REFERENCES rhnCustomDataKey (id) ON DELETE CASCADE;

ALTER TABLE suseProfileCustomDataValue DROP CONSTRAINT suse_pcdv_prid_fk;
ALTER TABLE suseProfileCustomDataValue ADD CONSTRAINT  suse_pcdv_prid_fk FOREIGN KEY (profile_id) REFERENCES suseImageProfile (profile_id) ON DELETE CASCADE;

ALTER TABLE suseProfileCustomDataValue DROP CONSTRAINT suse_pcdv_kid_fk;
ALTER TABLE suseProfileCustomDataValue ADD CONSTRAINT  suse_pcdv_kid_fk FOREIGN KEY (key_id) REFERENCES rhnCustomDataKey (id) ON DELETE CASCADE;

ALTER TABLE suseImageInfo DROP CONSTRAINT rhn_imginfo_said_fk;
ALTER TABLE suseImageInfo ADD CONSTRAINT suse_imginfo_said_fk FOREIGN KEY (image_arch_id) REFERENCES rhnServerArch (id);
07070100000C4A000081B400000000000000000000000167AE111400000587000000000000000000000000000000000000006C00000000susemanager-schema/upgrade/susemanager-schema-3.1.4-to-susemanager-schema-3.1.5/014-suseCVEImageChannel.sql   --
-- Copyright (c) 2017 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

CREATE TABLE suseCVEImageChannel
(
    image_info_id    NUMERIC NOT NULL
                     CONSTRAINT suse_cveimg_iid_fk
                         REFERENCES suseImageInfo (id)
                         ON DELETE CASCADE,
    channel_id   NUMERIC NOT NULL
                     CONSTRAINT suse_cveimg_cid_fk
                         REFERENCES rhnChannel (id)
                         ON DELETE CASCADE,
    channel_rank NUMERIC NOT NULL,
    created   TIMESTAMPTZ
                  DEFAULT (current_timestamp) NOT NULL,
    modified  TIMESTAMPTZ
                  DEFAULT (current_timestamp) NOT NULL
)

;

CREATE UNIQUE INDEX suse_cveimg_iid_cid_uq
    ON suseCVEImageChannel (image_info_id, channel_id)
    ;

CREATE INDEX suse_cveimg_cid_idx
    ON suseCVEImageChannel (channel_id)
    
    ;

 07070100000C4B000081B400000000000000000000000167AE11140000007E000000000000000000000000000000000000006E00000000susemanager-schema/upgrade/susemanager-schema-3.1.4-to-susemanager-schema-3.1.5/015-rename-tag-to-version.sql ALTER TABLE rhnActionImageBuild RENAME COLUMN tag to version;
ALTER TABLE rhnActionImageInspect RENAME COLUMN tag to version;
  07070100000C4C000081B400000000000000000000000167AE111400000082000000000000000000000000000000000000007200000000susemanager-schema/upgrade/susemanager-schema-3.1.4-to-susemanager-schema-3.1.5/507-drop-monitoring-leftovers.sql DROP TABLE if exists rhn_config_parameter;
DROP TABLE if exists rhn_config_group;
DROP TABLE if exists rhn_config_security_type;

  07070100000C4D000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005000000000susemanager-schema/upgrade/susemanager-schema-3.1.5-to-susemanager-schema-3.1.6   07070100000C4E000081B400000000000000000000000167AE1114000005D1000000000000000000000000000000000000006A00000000susemanager-schema/upgrade/susemanager-schema-3.1.5-to-susemanager-schema-3.1.6/008-rhnSet-uniqueness.sql --
-- Copyright (c) 2017 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

SELECT * INTO TEMPORARY rhnSet_all from rhnSet;
DELETE FROM rhnSet;
INSERT INTO rhnSet SELECT DISTINCT * FROM rhnSet_all;

ALTER TABLE rhnSet DROP CONSTRAINT rhn_set_user_label_elem_unq;

CREATE UNIQUE INDEX rhn_set_user_label_elem_unq
    ON rhnSet (user_id, label, element)
    WHERE element_two IS NULL AND element_three IS NULL;

CREATE UNIQUE INDEX rhn_set_user_label_elem_elem2_unq
    ON rhnSet (user_id, label, element, element_two)
    WHERE element_two IS NOT NULL AND element_three IS NULL;

CREATE UNIQUE INDEX rhn_set_user_label_elem_elem3_unq
    ON rhnSet (user_id, label, element, element_three)
    WHERE element_two IS NULL AND element_three IS NOT NULL;

CREATE UNIQUE INDEX rhn_set_user_label_elem_elem2_elem3_unq
    ON rhnSet (user_id, label, element, element_two, element_three)
    WHERE element_two IS NOT NULL AND element_three IS NOT NULL;
   07070100000C4F000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005000000000susemanager-schema/upgrade/susemanager-schema-3.1.6-to-susemanager-schema-3.1.7   07070100000C50000081B400000000000000000000000167AE111400002FD6000000000000000000000000000000000000006D00000000susemanager-schema/upgrade/susemanager-schema-3.1.6-to-susemanager-schema-3.1.7/001-rhn_entitlements.pkb.sql  --
-- Copyright (c) 2008--2015 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

-- create schema rhn_entitlements;

-- setup search_path so that these functions are created in appropriate schema.
update pg_settings set setting = 'rhn_entitlements,' || setting where name = 'search_path';

   create or replace function find_compatible_sg (
      server_id_in in numeric,
      type_label_in in varchar
   )
   returns numeric
as $$
    declare
      servergroups cursor for
         select sg.id
           from rhnServerGroupType             sgt,
                rhnServerGroup                 sg,
                rhnServer                     s,
                rhnServerServerGroupArchCompat ssgac
          where s.id = server_id_in
            and s.org_id = sg.org_id
            and sgt.label = type_label_in
            and sg.group_type = sgt.id
            and ssgac.server_group_type = sgt.id
            and ssgac.server_arch_id = s.server_arch_id
            and not exists (
                     select 1
                      from rhnServerGroupMembers sgm
                     where sgm.server_group_id = sg.id
                       and sgm.server_id = s.id);


   begin
      for servergroup in servergroups loop
         return servergroup.id;
      end loop;

      --no servergroup found
      return NULL;
   end$$
language plpgsql;


    create or replace function entitlement_grants_service (
        entitlement_in in varchar,
        service_level_in in varchar
    ) returns numeric
as $$
    begin
        if service_level_in = 'management' then
            if entitlement_in = 'enterprise_entitled' or entitlement_in = 'salt_entitled' then
                return 1;
            else
                return 0;
            end if;
        elsif service_level_in = 'updates' then
            return 1;
        else
            return 0;
        end if;
    end$$
language plpgsql;

   create or replace function can_entitle_server (
      server_id_in   in numeric,
      type_label_in  in varchar
   )
   returns numeric
as $$
    declare
      addon_servergroups cursor (base_label_in varchar,
                                 addon_label_in varchar) for
         select
            addon_id
         from
            rhnSGTypeBaseAddonCompat
         where base_id = lookup_sg_type (base_label_in)
           and addon_id = lookup_sg_type (addon_label_in);

      previous_ent        varchar[];
      is_base_in          char   := 'N';
      is_base_current     char   := 'N';
      i                   numeric := 0;
      sgid                numeric := 0;

   begin

      previous_ent := rhn_entitlements.get_server_entitlement(server_id_in);
      RAISE NOTICE 'can_entitle_server - % - % prev ents: %', server_id_in, type_label_in, previous_ent;

      select distinct is_base
      into is_base_in
      from rhnServerGroupType
      where label = type_label_in;

      if array_upper(previous_ent, 1) is null or array_upper(previous_ent, 1) = 0 then
         if is_base_in = 'Y' then
            sgid := rhn_entitlements.find_compatible_sg (server_id_in, type_label_in);
            if sgid is not null then
              -- rhn_server.insert_into_servergroup (server_id_in, sgid);
              return 1;
            else
              -- rhn_exception.raise_exception ('invalid_base_entitlement');
              RAISE NOTICE 'invalid_base_entitlement - no compatible server group';
              return 0;
            end if;
         else
            -- rhn_exception.raise_exception ('invalid_base_entitlement');
            RAISE NOTICE 'invalid_base_entitlement - not a base entitlement';
            return 0;
         end if;

      -- there are previous ents, first make sure we're not trying to entitle a base ent
      elsif is_base_in = 'Y' then
         -- rhn_exception.raise_exception ('invalid_addon_entitlement');
         RAISE NOTICE 'invalid_addon_entitlement - found another base';
         return 0;

      -- it must be an addon, so proceed with the entitlement
      else

         -- find the servers base ent
         is_base_current := 'N';
         i := 0;
         while is_base_current = 'N' and i < array_upper(previous_ent, 1)
         loop
            i := i + 1;
            select is_base
            into is_base_current
            from rhnServerGroupType
            where label = previous_ent[i];
         end loop;

         -- never found a base ent, that would be strange
         if is_base_current  = 'N' then
            -- rhn_exception.raise_exception ('invalid_base_entitlement');
            RAISE NOTICE 'invalid_base_entitlement - never found a base';
            return 0;
         end if;

         -- this for loop verifies the validity of the addon path
         for addon_servergroup in addon_servergroups  (previous_ent[i], type_label_in) loop
            -- find an appropriate sgid for the addon and entitle the server
            sgid := rhn_entitlements.find_compatible_sg (server_id_in, type_label_in);
            if sgid is not null then
               -- rhn_server.insert_into_servergroup (server_id_in, sgid);
               return 1;
            else
               -- rhn_exception.raise_exception ('invalid_addon_entitlement');
               RAISE NOTICE 'invalid_addon_entitlement - no server group found';
               return 0;
            end if;
         end loop;

      end if;
      RAISE NOTICE 'final error';
      return 0;

   end$$
language plpgsql;

   create or replace function can_switch_base (
      server_id_in   in    integer,
      type_label_in  in    varchar
   )
   returns numeric
as $$
   declare
      type_label_in_is_base   char(1);
      sgid                    numeric;

   begin

       select is_base into type_label_in_is_base
       from rhnServerGroupType
       where label = type_label_in;

       if not found then
          perform rhn_exception.raise_exception ( 'invalid_entitlement' );
       end if;

      if type_label_in_is_base = 'N' then
         perform rhn_exception.raise_exception ( 'invalid_entitlement' );
      else
         sgid := rhn_entitlements.find_compatible_sg ( server_id_in,
                                                       type_label_in );
         if sgid is not null then
           return 1;
         else
           return 0;
         end if;
      end if;

   end$$
language plpgsql;

    create or replace function entitle_server (
        server_id_in in numeric,
        type_label_in in varchar
    ) returns void
as $$
    declare
      sgid  numeric := 0;

    begin

      if rhn_entitlements.can_entitle_server(server_id_in,
                                             type_label_in) = 1 then
         sgid := rhn_entitlements.find_compatible_sg (server_id_in,
                                                      type_label_in);
         if sgid is not null then
            insert into rhnServerHistory ( id, server_id, summary, details )
            values ( nextval('rhn_event_id_seq'), server_id_in,
                     'added system entitlement ',
                      case type_label_in
                       when 'enterprise_entitled' then 'Management'
                       when 'bootstrap_entitled' then 'Bootstrap'
                       when 'salt_entitled' then 'Salt'
                       when 'foreign_entitled' then 'Foreign'
                       when 'virtualization_host' then 'Virtualization'
                      end  );

            perform rhn_server.insert_into_servergroup (server_id_in, sgid);

         else
            perform rhn_exception.raise_exception ('no_available_server_group');
         end if;
      else
         perform rhn_exception.raise_exception ('invalid_entitlement');
      end if;
   end$$
language plpgsql;

    create or replace function remove_server_entitlement (
        server_id_in in numeric,
        type_label_in in varchar
    ) returns void
as $$
    declare
      group_id numeric;
      type_is_base char;
    begin

        select  sg.id, sgt.is_base
        into group_id, type_is_base
        from    rhnServerGroupType sgt,
            rhnServerGroup sg,
                rhnServerGroupMembers sgm,
                rhnServer s
        where   s.id = server_id_in
            and s.id = sgm.server_id
            and sgm.server_group_id = sg.id
            and sg.org_id = s.org_id
            and sgt.label = type_label_in
            and sgt.id = sg.group_type;

        if not found then
          perform rhn_exception.raise_exception('invalid_server_group_member');
        end if;

      if ( type_is_base = 'Y' ) then
         -- unentitle_server should handle everything, don't really need to do anything else special here
         perform rhn_entitlements.unentitle_server ( server_id_in );
      else

         insert into rhnServerHistory ( id, server_id, summary, details )
         values ( nextval('rhn_event_id_seq'), server_id_in,
                  'removed system entitlement ',
                   case type_label_in
                    when 'enterprise_entitled' then 'Management'
                    when 'bootstrap_entitled' then 'Bootstrap'
                    when 'salt_entitled' then 'Salt'
                    when 'foreign_entitled' then 'Foreign'
                    when 'virtualization_host' then 'Virtualization'
                   end  );

         perform rhn_server.delete_from_servergroup(server_id_in, group_id);

      end if;

    end$$
language plpgsql;

    create or replace function unentitle_server (
        server_id_in in numeric
    ) returns void
as $$
    declare
      servergroups cursor for
         select distinct sgt.label, sg.id server_group_id
         from  rhnServerGroupType sgt,
               rhnServerGroup sg,
               rhnServer s,
               rhnServerGroupMembers sgm
         where s.id = server_id_in
            and s.org_id = sg.org_id
            and sg.group_type = sgt.id
            and sgm.server_group_id = sg.id
            and sgm.server_id = s.id;

   begin

      for servergroup in servergroups loop

         insert into rhnServerHistory ( id, server_id, summary, details )
         values ( nextval('rhn_event_id_seq'), server_id_in,
                  'removed system entitlement ',
                   case servergroup.label
                    when 'enterprise_entitled' then 'Management'
                    when 'bootstrap_entitled' then 'Bootstrap'
                    when 'salt_entitled' then 'Salt'
                    when 'foreign_entitled' then 'Foreign'
                    when 'virtualization_host' then 'Virtualization'
                   end  );

         perform rhn_server.delete_from_servergroup(server_id_in,
                                            servergroup.server_group_id );
      end loop;

   end$$
language plpgsql;


    create or replace function get_server_entitlement (
        server_id_in in numeric
    ) returns varchar[]
as $$
    declare
        server_groups cursor for
            select  sgt.label
            from    rhnServerGroupType      sgt,
                    rhnServerGroup          sg,
                    rhnServerGroupMembers   sgm
            where   1=1
                and sgm.server_id = server_id_in
                and sg.id = sgm.server_group_id
                and sgt.id = sg.group_type;

         ent_array varchar[];

    begin

      ent_array := '{}';

      for sg in server_groups loop
         ent_array := ent_array || sg.label;
      end loop;

      return ent_array;

    end$$
language plpgsql;

-- restore the original setting
update pg_settings set setting = overlay( setting placing '' from 1 for (length('rhn_entitlements')+1) ) where name = 'search_path';
  07070100000C51000081B400000000000000000000000167AE111400000295000000000000000000000000000000000000007100000000susemanager-schema/upgrade/susemanager-schema-3.1.6-to-susemanager-schema-3.1.7/002-suseProducts-add-columns.sql  -- Adding the column 'channel_family_id' to suseProducts
-- Adding the column 'base' to suseProducts

DO $$
    BEGIN
        BEGIN
            ALTER TABLE suseProducts ADD channel_family_id NUMERIC CONSTRAINT suse_products_cfid_fk REFERENCES rhnChannelFamily (id) ON DELETE SET NULL;
        EXCEPTION
            WHEN duplicate_column THEN RAISE NOTICE 'column channel_family_id already exists in suseProducts';
        END;
        BEGIN
            ALTER TABLE suseProducts ADD base CHAR(1) DEFAULT ('N') NOT NULL;
        EXCEPTION
            WHEN duplicate_column THEN RAISE NOTICE 'column base already exists in suseProducts';
        END;
    END;
$$;
   07070100000C52000081B400000000000000000000000167AE111400000453000000000000000000000000000000000000006700000000susemanager-schema/upgrade/susemanager-schema-3.1.6-to-susemanager-schema-3.1.7/009-rhnErrata-uniq.sql    --
-- Copyright (c) 2017 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

DROP INDEX rhn_errata_advisory_name_uq;
DROP INDEX rhn_errata_advisory_uq;

CREATE UNIQUE INDEX rhn_errata_advname_uq
    ON rhnErrata (advisory_name)
 WHERE org_id IS NULL;

CREATE UNIQUE INDEX rhn_errata_advname_org_uq
    ON rhnErrata (advisory_name, org_id)
 WHERE org_id IS NOT NULL;

CREATE UNIQUE INDEX rhn_errata_adv_uq
    ON rhnErrata (advisory)
 WHERE org_id IS NULL;

CREATE UNIQUE INDEX rhn_errata_adv_org_uq
    ON rhnErrata (advisory, org_id)
 WHERE org_id IS NOT NULL;
 07070100000C53000081B400000000000000000000000167AE11140000059D000000000000000000000000000000000000007100000000susemanager-schema/upgrade/susemanager-schema-3.1.6-to-susemanager-schema-3.1.7/010-remove-misaligned-errata.sql  --
-- Copyright (c) 2017 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

DELETE FROM rhnchannelerrata
      WHERE (channel_id, errata_id) in (SELECT ce.channel_id, ce.errata_id
                                          FROM rhnchannelerrata ce
                                          JOIN rhnchannel c ON c.id = ce.channel_id
                                          JOIN rhnerrata e ON e.id = ce.errata_id
                                         WHERE e.org_id <> c.org_id);

DELETE FROM rhnerratapackage
      WHERE (errata_id, package_id) in (SELECT pe.errata_id, pe.package_id
                                          FROM rhnerratapackage pe
                                          JOIN rhnpackage p ON p.id = pe.package_id
                                          JOIN rhnerrata e ON e.id = pe.errata_id
                                         WHERE e.org_id <> p.org_id);
   07070100000C54000081B400000000000000000000000167AE1114000000DD000000000000000000000000000000000000007700000000susemanager-schema/upgrade/susemanager-schema-3.1.6-to-susemanager-schema-3.1.7/011-rhncontentsourcefilter-cascade.sql    alter table rhnContentSourceFilter drop constraint rhn_csf_source_fk;

alter table rhnContentSourceFilter add constraint rhn_csf_source_fk
  foreign key (source_id)
  references rhnContentSource (id)
  on delete cascade;
   07070100000C55000081B400000000000000000000000167AE111400004DE0000000000000000000000000000000000000006E00000000susemanager-schema/upgrade/susemanager-schema-3.1.6-to-susemanager-schema-3.1.7/012-rhnConfigInfo_indexes.sql --
-- Copyright (c) 2017 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--
-- We have to fix rhnConfigInfo in the presence of dups (and the rhnCOnfigRevisions that
-- might be pointing at them)
-- Clean up table, and then create corrected postgresql indicies to prevent dups
-- in the future
--
-- FOUR CASES:
--  Cfg-file is a FILE - username/groupname/filemode are NOT NULL, symlink_target_filename_id IS NULL, AND:
--    selinux_ctx IS NULL
--    selinux_ctx IS NOT NULL
--  Cfg-file is a LINK - username/groupname/filemode ARE ALL NULL, AND symlink_target_filename_id is NOT NULL, AND:
--    selinux_ctx NULL
--    selinux_ctx IS NOT NULL
--
-- Check all FOUR - if ANY show multiple rows, table is broken :(
--
create or replace function
is_cfginfo_broken() returns boolean
as
$$
declare
    throwaway       numeric;
    bad_data_exists boolean := false;
begin
    -- (1) Count username, groupname, filemode combinations where
    --     selinux_ctx is null
    select 1 into throwaway
    from (
        select username, groupname, filemode, count(id) as num
          from rhnConfigInfo
         where username is not null and groupname is not null and filemode is not null
           and symlink_target_filename_id is null and selinux_ctx is null
         group by username, groupname, filemode
    ) x
    where x.num > 1;

    if found then
        raise info 'DUP FILE INFO found, selinux NULL';
        bad_data_exists := true;
    end if;

    -- (2) Count username, groupname, filemode, selinux_ctx combinations where
    --     selinux is not null
    select 1 into throwaway
    from (
        select username, groupname, filemode, selinux_ctx, count(id) as num
          from rhnConfigInfo
         where username is not null and groupname is not null and filemode is not null
           and symlink_target_filename_id is null and selinux_ctx is not null
         group by username, groupname, filemode, selinux_ctx
    ) x
    where x.num > 1;

    if found then
        raise info 'DUP FILE INFO found, selinux is NOT NULL';
        bad_data_exists := true;
    end if;

    -- (3) Count symlink_target_filename_id combinations
    --     where username, groupname, filemode are null and selinux_ctx is null
    select 1 into throwaway
    from (
        select symlink_target_filename_id, count(id) as num
          from rhnConfigInfo
         where symlink_target_filename_id is not null
           and username is null and groupname is null and filemode is null
           and selinux_ctx is null
         group by symlink_target_filename_id
    ) x
    where x.num > 1;

    if found then
        raise info 'DUP LINK INFO found, selinux IS NULL';
        bad_data_exists := true;
    end if;

    -- (4) Count symlink_target_filename_id combinations
    --     where username, groupname, filemode are null and selinux_ctx IS NOT null
    select 1 into throwaway
    from (
        select symlink_target_filename_id, count(id) as num
          from rhnConfigInfo
         where symlink_target_filename_id is not null
           and username is null and groupname is null and filemode is null
           and selinux_ctx is not null
         group by symlink_target_filename_id
    ) x
    where x.num > 1;

    if found then
        raise info 'DUP LINK INFO found, selinux NOT NULL';
        bad_data_exists := true;
    end if;

    return bad_data_exists;
end
$$
language plpgsql;

--
-- Fix rhnConfigRevision pointers into rhnConfigInfo where there are dups
--  Cfg-file is a FILE - username/groupname/filemode are NOT NULL, AND symlink_target_filename_id NULL, AND:
--    fix_cfgrev_files_SELINUX_NULL     : selinux_ctx NULL
--    fix_cfgrev_files_SELINUX_NOT_NULL : selinux_ctx NOT NULL
--  Cfg-file is a LINK - username/groupname/filemode ARE ALL NULL, AND symlink_target_filename_id is NOT NULL, AND:
--    fix_cfgrev_links_SELINUX_NULL     : selinux_ctx NULL
--    fix_cfgrev_links_SELINUX_NOT_NULL : selinux_ctx NOT NULL
--
-- (The following is Ugly Repetitive Code - but it's one-use-only and gets the job done in the most obvious way possible)
--
create or replace function
fix_cfgrev_files_SELINUX_NULL() returns void
as
$$
declare
    d record;
    first_time      boolean               := true;
    good_cfginfo_id numeric               := -1;
    good_username   character varying(32) := '';
    good_groupname  character varying(32) := '';
    good_filemode   numeric               := -1;
begin
    for d in
        -- Find the cardinality of the IDs of the dups
        -- We will remember the most-used rhnConfigInfo.id, and repoint rhnConfigRevisions at it
        SELECT z.id as dup_cfginfo_id, z.username, z.groupname, z.filemode, count(crev.id) as num_rhnConfigRevision_using
        from (
            -- Find the IDs of the dups
            SELECT ci.id, ci.username, ci.groupname, ci.filemode
              from rhnConfigInfo ci
                   inner join (
			-- Find just the ones that are dups
			SELECT x.username, x.groupname, x.filemode, x.num
			from (
			    -- Count username,groupname,filemode combinations where symlink_target_filename_id and selinux_ctx are null
			    select username, groupname, filemode, count(id) as num
			      from rhnConfigInfo
			     where symlink_target_filename_id is null and selinux_ctx is null
			     group by username, groupname, filemode
			     ) x
			where x.num > 1
		    ) y on y.username = ci.username and y.groupname = ci.groupname and y.filemode = ci.filemode
             where 1=1
               and ci.symlink_target_filename_id is null and ci.selinux_ctx is null
             order by username, groupname, filemode, id
        ) z
        left outer join rhnConfigRevision crev on crev.config_info_id = z.id
        group by z.id, z.username, z.groupname, z.filemode
        order by z.username, z.groupname, z.filemode, count(crev.id) desc, z.id
    loop
        -- First time in, or when we move to a new kind-of dup, remember that one
        if first_time or (d.username <> good_username or d.groupname <> good_groupname or d.filemode <> good_filemode)
        then
            first_time := false;
            -- Remember the 'good values' so we can tell when we've moved to a new set in the dataresult
            good_cfginfo_id := d.dup_cfginfo_id;
            good_username   := d.username;
            good_groupname  := d.groupname;
            good_filemode   := d.filemode;
        -- we have seen this one before - repoint users at 'good' and remove this one
        else
            if d.num_rhnconfigrevision_using > 0
            then
                raise info '...REPOINTING RECORDS, rhnConfigInfo = %',d.dup_cfginfo_id;
                UPDATE rhnConfigRevision
                   set config_info_id = good_cfginfo_id
                 where config_info_id = d.dup_cfginfo_id;
            end if;
            DELETE from rhnConfigInfo ci
             where 1=1
               and ci.username = good_username
               and ci.groupname = good_groupname
               and ci.filemode = good_filemode
               and ci.selinux_ctx is null
               and ci.id <> good_cfginfo_id;
        end if;
    end loop;
end
$$
language plpgsql;

create or replace function
fix_cfgrev_files_SELINUX_NOT_NULL() returns void
as
$$
declare
    d record;
    first_time       boolean               := true;
    good_cfginfo_id  numeric               := -1;
    good_username    character varying(32) := '';
    good_groupname   character varying(32) := '';
    good_selinux_ctx character varying(64) := '';
    good_filemode    numeric               := -1;
begin
    for d in
        -- Find the cardinality of the IDs of the dups
        -- We will remember the most-used rhnConfigInfo.id, and repoint rhnConfigRevisions at it
        SELECT z.id as dup_cfginfo_id, z.username, z.groupname, z.filemode, z.selinux_ctx, count(crev.id) as num_rhnConfigRevision_using
        from (
            -- Find the IDs of the dups
            SELECT ci.id, ci.username, ci.groupname, ci.filemode, ci.selinux_ctx
              from rhnConfigInfo ci
                   inner join (
			-- Find just the ones that are dups
			SELECT x.username, x.groupname, x.filemode, x.selinux_ctx, x.num
			from (
			    -- Count username,groupname,filemode combinations where symlink_target_filename_id and selinux_ctx are null
			    select username, groupname, filemode, selinux_ctx, count(id) as num
			      from rhnConfigInfo
			     where symlink_target_filename_id is null and selinux_ctx is not null
			     group by username, groupname, filemode, selinux_ctx
			     ) x
			where x.num > 1
		    ) y on y.username = ci.username and y.groupname = ci.groupname and y.filemode = ci.filemode and y.selinux_ctx = ci.selinux_ctx
             where 1=1
               and ci.symlink_target_filename_id is null and ci.selinux_ctx is not null
             order by username, groupname, filemode, selinux_ctx, id
        ) z
        left outer join rhnConfigRevision crev on crev.config_info_id = z.id
        group by z.id, z.username, z.groupname, z.filemode, z.selinux_ctx
        order by z.username, z.groupname, z.filemode, z.selinux_ctx, count(crev.id) desc, z.id
    loop
        -- First time in, or when we move to a new kind-of dup, remember that one
        if first_time or (d.username <> good_username or d.groupname <> good_groupname or d.filemode <> good_filemode)
        then
            first_time := false;
            -- Remember the 'good values' so we can tell when we've moved to a new set in the dataresult
            good_cfginfo_id  := d.dup_cfginfo_id;
            good_username    := d.username;
            good_groupname   := d.groupname;
            good_filemode    := d.filemode;
            good_selinux_ctx := d.selinux_ctx;
        -- we have seen this one before - repoint users at 'good' and remove this one
        else
            if d.num_rhnconfigrevision_using > 0
            then
                raise info '...REPOINTING RECORDS, rhnConfigInfo = %',d.dup_cfginfo_id;
                UPDATE rhnConfigRevision
                   set config_info_id = good_cfginfo_id
                 where config_info_id = d.dup_cfginfo_id;
            end if;
            DELETE from rhnConfigInfo ci
             where 1=1
               and ci.username = good_username
               and ci.groupname = good_groupname
               and ci.filemode = good_filemode
               and ci.selinux_ctx = good_selinux_ctx
               and ci.id <> good_cfginfo_id;
        end if;
    end loop;
end
$$
language plpgsql;

create or replace function
fix_cfgrev_links_SELINUX_NOT_NULL() returns void
as
$$
declare
    d record;
    first_time                      boolean               := true;
    good_cfginfo_id                 numeric               := -1;
    good_symlink_target_filename_id numeric               := -1;
    good_selinux_ctx                character varying(64) := null;
begin
    for d in
        -- Find the cardinality of the IDs of the dups
        -- We will remember the most-used rhnConfigInfo.id, and repoint rhnConfigRevisions at it
        SELECT z.id as dup_cfginfo_id, z.symlink_target_filename_id, z.selinux_ctx, count(crev.id) as num_rhnConfigRevision_using
        from (
            -- Find the IDs of the dups
            SELECT ci.id, ci.symlink_target_filename_id, ci.selinux_ctx
              from rhnConfigInfo ci
                   inner join (
			-- Find just the ones that are dups
			SELECT x.symlink_target_filename_id, x.selinux_ctx, x.num
			from (
			    -- Count where symlink_target_filename_id is not null and selinux_ctx is not null
			    select symlink_target_filename_id, selinux_ctx, count(id) as num
			      from rhnConfigInfo
			     where username is null
                               and groupname is null
                               and filemode is null
                               and symlink_target_filename_id is not null
                               and selinux_ctx is not null
			     group by symlink_target_filename_id, selinux_ctx
			     ) x
			where x.num > 1
		    ) y on y.symlink_target_filename_id = ci.symlink_target_filename_id and y.selinux_ctx = ci.selinux_ctx
             where 1=1
               and ci.symlink_target_filename_id is not null and ci.selinux_ctx is not null
             order by symlink_target_filename_id, selinux_ctx, id
        ) z
        left outer join rhnConfigRevision crev on crev.config_info_id = z.id
        group by z.id, z.symlink_target_filename_id, z.selinux_ctx
        order by z.symlink_target_filename_id, z.selinux_ctx, count(crev.id) desc, z.id
    loop
        -- First time in, or when we move to a new kind-of dup, remember that one
        if first_time or (d.symlink_target_filename_id <> good_symlink_target_filename_id or d.selinux_ctx <> good_selinux_ctx)
        then
            first_time := false;
            -- Remember the 'good values' so we can tell when we've moved to a new set in the dataresult
            good_cfginfo_id                 := d.dup_cfginfo_id;
            good_symlink_target_filename_id := d.symlink_target_filename_id;
            good_selinux_ctx                := d.selinux_ctx;
        -- we have seen this one before - repoint users at 'good' and remove this one
        else
            if d.num_rhnconfigrevision_using > 0
            then
                raise info '...REPOINTING RECORDS, rhnConfigInfo = %',d.dup_cfginfo_id;
                UPDATE rhnConfigRevision
                   set config_info_id = good_cfginfo_id
                 where config_info_id = d.dup_cfginfo_id;
            end if;
            DELETE from rhnConfigInfo ci
             where 1=1
               and ci.symlink_target_filename_id = good_symlink_target_filename_id
               and ci.selinux_ctx                = good_selinux_ctx
               and ci.id <> good_cfginfo_id;
        end if;
    end loop;
end
$$
language plpgsql;

create or replace function
fix_cfgrev_links_SELINUX_NULL() returns void
as
$$
declare
    d record;
    first_time      boolean                 := true;
    good_cfginfo_id numeric                 := -1;
    good_symlink_target_filename_id numeric := -1;
begin
    raise info 'ENTERING fix_cfgrev_links_SELINUX_NULL';
    for d in
        -- Find the cardinality of the IDs of the dups
        -- We will remember the most-used rhnConfigInfo.id, and repoint rhnConfigRevisions at it
        SELECT z.id as dup_cfginfo_id, z.symlink_target_filename_id, count(crev.id) as num_rhnConfigRevision_using
        from (
            -- Find the IDs of the dups
            SELECT ci.id, ci.symlink_target_filename_id
              from rhnConfigInfo ci
                   inner join (
			-- Find just the ones that are dups
			SELECT x.symlink_target_filename_id, x.num
			from (
			    -- Count where symlink_target_filename_id is not null and selinux_ctx is null
			    select symlink_target_filename_id, count(id) as num
			      from rhnConfigInfo
			     where username is null
                               and groupname is null
                               and filemode is null
                               and symlink_target_filename_id is not null
                               and selinux_ctx is null
			     group by symlink_target_filename_id
			     ) x
			where x.num > 1
		    ) y on y.symlink_target_filename_id = ci.symlink_target_filename_id
             where 1=1
               and ci.symlink_target_filename_id is not null and ci.selinux_ctx is null
             order by symlink_target_filename_id, id
        ) z
        left outer join rhnConfigRevision crev on crev.config_info_id = z.id
        group by z.id, z.symlink_target_filename_id
        order by z.symlink_target_filename_id, count(crev.id) desc, z.id
    loop
        -- First time in, or when we move to a new kind-of dup, remember that one
        if first_time or (d.symlink_target_filename_id <> good_symlink_target_filename_id)
        then
            raise info '...NEW GOOD rhnConfigInfo = %',d.dup_cfginfo_id;
            first_time := false;
            -- Remember the 'good values' so we can tell when we've moved to a new set in the dataresult
            good_cfginfo_id                 := d.dup_cfginfo_id;
            good_symlink_target_filename_id := d.symlink_target_filename_id;
        -- we have seen this one before - repoint users at 'good' and remove this one
        else
            if d.num_rhnconfigrevision_using > 0
            then
                raise info '...REPOINTING RECORDS, rhnConfigInfo = %',d.dup_cfginfo_id;
                UPDATE rhnConfigRevision
                   set config_info_id = good_cfginfo_id
                 where config_info_id = d.dup_cfginfo_id;
            end if;
            DELETE from rhnConfigInfo ci
             where 1=1
               and ci.symlink_target_filename_id = good_symlink_target_filename_id
               and ci.selinux_ctx                is null
               and ci.id <> good_cfginfo_id;
        end if;
    end loop;
    raise info 'EXITING fix_cfgrev_links_SELINUX_NULL';
end
$$
language plpgsql;

create or replace function
fix_cfgrev_files() returns void
as
$$
declare
 throwaway character varying(32);
 is_broken boolean := false;
begin
  select is_cfginfo_broken() into is_broken;
  if is_broken then
    select fix_cfgrev_files_SELINUX_NOT_NULL() into throwaway;
    select fix_cfgrev_files_SELINUX_NULL() into throwaway;
    select fix_cfgrev_links_SELINUX_NOT_NULL() into throwaway;
    select fix_cfgrev_links_SELINUX_NULL() into throwaway;
  end if;
end
$$
language plpgsql;

-- FOUR CASES:
-- u|g|f-not  link-null selinux-null
-- u|g|f-not  link-null selinux-not
-- u|g|f null link-not  selinux-not
-- u|g|f null link-not  selinux-null

-- Fix potential dups
select fix_cfgrev_files();

-- Drop no-longer-necessary functions
drop function if exists fix_cfgrev_files();
drop function if exists is_cfginfo_broken();
drop function if exists fix_cfgrev_files_SELINUX_NOT_NULL();
drop function if exists fix_cfgrev_files_SELINUX_NULL();
drop function if exists fix_cfgrev_links_SELINUX_NOT_NULL();
drop function if exists fix_cfgrev_links_SELINUX_NULL();

-- Make adding new indices idempotent
drop index if exists rhn_confinfo_ugf_uq;
drop index if exists rhn_confinfo_ugf_se_uq;
drop index if exists rhn_confinfo_s_uq;
drop index if exists rhn_confinfo_s_se_uq;

-- Create correct multiple indices to handle null-column cases
create unique index rhn_confinfo_ugf_uq
    on rhnConfigInfo (username, groupname, filemode)
where username is not null and groupname is not null and filemode is not null
  and selinux_ctx is null and symlink_target_filename_id is null;

create unique index rhn_confinfo_ugf_se_uq
    on rhnConfigInfo (username, groupname, filemode, selinux_ctx)
where username is not null and groupname is not null and filemode is not null
  and selinux_ctx is not null and symlink_target_filename_id is null;

create unique index rhn_confinfo_s_uq
    on rhnConfigInfo (symlink_target_filename_id)
where username is null and groupname is null and filemode is null
  and selinux_ctx is null and symlink_target_filename_id is not null;

create unique index rhn_confinfo_s_se_uq
    on rhnConfigInfo (symlink_target_filename_id, selinux_ctx)
where username is null and groupname is null and filemode is null
  and selinux_ctx is not null and symlink_target_filename_id is not null;
07070100000C56000081B400000000000000000000000167AE11140000069D000000000000000000000000000000000000007800000000susemanager-schema/upgrade/susemanager-schema-3.1.6-to-susemanager-schema-3.1.7/020-suseImageInfo-inspect_action_id.sql   ALTER TABLE suseImageInfo RENAME COLUMN action_id TO build_action_id;

ALTER TABLE suseImageInfo ADD inspect_action_id NUMERIC;

ALTER TABLE suseImageInfo ADD CONSTRAINT suse_imginfo_aid_insp_fk
    FOREIGN KEY (inspect_action_id, build_server_id)
    REFERENCES rhnServerAction (action_id, server_id);

DROP VIEW suseImageOverview;

CREATE OR REPLACE VIEW
suseImageOverview
(
    org_id,
    image_id,
    image_name,
    image_version,
    checksum_id,
    modified,
    image_arch_name,
    build_action_id,
    inspect_action_id,
    profile_id,
    store_id,
    build_server_id,
    security_errata,
    bug_errata,
    enhancement_errata,
    outdated_packages,
    installed_packages
)
AS
SELECT
    i.org_id, i.id, i.name, i.version, i.checksum_id, i.modified,
    ( select name from rhnServerArch where id = i.image_arch_id), i.build_action_id,
    i.inspect_action_id, i.profile_id, i.store_id, i.build_server_id,
    ( select count(*) from rhnImageErrataTypeView ietv
      where
            ietv.image_id = i.id
        and ietv.errata_type = 'Security Advisory'),
    ( select count(*) from rhnImageErrataTypeView ietv
      where
            ietv.image_id = i.id
        and ietv.errata_type = 'Bug Fix Advisory'),
    ( select count(*) from rhnImageErrataTypeView ietv
      where
            ietv.image_id = i.id
        and ietv.errata_type = 'Product Enhancement Advisory'),
    ( select count(distinct p.name_id) from rhnPackage p, rhnImageNeededPackageCache inpc
      where
            inpc.image_id = i.id
        and p.id = inpc.package_id),
    (select count(*) from suseImageInfoPackage iip
     where
            iip.image_info_id = i.id)
FROM
    suseImageInfo i
;
   07070100000C57000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005000000000susemanager-schema/upgrade/susemanager-schema-3.1.7-to-susemanager-schema-3.1.8   07070100000C58000081B400000000000000000000000167AE111400004DE4000000000000000000000000000000000000006E00000000susemanager-schema/upgrade/susemanager-schema-3.1.7-to-susemanager-schema-3.1.8/012-rhnConfigInfo_indexes.sql --
-- Copyright (c) 2017 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--
-- We have to fix rhnConfigInfo in the presence of dups (and the rhnCOnfigRevisions that
-- might be pointing at them)
-- Clean up table, and then create corrected postgresql indicies to prevent dups
-- in the future
--
-- FOUR CASES:
--  Cfg-file is a FILE - username/groupname/filemode are NOT NULL, symlink_target_filename_id IS NULL, AND:
--    selinux_ctx IS NULL
--    selinux_ctx IS NOT NULL
--  Cfg-file is a LINK - username/groupname/filemode ARE ALL NULL, AND symlink_target_filename_id is NOT NULL, AND:
--    selinux_ctx NULL
--    selinux_ctx IS NOT NULL
--
-- Check all FOUR - if ANY show multiple rows, table is broken :(
--
create or replace function
is_cfginfo_broken() returns boolean
as
$$
declare
    throwaway       numeric;
    bad_data_exists boolean := false;
begin
    -- (1) Count username, groupname, filemode combinations where
    --     selinux_ctx is null
    select 1 into throwaway
    from (
        select username, groupname, filemode, count(id) as num
          from rhnConfigInfo
         where username is not null and groupname is not null and filemode is not null
           and symlink_target_filename_id is null and selinux_ctx is null
         group by username, groupname, filemode
    ) x
    where x.num > 1;

    if found then
        raise info 'DUP FILE INFO found, selinux NULL';
        bad_data_exists := true;
    end if;

    -- (2) Count username, groupname, filemode, selinux_ctx combinations where
    --     selinux is not null
    select 1 into throwaway
    from (
        select username, groupname, filemode, selinux_ctx, count(id) as num
          from rhnConfigInfo
         where username is not null and groupname is not null and filemode is not null
           and symlink_target_filename_id is null and selinux_ctx is not null
         group by username, groupname, filemode, selinux_ctx
    ) x
    where x.num > 1;

    if found then
        raise info 'DUP FILE INFO found, selinux is NOT NULL';
        bad_data_exists := true;
    end if;

    -- (3) Count symlink_target_filename_id combinations
    --     where username, groupname, filemode are null and selinux_ctx is null
    select 1 into throwaway
    from (
        select symlink_target_filename_id, count(id) as num
          from rhnConfigInfo
         where symlink_target_filename_id is not null
           and username is null and groupname is null and filemode is null
           and selinux_ctx is null
         group by symlink_target_filename_id
    ) x
    where x.num > 1;

    if found then
        raise info 'DUP LINK INFO found, selinux IS NULL';
        bad_data_exists := true;
    end if;

    -- (4) Count symlink_target_filename_id combinations
    --     where username, groupname, filemode are null and selinux_ctx IS NOT null
    select 1 into throwaway
    from (
        select symlink_target_filename_id, count(id) as num
          from rhnConfigInfo
         where symlink_target_filename_id is not null
           and username is null and groupname is null and filemode is null
           and selinux_ctx is not null
         group by symlink_target_filename_id
    ) x
    where x.num > 1;

    if found then
        raise info 'DUP LINK INFO found, selinux NOT NULL';
        bad_data_exists := true;
    end if;

    return bad_data_exists;
end
$$
language plpgsql;

--
-- Fix rhnConfigRevision pointers into rhnConfigInfo where there are dups
--  Cfg-file is a FILE - username/groupname/filemode are NOT NULL, AND symlink_target_filename_id NULL, AND:
--    fix_cfgrev_files_SELINUX_NULL     : selinux_ctx NULL
--    fix_cfgrev_files_SELINUX_NOT_NULL : selinux_ctx NOT NULL
--  Cfg-file is a LINK - username/groupname/filemode ARE ALL NULL, AND symlink_target_filename_id is NOT NULL, AND:
--    fix_cfgrev_links_SELINUX_NULL     : selinux_ctx NULL
--    fix_cfgrev_links_SELINUX_NOT_NULL : selinux_ctx NOT NULL
--
-- (The following is Ugly Repetitive Code - but it's one-use-only and gets the job done in the most obvious way possible)
--
create or replace function
fix_cfgrev_files_SELINUX_NULL() returns void
as
$$
declare
    d record;
    first_time      boolean               := true;
    good_cfginfo_id numeric               := -1;
    good_username   character varying(32) := '';
    good_groupname  character varying(32) := '';
    good_filemode   numeric               := -1;
begin
    for d in
        -- Find the cardinality of the IDs of the dups
        -- We will remember the most-used rhnConfigInfo.id, and repoint rhnConfigRevisions at it
        SELECT z.id as dup_cfginfo_id, z.username, z.groupname, z.filemode, count(crev.id) as num_rhnConfigRevision_using
        from (
            -- Find the IDs of the dups
            SELECT ci.id, ci.username, ci.groupname, ci.filemode
              from rhnConfigInfo ci
                   inner join (
			-- Find just the ones that are dups
			SELECT x.username, x.groupname, x.filemode, x.num
			from (
			    -- Count username,groupname,filemode combinations where symlink_target_filename_id and selinux_ctx are null
			    select username, groupname, filemode, count(id) as num
			      from rhnConfigInfo
			     where symlink_target_filename_id is null and selinux_ctx is null
			     group by username, groupname, filemode
			     ) x
			where x.num > 1
		    ) y on y.username = ci.username and y.groupname = ci.groupname and y.filemode = ci.filemode
             where 1=1
               and ci.symlink_target_filename_id is null and ci.selinux_ctx is null
             order by username, groupname, filemode, id
        ) z
        left outer join rhnConfigRevision crev on crev.config_info_id = z.id
        group by z.id, z.username, z.groupname, z.filemode
        order by z.username, z.groupname, z.filemode, count(crev.id) desc, z.id
    loop
        -- First time in, or when we move to a new kind-of dup, remember that one
        if first_time or (d.username <> good_username or d.groupname <> good_groupname or d.filemode <> good_filemode)
        then
            first_time := false;
            -- Remember the 'good values' so we can tell when we've moved to a new set in the dataresult
            good_cfginfo_id := d.dup_cfginfo_id;
            good_username   := d.username;
            good_groupname  := d.groupname;
            good_filemode   := d.filemode;
        -- we have seen this one before - repoint users at 'good' and remove this one
        else
            if d.num_rhnconfigrevision_using > 0
            then
                raise info '...REPOINTING RECORDS, rhnConfigInfo = %',d.dup_cfginfo_id;
                UPDATE rhnConfigRevision
                   set config_info_id = good_cfginfo_id
                 where config_info_id = d.dup_cfginfo_id;
            end if;
            DELETE from rhnConfigInfo ci
             where 1=1
               and ci.username = good_username
               and ci.groupname = good_groupname
               and ci.filemode = good_filemode
               and ci.selinux_ctx is null
               and ci.id = d.dup_cfginfo_id;
        end if;
    end loop;
end
$$
language plpgsql;

create or replace function
fix_cfgrev_files_SELINUX_NOT_NULL() returns void
as
$$
declare
    d record;
    first_time       boolean               := true;
    good_cfginfo_id  numeric               := -1;
    good_username    character varying(32) := '';
    good_groupname   character varying(32) := '';
    good_selinux_ctx character varying(64) := '';
    good_filemode    numeric               := -1;
begin
    for d in
        -- Find the cardinality of the IDs of the dups
        -- We will remember the most-used rhnConfigInfo.id, and repoint rhnConfigRevisions at it
        SELECT z.id as dup_cfginfo_id, z.username, z.groupname, z.filemode, z.selinux_ctx, count(crev.id) as num_rhnConfigRevision_using
        from (
            -- Find the IDs of the dups
            SELECT ci.id, ci.username, ci.groupname, ci.filemode, ci.selinux_ctx
              from rhnConfigInfo ci
                   inner join (
			-- Find just the ones that are dups
			SELECT x.username, x.groupname, x.filemode, x.selinux_ctx, x.num
			from (
			    -- Count username,groupname,filemode combinations where symlink_target_filename_id and selinux_ctx are null
			    select username, groupname, filemode, selinux_ctx, count(id) as num
			      from rhnConfigInfo
			     where symlink_target_filename_id is null and selinux_ctx is not null
			     group by username, groupname, filemode, selinux_ctx
			     ) x
			where x.num > 1
		    ) y on y.username = ci.username and y.groupname = ci.groupname and y.filemode = ci.filemode and y.selinux_ctx = ci.selinux_ctx
             where 1=1
               and ci.symlink_target_filename_id is null and ci.selinux_ctx is not null
             order by username, groupname, filemode, selinux_ctx, id
        ) z
        left outer join rhnConfigRevision crev on crev.config_info_id = z.id
        group by z.id, z.username, z.groupname, z.filemode, z.selinux_ctx
        order by z.username, z.groupname, z.filemode, z.selinux_ctx, count(crev.id) desc, z.id
    loop
        -- First time in, or when we move to a new kind-of dup, remember that one
        if first_time or (d.username <> good_username or d.groupname <> good_groupname or d.filemode <> good_filemode)
        then
            first_time := false;
            -- Remember the 'good values' so we can tell when we've moved to a new set in the dataresult
            good_cfginfo_id  := d.dup_cfginfo_id;
            good_username    := d.username;
            good_groupname   := d.groupname;
            good_filemode    := d.filemode;
            good_selinux_ctx := d.selinux_ctx;
        -- we have seen this one before - repoint users at 'good' and remove this one
        else
            if d.num_rhnconfigrevision_using > 0
            then
                raise info '...REPOINTING RECORDS, rhnConfigInfo = %',d.dup_cfginfo_id;
                UPDATE rhnConfigRevision
                   set config_info_id = good_cfginfo_id
                 where config_info_id = d.dup_cfginfo_id;
            end if;
            DELETE from rhnConfigInfo ci
             where 1=1
               and ci.username = good_username
               and ci.groupname = good_groupname
               and ci.filemode = good_filemode
               and ci.selinux_ctx = good_selinux_ctx
               and ci.id = d.dup_cfginfo_id;
        end if;
    end loop;
end
$$
language plpgsql;

create or replace function
fix_cfgrev_links_SELINUX_NOT_NULL() returns void
as
$$
declare
    d record;
    first_time                      boolean               := true;
    good_cfginfo_id                 numeric               := -1;
    good_symlink_target_filename_id numeric               := -1;
    good_selinux_ctx                character varying(64) := null;
begin
    for d in
        -- Find the cardinality of the IDs of the dups
        -- We will remember the most-used rhnConfigInfo.id, and repoint rhnConfigRevisions at it
        SELECT z.id as dup_cfginfo_id, z.symlink_target_filename_id, z.selinux_ctx, count(crev.id) as num_rhnConfigRevision_using
        from (
            -- Find the IDs of the dups
            SELECT ci.id, ci.symlink_target_filename_id, ci.selinux_ctx
              from rhnConfigInfo ci
                   inner join (
			-- Find just the ones that are dups
			SELECT x.symlink_target_filename_id, x.selinux_ctx, x.num
			from (
			    -- Count where symlink_target_filename_id is not null and selinux_ctx is not null
			    select symlink_target_filename_id, selinux_ctx, count(id) as num
			      from rhnConfigInfo
			     where username is null
                               and groupname is null
                               and filemode is null
                               and symlink_target_filename_id is not null
                               and selinux_ctx is not null
			     group by symlink_target_filename_id, selinux_ctx
			     ) x
			where x.num > 1
		    ) y on y.symlink_target_filename_id = ci.symlink_target_filename_id and y.selinux_ctx = ci.selinux_ctx
             where 1=1
               and ci.symlink_target_filename_id is not null and ci.selinux_ctx is not null
             order by symlink_target_filename_id, selinux_ctx, id
        ) z
        left outer join rhnConfigRevision crev on crev.config_info_id = z.id
        group by z.id, z.symlink_target_filename_id, z.selinux_ctx
        order by z.symlink_target_filename_id, z.selinux_ctx, count(crev.id) desc, z.id
    loop
        -- First time in, or when we move to a new kind-of dup, remember that one
        if first_time or (d.symlink_target_filename_id <> good_symlink_target_filename_id or d.selinux_ctx <> good_selinux_ctx)
        then
            first_time := false;
            -- Remember the 'good values' so we can tell when we've moved to a new set in the dataresult
            good_cfginfo_id                 := d.dup_cfginfo_id;
            good_symlink_target_filename_id := d.symlink_target_filename_id;
            good_selinux_ctx                := d.selinux_ctx;
        -- we have seen this one before - repoint users at 'good' and remove this one
        else
            if d.num_rhnconfigrevision_using > 0
            then
                raise info '...REPOINTING RECORDS, rhnConfigInfo = %',d.dup_cfginfo_id;
                UPDATE rhnConfigRevision
                   set config_info_id = good_cfginfo_id
                 where config_info_id = d.dup_cfginfo_id;
            end if;
            DELETE from rhnConfigInfo ci
             where 1=1
               and ci.symlink_target_filename_id = good_symlink_target_filename_id
               and ci.selinux_ctx                = good_selinux_ctx
               and ci.id = d.dup_cfginfo_id;
        end if;
    end loop;
end
$$
language plpgsql;

create or replace function
fix_cfgrev_links_SELINUX_NULL() returns void
as
$$
declare
    d record;
    first_time      boolean                 := true;
    good_cfginfo_id numeric                 := -1;
    good_symlink_target_filename_id numeric := -1;
begin
    raise info 'ENTERING fix_cfgrev_links_SELINUX_NULL';
    for d in
        -- Find the cardinality of the IDs of the dups
        -- We will remember the most-used rhnConfigInfo.id, and repoint rhnConfigRevisions at it
        SELECT z.id as dup_cfginfo_id, z.symlink_target_filename_id, count(crev.id) as num_rhnConfigRevision_using
        from (
            -- Find the IDs of the dups
            SELECT ci.id, ci.symlink_target_filename_id
              from rhnConfigInfo ci
                   inner join (
			-- Find just the ones that are dups
			SELECT x.symlink_target_filename_id, x.num
			from (
			    -- Count where symlink_target_filename_id is not null and selinux_ctx is null
			    select symlink_target_filename_id, count(id) as num
			      from rhnConfigInfo
			     where username is null
                               and groupname is null
                               and filemode is null
                               and symlink_target_filename_id is not null
                               and selinux_ctx is null
			     group by symlink_target_filename_id
			     ) x
			where x.num > 1
		    ) y on y.symlink_target_filename_id = ci.symlink_target_filename_id
             where 1=1
               and ci.symlink_target_filename_id is not null and ci.selinux_ctx is null
             order by symlink_target_filename_id, id
        ) z
        left outer join rhnConfigRevision crev on crev.config_info_id = z.id
        group by z.id, z.symlink_target_filename_id
        order by z.symlink_target_filename_id, count(crev.id) desc, z.id
    loop
        -- First time in, or when we move to a new kind-of dup, remember that one
        if first_time or (d.symlink_target_filename_id <> good_symlink_target_filename_id)
        then
            raise info '...NEW GOOD rhnConfigInfo = %',d.dup_cfginfo_id;
            first_time := false;
            -- Remember the 'good values' so we can tell when we've moved to a new set in the dataresult
            good_cfginfo_id                 := d.dup_cfginfo_id;
            good_symlink_target_filename_id := d.symlink_target_filename_id;
        -- we have seen this one before - repoint users at 'good' and remove this one
        else
            if d.num_rhnconfigrevision_using > 0
            then
                raise info '...REPOINTING RECORDS, rhnConfigInfo = %',d.dup_cfginfo_id;
                UPDATE rhnConfigRevision
                   set config_info_id = good_cfginfo_id
                 where config_info_id = d.dup_cfginfo_id;
            end if;
            DELETE from rhnConfigInfo ci
             where 1=1
               and ci.symlink_target_filename_id = good_symlink_target_filename_id
               and ci.selinux_ctx                is null
               and ci.id = d.dup_cfginfo_id;
        end if;
    end loop;
    raise info 'EXITING fix_cfgrev_links_SELINUX_NULL';
end
$$
language plpgsql;

create or replace function
fix_cfgrev_files() returns void
as
$$
declare
 throwaway character varying(32);
 is_broken boolean := false;
begin
  select is_cfginfo_broken() into is_broken;
  if is_broken then
    select fix_cfgrev_files_SELINUX_NOT_NULL() into throwaway;
    select fix_cfgrev_files_SELINUX_NULL() into throwaway;
    select fix_cfgrev_links_SELINUX_NOT_NULL() into throwaway;
    select fix_cfgrev_links_SELINUX_NULL() into throwaway;
  end if;
end
$$
language plpgsql;

-- FOUR CASES:
-- u|g|f-not  link-null selinux-null
-- u|g|f-not  link-null selinux-not
-- u|g|f null link-not  selinux-not
-- u|g|f null link-not  selinux-null

-- Fix potential dups
select fix_cfgrev_files();

-- Drop no-longer-necessary functions
drop function if exists fix_cfgrev_files();
drop function if exists is_cfginfo_broken();
drop function if exists fix_cfgrev_files_SELINUX_NOT_NULL();
drop function if exists fix_cfgrev_files_SELINUX_NULL();
drop function if exists fix_cfgrev_links_SELINUX_NOT_NULL();
drop function if exists fix_cfgrev_links_SELINUX_NULL();

-- Make adding new indices idempotent
drop index if exists rhn_confinfo_ugf_uq;
drop index if exists rhn_confinfo_ugf_se_uq;
drop index if exists rhn_confinfo_s_uq;
drop index if exists rhn_confinfo_s_se_uq;

-- 
-- Create correct multiple indices to handle null-column cases
create unique index rhn_confinfo_ugf_uq
    on rhnConfigInfo (username, groupname, filemode)
where username is not null and groupname is not null and filemode is not null
  and selinux_ctx is null and symlink_target_filename_id is null;

create unique index rhn_confinfo_ugf_se_uq
    on rhnConfigInfo (username, groupname, filemode, selinux_ctx)
where username is not null and groupname is not null and filemode is not null
  and selinux_ctx is not null and symlink_target_filename_id is null;

create unique index rhn_confinfo_s_uq
    on rhnConfigInfo (symlink_target_filename_id)
where username is null and groupname is null and filemode is null
  and selinux_ctx is null and symlink_target_filename_id is not null;

create unique index rhn_confinfo_s_se_uq
    on rhnConfigInfo (symlink_target_filename_id, selinux_ctx)
where username is null and groupname is null and filemode is null
  and selinux_ctx is not null and symlink_target_filename_id is not null;
07070100000C59000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005000000000susemanager-schema/upgrade/susemanager-schema-3.1.8-to-susemanager-schema-3.1.9   07070100000C5A000081B400000000000000000000000167AE11140000016E000000000000000000000000000000000000007400000000susemanager-schema/upgrade/susemanager-schema-3.1.8-to-susemanager-schema-3.1.9/001-add-channel-gpgcheck-column.sql   -- Adding the column 'gpg_check' to rhnChannel

DO $$
    BEGIN
        BEGIN
            ALTER TABLE rhnChannel ADD gpg_check CHAR(1) DEFAULT ('Y') NOT NULL CONSTRAINT rhn_channel_gc_ck CHECK (gpg_check in ('Y', 'N'));
        EXCEPTION
            WHEN duplicate_column THEN RAISE NOTICE 'column rhnChannel already exists in rhnChannel';
        END;
    END;
$$;
  07070100000C5B000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005100000000susemanager-schema/upgrade/susemanager-schema-3.1.9-to-susemanager-schema-3.1.10  07070100000C5C000081B400000000000000000000000167AE1114000001B5000000000000000000000000000000000000007000000000susemanager-schema/upgrade/susemanager-schema-3.1.9-to-susemanager-schema-3.1.10/001-suseImageInfo-actionFk.sql   ALTER TABLE suseImageInfo DROP CONSTRAINT suse_imginfo_aid_fk;
ALTER TABLE suseImageInfo DROP CONSTRAINT suse_imginfo_aid_insp_fk;

ALTER TABLE suseImageInfo ADD CONSTRAINT suse_imginfo_bldaid_fk
    FOREIGN KEY (build_action_id)
    REFERENCES rhnAction(id)
    ON DELETE SET NULL;

ALTER TABLE suseImageInfo ADD CONSTRAINT suse_imginfo_insaid_fk
    FOREIGN KEY (inspect_action_id)
    REFERENCES rhnAction(id)
    ON DELETE SET NULL;
   07070100000C5D000081B400000000000000000000000167AE111400000190000000000000000000000000000000000000006B00000000susemanager-schema/upgrade/susemanager-schema-3.1.9-to-susemanager-schema-3.1.10/002-Adelaide-Timezone.sql    insert into rhnTimezone (id, olson_name, display_name) (
    select sequence_nextval('rhn_timezone_id_seq'),
           'Australia/Adelaide',
           'Australia Central (Adelaide)'
      from dual
     where not exists (
           select 1
             from rhnTimezone
            where olson_name = 'Australia/Adelaide'
              and display_name = 'Australia Central (Adelaide)'
     )
);
07070100000C5E000081B400000000000000000000000167AE11140000004D000000000000000000000000000000000000007500000000susemanager-schema/upgrade/susemanager-schema-3.1.9-to-susemanager-schema-3.1.10/101-suseImageInfo-externalImage.sql  ALTER TABLE suseImageInfo ADD external_image CHAR(1) DEFAULT ('N') NOT NULL;
   07070100000C5F000081B400000000000000000000000167AE111400000593000000000000000000000000000000000000007900000000susemanager-schema/upgrade/susemanager-schema-3.1.9-to-susemanager-schema-3.1.10/102-suseImageOverview-externalImage.sql  drop view suseImageOverview;

create or replace view
suseImageOverview
(
    org_id,
    image_id,
    image_name,
    image_version,
    checksum_id,
    modified,
    image_arch_name,
    build_action_id,
    inspect_action_id,
    profile_id,
    store_id,
    build_server_id,
    external_image,
    security_errata,
    bug_errata,
    enhancement_errata,
    outdated_packages,
    installed_packages
)
as
select
    i.org_id, i.id, i.name, i.version, i.checksum_id, i.modified,
    ( select name from rhnServerArch where id = i.image_arch_id), i.build_action_id,
    i.inspect_action_id, i.profile_id, i.store_id, i.build_server_id, i.external_image,
    ( select count(*) from rhnImageErrataTypeView ietv
      where
            ietv.image_id = i.id
        and ietv.errata_type = 'Security Advisory'),
    ( select count(*) from rhnImageErrataTypeView ietv
      where
            ietv.image_id = i.id
        and ietv.errata_type = 'Bug Fix Advisory'),
    ( select count(*) from rhnImageErrataTypeView ietv
      where
            ietv.image_id = i.id
        and ietv.errata_type = 'Product Enhancement Advisory'),
    ( select count(distinct p.name_id) from rhnPackage p, rhnImageNeededPackageCache inpc
      where
            inpc.image_id = i.id
        and p.id = inpc.package_id),
    (select count(*) from suseImageInfoPackage iip
     where
            iip.image_info_id = i.id)
from
    suseImageInfo i
;
 07070100000C60000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005000000000susemanager-schema/upgrade/susemanager-schema-3.2.0-to-susemanager-schema-3.2.1   07070100000C61000081B400000000000000000000000167AE111400000147000000000000000000000000000000000000006E00000000susemanager-schema/upgrade/susemanager-schema-3.2.0-to-susemanager-schema-3.2.1/0013-nonlinux-entitlement.sql 
delete from rhnServerGroupMembers where server_group_id in (select id from rhnServerGroup where name = 'Non-Linux Entitled Servers' and group_type is not null);

delete from rhnServerGroup where name = 'Non-Linux Entitled Servers' and group_type is not null;

delete from rhnServerGroupType where label = 'nonlinux_entitled';
 07070100000C62000081B400000000000000000000000167AE111400001FEB000000000000000000000000000000000000006F00000000susemanager-schema/upgrade/susemanager-schema-3.2.0-to-susemanager-schema-3.2.1/0100-quartz-schema-upgrade.sql    --
-- drop tables that are no longer used
--
drop table qrtz_job_listeners;
drop table qrtz_trigger_listeners;
--
-- drop columns that are no longer used
--
alter table qrtz_job_details drop column is_volatile;
alter table qrtz_triggers drop column is_volatile;
alter table qrtz_fired_triggers drop column is_volatile;
--
-- add new columns that replace the 'is_stateful' column
--
alter table qrtz_job_details add column is_nonconcurrent bool;
alter table qrtz_job_details add column is_update_data bool;
update qrtz_job_details set is_nonconcurrent = is_stateful;
update qrtz_job_details set is_update_data = is_stateful;
alter table qrtz_job_details drop column is_stateful;
alter table qrtz_fired_triggers add column is_nonconcurrent bool;
update qrtz_fired_triggers set is_nonconcurrent = is_stateful;
alter table qrtz_fired_triggers drop column is_stateful;
--
-- add new 'sched_name' column to all tables --- replace "TestScheduler" with your scheduler's configured name
--
alter table qrtz_blob_triggers add column sched_name varchar(120) not null DEFAULT 'TestScheduler';
alter table qrtz_calendars add column sched_name varchar(120) not null DEFAULT 'TestScheduler';
alter table qrtz_cron_triggers add column sched_name varchar(120) not null DEFAULT 'TestScheduler';
alter table qrtz_fired_triggers add column sched_name varchar(120) not null DEFAULT 'TestScheduler';
alter table qrtz_job_details add column sched_name varchar(120) not null DEFAULT 'TestScheduler';
alter table qrtz_locks add column sched_name varchar(120) not null DEFAULT 'TestScheduler';
alter table qrtz_paused_trigger_grps add column sched_name varchar(120) not null DEFAULT 'TestScheduler';
alter table qrtz_scheduler_state add column sched_name varchar(120) not null DEFAULT 'TestScheduler';
alter table qrtz_simple_triggers add column sched_name varchar(120) not null DEFAULT 'TestScheduler';
alter table qrtz_triggers add column sched_name varchar(120) not null DEFAULT 'TestScheduler';
--
-- add new 'sched_time' column to qrtz_fired_triggers
--
alter table qrtz_fired_triggers add column sched_time BIGINT;
update qrtz_fired_triggers set sched_time = fired_time;
alter table qrtz_fired_triggers ALTER COLUMN sched_time SET NOT NULL;
--
-- drop all primary and foreign key constraints, so that we can define new ones
--
alter table qrtz_triggers drop constraint qrtz_triggers_job_name_fkey;
alter table qrtz_blob_triggers drop constraint qrtz_blob_triggers_pkey;
alter table qrtz_blob_triggers drop constraint qrtz_blob_triggers_trigger_name_fkey;
alter table qrtz_simple_triggers drop constraint qrtz_simple_triggers_pkey;
alter table qrtz_simple_triggers drop constraint qrtz_simple_triggers_trigger_name_fkey;
alter table qrtz_cron_triggers drop constraint qrtz_cron_triggers_pkey;
alter table qrtz_cron_triggers drop constraint qrtz_cron_triggers_trigger_name_fkey;
alter table qrtz_job_details drop constraint qrtz_job_details_pkey;
alter table qrtz_job_details add primary key (sched_name, job_name, job_group);
alter table qrtz_triggers drop constraint qrtz_triggers_pkey;
--
-- add all primary and foreign key constraints, based on new columns
--
alter table qrtz_triggers add primary key (sched_name, trigger_name, trigger_group);
alter table qrtz_triggers add foreign key (sched_name, job_name, job_group) references qrtz_job_details(sched_name, job_name, job_group);
alter table qrtz_blob_triggers add primary key (sched_name, trigger_name, trigger_group);
alter table qrtz_blob_triggers add foreign key (sched_name, trigger_name, trigger_group) references qrtz_triggers(sched_name, trigger_name, trigger_group);
alter table qrtz_cron_triggers add primary key (sched_name, trigger_name, trigger_group);
alter table qrtz_cron_triggers add foreign key (sched_name, trigger_name, trigger_group) references qrtz_triggers(sched_name, trigger_name, trigger_group);
alter table qrtz_simple_triggers add primary key (sched_name, trigger_name, trigger_group);
alter table qrtz_simple_triggers add foreign key (sched_name, trigger_name, trigger_group) references qrtz_triggers(sched_name, trigger_name, trigger_group);
alter table qrtz_fired_triggers drop constraint qrtz_fired_triggers_pkey;
alter table qrtz_fired_triggers add primary key (sched_name, entry_id);
alter table qrtz_calendars drop constraint qrtz_calendars_pkey;
alter table qrtz_calendars add primary key (sched_name, calendar_name);
alter table qrtz_locks drop constraint qrtz_locks_pkey;
alter table qrtz_locks add primary key (sched_name, lock_name);
alter table qrtz_paused_trigger_grps drop constraint qrtz_paused_trigger_grps_pkey;
alter table qrtz_paused_trigger_grps add primary key (sched_name, trigger_group);
alter table qrtz_scheduler_state drop constraint qrtz_scheduler_state_pkey;
alter table qrtz_scheduler_state add primary key (sched_name, instance_name);
--
-- add new simprop_triggers table
--
CREATE TABLE qrtz_simprop_triggers
 (
    SCHED_NAME VARCHAR(120) NOT NULL,
    TRIGGER_NAME VARCHAR(200) NOT NULL,
    TRIGGER_GROUP VARCHAR(200) NOT NULL,
    STR_PROP_1 VARCHAR(512) NULL,
    STR_PROP_2 VARCHAR(512) NULL,
    STR_PROP_3 VARCHAR(512) NULL,
    INT_PROP_1 INT NULL,
    INT_PROP_2 INT NULL,
    LONG_PROP_1 BIGINT NULL,
    LONG_PROP_2 BIGINT NULL,
    DEC_PROP_1 NUMERIC(13,4) NULL,
    DEC_PROP_2 NUMERIC(13,4) NULL,
    BOOL_PROP_1 BOOL NULL,
    BOOL_PROP_2 BOOL NULL,
    PRIMARY KEY (SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP),
    FOREIGN KEY (SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP)
    REFERENCES QRTZ_TRIGGERS(SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP)
);
--
-- create indexes for faster queries
--

drop index if exists idx_qrtz_j_req_recovery;
drop index if exists idx_qrtz_j_grp;
drop index if exists idx_qrtz_t_j;
drop index if exists idx_qrtz_t_jg;
drop index if exists idx_qrtz_t_c;
drop index if exists idx_qrtz_t_g;
drop index if exists idx_qrtz_t_state;
drop index if exists idx_qrtz_t_n_state;
drop index if exists idx_qrtz_t_n_g_state;
drop index if exists idx_qrtz_t_next_fire_time;
drop index if exists idx_qrtz_t_nft_st;
drop index if exists idx_qrtz_t_nft_misfire;
drop index if exists idx_qrtz_t_nft_st_misfire;
drop index if exists idx_qrtz_t_nft_st_misfire_grp;
drop index if exists idx_qrtz_ft_trig_inst_name;
drop index if exists idx_qrtz_ft_inst_job_req_rcvry;
drop index if exists idx_qrtz_ft_j_g;
drop index if exists idx_qrtz_ft_jg;
drop index if exists idx_qrtz_ft_t_g;
drop index if exists idx_qrtz_ft_tg;
create index idx_qrtz_j_req_recovery on qrtz_job_details(SCHED_NAME,REQUESTS_RECOVERY);
create index idx_qrtz_j_grp on qrtz_job_details(SCHED_NAME,JOB_GROUP);
create index idx_qrtz_t_j on qrtz_triggers(SCHED_NAME,JOB_NAME,JOB_GROUP);
create index idx_qrtz_t_jg on qrtz_triggers(SCHED_NAME,JOB_GROUP);
create index idx_qrtz_t_c on qrtz_triggers(SCHED_NAME,CALENDAR_NAME);
create index idx_qrtz_t_g on qrtz_triggers(SCHED_NAME,TRIGGER_GROUP);
create index idx_qrtz_t_state on qrtz_triggers(SCHED_NAME,TRIGGER_STATE);
create index idx_qrtz_t_n_state on qrtz_triggers(SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP,TRIGGER_STATE);
create index idx_qrtz_t_n_g_state on qrtz_triggers(SCHED_NAME,TRIGGER_GROUP,TRIGGER_STATE);
create index idx_qrtz_t_next_fire_time on qrtz_triggers(SCHED_NAME,NEXT_FIRE_TIME);
create index idx_qrtz_t_nft_st on qrtz_triggers(SCHED_NAME,TRIGGER_STATE,NEXT_FIRE_TIME);
create index idx_qrtz_t_nft_misfire on qrtz_triggers(SCHED_NAME,MISFIRE_INSTR,NEXT_FIRE_TIME);
create index idx_qrtz_t_nft_st_misfire on qrtz_triggers(SCHED_NAME,MISFIRE_INSTR,NEXT_FIRE_TIME,TRIGGER_STATE);
create index idx_qrtz_t_nft_st_misfire_grp on qrtz_triggers(SCHED_NAME,MISFIRE_INSTR,NEXT_FIRE_TIME,TRIGGER_GROUP,TRIGGER_STATE);
create index idx_qrtz_ft_trig_inst_name on qrtz_fired_triggers(SCHED_NAME,INSTANCE_NAME);
create index idx_qrtz_ft_inst_job_req_rcvry on qrtz_fired_triggers(SCHED_NAME,INSTANCE_NAME,REQUESTS_RECOVERY);
create index idx_qrtz_ft_j_g on qrtz_fired_triggers(SCHED_NAME,JOB_NAME,JOB_GROUP);
create index idx_qrtz_ft_jg on qrtz_fired_triggers(SCHED_NAME,JOB_GROUP);
create index idx_qrtz_ft_t_g on qrtz_fired_triggers(SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP);
create index idx_qrtz_ft_tg on qrtz_fired_triggers(SCHED_NAME,TRIGGER_GROUP);
 07070100000C63000081B400000000000000000000000167AE11140000029C000000000000000000000000000000000000008000000000susemanager-schema/upgrade/susemanager-schema-3.2.0-to-susemanager-schema-3.2.1/0201-add-root_pdid-to-suseProductExtensions.sql   
DO $$
  BEGIN
    alter table suseProductExtension add root_pdid numeric CONSTRAINT suse_prdext_rootid_fk REFERENCES suseProducts (id) ON DELETE CASCADE;
    update suseProductExtension set root_pdid = base_pdid;
    alter table suseProductExtension ALTER COLUMN root_pdid SET NOT NULL;

    CREATE UNIQUE INDEX prdext_ber_id_uq
    ON suseProductExtension (base_pdid, ext_pdid, root_pdid);

    alter table suseProductExtension add recommended CHAR(1) DEFAULT ('N') NOT NULL CONSTRAINT suse_prdext_rec_ck CHECK (recommended in ('Y', 'N'));
  EXCEPTION
    WHEN duplicate_column THEN RAISE NOTICE 'column root_pdid already exists in suseProductExtension';
  END;
$$;
07070100000C64000081B400000000000000000000000167AE1114000003B0000000000000000000000000000000000000006600000000susemanager-schema/upgrade/susemanager-schema-3.2.0-to-susemanager-schema-3.2.1/1002-rhnCompsType.sql --
-- Copyright (c) 2018 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

CREATE TABLE rhnCompsType
(
  id      NUMERIC NOT NULL
              CONSTRAINT rhn_comps_type_id_pk primary key,
  label   VARCHAR(32) NOT NULL
              CONSTRAINT rhn_comps_type_type_uq UNIQUE
);

INSERT INTO rhnCompsType (id, label) VALUES (1, 'comps');
INSERT INTO rhnCompsType (id, label) VALUES (2, 'modules');
07070100000C65000081B400000000000000000000000167AE1114000001E1000000000000000000000000000000000000006900000000susemanager-schema/upgrade/susemanager-schema-3.2.0-to-susemanager-schema-3.2.1/1003-rhnChannelComps.sql  
alter table rhnChannelComps add column comps_type_id numeric not null default 1 constraint rhn_channelcomps_comps_type_fk references rhnCompsType(id);

update rhnChannelComps set comps_type_id = (select id from rhnCompsType where label = 'comps');

alter table rhnChannelComps alter comps_type_id drop default;

alter table rhnChannelComps drop constraint rhn_channelcomps_cid_uq;

create unique index rhn_channelcomps_cid_ctype_uq on rhnChannelComps (channel_id, comps_type_id);
   07070100000C66000081B400000000000000000000000167AE111400007819000000000000000000000000000000000000006300000000susemanager-schema/upgrade/susemanager-schema-3.2.0-to-susemanager-schema-3.2.1/1004-set_comps.sql    --
-- Copyright (c) 2008--2016 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--
--
--
--

-- create schema rhn_channel;

--update pg_setting
update pg_settings set setting = 'rhn_channel,' || setting where name = 'search_path';

    -- this "emulates" cursor server_base_subscriptions defined in oracle/rhn_channel.pks
    create or replace function server_base_subscriptions(server_id_in NUMERIC)
    returns boolean as $$
    begin
      return exists(SELECT C.id FROM rhnChannel C, rhnServerChannel SC
		    WHERE C.id = SC.channel_id
		      AND SC.server_id = server_id_in
		      AND C.parent_channel IS NULL);
    end$$ language plpgsql;

    -- this "emulates" cursor server_base_subscriptions defined in oracle/rhn_channel.pks
    create or replace function check_server_subscription(server_id_in NUMERIC, channel_id_in NUMERIC)
    returns boolean as $$
    begin
      return exists(SELECT channel_id FROM rhnServerChannel WHERE server_id = server_id_in AND channel_id = channel_id_in);
    end$$ language plpgsql;


    CREATE OR REPLACE FUNCTION subscribe_server(server_id_in IN NUMERIC, channel_id_in NUMERIC, immediate_in NUMERIC default 1, user_id_in in numeric default null) returns void
    AS $$
    declare
        channel_parent_val      rhnChannel.parent_channel%TYPE;
        parent_subscribed       BOOLEAN;
        server_has_base_chan    BOOLEAN;
        server_already_in_chan  BOOLEAN;
        channel_family_id_val   NUMERIC;
        allowed                 numeric;
    BEGIN
        if user_id_in is not null then
            allowed := rhn_channel.user_role_check(channel_id_in, user_id_in, 'subscribe');
        else
            allowed := 1;
        end if;

        if allowed = 0 then
            perform rhn_exception.raise_exception('no_subscribe_permissions');
        end if;
        
        server_already_in_chan := rhn_channel.check_server_subscription(server_id_in, channel_id_in);

        IF server_already_in_chan
        THEN
            RETURN;
        END IF;

        SELECT parent_channel INTO channel_parent_val FROM rhnChannel WHERE id = channel_id_in;

        IF channel_parent_val IS NOT NULL
        THEN
            -- child channel; if attempting to cross-subscribe a child to the wrong base, silently ignore
            parent_subscribed := rhn_channel.check_server_subscription(server_id_in, channel_parent_val);

            IF NOT parent_subscribed
            THEN
                RETURN;
            END IF;
        ELSE
            -- base channel
            server_has_base_chan := rhn_channel.server_base_subscriptions(server_id_in);

            IF server_has_base_chan
            THEN
                perform rhn_exception.raise_exception('channel_server_one_base');
            END IF;
        END IF;

        channel_family_id_val := rhn_channel.family_for_channel(channel_id_in);
        IF channel_family_id_val IS NULL
        THEN
            perform rhn_exception.raise_exception('channel_subscribe_no_family');
        END IF;

        insert into rhnServerHistory (id,server_id,summary,details) (
            select  nextval('rhn_event_id_seq'),
                    server_id_in,
                    'subscribed to channel ' || SUBSTR(c.label, 0, 106),
                    c.label
            from    rhnChannel c
            where   c.id = channel_id_in
        );

        INSERT INTO rhnServerChannel (server_id, channel_id) VALUES (server_id_in, channel_id_in);

        perform queue_server(server_id_in, immediate_in);

        update rhnServer
           set channels_changed = current_timestamp
         where id = server_id_in;
    END$$ language plpgsql;

    create or replace function guess_server_base(
        server_id_in in numeric
    ) RETURNS numeric as $$
    declare
        server_cursor cursor for
            select s.server_arch_id, s.release, s.org_id
              from rhnServer s
             where s.id = server_id_in;
    -- Cursor that fetches all the possible base channels for a
    -- (server_arch_id, release, org_id) combination
        base_channel_cursor cursor(
                release_in varchar,
                server_arch_id_in numeric,
                org_id_in numeric
        ) for
                select distinct c.*
                from    rhnOrgDistChannelMap                       odcm,
                                rhnServerChannelArchCompat      scac,
                                rhnChannel                                      c
                where   c.parent_channel is null
                        and c.id = odcm.channel_id
                        and c.channel_arch_id = odcm.channel_arch_id
                        and odcm.release = release_in
                        and odcm.for_org_id = org_id_in
                        and scac.server_arch_id = server_arch_id_in
                        and scac.channel_arch_id = c.channel_arch_id;

    begin
        for s in server_cursor loop
            for channel in base_channel_cursor(s.release,
                s.server_arch_id, s.org_id)
            loop
                return channel.id;
            end loop;
        end loop;
        -- Server not found, or no base channel applies to it
        return null;
    end$$ language plpgsql;

    -- Private function
    create or replace function normalize_server_arch(server_arch_in in varchar)
    returns varchar
    as $$
    declare
        suffix VARCHAR(128) := '-redhat-linux';
    begin
        if server_arch_in is NULL then
            return NULL;
        end if;
        if position('-' IN server_arch_in) > 0
        then
            -- Suffix already present
            return server_arch_in;
        end if;
        return server_arch_in || suffix;
    end$$ language plpgsql;

    --
    -- Raises:
    --   server_arch_not_found
    --   no_subscribe_permissions
    create or replace function base_channel_for_release_arch(
        release_in in varchar,
        server_arch_in in varchar,
        org_id_in in numeric default -1,
        user_id_in in numeric default null
    ) returns numeric as $$
    declare
        server_arch varchar(256) := rhn_channel.normalize_server_arch(server_arch_in);
        server_arch_id numeric;
    begin
        -- Look up the server arch
            select id
              into server_arch_id
              from rhnServerArch
             where label = server_arch;
            if not found then
                perform rhn_exception.raise_exception('server_arch_not_found');
            end if;

        return rhn_channel.base_channel_rel_archid(release_in, server_arch_id,
            org_id_in, user_id_in);
    end$$ language plpgsql;

    create or replace function base_channel_rel_archid(
        release_in in varchar,
        server_arch_id_in in numeric,
        org_id_in in numeric default -1,
        user_id_in in numeric default null
    ) returns numeric as $$
    declare
        denied_channel_id numeric := null;
        valid_org_id numeric := org_id_in;
        valid_user_id numeric := user_id_in;
        channel_subscribable numeric;
    -- Cursor that fetches all the possible base channels for a
    -- (server_arch_id, release, org_id) combination
        base_channel_cursor cursor(
                release_in varchar,
                server_arch_id_in numeric,
                org_id_in numeric
        ) for
                select distinct c.*
                from    rhnOrgDistChannelMap                       odcm,
                                rhnServerChannelArchCompat      scac,
                                rhnChannel                                      c
                where   c.parent_channel is null
                        and c.id = odcm.channel_id
                        and c.channel_arch_id = odcm.channel_arch_id
                        and odcm.release = release_in
                        and odcm.for_org_id = org_id_in
                        and scac.server_arch_id = server_arch_id_in
                        and scac.channel_arch_id = c.channel_arch_id;

    begin
        if org_id_in = -1 and user_id_in is not null then
            -- Get the org id from the user id

                select org_id
                  into valid_org_id
                  from web_contact
                 where id = user_id_in;

                if not found then
                    -- User doesn't exist
                    -- XXX Only list public stuff for now
                    valid_user_id := null;
                    valid_org_id := -1;
                end if;
        end if;

        for c in base_channel_cursor(release_in, server_arch_id_in, valid_org_id)
        loop
            -- This row is a possible match
            if valid_user_id is null then
                -- User ID not specified, so no user to channel permissions to
                -- check
                return c.id;
            end if;

            -- Check user to channel permissions
            select rhn_channel.loose_user_role_check(c.id, user_id_in, 'subscribe')
              into channel_subscribable;

            if channel_subscribable = 1 then
                return c.id;
            end if;

            -- Base channel exists, but is not subscribable; keep trying
            denied_channel_id := c.id;
        end loop;

        if denied_channel_id is not null then
            perform rhn_exception.raise_exception('no_subscribe_permissions');
        end if;
        -- No base channel applies
        return NULL;
    end$$ language plpgsql;

    CREATE OR REPLACE FUNCTION clear_subscriptions(server_id_in IN NUMERIC, deleting_server IN NUMERIC default 0) returns void
    AS $$
    declare
        server_channels cursor(server_id_in numeric) for
                select  s.org_id, sc.channel_id, cfm.channel_family_id
                from    rhnServer s,
                        rhnServerChannel sc,
                        rhnChannelFamilyMembers cfm
                where   s.id = server_id_in
                        and s.id = sc.server_id
                        and sc.channel_id = cfm.channel_id
                order by cfm.channel_family_id;
        last_channel_family_id rhnChannelFamilyMembers.channel_family_id%type := -1;
        last_channel_org_id    rhnServer.org_id%type := -1;
    BEGIN
        for channel in server_channels(server_id_in)
        loop
                perform rhn_channel.unsubscribe_server(server_id_in, channel.channel_id, 1, 1, deleting_server);
        end loop;
    END$$ language plpgsql;

    CREATE OR REPLACE FUNCTION unsubscribe_server(server_id_in IN NUMERIC, channel_id_in NUMERIC, immediate_in NUMERIC default 1, unsubscribe_children_in numeric default 0,
                                 deleting_server in numeric default 0) returns void
    AS $$
    declare
        channel_family_id_val   NUMERIC;
        server_org_id_val       NUMERIC;
        server_already_in_chan  BOOLEAN;
        channel_family_is_proxy cursor(channel_family_id_in numeric) for
                select  1
                from    rhnChannelFamily
                where   id = channel_family_id_in
                    and label = 'rhn-proxy';
        channel_family_is_satellite cursor(channel_family_id_in numeric) for
                select  1
                from    rhnChannelFamily
                where   id = channel_family_id_in
                    and label = 'rhn-satellite';
        child record;
    BEGIN
        -- In PostgreSQL recursion with opened cursors is not allowed so we use
        -- FOR IN SELECT form which is ok.
        FOR child IN select  c.id
                from    rhnChannel                      c,
                                rhnServerChannel        sc
                where   1=1
                        and c.parent_channel = channel_id_in
                        and c.id = sc.channel_id
                        and sc.server_id = server_id_in
        LOOP
            if unsubscribe_children_in = 1 then
                perform rhn_channel.unsubscribe_server(server_id_in,
                                                       child.id,
                                                       immediate_in,
                                                       unsubscribe_children_in,
                                                       deleting_server);
            else
                perform rhn_exception.raise_exception('channel_unsubscribe_child_exists');
            end if;
        END LOOP;

        server_already_in_chan := rhn_channel.check_server_subscription(server_id_in, channel_id_in);

        IF NOT server_already_in_chan
        THEN
            RETURN;
        END IF;

   if deleting_server = 0 then
      insert into rhnServerHistory (id,server_id,summary,details) (
          select  nextval('rhn_event_id_seq'),
                server_id_in,
             'unsubscribed from channel ' || SUBSTR(c.label, 0, 106),
             c.label
          from    rhnChannel c
          where   c.id = channel_id_in
      );
   end if;

   DELETE FROM rhnServerChannel WHERE server_id = server_id_in AND channel_id = channel_id_in;

   if deleting_server = 0 then
        perform queue_server(server_id_in, immediate_in);

        update rhnServer
           set channels_changed = current_timestamp
         where id = server_id_in;
   end if;

        channel_family_id_val := rhn_channel.family_for_channel(channel_id_in);
        IF channel_family_id_val IS NULL
        THEN
            perform rhn_exception.raise_exception('channel_unsubscribe_no_family');
        END IF;

        for ignore in channel_family_is_satellite(channel_family_id_val) loop
                delete from rhnSatelliteInfo where server_id = server_id_in;
        end loop;

        for ignore in channel_family_is_proxy(channel_family_id_val) loop
                delete from rhnProxyInfo where server_id = server_id_in;
        end loop;
        SELECT org_id INTO server_org_id_val
          FROM rhnServer
         WHERE id = server_id_in;

    END$$ language plpgsql;

    CREATE OR REPLACE FUNCTION family_for_channel(channel_id_in IN NUMERIC)
    RETURNS NUMERIC
    AS $$
    declare
        channel_family_id_val NUMERIC;
    BEGIN
        SELECT channel_family_id INTO channel_family_id_val
          FROM rhnChannelFamilyMembers
         WHERE channel_id = channel_id_in;

        IF NOT FOUND THEN
          RETURN NULL;
        END IF;

        RETURN channel_family_id_val;
    END$$ language plpgsql;

    create or replace function unsubscribe_server_from_family(server_id_in in numeric,
                                             channel_family_id_in in numeric)
    returns void
    as $$
    begin
        delete
        from    rhnServerChannel rsc
        where   rsc.server_id = server_id_in
            and channel_id in (
                select  rcfm.channel_id
                from    rhnChannelFamilyMembers rcfm
                where   rcfm.channel_family_id = channel_family_id_in);
    end$$ language plpgsql;

    create or replace function get_org_id(channel_id_in in numeric)
    returns numeric
    as $$
    declare
        org_id_out numeric;
    begin
        select org_id into strict org_id_out
            from rhnChannel
            where id = channel_id_in;

            return org_id_out;
    end$$ language plpgsql;

    create or replace function get_cfam_org_access(cfam_id_in in numeric, org_id_in in numeric)
    returns numeric
    as $$
    begin
      if exists(
                        select  1
                        from    rhnOrgChannelFamilyPermissions cfp
                        where   cfp.org_id = org_id_in
      ) then
                return 1;
      else
                return 0;
      end if;
    end$$ language plpgsql;

    create or replace function get_org_access(channel_id_in in numeric, org_id_in in numeric)
    returns integer
    as $$
    begin
        -- the idea: if we get past this query,
        -- the org has access to the channel, else not
        if exists(
        select 1
          from rhnChannelFamilyMembers CFM,
               rhnOrgChannelFamilyPermissions CFP
         where cfp.org_id = org_id_in
           and CFM.channel_family_id = CFP.channel_family_id
           and CFM.channel_id = channel_id_in)
        then
          return 1;
        else
          return 0;
        end if;
    end$$ language plpgsql;

    -- check if a user has a given role, or if such a role is inferrable
    -- returns NULL if OK, error message otherwise
    create or replace function user_role_check_debug(channel_id_in in numeric,
                                   user_id_in in numeric,
                                   role_in in varchar)
    returns varchar
    as $$
    declare
        org_id numeric;
    begin
        org_id := rhn_user.get_org_id(user_id_in);

        -- channel might be shared
        if role_in = 'subscribe' and
           rhn_channel.shared_user_role_check(channel_id_in, user_id_in, role_in) = 1 then
            return NULL;
        end if;

        if role_in = 'manage' and
           COALESCE(rhn_channel.get_org_id(channel_id_in), -1) <> org_id then
               return 'channel_not_owned';
        end if;

        if role_in = 'subscribe' and
           rhn_channel.get_org_access(channel_id_in, org_id) = 0 then
                return 'channel_not_available';
        end if;

        -- channel admins have all roles
        if rhn_user.check_role_implied(user_id_in, 'channel_admin') = 1 then
            return NULL;
        end if;

        -- the subscribe permission is inferred
        -- UNLESS the not_globally_subscribable flag is set
        if role_in = 'subscribe'
        then
            if rhn_channel.org_channel_setting(channel_id_in,
                       org_id,
                       'not_globally_subscribable') = 0 then
                return NULL;
            end if;
        end if;

        -- all other roles (manage right now) are explicitly granted
        if rhn_channel.direct_user_role_check(channel_id_in,
                                              user_id_in, role_in) = 1 then
            return NULL;
        end if;
        return 'direct_permission';
    end$$ language plpgsql;

    -- same as above, but with 1/0 output; useful in views, etc
    create or replace function user_role_check(channel_id_in in numeric, user_id_in in numeric, role_in in varchar)
    returns numeric
    as $$
    begin
        if rhn_channel.user_role_check_debug(channel_id_in,
                                             user_id_in, role_in) is NULL then
            return 1;
        else
            return 0;
        end if;
    end$$ language plpgsql;

    --
    -- For multiorg phase II, this function simply checks to see if the user's
    -- has a trust relationship that includes this channel by id.
    --
    create or replace function shared_user_role_check(channel_id in numeric, user_id in numeric, role in varchar)
    returns numeric
    as $$
    declare
      n numeric;
      oid numeric;
    begin
      oid := rhn_user.get_org_id(user_id);
      select 1 into n
      from rhnSharedChannelView s
      where s.id = channel_id and s.org_trust_id = oid;

      if not found then
        return 0;
      end if;

      return 1;
    end$$ language plpgsql;

    -- same as above, but returns 1 if user_id_in is null
    -- This is useful in queries where user_id is not specified
    create or replace function loose_user_role_check(channel_id_in in numeric, user_id_in in numeric, role_in in varchar)
    returns numeric
    as $$
    begin
        if user_id_in is null then
            return 1;
        end if;
        return rhn_channel.user_role_check(channel_id_in, user_id_in, role_in);
    end$$ language plpgsql;

    -- directly checks the table, no inferred permissions
    create or replace function direct_user_role_check(channel_id_in in numeric, user_id_in in numeric, role_in in varchar)
    returns numeric
    as $$
    declare
        throwaway numeric;
    begin
        -- the idea: if we get past this query, the user has the role, else no
        select 1 into throwaway
          from rhnChannelPermissionRole CPR,
               rhnChannelPermission CP
         where CP.user_id = user_id_in
           and CP.channel_id = channel_id_in
           and CPR.label = role_in
           and CP.role_id = CPR.id;

      if not found then
        return 0;
      end if;

      return 1;
    end$$ language plpgsql;

    -- check if an org has a certain setting
    create or replace function org_channel_setting(channel_id_in in numeric, org_id_in in numeric, setting_in in varchar)
    returns numeric
    as $$
    declare
        throwaway numeric;
    begin
        -- the idea: if we get past this query, the org has the setting
        select 1 into throwaway
          from rhnOrgChannelSettingsType OCST,
               rhnOrgChannelSettings OCS
         where OCS.org_id = org_id_in
           and OCS.channel_id = channel_id_in
           and OCST.label = setting_in
           and OCS.setting_id = OCST.id;

      if not found then
        return 0;
      end if;

      return 1;
    end$$ language plpgsql;

    CREATE OR REPLACE FUNCTION channel_priority(channel_id_in IN numeric)
    RETURNS numeric
    AS $$
    declare
         channel_name varchar(256);
         priority numeric;
         end_of_life_val timestamptz;
         org_id_val numeric;
    BEGIN

        select name, end_of_life, org_id
        into channel_name, end_of_life_val, org_id_val
        from rhnChannel
        where id = channel_id_in;

        if end_of_life_val is not null then
          return -400;
        end if;

        if channel_name like 'Red Hat Enterprise Linux%' or channel_name like 'RHEL%' then
          priority := 1000;
          if channel_name not like '%Beta%' then
            priority := priority + 1000;
          end if;

          priority := priority +
            case
              when channel_name like '%v. 5%' then 600
              when channel_name like '%v. 4%' then 500
              when channel_name like '%v. 3%' then 400
              when channel_name like '%v. 2%' then 300
              when channel_name like '%v. 1%' then 200
              else 0
            end;

          priority := priority +
            case
              when channel_name like 'Red Hat Enterprise Linux (v. 5%' then 60
              when (channel_name like '%AS%' and channel_name not like '%Extras%') then 50
              when (channel_name like '%ES%' and channel_name not like '%Extras%') then 40
              when (channel_name like '%WS%' and channel_name not like '%Extras%') then 30
              when (channel_name like '%Desktop%' and channel_name not like '%Extras%') then 20
              when channel_name like '%Extras%' then 10
              else 0
            end;

          priority := priority +
            case
              when channel_name like '%)' then 5
              else 0
            end;

          priority := priority +
            case
              when channel_name like '%32-bit x86%' then 4
              when channel_name like '%64-bit Intel Itanium%' then 3
              when channel_name like '%64-bit AMD64/Intel EM64T%' then 2
              else 0
            end;
        elsif channel_name like 'Red Hat Desktop%' then
            priority := 900;

            if channel_name not like '%Beta%' then
               priority := priority + 50;
            end if;

          priority := priority +
            case
              when channel_name like '%v. 4%' then 40
              when channel_name like '%v. 3%' then 30
              when channel_name like '%v. 2%' then 20
              when channel_name like '%v. 1%' then 10
              else 0
            end;

          priority := priority +
            case
              when channel_name like '%32-bit x86%' then 4
              when channel_name like '%64-bit Intel Itanium%' then 3
              when channel_name like '%64-bit AMD64/Intel EM64T%' then 2
              else 0
            end;

        elsif org_id_val is not null then
          priority := 600;
        else
          priority := 500;
        end if;

      return -priority;

    end$$ language plpgsql;

    -- this could certainly be optimized to do updates if needs be
    create or replace function refresh_newest_package(channel_id_in in numeric,
                                      caller_in in varchar default '(unknown)',
                                      package_name_id_in in numeric default null)
    returns void
    as $$
    -- procedure refreshes rows for name_id = package_name_id_in or
    -- all rows if package_name_id_in is null
    begin
        delete from rhnChannelNewestPackage
              where channel_id = channel_id_in
                and (package_name_id_in is null
                     or name_id = package_name_id_in);
        insert into rhnChannelNewestPackage
                (channel_id, name_id, evr_id, package_id, package_arch_id)
                (select channel_id,
                        name_id, evr_id,
                        package_id, package_arch_id
                   from rhnChannelNewestPackageView
                  where channel_id = channel_id_in
                    and (package_name_id_in is null
                         or name_id = package_name_id_in)
                );
        insert into rhnChannelNewestPackageAudit (channel_id, caller)
             values (channel_id_in, caller_in);
        update rhnChannel
           set last_modified = greatest(current_timestamp,
                                        last_modified + interval '1 second')
         where id = channel_id_in;
    end$$ language plpgsql;

   create or replace function update_channel ( channel_id_in in numeric, invalidate_ss in numeric default 0,
                              date_to_use in timestamptz default current_timestamp ) returns void
   as $$
   declare
   channel_last_modified timestamptz;
   last_modified_value timestamptz;

   snapshots cursor for
   select  snapshot_id id
   from    rhnSnapshotChannel
   where   channel_id = channel_id_in;

   begin

      select last_modified
      into channel_last_modified
      from rhnChannel
      where id = channel_id_in;

      last_modified_value := date_to_use;

      if last_modified_value <= channel_last_modified then
          last_modified_value := last_modified_value + interval '1 second';
      end if;

      update rhnChannel set last_modified = last_modified_value
      where id = channel_id_in;

      if invalidate_ss = 1 then
        for snapshot in snapshots loop
            update rhnSnapshot
            set invalid = lookup_snapshot_invalid_reason('channel_modified')
            where id = snapshot.id;
        end loop;
      end if;

   end$$ language plpgsql;

   create or replace function update_channels_by_package ( package_id_in in numeric, date_to_use in timestamptz default current_timestamp ) returns void
   as $$
   declare
   channels cursor for
   select channel_id
   from rhnChannelPackage
   where package_id = package_id_in
   order by channel_id;

   begin
      for channel in channels loop
         -- we want to invalidate the snapshot assocated with the channel when we
         -- do this b/c we know we've added or removed or packages
         perform rhn_channel.update_channel ( channel.channel_id, 1, date_to_use );
      end loop;
   end$$ language plpgsql;


   create or replace function update_channels_by_errata ( errata_id_in numeric, date_to_use in timestamptz default current_timestamp ) returns void
   as $$
   declare
   channels cursor for
   select channel_id
   from rhnChannelErrata
   where errata_id = errata_id_in
   order by channel_id;

   begin
      for channel in channels loop
         -- we won't invalidate snapshots, b/c just changing the errata associated with
         -- a channel shouldn't invalidate snapshots
         perform rhn_channel.update_channel ( channel.channel_id, 0, date_to_use );
      end loop;
   end$$ language plpgsql;

   create or replace function update_needed_cache(channel_id_in in numeric) returns void
   as $$
   declare
   server record;
   image record;
   begin
      -- we intentionaly do a loop here instead of one huge select
      -- b/c we want to break update into smaller transaction to unblock other sessions
      -- querying rhnServerNeededCache
      for server in (
                select sc.server_id as id
                  from rhnServerChannel sc
                 where sc.channel_id = channel_id_in
                 order by id asc
      ) loop
         perform queue_server(server.id, 0); -- NOT IMMEDIATE
      end loop;
      for image in (
        select ic.image_info_id as id
          from suseImageInfoChannel ic
         where ic.channel_id = channel_id_in
        order by id asc
      ) loop
         perform queue_image(image.id, 0);
      end loop;
   end$$ language plpgsql;

    create or replace function set_comps(channel_id_in in numeric, path_in in varchar, comps_type_id_in in numeric, timestamp_in in varchar) returns void
    as $$
    declare
    row record;
    begin
        for row in (
            select relative_filename, last_modified
            from rhnChannelComps
            where channel_id = channel_id_in
            and comps_type_id = comps_type_id_in
            ) loop
            if row.relative_filename = path_in
                and row.last_modified = to_timestamp(timestamp_in, 'YYYYMMDDHH24MISS') then
                return;
            end if;
        end loop;
        delete from rhnChannelComps
        where channel_id = channel_id_in and comps_type_id = comps_type_id_in;
        insert into rhnChannelComps (id, channel_id, relative_filename, comps_type_id, last_modified, created, modified)
        values (sequence_nextval('rhn_channelcomps_id_seq'), channel_id_in, path_in, comps_type_id_in, to_timestamp(timestamp_in, 'YYYYMMDDHH24MISS'), current_timestamp, current_timestamp);
    end$$ language plpgsql;

-- restore the original setting
update pg_settings set setting = overlay( setting placing '' from 1 for (length('rhn_channel')+1) ) where name = 'search_path';
   07070100000C67000081B400000000000000000000000167AE111400000179000000000000000000000000000000000000007600000000susemanager-schema/upgrade/susemanager-schema-3.2.0-to-susemanager-schema-3.2.1/1010-rhnerratatmp-add_severity_id.sql -- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
-- ALTER TABLE rhnErrataTmp
--  ADD severity_id NUMERIC;

ALTER TABLE rhnErrataTmp
 ADD CONSTRAINT rhn_erratatmp_sevid_fk
 FOREIGN KEY (severity_id) REFERENCES rhnErrataSeverity(id);
   07070100000C68000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005000000000susemanager-schema/upgrade/susemanager-schema-3.2.1-to-susemanager-schema-3.2.2   07070100000C69000081B400000000000000000000000167AE111400000000000000000000000000000000000000000000005900000000susemanager-schema/upgrade/susemanager-schema-3.2.1-to-susemanager-schema-3.2.2/.gitkeep  07070100000C6A000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005200000000susemanager-schema/upgrade/susemanager-schema-3.2.10-to-susemanager-schema-3.2.11 07070100000C6B000081B400000000000000000000000167AE111400000000000000000000000000000000000000000000005B00000000susemanager-schema/upgrade/susemanager-schema-3.2.10-to-susemanager-schema-3.2.11/.gitkeep    07070100000C6C000081B400000000000000000000000167AE111400000561000000000000000000000000000000000000007100000000susemanager-schema/upgrade/susemanager-schema-3.2.10-to-susemanager-schema-3.2.11/001-define-sle15-ostargets.sql  insert into suseOSTarget (id, os, target, channel_arch_id)
  select sequence_nextval('suse_ostarget_id_seq'), 'sle-15-x86_64', 'sle-15-x86_64', LOOKUP_CHANNEL_ARCH('channel-x86_64') from dual
   where not exists (select 1 from suseOSTarget where target = 'sle-15-x86_64');

insert into suseOSTarget (id, os, target, channel_arch_id)
  select sequence_nextval('suse_ostarget_id_seq'), 'sle-15-s390x', 'sle-15-s390x', LOOKUP_CHANNEL_ARCH('channel-s390x') from dual
   where not exists (select 1 from suseOSTarget where target = 'sle-15-s390x');

insert into suseOSTarget (id, os, target, channel_arch_id)
  select sequence_nextval('suse_ostarget_id_seq'), 'sle-15-ppc64le', 'sle-15-ppc64le', LOOKUP_CHANNEL_ARCH('channel-ppc64le') from dual
   where not exists (select 1 from suseOSTarget where target = 'sle-15-ppc64le');

insert into suseOSTarget (id, os, target, channel_arch_id)
  select sequence_nextval('suse_ostarget_id_seq'), 'sle-15-aarch64', 'sle-15-aarch64', LOOKUP_CHANNEL_ARCH('channel-aarch64') from dual
   where not exists (select 1 from suseOSTarget where target = 'sle-15-aarch64');

insert into suseOSTarget (id, os, target, channel_arch_id)
  select sequence_nextval('suse_ostarget_id_seq'), 'sle-12-aarch64', 'sle-12-aarch64', LOOKUP_CHANNEL_ARCH('channel-aarch64') from dual
   where not exists (select 1 from suseOSTarget where target = 'sle-12-aarch64');
   07070100000C6D000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005200000000susemanager-schema/upgrade/susemanager-schema-3.2.11-to-susemanager-schema-3.2.12 07070100000C6E000081B400000000000000000000000167AE111400000168000000000000000000000000000000000000007700000000susemanager-schema/upgrade/susemanager-schema-3.2.11-to-susemanager-schema-3.2.12/001-fix-truncated-action-results.sql    
DO $$
  declare
    result_msg_data_type text;
  BEGIN
    SELECT data_type INTO result_msg_data_type
    FROM information_schema.columns
    WHERE table_name = 'rhnserveraction' and column_name = 'result_msg';

    IF (result_msg_data_type='character varying') THEN
      ALTER TABLE rhnserveraction ALTER COLUMN result_msg TYPE text;
    END IF;
  END;
$$;
07070100000C6F000081B400000000000000000000000167AE11140000072F000000000000000000000000000000000000007D00000000susemanager-schema/upgrade/susemanager-schema-3.2.11-to-susemanager-schema-3.2.12/007-add-minionactionchainexecutor-task.sql  --
-- Copyright (c) 2018 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

INSERT INTO rhnTaskoBunch (id, name, description, org_bunch)
  SELECT sequence_nextval('rhn_tasko_bunch_id_seq'), 'minion-action-chain-executor-bunch', 'Execute action chains on Minions', null from dual
   where not exists (select 1 from rhnTaskoBunch where name = 'minion-action-chain-executor-bunch');

INSERT INTO rhnTaskoTask (id, name, class)
    SELECT sequence_nextval('rhn_tasko_task_id_seq'), 'minion-action-chain-executor', 'com.redhat.rhn.taskomatic.task.MinionActionChainExecutor' from dual
     where not exists (select 1 from rhnTaskoTask where name = 'minion-action-chain-executor');

INSERT INTO rhnTaskoTemplate (id, bunch_id, task_id, ordering, start_if)
    SELECT sequence_nextval('rhn_tasko_template_id_seq'),
        (SELECT id FROM rhnTaskoBunch WHERE name='minion-action-chain-executor-bunch'),
        (SELECT id FROM rhnTaskoTask WHERE name='minion-action-chain-executor'),
        0,
        null from dual
     where not exists (select 1 from rhnTaskoTemplate
                        where bunch_id = (SELECT id FROM rhnTaskoBunch WHERE name='minion-action-chain-executor-bunch')
                          and task_id = (SELECT id FROM rhnTaskoTask WHERE name='minion-action-chain-executor'));
 07070100000C70000081B400000000000000000000000167AE1114000006CE000000000000000000000000000000000000008400000000susemanager-schema/upgrade/susemanager-schema-3.2.11-to-susemanager-schema-3.2.12/008-add-minion-action-chain-cleanup-tasko-job.sql   INSERT INTO rhnTaskoBunch (id, name, description, org_bunch)
    SELECT sequence_nextval('rhn_tasko_bunch_id_seq'), 'minion-action-chain-cleanup-bunch', 'Cleanup actions chains for Minions', null
    FROM dual WHERE NOT EXISTS (
        SELECT 1 FROM rhnTaskoBunch WHERE
        name='minion-action-chain-cleanup-bunch'
    );

INSERT INTO rhnTaskoSchedule (id, job_label, bunch_id, active_from, cron_expr)
    SELECT sequence_nextval('rhn_tasko_schedule_id_seq'), 'minion-action-chain-cleanup-default',
        (SELECT id FROM rhnTaskoBunch WHERE name='minion-action-chain-cleanup-bunch'),
        current_timestamp, '0 0 * * * ?'
    FROM dual WHERE NOT EXISTS (
        SELECT 1 FROM rhnTaskoSchedule WHERE
        job_label='minion-action-chain-cleanup-default'
    );

INSERT INTO rhnTaskoTask (id, name, class)
    SELECT sequence_nextval('rhn_tasko_task_id_seq'), 'minion-action-chain-cleanup', 'com.redhat.rhn.taskomatic.task.MinionActionChainCleanup'
    FROM dual WHERE NOT EXISTS (
        SELECT 1 FROM rhnTaskoTask WHERE
        name='minion-action-chain-cleanup'
    );

INSERT INTO rhnTaskoTemplate (id, bunch_id, task_id, ordering, start_if)
    SELECT sequence_nextval('rhn_tasko_template_id_seq'),
                        (SELECT id FROM rhnTaskoBunch WHERE name='minion-action-chain-cleanup-bunch'),
                        (SELECT id FROM rhnTaskoTask WHERE name='minion-action-chain-cleanup'),
                        0,
                        null
    FROM dual WHERE NOT EXISTS (
        SELECT 1 FROM rhnTaskoTemplate WHERE
        bunch_id=(SELECT id FROM rhnTaskoBunch WHERE name='minion-action-chain-cleanup-bunch') AND
        task_id=(SELECT id FROM rhnTaskoTask WHERE name='minion-action-chain-cleanup')
    );
  07070100000C71000081B400000000000000000000000167AE1114000006A6000000000000000000000000000000000000008B00000000susemanager-schema/upgrade/susemanager-schema-3.2.11-to-susemanager-schema-3.2.12/100-fix-inconsistent-config-state-channel-assignment.sql    -- Remove inconsistent config channel state revisions where config channel org is
-- not equal to staterevision org.
DELETE FROM suseStateRevisionConfigChannel scc WHERE
NOT EXISTS (SELECT 1
            FROM rhnConfigChannel cc, suseStateRevision sr, web_contact wc
            WHERE cc.id = scc.config_channel_id
            AND scc.state_revision_id = sr.id
            AND sr.creator_id = wc.id
            AND wc.org_id = cc.org_id);

DELETE from rhnServerConfigChannel sscc WHERE
NOT EXISTS (SELECT 1
            FROM rhnConfigChannel cc, rhnserver s
            WHERE cc.id = sscc.config_channel_id
            AND sscc.server_id = s.id
            AND s.org_id = cc.org_id);

-- Recalculate positions for entries after removing some of them on the previous step.
-- These SQL queries will keep the actual position ordering but ensuring there is no missing position.
UPDATE suseStateRevisionConfigChannel
SET position = (
    SELECT rank
    FROM (
        SELECT state_revision_id, config_channel_id, position, (row_number() OVER (PARTITION BY state_revision_id ORDER BY position ASC)) rank
        FROM suseStateRevisionConfigChannel scc
    ) ranking
    WHERE config_channel_id = suseStateRevisionConfigChannel.config_channel_id
    AND state_revision_id = suseStateRevisionConfigChannel.state_revision_id);


UPDATE rhnServerConfigChannel
SET position = (
    select rank
    from (
        SELECT server_id, config_channel_id, position, (row_number() OVER (PARTITION BY server_id ORDER BY position ASC)) rank
        FROM rhnServerConfigChannel sscc
    ) ranking
    WHERE config_channel_id = rhnServerConfigChannel.config_channel_id
    AND server_id = rhnServerConfigChannel.server_id);
  07070100000C72000081B400000000000000000000000167AE111400000093000000000000000000000000000000000000007C00000000susemanager-schema/upgrade/susemanager-schema-3.2.11-to-susemanager-schema-3.2.12/101-run-refresh-custom-sls-files-task.sql   INSERT INTO rhnTaskQueue (org_id, task_name, task_data)
SELECT id, 'upgrade_satellite_refresh_custom_sls_files', 0
FROM web_customer
WHERE id = 1;
 07070100000C73000081B400000000000000000000000167AE11140000019C000000000000000000000000000000000000007A00000000susemanager-schema/upgrade/susemanager-schema-3.2.11-to-susemanager-schema-3.2.12/102-feature-system-preferences-salt.sql INSERT INTO rhnServerGroupTypeFeature (server_group_type_id, feature_id, created, modified)
SELECT lookup_sg_type('salt_entitled'), lookup_feature_type('ftr_system_preferences'),  current_timestamp, current_timestamp FROM dual
WHERE NOT EXISTS (SELECT 1 FROM rhnServerGroupTypeFeature WHERE server_group_type_id = lookup_sg_type('salt_entitled') AND feature_id = lookup_feature_type('ftr_system_preferences'));

07070100000C74000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005200000000susemanager-schema/upgrade/susemanager-schema-3.2.12-to-susemanager-schema-3.2.13 07070100000C75000081B400000000000000000000000167AE111400000364000000000000000000000000000000000000007100000000susemanager-schema/upgrade/susemanager-schema-3.2.12-to-susemanager-schema-3.2.13/100-add-osimage-build-host.sql  -- osimage_build_host type ----------------------------------------------------

insert into rhnServerGroupType ( id, label, name, permanent, is_base)
   values ( sequence_nextval('rhn_servergroup_type_seq'),
      'osimage_build_host', 'OS Image Build Host',
      'N', 'N'
   );

-- osimage_build_host* compatibilities --

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type)
   values (lookup_server_arch('amd64-redhat-linux'),
           lookup_sg_type('osimage_build_host'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type)
   values (lookup_server_arch('x86_64-redhat-linux'),
           lookup_sg_type('osimage_build_host'));

-- rhnSGTypeBaseAddonCompat

insert into rhnSGTypeBaseAddonCompat (base_id, addon_id)
values (lookup_sg_type('salt_entitled'),
        lookup_sg_type('osimage_build_host'));
07070100000C76000081B400000000000000000000000167AE11140000027A000000000000000000000000000000000000007200000000susemanager-schema/upgrade/susemanager-schema-3.2.12-to-susemanager-schema-3.2.13/101-add-system-type-to-orgs.sql -- create server group for 'osimage_build_host' everywhere
insert into rhnServerGroup ( id, name, description, group_type, org_id )
  select sequence_nextval('rhn_server_group_id_seq'), sgt.name, sgt.name, sgt.id, X.org_id
  from rhnServerGroupType sgt,
     (select distinct msg.org_id
        from rhnServerGroup msg
       where msg.org_id not in (select org_id
                                  from rhnServerGroup sg
                                  join rhnServerGroupType sgt ON sgt.id = sg.group_type
                                 where sgt.label = 'osimage_build_host')
     ) X
  where sgt.label = 'osimage_build_host';
  07070100000C77000081B400000000000000000000000167AE111400001E3B000000000000000000000000000000000000006E00000000susemanager-schema/upgrade/susemanager-schema-3.2.12-to-susemanager-schema-3.2.13/105-proc-create_new_org.sql --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--

create or replace function create_new_org
(
        name_in      in varchar,
        password_in  in varchar
        --org_id_out   out NUMERIC
) returns numeric
as
$$
declare
        ug_type                 numeric;
        group_val               numeric;
        new_org_id              numeric;
        org_id_out		numeric;
begin

        select nextval('web_customer_id_seq') into new_org_id from dual;

        insert into web_customer (
                id, name
        ) values (
                new_org_id, name_in
        );

        select nextval('rhn_user_group_id_seq') into group_val from dual;

        select  id
        into    ug_type
        from    rhnUserGroupType
        where   label = 'org_admin';

        insert into rhnUserGroup (
                id, name,
                description,
                max_members, group_type, org_id
        ) values (
                group_val, 'Organization Administrators',
                'Organization Administrators for Org ' || name_in,
                NULL, ug_type, new_org_id
        );

        select nextval('rhn_user_group_id_seq') into group_val from dual;

        select  id
        into    ug_type
        from    rhnUserGroupType
        where   label = 'system_group_admin';

        insert into rhnUserGroup (
                id, name,
                description,
                max_members, group_type, org_id
        ) values (
                group_val, 'System Group Administrators',
                'System Group Administrators for Org ' || name_in,
                NULL, ug_type, new_org_id
        );


        select nextval('rhn_user_group_id_seq') into group_val from dual;

        select  id
        into    ug_type
        from    rhnUserGroupType
        where   label = 'activation_key_admin';

        insert into rhnUserGroup (
                id, name,
                description,
                max_members, group_type, org_id
        ) values (
                group_val, 'Activation Key Administrators',
                'Activation Key Administrators for Org ' || name_in,
                NULL, ug_type, new_org_id
        );

        select nextval('rhn_user_group_id_seq') into group_val from dual;

        select  id
        into    ug_type
        from    rhnUserGroupType
        where   label = 'channel_admin';

        insert into rhnUserGroup (
                id, name,
                description,
                max_members, group_type, org_id
        ) values (
                group_val, 'Channel Administrators',
                'Channel Administrators for Org ' || name_in,
                NULL, ug_type, new_org_id
        );

	if new_org_id = 1 then
            select nextval('rhn_user_group_id_seq') into group_val from dual;

            select  id
            into    ug_type
            from    rhnUserGroupType
            where   label = 'satellite_admin';

            insert into rhnUserGroup (
                    id, name,
                    description,
                    max_members, group_type, org_id
            ) values (
                    group_val, 'SUSE Manager Administrators',
                    'SUSE Manager Administrators for Org ' || name_in,
                    NULL, ug_type, new_org_id
            );
        end if;

        select nextval('rhn_user_group_id_seq') into group_val from dual;

        select  id
        into    ug_type
        from    rhnUserGroupType
        where   label = 'config_admin';

        insert into rhnUserGroup (
                id, name,
                description,
                max_members, group_type, org_id
        ) values (
                group_val, 'Configuration Administrators',
                'Configuration Administrators for Org ' || name_in,
                NULL, ug_type, new_org_id
        );

        select nextval('rhn_user_group_id_seq') into group_val from dual;

        select  id
        into    ug_type
        from    rhnUserGroupType
        where   label = 'image_admin';

        insert into rhnUserGroup (
                id, name,
                description,
                max_members, group_type, org_id
        ) values (
                group_val, 'Image Administrators',
                'Image Administrators for Org ' || name_in,
                NULL, ug_type, new_org_id
        );

        -- there aren't any users yet, so we don't need to update
        -- rhnUserServerPerms

        insert into rhnServerGroup
                ( id, name, description, group_type, org_id )
                select nextval('rhn_server_group_id_seq'), sgt.name, sgt.name,
                        sgt.id, new_org_id
                from rhnServerGroupType sgt
                where sgt.label = 'bootstrap_entitled';

        insert into rhnServerGroup
                ( id, name, description, group_type, org_id )
                select nextval('rhn_server_group_id_seq'), sgt.name, sgt.name,
                        sgt.id, new_org_id
                from rhnServerGroupType sgt
                where sgt.label = 'enterprise_entitled';

        insert into rhnServerGroup
                ( id, name, description, group_type, org_id )
                select nextval('rhn_server_group_id_seq'), sgt.name, sgt.name,
                        sgt.id, new_org_id
                from rhnServerGroupType sgt
                where sgt.label = 'salt_entitled';

        insert into rhnServerGroup
                ( id, name, description, group_type, org_id )
                select nextval('rhn_server_group_id_seq'), sgt.name, sgt.name,
                        sgt.id, new_org_id
                from rhnServerGroupType sgt
                where sgt.label = 'foreign_entitled';

        insert into rhnServerGroup
                ( id, name, description, group_type, org_id )
                select nextval('rhn_server_group_id_seq'), sgt.name, sgt.name,
                        sgt.id, new_org_id
                from rhnServerGroupType sgt
                where sgt.label = 'virtualization_host';

        insert into rhnServerGroup
                ( id, name, description, group_type, org_id )
                select nextval('rhn_server_group_id_seq'), sgt.name, sgt.name,
                        sgt.id, new_org_id
                from rhnServerGroupType sgt
                where sgt.label = 'container_build_host';

        insert into rhnServerGroup
                ( id, name, description, group_type, org_id )
                select nextval('rhn_server_group_id_seq'), sgt.name, sgt.name,
                        sgt.id, new_org_id
                from rhnServerGroupType sgt
                where sgt.label = 'osimage_build_host';

        insert into suseImageStore (id, label, uri, store_type_id, org_id)
        values (
            nextval('suse_imgstore_id_seq'),
            'SUSE Manager OS Image Store',
            new_org_id || '/',
            (SELECT id FROM suseImageStoreType WHERE label = 'os_image'),
            new_org_id
        );

        org_id_out := new_org_id;

	-- Returning the value of OUT parameter
        return org_id_out;

end;
$$
language plpgsql;
 07070100000C78000081B400000000000000000000000167AE111400003159000000000000000000000000000000000000006F00000000susemanager-schema/upgrade/susemanager-schema-3.2.12-to-susemanager-schema-3.2.13/110-pkb-rhn_entitlements.sql    --
-- Copyright (c) 2008--2015 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

-- create schema rhn_entitlements;

-- setup search_path so that these functions are created in appropriate schema.
update pg_settings set setting = 'rhn_entitlements,' || setting where name = 'search_path';

   create or replace function find_compatible_sg (
      server_id_in in numeric,
      type_label_in in varchar
   )
   returns numeric
as $$
    declare
      servergroups cursor for
         select sg.id
           from rhnServerGroupType             sgt,
                rhnServerGroup                 sg,
                rhnServer                     s,
                rhnServerServerGroupArchCompat ssgac
          where s.id = server_id_in
            and s.org_id = sg.org_id
            and sgt.label = type_label_in
            and sg.group_type = sgt.id
            and ssgac.server_group_type = sgt.id
            and ssgac.server_arch_id = s.server_arch_id
            and not exists (
                     select 1
                      from rhnServerGroupMembers sgm
                     where sgm.server_group_id = sg.id
                       and sgm.server_id = s.id);


   begin
      for servergroup in servergroups loop
         return servergroup.id;
      end loop;

      --no servergroup found
      return NULL;
   end$$
language plpgsql;


    create or replace function entitlement_grants_service (
        entitlement_in in varchar,
        service_level_in in varchar
    ) returns numeric
as $$
    begin
        if service_level_in = 'management' then
            if entitlement_in = 'enterprise_entitled' or entitlement_in = 'salt_entitled' then
                return 1;
            else
                return 0;
            end if;
        elsif service_level_in = 'updates' then
            return 1;
        else
            return 0;
        end if;
    end$$
language plpgsql;

   create or replace function can_entitle_server (
      server_id_in   in numeric,
      type_label_in  in varchar
   )
   returns numeric
as $$
    declare
      addon_servergroups cursor (base_label_in varchar,
                                 addon_label_in varchar) for
         select
            addon_id
         from
            rhnSGTypeBaseAddonCompat
         where base_id = lookup_sg_type (base_label_in)
           and addon_id = lookup_sg_type (addon_label_in);

      previous_ent        varchar[];
      is_base_in          char   := 'N';
      is_base_current     char   := 'N';
      i                   numeric := 0;
      sgid                numeric := 0;

   begin

      previous_ent := rhn_entitlements.get_server_entitlement(server_id_in);
      RAISE NOTICE 'can_entitle_server - % - % prev ents: %', server_id_in, type_label_in, previous_ent;

      select distinct is_base
      into is_base_in
      from rhnServerGroupType
      where label = type_label_in;

      if array_upper(previous_ent, 1) is null or array_upper(previous_ent, 1) = 0 then
         if is_base_in = 'Y' then
            sgid := rhn_entitlements.find_compatible_sg (server_id_in, type_label_in);
            if sgid is not null then
              -- rhn_server.insert_into_servergroup (server_id_in, sgid);
              return 1;
            else
              -- rhn_exception.raise_exception ('invalid_base_entitlement');
              RAISE NOTICE 'invalid_base_entitlement - no compatible server group';
              return 0;
            end if;
         else
            -- rhn_exception.raise_exception ('invalid_base_entitlement');
            RAISE NOTICE 'invalid_base_entitlement - not a base entitlement';
            return 0;
         end if;

      -- there are previous ents, first make sure we're not trying to entitle a base ent
      elsif is_base_in = 'Y' then
         -- rhn_exception.raise_exception ('invalid_addon_entitlement');
         RAISE NOTICE 'invalid_addon_entitlement - found another base';
         return 0;

      -- it must be an addon, so proceed with the entitlement
      else

         -- find the servers base ent
         is_base_current := 'N';
         i := 0;
         while is_base_current = 'N' and i < array_upper(previous_ent, 1)
         loop
            i := i + 1;
            select is_base
            into is_base_current
            from rhnServerGroupType
            where label = previous_ent[i];
         end loop;

         -- never found a base ent, that would be strange
         if is_base_current  = 'N' then
            -- rhn_exception.raise_exception ('invalid_base_entitlement');
            RAISE NOTICE 'invalid_base_entitlement - never found a base';
            return 0;
         end if;

         -- this for loop verifies the validity of the addon path
         for addon_servergroup in addon_servergroups  (previous_ent[i], type_label_in) loop
            -- find an appropriate sgid for the addon and entitle the server
            sgid := rhn_entitlements.find_compatible_sg (server_id_in, type_label_in);
            if sgid is not null then
               -- rhn_server.insert_into_servergroup (server_id_in, sgid);
               return 1;
            else
               -- rhn_exception.raise_exception ('invalid_addon_entitlement');
               RAISE NOTICE 'invalid_addon_entitlement - no server group found';
               return 0;
            end if;
         end loop;

      end if;
      RAISE NOTICE 'final error';
      return 0;

   end$$
language plpgsql;

   create or replace function can_switch_base (
      server_id_in   in    integer,
      type_label_in  in    varchar
   )
   returns numeric
as $$
   declare
      type_label_in_is_base   char(1);
      sgid                    numeric;

   begin

       select is_base into type_label_in_is_base
       from rhnServerGroupType
       where label = type_label_in;

       if not found then
          perform rhn_exception.raise_exception ( 'invalid_entitlement' );
       end if;

      if type_label_in_is_base = 'N' then
         perform rhn_exception.raise_exception ( 'invalid_entitlement' );
      else
         sgid := rhn_entitlements.find_compatible_sg ( server_id_in,
                                                       type_label_in );
         if sgid is not null then
           return 1;
         else
           return 0;
         end if;
      end if;

   end$$
language plpgsql;

    create or replace function entitle_server (
        server_id_in in numeric,
        type_label_in in varchar
    ) returns void
as $$
    declare
      sgid  numeric := 0;

    begin

      if rhn_entitlements.can_entitle_server(server_id_in,
                                             type_label_in) = 1 then
         sgid := rhn_entitlements.find_compatible_sg (server_id_in,
                                                      type_label_in);
         if sgid is not null then
            insert into rhnServerHistory ( id, server_id, summary, details )
            values ( nextval('rhn_event_id_seq'), server_id_in,
                     'added system entitlement ',
                      case type_label_in
                       when 'enterprise_entitled' then 'Management'
                       when 'bootstrap_entitled' then 'Bootstrap'
                       when 'salt_entitled' then 'Salt'
                       when 'foreign_entitled' then 'Foreign'
                       when 'virtualization_host' then 'Virtualization'
                       when 'container_build_host' then 'Container'
                       when 'osimage_build_host' then 'OS Image'
                      end  );

            perform rhn_server.insert_into_servergroup (server_id_in, sgid);

         else
            perform rhn_exception.raise_exception ('no_available_server_group');
         end if;
      else
         perform rhn_exception.raise_exception ('invalid_entitlement');
      end if;
   end$$
language plpgsql;

    create or replace function remove_server_entitlement (
        server_id_in in numeric,
        type_label_in in varchar
    ) returns void
as $$
    declare
      group_id numeric;
      type_is_base char;
    begin

        select  sg.id, sgt.is_base
        into group_id, type_is_base
        from    rhnServerGroupType sgt,
            rhnServerGroup sg,
                rhnServerGroupMembers sgm,
                rhnServer s
        where   s.id = server_id_in
            and s.id = sgm.server_id
            and sgm.server_group_id = sg.id
            and sg.org_id = s.org_id
            and sgt.label = type_label_in
            and sgt.id = sg.group_type;

        if not found then
          perform rhn_exception.raise_exception('invalid_server_group_member');
        end if;

      if ( type_is_base = 'Y' ) then
         -- unentitle_server should handle everything, don't really need to do anything else special here
         perform rhn_entitlements.unentitle_server ( server_id_in );
      else

         insert into rhnServerHistory ( id, server_id, summary, details )
         values ( nextval('rhn_event_id_seq'), server_id_in,
                  'removed system entitlement ',
                   case type_label_in
                    when 'enterprise_entitled' then 'Management'
                    when 'bootstrap_entitled' then 'Bootstrap'
                    when 'salt_entitled' then 'Salt'
                    when 'foreign_entitled' then 'Foreign'
                    when 'virtualization_host' then 'Virtualization'
                    when 'container_build_host' then 'Container'
                    when 'osimage_build_host' then 'OS Image'
                   end  );

         perform rhn_server.delete_from_servergroup(server_id_in, group_id);

      end if;

    end$$
language plpgsql;

    create or replace function unentitle_server (
        server_id_in in numeric
    ) returns void
as $$
    declare
      servergroups cursor for
         select distinct sgt.label, sg.id server_group_id
         from  rhnServerGroupType sgt,
               rhnServerGroup sg,
               rhnServer s,
               rhnServerGroupMembers sgm
         where s.id = server_id_in
            and s.org_id = sg.org_id
            and sg.group_type = sgt.id
            and sgm.server_group_id = sg.id
            and sgm.server_id = s.id;

   begin

      for servergroup in servergroups loop

         insert into rhnServerHistory ( id, server_id, summary, details )
         values ( nextval('rhn_event_id_seq'), server_id_in,
                  'removed system entitlement ',
                   case servergroup.label
                    when 'enterprise_entitled' then 'Management'
                    when 'bootstrap_entitled' then 'Bootstrap'
                    when 'salt_entitled' then 'Salt'
                    when 'foreign_entitled' then 'Foreign'
                    when 'virtualization_host' then 'Virtualization'
                    when 'container_build_host' then 'Container'
                    when 'osimage_build_host' then 'OS Image'
                   end  );

         perform rhn_server.delete_from_servergroup(server_id_in,
                                            servergroup.server_group_id );
      end loop;

   end$$
language plpgsql;


    create or replace function get_server_entitlement (
        server_id_in in numeric
    ) returns varchar[]
as $$
    declare
        server_groups cursor for
            select  sgt.label
            from    rhnServerGroupType      sgt,
                    rhnServerGroup          sg,
                    rhnServerGroupMembers   sgm
            where   1=1
                and sgm.server_id = server_id_in
                and sg.id = sgm.server_group_id
                and sgt.id = sg.group_type;

         ent_array varchar[];

    begin

      ent_array := '{}';

      for sg in server_groups loop
         ent_array := ent_array || sg.label;
      end loop;

      return ent_array;

    end$$
language plpgsql;

-- restore the original setting
update pg_settings set setting = overlay( setting placing '' from 1 for (length('rhn_entitlements')+1) ) where name = 'search_path';
   07070100000C79000081B400000000000000000000000167AE1114000000B6000000000000000000000000000000000000007B00000000susemanager-schema/upgrade/susemanager-schema-3.2.12-to-susemanager-schema-3.2.13/500-update-image-store-uq-constraint.sql    
DROP INDEX IF EXISTS suse_imgstore_label_uq;
DROP INDEX IF EXISTS suse_imgstore_oid_label_uq;

CREATE UNIQUE INDEX suse_imgstore_oid_label_uq
    ON suseImageStore (org_id, label);
  07070100000C7A000081B400000000000000000000000167AE111400000289000000000000000000000000000000000000007A00000000susemanager-schema/upgrade/susemanager-schema-3.2.12-to-susemanager-schema-3.2.13/501-add-suse-manager-os-image-store.sql INSERT INTO suseImageStoreType (id, label, name) VALUES
    (sequence_nextval('suse_imgstore_type_id_seq'), 'os_image', 'OS Image');

INSERT INTO suseImageStore (id, label, uri, store_type_id, org_id)
SELECT
    sequence_nextval('suse_imgstore_id_seq'),
    'SUSE Manager OS Image Store',
    wc.id || '/',
    (SELECT id FROM suseImageStoreType WHERE label = 'os_image'),
    wc.id
FROM web_customer wc
WHERE wc.id NOT IN (SELECT org_id
                    FROM suseImageStore
                    WHERE store_type_id = (SELECT id FROM suseImageStoreType WHERE label = 'os_image')
                        AND label = 'suse-manager-os-image-store');
   07070100000C7B000081B400000000000000000000000167AE11140000036A000000000000000000000000000000000000006E00000000susemanager-schema/upgrade/susemanager-schema-3.2.12-to-susemanager-schema-3.2.13/600-add-susekiwiprofile.sql --
-- Copyright (c) 2018 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

CREATE TABLE suseKiwiProfile
(
    profile_id  NUMERIC NOT NULL
                  CONSTRAINT suse_kiwi_prid_fk
                     REFERENCES suseImageProfile (profile_id)
                     ON DELETE CASCADE,
    path        VARCHAR(1024) NOT NULL
)

;
  07070100000C7C000081B400000000000000000000000167AE1114000000B5000000000000000000000000000000000000007D00000000susemanager-schema/upgrade/susemanager-schema-3.2.12-to-susemanager-schema-3.2.13/601-update-image-profile-uq-constraint.sql  
DROP INDEX IF EXISTS suse_imgprof_label_uq;
DROP INDEX IF EXISTS suse_imgprof_oid_label_uq;

CREATE UNIQUE INDEX suse_imgprof_oid_label_uq
    ON suseImageProfile (org_id, label);
   07070100000C7D000081B400000000000000000000000167AE111400000047000000000000000000000000000000000000007700000000susemanager-schema/upgrade/susemanager-schema-3.2.12-to-susemanager-schema-3.2.13/700-modify-rhnactionimageinspect.sql    ALTER TABLE rhnActionImageInspect ADD COLUMN build_action_id NUMERIC;

 07070100000C7E000081B400000000000000000000000167AE11140000003F000000000000000000000000000000000000007500000000susemanager-schema/upgrade/susemanager-schema-3.2.12-to-susemanager-schema-3.2.13/800-suseImageInfo-null-version.sql  
ALTER TABLE suseImageInfo ALTER COLUMN version DROP NOT NULL;
 07070100000C7F000081B400000000000000000000000167AE111400000096000000000000000000000000000000000000007300000000susemanager-schema/upgrade/susemanager-schema-3.2.12-to-susemanager-schema-3.2.13/801-suseImageInfo-image-type.sql    
ALTER TABLE suseImageInfo ADD image_type VARCHAR(32) NOT NULL DEFAULT 'dockerfile';
ALTER TABLE suseImageInfo ALTER COLUMN image_type DROP DEFAULT;

  07070100000C80000081B400000000000000000000000167AE1114000005E1000000000000000000000000000000000000007700000000susemanager-schema/upgrade/susemanager-schema-3.2.12-to-susemanager-schema-3.2.13/802-suseImageOverview-image-type.sql    DROP VIEW suseImageOverview;

CREATE OR REPLACE VIEW suseImageOverview
(
    org_id,
    image_id,
    image_name,
    image_version,
    image_type,
    checksum_id,
    modified,
    image_arch_name,
    build_action_id,
    inspect_action_id,
    profile_id,
    store_id,
    build_server_id,
    curr_revision_num,
    external_image,
    security_errata,
    bug_errata,
    enhancement_errata,
    outdated_packages,
    installed_packages
)
as
select
    i.org_id, i.id, i.name, i.version, i.image_type, i.checksum_id, i.modified,
    ( select name from rhnServerArch where id = i.image_arch_id), i.build_action_id,
    i.inspect_action_id, i.profile_id, i.store_id, i.build_server_id, i.curr_revision_num,
    i.external_image,
    ( select count(*) from rhnImageErrataTypeView ietv
      where
            ietv.image_id = i.id
        and ietv.errata_type = 'Security Advisory'),
    ( select count(*) from rhnImageErrataTypeView ietv
      where
            ietv.image_id = i.id
        and ietv.errata_type = 'Bug Fix Advisory'),
    ( select count(*) from rhnImageErrataTypeView ietv
      where
            ietv.image_id = i.id
        and ietv.errata_type = 'Product Enhancement Advisory'),
    ( select count(distinct p.name_id) from rhnPackage p, rhnImageNeededPackageCache inpc
      where
            inpc.image_id = i.id
        and p.id = inpc.package_id),
    (select count(*) from suseImageInfoPackage iip
     where
            iip.image_info_id = i.id)
from
    suseImageInfo i
;
   07070100000C81000081B400000000000000000000000167AE11140000019E000000000000000000000000000000000000007700000000susemanager-schema/upgrade/susemanager-schema-3.2.12-to-susemanager-schema-3.2.13/900-ftr-auto-errata-updates-salt.sql    INSERT INTO rhnServerGroupTypeFeature (server_group_type_id, feature_id, created, modified)
SELECT lookup_sg_type('salt_entitled'), lookup_feature_type('ftr_auto_errata_updates'),  current_timestamp, current_timestamp FROM dual
WHERE NOT EXISTS (SELECT 1 FROM rhnServerGroupTypeFeature WHERE server_group_type_id = lookup_sg_type('salt_entitled') AND feature_id = lookup_feature_type('ftr_auto_errata_updates'));

  07070100000C82000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005200000000susemanager-schema/upgrade/susemanager-schema-3.2.13-to-susemanager-schema-3.2.14 07070100000C83000081B400000000000000000000000167AE111400000059000000000000000000000000000000000000007C00000000susemanager-schema/upgrade/susemanager-schema-3.2.13-to-susemanager-schema-3.2.14/100-rhnServerNetInterfaceHwAddressIdx.sql   CREATE INDEX rhn_srv_net_iface_hw_addr_idx
    ON rhnServerNetInterface (hw_addr)
    ;

   07070100000C84000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005200000000susemanager-schema/upgrade/susemanager-schema-3.2.14-to-susemanager-schema-3.2.15 07070100000C85000081B400000000000000000000000167AE11140000068C000000000000000000000000000000000000007000000000susemanager-schema/upgrade/susemanager-schema-3.2.14-to-susemanager-schema-3.2.15/100-notifications-cleanup.sql   INSERT INTO rhnTaskoBunch (id, name, description, org_bunch)
    SELECT sequence_nextval('rhn_tasko_bunch_id_seq'), 'notifications-cleanup-bunch', 'Cleanup expired notification messages', null
    FROM dual WHERE NOT EXISTS (
        SELECT 1 FROM rhnTaskoBunch WHERE
        name='notifications-cleanup-bunch'
    );

INSERT INTO rhnTaskoSchedule (id, job_label, bunch_id, active_from, cron_expr)
    SELECT sequence_nextval('rhn_tasko_schedule_id_seq'), 'notifications-cleanup-default',
        (SELECT id FROM rhnTaskoBunch WHERE name='notifications-cleanup-bunch'),
        current_timestamp, '0 0 0 ? * *'
    FROM dual WHERE NOT EXISTS (
        SELECT 1 FROM rhnTaskoSchedule WHERE
        job_label='notifications-cleanup-default'
    );

INSERT INTO rhnTaskoTask (id, name, class)
    SELECT sequence_nextval('rhn_tasko_task_id_seq'), 'notifications-cleanup', 'com.redhat.rhn.taskomatic.task.NotificationsCleanup'
    FROM dual WHERE NOT EXISTS (
        SELECT 1 FROM rhnTaskoTask WHERE
        name='notifications-cleanup'
    );

INSERT INTO rhnTaskoTemplate (id, bunch_id, task_id, ordering, start_if)
    SELECT sequence_nextval('rhn_tasko_template_id_seq'),
                        (SELECT id FROM rhnTaskoBunch WHERE name='notifications-cleanup-bunch'),
                        (SELECT id FROM rhnTaskoTask WHERE name='notifications-cleanup'),
                        0,
                        null
    FROM dual WHERE NOT EXISTS (
        SELECT 1 FROM rhnTaskoTemplate WHERE
        bunch_id=(SELECT id FROM rhnTaskoBunch WHERE name='notifications-cleanup-bunch') AND
        task_id=(SELECT id FROM rhnTaskoTask WHERE name='notifications-cleanup')
    );

07070100000C86000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005200000000susemanager-schema/upgrade/susemanager-schema-3.2.15-to-susemanager-schema-3.2.16 07070100000C87000081B400000000000000000000000167AE1114000000EA000000000000000000000000000000000000006F00000000susemanager-schema/upgrade/susemanager-schema-3.2.15-to-susemanager-schema-3.2.16/001-create-susesaltevent.sql    
CREATE TABLE IF NOT EXISTS suseSaltEvent (
  id SERIAL PRIMARY KEY,
  minion_id CHARACTER VARYING(256),
  data TEXT NOT NULL
);

CREATE INDEX IF NOT EXISTS suse_salt_event_minion_id_idx
  ON suseSaltEvent (minion_id NULLS LAST, id);
  07070100000C88000081B400000000000000000000000167AE11140000056D000000000000000000000000000000000000006C00000000susemanager-schema/upgrade/susemanager-schema-3.2.15-to-susemanager-schema-3.2.16/001-suseSCCRepository.sql   --
-- Copyright (c) 2014--2018 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

delete from susesccrepository;

ALTER TABLE suseSCCRepository
  ALTER COLUMN scc_id SET NOT NULL,
  ALTER COLUMN name SET NOT NULL,
  ALTER COLUMN description SET NOT NULL,
  ALTER COLUMN url SET NOT NULL;
  
alter table suseSCCRepository drop column if exists credentials_id;
alter table suseSCCRepository add column if not exists
    signed CHAR(1) DEFAULT ('N') NOT NULL;

alter table suseSCCRepository drop CONSTRAINT if exists suse_sccrepo_sig_ck;
alter table suseSCCRepository add CONSTRAINT suse_sccrepo_sig_ck CHECK (signed in ('Y', 'N'));

DROP INDEX if exists suse_sccrepo_sccid_idx;
CREATE UNIQUE INDEX if not exists suse_sccrepo_sccid_uq
    ON suseSCCRepository (scc_id);

CREATE INDEX if not exists suse_sccrepo_url_idx
    ON suseSCCRepository (url);
   07070100000C89000081B400000000000000000000000167AE1114000006B6000000000000000000000000000000000000007300000000susemanager-schema/upgrade/susemanager-schema-3.2.15-to-susemanager-schema-3.2.16/002-suseProductSCCRepository.sql    
CREATE TABLE if not exists
suseProductSCCRepository
(
    id                     NUMERIC NOT NULL primary key,
    product_id             NUMERIC NOT NULL
                                  CONSTRAINT suse_prdrepo_pid_fk
                                  REFERENCES suseProducts (id)
                                  ON DELETE CASCADE,
    root_product_id        NUMERIC NOT NULL
                                  CONSTRAINT suse_prdrepo_rpid_fk
                                  REFERENCES suseProducts (id)
                                  ON DELETE CASCADE,
    repo_id                NUMERIC NOT NULL
                                  CONSTRAINT suse_prdrepo_rid_fk
                                  REFERENCES suseSCCRepository (id)
                                  ON DELETE CASCADE,
    channel_label          VARCHAR(128) not null,
    parent_channel_label   VARCHAR(128),
    channel_name           VARCHAR(256) not null,
    mandatory              CHAR(1) DEFAULT ('N') NOT NULL
                                   CONSTRAINT suse_prdrepo_mand_ck
                                   CHECK (mandatory in ('Y', 'N')),
    update_tag             VARCHAR(128),
    created                TIMESTAMPTZ
                           DEFAULT (current_timestamp) NOT NULL,
    modified               TIMESTAMPTZ
                           DEFAULT (current_timestamp) NOT NULL
);

CREATE SEQUENCE if not exists suse_prdrepo_id_seq START WITH 1;

DROP INDEX if exists suse_prdrepo_pid_rid_cl_uq;
CREATE UNIQUE INDEX if not exists suse_prdrepo_pid_rpid_rid_uq
ON suseProductSCCRepository (product_id, root_product_id, repo_id);

CREATE INDEX if not exists suse_prdrepo_chl_idx
ON suseProductSCCRepository (channel_label);
  07070100000C8A000081B400000000000000000000000167AE1114000002A1000000000000000000000000000000000000007400000000susemanager-schema/upgrade/susemanager-schema-3.2.15-to-susemanager-schema-3.2.16/003-change-suseProductChannel.sql   
DELETE FROM suseProductChannel WHERE channel_id IS NULL;

ALTER TABLE suseProductChannel ALTER COLUMN channel_id SET NOT NULL;

alter table suseProductChannel drop column if exists channel_label;
alter table suseProductChannel drop column if exists parent_channel_label;

alter table suseProductChannel add column if not exists
    mandatory  CHAR(1) DEFAULT ('N') NOT NULL;

alter table suseProductChannel drop CONSTRAINT if exists spc_mand_ck;
alter table suseProductChannel add CONSTRAINT spc_mand_ck CHECK (mandatory in ('Y', 'N'));

drop index if exists suse_prd_chan_label_uq;
drop index if exists suse_prd_chan_pcl_idx;
drop index if exists suse_prd_chan_chan_idx;
   07070100000C8B000081B400000000000000000000000167AE11140000010B000000000000000000000000000000000000006E00000000susemanager-schema/upgrade/susemanager-schema-3.2.15-to-susemanager-schema-3.2.16/004-change-suseProducts.sql 
alter table suseProducts add column if not exists release_stage VARCHAR(10) DEFAULT ('released') NOT NULL;
alter table suseProducts add column if not exists description VARCHAR(4000);

CREATE UNIQUE INDEX if not exists suseprod_pdid_uq
ON suseProducts (product_id);
 07070100000C8C000081B400000000000000000000000167AE111400000041000000000000000000000000000000000000006A00000000susemanager-schema/upgrade/susemanager-schema-3.2.15-to-susemanager-schema-3.2.16/005-drop-productUrl.sql 
alter table rhnChannelFamily drop column if exists product_url;
   07070100000C8D000081B400000000000000000000000167AE111400000643000000000000000000000000000000000000007000000000susemanager-schema/upgrade/susemanager-schema-3.2.15-to-susemanager-schema-3.2.16/006-suseSCCRepositoryAuth.sql   --
-- Copyright (c) 2018 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

CREATE TABLE if not exists suseSCCRepositoryAuth
(
    id             NUMERIC NOT NULL PRIMARY KEY,
    repo_id        NUMERIC NOT NULL
                       CONSTRAINT suse_sccrepoauth_rid_fk
		       REFERENCES suseSCCRepository (id),
--                     NO ON DELETE !
    credentials_id NUMERIC NULL
                       CONSTRAINT suse_sccrepo_credsid_fk
                       REFERENCES suseCredentials (id),
--                     NO ON DELETE !,
    source_id      NUMERIC NULL
                         CONSTRAINT suse_sccrepo_src_id_fk
                             REFERENCES rhnContentSource (id)
                             ON DELETE SET NULL,
    auth_type      VARCHAR(10) NOT NULL,
    auth           VARCHAR(4000) NULL,
    created        TIMESTAMPTZ
                       DEFAULT (current_timestamp) NOT NULL,
    modified       TIMESTAMPTZ
                       DEFAULT (current_timestamp) NOT NULL
) ;

CREATE SEQUENCE if not exists suse_sccrepoauth_id_seq;
 07070100000C8E000081B400000000000000000000000167AE1114000002C1000000000000000000000000000000000000006A00000000susemanager-schema/upgrade/susemanager-schema-3.2.15-to-susemanager-schema-3.2.16/007-suseManagerInfo.sql --
-- Copyright (c) 2018 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

CREATE TABLE if not exists suseManagerInfo
(
    last_mgr_sync_refresh   TIMESTAMPTZ
);
   07070100000C8F000081B400000000000000000000000167AE111400000D4C000000000000000000000000000000000000006B00000000susemanager-schema/upgrade/susemanager-schema-3.2.15-to-susemanager-schema-3.2.16/200-suseUserRoleView.sql    --
-- Copyright (c) 2018 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--

CREATE OR REPLACE VIEW
suseChannelUserRoleView
AS
  SELECT
    combination.channel_id,
    combination.user_id,
    combination.role,
    CASE
      -- if channel is in an org trusted by the user's org, and if the channel itself is shared between the two, then user can subscribe it
      WHEN combination.role = 'subscribe' AND combination.user_id IN (
        SELECT u.id
        FROM web_contact u
          JOIN rhnSharedChannelView s ON s.org_trust_id = u.org_id
        WHERE channel_id = combination.channel_id
      )
        THEN NULL
      -- otherwise, if channel is not in user's org, then user can't manage it
      WHEN combination.role = 'manage' AND combination.channel_org_id IS NULL OR combination.channel_org_id <> combination.user_org_id
        THEN 'channel_not_owned'
      -- otherwise, if channel is in a family without permissions for the user's org, then user can't subscribe it
      WHEN combination.role = 'subscribe' AND combination.user_org_id NOT IN (
        SELECT cfp.org_id
          FROM rhnChannelFamilyMembers cfm
            JOIN rhnOrgChannelFamilyPermissions cfp ON cfp.channel_family_id = cfm.channel_family_id
            WHERE cfm.channel_id = combination.channel_id
      )
        THEN 'channel_not_available'
      -- otherwise, if user is a channel admin or an org admin, he can both manage and subscribe it
      WHEN combination.user_id IN (
        SELECT u.id
          FROM web_contact u
            JOIN rhnUserGroupMembers m ON m.user_id = u.id
            JOIN rhnUserGroup g ON g.id = m.user_group_id
            JOIN rhnUserGroupType t ON t.id = g.group_type
          WHERE t.label = 'channel_admin' OR t.label = 'org_admin'
      )
        THEN NULL
      -- otherwise, if channel does not have the "not_globally_subscribable" bit set, user can subscribe it
      WHEN combination.role = 'subscribe' AND combination.channel_id NOT IN (
        SELECT ocs.channel_id
        FROM rhnOrgChannelSettings ocs
          JOIN rhnOrgChannelSettingsType ocst ON ocst.id = ocs.setting_id
        WHERE ocst.label = 'not_globally_subscribable' AND ocs.org_id = combination.user_org_id
      )
        THEN NULL
      -- otherwise, user might have an explicit permission on this channel
      WHEN combination.role IN (
        SELECT cpr.label
          FROM rhnChannelPermission cp
            JOIN rhnChannelPermissionRole cpr ON cpr.id = cp.role_id
          WHERE cp.channel_id = combination.channel_id AND cp.user_id = combination.user_id
      )
        THEN NULL
        -- otherwise, user can't either manage nor subscribe the channel
        ELSE 'direct_permission'
    END AS deny_reason
    FROM
      (SELECT
          c.id AS channel_id,
          c.org_id AS channel_org_id,
          u.id AS user_id,
          u.org_id AS user_org_id,
          r.label AS role
          FROM rhnChannel c, web_contact u, rhnChannelPermissionRole r
      ) combination
    -- ORDER BY channel_id, user_id, role, result
;
07070100000C90000081B400000000000000000000000167AE11140000719B000000000000000000000000000000000000006A00000000susemanager-schema/upgrade/susemanager-schema-3.2.15-to-susemanager-schema-3.2.16/201-rhn_channel.pkb.sql --
-- Copyright (c) 2008--2018 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--
--
--
--

-- create schema rhn_channel;

--update pg_setting
update pg_settings set setting = 'rhn_channel,' || setting where name = 'search_path';

    -- this "emulates" cursor server_base_subscriptions defined in oracle/rhn_channel.pks
    create or replace function server_base_subscriptions(server_id_in NUMERIC)
    returns boolean as $$
    begin
      return exists(SELECT C.id FROM rhnChannel C, rhnServerChannel SC
		    WHERE C.id = SC.channel_id
		      AND SC.server_id = server_id_in
		      AND C.parent_channel IS NULL);
    end$$ language plpgsql;

    -- this "emulates" cursor server_base_subscriptions defined in oracle/rhn_channel.pks
    create or replace function check_server_subscription(server_id_in NUMERIC, channel_id_in NUMERIC)
    returns boolean as $$
    begin
      return exists(SELECT channel_id FROM rhnServerChannel WHERE server_id = server_id_in AND channel_id = channel_id_in);
    end$$ language plpgsql;


    CREATE OR REPLACE FUNCTION subscribe_server(server_id_in IN NUMERIC, channel_id_in NUMERIC, immediate_in NUMERIC default 1, user_id_in in numeric default null) returns void
    AS $$
    declare
        channel_parent_val      rhnChannel.parent_channel%TYPE;
        parent_subscribed       BOOLEAN;
        server_has_base_chan    BOOLEAN;
        server_already_in_chan  BOOLEAN;
        channel_family_id_val   NUMERIC;
        allowed                 numeric;
    BEGIN
        if user_id_in is not null then
            allowed := rhn_channel.user_role_check(channel_id_in, user_id_in, 'subscribe');
        else
            allowed := 1;
        end if;

        if allowed = 0 then
            perform rhn_exception.raise_exception('no_subscribe_permissions');
        end if;
        
        server_already_in_chan := rhn_channel.check_server_subscription(server_id_in, channel_id_in);

        IF server_already_in_chan
        THEN
            RETURN;
        END IF;

        SELECT parent_channel INTO channel_parent_val FROM rhnChannel WHERE id = channel_id_in;

        IF channel_parent_val IS NOT NULL
        THEN
            -- child channel; if attempting to cross-subscribe a child to the wrong base, silently ignore
            parent_subscribed := rhn_channel.check_server_subscription(server_id_in, channel_parent_val);

            IF NOT parent_subscribed
            THEN
                RETURN;
            END IF;
        ELSE
            -- base channel
            server_has_base_chan := rhn_channel.server_base_subscriptions(server_id_in);

            IF server_has_base_chan
            THEN
                perform rhn_exception.raise_exception('channel_server_one_base');
            END IF;
        END IF;

        channel_family_id_val := rhn_channel.family_for_channel(channel_id_in);
        IF channel_family_id_val IS NULL
        THEN
            perform rhn_exception.raise_exception('channel_subscribe_no_family');
        END IF;

        insert into rhnServerHistory (id,server_id,summary,details) (
            select  nextval('rhn_event_id_seq'),
                    server_id_in,
                    'subscribed to channel ' || SUBSTR(c.label, 0, 106),
                    c.label
            from    rhnChannel c
            where   c.id = channel_id_in
        );

        INSERT INTO rhnServerChannel (server_id, channel_id) VALUES (server_id_in, channel_id_in);

        perform queue_server(server_id_in, immediate_in);

        update rhnServer
           set channels_changed = current_timestamp
         where id = server_id_in;
    END$$ language plpgsql;

    create or replace function guess_server_base(
        server_id_in in numeric
    ) RETURNS numeric as $$
    declare
        server_cursor cursor for
            select s.server_arch_id, s.release, s.org_id
              from rhnServer s
             where s.id = server_id_in;
    -- Cursor that fetches all the possible base channels for a
    -- (server_arch_id, release, org_id) combination
        base_channel_cursor cursor(
                release_in varchar,
                server_arch_id_in numeric,
                org_id_in numeric
        ) for
                select distinct c.*
                from    rhnOrgDistChannelMap                       odcm,
                                rhnServerChannelArchCompat      scac,
                                rhnChannel                                      c
                where   c.parent_channel is null
                        and c.id = odcm.channel_id
                        and c.channel_arch_id = odcm.channel_arch_id
                        and odcm.release = release_in
                        and odcm.for_org_id = org_id_in
                        and scac.server_arch_id = server_arch_id_in
                        and scac.channel_arch_id = c.channel_arch_id;

    begin
        for s in server_cursor loop
            for channel in base_channel_cursor(s.release,
                s.server_arch_id, s.org_id)
            loop
                return channel.id;
            end loop;
        end loop;
        -- Server not found, or no base channel applies to it
        return null;
    end$$ language plpgsql;

    -- Private function
    create or replace function normalize_server_arch(server_arch_in in varchar)
    returns varchar
    as $$
    declare
        suffix VARCHAR(128) := '-redhat-linux';
    begin
        if server_arch_in is NULL then
            return NULL;
        end if;
        if position('-' IN server_arch_in) > 0
        then
            -- Suffix already present
            return server_arch_in;
        end if;
        return server_arch_in || suffix;
    end$$ language plpgsql;

    --
    -- Raises:
    --   server_arch_not_found
    --   no_subscribe_permissions
    create or replace function base_channel_for_release_arch(
        release_in in varchar,
        server_arch_in in varchar,
        org_id_in in numeric default -1,
        user_id_in in numeric default null
    ) returns numeric as $$
    declare
        server_arch varchar(256) := rhn_channel.normalize_server_arch(server_arch_in);
        server_arch_id numeric;
    begin
        -- Look up the server arch
            select id
              into server_arch_id
              from rhnServerArch
             where label = server_arch;
            if not found then
                perform rhn_exception.raise_exception('server_arch_not_found');
            end if;

        return rhn_channel.base_channel_rel_archid(release_in, server_arch_id,
            org_id_in, user_id_in);
    end$$ language plpgsql;

    create or replace function base_channel_rel_archid(
        release_in in varchar,
        server_arch_id_in in numeric,
        org_id_in in numeric default -1,
        user_id_in in numeric default null
    ) returns numeric as $$
    declare
        denied_channel_id numeric := null;
        valid_org_id numeric := org_id_in;
        valid_user_id numeric := user_id_in;
        channel_subscribable numeric;
    -- Cursor that fetches all the possible base channels for a
    -- (server_arch_id, release, org_id) combination
        base_channel_cursor cursor(
                release_in varchar,
                server_arch_id_in numeric,
                org_id_in numeric
        ) for
                select distinct c.*
                from    rhnOrgDistChannelMap                       odcm,
                                rhnServerChannelArchCompat      scac,
                                rhnChannel                                      c
                where   c.parent_channel is null
                        and c.id = odcm.channel_id
                        and c.channel_arch_id = odcm.channel_arch_id
                        and odcm.release = release_in
                        and odcm.for_org_id = org_id_in
                        and scac.server_arch_id = server_arch_id_in
                        and scac.channel_arch_id = c.channel_arch_id;

    begin
        if org_id_in = -1 and user_id_in is not null then
            -- Get the org id from the user id

                select org_id
                  into valid_org_id
                  from web_contact
                 where id = user_id_in;

                if not found then
                    -- User doesn't exist
                    -- XXX Only list public stuff for now
                    valid_user_id := null;
                    valid_org_id := -1;
                end if;
        end if;

        for c in base_channel_cursor(release_in, server_arch_id_in, valid_org_id)
        loop
            -- This row is a possible match
            if valid_user_id is null then
                -- User ID not specified, so no user to channel permissions to
                -- check
                return c.id;
            end if;

            -- Check user to channel permissions
            select rhn_channel.loose_user_role_check(c.id, user_id_in, 'subscribe')
              into channel_subscribable;

            if channel_subscribable = 1 then
                return c.id;
            end if;

            -- Base channel exists, but is not subscribable; keep trying
            denied_channel_id := c.id;
        end loop;

        if denied_channel_id is not null then
            perform rhn_exception.raise_exception('no_subscribe_permissions');
        end if;
        -- No base channel applies
        return NULL;
    end$$ language plpgsql;

    CREATE OR REPLACE FUNCTION clear_subscriptions(server_id_in IN NUMERIC, deleting_server IN NUMERIC default 0) returns void
    AS $$
    declare
        server_channels cursor(server_id_in numeric) for
                select  s.org_id, sc.channel_id, cfm.channel_family_id
                from    rhnServer s,
                        rhnServerChannel sc,
                        rhnChannelFamilyMembers cfm
                where   s.id = server_id_in
                        and s.id = sc.server_id
                        and sc.channel_id = cfm.channel_id
                order by cfm.channel_family_id;
        last_channel_family_id rhnChannelFamilyMembers.channel_family_id%type := -1;
        last_channel_org_id    rhnServer.org_id%type := -1;
    BEGIN
        for channel in server_channels(server_id_in)
        loop
                perform rhn_channel.unsubscribe_server(server_id_in, channel.channel_id, 1, 1, deleting_server);
        end loop;
    END$$ language plpgsql;

    CREATE OR REPLACE FUNCTION unsubscribe_server(server_id_in IN NUMERIC, channel_id_in NUMERIC, immediate_in NUMERIC default 1, unsubscribe_children_in numeric default 0,
                                 deleting_server in numeric default 0) returns void
    AS $$
    declare
        channel_family_id_val   NUMERIC;
        server_org_id_val       NUMERIC;
        server_already_in_chan  BOOLEAN;
        channel_family_is_proxy cursor(channel_family_id_in numeric) for
                select  1
                from    rhnChannelFamily
                where   id = channel_family_id_in
                    and label = 'rhn-proxy';
        channel_family_is_satellite cursor(channel_family_id_in numeric) for
                select  1
                from    rhnChannelFamily
                where   id = channel_family_id_in
                    and label = 'rhn-satellite';
        child record;
    BEGIN
        -- In PostgreSQL recursion with opened cursors is not allowed so we use
        -- FOR IN SELECT form which is ok.
        FOR child IN select  c.id
                from    rhnChannel                      c,
                                rhnServerChannel        sc
                where   1=1
                        and c.parent_channel = channel_id_in
                        and c.id = sc.channel_id
                        and sc.server_id = server_id_in
        LOOP
            if unsubscribe_children_in = 1 then
                perform rhn_channel.unsubscribe_server(server_id_in,
                                                       child.id,
                                                       immediate_in,
                                                       unsubscribe_children_in,
                                                       deleting_server);
            else
                perform rhn_exception.raise_exception('channel_unsubscribe_child_exists');
            end if;
        END LOOP;

        server_already_in_chan := rhn_channel.check_server_subscription(server_id_in, channel_id_in);

        IF NOT server_already_in_chan
        THEN
            RETURN;
        END IF;

   if deleting_server = 0 then
      insert into rhnServerHistory (id,server_id,summary,details) (
          select  nextval('rhn_event_id_seq'),
                server_id_in,
             'unsubscribed from channel ' || SUBSTR(c.label, 0, 106),
             c.label
          from    rhnChannel c
          where   c.id = channel_id_in
      );
   end if;

   DELETE FROM rhnServerChannel WHERE server_id = server_id_in AND channel_id = channel_id_in;

   if deleting_server = 0 then
        perform queue_server(server_id_in, immediate_in);

        update rhnServer
           set channels_changed = current_timestamp
         where id = server_id_in;
   end if;

        channel_family_id_val := rhn_channel.family_for_channel(channel_id_in);
        IF channel_family_id_val IS NULL
        THEN
            perform rhn_exception.raise_exception('channel_unsubscribe_no_family');
        END IF;

        for ignore in channel_family_is_satellite(channel_family_id_val) loop
                delete from rhnSatelliteInfo where server_id = server_id_in;
        end loop;

        for ignore in channel_family_is_proxy(channel_family_id_val) loop
                delete from rhnProxyInfo where server_id = server_id_in;
        end loop;
        SELECT org_id INTO server_org_id_val
          FROM rhnServer
         WHERE id = server_id_in;

    END$$ language plpgsql;

    CREATE OR REPLACE FUNCTION family_for_channel(channel_id_in IN NUMERIC)
    RETURNS NUMERIC
    AS $$
    declare
        channel_family_id_val NUMERIC;
    BEGIN
        SELECT channel_family_id INTO channel_family_id_val
          FROM rhnChannelFamilyMembers
         WHERE channel_id = channel_id_in;

        IF NOT FOUND THEN
          RETURN NULL;
        END IF;

        RETURN channel_family_id_val;
    END$$ language plpgsql;

    create or replace function unsubscribe_server_from_family(server_id_in in numeric,
                                             channel_family_id_in in numeric)
    returns void
    as $$
    begin
        delete
        from    rhnServerChannel rsc
        where   rsc.server_id = server_id_in
            and channel_id in (
                select  rcfm.channel_id
                from    rhnChannelFamilyMembers rcfm
                where   rcfm.channel_family_id = channel_family_id_in);
    end$$ language plpgsql;

    create or replace function get_org_id(channel_id_in in numeric)
    returns numeric
    as $$
    declare
        org_id_out numeric;
    begin
        select org_id into strict org_id_out
            from rhnChannel
            where id = channel_id_in;

            return org_id_out;
    end$$ language plpgsql;

    create or replace function get_cfam_org_access(cfam_id_in in numeric, org_id_in in numeric)
    returns numeric
    as $$
    begin
      if exists(
                        select  1
                        from    rhnOrgChannelFamilyPermissions cfp
                        where   cfp.org_id = org_id_in
      ) then
                return 1;
      else
                return 0;
      end if;
    end$$ language plpgsql;

    create or replace function get_org_access(channel_id_in in numeric, org_id_in in numeric)
    returns integer
    as $$
    begin
        -- the idea: if we get past this query,
        -- the org has access to the channel, else not
        if exists(
        select 1
          from rhnChannelFamilyMembers CFM,
               rhnOrgChannelFamilyPermissions CFP
         where cfp.org_id = org_id_in
           and CFM.channel_family_id = CFP.channel_family_id
           and CFM.channel_id = channel_id_in)
        then
          return 1;
        else
          return 0;
        end if;
    end$$ language plpgsql;

    create or replace function rhn_channel.user_role_check(channel_id_in in numeric, user_id_in in numeric, role_in in varchar)
    returns numeric
    as $$
    declare
        result NUMERIC;
    begin
        SELECT
          INTO result
          CASE
            WHEN suseChannelUserRoleView.deny_reason IS NULL THEN 1
            ELSE 0
            END
          FROM suseChannelUserRoleView
          WHERE channel_id = channel_id_in AND
            user_id = user_id_in AND
            role = role_in;

         if result IS NULL then
           result := 0;
         end if;

         RETURN result;
    end$$ language plpgsql;

    --
    -- For multiorg phase II, this function simply checks to see if the user's
    -- has a trust relationship that includes this channel by id.
    --
    create or replace function shared_user_role_check(channel_id in numeric, user_id in numeric, role in varchar)
    returns numeric
    as $$
    declare
      n numeric;
      oid numeric;
    begin
      oid := rhn_user.get_org_id(user_id);
      select 1 into n
      from rhnSharedChannelView s
      where s.id = channel_id and s.org_trust_id = oid;

      if not found then
        return 0;
      end if;

      return 1;
    end$$ language plpgsql;

    -- same as above, but returns 1 if user_id_in is null
    -- This is useful in queries where user_id is not specified
    create or replace function loose_user_role_check(channel_id_in in numeric, user_id_in in numeric, role_in in varchar)
    returns numeric
    as $$
    begin
        if user_id_in is null then
            return 1;
        end if;
        return rhn_channel.user_role_check(channel_id_in, user_id_in, role_in);
    end$$ language plpgsql;

    -- directly checks the table, no inferred permissions
    create or replace function direct_user_role_check(channel_id_in in numeric, user_id_in in numeric, role_in in varchar)
    returns numeric
    as $$
    declare
        throwaway numeric;
    begin
        -- the idea: if we get past this query, the user has the role, else no
        select 1 into throwaway
          from rhnChannelPermissionRole CPR,
               rhnChannelPermission CP
         where CP.user_id = user_id_in
           and CP.channel_id = channel_id_in
           and CPR.label = role_in
           and CP.role_id = CPR.id;

      if not found then
        return 0;
      end if;

      return 1;
    end$$ language plpgsql;

    -- check if an org has a certain setting
    create or replace function org_channel_setting(channel_id_in in numeric, org_id_in in numeric, setting_in in varchar)
    returns numeric
    as $$
    declare
        throwaway numeric;
    begin
        -- the idea: if we get past this query, the org has the setting
        select 1 into throwaway
          from rhnOrgChannelSettingsType OCST,
               rhnOrgChannelSettings OCS
         where OCS.org_id = org_id_in
           and OCS.channel_id = channel_id_in
           and OCST.label = setting_in
           and OCS.setting_id = OCST.id;

      if not found then
        return 0;
      end if;

      return 1;
    end$$ language plpgsql;

    CREATE OR REPLACE FUNCTION channel_priority(channel_id_in IN numeric)
    RETURNS numeric
    AS $$
    declare
         channel_name varchar(256);
         priority numeric;
         end_of_life_val timestamptz;
         org_id_val numeric;
    BEGIN

        select name, end_of_life, org_id
        into channel_name, end_of_life_val, org_id_val
        from rhnChannel
        where id = channel_id_in;

        if end_of_life_val is not null then
          return -400;
        end if;

        if channel_name like 'Red Hat Enterprise Linux%' or channel_name like 'RHEL%' then
          priority := 1000;
          if channel_name not like '%Beta%' then
            priority := priority + 1000;
          end if;

          priority := priority +
            case
              when channel_name like '%v. 5%' then 600
              when channel_name like '%v. 4%' then 500
              when channel_name like '%v. 3%' then 400
              when channel_name like '%v. 2%' then 300
              when channel_name like '%v. 1%' then 200
              else 0
            end;

          priority := priority +
            case
              when channel_name like 'Red Hat Enterprise Linux (v. 5%' then 60
              when (channel_name like '%AS%' and channel_name not like '%Extras%') then 50
              when (channel_name like '%ES%' and channel_name not like '%Extras%') then 40
              when (channel_name like '%WS%' and channel_name not like '%Extras%') then 30
              when (channel_name like '%Desktop%' and channel_name not like '%Extras%') then 20
              when channel_name like '%Extras%' then 10
              else 0
            end;

          priority := priority +
            case
              when channel_name like '%)' then 5
              else 0
            end;

          priority := priority +
            case
              when channel_name like '%32-bit x86%' then 4
              when channel_name like '%64-bit Intel Itanium%' then 3
              when channel_name like '%64-bit AMD64/Intel EM64T%' then 2
              else 0
            end;
        elsif channel_name like 'Red Hat Desktop%' then
            priority := 900;

            if channel_name not like '%Beta%' then
               priority := priority + 50;
            end if;

          priority := priority +
            case
              when channel_name like '%v. 4%' then 40
              when channel_name like '%v. 3%' then 30
              when channel_name like '%v. 2%' then 20
              when channel_name like '%v. 1%' then 10
              else 0
            end;

          priority := priority +
            case
              when channel_name like '%32-bit x86%' then 4
              when channel_name like '%64-bit Intel Itanium%' then 3
              when channel_name like '%64-bit AMD64/Intel EM64T%' then 2
              else 0
            end;

        elsif org_id_val is not null then
          priority := 600;
        else
          priority := 500;
        end if;

      return -priority;

    end$$ language plpgsql;

    -- this could certainly be optimized to do updates if needs be
    create or replace function refresh_newest_package(channel_id_in in numeric,
                                      caller_in in varchar default '(unknown)',
                                      package_name_id_in in numeric default null)
    returns void
    as $$
    -- procedure refreshes rows for name_id = package_name_id_in or
    -- all rows if package_name_id_in is null
    begin
        delete from rhnChannelNewestPackage
              where channel_id = channel_id_in
                and (package_name_id_in is null
                     or name_id = package_name_id_in);
        insert into rhnChannelNewestPackage
                (channel_id, name_id, evr_id, package_id, package_arch_id)
                (select channel_id,
                        name_id, evr_id,
                        package_id, package_arch_id
                   from rhnChannelNewestPackageView
                  where channel_id = channel_id_in
                    and (package_name_id_in is null
                         or name_id = package_name_id_in)
                );
        insert into rhnChannelNewestPackageAudit (channel_id, caller)
             values (channel_id_in, caller_in);
        update rhnChannel
           set last_modified = greatest(current_timestamp,
                                        last_modified + interval '1 second')
         where id = channel_id_in;
    end$$ language plpgsql;

   create or replace function update_channel ( channel_id_in in numeric, invalidate_ss in numeric default 0,
                              date_to_use in timestamptz default current_timestamp ) returns void
   as $$
   declare
   channel_last_modified timestamptz;
   last_modified_value timestamptz;

   snapshots cursor for
   select  snapshot_id id
   from    rhnSnapshotChannel
   where   channel_id = channel_id_in;

   begin

      select last_modified
      into channel_last_modified
      from rhnChannel
      where id = channel_id_in;

      last_modified_value := date_to_use;

      if last_modified_value <= channel_last_modified then
          last_modified_value := last_modified_value + interval '1 second';
      end if;

      update rhnChannel set last_modified = last_modified_value
      where id = channel_id_in;

      if invalidate_ss = 1 then
        for snapshot in snapshots loop
            update rhnSnapshot
            set invalid = lookup_snapshot_invalid_reason('channel_modified')
            where id = snapshot.id;
        end loop;
      end if;

   end$$ language plpgsql;

   create or replace function update_channels_by_package ( package_id_in in numeric, date_to_use in timestamptz default current_timestamp ) returns void
   as $$
   declare
   channels cursor for
   select channel_id
   from rhnChannelPackage
   where package_id = package_id_in
   order by channel_id;

   begin
      for channel in channels loop
         -- we want to invalidate the snapshot assocated with the channel when we
         -- do this b/c we know we've added or removed or packages
         perform rhn_channel.update_channel ( channel.channel_id, 1, date_to_use );
      end loop;
   end$$ language plpgsql;


   create or replace function update_channels_by_errata ( errata_id_in numeric, date_to_use in timestamptz default current_timestamp ) returns void
   as $$
   declare
   channels cursor for
   select channel_id
   from rhnChannelErrata
   where errata_id = errata_id_in
   order by channel_id;

   begin
      for channel in channels loop
         -- we won't invalidate snapshots, b/c just changing the errata associated with
         -- a channel shouldn't invalidate snapshots
         perform rhn_channel.update_channel ( channel.channel_id, 0, date_to_use );
      end loop;
   end$$ language plpgsql;

   create or replace function update_needed_cache(channel_id_in in numeric) returns void
   as $$
   declare
   server record;
   image record;
   begin
      -- we intentionaly do a loop here instead of one huge select
      -- b/c we want to break update into smaller transaction to unblock other sessions
      -- querying rhnServerNeededCache
      for server in (
                select sc.server_id as id
                  from rhnServerChannel sc
                 where sc.channel_id = channel_id_in
                 order by id asc
      ) loop
         perform queue_server(server.id, 0); -- NOT IMMEDIATE
      end loop;
      for image in (
        select ic.image_info_id as id
          from suseImageInfoChannel ic
         where ic.channel_id = channel_id_in
        order by id asc
      ) loop
         perform queue_image(image.id, 0);
      end loop;
   end$$ language plpgsql;

    create or replace function set_comps(channel_id_in in numeric, path_in in varchar, comps_type_id_in in numeric, timestamp_in in varchar) returns void
    as $$
    declare
    row record;
    begin
        for row in (
            select relative_filename, last_modified
            from rhnChannelComps
            where channel_id = channel_id_in
            and comps_type_id = comps_type_id_in
            ) loop
            if row.relative_filename = path_in
                and row.last_modified = to_timestamp(timestamp_in, 'YYYYMMDDHH24MISS') then
                return;
            end if;
        end loop;
        delete from rhnChannelComps
        where channel_id = channel_id_in and comps_type_id = comps_type_id_in;
        insert into rhnChannelComps (id, channel_id, relative_filename, comps_type_id, last_modified, created, modified)
        values (sequence_nextval('rhn_channelcomps_id_seq'), channel_id_in, path_in, comps_type_id_in, to_timestamp(timestamp_in, 'YYYYMMDDHH24MISS'), current_timestamp, current_timestamp);
    end$$ language plpgsql;

-- restore the original setting
update pg_settings set setting = overlay( setting placing '' from 1 for (length('rhn_channel')+1) ) where name = 'search_path';
 07070100000C91000081B400000000000000000000000167AE11140000073D000000000000000000000000000000000000006900000000susemanager-schema/upgrade/susemanager-schema-3.2.15-to-susemanager-schema-3.2.16/202-rhnUserChannel.sql  --
-- Copyright (c) 2008 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--

create or replace view rhnUserChannel
as
select
   cfp.user_id,
   cfp.org_id,
   cfm.channel_id,
   'manage' as role
from rhnChannelFamilyMembers cfm,
      rhnUserChannelFamilyPerms cfp
where
   cfp.channel_family_id = cfm.channel_family_id and
   (select deny_reason
      from suseChannelUserRoleView scur
      where scur.channel_id = cfm.channel_id and
        scur.user_id = cfp.user_id and
        scur.role = 'manage'
   ) is null
union all
select
   cfp.user_id,
   cfp.org_id,
   cfm.channel_id,
   'subscribe' as role
from rhnChannelFamilyMembers cfm,
      rhnUserChannelFamilyPerms cfp
where
   cfp.channel_family_id = cfm.channel_family_id and
   (select deny_reason
      from suseChannelUserRoleView scur
      where scur.channel_id = cfm.channel_id and
        scur.user_id = cfp.user_id and
        scur.role = 'subscribe'
   ) is null
union all
select
   w.id as user_id,
   w.org_id,
   s.id as channel_id,
   'subscribe' as role
from rhnSharedChannelView s,
      web_contact w
where
   w.org_id = s.org_trust_id and
   (select deny_reason
      from suseChannelUserRoleView scur
      where scur.channel_id = s.id and
        scur.user_id = w.id and
        scur.role = 'subscribe'
   ) is null
;
   07070100000C92000081B400000000000000000000000167AE1114000028A1000000000000000000000000000000000000007800000000susemanager-schema/upgrade/susemanager-schema-3.2.15-to-susemanager-schema-3.2.16/300-delete_server-archive-actions.sql   --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--
--
--
-- This deletes a server.  All codepaths which delete servers should hit this
-- or delete_server_bulk()

create or replace
function delete_server (
        server_id_in in numeric
) returns void
as
$$
declare
         servergroups cursor for
                select  server_id, server_group_id
                from    rhnServerGroupMembers sgm
                where   sgm.server_id = server_id_in;

         configchannels cursor for
                select  cc.id
                from    rhnConfigChannel cc,
                        rhnConfigChannelType cct,
                        rhnServerConfigChannel scc
                where   1=1
                        and scc.server_id = server_id_in
                        and scc.config_channel_id = cc.id
                        -- these config channel types are reserved
                        -- for use by a single server, so we don't
                        -- need to check for other servers subscribed
                        and cct.label in
                                ('local_override','server_import')
                        and cct.id = cc.confchan_type_id;

    update_lock numeric;
begin
    -- lock the rhnServer row to prevent deadlocks
    -- we want rhnServer to be locked first, followed by tables that depend on it
    select id into update_lock from rhnServer where id = server_id_in for update;

        -- filelists
        delete from rhnFileList where id in (
	select	spfl.file_list_id
	  from	rhnServerPreserveFileList spfl
	 where	spfl.server_id = server_id_in
			and not exists (
				select	1
				from	rhnServerPreserveFileList
				where	file_list_id = spfl.file_list_id
					and server_id != server_id_in
				union all
				select	1
				from	rhnKickstartPreserveFileList
				where	file_list_id = spfl.file_list_id
			)
        );

	for configchannel in configchannels loop
		perform rhn_config.delete_channel(configchannel.id);
	end loop;

	for sgm in servergroups loop
		perform rhn_server.delete_from_servergroup(
			sgm.server_id, sgm.server_group_id);
	end loop;


        -- we're handling this instead of letting an "on delete
        -- set null" do it so that we don't run the risk
        -- of setting off the triggers and killing us with a
        -- mutating table

        -- this is merge of two single updates:
        --  update ... set old_server_id = null where old_server_id = server_id_in;
        --  update ... set new_server_id = null where new_server_id = server_id_in;
        -- so we scan rhnKickstartSession table only once
        update rhnKickstartSession
                set old_server_id = case when old_server_id = server_id_in then null else old_server_id end,
                    new_server_id = case when new_server_id = server_id_in then null else new_server_id end
                where old_server_id = server_id_in
                   or new_server_id = server_id_in;

        perform rhn_channel.clear_subscriptions(server_id_in, 1);

        -- A little complicated here, but the goal is to
        -- delete records from rhnVirtualInstace only if we don't
        -- care about them anymore.  We don't care about records
        -- in rhnVirtualInstance if we are deleting the host
        -- system and the virtual system is already null, or
        -- vice-versa.  We *do* care about them if either the
        -- host or virtual system is still registered because we
        -- still want them to show up in the UI.
    -- If there's a newer row in rhnVirtualInstance with the same
    -- uuid, this guest must have been re-registered, so we can clean
    -- this data up.

        delete from rhnVirtualInstance vi
              where (host_system_id = server_id_in and virtual_system_id is null)
                 or (virtual_system_id = server_id_in and host_system_id is null)
                 or (vi.virtual_system_id = server_id_in and vi.modified < (select max(vi2.modified)
                    from rhnVirtualInstance vi2 where vi2.uuid = vi.uuid));

        -- this is merge of two single updates:
        --  update ... set host_system_id = null where host_system_id = server_id_in;
        --  update ... set virtual_system_id = null where virtual_system_id = server_id_in;
        -- so we scan rhnVirtualInstance table only once
        update rhnVirtualInstance
           set host_system_id = case when host_system_id = server_id_in then null else host_system_id end,
               virtual_system_id = case when virtual_system_id = server_id_in then null else virtual_system_id end
         where host_system_id = server_id_in
            or virtual_system_id = server_id_in;

        -- this is merge of two single updates:
        --  update ... set old_host_system_id = null when old_host_system_id = server_id_in;
        --  update ... set new_host_system_id = null when new_host_system_id = server_id_in;
        -- so we scan rhnVirtualInstanceEventLog table only once
        update rhnVirtualInstanceEventLog
           set old_host_system_id = case when old_host_system_id = server_id_in then null else old_host_system_id end,
               new_host_system_id = case when new_host_system_id = server_id_in then null else new_host_system_id end
         where old_host_system_id = server_id_in
            or new_host_system_id = server_id_in;

        -- archive related actions, only if they have no other servers assigned
        update rhnAction set archived = 1 where id in (
            select action_id from rhnServerAction sa
            where not exists (
                select server_id from rhnServerAction
                where action_id = sa.action_id and server_id != server_id_in
            )
        );

        -- We're deleting everything with a foreign key to rhnServer
        -- here, now.  I'm hoping this will help aleviate our deadlock
        -- problem.

        delete from rhnActionApplyStatesResult where server_id = server_id_in;
        delete from rhnActionConfigChannel where server_id = server_id_in;
        delete from rhnActionConfigRevision where server_id = server_id_in;
        delete from rhnActionPackageRemovalFailure where server_id = server_id_in;
        delete from rhnClientCapability where server_id = server_id_in;
        delete from rhnCpu where server_id = server_id_in;
        -- there's still a cascade here, because the constraint keeps the
        -- table locked for too long to rebuild it.  Ugh...
        delete from rhnDevice where server_id = server_id_in;
        delete from rhnProxyInfo where server_id = server_id_in;
        delete from rhnRam where server_id = server_id_in;
        delete from rhnRegToken where server_id = server_id_in;
        delete from rhnSatelliteInfo where server_id = server_id_in;
        -- this cascades to rhnActionConfigChannel and rhnActionConfigFileName
        delete from rhnServerAction where server_id = server_id_in;
        delete from rhnServerActionPackageResult where server_id = server_id_in;
        delete from rhnServerActionScriptResult where server_id = server_id_in;
        delete from rhnServerActionVerifyResult where server_id = server_id_in;
        delete from rhnServerActionVerifyMissing where server_id = server_id_in;
        -- counts are handled above.  this should be a delete_ function.
        delete from rhnServerChannel where server_id = server_id_in;
        delete from rhnServerConfigChannel where server_id = server_id_in;
        delete from rhnServerCustomDataValue where server_id = server_id_in;
        delete from rhnServerDMI where server_id = server_id_in;
        delete from rhnServerEvent where server_id = server_id_in;
        delete from rhnServerFQDN where server_id = server_id_in;
        delete from rhnServerHistory where server_id = server_id_in;
        delete from rhnServerInfo where server_id = server_id_in;
        delete from rhnServerInstallInfo where server_id = server_id_in;
        delete from rhnServerLocation where server_id = server_id_in;
        delete from rhnServerLock where server_id = server_id_in;
        delete from rhnServerNeededCache where server_id = server_id_in;
        delete from rhnServerNotes where server_id = server_id_in;
        -- I'm not removing the foreign key from rhnServerPackage; that'll
        -- take forever.  Do the delete anyway.
        delete from rhnServerPackage where server_id = server_id_in;
        delete from rhnServerTokenRegs where server_id = server_id_in;
        delete from rhnSnapshotTag where server_id = server_id_in;
        -- this cascades to:
        --   rhnSnapshotChannel, rhnSnapshotConfigChannel, rhnSnapshotPackage,
        --   rhnSnapshotConfigRevision, rhnSnapshotServerGroup,
        --   rhnSnapshotTag.
        -- We may want to consider delete_snapshot() at some point, but
        --   I don't think we need to yet.
        delete from rhnSnapshot where server_id = server_id_in;
        delete from rhnUserServerPrefs where server_id = server_id_in;
        -- hrm, this one's interesting... we _probably_ should delete
        -- everything for the parent server_id when we delete the proxy,
        -- but we don't currently.
        delete from rhnServerPath where server_id_in in (server_id, proxy_server_id);
        delete from rhnUserServerPerms where server_id = server_id_in;

        delete from rhnServerNetInterface where server_id = server_id_in;

        delete from rhnServerUuid where server_id = server_id_in;

        delete from rhnPushClient where server_id = server_id_in;

        -- now get rhnServer itself.
        delete
        from    rhnServer
                where id = server_id_in;

        delete
        from    rhnSet
        where   label = 'system_list'
                and element = server_id_in;
end;
$$
language plpgsql;
   07070100000C93000081B400000000000000000000000167AE111400000783000000000000000000000000000000000000008000000000susemanager-schema/upgrade/susemanager-schema-3.2.15-to-susemanager-schema-3.2.16/301-rhnUserActionOverview-include-orphans.sql   --
-- Copyright (c) 2008 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--
--
--
--
-- rhnActionOverview, but on a per-user basis.

-- invoke as:
--
-- select	*
-- from		rhnUserActionOverview
-- where	org_id = :oid
--		and user_id = :uid;
--

create or replace view rhnUserActionOverview as
select	ao.org_id                                       as org_id,
	usp.user_id                                     as user_id,
        ao.action_id                                    as id,
	ao.type_name                                    as type_name,
        ao.scheduler                                    as scheduler,
	ao.earliest_action                              as earliest_action,
	coalesce( ao.name, ao.type_name )		as action_name,
	sa.status					as action_status_id,
	astat.name                                      as action_status,
	count(sa.action_id)				as tally,
	ao.archived                                     as archived
from    rhnActionOverview ao
        left join rhnServerAction sa on ao.action_id = sa.action_id
        left join rhnActionStatus astat on sa.status = astat.id
        left join rhnUserServerPerms usp on sa.server_id = usp.server_id
group by ao.org_id,
	 usp.user_id,
	 ao.action_id,
	 ao.type_name,
	 ao.scheduler,
	 ao.earliest_action,
	 coalesce( ao.name, ao.type_name ),
	 sa.status,
	 astat.name,
	 ao.archived
order by earliest_action;

 07070100000C94000081B400000000000000000000000167AE1114000000A8000000000000000000000000000000000000007B00000000susemanager-schema/upgrade/susemanager-schema-3.2.15-to-susemanager-schema-3.2.16/302-rhnAction-archive-orphan-actions.sql    -- Archive actions which have no servers assigned
UPDATE rhnAction SET archived = 1 WHERE id IN (
    SELECT id FROM rhnUserActionOverview
    WHERE user_id IS NULL
);
07070100000C95000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005200000000susemanager-schema/upgrade/susemanager-schema-3.2.16-to-susemanager-schema-3.2.17 07070100000C96000081B400000000000000000000000167AE111400000046000000000000000000000000000000000000006E00000000susemanager-schema/upgrade/susemanager-schema-3.2.16-to-susemanager-schema-3.2.17/001-rhnXccdfIdent-ident.sql 
alter table rhnXccdfIdent alter column identifier type varchar(255);
  07070100000C97000081B400000000000000000000000167AE111400000221000000000000000000000000000000000000006700000000susemanager-schema/upgrade/susemanager-schema-3.2.16-to-susemanager-schema-3.2.17/001-rhn_user.pkb.sql    --
-- Copyright (c) 2019 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--

DROP FUNCTION IF EXISTS rhn_user.remove_servergroup_perm(user_id_in in numeric, server_group_id_in in numeric);


   07070100000C98000081B400000000000000000000000167AE111400000517000000000000000000000000000000000000008400000000susemanager-schema/upgrade/susemanager-schema-3.2.16-to-susemanager-schema-3.2.17/001-suseproductsccrepo-delete-invalid-entries.sql   delete from suseproductsccrepository where channel_label = 'suse-openstack-cloud-6-pool-x86_64-sp1';
delete from suseproductsccrepository where channel_label = 'suse-openstack-cloud-6-updates-x86_64-sp1';
delete from suseproductsccrepository where channel_label = 'suse-openstack-cloud-6-debuginfo-pool-x86_64-sp1';
delete from suseproductsccrepository where channel_label = 'suse-openstack-cloud-6-debuginfo-updates-x86_64-sp1';

delete from suseproductsccrepository where channel_label = 'suse-packagehub-12-sp4-aarch64';
delete from suseproductsccrepository where channel_label = 'suse-packagehub-12-sp4-aarch64-hpc-sp4';
delete from suseproductsccrepository where channel_label = 'suse-packagehub-12-sp4-ppc64le';
delete from suseproductsccrepository where channel_label = 'suse-packagehub-12-sp4-ppc64le-sap-sp4';
delete from suseproductsccrepository where channel_label = 'suse-packagehub-12-sp4-s390x';
delete from suseproductsccrepository where channel_label = 'suse-packagehub-12-sp4-x86_64';
delete from suseproductsccrepository where channel_label = 'suse-packagehub-12-sp4-x86_64-sled-sp4';
delete from suseproductsccrepository where channel_label = 'suse-packagehub-12-sp4-x86_64-sap-sp4';
delete from suseproductsccrepository where channel_label = 'suse-packagehub-12-sp4-x86_64-hpc-sp4';
 07070100000C99000081B400000000000000000000000167AE111400000113000000000000000000000000000000000000007800000000susemanager-schema/upgrade/susemanager-schema-3.2.16-to-susemanager-schema-3.2.17/005-cleanup-channel_family-labels.sql   DELETE FROM rhnPublicChannelFamily
 WHERE channel_family_id IN (
        SELECT id
          FROM rhnChannelFamily
         WHERE label LIKE '%-alpha'
            OR label LIKE '%-beta'
);

DELETE FROM rhnChannelFamily
 WHERE label LIKE '%-alpha'
    OR label LIKE '%-beta';
 07070100000C9A000081B400000000000000000000000167AE1114000000B3000000000000000000000000000000000000007500000000susemanager-schema/upgrade/susemanager-schema-3.2.16-to-susemanager-schema-3.2.17/100-rhnTaskoSchedule-cron-freq.sql  UPDATE rhnTaskoSchedule SET cron_expr = '0 0 0 * * ?'
    WHERE job_label = 'minion-action-cleanup-default'
        AND active_till IS NULL
        AND cron_expr = '0 0 * * * ?';
 07070100000C9B000081B400000000000000000000000167AE11140000029A000000000000000000000000000000000000006A00000000susemanager-schema/upgrade/susemanager-schema-3.2.16-to-susemanager-schema-3.2.17/201-insert_checksum.sql 
create or replace function
insert_checksum(checksum_type_in in varchar, checksum_in in varchar)
returns numeric
as
$$
declare
    checksum_id     numeric;
begin
    checksum_id := nextval('rhnchecksum_seq');

    insert into rhnChecksum (id, checksum_type_id, checksum)
      values (
          checksum_id,
          (select id from rhnChecksumType where label = checksum_type_in),
          checksum_in
      )
      on conflict do nothing;

    select c.id
        into strict checksum_id
        from rhnChecksumView c
        where c.checksum = checksum_in and
            c.checksum_type = checksum_type_in;

    return checksum_id;
end;
$$ language plpgsql;
  07070100000C9C000081B400000000000000000000000167AE1114000001E1000000000000000000000000000000000000007300000000susemanager-schema/upgrade/susemanager-schema-3.2.16-to-susemanager-schema-3.2.17/202-insert_client_capability.sql    
create or replace function
insert_client_capability(name_in in varchar)
returns numeric
as $$
declare
    cap_name_id     numeric;
begin
    cap_name_id := nextval('rhn_client_capname_id_seq');

    insert into rhnClientCapabilityName(id, name)
        values (cap_name_id, name_in)
        on conflict do nothing;

    select id
        into strict cap_name_id
        from rhnclientcapabilityname
        where name = name_in;

    return cap_name_id;
end;
$$ language plpgsql;
   07070100000C9D000081B400000000000000000000000167AE1114000001B8000000000000000000000000000000000000007100000000susemanager-schema/upgrade/susemanager-schema-3.2.16-to-susemanager-schema-3.2.17/203-insert_config_filename.sql  
create or replace function
insert_config_filename(name_in in varchar)
returns numeric as
$$
declare
    name_id     numeric;
begin
    name_id := nextval('rhn_cfname_id_seq');

    insert into rhnConfigFileName (id, path)
        values (name_id, name_in)
        on conflict do nothing;

    select id
        into strict name_id
        from rhnconfigfilename
        where path = name_in;

    return name_id;
end;
$$ language plpgsql;
07070100000C9E000081B400000000000000000000000167AE11140000049B000000000000000000000000000000000000006D00000000susemanager-schema/upgrade/susemanager-schema-3.2.16-to-susemanager-schema-3.2.17/204-insert_config_info.sql  
create or replace function
insert_config_info(
    username_in     in varchar,
    groupname_in    in varchar,
    filemode_in     in numeric,
    selinux_ctx_in  in varchar,
    symlink_target_id in numeric
)
returns numeric
as
$$
declare
    config_info_id    numeric;
begin
    config_info_id := nextval('rhn_confinfo_id_seq');

    insert into rhnConfigInfo (id, username, groupname, filemode, selinux_ctx, symlink_target_filename_id)
        values (config_info_id, username_in, groupname_in, filemode_in, selinux_ctx_in, symlink_target_id)
        on conflict do nothing;

    select id
      into config_info_id
      from rhnConfigInfo
      where (username = username_in or (username is null and username_in is null))
        and (groupname = groupname_in or (groupname is null and groupname_in is null))
        and (filemode = filemode_in or (filemode is null and filemode_in is null))
        and (selinux_ctx = selinux_ctx_in or (selinux_ctx is null and selinux_ctx_in is null))
        and (symlink_target_filename_id = symlink_target_id or (symlink_target_filename_id is null and symlink_target_id is null));

    return config_info_id;
end;
$$ language plpgsql;
 07070100000C9F000081B400000000000000000000000167AE111400000193000000000000000000000000000000000000006500000000susemanager-schema/upgrade/susemanager-schema-3.2.16-to-susemanager-schema-3.2.17/205-insert_cve.sql  
create or replace function
insert_cve(name_in in varchar)
returns numeric
as $$
declare
    name_id     numeric;
begin
    name_id := nextval('rhn_cve_id_seq');

    insert into rhnCVE (id, name)
        values (name_id, name_in)
        on conflict do nothing;

    select id
        into strict name_id
        from rhnCVE
        where name = name_in;

    return name_id;
end;
$$ language plpgsql;
 07070100000CA0000081B400000000000000000000000167AE111400000249000000000000000000000000000000000000006500000000susemanager-schema/upgrade/susemanager-schema-3.2.16-to-susemanager-schema-3.2.17/206-insert_evr.sql  
create or replace function
insert_evr(e_in in varchar, v_in in varchar, r_in in varchar)
returns numeric
as
$$
declare
    evr_id  numeric;
begin
    evr_id := nextval('rhn_pkg_evr_seq');

    insert into rhnPackageEVR(id, epoch, version, release, evr)
        values (evr_id, e_in, v_in, r_in, evr_t(e_in, v_in, r_in))
        on conflict do nothing;

    select id
        into strict evr_id
        from rhnPackageEVR
        where ((epoch is null and e_in is null) or (epoch = e_in)) and
           version = v_in and release = r_in;

    return evr_id;
end;
$$ language plpgsql;
   07070100000CA1000081B400000000000000000000000167AE1114000001CE000000000000000000000000000000000000006C00000000susemanager-schema/upgrade/susemanager-schema-3.2.16-to-susemanager-schema-3.2.17/207-insert_md_keyword.sql   
create or replace function
insert_md_keyword(label_in in varchar)
returns numeric
as
$$
declare
    md_keyword_id numeric;
begin
    md_keyword_id := nextval('suse_mdkeyword_id_seq');

    insert into suseMdKeyword (id, label)
        values (md_keyword_id, label_in)
        on conflict do nothing;

    select id
        into strict md_keyword_id
        from suseMdKeyword
        where label = label_in;

    return md_keyword_id;
end;
$$ language plpgsql;
  07070100000CA2000081B400000000000000000000000167AE1114000002E8000000000000000000000000000000000000007400000000susemanager-schema/upgrade/susemanager-schema-3.2.16-to-susemanager-schema-3.2.17/208-insert_package_capability.sql   
create or replace function
insert_package_capability(name_in in varchar, version_in in varchar default null)
returns numeric
as
$$
declare
    name_id numeric;
begin
    name_id := nextval('rhn_pkg_capability_id_seq');

    insert into rhnPackageCapability(id, name, version)
        values (name_id, name_in, version_in)
        on conflict do nothing;

    if version_in is null then
        select id
            into strict name_id
            from rhnpackagecapability
            where name = name_in and version is null;
    else
        select id
            into strict name_id
            from rhnpackagecapability
            where name = name_in and version = version_in;
    end if;

    return name_id;
end;
$$ language plpgsql;
07070100000CA3000081B400000000000000000000000167AE1114000001B0000000000000000000000000000000000000006F00000000susemanager-schema/upgrade/susemanager-schema-3.2.16-to-susemanager-schema-3.2.17/209-insert_package_delta.sql    
create or replace function
insert_package_delta(n_in in varchar)
returns numeric
as
$$
declare
    name_id     numeric;
begin
    name_id := nextval('rhn_packagedelta_id_seq');

    insert into rhnPackageDelta(id, label)
        values (name_id, n_in)
        on conflict do nothing;

    select id
        into strict name_id
        from rhnpackagedelta
        where label = n_in;

    return name_id;
end;
$$ language plpgsql;
07070100000CA4000081B400000000000000000000000167AE1114000001C5000000000000000000000000000000000000006F00000000susemanager-schema/upgrade/susemanager-schema-3.2.16-to-susemanager-schema-3.2.17/210-insert_package_group.sql    
create or replace function
insert_package_group(name_in in varchar)
returns numeric
as
$$
declare
    package_id   numeric;
begin
    package_id := nextval('rhn_package_group_id_seq');

    insert into rhnPackageGroup(id, name)
        values (package_id, name_in)
        on conflict do nothing;

    select id
        into strict package_id
        from rhnPackageGroup
        where name = name_in;

    return package_id;
end;
$$ language plpgsql;
   07070100000CA5000081B400000000000000000000000167AE1114000001AD000000000000000000000000000000000000006E00000000susemanager-schema/upgrade/susemanager-schema-3.2.16-to-susemanager-schema-3.2.17/211-insert_package_name.sql 
create or replace function
insert_package_name(name_in in varchar)
returns numeric
as
$$
declare
    name_id     numeric;
begin
    name_id := nextval('rhn_pkg_name_seq');

    insert into rhnPackageName(id, name)
        values (name_id, name_in)
        on conflict do nothing;

    select id
        into strict name_id
        from rhnPackageName
        where name = name_in;

    return name_id;
end;
$$ language plpgsql;
   07070100000CA6000081B400000000000000000000000167AE1114000002E0000000000000000000000000000000000000006F00000000susemanager-schema/upgrade/susemanager-schema-3.2.16-to-susemanager-schema-3.2.17/212-insert_package_nevra.sql    
create or replace function
insert_package_nevra(
        name_id_in in numeric,
        evr_id_in in numeric,
        package_arch_id_in in numeric
) returns numeric
as
$$
declare
    nevra_id numeric;
begin
    nevra_id := nextval('rhn_pkgnevra_id_seq');

    insert into rhnPackageNEVRA(id, name_id, evr_id, package_arch_id)
        values (nevra_id, name_id_in, evr_id_in, package_arch_id_in)
        on conflict do nothing;

    select id
        into strict nevra_id
        from rhnPackageNEVRA
        where name_id = name_id_in and evr_id = evr_id_in and
            (package_arch_id = package_arch_id_in or
            (package_arch_id is null and package_arch_id_in is null));

    return nevra_id;
end;
$$ language plpgsql;
07070100000CA7000081B400000000000000000000000167AE1114000001B4000000000000000000000000000000000000006D00000000susemanager-schema/upgrade/susemanager-schema-3.2.16-to-susemanager-schema-3.2.17/213-insert_source_name.sql  
create or replace function
insert_source_name(name_in in varchar)
returns numeric
as
$$
declare
    source_id   numeric;
begin
    source_id := nextval('rhn_sourcerpm_id_seq');

    insert into rhnSourceRPM(id, name)
        values (source_id, name_in)
        on conflict do nothing;

    select id
        into strict source_id
        from rhnSourceRPM
        where name = name_in;

    return source_id;
end;
$$ language plpgsql;
07070100000CA8000081B400000000000000000000000167AE1114000001F1000000000000000000000000000000000000006500000000susemanager-schema/upgrade/susemanager-schema-3.2.16-to-susemanager-schema-3.2.17/214-insert_tag.sql  
create or replace function
insert_tag(org_id_in in numeric, tag_name_id_in in numeric)
returns numeric
as $$
declare
    tag_id  numeric;
begin
    tag_id := nextval('rhn_tag_id_seq');

    insert into rhnTag(id, org_id, name_id)
        values (tag_id, org_id_in, tag_name_id_in)
        on conflict do nothing;

    select id
        into strict tag_id
        from rhnTag
        where org_id = org_id_in and
            name_id = tag_name_id_in;

    return tag_id;
end;
$$ language plpgsql;
   07070100000CA9000081B400000000000000000000000167AE11140000019F000000000000000000000000000000000000006A00000000susemanager-schema/upgrade/susemanager-schema-3.2.16-to-susemanager-schema-3.2.17/215-insert_tag_name.sql 
create or replace function
insert_tag_name(name_in in varchar)
returns numeric
as
$$
declare
    name_id numeric;
begin
    name_id := nextval('rhn_tagname_id_seq');

    insert into rhnTagName(id, name)
        values (name_id, name_in)
        on conflict do nothing;

    select id
        into strict name_id
        from rhnTagName
        where name = name_in;

    return name_id;
end;
$$ language plpgsql;
 07070100000CAA000081B400000000000000000000000167AE1114000002F8000000000000000000000000000000000000007500000000susemanager-schema/upgrade/susemanager-schema-3.2.16-to-susemanager-schema-3.2.17/216-insert_transaction_package.sql  
create or replace function
insert_transaction_package(
    o_id_in      in numeric,
    n_id_in      in numeric,
    e_id_in      in numeric,
    p_arch_id_in in numeric
)
returns numeric
as
$$
declare
    tp_id       numeric;
begin
    tp_id := nextval('rhn_transpack_id_seq');

    insert into rhnTransactionPackage (id, operation, name_id, evr_id, package_arch_id)
        values (tp_id, o_id_in, n_id_in, e_id_in, p_arch_id_in)
        on conflict do nothing;

    select id
        into strict tp_id
        from rhnTransactionPackage
     where operation = o_id_in and name_id = n_id_in and evr_id = e_id_in and
        (package_arch_id = p_arch_id_in or (p_arch_id_in is null and package_arch_id is null));

    return tp_id;
end;
$$ language plpgsql;
07070100000CAB000081B400000000000000000000000167AE111400000239000000000000000000000000000000000000007100000000susemanager-schema/upgrade/susemanager-schema-3.2.16-to-susemanager-schema-3.2.17/217-insert_xccdf_benchmark.sql  
create or replace function
insert_xccdf_benchmark(identifier_in in varchar, version_in in varchar)
returns numeric
as
$$
declare
    benchmark_id numeric;
begin
    benchmark_id := nextval('rhn_xccdf_benchmark_id_seq');

    insert into rhnXccdfBenchmark (id, identifier, version)
        values (benchmark_id, identifier_in, version_in)
        on conflict do nothing;

    select id
        into strict benchmark_id
        from rhnXccdfBenchmark
        where identifier = identifier_in and version = version_in;

    return benchmark_id;
end;
$$ language plpgsql;
   07070100000CAC000081B400000000000000000000000167AE111400000250000000000000000000000000000000000000006D00000000susemanager-schema/upgrade/susemanager-schema-3.2.16-to-susemanager-schema-3.2.17/218-insert_xccdf_ident.sql  
create or replace function
insert_xccdf_ident(ident_sys_id_in in numeric, identifier_in in varchar)
returns numeric
as
$$
declare
    xccdf_ident_id numeric;
begin
    xccdf_ident_id := nextval('rhn_xccdf_ident_id_seq');

    insert into rhnXccdfIdent (id, identsystem_id, identifier)
        values (xccdf_ident_id, ident_sys_id_in, identifier_in)
        on conflict do nothing;

    select id
        into strict xccdf_ident_id
        from rhnXccdfIdent
        where identsystem_id = ident_sys_id_in and identifier = identifier_in;

    return xccdf_ident_id;
end;
$$ language plpgsql;
07070100000CAD000081B400000000000000000000000167AE1114000001E8000000000000000000000000000000000000007400000000susemanager-schema/upgrade/susemanager-schema-3.2.16-to-susemanager-schema-3.2.17/219-insert_xccdf_ident_system.sql   
create or replace function
insert_xccdf_ident_system(system_in in varchar)
returns numeric
as
$$
declare
    ident_sys_id numeric;
begin
    ident_sys_id := nextval('rhn_xccdf_identsytem_id_seq');

    insert into rhnXccdfIdentSystem (id, system)
        values (ident_sys_id, system_in)
        on conflict do nothing;

    select id
        into strict ident_sys_id
        from rhnXccdfIdentSystem
        where system = system_in;

    return ident_sys_id;
end;
$$ language plpgsql;
07070100000CAE000081B400000000000000000000000167AE111400000216000000000000000000000000000000000000006F00000000susemanager-schema/upgrade/susemanager-schema-3.2.16-to-susemanager-schema-3.2.17/220-insert_xccdf_profile.sql    
create or replace function
insert_xccdf_profile(identifier_in in varchar, title_in in varchar)
returns numeric
as
$$
declare
    profile_id numeric;
begin
    profile_id := nextval('rhn_xccdf_profile_id_seq');

    insert into rhnXccdfProfile (id, identifier, title)
        values (profile_id, identifier_in, title_in)
        on conflict do nothing;

    select id
        into profile_id
        from rhnXccdfProfile
        where identifier = identifier_in and title = title_in;

    return profile_id;
end;
$$ language plpgsql;
  07070100000CAF000081B400000000000000000000000167AE111400000902000000000000000000000000000000000000006A00000000susemanager-schema/upgrade/susemanager-schema-3.2.16-to-susemanager-schema-3.2.17/221-lookup_checksum.sql --
-- Copyright (c) 2010 - 2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

create or replace function
lookup_checksum(checksum_type_in in varchar, checksum_in in varchar)
returns numeric
as
$$
declare
    checksum_id     numeric;
begin
    if checksum_in is null then
        return null;
    end if;

    select c.id
      into checksum_id
      from rhnChecksumView c
     where c.checksum = checksum_in and
           c.checksum_type = checksum_type_in;

    if not found then
        -- HACK: insert is isolated in own function in order to be able to declare this function immutable
        -- Postgres optimizes immutable functions calls but those are compatible with the contract of lookup_\*
        -- see https://www.postgresql.org/docs/9.6/xfunc-volatility.html
        return insert_checksum(checksum_type_in, checksum_in);
    end if;

    return checksum_id;
end;
$$ language plpgsql immutable;

-- NOTE: This is intentionally not thread safe! You must lock rhnChecksum
-- if you are going to use this procedure!
create or replace function
lookup_checksum_fast(checksum_type_in in varchar, checksum_in in varchar)
returns numeric
as
$$
declare
    checksum_id     numeric;
begin
    if checksum_in is null then
        return null;
    end if;

    select c.id
      into checksum_id
      from rhnChecksumView c
     where c.checksum = checksum_in and
           c.checksum_type = checksum_type_in;

    if not found then
        checksum_id := nextval('rhnchecksum_seq');
        insert into rhnChecksum (id, checksum_type_id, checksum) values (
            checksum_id,
            (select id from rhnChecksumType where label = checksum_type_in),
            checksum_in);
    end if;

    return checksum_id;
end;
$$ language plpgsql;
  07070100000CB0000081B400000000000000000000000167AE111400000515000000000000000000000000000000000000007300000000susemanager-schema/upgrade/susemanager-schema-3.2.16-to-susemanager-schema-3.2.17/222-lookup_client_capability.sql    --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 

create or replace function
lookup_client_capability(name_in in varchar)
returns numeric
as $$
declare
    cap_name_id     numeric;
begin
    select id
      into cap_name_id
      from rhnclientcapabilityname
     where name = name_in;

    if not found then
        -- HACK: insert is isolated in own function in order to be able to declare this function immutable
        -- Postgres optimizes immutable functions calls but those are compatible with the contract of lookup_\*
        -- see https://www.postgresql.org/docs/9.6/xfunc-volatility.html
        return insert_client_capability(name_in);
    end if;

    return cap_name_id;
end;
$$ language plpgsql immutable;
   07070100000CB1000081B400000000000000000000000167AE1114000004FD000000000000000000000000000000000000007100000000susemanager-schema/upgrade/susemanager-schema-3.2.16-to-susemanager-schema-3.2.17/223-lookup_config_filename.sql  --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.

create or replace function
lookup_config_filename(name_in in varchar)
returns numeric as
$$
declare
    name_id     numeric;
begin
    select id
      into name_id
      from rhnconfigfilename
     where path = name_in;

    if not found then
        -- HACK: insert is isolated in own function in order to be able to declare this function immutable
        -- Postgres optimizes immutable functions calls but those are compatible with the contract of lookup_\*
        -- see https://www.postgresql.org/docs/9.6/xfunc-volatility.html
        return insert_config_filename(name_in);
    end if;

    return name_id;
end;
$$ language plpgsql immutable;
   07070100000CB2000081B400000000000000000000000167AE11140000079F000000000000000000000000000000000000006D00000000susemanager-schema/upgrade/susemanager-schema-3.2.16-to-susemanager-schema-3.2.17/224-lookup_config_info.sql  --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

create or replace function
lookup_config_info(
    username_in     in varchar,
    groupname_in    in varchar,
    filemode_in     in numeric,
    selinux_ctx_in  in varchar,
    symlink_target_id in numeric
)
returns numeric
as
$$
declare
    config_info_id    numeric;
begin
    select id
      into config_info_id
      from rhnConfigInfo
      where (username = username_in or (username is null and username_in is null))
        and (groupname = groupname_in or (groupname is null and groupname_in is null))
        and (filemode = filemode_in or (filemode is null and filemode_in is null))
        and (selinux_ctx = selinux_ctx_in or (selinux_ctx is null and selinux_ctx_in is null))
        and (symlink_target_filename_id = symlink_target_id or (symlink_target_filename_id is null and symlink_target_id is null));

    if not found then
        -- HACK: insert is isolated in own function in order to be able to declare this function immutable
        -- Postgres optimizes immutable functions calls but those are compatible with the contract of lookup_\*
        -- see https://www.postgresql.org/docs/9.6/xfunc-volatility.html
        return insert_config_info(username_in, groupname_in, filemode_in, selinux_ctx_in, symlink_target_id);
    end if;

    return config_info_id;
end;
$$ language plpgsql immutable;
 07070100000CB3000081B400000000000000000000000167AE1114000004DA000000000000000000000000000000000000006500000000susemanager-schema/upgrade/susemanager-schema-3.2.16-to-susemanager-schema-3.2.17/225-lookup_cve.sql  --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.

create or replace function
lookup_cve(name_in in varchar)
returns numeric
as $$
declare
    name_id     numeric;
begin
    select id
      into name_id
      from rhnCVE
     where name = name_in;

    if not found then
        -- HACK: insert is isolated in own function in order to be able to declare this function immutable
        -- Postgres optimizes immutable functions calls but those are compatible with the contract of lookup_\*
        -- see https://www.postgresql.org/docs/9.6/xfunc-volatility.html
        return insert_cve(name_in);
    end if;

    return name_id;
end;
$$ language plpgsql immutable;
  07070100000CB4000081B400000000000000000000000167AE111400000565000000000000000000000000000000000000006500000000susemanager-schema/upgrade/susemanager-schema-3.2.16-to-susemanager-schema-3.2.17/226-lookup_evr.sql  --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.

create or replace function
lookup_evr(e_in in varchar, v_in in varchar, r_in in varchar)
returns numeric
as
$$
declare
    evr_id  numeric;
begin
    select id
      into evr_id
      from rhnPackageEVR
     where ((epoch is null and e_in is null) or (epoch = e_in)) and
           version = v_in and
           release = r_in;

    if not found then
        -- HACK: insert is isolated in own function in order to be able to declare this function immutable
        -- Postgres optimizes immutable functions calls but those are compatible with the contract of lookup_\*
        -- see https://www.postgresql.org/docs/9.6/xfunc-volatility.html
        return insert_evr(e_in, v_in, r_in);
    end if;

    return evr_id;
end;
$$ language plpgsql immutable;
   07070100000CB5000081B400000000000000000000000167AE11140000043D000000000000000000000000000000000000006C00000000susemanager-schema/upgrade/susemanager-schema-3.2.16-to-susemanager-schema-3.2.17/227-lookup_md_keyword.sql   --
-- Copyright (c) 2012 Novell
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--

create or replace function
lookup_md_keyword(label_in in varchar)
returns numeric
as
$$
declare
    md_keyword_id numeric;
begin
    select id
      into md_keyword_id
      from suseMdKeyword
     where label = label_in;

    if not found then
        -- HACK: insert is isolated in own function in order to be able to declare this function immutable
        -- Postgres optimizes immutable functions calls but those are compatible with the contract of lookup_\*
        -- see https://www.postgresql.org/docs/9.6/xfunc-volatility.html
        return insert_md_keyword(label_in);
    end if;

    return md_keyword_id;
end;
$$ language plpgsql immutable;
   07070100000CB6000081B400000000000000000000000167AE1114000009BD000000000000000000000000000000000000007400000000susemanager-schema/upgrade/susemanager-schema-3.2.16-to-susemanager-schema-3.2.17/228-lookup_package_capability.sql   --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 

create or replace function
lookup_package_capability(name_in in varchar, version_in in varchar default null)
returns numeric
as
$$
declare
    name_id numeric;
begin
    if version_in is null then
        select id
          into name_id
          from rhnpackagecapability
         where name = name_in and
               version is null;
    else
        select id
          into name_id
          from rhnpackagecapability
         where name = name_in and
               version = version_in;
    end if;

    if not found then
        -- HACK: insert is isolated in own function in order to be able to declare this function immutable
        -- Postgres optimizes immutable functions calls but those are compatible with the contract of lookup_\*
        -- see https://www.postgresql.org/docs/9.6/xfunc-volatility.html
        return insert_package_capability(name_in, version_in);
    end if;

    return name_id;
end;
$$ language plpgsql immutable;

-- Note: intentionally not thread-safe! You must aquire a write lock on the
-- rhnPackageCapability tabel if you are going to use this proc!
create or replace function lookup_package_capability_fast(name_in in varchar, version_in in varchar default null)
returns numeric
as
$$
declare
    name_id numeric;
begin
    if version_in is null then
        select id
          into name_id
          from rhnpackagecapability
         where name = name_in and
               version is null;
    else
        select id
          into name_id
          from rhnpackagecapability
         where name = name_in and
               version = version_in;
    end if;

    if not found then
        name_id := nextval('rhn_pkg_capability_id_seq');
        insert into rhnPackageCapability(id, name, version) values (
               name_id, name_in, version_in);
    end if;

    return name_id;
end;
$$ language plpgsql;
   07070100000CB7000081B400000000000000000000000167AE1114000004F1000000000000000000000000000000000000006F00000000susemanager-schema/upgrade/susemanager-schema-3.2.16-to-susemanager-schema-3.2.17/229-lookup_package_delta.sql    --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 

create or replace function
lookup_package_delta(n_in in varchar)
returns numeric
as
$$
declare
    name_id     numeric;
begin
    select id
      into name_id
      from rhnPackageDelta
     where label = n_in;

    if not found then
        -- HACK: insert is isolated in own function in order to be able to declare this function immutable
        -- Postgres optimizes immutable functions calls but those are compatible with the contract of lookup_\*
        -- see https://www.postgresql.org/docs/9.6/xfunc-volatility.html
        return insert_package_delta(n_in);
    end if;

    return name_id;
end;
$$ language plpgsql immutable;
   07070100000CB8000081B400000000000000000000000167AE111400000500000000000000000000000000000000000000006F00000000susemanager-schema/upgrade/susemanager-schema-3.2.16-to-susemanager-schema-3.2.17/230-lookup_package_group.sql    --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 

create or replace function
lookup_package_group(name_in in varchar)
returns numeric
as
$$
declare
    package_id   numeric;
begin
    select id
      into package_id
      from rhnPackageGroup
     where name = name_in;

    if not found then
        -- HACK: insert is isolated in own function in order to be able to declare this function immutable
        -- Postgres optimizes immutable functions calls but those are compatible with the contract of lookup_\*
        -- see https://www.postgresql.org/docs/9.6/xfunc-volatility.html
        return insert_package_group(name_in);
    end if;

    return package_id;
end;
$$ language plpgsql immutable;
07070100000CB9000081B400000000000000000000000167AE11140000056A000000000000000000000000000000000000006E00000000susemanager-schema/upgrade/susemanager-schema-3.2.16-to-susemanager-schema-3.2.17/231-lookup_package_name.sql --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 

create or replace function
lookup_package_name(name_in in varchar, ignore_null in numeric default 0)
returns numeric
as
$$
declare
    name_id     numeric;
begin
    if ignore_null = 1 and name_in is null then
        return null;
    end if;

    select id
      into name_id
      from rhnPackageName
     where name = name_in;

    if not found then
        -- HACK: insert is isolated in own function in order to be able to declare this function immutable
        -- Postgres optimizes immutable functions calls but those are compatible with the contract of lookup_\*
        -- see https://www.postgresql.org/docs/9.6/xfunc-volatility.html
        return insert_package_name(name_in);
    end if;

    return name_id;
end;
$$ language plpgsql immutable;
  07070100000CBA000081B400000000000000000000000167AE11140000069B000000000000000000000000000000000000006F00000000susemanager-schema/upgrade/susemanager-schema-3.2.16-to-susemanager-schema-3.2.17/232-lookup_package_nevra.sql    --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 

create or replace function
lookup_package_nevra(
        name_id_in in numeric,
        evr_id_in in numeric,
        package_arch_id_in in numeric,
        ignore_null_name in numeric default 0
) returns numeric
as
$$
declare
    nevra_id numeric;
begin
    if ignore_null_name = 1 and name_id_in is null then
        return null;
    end if;

    select id
      into nevra_id
      from rhnPackageNEVRA
     where name_id = name_id_in and
           evr_id = evr_id_in and
           (package_arch_id = package_arch_id_in or
            (package_arch_id is null and package_arch_id_in is null));

    if not found then
        -- HACK: insert is isolated in own function in order to be able to declare this function immutable
        -- Postgres optimizes immutable functions calls but those are compatible with the contract of lookup_\*
        -- see https://www.postgresql.org/docs/9.6/xfunc-volatility.html
        return insert_package_nevra(name_id_in, evr_id_in, package_arch_id_in);
    end if;

    return nevra_id;
end;
$$ language plpgsql immutable;
 07070100000CBB000081B400000000000000000000000167AE1114000004F6000000000000000000000000000000000000006D00000000susemanager-schema/upgrade/susemanager-schema-3.2.16-to-susemanager-schema-3.2.17/233-lookup_source_name.sql  --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 

create or replace function
lookup_source_name(name_in in varchar)
returns numeric
as
$$
declare
    source_id   numeric;
begin
    select id
      into source_id
      from rhnSourceRPM
     where name = name_in;

    if not found then
        -- HACK: insert is isolated in own function in order to be able to declare this function immutable
        -- Postgres optimizes immutable functions calls but those are compatible with the contract of lookup_\*
        -- see https://www.postgresql.org/docs/9.6/xfunc-volatility.html
        return insert_source_name(name_in);
    end if;

    return source_id;
end;
$$ language plpgsql immutable;
  07070100000CBC000081B400000000000000000000000167AE11140000056B000000000000000000000000000000000000006500000000susemanager-schema/upgrade/susemanager-schema-3.2.16-to-susemanager-schema-3.2.17/234-lookup_tag.sql  --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 

create or replace function
lookup_tag(org_id_in in numeric, name_in in varchar)
returns numeric
as $$
declare
    tag_id  numeric;
    tag_name_id numeric;
begin
    tag_name_id := lookup_tag_name(name_in);

    select id
      into tag_id
      from rhnTag
     where org_id = org_id_in and
           name_id = tag_name_id;

    if not found then
        -- HACK: insert is isolated in own function in order to be able to declare this function immutable
        -- Postgres optimizes immutable functions calls but those are compatible with the contract of lookup_\*
        -- see https://www.postgresql.org/docs/9.6/xfunc-volatility.html
        return insert_tag(org_id_in, tag_name_id);
    end if;

    return tag_id;
end;
$$ language plpgsql immutable;
 07070100000CBD000081B400000000000000000000000167AE1114000004E6000000000000000000000000000000000000006A00000000susemanager-schema/upgrade/susemanager-schema-3.2.16-to-susemanager-schema-3.2.17/235-lookup_tag_name.sql --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 

create or replace function
lookup_tag_name(name_in in varchar)
returns numeric
as
$$
declare
    name_id numeric;
begin
    select id
      into name_id
      from rhnTagName
     where name = name_in;

    if not found then
        -- HACK: insert is isolated in own function in order to be able to declare this function immutable
        -- Postgres optimizes immutable functions calls but those are compatible with the contract of lookup_\*
        -- see https://www.postgresql.org/docs/9.6/xfunc-volatility.html
        return insert_tag_name(name_in);
    end if;

    return name_id;
end;
$$ language plpgsql immutable;
  07070100000CBE000081B400000000000000000000000167AE111400000817000000000000000000000000000000000000007500000000susemanager-schema/upgrade/susemanager-schema-3.2.16-to-susemanager-schema-3.2.17/236-lookup_transaction_package.sql  --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 

create or replace function
lookup_transaction_package(
    o_in in varchar,
    n_in in varchar,
    e_in in varchar,
    v_in in varchar,
    r_in in varchar,
    a_in in varchar)
returns numeric
as
$$
declare
    o_id        numeric;
    n_id        numeric;
    e_id        numeric;
    p_arch_id   numeric;
    tp_id       numeric;
begin
    select id
      into o_id
      from rhnTransactionOperation
     where label = o_in;

    if not found then
        perform rhn_exception.raise_exception('invalid_transaction_operation');
    end if;

    n_id := lookup_package_name(n_in);
    e_id := lookup_evr(e_in, v_in, r_in);
    p_arch_id := null;

    if a_in is not null then
        p_arch_id := lookup_package_arch(a_in);
    end if;

    select id
      into tp_id
      from rhnTransactionPackage
     where operation = o_id and
           name_id = n_id and
           evr_id = e_id and
           (package_arch_id = p_arch_id or (p_arch_id is null and package_arch_id is null));

    if not found then
        -- HACK: insert is isolated in own function in order to be able to declare this function immutable
        -- Postgres optimizes immutable functions calls but those are compatible with the contract of lookup_\*
        -- see https://www.postgresql.org/docs/9.6/xfunc-volatility.html
        return insert_transaction_package(o_id, n_id, e_id, p_arch_id);
    end if;
    return tp_id;
end;
$$ language plpgsql immutable;
 07070100000CBF000081B400000000000000000000000167AE111400000559000000000000000000000000000000000000007100000000susemanager-schema/upgrade/susemanager-schema-3.2.16-to-susemanager-schema-3.2.17/237-lookup_xccdf_benchmark.sql  --
-- Copyright (c) 2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

create or replace function
lookup_xccdf_benchmark(identifier_in in varchar, version_in in varchar)
returns numeric
as
$$
declare
    benchmark_id numeric;
begin
    select id
      into benchmark_id
      from rhnXccdfBenchmark
     where identifier = identifier_in and version = version_in;

    if not found then
        -- HACK: insert is isolated in own function in order to be able to declare this function immutable
        -- Postgres optimizes immutable functions calls but those are compatible with the contract of lookup_\*
        -- see https://www.postgresql.org/docs/9.6/xfunc-volatility.html
        return insert_xccdf_benchmark(identifier_in, version_in);
    end if;

    return benchmark_id;
end;
$$ language plpgsql immutable;
   07070100000CC0000081B400000000000000000000000167AE11140000063A000000000000000000000000000000000000006D00000000susemanager-schema/upgrade/susemanager-schema-3.2.16-to-susemanager-schema-3.2.17/238-lookup_xccdf_ident.sql  --
-- Copyright (c) 2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.

create or replace function
lookup_xccdf_ident(system_in in varchar, identifier_in in varchar)
returns numeric
as
$$
declare
    xccdf_ident_id numeric;
    ident_sys_id numeric;
begin
    select id
      into ident_sys_id
      from rhnXccdfIdentSystem
     where system = system_in;

    if not found then
        -- HACK: insert is isolated in own function in order to be able to declare this function immutable
        -- Postgres optimizes immutable functions calls but those are compatible with the contract of lookup_\*
        -- see https://www.postgresql.org/docs/9.6/xfunc-volatility.html
        ident_sys_id := insert_xccdf_ident_system(system_in);
    end if;

    select id
      into xccdf_ident_id
      from rhnXccdfIdent
     where identsystem_id = ident_sys_id and identifier = identifier_in;

    if not found then
        return insert_xccdf_ident(ident_sys_id, identifier_in);
    end if;

    return xccdf_ident_id;
end;
$$ language plpgsql immutable;
  07070100000CC1000081B400000000000000000000000167AE111400000545000000000000000000000000000000000000006F00000000susemanager-schema/upgrade/susemanager-schema-3.2.16-to-susemanager-schema-3.2.17/239-lookup_xccdf_profile.sql    --
-- Copyright (c) 2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

create or replace function
lookup_xccdf_profile(identifier_in in varchar, title_in in varchar)
returns numeric
as
$$
declare
    profile_id numeric;
begin
    select id
      into profile_id
      from rhnXccdfProfile
     where identifier = identifier_in and title = title_in;

    if not found then
        -- HACK: insert is isolated in own function in order to be able to declare this function immutable
        -- Postgres optimizes immutable functions calls but those are compatible with the contract of lookup_\*
        -- see https://www.postgresql.org/docs/9.6/xfunc-volatility.html
        return insert_xccdf_profile(identifier_in, title_in);
    end if;

    return profile_id;
end;
$$ language plpgsql immutable;
   07070100000CC2000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005100000000susemanager-schema/upgrade/susemanager-schema-3.2.16-to-susemanager-schema-4.0.0  07070100000CC3000081B400000000000000000000000167AE111400000000000000000000000000000000000000000000005A00000000susemanager-schema/upgrade/susemanager-schema-3.2.16-to-susemanager-schema-4.0.0/.gitkeep 07070100000CC4000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005200000000susemanager-schema/upgrade/susemanager-schema-3.2.17-to-susemanager-schema-3.2.18 07070100000CC5000081B400000000000000000000000167AE1114000007E3000000000000000000000000000000000000007700000000susemanager-schema/upgrade/susemanager-schema-3.2.17-to-susemanager-schema-3.2.18/001-add-minion-checkin-tasko-job.sql    -- Copyright (c) 2019 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--

INSERT INTO rhnTaskoBunch (id, name, description, org_bunch)
    SELECT sequence_nextval('rhn_tasko_bunch_id_seq'), 'minion-checkin-bunch', 'Perform a regular check-in on minions', null
    FROM dual WHERE NOT EXISTS (
        SELECT 1 FROM rhnTaskoBunch WHERE
        name='minion-checkin-bunch'
    );

INSERT INTO rhnTaskoSchedule (id, job_label, bunch_id, active_from, cron_expr)
    SELECT sequence_nextval('rhn_tasko_schedule_id_seq'), 'minion-checkin-default',
        (SELECT id FROM rhnTaskoBunch WHERE name='minion-checkin-bunch'),
        current_timestamp, '0 0 * * * ?'
    FROM dual WHERE NOT EXISTS (
        SELECT 1 FROM rhnTaskoSchedule WHERE
        job_label='minion-checkin-default'
    );

INSERT INTO rhnTaskoTask (id, name, class)
    SELECT sequence_nextval('rhn_tasko_task_id_seq'), 'minion-checkin', 'com.redhat.rhn.taskomatic.task.MinionCheckin'
    FROM dual WHERE NOT EXISTS (
        SELECT 1 FROM rhnTaskoTask WHERE
        name='minion-checkin'
    );

INSERT INTO rhnTaskoTemplate (id, bunch_id, task_id, ordering, start_if)
    SELECT sequence_nextval('rhn_tasko_template_id_seq'),
                        (SELECT id FROM rhnTaskoBunch WHERE name='minion-checkin-bunch'),
                        (SELECT id FROM rhnTaskoTask WHERE name='minion-checkin'),
                        0,
                        null
    FROM dual WHERE NOT EXISTS (
        SELECT 1 FROM rhnTaskoTemplate WHERE
        bunch_id=(SELECT id FROM rhnTaskoBunch WHERE name='minion-checkin-bunch') AND
        task_id=(SELECT id FROM rhnTaskoTask WHERE name='minion-checkin')
    );
 07070100000CC6000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005100000000susemanager-schema/upgrade/susemanager-schema-3.2.17-to-susemanager-schema-4.0.0  07070100000CC7000081B400000000000000000000000167AE111400000000000000000000000000000000000000000000005A00000000susemanager-schema/upgrade/susemanager-schema-3.2.17-to-susemanager-schema-4.0.0/.gitkeep 07070100000CC8000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005200000000susemanager-schema/upgrade/susemanager-schema-3.2.18-to-susemanager-schema-3.2.19 07070100000CC9000081B400000000000000000000000167AE11140000009F000000000000000000000000000000000000006E00000000susemanager-schema/upgrade/susemanager-schema-3.2.18-to-susemanager-schema-3.2.19/002-alter-susesaltevent.sql 
DROP INDEX IF EXISTS suse_salt_event_minion_id_idx;

CREATE INDEX IF NOT EXISTS suse_salt_event_minion_id_idx
  ON suseSaltEvent (minion_id NULLS FIRST, id);
 07070100000CCA000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005100000000susemanager-schema/upgrade/susemanager-schema-3.2.18-to-susemanager-schema-4.0.0  07070100000CCB000081B400000000000000000000000167AE111400000000000000000000000000000000000000000000005A00000000susemanager-schema/upgrade/susemanager-schema-3.2.18-to-susemanager-schema-4.0.0/.gitkeep 07070100000CCC000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005100000000susemanager-schema/upgrade/susemanager-schema-3.2.19-to-susemanager-schema-4.0.0  07070100000CCD000081B400000000000000000000000167AE111400000000000000000000000000000000000000000000005A00000000susemanager-schema/upgrade/susemanager-schema-3.2.19-to-susemanager-schema-4.0.0/.gitkeep 07070100000CCE000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005000000000susemanager-schema/upgrade/susemanager-schema-3.2.2-to-susemanager-schema-3.2.3   07070100000CCF000081B400000000000000000000000167AE111400000000000000000000000000000000000000000000005900000000susemanager-schema/upgrade/susemanager-schema-3.2.2-to-susemanager-schema-3.2.3/.gitkeep  07070100000CD0000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005100000000susemanager-schema/upgrade/susemanager-schema-3.2.20-to-susemanager-schema-4.0.0  07070100000CD1000081B400000000000000000000000167AE111400000000000000000000000000000000000000000000005A00000000susemanager-schema/upgrade/susemanager-schema-3.2.20-to-susemanager-schema-4.0.0/.gitkeep 07070100000CD2000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005100000000susemanager-schema/upgrade/susemanager-schema-3.2.21-to-susemanager-schema-4.0.0  07070100000CD3000081B400000000000000000000000167AE111400000000000000000000000000000000000000000000005A00000000susemanager-schema/upgrade/susemanager-schema-3.2.21-to-susemanager-schema-4.0.0/.gitkeep 07070100000CD4000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005200000000susemanager-schema/upgrade/susemanager-schema-3.2.22-to-susemanager-schema-3.2.23 07070100000CD5000081B400000000000000000000000167AE1114000001F9000000000000000000000000000000000000006A00000000susemanager-schema/upgrade/susemanager-schema-3.2.22-to-susemanager-schema-3.2.23/005-fix-none-vendor.sql delete from rhnpackagerepodata where package_id in (select id from rhnpackage where vendor = 'Not defined');

insert into rhnRepoRegenQueue (id, CHANNEL_LABEL, REASON, FORCE)
(select sequence_nextval('rhn_repo_regen_queue_id_seq'),
        C.label,
        'fix empty vendor',
        'Y'
   from rhnChannel C
   where C.id in (select distinct cp.channel_id
                    from rhnpackage p
	            join rhnchannelpackage cp on p.id = cp.package_id
	           where p.vendor = 'Not defined'));
   07070100000CD6000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005100000000susemanager-schema/upgrade/susemanager-schema-3.2.22-to-susemanager-schema-4.0.0  07070100000CD7000081B400000000000000000000000167AE111400000000000000000000000000000000000000000000005A00000000susemanager-schema/upgrade/susemanager-schema-3.2.22-to-susemanager-schema-4.0.0/.gitkeep 07070100000CD8000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005100000000susemanager-schema/upgrade/susemanager-schema-3.2.23-to-susemanager-schema-4.0.0  07070100000CD9000081B400000000000000000000000167AE111400000000000000000000000000000000000000000000005A00000000susemanager-schema/upgrade/susemanager-schema-3.2.23-to-susemanager-schema-4.0.0/.gitkeep 07070100000CDA000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005100000000susemanager-schema/upgrade/susemanager-schema-3.2.24-to-susemanager-schema-4.0.0  07070100000CDB000081B400000000000000000000000167AE111400000000000000000000000000000000000000000000005A00000000susemanager-schema/upgrade/susemanager-schema-3.2.24-to-susemanager-schema-4.0.0/.gitkeep 07070100000CDC000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005100000000susemanager-schema/upgrade/susemanager-schema-3.2.25-to-susemanager-schema-4.0.0  07070100000CDD000081B400000000000000000000000167AE111400000000000000000000000000000000000000000000005A00000000susemanager-schema/upgrade/susemanager-schema-3.2.25-to-susemanager-schema-4.0.0/.gitkeep 07070100000CDE000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005100000000susemanager-schema/upgrade/susemanager-schema-3.2.26-to-susemanager-schema-4.0.0  07070100000CDF000081B400000000000000000000000167AE111400000000000000000000000000000000000000000000005A00000000susemanager-schema/upgrade/susemanager-schema-3.2.26-to-susemanager-schema-4.0.0/.gitkeep 07070100000CE0000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005100000000susemanager-schema/upgrade/susemanager-schema-3.2.27-to-susemanager-schema-4.0.0  07070100000CE1000081B400000000000000000000000167AE111400000000000000000000000000000000000000000000005A00000000susemanager-schema/upgrade/susemanager-schema-3.2.27-to-susemanager-schema-4.0.0/.gitkeep 07070100000CE2000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005100000000susemanager-schema/upgrade/susemanager-schema-3.2.28-to-susemanager-schema-4.0.0  07070100000CE3000081B400000000000000000000000167AE111400000000000000000000000000000000000000000000005A00000000susemanager-schema/upgrade/susemanager-schema-3.2.28-to-susemanager-schema-4.0.0/.gitkeep 07070100000CE4000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005100000000susemanager-schema/upgrade/susemanager-schema-3.2.29-to-susemanager-schema-4.0.0  07070100000CE5000081B400000000000000000000000167AE111400000000000000000000000000000000000000000000005A00000000susemanager-schema/upgrade/susemanager-schema-3.2.29-to-susemanager-schema-4.0.0/.gitkeep 07070100000CE6000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005000000000susemanager-schema/upgrade/susemanager-schema-3.2.3-to-susemanager-schema-3.2.4   07070100000CE7000081B400000000000000000000000167AE111400000000000000000000000000000000000000000000005900000000susemanager-schema/upgrade/susemanager-schema-3.2.3-to-susemanager-schema-3.2.4/.gitkeep  07070100000CE8000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005100000000susemanager-schema/upgrade/susemanager-schema-3.2.30-to-susemanager-schema-4.0.0  07070100000CE9000081B400000000000000000000000167AE111400000000000000000000000000000000000000000000005A00000000susemanager-schema/upgrade/susemanager-schema-3.2.30-to-susemanager-schema-4.0.0/.gitkeep 07070100000CEA000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005000000000susemanager-schema/upgrade/susemanager-schema-3.2.4-to-susemanager-schema-3.2.5   07070100000CEB000081B400000000000000000000000167AE111400000000000000000000000000000000000000000000005900000000susemanager-schema/upgrade/susemanager-schema-3.2.4-to-susemanager-schema-3.2.5/.gitkeep  07070100000CEC000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005000000000susemanager-schema/upgrade/susemanager-schema-3.2.5-to-susemanager-schema-3.2.6   07070100000CED000081B400000000000000000000000167AE111400000000000000000000000000000000000000000000005900000000susemanager-schema/upgrade/susemanager-schema-3.2.5-to-susemanager-schema-3.2.6/.gitkeep  07070100000CEE000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005000000000susemanager-schema/upgrade/susemanager-schema-3.2.6-to-susemanager-schema-3.2.7   07070100000CEF000081B400000000000000000000000167AE111400000000000000000000000000000000000000000000005900000000susemanager-schema/upgrade/susemanager-schema-3.2.6-to-susemanager-schema-3.2.7/.gitkeep  07070100000CF0000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005000000000susemanager-schema/upgrade/susemanager-schema-3.2.7-to-susemanager-schema-3.2.8   07070100000CF1000081B400000000000000000000000167AE11140000043F000000000000000000000000000000000000006F00000000susemanager-schema/upgrade/susemanager-schema-3.2.7-to-susemanager-schema-3.2.8/001-add-latest-fedora-keys.sql    insert into rhnPackageKey (id, key_id, key_type_id, provider_id) select sequence_nextval('rhn_pkey_id_seq'), 'FDB19C98', lookup_package_key_type('gpg'), lookup_package_provider('Fedora') from dual where not exists (select 1 from rhnPackageKey where key_id = 'FDB19C98');

insert into rhnPackageKey (id, key_id, key_type_id, provider_id) select sequence_nextval('rhn_pkey_id_seq'), '64DAB85D', lookup_package_key_type('gpg'), lookup_package_provider('Fedora') from dual where not exists (select 1 from rhnPackageKey where key_id = '64DAB85D');

insert into rhnPackageKey (id, key_id, key_type_id, provider_id) select sequence_nextval('rhn_pkey_id_seq'), 'F5282EE4', lookup_package_key_type('gpg'), lookup_package_provider('Fedora') from dual where not exists (select 1 from rhnPackageKey where key_id = 'F5282EE4');

insert into rhnPackageKey (id, key_id, key_type_id, provider_id) select sequence_nextval('rhn_pkey_id_seq'), '9DB62FB1', lookup_package_key_type('gpg'), lookup_package_provider('Fedora') from dual where not exists (select 1 from rhnPackageKey where key_id = '9DB62FB1');
 07070100000CF2000081B400000000000000000000000167AE1114000000FC000000000000000000000000000000000000007400000000susemanager-schema/upgrade/susemanager-schema-3.2.7-to-susemanager-schema-3.2.8/002-clean-up-studio-credentials.sql   -- Delete all credentials of type SUSE Studio
delete from suseCredentials where type_id =
    (select id from suseCredentialsType where label = 'susestudio');

-- Delete the credentials type
delete from suseCredentialsType where label = 'susestudio';

07070100000CF3000081B400000000000000000000000167AE1114000000EE000000000000000000000000000000000000007100000000susemanager-schema/upgrade/susemanager-schema-3.2.7-to-susemanager-schema-3.2.8/003-add-sles15-KSInstallType.sql  insert into rhnKSInstallType (id, label, name)
(select sequence_nextval('rhn_ksinstalltype_id_seq'), 'sles15generic','SUSE Enterprise Linux 15' from dual
  where not exists (select 1 from rhnKSInstallType where label = 'sles15generic'));
  07070100000CF4000081B400000000000000000000000167AE111400000642000000000000000000000000000000000000006900000000susemanager-schema/upgrade/susemanager-schema-3.2.7-to-susemanager-schema-3.2.8/005-rhnChannelCloned.sql  --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--

drop trigger rhn_channel_cloned_comps_trig on rhnChannelCloned;

create or replace function rhn_channel_cloned_comps_trig_fun() returns trigger
as
$$
begin
	new.modified := current_timestamp;

	if tg_op = 'INSERT' then
		-- if there are not comps in the cloned channel by now,
		-- we shall clone comps from the original channel
		insert into rhnChannelComps
			( id, channel_id, comps_type_id, relative_filename,
				last_modified, created, modified )
		select nextval('rhn_channelcomps_id_seq'), new.id, comps_type_id, relative_filename,
				current_timestamp, current_timestamp, current_timestamp
		from rhnChannelComps
		where channel_id = new.original_id
			and not exists (
				select 1
				from rhnChannelComps x
				where x.channel_id = new.id
			);
	end if;
        return new;
end;
$$
language plpgsql;


create trigger
rhn_channel_cloned_comps_trig
before insert or update on rhnChannelCloned
for each row
execute procedure rhn_channel_cloned_comps_trig_fun();
  07070100000CF5000081B400000000000000000000000167AE111400000A9C000000000000000000000000000000000000007200000000susemanager-schema/upgrade/susemanager-schema-3.2.7-to-susemanager-schema-3.2.8/100-lookup_package_capability.sql --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 

create or replace function lookup_package_capability(name_in in varchar, version_in in varchar default null)
returns numeric
as
$$
declare
    name_id numeric;
begin
    if version_in is null then
        select id
          into name_id
          from rhnpackagecapability
         where name = name_in and
               version is null;
    else
        select id
          into name_id
          from rhnpackagecapability
         where name = name_in and
               version = version_in;
    end if;

    if not found then
        name_id = nextval('rhn_pkg_capability_id_seq');

        insert into rhnPackageCapability(id, name, version)
            values (name_id, name_in, version_in)
            on conflict do nothing;

        if version_in is null then
            select id
                into strict name_id
                from rhnpackagecapability
                where name = name_in and version is null;
        else
            select id
                into strict name_id
                from rhnpackagecapability
                where name = name_in and version = version_in;
        end if;
    end if;

    return name_id;
end;
$$ language plpgsql;

-- Note: intentionally not thread-safe! You must aquire a write lock on the
-- rhnPackageCapability tabel if you are going to use this proc!
create or replace function lookup_package_capability_fast(name_in in varchar, version_in in varchar default null)
returns numeric
as
$$
declare
    name_id numeric;
begin
    if version_in is null then
        select id
          into name_id
          from rhnpackagecapability
         where name = name_in and
               version is null;
    else
        select id
          into name_id
          from rhnpackagecapability
         where name = name_in and
               version = version_in;
    end if;

    if not found then
        name_id = nextval('rhn_pkg_capability_id_seq');
        insert into rhnPackageCapability(id, name, version) values (
               name_id, name_in, version_in);
    end if;

    return name_id;
end;
$$
language plpgsql;
07070100000CF6000081B400000000000000000000000167AE111400000998000000000000000000000000000000000000006800000000susemanager-schema/upgrade/susemanager-schema-3.2.7-to-susemanager-schema-3.2.8/101-lookup_checksum.sql   --
-- Copyright (c) 2010 - 2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

create or replace function
lookup_checksum(checksum_type_in in varchar, checksum_in in varchar)
returns numeric
as
$$
declare
    checksum_id     numeric;
begin
    if checksum_in is null then
        return null;
    end if;

    select c.id
      into checksum_id
      from rhnChecksumView c
     where c.checksum = checksum_in and
           c.checksum_type = checksum_type_in;

    if not found then
        checksum_id := nextval('rhnchecksum_seq');

        insert into rhnChecksum (id, checksum_type_id, checksum)
          values (
              checksum_id,
              (select id from rhnChecksumType where label = checksum_type_in),
              checksum_in
          )
          on conflict do nothing;

          select c.id
              into strict checksum_id
              from rhnChecksumView c
              where c.checksum = checksum_in and
                  c.checksum_type = checksum_type_in;
    end if;

    return checksum_id;
end;
$$ language plpgsql;

-- NOTE: This is intentionally not thread safe! You must lock rhnChecksum
-- if you are going to use this procedure!
create or replace function
lookup_checksum_fast(checksum_type_in in varchar, checksum_in in varchar)
returns numeric
as
$$
declare
    checksum_id     numeric;
begin
    if checksum_in is null then
        return null;
    end if;

    select c.id
      into checksum_id
      from rhnChecksumView c
     where c.checksum = checksum_in and
           c.checksum_type = checksum_type_in;

    if not found then
        checksum_id := nextval('rhnchecksum_seq');
        insert into rhnChecksum (id, checksum_type_id, checksum) values (
            checksum_id,
            (select id from rhnChecksumType where label = checksum_type_in),
            checksum_in);
    end if;

    return checksum_id;
end;
$$
language plpgsql;
07070100000CF7000081B400000000000000000000000167AE1114000004F9000000000000000000000000000000000000007100000000susemanager-schema/upgrade/susemanager-schema-3.2.7-to-susemanager-schema-3.2.8/102-lookup_client_capability.sql  --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 

create or replace function
lookup_client_capability(name_in in varchar)
returns numeric
as $$
declare
    cap_name_id     numeric;
begin
    select id
      into cap_name_id
      from rhnclientcapabilityname
     where name = name_in;

    if not found then
        cap_name_id := nextval('rhn_client_capname_id_seq');

        insert into rhnClientCapabilityName(id, name)
            values (cap_name_id, name_in)
            on conflict do nothing;

        select id
            into strict cap_name_id
            from rhnclientcapabilityname
            where name = name_in;
    end if;

    return cap_name_id;
end;
$$ language plpgsql;
   07070100000CF8000081B400000000000000000000000167AE1114000004C4000000000000000000000000000000000000006F00000000susemanager-schema/upgrade/susemanager-schema-3.2.7-to-susemanager-schema-3.2.8/103-lookup_config_filename.sql    --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.

create or replace function
lookup_config_filename(name_in in varchar)
returns numeric as
$$
declare
    name_id     numeric;
begin
    select id
      into name_id
      from rhnconfigfilename
     where path = name_in;

    if not found then
        name_id := nextval('rhn_cfname_id_seq');

        insert into rhnConfigFileName (id, path)
            values (name_id, name_in)
            on conflict do nothing;

        select id
            into strict name_id
            from rhnconfigfilename
            where path = name_in;
    end if;

    return name_id;
end;
$$ language plpgsql;
07070100000CF9000081B400000000000000000000000167AE1114000007FC000000000000000000000000000000000000006B00000000susemanager-schema/upgrade/susemanager-schema-3.2.7-to-susemanager-schema-3.2.8/104-lookup_config_info.sql    --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

create or replace function
lookup_config_info
(
    username_in     in varchar,
    groupname_in    in varchar,
    filemode_in     in numeric,
    selinux_ctx_in  in varchar,
    symlink_target_id in numeric
)
returns numeric
as
$$
declare
    r numeric;
    v_id    numeric;
    lookup_cursor cursor  for
        select id
          from rhnConfigInfo
         where 1=1
           and (username = username_in or (username is null and username_in is null))
           and (groupname = groupname_in or (groupname is null and groupname_in is null))
           and (filemode = filemode_in or (filemode is null and filemode_in is null))
           and (selinux_ctx = selinux_ctx_in or
               (selinux_ctx is null and selinux_ctx_in is null))
           and (symlink_target_filename_id = symlink_target_id or
               (symlink_target_filename_id is null and symlink_target_id is null))
        ;
begin
    for r in lookup_cursor loop
        return r.id;
    end loop;
    -- If we got here, we don't have the id
    v_id := nextval('rhn_confinfo_id_seq');

    insert into rhnConfigInfo (id, username, groupname, filemode, selinux_ctx, symlink_target_filename_id)
        values (v_id, username_in, groupname_in, filemode_in, selinux_ctx_in, symlink_target_id)
        on conflict do nothing;

    for r in lookup_cursor loop
        return r.id;
    end loop;
    return v_id;
end;
$$ language plpgsql;
07070100000CFA000081B400000000000000000000000167AE111400000494000000000000000000000000000000000000006300000000susemanager-schema/upgrade/susemanager-schema-3.2.7-to-susemanager-schema-3.2.8/105-lookup_cve.sql    --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.

create or replace function
lookup_cve(name_in in varchar)
returns numeric
as $$
declare
    name_id     numeric;
begin
    select id
      into name_id
      from rhnCVE
     where name = name_in;

    if not found then
        name_id := nextval('rhn_cve_id_seq');

        insert into rhnCVE (id, name)
            values (name_id, name_in)
            on conflict do nothing;

        select id
            into strict name_id
            from rhnCVE
            where name = name_in;
    end if;

    return name_id;
end;
$$ language plpgsql;
07070100000CFB000081B400000000000000000000000167AE1114000005B6000000000000000000000000000000000000006300000000susemanager-schema/upgrade/susemanager-schema-3.2.7-to-susemanager-schema-3.2.8/106-lookup_evr.sql    --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.

create or replace function
lookup_evr(e_in in varchar, v_in in varchar, r_in in varchar)
returns numeric
as
$$
declare
    evr_id  numeric;
begin
    select id
      into evr_id
      from rhnPackageEVR
     where ((epoch is null and e_in is null) or (epoch = e_in)) and
           version = v_in and
           release = r_in;

    if not found then
        evr_id := nextval('rhn_pkg_evr_seq');

        insert into rhnPackageEVR(id, epoch, version, release, evr)
            values (evr_id, e_in, v_in, r_in, evr_t(e_in, v_in, r_in))
            on conflict do nothing;

        select id
            into strict evr_id
            from rhnPackageEVR
            where ((epoch is null and e_in is null) or (epoch = e_in)) and
               version = v_in and release = r_in;
    end if;

    return evr_id;
end;
$$ language plpgsql;
  07070100000CFC000081B400000000000000000000000167AE111400000419000000000000000000000000000000000000006A00000000susemanager-schema/upgrade/susemanager-schema-3.2.7-to-susemanager-schema-3.2.8/107-lookup_md_keyword.sql --
-- Copyright (c) 2012 Novell
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--

create or replace function
lookup_md_keyword(label_in in varchar)
returns numeric
as
$$
declare
    md_keyword_id numeric;
begin
    select id
      into md_keyword_id
      from suseMdKeyword
     where label = label_in;
    if not found then
        md_keyword_id := nextval('suse_mdkeyword_id_seq');

        insert into suseMdKeyword (id, label)
            values (md_keyword_id, label_in)
            on conflict do nothing;

        select id
            into strict md_keyword_id
            from suseMdKeyword
            where label = label_in;
    end if;

    return md_keyword_id;
end;
$$ language plpgsql;
   07070100000CFD000081B400000000000000000000000167AE1114000004BA000000000000000000000000000000000000006D00000000susemanager-schema/upgrade/susemanager-schema-3.2.7-to-susemanager-schema-3.2.8/108-lookup_package_delta.sql  --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 

create or replace function lookup_package_delta(n_in in varchar)
returns numeric
as
$$
declare
    name_id     numeric;
begin
    select id
      into name_id
      from rhnPackageDelta
     where label = n_in;

    if not found then
        name_id := nextval('rhn_packagedelta_id_seq');

        insert into rhnPackageDelta(id, label)
            values (name_id, n_in)
            on conflict do nothing;

        select id
            into strict name_id
            from rhnpackagedelta
            where label = n_in;
    end if;

    return name_id;
end;
$$ language plpgsql;
  07070100000CFE000081B400000000000000000000000167AE1114000004D4000000000000000000000000000000000000006D00000000susemanager-schema/upgrade/susemanager-schema-3.2.7-to-susemanager-schema-3.2.8/109-lookup_package_group.sql  --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 

create or replace function
lookup_package_group(name_in in varchar)
returns numeric
as
$$
declare
    package_id   numeric;
begin
    select id
      into package_id
      from rhnPackageGroup
     where name = name_in;

    if not found then
        package_id := nextval('rhn_package_group_id_seq');

        insert into rhnPackageGroup(id, name)
            values (package_id, name_in)
            on conflict do nothing;

        select id
            into strict package_id
            from rhnPackageGroup
            where name = name_in;
    end if;

    return package_id;
end;
$$ language plpgsql;
07070100000CFF000081B400000000000000000000000167AE11140000052C000000000000000000000000000000000000006C00000000susemanager-schema/upgrade/susemanager-schema-3.2.7-to-susemanager-schema-3.2.8/110-lookup_package_name.sql   --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 

create or replace function
lookup_package_name(name_in in varchar, ignore_null in numeric default 0)
returns numeric
as
$$
declare
    name_id     numeric;
begin
    if ignore_null = 1 and name_in is null then
        return null;
    end if;

    select id
      into name_id
      from rhnPackageName
     where name = name_in;

    if not found then
        name_id := nextval('rhn_pkg_name_seq');

        insert into rhnPackageName(id, name)
            values (name_id, name_in)
            on conflict do nothing;

        select id
            into strict name_id
            from rhnPackageName
            where name = name_in;
    end if;

    return name_id;
end;
$$ language plpgsql;
07070100000D00000081B400000000000000000000000167AE111400000724000000000000000000000000000000000000006D00000000susemanager-schema/upgrade/susemanager-schema-3.2.7-to-susemanager-schema-3.2.8/111-lookup_package_nevra.sql  --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 

create or replace function
lookup_package_nevra(
        name_id_in in numeric,
        evr_id_in in numeric,
        package_arch_id_in in numeric,
        ignore_null_name in numeric default 0
) returns numeric
as
$$
declare
    nevra_id numeric;
begin
    if ignore_null_name = 1 and name_id_in is null then
        return null;
    end if;

    select id
      into nevra_id
      from rhnPackageNEVRA
     where name_id = name_id_in and
           evr_id = evr_id_in and
           (package_arch_id = package_arch_id_in or
            (package_arch_id is null and package_arch_id_in is null));

    if not found then
        nevra_id := nextval('rhn_pkgnevra_id_seq');

        insert into rhnPackageNEVRA(id, name_id, evr_id, package_arch_id)
            values (nevra_id, name_id_in, evr_id_in, package_arch_id_in)
            on conflict do nothing;

        select id
            into strict nevra_id
            from rhnPackageNEVRA
            where name_id = name_id_in and evr_id = evr_id_in and
                (package_arch_id = package_arch_id_in or
                (package_arch_id is null and package_arch_id_in is null));
    end if;

    return nevra_id;
end;
$$ language plpgsql;
07070100000D01000081B400000000000000000000000167AE1114000004BF000000000000000000000000000000000000006B00000000susemanager-schema/upgrade/susemanager-schema-3.2.7-to-susemanager-schema-3.2.8/112-lookup_source_name.sql    --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 

create or replace function
lookup_source_name(name_in in varchar)
returns numeric
as
$$
declare
    source_id   numeric;
begin
    select id
      into source_id
      from rhnSourceRPM
     where name = name_in;

    if not found then
        source_id := nextval('rhn_sourcerpm_id_seq');

        insert into rhnSourceRPM(id, name)
            values (source_id, name_in)
            on conflict do nothing;

        select id
            into strict source_id
            from rhnSourceRPM
            where name = name_in;
    end if;

    return source_id;
end;
$$ language plpgsql;
 07070100000D02000081B400000000000000000000000167AE111400000567000000000000000000000000000000000000006300000000susemanager-schema/upgrade/susemanager-schema-3.2.7-to-susemanager-schema-3.2.8/113-lookup_tag.sql    --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 

create or replace function
lookup_tag(org_id_in in numeric, name_in in varchar)
returns numeric
as $$
declare
    tag_id  numeric;
    tag_name_id numeric;
begin
    tag_name_id := lookup_tag_name(name_in);

    select id
      into tag_id
      from rhnTag
     where org_id = org_id_in and
           name_id = tag_name_id;

    if not found then
        tag_id := nextval('rhn_tag_id_seq');

        insert into rhnTag(id, org_id, name_id)
            values (tag_id, org_id_in, tag_name_id)
            on conflict do nothing;

        select id
            into strict tag_id
            from rhnTag
            where org_id = org_id_in and
                name_id = lookup_tag_name(name_in);
    end if;

    return tag_id;
end;
$$ language plpgsql;
 07070100000D03000081B400000000000000000000000167AE1114000004A6000000000000000000000000000000000000006800000000susemanager-schema/upgrade/susemanager-schema-3.2.7-to-susemanager-schema-3.2.8/114-lookup_tag_name.sql   --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 

create or replace function
lookup_tag_name(name_in in varchar)
returns numeric
as
$$
declare
    name_id numeric;
begin
    select id
      into name_id
      from rhnTagName
     where name = name_in;

    if not found then
        name_id := nextval('rhn_tagname_id_seq');

        insert into rhnTagName(id, name)
            values (name_id, name_in)
            on conflict do nothing;

        select id
            into strict name_id
            from rhnTagName
            where name = name_in;
    end if;

    return name_id;
end;
$$ language plpgsql;
  07070100000D04000081B400000000000000000000000167AE11140000088B000000000000000000000000000000000000007300000000susemanager-schema/upgrade/susemanager-schema-3.2.7-to-susemanager-schema-3.2.8/115-lookup_transaction_package.sql    --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 

create or replace function
lookup_transaction_package(
    o_in in varchar,
    n_in in varchar,
    e_in in varchar,
    v_in in varchar,
    r_in in varchar,
    a_in in varchar)
returns numeric
as
$$
declare
    o_id        numeric;
    n_id        numeric;
    e_id        numeric;
    p_arch_id   numeric;
    tp_id       numeric;
begin
    select id
      into o_id
      from rhnTransactionOperation
     where label = o_in;

    if not found then
        perform rhn_exception.raise_exception('invalid_transaction_operation');
    end if;

    n_id := lookup_package_name(n_in);
    e_id := lookup_evr(e_in, v_in, r_in);
    p_arch_id := null;

    if a_in is not null then
        p_arch_id := lookup_package_arch(a_in);
    end if;

    select id
      into tp_id
      from rhnTransactionPackage
     where operation = o_id and
           name_id = n_id and
           evr_id = e_id and
           (package_arch_id = p_arch_id or (p_arch_id is null and package_arch_id is null));

    if not found then
        tp_id := nextval('rhn_transpack_id_seq');

        insert into rhnTransactionPackage (id, operation, name_id, evr_id, package_arch_id)
            values (tp_id, o_id, n_id, e_id, p_arch_id)
            on conflict do nothing;

        select id
            into strict tp_id
            from rhnTransactionPackage
         where operation = o_id and name_id = n_id and evr_id = e_id and
            (package_arch_id = p_arch_id or (p_arch_id is null and package_arch_id is null));
    end if;
    return tp_id;
end;
$$ language plpgsql;
 07070100000D05000081B400000000000000000000000167AE11140000056C000000000000000000000000000000000000006F00000000susemanager-schema/upgrade/susemanager-schema-3.2.7-to-susemanager-schema-3.2.8/116-lookup_xccdf_benchmark.sql    --
-- Copyright (c) 2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

create or replace function
lookup_xccdf_benchmark(identifier_in in varchar, version_in in varchar)
returns numeric
as
$$
declare
    benchmark_id numeric;
begin
    select id
      into benchmark_id
      from rhnXccdfBenchmark
     where identifier = identifier_in and version = version_in;

    if not found then
        benchmark_id := nextval('rhn_xccdf_benchmark_id_seq');

        insert into rhnXccdfBenchmark (id, identifier, version)
            values (benchmark_id, identifier_in, version_in)
            on conflict do nothing;

        select id
            into strict benchmark_id
            from rhnXccdfBenchmark
            where identifier = identifier_in and version = version_in;
    end if;

    return benchmark_id;
end;
$$ language plpgsql;
07070100000D06000081B400000000000000000000000167AE111400000764000000000000000000000000000000000000006B00000000susemanager-schema/upgrade/susemanager-schema-3.2.7-to-susemanager-schema-3.2.8/117-lookup_xccdf_ident.sql    --
-- Copyright (c) 2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.

create or replace function
lookup_xccdf_ident(system_in in varchar, identifier_in in varchar)
returns numeric
as
$$
declare
    xccdf_ident_id numeric;
    ident_sys_id numeric;
begin
    select id
      into ident_sys_id
      from rhnXccdfIdentSystem
     where system = system_in;
    if not found then
        ident_sys_id := nextval('rhn_xccdf_identsytem_id_seq');

        insert into rhnXccdfIdentSystem (id, system)
            values (ident_sys_id, system_in)
            on conflict do nothing;

        select id
            into strict ident_sys_id
            from rhnXccdfIdentSystem
            where system = system_in;
    end if;

    select id
      into xccdf_ident_id
      from rhnXccdfIdent
     where identsystem_id = ident_sys_id and identifier = identifier_in;
    if not found then
        xccdf_ident_id := nextval('rhn_xccdf_ident_id_seq');

        insert into rhnXccdfIdent (id, identsystem_id, identifier)
            values (xccdf_ident_id, ident_sys_id, identifier_in)
            on conflict do nothing;

        select id
            into strict xccdf_ident_id
            from rhnXccdfIdent
            where identsystem_id = ident_sys_id and identifier = identifier_in;
    end if;
    return xccdf_ident_id;
end;
$$ language plpgsql;
07070100000D07000081B400000000000000000000000167AE111400000541000000000000000000000000000000000000006D00000000susemanager-schema/upgrade/susemanager-schema-3.2.7-to-susemanager-schema-3.2.8/118-lookup_xccdf_profile.sql  --
-- Copyright (c) 2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

create or replace function
lookup_xccdf_profile(identifier_in in varchar, title_in in varchar)
returns numeric
as
$$
declare
    profile_id numeric;
begin
    select id
      into profile_id
      from rhnXccdfProfile
     where identifier = identifier_in and title = title_in;

    if not found then
        profile_id := nextval('rhn_xccdf_profile_id_seq');

        insert into rhnXccdfProfile (id, identifier, title)
            values (profile_id, identifier_in, title_in)
            on conflict do nothing;

        select id
            into profile_id
            from rhnXccdfProfile
            where identifier = identifier_in and title = title_in;
    end if;

    return profile_id;
end;
$$ language plpgsql;
   07070100000D08000081B400000000000000000000000167AE111400000521000000000000000000000000000000000000006B00000000susemanager-schema/upgrade/susemanager-schema-3.2.7-to-susemanager-schema-3.2.8/119-create_pxt_session.sql    -- retrieved from ./1241042199/53fa26df463811901487b608eecc3f77ca7783a1/schema/spacewalk/oracle/procs/create_pxt_session.sql
--
-- Copyright (c) 2008--2015 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--

create or replace function
create_pxt_session(p_web_user_id in numeric, p_expires in numeric, p_value in varchar)
returns numeric as $$
declare
	l_id numeric;
begin
    l_id := nextval( 'pxt_id_seq' );

    insert into PXTSessions (id, value, expires, web_user_id)
        values (l_id, p_value, p_expires, p_web_user_id)
        on conflict do nothing;

    select id
        into strict l_id
        from PXTSessions
        where value = p_value and expires = p_expires and web_user_id = p_web_user_id;

	  return l_id;
end;
$$ language plpgsql;
   07070100000D09000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005000000000susemanager-schema/upgrade/susemanager-schema-3.2.8-to-susemanager-schema-3.2.9   07070100000D0A000081B400000000000000000000000167AE111400000000000000000000000000000000000000000000005B00000000susemanager-schema/upgrade/susemanager-schema-3.2.8-to-susemanager-schema-3.2.9/.gitignore    07070100000D0B000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005100000000susemanager-schema/upgrade/susemanager-schema-3.2.9-to-susemanager-schema-3.2.10  07070100000D0C000081B400000000000000000000000167AE111400000096000000000000000000000000000000000000007500000000susemanager-schema/upgrade/susemanager-schema-3.2.9-to-susemanager-schema-3.2.10/000-fix-suse_img_repodigest_idx.sql  DROP INDEX suse_img_repodigest_idx;

CREATE UNIQUE INDEX suse_img_repodigest_idx
    ON suseImageRepoDigest(repo_digest, image_history_id)
    
    ;
  07070100000D0D000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005000000000susemanager-schema/upgrade/susemanager-schema-4.0.0-to-susemanager-schema-4.0.1   07070100000D0E000081B400000000000000000000000167AE111400000000000000000000000000000000000000000000005900000000susemanager-schema/upgrade/susemanager-schema-4.0.0-to-susemanager-schema-4.0.1/.gitkeep  07070100000D0F000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005000000000susemanager-schema/upgrade/susemanager-schema-4.0.1-to-susemanager-schema-4.0.2   07070100000D10000081B400000000000000000000000167AE111400000115000000000000000000000000000000000000006900000000susemanager-schema/upgrade/susemanager-schema-4.0.1-to-susemanager-schema-4.0.2/003-rhnKSInstallType.sql  insert into rhnKSInstallType (id, label, name) (
        select sequence_nextval('rhn_ksinstalltype_id_seq'),
               'rhel_8','Red Hat Enterprise Linux 8'
          from dual
         where not exists (select 1 from rhnKSInstallType where  label = 'rhel_8')
        );
   07070100000D11000081B400000000000000000000000167AE111400035F7F000000000000000000000000000000000000006D00000000susemanager-schema/upgrade/susemanager-schema-4.0.1-to-susemanager-schema-4.0.2/004-rhnKickstartTimezome.sql  insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
               'Africa/Abidjan',
               'Africa/Abidjan',
               (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Africa/Abidjan'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Accra',
                'Africa/Accra',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Africa/Accra'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Addis_Ababa',
                'Africa/Addis_Ababa',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Africa/Addis_Ababa'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Algiers',
                'Africa/Algiers',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Africa/Algiers'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Asmara',
                'Africa/Asmara',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Africa/Asmara'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Bamako',
                'Africa/Bamako',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Africa/Bamako'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Bangui',
                'Africa/Bangui',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Africa/Bangui'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Banjul',
                'Africa/Banjul',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Africa/Banjul'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Bissau',
                'Africa/Bissau',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Africa/Bissau'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Blantyre',
                'Africa/Blantyre',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Africa/Blantyre'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Brazzaville',
                'Africa/Brazzaville',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Africa/Brazzaville'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Bujumbura',
                'Africa/Bujumbura',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Africa/Bujumbura'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Cairo',
                'Africa/Cairo',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Africa/Cairo'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Casablanca',
                'Africa/Casablanca',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Africa/Casablanca'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Ceuta',
                'Africa/Ceuta',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Africa/Ceuta'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Conakry',
                'Africa/Conakry',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Africa/Conakry'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Dakar',
                'Africa/Dakar',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Africa/Dakar'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Dar_es_Salaam',
                'Africa/Dar_es_Salaam',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Africa/Dar_es_Salaam'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Djibouti',
                'Africa/Djibouti',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Africa/Djibouti'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Douala',
                'Africa/Douala',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Africa/Douala'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/El_Aaiun',
                'Africa/El_Aaiun',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Africa/El_Aaiun'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Freetown',
                'Africa/Freetown',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Africa/Freetown'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Gaborone',
                'Africa/Gaborone',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Africa/Gaborone'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Harare',
                'Africa/Harare',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Africa/Harare'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Johannesburg',
                'Africa/Johannesburg',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Africa/Johannesburg'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Juba',
                'Africa/Juba',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Africa/Juba'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Kampala',
                'Africa/Kampala',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Africa/Kampala'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Khartoum',
                'Africa/Khartoum',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Africa/Khartoum'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Kigali',
                'Africa/Kigali',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Africa/Kigali'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Kinshasa',
                'Africa/Kinshasa',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Africa/Kinshasa'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Lagos',
                'Africa/Lagos',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Africa/Lagos'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Libreville',
                'Africa/Libreville',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Africa/Libreville'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Lome',
                'Africa/Lome',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Africa/Lome'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Luanda',
                'Africa/Luanda',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Africa/Luanda'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Lubumbashi',
                'Africa/Lubumbashi',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Africa/Lubumbashi'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Lusaka',
                'Africa/Lusaka',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Africa/Lusaka'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Malabo',
                'Africa/Malabo',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Africa/Malabo'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Maputo',
                'Africa/Maputo',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Africa/Maputo'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Maseru',
                'Africa/Maseru',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Africa/Maseru'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Mbabane',
                'Africa/Mbabane',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Africa/Mbabane'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Mogadishu',
                'Africa/Mogadishu',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Africa/Mogadishu'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Monrovia',
                'Africa/Monrovia',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Africa/Monrovia'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Nairobi',
                'Africa/Nairobi',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Africa/Nairobi'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Ndjamena',
                'Africa/Ndjamena',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Africa/Ndjamena'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Niamey',
                'Africa/Niamey',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Africa/Niamey'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Nouakchott',
                'Africa/Nouakchott',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Africa/Nouakchott'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Ouagadougou',
                'Africa/Ouagadougou',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Africa/Ouagadougou'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Porto-Novo',
                'Africa/Porto-Novo',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Africa/Porto-Novo'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Sao_Tome',
                'Africa/Sao_Tome',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Africa/Sao_Tome'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Tripoli',
                'Africa/Tripoli',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Africa/Tripoli'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Tunis',
                'Africa/Tunis',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Africa/Tunis'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Windhoek',
                'Africa/Windhoek',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Africa/Windhoek'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Adak',
                'America/Adak',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Adak'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Anchorage',
                'America/Anchorage',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Anchorage'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Anguilla',
                'America/Anguilla',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Anguilla'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Antigua',
                'America/Antigua',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Antigua'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Araguaina',
                'America/Araguaina',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Araguaina'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Argentina/Buenos_Aires',
                'America/Argentina/Buenos_Aires',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Argentina/Buenos_Aires'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Argentina/Catamarca',
                'America/Argentina/Catamarca',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Argentina/Catamarca'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Argentina/Cordoba',
                'America/Argentina/Cordoba',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Argentina/Cordoba'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Argentina/Jujuy',
                'America/Argentina/Jujuy',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Argentina/Jujuy'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Argentina/La_Rioja',
                'America/Argentina/La_Rioja',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Argentina/La_Rioja'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Argentina/Mendoza',
                'America/Argentina/Mendoza',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Argentina/Mendoza'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Argentina/Rio_Gallegos',
                'America/Argentina/Rio_Gallegos',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Argentina/Rio_Gallegos'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Argentina/Salta',
                'America/Argentina/Salta',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Argentina/Salta'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Argentina/San_Juan',
                'America/Argentina/San_Juan',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Argentina/San_Juan'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Argentina/San_Luis',
                'America/Argentina/San_Luis',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Argentina/San_Luis'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Argentina/Tucuman',
                'America/Argentina/Tucuman',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Argentina/Tucuman'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Argentina/Ushuaia',
                'America/Argentina/Ushuaia',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Argentina/Ushuaia'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Aruba',
                'America/Aruba',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Aruba'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Asuncion',
                'America/Asuncion',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Asuncion'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Atikokan',
                'America/Atikokan',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Atikokan'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Bahia',
                'America/Bahia',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Bahia'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Bahia_Banderas',
                'America/Bahia_Banderas',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Bahia_Banderas'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Barbados',
                'America/Barbados',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Barbados'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Belem',
                'America/Belem',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Belem'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Belize',
                'America/Belize',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Belize'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Blanc-Sablon',
                'America/Blanc-Sablon',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Blanc-Sablon'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Boa_Vista',
                'America/Boa_Vista',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Boa_Vista'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Bogota',
                'America/Bogota',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Bogota'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Boise',
                'America/Boise',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Boise'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Cambridge_Bay',
                'America/Cambridge_Bay',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Cambridge_Bay'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Campo_Grande',
                'America/Campo_Grande',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Campo_Grande'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Cancun',
                'America/Cancun',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Cancun'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Caracas',
                'America/Caracas',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Caracas'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Cayenne',
                'America/Cayenne',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Cayenne'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Cayman',
                'America/Cayman',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Cayman'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Chicago',
                'America/Chicago',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Chicago'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Chihuahua',
                'America/Chihuahua',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Chihuahua'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Costa_Rica',
                'America/Costa_Rica',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Costa_Rica'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Creston',
                'America/Creston',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Creston'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Cuiaba',
                'America/Cuiaba',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Cuiaba'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Curacao',
                'America/Curacao',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Curacao'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Danmarkshavn',
                'America/Danmarkshavn',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Danmarkshavn'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Dawson',
                'America/Dawson',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Dawson'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Dawson_Creek',
                'America/Dawson_Creek',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Dawson_Creek'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Denver',
                'America/Denver',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Denver'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Detroit',
                'America/Detroit',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Detroit'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Dominica',
                'America/Dominica',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Dominica'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Edmonton',
                'America/Edmonton',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Edmonton'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Eirunepe',
                'America/Eirunepe',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Eirunepe'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/El_Salvador',
                'America/El_Salvador',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/El_Salvador'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Fortaleza',
                'America/Fortaleza',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Fortaleza'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Glace_Bay',
                'America/Glace_Bay',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Glace_Bay'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Godthab',
                'America/Godthab',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Godthab'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Goose_Bay',
                'America/Goose_Bay',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Goose_Bay'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Grand_Turk',
                'America/Grand_Turk',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Grand_Turk'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Grenada',
                'America/Grenada',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Grenada'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Guadeloupe',
                'America/Guadeloupe',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Guadeloupe'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Guatemala',
                'America/Guatemala',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Guatemala'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Guayaquil',
                'America/Guayaquil',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Guayaquil'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Guyana',
                'America/Guyana',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Guyana'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Halifax',
                'America/Halifax',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Halifax'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Havana',
                'America/Havana',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Havana'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Hermosillo',
                'America/Hermosillo',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Hermosillo'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Indiana/Indianapolis',
                'America/Indiana/Indianapolis',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Indiana/Indianapolis'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Indiana/Knox',
                'America/Indiana/Knox',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Indiana/Knox'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Indiana/Marengo',
                'America/Indiana/Marengo',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Indiana/Marengo'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Indiana/Petersburg',
                'America/Indiana/Petersburg',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Indiana/Petersburg'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Indiana/Tell_City',
                'America/Indiana/Tell_City',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Indiana/Tell_City'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Indiana/Vevay',
                'America/Indiana/Vevay',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Indiana/Vevay'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Indiana/Vincennes',
                'America/Indiana/Vincennes',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Indiana/Vincennes'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Indiana/Winamac',
                'America/Indiana/Winamac',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Indiana/Winamac'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Inuvik',
                'America/Inuvik',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Inuvik'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Iqaluit',
                'America/Iqaluit',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Iqaluit'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Jamaica',
                'America/Jamaica',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Jamaica'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Juneau',
                'America/Juneau',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Juneau'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Kentucky/Louisville',
                'America/Kentucky/Louisville',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Kentucky/Louisville'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Kentucky/Monticello',
                'America/Kentucky/Monticello',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Kentucky/Monticello'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Kralendijk',
                'America/Kralendijk',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Kralendijk'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/La_Paz',
                'America/La_Paz',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/La_Paz'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Lima',
                'America/Lima',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Lima'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Los_Angeles',
                'America/Los_Angeles',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Los_Angeles'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Lower_Princes',
                'America/Lower_Princes',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Lower_Princes'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Maceio',
                'America/Maceio',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Maceio'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Managua',
                'America/Managua',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Managua'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Manaus',
                'America/Manaus',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Manaus'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Marigot',
                'America/Marigot',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Marigot'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Martinique',
                'America/Martinique',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Martinique'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Matamoros',
                'America/Matamoros',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Matamoros'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Mazatlan',
                'America/Mazatlan',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Mazatlan'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Menominee',
                'America/Menominee',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Menominee'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Merida',
                'America/Merida',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Merida'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Metlakatla',
                'America/Metlakatla',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Metlakatla'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Mexico_City',
                'America/Mexico_City',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Mexico_City'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Miquelon',
                'America/Miquelon',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Miquelon'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Moncton',
                'America/Moncton',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Moncton'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Monterrey',
                'America/Monterrey',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Monterrey'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Montevideo',
                'America/Montevideo',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Montevideo'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Montreal',
                'America/Montreal',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Montreal'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Montserrat',
                'America/Montserrat',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Montserrat'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Nassau',
                'America/Nassau',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Nassau'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/New_York',
                'America/New_York',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/New_York'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Nipigon',
                'America/Nipigon',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Nipigon'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Nome',
                'America/Nome',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Nome'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Noronha',
                'America/Noronha',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Noronha'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/North_Dakota/Beulah',
                'America/North_Dakota/Beulah',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/North_Dakota/Beulah'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/North_Dakota/Center',
                'America/North_Dakota/Center',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/North_Dakota/Center'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/North_Dakota/New_Salem',
                'America/North_Dakota/New_Salem',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/North_Dakota/New_Salem'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Ojinaga',
                'America/Ojinaga',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Ojinaga'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Panama',
                'America/Panama',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Panama'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Pangnirtung',
                'America/Pangnirtung',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Pangnirtung'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Paramaribo',
                'America/Paramaribo',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Paramaribo'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Phoenix',
                'America/Phoenix',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Phoenix'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Port_of_Spain',
                'America/Port_of_Spain',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Port_of_Spain'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Port-au-Prince',
                'America/Port-au-Prince',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Port-au-Prince'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Porto_Velho',
                'America/Porto_Velho',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Porto_Velho'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Puerto_Rico',
                'America/Puerto_Rico',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Puerto_Rico'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Rainy_River',
                'America/Rainy_River',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Rainy_River'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Rankin_Inlet',
                'America/Rankin_Inlet',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Rankin_Inlet'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Recife',
                'America/Recife',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Recife'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Regina',
                'America/Regina',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Regina'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Resolute',
                'America/Resolute',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Resolute'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Rio_Branco',
                'America/Rio_Branco',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Rio_Branco'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Santa_Isabel',
                'America/Santa_Isabel',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Santa_Isabel'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Santarem',
                'America/Santarem',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Santarem'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Santiago',
                'America/Santiago',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Santiago'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Santo_Domingo',
                'America/Santo_Domingo',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Santo_Domingo'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Sao_Paulo',
                'America/Sao_Paulo',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Sao_Paulo'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Scoresbysund',
                'America/Scoresbysund',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Scoresbysund'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Shiprock',
                'America/Shiprock',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Shiprock'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Sitka',
                'America/Sitka',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Sitka'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/St_Barthelemy',
                'America/St_Barthelemy',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/St_Barthelemy'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/St_Johns',
                'America/St_Johns',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/St_Johns'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/St_Kitts',
                'America/St_Kitts',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/St_Kitts'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/St_Lucia',
                'America/St_Lucia',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/St_Lucia'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/St_Thomas',
                'America/St_Thomas',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/St_Thomas'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/St_Vincent',
                'America/St_Vincent',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/St_Vincent'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Swift_Current',
                'America/Swift_Current',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Swift_Current'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Tegucigalpa',
                'America/Tegucigalpa',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Tegucigalpa'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Thule',
                'America/Thule',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Thule'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Thunder_Bay',
                'America/Thunder_Bay',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Thunder_Bay'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Tijuana',
                'America/Tijuana',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Tijuana'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Toronto',
                'America/Toronto',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Toronto'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Tortola',
                'America/Tortola',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Tortola'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Vancouver',
                'America/Vancouver',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Vancouver'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Whitehorse',
                'America/Whitehorse',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Whitehorse'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Winnipeg',
                'America/Winnipeg',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Winnipeg'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Yakutat',
                'America/Yakutat',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Yakutat'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Yellowknife',
                'America/Yellowknife',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Yellowknife'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Antarctica/Casey',
                'Antarctica/Casey',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Antarctica/Casey'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Antarctica/Davis',
                'Antarctica/Davis',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Antarctica/Davis'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Antarctica/DumontDUrville',
                'Antarctica/DumontDUrville',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Antarctica/DumontDUrville'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Antarctica/Macquarie',
                'Antarctica/Macquarie',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Antarctica/Macquarie'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Antarctica/Mawson',
                'Antarctica/Mawson',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Antarctica/Mawson'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Antarctica/McMurdo',
                'Antarctica/McMurdo',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Antarctica/McMurdo'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Antarctica/Palmer',
                'Antarctica/Palmer',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Antarctica/Palmer'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Antarctica/Rothera',
                'Antarctica/Rothera',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Antarctica/Rothera'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Antarctica/South_Pole',
                'Antarctica/South_Pole',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Antarctica/South_Pole'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Antarctica/Syowa',
                'Antarctica/Syowa',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Antarctica/Syowa'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Antarctica/Vostok',
                'Antarctica/Vostok',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Antarctica/Vostok'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Arctic/Longyearbyen',
                'Arctic/Longyearbyen',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Arctic/Longyearbyen'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Aden',
                'Asia/Aden',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Asia/Aden'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Almaty',
                'Asia/Almaty',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Asia/Almaty'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Amman',
                'Asia/Amman',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Asia/Amman'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Anadyr',
                'Asia/Anadyr',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Asia/Anadyr'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Aqtau',
                'Asia/Aqtau',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Asia/Aqtau'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Aqtobe',
                'Asia/Aqtobe',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Asia/Aqtobe'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Ashgabat',
                'Asia/Ashgabat',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Asia/Ashgabat'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Baghdad',
                'Asia/Baghdad',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Asia/Baghdad'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Bahrain',
                'Asia/Bahrain',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Asia/Bahrain'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Baku',
                'Asia/Baku',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Asia/Baku'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Bangkok',
                'Asia/Bangkok',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Asia/Bangkok'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Beirut',
                'Asia/Beirut',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Asia/Beirut'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Bishkek',
                'Asia/Bishkek',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Asia/Bishkek'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Brunei',
                'Asia/Brunei',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Asia/Brunei'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Choibalsan',
                'Asia/Choibalsan',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Asia/Choibalsan'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Chongqing',
                'Asia/Chongqing',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Asia/Chongqing'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Colombo',
                'Asia/Colombo',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Asia/Colombo'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Damascus',
                'Asia/Damascus',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Asia/Damascus'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Dhaka',
                'Asia/Dhaka',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Asia/Dhaka'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Dili',
                'Asia/Dili',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Asia/Dili'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Dubai',
                'Asia/Dubai',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Asia/Dubai'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Dushanbe',
                'Asia/Dushanbe',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Asia/Dushanbe'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Gaza',
                'Asia/Gaza',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Asia/Gaza'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Harbin',
                'Asia/Harbin',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Asia/Harbin'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Hebron',
                'Asia/Hebron',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Asia/Hebron'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Ho_Chi_Minh',
                'Asia/Ho_Chi_Minh',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Asia/Ho_Chi_Minh'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Hong_Kong',
                'Asia/Hong_Kong',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Asia/Hong_Kong'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Hovd',
                'Asia/Hovd',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Asia/Hovd'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Irkutsk',
                'Asia/Irkutsk',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Asia/Irkutsk'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Jakarta',
                'Asia/Jakarta',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Asia/Jakarta'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Jayapura',
                'Asia/Jayapura',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Asia/Jayapura'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Jerusalem',
                'Asia/Jerusalem',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Asia/Jerusalem'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Kabul',
                'Asia/Kabul',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Asia/Kabul'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Kamchatka',
                'Asia/Kamchatka',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Asia/Kamchatka'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Karachi',
                'Asia/Karachi',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Asia/Karachi'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Kashgar',
                'Asia/Kashgar',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Asia/Kashgar'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Kathmandu',
                'Asia/Kathmandu',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Asia/Kathmandu'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Kolkata',
                'Asia/Kolkata',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Asia/Kolkata'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Krasnoyarsk',
                'Asia/Krasnoyarsk',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Asia/Krasnoyarsk'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Kuala_Lumpur',
                'Asia/Kuala_Lumpur',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Asia/Kuala_Lumpur'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Kuching',
                'Asia/Kuching',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Asia/Kuching'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Kuwait',
                'Asia/Kuwait',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Asia/Kuwait'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Macau',
                'Asia/Macau',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Asia/Macau'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Magadan',
                'Asia/Magadan',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Asia/Magadan'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Makassar',
                'Asia/Makassar',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Asia/Makassar'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Manila',
                'Asia/Manila',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Asia/Manila'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Muscat',
                'Asia/Muscat',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Asia/Muscat'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Nicosia',
                'Asia/Nicosia',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Asia/Nicosia'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Novokuznetsk',
                'Asia/Novokuznetsk',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Asia/Novokuznetsk'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Novosibirsk',
                'Asia/Novosibirsk',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Asia/Novosibirsk'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Omsk',
                'Asia/Omsk',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Asia/Omsk'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Oral',
                'Asia/Oral',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Asia/Oral'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Phnom_Penh',
                'Asia/Phnom_Penh',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Asia/Phnom_Penh'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Pontianak',
                'Asia/Pontianak',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Asia/Pontianak'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Pyongyang',
                'Asia/Pyongyang',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Asia/Pyongyang'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Qatar',
                'Asia/Qatar',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Asia/Qatar'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Qyzylorda',
                'Asia/Qyzylorda',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Asia/Qyzylorda'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Rangoon',
                'Asia/Rangoon',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Asia/Rangoon'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Riyadh',
                'Asia/Riyadh',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Asia/Riyadh'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Sakhalin',
                'Asia/Sakhalin',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Asia/Sakhalin'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Samarkand',
                'Asia/Samarkand',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Asia/Samarkand'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Seoul',
                'Asia/Seoul',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Asia/Seoul'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Shanghai',
                'Asia/Shanghai',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Asia/Shanghai'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Singapore',
                'Asia/Singapore',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Asia/Singapore'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Taipei',
                'Asia/Taipei',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Asia/Taipei'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Tashkent',
                'Asia/Tashkent',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Asia/Tashkent'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Tbilisi',
                'Asia/Tbilisi',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Asia/Tbilisi'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Tehran',
                'Asia/Tehran',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Asia/Tehran'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Thimphu',
                'Asia/Thimphu',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Asia/Thimphu'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Tokyo',
                'Asia/Tokyo',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Asia/Tokyo'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Ulaanbaatar',
                'Asia/Ulaanbaatar',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Asia/Ulaanbaatar'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Urumqi',
                'Asia/Urumqi',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Asia/Urumqi'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Vientiane',
                'Asia/Vientiane',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Asia/Vientiane'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Vladivostok',
                'Asia/Vladivostok',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Asia/Vladivostok'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Yakutsk',
                'Asia/Yakutsk',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Asia/Yakutsk'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Yekaterinburg',
                'Asia/Yekaterinburg',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Asia/Yekaterinburg'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Yerevan',
                'Asia/Yerevan',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Asia/Yerevan'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Atlantic/Azores',
                'Atlantic/Azores',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Atlantic/Azores'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Atlantic/Bermuda',
                'Atlantic/Bermuda',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Atlantic/Bermuda'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Atlantic/Canary',
                'Atlantic/Canary',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Atlantic/Canary'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Atlantic/Cape_Verde',
                'Atlantic/Cape_Verde',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Atlantic/Cape_Verde'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Atlantic/Faroe',
                'Atlantic/Faroe',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Atlantic/Faroe'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Atlantic/Madeira',
                'Atlantic/Madeira',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Atlantic/Madeira'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Atlantic/Reykjavik',
                'Atlantic/Reykjavik',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Atlantic/Reykjavik'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Atlantic/South_Georgia',
                'Atlantic/South_Georgia',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Atlantic/South_Georgia'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Atlantic/St_Helena',
                'Atlantic/St_Helena',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Atlantic/St_Helena'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Atlantic/Stanley',
                'Atlantic/Stanley',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Atlantic/Stanley'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Australia/Adelaide',
                'Australia/Adelaide',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Australia/Adelaide'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Australia/Brisbane',
                'Australia/Brisbane',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Australia/Brisbane'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Australia/Broken_Hill',
                'Australia/Broken_Hill',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Australia/Broken_Hill'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Australia/Currie',
                'Australia/Currie',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Australia/Currie'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Australia/Darwin',
                'Australia/Darwin',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Australia/Darwin'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Australia/Eucla',
                'Australia/Eucla',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Australia/Eucla'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Australia/Hobart',
                'Australia/Hobart',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Australia/Hobart'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Australia/Lindeman',
                'Australia/Lindeman',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Australia/Lindeman'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Australia/Lord_Howe',
                'Australia/Lord_Howe',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Australia/Lord_Howe'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Australia/Melbourne',
                'Australia/Melbourne',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Australia/Melbourne'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Australia/Perth',
                'Australia/Perth',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Australia/Perth'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Australia/Sydney',
                'Australia/Sydney',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Australia/Sydney'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Amsterdam',
                'Europe/Amsterdam',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Europe/Amsterdam'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Andorra',
                'Europe/Andorra',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Europe/Andorra'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Athens',
                'Europe/Athens',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Europe/Athens'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Belgrade',
                'Europe/Belgrade',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Europe/Belgrade'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Berlin',
                'Europe/Berlin',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Europe/Berlin'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Bratislava',
                'Europe/Bratislava',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Europe/Bratislava'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Brussels',
                'Europe/Brussels',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Europe/Brussels'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Bucharest',
                'Europe/Bucharest',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Europe/Bucharest'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Budapest',
                'Europe/Budapest',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Europe/Budapest'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Chisinau',
                'Europe/Chisinau',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Europe/Chisinau'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Copenhagen',
                'Europe/Copenhagen',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Europe/Copenhagen'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Dublin',
                'Europe/Dublin',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Europe/Dublin'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Gibraltar',
                'Europe/Gibraltar',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Europe/Gibraltar'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Guernsey',
                'Europe/Guernsey',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Europe/Guernsey'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Helsinki',
                'Europe/Helsinki',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Europe/Helsinki'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Isle_of_Man',
                'Europe/Isle_of_Man',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Europe/Isle_of_Man'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Istanbul',
                'Europe/Istanbul',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Europe/Istanbul'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Jersey',
                'Europe/Jersey',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Europe/Jersey'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Kaliningrad',
                'Europe/Kaliningrad',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Europe/Kaliningrad'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Kiev',
                'Europe/Kiev',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Europe/Kiev'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Lisbon',
                'Europe/Lisbon',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Europe/Lisbon'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Ljubljana',
                'Europe/Ljubljana',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Europe/Ljubljana'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/London',
                'Europe/London',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Europe/London'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Luxembourg',
                'Europe/Luxembourg',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Europe/Luxembourg'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Madrid',
                'Europe/Madrid',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Europe/Madrid'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Malta',
                'Europe/Malta',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Europe/Malta'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Mariehamn',
                'Europe/Mariehamn',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Europe/Mariehamn'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Minsk',
                'Europe/Minsk',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Europe/Minsk'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Monaco',
                'Europe/Monaco',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Europe/Monaco'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Moscow',
                'Europe/Moscow',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Europe/Moscow'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Oslo',
                'Europe/Oslo',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Europe/Oslo'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Paris',
                'Europe/Paris',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Europe/Paris'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Podgorica',
                'Europe/Podgorica',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Europe/Podgorica'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Prague',
                'Europe/Prague',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Europe/Prague'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Riga',
                'Europe/Riga',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Europe/Riga'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Rome',
                'Europe/Rome',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Europe/Rome'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Samara',
                'Europe/Samara',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Europe/Samara'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/San_Marino',
                'Europe/San_Marino',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Europe/San_Marino'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Sarajevo',
                'Europe/Sarajevo',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Europe/Sarajevo'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Simferopol',
                'Europe/Simferopol',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Europe/Simferopol'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Skopje',
                'Europe/Skopje',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Europe/Skopje'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Sofia',
                'Europe/Sofia',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Europe/Sofia'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Stockholm',
                'Europe/Stockholm',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Europe/Stockholm'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Tallinn',
                'Europe/Tallinn',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Europe/Tallinn'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Tirane',
                'Europe/Tirane',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Europe/Tirane'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Uzhgorod',
                'Europe/Uzhgorod',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Europe/Uzhgorod'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Vaduz',
                'Europe/Vaduz',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Europe/Vaduz'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Vatican',
                'Europe/Vatican',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Europe/Vatican'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Vienna',
                'Europe/Vienna',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Europe/Vienna'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Vilnius',
                'Europe/Vilnius',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Europe/Vilnius'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Volgograd',
                'Europe/Volgograd',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Europe/Volgograd'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Warsaw',
                'Europe/Warsaw',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Europe/Warsaw'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Zagreb',
                'Europe/Zagreb',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Europe/Zagreb'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Zaporozhye',
                'Europe/Zaporozhye',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Europe/Zaporozhye'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Zurich',
                'Europe/Zurich',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Europe/Zurich'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Indian/Antananarivo',
                'Indian/Antananarivo',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Indian/Antananarivo'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Indian/Chagos',
                'Indian/Chagos',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Indian/Chagos'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Indian/Christmas',
                'Indian/Christmas',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Indian/Christmas'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Indian/Cocos',
                'Indian/Cocos',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Indian/Cocos'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Indian/Comoro',
                'Indian/Comoro',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Indian/Comoro'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Indian/Kerguelen',
                'Indian/Kerguelen',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Indian/Kerguelen'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Indian/Mahe',
                'Indian/Mahe',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Indian/Mahe'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Indian/Maldives',
                'Indian/Maldives',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Indian/Maldives'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Indian/Mauritius',
                'Indian/Mauritius',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Indian/Mauritius'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Indian/Mayotte',
                'Indian/Mayotte',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Indian/Mayotte'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Indian/Reunion',
                'Indian/Reunion',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Indian/Reunion'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Apia',
                'Pacific/Apia',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Pacific/Apia'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Auckland',
                'Pacific/Auckland',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Pacific/Auckland'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Chatham',
                'Pacific/Chatham',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Pacific/Chatham'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Chuuk',
                'Pacific/Chuuk',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Pacific/Chuuk'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Easter',
                'Pacific/Easter',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Pacific/Easter'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Efate',
                'Pacific/Efate',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Pacific/Efate'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Enderbury',
                'Pacific/Enderbury',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Pacific/Enderbury'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Fakaofo',
                'Pacific/Fakaofo',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Pacific/Fakaofo'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Fiji',
                'Pacific/Fiji',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Pacific/Fiji'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Funafuti',
                'Pacific/Funafuti',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Pacific/Funafuti'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Galapagos',
                'Pacific/Galapagos',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Pacific/Galapagos'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Gambier',
                'Pacific/Gambier',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Pacific/Gambier'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Guadalcanal',
                'Pacific/Guadalcanal',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Pacific/Guadalcanal'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Guam',
                'Pacific/Guam',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Pacific/Guam'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Honolulu',
                'Pacific/Honolulu',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Pacific/Honolulu'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Johnston',
                'Pacific/Johnston',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Pacific/Johnston'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Kiritimati',
                'Pacific/Kiritimati',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Pacific/Kiritimati'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Kosrae',
                'Pacific/Kosrae',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Pacific/Kosrae'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Kwajalein',
                'Pacific/Kwajalein',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Pacific/Kwajalein'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Majuro',
                'Pacific/Majuro',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Pacific/Majuro'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Marquesas',
                'Pacific/Marquesas',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Pacific/Marquesas'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Midway',
                'Pacific/Midway',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Pacific/Midway'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Nauru',
                'Pacific/Nauru',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Pacific/Nauru'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Niue',
                'Pacific/Niue',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Pacific/Niue'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Norfolk',
                'Pacific/Norfolk',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Pacific/Norfolk'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Noumea',
                'Pacific/Noumea',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Pacific/Noumea'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Pago_Pago',
                'Pacific/Pago_Pago',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Pacific/Pago_Pago'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Palau',
                'Pacific/Palau',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Pacific/Palau'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Pitcairn',
                'Pacific/Pitcairn',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Pacific/Pitcairn'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Pohnpei',
                'Pacific/Pohnpei',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Pacific/Pohnpei'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Port_Moresby',
                'Pacific/Port_Moresby',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Pacific/Port_Moresby'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Rarotonga',
                'Pacific/Rarotonga',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Pacific/Rarotonga'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Saipan',
                'Pacific/Saipan',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Pacific/Saipan'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Tahiti',
                'Pacific/Tahiti',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Pacific/Tahiti'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Tarawa',
                'Pacific/Tarawa',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Pacific/Tarawa'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Tongatapu',
                'Pacific/Tongatapu',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Pacific/Tongatapu'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Wake',
                'Pacific/Wake',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Pacific/Wake'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Wallis',
                'Pacific/Wallis',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Pacific/Wallis'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_8'));

 07070100000D12000081B400000000000000000000000167AE1114000000E7000000000000000000000000000000000000007600000000susemanager-schema/upgrade/susemanager-schema-4.0.1-to-susemanager-schema-4.0.2/005-add_virt_delete_rhnActionType.sql insert into rhnActionType (id, label, name, trigger_snapshot, unlocked_only) (
    select 507, 'virt.delete', 'Deletes a virtual domain.', 'N', 'N'
    from dual
    where not exists (select 1 from rhnActionType where id = 507)
);
 07070100000D13000081B400000000000000000000000167AE111400000259000000000000000000000000000000000000007000000000susemanager-schema/upgrade/susemanager-schema-4.0.1-to-susemanager-schema-4.0.2/006-add_rhnVirtActionDelete.sql   -- oracle equivalent source none
CREATE TABLE IF NOT EXISTS rhnActionVirtDelete
(
    action_id  NUMERIC NOT NULL
                   CONSTRAINT rhn_avdl_aid_fk
                       REFERENCES rhnAction (id)
                       ON DELETE CASCADE
                    CONSTRAINT rhn_avdl_aid_pk PRIMARY KEY,
    uuid       VARCHAR(128) NOT NULL,
    created    TIMESTAMPTZ
               DEFAULT (current_timestamp) NOT NULL,
    modified   TIMESTAMPTZ
               DEFAULT (current_timestamp) NOT NULL
);

CREATE UNIQUE INDEX IF NOT EXISTS rhn_avdl_aid_uq
    ON rhnActionVirtDelete (action_id);
   07070100000D14000081B400000000000000000000000167AE11140000005D000000000000000000000000000000000000007A00000000susemanager-schema/upgrade/susemanager-schema-4.0.1-to-susemanager-schema-4.0.2/010-rhnServerNetInterfaceHwAddressIdx.sql CREATE INDEX IF NOT EXISTS rhn_srv_net_iface_hw_addr_idx
ON rhnServerNetInterface (hw_addr);
   07070100000D15000081B400000000000000000000000167AE111400000191000000000000000000000000000000000000006A00000000susemanager-schema/upgrade/susemanager-schema-4.0.1-to-susemanager-schema-4.0.2/100-rhn_avdl_mod_trig.sql -- oracle equivalent source none
create or replace function rhn_avdl_mod_trig_fun() returns trigger as
$$
begin
       new.modified := current_timestamp;
       return new;
end;
$$ language plpgsql;

drop trigger if exists rhn_avdl_mod_trig on rhnActionVirtDelete;
create trigger
rhn_avdl_mod_trig
before insert or update on rhnActionVirtDelete
for each row
execute procedure rhn_avdl_mod_trig_fun();
   07070100000D16000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005200000000susemanager-schema/upgrade/susemanager-schema-4.0.10-to-susemanager-schema-4.0.11 07070100000D17000081B400000000000000000000000167AE1114000007E3000000000000000000000000000000000000007700000000susemanager-schema/upgrade/susemanager-schema-4.0.10-to-susemanager-schema-4.0.11/001-add-minion-checkin-tasko-job.sql    -- Copyright (c) 2019 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--

INSERT INTO rhnTaskoBunch (id, name, description, org_bunch)
    SELECT sequence_nextval('rhn_tasko_bunch_id_seq'), 'minion-checkin-bunch', 'Perform a regular check-in on minions', null
    FROM dual WHERE NOT EXISTS (
        SELECT 1 FROM rhnTaskoBunch WHERE
        name='minion-checkin-bunch'
    );

INSERT INTO rhnTaskoSchedule (id, job_label, bunch_id, active_from, cron_expr)
    SELECT sequence_nextval('rhn_tasko_schedule_id_seq'), 'minion-checkin-default',
        (SELECT id FROM rhnTaskoBunch WHERE name='minion-checkin-bunch'),
        current_timestamp, '0 0 * * * ?'
    FROM dual WHERE NOT EXISTS (
        SELECT 1 FROM rhnTaskoSchedule WHERE
        job_label='minion-checkin-default'
    );

INSERT INTO rhnTaskoTask (id, name, class)
    SELECT sequence_nextval('rhn_tasko_task_id_seq'), 'minion-checkin', 'com.redhat.rhn.taskomatic.task.MinionCheckin'
    FROM dual WHERE NOT EXISTS (
        SELECT 1 FROM rhnTaskoTask WHERE
        name='minion-checkin'
    );

INSERT INTO rhnTaskoTemplate (id, bunch_id, task_id, ordering, start_if)
    SELECT sequence_nextval('rhn_tasko_template_id_seq'),
                        (SELECT id FROM rhnTaskoBunch WHERE name='minion-checkin-bunch'),
                        (SELECT id FROM rhnTaskoTask WHERE name='minion-checkin'),
                        0,
                        null
    FROM dual WHERE NOT EXISTS (
        SELECT 1 FROM rhnTaskoTemplate WHERE
        bunch_id=(SELECT id FROM rhnTaskoBunch WHERE name='minion-checkin-bunch') AND
        task_id=(SELECT id FROM rhnTaskoTask WHERE name='minion-checkin')
    );
 07070100000D18000081B400000000000000000000000167AE11140000009F000000000000000000000000000000000000006E00000000susemanager-schema/upgrade/susemanager-schema-4.0.10-to-susemanager-schema-4.0.11/002-alter-susesaltevent.sql 
DROP INDEX IF EXISTS suse_salt_event_minion_id_idx;

CREATE INDEX IF NOT EXISTS suse_salt_event_minion_id_idx
  ON suseSaltEvent (minion_id NULLS FIRST, id);
 07070100000D19000081B400000000000000000000000167AE111400000290000000000000000000000000000000000000006C00000000susemanager-schema/upgrade/susemanager-schema-4.0.10-to-susemanager-schema-4.0.11/010-drop_state_change.sql   --
--
-- Copyright (c) 2019 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

DROP TABLE IF EXISTS state_change;

07070100000D1A000081B400000000000000000000000167AE1114000000A9000000000000000000000000000000000000007300000000susemanager-schema/upgrade/susemanager-schema-4.0.10-to-susemanager-schema-4.0.11/020-environment-target-state.sql    
ALTER TABLE suseContentEnvironmentTarget ADD COLUMN IF NOT EXISTS status VARCHAR(32) NOT NULL DEFAULT 'NEW';
UPDATE suseContentEnvironmentTarget SET status = 'BUILT';

   07070100000D1B000081B400000000000000000000000167AE111400000121000000000000000000000000000000000000007200000000susemanager-schema/upgrade/susemanager-schema-4.0.10-to-susemanager-schema-4.0.11/030-content-filter-criteria.sql 
ALTER TABLE suseContentFilter ADD COLUMN IF NOT EXISTS matcher VARCHAR(32);
ALTER TABLE suseContentFilter ADD COLUMN IF NOT EXISTS field VARCHAR(32);
ALTER TABLE suseContentFilter ADD COLUMN IF NOT EXISTS value VARCHAR(128);
ALTER TABLE suseContentFilter DROP COLUMN IF EXISTS criteria;

   07070100000D1C000081B400000000000000000000000167AE11140000004B000000000000000000000000000000000000006E00000000susemanager-schema/upgrade/susemanager-schema-4.0.10-to-susemanager-schema-4.0.11/040-content-filter-rule.sql 
ALTER TABLE suseContentFilter ADD COLUMN IF NOT EXISTS rule VARCHAR(16);

 07070100000D1D000081B400000000000000000000000167AE111400000047000000000000000000000000000000000000008100000000susemanager-schema/upgrade/susemanager-schema-4.0.10-to-susemanager-schema-4.0.11/050-drop-susecontentfilterproject-position.sql  
ALTER TABLE suseContentFilterProject DROP COLUMN IF EXISTS position;

 07070100000D1E000081B400000000000000000000000167AE111400000817000000000000000000000000000000000000007500000000susemanager-schema/upgrade/susemanager-schema-4.0.10-to-susemanager-schema-4.0.11/060-add-monitoring-entitlement.sql  -- monitoring_entitled type ----------------------------------------------------

insert into rhnServerGroupType (id, label, name, permanent, is_base)
   select sequence_nextval('rhn_servergroup_type_seq'),
      'monitoring_entitled', 'Monitoring',
      'N', 'N'
   from dual where not exists (
       SELECT 1 FROM rhnServerGroupType WHERE
       label='monitoring_entitled'
   );

-- monitoring_entitled base compatibility

insert into rhnSGTypeBaseAddonCompat (base_id, addon_id)
    select lookup_sg_type('salt_entitled'),
        lookup_sg_type('monitoring_entitled')
    from dual where not exists(
        select 1 from rhnSGTypeBaseAddonCompat where
        base_id=lookup_sg_type('salt_entitled') and
        addon_id=lookup_sg_type('monitoring_entitled')
    );

-- monitoring_entitled compatibilities

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type)
    select lookup_server_arch('amd64-redhat-linux'),
            lookup_sg_type('monitoring_entitled')
    from dual where not exists (
        select 1 from rhnServerServerGroupArchCompat where
        server_arch_id=lookup_server_arch('amd64-redhat-linux') and
        server_group_type=lookup_sg_type('monitoring_entitled')
    );

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type)
    select lookup_server_arch('x86_64-redhat-linux'),
            lookup_sg_type('monitoring_entitled')
    from dual where not exists (
        select 1 from rhnServerServerGroupArchCompat where
        server_arch_id=lookup_server_arch('x86_64-redhat-linux') and
        server_group_type=lookup_sg_type('monitoring_entitled')
    );

-- add monitoring entitlement to all orgs

insert into rhnServerGroup
        ( id, name, description, group_type, org_id )
        select nextval('rhn_server_group_id_seq'), sgt.name, sgt.name, sgt.id, org.id
        from rhnServerGroupType sgt, web_customer org
        where sgt.label = 'monitoring_entitled' and org.id not in (
            select sg.org_id from rhnServerGroup sg where sg.name = 'Monitoring'
        );
 07070100000D1F000081B400000000000000000000000167AE11140000078A000000000000000000000000000000000000006900000000susemanager-schema/upgrade/susemanager-schema-4.0.10-to-susemanager-schema-4.0.11/061-entitle-server.sql  -- setup search_path so that these functions are created in appropriate schema.
update pg_settings set setting = 'rhn_entitlements,' || setting where name = 'search_path';

    create or replace function entitle_server (
        server_id_in in numeric,
        type_label_in in varchar
    ) returns void
as $$
    declare
      sgid  numeric := 0;

    begin

      if rhn_entitlements.can_entitle_server(server_id_in,
                                             type_label_in) = 1 then
         sgid := rhn_entitlements.find_compatible_sg (server_id_in,
                                                      type_label_in);
         if sgid is not null then
            insert into rhnServerHistory ( id, server_id, summary, details )
            values ( nextval('rhn_event_id_seq'), server_id_in,
                     'added system entitlement ',
                      case type_label_in
                       when 'enterprise_entitled' then 'Management'
                       when 'bootstrap_entitled' then 'Bootstrap'
                       when 'salt_entitled' then 'Salt'
                       when 'foreign_entitled' then 'Foreign'
                       when 'virtualization_host' then 'Virtualization'
                       when 'container_build_host' then 'Container'
                       when 'osimage_build_host' then 'OS Image'
                       when 'monitoring_entitled' then 'Monitoring'
                      end  );

            perform rhn_server.insert_into_servergroup (server_id_in, sgid);

         else
            perform rhn_exception.raise_exception ('no_available_server_group');
         end if;
      else
         perform rhn_exception.raise_exception ('invalid_entitlement');
      end if;
   end$$
language plpgsql;

-- restore the original setting
update pg_settings set setting = overlay( setting placing '' from 1 for (length('rhn_entitlements')+1) ) where name = 'search_path';
  07070100000D20000081B400000000000000000000000167AE111400001D05000000000000000000000000000000000000006900000000susemanager-schema/upgrade/susemanager-schema-4.0.10-to-susemanager-schema-4.0.11/062-create-new-org.sql  create or replace function create_new_org
(
        name_in      in varchar,
        password_in  in varchar
        --org_id_out   out NUMERIC
) returns numeric
as
$$
declare
        ug_type                 numeric;
        group_val               numeric;
        new_org_id              numeric;
        org_id_out		numeric;
begin

        select nextval('web_customer_id_seq') into new_org_id from dual;

        insert into web_customer (
                id, name
        ) values (
                new_org_id, name_in
        );

        select nextval('rhn_user_group_id_seq') into group_val from dual;

        select  id
        into    ug_type
        from    rhnUserGroupType
        where   label = 'org_admin';

        insert into rhnUserGroup (
                id, name,
                description,
                max_members, group_type, org_id
        ) values (
                group_val, 'Organization Administrators',
                'Organization Administrators for Org ' || name_in,
                NULL, ug_type, new_org_id
        );

        select nextval('rhn_user_group_id_seq') into group_val from dual;

        select  id
        into    ug_type
        from    rhnUserGroupType
        where   label = 'system_group_admin';

        insert into rhnUserGroup (
                id, name,
                description,
                max_members, group_type, org_id
        ) values (
                group_val, 'System Group Administrators',
                'System Group Administrators for Org ' || name_in,
                NULL, ug_type, new_org_id
        );


        select nextval('rhn_user_group_id_seq') into group_val from dual;

        select  id
        into    ug_type
        from    rhnUserGroupType
        where   label = 'activation_key_admin';

        insert into rhnUserGroup (
                id, name,
                description,
                max_members, group_type, org_id
        ) values (
                group_val, 'Activation Key Administrators',
                'Activation Key Administrators for Org ' || name_in,
                NULL, ug_type, new_org_id
        );

        select nextval('rhn_user_group_id_seq') into group_val from dual;

        select  id
        into    ug_type
        from    rhnUserGroupType
        where   label = 'channel_admin';

        insert into rhnUserGroup (
                id, name,
                description,
                max_members, group_type, org_id
        ) values (
                group_val, 'Channel Administrators',
                'Channel Administrators for Org ' || name_in,
                NULL, ug_type, new_org_id
        );

	if new_org_id = 1 then
            select nextval('rhn_user_group_id_seq') into group_val from dual;

            select  id
            into    ug_type
            from    rhnUserGroupType
            where   label = 'satellite_admin';

            insert into rhnUserGroup (
                    id, name,
                    description,
                    max_members, group_type, org_id
            ) values (
                    group_val, 'SUSE Manager Administrators',
                    'SUSE Manager Administrators for Org ' || name_in,
                    NULL, ug_type, new_org_id
            );
        end if;

        select nextval('rhn_user_group_id_seq') into group_val from dual;

        select  id
        into    ug_type
        from    rhnUserGroupType
        where   label = 'config_admin';

        insert into rhnUserGroup (
                id, name,
                description,
                max_members, group_type, org_id
        ) values (
                group_val, 'Configuration Administrators',
                'Configuration Administrators for Org ' || name_in,
                NULL, ug_type, new_org_id
        );

        select nextval('rhn_user_group_id_seq') into group_val from dual;

        select  id
        into    ug_type
        from    rhnUserGroupType
        where   label = 'image_admin';

        insert into rhnUserGroup (
                id, name,
                description,
                max_members, group_type, org_id
        ) values (
                group_val, 'Image Administrators',
                'Image Administrators for Org ' || name_in,
                NULL, ug_type, new_org_id
        );

        -- there aren't any users yet, so we don't need to update
        -- rhnUserServerPerms

        insert into rhnServerGroup
                ( id, name, description, group_type, org_id )
                select nextval('rhn_server_group_id_seq'), sgt.name, sgt.name,
                        sgt.id, new_org_id
                from rhnServerGroupType sgt
                where sgt.label = 'bootstrap_entitled';

        insert into rhnServerGroup
                ( id, name, description, group_type, org_id )
                select nextval('rhn_server_group_id_seq'), sgt.name, sgt.name,
                        sgt.id, new_org_id
                from rhnServerGroupType sgt
                where sgt.label = 'enterprise_entitled';

        insert into rhnServerGroup
                ( id, name, description, group_type, org_id )
                select nextval('rhn_server_group_id_seq'), sgt.name, sgt.name,
                        sgt.id, new_org_id
                from rhnServerGroupType sgt
                where sgt.label = 'salt_entitled';

        insert into rhnServerGroup
                ( id, name, description, group_type, org_id )
                select nextval('rhn_server_group_id_seq'), sgt.name, sgt.name,
                        sgt.id, new_org_id
                from rhnServerGroupType sgt
                where sgt.label = 'foreign_entitled';

        insert into rhnServerGroup
                ( id, name, description, group_type, org_id )
                select nextval('rhn_server_group_id_seq'), sgt.name, sgt.name,
                        sgt.id, new_org_id
                from rhnServerGroupType sgt
                where sgt.label = 'virtualization_host';

        insert into rhnServerGroup
                ( id, name, description, group_type, org_id )
                select nextval('rhn_server_group_id_seq'), sgt.name, sgt.name,
                        sgt.id, new_org_id
                from rhnServerGroupType sgt
                where sgt.label = 'container_build_host';

        insert into rhnServerGroup
                ( id, name, description, group_type, org_id )
                select nextval('rhn_server_group_id_seq'), sgt.name, sgt.name,
                        sgt.id, new_org_id
                from rhnServerGroupType sgt
                where sgt.label = 'osimage_build_host';

        insert into rhnServerGroup
                ( id, name, description, group_type, org_id )
                select nextval('rhn_server_group_id_seq'), sgt.name, sgt.name,
                        sgt.id, new_org_id
                from rhnServerGroupType sgt
                where sgt.label = 'monitoring_entitled';

        insert into suseImageStore (id, label, uri, store_type_id, org_id)
        values (
            nextval('suse_imgstore_id_seq'),
            'SUSE Manager OS Image Store',
            new_org_id || '/',
            (SELECT id FROM suseImageStoreType WHERE label = 'os_image'),
            new_org_id
        );

        org_id_out := new_org_id;

	-- Returning the value of OUT parameter
        return org_id_out;

end;
$$
language plpgsql;   07070100000D21000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005200000000susemanager-schema/upgrade/susemanager-schema-4.0.11-to-susemanager-schema-4.0.12 07070100000D22000081B400000000000000000000000167AE11140000016B000000000000000000000000000000000000006E00000000susemanager-schema/upgrade/susemanager-schema-4.0.11-to-susemanager-schema-4.0.12/001-alter-susesaltevent.sql 
ALTER TABLE suseSaltEvent DROP COLUMN IF EXISTS queue;

ALTER TABLE suseSaltEvent ADD queue NUMERIC;
UPDATE suseSaltEvent SET queue = 0;
ALTER TABLE suseSaltEvent ALTER COLUMN queue SET NOT NULL;

DROP INDEX IF EXISTS suse_salt_event_minion_id_idx;

CREATE INDEX IF NOT EXISTS suse_salt_event_minion_id_idx
  ON suseSaltEvent (queue, minion_id NULLS FIRST, id);
 07070100000D23000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005200000000susemanager-schema/upgrade/susemanager-schema-4.0.12-to-susemanager-schema-4.0.13 07070100000D24000081B400000000000000000000000167AE111400000656000000000000000000000000000000000000006F00000000susemanager-schema/upgrade/susemanager-schema-4.0.12-to-susemanager-schema-4.0.13/001-rhnVirtActions-force.sql    --
--
-- Copyright (c) 2019 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is                                                                                                                                               
-- granted to use or replicate Red Hat trademarks that are incorporated                                                                                                                                            
-- in this software or its documentation.                                                                                                                                                                          
--

ALTER TABLE rhnActionVirtShutdown
    DROP CONSTRAINT IF EXISTS rhn_avshutdown_force_ck;

ALTER TABLE rhnActionVirtShutdown
    ADD COLUMN IF NOT EXISTS force CHAR(1)
       DEFAULT ('N') NOT NULL
       CONSTRAINT rhn_avshutdown_force_ck
           CHECK (force in ('Y','N'));

ALTER TABLE rhnActionVirtReboot
    DROP CONSTRAINT IF EXISTS rhn_avreboot_force_ck;

ALTER TABLE rhnActionVirtReboot
    ADD COLUMN IF NOT EXISTS force CHAR(1)
       DEFAULT ('N') NOT NULL
       CONSTRAINT rhn_avreboot_force_ck
           CHECK (force in ('Y','N'));
  07070100000D25000081B400000000000000000000000167AE111400000032000000000000000000000000000000000000008000000000susemanager-schema/upgrade/susemanager-schema-4.0.12-to-susemanager-schema-4.0.13/002-drop_allServerKeywordSinceReboot_view.sql   
DROP VIEW IF EXISTS allServerKeywordSinceReboot;
  07070100000D26000081B400000000000000000000000167AE11140000005B000000000000000000000000000000000000007700000000susemanager-schema/upgrade/susemanager-schema-4.0.12-to-susemanager-schema-4.0.13/051-suseContentEnvironmentTarget.sql    
ALTER TABLE suseContentEnvironmentTarget ADD COLUMN IF NOT EXISTS built_time TIMESTAMPTZ;
 07070100000D27000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005200000000susemanager-schema/upgrade/susemanager-schema-4.0.13-to-susemanager-schema-4.0.14 07070100000D28000081B400000000000000000000000167AE1114000000E0000000000000000000000000000000000000007A00000000susemanager-schema/upgrade/susemanager-schema-4.0.13-to-susemanager-schema-4.0.14/003-rhnContentSource-rhn_cs_repo_uq.sql 
DROP INDEX rhn_cs_repo_uq;

CREATE UNIQUE INDEX rhn_cs_repo_uq
    ON rhnContentSource(COALESCE(org_id, 0), type_id, source_url,
                            (case when label like 'manifest_%' then 1 else 0 end))
        ;

07070100000D29000081B400000000000000000000000167AE111400001D2D000000000000000000000000000000000000006200000000susemanager-schema/upgrade/susemanager-schema-4.0.13-to-susemanager-schema-4.0.14/004-rpm.pkb.sql -- create schema rpm;

--update pg_setting
update pg_settings set setting = 'rpm,' || setting where name = 'search_path';

create or replace function isdigit(ch CHAR)
    RETURNS BOOLEAN as $$
    BEGIN
        if ascii(ch) between ascii('0') and ascii('9')
        then
            return TRUE;
        end if;
        return FALSE;
    END ;
$$ language 'plpgsql';

    
    create or replace FUNCTION isalpha(ch CHAR)
    RETURNS BOOLEAN as $$
    BEGIN
        if ascii(ch) between ascii('a') and ascii('z') or 
            ascii(ch) between ascii('A') and ascii('Z')
        then
            return TRUE;
        end if;
        return FALSE;
    END;
$$ language 'plpgsql';


    create or replace FUNCTION isalphanum(ch CHAR)
    RETURNS BOOLEAN as $$ 
    BEGIN
        if ascii(ch) between ascii('a') and ascii('z') or 
            ascii(ch) between ascii('A') and ascii('Z') or
            ascii(ch) between ascii('0') and ascii('9')
        then
            return TRUE;
        end if;
        return FALSE;
    END;
    $$ language 'plpgsql';


    create or replace FUNCTION rpmstrcmp (string1 IN VARCHAR, string2 IN VARCHAR)
    RETURNS INTEGER as $$
    declare
        str1 VARCHAR := string1;
        str2 VARCHAR := string2;
        digits VARCHAR(10) := '0123456789';
        lc_alpha VARCHAR(27) := 'abcdefghijklmnopqrstuvwxyz';
        uc_alpha VARCHAR(27) := 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
        alpha VARCHAR(54) := lc_alpha || uc_alpha;
        one VARCHAR;
        two VARCHAR;
        isnum BOOLEAN;
    BEGIN
        if str1 is NULL or str2 is NULL
        then
            RAISE EXCEPTION 'VALUE_ERROR.';
        end if;
      
        if str1 = str2
        then
            return 0;
        end if;
        one := str1;
        two := str2;

        <<segment_loop>>
        while one <> '' or two <> ''
        loop
            declare
                segm1 VARCHAR;
                segm2 VARCHAR;
                onechar CHAR(1);
                twochar CHAR(1);
            begin
                --raise notice 'Params: %, %',  one, two;
                -- Throw out all non-alphanum characters
                onechar := substr(one, 1, 1);
                twochar := substr(two, 1, 1);
                while one <> '' and not rpm.isalphanum(one) and onechar != '~' and onechar != '^'
                loop
                    one := substr(one, 2);
                end loop;
                while two <> '' and not rpm.isalphanum(two) and twochar != '~' and twochar != '^'
                loop
                    two := substr(two, 2);
                end loop;
                --raise notice 'new params: %, %', one, two;

                onechar := substr(one, 1, 1);
                twochar := substr(two, 1, 1);
                --raise notice 'new chars 1: %, %', onechar, twochar;
                /* handle the tilde separator, it sorts before everything else */
                if (onechar = '~' or twochar = '~')
                then
                    if (onechar != '~') then return 1; end if;
                    if (twochar != '~') then return -1; end if;
                    --raise notice 'passed tilde chars: %, %', onechar, twochar;
                    one := substr(one, 2);
                    two := substr(two, 2);
                    continue;
                end if;

                /*
                 * Handle caret separator. Concept is the same as tilde,
                 * except that if one of the strings ends (base version),
                 * the other is considered as higher version.
                 */
                onechar := substr(one, 1, 1);
                twochar := substr(two, 1, 1);
                --raise notice 'new chars 2: %, %', onechar, twochar;
                if (onechar = '^' or twochar = '^')
                then
                    if (one = '') then return -1; end if;
                    --raise notice 'passed caret chars 1: %, %', onechar, twochar;
                    if (two = '') then return 1; end if;
                    --raise notice 'passed caret chars 2: %, %', onechar, twochar;
                    if (onechar != '^') then return 1; end if;
                    --raise notice 'passed caret chars 3: %, %', onechar, twochar;
                    if (twochar != '^') then return -1; end if;
                    --raise notice 'passed caret chars 4: %, %', onechar, twochar;
                    one := substr(one, 2);
                    two := substr(two, 2);
                    continue;
                end if;

                if (not (one <> '' and two <> '')) then exit segment_loop; end if;

                str1 := one;
                str2 := two;
                if rpm.isdigit(str1) or rpm.isdigit(str2)
                then
                    str1 := ltrim(str1, digits);
                    str2 := ltrim(str2, digits);
                    isnum := true;
                else
                    str1 := ltrim(str1, alpha);
                    str2 := ltrim(str2, alpha);
                    isnum := false;
                end if;
                if str1 <> ''
                then segm1 := substr(one, 1, length(one) - length(str1));
                else segm1 := one;
                end if;

                if str2 <> ''
                then segm2 := substr(two, 1, length(two) - length(str2));
                else segm2 := two;
                end if;

                if isnum
                then
                    if segm1 = '' then return -1; end if;
                    if segm2 = '' then return 1; end if;

                    segm1 := ltrim(segm1, '0');
                    segm2 := ltrim(segm2, '0');

                    if segm1 = '' and segm2 <> ''
                    then
                        return -1;
                    end if;
                    if segm1 <> '' and segm2 = ''
                    then
                        return 1;
                    end if;
                    if length(segm1) < length(segm2) then return -1; end if;
                    if length(segm1) > length(segm2) then return 1; end if;
                end if;
                if segm1 < segm2 then return -1; end if;
                if segm1 > segm2 then return 1; end if;
               one := str1;
                two := str2;
            end;
        end loop segment_loop;
     
        if one = '' and two = '' then return 0; end if;
        if one = '' then return -1; end if;
        return 1;
    END ;
$$ language 'plpgsql';



   create or replace FUNCTION vercmp(
        e1 VARCHAR, v1 VARCHAR, r1 VARCHAR, 
        e2 VARCHAR, v2 VARCHAR, r2 VARCHAR)
    RETURNS INTEGER as $$
    declare
        rc INTEGER;
          ep1 INTEGER;
          ep2 INTEGER;
          BEGIN
            if e1 is null or e1 = '' then
              ep1 := 0;
            else
              ep1 := e1::integer;
            end if;
            if e2 is null or e2 = '' then
              ep2 := 0;
            else
              ep2 := e2::integer;
            end if;
            -- Epochs are non-null; compare them
            if ep1 < ep2 then return -1; end if;
            if ep1 > ep2 then return 1; end if;
            rc := rpm.rpmstrcmp(v1, v2);
            if rc != 0 then return rc; end if;
           return rpm.rpmstrcmp(r1, r2);
         END;
         $$ language 'plpgsql';

-- restore the original setting
update pg_settings set setting = overlay( setting placing '' from 1 for (length('rpm')+1) ) where name = 'search_path';

   07070100000D2A000081B400000000000000000000000167AE111400000025000000000000000000000000000000000000007300000000susemanager-schema/upgrade/susemanager-schema-4.0.13-to-susemanager-schema-4.0.14/005-drop_rhnUserChannel_view.sql    
DROP VIEW IF EXISTS rhnUserChannel;
   07070100000D2B000081B400000000000000000000000167AE111400001090000000000000000000000000000000000000007200000000susemanager-schema/upgrade/susemanager-schema-4.0.13-to-susemanager-schema-4.0.14/006-suseChannelUserRoleView.sql --
-- Copyright (c) 2019 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
DROP VIEW IF EXISTS suseChannelUserRoleView;

CREATE OR REPLACE VIEW
suseChannelUserRoleView
AS
  SELECT
    combination.channel_id,
    combination.user_id,
    combination.role,
    combination.user_org_id AS org_id,
    CASE
      -- if channel is in an org trusted by the user's org, and if the channel itself is shared between the two, then user can subscribe it
      WHEN combination.role = 'subscribe' AND sharedChannels.is_shared_channel IS NOT NULL
        THEN NULL
      -- otherwise, if channel is not in user's org, then user can't manage it
      WHEN combination.role = 'manage' AND combination.channel_org_id IS NULL OR combination.channel_org_id <> combination.user_org_id
        THEN 'channel_not_owned'
      -- otherwise, if channel is in a family without permissions for the user's org, then user can't subscribe it
      WHEN combination.role = 'subscribe' AND channelPermissions.is_channel_available IS NULL
        THEN 'channel_not_available'
      -- otherwise, if channel is in a family without permissions for the user's org, then user can't subscribe it
      WHEN adminUsers.is_admin_user IS NOT NULL
        THEN NULL
      -- otherwise, if channel does not have the "not_globally_subscribable" bit set, user can subscribe it
      WHEN combination.role = 'subscribe' AND notGloballySubscribableChannels.is_not_globally_subscribable IS NULL
        THEN NULL
      -- otherwise, user might have an explicit permission on this channel
      WHEN explicitPermissions.has_explicit_permission IS NOT NULL
        THEN NULL
        -- otherwise, user can't either manage nor subscribe the channel
        ELSE 'direct_permission'
    END AS deny_reason
    FROM
      (SELECT
          c.id AS channel_id,
          c.org_id AS channel_org_id,
          u.id AS user_id,
          u.org_id AS user_org_id,
          r.label AS role
          FROM rhnChannel c, web_contact u, rhnChannelPermissionRole r
      ) combination
     LEFT JOIN 
       (SELECT DISTINCT s.org_trust_id, s.id, 1 AS is_shared_channel
        FROM rhnSharedChannelView s) sharedChannels
     ON (sharedChannels.id = combination.channel_id AND sharedChannels.org_trust_id = combination.user_org_id)
     LEFT JOIN
       (SELECT DISTINCT cfp.org_id, cfm.channel_id, 1 AS is_channel_available
        FROM rhnChannelFamilyMembers cfm
          JOIN rhnOrgChannelFamilyPermissions cfp ON cfp.channel_family_id = cfm.channel_family_id) channelPermissions
     ON (combination.user_org_id = channelPermissions.org_id AND channelPermissions.channel_id = combination.channel_id)
     LEFT JOIN
       (SELECT DISTINCT m.user_id, 1 AS is_admin_user
        FROM rhnUserGroupMembers m
          JOIN rhnUserGroup g ON g.id = m.user_group_id
          JOIN rhnUserGroupType t ON t.id = g.group_type
        WHERE t.label = 'channel_admin' OR t.label = 'org_admin') adminUsers
     ON (adminUsers.user_id = combination.user_id)
     LEFT JOIN
       (SELECT DISTINCT ocs.channel_id, ocs.org_id, 1 AS is_not_globally_subscribable
        FROM rhnOrgChannelSettings ocs
          JOIN rhnOrgChannelSettingsType ocst ON ocst.id = ocs.setting_id
        WHERE ocst.label = 'not_globally_subscribable') notGloballySubscribableChannels
     ON (notGloballySubscribableChannels.channel_id = combination.channel_id AND notGloballySubscribableChannels.org_id = combination.user_org_id)
     LEFT JOIN
       (SELECT cpr.label, cp.channel_id, cp.user_id, 1 AS has_explicit_permission
        FROM rhnChannelPermission cp
          JOIN rhnChannelPermissionRole cpr ON cpr.id = cp.role_id) explicitPermissions
     ON (explicitPermissions.channel_id = combination.channel_id AND explicitPermissions.user_id = combination.user_id AND explicitPermissions.label = combination.role)
    -- ORDER BY channel_id, user_id, role, result
;
07070100000D2C000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005200000000susemanager-schema/upgrade/susemanager-schema-4.0.14-to-susemanager-schema-4.0.15 07070100000D2D000081B400000000000000000000000167AE1114000001C2000000000000000000000000000000000000006D00000000susemanager-schema/upgrade/susemanager-schema-4.0.14-to-susemanager-schema-4.0.15/010_kickstart_for_salt.sql  insert into rhnServerGroupTypeFeature (server_group_type_id, feature_id,
                                       created, modified)
select lookup_sg_type('salt_entitled'), lookup_feature_type('ftr_kickstart'),
        current_timestamp,current_timestamp from dual
where not exists ( select 1 from rhnServerGroupTypeFeature
    where server_group_type_id = lookup_sg_type('salt_entitled')
      and feature_id = lookup_feature_type('ftr_kickstart') );
  07070100000D2E000081B400000000000000000000000167AE11140000011D000000000000000000000000000000000000007800000000susemanager-schema/upgrade/susemanager-schema-4.0.14-to-susemanager-schema-4.0.15/011-add-upgrade-ks-action-details.sql   alter table rhnActionKickstart drop CONSTRAINT if exists rhn_actionks_up_ck;
alter table rhnActionKickstart add column if not exists
            upgrade CHAR(1) DEFAULT ('N') NOT NULL
                    CONSTRAINT rhn_actionks_up_ck
                    CHECK (upgrade in ('Y', 'N'));
   07070100000D2F000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005100000000susemanager-schema/upgrade/susemanager-schema-4.0.14-to-susemanager-schema-4.1.0  07070100000D30000081B400000000000000000000000167AE11140000005B000000000000000000000000000000000000005800000000susemanager-schema/upgrade/susemanager-schema-4.0.14-to-susemanager-schema-4.1.0/README   -- Schema upgrade scripts.
-- Intentionally left empty. Please leave this directory empty.
 07070100000D31000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005100000000susemanager-schema/upgrade/susemanager-schema-4.0.15-to-susemanager-schema-4.1.0  07070100000D32000081B400000000000000000000000167AE11140000005B000000000000000000000000000000000000005800000000susemanager-schema/upgrade/susemanager-schema-4.0.15-to-susemanager-schema-4.1.0/README   -- Schema upgrade scripts.
-- Intentionally left empty. Please leave this directory empty.
 07070100000D33000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005100000000susemanager-schema/upgrade/susemanager-schema-4.0.16-to-susemanager-schema-4.1.0  07070100000D34000081B400000000000000000000000167AE11140000005B000000000000000000000000000000000000005800000000susemanager-schema/upgrade/susemanager-schema-4.0.16-to-susemanager-schema-4.1.0/README   -- Schema upgrade scripts.
-- Intentionally left empty. Please leave this directory empty.
 07070100000D35000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005200000000susemanager-schema/upgrade/susemanager-schema-4.0.17-to-susemanager-schema-4.0.18 07070100000D36000081B400000000000000000000000167AE1114000001F9000000000000000000000000000000000000006A00000000susemanager-schema/upgrade/susemanager-schema-4.0.17-to-susemanager-schema-4.0.18/005-fix-none-vendor.sql delete from rhnpackagerepodata where package_id in (select id from rhnpackage where vendor = 'Not defined');

insert into rhnRepoRegenQueue (id, CHANNEL_LABEL, REASON, FORCE)
(select sequence_nextval('rhn_repo_regen_queue_id_seq'),
        C.label,
        'fix empty vendor',
        'Y'
   from rhnChannel C
   where C.id in (select distinct cp.channel_id
                    from rhnpackage p
	            join rhnchannelpackage cp on p.id = cp.package_id
	           where p.vendor = 'Not defined'));
   07070100000D37000081B400000000000000000000000167AE1114000001C6000000000000000000000000000000000000007500000000susemanager-schema/upgrade/susemanager-schema-4.0.17-to-susemanager-schema-4.0.18/010_reactivation_keys_for_salt.sql  insert into rhnServerGroupTypeFeature (server_group_type_id, feature_id,
                                       created, modified)
select lookup_sg_type('salt_entitled'), lookup_feature_type('ftr_agent_smith'),
        current_timestamp,current_timestamp from dual
where not exists ( select 1 from rhnServerGroupTypeFeature
    where server_group_type_id = lookup_sg_type('salt_entitled')
      and feature_id = lookup_feature_type('ftr_agent_smith') );
  07070100000D38000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005100000000susemanager-schema/upgrade/susemanager-schema-4.0.17-to-susemanager-schema-4.1.0  07070100000D39000081B400000000000000000000000167AE11140000005B000000000000000000000000000000000000005800000000susemanager-schema/upgrade/susemanager-schema-4.0.17-to-susemanager-schema-4.1.0/README   -- Schema upgrade scripts.
-- Intentionally left empty. Please leave this directory empty.
 07070100000D3A000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005100000000susemanager-schema/upgrade/susemanager-schema-4.0.18-to-susemanager-schema-4.1.0  07070100000D3B000081B400000000000000000000000167AE11140000005B000000000000000000000000000000000000005800000000susemanager-schema/upgrade/susemanager-schema-4.0.18-to-susemanager-schema-4.1.0/README   -- Schema upgrade scripts.
-- Intentionally left empty. Please leave this directory empty.
 07070100000D3C000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005100000000susemanager-schema/upgrade/susemanager-schema-4.0.19-to-susemanager-schema-4.1.0  07070100000D3D000081B400000000000000000000000167AE11140000005B000000000000000000000000000000000000005800000000susemanager-schema/upgrade/susemanager-schema-4.0.19-to-susemanager-schema-4.1.0/README   -- Schema upgrade scripts.
-- Intentionally left empty. Please leave this directory empty.
 07070100000D3E000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005000000000susemanager-schema/upgrade/susemanager-schema-4.0.2-to-susemanager-schema-4.0.3   07070100000D3F000081B400000000000000000000000167AE1114000000EA000000000000000000000000000000000000006D00000000susemanager-schema/upgrade/susemanager-schema-4.0.2-to-susemanager-schema-4.0.3/002-create-susesaltevent.sql  
CREATE TABLE IF NOT EXISTS suseSaltEvent (
  id SERIAL PRIMARY KEY,
  minion_id CHARACTER VARYING(256),
  data TEXT NOT NULL
);

CREATE INDEX IF NOT EXISTS suse_salt_event_minion_id_idx
  ON suseSaltEvent (minion_id NULLS LAST, id);
  07070100000D40000081B400000000000000000000000167AE11140000068C000000000000000000000000000000000000006E00000000susemanager-schema/upgrade/susemanager-schema-4.0.2-to-susemanager-schema-4.0.3/100-notifications-cleanup.sql INSERT INTO rhnTaskoBunch (id, name, description, org_bunch)
    SELECT sequence_nextval('rhn_tasko_bunch_id_seq'), 'notifications-cleanup-bunch', 'Cleanup expired notification messages', null
    FROM dual WHERE NOT EXISTS (
        SELECT 1 FROM rhnTaskoBunch WHERE
        name='notifications-cleanup-bunch'
    );

INSERT INTO rhnTaskoSchedule (id, job_label, bunch_id, active_from, cron_expr)
    SELECT sequence_nextval('rhn_tasko_schedule_id_seq'), 'notifications-cleanup-default',
        (SELECT id FROM rhnTaskoBunch WHERE name='notifications-cleanup-bunch'),
        current_timestamp, '0 0 0 ? * *'
    FROM dual WHERE NOT EXISTS (
        SELECT 1 FROM rhnTaskoSchedule WHERE
        job_label='notifications-cleanup-default'
    );

INSERT INTO rhnTaskoTask (id, name, class)
    SELECT sequence_nextval('rhn_tasko_task_id_seq'), 'notifications-cleanup', 'com.redhat.rhn.taskomatic.task.NotificationsCleanup'
    FROM dual WHERE NOT EXISTS (
        SELECT 1 FROM rhnTaskoTask WHERE
        name='notifications-cleanup'
    );

INSERT INTO rhnTaskoTemplate (id, bunch_id, task_id, ordering, start_if)
    SELECT sequence_nextval('rhn_tasko_template_id_seq'),
                        (SELECT id FROM rhnTaskoBunch WHERE name='notifications-cleanup-bunch'),
                        (SELECT id FROM rhnTaskoTask WHERE name='notifications-cleanup'),
                        0,
                        null
    FROM dual WHERE NOT EXISTS (
        SELECT 1 FROM rhnTaskoTemplate WHERE
        bunch_id=(SELECT id FROM rhnTaskoBunch WHERE name='notifications-cleanup-bunch') AND
        task_id=(SELECT id FROM rhnTaskoTask WHERE name='notifications-cleanup')
    );

07070100000D41000081B400000000000000000000000167AE1114000001D3000000000000000000000000000000000000006C00000000susemanager-schema/upgrade/susemanager-schema-4.0.2-to-susemanager-schema-4.0.3/199-drop_rhnUserChannel.sql   --
-- Copyright (c) 2018 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--

DROP VIEW IF EXISTS rhnUserChannel;
 07070100000D42000081B400000000000000000000000167AE111400000D7A000000000000000000000000000000000000006900000000susemanager-schema/upgrade/susemanager-schema-4.0.2-to-susemanager-schema-4.0.3/200-suseUserRoleView.sql  --
-- Copyright (c) 2018 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--

DROP VIEW IF EXISTS suseChannelUserRoleView;

CREATE OR REPLACE VIEW
suseChannelUserRoleView
AS
  SELECT
    combination.channel_id,
    combination.user_id,
    combination.role,
    CASE
      -- if channel is in an org trusted by the user's org, and if the channel itself is shared between the two, then user can subscribe it
      WHEN combination.role = 'subscribe' AND combination.user_id IN (
        SELECT u.id
        FROM web_contact u
          JOIN rhnSharedChannelView s ON s.org_trust_id = u.org_id
        WHERE channel_id = combination.channel_id
      )
        THEN NULL
      -- otherwise, if channel is not in user's org, then user can't manage it
      WHEN combination.role = 'manage' AND combination.channel_org_id IS NULL OR combination.channel_org_id <> combination.user_org_id
        THEN 'channel_not_owned'
      -- otherwise, if channel is in a family without permissions for the user's org, then user can't subscribe it
      WHEN combination.role = 'subscribe' AND combination.user_org_id NOT IN (
        SELECT cfp.org_id
          FROM rhnChannelFamilyMembers cfm
            JOIN rhnOrgChannelFamilyPermissions cfp ON cfp.channel_family_id = cfm.channel_family_id
            WHERE cfm.channel_id = combination.channel_id
      )
        THEN 'channel_not_available'
      -- otherwise, if user is a channel admin or an org admin, he can both manage and subscribe it
      WHEN combination.user_id IN (
        SELECT u.id
          FROM web_contact u
            JOIN rhnUserGroupMembers m ON m.user_id = u.id
            JOIN rhnUserGroup g ON g.id = m.user_group_id
            JOIN rhnUserGroupType t ON t.id = g.group_type
          WHERE t.label = 'channel_admin' OR t.label = 'org_admin'
      )
        THEN NULL
      -- otherwise, if channel does not have the "not_globally_subscribable" bit set, user can subscribe it
      WHEN combination.role = 'subscribe' AND combination.channel_id NOT IN (
        SELECT ocs.channel_id
        FROM rhnOrgChannelSettings ocs
          JOIN rhnOrgChannelSettingsType ocst ON ocst.id = ocs.setting_id
        WHERE ocst.label = 'not_globally_subscribable' AND ocs.org_id = combination.user_org_id
      )
        THEN NULL
      -- otherwise, user might have an explicit permission on this channel
      WHEN combination.role IN (
        SELECT cpr.label
          FROM rhnChannelPermission cp
            JOIN rhnChannelPermissionRole cpr ON cpr.id = cp.role_id
          WHERE cp.channel_id = combination.channel_id AND cp.user_id = combination.user_id
      )
        THEN NULL
        -- otherwise, user can't either manage nor subscribe the channel
        ELSE 'direct_permission'
    END AS deny_reason
    FROM
      (SELECT
          c.id AS channel_id,
          c.org_id AS channel_org_id,
          u.id AS user_id,
          u.org_id AS user_org_id,
          r.label AS role
          FROM rhnChannel c, web_contact u, rhnChannelPermissionRole r
      ) combination
    -- ORDER BY channel_id, user_id, role, result
;
  07070100000D43000081B400000000000000000000000167AE11140000719B000000000000000000000000000000000000006800000000susemanager-schema/upgrade/susemanager-schema-4.0.2-to-susemanager-schema-4.0.3/201-rhn_channel.pkb.sql   --
-- Copyright (c) 2008--2018 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--
--
--
--

-- create schema rhn_channel;

--update pg_setting
update pg_settings set setting = 'rhn_channel,' || setting where name = 'search_path';

    -- this "emulates" cursor server_base_subscriptions defined in oracle/rhn_channel.pks
    create or replace function server_base_subscriptions(server_id_in NUMERIC)
    returns boolean as $$
    begin
      return exists(SELECT C.id FROM rhnChannel C, rhnServerChannel SC
		    WHERE C.id = SC.channel_id
		      AND SC.server_id = server_id_in
		      AND C.parent_channel IS NULL);
    end$$ language plpgsql;

    -- this "emulates" cursor server_base_subscriptions defined in oracle/rhn_channel.pks
    create or replace function check_server_subscription(server_id_in NUMERIC, channel_id_in NUMERIC)
    returns boolean as $$
    begin
      return exists(SELECT channel_id FROM rhnServerChannel WHERE server_id = server_id_in AND channel_id = channel_id_in);
    end$$ language plpgsql;


    CREATE OR REPLACE FUNCTION subscribe_server(server_id_in IN NUMERIC, channel_id_in NUMERIC, immediate_in NUMERIC default 1, user_id_in in numeric default null) returns void
    AS $$
    declare
        channel_parent_val      rhnChannel.parent_channel%TYPE;
        parent_subscribed       BOOLEAN;
        server_has_base_chan    BOOLEAN;
        server_already_in_chan  BOOLEAN;
        channel_family_id_val   NUMERIC;
        allowed                 numeric;
    BEGIN
        if user_id_in is not null then
            allowed := rhn_channel.user_role_check(channel_id_in, user_id_in, 'subscribe');
        else
            allowed := 1;
        end if;

        if allowed = 0 then
            perform rhn_exception.raise_exception('no_subscribe_permissions');
        end if;
        
        server_already_in_chan := rhn_channel.check_server_subscription(server_id_in, channel_id_in);

        IF server_already_in_chan
        THEN
            RETURN;
        END IF;

        SELECT parent_channel INTO channel_parent_val FROM rhnChannel WHERE id = channel_id_in;

        IF channel_parent_val IS NOT NULL
        THEN
            -- child channel; if attempting to cross-subscribe a child to the wrong base, silently ignore
            parent_subscribed := rhn_channel.check_server_subscription(server_id_in, channel_parent_val);

            IF NOT parent_subscribed
            THEN
                RETURN;
            END IF;
        ELSE
            -- base channel
            server_has_base_chan := rhn_channel.server_base_subscriptions(server_id_in);

            IF server_has_base_chan
            THEN
                perform rhn_exception.raise_exception('channel_server_one_base');
            END IF;
        END IF;

        channel_family_id_val := rhn_channel.family_for_channel(channel_id_in);
        IF channel_family_id_val IS NULL
        THEN
            perform rhn_exception.raise_exception('channel_subscribe_no_family');
        END IF;

        insert into rhnServerHistory (id,server_id,summary,details) (
            select  nextval('rhn_event_id_seq'),
                    server_id_in,
                    'subscribed to channel ' || SUBSTR(c.label, 0, 106),
                    c.label
            from    rhnChannel c
            where   c.id = channel_id_in
        );

        INSERT INTO rhnServerChannel (server_id, channel_id) VALUES (server_id_in, channel_id_in);

        perform queue_server(server_id_in, immediate_in);

        update rhnServer
           set channels_changed = current_timestamp
         where id = server_id_in;
    END$$ language plpgsql;

    create or replace function guess_server_base(
        server_id_in in numeric
    ) RETURNS numeric as $$
    declare
        server_cursor cursor for
            select s.server_arch_id, s.release, s.org_id
              from rhnServer s
             where s.id = server_id_in;
    -- Cursor that fetches all the possible base channels for a
    -- (server_arch_id, release, org_id) combination
        base_channel_cursor cursor(
                release_in varchar,
                server_arch_id_in numeric,
                org_id_in numeric
        ) for
                select distinct c.*
                from    rhnOrgDistChannelMap                       odcm,
                                rhnServerChannelArchCompat      scac,
                                rhnChannel                                      c
                where   c.parent_channel is null
                        and c.id = odcm.channel_id
                        and c.channel_arch_id = odcm.channel_arch_id
                        and odcm.release = release_in
                        and odcm.for_org_id = org_id_in
                        and scac.server_arch_id = server_arch_id_in
                        and scac.channel_arch_id = c.channel_arch_id;

    begin
        for s in server_cursor loop
            for channel in base_channel_cursor(s.release,
                s.server_arch_id, s.org_id)
            loop
                return channel.id;
            end loop;
        end loop;
        -- Server not found, or no base channel applies to it
        return null;
    end$$ language plpgsql;

    -- Private function
    create or replace function normalize_server_arch(server_arch_in in varchar)
    returns varchar
    as $$
    declare
        suffix VARCHAR(128) := '-redhat-linux';
    begin
        if server_arch_in is NULL then
            return NULL;
        end if;
        if position('-' IN server_arch_in) > 0
        then
            -- Suffix already present
            return server_arch_in;
        end if;
        return server_arch_in || suffix;
    end$$ language plpgsql;

    --
    -- Raises:
    --   server_arch_not_found
    --   no_subscribe_permissions
    create or replace function base_channel_for_release_arch(
        release_in in varchar,
        server_arch_in in varchar,
        org_id_in in numeric default -1,
        user_id_in in numeric default null
    ) returns numeric as $$
    declare
        server_arch varchar(256) := rhn_channel.normalize_server_arch(server_arch_in);
        server_arch_id numeric;
    begin
        -- Look up the server arch
            select id
              into server_arch_id
              from rhnServerArch
             where label = server_arch;
            if not found then
                perform rhn_exception.raise_exception('server_arch_not_found');
            end if;

        return rhn_channel.base_channel_rel_archid(release_in, server_arch_id,
            org_id_in, user_id_in);
    end$$ language plpgsql;

    create or replace function base_channel_rel_archid(
        release_in in varchar,
        server_arch_id_in in numeric,
        org_id_in in numeric default -1,
        user_id_in in numeric default null
    ) returns numeric as $$
    declare
        denied_channel_id numeric := null;
        valid_org_id numeric := org_id_in;
        valid_user_id numeric := user_id_in;
        channel_subscribable numeric;
    -- Cursor that fetches all the possible base channels for a
    -- (server_arch_id, release, org_id) combination
        base_channel_cursor cursor(
                release_in varchar,
                server_arch_id_in numeric,
                org_id_in numeric
        ) for
                select distinct c.*
                from    rhnOrgDistChannelMap                       odcm,
                                rhnServerChannelArchCompat      scac,
                                rhnChannel                                      c
                where   c.parent_channel is null
                        and c.id = odcm.channel_id
                        and c.channel_arch_id = odcm.channel_arch_id
                        and odcm.release = release_in
                        and odcm.for_org_id = org_id_in
                        and scac.server_arch_id = server_arch_id_in
                        and scac.channel_arch_id = c.channel_arch_id;

    begin
        if org_id_in = -1 and user_id_in is not null then
            -- Get the org id from the user id

                select org_id
                  into valid_org_id
                  from web_contact
                 where id = user_id_in;

                if not found then
                    -- User doesn't exist
                    -- XXX Only list public stuff for now
                    valid_user_id := null;
                    valid_org_id := -1;
                end if;
        end if;

        for c in base_channel_cursor(release_in, server_arch_id_in, valid_org_id)
        loop
            -- This row is a possible match
            if valid_user_id is null then
                -- User ID not specified, so no user to channel permissions to
                -- check
                return c.id;
            end if;

            -- Check user to channel permissions
            select rhn_channel.loose_user_role_check(c.id, user_id_in, 'subscribe')
              into channel_subscribable;

            if channel_subscribable = 1 then
                return c.id;
            end if;

            -- Base channel exists, but is not subscribable; keep trying
            denied_channel_id := c.id;
        end loop;

        if denied_channel_id is not null then
            perform rhn_exception.raise_exception('no_subscribe_permissions');
        end if;
        -- No base channel applies
        return NULL;
    end$$ language plpgsql;

    CREATE OR REPLACE FUNCTION clear_subscriptions(server_id_in IN NUMERIC, deleting_server IN NUMERIC default 0) returns void
    AS $$
    declare
        server_channels cursor(server_id_in numeric) for
                select  s.org_id, sc.channel_id, cfm.channel_family_id
                from    rhnServer s,
                        rhnServerChannel sc,
                        rhnChannelFamilyMembers cfm
                where   s.id = server_id_in
                        and s.id = sc.server_id
                        and sc.channel_id = cfm.channel_id
                order by cfm.channel_family_id;
        last_channel_family_id rhnChannelFamilyMembers.channel_family_id%type := -1;
        last_channel_org_id    rhnServer.org_id%type := -1;
    BEGIN
        for channel in server_channels(server_id_in)
        loop
                perform rhn_channel.unsubscribe_server(server_id_in, channel.channel_id, 1, 1, deleting_server);
        end loop;
    END$$ language plpgsql;

    CREATE OR REPLACE FUNCTION unsubscribe_server(server_id_in IN NUMERIC, channel_id_in NUMERIC, immediate_in NUMERIC default 1, unsubscribe_children_in numeric default 0,
                                 deleting_server in numeric default 0) returns void
    AS $$
    declare
        channel_family_id_val   NUMERIC;
        server_org_id_val       NUMERIC;
        server_already_in_chan  BOOLEAN;
        channel_family_is_proxy cursor(channel_family_id_in numeric) for
                select  1
                from    rhnChannelFamily
                where   id = channel_family_id_in
                    and label = 'rhn-proxy';
        channel_family_is_satellite cursor(channel_family_id_in numeric) for
                select  1
                from    rhnChannelFamily
                where   id = channel_family_id_in
                    and label = 'rhn-satellite';
        child record;
    BEGIN
        -- In PostgreSQL recursion with opened cursors is not allowed so we use
        -- FOR IN SELECT form which is ok.
        FOR child IN select  c.id
                from    rhnChannel                      c,
                                rhnServerChannel        sc
                where   1=1
                        and c.parent_channel = channel_id_in
                        and c.id = sc.channel_id
                        and sc.server_id = server_id_in
        LOOP
            if unsubscribe_children_in = 1 then
                perform rhn_channel.unsubscribe_server(server_id_in,
                                                       child.id,
                                                       immediate_in,
                                                       unsubscribe_children_in,
                                                       deleting_server);
            else
                perform rhn_exception.raise_exception('channel_unsubscribe_child_exists');
            end if;
        END LOOP;

        server_already_in_chan := rhn_channel.check_server_subscription(server_id_in, channel_id_in);

        IF NOT server_already_in_chan
        THEN
            RETURN;
        END IF;

   if deleting_server = 0 then
      insert into rhnServerHistory (id,server_id,summary,details) (
          select  nextval('rhn_event_id_seq'),
                server_id_in,
             'unsubscribed from channel ' || SUBSTR(c.label, 0, 106),
             c.label
          from    rhnChannel c
          where   c.id = channel_id_in
      );
   end if;

   DELETE FROM rhnServerChannel WHERE server_id = server_id_in AND channel_id = channel_id_in;

   if deleting_server = 0 then
        perform queue_server(server_id_in, immediate_in);

        update rhnServer
           set channels_changed = current_timestamp
         where id = server_id_in;
   end if;

        channel_family_id_val := rhn_channel.family_for_channel(channel_id_in);
        IF channel_family_id_val IS NULL
        THEN
            perform rhn_exception.raise_exception('channel_unsubscribe_no_family');
        END IF;

        for ignore in channel_family_is_satellite(channel_family_id_val) loop
                delete from rhnSatelliteInfo where server_id = server_id_in;
        end loop;

        for ignore in channel_family_is_proxy(channel_family_id_val) loop
                delete from rhnProxyInfo where server_id = server_id_in;
        end loop;
        SELECT org_id INTO server_org_id_val
          FROM rhnServer
         WHERE id = server_id_in;

    END$$ language plpgsql;

    CREATE OR REPLACE FUNCTION family_for_channel(channel_id_in IN NUMERIC)
    RETURNS NUMERIC
    AS $$
    declare
        channel_family_id_val NUMERIC;
    BEGIN
        SELECT channel_family_id INTO channel_family_id_val
          FROM rhnChannelFamilyMembers
         WHERE channel_id = channel_id_in;

        IF NOT FOUND THEN
          RETURN NULL;
        END IF;

        RETURN channel_family_id_val;
    END$$ language plpgsql;

    create or replace function unsubscribe_server_from_family(server_id_in in numeric,
                                             channel_family_id_in in numeric)
    returns void
    as $$
    begin
        delete
        from    rhnServerChannel rsc
        where   rsc.server_id = server_id_in
            and channel_id in (
                select  rcfm.channel_id
                from    rhnChannelFamilyMembers rcfm
                where   rcfm.channel_family_id = channel_family_id_in);
    end$$ language plpgsql;

    create or replace function get_org_id(channel_id_in in numeric)
    returns numeric
    as $$
    declare
        org_id_out numeric;
    begin
        select org_id into strict org_id_out
            from rhnChannel
            where id = channel_id_in;

            return org_id_out;
    end$$ language plpgsql;

    create or replace function get_cfam_org_access(cfam_id_in in numeric, org_id_in in numeric)
    returns numeric
    as $$
    begin
      if exists(
                        select  1
                        from    rhnOrgChannelFamilyPermissions cfp
                        where   cfp.org_id = org_id_in
      ) then
                return 1;
      else
                return 0;
      end if;
    end$$ language plpgsql;

    create or replace function get_org_access(channel_id_in in numeric, org_id_in in numeric)
    returns integer
    as $$
    begin
        -- the idea: if we get past this query,
        -- the org has access to the channel, else not
        if exists(
        select 1
          from rhnChannelFamilyMembers CFM,
               rhnOrgChannelFamilyPermissions CFP
         where cfp.org_id = org_id_in
           and CFM.channel_family_id = CFP.channel_family_id
           and CFM.channel_id = channel_id_in)
        then
          return 1;
        else
          return 0;
        end if;
    end$$ language plpgsql;

    create or replace function rhn_channel.user_role_check(channel_id_in in numeric, user_id_in in numeric, role_in in varchar)
    returns numeric
    as $$
    declare
        result NUMERIC;
    begin
        SELECT
          INTO result
          CASE
            WHEN suseChannelUserRoleView.deny_reason IS NULL THEN 1
            ELSE 0
            END
          FROM suseChannelUserRoleView
          WHERE channel_id = channel_id_in AND
            user_id = user_id_in AND
            role = role_in;

         if result IS NULL then
           result := 0;
         end if;

         RETURN result;
    end$$ language plpgsql;

    --
    -- For multiorg phase II, this function simply checks to see if the user's
    -- has a trust relationship that includes this channel by id.
    --
    create or replace function shared_user_role_check(channel_id in numeric, user_id in numeric, role in varchar)
    returns numeric
    as $$
    declare
      n numeric;
      oid numeric;
    begin
      oid := rhn_user.get_org_id(user_id);
      select 1 into n
      from rhnSharedChannelView s
      where s.id = channel_id and s.org_trust_id = oid;

      if not found then
        return 0;
      end if;

      return 1;
    end$$ language plpgsql;

    -- same as above, but returns 1 if user_id_in is null
    -- This is useful in queries where user_id is not specified
    create or replace function loose_user_role_check(channel_id_in in numeric, user_id_in in numeric, role_in in varchar)
    returns numeric
    as $$
    begin
        if user_id_in is null then
            return 1;
        end if;
        return rhn_channel.user_role_check(channel_id_in, user_id_in, role_in);
    end$$ language plpgsql;

    -- directly checks the table, no inferred permissions
    create or replace function direct_user_role_check(channel_id_in in numeric, user_id_in in numeric, role_in in varchar)
    returns numeric
    as $$
    declare
        throwaway numeric;
    begin
        -- the idea: if we get past this query, the user has the role, else no
        select 1 into throwaway
          from rhnChannelPermissionRole CPR,
               rhnChannelPermission CP
         where CP.user_id = user_id_in
           and CP.channel_id = channel_id_in
           and CPR.label = role_in
           and CP.role_id = CPR.id;

      if not found then
        return 0;
      end if;

      return 1;
    end$$ language plpgsql;

    -- check if an org has a certain setting
    create or replace function org_channel_setting(channel_id_in in numeric, org_id_in in numeric, setting_in in varchar)
    returns numeric
    as $$
    declare
        throwaway numeric;
    begin
        -- the idea: if we get past this query, the org has the setting
        select 1 into throwaway
          from rhnOrgChannelSettingsType OCST,
               rhnOrgChannelSettings OCS
         where OCS.org_id = org_id_in
           and OCS.channel_id = channel_id_in
           and OCST.label = setting_in
           and OCS.setting_id = OCST.id;

      if not found then
        return 0;
      end if;

      return 1;
    end$$ language plpgsql;

    CREATE OR REPLACE FUNCTION channel_priority(channel_id_in IN numeric)
    RETURNS numeric
    AS $$
    declare
         channel_name varchar(256);
         priority numeric;
         end_of_life_val timestamptz;
         org_id_val numeric;
    BEGIN

        select name, end_of_life, org_id
        into channel_name, end_of_life_val, org_id_val
        from rhnChannel
        where id = channel_id_in;

        if end_of_life_val is not null then
          return -400;
        end if;

        if channel_name like 'Red Hat Enterprise Linux%' or channel_name like 'RHEL%' then
          priority := 1000;
          if channel_name not like '%Beta%' then
            priority := priority + 1000;
          end if;

          priority := priority +
            case
              when channel_name like '%v. 5%' then 600
              when channel_name like '%v. 4%' then 500
              when channel_name like '%v. 3%' then 400
              when channel_name like '%v. 2%' then 300
              when channel_name like '%v. 1%' then 200
              else 0
            end;

          priority := priority +
            case
              when channel_name like 'Red Hat Enterprise Linux (v. 5%' then 60
              when (channel_name like '%AS%' and channel_name not like '%Extras%') then 50
              when (channel_name like '%ES%' and channel_name not like '%Extras%') then 40
              when (channel_name like '%WS%' and channel_name not like '%Extras%') then 30
              when (channel_name like '%Desktop%' and channel_name not like '%Extras%') then 20
              when channel_name like '%Extras%' then 10
              else 0
            end;

          priority := priority +
            case
              when channel_name like '%)' then 5
              else 0
            end;

          priority := priority +
            case
              when channel_name like '%32-bit x86%' then 4
              when channel_name like '%64-bit Intel Itanium%' then 3
              when channel_name like '%64-bit AMD64/Intel EM64T%' then 2
              else 0
            end;
        elsif channel_name like 'Red Hat Desktop%' then
            priority := 900;

            if channel_name not like '%Beta%' then
               priority := priority + 50;
            end if;

          priority := priority +
            case
              when channel_name like '%v. 4%' then 40
              when channel_name like '%v. 3%' then 30
              when channel_name like '%v. 2%' then 20
              when channel_name like '%v. 1%' then 10
              else 0
            end;

          priority := priority +
            case
              when channel_name like '%32-bit x86%' then 4
              when channel_name like '%64-bit Intel Itanium%' then 3
              when channel_name like '%64-bit AMD64/Intel EM64T%' then 2
              else 0
            end;

        elsif org_id_val is not null then
          priority := 600;
        else
          priority := 500;
        end if;

      return -priority;

    end$$ language plpgsql;

    -- this could certainly be optimized to do updates if needs be
    create or replace function refresh_newest_package(channel_id_in in numeric,
                                      caller_in in varchar default '(unknown)',
                                      package_name_id_in in numeric default null)
    returns void
    as $$
    -- procedure refreshes rows for name_id = package_name_id_in or
    -- all rows if package_name_id_in is null
    begin
        delete from rhnChannelNewestPackage
              where channel_id = channel_id_in
                and (package_name_id_in is null
                     or name_id = package_name_id_in);
        insert into rhnChannelNewestPackage
                (channel_id, name_id, evr_id, package_id, package_arch_id)
                (select channel_id,
                        name_id, evr_id,
                        package_id, package_arch_id
                   from rhnChannelNewestPackageView
                  where channel_id = channel_id_in
                    and (package_name_id_in is null
                         or name_id = package_name_id_in)
                );
        insert into rhnChannelNewestPackageAudit (channel_id, caller)
             values (channel_id_in, caller_in);
        update rhnChannel
           set last_modified = greatest(current_timestamp,
                                        last_modified + interval '1 second')
         where id = channel_id_in;
    end$$ language plpgsql;

   create or replace function update_channel ( channel_id_in in numeric, invalidate_ss in numeric default 0,
                              date_to_use in timestamptz default current_timestamp ) returns void
   as $$
   declare
   channel_last_modified timestamptz;
   last_modified_value timestamptz;

   snapshots cursor for
   select  snapshot_id id
   from    rhnSnapshotChannel
   where   channel_id = channel_id_in;

   begin

      select last_modified
      into channel_last_modified
      from rhnChannel
      where id = channel_id_in;

      last_modified_value := date_to_use;

      if last_modified_value <= channel_last_modified then
          last_modified_value := last_modified_value + interval '1 second';
      end if;

      update rhnChannel set last_modified = last_modified_value
      where id = channel_id_in;

      if invalidate_ss = 1 then
        for snapshot in snapshots loop
            update rhnSnapshot
            set invalid = lookup_snapshot_invalid_reason('channel_modified')
            where id = snapshot.id;
        end loop;
      end if;

   end$$ language plpgsql;

   create or replace function update_channels_by_package ( package_id_in in numeric, date_to_use in timestamptz default current_timestamp ) returns void
   as $$
   declare
   channels cursor for
   select channel_id
   from rhnChannelPackage
   where package_id = package_id_in
   order by channel_id;

   begin
      for channel in channels loop
         -- we want to invalidate the snapshot assocated with the channel when we
         -- do this b/c we know we've added or removed or packages
         perform rhn_channel.update_channel ( channel.channel_id, 1, date_to_use );
      end loop;
   end$$ language plpgsql;


   create or replace function update_channels_by_errata ( errata_id_in numeric, date_to_use in timestamptz default current_timestamp ) returns void
   as $$
   declare
   channels cursor for
   select channel_id
   from rhnChannelErrata
   where errata_id = errata_id_in
   order by channel_id;

   begin
      for channel in channels loop
         -- we won't invalidate snapshots, b/c just changing the errata associated with
         -- a channel shouldn't invalidate snapshots
         perform rhn_channel.update_channel ( channel.channel_id, 0, date_to_use );
      end loop;
   end$$ language plpgsql;

   create or replace function update_needed_cache(channel_id_in in numeric) returns void
   as $$
   declare
   server record;
   image record;
   begin
      -- we intentionaly do a loop here instead of one huge select
      -- b/c we want to break update into smaller transaction to unblock other sessions
      -- querying rhnServerNeededCache
      for server in (
                select sc.server_id as id
                  from rhnServerChannel sc
                 where sc.channel_id = channel_id_in
                 order by id asc
      ) loop
         perform queue_server(server.id, 0); -- NOT IMMEDIATE
      end loop;
      for image in (
        select ic.image_info_id as id
          from suseImageInfoChannel ic
         where ic.channel_id = channel_id_in
        order by id asc
      ) loop
         perform queue_image(image.id, 0);
      end loop;
   end$$ language plpgsql;

    create or replace function set_comps(channel_id_in in numeric, path_in in varchar, comps_type_id_in in numeric, timestamp_in in varchar) returns void
    as $$
    declare
    row record;
    begin
        for row in (
            select relative_filename, last_modified
            from rhnChannelComps
            where channel_id = channel_id_in
            and comps_type_id = comps_type_id_in
            ) loop
            if row.relative_filename = path_in
                and row.last_modified = to_timestamp(timestamp_in, 'YYYYMMDDHH24MISS') then
                return;
            end if;
        end loop;
        delete from rhnChannelComps
        where channel_id = channel_id_in and comps_type_id = comps_type_id_in;
        insert into rhnChannelComps (id, channel_id, relative_filename, comps_type_id, last_modified, created, modified)
        values (sequence_nextval('rhn_channelcomps_id_seq'), channel_id_in, path_in, comps_type_id_in, to_timestamp(timestamp_in, 'YYYYMMDDHH24MISS'), current_timestamp, current_timestamp);
    end$$ language plpgsql;

-- restore the original setting
update pg_settings set setting = overlay( setting placing '' from 1 for (length('rhn_channel')+1) ) where name = 'search_path';
 07070100000D44000081B400000000000000000000000167AE11140000073D000000000000000000000000000000000000006700000000susemanager-schema/upgrade/susemanager-schema-4.0.2-to-susemanager-schema-4.0.3/202-rhnUserChannel.sql    --
-- Copyright (c) 2008 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--

create or replace view rhnUserChannel
as
select
   cfp.user_id,
   cfp.org_id,
   cfm.channel_id,
   'manage' as role
from rhnChannelFamilyMembers cfm,
      rhnUserChannelFamilyPerms cfp
where
   cfp.channel_family_id = cfm.channel_family_id and
   (select deny_reason
      from suseChannelUserRoleView scur
      where scur.channel_id = cfm.channel_id and
        scur.user_id = cfp.user_id and
        scur.role = 'manage'
   ) is null
union all
select
   cfp.user_id,
   cfp.org_id,
   cfm.channel_id,
   'subscribe' as role
from rhnChannelFamilyMembers cfm,
      rhnUserChannelFamilyPerms cfp
where
   cfp.channel_family_id = cfm.channel_family_id and
   (select deny_reason
      from suseChannelUserRoleView scur
      where scur.channel_id = cfm.channel_id and
        scur.user_id = cfp.user_id and
        scur.role = 'subscribe'
   ) is null
union all
select
   w.id as user_id,
   w.org_id,
   s.id as channel_id,
   'subscribe' as role
from rhnSharedChannelView s,
      web_contact w
where
   w.org_id = s.org_trust_id and
   (select deny_reason
      from suseChannelUserRoleView scur
      where scur.channel_id = s.id and
        scur.user_id = w.id and
        scur.role = 'subscribe'
   ) is null
;
   07070100000D45000081B400000000000000000000000167AE1114000001E0000000000000000000000000000000000000006700000000susemanager-schema/upgrade/susemanager-schema-4.0.2-to-susemanager-schema-4.0.3/300-add-uyuni-keys.sql    insert into rhnPackageProvider (id, name) (select sequence_nextval('rhn_package_provider_id_seq'), 'Uyuni' from dual where not exists (select 1 from rhnPackageProvider where name = 'Uyuni'));
insert into rhnPackageKey (id, key_id, key_type_id, provider_id) (select sequence_nextval('rhn_pkey_id_seq'), '972e5d6c0d20833e', lookup_package_key_type('gpg'), lookup_package_provider('Uyuni') from dual where not exists (select 1 from rhnPackageKey where key_id = '972e5d6c0d20833e'));
07070100000D46000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005100000000susemanager-schema/upgrade/susemanager-schema-4.0.20-to-susemanager-schema-4.1.0  07070100000D47000081B400000000000000000000000167AE11140000005B000000000000000000000000000000000000005800000000susemanager-schema/upgrade/susemanager-schema-4.0.20-to-susemanager-schema-4.1.0/README   -- Schema upgrade scripts.
-- Intentionally left empty. Please leave this directory empty.
 07070100000D48000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005100000000susemanager-schema/upgrade/susemanager-schema-4.0.21-to-susemanager-schema-4.1.0  07070100000D49000081B400000000000000000000000167AE11140000005B000000000000000000000000000000000000005800000000susemanager-schema/upgrade/susemanager-schema-4.0.21-to-susemanager-schema-4.1.0/README   -- Schema upgrade scripts.
-- Intentionally left empty. Please leave this directory empty.
 07070100000D4A000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005100000000susemanager-schema/upgrade/susemanager-schema-4.0.22-to-susemanager-schema-4.1.0  07070100000D4B000081B400000000000000000000000167AE11140000005B000000000000000000000000000000000000005800000000susemanager-schema/upgrade/susemanager-schema-4.0.22-to-susemanager-schema-4.1.0/README   -- Schema upgrade scripts.
-- Intentionally left empty. Please leave this directory empty.
 07070100000D4C000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005100000000susemanager-schema/upgrade/susemanager-schema-4.0.23-to-susemanager-schema-4.1.0  07070100000D4D000081B400000000000000000000000167AE11140000005B000000000000000000000000000000000000005800000000susemanager-schema/upgrade/susemanager-schema-4.0.23-to-susemanager-schema-4.1.0/README   -- Schema upgrade scripts.
-- Intentionally left empty. Please leave this directory empty.
 07070100000D4E000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005100000000susemanager-schema/upgrade/susemanager-schema-4.0.24-to-susemanager-schema-4.1.0  07070100000D4F000081B400000000000000000000000167AE11140000005B000000000000000000000000000000000000005800000000susemanager-schema/upgrade/susemanager-schema-4.0.24-to-susemanager-schema-4.1.0/README   -- Schema upgrade scripts.
-- Intentionally left empty. Please leave this directory empty.
 07070100000D50000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005100000000susemanager-schema/upgrade/susemanager-schema-4.0.25-to-susemanager-schema-4.1.0  07070100000D51000081B400000000000000000000000167AE11140000005B000000000000000000000000000000000000005800000000susemanager-schema/upgrade/susemanager-schema-4.0.25-to-susemanager-schema-4.1.0/README   -- Schema upgrade scripts.
-- Intentionally left empty. Please leave this directory empty.
 07070100000D52000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005100000000susemanager-schema/upgrade/susemanager-schema-4.0.26-to-susemanager-schema-4.1.0  07070100000D53000081B400000000000000000000000167AE11140000005B000000000000000000000000000000000000005800000000susemanager-schema/upgrade/susemanager-schema-4.0.26-to-susemanager-schema-4.1.0/README   -- Schema upgrade scripts.
-- Intentionally left empty. Please leave this directory empty.
 07070100000D54000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005100000000susemanager-schema/upgrade/susemanager-schema-4.0.27-to-susemanager-schema-4.1.0  07070100000D55000081B400000000000000000000000167AE11140000005B000000000000000000000000000000000000005800000000susemanager-schema/upgrade/susemanager-schema-4.0.27-to-susemanager-schema-4.1.0/README   -- Schema upgrade scripts.
-- Intentionally left empty. Please leave this directory empty.
 07070100000D56000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005100000000susemanager-schema/upgrade/susemanager-schema-4.0.28-to-susemanager-schema-4.1.0  07070100000D57000081B400000000000000000000000167AE11140000005B000000000000000000000000000000000000005800000000susemanager-schema/upgrade/susemanager-schema-4.0.28-to-susemanager-schema-4.1.0/README   -- Schema upgrade scripts.
-- Intentionally left empty. Please leave this directory empty.
 07070100000D58000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005100000000susemanager-schema/upgrade/susemanager-schema-4.0.29-to-susemanager-schema-4.1.0  07070100000D59000081B400000000000000000000000167AE11140000005B000000000000000000000000000000000000005800000000susemanager-schema/upgrade/susemanager-schema-4.0.29-to-susemanager-schema-4.1.0/README   -- Schema upgrade scripts.
-- Intentionally left empty. Please leave this directory empty.
 07070100000D5A000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005000000000susemanager-schema/upgrade/susemanager-schema-4.0.3-to-susemanager-schema-4.0.4   07070100000D5B000081B400000000000000000000000167AE111400000613000000000000000000000000000000000000006A00000000susemanager-schema/upgrade/susemanager-schema-4.0.3-to-susemanager-schema-4.0.4/001-suseSCCRepository.sql --
-- Copyright (c) 2014--2018 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

DO $$
BEGIN
IF EXISTS (SELECT * FROM pg_tables WHERE tablename='susesccrepositoryauth')
THEN
  BEGIN
    delete from susesccrepositoryauth;
  END;
  END IF;
END $$;

delete from susesccrepository;

ALTER TABLE suseSCCRepository
  ALTER COLUMN scc_id SET NOT NULL,
  ALTER COLUMN name SET NOT NULL,
  ALTER COLUMN description SET NOT NULL,
  ALTER COLUMN url SET NOT NULL;
  
alter table suseSCCRepository drop column if exists credentials_id;
alter table suseSCCRepository add column if not exists
    signed CHAR(1) DEFAULT ('N') NOT NULL;

alter table suseSCCRepository drop CONSTRAINT if exists suse_sccrepo_sig_ck;
alter table suseSCCRepository add CONSTRAINT suse_sccrepo_sig_ck CHECK (signed in ('Y', 'N'));

DROP INDEX if exists suse_sccrepo_sccid_idx;
CREATE UNIQUE INDEX if not exists suse_sccrepo_sccid_uq
    ON suseSCCRepository (scc_id);

CREATE INDEX if not exists suse_sccrepo_url_idx
    ON suseSCCRepository (url);
 07070100000D5C000081B400000000000000000000000167AE1114000006B6000000000000000000000000000000000000007100000000susemanager-schema/upgrade/susemanager-schema-4.0.3-to-susemanager-schema-4.0.4/002-suseProductSCCRepository.sql  
CREATE TABLE if not exists
suseProductSCCRepository
(
    id                     NUMERIC NOT NULL primary key,
    product_id             NUMERIC NOT NULL
                                  CONSTRAINT suse_prdrepo_pid_fk
                                  REFERENCES suseProducts (id)
                                  ON DELETE CASCADE,
    root_product_id        NUMERIC NOT NULL
                                  CONSTRAINT suse_prdrepo_rpid_fk
                                  REFERENCES suseProducts (id)
                                  ON DELETE CASCADE,
    repo_id                NUMERIC NOT NULL
                                  CONSTRAINT suse_prdrepo_rid_fk
                                  REFERENCES suseSCCRepository (id)
                                  ON DELETE CASCADE,
    channel_label          VARCHAR(128) not null,
    parent_channel_label   VARCHAR(128),
    channel_name           VARCHAR(256) not null,
    mandatory              CHAR(1) DEFAULT ('N') NOT NULL
                                   CONSTRAINT suse_prdrepo_mand_ck
                                   CHECK (mandatory in ('Y', 'N')),
    update_tag             VARCHAR(128),
    created                TIMESTAMPTZ
                           DEFAULT (current_timestamp) NOT NULL,
    modified               TIMESTAMPTZ
                           DEFAULT (current_timestamp) NOT NULL
);

CREATE SEQUENCE if not exists suse_prdrepo_id_seq START WITH 1;

DROP INDEX if exists suse_prdrepo_pid_rid_cl_uq;
CREATE UNIQUE INDEX if not exists suse_prdrepo_pid_rpid_rid_uq
ON suseProductSCCRepository (product_id, root_product_id, repo_id);

CREATE INDEX if not exists suse_prdrepo_chl_idx
ON suseProductSCCRepository (channel_label);
  07070100000D5D000081B400000000000000000000000167AE1114000002A1000000000000000000000000000000000000007200000000susemanager-schema/upgrade/susemanager-schema-4.0.3-to-susemanager-schema-4.0.4/003-change-suseProductChannel.sql 
DELETE FROM suseProductChannel WHERE channel_id IS NULL;

ALTER TABLE suseProductChannel ALTER COLUMN channel_id SET NOT NULL;

alter table suseProductChannel drop column if exists channel_label;
alter table suseProductChannel drop column if exists parent_channel_label;

alter table suseProductChannel add column if not exists
    mandatory  CHAR(1) DEFAULT ('N') NOT NULL;

alter table suseProductChannel drop CONSTRAINT if exists spc_mand_ck;
alter table suseProductChannel add CONSTRAINT spc_mand_ck CHECK (mandatory in ('Y', 'N'));

drop index if exists suse_prd_chan_label_uq;
drop index if exists suse_prd_chan_pcl_idx;
drop index if exists suse_prd_chan_chan_idx;
   07070100000D5E000081B400000000000000000000000167AE11140000010B000000000000000000000000000000000000006C00000000susemanager-schema/upgrade/susemanager-schema-4.0.3-to-susemanager-schema-4.0.4/004-change-suseProducts.sql   
alter table suseProducts add column if not exists release_stage VARCHAR(10) DEFAULT ('released') NOT NULL;
alter table suseProducts add column if not exists description VARCHAR(4000);

CREATE UNIQUE INDEX if not exists suseprod_pdid_uq
ON suseProducts (product_id);
 07070100000D5F000081B400000000000000000000000167AE111400000041000000000000000000000000000000000000006800000000susemanager-schema/upgrade/susemanager-schema-4.0.3-to-susemanager-schema-4.0.4/005-drop-productUrl.sql   
alter table rhnChannelFamily drop column if exists product_url;
   07070100000D60000081B400000000000000000000000167AE111400000643000000000000000000000000000000000000006E00000000susemanager-schema/upgrade/susemanager-schema-4.0.3-to-susemanager-schema-4.0.4/006-suseSCCRepositoryAuth.sql --
-- Copyright (c) 2018 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

CREATE TABLE if not exists suseSCCRepositoryAuth
(
    id             NUMERIC NOT NULL PRIMARY KEY,
    repo_id        NUMERIC NOT NULL
                       CONSTRAINT suse_sccrepoauth_rid_fk
		       REFERENCES suseSCCRepository (id),
--                     NO ON DELETE !
    credentials_id NUMERIC NULL
                       CONSTRAINT suse_sccrepo_credsid_fk
                       REFERENCES suseCredentials (id),
--                     NO ON DELETE !,
    source_id      NUMERIC NULL
                         CONSTRAINT suse_sccrepo_src_id_fk
                             REFERENCES rhnContentSource (id)
                             ON DELETE SET NULL,
    auth_type      VARCHAR(10) NOT NULL,
    auth           VARCHAR(4000) NULL,
    created        TIMESTAMPTZ
                       DEFAULT (current_timestamp) NOT NULL,
    modified       TIMESTAMPTZ
                       DEFAULT (current_timestamp) NOT NULL
) ;

CREATE SEQUENCE if not exists suse_sccrepoauth_id_seq;
 07070100000D61000081B400000000000000000000000167AE1114000002C1000000000000000000000000000000000000006800000000susemanager-schema/upgrade/susemanager-schema-4.0.3-to-susemanager-schema-4.0.4/007-suseManagerInfo.sql   --
-- Copyright (c) 2018 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

CREATE TABLE if not exists suseManagerInfo
(
    last_mgr_sync_refresh   TIMESTAMPTZ
);
   07070100000D62000081B400000000000000000000000167AE111400000221000000000000000000000000000000000000006500000000susemanager-schema/upgrade/susemanager-schema-4.0.3-to-susemanager-schema-4.0.4/203-rhn_user.pkb.sql  --
-- Copyright (c) 2019 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--

DROP FUNCTION IF EXISTS rhn_user.remove_servergroup_perm(user_id_in in numeric, server_group_id_in in numeric);


   07070100000D63000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005100000000susemanager-schema/upgrade/susemanager-schema-4.0.30-to-susemanager-schema-4.1.0  07070100000D64000081B400000000000000000000000167AE11140000005B000000000000000000000000000000000000005800000000susemanager-schema/upgrade/susemanager-schema-4.0.30-to-susemanager-schema-4.1.0/README   -- Schema upgrade scripts.
-- Intentionally left empty. Please leave this directory empty.
 07070100000D65000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005100000000susemanager-schema/upgrade/susemanager-schema-4.0.31-to-susemanager-schema-4.1.0  07070100000D66000081B400000000000000000000000167AE11140000005B000000000000000000000000000000000000005800000000susemanager-schema/upgrade/susemanager-schema-4.0.31-to-susemanager-schema-4.1.0/README   -- Schema upgrade scripts.
-- Intentionally left empty. Please leave this directory empty.
 07070100000D67000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005100000000susemanager-schema/upgrade/susemanager-schema-4.0.32-to-susemanager-schema-4.1.0  07070100000D68000081B400000000000000000000000167AE11140000005B000000000000000000000000000000000000005800000000susemanager-schema/upgrade/susemanager-schema-4.0.32-to-susemanager-schema-4.1.0/README   -- Schema upgrade scripts.
-- Intentionally left empty. Please leave this directory empty.
 07070100000D69000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005100000000susemanager-schema/upgrade/susemanager-schema-4.0.33-to-susemanager-schema-4.1.0  07070100000D6A000081B400000000000000000000000167AE11140000005B000000000000000000000000000000000000005800000000susemanager-schema/upgrade/susemanager-schema-4.0.33-to-susemanager-schema-4.1.0/README   -- Schema upgrade scripts.
-- Intentionally left empty. Please leave this directory empty.
 07070100000D6B000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005100000000susemanager-schema/upgrade/susemanager-schema-4.0.34-to-susemanager-schema-4.1.0  07070100000D6C000081B400000000000000000000000167AE11140000005B000000000000000000000000000000000000005800000000susemanager-schema/upgrade/susemanager-schema-4.0.34-to-susemanager-schema-4.1.0/README   -- Schema upgrade scripts.
-- Intentionally left empty. Please leave this directory empty.
 07070100000D6D000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005100000000susemanager-schema/upgrade/susemanager-schema-4.0.35-to-susemanager-schema-4.1.0  07070100000D6E000081B400000000000000000000000167AE11140000005B000000000000000000000000000000000000005800000000susemanager-schema/upgrade/susemanager-schema-4.0.35-to-susemanager-schema-4.1.0/README   -- Schema upgrade scripts.
-- Intentionally left empty. Please leave this directory empty.
 07070100000D6F000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005100000000susemanager-schema/upgrade/susemanager-schema-4.0.36-to-susemanager-schema-4.1.0  07070100000D70000081B400000000000000000000000167AE11140000005B000000000000000000000000000000000000005800000000susemanager-schema/upgrade/susemanager-schema-4.0.36-to-susemanager-schema-4.1.0/README   -- Schema upgrade scripts.
-- Intentionally left empty. Please leave this directory empty.
 07070100000D71000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005100000000susemanager-schema/upgrade/susemanager-schema-4.0.37-to-susemanager-schema-4.1.0  07070100000D72000081B400000000000000000000000167AE11140000005B000000000000000000000000000000000000005800000000susemanager-schema/upgrade/susemanager-schema-4.0.37-to-susemanager-schema-4.1.0/README   -- Schema upgrade scripts.
-- Intentionally left empty. Please leave this directory empty.
 07070100000D73000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005100000000susemanager-schema/upgrade/susemanager-schema-4.0.38-to-susemanager-schema-4.1.0  07070100000D74000081B400000000000000000000000167AE11140000005B000000000000000000000000000000000000005800000000susemanager-schema/upgrade/susemanager-schema-4.0.38-to-susemanager-schema-4.1.0/README   -- Schema upgrade scripts.
-- Intentionally left empty. Please leave this directory empty.
 07070100000D75000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005100000000susemanager-schema/upgrade/susemanager-schema-4.0.39-to-susemanager-schema-4.1.0  07070100000D76000081B400000000000000000000000167AE11140000005B000000000000000000000000000000000000005800000000susemanager-schema/upgrade/susemanager-schema-4.0.39-to-susemanager-schema-4.1.0/README   -- Schema upgrade scripts.
-- Intentionally left empty. Please leave this directory empty.
 07070100000D77000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005000000000susemanager-schema/upgrade/susemanager-schema-4.0.4-to-susemanager-schema-4.0.5   07070100000D78000081B400000000000000000000000167AE111400000115000000000000000000000000000000000000006400000000susemanager-schema/upgrade/susemanager-schema-4.0.4-to-susemanager-schema-4.0.5/005-fedora-keys.sql   insert into rhnPackageKey (id, key_id, key_type_id, provider_id)
  select sequence_nextval('rhn_pkey_id_seq'), '429476B4', lookup_package_key_type('gpg'), lookup_package_provider('Fedora') from dual
   where not exists (select 1 from rhnPackageKey where key_id = '429476B4');

   07070100000D79000081B400000000000000000000000167AE111400000113000000000000000000000000000000000000007600000000susemanager-schema/upgrade/susemanager-schema-4.0.4-to-susemanager-schema-4.0.5/006-cleanup-channel_family-labels.sql DELETE FROM rhnPublicChannelFamily
 WHERE channel_family_id IN (
        SELECT id
          FROM rhnChannelFamily
         WHERE label LIKE '%-alpha'
            OR label LIKE '%-beta'
);

DELETE FROM rhnChannelFamily
 WHERE label LIKE '%-alpha'
    OR label LIKE '%-beta';
 07070100000D7A000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005100000000susemanager-schema/upgrade/susemanager-schema-4.0.40-to-susemanager-schema-4.1.0  07070100000D7B000081B400000000000000000000000167AE11140000005B000000000000000000000000000000000000005800000000susemanager-schema/upgrade/susemanager-schema-4.0.40-to-susemanager-schema-4.1.0/README   -- Schema upgrade scripts.
-- Intentionally left empty. Please leave this directory empty.
 07070100000D7C000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005000000000susemanager-schema/upgrade/susemanager-schema-4.0.5-to-susemanager-schema-4.0.6   07070100000D7D000081B400000000000000000000000167AE111400000000000000000000000000000000000000000000005900000000susemanager-schema/upgrade/susemanager-schema-4.0.5-to-susemanager-schema-4.0.6/.gitkeep  07070100000D7E000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005000000000susemanager-schema/upgrade/susemanager-schema-4.0.6-to-susemanager-schema-4.0.7   07070100000D7F000081B400000000000000000000000167AE1114000000E7000000000000000000000000000000000000007600000000susemanager-schema/upgrade/susemanager-schema-4.0.6-to-susemanager-schema-4.0.7/001-add_virt_create_rhnActionType.sql insert into rhnActionType (id, label, name, trigger_snapshot, unlocked_only) (
    select 508, 'virt.create', 'Creates a virtual domain.', 'N', 'N'
    from dual
    where not exists (select 1 from rhnActionType where id = 508)
);
 07070100000D80000081B400000000000000000000000167AE111400000046000000000000000000000000000000000000006C00000000susemanager-schema/upgrade/susemanager-schema-4.0.6-to-susemanager-schema-4.0.7/001-rhnXccdfIdent-ident.sql   
alter table rhnXccdfIdent alter column identifier type varchar(255);
  07070100000D81000081B400000000000000000000000167AE111400000A96000000000000000000000000000000000000007000000000susemanager-schema/upgrade/susemanager-schema-4.0.6-to-susemanager-schema-4.0.7/002-add_rhnVirtCreateAction.sql   -- oracle equivalent source none
CREATE TABLE IF NOT EXISTS rhnActionVirtCreate
(
    action_id            NUMERIC NOT NULL
                             CONSTRAINT rhn_action_virt_create_aid_fk
                                 REFERENCES rhnAction (id)
                                 ON DELETE CASCADE
                             CONSTRAINT rhn_action_virt_create_aid_pk
                                 PRIMARY KEY,
    uuid                 VARCHAR(128),
    vm_type              VARCHAR(10),
    vm_name              VARCHAR(256),
    os_type              VARCHAR(20),
    memory               NUMERIC,
    vcpus                NUMERIC,
    arch                 VARCHAR(20),
    graphics_type        VARCHAR(20),
    remove_disks         CHAR(1),
    remove_interfaces    CHAR(1)
);

CREATE UNIQUE INDEX IF NOT EXISTS rhn_action_virt_create_aid_uq
    ON rhnActionVirtCreate (action_id);


CREATE TABLE IF NOT EXISTS rhnActionVirtCreateDiskDetails
(
    id                   NUMERIC NOT NULL
                             CONSTRAINT rhn_action_virt_create_disk_details_id_pk
                                 PRIMARY KEY,
    type                 VARCHAR(15),
    device               VARCHAR(10),
    template             VARCHAR(256),
    size                 NUMERIC,
    bus                  VARCHAR(10),
    pool                 VARCHAR(256),
    source_file          VARCHAR(1024),
    idx                  NUMERIC,
    action_id            NUMERIC NOT NULL
                             CONSTRAINT rhn_action_virt_create_disk_details_aid_fk
                                 REFERENCES rhnActionVirtCreate (action_id)
                                 ON DELETE CASCADE
);

CREATE INDEX IF NOT EXISTS rhn_action_virt_create_disk_details_id_idx
    ON rhnActionVirtCreateDiskDetails (id);

CREATE SEQUENCE IF NOT EXISTS rhn_action_virt_create_disk_details_id_seq;


CREATE TABLE IF NOT EXISTS rhnActionVirtCreateInterfaceDetails
(
    id                   NUMERIC NOT NULL
                             CONSTRAINT rhn_action_virt_create_iface_details_id_pk
                                 PRIMARY KEY,
    type                 VARCHAR(20),
    source               VARCHAR(256),
    mac                  VARCHAR(20),
    idx                  NUMERIC,
    action_id            NUMERIC NOT NULL
                             CONSTRAINT rhn_action_virt_create_iface_details_aid_fk
                                 REFERENCES rhnActionVirtCreate (action_id)
                                 ON DELETE CASCADE
);

CREATE INDEX IF NOT EXISTS rhn_action_virt_create_iface_details_id_idx
    ON rhnActionVirtCreateInterfaceDetails (id);

CREATE SEQUENCE IF NOT EXISTS rhn_action_virt_create_iface_details_id_seq;
  07070100000D82000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005000000000susemanager-schema/upgrade/susemanager-schema-4.0.7-to-susemanager-schema-4.0.8   07070100000D83000081B400000000000000000000000167AE111400000517000000000000000000000000000000000000008200000000susemanager-schema/upgrade/susemanager-schema-4.0.7-to-susemanager-schema-4.0.8/001-suseproductsccrepo-delete-invalid-entries.sql delete from suseproductsccrepository where channel_label = 'suse-openstack-cloud-6-pool-x86_64-sp1';
delete from suseproductsccrepository where channel_label = 'suse-openstack-cloud-6-updates-x86_64-sp1';
delete from suseproductsccrepository where channel_label = 'suse-openstack-cloud-6-debuginfo-pool-x86_64-sp1';
delete from suseproductsccrepository where channel_label = 'suse-openstack-cloud-6-debuginfo-updates-x86_64-sp1';

delete from suseproductsccrepository where channel_label = 'suse-packagehub-12-sp4-aarch64';
delete from suseproductsccrepository where channel_label = 'suse-packagehub-12-sp4-aarch64-hpc-sp4';
delete from suseproductsccrepository where channel_label = 'suse-packagehub-12-sp4-ppc64le';
delete from suseproductsccrepository where channel_label = 'suse-packagehub-12-sp4-ppc64le-sap-sp4';
delete from suseproductsccrepository where channel_label = 'suse-packagehub-12-sp4-s390x';
delete from suseproductsccrepository where channel_label = 'suse-packagehub-12-sp4-x86_64';
delete from suseproductsccrepository where channel_label = 'suse-packagehub-12-sp4-x86_64-sled-sp4';
delete from suseproductsccrepository where channel_label = 'suse-packagehub-12-sp4-x86_64-sap-sp4';
delete from suseproductsccrepository where channel_label = 'suse-packagehub-12-sp4-x86_64-hpc-sp4';
 07070100000D84000081B400000000000000000000000167AE1114000028A1000000000000000000000000000000000000007600000000susemanager-schema/upgrade/susemanager-schema-4.0.7-to-susemanager-schema-4.0.8/100-delete_server-archive-actions.sql --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--
--
--
-- This deletes a server.  All codepaths which delete servers should hit this
-- or delete_server_bulk()

create or replace
function delete_server (
        server_id_in in numeric
) returns void
as
$$
declare
         servergroups cursor for
                select  server_id, server_group_id
                from    rhnServerGroupMembers sgm
                where   sgm.server_id = server_id_in;

         configchannels cursor for
                select  cc.id
                from    rhnConfigChannel cc,
                        rhnConfigChannelType cct,
                        rhnServerConfigChannel scc
                where   1=1
                        and scc.server_id = server_id_in
                        and scc.config_channel_id = cc.id
                        -- these config channel types are reserved
                        -- for use by a single server, so we don't
                        -- need to check for other servers subscribed
                        and cct.label in
                                ('local_override','server_import')
                        and cct.id = cc.confchan_type_id;

    update_lock numeric;
begin
    -- lock the rhnServer row to prevent deadlocks
    -- we want rhnServer to be locked first, followed by tables that depend on it
    select id into update_lock from rhnServer where id = server_id_in for update;

        -- filelists
        delete from rhnFileList where id in (
	select	spfl.file_list_id
	  from	rhnServerPreserveFileList spfl
	 where	spfl.server_id = server_id_in
			and not exists (
				select	1
				from	rhnServerPreserveFileList
				where	file_list_id = spfl.file_list_id
					and server_id != server_id_in
				union all
				select	1
				from	rhnKickstartPreserveFileList
				where	file_list_id = spfl.file_list_id
			)
        );

	for configchannel in configchannels loop
		perform rhn_config.delete_channel(configchannel.id);
	end loop;

	for sgm in servergroups loop
		perform rhn_server.delete_from_servergroup(
			sgm.server_id, sgm.server_group_id);
	end loop;


        -- we're handling this instead of letting an "on delete
        -- set null" do it so that we don't run the risk
        -- of setting off the triggers and killing us with a
        -- mutating table

        -- this is merge of two single updates:
        --  update ... set old_server_id = null where old_server_id = server_id_in;
        --  update ... set new_server_id = null where new_server_id = server_id_in;
        -- so we scan rhnKickstartSession table only once
        update rhnKickstartSession
                set old_server_id = case when old_server_id = server_id_in then null else old_server_id end,
                    new_server_id = case when new_server_id = server_id_in then null else new_server_id end
                where old_server_id = server_id_in
                   or new_server_id = server_id_in;

        perform rhn_channel.clear_subscriptions(server_id_in, 1);

        -- A little complicated here, but the goal is to
        -- delete records from rhnVirtualInstace only if we don't
        -- care about them anymore.  We don't care about records
        -- in rhnVirtualInstance if we are deleting the host
        -- system and the virtual system is already null, or
        -- vice-versa.  We *do* care about them if either the
        -- host or virtual system is still registered because we
        -- still want them to show up in the UI.
    -- If there's a newer row in rhnVirtualInstance with the same
    -- uuid, this guest must have been re-registered, so we can clean
    -- this data up.

        delete from rhnVirtualInstance vi
              where (host_system_id = server_id_in and virtual_system_id is null)
                 or (virtual_system_id = server_id_in and host_system_id is null)
                 or (vi.virtual_system_id = server_id_in and vi.modified < (select max(vi2.modified)
                    from rhnVirtualInstance vi2 where vi2.uuid = vi.uuid));

        -- this is merge of two single updates:
        --  update ... set host_system_id = null where host_system_id = server_id_in;
        --  update ... set virtual_system_id = null where virtual_system_id = server_id_in;
        -- so we scan rhnVirtualInstance table only once
        update rhnVirtualInstance
           set host_system_id = case when host_system_id = server_id_in then null else host_system_id end,
               virtual_system_id = case when virtual_system_id = server_id_in then null else virtual_system_id end
         where host_system_id = server_id_in
            or virtual_system_id = server_id_in;

        -- this is merge of two single updates:
        --  update ... set old_host_system_id = null when old_host_system_id = server_id_in;
        --  update ... set new_host_system_id = null when new_host_system_id = server_id_in;
        -- so we scan rhnVirtualInstanceEventLog table only once
        update rhnVirtualInstanceEventLog
           set old_host_system_id = case when old_host_system_id = server_id_in then null else old_host_system_id end,
               new_host_system_id = case when new_host_system_id = server_id_in then null else new_host_system_id end
         where old_host_system_id = server_id_in
            or new_host_system_id = server_id_in;

        -- archive related actions, only if they have no other servers assigned
        update rhnAction set archived = 1 where id in (
            select action_id from rhnServerAction sa
            where not exists (
                select server_id from rhnServerAction
                where action_id = sa.action_id and server_id != server_id_in
            )
        );

        -- We're deleting everything with a foreign key to rhnServer
        -- here, now.  I'm hoping this will help aleviate our deadlock
        -- problem.

        delete from rhnActionApplyStatesResult where server_id = server_id_in;
        delete from rhnActionConfigChannel where server_id = server_id_in;
        delete from rhnActionConfigRevision where server_id = server_id_in;
        delete from rhnActionPackageRemovalFailure where server_id = server_id_in;
        delete from rhnClientCapability where server_id = server_id_in;
        delete from rhnCpu where server_id = server_id_in;
        -- there's still a cascade here, because the constraint keeps the
        -- table locked for too long to rebuild it.  Ugh...
        delete from rhnDevice where server_id = server_id_in;
        delete from rhnProxyInfo where server_id = server_id_in;
        delete from rhnRam where server_id = server_id_in;
        delete from rhnRegToken where server_id = server_id_in;
        delete from rhnSatelliteInfo where server_id = server_id_in;
        -- this cascades to rhnActionConfigChannel and rhnActionConfigFileName
        delete from rhnServerAction where server_id = server_id_in;
        delete from rhnServerActionPackageResult where server_id = server_id_in;
        delete from rhnServerActionScriptResult where server_id = server_id_in;
        delete from rhnServerActionVerifyResult where server_id = server_id_in;
        delete from rhnServerActionVerifyMissing where server_id = server_id_in;
        -- counts are handled above.  this should be a delete_ function.
        delete from rhnServerChannel where server_id = server_id_in;
        delete from rhnServerConfigChannel where server_id = server_id_in;
        delete from rhnServerCustomDataValue where server_id = server_id_in;
        delete from rhnServerDMI where server_id = server_id_in;
        delete from rhnServerEvent where server_id = server_id_in;
        delete from rhnServerFQDN where server_id = server_id_in;
        delete from rhnServerHistory where server_id = server_id_in;
        delete from rhnServerInfo where server_id = server_id_in;
        delete from rhnServerInstallInfo where server_id = server_id_in;
        delete from rhnServerLocation where server_id = server_id_in;
        delete from rhnServerLock where server_id = server_id_in;
        delete from rhnServerNeededCache where server_id = server_id_in;
        delete from rhnServerNotes where server_id = server_id_in;
        -- I'm not removing the foreign key from rhnServerPackage; that'll
        -- take forever.  Do the delete anyway.
        delete from rhnServerPackage where server_id = server_id_in;
        delete from rhnServerTokenRegs where server_id = server_id_in;
        delete from rhnSnapshotTag where server_id = server_id_in;
        -- this cascades to:
        --   rhnSnapshotChannel, rhnSnapshotConfigChannel, rhnSnapshotPackage,
        --   rhnSnapshotConfigRevision, rhnSnapshotServerGroup,
        --   rhnSnapshotTag.
        -- We may want to consider delete_snapshot() at some point, but
        --   I don't think we need to yet.
        delete from rhnSnapshot where server_id = server_id_in;
        delete from rhnUserServerPrefs where server_id = server_id_in;
        -- hrm, this one's interesting... we _probably_ should delete
        -- everything for the parent server_id when we delete the proxy,
        -- but we don't currently.
        delete from rhnServerPath where server_id_in in (server_id, proxy_server_id);
        delete from rhnUserServerPerms where server_id = server_id_in;

        delete from rhnServerNetInterface where server_id = server_id_in;

        delete from rhnServerUuid where server_id = server_id_in;

        delete from rhnPushClient where server_id = server_id_in;

        -- now get rhnServer itself.
        delete
        from    rhnServer
                where id = server_id_in;

        delete
        from    rhnSet
        where   label = 'system_list'
                and element = server_id_in;
end;
$$
language plpgsql;
   07070100000D85000081B400000000000000000000000167AE111400000783000000000000000000000000000000000000007E00000000susemanager-schema/upgrade/susemanager-schema-4.0.7-to-susemanager-schema-4.0.8/101-rhnUserActionOverview-include-orphans.sql --
-- Copyright (c) 2008 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--
--
--
--
-- rhnActionOverview, but on a per-user basis.

-- invoke as:
--
-- select	*
-- from		rhnUserActionOverview
-- where	org_id = :oid
--		and user_id = :uid;
--

create or replace view rhnUserActionOverview as
select	ao.org_id                                       as org_id,
	usp.user_id                                     as user_id,
        ao.action_id                                    as id,
	ao.type_name                                    as type_name,
        ao.scheduler                                    as scheduler,
	ao.earliest_action                              as earliest_action,
	coalesce( ao.name, ao.type_name )		as action_name,
	sa.status					as action_status_id,
	astat.name                                      as action_status,
	count(sa.action_id)				as tally,
	ao.archived                                     as archived
from    rhnActionOverview ao
        left join rhnServerAction sa on ao.action_id = sa.action_id
        left join rhnActionStatus astat on sa.status = astat.id
        left join rhnUserServerPerms usp on sa.server_id = usp.server_id
group by ao.org_id,
	 usp.user_id,
	 ao.action_id,
	 ao.type_name,
	 ao.scheduler,
	 ao.earliest_action,
	 coalesce( ao.name, ao.type_name ),
	 sa.status,
	 astat.name,
	 ao.archived
order by earliest_action;

 07070100000D86000081B400000000000000000000000167AE1114000000A8000000000000000000000000000000000000007900000000susemanager-schema/upgrade/susemanager-schema-4.0.7-to-susemanager-schema-4.0.8/102-rhnAction-archive-orphan-actions.sql  -- Archive actions which have no servers assigned
UPDATE rhnAction SET archived = 1 WHERE id IN (
    SELECT id FROM rhnUserActionOverview
    WHERE user_id IS NULL
);
07070100000D87000081B400000000000000000000000167AE1114000000B3000000000000000000000000000000000000007300000000susemanager-schema/upgrade/susemanager-schema-4.0.7-to-susemanager-schema-4.0.8/200-rhnTaskoSchedule-cron-freq.sql    UPDATE rhnTaskoSchedule SET cron_expr = '0 0 0 * * ?'
    WHERE job_label = 'minion-action-cleanup-default'
        AND active_till IS NULL
        AND cron_expr = '0 0 * * * ?';
 07070100000D88000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005000000000susemanager-schema/upgrade/susemanager-schema-4.0.8-to-susemanager-schema-4.0.9   07070100000D89000081B400000000000000000000000167AE11140000067F000000000000000000000000000000000000007400000000susemanager-schema/upgrade/susemanager-schema-4.0.8-to-susemanager-schema-4.0.9/002-rhnXccdfIdent-ident-upgrade.sql   -- select data about tests with truncated identifiers into temp table
create table tmp_oscap_upgrade as
        select row_number() over (partition by testresult_id order by rr.id) as rn,
               rr.id, rr.testresult_id, rr.result_id,
               xi.id as ident_id,
               0 as new_ident_id
          from rhnXccdfRuleresult rr
          join rhnXccdfRuleIdentmap rim
            on rim.rresult_id=rr.id
          join rhnxccdfident xi
            on xi.id = rim.ident_id
         where xi.identifier like '%...';

-- create new ids to truncated identifiers
create table tmp_oscap_upgrade_ids as
        select rn, ident_id, sequence_nextval('rhn_xccdf_ident_id_seq') as new_id
          from (select distinct rn, ident_id from tmp_oscap_upgrade) X;

-- assign new ids to selected identifiers
update tmp_oscap_upgrade u set new_ident_id = (select new_id from tmp_oscap_upgrade_ids i 
                                                where i.rn = u.rn and i.ident_id = u.ident_id);

-- create new (separated) test identifiers
insert into rhnxccdfident (id, identsystem_id, identifier)
        select distinct u.new_ident_id, o.identsystem_id, o.identifier || u.rn
          from tmp_oscap_upgrade u
          join rhnxccdfident o on u.ident_id = o.id
         where o.identifier like '%...';

-- create new rule maps
insert into rhnXccdfRuleIdentmap (rresult_id, ident_id)
        select id, new_ident_id from tmp_oscap_upgrade;

-- delete old rule maps
delete from rhnXccdfRuleIdentmap where ident_id in
        (select ident_id from tmp_oscap_upgrade);

-- remove temporary tables
drop table tmp_oscap_upgrade_ids;
drop table tmp_oscap_upgrade;
 07070100000D8A000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005100000000susemanager-schema/upgrade/susemanager-schema-4.0.9-to-susemanager-schema-4.0.10  07070100000D8B000081B400000000000000000000000167AE1114000005D2000000000000000000000000000000000000006C00000000susemanager-schema/upgrade/susemanager-schema-4.0.9-to-susemanager-schema-4.0.10/050-susecontentproject.sql   --
--
-- Copyright (c) 2018 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

CREATE TABLE IF NOT EXISTS suseContentProject(
    id          NUMERIC NOT NULL
                    CONSTRAINT suse_ct_project_id_pk PRIMARY KEY,
    name        VARCHAR(128) NOT NULL,
    org_id      NUMERIC NOT NULL
                    CONSTRAINT suse_ct_project_oid_fk
                    REFERENCES web_customer(id)
                    ON DELETE CASCADE,
    label       VARCHAR(24) NOT NULL,
    description TEXT,
    first_env_id NUMERIC,
    created     TIMESTAMPTZ
                    DEFAULT (current_timestamp) NOT NULL,
    modified    TIMESTAMPTZ
                    DEFAULT (current_timestamp) NOT NULL
)

;

CREATE SEQUENCE IF NOT EXISTS suse_ct_project_seq;

CREATE UNIQUE INDEX IF NOT EXISTS suse_ct_project_lblid_uq
    ON suseContentProject(label);

CREATE UNIQUE INDEX IF NOT EXISTS suse_ct_prj_nameid_oid_uq
    ON suseContentProject(org_id, name);

  07070100000D8C000081B400000000000000000000000167AE1114000005CC000000000000000000000000000000000000007200000000susemanager-schema/upgrade/susemanager-schema-4.0.9-to-susemanager-schema-4.0.10/051-susecontentprojectsource.sql --
-- Copyright (c) 2018 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

CREATE TABLE IF NOT EXISTS suseContentProjectSource(
    id         NUMERIC NOT NULL
                   CONSTRAINT suse_ct_prj_src_id_pk PRIMARY KEY,
    type       VARCHAR(16) NOT NULL,
    state      VARCHAR(16) NOT NULL,
    position   NUMERIC,
    project_id NUMERIC NOT NULL
                   CONSTRAINT suse_ct_prj_src_prjid_fk
                       REFERENCES suseContentProject(id)
                       ON DELETE CASCADE,
    channel_id NUMERIC
                   CONSTRAINT suse_ct_prj_src_chanid_fk
                       REFERENCES rhnChannel(id)
                       ON DELETE CASCADE
)

;

CREATE SEQUENCE IF NOT EXISTS suse_ct_prj_src_seq;

CREATE UNIQUE INDEX IF NOT EXISTS suse_ct_prj_src_pid_cid_uq
    ON suseContentProjectSource(project_id, channel_id);

CREATE INDEX IF NOT EXISTS suse_ct_prj_src_type
    ON suseContentProjectSource(type);
07070100000D8D000081B400000000000000000000000167AE1114000005AA000000000000000000000000000000000000007800000000susemanager-schema/upgrade/susemanager-schema-4.0.9-to-susemanager-schema-4.0.10/052-susecontentprojecthistoryentry.sql   --
-- Copyright (c) 2018 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

CREATE TABLE IF NOT EXISTS suseContentProjectHistoryEntry(
    id         NUMERIC NOT NULL
                   CONSTRAINT suse_ct_prj_hist_id_pk PRIMARY KEY,
    project_id NUMERIC NOT NULL
                   CONSTRAINT suse_ct_prj_hist_prjid_fk
                       REFERENCES suseContentProject(id)
                       ON DELETE CASCADE,
    message    TEXT,
    version    NUMERIC NOT NULL,
    created    TIMESTAMPTZ
                   DEFAULT (current_timestamp) NOT NULL,
    user_id    NUMERIC
                   CONSTRAINT suse_ct_prj_hist_uid_fk
                       REFERENCES web_contact (id)
                       ON DELETE SET NULL
)

;

CREATE SEQUENCE IF NOT EXISTS suse_ct_prj_hist_seq;

CREATE UNIQUE INDEX IF NOT EXISTS suse_ct_prj_hist_pid_ver_uq
    ON suseContentProjectHistoryEntry(project_id, version);
  07070100000D8E000081B400000000000000000000000167AE111400000584000000000000000000000000000000000000006B00000000susemanager-schema/upgrade/susemanager-schema-4.0.9-to-susemanager-schema-4.0.10/053-susecontentfilter.sql    --
-- Copyright (c) 2018 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

CREATE TABLE IF NOT EXISTS suseContentFilter(
    id       NUMERIC NOT NULL
                 CONSTRAINT suse_ct_filter_id_pk PRIMARY KEY,
    org_id   NUMERIC NOT NULL
                 CONSTRAINT suse_ct_project_oid_fk
                     REFERENCES web_customer(id)
                     ON DELETE CASCADE,
    type     VARCHAR(16) NOT NULL,
    name     VARCHAR(128) NOT NULL,
    criteria TEXT,
    created  TIMESTAMPTZ
                 DEFAULT (current_timestamp) NOT NULL,
    modified TIMESTAMPTZ
                 DEFAULT (current_timestamp) NOT NULL
)

;

CREATE SEQUENCE IF NOT EXISTS suse_ct_filter_seq;

CREATE UNIQUE INDEX IF NOT EXISTS suse_ct_filter_org_name_uq
    ON suseContentFilter(org_id, name);

CREATE INDEX IF NOT EXISTS suse_ct_filter_type
    ON suseContentFilter(type);
07070100000D8F000081B400000000000000000000000167AE111400000513000000000000000000000000000000000000007200000000susemanager-schema/upgrade/susemanager-schema-4.0.9-to-susemanager-schema-4.0.10/054-susecontentfilterproject.sql --
-- Copyright (c) 2018 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

CREATE TABLE IF NOT EXISTS suseContentFilterProject(
    id         NUMERIC PRIMARY KEY,
    filter_id  NUMERIC NOT NULL
                   CONSTRAINT suse_ct_filter_fid_fk
                       REFERENCES suseContentFilter(id)
                       ON DELETE CASCADE,
    project_id NUMERIC NOT NULL
                   CONSTRAINT suse_ct_filter_pid_fk
                       REFERENCES suseContentProject(id)
                       ON DELETE CASCADE,
    state      VARCHAR(16) NOT NULL,
    position   NUMERIC
);

CREATE SEQUENCE IF NOT EXISTS suse_ct_f_p_seq;

CREATE UNIQUE INDEX IF NOT EXISTS suse_ct_filter_project_uq
    ON suseContentFilterProject(filter_id, project_id);
 07070100000D90000081B400000000000000000000000167AE1114000007CC000000000000000000000000000000000000007000000000susemanager-schema/upgrade/susemanager-schema-4.0.9-to-susemanager-schema-4.0.10/055-susecontentenvironment.sql   --
-- Copyright (c) 2018 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

CREATE TABLE IF NOT EXISTS suseContentEnvironment(
    id          NUMERIC NOT NULL
                    CONSTRAINT suse_ct_env_id_pk PRIMARY KEY,
    project_id  NUMERIC
                    CONSTRAINT suse_ct_env_pid_fk
                        REFERENCES suseContentProject(id)
                        ON DELETE CASCADE,
    label       VARCHAR(16) NOT NULL,
    name        VARCHAR(128) NOT NULL,
    description TEXT,
    version     NUMERIC,
    next_env_id NUMERIC
                    CONSTRAINT suse_ct_env_nid_fk
                        REFERENCES suseContentEnvironment(id),
    created     TIMESTAMPTZ
                    DEFAULT (current_timestamp) NOT NULL,
    modified    TIMESTAMPTZ
                    DEFAULT (current_timestamp) NOT NULL
)

;

CREATE SEQUENCE IF NOT EXISTS suse_ct_env_seq;

CREATE UNIQUE INDEX IF NOT EXISTS suse_ct_env_pid_lbl_uq
    ON suseContentEnvironment(project_id, label);

CREATE UNIQUE INDEX IF NOT EXISTS suse_ct_env_pid_name_uq
    ON suseContentEnvironment(project_id, name);

-- CREATE UNIQUE INDEX IF NOT EXISTS suse_ct_env_nid_uq
--     ON suseContentEnvironment(next_env_id);

ALTER TABLE suseContentProject
  DROP CONSTRAINT IF EXISTS suse_ct_project_fenvid_fk;

ALTER TABLE suseContentProject
  ADD CONSTRAINT suse_ct_project_fenvid_fk
  FOREIGN KEY (first_env_id)
  REFERENCES suseContentEnvironment(id)
  ON DELETE SET NULL;
07070100000D91000081B400000000000000000000000167AE111400000568000000000000000000000000000000000000007600000000susemanager-schema/upgrade/susemanager-schema-4.0.9-to-susemanager-schema-4.0.10/057-susecontentenvironmenttarget.sql --
-- Copyright (c) 2018 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

CREATE TABLE IF NOT EXISTS suseContentEnvironmentTarget(
    id         NUMERIC NOT NULL
                   CONSTRAINT suse_ct_env_tgt_id_pk PRIMARY KEY,
    env_id     NUMERIC
                   CONSTRAINT suse_ct_env_tgt_eid_fk
                       REFERENCES suseContentEnvironment(id)
                       ON DELETE CASCADE,
    type       VARCHAR(16) NOT NULL,
    channel_id NUMERIC
                   CONSTRAINT suse_ct_env_tgt_chanid_fk
                       REFERENCES rhnChannel(id)
)

;

CREATE SEQUENCE IF NOT EXISTS suse_ct_env_tgt_seq;

CREATE UNIQUE INDEX IF NOT EXISTS suse_ct_env_tgt_env_cid_uq
    ON suseContentEnvironmentTarget(env_id, channel_id);

CREATE INDEX IF NOT EXISTS suse_ct_env_tgt_type
    ON suseContentEnvironmentTarget(type);

07070100000D92000081B400000000000000000000000167AE11140000029A000000000000000000000000000000000000006900000000susemanager-schema/upgrade/susemanager-schema-4.0.9-to-susemanager-schema-4.0.10/101-insert_checksum.sql  
create or replace function
insert_checksum(checksum_type_in in varchar, checksum_in in varchar)
returns numeric
as
$$
declare
    checksum_id     numeric;
begin
    checksum_id := nextval('rhnchecksum_seq');

    insert into rhnChecksum (id, checksum_type_id, checksum)
      values (
          checksum_id,
          (select id from rhnChecksumType where label = checksum_type_in),
          checksum_in
      )
      on conflict do nothing;

    select c.id
        into strict checksum_id
        from rhnChecksumView c
        where c.checksum = checksum_in and
            c.checksum_type = checksum_type_in;

    return checksum_id;
end;
$$ language plpgsql;
  07070100000D93000081B400000000000000000000000167AE1114000001E1000000000000000000000000000000000000007200000000susemanager-schema/upgrade/susemanager-schema-4.0.9-to-susemanager-schema-4.0.10/102-insert_client_capability.sql 
create or replace function
insert_client_capability(name_in in varchar)
returns numeric
as $$
declare
    cap_name_id     numeric;
begin
    cap_name_id := nextval('rhn_client_capname_id_seq');

    insert into rhnClientCapabilityName(id, name)
        values (cap_name_id, name_in)
        on conflict do nothing;

    select id
        into strict cap_name_id
        from rhnclientcapabilityname
        where name = name_in;

    return cap_name_id;
end;
$$ language plpgsql;
   07070100000D94000081B400000000000000000000000167AE1114000001B8000000000000000000000000000000000000007000000000susemanager-schema/upgrade/susemanager-schema-4.0.9-to-susemanager-schema-4.0.10/103-insert_config_filename.sql   
create or replace function
insert_config_filename(name_in in varchar)
returns numeric as
$$
declare
    name_id     numeric;
begin
    name_id := nextval('rhn_cfname_id_seq');

    insert into rhnConfigFileName (id, path)
        values (name_id, name_in)
        on conflict do nothing;

    select id
        into strict name_id
        from rhnconfigfilename
        where path = name_in;

    return name_id;
end;
$$ language plpgsql;
07070100000D95000081B400000000000000000000000167AE11140000049B000000000000000000000000000000000000006C00000000susemanager-schema/upgrade/susemanager-schema-4.0.9-to-susemanager-schema-4.0.10/104-insert_config_info.sql   
create or replace function
insert_config_info(
    username_in     in varchar,
    groupname_in    in varchar,
    filemode_in     in numeric,
    selinux_ctx_in  in varchar,
    symlink_target_id in numeric
)
returns numeric
as
$$
declare
    config_info_id    numeric;
begin
    config_info_id := nextval('rhn_confinfo_id_seq');

    insert into rhnConfigInfo (id, username, groupname, filemode, selinux_ctx, symlink_target_filename_id)
        values (config_info_id, username_in, groupname_in, filemode_in, selinux_ctx_in, symlink_target_id)
        on conflict do nothing;

    select id
      into config_info_id
      from rhnConfigInfo
      where (username = username_in or (username is null and username_in is null))
        and (groupname = groupname_in or (groupname is null and groupname_in is null))
        and (filemode = filemode_in or (filemode is null and filemode_in is null))
        and (selinux_ctx = selinux_ctx_in or (selinux_ctx is null and selinux_ctx_in is null))
        and (symlink_target_filename_id = symlink_target_id or (symlink_target_filename_id is null and symlink_target_id is null));

    return config_info_id;
end;
$$ language plpgsql;
 07070100000D96000081B400000000000000000000000167AE111400000193000000000000000000000000000000000000006400000000susemanager-schema/upgrade/susemanager-schema-4.0.9-to-susemanager-schema-4.0.10/105-insert_cve.sql   
create or replace function
insert_cve(name_in in varchar)
returns numeric
as $$
declare
    name_id     numeric;
begin
    name_id := nextval('rhn_cve_id_seq');

    insert into rhnCVE (id, name)
        values (name_id, name_in)
        on conflict do nothing;

    select id
        into strict name_id
        from rhnCVE
        where name = name_in;

    return name_id;
end;
$$ language plpgsql;
 07070100000D97000081B400000000000000000000000167AE111400000249000000000000000000000000000000000000006400000000susemanager-schema/upgrade/susemanager-schema-4.0.9-to-susemanager-schema-4.0.10/106-insert_evr.sql   
create or replace function
insert_evr(e_in in varchar, v_in in varchar, r_in in varchar)
returns numeric
as
$$
declare
    evr_id  numeric;
begin
    evr_id := nextval('rhn_pkg_evr_seq');

    insert into rhnPackageEVR(id, epoch, version, release, evr)
        values (evr_id, e_in, v_in, r_in, evr_t(e_in, v_in, r_in))
        on conflict do nothing;

    select id
        into strict evr_id
        from rhnPackageEVR
        where ((epoch is null and e_in is null) or (epoch = e_in)) and
           version = v_in and release = r_in;

    return evr_id;
end;
$$ language plpgsql;
   07070100000D98000081B400000000000000000000000167AE1114000001CE000000000000000000000000000000000000006B00000000susemanager-schema/upgrade/susemanager-schema-4.0.9-to-susemanager-schema-4.0.10/107-insert_md_keyword.sql    
create or replace function
insert_md_keyword(label_in in varchar)
returns numeric
as
$$
declare
    md_keyword_id numeric;
begin
    md_keyword_id := nextval('suse_mdkeyword_id_seq');

    insert into suseMdKeyword (id, label)
        values (md_keyword_id, label_in)
        on conflict do nothing;

    select id
        into strict md_keyword_id
        from suseMdKeyword
        where label = label_in;

    return md_keyword_id;
end;
$$ language plpgsql;
  07070100000D99000081B400000000000000000000000167AE1114000002E8000000000000000000000000000000000000007300000000susemanager-schema/upgrade/susemanager-schema-4.0.9-to-susemanager-schema-4.0.10/108-insert_package_capability.sql    
create or replace function
insert_package_capability(name_in in varchar, version_in in varchar default null)
returns numeric
as
$$
declare
    name_id numeric;
begin
    name_id := nextval('rhn_pkg_capability_id_seq');

    insert into rhnPackageCapability(id, name, version)
        values (name_id, name_in, version_in)
        on conflict do nothing;

    if version_in is null then
        select id
            into strict name_id
            from rhnpackagecapability
            where name = name_in and version is null;
    else
        select id
            into strict name_id
            from rhnpackagecapability
            where name = name_in and version = version_in;
    end if;

    return name_id;
end;
$$ language plpgsql;
07070100000D9A000081B400000000000000000000000167AE1114000001B0000000000000000000000000000000000000006E00000000susemanager-schema/upgrade/susemanager-schema-4.0.9-to-susemanager-schema-4.0.10/109-insert_package_delta.sql 
create or replace function
insert_package_delta(n_in in varchar)
returns numeric
as
$$
declare
    name_id     numeric;
begin
    name_id := nextval('rhn_packagedelta_id_seq');

    insert into rhnPackageDelta(id, label)
        values (name_id, n_in)
        on conflict do nothing;

    select id
        into strict name_id
        from rhnpackagedelta
        where label = n_in;

    return name_id;
end;
$$ language plpgsql;
07070100000D9B000081B400000000000000000000000167AE1114000001C5000000000000000000000000000000000000006E00000000susemanager-schema/upgrade/susemanager-schema-4.0.9-to-susemanager-schema-4.0.10/110-insert_package_group.sql 
create or replace function
insert_package_group(name_in in varchar)
returns numeric
as
$$
declare
    package_id   numeric;
begin
    package_id := nextval('rhn_package_group_id_seq');

    insert into rhnPackageGroup(id, name)
        values (package_id, name_in)
        on conflict do nothing;

    select id
        into strict package_id
        from rhnPackageGroup
        where name = name_in;

    return package_id;
end;
$$ language plpgsql;
   07070100000D9C000081B400000000000000000000000167AE1114000001AD000000000000000000000000000000000000006D00000000susemanager-schema/upgrade/susemanager-schema-4.0.9-to-susemanager-schema-4.0.10/111-insert_package_name.sql  
create or replace function
insert_package_name(name_in in varchar)
returns numeric
as
$$
declare
    name_id     numeric;
begin
    name_id := nextval('rhn_pkg_name_seq');

    insert into rhnPackageName(id, name)
        values (name_id, name_in)
        on conflict do nothing;

    select id
        into strict name_id
        from rhnPackageName
        where name = name_in;

    return name_id;
end;
$$ language plpgsql;
   07070100000D9D000081B400000000000000000000000167AE1114000002E0000000000000000000000000000000000000006E00000000susemanager-schema/upgrade/susemanager-schema-4.0.9-to-susemanager-schema-4.0.10/112-insert_package_nevra.sql 
create or replace function
insert_package_nevra(
        name_id_in in numeric,
        evr_id_in in numeric,
        package_arch_id_in in numeric
) returns numeric
as
$$
declare
    nevra_id numeric;
begin
    nevra_id := nextval('rhn_pkgnevra_id_seq');

    insert into rhnPackageNEVRA(id, name_id, evr_id, package_arch_id)
        values (nevra_id, name_id_in, evr_id_in, package_arch_id_in)
        on conflict do nothing;

    select id
        into strict nevra_id
        from rhnPackageNEVRA
        where name_id = name_id_in and evr_id = evr_id_in and
            (package_arch_id = package_arch_id_in or
            (package_arch_id is null and package_arch_id_in is null));

    return nevra_id;
end;
$$ language plpgsql;
07070100000D9E000081B400000000000000000000000167AE1114000001B4000000000000000000000000000000000000006C00000000susemanager-schema/upgrade/susemanager-schema-4.0.9-to-susemanager-schema-4.0.10/113-insert_source_name.sql   
create or replace function
insert_source_name(name_in in varchar)
returns numeric
as
$$
declare
    source_id   numeric;
begin
    source_id := nextval('rhn_sourcerpm_id_seq');

    insert into rhnSourceRPM(id, name)
        values (source_id, name_in)
        on conflict do nothing;

    select id
        into strict source_id
        from rhnSourceRPM
        where name = name_in;

    return source_id;
end;
$$ language plpgsql;
07070100000D9F000081B400000000000000000000000167AE1114000001F1000000000000000000000000000000000000006400000000susemanager-schema/upgrade/susemanager-schema-4.0.9-to-susemanager-schema-4.0.10/114-insert_tag.sql   
create or replace function
insert_tag(org_id_in in numeric, tag_name_id_in in numeric)
returns numeric
as $$
declare
    tag_id  numeric;
begin
    tag_id := nextval('rhn_tag_id_seq');

    insert into rhnTag(id, org_id, name_id)
        values (tag_id, org_id_in, tag_name_id_in)
        on conflict do nothing;

    select id
        into strict tag_id
        from rhnTag
        where org_id = org_id_in and
            name_id = tag_name_id_in;

    return tag_id;
end;
$$ language plpgsql;
   07070100000DA0000081B400000000000000000000000167AE11140000019F000000000000000000000000000000000000006900000000susemanager-schema/upgrade/susemanager-schema-4.0.9-to-susemanager-schema-4.0.10/115-insert_tag_name.sql  
create or replace function
insert_tag_name(name_in in varchar)
returns numeric
as
$$
declare
    name_id numeric;
begin
    name_id := nextval('rhn_tagname_id_seq');

    insert into rhnTagName(id, name)
        values (name_id, name_in)
        on conflict do nothing;

    select id
        into strict name_id
        from rhnTagName
        where name = name_in;

    return name_id;
end;
$$ language plpgsql;
 07070100000DA1000081B400000000000000000000000167AE1114000002F8000000000000000000000000000000000000007400000000susemanager-schema/upgrade/susemanager-schema-4.0.9-to-susemanager-schema-4.0.10/116-insert_transaction_package.sql   
create or replace function
insert_transaction_package(
    o_id_in      in numeric,
    n_id_in      in numeric,
    e_id_in      in numeric,
    p_arch_id_in in numeric
)
returns numeric
as
$$
declare
    tp_id       numeric;
begin
    tp_id := nextval('rhn_transpack_id_seq');

    insert into rhnTransactionPackage (id, operation, name_id, evr_id, package_arch_id)
        values (tp_id, o_id_in, n_id_in, e_id_in, p_arch_id_in)
        on conflict do nothing;

    select id
        into strict tp_id
        from rhnTransactionPackage
     where operation = o_id_in and name_id = n_id_in and evr_id = e_id_in and
        (package_arch_id = p_arch_id_in or (p_arch_id_in is null and package_arch_id is null));

    return tp_id;
end;
$$ language plpgsql;
07070100000DA2000081B400000000000000000000000167AE111400000239000000000000000000000000000000000000007000000000susemanager-schema/upgrade/susemanager-schema-4.0.9-to-susemanager-schema-4.0.10/117-insert_xccdf_benchmark.sql   
create or replace function
insert_xccdf_benchmark(identifier_in in varchar, version_in in varchar)
returns numeric
as
$$
declare
    benchmark_id numeric;
begin
    benchmark_id := nextval('rhn_xccdf_benchmark_id_seq');

    insert into rhnXccdfBenchmark (id, identifier, version)
        values (benchmark_id, identifier_in, version_in)
        on conflict do nothing;

    select id
        into strict benchmark_id
        from rhnXccdfBenchmark
        where identifier = identifier_in and version = version_in;

    return benchmark_id;
end;
$$ language plpgsql;
   07070100000DA3000081B400000000000000000000000167AE111400000250000000000000000000000000000000000000006C00000000susemanager-schema/upgrade/susemanager-schema-4.0.9-to-susemanager-schema-4.0.10/118-insert_xccdf_ident.sql   
create or replace function
insert_xccdf_ident(ident_sys_id_in in numeric, identifier_in in varchar)
returns numeric
as
$$
declare
    xccdf_ident_id numeric;
begin
    xccdf_ident_id := nextval('rhn_xccdf_ident_id_seq');

    insert into rhnXccdfIdent (id, identsystem_id, identifier)
        values (xccdf_ident_id, ident_sys_id_in, identifier_in)
        on conflict do nothing;

    select id
        into strict xccdf_ident_id
        from rhnXccdfIdent
        where identsystem_id = ident_sys_id_in and identifier = identifier_in;

    return xccdf_ident_id;
end;
$$ language plpgsql;
07070100000DA4000081B400000000000000000000000167AE1114000001E8000000000000000000000000000000000000007300000000susemanager-schema/upgrade/susemanager-schema-4.0.9-to-susemanager-schema-4.0.10/119-insert_xccdf_ident_system.sql    
create or replace function
insert_xccdf_ident_system(system_in in varchar)
returns numeric
as
$$
declare
    ident_sys_id numeric;
begin
    ident_sys_id := nextval('rhn_xccdf_identsytem_id_seq');

    insert into rhnXccdfIdentSystem (id, system)
        values (ident_sys_id, system_in)
        on conflict do nothing;

    select id
        into strict ident_sys_id
        from rhnXccdfIdentSystem
        where system = system_in;

    return ident_sys_id;
end;
$$ language plpgsql;
07070100000DA5000081B400000000000000000000000167AE111400000216000000000000000000000000000000000000006E00000000susemanager-schema/upgrade/susemanager-schema-4.0.9-to-susemanager-schema-4.0.10/120-insert_xccdf_profile.sql 
create or replace function
insert_xccdf_profile(identifier_in in varchar, title_in in varchar)
returns numeric
as
$$
declare
    profile_id numeric;
begin
    profile_id := nextval('rhn_xccdf_profile_id_seq');

    insert into rhnXccdfProfile (id, identifier, title)
        values (profile_id, identifier_in, title_in)
        on conflict do nothing;

    select id
        into profile_id
        from rhnXccdfProfile
        where identifier = identifier_in and title = title_in;

    return profile_id;
end;
$$ language plpgsql;
  07070100000DA6000081B400000000000000000000000167AE111400000902000000000000000000000000000000000000006900000000susemanager-schema/upgrade/susemanager-schema-4.0.9-to-susemanager-schema-4.0.10/121-lookup_checksum.sql  --
-- Copyright (c) 2010 - 2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

create or replace function
lookup_checksum(checksum_type_in in varchar, checksum_in in varchar)
returns numeric
as
$$
declare
    checksum_id     numeric;
begin
    if checksum_in is null then
        return null;
    end if;

    select c.id
      into checksum_id
      from rhnChecksumView c
     where c.checksum = checksum_in and
           c.checksum_type = checksum_type_in;

    if not found then
        -- HACK: insert is isolated in own function in order to be able to declare this function immutable
        -- Postgres optimizes immutable functions calls but those are compatible with the contract of lookup_\*
        -- see https://www.postgresql.org/docs/9.6/xfunc-volatility.html
        return insert_checksum(checksum_type_in, checksum_in);
    end if;

    return checksum_id;
end;
$$ language plpgsql immutable;

-- NOTE: This is intentionally not thread safe! You must lock rhnChecksum
-- if you are going to use this procedure!
create or replace function
lookup_checksum_fast(checksum_type_in in varchar, checksum_in in varchar)
returns numeric
as
$$
declare
    checksum_id     numeric;
begin
    if checksum_in is null then
        return null;
    end if;

    select c.id
      into checksum_id
      from rhnChecksumView c
     where c.checksum = checksum_in and
           c.checksum_type = checksum_type_in;

    if not found then
        checksum_id := nextval('rhnchecksum_seq');
        insert into rhnChecksum (id, checksum_type_id, checksum) values (
            checksum_id,
            (select id from rhnChecksumType where label = checksum_type_in),
            checksum_in);
    end if;

    return checksum_id;
end;
$$ language plpgsql;
  07070100000DA7000081B400000000000000000000000167AE111400000515000000000000000000000000000000000000007200000000susemanager-schema/upgrade/susemanager-schema-4.0.9-to-susemanager-schema-4.0.10/122-lookup_client_capability.sql --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 

create or replace function
lookup_client_capability(name_in in varchar)
returns numeric
as $$
declare
    cap_name_id     numeric;
begin
    select id
      into cap_name_id
      from rhnclientcapabilityname
     where name = name_in;

    if not found then
        -- HACK: insert is isolated in own function in order to be able to declare this function immutable
        -- Postgres optimizes immutable functions calls but those are compatible with the contract of lookup_\*
        -- see https://www.postgresql.org/docs/9.6/xfunc-volatility.html
        return insert_client_capability(name_in);
    end if;

    return cap_name_id;
end;
$$ language plpgsql immutable;
   07070100000DA8000081B400000000000000000000000167AE1114000004FD000000000000000000000000000000000000007000000000susemanager-schema/upgrade/susemanager-schema-4.0.9-to-susemanager-schema-4.0.10/123-lookup_config_filename.sql   --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.

create or replace function
lookup_config_filename(name_in in varchar)
returns numeric as
$$
declare
    name_id     numeric;
begin
    select id
      into name_id
      from rhnconfigfilename
     where path = name_in;

    if not found then
        -- HACK: insert is isolated in own function in order to be able to declare this function immutable
        -- Postgres optimizes immutable functions calls but those are compatible with the contract of lookup_\*
        -- see https://www.postgresql.org/docs/9.6/xfunc-volatility.html
        return insert_config_filename(name_in);
    end if;

    return name_id;
end;
$$ language plpgsql immutable;
   07070100000DA9000081B400000000000000000000000167AE11140000079F000000000000000000000000000000000000006C00000000susemanager-schema/upgrade/susemanager-schema-4.0.9-to-susemanager-schema-4.0.10/124-lookup_config_info.sql   --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

create or replace function
lookup_config_info(
    username_in     in varchar,
    groupname_in    in varchar,
    filemode_in     in numeric,
    selinux_ctx_in  in varchar,
    symlink_target_id in numeric
)
returns numeric
as
$$
declare
    config_info_id    numeric;
begin
    select id
      into config_info_id
      from rhnConfigInfo
      where (username = username_in or (username is null and username_in is null))
        and (groupname = groupname_in or (groupname is null and groupname_in is null))
        and (filemode = filemode_in or (filemode is null and filemode_in is null))
        and (selinux_ctx = selinux_ctx_in or (selinux_ctx is null and selinux_ctx_in is null))
        and (symlink_target_filename_id = symlink_target_id or (symlink_target_filename_id is null and symlink_target_id is null));

    if not found then
        -- HACK: insert is isolated in own function in order to be able to declare this function immutable
        -- Postgres optimizes immutable functions calls but those are compatible with the contract of lookup_\*
        -- see https://www.postgresql.org/docs/9.6/xfunc-volatility.html
        return insert_config_info(username_in, groupname_in, filemode_in, selinux_ctx_in, symlink_target_id);
    end if;

    return config_info_id;
end;
$$ language plpgsql immutable;
 07070100000DAA000081B400000000000000000000000167AE1114000004DA000000000000000000000000000000000000006400000000susemanager-schema/upgrade/susemanager-schema-4.0.9-to-susemanager-schema-4.0.10/125-lookup_cve.sql   --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.

create or replace function
lookup_cve(name_in in varchar)
returns numeric
as $$
declare
    name_id     numeric;
begin
    select id
      into name_id
      from rhnCVE
     where name = name_in;

    if not found then
        -- HACK: insert is isolated in own function in order to be able to declare this function immutable
        -- Postgres optimizes immutable functions calls but those are compatible with the contract of lookup_\*
        -- see https://www.postgresql.org/docs/9.6/xfunc-volatility.html
        return insert_cve(name_in);
    end if;

    return name_id;
end;
$$ language plpgsql immutable;
  07070100000DAB000081B400000000000000000000000167AE111400000565000000000000000000000000000000000000006400000000susemanager-schema/upgrade/susemanager-schema-4.0.9-to-susemanager-schema-4.0.10/126-lookup_evr.sql   --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.

create or replace function
lookup_evr(e_in in varchar, v_in in varchar, r_in in varchar)
returns numeric
as
$$
declare
    evr_id  numeric;
begin
    select id
      into evr_id
      from rhnPackageEVR
     where ((epoch is null and e_in is null) or (epoch = e_in)) and
           version = v_in and
           release = r_in;

    if not found then
        -- HACK: insert is isolated in own function in order to be able to declare this function immutable
        -- Postgres optimizes immutable functions calls but those are compatible with the contract of lookup_\*
        -- see https://www.postgresql.org/docs/9.6/xfunc-volatility.html
        return insert_evr(e_in, v_in, r_in);
    end if;

    return evr_id;
end;
$$ language plpgsql immutable;
   07070100000DAC000081B400000000000000000000000167AE11140000043D000000000000000000000000000000000000006B00000000susemanager-schema/upgrade/susemanager-schema-4.0.9-to-susemanager-schema-4.0.10/127-lookup_md_keyword.sql    --
-- Copyright (c) 2012 Novell
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--

create or replace function
lookup_md_keyword(label_in in varchar)
returns numeric
as
$$
declare
    md_keyword_id numeric;
begin
    select id
      into md_keyword_id
      from suseMdKeyword
     where label = label_in;

    if not found then
        -- HACK: insert is isolated in own function in order to be able to declare this function immutable
        -- Postgres optimizes immutable functions calls but those are compatible with the contract of lookup_\*
        -- see https://www.postgresql.org/docs/9.6/xfunc-volatility.html
        return insert_md_keyword(label_in);
    end if;

    return md_keyword_id;
end;
$$ language plpgsql immutable;
   07070100000DAD000081B400000000000000000000000167AE1114000009BD000000000000000000000000000000000000007300000000susemanager-schema/upgrade/susemanager-schema-4.0.9-to-susemanager-schema-4.0.10/128-lookup_package_capability.sql    --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 

create or replace function
lookup_package_capability(name_in in varchar, version_in in varchar default null)
returns numeric
as
$$
declare
    name_id numeric;
begin
    if version_in is null then
        select id
          into name_id
          from rhnpackagecapability
         where name = name_in and
               version is null;
    else
        select id
          into name_id
          from rhnpackagecapability
         where name = name_in and
               version = version_in;
    end if;

    if not found then
        -- HACK: insert is isolated in own function in order to be able to declare this function immutable
        -- Postgres optimizes immutable functions calls but those are compatible with the contract of lookup_\*
        -- see https://www.postgresql.org/docs/9.6/xfunc-volatility.html
        return insert_package_capability(name_in, version_in);
    end if;

    return name_id;
end;
$$ language plpgsql immutable;

-- Note: intentionally not thread-safe! You must aquire a write lock on the
-- rhnPackageCapability tabel if you are going to use this proc!
create or replace function lookup_package_capability_fast(name_in in varchar, version_in in varchar default null)
returns numeric
as
$$
declare
    name_id numeric;
begin
    if version_in is null then
        select id
          into name_id
          from rhnpackagecapability
         where name = name_in and
               version is null;
    else
        select id
          into name_id
          from rhnpackagecapability
         where name = name_in and
               version = version_in;
    end if;

    if not found then
        name_id := nextval('rhn_pkg_capability_id_seq');
        insert into rhnPackageCapability(id, name, version) values (
               name_id, name_in, version_in);
    end if;

    return name_id;
end;
$$ language plpgsql;
   07070100000DAE000081B400000000000000000000000167AE1114000004F1000000000000000000000000000000000000006E00000000susemanager-schema/upgrade/susemanager-schema-4.0.9-to-susemanager-schema-4.0.10/129-lookup_package_delta.sql --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 

create or replace function
lookup_package_delta(n_in in varchar)
returns numeric
as
$$
declare
    name_id     numeric;
begin
    select id
      into name_id
      from rhnPackageDelta
     where label = n_in;

    if not found then
        -- HACK: insert is isolated in own function in order to be able to declare this function immutable
        -- Postgres optimizes immutable functions calls but those are compatible with the contract of lookup_\*
        -- see https://www.postgresql.org/docs/9.6/xfunc-volatility.html
        return insert_package_delta(n_in);
    end if;

    return name_id;
end;
$$ language plpgsql immutable;
   07070100000DAF000081B400000000000000000000000167AE111400000500000000000000000000000000000000000000006E00000000susemanager-schema/upgrade/susemanager-schema-4.0.9-to-susemanager-schema-4.0.10/130-lookup_package_group.sql --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 

create or replace function
lookup_package_group(name_in in varchar)
returns numeric
as
$$
declare
    package_id   numeric;
begin
    select id
      into package_id
      from rhnPackageGroup
     where name = name_in;

    if not found then
        -- HACK: insert is isolated in own function in order to be able to declare this function immutable
        -- Postgres optimizes immutable functions calls but those are compatible with the contract of lookup_\*
        -- see https://www.postgresql.org/docs/9.6/xfunc-volatility.html
        return insert_package_group(name_in);
    end if;

    return package_id;
end;
$$ language plpgsql immutable;
07070100000DB0000081B400000000000000000000000167AE11140000056A000000000000000000000000000000000000006D00000000susemanager-schema/upgrade/susemanager-schema-4.0.9-to-susemanager-schema-4.0.10/131-lookup_package_name.sql  --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 

create or replace function
lookup_package_name(name_in in varchar, ignore_null in numeric default 0)
returns numeric
as
$$
declare
    name_id     numeric;
begin
    if ignore_null = 1 and name_in is null then
        return null;
    end if;

    select id
      into name_id
      from rhnPackageName
     where name = name_in;

    if not found then
        -- HACK: insert is isolated in own function in order to be able to declare this function immutable
        -- Postgres optimizes immutable functions calls but those are compatible with the contract of lookup_\*
        -- see https://www.postgresql.org/docs/9.6/xfunc-volatility.html
        return insert_package_name(name_in);
    end if;

    return name_id;
end;
$$ language plpgsql immutable;
  07070100000DB1000081B400000000000000000000000167AE11140000069B000000000000000000000000000000000000006E00000000susemanager-schema/upgrade/susemanager-schema-4.0.9-to-susemanager-schema-4.0.10/132-lookup_package_nevra.sql --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 

create or replace function
lookup_package_nevra(
        name_id_in in numeric,
        evr_id_in in numeric,
        package_arch_id_in in numeric,
        ignore_null_name in numeric default 0
) returns numeric
as
$$
declare
    nevra_id numeric;
begin
    if ignore_null_name = 1 and name_id_in is null then
        return null;
    end if;

    select id
      into nevra_id
      from rhnPackageNEVRA
     where name_id = name_id_in and
           evr_id = evr_id_in and
           (package_arch_id = package_arch_id_in or
            (package_arch_id is null and package_arch_id_in is null));

    if not found then
        -- HACK: insert is isolated in own function in order to be able to declare this function immutable
        -- Postgres optimizes immutable functions calls but those are compatible with the contract of lookup_\*
        -- see https://www.postgresql.org/docs/9.6/xfunc-volatility.html
        return insert_package_nevra(name_id_in, evr_id_in, package_arch_id_in);
    end if;

    return nevra_id;
end;
$$ language plpgsql immutable;
 07070100000DB2000081B400000000000000000000000167AE1114000004F6000000000000000000000000000000000000006C00000000susemanager-schema/upgrade/susemanager-schema-4.0.9-to-susemanager-schema-4.0.10/133-lookup_source_name.sql   --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 

create or replace function
lookup_source_name(name_in in varchar)
returns numeric
as
$$
declare
    source_id   numeric;
begin
    select id
      into source_id
      from rhnSourceRPM
     where name = name_in;

    if not found then
        -- HACK: insert is isolated in own function in order to be able to declare this function immutable
        -- Postgres optimizes immutable functions calls but those are compatible with the contract of lookup_\*
        -- see https://www.postgresql.org/docs/9.6/xfunc-volatility.html
        return insert_source_name(name_in);
    end if;

    return source_id;
end;
$$ language plpgsql immutable;
  07070100000DB3000081B400000000000000000000000167AE11140000056B000000000000000000000000000000000000006400000000susemanager-schema/upgrade/susemanager-schema-4.0.9-to-susemanager-schema-4.0.10/134-lookup_tag.sql   --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 

create or replace function
lookup_tag(org_id_in in numeric, name_in in varchar)
returns numeric
as $$
declare
    tag_id  numeric;
    tag_name_id numeric;
begin
    tag_name_id := lookup_tag_name(name_in);

    select id
      into tag_id
      from rhnTag
     where org_id = org_id_in and
           name_id = tag_name_id;

    if not found then
        -- HACK: insert is isolated in own function in order to be able to declare this function immutable
        -- Postgres optimizes immutable functions calls but those are compatible with the contract of lookup_\*
        -- see https://www.postgresql.org/docs/9.6/xfunc-volatility.html
        return insert_tag(org_id_in, tag_name_id);
    end if;

    return tag_id;
end;
$$ language plpgsql immutable;
 07070100000DB4000081B400000000000000000000000167AE1114000004E6000000000000000000000000000000000000006900000000susemanager-schema/upgrade/susemanager-schema-4.0.9-to-susemanager-schema-4.0.10/135-lookup_tag_name.sql  --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 

create or replace function
lookup_tag_name(name_in in varchar)
returns numeric
as
$$
declare
    name_id numeric;
begin
    select id
      into name_id
      from rhnTagName
     where name = name_in;

    if not found then
        -- HACK: insert is isolated in own function in order to be able to declare this function immutable
        -- Postgres optimizes immutable functions calls but those are compatible with the contract of lookup_\*
        -- see https://www.postgresql.org/docs/9.6/xfunc-volatility.html
        return insert_tag_name(name_in);
    end if;

    return name_id;
end;
$$ language plpgsql immutable;
  07070100000DB5000081B400000000000000000000000167AE111400000817000000000000000000000000000000000000007400000000susemanager-schema/upgrade/susemanager-schema-4.0.9-to-susemanager-schema-4.0.10/136-lookup_transaction_package.sql   --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 

create or replace function
lookup_transaction_package(
    o_in in varchar,
    n_in in varchar,
    e_in in varchar,
    v_in in varchar,
    r_in in varchar,
    a_in in varchar)
returns numeric
as
$$
declare
    o_id        numeric;
    n_id        numeric;
    e_id        numeric;
    p_arch_id   numeric;
    tp_id       numeric;
begin
    select id
      into o_id
      from rhnTransactionOperation
     where label = o_in;

    if not found then
        perform rhn_exception.raise_exception('invalid_transaction_operation');
    end if;

    n_id := lookup_package_name(n_in);
    e_id := lookup_evr(e_in, v_in, r_in);
    p_arch_id := null;

    if a_in is not null then
        p_arch_id := lookup_package_arch(a_in);
    end if;

    select id
      into tp_id
      from rhnTransactionPackage
     where operation = o_id and
           name_id = n_id and
           evr_id = e_id and
           (package_arch_id = p_arch_id or (p_arch_id is null and package_arch_id is null));

    if not found then
        -- HACK: insert is isolated in own function in order to be able to declare this function immutable
        -- Postgres optimizes immutable functions calls but those are compatible with the contract of lookup_\*
        -- see https://www.postgresql.org/docs/9.6/xfunc-volatility.html
        return insert_transaction_package(o_id, n_id, e_id, p_arch_id);
    end if;
    return tp_id;
end;
$$ language plpgsql immutable;
 07070100000DB6000081B400000000000000000000000167AE111400000559000000000000000000000000000000000000007000000000susemanager-schema/upgrade/susemanager-schema-4.0.9-to-susemanager-schema-4.0.10/137-lookup_xccdf_benchmark.sql   --
-- Copyright (c) 2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

create or replace function
lookup_xccdf_benchmark(identifier_in in varchar, version_in in varchar)
returns numeric
as
$$
declare
    benchmark_id numeric;
begin
    select id
      into benchmark_id
      from rhnXccdfBenchmark
     where identifier = identifier_in and version = version_in;

    if not found then
        -- HACK: insert is isolated in own function in order to be able to declare this function immutable
        -- Postgres optimizes immutable functions calls but those are compatible with the contract of lookup_\*
        -- see https://www.postgresql.org/docs/9.6/xfunc-volatility.html
        return insert_xccdf_benchmark(identifier_in, version_in);
    end if;

    return benchmark_id;
end;
$$ language plpgsql immutable;
   07070100000DB7000081B400000000000000000000000167AE11140000063A000000000000000000000000000000000000006C00000000susemanager-schema/upgrade/susemanager-schema-4.0.9-to-susemanager-schema-4.0.10/138-lookup_xccdf_ident.sql   --
-- Copyright (c) 2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.

create or replace function
lookup_xccdf_ident(system_in in varchar, identifier_in in varchar)
returns numeric
as
$$
declare
    xccdf_ident_id numeric;
    ident_sys_id numeric;
begin
    select id
      into ident_sys_id
      from rhnXccdfIdentSystem
     where system = system_in;

    if not found then
        -- HACK: insert is isolated in own function in order to be able to declare this function immutable
        -- Postgres optimizes immutable functions calls but those are compatible with the contract of lookup_\*
        -- see https://www.postgresql.org/docs/9.6/xfunc-volatility.html
        ident_sys_id := insert_xccdf_ident_system(system_in);
    end if;

    select id
      into xccdf_ident_id
      from rhnXccdfIdent
     where identsystem_id = ident_sys_id and identifier = identifier_in;

    if not found then
        return insert_xccdf_ident(ident_sys_id, identifier_in);
    end if;

    return xccdf_ident_id;
end;
$$ language plpgsql immutable;
  07070100000DB8000081B400000000000000000000000167AE111400000545000000000000000000000000000000000000006E00000000susemanager-schema/upgrade/susemanager-schema-4.0.9-to-susemanager-schema-4.0.10/139-lookup_xccdf_profile.sql --
-- Copyright (c) 2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

create or replace function
lookup_xccdf_profile(identifier_in in varchar, title_in in varchar)
returns numeric
as
$$
declare
    profile_id numeric;
begin
    select id
      into profile_id
      from rhnXccdfProfile
     where identifier = identifier_in and title = title_in;

    if not found then
        -- HACK: insert is isolated in own function in order to be able to declare this function immutable
        -- Postgres optimizes immutable functions calls but those are compatible with the contract of lookup_\*
        -- see https://www.postgresql.org/docs/9.6/xfunc-volatility.html
        return insert_xccdf_profile(identifier_in, title_in);
    end if;

    return profile_id;
end;
$$ language plpgsql immutable;
   07070100000DB9000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005000000000susemanager-schema/upgrade/susemanager-schema-4.1.0-to-susemanager-schema-4.1.1   07070100000DBA000081B400000000000000000000000167AE1114000003F0000000000000000000000000000000000000008C00000000susemanager-schema/upgrade/susemanager-schema-4.1.0-to-susemanager-schema-4.1.1/000-use-blob-instead-of-varchar-rhnpackagechangelogdata.sql   --
-- Copyright (c) 2019 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--

DROP VIEW rhnPackageChangeLog;

ALTER TABLE rhnPackageChangeLogData ALTER COLUMN text TYPE TEXT;

CREATE VIEW rhnPackageChangeLog
AS
SELECT rhnPackageChangeLogRec.id,
       rhnPackageChangeLogRec.package_id,
       rhnPackageChangeLogRec.changelog_data_id,
       rhnPackageChangeLogData.name,
       rhnPackageChangeLogData.text,
       rhnPackageChangeLogData.time,
       rhnPackageChangeLogRec.created,
       rhnPackageChangeLogRec.modified
FROM rhnPackageChangeLogRec, rhnPackageChangeLogData
WHERE rhnPackageChangeLogRec.changelog_data_id = rhnPackageChangeLogData.id;
07070100000DBB000081B400000000000000000000000167AE11140000058C000000000000000000000000000000000000006B00000000susemanager-schema/upgrade/susemanager-schema-4.1.0-to-susemanager-schema-4.1.1/001-rhnPackageExtraTag.sql    --
-- Copyright (c) 2019 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--

CREATE TABLE IF NOT EXISTS rhnPackageExtraTagKey
(
    id          NUMERIC NOT NULL
                    CONSTRAINT rhn_pkg_extra_tags_keys_id_pk PRIMARY KEY,
    name        VARCHAR(256) NOT NULL,
    created     TIMESTAMPTZ
                     DEFAULT (current_timestamp) NOT NULL
)
;

CREATE SEQUENCE IF NOT EXISTS rhn_package_extra_tags_keys_id_seq;

CREATE UNIQUE INDEX IF NOT EXISTS rhn_pkg_extra_tag_key_idx
    ON rhnPackageExtraTagKey (name);

CREATE TABLE IF NOT EXISTS rhnPackageExtraTag
(
    package_id  NUMERIC NOT NULL
                    CONSTRAINT rhn_pkg_extratags_pid_fk
                       REFERENCES rhnPackage (id)
                       ON DELETE CASCADE,
    key_id      NUMERIC NOT NULL
                       REFERENCES rhnPackageExtraTagKey (id)
                       ON DELETE CASCADE,
    value       VARCHAR(2048) NOT NULL,
    created     TIMESTAMPTZ
                     DEFAULT (current_timestamp) NOT NULL,
    primary key (package_id, key_id)
)
;



07070100000DBC000081B400000000000000000000000167AE1114000010DA000000000000000000000000000000000000007900000000susemanager-schema/upgrade/susemanager-schema-4.1.0-to-susemanager-schema-4.1.1/002-refactor_suseChannelUserRoleView.sql  --
-- Copyright (c) 2019 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--

DROP VIEW IF EXISTS rhnUserChannel;

DROP VIEW IF EXISTS suseChannelUserRoleView;

CREATE OR REPLACE VIEW
suseChannelUserRoleView
AS
  SELECT
    combination.channel_id,
    combination.user_id,
    combination.role,
    combination.user_org_id AS org_id,
    combination.parent_channel_id,
    CASE
      -- if channel is in an org trusted by the user's org, and if the channel itself is shared between the two, then user can subscribe it
      WHEN combination.role = 'subscribe' AND sharedChannels.is_shared_channel IS NOT NULL
        THEN NULL
      -- otherwise, if channel is not in user's org, then user can't manage it
      WHEN combination.role = 'manage' AND combination.channel_org_id IS NULL OR combination.channel_org_id <> combination.user_org_id
        THEN 'channel_not_owned'
      -- otherwise, if channel is in a family without permissions for the user's org, then user can't subscribe it
      WHEN combination.role = 'subscribe' AND channelPermissions.is_channel_available IS NULL
        THEN 'channel_not_available'
      -- otherwise, if channel is in a family without permissions for the user's org, then user can't subscribe it
      WHEN adminUsers.is_admin_user IS NOT NULL
        THEN NULL
      -- otherwise, if channel does not have the "not_globally_subscribable" bit set, user can subscribe it
      WHEN combination.role = 'subscribe' AND notGlobSubsChannels.is_not_globally_subscribable IS NULL
        THEN NULL
      -- otherwise, user might have an explicit permission on this channel
      WHEN explicitPermissions.has_explicit_permission IS NOT NULL
        THEN NULL
        -- otherwise, user can't either manage nor subscribe the channel
        ELSE 'direct_permission'
    END AS deny_reason
    FROM
      (SELECT
          c.id AS channel_id,
          c.org_id AS channel_org_id,
          c.parent_channel AS parent_channel_id,
          u.id AS user_id,
          u.org_id AS user_org_id,
          r.label AS role
          FROM rhnChannel c, web_contact u, rhnChannelPermissionRole r
      ) combination
     LEFT JOIN 
       (SELECT DISTINCT s.org_trust_id, s.id, 1 AS is_shared_channel
        FROM rhnSharedChannelView s) sharedChannels
     ON (sharedChannels.id = combination.channel_id AND sharedChannels.org_trust_id = combination.user_org_id)
     LEFT JOIN
       (SELECT DISTINCT cfp.org_id, cfm.channel_id, 1 AS is_channel_available
        FROM rhnChannelFamilyMembers cfm
          JOIN rhnOrgChannelFamilyPermissions cfp ON cfp.channel_family_id = cfm.channel_family_id) channelPermissions
     ON (combination.user_org_id = channelPermissions.org_id AND channelPermissions.channel_id = combination.channel_id)
     LEFT JOIN
       (SELECT DISTINCT m.user_id, 1 AS is_admin_user
        FROM rhnUserGroupMembers m
          JOIN rhnUserGroup g ON g.id = m.user_group_id
          JOIN rhnUserGroupType t ON t.id = g.group_type
        WHERE t.label = 'channel_admin' OR t.label = 'org_admin') adminUsers
     ON (adminUsers.user_id = combination.user_id)
     LEFT JOIN
       (SELECT DISTINCT ocs.channel_id, ocs.org_id, 1 AS is_not_globally_subscribable
        FROM rhnOrgChannelSettings ocs
          JOIN rhnOrgChannelSettingsType ocst ON ocst.id = ocs.setting_id
        WHERE ocst.label = 'not_globally_subscribable') notGlobSubsChannels
     ON (notGlobSubsChannels.channel_id = combination.channel_id AND notGlobSubsChannels.org_id = combination.user_org_id)
     LEFT JOIN
       (SELECT cpr.label, cp.channel_id, cp.user_id, 1 AS has_explicit_permission
        FROM rhnChannelPermission cp
          JOIN rhnChannelPermissionRole cpr ON cpr.id = cp.role_id) explicitPermissions
     ON (explicitPermissions.channel_id = combination.channel_id AND explicitPermissions.user_id = combination.user_id AND explicitPermissions.label = combination.role)
    -- ORDER BY channel_id, user_id, role, result
;
  07070100000DBD000081B400000000000000000000000167AE1114000001C2000000000000000000000000000000000000006B00000000susemanager-schema/upgrade/susemanager-schema-4.1.0-to-susemanager-schema-4.1.1/010_kickstart_for_salt.sql    insert into rhnServerGroupTypeFeature (server_group_type_id, feature_id,
                                       created, modified)
select lookup_sg_type('salt_entitled'), lookup_feature_type('ftr_kickstart'),
        current_timestamp,current_timestamp from dual
where not exists ( select 1 from rhnServerGroupTypeFeature
    where server_group_type_id = lookup_sg_type('salt_entitled')
      and feature_id = lookup_feature_type('ftr_kickstart') );
  07070100000DBE000081B400000000000000000000000167AE11140000011D000000000000000000000000000000000000007600000000susemanager-schema/upgrade/susemanager-schema-4.1.0-to-susemanager-schema-4.1.1/011-add-upgrade-ks-action-details.sql alter table rhnActionKickstart drop CONSTRAINT if exists rhn_actionks_up_ck;
alter table rhnActionKickstart add column if not exists
            upgrade CHAR(1) DEFAULT ('N') NOT NULL
                    CONSTRAINT rhn_actionks_up_ck
                    CHECK (upgrade in ('Y', 'N'));
   07070100000DBF000081B400000000000000000000000167AE11140000019D000000000000000000000000000000000000007600000000susemanager-schema/upgrade/susemanager-schema-4.1.0-to-susemanager-schema-4.1.1/020-monitoring-entitlement-debian.sql insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type)
    select lookup_server_arch('amd64-debian-linux'),
            lookup_sg_type('monitoring_entitled')
    from dual where not exists (
        select 1 from rhnServerServerGroupArchCompat where
        server_arch_id=lookup_server_arch('amd64-debian-linux') and
        server_group_type=lookup_sg_type('monitoring_entitled')
    );
   07070100000DC0000081B400000000000000000000000167AE111400000587000000000000000000000000000000000000008A00000000susemanager-schema/upgrade/susemanager-schema-4.1.0-to-susemanager-schema-4.1.1/100-enable-support-for-public-cloud-virtual-instances.sql INSERT INTO rhnCpuArch (id, label, name)
SELECT sequence_nextval('rhn_cpu_arch_id_seq'), 'cloud', 'cloud'
WHERE NOT EXISTS ( SELECT 1 FROM rhnCpuArch WHERE label = 'cloud' AND name = 'cloud');

INSERT INTO rhnServerArch (id, label, name, arch_type_id)
SELECT sequence_nextval('rhn_server_arch_id_seq'), 'cloud', 'cloud', lookup_arch_type('rpm')
WHERE NOT EXISTS ( SELECT 1 FROM rhnServerArch WHERE label = 'cloud' AND name = 'cloud');

INSERT INTO rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
SELECT lookup_server_arch('cloud'), lookup_sg_type('foreign_entitled')
WHERE NOT EXISTS ( SELECT 1 FROM rhnServerServerGroupArchCompat 
	WHERE server_arch_id = lookup_server_arch('cloud') AND server_group_type = lookup_sg_type('foreign_entitled'));

INSERT INTO rhnVirtualInstanceType (id, name, label)
SELECT sequence_nextval('rhn_vit_id_seq'), 'Azure', 'azure'
WHERE NOT EXISTS ( SELECT 1 FROM rhnVirtualInstanceType WHERE label = 'azure' AND name = 'Azure');

INSERT INTO rhnVirtualInstanceType (id, name, label)
SELECT sequence_nextval('rhn_vit_id_seq'), 'Amazon EC2', 'aws'
WHERE NOT EXISTS ( SELECT 1 FROM rhnVirtualInstanceType WHERE label = 'aws' AND name = 'Amazon EC2');

INSERT INTO rhnVirtualInstanceType (id, name, label)
SELECT sequence_nextval('rhn_vit_id_seq'), 'Google CE', 'gce'
WHERE NOT EXISTS ( SELECT 1 FROM rhnVirtualInstanceType WHERE label = 'gce' AND name = 'Google CE');
 07070100000DC1000081B400000000000000000000000167AE1114000020EF000000000000000000000000000000000000006000000000susemanager-schema/upgrade/susemanager-schema-4.1.0-to-susemanager-schema-4.1.1/200-rpm.pkb.sql   -- create schema rpm;

--update pg_setting
update pg_settings set setting = 'rpm,' || setting where name = 'search_path';

create or replace function isdigit(ch CHAR)
    RETURNS BOOLEAN as $$
    BEGIN
        if ascii(ch) between ascii('0') and ascii('9')
        then
            return TRUE;
        end if;
        return FALSE;
    END ;
$$ language 'plpgsql';

    
    create or replace FUNCTION isalpha(ch CHAR)
    RETURNS BOOLEAN as $$
    BEGIN
        if ascii(ch) between ascii('a') and ascii('z') or 
            ascii(ch) between ascii('A') and ascii('Z')
        then
            return TRUE;
        end if;
        return FALSE;
    END;
$$ language 'plpgsql';


    create or replace FUNCTION isalphanum(ch CHAR)
    RETURNS BOOLEAN as $$ 
    BEGIN
        if ascii(ch) between ascii('a') and ascii('z') or 
            ascii(ch) between ascii('A') and ascii('Z') or
            ascii(ch) between ascii('0') and ascii('9')
        then
            return TRUE;
        end if;
        return FALSE;
    END;
    $$ language 'plpgsql';


    create or replace FUNCTION rpmstrcmp (string1 IN VARCHAR, string2 IN VARCHAR)
    RETURNS INTEGER as $$
    declare
        str1 VARCHAR := string1;
        str2 VARCHAR := string2;
        digits VARCHAR(10) := '0123456789';
        lc_alpha VARCHAR(27) := 'abcdefghijklmnopqrstuvwxyz';
        uc_alpha VARCHAR(27) := 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
        alpha VARCHAR(54) := lc_alpha || uc_alpha;
        one VARCHAR;
        two VARCHAR;
        debupstreamv1 VARCHAR;
        debupstreamv2 VARCHAR;
        debrevisionv1 VARCHAR;
        debrevisionv2 VARCHAR;
        isnum BOOLEAN;
    BEGIN
        if str1 is NULL or str2 is NULL
        then
            RAISE EXCEPTION 'VALUE_ERROR.';
        end if;
      
        if str1 = str2
        then
            return 0;
        end if;
        debupstreamv1 := str1;
        debupstreamv2 := str2;
        debrevisionv1 := '';
        debrevisionv2 := '';
        if INSTR(str1, '-') <> 0
        then
            debupstreamv1 := SUBSTR(str1, 0, INSTR(str1, '-'));
        end if;
        if INSTR(str2, '-') <> 0
        then
            debupstreamv2 := SUBSTR(str2, 0, INSTR(str2, '-'));
        end if;
        if (str1 <> str2)
        then
            str1 := debupstreamv1;
            str2 := debupstreamv2;
        else
            if INSTR(str1, '-') <> 0 and INSTR(str2, '-') <> 0
            then
                debrevisionv1 := SUBSTR(str1, INSTR(str1, '-') + 1);
                debrevisionv2 := SUBSTR(str2, INSTR(str2, '-') + 1);
	    else
		return 0;
            end if;
            str1 = debrevisionv1;
            str2 = debrevisionv2;
        end if;
        one := str1;
        two := str2;

        <<segment_loop>>
        while one <> '' or two <> ''
        loop
            declare
                segm1 VARCHAR;
                segm2 VARCHAR;
                onechar CHAR(1);
                twochar CHAR(1);
            begin
                --raise notice 'Params: %, %',  one, two;
                -- Throw out all non-alphanum characters
                onechar := substr(one, 1, 1);
                twochar := substr(two, 1, 1);
                while one <> '' and not rpm.isalphanum(one) and onechar != '~' and onechar != '^'
                loop
                    one := substr(one, 2);
                end loop;
                while two <> '' and not rpm.isalphanum(two) and twochar != '~' and twochar != '^'
                loop
                    two := substr(two, 2);
                end loop;
                --raise notice 'new params: %, %', one, two;

                onechar := substr(one, 1, 1);
                twochar := substr(two, 1, 1);
                --raise notice 'new chars 1: %, %', onechar, twochar;
                /* handle the tilde separator, it sorts before everything else */
                if (onechar = '~' or twochar = '~')
                then
                    if (onechar != '~') then return 1; end if;
                    if (twochar != '~') then return -1; end if;
                    --raise notice 'passed tilde chars: %, %', onechar, twochar;
                    one := substr(one, 2);
                    two := substr(two, 2);
                    continue;
                end if;

                /*
                 * Handle caret separator. Concept is the same as tilde,
                 * except that if one of the strings ends (base version),
                 * the other is considered as higher version.
                 */
                onechar := substr(one, 1, 1);
                twochar := substr(two, 1, 1);
                --raise notice 'new chars 2: %, %', onechar, twochar;
                if (onechar = '^' or twochar = '^')
                then
                    if (one = '') then return -1; end if;
                    --raise notice 'passed caret chars 1: %, %', onechar, twochar;
                    if (two = '') then return 1; end if;
                    --raise notice 'passed caret chars 2: %, %', onechar, twochar;
                    if (onechar != '^') then return 1; end if;
                    --raise notice 'passed caret chars 3: %, %', onechar, twochar;
                    if (twochar != '^') then return -1; end if;
                    --raise notice 'passed caret chars 4: %, %', onechar, twochar;
                    one := substr(one, 2);
                    two := substr(two, 2);
                    continue;
                end if;

                if (not (one <> '' and two <> '')) then exit segment_loop; end if;

                str1 := one;
                str2 := two;
                if rpm.isdigit(str1) or rpm.isdigit(str2)
                then
                    str1 := ltrim(str1, digits);
                    str2 := ltrim(str2, digits);
                    isnum := true;
                else
                    str1 := ltrim(str1, alpha);
                    str2 := ltrim(str2, alpha);
                    isnum := false;
                end if;
                if str1 <> ''
                then segm1 := substr(one, 1, length(one) - length(str1));
                else segm1 := one;
                end if;

                if str2 <> ''
                then segm2 := substr(two, 1, length(two) - length(str2));
                else segm2 := two;
                end if;

                if isnum
                then
                    if segm1 = '' then return -1; end if;
                    if segm2 = '' then return 1; end if;

                    segm1 := ltrim(segm1, '0');
                    segm2 := ltrim(segm2, '0');

                    if segm1 = '' and segm2 <> ''
                    then
                        return -1;
                    end if;
                    if segm1 <> '' and segm2 = ''
                    then
                        return 1;
                    end if;
                    if length(segm1) < length(segm2) then return -1; end if;
                    if length(segm1) > length(segm2) then return 1; end if;
                end if;
                if segm1 < segm2 then return -1; end if;
                if segm1 > segm2 then return 1; end if;
               one := str1;
                two := str2;
            end;
        end loop segment_loop;
     
        if one = '' and two = '' then return 0; end if;
        if one = '' then return -1; end if;
        return 1;
    END ;
$$ language 'plpgsql';



   create or replace FUNCTION vercmp(
        e1 VARCHAR, v1 VARCHAR, r1 VARCHAR, 
        e2 VARCHAR, v2 VARCHAR, r2 VARCHAR)
    RETURNS INTEGER as $$
    declare
        rc INTEGER;
          ep1 INTEGER;
          ep2 INTEGER;
          BEGIN
            if e1 is null or e1 = '' then
              ep1 := 0;
            else
              ep1 := e1::integer;
            end if;
            if e2 is null or e2 = '' then
              ep2 := 0;
            else
              ep2 := e2::integer;
            end if;
            -- Epochs are non-null; compare them
            if ep1 < ep2 then return -1; end if;
            if ep1 > ep2 then return 1; end if;
            rc := rpm.rpmstrcmp(v1, v2);
            if rc != 0 then return rc; end if;
           return rpm.rpmstrcmp(r1, r2);
         END;
         $$ language 'plpgsql';

-- restore the original setting
update pg_settings set setting = overlay( setting placing '' from 1 for (length('rpm')+1) ) where name = 'search_path';

 07070100000DC2000081B400000000000000000000000167AE111400002103000000000000000000000000000000000000006000000000susemanager-schema/upgrade/susemanager-schema-4.1.0-to-susemanager-schema-4.1.1/300-rpm.pkb.sql   -- create schema rpm;

--update pg_setting
update pg_settings set setting = 'rpm,' || setting where name = 'search_path';

create or replace function isdigit(ch CHAR)
    RETURNS BOOLEAN as $$
    BEGIN
        if ascii(ch) between ascii('0') and ascii('9')
        then
            return TRUE;
        end if;
        return FALSE;
    END ;
$$ language 'plpgsql';

    
    create or replace FUNCTION isalpha(ch CHAR)
    RETURNS BOOLEAN as $$
    BEGIN
        if ascii(ch) between ascii('a') and ascii('z') or 
            ascii(ch) between ascii('A') and ascii('Z')
        then
            return TRUE;
        end if;
        return FALSE;
    END;
$$ language 'plpgsql';


    create or replace FUNCTION isalphanum(ch CHAR)
    RETURNS BOOLEAN as $$ 
    BEGIN
        if ascii(ch) between ascii('a') and ascii('z') or 
            ascii(ch) between ascii('A') and ascii('Z') or
            ascii(ch) between ascii('0') and ascii('9')
        then
            return TRUE;
        end if;
        return FALSE;
    END;
    $$ language 'plpgsql';


    create or replace FUNCTION rpmstrcmp (string1 IN VARCHAR, string2 IN VARCHAR)
    RETURNS INTEGER as $$
    declare
        str1 VARCHAR := string1;
        str2 VARCHAR := string2;
        digits VARCHAR(10) := '0123456789';
        lc_alpha VARCHAR(27) := 'abcdefghijklmnopqrstuvwxyz';
        uc_alpha VARCHAR(27) := 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
        alpha VARCHAR(54) := lc_alpha || uc_alpha;
        one VARCHAR;
        two VARCHAR;
        debupstreamv1 VARCHAR;
        debupstreamv2 VARCHAR;
        debrevisionv1 VARCHAR;
        debrevisionv2 VARCHAR;
        isnum BOOLEAN;
    BEGIN
        if str1 is NULL or str2 is NULL
        then
            RAISE EXCEPTION 'VALUE_ERROR.';
        end if;
      
        if str1 = str2
        then
            return 0;
        end if;
        debupstreamv1 := str1;
        debupstreamv2 := str2;
        debrevisionv1 := '';
        debrevisionv2 := '';
        if INSTR(str1, '-') <> 0
        then
            debupstreamv1 := SUBSTR(str1, 0, INSTR(str1, '-'));
        end if;
        if INSTR(str2, '-') <> 0
        then
            debupstreamv2 := SUBSTR(str2, 0, INSTR(str2, '-'));
        end if;
        if (debupstreamv1 <> debupstreamv2)
        then
            str1 := debupstreamv1;
            str2 := debupstreamv2;
        else
            if INSTR(str1, '-') <> 0 and INSTR(str2, '-') <> 0
            then
                debrevisionv1 := SUBSTR(str1, INSTR(str1, '-') + 1);
                debrevisionv2 := SUBSTR(str2, INSTR(str2, '-') + 1);
	    else
		return 0;
            end if;
            str1 := debrevisionv1;
            str2 := debrevisionv2;
        end if;
        one := str1;
        two := str2;

        <<segment_loop>>
        while one <> '' or two <> ''
        loop
            declare
                segm1 VARCHAR;
                segm2 VARCHAR;
                onechar CHAR(1);
                twochar CHAR(1);
            begin
                --raise notice 'Params: %, %',  one, two;
                -- Throw out all non-alphanum characters
                onechar := substr(one, 1, 1);
                twochar := substr(two, 1, 1);
                while one <> '' and not rpm.isalphanum(one) and onechar != '~' and onechar != '^'
                loop
                    one := substr(one, 2);
                end loop;
                while two <> '' and not rpm.isalphanum(two) and twochar != '~' and twochar != '^'
                loop
                    two := substr(two, 2);
                end loop;
                --raise notice 'new params: %, %', one, two;

                onechar := substr(one, 1, 1);
                twochar := substr(two, 1, 1);
                --raise notice 'new chars 1: %, %', onechar, twochar;
                /* handle the tilde separator, it sorts before everything else */
                if (onechar = '~' or twochar = '~')
                then
                    if (onechar != '~') then return 1; end if;
                    if (twochar != '~') then return -1; end if;
                    --raise notice 'passed tilde chars: %, %', onechar, twochar;
                    one := substr(one, 2);
                    two := substr(two, 2);
                    continue;
                end if;

                /*
                 * Handle caret separator. Concept is the same as tilde,
                 * except that if one of the strings ends (base version),
                 * the other is considered as higher version.
                 */
                onechar := substr(one, 1, 1);
                twochar := substr(two, 1, 1);
                --raise notice 'new chars 2: %, %', onechar, twochar;
                if (onechar = '^' or twochar = '^')
                then
                    if (one = '') then return -1; end if;
                    --raise notice 'passed caret chars 1: %, %', onechar, twochar;
                    if (two = '') then return 1; end if;
                    --raise notice 'passed caret chars 2: %, %', onechar, twochar;
                    if (onechar != '^') then return 1; end if;
                    --raise notice 'passed caret chars 3: %, %', onechar, twochar;
                    if (twochar != '^') then return -1; end if;
                    --raise notice 'passed caret chars 4: %, %', onechar, twochar;
                    one := substr(one, 2);
                    two := substr(two, 2);
                    continue;
                end if;

                if (not (one <> '' and two <> '')) then exit segment_loop; end if;

                str1 := one;
                str2 := two;
                if rpm.isdigit(str1) or rpm.isdigit(str2)
                then
                    str1 := ltrim(str1, digits);
                    str2 := ltrim(str2, digits);
                    isnum := true;
                else
                    str1 := ltrim(str1, alpha);
                    str2 := ltrim(str2, alpha);
                    isnum := false;
                end if;
                if str1 <> ''
                then segm1 := substr(one, 1, length(one) - length(str1));
                else segm1 := one;
                end if;

                if str2 <> ''
                then segm2 := substr(two, 1, length(two) - length(str2));
                else segm2 := two;
                end if;

                if isnum
                then
                    if segm1 = '' then return -1; end if;
                    if segm2 = '' then return 1; end if;

                    segm1 := ltrim(segm1, '0');
                    segm2 := ltrim(segm2, '0');

                    if segm1 = '' and segm2 <> ''
                    then
                        return -1;
                    end if;
                    if segm1 <> '' and segm2 = ''
                    then
                        return 1;
                    end if;
                    if length(segm1) < length(segm2) then return -1; end if;
                    if length(segm1) > length(segm2) then return 1; end if;
                end if;
                if segm1 < segm2 then return -1; end if;
                if segm1 > segm2 then return 1; end if;
               one := str1;
                two := str2;
            end;
        end loop segment_loop;
     
        if one = '' and two = '' then return 0; end if;
        if one = '' then return -1; end if;
        return 1;
    END ;
$$ language 'plpgsql';



   create or replace FUNCTION vercmp(
        e1 VARCHAR, v1 VARCHAR, r1 VARCHAR, 
        e2 VARCHAR, v2 VARCHAR, r2 VARCHAR)
    RETURNS INTEGER as $$
    declare
        rc INTEGER;
          ep1 INTEGER;
          ep2 INTEGER;
          BEGIN
            if e1 is null or e1 = '' then
              ep1 := 0;
            else
              ep1 := e1::integer;
            end if;
            if e2 is null or e2 = '' then
              ep2 := 0;
            else
              ep2 := e2::integer;
            end if;
            -- Epochs are non-null; compare them
            if ep1 < ep2 then return -1; end if;
            if ep1 > ep2 then return 1; end if;
            rc := rpm.rpmstrcmp(v1, v2);
            if rc != 0 then return rc; end if;
           return rpm.rpmstrcmp(r1, r2);
         END;
         $$ language 'plpgsql';

-- restore the original setting
update pg_settings set setting = overlay( setting placing '' from 1 for (length('rpm')+1) ) where name = 'search_path';

 07070100000DC3000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005000000000susemanager-schema/upgrade/susemanager-schema-4.1.1-to-susemanager-schema-4.1.2   07070100000DC4000081B400000000000000000000000167AE11140000212B000000000000000000000000000000000000006000000000susemanager-schema/upgrade/susemanager-schema-4.1.1-to-susemanager-schema-4.1.2/001-rpm.pkb.sql   -- create schema rpm;

--update pg_setting
update pg_settings set setting = 'rpm,' || setting where name = 'search_path';

create or replace function isdigit(ch CHAR)
    RETURNS BOOLEAN as $$
    BEGIN
        if ascii(ch) between ascii('0') and ascii('9')
        then
            return TRUE;
        end if;
        return FALSE;
    END ;
$$ language 'plpgsql';

    
    create or replace FUNCTION isalpha(ch CHAR)
    RETURNS BOOLEAN as $$
    BEGIN
        if ascii(ch) between ascii('a') and ascii('z') or 
            ascii(ch) between ascii('A') and ascii('Z')
        then
            return TRUE;
        end if;
        return FALSE;
    END;
$$ language 'plpgsql';


    create or replace FUNCTION isalphanum(ch CHAR)
    RETURNS BOOLEAN as $$ 
    BEGIN
        if ascii(ch) between ascii('a') and ascii('z') or 
            ascii(ch) between ascii('A') and ascii('Z') or
            ascii(ch) between ascii('0') and ascii('9')
        then
            return TRUE;
        end if;
        return FALSE;
    END;
    $$ language 'plpgsql';


    create or replace FUNCTION rpmstrcmp (string1 IN VARCHAR, string2 IN VARCHAR)
    RETURNS INTEGER as $$
    declare
        str1 VARCHAR := string1;
        str2 VARCHAR := string2;
        digits VARCHAR(10) := '0123456789';
        lc_alpha VARCHAR(27) := 'abcdefghijklmnopqrstuvwxyz';
        uc_alpha VARCHAR(27) := 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
        alpha VARCHAR(54) := lc_alpha || uc_alpha;
        one VARCHAR;
        two VARCHAR;
        debupstreamv1 VARCHAR;
        debupstreamv2 VARCHAR;
        debrevisionv1 VARCHAR;
        debrevisionv2 VARCHAR;
        isnum BOOLEAN;
    BEGIN
        if str1 is NULL or str2 is NULL
        then
            RAISE EXCEPTION 'VALUE_ERROR.';
        end if;
      
        if str1 = str2
        then
            return 0;
        end if;
        debupstreamv1 := str1;
        debupstreamv2 := str2;
        debrevisionv1 := '';
        debrevisionv2 := '';
        if POSITION('-' in str1) <> 0
        then
            debupstreamv1 := SUBSTR(str1, 0, POSITION('-' in str1));
        end if;
        if POSITION('-' in str2) <> 0
        then
            debupstreamv2 := SUBSTR(str2, 0, POSITION('-' in str2));
        end if;
        if (debupstreamv1 <> debupstreamv2)
        then
            str1 := debupstreamv1;
            str2 := debupstreamv2;
        else
            if POSITION('-' in str1) <> 0 AND POSITION('-' in str2) <> 0
            then
                debrevisionv1 := SUBSTR(str1, POSITION('-' in str1) + 1);
                debrevisionv2 := SUBSTR(str2, POSITION('-' in str2) + 1);
	    else
		return 0;
            end if;
            str1 := debrevisionv1;
            str2 := debrevisionv2;
        end if;
        one := str1;
        two := str2;

        <<segment_loop>>
        while one <> '' or two <> ''
        loop
            declare
                segm1 VARCHAR;
                segm2 VARCHAR;
                onechar CHAR(1);
                twochar CHAR(1);
            begin
                --raise notice 'Params: %, %',  one, two;
                -- Throw out all non-alphanum characters
                onechar := substr(one, 1, 1);
                twochar := substr(two, 1, 1);
                while one <> '' and not rpm.isalphanum(one) and onechar != '~' and onechar != '^'
                loop
                    one := substr(one, 2);
                end loop;
                while two <> '' and not rpm.isalphanum(two) and twochar != '~' and twochar != '^'
                loop
                    two := substr(two, 2);
                end loop;
                --raise notice 'new params: %, %', one, two;

                onechar := substr(one, 1, 1);
                twochar := substr(two, 1, 1);
                --raise notice 'new chars 1: %, %', onechar, twochar;
                /* handle the tilde separator, it sorts before everything else */
                if (onechar = '~' or twochar = '~')
                then
                    if (onechar != '~') then return 1; end if;
                    if (twochar != '~') then return -1; end if;
                    --raise notice 'passed tilde chars: %, %', onechar, twochar;
                    one := substr(one, 2);
                    two := substr(two, 2);
                    continue;
                end if;

                /*
                 * Handle caret separator. Concept is the same as tilde,
                 * except that if one of the strings ends (base version),
                 * the other is considered as higher version.
                 */
                onechar := substr(one, 1, 1);
                twochar := substr(two, 1, 1);
                --raise notice 'new chars 2: %, %', onechar, twochar;
                if (onechar = '^' or twochar = '^')
                then
                    if (one = '') then return -1; end if;
                    --raise notice 'passed caret chars 1: %, %', onechar, twochar;
                    if (two = '') then return 1; end if;
                    --raise notice 'passed caret chars 2: %, %', onechar, twochar;
                    if (onechar != '^') then return 1; end if;
                    --raise notice 'passed caret chars 3: %, %', onechar, twochar;
                    if (twochar != '^') then return -1; end if;
                    --raise notice 'passed caret chars 4: %, %', onechar, twochar;
                    one := substr(one, 2);
                    two := substr(two, 2);
                    continue;
                end if;

                if (not (one <> '' and two <> '')) then exit segment_loop; end if;

                str1 := one;
                str2 := two;
                if rpm.isdigit(str1) or rpm.isdigit(str2)
                then
                    str1 := ltrim(str1, digits);
                    str2 := ltrim(str2, digits);
                    isnum := true;
                else
                    str1 := ltrim(str1, alpha);
                    str2 := ltrim(str2, alpha);
                    isnum := false;
                end if;
                if str1 <> ''
                then segm1 := substr(one, 1, length(one) - length(str1));
                else segm1 := one;
                end if;

                if str2 <> ''
                then segm2 := substr(two, 1, length(two) - length(str2));
                else segm2 := two;
                end if;

                if isnum
                then
                    if segm1 = '' then return -1; end if;
                    if segm2 = '' then return 1; end if;

                    segm1 := ltrim(segm1, '0');
                    segm2 := ltrim(segm2, '0');

                    if segm1 = '' and segm2 <> ''
                    then
                        return -1;
                    end if;
                    if segm1 <> '' and segm2 = ''
                    then
                        return 1;
                    end if;
                    if length(segm1) < length(segm2) then return -1; end if;
                    if length(segm1) > length(segm2) then return 1; end if;
                end if;
                if segm1 < segm2 then return -1; end if;
                if segm1 > segm2 then return 1; end if;
               one := str1;
                two := str2;
            end;
        end loop segment_loop;
     
        if one = '' and two = '' then return 0; end if;
        if one = '' then return -1; end if;
        return 1;
    END ;
$$ language 'plpgsql';



   create or replace FUNCTION vercmp(
        e1 VARCHAR, v1 VARCHAR, r1 VARCHAR, 
        e2 VARCHAR, v2 VARCHAR, r2 VARCHAR)
    RETURNS INTEGER as $$
    declare
        rc INTEGER;
          ep1 INTEGER;
          ep2 INTEGER;
          BEGIN
            if e1 is null or e1 = '' then
              ep1 := 0;
            else
              ep1 := e1::integer;
            end if;
            if e2 is null or e2 = '' then
              ep2 := 0;
            else
              ep2 := e2::integer;
            end if;
            -- Epochs are non-null; compare them
            if ep1 < ep2 then return -1; end if;
            if ep1 > ep2 then return 1; end if;
            rc := rpm.rpmstrcmp(v1, v2);
            if rc != 0 then return rc; end if;
           return rpm.rpmstrcmp(r1, r2);
         END;
         $$ language 'plpgsql';

-- restore the original setting
update pg_settings set setting = overlay( setting placing '' from 1 for (length('rpm')+1) ) where name = 'search_path';

 07070100000DC5000081B400000000000000000000000167AE11140000026F000000000000000000000000000000000000006800000000susemanager-schema/upgrade/susemanager-schema-4.1.1-to-susemanager-schema-4.1.2/005-fix-none-vendor.sql   delete from rhnpackagerepodata where package_id in (select id from rhnpackage where vendor = 'Not defined');

ALTER TABLE rhnpackage ALTER COLUMN vendor DROP NOT NULL;

update rhnpackage set vendor = NULL where vendor = 'Not defined';

insert into rhnRepoRegenQueue (id, CHANNEL_LABEL, REASON, FORCE)
(select sequence_nextval('rhn_repo_regen_queue_id_seq'),
        C.label,
        'fix empty vendor',
        'Y'
   from rhnChannel C
   where C.id in (select distinct cp.channel_id
                    from rhnpackage p
	            join rhnchannelpackage cp on p.id = cp.package_id
	           where p.vendor is NULL));
 07070100000DC6000081B400000000000000000000000167AE1114000001C6000000000000000000000000000000000000007300000000susemanager-schema/upgrade/susemanager-schema-4.1.1-to-susemanager-schema-4.1.2/010_reactivation_keys_for_salt.sql    insert into rhnServerGroupTypeFeature (server_group_type_id, feature_id,
                                       created, modified)
select lookup_sg_type('salt_entitled'), lookup_feature_type('ftr_agent_smith'),
        current_timestamp,current_timestamp from dual
where not exists ( select 1 from rhnServerGroupTypeFeature
    where server_group_type_id = lookup_sg_type('salt_entitled')
      and feature_id = lookup_feature_type('ftr_agent_smith') );
  07070100000DC7000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005200000000susemanager-schema/upgrade/susemanager-schema-4.1.10-to-susemanager-schema-4.1.11 07070100000DC8000081B400000000000000000000000167AE1114000010E2000000000000000000000000000000000000007600000000susemanager-schema/upgrade/susemanager-schema-4.1.10-to-susemanager-schema-4.1.11/001-fix_suseChannelUserRoleView.sql -- Copyright (c) 2020 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--

DROP VIEW IF EXISTS suseChannelUserRoleView;

CREATE OR REPLACE VIEW
suseChannelUserRoleView
AS
  SELECT
    combination.channel_id,
    combination.user_id,
    combination.role,
    combination.user_org_id AS org_id,
    combination.parent_channel_id,
    CASE
      -- if channel is in an org trusted by the user's org, and if the channel itself is shared between the two, then user can subscribe it
      WHEN combination.role = 'subscribe' AND sharedChannels.is_shared_channel IS NOT NULL
        THEN NULL
      -- otherwise, if channel is not in user's org, then user can't manage it
      WHEN combination.role = 'manage' AND combination.channel_org_id IS NULL OR combination.channel_org_id <> combination.user_org_id
        THEN 'channel_not_owned'
      -- otherwise, if channel is in a family without permissions for the user's org, then user can't subscribe it
      WHEN combination.role = 'subscribe' AND channelPermissions.is_channel_available IS NULL
        THEN 'channel_not_available'
      -- otherwise, if channel is in a family without permissions for the user's org, then user can't subscribe it
      WHEN adminUsers.is_admin_user IS NOT NULL
        THEN NULL
      -- otherwise, if channel does not have the "not_globally_subscribable" bit set, user can subscribe it
      WHEN combination.role = 'subscribe' AND notGloballySubscribableChannels.is_not_globally_subscribable IS NULL
        THEN NULL
      -- otherwise, user might have an explicit permission on this channel
      WHEN explicitPermissions.has_explicit_permission IS NOT NULL
        THEN NULL
        -- otherwise, user can't either manage nor subscribe the channel
        ELSE 'direct_permission'
    END AS deny_reason
    FROM
      (SELECT
          c.id AS channel_id,
          c.org_id AS channel_org_id,
          c.parent_channel AS parent_channel_id,
          u.id AS user_id,
          u.org_id AS user_org_id,
          r.label AS role
          FROM rhnChannel c, web_contact u, rhnChannelPermissionRole r
      ) combination
     LEFT JOIN 
       (SELECT DISTINCT s.org_trust_id, s.id, 1 AS is_shared_channel
        FROM rhnSharedChannelView s) sharedChannels
     ON (sharedChannels.id = combination.channel_id AND sharedChannels.org_trust_id = combination.user_org_id)
     LEFT JOIN
       (SELECT DISTINCT cfp.org_id, cfm.channel_id, 1 AS is_channel_available
        FROM rhnChannelFamilyMembers cfm
          JOIN rhnOrgChannelFamilyPermissions cfp ON cfp.channel_family_id = cfm.channel_family_id) channelPermissions
     ON (combination.user_org_id = channelPermissions.org_id AND channelPermissions.channel_id = combination.channel_id)
     LEFT JOIN
       (SELECT DISTINCT m.user_id, 1 AS is_admin_user
        FROM rhnUserGroupMembers m
          JOIN rhnUserGroup g ON g.id = m.user_group_id
          JOIN rhnUserGroupType t ON t.id = g.group_type
        WHERE t.label = 'channel_admin' OR t.label = 'org_admin') adminUsers
     ON (adminUsers.user_id = combination.user_id)
     LEFT JOIN
       (SELECT DISTINCT ocs.channel_id, ocs.org_id, 1 AS is_not_globally_subscribable
        FROM rhnOrgChannelSettings ocs
          JOIN rhnOrgChannelSettingsType ocst ON ocst.id = ocs.setting_id
        WHERE ocst.label = 'not_globally_subscribable') notGloballySubscribableChannels
     ON (notGloballySubscribableChannels.channel_id = combination.channel_id AND notGloballySubscribableChannels.org_id = combination.user_org_id)
     LEFT JOIN
       (SELECT cpr.label, cp.channel_id, cp.user_id, 1 AS has_explicit_permission
        FROM rhnChannelPermission cp
          JOIN rhnChannelPermissionRole cpr ON cpr.id = cp.role_id) explicitPermissions
     ON (explicitPermissions.channel_id = combination.channel_id AND explicitPermissions.user_id = combination.user_id AND explicitPermissions.label = combination.role)
    -- ORDER BY channel_id, user_id, role, result
;
  07070100000DC9000081B400000000000000000000000167AE1114000007F3000000000000000000000000000000000000006900000000susemanager-schema/upgrade/susemanager-schema-4.1.10-to-susemanager-schema-4.1.11/002-entitle-server.sql  -- drop function in the public schema created there by accident
drop function if exists entitle_server;

-- setup search_path so that these functions are created in appropriate schema.
update pg_settings set setting = 'rhn_entitlements,' || setting where name = 'search_path';

    create or replace function entitle_server (
        server_id_in in numeric,
        type_label_in in varchar
    ) returns void
as $$
    declare
      sgid  numeric := 0;

    begin

      if rhn_entitlements.can_entitle_server(server_id_in,
                                             type_label_in) = 1 then
         sgid := rhn_entitlements.find_compatible_sg (server_id_in,
                                                      type_label_in);
         if sgid is not null then
            insert into rhnServerHistory ( id, server_id, summary, details )
            values ( nextval('rhn_event_id_seq'), server_id_in,
                     'added system entitlement ',
                      case type_label_in
                       when 'enterprise_entitled' then 'Management'
                       when 'bootstrap_entitled' then 'Bootstrap'
                       when 'salt_entitled' then 'Salt'
                       when 'foreign_entitled' then 'Foreign'
                       when 'virtualization_host' then 'Virtualization'
                       when 'container_build_host' then 'Container'
                       when 'osimage_build_host' then 'OS Image'
                       when 'monitoring_entitled' then 'Monitoring'
                      end  );

            perform rhn_server.insert_into_servergroup (server_id_in, sgid);

         else
            perform rhn_exception.raise_exception ('no_available_server_group');
         end if;
      else
         perform rhn_exception.raise_exception ('invalid_entitlement');
      end if;
   end$$
language plpgsql;

-- restore the original setting
update pg_settings set setting = overlay( setting placing '' from 1 for (length('rhn_entitlements')+1) ) where name = 'search_path';
 07070100000DCA000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005100000000susemanager-schema/upgrade/susemanager-schema-4.1.11-to-susemanager-schema-4.2.0  07070100000DCB000081B400000000000000000000000167AE111400000000000000000000000000000000000000000000005A00000000susemanager-schema/upgrade/susemanager-schema-4.1.11-to-susemanager-schema-4.2.0/.gitkeep 07070100000DCC000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005100000000susemanager-schema/upgrade/susemanager-schema-4.1.12-to-susemanager-schema-4.2.0  07070100000DCD000081B400000000000000000000000167AE111400000000000000000000000000000000000000000000005A00000000susemanager-schema/upgrade/susemanager-schema-4.1.12-to-susemanager-schema-4.2.0/.gitkeep 07070100000DCE000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005100000000susemanager-schema/upgrade/susemanager-schema-4.1.13-to-susemanager-schema-4.2.0  07070100000DCF000081B400000000000000000000000167AE111400000000000000000000000000000000000000000000005A00000000susemanager-schema/upgrade/susemanager-schema-4.1.13-to-susemanager-schema-4.2.0/.gitkeep 07070100000DD0000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005100000000susemanager-schema/upgrade/susemanager-schema-4.1.14-to-susemanager-schema-4.2.0  07070100000DD1000081B400000000000000000000000167AE111400000000000000000000000000000000000000000000005A00000000susemanager-schema/upgrade/susemanager-schema-4.1.14-to-susemanager-schema-4.2.0/.gitkeep 07070100000DD2000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005100000000susemanager-schema/upgrade/susemanager-schema-4.1.15-to-susemanager-schema-4.2.0  07070100000DD3000081B400000000000000000000000167AE111400000000000000000000000000000000000000000000005A00000000susemanager-schema/upgrade/susemanager-schema-4.1.15-to-susemanager-schema-4.2.0/.gitkeep 07070100000DD4000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005100000000susemanager-schema/upgrade/susemanager-schema-4.1.16-to-susemanager-schema-4.2.0  07070100000DD5000081B400000000000000000000000167AE111400000000000000000000000000000000000000000000005A00000000susemanager-schema/upgrade/susemanager-schema-4.1.16-to-susemanager-schema-4.2.0/.gitkeep 07070100000DD6000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005100000000susemanager-schema/upgrade/susemanager-schema-4.1.17-to-susemanager-schema-4.2.0  07070100000DD7000081B400000000000000000000000167AE111400000000000000000000000000000000000000000000005A00000000susemanager-schema/upgrade/susemanager-schema-4.1.17-to-susemanager-schema-4.2.0/.gitkeep 07070100000DD8000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005100000000susemanager-schema/upgrade/susemanager-schema-4.1.18-to-susemanager-schema-4.2.0  07070100000DD9000081B400000000000000000000000167AE111400000000000000000000000000000000000000000000005A00000000susemanager-schema/upgrade/susemanager-schema-4.1.18-to-susemanager-schema-4.2.0/.gitkeep 07070100000DDA000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005100000000susemanager-schema/upgrade/susemanager-schema-4.1.19-to-susemanager-schema-4.2.0  07070100000DDB000081B400000000000000000000000167AE111400000000000000000000000000000000000000000000005A00000000susemanager-schema/upgrade/susemanager-schema-4.1.19-to-susemanager-schema-4.2.0/.gitkeep 07070100000DDC000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005000000000susemanager-schema/upgrade/susemanager-schema-4.1.2-to-susemanager-schema-4.1.3   07070100000DDD000081B400000000000000000000000167AE11140000005F000000000000000000000000000000000000006E00000000susemanager-schema/upgrade/susemanager-schema-4.1.2-to-susemanager-schema-4.1.3/001-add-payg-to-rhnServer.sql ALTER TABLE rhnServer
    ADD COLUMN IF NOT EXISTS payg CHAR(1)
       DEFAULT ('N') NOT NULL;
 07070100000DDE000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005100000000susemanager-schema/upgrade/susemanager-schema-4.1.20-to-susemanager-schema-4.2.0  07070100000DDF000081B400000000000000000000000167AE111400000000000000000000000000000000000000000000005A00000000susemanager-schema/upgrade/susemanager-schema-4.1.20-to-susemanager-schema-4.2.0/.gitkeep 07070100000DE0000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005100000000susemanager-schema/upgrade/susemanager-schema-4.1.21-to-susemanager-schema-4.2.0  07070100000DE1000081B400000000000000000000000167AE111400000000000000000000000000000000000000000000005A00000000susemanager-schema/upgrade/susemanager-schema-4.1.21-to-susemanager-schema-4.2.0/.gitkeep 07070100000DE2000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005100000000susemanager-schema/upgrade/susemanager-schema-4.1.22-to-susemanager-schema-4.2.0  07070100000DE3000081B400000000000000000000000167AE111400000000000000000000000000000000000000000000005A00000000susemanager-schema/upgrade/susemanager-schema-4.1.22-to-susemanager-schema-4.2.0/.gitkeep 07070100000DE4000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005100000000susemanager-schema/upgrade/susemanager-schema-4.1.23-to-susemanager-schema-4.2.0  07070100000DE5000081B400000000000000000000000167AE111400000000000000000000000000000000000000000000005A00000000susemanager-schema/upgrade/susemanager-schema-4.1.23-to-susemanager-schema-4.2.0/.gitkeep 07070100000DE6000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005100000000susemanager-schema/upgrade/susemanager-schema-4.1.24-to-susemanager-schema-4.2.0  07070100000DE7000081B400000000000000000000000167AE111400000000000000000000000000000000000000000000005A00000000susemanager-schema/upgrade/susemanager-schema-4.1.24-to-susemanager-schema-4.2.0/.gitkeep 07070100000DE8000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005100000000susemanager-schema/upgrade/susemanager-schema-4.1.25-to-susemanager-schema-4.2.0  07070100000DE9000081B400000000000000000000000167AE111400000000000000000000000000000000000000000000005A00000000susemanager-schema/upgrade/susemanager-schema-4.1.25-to-susemanager-schema-4.2.0/.gitkeep 07070100000DEA000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005100000000susemanager-schema/upgrade/susemanager-schema-4.1.26-to-susemanager-schema-4.2.0  07070100000DEB000081B400000000000000000000000167AE111400000000000000000000000000000000000000000000005A00000000susemanager-schema/upgrade/susemanager-schema-4.1.26-to-susemanager-schema-4.2.0/.gitkeep 07070100000DEC000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005100000000susemanager-schema/upgrade/susemanager-schema-4.1.27-to-susemanager-schema-4.2.0  07070100000DED000081B400000000000000000000000167AE111400000000000000000000000000000000000000000000005A00000000susemanager-schema/upgrade/susemanager-schema-4.1.27-to-susemanager-schema-4.2.0/.gitkeep 07070100000DEE000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005100000000susemanager-schema/upgrade/susemanager-schema-4.1.28-to-susemanager-schema-4.2.0  07070100000DEF000081B400000000000000000000000167AE111400000000000000000000000000000000000000000000005A00000000susemanager-schema/upgrade/susemanager-schema-4.1.28-to-susemanager-schema-4.2.0/.gitkeep 07070100000DF0000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005100000000susemanager-schema/upgrade/susemanager-schema-4.1.29-to-susemanager-schema-4.2.0  07070100000DF1000081B400000000000000000000000167AE111400000000000000000000000000000000000000000000005A00000000susemanager-schema/upgrade/susemanager-schema-4.1.29-to-susemanager-schema-4.2.0/.gitkeep 07070100000DF2000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005000000000susemanager-schema/upgrade/susemanager-schema-4.1.3-to-susemanager-schema-4.1.4   07070100000DF3000081B400000000000000000000000167AE111400000024000000000000000000000000000000000000006B00000000susemanager-schema/upgrade/susemanager-schema-4.1.3-to-susemanager-schema-4.1.4/001-drop-suseDelServer.sql    DROP TABLE IF EXISTS suseDelServer;
07070100000DF4000081B400000000000000000000000167AE11140000008B000000000000000000000000000000000000006800000000susemanager-schema/upgrade/susemanager-schema-4.1.3-to-susemanager-schema-4.1.4/002-drop-suseServer.sql   DROP TABLE IF EXISTS suseServer;

DROP FUNCTION IF EXISTS suse_server_mod_trig_fun();

DROP FUNCTION IF EXISTS suse_server_del_trig_fun();
 07070100000DF5000081B400000000000000000000000167AE111400000089000000000000000000000000000000000000006A00000000susemanager-schema/upgrade/susemanager-schema-4.1.3-to-susemanager-schema-4.1.4/003-drop-suseOSTarget.sql DROP TABLE IF EXISTS suseOSTarget;

DROP SEQUENCE IF EXISTS suse_ostarget_id_seq;

DROP FUNCTION IF EXISTS suse_ostarget_mod_trig_fun();
   07070100000DF6000081B400000000000000000000000167AE111400000281000000000000000000000000000000000000006F00000000susemanager-schema/upgrade/susemanager-schema-4.1.3-to-susemanager-schema-4.1.4/004-drop-mgr-register-task.sql    DELETE FROM rhnTaskoRun
 WHERE template_id in (
        SELECT id
          FROM rhnTaskoTemplate
         WHERE bunch_id = (SELECT id FROM rhnTaskoBunch WHERE name='mgr-register-bunch')
           AND task_id = (SELECT id FROM rhnTaskoTask WHERE name='mgr-register')
);
DELETE FROM rhnTaskoTemplate
 WHERE bunch_id = (SELECT id FROM rhnTaskoBunch WHERE name='mgr-register-bunch')
   AND task_id = (SELECT id FROM rhnTaskoTask WHERE name='mgr-register');
DELETE FROM rhnTaskoTask WHERE name = 'mgr-register';
DELETE FROM rhnTaskoSchedule WHERE job_label = 'mgr-register-default';
DELETE FROM rhnTaskoBunch WHERE name = 'mgr-register-bunch';
   07070100000DF7000081B400000000000000000000000167AE111400000D24000000000000000000000000000000000000006A00000000susemanager-schema/upgrade/susemanager-schema-4.1.3-to-susemanager-schema-4.1.4/005-rhnServerOverview.sql drop view if exists rhnServerOverview;
create or replace view
rhnServerOverview
(
    org_id,
    server_id,
    server_name,
    modified,
    server_admins,
    group_count,
    channel_id,
    channel_labels,
    history_count,
    security_errata,
    bug_errata,
    enhancement_errata,
    outdated_packages,
	config_files_with_differences,
    unique_crash_count,
    total_crash_count,
    last_checkin_days_ago,
    last_checkin,
    pending_updates,
    os,
    release,
    server_arch_name,
    locked,
    proxy_id
)
as
select
    s.org_id, s.id, s.name, s.modified,
    ( select count(user_id) from rhnUserServerPerms ap
      where server_id = s.id ),
    ( select count(server_group_id) from rhnVisibleServerGroupMembers
      where server_id = s.id ),
    ( select C.id
        from rhnChannel C,
	     rhnServerChannel SC
       where SC.server_id = S.id
         and SC.channel_id = C.id
	 and C.parent_channel IS NULL),
    coalesce(( select C.name
        from rhnChannel C,
	     rhnServerChannel SC
       where SC.server_id = S.id
         and SC.channel_id = C.id
	 and C.parent_channel IS NULL), '(none)'),
    ( select count(id) from rhnServerHistory
      where
            server_id = S.id),
    ( select count(*) from rhnServerErrataTypeView setv
      where
            setv.server_id = s.id
        and setv.errata_type = 'Security Advisory'),
    ( select count(*) from rhnServerErrataTypeView setv
      where
            setv.server_id = s.id
        and setv.errata_type = 'Bug Fix Advisory'),
    ( select count(*) from rhnServerErrataTypeView setv
      where
            setv.server_id = s.id
        and setv.errata_type = 'Product Enhancement Advisory'),
    ( select count(distinct p.name_id) from rhnPackage p, rhnServerNeededCache snc
      where
             snc.server_id = S.id
	 and p.id = snc.package_id
	 ),
    ( select count(*)
        from rhnActionConfigRevision ACR
             INNER JOIN rhnActionConfigRevisionResult ACRR on ACR.id = ACRR.action_config_revision_id
       where ACR.server_id = S.id
         and ACR.action_id = (
              select MAX(rA.id)
                from rhnAction rA
                     INNER JOIN rhnServerAction rSA on rSA.action_id = rA.id
                     INNER JOIN rhnActionStatus rAS on rAS.id = rSA.status
                     INNER JOIN rhnActionType rAT on rAT.id = rA.action_type
               where rSA.server_id = S.id
                 and rAS.name in ('Completed', 'Failed')
                 and rAT.label = 'configfiles.diff'
         )
         and ACR.failure_id is null
         and ACRR.result is not null
        ),
    ( select unique_count from rhnServerCrashCount where server_id = S.id ),
    ( select total_count from rhnServerCrashCount where server_id = S.id ),
    ( select date_diff_in_days(checkin, current_timestamp) from rhnServerInfo where server_id = S.id ),
    ( select TO_CHAR(checkin, 'YYYY-MM-DD HH24:MI:SS') from rhnServerInfo where server_id = S.id ),
    ( select count(1)
        from rhnServerAction
       where server_id = S.id
         and status in (0, 1)),
    os,
    release,
    ( select name from rhnServerArch where id = s.server_arch_id),
    coalesce((select 1 from rhnServerLock SL WHERE SL.server_id = S.id), 0),
    ( select pxy.server_Id from rhnProxyInfo pxy where pxy.server_id = S.id)
from
    rhnServer S
;
07070100000DF8000081B400000000000000000000000167AE111400000BCB000000000000000000000000000000000000007300000000susemanager-schema/upgrade/susemanager-schema-4.1.3-to-susemanager-schema-4.1.4/010-schedule-recurring-actions.sql    INSERT INTO rhnTaskoBunch (id, name, description, org_bunch)
SELECT sequence_nextval('rhn_tasko_bunch_id_seq'), 'recurring-state-apply-bunch', 'Applies salt state to minion/group/org', null
WHERE NOT EXISTS ( SELECT 1 FROM rhnTaskoBunch WHERE name = 'recurring-state-apply-bunch');

INSERT INTO rhnTaskoTask (id, name, class)
SELECT sequence_nextval('rhn_tasko_task_id_seq'), 'recurring-state-apply', 'com.redhat.rhn.taskomatic.task.RecurringStateApplyJob'
WHERE NOT EXISTS ( SELECT 1 FROM rhnTaskoTask WHERE name = 'recurring-state-apply');

INSERT INTO rhnTaskoTemplate (id, bunch_id, task_id, ordering, start_if)
SELECT sequence_nextval('rhn_tasko_template_id_seq'), ( SELECT id FROM rhnTaskoBunch WHERE name = 'recurring-state-apply-bunch' ), ( SELECT id FROM rhnTaskoTask WHERE name = 'recurring-state-apply' ), 0, null
WHERE NOT EXISTS ( SELECT 1 FROM rhnTaskoTemplate WHERE bunch_id = ( SELECT id FROM rhnTaskoBunch WHERE name = 'recurring-state-apply-bunch' ) );

CREATE TABLE IF NOT EXISTS suseRecurringAction
(
  id                NUMERIC NOT NULL
                    CONSTRAINT suse_recurring_action_id_pk PRIMARY KEY,
  target_type       VARCHAR(32) NOT NULL,
  name              VARCHAR(256) NOT NULL,
  cron_expr         VARCHAR(32) NOT NULL,
  minion_id         NUMERIC
                    CONSTRAINT suse_rec_action_minion_fk
                      REFERENCES suseMinionInfo(server_id)
                      ON DELETE CASCADE,
  group_id          NUMERIC
                    CONSTRAINT suse_rec_action_group_fk
                      REFERENCES rhnServerGroup(id)
                      ON DELETE CASCADE,
  org_id            NUMERIC
                    CONSTRAINT suse_rec_action_org_fk
                      REFERENCES web_customer(id)
                      ON DELETE CASCADE,
  creator_id        NUMERIC
                    CONSTRAINT suse_rec_action_creator_fk
                      REFERENCES web_contact(id)
                      ON DELETE CASCADE,
  active            CHAR(1) DEFAULT ('Y') NOT NULL,
  test_mode         CHAR(1) DEFAULT ('Y') NOT NULL,
  created           TIMESTAMP WITH TIME ZONE
                      DEFAULT (current_timestamp)
                      NOT NULL,
  modified          TIMESTAMP WITH TIME ZONE
                      DEFAULT (current_timestamp)
                      NOT NULL
);

CREATE SEQUENCE IF NOT EXISTS suse_recurring_action_id_seq;

CREATE INDEX IF NOT EXISTS suse_rec_action_type
    ON suseRecurringAction(target_type);

CREATE UNIQUE INDEX IF NOT EXISTS suse_rec_action_name_minion_uq
    ON suseRecurringAction(name, minion_id)
    WHERE group_id IS NULL AND org_id IS NULL AND minion_id IS NOT NULL;

CREATE UNIQUE INDEX IF NOT EXISTS suse_rec_action_name_grp_uq
    ON suseRecurringAction(name, group_id)
    WHERE minion_id IS NULL AND org_id IS NULL AND group_id IS NOT NULL;

CREATE UNIQUE INDEX IF NOT EXISTS suse_rec_action_name_org_uq
    ON suseRecurringAction(name, org_id)
    WHERE minion_id IS NULL AND group_id IS NULL AND org_id IS NOT NULL;

 07070100000DF9000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005100000000susemanager-schema/upgrade/susemanager-schema-4.1.30-to-susemanager-schema-4.2.0  07070100000DFA000081B400000000000000000000000167AE111400000000000000000000000000000000000000000000005A00000000susemanager-schema/upgrade/susemanager-schema-4.1.30-to-susemanager-schema-4.2.0/.gitkeep 07070100000DFB000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005100000000susemanager-schema/upgrade/susemanager-schema-4.1.31-to-susemanager-schema-4.2.0  07070100000DFC000081B400000000000000000000000167AE111400000000000000000000000000000000000000000000005A00000000susemanager-schema/upgrade/susemanager-schema-4.1.31-to-susemanager-schema-4.2.0/.gitkeep 07070100000DFD000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005100000000susemanager-schema/upgrade/susemanager-schema-4.1.32-to-susemanager-schema-4.2.0  07070100000DFE000081B400000000000000000000000167AE111400000000000000000000000000000000000000000000005A00000000susemanager-schema/upgrade/susemanager-schema-4.1.32-to-susemanager-schema-4.2.0/.gitkeep 07070100000DFF000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005100000000susemanager-schema/upgrade/susemanager-schema-4.1.33-to-susemanager-schema-4.2.0  07070100000E00000081B400000000000000000000000167AE111400000000000000000000000000000000000000000000005A00000000susemanager-schema/upgrade/susemanager-schema-4.1.33-to-susemanager-schema-4.2.0/.gitkeep 07070100000E01000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005100000000susemanager-schema/upgrade/susemanager-schema-4.1.34-to-susemanager-schema-4.2.0  07070100000E02000081B400000000000000000000000167AE111400000000000000000000000000000000000000000000005A00000000susemanager-schema/upgrade/susemanager-schema-4.1.34-to-susemanager-schema-4.2.0/.gitkeep 07070100000E03000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005100000000susemanager-schema/upgrade/susemanager-schema-4.1.35-to-susemanager-schema-4.2.0  07070100000E04000081B400000000000000000000000167AE111400000000000000000000000000000000000000000000005A00000000susemanager-schema/upgrade/susemanager-schema-4.1.35-to-susemanager-schema-4.2.0/.gitkeep 07070100000E05000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005100000000susemanager-schema/upgrade/susemanager-schema-4.1.36-to-susemanager-schema-4.2.0  07070100000E06000081B400000000000000000000000167AE111400000000000000000000000000000000000000000000005A00000000susemanager-schema/upgrade/susemanager-schema-4.1.36-to-susemanager-schema-4.2.0/.gitkeep 07070100000E07000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005100000000susemanager-schema/upgrade/susemanager-schema-4.1.37-to-susemanager-schema-4.2.0  07070100000E08000081B400000000000000000000000167AE111400000000000000000000000000000000000000000000005A00000000susemanager-schema/upgrade/susemanager-schema-4.1.37-to-susemanager-schema-4.2.0/.gitkeep 07070100000E09000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005100000000susemanager-schema/upgrade/susemanager-schema-4.1.38-to-susemanager-schema-4.2.0  07070100000E0A000081B400000000000000000000000167AE111400000000000000000000000000000000000000000000005A00000000susemanager-schema/upgrade/susemanager-schema-4.1.38-to-susemanager-schema-4.2.0/.gitkeep 07070100000E0B000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005100000000susemanager-schema/upgrade/susemanager-schema-4.1.39-to-susemanager-schema-4.2.0  07070100000E0C000081B400000000000000000000000167AE111400000000000000000000000000000000000000000000005A00000000susemanager-schema/upgrade/susemanager-schema-4.1.39-to-susemanager-schema-4.2.0/.gitkeep 07070100000E0D000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005000000000susemanager-schema/upgrade/susemanager-schema-4.1.4-to-susemanager-schema-4.1.5   07070100000E0E000081B400000000000000000000000167AE11140000071A000000000000000000000000000000000000007C00000000susemanager-schema/upgrade/susemanager-schema-4.1.4-to-susemanager-schema-4.1.5/001-add_virt_pool_actions_rhnActionType.sql   -- Copyright (c) 2020 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

insert into rhnActionType (id, label, name, trigger_snapshot, unlocked_only) (
    select 509, 'virt.pool_refresh', 'Refresh a virtual storage pool', 'N', 'N'
    from dual
    where not exists (select 1 from rhnActionType where id = 509)
);

insert into rhnActionType (id, label, name, trigger_snapshot, unlocked_only) (
    select 510, 'virt.pool_start', 'Starts a virtual storage pool', 'N', 'N'
    from dual
    where not exists (select 1 from rhnActionType where id = 510)
);

insert into rhnActionType (id, label, name, trigger_snapshot, unlocked_only) (
    select 511, 'virt.pool_stop', 'Stops a virtual storage pool', 'N', 'N'
    from dual
    where not exists (select 1 from rhnActionType where id = 511)
);

insert into rhnActionType (id, label, name, trigger_snapshot, unlocked_only) (
    select 512, 'virt.pool_delete', 'Deletes a virtual storage pool', 'N', 'N'
    from dual
    where not exists (select 1 from rhnActionType where id = 512)
);

insert into rhnActionType (id, label, name, trigger_snapshot, unlocked_only) (
    select 513, 'virt.pool_create', 'Creates a virtual storage pool', 'N', 'N'
    from dual
    where not exists (select 1 from rhnActionType where id = 513)
);
  07070100000E0F000081B400000000000000000000000167AE111400000343000000000000000000000000000000000000007300000000susemanager-schema/upgrade/susemanager-schema-4.1.4-to-susemanager-schema-4.1.5/002-monitoring-ppc64le-aarch64.sql    insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type)
    select lookup_server_arch('ppc64le-redhat-linux'),
            lookup_sg_type('monitoring_entitled')
    from dual where not exists (
        select 1 from rhnServerServerGroupArchCompat where
        server_arch_id=lookup_server_arch('ppc64le-redhat-linux') and
        server_group_type=lookup_sg_type('monitoring_entitled')
    );

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type)
    select lookup_server_arch('aarch64-redhat-linux'),
            lookup_sg_type('monitoring_entitled')
    from dual where not exists (
        select 1 from rhnServerServerGroupArchCompat where
        server_arch_id=lookup_server_arch('aarch64-redhat-linux') and
        server_group_type=lookup_sg_type('monitoring_entitled')
    );
 07070100000E10000081B400000000000000000000000167AE111400000499000000000000000000000000000000000000007100000000susemanager-schema/upgrade/susemanager-schema-4.1.4-to-susemanager-schema-4.1.5/002-rhnActionVirtPoolRefresh.sql  -- Copyright (c) 2020 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

CREATE TABLE IF NOT EXISTS rhnActionVirtPoolRefresh
(
    action_id            NUMERIC NOT NULL
                             CONSTRAINT rhn_action_virt_pool_refresh_aid_fk
                                 REFERENCES rhnAction (id)
                                 ON DELETE CASCADE
                             CONSTRAINT rhn_action_virt_pool_refresh_aid_pk
                                 PRIMARY KEY,
    pool_name            VARCHAR(256)
)
;

CREATE UNIQUE INDEX IF NOT EXISTS rhn_action_virt_pool_refresh_aid_uq
    ON rhnActionVirtPoolRefresh (action_id);

   07070100000E11000081B400000000000000000000000167AE11140000048F000000000000000000000000000000000000006F00000000susemanager-schema/upgrade/susemanager-schema-4.1.4-to-susemanager-schema-4.1.5/003-rhnActionVirtPoolStart.sql    -- Copyright (c) 2020 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

CREATE TABLE IF NOT EXISTS rhnActionVirtPoolStart
(
    action_id            NUMERIC NOT NULL
                             CONSTRAINT rhn_action_virt_pool_start_aid_fk
                                 REFERENCES rhnAction (id)
                                 ON DELETE CASCADE
                             CONSTRAINT rhn_action_virt_pool_start_aid_pk
                                 PRIMARY KEY,
    pool_name            VARCHAR(256)
)
;

CREATE UNIQUE INDEX IF NOT EXISTS rhn_action_virt_pool_start_aid_uq
    ON rhnActionVirtPoolStart (action_id);

 07070100000E12000081B400000000000000000000000167AE11140000048A000000000000000000000000000000000000006E00000000susemanager-schema/upgrade/susemanager-schema-4.1.4-to-susemanager-schema-4.1.5/004-rhnActionVirtPoolStop.sql -- Copyright (c) 2020 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

CREATE TABLE IF NOT EXISTS rhnActionVirtPoolStop
(
    action_id            NUMERIC NOT NULL
                             CONSTRAINT rhn_action_virt_pool_stop_aid_fk
                                 REFERENCES rhnAction (id)
                                 ON DELETE CASCADE
                             CONSTRAINT rhn_action_virt_pool_stop_aid_pk
                                 PRIMARY KEY,
    pool_name            VARCHAR(256)
)
;

CREATE UNIQUE INDEX IF NOT EXISTS rhn_action_virt_pool_stop_aid_uq
    ON rhnActionVirtPoolStop (action_id);

  07070100000E13000081B400000000000000000000000167AE111400000561000000000000000000000000000000000000007000000000susemanager-schema/upgrade/susemanager-schema-4.1.4-to-susemanager-schema-4.1.5/005-rhnActionVirtPoolDelete.sql   -- Copyright (c) 2020 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

CREATE TABLE IF NOT EXISTS rhnActionVirtPoolDelete
(
    action_id            NUMERIC NOT NULL
                             CONSTRAINT rhn_action_virt_pool_delete_aid_fk
                                 REFERENCES rhnAction (id)
                                 ON DELETE CASCADE
                             CONSTRAINT rhn_action_virt_pool_delete_aid_pk
                                 PRIMARY KEY,
    pool_name            VARCHAR(256),
    purge                CHAR(1)
                            DEFAULT ('Y') NOT NULL
                            CONSTRAINT rhn_avpdelete_purge_ck
                                CHECK (purge in ('Y','N'))
)
;

CREATE UNIQUE INDEX IF NOT EXISTS rhn_action_virt_pool_delete_aid_uq
    ON rhnActionVirtPoolDelete (action_id);
   07070100000E14000081B400000000000000000000000167AE11140000069E000000000000000000000000000000000000007000000000susemanager-schema/upgrade/susemanager-schema-4.1.4-to-susemanager-schema-4.1.5/006-rhnActionVirtPoolCreate.sql   -- Copyright (c) 2020 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

CREATE TABLE IF NOT EXISTS rhnActionVirtPoolCreate
(
    action_id            NUMERIC NOT NULL
                             CONSTRAINT rhn_action_virt_pool_create_aid_fk
                                 REFERENCES rhnAction (id)
                                 ON DELETE CASCADE
                             CONSTRAINT rhn_action_virt_pool_create_aid_pk
                                 PRIMARY KEY,
    pool_name            VARCHAR(256),
    uuid                 VARCHAR(128),
    type                 VARCHAR(25),
    target               VARCHAR(256),
    autostart            CHAR(1)
                            DEFAULT ('Y') NOT NULL
                            CONSTRAINT rhn_avpcreate_autostart_ck
                                CHECK (autostart in ('Y','N')),
    permission_mode      VARCHAR(4),
    permission_owner     VARCHAR(10),
    permission_group     VARCHAR(10),
    permission_seclabel  VARCHAR(256),
    source               VARCHAR(2048)
)
;

CREATE UNIQUE INDEX IF NOT EXISTS rhn_action_virt_pool_create_aid_uq
    ON rhnActionVirtPoolCreate (action_id);

  07070100000E15000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005100000000susemanager-schema/upgrade/susemanager-schema-4.1.40-to-susemanager-schema-4.2.0  07070100000E16000081B400000000000000000000000167AE111400000000000000000000000000000000000000000000005A00000000susemanager-schema/upgrade/susemanager-schema-4.1.40-to-susemanager-schema-4.2.0/.gitkeep 07070100000E17000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005000000000susemanager-schema/upgrade/susemanager-schema-4.1.5-to-susemanager-schema-4.1.6   07070100000E18000081B400000000000000000000000167AE111400000043000000000000000000000000000000000000007600000000susemanager-schema/upgrade/susemanager-schema-4.1.5-to-susemanager-schema-4.1.6/001-notificationMessage-data-text.sql 
ALTER TABLE suseNotificationMessage ALTER COLUMN data TYPE text;

 07070100000E19000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005000000000susemanager-schema/upgrade/susemanager-schema-4.1.6-to-susemanager-schema-4.1.7   07070100000E1A000081B400000000000000000000000167AE111400000810000000000000000000000000000000000000007C00000000susemanager-schema/upgrade/susemanager-schema-4.1.6-to-susemanager-schema-4.1.7/001-add_virt_pool_actions_rhnActionType.sql   -- Copyright (c) 2020 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

insert into rhnActionType (id, label, name, trigger_snapshot, unlocked_only) (
    select 509, 'virt.pool_refresh', 'Refresh a virtual storage pool', 'N', 'N'
    from dual
    where not exists (select 1 from rhnActionType where id = 509)
);

insert into rhnActionType (id, label, name, trigger_snapshot, unlocked_only) (
    select 510, 'virt.pool_start', 'Starts a virtual storage pool', 'N', 'N'
    from dual
    where not exists (select 1 from rhnActionType where id = 510)
);

insert into rhnActionType (id, label, name, trigger_snapshot, unlocked_only) (
    select 511, 'virt.pool_stop', 'Stops a virtual storage pool', 'N', 'N'
    from dual
    where not exists (select 1 from rhnActionType where id = 511)
);

insert into rhnActionType (id, label, name, trigger_snapshot, unlocked_only) (
    select 512, 'virt.pool_delete', 'Deletes a virtual storage pool', 'N', 'N'
    from dual
    where not exists (select 1 from rhnActionType where id = 512)
);

insert into rhnActionType (id, label, name, trigger_snapshot, unlocked_only) (
    select 513, 'virt.pool_create', 'Creates a virtual storage pool', 'N', 'N'
    from dual
    where not exists (select 1 from rhnActionType where id = 513)
);

insert into rhnActionType (id, label, name, trigger_snapshot, unlocked_only) (
    select 514, 'virt.volume_delete', 'Deletes a virtual storage volume', 'N', 'N'
    from dual
    where not exists (select 1 from rhnActionType where id = 514)
);
07070100000E1B000081B400000000000000000000000167AE111400000499000000000000000000000000000000000000007100000000susemanager-schema/upgrade/susemanager-schema-4.1.6-to-susemanager-schema-4.1.7/002-rhnActionVirtPoolRefresh.sql  -- Copyright (c) 2020 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

CREATE TABLE IF NOT EXISTS rhnActionVirtPoolRefresh
(
    action_id            NUMERIC NOT NULL
                             CONSTRAINT rhn_action_virt_pool_refresh_aid_fk
                                 REFERENCES rhnAction (id)
                                 ON DELETE CASCADE
                             CONSTRAINT rhn_action_virt_pool_refresh_aid_pk
                                 PRIMARY KEY,
    pool_name            VARCHAR(256)
)
;

CREATE UNIQUE INDEX IF NOT EXISTS rhn_action_virt_pool_refresh_aid_uq
    ON rhnActionVirtPoolRefresh (action_id);

   07070100000E1C000081B400000000000000000000000167AE1114000004B2000000000000000000000000000000000000006F00000000susemanager-schema/upgrade/susemanager-schema-4.1.6-to-susemanager-schema-4.1.7/002-rhnActionVirtVolDelete.sql    -- Copyright (c) 2020 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

CREATE TABLE IF NOT EXISTS rhnActionVirtVolDelete
(
    action_id            NUMERIC NOT NULL
                             CONSTRAINT rhn_action_virt_vol_delete_aid_fk
                                 REFERENCES rhnAction (id)
                                 ON DELETE CASCADE
                             CONSTRAINT rhn_action_virt_vol_delete_aid_pk
                                 PRIMARY KEY,
    pool_name            VARCHAR(256),
    volume_name          VARCHAR(256)
);

CREATE UNIQUE INDEX IF NOT EXISTS rhn_action_virt_delete_aid_uq
    ON rhnActionVirtVolDelete (action_id);


  07070100000E1D000081B400000000000000000000000167AE11140000048F000000000000000000000000000000000000006F00000000susemanager-schema/upgrade/susemanager-schema-4.1.6-to-susemanager-schema-4.1.7/003-rhnActionVirtPoolStart.sql    -- Copyright (c) 2020 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

CREATE TABLE IF NOT EXISTS rhnActionVirtPoolStart
(
    action_id            NUMERIC NOT NULL
                             CONSTRAINT rhn_action_virt_pool_start_aid_fk
                                 REFERENCES rhnAction (id)
                                 ON DELETE CASCADE
                             CONSTRAINT rhn_action_virt_pool_start_aid_pk
                                 PRIMARY KEY,
    pool_name            VARCHAR(256)
)
;

CREATE UNIQUE INDEX IF NOT EXISTS rhn_action_virt_pool_start_aid_uq
    ON rhnActionVirtPoolStart (action_id);

 07070100000E1E000081B400000000000000000000000167AE11140000005F000000000000000000000000000000000000007800000000susemanager-schema/upgrade/susemanager-schema-4.1.6-to-susemanager-schema-4.1.7/003-rhnpackagecapability-name-index.sql   CREATE INDEX IF NOT EXISTS rhn_pkg_cap_name_idx
    ON rhnPackageCapability USING HASH (name);
 07070100000E1F000081B400000000000000000000000167AE11140000048A000000000000000000000000000000000000006E00000000susemanager-schema/upgrade/susemanager-schema-4.1.6-to-susemanager-schema-4.1.7/004-rhnActionVirtPoolStop.sql -- Copyright (c) 2020 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

CREATE TABLE IF NOT EXISTS rhnActionVirtPoolStop
(
    action_id            NUMERIC NOT NULL
                             CONSTRAINT rhn_action_virt_pool_stop_aid_fk
                                 REFERENCES rhnAction (id)
                                 ON DELETE CASCADE
                             CONSTRAINT rhn_action_virt_pool_stop_aid_pk
                                 PRIMARY KEY,
    pool_name            VARCHAR(256)
)
;

CREATE UNIQUE INDEX IF NOT EXISTS rhn_action_virt_pool_stop_aid_uq
    ON rhnActionVirtPoolStop (action_id);

  07070100000E20000081B400000000000000000000000167AE111400000561000000000000000000000000000000000000007000000000susemanager-schema/upgrade/susemanager-schema-4.1.6-to-susemanager-schema-4.1.7/005-rhnActionVirtPoolDelete.sql   -- Copyright (c) 2020 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

CREATE TABLE IF NOT EXISTS rhnActionVirtPoolDelete
(
    action_id            NUMERIC NOT NULL
                             CONSTRAINT rhn_action_virt_pool_delete_aid_fk
                                 REFERENCES rhnAction (id)
                                 ON DELETE CASCADE
                             CONSTRAINT rhn_action_virt_pool_delete_aid_pk
                                 PRIMARY KEY,
    pool_name            VARCHAR(256),
    purge                CHAR(1)
                            DEFAULT ('Y') NOT NULL
                            CONSTRAINT rhn_avpdelete_purge_ck
                                CHECK (purge in ('Y','N'))
)
;

CREATE UNIQUE INDEX IF NOT EXISTS rhn_action_virt_pool_delete_aid_uq
    ON rhnActionVirtPoolDelete (action_id);
   07070100000E21000081B400000000000000000000000167AE11140000069E000000000000000000000000000000000000007000000000susemanager-schema/upgrade/susemanager-schema-4.1.6-to-susemanager-schema-4.1.7/006-rhnActionVirtPoolCreate.sql   -- Copyright (c) 2020 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

CREATE TABLE IF NOT EXISTS rhnActionVirtPoolCreate
(
    action_id            NUMERIC NOT NULL
                             CONSTRAINT rhn_action_virt_pool_create_aid_fk
                                 REFERENCES rhnAction (id)
                                 ON DELETE CASCADE
                             CONSTRAINT rhn_action_virt_pool_create_aid_pk
                                 PRIMARY KEY,
    pool_name            VARCHAR(256),
    uuid                 VARCHAR(128),
    type                 VARCHAR(25),
    target               VARCHAR(256),
    autostart            CHAR(1)
                            DEFAULT ('Y') NOT NULL
                            CONSTRAINT rhn_avpcreate_autostart_ck
                                CHECK (autostart in ('Y','N')),
    permission_mode      VARCHAR(4),
    permission_owner     VARCHAR(10),
    permission_group     VARCHAR(10),
    permission_seclabel  VARCHAR(256),
    source               VARCHAR(2048)
)
;

CREATE UNIQUE INDEX IF NOT EXISTS rhn_action_virt_pool_create_aid_uq
    ON rhnActionVirtPoolCreate (action_id);

  07070100000E22000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005000000000susemanager-schema/upgrade/susemanager-schema-4.1.7-to-susemanager-schema-4.1.8   07070100000E23000081B400000000000000000000000167AE1114000004F0000000000000000000000000000000000000007100000000susemanager-schema/upgrade/susemanager-schema-4.1.7-to-susemanager-schema-4.1.8/001-package-provider-changes.sql  update rhnPackageProvider set name = 'SUSE LLC' where name = 'SUSE LINUX Products GmbH';

insert into rhnPackageKey (id, key_id, key_type_id, provider_id) (select sequence_nextval('rhn_pkey_id_seq'), '044adaee04881839', lookup_package_key_type('gpg'), lookup_package_provider('Novell Inc.') from dual where not exists (select 1 from rhnPackageKey where key_id = '044adaee04881839'));

insert into rhnPackageKey (id, key_id, key_type_id, provider_id) (select sequence_nextval('rhn_pkey_id_seq'), '57da9a6804a29db0', lookup_package_key_type('gpg'), lookup_package_provider('Novell Inc.') from dual where not exists (select 1 from rhnPackageKey where key_id = '57da9a6804a29db0'));

insert into rhnPackageKey (id, key_id, key_type_id, provider_id) (select sequence_nextval('rhn_pkey_id_seq'), '05b555b38483c65d', lookup_package_key_type('gpg'), lookup_package_provider('CentOS') from dual where not exists (select 1 from rhnPackageKey where key_id = '05b555b38483c65d'));

insert into rhnPackageKey (id, key_id, key_type_id, provider_id) (select sequence_nextval('rhn_pkey_id_seq'), '82562ea9ad986da3', lookup_package_key_type('gpg'), lookup_package_provider('Oracle Inc.') from dual where not exists (select 1 from rhnPackageKey where key_id = '82562ea9ad986da3'));
07070100000E24000081B400000000000000000000000167AE11140000019E000000000000000000000000000000000000007000000000susemanager-schema/upgrade/susemanager-schema-4.1.7-to-susemanager-schema-4.1.8/002-monitoring-enable-s390x.sql   insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type)
    select lookup_server_arch('s390x-redhat-linux'),
            lookup_sg_type('monitoring_entitled')
    from dual where not exists (
        select 1 from rhnServerServerGroupArchCompat where
        server_arch_id=lookup_server_arch('s390x-redhat-linux') and
        server_group_type=lookup_sg_type('monitoring_entitled')
    );

  07070100000E25000081B400000000000000000000000167AE1114000003CA000000000000000000000000000000000000007100000000susemanager-schema/upgrade/susemanager-schema-4.1.7-to-susemanager-schema-4.1.8/500-cluster-rhnusergrouptype.sql  insert into rhnUserGroupType (id, label, name) (
	select sequence_nextval('rhn_usergroup_type_seq'),
	'cluster_admin',
	'Cluster Administrator'
	from dual
	where not exists (select 1 from rhnUserGroupType where label = 'cluster_admin')
);

-- create cluster_admin role to existing orgs
insert into rhnUserGroup (id, name, description, max_members, group_type, org_id)
   (select sequence_nextval('rhn_user_group_id_seq'), 'Cluster Administrators',
          'Cluster Administrators for Org ' || wc.name, NULL,
          (select id from rhnUserGroupType where label = 'cluster_admin'), wc.id
   from web_customer wc,
        (select distinct ug.org_id
         from rhnUserGroup ug
         where ug.org_id not in (select org_id
                                 from rhnUserGroup xug
                                 join rhnUserGroupType xugt ON xugt.id = xug.group_type
                                 where xugt.label = 'cluster_admin')) X
  where X.org_id = wc.id);
  07070100000E26000081B400000000000000000000000167AE111400001513000000000000000000000000000000000000006D00000000susemanager-schema/upgrade/susemanager-schema-4.1.7-to-susemanager-schema-4.1.8/501-cluster-rhn_user.pkb.sql  -- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

-- create schema rhn_user;

-- setup search_path so that these functions are created in appropriate schema.
update pg_settings set setting = 'rhn_user,' || setting where name = 'search_path';

create or replace function
check_role(user_id_in in numeric, role_in in varchar)
    returns numeric as $$
    declare
    	throwaway numeric;
    begin
    	-- the idea: if we get past this query, the org has the setting, else catch the exception and return 0
	select 1 into throwaway
	  from rhnUserGroupType UGT,
	       rhnUserGroup UG,
	       rhnUserGroupMembers UGM
	 where UGM.user_id = user_id_in
	   and UGM.user_group_id = UG.id
	   and UG.group_type = UGT.id
	   and UGT.label = role_in;

        if not found then
            return 0;
        end if;

	return 1;
    end;
$$ language plpgsql;

create or replace
    function check_role_implied(user_id_in in numeric, role_in in varchar)
    returns numeric as $$
    declare
    	throwaway numeric;
    begin
    	-- if the user directly has the role, they win
    	if rhn_user.check_role(user_id_in, role_in) = 1
	then
	    return 1;
    	end if;

	-- config_admin and channel_admin are automatically implied for org admins
	if role_in = 'config_admin' and rhn_user.check_role(user_id_in, 'org_admin') = 1
	then
	    return 1;
	end if;

	if role_in = 'channel_admin' and rhn_user.check_role(user_id_in, 'org_admin') = 1
	then
	    return 1;
	end if;

	if role_in = 'image_admin' and rhn_user.check_role(user_id_in, 'org_admin') = 1
	then
	    return 1;
	end if;

	if role_in = 'cluster_admin' and rhn_user.check_role(user_id_in, 'org_admin') = 1
	then
	    return 1;
	end if;

	return 0;
    end;
$$ language plpgsql;

create or replace
    function get_org_id(user_id_in in numeric)
    returns numeric as $$
    declare
    	org_id_out numeric;
    begin
    	select org_id into org_id_out
	  from web_contact
	 where id = user_id_in;

	return org_id_out;
    end;
$$ language plpgsql;

create or replace
	function add_servergroup_perm(
		user_id_in in numeric,
		server_group_id_in in numeric
	) returns void as $$
        declare
            okay record;
	begin
		for okay in
			select	1
			from	rhnServerGroup sg,
					web_contact u
			where	u.id = user_id_in
				and sg.id = server_group_id_in
				and sg.org_id = u.org_id
                loop
		insert into rhnUserServerGroupPerms(user_id, server_group_id)
				values (user_id_in, server_group_id_in);
			perform rhn_cache.update_perms_for_user(user_id_in);
			return;
		end loop;
		perform rhn_exception.raise_exception('usgp_different_orgs');
	exception when UNIQUE_VIOLATION then
		perform rhn_exception.raise_exception('usgp_already_allowed');
	end;
$$ language plpgsql;

create or replace
	function add_to_usergroup(
		user_id_in in numeric,
		user_group_id_in in numeric
	) returns void as $$
        declare
            ugr record;
	begin
		insert into rhnUserGroupMembers(user_id, user_group_id)
			values (user_id_in, user_group_id_in);

		for ugr in
			select	user_group_id_in
			from	rhnUserGroup		ug,
					rhnUserGroupType	ugt
			where	ugt.label in ('org_admin') -- and server_group_admin ?
				and ugr.id = user_group_id_in
				and ugr.group_type = ugt.id
                 loop
			perform rhn_cache.update_perms_for_user(user_id_in);
			return;
		end loop;
	end;
$$ language plpgsql;

create or replace
	function remove_from_usergroup(
		user_id_in in numeric,
		user_group_id_in in numeric
	) returns void as $$
        declare
            ugr record;
	begin
		-- we only do anything if you're really in the group, because
		-- testing is significantly cheaper than rebuilding the user's
		-- cache for no reason.
		for ugr in
			select	label
			from	rhnUserGroupType	ugt,
					rhnUserGroupMembers	ugm,
					rhnUserGroup		ug
			where	1=1
				and ug.id = user_group_id_in
				and ugm.user_group_id = user_group_id_in
				and ug.group_type = ugt.id
				and ugm.user_id = user_id_in
                 loop
			delete from rhnUserGroupMembers
				where	user_id = user_id_in
					and user_group_id = user_group_id_in;
			if ugr.label in ('org_admin') then
				perform rhn_cache.update_perms_for_user(user_id_in);
			end if;
		end loop;
	end;
$$ language plpgsql;

create or replace
        function role_names (user_id_in in numeric)
	returns varchar
	as
$$
	declare
		rec record;
		tmp varchar(4000);
	begin
		for rec in (
			select type_name
			from rhnUserTypeBase
			where user_id = user_id_in
			order by type_id
			) loop
			if tmp is null then
				tmp := rec.type_name;
			else
				tmp := tmp || ', ' || rec.type_name;
			end if;
		end loop;
		return tmp;
	end;
$$ language plpgsql;

-- restore the original setting
update pg_settings set setting = overlay( setting placing '' from 1 for (length('rhn_user')+1) ) where name = 'search_path';
 07070100000E27000081B400000000000000000000000167AE111400002180000000000000000000000000000000000000006F00000000susemanager-schema/upgrade/susemanager-schema-4.1.7-to-susemanager-schema-4.1.8/502-cluster-create_new_org.sql    --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

create or replace function create_new_org
(
        name_in      in varchar,
        password_in  in varchar
        --org_id_out   out number
) returns numeric
as
$$
declare
        ug_type                 numeric;
        group_val               numeric;
        new_org_id              numeric;
        org_id_out		numeric;
begin

        select nextval('web_customer_id_seq') into new_org_id from dual;

        insert into web_customer (
                id, name
        ) values (
                new_org_id, name_in
        );

        select nextval('rhn_user_group_id_seq') into group_val from dual;

        select  id
        into    ug_type
        from    rhnUserGroupType
        where   label = 'org_admin';

        insert into rhnUserGroup (
                id, name,
                description,
                max_members, group_type, org_id
        ) values (
                group_val, 'Organization Administrators',
                'Organization Administrators for Org ' || name_in,
                NULL, ug_type, new_org_id
        );

        select nextval('rhn_user_group_id_seq') into group_val from dual;

        select  id
        into    ug_type
        from    rhnUserGroupType
        where   label = 'system_group_admin';

        insert into rhnUserGroup (
                id, name,
                description,
                max_members, group_type, org_id
        ) values (
                group_val, 'System Group Administrators',
                'System Group Administrators for Org ' || name_in,
                NULL, ug_type, new_org_id
        );


        select nextval('rhn_user_group_id_seq') into group_val from dual;

        select  id
        into    ug_type
        from    rhnUserGroupType
        where   label = 'activation_key_admin';

        insert into rhnUserGroup (
                id, name,
                description,
                max_members, group_type, org_id
        ) values (
                group_val, 'Activation Key Administrators',
                'Activation Key Administrators for Org ' || name_in,
                NULL, ug_type, new_org_id
        );

        select nextval('rhn_user_group_id_seq') into group_val from dual;

        select  id
        into    ug_type
        from    rhnUserGroupType
        where   label = 'channel_admin';

        insert into rhnUserGroup (
                id, name,
                description,
                max_members, group_type, org_id
        ) values (
                group_val, 'Channel Administrators',
                'Channel Administrators for Org ' || name_in,
                NULL, ug_type, new_org_id
        );

	if new_org_id = 1 then
            select nextval('rhn_user_group_id_seq') into group_val from dual;

            select  id
            into    ug_type
            from    rhnUserGroupType
            where   label = 'satellite_admin';

            insert into rhnUserGroup (
                    id, name,
                    description,
                    max_members, group_type, org_id
            ) values (
                    group_val, 'SUSE Manager Administrators',
                    'SUSE Manager Administrators for Org ' || name_in,
                    NULL, ug_type, new_org_id
            );
        end if;

        select nextval('rhn_user_group_id_seq') into group_val from dual;

        select  id
        into    ug_type
        from    rhnUserGroupType
        where   label = 'config_admin';

        insert into rhnUserGroup (
                id, name,
                description,
                max_members, group_type, org_id
        ) values (
                group_val, 'Configuration Administrators',
                'Configuration Administrators for Org ' || name_in,
                NULL, ug_type, new_org_id
        );

        select nextval('rhn_user_group_id_seq') into group_val from dual;

        select  id
        into    ug_type
        from    rhnUserGroupType
        where   label = 'image_admin';

        insert into rhnUserGroup (
                id, name,
                description,
                max_members, group_type, org_id
        ) values (
                group_val, 'Image Administrators',
                'Image Administrators for Org ' || name_in,
                NULL, ug_type, new_org_id
        );

        select nextval('rhn_user_group_id_seq') into group_val from dual;

        select  id
        into    ug_type
        from    rhnUserGroupType
        where   label = 'cluster_admin';

        insert into rhnUserGroup (
                id, name,
                description,
                max_members, group_type, org_id
        ) values (
                group_val, 'Cluster Administrators',
                'Cluster Administrators for Org ' || name_in,
                NULL, ug_type, new_org_id
        );

        -- there aren't any users yet, so we don't need to update
        -- rhnUserServerPerms

        insert into rhnServerGroup
                ( id, name, description, group_type, org_id )
                select nextval('rhn_server_group_id_seq'), sgt.name, sgt.name,
                        sgt.id, new_org_id
                from rhnServerGroupType sgt
                where sgt.label = 'bootstrap_entitled';

        insert into rhnServerGroup
                ( id, name, description, group_type, org_id )
                select nextval('rhn_server_group_id_seq'), sgt.name, sgt.name,
                        sgt.id, new_org_id
                from rhnServerGroupType sgt
                where sgt.label = 'enterprise_entitled';

        insert into rhnServerGroup
                ( id, name, description, group_type, org_id )
                select nextval('rhn_server_group_id_seq'), sgt.name, sgt.name,
                        sgt.id, new_org_id
                from rhnServerGroupType sgt
                where sgt.label = 'salt_entitled';

        insert into rhnServerGroup
                ( id, name, description, group_type, org_id )
                select nextval('rhn_server_group_id_seq'), sgt.name, sgt.name,
                        sgt.id, new_org_id
                from rhnServerGroupType sgt
                where sgt.label = 'foreign_entitled';

        insert into rhnServerGroup
                ( id, name, description, group_type, org_id )
                select nextval('rhn_server_group_id_seq'), sgt.name, sgt.name,
                        sgt.id, new_org_id
                from rhnServerGroupType sgt
                where sgt.label = 'virtualization_host';

        insert into rhnServerGroup
                ( id, name, description, group_type, org_id )
                select nextval('rhn_server_group_id_seq'), sgt.name, sgt.name,
                        sgt.id, new_org_id
                from rhnServerGroupType sgt
                where sgt.label = 'container_build_host';

        insert into rhnServerGroup
                ( id, name, description, group_type, org_id )
                select nextval('rhn_server_group_id_seq'), sgt.name, sgt.name,
                        sgt.id, new_org_id
                from rhnServerGroupType sgt
                where sgt.label = 'osimage_build_host';

        insert into rhnServerGroup
                ( id, name, description, group_type, org_id )
                select nextval('rhn_server_group_id_seq'), sgt.name, sgt.name,
                        sgt.id, new_org_id
                from rhnServerGroupType sgt
                where sgt.label = 'monitoring_entitled';

        insert into suseImageStore (id, label, uri, store_type_id, org_id)
        values (
            nextval('suse_imgstore_id_seq'),
            'SUSE Manager OS Image Store',
            new_org_id || '/',
            (SELECT id FROM suseImageStoreType WHERE label = 'os_image'),
            new_org_id
        );

        org_id_out := new_org_id;

	-- Returning the value of OUT parameter
        return org_id_out;

end;
$$
language plpgsql;
07070100000E28000081B400000000000000000000000167AE111400000767000000000000000000000000000000000000006500000000susemanager-schema/upgrade/susemanager-schema-4.1.7-to-susemanager-schema-4.1.8/503-suseClusters.sql  -- Copyright (c) 2020 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

CREATE TABLE IF NOT EXISTS suseClusters (
    id          NUMERIC NOT NULL
                    CONSTRAINT suse_clusters_id_pk PRIMARY KEY,
    org_id      NUMERIC NOT NULL
                    CONSTRAINT rhn_server_oid_fk
                    REFERENCES web_customer (id)
                    ON DELETE CASCADE,
    label       VARCHAR(256) NOT NULL,
    name        VARCHAR(256) NOT NULL,
    description VARCHAR(4096) DEFAULT '',
    provider    VARCHAR(50) NOT NULL,
    management_node_id  NUMERIC
                        CONSTRAINT suse_clusters_mgmt_node_fk
                        REFERENCES rhnServer (id)
                        ON DELETE SET NULL,
    group_id    NUMERIC NOT NULL
                    CONSTRAINT suse_clusters_group_fk
                    REFERENCES rhnServerGroup (id),
    created     TIMESTAMPTZ
                     DEFAULT (current_timestamp) NOT NULL,
    modified    TIMESTAMPTZ
                     DEFAULT (current_timestamp) NOT NULL
);

CREATE SEQUENCE IF NOT EXISTS suse_cluster_id_seq;

CREATE UNIQUE INDEX IF NOT EXISTS suse_cluster_name_uq
    ON suseClusters (name);

CREATE UNIQUE INDEX IF NOT EXISTS suse_cluster_label_uq
    ON suseClusters (label);

CREATE UNIQUE INDEX IF NOT EXISTS suse_cluster_group_uq
    ON suseClusters (group_id);
 07070100000E29000081B400000000000000000000000167AE1114000005A0000000000000000000000000000000000000007A00000000susemanager-schema/upgrade/susemanager-schema-4.1.7-to-susemanager-schema-4.1.8/504-rhnActionClusterGroupRefreshNodes.sql -- Copyright (c) 2020 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

CREATE TABLE IF NOT EXISTS rhnActionClusterGroupRefreshNodes (
    action_id           NUMERIC NOT NULL
                            CONSTRAINT rhn_actionclgrref_aid_fk
                            REFERENCES rhnAction (id)
                            ON DELETE CASCADE,
    cluster_id          NUMERIC
                            CONSTRAINT rhn_actionclgrref_cluster_fk
                            REFERENCES suseClusters (id)
                            ON DELETE CASCADE,
    created             TIMESTAMPTZ
                            DEFAULT (CURRENT_TIMESTAMP) NOT NULL
)
;

CREATE UNIQUE INDEX IF NOT EXISTS rhnactionclustergrn_aid_uq ON rhnActionClusterGroupRefreshNodes (action_id);

insert into rhnActionType values (515, 'cluster.group_refresh_nodes', 'Refresh cluster group nodes', 'N', 'N') on conflict do nothing;
07070100000E2A000081B400000000000000000000000167AE1114000005A1000000000000000000000000000000000000007100000000susemanager-schema/upgrade/susemanager-schema-4.1.7-to-susemanager-schema-4.1.8/505-rhnActionClusterJoinNode.sql  -- Copyright (c) 2020 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

CREATE TABLE IF NOT EXISTS rhnActionClusterJoinNode (
    action_id           NUMERIC NOT NULL
                            CONSTRAINT rhn_actioncljoin_aid_fk
                            REFERENCES rhnAction (id)
                            ON DELETE CASCADE,
    cluster_id          NUMERIC NOT NULL
                            CONSTRAINT rhn_actioncljoin_cluster_fk
                            REFERENCES suseClusters (id)
                            ON DELETE CASCADE,
    json_params         TEXT,
    created             TIMESTAMPTZ
                            DEFAULT (CURRENT_TIMESTAMP) NOT NULL
)
;

CREATE UNIQUE INDEX IF NOT EXISTS rhnactionclusterjn_aid_uq ON rhnActionClusterJoinNode (action_id);

insert into rhnActionType values (516, 'cluster.join_node', 'Join node to cluster', 'N', 'N') on conflict do nothing;
   07070100000E2B000081B400000000000000000000000167AE1114000005AF000000000000000000000000000000000000007300000000susemanager-schema/upgrade/susemanager-schema-4.1.7-to-susemanager-schema-4.1.8/506-rhnActionClusterRemoveNode.sql    -- Copyright (c) 2020 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

CREATE TABLE IF NOT EXISTS rhnActionClusterRemoveNode (
    action_id           NUMERIC NOT NULL
                            CONSTRAINT rhn_actionclrmnode_aid_fk
                            REFERENCES rhnAction (id)
                            ON DELETE CASCADE,
    cluster_id          NUMERIC NOT NULL
                            CONSTRAINT rhn_actionclrmnode_cluster_fk
                            REFERENCES suseClusters (id)
                            ON DELETE CASCADE,
    json_params         TEXT,
    created             TIMESTAMPTZ
                            DEFAULT (CURRENT_TIMESTAMP) NOT NULL
)
;

CREATE UNIQUE INDEX IF NOT EXISTS rhnactionclusterrn_aid_uq ON rhnActionClusterRemoveNode (action_id);

insert into rhnActionType values (517, 'cluster.remove_node', 'Remove node from cluster', 'N', 'N') on conflict do nothing;
 07070100000E2C000081B400000000000000000000000167AE1114000005AA000000000000000000000000000000000000007700000000susemanager-schema/upgrade/susemanager-schema-4.1.7-to-susemanager-schema-4.1.8/507-rhnActionClusterUpgradeCluster.sql    -- Copyright (c) 2020 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

CREATE TABLE IF NOT EXISTS rhnActionClusterUpgradeCluster (
    action_id           NUMERIC NOT NULL
                            CONSTRAINT rhn_actionclupgrade_aid_fk
                            REFERENCES rhnAction (id)
                            ON DELETE CASCADE,
    cluster_id          NUMERIC
                            CONSTRAINT rhn_actionclrmnode_cluster_fk
                            REFERENCES suseClusters (id)
                            ON DELETE CASCADE,
    json_params         TEXT,
    created             TIMESTAMPTZ
                            DEFAULT (CURRENT_TIMESTAMP) NOT NULL
)
;

CREATE UNIQUE INDEX IF NOT EXISTS rhnactionclusteruc_aid_uq ON rhnActionClusterUpgradeCluster (action_id);

insert into rhnActionType values (518, 'cluster.upgrade_cluster', 'Upgrade cluster', 'N', 'N') on conflict do nothing;
  07070100000E2D000081B400000000000000000000000167AE11140000049F000000000000000000000000000000000000007000000000susemanager-schema/upgrade/susemanager-schema-4.1.7-to-susemanager-schema-4.1.8/508-rhnActionClusterServers.sql   -- Copyright (c) 2020 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

CREATE TABLE IF NOT EXISTS rhnActionClusterServers (
    action_id           NUMERIC NOT NULL
                            CONSTRAINT rhn_actionclsrvs_aid_fk
                            REFERENCES rhnAction (id)
                            ON DELETE CASCADE,
    server_id           NUMERIC
                            CONSTRAINT rhn_actionclsrvs_sid_fk
                            REFERENCES rhnServer (id)
                            ON DELETE CASCADE
);

CREATE UNIQUE INDEX IF NOT EXISTS rhn_action_cluster_srvs_uq ON rhnActionClusterServers (action_id, server_id);
 07070100000E2E000081B400000000000000000000000167AE111400000171000000000000000000000000000000000000006D00000000susemanager-schema/upgrade/susemanager-schema-4.1.7-to-susemanager-schema-4.1.8/509-suseClusters-trigger.sql  
create or replace function suse_clusters_mod_trig_fun() returns trigger as
$$
begin
        new.modified := current_timestamp;
	return new;
end;
$$ language plpgsql;

drop trigger if exists suse_clusters_mod_trig on suseClusters;
create trigger
suse_clusters_mod_trig
before insert or update on suseClusters
for each row
execute procedure suse_clusters_mod_trig_fun();   07070100000E2F000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005000000000susemanager-schema/upgrade/susemanager-schema-4.1.8-to-susemanager-schema-4.1.9   07070100000E30000081B400000000000000000000000167AE1114000004DC000000000000000000000000000000000000007800000000susemanager-schema/upgrade/susemanager-schema-4.1.8-to-susemanager-schema-4.1.9/001-osimage-build-host-enable-archs.sql   insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type)
    select lookup_server_arch('ppc64le-redhat-linux'),
            lookup_sg_type('osimage_build_host')
    from dual where not exists (
        select 1 from rhnServerServerGroupArchCompat where
        server_arch_id=lookup_server_arch('ppc64le-redhat-linux') and
        server_group_type=lookup_sg_type('osimage_build_host')
    );

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type)
    select lookup_server_arch('aarch64-redhat-linux'),
            lookup_sg_type('osimage_build_host')
    from dual where not exists (
        select 1 from rhnServerServerGroupArchCompat where
        server_arch_id=lookup_server_arch('aarch64-redhat-linux') and
        server_group_type=lookup_sg_type('osimage_build_host')
    );

insert into rhnServerServerGroupArchCompat (server_arch_id, server_group_type)
    select lookup_server_arch('s390x-redhat-linux'),
            lookup_sg_type('osimage_build_host')
    from dual where not exists (
        select 1 from rhnServerServerGroupArchCompat where
        server_arch_id=lookup_server_arch('s390x-redhat-linux') and
        server_group_type=lookup_sg_type('osimage_build_host')
    );

07070100000E31000081B400000000000000000000000167AE1114000002B7000000000000000000000000000000000000008300000000susemanager-schema/upgrade/susemanager-schema-4.1.8-to-susemanager-schema-4.1.9/001-rhnActionVirtCreateDiskDetails-remove-type.sql    -- Copyright (c) 2020 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

ALTER TABLE IF EXISTS rhnActionVirtCreateDiskDetails
DROP COLUMN IF EXISTS type;
 07070100000E32000081B400000000000000000000000167AE1114000002C9000000000000000000000000000000000000008200000000susemanager-schema/upgrade/susemanager-schema-4.1.8-to-susemanager-schema-4.1.9/002-rhnActionVirtCreateDiskDetails-add-fields.sql -- Copyright (c) 2020 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

ALTER TABLE IF EXISTS rhnActionVirtCreateDiskDetails
ADD COLUMN IF NOT EXISTS format VARCHAR(10);

   07070100000E33000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005100000000susemanager-schema/upgrade/susemanager-schema-4.1.9-to-susemanager-schema-4.1.10  07070100000E34000081B400000000000000000000000167AE111400000087000000000000000000000000000000000000006800000000susemanager-schema/upgrade/susemanager-schema-4.1.9-to-susemanager-schema-4.1.10/001-new-comps-type.sql   INSERT INTO rhnCompsType
  SELECT 3, 'mediaproducts'
   WHERE NOT EXISTS ( SELECT 1 FROM rhnCompsType WHERE label = 'mediaproducts');

 07070100000E35000081B400000000000000000000000167AE111400000100000000000000000000000000000000000000007F00000000susemanager-schema/upgrade/susemanager-schema-4.1.9-to-susemanager-schema-4.1.10/001-rhnActionDup-add-alllow-vendor-change.sql    ALTER TABLE rhnActionDup DROP CONSTRAINT IF EXISTS rhn_actiondup_avc_ck;
ALTER TABLE rhnActionDup
  ADD COLUMN IF NOT EXISTS allow_vendor_change CHAR(1)
  DEFAULT ('N') NOT NULL
  CONSTRAINT rhn_actiondup_avc_ck
  CHECK (allow_vendor_change in ('Y','N'));
07070100000E36000081B400000000000000000000000167AE11140000233C000000000000000000000000000000000000006100000000susemanager-schema/upgrade/susemanager-schema-4.1.9-to-susemanager-schema-4.1.10/100-rpm.pkb.sql  -- oracle equivalent source sha1 539cb03eb177b7e87992701071488bbb32bb0624
-- create schema rpm;

--update pg_setting
update pg_settings set setting = 'rpm,' || setting where name = 'search_path';

create or replace function isdigit(ch CHAR)
    RETURNS BOOLEAN as $$
    BEGIN
        if ascii(ch) between ascii('0') and ascii('9')
        then
            return TRUE;
        end if;
        return FALSE;
    END ;
$$ language 'plpgsql';

    
    create or replace FUNCTION isalpha(ch CHAR)
    RETURNS BOOLEAN as $$
    BEGIN
        if ascii(ch) between ascii('a') and ascii('z') or 
            ascii(ch) between ascii('A') and ascii('Z')
        then
            return TRUE;
        end if;
        return FALSE;
    END;
$$ language 'plpgsql';


    create or replace FUNCTION isalphanum(ch CHAR)
    RETURNS BOOLEAN as $$ 
    BEGIN
        if ascii(ch) between ascii('a') and ascii('z') or 
            ascii(ch) between ascii('A') and ascii('Z') or
            ascii(ch) between ascii('0') and ascii('9')
        then
            return TRUE;
        end if;
        return FALSE;
    END;
    $$ language 'plpgsql';


    create or replace FUNCTION rpmstrcmp (string1 IN VARCHAR, string2 IN VARCHAR)
    RETURNS INTEGER as $$
    declare
        str1 VARCHAR := string1;
        str2 VARCHAR := string2;
        digits VARCHAR(10) := '0123456789';
        lc_alpha VARCHAR(27) := 'abcdefghijklmnopqrstuvwxyz';
        uc_alpha VARCHAR(27) := 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
        alpha VARCHAR(54) := lc_alpha || uc_alpha;
        one VARCHAR;
        two VARCHAR;
        debupstreamv1 VARCHAR;
        debupstreamv2 VARCHAR;
        debrevisionv1 VARCHAR;
        debrevisionv2 VARCHAR;
        post1 VARCHAR;
        post2 VARCHAR;
        isnum BOOLEAN;
    BEGIN
        if str1 is NULL or str2 is NULL
        then
            RAISE EXCEPTION 'VALUE_ERROR.';
        end if;
      
        if str1 = str2
        then
            return 0;
        end if;
        if POSITION('+' in str1) <> 0 AND POSITION('+' in str2) <> 0
        then
            post1 := SUBSTR(str1, POSITION('+' in str1));
            post2 := SUBSTR(str2, POSITION('+' in str2));

            if post1 = post2
            then
                str1 := SUBSTR(str1, 0, POSITION('+' in str1));
                str2 := SUBSTR(str2, 0, POSITION('+' in str2));
            end if;
        end if;
        debupstreamv1 := str1;
        debupstreamv2 := str2;
        debrevisionv1 := '';
        debrevisionv2 := '';
        if POSITION('-' in str1) <> 0
        then
            debupstreamv1 := SUBSTR(str1, 0, POSITION('-' in str1));
        end if;
        if POSITION('-' in str2) <> 0
        then
            debupstreamv2 := SUBSTR(str2, 0, POSITION('-' in str2));
        end if;
        if (debupstreamv1 <> debupstreamv2)
        then
            str1 := debupstreamv1;
            str2 := debupstreamv2;
        else
            if POSITION('-' in str1) <> 0 AND POSITION('-' in str2) <> 0
            then
                debrevisionv1 := SUBSTR(str1, POSITION('-' in str1) + 1);
                debrevisionv2 := SUBSTR(str2, POSITION('-' in str2) + 1);
	    else
		return 0;
            end if;
            str1 := debrevisionv1;
            str2 := debrevisionv2;
        end if;
        one := str1;
        two := str2;

        <<segment_loop>>
        while one <> '' or two <> ''
        loop
            declare
                segm1 VARCHAR;
                segm2 VARCHAR;
                onechar CHAR(1);
                twochar CHAR(1);
            begin
                --raise notice 'Params: %, %',  one, two;
                -- Throw out all non-alphanum characters
                onechar := substr(one, 1, 1);
                twochar := substr(two, 1, 1);
                while one <> '' and not rpm.isalphanum(one) and onechar != '~' and onechar != '^'
                loop
                    one := substr(one, 2);
                end loop;
                while two <> '' and not rpm.isalphanum(two) and twochar != '~' and twochar != '^'
                loop
                    two := substr(two, 2);
                end loop;
                --raise notice 'new params: %, %', one, two;

                onechar := substr(one, 1, 1);
                twochar := substr(two, 1, 1);
                --raise notice 'new chars 1: %, %', onechar, twochar;
                /* handle the tilde separator, it sorts before everything else */
                if (onechar = '~' or twochar = '~')
                then
                    if (onechar != '~') then return 1; end if;
                    if (twochar != '~') then return -1; end if;
                    --raise notice 'passed tilde chars: %, %', onechar, twochar;
                    one := substr(one, 2);
                    two := substr(two, 2);
                    continue;
                end if;

                /*
                 * Handle caret separator. Concept is the same as tilde,
                 * except that if one of the strings ends (base version),
                 * the other is considered as higher version.
                 */
                onechar := substr(one, 1, 1);
                twochar := substr(two, 1, 1);
                --raise notice 'new chars 2: %, %', onechar, twochar;
                if (onechar = '^' or twochar = '^')
                then
                    if (one = '') then return -1; end if;
                    --raise notice 'passed caret chars 1: %, %', onechar, twochar;
                    if (two = '') then return 1; end if;
                    --raise notice 'passed caret chars 2: %, %', onechar, twochar;
                    if (onechar != '^') then return 1; end if;
                    --raise notice 'passed caret chars 3: %, %', onechar, twochar;
                    if (twochar != '^') then return -1; end if;
                    --raise notice 'passed caret chars 4: %, %', onechar, twochar;
                    one := substr(one, 2);
                    two := substr(two, 2);
                    continue;
                end if;

                if (not (one <> '' and two <> '')) then exit segment_loop; end if;

                str1 := one;
                str2 := two;
                if rpm.isdigit(str1) or rpm.isdigit(str2)
                then
                    str1 := ltrim(str1, digits);
                    str2 := ltrim(str2, digits);
                    isnum := true;
                else
                    str1 := ltrim(str1, alpha);
                    str2 := ltrim(str2, alpha);
                    isnum := false;
                end if;
                if str1 <> ''
                then segm1 := substr(one, 1, length(one) - length(str1));
                else segm1 := one;
                end if;

                if str2 <> ''
                then segm2 := substr(two, 1, length(two) - length(str2));
                else segm2 := two;
                end if;

                if isnum
                then
                    if segm1 = '' then return -1; end if;
                    if segm2 = '' then return 1; end if;

                    segm1 := ltrim(segm1, '0');
                    segm2 := ltrim(segm2, '0');

                    if segm1 = '' and segm2 <> ''
                    then
                        return -1;
                    end if;
                    if segm1 <> '' and segm2 = ''
                    then
                        return 1;
                    end if;
                    if length(segm1) < length(segm2) then return -1; end if;
                    if length(segm1) > length(segm2) then return 1; end if;
                end if;
                if segm1 < segm2 then return -1; end if;
                if segm1 > segm2 then return 1; end if;
               one := str1;
                two := str2;
            end;
        end loop segment_loop;
     
        if one = '' and two = '' then return 0; end if;
        if one = '' then return -1; end if;
        return 1;
    END ;
$$ language 'plpgsql';



   create or replace FUNCTION vercmp(
        e1 VARCHAR, v1 VARCHAR, r1 VARCHAR, 
        e2 VARCHAR, v2 VARCHAR, r2 VARCHAR)
    RETURNS INTEGER as $$
    declare
        rc INTEGER;
          ep1 INTEGER;
          ep2 INTEGER;
          BEGIN
            if e1 is null or e1 = '' then
              ep1 := 0;
            else
              ep1 := e1::integer;
            end if;
            if e2 is null or e2 = '' then
              ep2 := 0;
            else
              ep2 := e2::integer;
            end if;
            -- Epochs are non-null; compare them
            if ep1 < ep2 then return -1; end if;
            if ep1 > ep2 then return 1; end if;
            rc := rpm.rpmstrcmp(v1, v2);
            if rc != 0 then return rc; end if;
           return rpm.rpmstrcmp(r1, r2);
         END;
         $$ language 'plpgsql';

-- restore the original setting
update pg_settings set setting = overlay( setting placing '' from 1 for (length('rpm')+1) ) where name = 'search_path';

07070100000E37000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005000000000susemanager-schema/upgrade/susemanager-schema-4.2.0-to-susemanager-schema-4.2.1   07070100000E38000081B400000000000000000000000167AE111400000000000000000000000000000000000000000000005900000000susemanager-schema/upgrade/susemanager-schema-4.2.0-to-susemanager-schema-4.2.1/.gitkeep  07070100000E39000081B400000000000000000000000167AE111400000359000000000000000000000000000000000000007F00000000susemanager-schema/upgrade/susemanager-schema-4.2.0-to-susemanager-schema-4.2.1/001-add_virt_network_actions_rhnActionType.sql    -- Copyright (c) 2020 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

insert into rhnActionType (id, label, name, trigger_snapshot, unlocked_only) (
    select 519, 'virt.network_state', 'Change a virtual network state', 'N', 'N'
    from dual
    where not exists (select 1 from rhnActionType where id = 519)
);
   07070100000E3A000081B400000000000000000000000167AE1114000004E5000000000000000000000000000000000000007800000000susemanager-schema/upgrade/susemanager-schema-4.2.0-to-susemanager-schema-4.2.1/002-rhnActionVirtNetworkStateChange.sql   -- Copyright (c) 2020 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

CREATE TABLE IF NOT EXISTS rhnActionVirtNetworkStateChange
(
    action_id            NUMERIC NOT NULL
                             CONSTRAINT rhn_action_virt_network_state_change_aid_fk
                                 REFERENCES rhnAction (id)
                                 ON DELETE CASCADE
                             CONSTRAINT rhn_action_virt_network_state_change_aid_pk
                                 PRIMARY KEY,
    network_name         VARCHAR(256),
    state                VARCHAR(10)
)
;

CREATE UNIQUE INDEX IF NOT EXISTS rhn_action_virt_network_state_change_aid_uq
    ON rhnActionVirtNetworkStateChange (action_id);

   07070100000E3B000081B400000000000000000000000167AE11140000089A000000000000000000000000000000000000008700000000susemanager-schema/upgrade/susemanager-schema-4.2.0-to-susemanager-schema-4.2.1/003-Add-new-states-and-types-for-virtual-instances.sql    INSERT INTO rhnVirtualInstanceState (id, name, label) SELECT sequence_nextval('rhn_vis_id_seq'), 'Powering On', 'powering_on' from dual WHERE NOT EXISTS (SELECT 1 FROM rhnVirtualInstanceState WHERE label = 'powering_on');

INSERT INTO rhnVirtualInstanceState (id, name, label) SELECT sequence_nextval('rhn_vis_id_seq'), 'Shutting Down', 'shutting_down' from dual WHERE NOT EXISTS (SELECT 1 FROM rhnVirtualInstanceState WHERE label = 'shutting_down');

INSERT INTO rhnVirtualInstanceState (id, name, label) SELECT sequence_nextval('rhn_vis_id_seq'), 'Powering Off', 'powering_off' from dual WHERE NOT EXISTS (SELECT 1 FROM rhnVirtualInstanceState WHERE label = 'powering_off');

INSERT INTO rhnVirtualInstanceState (id, name, label) SELECT sequence_nextval('rhn_vis_id_seq'), 'Pausing', 'pausing' from dual WHERE NOT EXISTS (SELECT 1 FROM rhnVirtualInstanceState WHERE label = 'pausing');

INSERT INTO rhnVirtualInstanceState (id, name, label) SELECT sequence_nextval('rhn_vis_id_seq'), 'Suspending', 'suspending' from dual WHERE NOT EXISTS (SELECT 1 FROM rhnVirtualInstanceState WHERE label = 'suspending');

INSERT INTO rhnVirtualInstanceState (id, name, label) SELECT sequence_nextval('rhn_vis_id_seq'), 'Suspended', 'suspended' from dual WHERE NOT EXISTS (SELECT 1 FROM rhnVirtualInstanceState WHERE label = 'suspended');

INSERT INTO rhnVirtualInstanceState (id, name, label) SELECT sequence_nextval('rhn_vis_id_seq'), 'Resuming', 'resuming' from dual WHERE NOT EXISTS (SELECT 1 FROM rhnVirtualInstanceState WHERE label = 'resuming');

INSERT INTO rhnVirtualInstanceState (id, name, label) SELECT sequence_nextval('rhn_vis_id_seq'), 'Resetting', 'resetting' from dual WHERE NOT EXISTS (SELECT 1 FROM rhnVirtualInstanceState WHERE label = 'resetting');

INSERT INTO rhnVirtualInstanceState (id, name, label) SELECT sequence_nextval('rhn_vis_id_seq'), 'Migrating', 'migrating' from dual WHERE NOT EXISTS (SELECT 1 FROM rhnVirtualInstanceState WHERE label = 'migrating');

INSERT INTO rhnVirtualInstanceType (id, name, label)
SELECT sequence_nextval('rhn_vit_id_seq'), 'Nutanix AHV', 'nutanix'
WHERE NOT EXISTS ( SELECT 1 FROM rhnVirtualInstanceType WHERE label = 'nutanix' AND name = 'Nutanix AHV');
  07070100000E3C000081B400000000000000000000000167AE111400004F45000000000000000000000000000000000000007200000000susemanager-schema/upgrade/susemanager-schema-4.2.0-to-susemanager-schema-4.2.1/004-avoid-deadlock-bsc1173073.sql -- oracle equivalent source sha1 87bc50785a1b2a5e639cdc7371aa5c1b435adaa2
--
-- Copyright (c) 2008--2014 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--
--
--
--

-- create schema rhn_server;

--update pg_setting
update pg_settings set setting = 'rhn_server,' || setting where name = 'search_path';

    create or replace function system_service_level(
    	server_id_in in numeric,
	service_level_in in varchar
    ) returns numeric as $$
    declare
    ents cursor is
      select label from rhnServerEntitlementView
      where server_id = server_id_in;

    retval numeric := 0;

    begin
         for ent in ents loop
            retval := rhn_entitlements.entitlement_grants_service (ent.label, service_level_in);
            if retval = 1 then
               return retval;
            end if;
         end loop;

         return retval;

    end$$ language plpgsql;


    create or replace function can_change_base_channel(server_id_in IN NUMERIC)
    returns numeric
    as $$
    declare
    	throwaway numeric;
    begin
    	-- the idea: if we get past this query, the server is
	-- neither sat nor proxy, so base channel is changeable

	select 1 into throwaway
	  from rhnServer S
	 where S.id = server_id_in
	   and not exists (select 1 from rhnSatelliteInfo SI where SI.server_id = S.id)
	   and not exists (select 1 from rhnProxyInfo PI where PI.server_id = S.id);

        if not found then
	    return 0;
        end if;

	return 1;
    end$$ language plpgsql;

    create or replace function set_custom_value(
    	server_id_in in numeric,
	user_id_in in numeric,
	key_label_in in varchar,
	value_in in varchar
    ) returns void
    as $$
    declare
    	key_id_val numeric;
    begin
    	select CDK.id into strict key_id_val
	  from rhnCustomDataKey CDK,
	       rhnServer S
	 where S.id = server_id_in
	   and S.org_id = CDK.org_id
	   and CDK.label = key_label_in;

	begin
	    insert into rhnServerCustomDataValue (server_id, key_id, value, created_by, last_modified_by)
	    values (server_id_in, key_id_val, value_in, user_id_in, user_id_in);
	exception
	    when UNIQUE_VIOLATION
	    	then
		update rhnServerCustomDataValue
		   set value = value_in,
		       last_modified_by = user_id_in
		 where server_id = server_id_in
		   and key_id = key_id_val;
	end;

    end$$ language plpgsql;

    create or replace function bulk_set_custom_value(
    	key_label_in in varchar,
	value_in in varchar,
	set_label_in in varchar,
	set_uid_in in numeric
    )
    returns integer
    as $$
    declare
        i integer;
        server record;
    begin
        i := 0;
        for server in (
           SELECT user_id, label, element, element_two
	     FROM rhnSet
	    WHERE label = set_label_in
	      AND user_id = set_uid_in
	) loop
	    if rhn_server.system_service_level(server.element, 'management') = 1 then
	    	perform rhn_server.set_custom_value(server.element, set_uid_in, key_label_in, value_in);
            i := i + 1;
	    end if;
	end loop;
    return i;
    end$$ language plpgsql;

    create or replace function bulk_snapshot_tag(
    	org_id_in in numeric,
        tagname_in in varchar,
	set_label_in in varchar,
	set_uid_in in numeric
    ) returns void
    as $$
    declare
        server record;
    	snapshot_id numeric;
    begin
        for server in (
           SELECT user_id, label, element, element_two
	     FROM rhnSet
	    WHERE label = set_label_in
	      AND user_id = set_uid_in
	    ) loop
	    if rhn_server.system_service_level(server.element, 'management') = 1 then
	    	    select max(id) into snapshot_id
	    	    from rhnSnapshot
	    	    where server_id = server.element;

	    	    if snapshot_id is null then
		    	perform rhn_server.snapshot_server(server.element, 'tagging system:  ' || tagname_in);

			select max(id) into snapshot_id
			from rhnSnapshot
			where server_id = server.element;
		    end if;

		-- now have a snapshot_id to work with...
		begin
		    perform rhn_server.tag_snapshot(snapshot_id, org_id_in, tagname_in);
		exception
		    when UNIQUE_VIOLATION
		    	then
			-- do nothing, be forgiving...
			null;
		end;
	    end if;
	end loop;
    end$$ language plpgsql;

    create or replace function tag_delete(
    	server_id_in in numeric,
	tag_id_in in numeric
    ) returns void
    as $$
    declare
    	snapshots cursor is
		select	snapshot_id
		from	rhnSnapshotTag
		where	tag_id = tag_id_in;
	tag_id_tmp numeric;
    begin
    	select	id into tag_id_tmp
	from	rhnTag
	where	id = tag_id_in
	for update;

	delete
		from	rhnSnapshotTag
		where	server_id = server_id_in
			and tag_id = tag_id_in;
	for snapshot in snapshots loop
		return;
	end loop;
	delete
		from rhnTag
		where id = tag_id_in;
    end$$ language plpgsql;

    create or replace function tag_snapshot(
        snapshot_id_in in numeric,
	org_id_in in numeric,
	tagname_in in varchar
    ) returns void
    as $$
    begin
    	insert into rhnSnapshotTag (snapshot_id, server_id, tag_id)
	select snapshot_id_in, server_id, lookup_tag(org_id_in, tagname_in)
	from rhnSnapshot
	where id = snapshot_id_in;
    end$$ language plpgsql;

    create or replace function bulk_snapshot(
    	reason_in in varchar,
	set_label_in in varchar,
	set_uid_in in numeric
    ) returns void
    as $$
    declare
        server record;
    begin
        for server in (
           SELECT user_id, label, element, element_two
	     FROM rhnSet
	    WHERE label = set_label_in
	      AND user_id = set_uid_in
	    ) loop
	    if rhn_server.system_service_level(server.element, 'management') = 1 then
	    	perform rhn_server.snapshot_server(server.element, reason_in);
	    end if;
	end loop;
    end$$ language plpgsql;

    create or replace function snapshot_server(
    	server_id_in in numeric,
	reason_in in varchar
    ) returns void
    as $$
    declare
    	snapshot_id_v numeric;
	revisions cursor is
		select distinct
			cr.id
		from	rhnConfigRevision	cr,
			rhnConfigFileName	cfn,
			rhnConfigFile		cf,
			rhnConfigChannel	cc,
			rhnServerConfigChannel	scc
		where	1=1
			and scc.server_id = server_id_in
			and scc.config_channel_id = cc.id
			and cc.id = cf.config_channel_id
			and cf.id = cr.config_file_id
			and cr.id = cf.latest_config_revision_id
			and cf.config_file_name_id = cfn.id
			and cf.id = lookup_first_matching_cf(scc.server_id, cfn.path);
	locked integer;
    begin
    	select nextval('rhn_snapshot_id_seq') into snapshot_id_v;

	insert into rhnSnapshot (id, org_id, server_id, reason) (
		select	snapshot_id_v,
			s.org_id,
			server_id_in,
			reason_in
		from	rhnServer s
		where	s.id = server_id_in
	);
	insert into rhnSnapshotChannel (snapshot_id, channel_id) (
		select	snapshot_id_v, sc.channel_id
		from	rhnServerChannel sc
		where	sc.server_id = server_id_in
	);
	insert into rhnSnapshotServerGroup (snapshot_id, server_group_id) (
		select	snapshot_id_v, sgm.server_group_id
		from	rhnServerGroupMembers sgm
		where	sgm.server_id = server_id_in
	);
        locked := 0;
        <<iloop>>
        while true loop
            begin
                insert into rhnPackageNEVRA (id, name_id, evr_id, package_arch_id)
                select nextval('rhn_pkgnevra_id_seq'), sp.name_id, sp.evr_id, sp.package_arch_id
                from rhnServerPackage sp
                where sp.server_id = server_id_in
                        and not exists
                        (select 1
                                from rhnPackageNEVRA nevra
                                where nevra.name_id = sp.name_id
                                        and nevra.evr_id = sp.evr_id
                                        and (nevra.package_arch_id = sp.package_arch_id
                                            or (nevra.package_arch_id is null
                                                and sp.package_arch_id is null)));
                exit iloop;
            exception when unique_violation then
                if locked = 1 then
                    raise;
                else
                    lock table rhnPackageNEVRA in exclusive mode;
                    locked := 1;
                end if;
            end;
        end loop;
	insert into rhnSnapshotPackage (snapshot_id, nevra_id) (
                select distinct snapshot_id_v, nevra.id
                from    rhnServerPackage sp, rhnPackageNEVRA nevra
                where   sp.server_id = server_id_in
                        and nevra.name_id = sp.name_id
                        and nevra.evr_id = sp.evr_id
                        and (nevra.package_arch_id = sp.package_arch_id
                            or (nevra.package_arch_id is null
                                and sp.package_arch_id is null))
	);

	insert into rhnSnapshotConfigChannel ( snapshot_id, config_channel_id ) (
		select	snapshot_id_v, scc.config_channel_id
		from	rhnServerConfigChannel scc
		where	server_id = server_id_in
	);

	for revision in revisions loop
		insert into rhnSnapshotConfigRevision (
				snapshot_id, config_revision_id
			) values (
				snapshot_id_v, revision.id
			);
	end loop;
    end$$ language plpgsql;

    create or replace function remove_action(
    	server_id_in in numeric,
	action_id_in in numeric
    ) returns void
    as $$
    declare
    	-- this really wants "nulls last", but 8.1.7.3.0 sucks ass.
	-- instead, we make a local table that holds our
	-- list of ids with null prereqs.  There's surely a better way
	-- (an array instead of a table maybe?  who knows...)
	-- but I've got code to do this handy that I can look at ;)
    	chained_actions cursor is
                with recursive r(id, prerequisite) as (
			select	id, prerequisite
			from	rhnAction
			where id = action_id_in
		union all
			select	r1.id, r1.prerequisite
			from	rhnAction r1, r
			where r.id = r1.prerequisite
		)
		select * from r
		order by prerequisite desc;
	sessions cursor is
		select	s.id
		from	rhnKickstartSession s
		where	server_id_in in (s.old_server_id, s.new_server_id)
			and s.action_id = action_id_in
			and not exists (
				select	1
				from	rhnKickstartSessionState ss
				where	ss.id = s.state_id
					and ss.label in ('failed','complete')
			);
	chain_ends numeric[];
	i numeric;
	prereq numeric := 1;
    begin
	select	prerequisite
	into	prereq
	from	rhnAction
	where	id = action_id_in;

	if prereq is not null then
		perform rhn_exception.raise_exception('action_is_child');
	end if;

        chain_ends := '{}';
	i := 1;
	for action in chained_actions loop
		if action.prerequisite is null then
			chain_ends[i] := action.id;
			i := i + 1;
		else
			delete from rhnServerAction
				where server_id = server_id_in
				and action_id = action.id;
		end if;
	end loop;

	delete from rhnServerAction
		where server_id = server_id_in
		and action_id = any(chain_ends);

	for s in sessions loop
		update rhnKickstartSession
			set 	state_id = (
					select	id
					from	rhnKickstartSessionState
					where	label = 'failed'
				),
				action_id = null
			where	id = s.id;
		perform set_ks_session_history_message(s.id, 'failed', 'Kickstart cancelled due to action removal');
	end loop;
    end$$ language plpgsql;

    create or replace function check_user_access(server_id_in in numeric, user_id_in in numeric)
    returns numeric
    as $$
    declare
    	has_access numeric;
    begin
    	-- first check; if this returns no rows, then the server/user are in different orgs, and we bail
        select 1 into has_access
	  from rhnServer S,
	       web_contact wc
	 where wc.org_id = s.org_id
	   and s.id = server_id_in
	   and wc.id = user_id_in;

        if not found then
          return 0;
        end if;

	-- okay, so they're in the same org.  if we have an org admin, they get a free pass
    	if rhn_user.check_role(user_id_in, 'org_admin') = 1
	then
	    return 1;
	end if;

    	select 1 into has_access
	  from rhnServerGroupMembers SGM,
	       rhnUserServerGroupPerms USG
	 where SGM.server_group_id = USG.server_group_id
	   and SGM.server_id = server_id_in
	   and USG.user_id = user_id_in;

        if not found then
          return 0;
        end if;

	return 1;
    end$$ language plpgsql;

    create or replace function insert_into_servergroup (
		server_id_in in numeric,
		server_group_id_in in numeric
    ) returns void
    as $$
    declare
		group_type numeric;
	begin
		-- this will rowlock the servergroup we're trying to change;
		-- we probably need to lock the other one, but I think the chances
		-- of it being a real issue are very small for now...
		select	sg.group_type
		into	group_type
		from	rhnServerGroup sg
		where	sg.id = server_group_id_in
		for update of sg;

		insert into rhnServerGroupMembers(server_id, server_group_id)
		values (server_id_in, server_group_id_in);

		update rhnServerGroup
		set current_members = current_members + 1
		where id = server_group_id_in;

		if group_type is null then
			perform rhn_cache.update_perms_for_server_group(server_group_id_in);
		end if;

		return;
	end$$ language plpgsql;

	create or replace function insert_into_servergroup_maybe (
		server_id_in in numeric,
		server_group_id_in in numeric
	) returns numeric as $$
    declare
		retval numeric := 0;
		servergroups cursor is
			select	s.id	server_id,
					sg.id	server_group_id
			from	rhnServerGroup	sg,
					rhnServer		s
			where	s.id = server_id_in
				and sg.id = server_group_id_in
				and s.org_id = sg.org_id
				and not exists (
					select	1
					from	rhnServerGroupMembers sgm
					where	sgm.server_id = s.id
						and sgm.server_group_id = sg.id
				);
	begin
		for sgm in servergroups loop
			perform rhn_server.insert_into_servergroup(sgm.server_id, sgm.server_group_id);
			retval := retval + 1;
		end loop;
		return retval;
	end$$ language plpgsql;

	create or replace function insert_set_into_servergroup (
		server_group_id_in in numeric,
		user_id_in in numeric,
		set_label_in in varchar
	) returns void
        as $$
    declare
		servers cursor is
			select	st.element	id
			from	rhnSet		st
			where	st.user_id = user_id_in
				and st.label = set_label_in
				and exists (
					select	1
					from	rhnUserManagedServerGroups umsg
					where	umsg.server_group_id = server_group_id_in
						and umsg.user_id = user_id_in
					)
				and not exists (
					select	1
					from	rhnServerGroupMembers sgm
					where	sgm.server_id = st.element
						and sgm.server_group_id = server_group_id_in
				);
	begin
		for s in servers loop
			perform rhn_server.insert_into_servergroup(s.id, server_group_id_in);
		end loop;
	end$$ language plpgsql;

    create or replace function delete_from_servergroup (
    	server_id_in in numeric,
	server_group_id_in in numeric
    ) returns void
    as $$
    declare

		oid numeric;
		label varchar;
		group_type numeric;
	begin
		select	sg.group_type, sg.org_id
		into	group_type,	oid
		from	rhnServerGroupMembers	sgm,
			rhnServerGroup		sg
		where	sg.id = server_group_id_in
		and 	sg.id = sgm.server_group_id
		and 	sgm.server_id = server_id_in
		for update of sg;

		if not found then
			perform rhn_exception.raise_exception('server_not_in_group');
		end if;

		delete from rhnServerGroupMembers
		where server_group_id = server_group_id_in
		and	server_id = server_id_in;

		update rhnServerGroup
		set current_members = current_members - 1
		where id = server_group_id_in;

		-- do group_type is null first
		if group_type is null then
			perform rhn_cache.update_perms_for_server_group(server_group_id_in);
		end if;

	end$$ language plpgsql;

	create or replace function delete_set_from_servergroup (
		server_group_id_in in numeric,
		user_id_in in numeric,
		set_label_in in varchar
	) returns void
        as $$
        declare
		servergroups cursor is
			select	sgm.server_id, sgm.server_group_id
			from	rhnSet st,
					rhnServerGroupMembers sgm
			where	sgm.server_group_id = server_group_id_in
				and st.user_id = user_id_in
				and st.label = set_label_in
				and sgm.server_id = st.element
				and exists (
					select	1
					from	rhnUserManagedServerGroups usgp
					where	usgp.server_group_id = server_group_id_in
						and usgp.user_id = user_id_in
				);
	begin
		for sgm in servergroups loop
			perform rhn_server.delete_from_servergroup(sgm.server_id, server_group_id_in);
		end loop;
	end$$ language plpgsql;

	create or replace function clear_servergroup (
		server_group_id_in in numeric
	) returns void
        as $$
        declare
		servers cursor is
			select	sgm.server_id	id
			from	rhnServerGroupMembers sgm
			where	sgm.server_group_id = server_group_id_in;
	begin
		for s in servers loop
			perform rhn_server.delete_from_servergroup(s.id, server_group_id_in);
		end loop;
	end$$ language plpgsql;

	create or replace function delete_from_org_servergroups (
		server_id_in in numeric
	) returns void
        as $$
        declare
		servergroups cursor is
			select	sgm.server_group_id id
			from	rhnServerGroup sg,
					rhnServerGroupMembers sgm
			where	sgm.server_id = server_id_in
				and sgm.server_group_id = sg.id
				and sg.group_type is null;
	begin
		for sg in servergroups loop
			perform rhn_server.delete_from_servergroup(server_id_in, sg.id);
		end loop;
	end$$ language plpgsql;

	create or replace function get_ip_address (
		server_id_in in numeric
	) returns varchar as $$
        declare
		interfaces cursor is
			select	ni.name as name, na4.address as address
			from	rhnServerNetInterface ni,
			        rhnServerNetAddress4 na4
			where	server_id = server_id_in
		                and ni.id = na4.interface_id
				and na4.address != '127.0.0.1';
		addresses cursor is
			select	address ip_addr
			from	rhnServerNetInterface
      			left join rhnServerNetAddress4
      			on rhnServerNetInterface.id = rhnServerNetAddress4.interface_id
			where	server_id = server_id_in
				and address != '127.0.0.1'
				and is_primary = 'Y';
	begin
		for addr in addresses loop
			return addr.ip_addr;
		end loop;
		for iface in interfaces loop
			return iface.address;
		end loop;
		return NULL;
	end$$ language plpgsql;

    create or replace function update_needed_cache(
        server_id_in in numeric
	) returns void as $$
    begin
      delete from rhnServerNeededCache
        where server_id = server_id_in;
      insert into rhnServerNeededCache
             (server_id, errata_id, package_id, channel_id)
        (select distinct sp.server_id, x.errata_id, p.id, x.channel_id
           FROM (SELECT sp_sp.server_id, sp_sp.name_id,
		        sp_sp.package_arch_id, max(sp_pe.evr) AS max_evr
                   FROM rhnServerPackage sp_sp
                   join rhnPackageEvr sp_pe ON sp_pe.id = sp_sp.evr_id
                  GROUP BY sp_sp.server_id, sp_sp.name_id, sp_sp.package_arch_id) sp
           join rhnPackage p ON p.name_id = sp.name_id
           join rhnPackageEvr pe ON pe.id = p.evr_id AND sp.max_evr < pe.evr
           join rhnPackageUpgradeArchCompat puac
	            ON puac.package_arch_id = sp.package_arch_id
		    AND puac.package_upgrade_arch_id = p.package_arch_id
           join rhnServerChannel sc ON sc.server_id = sp.server_id
           join rhnChannelPackage cp ON cp.package_id = p.id
	            AND cp.channel_id = sc.channel_id
           left join (SELECT ep.errata_id, ce.channel_id, ep.package_id
                        FROM rhnChannelErrata ce
                        join rhnErrataPackage ep
			         ON ep.errata_id = ce.errata_id
			join rhnServerChannel sc_sc
			         ON sc_sc.channel_id = ce.channel_id
		       WHERE sc_sc.server_id = server_id_in) x
             ON x.channel_id = sc.channel_id AND x.package_id = cp.package_id
          where sp.server_id = server_id_in);
	end$$ language plpgsql;
-- restore the original setting
update pg_settings set setting = overlay( setting placing '' from 1 for (length('rhn_server')+1) ) where name = 'search_path';
   07070100000E3D000081B400000000000000000000000167AE1114000027B0000000000000000000000000000000000000007200000000susemanager-schema/upgrade/susemanager-schema-4.2.0-to-susemanager-schema-4.2.1/005-avoid-deadlock-bsc1173073.sql --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--
--
--
-- This deletes a server.  All codepaths which delete servers should hit this
-- or delete_server_bulk()

create or replace
function delete_server (
        server_id_in in numeric
) returns void
as
$$
declare
         servergroups cursor for
                select  server_id, server_group_id
                from    rhnServerGroupMembers sgm
                where   sgm.server_id = server_id_in;

         configchannels cursor for
                select  cc.id
                from    rhnConfigChannel cc,
                        rhnConfigChannelType cct,
                        rhnServerConfigChannel scc
                where   1=1
                        and scc.server_id = server_id_in
                        and scc.config_channel_id = cc.id
                        -- these config channel types are reserved
                        -- for use by a single server, so we don't
                        -- need to check for other servers subscribed
                        and cct.label in
                                ('local_override','server_import')
                        and cct.id = cc.confchan_type_id;

begin
        -- filelists
        delete from rhnFileList where id in (
	select	spfl.file_list_id
	  from	rhnServerPreserveFileList spfl
	 where	spfl.server_id = server_id_in
			and not exists (
				select	1
				from	rhnServerPreserveFileList
				where	file_list_id = spfl.file_list_id
					and server_id != server_id_in
				union all
				select	1
				from	rhnKickstartPreserveFileList
				where	file_list_id = spfl.file_list_id
			)
        );

	for configchannel in configchannels loop
		perform rhn_config.delete_channel(configchannel.id);
	end loop;

	for sgm in servergroups loop
		perform rhn_server.delete_from_servergroup(
			sgm.server_id, sgm.server_group_id);
	end loop;


        -- we're handling this instead of letting an "on delete
        -- set null" do it so that we don't run the risk
        -- of setting off the triggers and killing us with a
        -- mutating table

        -- this is merge of two single updates:
        --  update ... set old_server_id = null where old_server_id = server_id_in;
        --  update ... set new_server_id = null where new_server_id = server_id_in;
        -- so we scan rhnKickstartSession table only once
        update rhnKickstartSession
                set old_server_id = case when old_server_id = server_id_in then null else old_server_id end,
                    new_server_id = case when new_server_id = server_id_in then null else new_server_id end
                where old_server_id = server_id_in
                   or new_server_id = server_id_in;

        perform rhn_channel.clear_subscriptions(server_id_in, 1);

        -- A little complicated here, but the goal is to
        -- delete records from rhnVirtualInstace only if we don't
        -- care about them anymore.  We don't care about records
        -- in rhnVirtualInstance if we are deleting the host
        -- system and the virtual system is already null, or
        -- vice-versa.  We *do* care about them if either the
        -- host or virtual system is still registered because we
        -- still want them to show up in the UI.
    -- If there's a newer row in rhnVirtualInstance with the same
    -- uuid, this guest must have been re-registered, so we can clean
    -- this data up.

        delete from rhnVirtualInstance vi
              where (host_system_id = server_id_in and virtual_system_id is null)
                 or (virtual_system_id = server_id_in and host_system_id is null)
                 or (vi.virtual_system_id = server_id_in and vi.modified < (select max(vi2.modified)
                    from rhnVirtualInstance vi2 where vi2.uuid = vi.uuid));

        -- this is merge of two single updates:
        --  update ... set host_system_id = null where host_system_id = server_id_in;
        --  update ... set virtual_system_id = null where virtual_system_id = server_id_in;
        -- so we scan rhnVirtualInstance table only once
        update rhnVirtualInstance
           set host_system_id = case when host_system_id = server_id_in then null else host_system_id end,
               virtual_system_id = case when virtual_system_id = server_id_in then null else virtual_system_id end
         where host_system_id = server_id_in
            or virtual_system_id = server_id_in;

        -- this is merge of two single updates:
        --  update ... set old_host_system_id = null when old_host_system_id = server_id_in;
        --  update ... set new_host_system_id = null when new_host_system_id = server_id_in;
        -- so we scan rhnVirtualInstanceEventLog table only once
        update rhnVirtualInstanceEventLog
           set old_host_system_id = case when old_host_system_id = server_id_in then null else old_host_system_id end,
               new_host_system_id = case when new_host_system_id = server_id_in then null else new_host_system_id end
         where old_host_system_id = server_id_in
            or new_host_system_id = server_id_in;

        -- archive related actions, only if they have no other servers assigned
        update rhnAction set archived = 1 where id in (
            select action_id from rhnServerAction sa
            where not exists (
                select server_id from rhnServerAction
                where action_id = sa.action_id and server_id != server_id_in
            )
        );

        -- We're deleting everything with a foreign key to rhnServer
        -- here, now.  I'm hoping this will help aleviate our deadlock
        -- problem.

        delete from rhnActionApplyStatesResult where server_id = server_id_in;
        delete from rhnActionConfigChannel where server_id = server_id_in;
        delete from rhnActionConfigRevision where server_id = server_id_in;
        delete from rhnActionPackageRemovalFailure where server_id = server_id_in;
        delete from rhnClientCapability where server_id = server_id_in;
        delete from rhnCpu where server_id = server_id_in;
        -- there's still a cascade here, because the constraint keeps the
        -- table locked for too long to rebuild it.  Ugh...
        delete from rhnDevice where server_id = server_id_in;
        delete from rhnProxyInfo where server_id = server_id_in;
        delete from rhnRam where server_id = server_id_in;
        delete from rhnRegToken where server_id = server_id_in;
        delete from rhnSatelliteInfo where server_id = server_id_in;
        -- this cascades to rhnActionConfigChannel and rhnActionConfigFileName
        delete from rhnServerAction where server_id = server_id_in;
        delete from rhnServerActionPackageResult where server_id = server_id_in;
        delete from rhnServerActionScriptResult where server_id = server_id_in;
        delete from rhnServerActionVerifyResult where server_id = server_id_in;
        delete from rhnServerActionVerifyMissing where server_id = server_id_in;
        -- counts are handled above.  this should be a delete_ function.
        delete from rhnServerChannel where server_id = server_id_in;
        delete from rhnServerConfigChannel where server_id = server_id_in;
        delete from rhnServerCustomDataValue where server_id = server_id_in;
        delete from rhnServerDMI where server_id = server_id_in;
        delete from rhnServerEvent where server_id = server_id_in;
        delete from rhnServerFQDN where server_id = server_id_in;
        delete from rhnServerHistory where server_id = server_id_in;
        delete from rhnServerInfo where server_id = server_id_in;
        delete from rhnServerInstallInfo where server_id = server_id_in;
        delete from rhnServerLocation where server_id = server_id_in;
        delete from rhnServerLock where server_id = server_id_in;
        delete from rhnServerNeededCache where server_id = server_id_in;
        delete from rhnServerNotes where server_id = server_id_in;
        -- I'm not removing the foreign key from rhnServerPackage; that'll
        -- take forever.  Do the delete anyway.
        delete from rhnServerPackage where server_id = server_id_in;
        delete from rhnServerTokenRegs where server_id = server_id_in;
        delete from rhnSnapshotTag where server_id = server_id_in;
        -- this cascades to:
        --   rhnSnapshotChannel, rhnSnapshotConfigChannel, rhnSnapshotPackage,
        --   rhnSnapshotConfigRevision, rhnSnapshotServerGroup,
        --   rhnSnapshotTag.
        -- We may want to consider delete_snapshot() at some point, but
        --   I don't think we need to yet.
        delete from rhnSnapshot where server_id = server_id_in;
        delete from rhnUserServerPrefs where server_id = server_id_in;
        -- hrm, this one's interesting... we _probably_ should delete
        -- everything for the parent server_id when we delete the proxy,
        -- but we don't currently.
        delete from rhnServerPath where server_id_in in (server_id, proxy_server_id);
        delete from rhnUserServerPerms where server_id = server_id_in;

        delete from rhnServerNetInterface where server_id = server_id_in;

        delete from rhnServerUuid where server_id = server_id_in;

        delete from rhnPushClient where server_id = server_id_in;

        -- now get rhnServer itself.
        delete
        from    rhnServer
                where id = server_id_in;

        delete
        from    rhnSet
        where   label = 'system_list'
                and element = server_id_in;
end;
$$
language plpgsql;
07070100000E3E000081B400000000000000000000000167AE111400000117000000000000000000000000000000000000007900000000susemanager-schema/upgrade/susemanager-schema-4.2.0-to-susemanager-schema-4.2.1/010-add-installer_updates-rhnChannel.sql  ALTER TABLE rhnChannel DROP CONSTRAINT IF EXISTS rhn_channel_instup_ck;
ALTER TABLE rhnChannel ADD COLUMN IF NOT EXISTS
    installer_updates CHAR(1) DEFAULT ('N') NOT NULL;
ALTER TABLE rhnChannel ADD
    CONSTRAINT rhn_channel_instup_ck CHECK (installer_updates in ('Y', 'N'));
 07070100000E3F000081B400000000000000000000000167AE11140000012E000000000000000000000000000000000000008000000000susemanager-schema/upgrade/susemanager-schema-4.2.0-to-susemanager-schema-4.2.1/011-add-installer_updates-suseSCCRepository.sql   ALTER TABLE suseSCCRepository DROP CONSTRAINT IF EXISTS suse_sccrepo_instup_ck;
ALTER TABLE suseSCCRepository ADD COLUMN IF NOT EXISTS
    installer_updates CHAR(1) DEFAULT ('N') NOT NULL;
ALTER TABLE suseSCCRepository ADD
    CONSTRAINT suse_sccrepo_instup_ck CHECK (installer_updates in ('Y', 'N'));
  07070100000E40000081B400000000000000000000000167AE11140000062B000000000000000000000000000000000000006600000000susemanager-schema/upgrade/susemanager-schema-4.2.0-to-susemanager-schema-4.2.1/100-rhnActionType.sql --
-- Copyright (c) 2020 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--

alter table rhnActionType drop CONSTRAINT if exists rhn_action_type_mtmode_ck;
alter table rhnActionType add column if not exists
    maintenance_mode_only CHAR(1)
                          DEFAULT ('N') NOT NULL;
alter table rhnActionType add
    CONSTRAINT rhn_action_type_mtmode_ck
    CHECK (maintenance_mode_only in ('Y','N'));

update rhnActionType set maintenance_mode_only = 'Y'
where label in ('packages.update', 'packages.remove', 'errata.update',
       'up2date_config.get', 'up2date_config.update', 'packages.delta',
       'reboot.reboot', 'rollback.config', 'rollback.rollback', 'packages.autoupdate',
       'packages.runTransaction', 'configfiles.deploy', 'kickstart.initiate',
       'solarispkgs.install', 'solarispkgs.remove', 'solarispkgs.patchInstall',
       'solarispkgs.patchRemove', 'solarispkgs.patchClusterInstall', 'solarispkgs.patchClusterRemove',
       'script.run', 'solarispkgs.refresh_list', 'clientcert.update_client_cert',
       'distupgrade.upgrade', 'states.apply', 'cluster.group_refresh_nodes', 'cluster.join_node',
       'cluster.remove_node', 'cluster.upgrade_cluster')
and maintenance_mode_only = 'N';
 07070100000E41000081B400000000000000000000000167AE111400000AC5000000000000000000000000000000000000007000000000susemanager-schema/upgrade/susemanager-schema-4.2.0-to-susemanager-schema-4.2.1/101-suseMaintenanceSchedule.sql   --
-- Copyright (c) 2020 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--

CREATE TABLE IF NOT EXISTS suseMaintenanceCalendar
(
  id          NUMERIC NOT NULL
              CONSTRAINT suse_mtcal_id_pk PRIMARY KEY,
  org_id      NUMERIC NOT NULL
              CONSTRAINT suse_mtcal_oid_fk
              REFERENCES web_customer(id)
              ON DELETE CASCADE,
  label       VARCHAR(128) NOT NULL,
  url         VARCHAR(1024),
  ical        TEXT NOT NULL,
  created     TIMESTAMPTZ
              DEFAULT (current_timestamp) NOT NULL,
  modified    TIMESTAMPTZ
              DEFAULT (current_timestamp) NOT NULL
);

CREATE SEQUENCE IF NOT EXISTS suse_mtcal_id_seq;

CREATE UNIQUE INDEX IF NOT EXISTS suse_mtcal_oid_label_uq
  ON suseMaintenanceCalendar(org_id, label);


CREATE TABLE IF NOT EXISTS suseMaintenanceSchedule
(
  id          NUMERIC NOT NULL
              CONSTRAINT suse_mtsched_id_pk PRIMARY KEY,
  org_id      NUMERIC NOT NULL
              CONSTRAINT suse_mtsched_oid_fk
              REFERENCES web_customer(id)
              ON DELETE CASCADE,
  name        VARCHAR(128) NOT NULL,
  sched_type  VARCHAR(10) NOT NULL,
  ical_id     NUMERIC
              CONSTRAINT suse_mtsched_icid_fk
              REFERENCES suseMaintenanceCalendar(id)
              ON DELETE SET NULL,
  created     TIMESTAMPTZ
              DEFAULT (current_timestamp) NOT NULL,
  modified    TIMESTAMPTZ
              DEFAULT (current_timestamp) NOT NULL
);

CREATE SEQUENCE IF NOT EXISTS suse_mtsched_id_seq;

CREATE UNIQUE INDEX IF NOT EXISTS suse_mtsched_oid_name_uq
  ON suseMaintenanceSchedule(org_id, name);

-- trigger

create or replace function suse_mtcal_mod_trig_fun() returns trigger as
$$
begin
        new.modified := current_timestamp;
        return new;
end;
$$ language plpgsql;

drop trigger if exists suse_mtcal_mod_trig ON suseMaintenanceCalendar;
create trigger
suse_mtcal_mod_trig
before insert or update on suseMaintenanceCalendar
for each row
execute procedure suse_mtcal_mod_trig_fun();


create or replace function suse_mtsched_mod_trig_fun() returns trigger as
$$
begin
        new.modified := current_timestamp;
        return new;
end;
$$ language plpgsql;

drop trigger if exists suse_mtsched_mod_trig ON suseMaintenanceSchedule;
create trigger
suse_mtsched_mod_trig
before insert or update on suseMaintenanceSchedule
for each row
execute procedure suse_mtsched_mod_trig_fun();
   07070100000E42000081B400000000000000000000000167AE1114000002BE000000000000000000000000000000000000006200000000susemanager-schema/upgrade/susemanager-schema-4.2.0-to-susemanager-schema-4.2.1/102-rhnServer.sql --
-- Copyright (c) 2020 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--

alter table rhnServer add column if not exists
    maintenance_schedule_id NUMERIC
                            CONSTRAINT rhn_server_mtsched_id_fk
                                REFERENCES suseMaintenanceSchedule (id)
                                ON DELETE SET NULL;
  07070100000E43000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005000000000susemanager-schema/upgrade/susemanager-schema-4.2.1-to-susemanager-schema-4.2.2   07070100000E44000081B400000000000000000000000167AE111400001C55000000000000000000000000000000000000005E00000000susemanager-schema/upgrade/susemanager-schema-4.2.1-to-susemanager-schema-4.2.2/120-arm64.sql insert into rhnCpuArch (id, label, name) select
sequence_nextval('rhn_cpu_arch_id_seq'), 'arm64', 'ARM64' from dual
where not exists (select 1 from rhnCpuArch where label = 'arm64');


insert into rhnPackageArch (id, label, name, arch_type_id) select
sequence_nextval('rhn_package_arch_id_seq'), 'arm64-deb', 'ARM64-deb', lookup_arch_type('deb') from dual
where not exists (select 1 from rhnPackageArch where label = 'arm64-deb');


insert into rhnServerArch (id, label, name, arch_type_id) select
sequence_nextval('rhn_server_arch_id_seq'), 'arm64-debian-linux', 'ARM64 Debian', lookup_arch_type('deb') from dual
where not exists (select 1 from rhnServerArch where label = 'arm64-debian-linux');


insert into rhnChannelArch (id, label, name, arch_type_id) select
sequence_nextval('rhn_channel_arch_id_seq'), 'channel-arm64-deb', 'ARM64 Debian', lookup_arch_type('deb') from dual
where not exists (select 1 from rhnChannelArch where label = 'channel-arm64-deb');


insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) select 
LOOKUP_PACKAGE_ARCH('arm64-deb'), LOOKUP_PACKAGE_ARCH('all-deb'), current_timestamp, current_timestamp from dual
where not exists (select 1 from rhnPackageUpgradeArchCompat where package_arch_id = LOOKUP_PACKAGE_ARCH('arm64-deb') and package_upgrade_arch_id = LOOKUP_PACKAGE_ARCH('all-deb'));

insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) select 
LOOKUP_PACKAGE_ARCH('arm64-deb'), LOOKUP_PACKAGE_ARCH('arm64-deb'), current_timestamp, current_timestamp from dual
where not exists (select 1 from rhnPackageUpgradeArchCompat where package_arch_id = LOOKUP_PACKAGE_ARCH('arm64-deb') and package_upgrade_arch_id = LOOKUP_PACKAGE_ARCH('arm64-deb'));

insert into rhnPackageUpgradeArchCompat (package_arch_id, package_upgrade_arch_id, created, modified) select 
LOOKUP_PACKAGE_ARCH('all-deb'), LOOKUP_PACKAGE_ARCH('arm64-deb'), current_timestamp, current_timestamp from dual
where not exists (select 1 from rhnPackageUpgradeArchCompat where package_arch_id = LOOKUP_PACKAGE_ARCH('all-deb') and package_upgrade_arch_id = LOOKUP_PACKAGE_ARCH('arm64-deb'));


insert into rhnChannelPackageArchCompat (channel_arch_id, package_arch_id) select 
LOOKUP_CHANNEL_ARCH('channel-arm64-deb'), LOOKUP_PACKAGE_ARCH('arm64-deb') from dual
where not exists (select 1 from rhnChannelPackageArchCompat where channel_arch_id = LOOKUP_CHANNEL_ARCH('channel-arm64-deb') and package_arch_id = LOOKUP_PACKAGE_ARCH('arm64-deb'));

insert into rhnChannelPackageArchCompat (channel_arch_id, package_arch_id) select 
LOOKUP_CHANNEL_ARCH('channel-arm64-deb'), LOOKUP_PACKAGE_ARCH('all-deb') from dual
where not exists (select 1 from rhnChannelPackageArchCompat where channel_arch_id = LOOKUP_CHANNEL_ARCH('channel-arm64-deb') and package_arch_id = LOOKUP_PACKAGE_ARCH('all-deb'));

insert into rhnChannelPackageArchCompat (channel_arch_id, package_arch_id) select 
LOOKUP_CHANNEL_ARCH('channel-arm64-deb'), LOOKUP_PACKAGE_ARCH('src-deb') from dual
where not exists (select 1 from rhnChannelPackageArchCompat where channel_arch_id = LOOKUP_CHANNEL_ARCH('channel-arm64-deb') and package_arch_id = LOOKUP_PACKAGE_ARCH('src-deb'));


insert into rhnServerChannelArchCompat (server_arch_id, channel_arch_id) select
LOOKUP_SERVER_ARCH('arm64-debian-linux'), LOOKUP_CHANNEL_ARCH('channel-arm64-deb') from dual
where not exists (select 1 from rhnServerChannelArchCompat where server_arch_id = LOOKUP_SERVER_ARCH('arm64-debian-linux') and channel_arch_id = LOOKUP_CHANNEL_ARCH('channel-arm64-deb'));


insert into rhnServerPackageArchCompat (server_arch_id, package_arch_id, preference) select
LOOKUP_SERVER_ARCH('arm64-debian-linux'), LOOKUP_PACKAGE_ARCH('arm64-deb'), 0 from dual
where not exists (select 1 from rhnServerPackageArchCompat where server_arch_id = LOOKUP_SERVER_ARCH('arm64-debian-linux') and package_arch_id = LOOKUP_PACKAGE_ARCH('arm64-deb'));

insert into rhnServerPackageArchCompat (server_arch_id, package_arch_id, preference) select
LOOKUP_SERVER_ARCH('arm64-debian-linux'), LOOKUP_PACKAGE_ARCH('all-deb'), 1000 from dual
where not exists (select 1 from rhnServerPackageArchCompat where server_arch_id = LOOKUP_SERVER_ARCH('arm64-debian-linux') and package_arch_id = LOOKUP_PACKAGE_ARCH('all-deb'));



insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type) select 
lookup_server_arch('arm64-debian-linux'), lookup_sg_type('enterprise_entitled') from dual
where not exists (select 1 from rhnServerServerGroupArchCompat where server_arch_id = lookup_server_arch('arm64-debian-linux') and server_group_type = lookup_sg_type('enterprise_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type) select 
lookup_server_arch('arm64-debian-linux'), lookup_sg_type('virtualization_host') from dual
where not exists (select 1 from rhnServerServerGroupArchCompat where server_arch_id = lookup_server_arch('arm64-debian-linux') and server_group_type = lookup_sg_type('virtualization_host'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type) select 
lookup_server_arch('arm64-debian-linux'), lookup_sg_type('bootstrap_entitled') from dual
where not exists (select 1 from rhnServerServerGroupArchCompat where server_arch_id = lookup_server_arch('arm64-debian-linux') and server_group_type = lookup_sg_type('bootstrap_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type) select 
lookup_server_arch('arm64-debian-linux'), lookup_sg_type('salt_entitled') from dual
where not exists (select 1 from rhnServerServerGroupArchCompat where server_arch_id = lookup_server_arch('arm64-debian-linux') and server_group_type = lookup_sg_type('salt_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type) select 
lookup_server_arch('arm64-debian-linux'), lookup_sg_type('foreign_entitled') from dual
where not exists (select 1 from rhnServerServerGroupArchCompat where server_arch_id = lookup_server_arch('arm64-debian-linux') and server_group_type = lookup_sg_type('foreign_entitled'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type) select 
lookup_server_arch('arm64-debian-linux'), lookup_sg_type('container_build_host') from dual
where not exists (select 1 from rhnServerServerGroupArchCompat where server_arch_id = lookup_server_arch('arm64-debian-linux') and server_group_type = lookup_sg_type('container_build_host'));

insert into rhnServerServerGroupArchCompat ( server_arch_id, server_group_type) select 
lookup_server_arch('arm64-debian-linux'), lookup_sg_type('monitoring_entitled') from dual
where not exists (select 1 from rhnServerServerGroupArchCompat where server_arch_id = lookup_server_arch('arm64-debian-linux') and server_group_type = lookup_sg_type('monitoring_entitled'));


insert into rhnChildChannelArchCompat (parent_arch_id, child_arch_id) select
LOOKUP_CHANNEL_ARCH('channel-arm64-deb'), LOOKUP_CHANNEL_ARCH('channel-arm64-deb') from dual
where not exists (select 1 from rhnChildChannelArchCompat where parent_arch_id = LOOKUP_CHANNEL_ARCH('channel-arm64-deb') and child_arch_id = LOOKUP_CHANNEL_ARCH('channel-arm64-deb'));

commit;

   07070100000E45000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005200000000susemanager-schema/upgrade/susemanager-schema-4.2.10-to-susemanager-schema-4.2.11 07070100000E46000081B400000000000000000000000167AE111400000C59000000000000000000000000000000000000007B00000000susemanager-schema/upgrade/susemanager-schema-4.2.10-to-susemanager-schema-4.2.11/100-ansible_control_node_entitlement.sql    --------------------------------------------------------------------------------
-- rhnServerGroupType ----------------------------------------------------------
--------------------------------------------------------------------------------
INSERT INTO rhnServerGroupType(
    id,
    label,
    name,
    permanent,
    is_base)
SELECT
    sequence_nextval('rhn_servergroup_type_seq'),
    'ansible_control_node',
    'Ansible Control Node',
    'N',
    'N'
WHERE NOT EXISTS (
    SELECT 1
    FROM rhnServerGroupType
    WHERE label = 'ansible_control_node'
);


--------------------------------------------------------------------------------
-- rhnSGTypeBaseAddonCompat ----------------------------------------------------
--------------------------------------------------------------------------------
INSERT INTO rhnSGTypeBaseAddonCompat(
    base_id,
    addon_id)
SELECT
    lookup_sg_type('salt_entitled'),
    lookup_sg_type('ansible_control_node')
WHERE NOT EXISTS (
    SELECT 1
    FROM rhnSGTypeBaseAddonCompat
    WHERE base_id = lookup_sg_type('salt_entitled')
        AND addon_id = lookup_sg_type('ansible_control_node')
);


--------------------------------------------------------------------------------
-- rhnServerServerGroupArchCompat ----------------------------------------------
--------------------------------------------------------------------------------
INSERT INTO rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
SELECT
    lookup_server_arch('x86_64-redhat-linux'),
    lookup_sg_type('ansible_control_node')
WHERE NOT EXISTS (
    SELECT 1
    FROM rhnServerServerGroupArchCompat
    WHERE server_arch_id = lookup_server_arch('x86_64-redhat-linux')
        AND server_group_type = lookup_sg_type('ansible_control_node')
);


INSERT INTO rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
SELECT
    lookup_server_arch('amd64-redhat-linux'),
    lookup_sg_type('ansible_control_node')
WHERE NOT EXISTS (
    SELECT 1
    FROM rhnServerServerGroupArchCompat
    WHERE server_arch_id = lookup_server_arch('amd64-redhat-linux')
        AND server_group_type = lookup_sg_type('ansible_control_node')
);

INSERT INTO rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
SELECT
    lookup_server_arch('amd64-debian-linux'),
    lookup_sg_type('ansible_control_node')
WHERE NOT EXISTS (
    SELECT 1
    FROM rhnServerServerGroupArchCompat
    WHERE server_arch_id = lookup_server_arch('amd64-debian-linux')
        AND server_group_type = lookup_sg_type('ansible_control_node')
);

--------------------------------------------------------------------------------
-- existing server groups update -----------------------------------------------
--------------------------------------------------------------------------------
INSERT INTO rhnServerGroup ( id, name, description, group_type, org_id )
SELECT nextval('rhn_server_group_id_seq'), sgt.name, sgt.name, sgt.id, org.id
FROM rhnServerGroupType sgt, web_customer org
WHERE sgt.label = 'ansible_control_node' AND org.id NOT IN (
    SELECT sg.org_id from rhnServerGroup sg
    WHERE sg.name = 'Ansible Control Node'
);
   07070100000E47000081B400000000000000000000000167AE11140000325A000000000000000000000000000000000000006F00000000susemanager-schema/upgrade/susemanager-schema-4.2.10-to-susemanager-schema-4.2.11/101-rhn_entitlements.pkb.sql    -- Copyright (c) 2008--2015 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

-- create schema rhn_entitlements;

-- setup search_path so that these functions are created in appropriate schema.
update pg_settings set setting = 'rhn_entitlements,' || setting where name = 'search_path';

   create or replace function find_compatible_sg (
      server_id_in in numeric,
      type_label_in in varchar
   )
   returns numeric
as $$
    declare
      servergroups cursor for
         select sg.id
           from rhnServerGroupType             sgt,
                rhnServerGroup                 sg,
                rhnServer                     s,
                rhnServerServerGroupArchCompat ssgac
          where s.id = server_id_in
            and s.org_id = sg.org_id
            and sgt.label = type_label_in
            and sg.group_type = sgt.id
            and ssgac.server_group_type = sgt.id
            and ssgac.server_arch_id = s.server_arch_id
            and not exists (
                     select 1
                      from rhnServerGroupMembers sgm
                     where sgm.server_group_id = sg.id
                       and sgm.server_id = s.id);


   begin
      for servergroup in servergroups loop
         return servergroup.id;
      end loop;

      --no servergroup found
      return NULL;
   end$$
language plpgsql;


    create or replace function entitlement_grants_service (
        entitlement_in in varchar,
        service_level_in in varchar
    ) returns numeric
as $$
    begin
        if service_level_in = 'management' then
            if entitlement_in = 'enterprise_entitled' or entitlement_in = 'salt_entitled' then
                return 1;
            else
                return 0;
            end if;
        elsif service_level_in = 'updates' then
            return 1;
        else
            return 0;
        end if;
    end$$
language plpgsql;

   create or replace function can_entitle_server (
      server_id_in   in numeric,
      type_label_in  in varchar
   )
   returns numeric
as $$
    declare
      addon_servergroups cursor (base_label_in varchar,
                                 addon_label_in varchar) for
         select
            addon_id
         from
            rhnSGTypeBaseAddonCompat
         where base_id = lookup_sg_type (base_label_in)
           and addon_id = lookup_sg_type (addon_label_in);

      previous_ent        varchar[];
      is_base_in          char   := 'N';
      is_base_current     char   := 'N';
      i                   numeric := 0;
      sgid                numeric := 0;

   begin

      previous_ent := rhn_entitlements.get_server_entitlement(server_id_in);
      RAISE NOTICE 'can_entitle_server - % - % prev ents: %', server_id_in, type_label_in, previous_ent;

      select distinct is_base
      into is_base_in
      from rhnServerGroupType
      where label = type_label_in;

      if array_upper(previous_ent, 1) is null or array_upper(previous_ent, 1) = 0 then
         if is_base_in = 'Y' then
            sgid := rhn_entitlements.find_compatible_sg (server_id_in, type_label_in);
            if sgid is not null then
              -- rhn_server.insert_into_servergroup (server_id_in, sgid);
              return 1;
            else
              -- rhn_exception.raise_exception ('invalid_base_entitlement');
              RAISE NOTICE 'invalid_base_entitlement - no compatible server group';
              return 0;
            end if;
         else
            -- rhn_exception.raise_exception ('invalid_base_entitlement');
            RAISE NOTICE 'invalid_base_entitlement - not a base entitlement';
            return 0;
         end if;

      -- there are previous ents, first make sure we're not trying to entitle a base ent
      elsif is_base_in = 'Y' then
         -- rhn_exception.raise_exception ('invalid_addon_entitlement');
         RAISE NOTICE 'invalid_addon_entitlement - found another base';
         return 0;

      -- it must be an addon, so proceed with the entitlement
      else

         -- find the servers base ent
         is_base_current := 'N';
         i := 0;
         while is_base_current = 'N' and i < array_upper(previous_ent, 1)
         loop
            i := i + 1;
            select is_base
            into is_base_current
            from rhnServerGroupType
            where label = previous_ent[i];
         end loop;

         -- never found a base ent, that would be strange
         if is_base_current  = 'N' then
            -- rhn_exception.raise_exception ('invalid_base_entitlement');
            RAISE NOTICE 'invalid_base_entitlement - never found a base';
            return 0;
         end if;

         -- this for loop verifies the validity of the addon path
         for addon_servergroup in addon_servergroups  (previous_ent[i], type_label_in) loop
            -- find an appropriate sgid for the addon and entitle the server
            sgid := rhn_entitlements.find_compatible_sg (server_id_in, type_label_in);
            if sgid is not null then
               -- rhn_server.insert_into_servergroup (server_id_in, sgid);
               return 1;
            else
               -- rhn_exception.raise_exception ('invalid_addon_entitlement');
               RAISE NOTICE 'invalid_addon_entitlement - no server group found';
               return 0;
            end if;
         end loop;

      end if;
      RAISE NOTICE 'final error';
      return 0;

   end$$
language plpgsql;

   create or replace function can_switch_base (
      server_id_in   in    integer,
      type_label_in  in    varchar
   )
   returns numeric
as $$
   declare
      type_label_in_is_base   char(1);
      sgid                    numeric;

   begin

       select is_base into type_label_in_is_base
       from rhnServerGroupType
       where label = type_label_in;

       if not found then
          perform rhn_exception.raise_exception ( 'invalid_entitlement' );
       end if;

      if type_label_in_is_base = 'N' then
         perform rhn_exception.raise_exception ( 'invalid_entitlement' );
      else
         sgid := rhn_entitlements.find_compatible_sg ( server_id_in,
                                                       type_label_in );
         if sgid is not null then
           return 1;
         else
           return 0;
         end if;
      end if;

   end$$
language plpgsql;

    create or replace function entitle_server (
        server_id_in in numeric,
        type_label_in in varchar
    ) returns void
as $$
    declare
      sgid  numeric := 0;

    begin

      if rhn_entitlements.can_entitle_server(server_id_in,
                                             type_label_in) = 1 then
         sgid := rhn_entitlements.find_compatible_sg (server_id_in,
                                                      type_label_in);
         if sgid is not null then
            insert into rhnServerHistory ( id, server_id, summary, details )
            values ( nextval('rhn_event_id_seq'), server_id_in,
                     'added system entitlement ',
                      case type_label_in
                       when 'enterprise_entitled' then 'Management'
                       when 'bootstrap_entitled' then 'Bootstrap'
                       when 'salt_entitled' then 'Salt'
                       when 'foreign_entitled' then 'Foreign'
                       when 'virtualization_host' then 'Virtualization'
                       when 'container_build_host' then 'Container'
                       when 'osimage_build_host' then 'OS Image'
                       when 'monitoring_entitled' then 'Monitoring'
                       when 'ansible_control_node' then 'Ansible'
                      end  );

            perform rhn_server.insert_into_servergroup (server_id_in, sgid);

         else
            perform rhn_exception.raise_exception ('no_available_server_group');
         end if;
      else
         perform rhn_exception.raise_exception ('invalid_entitlement');
      end if;
   end$$
language plpgsql;

    create or replace function remove_server_entitlement (
        server_id_in in numeric,
        type_label_in in varchar
    ) returns void
as $$
    declare
      group_id numeric;
      type_is_base char;
    begin

        select  sg.id, sgt.is_base
        into group_id, type_is_base
        from    rhnServerGroupType sgt,
            rhnServerGroup sg,
                rhnServerGroupMembers sgm,
                rhnServer s
        where   s.id = server_id_in
            and s.id = sgm.server_id
            and sgm.server_group_id = sg.id
            and sg.org_id = s.org_id
            and sgt.label = type_label_in
            and sgt.id = sg.group_type;

        if not found then
          perform rhn_exception.raise_exception('invalid_server_group_member');
        end if;

      if ( type_is_base = 'Y' ) then
         -- unentitle_server should handle everything, don't really need to do anything else special here
         perform rhn_entitlements.unentitle_server ( server_id_in );
      else

         insert into rhnServerHistory ( id, server_id, summary, details )
         values ( nextval('rhn_event_id_seq'), server_id_in,
                  'removed system entitlement ',
                   case type_label_in
                    when 'enterprise_entitled' then 'Management'
                    when 'bootstrap_entitled' then 'Bootstrap'
                    when 'salt_entitled' then 'Salt'
                    when 'foreign_entitled' then 'Foreign'
                    when 'virtualization_host' then 'Virtualization'
                    when 'container_build_host' then 'Container'
                    when 'osimage_build_host' then 'OS Image'
                    when 'ansible_control_node' then 'Ansible'
                   end  );

         perform rhn_server.delete_from_servergroup(server_id_in, group_id);

      end if;

    end$$
language plpgsql;

    create or replace function unentitle_server (
        server_id_in in numeric
    ) returns void
as $$
    declare
      servergroups cursor for
         select distinct sgt.label, sg.id server_group_id
         from  rhnServerGroupType sgt,
               rhnServerGroup sg,
               rhnServer s,
               rhnServerGroupMembers sgm
         where s.id = server_id_in
            and s.org_id = sg.org_id
            and sg.group_type = sgt.id
            and sgm.server_group_id = sg.id
            and sgm.server_id = s.id;

   begin

      for servergroup in servergroups loop

         insert into rhnServerHistory ( id, server_id, summary, details )
         values ( nextval('rhn_event_id_seq'), server_id_in,
                  'removed system entitlement ',
                   case servergroup.label
                    when 'enterprise_entitled' then 'Management'
                    when 'bootstrap_entitled' then 'Bootstrap'
                    when 'salt_entitled' then 'Salt'
                    when 'foreign_entitled' then 'Foreign'
                    when 'virtualization_host' then 'Virtualization'
                    when 'container_build_host' then 'Container'
                    when 'osimage_build_host' then 'OS Image'
                    when 'ansible_control_node' then 'Ansible'
                   end  );

         perform rhn_server.delete_from_servergroup(server_id_in,
                                            servergroup.server_group_id );
      end loop;

   end$$
language plpgsql;


    create or replace function get_server_entitlement (
        server_id_in in numeric
    ) returns varchar[]
as $$
    declare
        server_groups cursor for
            select  sgt.label
            from    rhnServerGroupType      sgt,
                    rhnServerGroup          sg,
                    rhnServerGroupMembers   sgm
            where   1=1
                and sgm.server_id = server_id_in
                and sg.id = sgm.server_group_id
                and sgt.id = sg.group_type;

         ent_array varchar[];

    begin

      ent_array := '{}';

      for sg in server_groups loop
         ent_array := ent_array || sg.label;
      end loop;

      return ent_array;

    end$$
language plpgsql;

-- restore the original setting
update pg_settings set setting = overlay( setting placing '' from 1 for (length('rhn_entitlements')+1) ) where name = 'search_path';
  07070100000E48000081B400000000000000000000000167AE1114000022C4000000000000000000000000000000000000006900000000susemanager-schema/upgrade/susemanager-schema-4.2.10-to-susemanager-schema-4.2.11/102-create_new_org.sql  --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--

create or replace function create_new_org
(
        name_in      in varchar,
        password_in  in varchar
        --org_id_out   out number
) returns numeric
as
$$
declare
        ug_type                 numeric;
        group_val               numeric;
        new_org_id              numeric;
        org_id_out		numeric;
begin

        select nextval('web_customer_id_seq') into new_org_id from dual;

        insert into web_customer (
                id, name
        ) values (
                new_org_id, name_in
        );

        select nextval('rhn_user_group_id_seq') into group_val from dual;

        select  id
        into    ug_type
        from    rhnUserGroupType
        where   label = 'org_admin';

        insert into rhnUserGroup (
                id, name,
                description,
                max_members, group_type, org_id
        ) values (
                group_val, 'Organization Administrators',
                'Organization Administrators for Org ' || name_in,
                NULL, ug_type, new_org_id
        );

        select nextval('rhn_user_group_id_seq') into group_val from dual;

        select  id
        into    ug_type
        from    rhnUserGroupType
        where   label = 'system_group_admin';

        insert into rhnUserGroup (
                id, name,
                description,
                max_members, group_type, org_id
        ) values (
                group_val, 'System Group Administrators',
                'System Group Administrators for Org ' || name_in,
                NULL, ug_type, new_org_id
        );


        select nextval('rhn_user_group_id_seq') into group_val from dual;

        select  id
        into    ug_type
        from    rhnUserGroupType
        where   label = 'activation_key_admin';

        insert into rhnUserGroup (
                id, name,
                description,
                max_members, group_type, org_id
        ) values (
                group_val, 'Activation Key Administrators',
                'Activation Key Administrators for Org ' || name_in,
                NULL, ug_type, new_org_id
        );

        select nextval('rhn_user_group_id_seq') into group_val from dual;

        select  id
        into    ug_type
        from    rhnUserGroupType
        where   label = 'channel_admin';

        insert into rhnUserGroup (
                id, name,
                description,
                max_members, group_type, org_id
        ) values (
                group_val, 'Channel Administrators',
                'Channel Administrators for Org ' || name_in,
                NULL, ug_type, new_org_id
        );

	if new_org_id = 1 then
            select nextval('rhn_user_group_id_seq') into group_val from dual;

            select  id
            into    ug_type
            from    rhnUserGroupType
            where   label = 'satellite_admin';

            insert into rhnUserGroup (
                    id, name,
                    description,
                    max_members, group_type, org_id
            ) values (
                    group_val, 'SUSE Manager Administrators',
                    'SUSE Manager Administrators for Org ' || name_in,
                    NULL, ug_type, new_org_id
            );
        end if;

        select nextval('rhn_user_group_id_seq') into group_val from dual;

        select  id
        into    ug_type
        from    rhnUserGroupType
        where   label = 'config_admin';

        insert into rhnUserGroup (
                id, name,
                description,
                max_members, group_type, org_id
        ) values (
                group_val, 'Configuration Administrators',
                'Configuration Administrators for Org ' || name_in,
                NULL, ug_type, new_org_id
        );

        select nextval('rhn_user_group_id_seq') into group_val from dual;

        select  id
        into    ug_type
        from    rhnUserGroupType
        where   label = 'image_admin';

        insert into rhnUserGroup (
                id, name,
                description,
                max_members, group_type, org_id
        ) values (
                group_val, 'Image Administrators',
                'Image Administrators for Org ' || name_in,
                NULL, ug_type, new_org_id
        );

        select nextval('rhn_user_group_id_seq') into group_val from dual;

        select  id
        into    ug_type
        from    rhnUserGroupType
        where   label = 'cluster_admin';

        insert into rhnUserGroup (
                id, name,
                description,
                max_members, group_type, org_id
        ) values (
                group_val, 'Cluster Administrators',
                'Cluster Administrators for Org ' || name_in,
                NULL, ug_type, new_org_id
        );

        -- there aren't any users yet, so we don't need to update
        -- rhnUserServerPerms

        insert into rhnServerGroup
                ( id, name, description, group_type, org_id )
                select nextval('rhn_server_group_id_seq'), sgt.name, sgt.name,
                        sgt.id, new_org_id
                from rhnServerGroupType sgt
                where sgt.label = 'bootstrap_entitled';

        insert into rhnServerGroup
                ( id, name, description, group_type, org_id )
                select nextval('rhn_server_group_id_seq'), sgt.name, sgt.name,
                        sgt.id, new_org_id
                from rhnServerGroupType sgt
                where sgt.label = 'enterprise_entitled';

        insert into rhnServerGroup
                ( id, name, description, group_type, org_id )
                select nextval('rhn_server_group_id_seq'), sgt.name, sgt.name,
                        sgt.id, new_org_id
                from rhnServerGroupType sgt
                where sgt.label = 'salt_entitled';

        insert into rhnServerGroup
                ( id, name, description, group_type, org_id )
                select nextval('rhn_server_group_id_seq'), sgt.name, sgt.name,
                        sgt.id, new_org_id
                from rhnServerGroupType sgt
                where sgt.label = 'foreign_entitled';

        insert into rhnServerGroup
                ( id, name, description, group_type, org_id )
                select nextval('rhn_server_group_id_seq'), sgt.name, sgt.name,
                        sgt.id, new_org_id
                from rhnServerGroupType sgt
                where sgt.label = 'virtualization_host';

        insert into rhnServerGroup
                ( id, name, description, group_type, org_id )
                select nextval('rhn_server_group_id_seq'), sgt.name, sgt.name,
                        sgt.id, new_org_id
                from rhnServerGroupType sgt
                where sgt.label = 'container_build_host';

        insert into rhnServerGroup
                ( id, name, description, group_type, org_id )
                select nextval('rhn_server_group_id_seq'), sgt.name, sgt.name,
                        sgt.id, new_org_id
                from rhnServerGroupType sgt
                where sgt.label = 'osimage_build_host';

        insert into rhnServerGroup
                ( id, name, description, group_type, org_id )
                select nextval('rhn_server_group_id_seq'), sgt.name, sgt.name,
                        sgt.id, new_org_id
                from rhnServerGroupType sgt
                where sgt.label = 'monitoring_entitled';

        insert into rhnServerGroup
                ( id, name, description, group_type, org_id )
                select nextval('rhn_server_group_id_seq'), sgt.name, sgt.name,
                        sgt.id, new_org_id
                from rhnServerGroupType sgt
                where sgt.label = 'ansible_control_node';

        insert into suseImageStore (id, label, uri, store_type_id, org_id)
        values (
            nextval('suse_imgstore_id_seq'),
            'SUSE Manager OS Image Store',
            new_org_id || '/',
            (SELECT id FROM suseImageStoreType WHERE label = 'os_image'),
            new_org_id
        );

        org_id_out := new_org_id;

	-- Returning the value of OUT parameter
        return org_id_out;

end;
$$
language plpgsql;
07070100000E49000081B400000000000000000000000167AE111400000573000000000000000000000000000000000000006700000000susemanager-schema/upgrade/susemanager-schema-4.2.10-to-susemanager-schema-4.2.11/103-ansible_path.sql    
CREATE TABLE IF NOT EXISTS suseAnsiblePath(

    id NUMERIC NOT NULL
        CONSTRAINT suse_ansible_path_id_pk PRIMARY KEY,

    server_id NUMERIC NOT NULL
        CONSTRAINT suse_ansible_path_sid_fk
        REFERENCES rhnServer(id)
        ON DELETE CASCADE,

    path VARCHAR(1024) NOT NULL,

    type VARCHAR(16) NOT NULL
        CONSTRAINT suse_ansible_path_type_ck
        CHECK (type in ('inventory', 'playbook')),

    created     TIMESTAMPTZ
        DEFAULT (current_timestamp) NOT NULL,

    modified    TIMESTAMPTZ
        DEFAULT (current_timestamp) NOT NULL
);                                                                                                                                                       

CREATE SEQUENCE IF NOT EXISTS suse_ansible_path_seq;

CREATE UNIQUE INDEX IF NOT EXISTS suse_ansible_path_type_uq
    ON suseAnsiblePath(server_id, path, type);

CREATE UNIQUE INDEX IF NOT EXISTS suse_ansible_type_path_uq
    ON suseAnsiblePath(server_id, type, path);

CREATE OR REPLACE function suse_ansible_path_mod_trig_fun() RETURNS TRIGGER AS
$$
BEGIN
        new.modified := current_timestamp;
        RETURN new;
END;
$$ language plpgsql;

DROP TRIGGER IF EXISTS suse_ansible_path_mod_trig ON suseAnsiblePath;
CREATE TRIGGER
suse_ansible_path_mod_trig
BEFORE INSERT OR UPDATE ON suseAnsiblePath
FOR EACH ROW
EXECUTE PROCEDURE suse_ansible_path_mod_trig_fun();
 07070100000E4A000081B400000000000000000000000167AE1114000005C3000000000000000000000000000000000000007300000000susemanager-schema/upgrade/susemanager-schema-4.2.10-to-susemanager-schema-4.2.11/104-create-rhnActionPlaybook.sql    -- Copyright (c) 2021 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

CREATE TABLE IF NOT EXISTS rhnActionPlaybook
(
    id                  NUMERIC NOT NULL
                            CONSTRAINT rhn_action_playbook_id_pk
                                PRIMARY KEY,
    action_id           NUMERIC NOT NULL
                            CONSTRAINT rhn_action_playbook_aid_fk
                                REFERENCES rhnAction (id)
                                ON DELETE CASCADE,
    playbook_path       VARCHAR(1024) NOT NULL,
    inventory_path      VARCHAR(1024),
    created             TIMESTAMPTZ
                            DEFAULT (current_timestamp) NOT NULL,
    modified            TIMESTAMPTZ
                            DEFAULT (current_timestamp) NOT NULL
)
;

CREATE UNIQUE INDEX IF NOT EXISTS rhn_act_playbook_aid_uq
    ON rhnActionPlaybook (action_id);

CREATE SEQUENCE IF NOT EXISTS rhn_act_playbook_id_seq;
 07070100000E4B000081B400000000000000000000000167AE111400000370000000000000000000000000000000000000007900000000susemanager-schema/upgrade/susemanager-schema-4.2.10-to-susemanager-schema-4.2.11/105-insert-action-ansible-playbook.sql  -- Copyright (c) 2021 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

insert into rhnActionType (id, label, name, trigger_snapshot, unlocked_only, maintenance_mode_only) (
    select 521, 'ansible.playbook', 'Execute an Ansible playbook', 'N', 'N', 'N'
    from dual
    where not exists (select 1 from rhnActionType where id = 521)
);
07070100000E4C000081B400000000000000000000000167AE111400000718000000000000000000000000000000000000006A00000000susemanager-schema/upgrade/susemanager-schema-4.2.10-to-susemanager-schema-4.2.11/150-suseSCCRegCache.sql --
-- Copyright (c) 2021 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--


CREATE TABLE IF NOT EXISTS suseSCCRegCache
(
    id               NUMERIC
                         CONSTRAINT suse_sccregcache_id_pk
			 PRIMARY KEY,
    server_id        NUMERIC NULL
                         CONSTRAINT suse_sccregcache_sid_fk
                             REFERENCES rhnServer (id)
			 ON DELETE SET NULL,
    scc_reg_required char(1)
                         DEFAULT ('N') not null
                         CONSTRAINT suse_sccregcache_reg_ck
                             CHECK (scc_reg_required IN ('Y', 'N')),
    scc_id                 NUMERIC,
    scc_login              VARCHAR(64),
    scc_passwd             VARCHAR(64),
    scc_regerror_timestamp TIMESTAMPTZ,
    creds_id       NUMERIC NULL
                       CONSTRAINT suse_sccregcache_credsid_fk
		       REFERENCES suseCredentials (id),
---                    ON DELETE DO NOTHING !
    created        TIMESTAMPTZ
                       DEFAULT (current_timestamp) NOT NULL,
    modified       TIMESTAMPTZ
                       DEFAULT (current_timestamp) NOT NULL
);

CREATE INDEX IF NOT EXISTS suse_sccregcache_sid_idx
    ON suseSCCRegCache (server_id);

CREATE SEQUENCE IF NOT EXISTS suse_sccregcache_id_seq;
07070100000E4D000081B400000000000000000000000167AE11140000018A000000000000000000000000000000000000007200000000susemanager-schema/upgrade/susemanager-schema-4.2.10-to-susemanager-schema-4.2.11/151-suseSCCRegCache-trigger.sql 
create or replace function suse_sccregcache_mod_trig_fun() returns trigger as
$$
begin
        new.modified = current_timestamp;
        return new;
end;
$$ language plpgsql;

drop trigger if exists suse_sccregcache_mod_trig on suseSCCRegCache;
create trigger
suse_sccregcache_mod_trig
before insert or update on suseSCCRegCache
for each row
execute procedure suse_sccregcache_mod_trig_fun();
  07070100000E4E000081B400000000000000000000000167AE11140000063E000000000000000000000000000000000000007800000000susemanager-schema/upgrade/susemanager-schema-4.2.10-to-susemanager-schema-4.2.11/152-add-forward-registration-task.sql   
INSERT INTO rhnTaskoBunch (id, name, description, org_bunch)
  SELECT sequence_nextval('rhn_tasko_bunch_id_seq'), 'mgr-forward-registration-bunch',
         'Forward registrations to SUSE Customer Center', null
  WHERE NOT EXISTS (
	SELECT 1 FROM rhnTaskoBunch
         WHERE name = 'mgr-forward-registration-bunch'
  );

INSERT INTO rhnTaskoSchedule (id, job_label, bunch_id, active_from, cron_expr)
  SELECT sequence_nextval('rhn_tasko_schedule_id_seq'), 'mgr-forward-registration-default',
        (SELECT id FROM rhnTaskoBunch WHERE name='mgr-forward-registration-bunch'),
        current_timestamp, '0 0/15 * * * ?'
  WHERE NOT EXISTS (
	SELECT 1 FROM rhnTaskoSchedule
	WHERE job_label = 'mgr-forward-registration-default'
  );

INSERT INTO rhnTaskoTask (id, name, class)
  SELECT sequence_nextval('rhn_tasko_task_id_seq'), 'mgr-forward-registration',
         'com.redhat.rhn.taskomatic.task.ForwardRegistrationTask'
  WHERE NOT EXISTS (
	SELECT 1 FROM rhnTaskoTask
	WHERE name = 'mgr-forward-registration'
  );

INSERT INTO rhnTaskoTemplate (id, bunch_id, task_id, ordering, start_if)
  SELECT sequence_nextval('rhn_tasko_template_id_seq'),
         (SELECT id FROM rhnTaskoBunch WHERE name='mgr-forward-registration-bunch'),
         (SELECT id FROM rhnTaskoTask WHERE name='mgr-forward-registration'),
         0, null
  WHERE NOT EXISTS (
	SELECT 1 FROM rhnTaskoTemplate
	WHERE bunch_id = (SELECT id FROM rhnTaskoBunch WHERE name = 'mgr-forward-registration-bunch')
	  AND task_id = (SELECT id FROM rhnTaskoTask WHERE name = 'mgr-forward-registration')
	  AND ordering = 0
  );

commit;
  07070100000E4F000081B400000000000000000000000167AE1114000001EA000000000000000000000000000000000000006C00000000susemanager-schema/upgrade/susemanager-schema-4.2.10-to-susemanager-schema-4.2.11/153-rhnServer-trigger.sql   create or replace function rhn_server_up_trig_fun() returns trigger as
$$
begin
        update suseSCCRegCache
          set scc_reg_required = 'Y'
        where server_id = old.id;
       return new;
end;
$$ language plpgsql;

drop trigger if exists rhn_server_up_trig on rhnServer;
create trigger
rhn_server_up_trig
after update on rhnServer
for each row
when (OLD.hostname is distinct from NEW.hostname or OLD.payg is distinct from NEW.payg)
execute procedure rhn_server_up_trig_fun();

  07070100000E50000081B400000000000000000000000167AE11140000032B000000000000000000000000000000000000007D00000000susemanager-schema/upgrade/susemanager-schema-4.2.10-to-susemanager-schema-4.2.11/154-suseServerInstalledProduct-trigger.sql  create or replace function suse_srv_inst_prod_iud_trig_fun() returns trigger as
$$
begin
        if tg_op='INSERT' or tg_op='UPDATE' then
                update suseSCCRegCache
                   set scc_reg_required = 'Y'
                 where server_id = new.rhn_server_id;
                return new;
        end if;
        if tg_op='DELETE' then
                update suseSCCRegCache
                   set scc_reg_required = 'Y'
                 where server_id = old.rhn_server_id;
                return old;
        end if;
end;
$$ language plpgsql;

drop trigger if exists susesrvinstprod_iud_trig on suseServerInstalledProduct;
create trigger
susesrvinstprod_iud_trig
after insert or update or delete on suseServerInstalledProduct
for each row
execute procedure suse_srv_inst_prod_iud_trig_fun();

 07070100000E51000081B400000000000000000000000167AE111400000251000000000000000000000000000000000000007900000000susemanager-schema/upgrade/susemanager-schema-4.2.10-to-susemanager-schema-4.2.11/156-rhnVirtualInstanceInfo-trigger.sql  create or replace function rhn_virtinst_info_iud_trig_fun() returns trigger as
$$
begin
        update suseSCCRegCache
           set scc_reg_required = 'Y'
         where server_id = (select virtual_system_id from rhnvirtualinstance WHERE id = new.instance_id);
        return new;
end;
$$ language plpgsql;

drop trigger if exists rhn_virtinst_info_iud_trig on rhnVirtualInstanceInfo;
create trigger
rhn_virtinst_info_iud_trig
after update on rhnVirtualInstanceInfo
for each row
when (OLD.instance_type is distinct from NEW.instance_type)
execute procedure rhn_virtinst_info_iud_trig_fun();
   07070100000E52000081B400000000000000000000000167AE1114000001E3000000000000000000000000000000000000006900000000susemanager-schema/upgrade/susemanager-schema-4.2.10-to-susemanager-schema-4.2.11/157-rhnCpu-trigger.sql  create or replace function rhn_cpu_up_trig_fun() returns trigger as
$$
begin
        update suseSCCRegCache
           set scc_reg_required = 'Y'
         where server_id = new.server_id;
        return new;
end;
$$ language plpgsql;

drop trigger if exists rhn_cpu_up_trig on rhnCpu;
create trigger
rhn_cpu_up_trig
after update on rhnCpu
for each row
when (OLD.nrcpu is distinct from NEW.nrcpu OR OLD.nrsocket is distinct from NEW.nrsocket)
execute procedure rhn_cpu_up_trig_fun();
 07070100000E53000081B400000000000000000000000167AE111400000222000000000000000000000000000000000000007800000000susemanager-schema/upgrade/susemanager-schema-4.2.10-to-susemanager-schema-4.2.11/200-rename-service-pack-migration.sql   --
-- Copyright (c) 2021 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--

UPDATE rhnActionType SET name='Product Migration' WHERE label='distupgrade.upgrade' AND name!='Product Migration';
  07070100000E54000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005200000000susemanager-schema/upgrade/susemanager-schema-4.2.11-to-susemanager-schema-4.2.12 07070100000E55000081B400000000000000000000000167AE111400000425000000000000000000000000000000000000006600000000susemanager-schema/upgrade/susemanager-schema-4.2.11-to-susemanager-schema-4.2.12/100-alma-amazon.sql insert into rhnPackageProvider (id, name)
    (select sequence_nextval('rhn_package_provider_id_seq'), 'AlmaLinux' from dual
    where not exists (select 1 from rhnPackageProvider where name = 'AlmaLinux'));

-- Alma Linux 8
insert into rhnPackageKey (id, key_id, key_type_id, provider_id)
    (select sequence_nextval('rhn_pkey_id_seq'), '488fcf7c3abb34f8', lookup_package_key_type('gpg'),
    lookup_package_provider('AlmaLinux') from dual
    where not exists (select 1 from rhnPackageKey where key_id = '488fcf7c3abb34f8'));

insert into rhnPackageProvider (id, name)
    (select sequence_nextval('rhn_package_provider_id_seq'), 'Amazon' from dual
    where not exists (select 1 from rhnPackageProvider where name = 'Amazon'));

-- Amazon Linux 2
insert into rhnPackageKey (id, key_id, key_type_id, provider_id)
    (select sequence_nextval('rhn_pkey_id_seq'), '11cf1f95c87f5b1a', lookup_package_key_type('gpg'),
    lookup_package_provider('Amazon') from dual
    where not exists (select 1 from rhnPackageKey where key_id = '11cf1f95c87f5b1a'));

commit;
   07070100000E56000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005200000000susemanager-schema/upgrade/susemanager-schema-4.2.12-to-susemanager-schema-4.2.13 07070100000E57000081B400000000000000000000000167AE111400000000000000000000000000000000000000000000005B00000000susemanager-schema/upgrade/susemanager-schema-4.2.12-to-susemanager-schema-4.2.13/.gitkeep    07070100000E58000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005200000000susemanager-schema/upgrade/susemanager-schema-4.2.13-to-susemanager-schema-4.2.14 07070100000E59000081B400000000000000000000000167AE111400000000000000000000000000000000000000000000005B00000000susemanager-schema/upgrade/susemanager-schema-4.2.13-to-susemanager-schema-4.2.14/.gitkeep    07070100000E5A000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005200000000susemanager-schema/upgrade/susemanager-schema-4.2.14-to-susemanager-schema-4.2.15 07070100000E5B000081B400000000000000000000000167AE1114000001C8000000000000000000000000000000000000008100000000susemanager-schema/upgrade/susemanager-schema-4.2.14-to-susemanager-schema-4.2.15/000-almalinux-fix-uyuni-tools-repositories.sql  UPDATE rhnContentSource
SET source_url = 'https://download.opensuse.org/repositories/systemsmanagement:/Uyuni:/Master:/EL8-Uyuni-Client-Tools/EL_8/'
WHERE label = 'External - Uyuni Client Tools for AlmaLinux 8 (x86_64) (Development)';
UPDATE rhnContentSource
SET source_url = 'https://download.opensuse.org/repositories/systemsmanagement:/Uyuni:/Stable:/EL8-Uyuni-Client-Tools/EL_8/'
WHERE label = 'External - Uyuni Client Tools for AlmaLinux 8 (x86_64)';
07070100000E5C000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005100000000susemanager-schema/upgrade/susemanager-schema-4.2.14-to-susemanager-schema-4.3.0  07070100000E5D000081B400000000000000000000000167AE111400000000000000000000000000000000000000000000005A00000000susemanager-schema/upgrade/susemanager-schema-4.2.14-to-susemanager-schema-4.3.0/.gitkeep 07070100000E5E000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005200000000susemanager-schema/upgrade/susemanager-schema-4.2.15-to-susemanager-schema-4.2.16 07070100000E5F000081B400000000000000000000000167AE11140000000F000000000000000000000000000000000000006900000000susemanager-schema/upgrade/susemanager-schema-4.2.15-to-susemanager-schema-4.2.16/300-vacuum-analyze.sql  VACUUM ANALYZE; 07070100000E60000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005100000000susemanager-schema/upgrade/susemanager-schema-4.2.15-to-susemanager-schema-4.3.0  07070100000E61000081B400000000000000000000000167AE111400000000000000000000000000000000000000000000005A00000000susemanager-schema/upgrade/susemanager-schema-4.2.15-to-susemanager-schema-4.3.0/.gitkeep 07070100000E62000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005100000000susemanager-schema/upgrade/susemanager-schema-4.2.16-to-susemanager-schema-4.3.0  07070100000E63000081B400000000000000000000000167AE111400000000000000000000000000000000000000000000005A00000000susemanager-schema/upgrade/susemanager-schema-4.2.16-to-susemanager-schema-4.3.0/.gitkeep 07070100000E64000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005100000000susemanager-schema/upgrade/susemanager-schema-4.2.17-to-susemanager-schema-4.3.0  07070100000E65000081B400000000000000000000000167AE111400000000000000000000000000000000000000000000005A00000000susemanager-schema/upgrade/susemanager-schema-4.2.17-to-susemanager-schema-4.3.0/.gitkeep 07070100000E66000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005100000000susemanager-schema/upgrade/susemanager-schema-4.2.18-to-susemanager-schema-4.3.0  07070100000E67000081B400000000000000000000000167AE111400000000000000000000000000000000000000000000005A00000000susemanager-schema/upgrade/susemanager-schema-4.2.18-to-susemanager-schema-4.3.0/.gitkeep 07070100000E68000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005100000000susemanager-schema/upgrade/susemanager-schema-4.2.19-to-susemanager-schema-4.3.0  07070100000E69000081B400000000000000000000000167AE111400000000000000000000000000000000000000000000005A00000000susemanager-schema/upgrade/susemanager-schema-4.2.19-to-susemanager-schema-4.3.0/.gitkeep 07070100000E6A000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005000000000susemanager-schema/upgrade/susemanager-schema-4.2.2-to-susemanager-schema-4.2.3   07070100000E6B000081B400000000000000000000000167AE1114000003BF000000000000000000000000000000000000007A00000000susemanager-schema/upgrade/susemanager-schema-4.2.2-to-susemanager-schema-4.2.3/001-add_rhnVirtCreateAction_cobblerid.sql --
-- Copyright (c) 2020 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--

DO $$
    BEGIN
        IF EXISTS
            (
                SELECT 1
                FROM information_schema.columns
                WHERE table_name='rhnactionvirtcreate' AND column_name='vm_type'
            )
        THEN
            ALTER TABLE rhnActionVirtCreate
                ADD COLUMN IF NOT EXISTS cobbler_system VARCHAR(256),
                ADD COLUMN IF NOT EXISTS kickstart_host VARCHAR(256),
                ADD COLUMN IF NOT EXISTS kernel_options VARCHAR(256);
        END IF;
    END
$$ LANGUAGE plpgsql;
 07070100000E6C000081B400000000000000000000000167AE111400000119000000000000000000000000000000000000007E00000000susemanager-schema/upgrade/susemanager-schema-4.2.2-to-susemanager-schema-4.2.3/001-rhnActionDup-add-alllow-vendor-change.sql ALTER TABLE rhnActionDup DROP CONSTRAINT IF EXISTS rhn_actiondup_avc_ck;
ALTER TABLE rhnActionDup
  ADD COLUMN IF NOT EXISTS allow_vendor_change CHAR(1) DEFAULT ('N') NOT NULL;
ALTER TABLE rhnActionDup ADD CONSTRAINT rhn_actiondup_avc_ck CHECK (allow_vendor_change in ('Y', 'N'));
   07070100000E6D000081B400000000000000000000000167AE111400002278000000000000000000000000000000000000006000000000susemanager-schema/upgrade/susemanager-schema-4.2.2-to-susemanager-schema-4.2.3/103-rpm.pkb.sql   -- oracle equivalent source sha1 539cb03eb177b7e87992701071488bbb32bb0624
-- create schema rpm;

--update pg_setting
update pg_settings set setting = 'rpm,' || setting where name = 'search_path';

create or replace function isdigit(ch CHAR)
    RETURNS BOOLEAN as $$
    BEGIN
        if ascii(ch) between ascii('0') and ascii('9')
        then
            return TRUE;
        end if;
        return FALSE;
    END ;
$$ language 'plpgsql';


    create or replace FUNCTION isalpha(ch CHAR)
    RETURNS BOOLEAN as $$
    BEGIN
        if ascii(ch) between ascii('a') and ascii('z') or
            ascii(ch) between ascii('A') and ascii('Z')
        then
            return TRUE;
        end if;
        return FALSE;
    END;
$$ language 'plpgsql';


    create or replace FUNCTION isalphanum(ch CHAR)
    RETURNS BOOLEAN as $$
    BEGIN
        if ascii(ch) between ascii('a') and ascii('z') or
            ascii(ch) between ascii('A') and ascii('Z') or
            ascii(ch) between ascii('0') and ascii('9')
        then
            return TRUE;
        end if;
        return FALSE;
    END;
    $$ language 'plpgsql';


    create or replace FUNCTION rpmstrcmp (string1 IN VARCHAR, string2 IN VARCHAR)
    RETURNS INTEGER as $$
    declare
        str1 VARCHAR := string1;
        str2 VARCHAR := string2;
        digits VARCHAR(10) := '0123456789';
        lc_alpha VARCHAR(27) := 'abcdefghijklmnopqrstuvwxyz';
        uc_alpha VARCHAR(27) := 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
        alpha VARCHAR(54) := lc_alpha || uc_alpha;
        one VARCHAR;
        two VARCHAR;
        debupstreamv1 VARCHAR;
        debupstreamv2 VARCHAR;
        debrevisionv1 VARCHAR;
        debrevisionv2 VARCHAR;
        isnum BOOLEAN;
    BEGIN
        if str1 is NULL or str2 is NULL
        then
            RAISE EXCEPTION 'VALUE_ERROR.';
        end if;

        if str1 = str2
        then
            return 0;
        end if;
        if POSITION('+' in str1) <> 0 AND POSITION('+' in str2) <> 0 AND POSITION('~' in str1) = 0 AND POSITION('~' in str2) = 0

        then
            str1 := SUBSTR(str1, 0, POSITION('+' in str1));
            str2 := SUBSTR(str2, 0, POSITION('+' in str2));
        end if;
        debupstreamv1 := str1;
        debupstreamv2 := str2;
        debrevisionv1 := '';
        debrevisionv2 := '';
        if POSITION('-' in str1) <> 0
        then
            debupstreamv1 := SUBSTR(str1, 0, POSITION('-' in str1));
        end if;
        if POSITION('-' in str2) <> 0
        then
            debupstreamv2 := SUBSTR(str2, 0, POSITION('-' in str2));
        end if;
        if (debupstreamv1 <> debupstreamv2)
        then
            str1 := debupstreamv1;
            str2 := debupstreamv2;
        else
            if POSITION('-' in str1) <> 0 AND POSITION('-' in str2) <> 0
            then
                debrevisionv1 := SUBSTR(str1, POSITION('-' in str1) + 1);
                debrevisionv2 := SUBSTR(str2, POSITION('-' in str2) + 1);
	    else
		return 0;
            end if;
            str1 := debrevisionv1;
            str2 := debrevisionv2;
        end if;
        one := str1;
        two := str2;

        <<segment_loop>>
        while one <> '' or two <> ''
        loop
            declare
                segm1 VARCHAR;
                segm2 VARCHAR;
                onechar CHAR(1);
                twochar CHAR(1);
            begin
                --raise notice 'Params: %, %',  one, two;
                -- Throw out all non-alphanum characters
                onechar := substr(one, 1, 1);
                twochar := substr(two, 1, 1);
                while one <> '' and not rpm.isalphanum(one) and onechar != '~' and onechar != '^'
                loop
                    one := substr(one, 2);
                end loop;
                while two <> '' and not rpm.isalphanum(two) and twochar != '~' and twochar != '^'
                loop
                    two := substr(two, 2);
                end loop;
                --raise notice 'new params: %, %', one, two;

                onechar := substr(one, 1, 1);
                twochar := substr(two, 1, 1);
                --raise notice 'new chars 1: %, %', onechar, twochar;
                /* handle the tilde separator, it sorts before everything else */
                if (onechar = '~' or twochar = '~')
                then
                    if (onechar != '~') then return 1; end if;
                    if (twochar != '~') then return -1; end if;
                    --raise notice 'passed tilde chars: %, %', onechar, twochar;
                    one := substr(one, 2);
                    two := substr(two, 2);
                    continue;
                end if;

                /*
                 * Handle caret separator. Concept is the same as tilde,
                 * except that if one of the strings ends (base version),
                 * the other is considered as higher version.
                 */
                onechar := substr(one, 1, 1);
                twochar := substr(two, 1, 1);
                --raise notice 'new chars 2: %, %', onechar, twochar;
                if (onechar = '^' or twochar = '^')
                then
                    if (one = '') then return -1; end if;
                    --raise notice 'passed caret chars 1: %, %', onechar, twochar;
                    if (two = '') then return 1; end if;
                    --raise notice 'passed caret chars 2: %, %', onechar, twochar;
                    if (onechar != '^') then return 1; end if;
                    --raise notice 'passed caret chars 3: %, %', onechar, twochar;
                    if (twochar != '^') then return -1; end if;
                    --raise notice 'passed caret chars 4: %, %', onechar, twochar;
                    one := substr(one, 2);
                    two := substr(two, 2);
                    continue;
                end if;

                if (not (one <> '' and two <> '')) then exit segment_loop; end if;

                str1 := one;
                str2 := two;
                if rpm.isdigit(str1) or rpm.isdigit(str2)
                then
                    str1 := ltrim(str1, digits);
                    str2 := ltrim(str2, digits);
                    isnum := true;
                else
                    str1 := ltrim(str1, alpha);
                    str2 := ltrim(str2, alpha);
                    isnum := false;
                end if;
                if str1 <> ''
                then segm1 := substr(one, 1, length(one) - length(str1));
                else segm1 := one;
                end if;

                if str2 <> ''
                then segm2 := substr(two, 1, length(two) - length(str2));
                else segm2 := two;
                end if;

                if isnum
                then
                    if segm1 = '' then return -1; end if;
                    if segm2 = '' then return 1; end if;

                    segm1 := ltrim(segm1, '0');
                    segm2 := ltrim(segm2, '0');

                    if segm1 = '' and segm2 <> ''
                    then
                        return -1;
                    end if;
                    if segm1 <> '' and segm2 = ''
                    then
                        return 1;
                    end if;
                    if length(segm1) < length(segm2) then return -1; end if;
                    if length(segm1) > length(segm2) then return 1; end if;
                end if;
                if segm1 < segm2 then return -1; end if;
                if segm1 > segm2 then return 1; end if;
               one := str1;
                two := str2;
            end;
        end loop segment_loop;

        if one = '' and two = '' then return 0; end if;
        if one = '' then return -1; end if;
        return 1;
    END ;
$$ language 'plpgsql';



   create or replace FUNCTION vercmp(
        e1 VARCHAR, v1 VARCHAR, r1 VARCHAR,
        e2 VARCHAR, v2 VARCHAR, r2 VARCHAR)
    RETURNS INTEGER as $$
    declare
        rc INTEGER;
          ep1 INTEGER;
          ep2 INTEGER;
          BEGIN
            if e1 is null or e1 = '' then
              ep1 := 0;
            else
              ep1 := e1::integer;
            end if;
            if e2 is null or e2 = '' then
              ep2 := 0;
            else
              ep2 := e2::integer;
            end if;
            -- Epochs are non-null; compare them
            if ep1 < ep2 then return -1; end if;
            if ep1 > ep2 then return 1; end if;
            rc := rpm.rpmstrcmp(v1, v2);
            if rc != 0 then return rc; end if;
           return rpm.rpmstrcmp(r1, r2);
         END;
         $$ language 'plpgsql';

-- restore the original setting
update pg_settings set setting = overlay( setting placing '' from 1 for (length('rpm')+1) ) where name = 'search_path';
07070100000E6E000081B400000000000000000000000167AE111400000206000000000000000000000000000000000000006400000000susemanager-schema/upgrade/susemanager-schema-4.2.2-to-susemanager-schema-4.2.3/104-rhnUserInfo.sql   --
-- Copyright (c) 2020 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--

alter table rhnUserInfo add column if not exists
    preferred_docs_locale VARCHAR(8);
  07070100000E6F000081B400000000000000000000000167AE111400000047000000000000000000000000000000000000006200000000susemanager-schema/upgrade/susemanager-schema-4.2.2-to-susemanager-schema-4.2.3/104-web-theme.sql ALTER TABLE rhnUserInfo ADD COLUMN IF NOT EXISTS web_theme VARCHAR(32); 07070100000E70000081B400000000000000000000000167AE1114000022D3000000000000000000000000000000000000006000000000susemanager-schema/upgrade/susemanager-schema-4.2.2-to-susemanager-schema-4.2.3/110-rpm.pkb.sql   -- oracle equivalent source sha1 539cb03eb177b7e87992701071488bbb32bb0624
-- create schema rpm;

--update pg_setting
update pg_settings set setting = 'rpm,' || setting where name = 'search_path';

create or replace function isdigit(ch CHAR)
    RETURNS BOOLEAN as $$
    BEGIN
        if ascii(ch) between ascii('0') and ascii('9')
        then
            return TRUE;
        end if;
        return FALSE;
    END ;
$$ language 'plpgsql';

    
    create or replace FUNCTION isalpha(ch CHAR)
    RETURNS BOOLEAN as $$
    BEGIN
        if ascii(ch) between ascii('a') and ascii('z') or 
            ascii(ch) between ascii('A') and ascii('Z')
        then
            return TRUE;
        end if;
        return FALSE;
    END;
$$ language 'plpgsql';


    create or replace FUNCTION isalphanum(ch CHAR)
    RETURNS BOOLEAN as $$ 
    BEGIN
        if ascii(ch) between ascii('a') and ascii('z') or 
            ascii(ch) between ascii('A') and ascii('Z') or
            ascii(ch) between ascii('0') and ascii('9')
        then
            return TRUE;
        end if;
        return FALSE;
    END;
    $$ language 'plpgsql';


    create or replace FUNCTION rpmstrcmp (string1 IN VARCHAR, string2 IN VARCHAR)
    RETURNS INTEGER as $$
    declare
        str1 VARCHAR := string1;
        str2 VARCHAR := string2;
        digits VARCHAR(10) := '0123456789';
        lc_alpha VARCHAR(27) := 'abcdefghijklmnopqrstuvwxyz';
        uc_alpha VARCHAR(27) := 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
        alpha VARCHAR(54) := lc_alpha || uc_alpha;
        one VARCHAR;
        two VARCHAR;
        debupstreamv1 VARCHAR;
        debupstreamv2 VARCHAR;
        debrevisionv1 VARCHAR;
        debrevisionv2 VARCHAR;
        isnum BOOLEAN;
    BEGIN
        if str1 is NULL or str2 is NULL
        then
            RAISE EXCEPTION 'VALUE_ERROR.';
        end if;
      
        if str1 = str2
        then
            return 0;
        end if;
        if POSITION('+' in str1) <> 0 AND POSITION('+' in str2) <> 0 AND POSITION('~' in str1) = 0 AND POSITION('~' in str2) = 0 AND POSITION('.module' in str1) = 0 AND POSITION('.module' in str2) = 0
        then
            str1 := SUBSTR(str1, 0, POSITION('+' in str1));
            str2 := SUBSTR(str2, 0, POSITION('+' in str2));
        end if;
        debupstreamv1 := str1;
        debupstreamv2 := str2;
        debrevisionv1 := '';
        debrevisionv2 := '';
        if POSITION('-' in str1) <> 0
        then
            debupstreamv1 := SUBSTR(str1, 0, POSITION('-' in str1));
        end if;
        if POSITION('-' in str2) <> 0
        then
            debupstreamv2 := SUBSTR(str2, 0, POSITION('-' in str2));
        end if;
        if (debupstreamv1 <> debupstreamv2)
        then
            str1 := debupstreamv1;
            str2 := debupstreamv2;
        else
            if POSITION('-' in str1) <> 0 AND POSITION('-' in str2) <> 0
            then
                debrevisionv1 := SUBSTR(str1, POSITION('-' in str1) + 1);
                debrevisionv2 := SUBSTR(str2, POSITION('-' in str2) + 1);
	    else
		return 0;
            end if;
            str1 := debrevisionv1;
            str2 := debrevisionv2;
        end if;
        one := str1;
        two := str2;

        <<segment_loop>>
        while one <> '' or two <> ''
        loop
            declare
                segm1 VARCHAR;
                segm2 VARCHAR;
                onechar CHAR(1);
                twochar CHAR(1);
            begin
                --raise notice 'Params: %, %',  one, two;
                -- Throw out all non-alphanum characters
                onechar := substr(one, 1, 1);
                twochar := substr(two, 1, 1);
                while one <> '' and not rpm.isalphanum(one) and onechar != '~' and onechar != '^'
                loop
                    one := substr(one, 2);
                end loop;
                while two <> '' and not rpm.isalphanum(two) and twochar != '~' and twochar != '^'
                loop
                    two := substr(two, 2);
                end loop;
                --raise notice 'new params: %, %', one, two;

                onechar := substr(one, 1, 1);
                twochar := substr(two, 1, 1);
                --raise notice 'new chars 1: %, %', onechar, twochar;
                /* handle the tilde separator, it sorts before everything else */
                if (onechar = '~' or twochar = '~')
                then
                    if (onechar != '~') then return 1; end if;
                    if (twochar != '~') then return -1; end if;
                    --raise notice 'passed tilde chars: %, %', onechar, twochar;
                    one := substr(one, 2);
                    two := substr(two, 2);
                    continue;
                end if;

                /*
                 * Handle caret separator. Concept is the same as tilde,
                 * except that if one of the strings ends (base version),
                 * the other is considered as higher version.
                 */
                onechar := substr(one, 1, 1);
                twochar := substr(two, 1, 1);
                --raise notice 'new chars 2: %, %', onechar, twochar;
                if (onechar = '^' or twochar = '^')
                then
                    if (one = '') then return -1; end if;
                    --raise notice 'passed caret chars 1: %, %', onechar, twochar;
                    if (two = '') then return 1; end if;
                    --raise notice 'passed caret chars 2: %, %', onechar, twochar;
                    if (onechar != '^') then return 1; end if;
                    --raise notice 'passed caret chars 3: %, %', onechar, twochar;
                    if (twochar != '^') then return -1; end if;
                    --raise notice 'passed caret chars 4: %, %', onechar, twochar;
                    one := substr(one, 2);
                    two := substr(two, 2);
                    continue;
                end if;

                if (not (one <> '' and two <> '')) then exit segment_loop; end if;

                str1 := one;
                str2 := two;
                if rpm.isdigit(str1) or rpm.isdigit(str2)
                then
                    str1 := ltrim(str1, digits);
                    str2 := ltrim(str2, digits);
                    isnum := true;
                else
                    str1 := ltrim(str1, alpha);
                    str2 := ltrim(str2, alpha);
                    isnum := false;
                end if;
                if str1 <> ''
                then segm1 := substr(one, 1, length(one) - length(str1));
                else segm1 := one;
                end if;

                if str2 <> ''
                then segm2 := substr(two, 1, length(two) - length(str2));
                else segm2 := two;
                end if;

                if isnum
                then
                    if segm1 = '' then return -1; end if;
                    if segm2 = '' then return 1; end if;

                    segm1 := ltrim(segm1, '0');
                    segm2 := ltrim(segm2, '0');

                    if segm1 = '' and segm2 <> ''
                    then
                        return -1;
                    end if;
                    if segm1 <> '' and segm2 = ''
                    then
                        return 1;
                    end if;
                    if length(segm1) < length(segm2) then return -1; end if;
                    if length(segm1) > length(segm2) then return 1; end if;
                end if;
                if segm1 < segm2 then return -1; end if;
                if segm1 > segm2 then return 1; end if;
               one := str1;
                two := str2;
            end;
        end loop segment_loop;
     
        if one = '' and two = '' then return 0; end if;
        if one = '' then return -1; end if;
        return 1;
    END ;
$$ language 'plpgsql';



   create or replace FUNCTION vercmp(
        e1 VARCHAR, v1 VARCHAR, r1 VARCHAR, 
        e2 VARCHAR, v2 VARCHAR, r2 VARCHAR)
    RETURNS INTEGER as $$
    declare
        rc INTEGER;
          ep1 INTEGER;
          ep2 INTEGER;
          BEGIN
            if e1 is null or e1 = '' then
              ep1 := 0;
            else
              ep1 := e1::integer;
            end if;
            if e2 is null or e2 = '' then
              ep2 := 0;
            else
              ep2 := e2::integer;
            end if;
            -- Epochs are non-null; compare them
            if ep1 < ep2 then return -1; end if;
            if ep1 > ep2 then return 1; end if;
            rc := rpm.rpmstrcmp(v1, v2);
            if rc != 0 then return rc; end if;
           return rpm.rpmstrcmp(r1, r2);
         END;
         $$ language 'plpgsql';

-- restore the original setting
update pg_settings set setting = overlay( setting placing '' from 1 for (length('rpm')+1) ) where name = 'search_path';

 07070100000E71000081B400000000000000000000000167AE111400000403000000000000000000000000000000000000007000000000susemanager-schema/upgrade/susemanager-schema-4.2.2-to-susemanager-schema-4.2.3/200-minionSSHActionExecutor.sql   INSERT INTO rhnTaskoBunch (id, name, description, org_bunch)
SELECT sequence_nextval('rhn_tasko_bunch_id_seq'), 'ssh-minion-action-executor-bunch', 'Execute actions on SSH Minions', null
WHERE NOT EXISTS (
    SELECT 1 FROM rhnTaskoBunch WHERE name='ssh-minion-action-executor-bunch'
);

INSERT INTO rhnTaskoTask (id, name, class)
SELECT sequence_nextval('rhn_tasko_task_id_seq'), 'ssh-minion-action-executor', 'com.redhat.rhn.taskomatic.task.SSHMinionActionExecutor'
WHERE NOT EXISTS (
    SELECT 1 FROM rhnTaskoTask WHERE name='ssh-minion-action-executor'
);

INSERT INTO rhnTaskoTemplate (id, bunch_id, task_id, ordering, start_if)
SELECT sequence_nextval('rhn_tasko_template_id_seq'),
        (SELECT id FROM rhnTaskoBunch WHERE name='ssh-minion-action-executor-bunch'),
        (SELECT id FROM rhnTaskoTask WHERE name='ssh-minion-action-executor'),
        0,
        null
WHERE NOT EXISTS (
    SELECT 1 FROM rhnTaskoTemplate WHERE bunch_id=(SELECT id FROM rhnTaskoBunch WHERE name='ssh-minion-action-executor-bunch')
);
 07070100000E72000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005100000000susemanager-schema/upgrade/susemanager-schema-4.2.20-to-susemanager-schema-4.3.0  07070100000E73000081B400000000000000000000000167AE111400000000000000000000000000000000000000000000005A00000000susemanager-schema/upgrade/susemanager-schema-4.2.20-to-susemanager-schema-4.3.0/.gitkeep 07070100000E74000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005100000000susemanager-schema/upgrade/susemanager-schema-4.2.21-to-susemanager-schema-4.3.0  07070100000E75000081B400000000000000000000000167AE111400000000000000000000000000000000000000000000005A00000000susemanager-schema/upgrade/susemanager-schema-4.2.21-to-susemanager-schema-4.3.0/.gitkeep 07070100000E76000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005100000000susemanager-schema/upgrade/susemanager-schema-4.2.22-to-susemanager-schema-4.3.0  07070100000E77000081B400000000000000000000000167AE111400000000000000000000000000000000000000000000005A00000000susemanager-schema/upgrade/susemanager-schema-4.2.22-to-susemanager-schema-4.3.0/.gitkeep 07070100000E78000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005100000000susemanager-schema/upgrade/susemanager-schema-4.2.23-to-susemanager-schema-4.3.0  07070100000E79000081B400000000000000000000000167AE111400000000000000000000000000000000000000000000005A00000000susemanager-schema/upgrade/susemanager-schema-4.2.23-to-susemanager-schema-4.3.0/.gitkeep 07070100000E7A000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005100000000susemanager-schema/upgrade/susemanager-schema-4.2.24-to-susemanager-schema-4.3.0  07070100000E7B000081B400000000000000000000000167AE111400000000000000000000000000000000000000000000005A00000000susemanager-schema/upgrade/susemanager-schema-4.2.24-to-susemanager-schema-4.3.0/.gitkeep 07070100000E7C000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005100000000susemanager-schema/upgrade/susemanager-schema-4.2.25-to-susemanager-schema-4.3.0  07070100000E7D000081B400000000000000000000000167AE111400000000000000000000000000000000000000000000005A00000000susemanager-schema/upgrade/susemanager-schema-4.2.25-to-susemanager-schema-4.3.0/.gitkeep 07070100000E7E000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005100000000susemanager-schema/upgrade/susemanager-schema-4.2.26-to-susemanager-schema-4.3.0  07070100000E7F000081B400000000000000000000000167AE111400000000000000000000000000000000000000000000005A00000000susemanager-schema/upgrade/susemanager-schema-4.2.26-to-susemanager-schema-4.3.0/.gitkeep 07070100000E80000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005100000000susemanager-schema/upgrade/susemanager-schema-4.2.27-to-susemanager-schema-4.3.0  07070100000E81000081B400000000000000000000000167AE111400000000000000000000000000000000000000000000005A00000000susemanager-schema/upgrade/susemanager-schema-4.2.27-to-susemanager-schema-4.3.0/.gitkeep 07070100000E82000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005100000000susemanager-schema/upgrade/susemanager-schema-4.2.28-to-susemanager-schema-4.3.0  07070100000E83000081B400000000000000000000000167AE111400000000000000000000000000000000000000000000005A00000000susemanager-schema/upgrade/susemanager-schema-4.2.28-to-susemanager-schema-4.3.0/.gitkeep 07070100000E84000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005100000000susemanager-schema/upgrade/susemanager-schema-4.2.29-to-susemanager-schema-4.3.0  07070100000E85000081B400000000000000000000000167AE111400000000000000000000000000000000000000000000005A00000000susemanager-schema/upgrade/susemanager-schema-4.2.29-to-susemanager-schema-4.3.0/.gitkeep 07070100000E86000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005000000000susemanager-schema/upgrade/susemanager-schema-4.2.3-to-susemanager-schema-4.2.4   07070100000E87000081B400000000000000000000000167AE1114000000BD000000000000000000000000000000000000006600000000susemanager-schema/upgrade/susemanager-schema-4.2.3-to-susemanager-schema-4.2.4/001-new-countries.sql insert into valid_countries(code,short_name,name) ( 
  select 'RS', 'Serbia', 'Republic of Serbia' from dual
   where not exists (
	select 1 from valid_countries where code = 'RS'
   )
);

   07070100000E88000081B400000000000000000000000167AE1114000002E1000000000000000000000000000000000000006600000000susemanager-schema/upgrade/susemanager-schema-4.2.3-to-susemanager-schema-4.2.4/002-new-timezones.sql insert into rhnTimezone(id, olson_name, display_name) ( 
  select sequence_nextval('rhn_timezone_id_seq'), 'Asia/Jerusalem', 'Israel'
    from dual
   where not exists (
	select 1 from rhnTimezone where olson_name = 'Asia/Jerusalem'
   )
);

insert into rhnTimezone(id, olson_name, display_name) ( 
  select sequence_nextval('rhn_timezone_id_seq'), 'Asia/Singapore', 'Singapore'
    from dual
   where not exists (
	select 1 from rhnTimezone where olson_name = 'Asia/Singapore'
   )
);

insert into rhnTimezone(id, olson_name, display_name) ( 
  select sequence_nextval('rhn_timezone_id_seq'), 'Asia/Kuala_Lumpur', 'Malaysia'
    from dual
   where not exists (
	select 1 from rhnTimezone where olson_name = 'Asia/Kuala_Lumpur'
   )
);

   07070100000E89000081B400000000000000000000000167AE1114000000D9000000000000000000000000000000000000007200000000susemanager-schema/upgrade/susemanager-schema-4.2.3-to-susemanager-schema-4.2.4/003-add-virtual-instance-type.sql INSERT INTO rhnVirtualInstanceType (id, name, label)
  SELECT sequence_nextval('rhn_vit_id_seq'), 'VirtualPC', 'virtualpc'
  FROM dual
  WHERE NOT EXISTS(select 1 from rhnVirtualInstanceType WHERE label='virtualpc');
   07070100000E8A000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005100000000susemanager-schema/upgrade/susemanager-schema-4.2.30-to-susemanager-schema-4.3.0  07070100000E8B000081B400000000000000000000000167AE111400000000000000000000000000000000000000000000005A00000000susemanager-schema/upgrade/susemanager-schema-4.2.30-to-susemanager-schema-4.3.0/.gitkeep 07070100000E8C000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005100000000susemanager-schema/upgrade/susemanager-schema-4.2.31-to-susemanager-schema-4.3.0  07070100000E8D000081B400000000000000000000000167AE111400000000000000000000000000000000000000000000005A00000000susemanager-schema/upgrade/susemanager-schema-4.2.31-to-susemanager-schema-4.3.0/.gitkeep 07070100000E8E000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005100000000susemanager-schema/upgrade/susemanager-schema-4.2.32-to-susemanager-schema-4.3.0  07070100000E8F000081B400000000000000000000000167AE111400000000000000000000000000000000000000000000005A00000000susemanager-schema/upgrade/susemanager-schema-4.2.32-to-susemanager-schema-4.3.0/.gitkeep 07070100000E90000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005100000000susemanager-schema/upgrade/susemanager-schema-4.2.33-to-susemanager-schema-4.3.0  07070100000E91000081B400000000000000000000000167AE111400000000000000000000000000000000000000000000005A00000000susemanager-schema/upgrade/susemanager-schema-4.2.33-to-susemanager-schema-4.3.0/.gitkeep 07070100000E92000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005100000000susemanager-schema/upgrade/susemanager-schema-4.2.34-to-susemanager-schema-4.3.0  07070100000E93000081B400000000000000000000000167AE111400000000000000000000000000000000000000000000005A00000000susemanager-schema/upgrade/susemanager-schema-4.2.34-to-susemanager-schema-4.3.0/.gitkeep 07070100000E94000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005100000000susemanager-schema/upgrade/susemanager-schema-4.2.35-to-susemanager-schema-4.3.0  07070100000E95000081B400000000000000000000000167AE111400000000000000000000000000000000000000000000005A00000000susemanager-schema/upgrade/susemanager-schema-4.2.35-to-susemanager-schema-4.3.0/.gitkeep 07070100000E96000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005100000000susemanager-schema/upgrade/susemanager-schema-4.2.36-to-susemanager-schema-4.3.0  07070100000E97000081B400000000000000000000000167AE111400000000000000000000000000000000000000000000005A00000000susemanager-schema/upgrade/susemanager-schema-4.2.36-to-susemanager-schema-4.3.0/.gitkeep 07070100000E98000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005100000000susemanager-schema/upgrade/susemanager-schema-4.2.37-to-susemanager-schema-4.3.0  07070100000E99000081B400000000000000000000000167AE111400000000000000000000000000000000000000000000005A00000000susemanager-schema/upgrade/susemanager-schema-4.2.37-to-susemanager-schema-4.3.0/.gitkeep 07070100000E9A000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005100000000susemanager-schema/upgrade/susemanager-schema-4.2.38-to-susemanager-schema-4.3.0  07070100000E9B000081B400000000000000000000000167AE111400000000000000000000000000000000000000000000005A00000000susemanager-schema/upgrade/susemanager-schema-4.2.38-to-susemanager-schema-4.3.0/.gitkeep 07070100000E9C000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005100000000susemanager-schema/upgrade/susemanager-schema-4.2.39-to-susemanager-schema-4.3.0  07070100000E9D000081B400000000000000000000000167AE111400000000000000000000000000000000000000000000005A00000000susemanager-schema/upgrade/susemanager-schema-4.2.39-to-susemanager-schema-4.3.0/.gitkeep 07070100000E9E000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005000000000susemanager-schema/upgrade/susemanager-schema-4.2.4-to-susemanager-schema-4.2.5   07070100000E9F000081B400000000000000000000000167AE111400001820000000000000000000000000000000000000006000000000susemanager-schema/upgrade/susemanager-schema-4.2.4-to-susemanager-schema-4.2.5/700-deb.pkb.sql   -- oracle equivalent source sha1 539cb03eb177b7e87992701071488bbb32bb0624
create schema if not exists deb;

--update pg_setting
update pg_settings set setting = 'deb,' || setting where name = 'search_path';

-- Debian version comparison
-- See: https://www.debian.org/doc/debian-policy/ch-controlfields.html#version
-- See: https://salsa.debian.org/dpkg-team/dpkg/blob/master/lib/dpkg/version.c#L140

CREATE OR REPLACE FUNCTION lastIndexOf(needle text, haystack text)
RETURNS integer AS $$
    DECLARE
        rc INTEGER;
    BEGIN
     rc := length(haystack) - position(needle in reverse(haystack));
     if rc = length(haystack) then rc = -1; end if;
     return rc;
    END;
$$ language 'plpgsql';

create or replace function isdigit(ch CHAR)
    RETURNS BOOLEAN as $$
    BEGIN
        if ascii(ch) between ascii('0') and ascii('9')
        then
            return TRUE;
        end if;
        return FALSE;
    END ;
$$ language 'plpgsql';


create or replace FUNCTION isalpha(ch CHAR)
    RETURNS BOOLEAN as $$
    BEGIN
        if ascii(ch) between ascii('a') and ascii('z') or
            ascii(ch) between ascii('A') and ascii('Z')
        then
            return TRUE;
        end if;
        return FALSE;
    END;
$$ language 'plpgsql';

create or replace FUNCTION charAt(str IN VARCHAR, pos IN INTEGER)
    RETURNS CHARACTER as $$
    BEGIN
        return SUBSTR(str, pos + 1, 1);
    END;
$$ language 'plpgsql';

create or replace function deborder(c INTEGER)
    RETURNS INTEGER as $$
    BEGIN
        if deb.isdigit(chr(c)) then return 0; end if;
        if deb.isalpha(chr(c)) then return c; end if;
        if c = ascii('~') then return -1; end if;
        if c != 0 then return c + 256; end if;
        return 0;
    END ;
$$ language 'plpgsql';

create or replace FUNCTION verrevcmp(a1 IN VARCHAR, b1 IN VARCHAR)
    RETURNS INTEGER as $$
    DECLARE
        a VARCHAR;
        b VARCHAR;
        i INTEGER := 0;
        j INTEGER := 0;
    BEGIN
        IF a1 IS NULL then a := ''; end if;
        IF b1 IS NULL then b := ''; end if;
        a := a1;
        b := b1;
        WHILE (i < LENGTH(a)) or (j < LENGTH(b))
        LOOP
            DECLARE
                firstDiff INTEGER := 0;
            BEGIN
                while ((i < LENGTH(a)) and not deb.isdigit(deb.charAt(a,i))) or ((j < LENGTH(b)) and not deb.isdigit(deb.charAt(b,j)))
                LOOP
                DECLARE
                    ac INTEGER;
                    bc INTEGER;
                BEGIN
                    if i >= length(a)
                    then
                        ac := 0;
                    else
                        ac := deb.deborder(ascii(deb.charAt(a, i)));
                    end if;
                    if j >= length(b)
                    then
                        bc := 0;
                    else
                        bc := deb.deborder(ascii(deb.charAt(b, j)));
                    end if;
                    if ac != bc then return ac-bc; end if;
                    i := i + 1;
                    j := j + 1;
                END;
                END LOOP;
                while (i < length(a)) and (deb.charAt(a, i) = '0')
                LOOP
                    i := i + 1;
                END LOOP;
                while (j < length(b)) and (deb.charAt(b, j) = '0')
                LOOP
                    j := j + 1;
                END LOOP;
                WHILE (i < LENGTH(a)) and (j < LENGTH(b)) and (deb.isdigit(deb.charAt(a,i))) and (deb.isdigit(deb.charAt(b, j)))
                LOOP
                    if firstDiff = 0 then firstDiff := ascii(deb.charAt(a, i)) - ascii(deb.charAt(b, j)); end if;
                    i := i + 1;
                    j := j + 1;
                END LOOP;
                IF (i < LENGTH(a)) and (deb.isdigit(deb.charAt(a,i))) then return 1; end if;
                IF (j < LENGTH(b)) and (deb.isdigit(deb.charAt(b,j))) then return -1; end if;
                IF firstDiff != 0 then return firstDiff; end if;
            END;
        END LOOP;
        RETURN 0;
    END;
$$ language 'plpgsql';

create or replace FUNCTION debstrcmp (o1 IN VARCHAR, o2 IN VARCHAR)
    RETURNS INTEGER as $$
    declare
        version1 VARCHAR := o1;
        version2 VARCHAR := o2;
        revision1 VARCHAR;
        revision2 VARCHAR;
        rc INTEGER;
        rv INTEGER;
    BEGIN
        IF deb.lastIndexOf('-', version1) > 0
        then
            revision1 := SUBSTR(version1, POSITION('-' IN version1) + 1);
            version1 := SUBSTR(version1, 0, POSITION('-' IN version1));
        end if;
        IF deb.lastIndexOf('-',version2) > 0
        then
            revision2 := SUBSTR(version2, POSITION('-' IN version2) + 1);
            version2 := SUBSTR(version2, 0, POSITION('-' IN version2));
        end if;
        rc := deb.verrevcmp(version1, version2);
        if rc > 0 then return 1; end if;
        if rc < 0 then return -1; end if;
        if rc = 0
        then
            rv := deb.verrevcmp(revision1, revision2);
            if rv > 0 then return 1; end if;
            if rv < 0 then return -1; end if;
            return 0;
        end if;
    END;
$$ language 'plpgsql';

create or replace FUNCTION debvercmp(
        e1 VARCHAR, v1 VARCHAR, r1 VARCHAR,
        e2 VARCHAR, v2 VARCHAR, r2 VARCHAR)
    RETURNS INTEGER as $$
    declare
        rc INTEGER;
          ep1 INTEGER;
          ep2 INTEGER;
          BEGIN
            if e1 is null or e1 = '' then
              ep1 := 0;
            else
              ep1 := e1::integer;
            end if;
            if e2 is null or e2 = '' then
              ep2 := 0;
            else
              ep2 := e2::integer;
            end if;
            -- Epochs are non-null; compare them
            if ep1 < ep2 then return -1; end if;
            if ep1 > ep2 then return 1; end if;
            rc := deb.debstrcmp(v1, v2);
            if rc != 0 then return rc; end if;
           return deb.debstrcmp(r1, r2);
         END;
         $$ language 'plpgsql';

-- restore the original setting
update pg_settings set setting = overlay( setting placing '' from 1 for (length('deb')+1) ) where name = 'search_path';
07070100000EA0000081B400000000000000000000000167AE111400001D77000000000000000000000000000000000000006000000000susemanager-schema/upgrade/susemanager-schema-4.2.4-to-susemanager-schema-4.2.5/701-rpm.pkb.sql   -- oracle equivalent source sha1 539cb03eb177b7e87992701071488bbb32bb0624
-- create schema rpm;

--update pg_setting
update pg_settings set setting = 'rpm,' || setting where name = 'search_path';

create or replace function isdigit(ch CHAR)
    RETURNS BOOLEAN as $$
    BEGIN
        if ascii(ch) between ascii('0') and ascii('9')
        then
            return TRUE;
        end if;
        return FALSE;
    END ;
$$ language 'plpgsql';

    
    create or replace FUNCTION isalpha(ch CHAR)
    RETURNS BOOLEAN as $$
    BEGIN
        if ascii(ch) between ascii('a') and ascii('z') or 
            ascii(ch) between ascii('A') and ascii('Z')
        then
            return TRUE;
        end if;
        return FALSE;
    END;
$$ language 'plpgsql';


    create or replace FUNCTION isalphanum(ch CHAR)
    RETURNS BOOLEAN as $$ 
    BEGIN
        if ascii(ch) between ascii('a') and ascii('z') or 
            ascii(ch) between ascii('A') and ascii('Z') or
            ascii(ch) between ascii('0') and ascii('9')
        then
            return TRUE;
        end if;
        return FALSE;
    END;
    $$ language 'plpgsql';


    create or replace FUNCTION rpmstrcmp (string1 IN VARCHAR, string2 IN VARCHAR)
    RETURNS INTEGER as $$
    declare
        str1 VARCHAR := string1;
        str2 VARCHAR := string2;
        digits VARCHAR(10) := '0123456789';
        lc_alpha VARCHAR(27) := 'abcdefghijklmnopqrstuvwxyz';
        uc_alpha VARCHAR(27) := 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
        alpha VARCHAR(54) := lc_alpha || uc_alpha;
        one VARCHAR;
        two VARCHAR;
        isnum BOOLEAN;
    BEGIN
        if str1 is NULL or str2 is NULL
        then
            RAISE EXCEPTION 'VALUE_ERROR.';
        end if;
      
        if str1 = str2
        then
            return 0;
        end if;
        one := str1;
        two := str2;

        <<segment_loop>>
        while one <> '' or two <> ''
        loop
            declare
                segm1 VARCHAR;
                segm2 VARCHAR;
                onechar CHAR(1);
                twochar CHAR(1);
            begin
                --raise notice 'Params: %, %',  one, two;
                -- Throw out all non-alphanum characters
                onechar := substr(one, 1, 1);
                twochar := substr(two, 1, 1);
                while one <> '' and not rpm.isalphanum(one) and onechar != '~' and onechar != '^'
                loop
                    one := substr(one, 2);
                end loop;
                while two <> '' and not rpm.isalphanum(two) and twochar != '~' and twochar != '^'
                loop
                    two := substr(two, 2);
                end loop;
                --raise notice 'new params: %, %', one, two;

                onechar := substr(one, 1, 1);
                twochar := substr(two, 1, 1);
                --raise notice 'new chars 1: %, %', onechar, twochar;
                /* handle the tilde separator, it sorts before everything else */
                if (onechar = '~' or twochar = '~')
                then
                    if (onechar != '~') then return 1; end if;
                    if (twochar != '~') then return -1; end if;
                    --raise notice 'passed tilde chars: %, %', onechar, twochar;
                    one := substr(one, 2);
                    two := substr(two, 2);
                    continue;
                end if;

                /*
                 * Handle caret separator. Concept is the same as tilde,
                 * except that if one of the strings ends (base version),
                 * the other is considered as higher version.
                 */
                onechar := substr(one, 1, 1);
                twochar := substr(two, 1, 1);
                --raise notice 'new chars 2: %, %', onechar, twochar;
                if (onechar = '^' or twochar = '^')
                then
                    if (one = '') then return -1; end if;
                    --raise notice 'passed caret chars 1: %, %', onechar, twochar;
                    if (two = '') then return 1; end if;
                    --raise notice 'passed caret chars 2: %, %', onechar, twochar;
                    if (onechar != '^') then return 1; end if;
                    --raise notice 'passed caret chars 3: %, %', onechar, twochar;
                    if (twochar != '^') then return -1; end if;
                    --raise notice 'passed caret chars 4: %, %', onechar, twochar;
                    one := substr(one, 2);
                    two := substr(two, 2);
                    continue;
                end if;

                if (not (one <> '' and two <> '')) then exit segment_loop; end if;

                str1 := one;
                str2 := two;
                if rpm.isdigit(str1) or rpm.isdigit(str2)
                then
                    str1 := ltrim(str1, digits);
                    str2 := ltrim(str2, digits);
                    isnum := true;
                else
                    str1 := ltrim(str1, alpha);
                    str2 := ltrim(str2, alpha);
                    isnum := false;
                end if;
                if str1 <> ''
                then segm1 := substr(one, 1, length(one) - length(str1));
                else segm1 := one;
                end if;

                if str2 <> ''
                then segm2 := substr(two, 1, length(two) - length(str2));
                else segm2 := two;
                end if;

                if isnum
                then
                    if segm1 = '' then return -1; end if;
                    if segm2 = '' then return 1; end if;

                    segm1 := ltrim(segm1, '0');
                    segm2 := ltrim(segm2, '0');

                    if segm1 = '' and segm2 <> ''
                    then
                        return -1;
                    end if;
                    if segm1 <> '' and segm2 = ''
                    then
                        return 1;
                    end if;
                    if length(segm1) < length(segm2) then return -1; end if;
                    if length(segm1) > length(segm2) then return 1; end if;
                end if;
                if segm1 < segm2 then return -1; end if;
                if segm1 > segm2 then return 1; end if;
               one := str1;
                two := str2;
            end;
        end loop segment_loop;
     
        if one = '' and two = '' then return 0; end if;
        if one = '' then return -1; end if;
        return 1;
    END ;
$$ language 'plpgsql';



   create or replace FUNCTION vercmp(
        e1 VARCHAR, v1 VARCHAR, r1 VARCHAR, 
        e2 VARCHAR, v2 VARCHAR, r2 VARCHAR)
    RETURNS INTEGER as $$
    declare
        rc INTEGER;
          ep1 INTEGER;
          ep2 INTEGER;
          BEGIN
            if e1 is null or e1 = '' then
              ep1 := 0;
            else
              ep1 := e1::integer;
            end if;
            if e2 is null or e2 = '' then
              ep2 := 0;
            else
              ep2 := e2::integer;
            end if;
            -- Epochs are non-null; compare them
            if ep1 < ep2 then return -1; end if;
            if ep1 > ep2 then return 1; end if;
            rc := rpm.rpmstrcmp(v1, v2);
            if rc != 0 then return rc; end if;
           return rpm.rpmstrcmp(r1, r2);
         END;
         $$ language 'plpgsql';

-- restore the original setting
update pg_settings set setting = overlay( setting placing '' from 1 for (length('rpm')+1) ) where name = 'search_path';

 07070100000EA1000081B400000000000000000000000167AE111400005FF8000000000000000000000000000000000000006200000000susemanager-schema/upgrade/susemanager-schema-4.2.4-to-susemanager-schema-4.2.5/702-debvercmp.sql DO $$
BEGIN
    IF NOT EXISTS (
        SELECT 1
        FROM pg_type t
        JOIN pg_class c ON c.oid = t.typrelid
        JOIN pg_attribute a ON a.attrelid = c.oid
        WHERE t.typname = 'evr_t'
        AND a.attname = 'type'
        )
    THEN
        alter type evr_t add attribute type varchar(10);
    END IF;
END $$;

drop index if exists rhn_pe_v_r_e_uq;
create unique index rhn_pe_v_r_e_uq
    on rhnpackageevr (version, release, epoch, ((evr).type))
 where epoch is not null;

drop index if exists rhn_pe_v_r_uq;
create unique index rhn_pe_v_r_uq
    on rhnpackageevr (version, release, ((evr).type))
 where epoch is null;

create or replace function evr_t(e varchar, v varchar, r varchar, t varchar)
returns evr_t as $$
select row($1,$2,$3,$4)::evr_t
$$ language sql;


-- update evr_t comparison function to take type into account.
create or replace function evr_t_compare( a evr_t, b evr_t )
returns int as $$
begin
  if a.type = b.type then
      if a.type = 'rpm' then
        return rpm.vercmp(a.epoch, a.version, a.release, b.epoch, b.version, b.release);
      elsif a.type = 'deb' then
        return deb.debvercmp(a.epoch, a.version, a.release, b.epoch, b.version, b.release);
      else
        raise EXCEPTION 'unknown evr type (using rpm) -> %', a.type;
      end if;
  else
     raise NOTICE 'comparing incompatible evr types. Using %', a.type;
     if a.type = 'deb' then
       return -1;
     else
       return 1;
     end if;
  end if;
end;
$$ language plpgsql immutable strict;


create or replace function evr_t_ne( a evr_t, b evr_t )
returns boolean as $$
begin
  return evr_t_compare( a, b ) != 0;
end;
$$ language plpgsql immutable strict;

drop operator if exists <> (evr_t, evr_t);
create operator <> (
  leftarg = evr_t,
  rightarg = evr_t,
  procedure = evr_t_ne,
  commutator = <>,
  negator = =,
  restrict = eqsel,
  join = eqjoinsel
);


-- update insert_evr
create or replace function
insert_evr(e_in in varchar, v_in in varchar, r_in in varchar, t_in in varchar)
returns numeric
as
$$
declare
    evr_id  numeric;
begin
    evr_id := nextval('rhn_pkg_evr_seq');

    insert into rhnPackageEVR(id, epoch, version, release, evr)
        values (evr_id, e_in, v_in, r_in, evr_t(e_in, v_in, r_in, t_in))
        on conflict do nothing;

    select id
        into strict evr_id
        from rhnPackageEVR
        where ((epoch is null and e_in is null) or (epoch = e_in)) and
           version = v_in and release = r_in and (evr).type = t_in;

    return evr_id;
end;
$$ language plpgsql;


-- update lookup_evr
create or replace function
lookup_evr(e_in in varchar, v_in in varchar, r_in in varchar, t_in in varchar)
returns numeric
as
$$
declare
    evr_id  numeric;
begin
    select id
      into evr_id
      from rhnPackageEVR
     where ((epoch is null and e_in is null) or (epoch = e_in)) and
           version = v_in and
           release = r_in and
           (evr).type = t_in;

    if not found then
        -- HACK: insert is isolated in own function in order to be able to declare this function immutable
        -- Postgres optimizes immutable functions calls but those are compatible with the contract of lookup_\*
        -- see https://www.postgresql.org/docs/9.6/xfunc-volatility.html
        return insert_evr(e_in, v_in, r_in, t_in);
    end if;

    return evr_id;
end;
$$ language plpgsql immutable;


create or replace function
lookup_transaction_package(
    o_in in varchar,
    n_in in varchar,
    e_in in varchar,
    v_in in varchar,
    r_in in varchar,
    a_in in varchar)
returns numeric
as
$$
declare
    o_id        numeric;
    n_id        numeric;
    e_id        numeric;
    p_arch_id   numeric;
    tp_id       numeric;
    type        varchar;
begin
    select id
      into o_id
      from rhnTransactionOperation
     where label = o_in;

    if not found then
        perform rhn_exception.raise_exception('invalid_transaction_operation');
    end if;

    n_id := lookup_package_name(n_in);
    p_arch_id := null;

    if a_in is not null then
        p_arch_id := lookup_package_arch(a_in);
        SELECT t.label into type from rhnpackagearch pa join rhnarchtype t
         on t.id = pa.arch_type_id where pa.id = p_arch_id;
    else
        -- currently only used with kickstart and this is supported for Red Hat only
        type := 'rpm';
    end if;

    e_id := lookup_evr(e_in, v_in, r_in, type);

    select id
      into tp_id
      from rhnTransactionPackage
     where operation = o_id and
           name_id = n_id and
           evr_id = e_id and
           (package_arch_id = p_arch_id or (p_arch_id is null and package_arch_id is null));

    if not found then
        -- HACK: insert is isolated in own function in order to be able to declare this function immutable
        -- Postgres optimizes immutable functions calls but those are compatible with the contract of lookup_\*
        -- see https://www.postgresql.org/docs/9.6/xfunc-volatility.html
        return insert_transaction_package(o_id, n_id, e_id, p_arch_id);
    end if;
    return tp_id;
end;
$$ language plpgsql immutable;


ALTER TABLE rhnpackageevr DISABLE TRIGGER USER;

-- set all existing rhnpackageevr to rpm
update rhnpackageevr set evr.type = 'rpm' where (evr).type is NULL;

--    TABLE "rhnpackage" CONSTRAINT "rhn_package_eid_fk" FOREIGN KEY (evr_id) REFERENCES rhnpackageevr(id)
with sub as (
    select p.id, t.label, pe.evr
         from rhnpackage p
         join rhnpackagearch pa on p.package_arch_id = pa.id
         join rhnarchtype t on pa.arch_type_id = t.id
         join rhnpackageevr pe on p.evr_id = pe.id
	where t.label <> 'rpm'
)
update rhnpackage
set evr_id = lookup_evr((sub.evr).epoch, (sub.evr).version, (sub.evr).release, sub.label)
from sub
where rhnpackage.id = sub.id;

--    TABLE "rhnactionpackage" CONSTRAINT "rhn_act_p_evr_fk" FOREIGN KEY (evr_id) REFERENCES rhnpackageevr(id)
with sub as (
    select p.id, t.label, pe.evr
         from rhnactionpackage p
         join rhnpackagearch pa on p.package_arch_id = pa.id
         join rhnarchtype t on pa.arch_type_id = t.id
         join rhnpackageevr pe on p.evr_id = pe.id
	where t.label <> 'rpm'
)
update rhnactionpackage
set evr_id = lookup_evr((sub.evr).epoch, (sub.evr).version, (sub.evr).release, sub.label)
from sub
where rhnactionpackage.id = sub.id;


--    TABLE "rhnactionpackageremovalfailure" CONSTRAINT "rhn_apr_failure_eid_fk" FOREIGN KEY (evr_id) REFERENCES rhnpackageevr(id)
with sub as (
    select p.action_id, p.server_id, t.label, pe.evr
         from rhnactionpackageremovalfailure p
         join rhnserver s on s.id = p.server_id
         join rhnserverarch pa on s.server_arch_id = pa.id
         join rhnarchtype t on pa.arch_type_id = t.id
         join rhnpackageevr pe on p.evr_id = pe.id
	where t.label <> 'rpm'
)
update rhnactionpackageremovalfailure
set evr_id = lookup_evr((sub.evr).epoch, (sub.evr).version, (sub.evr).release, sub.label)
from sub
where rhnactionpackageremovalfailure.server_id = sub.server_id and
      rhnactionpackageremovalfailure.action_id = sub.action_id;


--    TABLE "rhnchannelnewestpackage" CONSTRAINT "rhn_cnp_eid_fk" FOREIGN KEY (evr_id) REFERENCES rhnpackageevr(id)
with sub as (
    select p.id, p.evr_id
         from rhnpackage p
)
update rhnchannelnewestpackage
set evr_id = sub.evr_id
from sub
where rhnchannelnewestpackage.package_id = sub.id;


--    TABLE "rhnpackagenevra" CONSTRAINT "rhn_pkgnevra_eid_fk" FOREIGN KEY (evr_id) REFERENCES rhnpackageevr(id)
with sub as (
    select p.id, t.label, pe.evr
         from rhnpackagenevra p
         join rhnpackagearch pa on p.package_arch_id = pa.id
         join rhnarchtype t on pa.arch_type_id = t.id
         join rhnpackageevr pe on p.evr_id = pe.id
	where t.label <> 'rpm'
)
update rhnpackagenevra
set evr_id = lookup_evr((sub.evr).epoch, (sub.evr).version, (sub.evr).release, sub.label)
from sub
where rhnpackagenevra.id = sub.id;

--    TABLE "rhnserverpackage" CONSTRAINT "rhnserverpackage_evr_id_fkey" FOREIGN KEY (evr_id) REFERENCES rhnpackageevr(id)
with sub as (
    select p.server_id, p.name_id, p.evr_id, p.package_arch_id, t.label, pe.evr
         from rhnserverpackage p
         join rhnpackagearch pa on p.package_arch_id = pa.id
         join rhnarchtype t on pa.arch_type_id = t.id
         join rhnpackageevr pe on p.evr_id = pe.id
	where t.label <> 'rpm'
)
update rhnserverpackage
set evr_id = lookup_evr((sub.evr).epoch, (sub.evr).version, (sub.evr).release, sub.label)
from sub
where rhnserverpackage.server_id = sub.server_id and
      rhnserverpackage.name_id = sub.name_id and
      rhnserverpackage.evr_id = sub.evr_id and
      rhnserverpackage.package_arch_id = sub.package_arch_id;

--    TABLE "suseproductfile" CONSTRAINT "suse_prod_file_eid_fk" FOREIGN KEY (evr_id) REFERENCES rhnpackageevr(id)
with sub as (
    select p.id, t.label, pe.evr
         from suseproductfile p
         join rhnpackagearch pa on p.package_arch_id = pa.id
         join rhnarchtype t on pa.arch_type_id = t.id
         join rhnpackageevr pe on p.evr_id = pe.id
	where t.label <> 'rpm'
)
update suseproductfile
set evr_id = lookup_evr((sub.evr).epoch, (sub.evr).version, (sub.evr).release, sub.label)
from sub
where suseproductfile.id = sub.id;

--    TABLE "suseimageinfopackage" CONSTRAINT "suseimageinfopackage_evr_id_fkey" FOREIGN KEY (evr_id) REFERENCES rhnpackageevr(id)
with sub as (
    select p.image_info_id, p.evr_id, p.name_id, p.package_arch_id, t.label, pe.evr
         from suseimageinfopackage p
         join rhnpackagearch pa on p.package_arch_id = pa.id
         join rhnarchtype t on pa.arch_type_id = t.id
         join rhnpackageevr pe on p.evr_id = pe.id
	where t.label <> 'rpm'
)
update suseimageinfopackage
set evr_id = lookup_evr((sub.evr).epoch, (sub.evr).version, (sub.evr).release, sub.label)
from sub
where suseimageinfopackage.image_info_id = sub.image_info_id and
      suseimageinfopackage.evr_id = sub.evr_id and
      suseimageinfopackage.name_id = sub.name_id and
      suseimageinfopackage.package_arch_id = sub.package_arch_id;


--    TABLE "rhnversioninfo" CONSTRAINT "rhn_versioninfo_eid_fk" FOREIGN KEY (evr_id) REFERENCES rhnpackageevr(id)
with sub as (
    select p.label, pe.evr
         from rhnversioninfo p
         join rhnpackageevr pe on p.evr_id = pe.id
)
update rhnversioninfo
set evr_id = lookup_evr((sub.evr).epoch, (sub.evr).version, (sub.evr).release, 'rpm')
from sub
where rhnversioninfo.label = sub.label;


--    TABLE "rhnproxyinfo" CONSTRAINT "rhn_proxy_info_peid_fk" FOREIGN KEY (proxy_evr_id) REFERENCES rhnpackageevr(id)
with sub as (
    select p.server_id, t.label, pe.evr
         from rhnproxyinfo p
         join rhnserver s on s.id = p.server_id
         join rhnserverarch pa on s.server_arch_id = pa.id
         join rhnarchtype t on pa.arch_type_id = t.id
         join rhnpackageevr pe on p.proxy_evr_id = pe.id
	where t.label <> 'rpm'
)
update rhnproxyinfo
set proxy_evr_id = lookup_evr((sub.evr).epoch, (sub.evr).version, (sub.evr).release, sub.label)
from sub
where rhnproxyinfo.server_id = sub.server_id;


DO $$
    BEGIN
      -- Schema migration must be idempotent, so we need to guarantee that it will not fail
      -- if 'rhnsatelliteinfo' table was already dropped by the '001-drop-rhnSatelliteInfo.sql' script
      IF EXISTS (
            SELECT 1
                from information_schema.tables
                where table_schema = current_schema()
                and table_name = 'rhnsatelliteinfo'
      ) THEN
        --    TABLE "rhnsatelliteinfo" CONSTRAINT "rhn_satellite_info_eid_fk" FOREIGN KEY (evr_id) REFERENCES rhnpackageevr(id)
        with sub as (
            select p.server_id, t.label, pe.evr
                 from rhnsatelliteinfo p
                 join rhnserver s on s.id = p.server_id
                 join rhnserverarch pa on s.server_arch_id = pa.id
                 join rhnarchtype t on pa.arch_type_id = t.id
                 join rhnpackageevr pe on p.evr_id = pe.id
		where t.label <> 'rpm'
        )
        update rhnsatelliteinfo
        set evr_id = lookup_evr((sub.evr).epoch, (sub.evr).version, (sub.evr).release, sub.label)
        from sub
        where rhnsatelliteinfo.server_id = sub.server_id;
      END IF ;
    END
$$ ;


--    TABLE "rhnserverprofilepackage" CONSTRAINT "rhn_sprofile_evrid_fk" FOREIGN KEY (evr_id) REFERENCES rhnpackageevr(id)
with sub as (
    select p.server_profile_id, p.name_id, p.evr_id, t.label, pe.evr
         from rhnserverprofilepackage p
         join rhnpackagearch pa on p.package_arch_id = pa.id
         join rhnarchtype t on pa.arch_type_id = t.id
         join rhnpackageevr pe on p.evr_id = pe.id
	where t.label <> 'rpm'
)
update rhnserverprofilepackage
set evr_id = lookup_evr((sub.evr).epoch, (sub.evr).version, (sub.evr).release, sub.label)
from sub
where rhnserverprofilepackage.server_profile_id = sub.server_profile_id and
      rhnserverprofilepackage.name_id = sub.name_id and
      rhnserverprofilepackage.evr_id = sub.evr_id;


--    TABLE "rhnservercrash" CONSTRAINT "rhn_server_crash_evr_id_fk" FOREIGN KEY (package_evr_id) REFERENCES rhnpackageevr(id)
DO $$
    BEGIN
      -- Schema migration must be idempotent, so we need to guarantee that it will not fail
      -- if 'rhnservercrash' table was already dropped by the '801-drop-servercrash.sql' script
      IF EXISTS (
            SELECT 1
                from information_schema.tables
                where table_schema = current_schema()
                and table_name = 'rhnservercrash'
      ) THEN
        with sub as (
            select p.server_id, p.crash, t.label, pe.evr
                 from rhnservercrash p
                 join rhnpackagearch pa on p.package_arch_id = pa.id
                 join rhnarchtype t on pa.arch_type_id = t.id
                 join rhnpackageevr pe on p.package_evr_id = pe.id
		where t.label <> 'rpm'
        )
        update rhnservercrash
        set package_evr_id = lookup_evr((sub.evr).epoch, (sub.evr).version, (sub.evr).release, sub.label)
        from sub
        where rhnservercrash.server_id = sub.server_id and
              rhnservercrash.crash = sub.crash;
      END IF ;
    END
$$ ;


--    TABLE "rhnlockedpackages" CONSTRAINT "rhnlockedpackages_evr_id_fkey" FOREIGN KEY (evr_id) REFERENCES rhnpackageevr(id)
with sub as (
    select p.server_id, p.name_id, p.evr_id, p.arch_id, t.label, pe.evr
         from rhnlockedpackages p
         join rhnpackagearch pa on p.arch_id = pa.id
         join rhnarchtype t on pa.arch_type_id = t.id
         join rhnpackageevr pe on p.evr_id = pe.id
	where t.label <> 'rpm'
)
update rhnlockedpackages
set evr_id = lookup_evr((sub.evr).epoch, (sub.evr).version, (sub.evr).release, sub.label)
from sub
where rhnlockedpackages.server_id = sub.server_id and
      rhnlockedpackages.name_id = sub.name_id and
      rhnlockedpackages.evr_id = sub.evr_id and
      rhnlockedpackages.arch_id = sub.arch_id;


--    TABLE "susepackagestate" CONSTRAINT "suse_pkg_state_eid_fk" FOREIGN KEY (evr_id) REFERENCES rhnpackageevr(id)
with sub as (
    select p.id, t.label, pe.evr
         from susepackagestate p
         join rhnpackagearch pa on p.package_arch_id = pa.id
         join rhnarchtype t on pa.arch_type_id = t.id
         join rhnpackageevr pe on p.evr_id = pe.id
	where t.label <> 'rpm'
)
update susepackagestate
set evr_id = lookup_evr((sub.evr).epoch, (sub.evr).version, (sub.evr).release, sub.label)
from sub
where susepackagestate.id = sub.id;


--    TABLE "rhnserveractionverifymissing" CONSTRAINT "rhn_sactionvm_peid_fk" FOREIGN KEY (package_evr_id) REFERENCES rhnpackageevr(id)
with sub as (
    select p.server_id, p.action_id, p.package_name_id, p.package_evr_id, p.package_arch_id, p.package_capability_id, t.label, pe.evr
         from rhnserveractionverifymissing p
         join rhnpackagearch pa on p.package_arch_id = pa.id
         join rhnarchtype t on pa.arch_type_id = t.id
         join rhnpackageevr pe on p.package_evr_id = pe.id
	where t.label <> 'rpm'
)
update rhnserveractionverifymissing
set package_evr_id = lookup_evr((sub.evr).epoch, (sub.evr).version, (sub.evr).release, sub.label)
from sub
where rhnserveractionverifymissing.server_id = sub.server_id and
      rhnserveractionverifymissing.action_id = sub.action_id and
      rhnserveractionverifymissing.package_name_id = sub.package_name_id and
      rhnserveractionverifymissing.package_evr_id = sub.package_evr_id and
      rhnserveractionverifymissing.package_arch_id = sub.package_arch_id and
      rhnserveractionverifymissing.package_capability_id = sub.package_capability_id;


--    TABLE "rhnserveractionverifyresult" CONSTRAINT "rhn_sactionvr_peid_fk" FOREIGN KEY (package_evr_id) REFERENCES rhnpackageevr(id)
with sub as (
    select p.server_id, p.action_id, p.package_name_id, p.package_evr_id, p.package_arch_id, p.package_capability_id, t.label, pe.evr
         from rhnserveractionverifyresult p
         join rhnpackagearch pa on p.package_arch_id = pa.id
         join rhnarchtype t on pa.arch_type_id = t.id
         join rhnpackageevr pe on p.package_evr_id = pe.id
	where t.label <> 'rpm'
)
update rhnserveractionverifyresult
set package_evr_id = lookup_evr((sub.evr).epoch, (sub.evr).version, (sub.evr).release, sub.label)
from sub
where rhnserveractionverifyresult.server_id = sub.server_id and
      rhnserveractionverifyresult.action_id = sub.action_id and
      rhnserveractionverifyresult.package_name_id = sub.package_name_id and
      rhnserveractionverifyresult.package_evr_id = sub.package_evr_id and
      rhnserveractionverifyresult.package_arch_id = sub.package_arch_id and
      rhnserveractionverifyresult.package_capability_id = sub.package_capability_id;


--    TABLE "rhntransactionpackage" CONSTRAINT "rhn_transpack_eid_fk" FOREIGN KEY (evr_id) REFERENCES rhnpackageevr(id)
with sub as (
    select p.id, t.label, pe.evr
         from rhntransactionpackage p
         join rhnpackagearch pa on p.package_arch_id = pa.id
         join rhnarchtype t on pa.arch_type_id = t.id
         join rhnpackageevr pe on p.evr_id = pe.id
	where t.label <> 'rpm'
)
update rhntransactionpackage
set evr_id = lookup_evr((sub.evr).epoch, (sub.evr).version, (sub.evr).release, sub.label)
from sub
where rhntransactionpackage.id = sub.id;

-- delete all rhnpackageevr entries that are not referenced anymore
DO $$
    BEGIN
      -- Schema migration must be idempotent, so we need to guarantee that it will not fail
      -- if 'rhnservercrash' table was already dropped by the '801-drop-servercrash.sql' script
      IF EXISTS (
            SELECT 1
                from information_schema.tables
                where table_schema = current_schema()
                and table_name = 'rhnservercrash'
      ) THEN
            delete from rhnpackageevr p
             using (
            select pe.id
              from rhnpackageevr pe
             where not exists (select 1 from rhnactionpackage f1 where f1.evr_id = pe.id)
               and not exists (select 1 from rhnactionpackageremovalfailure f2 where f2.evr_id = pe.id)
               and not exists (select 1 from rhnchannelnewestpackage f3 where f3.evr_id = pe.id)
               and not exists (select 1 from rhnpackage f4 where f4.evr_id = pe.id)
               and not exists (select 1 from rhnpackagenevra f5 where f5.evr_id = pe.id)
               and not exists (select 1 from rhnproxyinfo f6 where f6.proxy_evr_id = pe.id)
               and not exists (select 1 from rhnserveractionverifymissing f7 where f7.package_evr_id = pe.id)
               and not exists (select 1 from rhnserveractionverifyresult f8 where f8.package_evr_id = pe.id)
               and not exists (select 1 from rhnsatelliteinfo f9 where f9.evr_id = pe.id)
               and not exists (select 1 from rhnservercrash f10 where f10.package_evr_id = pe.id)
               and not exists (select 1 from rhnserverprofilepackage f11 where f11.evr_id = pe.id)
               and not exists (select 1 from rhntransactionpackage f12 where f12.evr_id = pe.id)
               and not exists (select 1 from rhnversioninfo f13 where f13.evr_id = pe.id)
               and not exists (select 1 from rhnlockedpackages f14 where f14.evr_id = pe.id)
               and not exists (select 1 from rhnserverpackage f15 where f15.evr_id = pe.id)
               and not exists (select 1 from susepackagestate f16 where f16.evr_id = pe.id)
               and not exists (select 1 from suseproductfile f17 where f17.evr_id = pe.id)
               and not exists (select 1 from suseimageinfopackage f18 where f18.evr_id = pe.id)
             ) as sub
            where p.id = sub.id;
        ELSIF EXISTS (
                SELECT 1
                    from information_schema.tables
                    where table_schema = current_schema()
                    and table_name = 'rhnsatelliteinfo'
          ) THEN
            delete from rhnpackageevr p
             using (
            select pe.id
              from rhnpackageevr pe
             where not exists (select 1 from rhnactionpackage f1 where f1.evr_id = pe.id)
               and not exists (select 1 from rhnactionpackageremovalfailure f2 where f2.evr_id = pe.id)
               and not exists (select 1 from rhnchannelnewestpackage f3 where f3.evr_id = pe.id)
               and not exists (select 1 from rhnpackage f4 where f4.evr_id = pe.id)
               and not exists (select 1 from rhnpackagenevra f5 where f5.evr_id = pe.id)
               and not exists (select 1 from rhnproxyinfo f6 where f6.proxy_evr_id = pe.id)
               and not exists (select 1 from rhnserveractionverifymissing f7 where f7.package_evr_id = pe.id)
               and not exists (select 1 from rhnserveractionverifyresult f8 where f8.package_evr_id = pe.id)
               and not exists (select 1 from rhnsatelliteinfo f9 where f9.evr_id = pe.id)
               and not exists (select 1 from rhnserverprofilepackage f11 where f11.evr_id = pe.id)
               and not exists (select 1 from rhntransactionpackage f12 where f12.evr_id = pe.id)
               and not exists (select 1 from rhnversioninfo f13 where f13.evr_id = pe.id)
               and not exists (select 1 from rhnlockedpackages f14 where f14.evr_id = pe.id)
               and not exists (select 1 from rhnserverpackage f15 where f15.evr_id = pe.id)
               and not exists (select 1 from susepackagestate f16 where f16.evr_id = pe.id)
               and not exists (select 1 from suseproductfile f17 where f17.evr_id = pe.id)
               and not exists (select 1 from suseimageinfopackage f18 where f18.evr_id = pe.id)
             ) as sub
            where p.id = sub.id;
        ELSE
            delete from rhnpackageevr p
             using (
            select pe.id
              from rhnpackageevr pe
             where not exists (select 1 from rhnactionpackage f1 where f1.evr_id = pe.id)
               and not exists (select 1 from rhnactionpackageremovalfailure f2 where f2.evr_id = pe.id)
               and not exists (select 1 from rhnchannelnewestpackage f3 where f3.evr_id = pe.id)
               and not exists (select 1 from rhnpackage f4 where f4.evr_id = pe.id)
               and not exists (select 1 from rhnpackagenevra f5 where f5.evr_id = pe.id)
               and not exists (select 1 from rhnproxyinfo f6 where f6.proxy_evr_id = pe.id)
               and not exists (select 1 from rhnserveractionverifymissing f7 where f7.package_evr_id = pe.id)
               and not exists (select 1 from rhnserveractionverifyresult f8 where f8.package_evr_id = pe.id)
               and not exists (select 1 from rhnserverprofilepackage f11 where f11.evr_id = pe.id)
               and not exists (select 1 from rhntransactionpackage f12 where f12.evr_id = pe.id)
               and not exists (select 1 from rhnversioninfo f13 where f13.evr_id = pe.id)
               and not exists (select 1 from rhnlockedpackages f14 where f14.evr_id = pe.id)
               and not exists (select 1 from rhnserverpackage f15 where f15.evr_id = pe.id)
               and not exists (select 1 from susepackagestate f16 where f16.evr_id = pe.id)
               and not exists (select 1 from suseproductfile f17 where f17.evr_id = pe.id)
               and not exists (select 1 from suseimageinfopackage f18 where f18.evr_id = pe.id)
             ) as sub
            where p.id = sub.id;
      END IF ;
    END
$$ ;

alter table rhnpackageevr add column if not exists type varchar(10) generated always as ((evr).type) stored;

ALTER TABLE rhnpackageevr ENABLE TRIGGER USER;
07070100000EA2000081B400000000000000000000000167AE111400004F6B000000000000000000000000000000000000006700000000susemanager-schema/upgrade/susemanager-schema-4.2.4-to-susemanager-schema-4.2.5/703-rhn_server.pkb.sql    -- oracle equivalent source sha1 87bc50785a1b2a5e639cdc7371aa5c1b435adaa2
--
-- Copyright (c) 2008--2014 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--
--
--
--

-- create schema rhn_server;

--update pg_setting
update pg_settings set setting = 'rhn_server,' || setting where name = 'search_path';

    create or replace function system_service_level(
    	server_id_in in numeric,
	service_level_in in varchar
    ) returns numeric as $$
    declare
    ents cursor is
      select label from rhnServerEntitlementView
      where server_id = server_id_in;

    retval numeric := 0;

    begin
         for ent in ents loop
            retval := rhn_entitlements.entitlement_grants_service (ent.label, service_level_in);
            if retval = 1 then
               return retval;
            end if;
         end loop;

         return retval;

    end$$ language plpgsql;


    create or replace function can_change_base_channel(server_id_in IN NUMERIC)
    returns numeric
    as $$
    declare
    	throwaway numeric;
    begin
    	-- the idea: if we get past this query, the server is
	-- neither sat nor proxy, so base channel is changeable

	select 1 into throwaway
	  from rhnServer S
	 where S.id = server_id_in
	   and not exists (select 1 from rhnSatelliteInfo SI where SI.server_id = S.id)
	   and not exists (select 1 from rhnProxyInfo PI where PI.server_id = S.id);

        if not found then
	    return 0;
        end if;

	return 1;
    end$$ language plpgsql;

    create or replace function set_custom_value(
    	server_id_in in numeric,
	user_id_in in numeric,
	key_label_in in varchar,
	value_in in varchar
    ) returns void
    as $$
    declare
    	key_id_val numeric;
    begin
    	select CDK.id into strict key_id_val
	  from rhnCustomDataKey CDK,
	       rhnServer S
	 where S.id = server_id_in
	   and S.org_id = CDK.org_id
	   and CDK.label = key_label_in;

	begin
	    insert into rhnServerCustomDataValue (server_id, key_id, value, created_by, last_modified_by)
	    values (server_id_in, key_id_val, value_in, user_id_in, user_id_in);
	exception
	    when UNIQUE_VIOLATION
	    	then
		update rhnServerCustomDataValue
		   set value = value_in,
		       last_modified_by = user_id_in
		 where server_id = server_id_in
		   and key_id = key_id_val;
	end;

    end$$ language plpgsql;

    create or replace function bulk_set_custom_value(
    	key_label_in in varchar,
	value_in in varchar,
	set_label_in in varchar,
	set_uid_in in numeric
    )
    returns integer
    as $$
    declare
        i integer;
        server record;
    begin
        i := 0;
        for server in (
           SELECT user_id, label, element, element_two
	     FROM rhnSet
	    WHERE label = set_label_in
	      AND user_id = set_uid_in
	) loop
	    if rhn_server.system_service_level(server.element, 'management') = 1 then
	    	perform rhn_server.set_custom_value(server.element, set_uid_in, key_label_in, value_in);
            i := i + 1;
	    end if;
	end loop;
    return i;
    end$$ language plpgsql;

    create or replace function bulk_snapshot_tag(
    	org_id_in in numeric,
        tagname_in in varchar,
	set_label_in in varchar,
	set_uid_in in numeric
    ) returns void
    as $$
    declare
        server record;
    	snapshot_id numeric;
    begin
        for server in (
           SELECT user_id, label, element, element_two
	     FROM rhnSet
	    WHERE label = set_label_in
	      AND user_id = set_uid_in
	    ) loop
	    if rhn_server.system_service_level(server.element, 'management') = 1 then
	    	    select max(id) into snapshot_id
	    	    from rhnSnapshot
	    	    where server_id = server.element;

	    	    if snapshot_id is null then
		    	perform rhn_server.snapshot_server(server.element, 'tagging system:  ' || tagname_in);

			select max(id) into snapshot_id
			from rhnSnapshot
			where server_id = server.element;
		    end if;

		-- now have a snapshot_id to work with...
		begin
		    perform rhn_server.tag_snapshot(snapshot_id, org_id_in, tagname_in);
		exception
		    when UNIQUE_VIOLATION
		    	then
			-- do nothing, be forgiving...
			null;
		end;
	    end if;
	end loop;
    end$$ language plpgsql;

    create or replace function tag_delete(
    	server_id_in in numeric,
	tag_id_in in numeric
    ) returns void
    as $$
    declare
    	snapshots cursor is
		select	snapshot_id
		from	rhnSnapshotTag
		where	tag_id = tag_id_in;
	tag_id_tmp numeric;
    begin
    	select	id into tag_id_tmp
	from	rhnTag
	where	id = tag_id_in
	for update;

	delete
		from	rhnSnapshotTag
		where	server_id = server_id_in
			and tag_id = tag_id_in;
	for snapshot in snapshots loop
		return;
	end loop;
	delete
		from rhnTag
		where id = tag_id_in;
    end$$ language plpgsql;

    create or replace function tag_snapshot(
        snapshot_id_in in numeric,
	org_id_in in numeric,
	tagname_in in varchar
    ) returns void
    as $$
    begin
    	insert into rhnSnapshotTag (snapshot_id, server_id, tag_id)
	select snapshot_id_in, server_id, lookup_tag(org_id_in, tagname_in)
	from rhnSnapshot
	where id = snapshot_id_in;
    end$$ language plpgsql;

    create or replace function bulk_snapshot(
    	reason_in in varchar,
	set_label_in in varchar,
	set_uid_in in numeric
    ) returns void
    as $$
    declare
        server record;
    begin
        for server in (
           SELECT user_id, label, element, element_two
	     FROM rhnSet
	    WHERE label = set_label_in
	      AND user_id = set_uid_in
	    ) loop
	    if rhn_server.system_service_level(server.element, 'management') = 1 then
	    	perform rhn_server.snapshot_server(server.element, reason_in);
	    end if;
	end loop;
    end$$ language plpgsql;

    create or replace function snapshot_server(
    	server_id_in in numeric,
	reason_in in varchar
    ) returns void
    as $$
    declare
    	snapshot_id_v numeric;
	revisions cursor is
		select distinct
			cr.id
		from	rhnConfigRevision	cr,
			rhnConfigFileName	cfn,
			rhnConfigFile		cf,
			rhnConfigChannel	cc,
			rhnServerConfigChannel	scc
		where	1=1
			and scc.server_id = server_id_in
			and scc.config_channel_id = cc.id
			and cc.id = cf.config_channel_id
			and cf.id = cr.config_file_id
			and cr.id = cf.latest_config_revision_id
			and cf.config_file_name_id = cfn.id
			and cf.id = lookup_first_matching_cf(scc.server_id, cfn.path);
	locked integer;
    begin
    	select nextval('rhn_snapshot_id_seq') into snapshot_id_v;

	insert into rhnSnapshot (id, org_id, server_id, reason) (
		select	snapshot_id_v,
			s.org_id,
			server_id_in,
			reason_in
		from	rhnServer s
		where	s.id = server_id_in
	);
	insert into rhnSnapshotChannel (snapshot_id, channel_id) (
		select	snapshot_id_v, sc.channel_id
		from	rhnServerChannel sc
		where	sc.server_id = server_id_in
	);
	insert into rhnSnapshotServerGroup (snapshot_id, server_group_id) (
		select	snapshot_id_v, sgm.server_group_id
		from	rhnServerGroupMembers sgm
		where	sgm.server_id = server_id_in
	);
        locked := 0;
        <<iloop>>
        while true loop
            begin
                insert into rhnPackageNEVRA (id, name_id, evr_id, package_arch_id)
                select nextval('rhn_pkgnevra_id_seq'), sp.name_id, sp.evr_id, sp.package_arch_id
                from rhnServerPackage sp
                where sp.server_id = server_id_in
                        and not exists
                        (select 1
                                from rhnPackageNEVRA nevra
                                where nevra.name_id = sp.name_id
                                        and nevra.evr_id = sp.evr_id
                                        and (nevra.package_arch_id = sp.package_arch_id
                                            or (nevra.package_arch_id is null
                                                and sp.package_arch_id is null)));
                exit iloop;
            exception when unique_violation then
                if locked = 1 then
                    raise;
                else
                    lock table rhnPackageNEVRA in exclusive mode;
                    locked := 1;
                end if;
            end;
        end loop;
	insert into rhnSnapshotPackage (snapshot_id, nevra_id) (
                select distinct snapshot_id_v, nevra.id
                from    rhnServerPackage sp, rhnPackageNEVRA nevra
                where   sp.server_id = server_id_in
                        and nevra.name_id = sp.name_id
                        and nevra.evr_id = sp.evr_id
                        and (nevra.package_arch_id = sp.package_arch_id
                            or (nevra.package_arch_id is null
                                and sp.package_arch_id is null))
	);

	insert into rhnSnapshotConfigChannel ( snapshot_id, config_channel_id ) (
		select	snapshot_id_v, scc.config_channel_id
		from	rhnServerConfigChannel scc
		where	server_id = server_id_in
	);

	for revision in revisions loop
		insert into rhnSnapshotConfigRevision (
				snapshot_id, config_revision_id
			) values (
				snapshot_id_v, revision.id
			);
	end loop;
    end$$ language plpgsql;

    create or replace function remove_action(
    	server_id_in in numeric,
	action_id_in in numeric
    ) returns void
    as $$
    declare
    	-- this really wants "nulls last", but 8.1.7.3.0 sucks ass.
	-- instead, we make a local table that holds our
	-- list of ids with null prereqs.  There's surely a better way
	-- (an array instead of a table maybe?  who knows...)
	-- but I've got code to do this handy that I can look at ;)
    	chained_actions cursor is
                with recursive r(id, prerequisite) as (
			select	id, prerequisite
			from	rhnAction
			where id = action_id_in
		union all
			select	r1.id, r1.prerequisite
			from	rhnAction r1, r
			where r.id = r1.prerequisite
		)
		select * from r
		order by prerequisite desc;
	sessions cursor is
		select	s.id
		from	rhnKickstartSession s
		where	server_id_in in (s.old_server_id, s.new_server_id)
			and s.action_id = action_id_in
			and not exists (
				select	1
				from	rhnKickstartSessionState ss
				where	ss.id = s.state_id
					and ss.label in ('failed','complete')
			);
	chain_ends numeric[];
	i numeric;
	prereq numeric := 1;
    begin
	select	prerequisite
	into	prereq
	from	rhnAction
	where	id = action_id_in;

	if prereq is not null then
		perform rhn_exception.raise_exception('action_is_child');
	end if;

        chain_ends := '{}';
	i := 1;
	for action in chained_actions loop
		if action.prerequisite is null then
			chain_ends[i] := action.id;
			i := i + 1;
		else
			delete from rhnServerAction
				where server_id = server_id_in
				and action_id = action.id;
		end if;
	end loop;

	delete from rhnServerAction
		where server_id = server_id_in
		and action_id = any(chain_ends);

	for s in sessions loop
		update rhnKickstartSession
			set 	state_id = (
					select	id
					from	rhnKickstartSessionState
					where	label = 'failed'
				),
				action_id = null
			where	id = s.id;
		perform set_ks_session_history_message(s.id, 'failed', 'Kickstart cancelled due to action removal');
	end loop;
    end$$ language plpgsql;

    create or replace function check_user_access(server_id_in in numeric, user_id_in in numeric)
    returns numeric
    as $$
    declare
    	has_access numeric;
    begin
    	-- first check; if this returns no rows, then the server/user are in different orgs, and we bail
        select 1 into has_access
	  from rhnServer S,
	       web_contact wc
	 where wc.org_id = s.org_id
	   and s.id = server_id_in
	   and wc.id = user_id_in;

        if not found then
          return 0;
        end if;

	-- okay, so they're in the same org.  if we have an org admin, they get a free pass
    	if rhn_user.check_role(user_id_in, 'org_admin') = 1
	then
	    return 1;
	end if;

    	select 1 into has_access
	  from rhnServerGroupMembers SGM,
	       rhnUserServerGroupPerms USG
	 where SGM.server_group_id = USG.server_group_id
	   and SGM.server_id = server_id_in
	   and USG.user_id = user_id_in;

        if not found then
          return 0;
        end if;

	return 1;
    end$$ language plpgsql;

    create or replace function insert_into_servergroup (
		server_id_in in numeric,
		server_group_id_in in numeric
    ) returns void
    as $$
    declare
		group_type numeric;
	begin
		-- this will rowlock the servergroup we're trying to change;
		-- we probably need to lock the other one, but I think the chances
		-- of it being a real issue are very small for now...
		select	sg.group_type
		into	group_type
		from	rhnServerGroup sg
		where	sg.id = server_group_id_in
		for update of sg;

		insert into rhnServerGroupMembers(server_id, server_group_id)
		values (server_id_in, server_group_id_in);

		update rhnServerGroup
		set current_members = current_members + 1
		where id = server_group_id_in;

		if group_type is null then
			perform rhn_cache.update_perms_for_server_group(server_group_id_in);
		end if;

		return;
	end$$ language plpgsql;

	create or replace function insert_into_servergroup_maybe (
		server_id_in in numeric,
		server_group_id_in in numeric
	) returns numeric as $$
    declare
		retval numeric := 0;
		servergroups cursor is
			select	s.id	server_id,
					sg.id	server_group_id
			from	rhnServerGroup	sg,
					rhnServer		s
			where	s.id = server_id_in
				and sg.id = server_group_id_in
				and s.org_id = sg.org_id
				and not exists (
					select	1
					from	rhnServerGroupMembers sgm
					where	sgm.server_id = s.id
						and sgm.server_group_id = sg.id
				);
	begin
		for sgm in servergroups loop
			perform rhn_server.insert_into_servergroup(sgm.server_id, sgm.server_group_id);
			retval := retval + 1;
		end loop;
		return retval;
	end$$ language plpgsql;

	create or replace function insert_set_into_servergroup (
		server_group_id_in in numeric,
		user_id_in in numeric,
		set_label_in in varchar
	) returns void
        as $$
    declare
		servers cursor is
			select	st.element	id
			from	rhnSet		st
			where	st.user_id = user_id_in
				and st.label = set_label_in
				and exists (
					select	1
					from	rhnUserManagedServerGroups umsg
					where	umsg.server_group_id = server_group_id_in
						and umsg.user_id = user_id_in
					)
				and not exists (
					select	1
					from	rhnServerGroupMembers sgm
					where	sgm.server_id = st.element
						and sgm.server_group_id = server_group_id_in
				);
	begin
		for s in servers loop
			perform rhn_server.insert_into_servergroup(s.id, server_group_id_in);
		end loop;
	end$$ language plpgsql;

    create or replace function delete_from_servergroup (
    	server_id_in in numeric,
	server_group_id_in in numeric
    ) returns void
    as $$
    declare

		oid numeric;
		label varchar;
		group_type numeric;
	begin
		select	sg.group_type, sg.org_id
		into	group_type,	oid
		from	rhnServerGroupMembers	sgm,
			rhnServerGroup		sg
		where	sg.id = server_group_id_in
		and 	sg.id = sgm.server_group_id
		and 	sgm.server_id = server_id_in
		for update of sg;

		if not found then
			perform rhn_exception.raise_exception('server_not_in_group');
		end if;

		delete from rhnServerGroupMembers
		where server_group_id = server_group_id_in
		and	server_id = server_id_in;

		update rhnServerGroup
		set current_members = current_members - 1
		where id = server_group_id_in;

		-- do group_type is null first
		if group_type is null then
			perform rhn_cache.update_perms_for_server_group(server_group_id_in);
		end if;

	end$$ language plpgsql;

	create or replace function delete_set_from_servergroup (
		server_group_id_in in numeric,
		user_id_in in numeric,
		set_label_in in varchar
	) returns void
        as $$
        declare
		servergroups cursor is
			select	sgm.server_id, sgm.server_group_id
			from	rhnSet st,
					rhnServerGroupMembers sgm
			where	sgm.server_group_id = server_group_id_in
				and st.user_id = user_id_in
				and st.label = set_label_in
				and sgm.server_id = st.element
				and exists (
					select	1
					from	rhnUserManagedServerGroups usgp
					where	usgp.server_group_id = server_group_id_in
						and usgp.user_id = user_id_in
				);
	begin
		for sgm in servergroups loop
			perform rhn_server.delete_from_servergroup(sgm.server_id, server_group_id_in);
		end loop;
	end$$ language plpgsql;

	create or replace function clear_servergroup (
		server_group_id_in in numeric
	) returns void
        as $$
        declare
		servers cursor is
			select	sgm.server_id	id
			from	rhnServerGroupMembers sgm
			where	sgm.server_group_id = server_group_id_in;
	begin
		for s in servers loop
			perform rhn_server.delete_from_servergroup(s.id, server_group_id_in);
		end loop;
	end$$ language plpgsql;

	create or replace function delete_from_org_servergroups (
		server_id_in in numeric
	) returns void
        as $$
        declare
		servergroups cursor is
			select	sgm.server_group_id id
			from	rhnServerGroup sg,
					rhnServerGroupMembers sgm
			where	sgm.server_id = server_id_in
				and sgm.server_group_id = sg.id
				and sg.group_type is null;
	begin
		for sg in servergroups loop
			perform rhn_server.delete_from_servergroup(server_id_in, sg.id);
		end loop;
	end$$ language plpgsql;

	create or replace function get_ip_address (
		server_id_in in numeric
	) returns varchar as $$
        declare
		interfaces cursor is
			select	ni.name as name, na4.address as address
			from	rhnServerNetInterface ni,
			        rhnServerNetAddress4 na4
			where	server_id = server_id_in
		                and ni.id = na4.interface_id
				and na4.address != '127.0.0.1';
		addresses cursor is
			select	address ip_addr
			from	rhnServerNetInterface
      			left join rhnServerNetAddress4
      			on rhnServerNetInterface.id = rhnServerNetAddress4.interface_id
			where	server_id = server_id_in
				and address != '127.0.0.1'
				and is_primary = 'Y';
	begin
		for addr in addresses loop
			return addr.ip_addr;
		end loop;
		for iface in interfaces loop
			return iface.address;
		end loop;
		return NULL;
	end$$ language plpgsql;

    create or replace function update_needed_cache(
        server_id_in in numeric
	) returns void as $$
    begin
      delete from rhnServerNeededCache
        where server_id = server_id_in;
      insert into rhnServerNeededCache
             (server_id, errata_id, package_id, channel_id)
        (select distinct sp.server_id, x.errata_id, p.id, x.channel_id
           FROM (SELECT sp_sp.server_id, sp_sp.name_id,
		        sp_sp.package_arch_id, max(sp_pe.evr) AS max_evr
                   FROM rhnServerPackage sp_sp
                   join rhnPackageEvr sp_pe ON sp_pe.id = sp_sp.evr_id
                  GROUP BY sp_sp.server_id, sp_sp.name_id, sp_sp.package_arch_id) sp
           join rhnPackage p ON p.name_id = sp.name_id
           join rhnPackageEvr pe ON pe.id = p.evr_id AND (sp.max_evr).type = (pe.evr).type AND sp.max_evr < pe.evr
           join rhnPackageUpgradeArchCompat puac
	            ON puac.package_arch_id = sp.package_arch_id
		    AND puac.package_upgrade_arch_id = p.package_arch_id
           join rhnServerChannel sc ON sc.server_id = sp.server_id
           join rhnChannelPackage cp ON cp.package_id = p.id
	            AND cp.channel_id = sc.channel_id
           left join (SELECT ep.errata_id, ce.channel_id, ep.package_id
                        FROM rhnChannelErrata ce
                        join rhnErrataPackage ep
			         ON ep.errata_id = ce.errata_id
			join rhnServerChannel sc_sc
			         ON sc_sc.channel_id = ce.channel_id
		       WHERE sc_sc.server_id = server_id_in) x
             ON x.channel_id = sc.channel_id AND x.package_id = cp.package_id
          where sp.server_id = server_id_in);
	end$$ language plpgsql;
-- restore the original setting
update pg_settings set setting = overlay( setting placing '' from 1 for (length('rhn_server')+1) ) where name = 'search_path';
 07070100000EA3000081B400000000000000000000000167AE1114000008F3000000000000000000000000000000000000007200000000susemanager-schema/upgrade/susemanager-schema-4.2.4-to-susemanager-schema-4.2.5/704-update_image_needed_cache.sql --
-- Copyright (c) 2017 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--

create or replace function
update_image_needed_cache(image_id_in in numeric)
returns void as $$
declare
  update_lock numeric;
begin
  select id into update_lock from suseImageInfo where id = image_id_in for update;
  delete from rhnImageNeededCache
   where image_id = image_id_in;
  insert into rhnImageNeededCache
         (image_id, errata_id, package_id, channel_id)
    (select distinct ip.image_info_id, x.errata_id, p.id, x.channel_id
       FROM (SELECT ip_ip.image_info_id, ip_ip.name_id,
                    ip_ip.package_arch_id, max(ip_pe.evr) AS max_evr
               FROM suseImageInfoPackage ip_ip
               join rhnPackageEvr ip_pe ON ip_pe.id = ip_ip.evr_id
              GROUP BY ip_ip.image_info_id, ip_ip.name_id, ip_ip.package_arch_id) ip
       join rhnPackage p ON p.name_id = ip.name_id
       join rhnPackageEvr pe ON pe.id = p.evr_id
                AND (ip.max_evr).type = (pe.evr).type AND ip.max_evr < pe.evr
       join rhnPackageUpgradeArchCompat puac
                ON puac.package_arch_id = ip.package_arch_id
                AND puac.package_upgrade_arch_id = p.package_arch_id
       join suseImageInfoChannel ic ON ic.image_info_id = ip.image_info_id
       join rhnChannelPackage cp ON cp.package_id = p.id
                AND cp.channel_id = ic.channel_id
       left join (SELECT ep.errata_id, ce.channel_id, ep.package_id
                    FROM rhnChannelErrata ce
                    join rhnErrataPackage ep
                             ON ep.errata_id = ce.errata_id
                    join suseImageInfoChannel ic_ic
                             ON ic_ic.channel_id = ce.channel_id
                   WHERE ic_ic.image_info_id = image_id_in) x
         ON x.channel_id = ic.channel_id
                AND x.package_id = cp.package_id
      where ip.image_info_id = image_id_in);
end;
$$
language plpgsql;
 07070100000EA4000081B400000000000000000000000167AE11140000014E000000000000000000000000000000000000006A00000000susemanager-schema/upgrade/susemanager-schema-4.2.4-to-susemanager-schema-4.2.5/801-drop-rhnerratatmp.sql DROP TABLE IF EXISTS rhnErrataBuglistTmp;
DROP TABLE IF EXISTS rhnErrataKeywordTmp;
DROP TABLE IF EXISTS rhnErrataPackageTmp;
DROP TABLE IF EXISTS rhnErrataClonedTmp;
DROP TABLE IF EXISTS rhnErrataFileChannelTmp;
DROP TABLE IF EXISTS rhnErrataFilePackageTmp;
DROP TABLE IF EXISTS rhnErrataFileTmp;
DROP TABLE IF EXISTS rhnErrataTmp;

  07070100000EA5000081B400000000000000000000000167AE111400000144000000000000000000000000000000000000006D00000000susemanager-schema/upgrade/susemanager-schema-4.2.4-to-susemanager-schema-4.2.5/802-add-missing-uq-index.sql  
CREATE UNIQUE INDEX IF NOT EXISTS suseproductchannel_product_id_channel_id_uq
ON suseProductChannel (product_id, channel_id);

CREATE UNIQUE INDEX IF NOT EXISTS susemdkeyword_label_uq
ON suseMdKeyword (label);

CREATE UNIQUE INDEX IF NOT EXISTS suseupgradepath_from_pdid_to_pdid_uq
ON suseUpgradePath (from_pdid, to_pdid);
07070100000EA6000081B400000000000000000000000167AE111400000182000000000000000000000000000000000000006600000000susemanager-schema/upgrade/susemanager-schema-4.2.4-to-susemanager-schema-4.2.5/900-centos6-vault.sql --- After CentOS EoL, it got removed from the mirrorlist and moved to the vault
UPDATE rhnContentSource
SET source_url = concat('https://vault.centos.org/centos/6/', array_to_string(regexp_match(source_url, 'repo=(.+)'), ''), '/' ,array_to_string(regexp_match(source_url, 'arch=(.+)&'), ''), '/')
WHERE source_url LIKE 'http://mirrorlist.centos.org/?release=6%' AND org_id IS NOT NULL;
  07070100000EA7000081B400000000000000000000000167AE11140000032F000000000000000000000000000000000000007900000000susemanager-schema/upgrade/susemanager-schema-4.2.4-to-susemanager-schema-4.2.5/950-channel-modular-data-cleaunp-job.sql  INSERT INTO rhnTaskoTask (id, name, class)
SELECT sequence_nextval('rhn_tasko_task_id_seq'), 'channel-modular-data-cleanup', 'com.redhat.rhn.taskomatic.task.ModularDataCleanup'
WHERE NOT EXISTS (SELECT 1 FROM rhnTaskoTask WHERE name='channel-modular-data-cleanup');

INSERT INTO rhnTaskoTemplate (id, bunch_id, task_id, ordering, start_if)
SELECT sequence_nextval('rhn_tasko_template_id_seq'),
    (SELECT id FROM rhnTaskoBunch WHERE name='cleanup-data-bunch'),
    (SELECT id FROM rhnTaskoTask WHERE name='channel-modular-data-cleanup'),
    1,
    null
WHERE NOT EXISTS (
    SELECT 1 FROM rhnTaskoTemplate
    WHERE bunch_id = (SELECT id FROM rhnTaskoBunch WHERE name = 'cleanup-data-bunch')
      AND task_id = (SELECT id FROM rhnTaskoTask WHERE name = 'channel-modular-data-cleanup')
      AND ordering = 1
);
 07070100000EA8000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005100000000susemanager-schema/upgrade/susemanager-schema-4.2.40-to-susemanager-schema-4.3.0  07070100000EA9000081B400000000000000000000000167AE111400000000000000000000000000000000000000000000005A00000000susemanager-schema/upgrade/susemanager-schema-4.2.40-to-susemanager-schema-4.3.0/.gitkeep 07070100000EAA000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005100000000susemanager-schema/upgrade/susemanager-schema-4.2.41-to-susemanager-schema-4.3.0  07070100000EAB000081B400000000000000000000000167AE111400000000000000000000000000000000000000000000005A00000000susemanager-schema/upgrade/susemanager-schema-4.2.41-to-susemanager-schema-4.3.0/.gitkeep 07070100000EAC000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005100000000susemanager-schema/upgrade/susemanager-schema-4.2.42-to-susemanager-schema-4.3.0  07070100000EAD000081B400000000000000000000000167AE111400000000000000000000000000000000000000000000005A00000000susemanager-schema/upgrade/susemanager-schema-4.2.42-to-susemanager-schema-4.3.0/.gitkeep 07070100000EAE000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005100000000susemanager-schema/upgrade/susemanager-schema-4.2.43-to-susemanager-schema-4.3.0  07070100000EAF000081B400000000000000000000000167AE111400000000000000000000000000000000000000000000005A00000000susemanager-schema/upgrade/susemanager-schema-4.2.43-to-susemanager-schema-4.3.0/.gitkeep 07070100000EB0000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005100000000susemanager-schema/upgrade/susemanager-schema-4.2.44-to-susemanager-schema-4.3.0  07070100000EB1000081B400000000000000000000000167AE111400000000000000000000000000000000000000000000005A00000000susemanager-schema/upgrade/susemanager-schema-4.2.44-to-susemanager-schema-4.3.0/.gitkeep 07070100000EB2000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005100000000susemanager-schema/upgrade/susemanager-schema-4.2.45-to-susemanager-schema-4.3.0  07070100000EB3000081B400000000000000000000000167AE111400000000000000000000000000000000000000000000005A00000000susemanager-schema/upgrade/susemanager-schema-4.2.45-to-susemanager-schema-4.3.0/.gitkeep 07070100000EB4000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005100000000susemanager-schema/upgrade/susemanager-schema-4.2.46-to-susemanager-schema-4.3.0  07070100000EB5000081B400000000000000000000000167AE111400000000000000000000000000000000000000000000005A00000000susemanager-schema/upgrade/susemanager-schema-4.2.46-to-susemanager-schema-4.3.0/.gitkeep 07070100000EB6000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005100000000susemanager-schema/upgrade/susemanager-schema-4.2.47-to-susemanager-schema-4.3.0  07070100000EB7000081B400000000000000000000000167AE111400000000000000000000000000000000000000000000005A00000000susemanager-schema/upgrade/susemanager-schema-4.2.47-to-susemanager-schema-4.3.0/.gitkeep 07070100000EB8000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005100000000susemanager-schema/upgrade/susemanager-schema-4.2.48-to-susemanager-schema-4.3.0  07070100000EB9000081B400000000000000000000000167AE111400000000000000000000000000000000000000000000005A00000000susemanager-schema/upgrade/susemanager-schema-4.2.48-to-susemanager-schema-4.3.0/.gitkeep 07070100000EBA000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005100000000susemanager-schema/upgrade/susemanager-schema-4.2.49-to-susemanager-schema-4.3.0  07070100000EBB000081B400000000000000000000000167AE111400000000000000000000000000000000000000000000005A00000000susemanager-schema/upgrade/susemanager-schema-4.2.49-to-susemanager-schema-4.3.0/.gitkeep 07070100000EBC000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005000000000susemanager-schema/upgrade/susemanager-schema-4.2.5-to-susemanager-schema-4.2.6   07070100000EBD000081B400000000000000000000000167AE111400000000000000000000000000000000000000000000005900000000susemanager-schema/upgrade/susemanager-schema-4.2.5-to-susemanager-schema-4.2.6/.gitkeep  07070100000EBE000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005100000000susemanager-schema/upgrade/susemanager-schema-4.2.50-to-susemanager-schema-4.3.0  07070100000EBF000081B400000000000000000000000167AE111400000000000000000000000000000000000000000000005A00000000susemanager-schema/upgrade/susemanager-schema-4.2.50-to-susemanager-schema-4.3.0/.gitkeep 07070100000EC0000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005000000000susemanager-schema/upgrade/susemanager-schema-4.2.6-to-susemanager-schema-4.2.7   07070100000EC1000081B400000000000000000000000167AE1114000001C8000000000000000000000000000000000000006E00000000susemanager-schema/upgrade/susemanager-schema-4.2.6-to-susemanager-schema-4.2.7/100-enable-audit-for-salt.sql insert into rhnServerGroupTypeFeature (server_group_type_id, feature_id,
                                       created, modified)
select lookup_sg_type('salt_entitled'), lookup_feature_type('ftr_system_audit'),
        current_timestamp,current_timestamp from dual
where not exists ( select 1 from rhnServerGroupTypeFeature
    where server_group_type_id = lookup_sg_type('salt_entitled')
      and feature_id = lookup_feature_type('ftr_system_audit') );
07070100000EC2000081B400000000000000000000000167AE111400001047000000000000000000000000000000000000006900000000susemanager-schema/upgrade/susemanager-schema-4.2.6-to-susemanager-schema-4.2.7/801-drop-servercrash.sql  DROP VIEW IF EXISTS rhnServerOverview;
DROP VIEW IF EXISTS rhnServerCrashCount;

create or replace view
rhnServerOverview
(
    org_id,
    server_id,
    server_name,
    modified,
    server_admins,
    group_count,
    channel_id,
    channel_labels,
    history_count,
    security_errata,
    bug_errata,
    enhancement_errata,
    outdated_packages,
	config_files_with_differences,
    last_checkin_days_ago,
    last_checkin,
    pending_updates,
    os,
    release,
    server_arch_name,
    locked,
    proxy_id
)
as
select
    s.org_id, s.id, s.name, s.modified,
    ( select count(user_id) from rhnUserServerPerms ap
      where server_id = s.id ),
    ( select count(server_group_id) from rhnVisibleServerGroupMembers
      where server_id = s.id ),
    ( select C.id
        from rhnChannel C,
	     rhnServerChannel SC
       where SC.server_id = S.id
         and SC.channel_id = C.id
	 and C.parent_channel IS NULL),
    coalesce(( select C.name
        from rhnChannel C,
	     rhnServerChannel SC
       where SC.server_id = S.id
         and SC.channel_id = C.id
	 and C.parent_channel IS NULL), '(none)'),
    ( select count(id) from rhnServerHistory
      where
            server_id = S.id),
    ( select count(*) from rhnServerErrataTypeView setv
      where
            setv.server_id = s.id
        and setv.errata_type = 'Security Advisory'),
    ( select count(*) from rhnServerErrataTypeView setv
      where
            setv.server_id = s.id
        and setv.errata_type = 'Bug Fix Advisory'),
    ( select count(*) from rhnServerErrataTypeView setv
      where
            setv.server_id = s.id
        and setv.errata_type = 'Product Enhancement Advisory'),
    ( select count(distinct p.name_id) from rhnPackage p, rhnServerNeededCache snc
      where
             snc.server_id = S.id
	 and p.id = snc.package_id
	 ),
    ( select count(*)
        from rhnActionConfigRevision ACR
             INNER JOIN rhnActionConfigRevisionResult ACRR on ACR.id = ACRR.action_config_revision_id
       where ACR.server_id = S.id
         and ACR.action_id = (
              select MAX(rA.id)
                from rhnAction rA
                     INNER JOIN rhnServerAction rSA on rSA.action_id = rA.id
                     INNER JOIN rhnActionStatus rAS on rAS.id = rSA.status
                     INNER JOIN rhnActionType rAT on rAT.id = rA.action_type
               where rSA.server_id = S.id
                 and rAS.name in ('Completed', 'Failed')
                 and rAT.label = 'configfiles.diff'
         )
         and ACR.failure_id is null
         and ACRR.result is not null
        ),
    ( select date_diff_in_days(checkin, current_timestamp) from rhnServerInfo where server_id = S.id ),
    ( select TO_CHAR(checkin, 'YYYY-MM-DD HH24:MI:SS') from rhnServerInfo where server_id = S.id ),
    ( select count(1)
        from rhnServerAction
       where server_id = S.id
         and status in (0, 1)),
    os,
    release,
    ( select name from rhnServerArch where id = s.server_arch_id),
    coalesce((select 1 from rhnServerLock SL WHERE SL.server_id = S.id), 0),
    ( select pxy.server_Id from rhnProxyInfo pxy where pxy.server_id = S.id)
from
    rhnServer S
;

DROP TRIGGER IF EXISTS rhn_server_crash_mod_trig ON rhnServerCrash;
DROP TRIGGER IF EXISTS rhn_server_crash_file_mod_trig ON rhnServerCrashFile;
DROP TRIGGER IF EXISTS rhn_server_crash_note_mod_trig ON rhnServerCrashNote;

DROP FUNCTION IF EXISTS insert_crash_file();
DROP FUNCTION IF EXISTS rhn_server_crash_mod_trig_fun();
DROP FUNCTION IF EXISTS rhn_server_crash_file_mod_trig_fun();
DROP FUNCTION IF EXISTS rhn_server_crash_note_mod_trig_fun();

DROP TABLE IF EXISTS rhnServerCrashFile;
DROP TABLE IF EXISTS rhnServerCrashNote;
DROP TABLE IF EXISTS rhnServerCrash;

DROP SEQUENCE IF EXISTS rhn_server_crash_id_seq;
DROP SEQUENCE IF EXISTS rhn_server_crash_file_id_seq;
DROP SEQUENCE IF EXISTS rhn_srv_crash_note_id_seq;

ALTER TABLE rhnOrgConfiguration DROP COLUMN IF EXISTS crash_reporting_enabled;
ALTER TABLE rhnOrgConfiguration DROP COLUMN IF EXISTS crashfile_upload_enabled;
ALTER TABLE rhnOrgConfiguration DROP COLUMN IF EXISTS crash_file_sizelimit;
 07070100000EC3000081B400000000000000000000000167AE11140000011D000000000000000000000000000000000000006C00000000susemanager-schema/upgrade/susemanager-schema-4.2.6-to-susemanager-schema-4.2.7/900-actionchaindispatch.sql   ALTER TABLE rhnActionChain DROP CONSTRAINT IF EXISTS rhn_actionchain_dispatched_ck;
ALTER TABLE rhnActionChain ADD COLUMN IF NOT EXISTS dispatched CHAR(1) DEFAULT ('N') NOT NULL;
ALTER TABLE rhnActionChain ADD CONSTRAINT rhn_actionchain_dispatched_ck CHECK (dispatched in ('Y', 'N'));
   07070100000EC4000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005000000000susemanager-schema/upgrade/susemanager-schema-4.2.7-to-susemanager-schema-4.2.8   07070100000EC5000081B400000000000000000000000167AE111400000102000000000000000000000000000000000000006B00000000susemanager-schema/upgrade/susemanager-schema-4.2.7-to-susemanager-schema-4.2.8/001-rename-memory-size.sql    DO $$
BEGIN
  IF EXISTS(SELECT *
    FROM information_schema.columns
    WHERE table_name='rhnvirtualinstanceinfo' and column_name='memory_size_k')
  THEN
      ALTER TABLE rhnVirtualInstanceInfo RENAME COLUMN memory_size_k TO memory_size;
  END IF;
END $$;
  07070100000EC6000081B400000000000000000000000167AE111400000048000000000000000000000000000000000000006900000000susemanager-schema/upgrade/susemanager-schema-4.2.7-to-susemanager-schema-4.2.8/500-rhnbuild-version.sql  alter table rhnActionImageBuild alter COLUMN version TYPE VARCHAR(128);
07070100000EC7000081B400000000000000000000000167AE11140000009A000000000000000000000000000000000000007100000000susemanager-schema/upgrade/susemanager-schema-4.2.7-to-susemanager-schema-4.2.8/801-drop-pxt_session_cleanup.sql  drop function if exists pxt_session_cleanup
   (bound_in in numeric, commit_interval in numeric,
    batch_size in numeric, sessions_deleted in numeric);
  07070100000EC8000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005000000000susemanager-schema/upgrade/susemanager-schema-4.2.8-to-susemanager-schema-4.2.9   07070100000EC9000081B400000000000000000000000167AE111400000046000000000000000000000000000000000000006800000000susemanager-schema/upgrade/susemanager-schema-4.2.8-to-susemanager-schema-4.2.9/100-password-length.sql   alter table susecredentials alter column password type varchar(4096);
  07070100000ECA000081B400000000000000000000000167AE1114000001C3000000000000000000000000000000000000006800000000susemanager-schema/upgrade/susemanager-schema-4.2.8-to-susemanager-schema-4.2.9/701-rhn_server_fqdn.sql   ALTER TABLE rhnServerFQDN ADD COLUMN IF NOT EXISTS is_primary CHAR(1) DEFAULT ('N') NOT NULL;

UPDATE rhnServerFQDN f1 SET is_primary = 'Y'
WHERE f1.name = (SELECT MIN(f2.name) FROM rhnServerFQDN f2 WHERE f2.server_id = f1.server_id)
AND NOT EXISTS (SELECT 1 FROM rhnServerFQDN f3 WHERE f3.server_id = f1.server_id AND is_primary='Y');

CREATE UNIQUE INDEX IF NOT EXISTS rhn_srv_fqdn_prim_fqdn
  ON rhnServerFQDN
  (server_id) where is_primary = 'Y';
 07070100000ECB000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005100000000susemanager-schema/upgrade/susemanager-schema-4.2.9-to-susemanager-schema-4.2.10  07070100000ECC000081B400000000000000000000000167AE111400000371000000000000000000000000000000000000007800000000susemanager-schema/upgrade/susemanager-schema-4.2.9-to-susemanager-schema-4.2.10/001-add_virt_network_create_action.sql   -- Copyright (c) 2021 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

insert into rhnActionType (id, label, name, trigger_snapshot, unlocked_only, maintenance_mode_only) (
    select 520, 'virt.network_create', 'Creates a virtual network', 'N', 'N', 'N'
    from dual
    where not exists (select 1 from rhnActionType where id = 520)
);
   07070100000ECD000081B400000000000000000000000167AE11140000071B000000000000000000000000000000000000007000000000susemanager-schema/upgrade/susemanager-schema-4.2.9-to-susemanager-schema-4.2.10/001-rhnaction-vendorchange.sql   --
-- Copyright (c) 2021 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

CREATE TABLE IF NOT EXISTS rhnActionPackageDetails
(
    id         NUMERIC NOT NULL
               CONSTRAINT rhn_actionpd_id_pk PRIMARY KEY,
    action_id  NUMERIC NOT NULL
                   CONSTRAINT rhn_act_eu_act_fk
                       REFERENCES rhnAction (id)
                       ON DELETE CASCADE,
    allow_vendor_change  CHAR(1) DEFAULT ('N') NOT NULL 
    CONSTRAINT rhn_actdet_avc_ck CHECK (allow_vendor_change in ('Y','N')),

    created   TIMESTAMPTZ
                  DEFAULT (current_timestamp) NOT NULL,
    modified  TIMESTAMPTZ
                  DEFAULT (current_timestamp) NOT NULL

);

CREATE INDEX IF NOT EXISTS rhn_act_eud_aid_idx
    ON rhnActionPackageDetails (action_id);

CREATE SEQUENCE IF NOT EXISTS rhn_actiondpd_id_seq;

create or replace function rhn_actionpackagedetails_mod_trig_fun() returns trigger as
$$
begin
        new.modified := current_timestamp;
        return new;
end;
$$ language plpgsql;

drop trigger if exists rhn_actionpackagedetails_mod_trig on rhnActionPackageDetails;
create trigger
rhn_actionpackagedetails_mod_trig
before insert or update on rhnActionPackageDetails
for each row
execute procedure rhn_actionpackagedetails_mod_trig_fun();
 07070100000ECE000081B400000000000000000000000167AE1114000004CB000000000000000000000000000000000000007400000000susemanager-schema/upgrade/susemanager-schema-4.2.9-to-susemanager-schema-4.2.10/002-rhnActionVirtNetworkCreate.sql   -- Copyright (c) 2021 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

CREATE TABLE IF NOT EXISTS rhnActionVirtNetworkCreate
(
    action_id            NUMERIC NOT NULL
                             CONSTRAINT rhn_action_virt_network_create_aid_fk
                                 REFERENCES rhnAction (id)
                                 ON DELETE CASCADE
                             CONSTRAINT rhn_action_virt_network_create_aid_pk
                                 PRIMARY KEY,
    network_name         VARCHAR(256),
    definition           VARCHAR(2048)
)
;

CREATE UNIQUE INDEX IF NOT EXISTS rhn_action_virt_network_create_aid_uq
    ON rhnActionVirtNetworkCreate (action_id);

 07070100000ECF000081B400000000000000000000000167AE11140000014F000000000000000000000000000000000000006700000000susemanager-schema/upgrade/susemanager-schema-4.2.9-to-susemanager-schema-4.2.10/010-errata-status.sql    ALTER TABLE rhnErrata DROP CONSTRAINT IF EXISTS rhn_errata_adv_status_ck;
ALTER TABLE rhnErrata ADD COLUMN IF NOT EXISTS
    advisory_status   VARCHAR(32) NOT NULL DEFAULT('final');
ALTER TABLE rhnErrata ADD
    CONSTRAINT rhn_errata_adv_status_ck
    CHECK (advisory_status in ('final', 'stable', 'testing', 'pending', 'retracted'));
 07070100000ED0000081B400000000000000000000000167AE111400000203000000000000000000000000000000000000007F00000000susemanager-schema/upgrade/susemanager-schema-4.2.9-to-susemanager-schema-4.2.10/011-susechannelpackageretractedstatusview.sql    CREATE OR REPLACE VIEW suseChannelPackageRetractedStatusView AS
 SELECT
    cp.channel_id,
    cp.package_id,
    CASE
        WHEN (EXISTS ( SELECT 1
           FROM rhnchannelerrata ce
             JOIN rhnerrata e ON ce.errata_id = e.id
             JOIN rhnerratapackage ep ON ep.errata_id = e.id
          WHERE e.advisory_status::text = 'retracted'::text AND ce.channel_id = cp.channel_id AND ep.package_id = cp.package_id)) THEN true
        ELSE false
    END AS is_retracted
   FROM rhnchannelpackage cp;

 07070100000ED1000081B400000000000000000000000167AE1114000001E4000000000000000000000000000000000000008000000000susemanager-schema/upgrade/susemanager-schema-4.2.9-to-susemanager-schema-4.2.10/012-suseserverchannelretractedpackagesview.sql   CREATE OR REPLACE VIEW suseServerChannelsRetractedPackagesView AS
 SELECT DISTINCT p.id AS pid,
    s.id AS sid
   FROM rhnserver s
     JOIN rhnserverchannel sc ON s.id = sc.server_id
     JOIN rhnchannel c ON c.id = sc.channel_id
     JOIN rhnchannelerrata ce ON ce.channel_id = c.id
     JOIN rhnerrata e ON e.id = ce.errata_id
     JOIN rhnerratapackage ep ON ep.errata_id = e.id
     JOIN rhnpackage p ON p.id = ep.package_id
  WHERE e.advisory_status::text = 'retracted'::text;
07070100000ED2000081B400000000000000000000000167AE111400000861000000000000000000000000000000000000006F00000000susemanager-schema/upgrade/susemanager-schema-4.2.9-to-susemanager-schema-4.2.10/013-update-rhn_server.pkb.sql    --update pg_setting
update pg_settings set setting = 'rhn_server,' || setting where name = 'search_path';

    create or replace function update_needed_cache(
        server_id_in in numeric
	) returns void as $$
    begin
      delete from rhnServerNeededCache
        where server_id = server_id_in;
      insert into rhnServerNeededCache
             (server_id, errata_id, package_id, channel_id)
        (select distinct sp.server_id, x.errata_id, p.id, x.channel_id
           FROM (SELECT sp_sp.server_id, sp_sp.name_id,
		        sp_sp.package_arch_id, max(sp_pe.evr) AS max_evr
                   FROM rhnServerPackage sp_sp
                   join rhnPackageEvr sp_pe ON sp_pe.id = sp_sp.evr_id
                  GROUP BY sp_sp.server_id, sp_sp.name_id, sp_sp.package_arch_id) sp
           join rhnPackage p ON p.name_id = sp.name_id
           join rhnPackageEvr pe ON pe.id = p.evr_id AND (sp.max_evr).type = (pe.evr).type AND sp.max_evr < pe.evr
           join rhnPackageUpgradeArchCompat puac
	            ON puac.package_arch_id = sp.package_arch_id
		    AND puac.package_upgrade_arch_id = p.package_arch_id
           join rhnServerChannel sc ON sc.server_id = sp.server_id
           join rhnChannelPackage cp ON cp.package_id = p.id
	            AND cp.channel_id = sc.channel_id
           left join (SELECT ep.errata_id, ce.channel_id, ep.package_id
                        FROM rhnChannelErrata ce
                        join rhnErrataPackage ep
			         ON ep.errata_id = ce.errata_id
			join rhnServerChannel sc_sc
			         ON sc_sc.channel_id = ce.channel_id
		       WHERE sc_sc.server_id = server_id_in) x
             ON x.channel_id = sc.channel_id AND x.package_id = cp.package_id
	   left join rhnErrata e on x.errata_id = e.id
          where sp.server_id = server_id_in
            and (x.errata_id IS NULL or e.advisory_status != 'retracted')); -- packages which are part of a retracted errata should not be installed
	end$$ language plpgsql;
-- restore the original setting
update pg_settings set setting = overlay( setting placing '' from 1 for (length('rhn_server')+1) ) where name = 'search_path';
   07070100000ED3000081B400000000000000000000000167AE1114000009B5000000000000000000000000000000000000007300000000susemanager-schema/upgrade/susemanager-schema-4.2.9-to-susemanager-schema-4.2.10/014-update_image_needed_cache.sql    --
-- Copyright (c) 2017 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--

create or replace function
update_image_needed_cache(image_id_in in numeric)
returns void as $$
declare
  update_lock numeric;
begin
  select id into update_lock from suseImageInfo where id = image_id_in for update;
  delete from rhnImageNeededCache
   where image_id = image_id_in;
  insert into rhnImageNeededCache
         (image_id, errata_id, package_id, channel_id)
    (select distinct ip.image_info_id, x.errata_id, p.id, x.channel_id
       FROM (SELECT ip_ip.image_info_id, ip_ip.name_id,
                    ip_ip.package_arch_id, max(ip_pe.evr) AS max_evr
               FROM suseImageInfoPackage ip_ip
               join rhnPackageEvr ip_pe ON ip_pe.id = ip_ip.evr_id
              GROUP BY ip_ip.image_info_id, ip_ip.name_id, ip_ip.package_arch_id) ip
       join rhnPackage p ON p.name_id = ip.name_id
       join rhnPackageEvr pe ON pe.id = p.evr_id
                AND (ip.max_evr).type = (pe.evr).type AND ip.max_evr < pe.evr
       join rhnPackageUpgradeArchCompat puac
                ON puac.package_arch_id = ip.package_arch_id
                AND puac.package_upgrade_arch_id = p.package_arch_id
       join suseImageInfoChannel ic ON ic.image_info_id = ip.image_info_id
       join rhnChannelPackage cp ON cp.package_id = p.id
                AND cp.channel_id = ic.channel_id
       left join (SELECT ep.errata_id, ce.channel_id, ep.package_id
                    FROM rhnChannelErrata ce
                    join rhnErrataPackage ep
                             ON ep.errata_id = ce.errata_id
                    join suseImageInfoChannel ic_ic
                             ON ic_ic.channel_id = ce.channel_id
                   WHERE ic_ic.image_info_id = image_id_in) x
         ON x.channel_id = ic.channel_id
                AND x.package_id = cp.package_id
       left join rhnErrata e on x.errata_id = e.id
      where ip.image_info_id = image_id_in
        and (x.errata_id IS NULL or e.advisory_status != 'retracted')); -- packages which are part of a retracted errata should not be installed
end;
$$
language plpgsql;
   07070100000ED4000081B400000000000000000000000167AE111400000141000000000000000000000000000000000000007900000000susemanager-schema/upgrade/susemanager-schema-4.2.9-to-susemanager-schema-4.2.10/015-add-clm-sync-patches-org-config.sql  ALTER TABLE rhnOrgConfiguration DROP CONSTRAINT IF EXISTS rhn_org_conf_clm_sync_patches;

ALTER TABLE rhnOrgConfiguration ADD COLUMN IF NOT EXISTS clm_sync_patches CHAR(1)
    DEFAULT('Y') NOT NULL;

ALTER TABLE rhnOrgConfiguration ADD CONSTRAINT rhn_org_conf_clm_sync_patches
    CHECK (clm_sync_patches in ('Y', 'N'));
   07070100000ED5000081B400000000000000000000000167AE11140000072E000000000000000000000000000000000000008300000000susemanager-schema/upgrade/susemanager-schema-4.2.9-to-susemanager-schema-4.2.10/015-ignore-retracted-pkgs-in-newest-pkgs-view.sql    --
-- Copyright (c) 2021 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--

create or replace view
rhnChannelNewestPackageView
as
SELECT channel_id,
       name_id,
       evr_id,
       package_arch_id,
       max(package_id) as package_id
FROM (
       SELECT m.channel_id          as channel_id,
              p.name_id             as name_id,
              p.evr_id              as evr_id,
              m.package_arch_id     as package_arch_id,
              p.id                  as package_id
         FROM
              (select max(pe.evr) AS max_evr,
                      cp.channel_id,
                      p.name_id,
                      p.package_arch_id
                 from rhnPackageEVR                           pe,
                      rhnPackage                              p,
                      suseChannelPackageRetractedStatusView   cp
                where p.evr_id = pe.id
                  and cp.package_id = p.id
                  and NOT cp.is_retracted
                group by cp.channel_id, p.name_id, p.package_arch_id) m,
              rhnPackageEVR       pe,
              rhnPackage          p,
              rhnChannelPackage   chp
        WHERE m.max_evr = pe.evr
          AND m.name_id = p.name_id
          AND m.package_arch_id = p.package_arch_id
          AND p.evr_id = pe.id
          AND chp.package_id = p.id
          AND chp.channel_id = m.channel_id
) latest_packages
group by channel_id, name_id, evr_id, package_arch_id
;

  07070100000ED6000081B400000000000000000000000167AE11140000025A000000000000000000000000000000000000007800000000susemanager-schema/upgrade/susemanager-schema-4.2.9-to-susemanager-schema-4.2.10/100-increase-kernel-options-length.sql   ALTER TABLE rhnKickstartableTree ALTER COLUMN kernel_options TYPE VARCHAR(2048);
ALTER TABLE rhnKickstartableTree ALTER COLUMN kernel_options_post TYPE VARCHAR(2048);
ALTER TABLE rhnKSData ALTER COLUMN kernel_params TYPE VARCHAR(2048);
DO $$
    BEGIN
        IF EXISTS
            (
                SELECT 1
                FROM information_schema.columns
                WHERE table_name='rhnactionvirtcreate' AND column_name='vm_type'
            )
        THEN
            ALTER TABLE rhnActionVirtCreate ALTER COLUMN kernel_options TYPE VARCHAR(2048);
        END IF;
    END
$$ LANGUAGE plpgsql;
  07070100000ED7000081B400000000000000000000000167AE111400000357000000000000000000000000000000000000006100000000susemanager-schema/upgrade/susemanager-schema-4.2.9-to-susemanager-schema-4.2.10/300-alibaba.sql  --EPEL 8
insert into rhnPackageKey (id, key_id, key_type_id, provider_id)
    (select sequence_nextval('rhn_pkey_id_seq'), '21ea45ab2f86d6a1', lookup_package_key_type('gpg'),
    lookup_package_provider('EPEL') from dual
    where not exists (select 1 from rhnPackageKey where key_id = '21ea45ab2f86d6a1'));

insert into rhnPackageProvider (id, name)
    (select sequence_nextval('rhn_package_provider_id_seq'), 'Alibaba' from dual
    where not exists (select 1 from rhnPackageProvider where name = 'Alibaba'));

-- Alibaba Cloud Linux 2.1903
insert into rhnPackageKey (id, key_id, key_type_id, provider_id)
    (select sequence_nextval('rhn_pkey_id_seq'), 'eb801c41873141a8', lookup_package_key_type('gpg'),
    lookup_package_provider('Alibaba') from dual
    where not exists (select 1 from rhnPackageKey where key_id = 'eb801c41873141a8'));

commit;
 07070100000ED8000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005000000000susemanager-schema/upgrade/susemanager-schema-4.3.0-to-susemanager-schema-4.3.1   07070100000ED9000081B400000000000000000000000167AE111400000000000000000000000000000000000000000000005900000000susemanager-schema/upgrade/susemanager-schema-4.3.0-to-susemanager-schema-4.3.1/.gitkeep  07070100000EDA000081B400000000000000000000000167AE111400000052000000000000000000000000000000000000007F00000000susemanager-schema/upgrade/susemanager-schema-4.3.0-to-susemanager-schema-4.3.1/0001-rhnActionScap-add-ovalfiles-attribute.sql    ALTER TABLE rhnActionScap ADD COLUMN IF NOT EXISTS
    ovalfiles   VARCHAR(8192);
  07070100000EDB000081B400000000000000000000000167AE1114000003F0000000000000000000000000000000000000006C00000000susemanager-schema/upgrade/susemanager-schema-4.3.0-to-susemanager-schema-4.3.1/001-virt-create-cluster.sql   -- Copyright (c) 2021 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

DO $$
    BEGIN
        IF EXISTS
            (
                SELECT 1
                FROM information_schema.columns
                WHERE table_name='rhnactionvirtcreate' AND column_name='vm_type'
            )
        THEN
            ALTER TABLE rhnActionVirtCreate
                ADD COLUMN IF NOT EXISTS cluster_definitions VARCHAR(2048);
        END IF;
    END
$$ LANGUAGE plpgsql;
07070100000EDC000081B400000000000000000000000167AE1114000000E7000000000000000000000000000000000000006600000000susemanager-schema/upgrade/susemanager-schema-4.3.0-to-susemanager-schema-4.3.1/002-new-timezones.sql insert into rhnTimezone(id, olson_name, display_name) ( 
  select sequence_nextval('rhn_timezone_id_seq'), 'Asia/Beijing', 'China'
    from dual
   where not exists (
	select 1 from rhnTimezone where display_name = 'China'
   )
);
 07070100000EDD000081B400000000000000000000000167AE111400000370000000000000000000000000000000000000006A00000000susemanager-schema/upgrade/susemanager-schema-4.3.0-to-susemanager-schema-4.3.1/002-virt.migrate-type.sql -- Copyright (c) 2021 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

insert into rhnActionType (id, label, name, trigger_snapshot, unlocked_only, maintenance_mode_only) (
    select 522, 'virt.guest_migrate', 'Migrate a virtual domain', 'N', 'N', 'N'
    from dual
    where not exists (select 1 from rhnActionType where id = 522)
);

07070100000EDE000081B400000000000000000000000167AE111400000421000000000000000000000000000000000000006D00000000susemanager-schema/upgrade/susemanager-schema-4.3.0-to-susemanager-schema-4.3.1/003-rhnActionVirtMigrate.sql  -- Copyright (c) 2021 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

CREATE TABLE IF NOT EXISTS rhnActionVirtMigrate
(
    action_id  NUMERIC NOT NULL
                   CONSTRAINT rhn_virt_guest_migrate_aid_fk
                       REFERENCES rhnAction (id)
                       ON DELETE CASCADE
                   CONSTRAINT rhn_action_virt_guest_migrate_aid_pk
                       PRIMARY KEY,
    uuid       VARCHAR(128) NOT NULL,
    primitive  VARCHAR(128),
    target     VARCHAR(128) NOT NULL
)
;
   07070100000EDF000081B400000000000000000000000167AE111400000056000000000000000000000000000000000000006800000000susemanager-schema/upgrade/susemanager-schema-4.3.0-to-susemanager-schema-4.3.1/004-suseKiwiProfile.sql   alter table suseKiwiProfile add column if not exists
    kiwi_options  VARCHAR(1024);
  07070100000EE0000081B400000000000000000000000167AE111400000092000000000000000000000000000000000000007700000000susemanager-schema/upgrade/susemanager-schema-4.3.0-to-susemanager-schema-4.3.1/100-enable-virthost-pillar-refresh.sql    INSERT INTO rhnTaskQueue (org_id, task_name, task_data)
SELECT id, 'upgrade_satellite_virthost_pillar_refresh', 0
FROM web_customer
WHERE id = 1;
  07070100000EE1000081B400000000000000000000000167AE1114000000C4000000000000000000000000000000000000007100000000susemanager-schema/upgrade/susemanager-schema-4.3.0-to-susemanager-schema-4.3.1/100-playbook-action-testmode.sql  ALTER TABLE rhnActionPlaybook ADD COLUMN IF NOT EXISTS
    test_mode CHAR(1) DEFAULT ('N') NOT NULL
        CONSTRAINT rhn_action_playbook_testmode_ck
            CHECK (test_mode IN ('Y', 'N'));
07070100000EE2000081B400000000000000000000000167AE111400000217000000000000000000000000000000000000005E00000000susemanager-schema/upgrade/susemanager-schema-4.3.0-to-susemanager-schema-4.3.1/100-rocky.sql insert into rhnPackageProvider (id, name)
    (select sequence_nextval('rhn_package_provider_id_seq'), 'Rocky Linux' from dual
    where not exists (select 1 from rhnPackageProvider where name = 'Rocky Linux'));

-- Alma Linux 8
insert into rhnPackageKey (id, key_id, key_type_id, provider_id)
    (select sequence_nextval('rhn_pkey_id_seq'), '15af5dac6d745a60', lookup_package_key_type('gpg'),
    lookup_package_provider('Rocky Linux') from dual
    where not exists (select 1 from rhnPackageKey where key_id = '15af5dac6d745a60'));
 07070100000EE3000081B400000000000000000000000167AE1114000012C5000000000000000000000000000000000000007800000000susemanager-schema/upgrade/susemanager-schema-4.3.0-to-susemanager-schema-4.3.1/200-rhnactionvirtcreate-refactoring.sql   DO $$
    BEGIN
        IF EXISTS
            (
                SELECT 1
                FROM information_schema.columns
                WHERE table_name='rhnactionvirtcreate' AND column_name='vm_type'
            )
        THEN
            -- Create the details colument
            ALTER TABLE rhnactionvirtcreate ADD COLUMN IF NOT EXISTS details TEXT;

            -- Convert all data into the details field
            UPDATE rhnactionvirtcreate
            SET details = action_details.json
            FROM
            (
                SELECT a.action_id AS id,
                   CONCAT(
                     '{',
                       CASE WHEN a.uuid IS NOT NULL THEN CONCAT('"uuid": "', a.uuid, '", ') END,
                       '"type": "', a.vm_type, '", ',
                       '"name": "', a.vm_name, '", ',
                       '"osType": "', a.os_type, '", ',
                       '"memory": ', a.memory, ', ',
                       '"vcpu": ', a.vcpus, ', ',
                       '"arch": "', a.arch, '", ',
                       CASE WHEN a.graphics_type IS NOT NULL THEN CONCAT('"graphicsType": "', a.graphics_type, '", ') END,
                       CASE WHEN a.cobbler_system IS NOT NULL THEN CONCAT('"cobbler_system": "', a.cobbler_system, '", ') END,
                       CASE WHEN a.kickstart_host IS NOT NULL THEN CONCAT('"kickstart_host": "', a.kickstart_host , '", ') END,
                       CASE WHEN a.kernel_options IS NOT NULL THEN CONCAT('"kernel_options": "', a.kernel_options , '", ') END,
                       CASE WHEN a.cluster_definitions IS NOT NULL THEN CONCAT('"cluster_definitions": "', a.cluster_definitions, '", ') END,
                       CASE WHEN string_agg(d.json, '') IS NOT NULL THEN CONCAT('"disks": [', string_agg(d.json, ''), '], ') END,
                       CASE WHEN string_agg(i.json, '') IS NOT NULL THEN CONCAT('"interfaces": [', string_agg(i.json, ''), '], ') END,
                       '"remove_disks": ', CASE WHEN a.remove_disks = 'Y' THEN 'true' ELSE 'false' END, ', ',
                       '"remove_interfaces": ', CASE WHEN a.remove_interfaces = 'Y' THEN 'true' ELSE 'false' END,
                     '}'
                   ) AS json
                FROM rhnactionvirtcreate a
                LEFT JOIN (
                  SELECT action_id, CONCAT(
                    '{',
                        CASE WHEN bus IS NOT NULL THEN CONCAT('"bus": "', bus, '", ') END,
                        CASE WHEN format IS NOT NULL THEN CONCAT('"format": "', format, '", ') END,
                        CASE WHEN pool IS NOT NULL THEN CONCAT('"pool": "', pool, '", ') END,
                        CASE WHEN source_file IS NOT NULL THEN CONCAT('"source_file": "', source_file, '",') END,
                        '"size": ', size, ', '
                        '"device": "', device, '"'
                    '}'
                  ) AS json
                  FROM rhnactionvirtcreatediskdetails
                ) AS d ON a.action_id = d.action_id
                LEFT JOIN (
                  SELECT action_id, CONCAT(
                    '{',
                      CASE WHEN mac IS NOT NULL THEN CONCAT('"mac": "', mac, '", ') END,
                      '"type": "', type, '", '
                      '"source": "', source, '"'
                    '}'
                  ) AS json
                  FROM rhnactionvirtcreateinterfacedetails
                ) AS i ON a.action_id = i.action_id
                GROUP BY a.action_id
            ) AS action_details
            WHERE action_id = action_details.id;

            -- Remove the now useless columns and tables
            ALTER TABLE rhnactionvirtcreate
                DROP COLUMN IF EXISTS vm_type CASCADE,
                DROP COLUMN IF EXISTS vm_name CASCADE,
                DROP COLUMN IF EXISTS os_type CASCADE,
                DROP COLUMN IF EXISTS memory,
                DROP COLUMN IF EXISTS vcpus,
                DROP COLUMN IF EXISTS arch CASCADE,
                DROP COLUMN IF EXISTS graphics_type CASCADE,
                DROP COLUMN IF EXISTS remove_disks,
                DROP COLUMN IF EXISTS remove_interfaces,
                DROP COLUMN IF EXISTS cobbler_system CASCADE,
                DROP COLUMN IF EXISTS kickstart_host CASCADE,
                DROP COLUMN IF EXISTS kernel_options CASCADE,
                DROP COLUMN IF EXISTS cluster_definitions;
            DROP TABLE IF EXISTS rhnactionvirtcreatediskdetails, rhnactionvirtcreateinterfacedetails;
            DROP INDEX IF EXISTS rhn_action_virt_create_disk_details_id_idx, rhn_action_virt_create_iface_details_id_idx;
            DROP SEQUENCE IF EXISTS rhn_action_virt_create_disk_details_id_seq, rhn_action_virt_create_iface_details_id_seq;
        END IF;
    END
$$ LANGUAGE plpgsql;
   07070100000EE4000081B400000000000000000000000167AE1114000007DE000000000000000000000000000000000000006900000000susemanager-schema/upgrade/susemanager-schema-4.3.0-to-susemanager-schema-4.3.1/300-fix-entitlements.sql  -- Copyright (c) 2021 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

-- First determine which systems belong to wrong entitlement groups
CREATE TEMPORARY VIEW rhnWrongEntitlements AS
  SELECT t1.id, t1.group_id AS wrong_id, t2.id AS right_id
  FROM (SELECT s1.org_id, s1.id, s2.group_id, s2.group_type
    FROM rhnserver AS s1
    JOIN rhnservergroupmembership AS s2
    ON s1.id=s2.server_id
    WHERE s1.org_id != s2.org_id) AS t1
  JOIN (SELECT s1.id, org_id, label
    FROM rhnservergroup AS s1
    JOIN rhnservergrouptype AS s2
    ON group_type=s2.id) AS t2
  ON t1.group_type = t2.label AND t1.org_id = t2.org_id;

-- Update wrong entitlements to the right ones
UPDATE rhnServerGroupMembers
SET server_group_id = rhnWrongEntitlements.right_id
FROM rhnWrongEntitlements
WHERE
  rhnServerGroupMembers.server_id = rhnWrongEntitlements.id
  AND rhnServerGroupMembers.server_group_id = rhnWrongEntitlements.wrong_id;

-- Next we also need to update the member count of each group
-- We set current members to 0 for all the groups to also account for groups
-- that don't have any systems assigned to them.
UPDATE rhnServerGroup
SET current_members = 0;

-- Count the number of systems that belong to each group and
-- set the correct member count
UPDATE rhnServerGroup
SET current_members = t1.count
FROM
  (SELECT server_group_id, count(server_id)
  FROM rhnservergroupmembers
  GROUP BY server_group_id) AS t1
WHERE rhnServerGroup.id = t1.server_group_id;

COMMIT;
  07070100000EE5000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005000000000susemanager-schema/upgrade/susemanager-schema-4.3.1-to-susemanager-schema-4.3.2   07070100000EE6000081B400000000000000000000000167AE1114000004D8000000000000000000000000000000000000006D00000000susemanager-schema/upgrade/susemanager-schema-4.3.1-to-susemanager-schema-4.3.2/001-package-lock-feature.sql  insert into rhnFeature (id, label, name, created, modified)
  select sequence_nextval('rhn_feature_seq'), 'ftr_package_lock', 'Lock Packages',
         current_timestamp, current_timestamp from dual
   where not exists (select 1 from rhnFeature where label = 'ftr_package_lock');

insert into rhnServerGroupTypeFeature (server_group_type_id, feature_id, created, modified)
  select lookup_sg_type('enterprise_entitled'), lookup_feature_type('ftr_package_lock'),
         current_timestamp,current_timestamp from dual
   where not exists ( select 1 from rhnServerGroupTypeFeature
                              where server_group_type_id = lookup_sg_type('enterprise_entitled')
                              and feature_id = lookup_feature_type('ftr_package_lock') );

insert into rhnServerGroupTypeFeature (server_group_type_id, feature_id, created, modified)
  select lookup_sg_type('salt_entitled'), lookup_feature_type('ftr_package_lock'),
         current_timestamp,current_timestamp from dual
   where not exists ( select 1 from rhnServerGroupTypeFeature
                              where server_group_type_id = lookup_sg_type('salt_entitled')
                              and feature_id = lookup_feature_type('ftr_package_lock') );
07070100000EE7000081B400000000000000000000000167AE1114000004A0000000000000000000000000000000000000007A00000000susemanager-schema/upgrade/susemanager-schema-4.3.1-to-susemanager-schema-4.3.2/002-ansible-entitlement-for-all-archs.sql INSERT INTO rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
SELECT
    lookup_server_arch('aarch64-redhat-linux'),
    lookup_sg_type('ansible_control_node')
WHERE NOT EXISTS (
    SELECT 1
    FROM rhnServerServerGroupArchCompat
    WHERE server_arch_id = lookup_server_arch('aarch64-redhat-linux')
        AND server_group_type = lookup_sg_type('ansible_control_node')
);

INSERT INTO rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
SELECT
    lookup_server_arch('ppc64le-redhat-linux'),
    lookup_sg_type('ansible_control_node')
WHERE NOT EXISTS (
    SELECT 1
    FROM rhnServerServerGroupArchCompat
    WHERE server_arch_id = lookup_server_arch('ppc64le-redhat-linux')
        AND server_group_type = lookup_sg_type('ansible_control_node')
);

INSERT INTO rhnServerServerGroupArchCompat ( server_arch_id, server_group_type )
SELECT
    lookup_server_arch('s390x-redhat-linux'),
    lookup_sg_type('ansible_control_node')
WHERE NOT EXISTS (
    SELECT 1
    FROM rhnServerServerGroupArchCompat
    WHERE server_arch_id = lookup_server_arch('s390x-redhat-linux')
        AND server_group_type = lookup_sg_type('ansible_control_node')
);

07070100000EE8000081B400000000000000000000000167AE1114000000E4000000000000000000000000000000000000007400000000susemanager-schema/upgrade/susemanager-schema-4.3.1-to-susemanager-schema-4.3.2/310-add-pending-advisory-status.sql   ALTER TABLE rhnErrata DROP CONSTRAINT IF EXISTS rhn_errata_adv_status_ck;
ALTER TABLE rhnErrata ADD
    CONSTRAINT rhn_errata_adv_status_ck
    CHECK (advisory_status in ('final', 'stable', 'testing', 'pending', 'retracted'));

07070100000EE9000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005200000000susemanager-schema/upgrade/susemanager-schema-4.3.10-to-susemanager-schema-4.3.11 07070100000EEA000081B400000000000000000000000167AE111400000099000000000000000000000000000000000000007D00000000susemanager-schema/upgrade/susemanager-schema-4.3.10-to-susemanager-schema-4.3.11/001-rhnActionDup-add-missing_successor.sql  -- add the new column to store the products which have no successors

ALTER TABLE rhnActionDup ADD COLUMN IF NOT EXISTS missing_successors VARCHAR(512);
   07070100000EEB000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005200000000susemanager-schema/upgrade/susemanager-schema-4.3.11-to-susemanager-schema-4.3.12 07070100000EEC000081B400000000000000000000000167AE111400000041000000000000000000000000000000000000006900000000susemanager-schema/upgrade/susemanager-schema-4.3.11-to-susemanager-schema-4.3.12/900-vacuum-analyze.sql  -- force a vacuum analyze after this update runs
VACUUM ANALYZE;
   07070100000EED000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005200000000susemanager-schema/upgrade/susemanager-schema-4.3.12-to-susemanager-schema-4.3.13 07070100000EEE000081B400000000000000000000000167AE1114000001F5000000000000000000000000000000000000008100000000susemanager-schema/upgrade/susemanager-schema-4.3.12-to-susemanager-schema-4.3.13/001-add-gpgkey-to-suseProductSCCRepository.sql  DO $$
  BEGIN
    IF EXISTS (SELECT 1 FROM information_schema.tables WHERE table_name = 'suseproductsccrepository') THEN

      ALTER TABLE suseProductSCCRepository ADD COLUMN IF NOT EXISTS gpg_key_url  VARCHAR(256);
      ALTER TABLE suseProductSCCRepository ADD COLUMN IF NOT EXISTS gpg_key_id   VARCHAR(14);
      ALTER TABLE suseProductSCCRepository ADD COLUMN IF NOT EXISTS gpg_key_fp   VARCHAR(50);

    ELSE
      RAISE NOTICE 'suseProductSCCRepository does not exists';
    END IF;
  END;
$$;
   07070100000EEF000081B400000000000000000000000167AE111400001690000000000000000000000000000000000000007300000000susemanager-schema/upgrade/susemanager-schema-4.3.12-to-susemanager-schema-4.3.13/010-uyuni-gpg-key-url-update.sql    
update rhnchannel set
gpg_key_url = 'file:///etc/pki/rpm-gpg/RPM-GPG-KEY-centosofficial' where
gpg_key_url = 'http://mirror.centos.org/centos/RPM-GPG-KEY-CentOS-Official';

update rhnchannel set
gpg_key_url = 'file:///etc/pki/rpm-gpg/uyuni-tools-gpg-pubkey-0d20833e.key' where
gpg_key_url = 'https://download.opensuse.org/repositories/systemsmanagement:/Uyuni:/Stable:/EL8-Uyuni-Client-Tools/EL_8/repodata/repomd.xml.key';

update rhnchannel set
gpg_key_url = 'file:///etc/pki/rpm-gpg/uyuni-tools-gpg-pubkey-0d20833e.key' where
gpg_key_url = 'https://download.opensuse.org/repositories/systemsmanagement:/Uyuni:/Master:/EL8-Uyuni-Client-Tools/EL_8/repodata/repomd.xml.key';

update rhnchannel set
gpg_key_url = 'file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-7' where
gpg_key_url = 'http://mirror.centos.org/centos/RPM-GPG-KEY-CentOS-7';

update rhnchannel set
gpg_key_url = 'file:///etc/pki/rpm-gpg/uyuni-tools-gpg-pubkey-0d20833e.key' where
gpg_key_url = 'https://download.opensuse.org/repositories/systemsmanagement:/Uyuni:/Stable:/CentOS7-Uyuni-Client-Tools/CentOS_7/repodata/repomd.xml.key';

update rhnchannel set
gpg_key_url = 'file:///etc/pki/rpm-gpg/uyuni-tools-gpg-pubkey-0d20833e.key' where
gpg_key_url = 'https://download.opensuse.org/repositories/systemsmanagement:/Uyuni:/Master:/CentOS7-Uyuni-Client-Tools/CentOS_7/repodata/repomd.xml.key';

update rhnchannel set
gpg_key_url = 'file:///etc/pki/rpm-gpg/uyuni-tools-gpg-pubkey-0d20833e.key' where
gpg_key_url = 'https://download.opensuse.org/repositories/systemsmanagement:/Uyuni:/Stable:/CentOS6-Uyuni-Client-Tools/CentOS_6/repodata/repomd.xml.key';

update rhnchannel set
gpg_key_url = 'file:///etc/pki/rpm-gpg/uyuni-tools-gpg-pubkey-0d20833e.key' where
gpg_key_url = 'https://download.opensuse.org/repositories/systemsmanagement:/Uyuni:/Master:/CentOS6-Uyuni-Client-Tools/CentOS_6/repodata/repomd.xml.key';

update rhnchannel set
gpg_key_url = 'file:///etc/pki/rpm-gpg/uyuni-tools-gpg-pubkey-0d20833e.key' where
gpg_key_url = 'https://download.opensuse.org/repositories/systemsmanagement:/Uyuni:/Stable:/openSUSE_Leap_15-Uyuni-Client-Tools/openSUSE_Leap_15.0/repodata/repomd.xml.key';

update rhnchannel set
gpg_key_url = 'file:///etc/pki/rpm-gpg/uyuni-tools-gpg-pubkey-0d20833e.key' where
gpg_key_url = 'https://download.opensuse.org/repositories/systemsmanagement:/Uyuni:/Master:/openSUSE_Leap_15-Uyuni-Client-Tools/openSUSE_Leap_15.0/repodata/repomd.xml.key';

update rhnchannel set
gpg_key_url = 'file:///etc/pki/rpm-gpg/uyuni-tools-gpg-pubkey-0d20833e.key' where
gpg_key_url = 'https://download.opensuse.org/repositories/systemsmanagement:/Uyuni:/Stable:/SLE12-Uyuni-Client-Tools/SLE_12/repodata/repomd.xml.key';

update rhnchannel set
gpg_key_url = 'file:///etc/pki/rpm-gpg/uyuni-tools-gpg-pubkey-0d20833e.key' where
gpg_key_url = 'https://download.opensuse.org/repositories/systemsmanagement:/Uyuni:/Master:/SLE12-Uyuni-Client-Tools/SLE_12/repodata/repomd.xml.key';

update rhnchannel set
gpg_key_url = 'file:///etc/pki/rpm-gpg/uyuni-tools-gpg-pubkey-0d20833e.key' where
gpg_key_url = 'https://download.opensuse.org/repositories/systemsmanagement:/Uyuni:/Stable:/SLE15-Uyuni-Client-Tools/SLE_15/repodata/repomd.xml.key';

update rhnchannel set
gpg_key_url = 'file:///etc/pki/rpm-gpg/uyuni-tools-gpg-pubkey-0d20833e.key' where
gpg_key_url = 'https://download.opensuse.org/repositories/systemsmanagement:/Uyuni:/Master:/SLE15-Uyuni-Client-Tools/SLE_15/repodata/repomd.xml.key';

update rhnchannel set
gpg_key_url = 'file:///etc/pki/rpm-gpg/uyuni-tools-gpg-pubkey-0d20833e.key' where
gpg_key_url = 'https://download.opensuse.org/repositories/systemsmanagement:/Uyuni:/Stable:/EL9-Uyuni-Client-Tools/EL_9/repodata/repomd.xml.key';

update rhnchannel set
gpg_key_url = 'file:///etc/pki/rpm-gpg/uyuni-tools-gpg-pubkey-0d20833e.key' where
gpg_key_url = 'https://download.opensuse.org/repositories/systemsmanagement:/Uyuni:/Master:/EL9-Uyuni-Client-Tools/EL_9/repodata/repomd.xml.key';

update rhnchannel set
gpg_key_url = 'file:///etc/pki/rpm-gpg/RPM-GPG-KEY-oracle' where
gpg_key_url = 'https://yum.oracle.com/RPM-GPG-KEY-oracle-ol8';

update rhnchannel set
gpg_key_url = 'file:///etc/pki/rpm-gpg/RPM-GPG-KEY-oracle' where
gpg_key_url = 'https://yum.oracle.com/RPM-GPG-KEY-oracle-ol8';

update rhnchannel set
gpg_key_url = 'file:///etc/pki/rpm-gpg/uyuni-tools-gpg-pubkey-0d20833e.key' where
gpg_key_url = 'https://download.opensuse.org/repositories/systemsmanagement:/Uyuni:/Stable:/EL8-Uyuni-Client-Tools/EL_8/repodata/repomd.xml.key';

update rhnchannel set
gpg_key_url = 'file:///etc/pki/rpm-gpg/uyuni-tools-gpg-pubkey-0d20833e.key' where
gpg_key_url = 'https://download.opensuse.org/repositories/systemsmanagement:/Uyuni:/Master:/EL8-Uyuni-Client-Tools/EL_8/repodata/repomd.xml.key';

update rhnchannel set
gpg_key_url = 'file:///etc/pki/rpm-gpg/RPM-GPG-KEY-oracle' where
gpg_key_url = 'https://yum.oracle.com/RPM-GPG-KEY-oracle-ol7';

update rhnchannel set
gpg_key_url = 'file:///etc/pki/rpm-gpg/uyuni-tools-gpg-pubkey-0d20833e.key' where
gpg_key_url = 'https://download.opensuse.org/repositories/systemsmanagement:/Uyuni:/Stable/images/repo/Uyuni-Server-POOL-x86_64-Media1/repodata/repomd.xml.key';

update rhnchannel set
gpg_key_url = 'file:///etc/pki/rpm-gpg/uyuni-tools-gpg-pubkey-0d20833e.key' where
gpg_key_url = 'https://download.opensuse.org/repositories/systemsmanagement:/Uyuni:/Master/images/repo/Uyuni-Proxy-POOL-x86_64-Media1/repodata/repomd.xml.key';

update rhnchannel set
gpg_key_url = 'file:///etc/pki/rpm-gpg/RPM-GPG-KEY-AlmaLinux' where
gpg_key_url = 'https://repo.almalinux.org/almalinux/RPM-GPG-KEY-AlmaLinux';

update rhnchannel set
gpg_key_url = 'file:///etc/pki/rpm-gpg/RPM-GPG-KEY-rockyofficial' where
gpg_key_url = 'https://dl.rockylinux.org/pub/rocky/RPM-GPG-KEY-rockyofficial';
07070100000EF0000081B400000000000000000000000167AE11140000010B000000000000000000000000000000000000007300000000susemanager-schema/upgrade/susemanager-schema-4.3.12-to-susemanager-schema-4.3.13/110-suseImageInfo_del_pillar.sql    CREATE OR REPLACE FUNCTION suse_image_info_image_removed_trig_fun() RETURNS TRIGGER AS $$
BEGIN
  DELETE FROM suseSaltPillar WHERE id = OLD.pillar_id;
  DELETE FROM suseSaltPillar WHERE category = concat('SyncedImage', OLD.id);
  RETURN OLD;
END $$ LANGUAGE PLPGSQL;
 07070100000EF1000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005200000000susemanager-schema/upgrade/susemanager-schema-4.3.13-to-susemanager-schema-4.3.14 07070100000EF2000081B400000000000000000000000167AE11140000009A000000000000000000000000000000000000007200000000susemanager-schema/upgrade/susemanager-schema-4.3.13-to-susemanager-schema-4.3.14/200-fix-rhnActionImage-null.sql ALTER TABLE rhnActionImageBuild ALTER COLUMN image_profile_id DROP NOT NULL;
ALTER TABLE rhnActionImageInspect ALTER COLUMN image_store_id DROP NOT NULL;
  07070100000EF3000081B400000000000000000000000167AE1114000001B4000000000000000000000000000000000000007100000000susemanager-schema/upgrade/susemanager-schema-4.3.13-to-susemanager-schema-4.3.14/300-rhnVirtualInstanceType.sql  INSERT INTO rhnVirtualInstanceType (id, name, label)
SELECT sequence_nextval('rhn_vit_id_seq'), 'Amazon EC2/KVM', 'aws_kvm'
WHERE NOT EXISTS ( SELECT 1 FROM rhnVirtualInstanceType WHERE label = 'aws_kvm' OR label = 'aws_nitro');

INSERT INTO rhnVirtualInstanceType (id, name, label)
SELECT sequence_nextval('rhn_vit_id_seq'), 'Amazon EC2/Xen', 'aws_xen'
WHERE NOT EXISTS ( SELECT 1 FROM rhnVirtualInstanceType WHERE label = 'aws_xen');
07070100000EF4000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005200000000susemanager-schema/upgrade/susemanager-schema-4.3.14-to-susemanager-schema-4.3.15 07070100000EF5000081B400000000000000000000000167AE111400000217000000000000000000000000000000000000007C00000000susemanager-schema/upgrade/susemanager-schema-4.3.14-to-susemanager-schema-4.3.15/100-rhnChannelComps-drop_unique_index.sql   -- Replace the index with a non-unique one
DROP INDEX IF EXISTS rhn_channelcomps_cid_ctype_uq;
DROP INDEX IF EXISTS rhn_channelcomps_cid_ctype_idx;

CREATE INDEX rhn_channelcomps_cid_ctype_idx ON rhnChannelComps(channel_id, comps_type_id);

-- Add a unique constraint as (cid, comps_type, filename)
ALTER TABLE rhnChannelComps DROP CONSTRAINT IF EXISTS rhn_channelcomps_cid_ctype_filename_uq;

ALTER TABLE rhnChannelComps ADD CONSTRAINT rhn_channelcomps_cid_ctype_filename_uq
    UNIQUE (channel_id, comps_type_id, relative_filename);
 07070100000EF6000081B400000000000000000000000167AE1114000003D1000000000000000000000000000000000000007C00000000susemanager-schema/upgrade/susemanager-schema-4.3.14-to-susemanager-schema-4.3.15/101-rhn_channel_cloned_comps_trig_fun.sql   create or replace function rhn_channel_cloned_comps_trig_fun() returns trigger
as
$$
begin
	new.modified := current_timestamp;

	if tg_op = 'INSERT' then
		-- if there are not comps in the cloned channel by now,
		-- we shall clone comps from the original channel
		insert into rhnChannelComps
			( id, channel_id, comps_type_id, relative_filename,
				last_modified, created, modified )
		select nextval('rhn_channelcomps_id_seq'), new.id, comps_type_id, relative_filename,
				last_modified, current_timestamp, current_timestamp
		from rhnChannelComps
		where channel_id = new.original_id
			and not exists (
				select 1
				from rhnChannelComps x
				where x.channel_id = new.id
			);
	end if;
        return new;
end;
$$
language plpgsql;

drop trigger if exists rhn_channel_cloned_comps_trig on rhnChannelCloned;

create trigger rhn_channel_cloned_comps_trig
before insert or update on rhnChannelCloned
for each row
execute procedure rhn_channel_cloned_comps_trig_fun();
   07070100000EF7000081B400000000000000000000000167AE111400000064000000000000000000000000000000000000007700000000susemanager-schema/upgrade/susemanager-schema-4.3.14-to-susemanager-schema-4.3.15/200-rhnVirtualInstanceType-Nitro.sql    UPDATE rhnVirtualInstanceType SET name='Amazon EC2/Nitro', label='aws_nitro' WHERE label='aws_kvm';
07070100000EF8000081B400000000000000000000000167AE11140000004F000000000000000000000000000000000000008300000000susemanager-schema/upgrade/susemanager-schema-4.3.14-to-susemanager-schema-4.3.15/300-add-reboot-need-column-to-suseMinionInfo.sql    ALTER TABLE suseMinionInfo
    ADD COLUMN IF NOT EXISTS reboot_needed CHAR(1);
 07070100000EF9000081B400000000000000000000000167AE11140000010E000000000000000000000000000000000000006B00000000susemanager-schema/upgrade/susemanager-schema-4.3.14-to-susemanager-schema-4.3.15/400-rhnKSInstallType.sql    insert into rhnKSInstallType (id, label, name) (
        select sequence_nextval('rhn_ksinstalltype_id_seq'),
               'rhel_9','Red Hat Enterprise Linux 9'
        from dual
        where not exists (select 1 from rhnKSInstallType where  label = 'rhel_9')
    );
  07070100000EFA000081B400000000000000000000000167AE111400035F7E000000000000000000000000000000000000006F00000000susemanager-schema/upgrade/susemanager-schema-4.3.14-to-susemanager-schema-4.3.15/401-rhnKickstartTimezome.sql    insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
               'Africa/Abidjan',
               'Africa/Abidjan',
               (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Africa/Abidjan'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Accra',
                'Africa/Accra',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Africa/Accra'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Addis_Ababa',
                'Africa/Addis_Ababa',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Africa/Addis_Ababa'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Algiers',
                'Africa/Algiers',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Africa/Algiers'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Asmara',
                'Africa/Asmara',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Africa/Asmara'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Bamako',
                'Africa/Bamako',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Africa/Bamako'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Bangui',
                'Africa/Bangui',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Africa/Bangui'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Banjul',
                'Africa/Banjul',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Africa/Banjul'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Bissau',
                'Africa/Bissau',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Africa/Bissau'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Blantyre',
                'Africa/Blantyre',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Africa/Blantyre'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Brazzaville',
                'Africa/Brazzaville',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Africa/Brazzaville'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Bujumbura',
                'Africa/Bujumbura',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Africa/Bujumbura'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Cairo',
                'Africa/Cairo',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Africa/Cairo'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Casablanca',
                'Africa/Casablanca',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Africa/Casablanca'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Ceuta',
                'Africa/Ceuta',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Africa/Ceuta'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Conakry',
                'Africa/Conakry',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Africa/Conakry'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Dakar',
                'Africa/Dakar',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Africa/Dakar'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Dar_es_Salaam',
                'Africa/Dar_es_Salaam',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Africa/Dar_es_Salaam'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Djibouti',
                'Africa/Djibouti',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Africa/Djibouti'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Douala',
                'Africa/Douala',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Africa/Douala'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/El_Aaiun',
                'Africa/El_Aaiun',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Africa/El_Aaiun'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Freetown',
                'Africa/Freetown',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Africa/Freetown'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Gaborone',
                'Africa/Gaborone',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Africa/Gaborone'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Harare',
                'Africa/Harare',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Africa/Harare'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Johannesburg',
                'Africa/Johannesburg',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Africa/Johannesburg'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Juba',
                'Africa/Juba',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Africa/Juba'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Kampala',
                'Africa/Kampala',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Africa/Kampala'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Khartoum',
                'Africa/Khartoum',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Africa/Khartoum'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Kigali',
                'Africa/Kigali',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Africa/Kigali'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Kinshasa',
                'Africa/Kinshasa',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Africa/Kinshasa'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Lagos',
                'Africa/Lagos',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Africa/Lagos'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Libreville',
                'Africa/Libreville',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Africa/Libreville'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Lome',
                'Africa/Lome',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Africa/Lome'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Luanda',
                'Africa/Luanda',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Africa/Luanda'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Lubumbashi',
                'Africa/Lubumbashi',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Africa/Lubumbashi'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Lusaka',
                'Africa/Lusaka',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Africa/Lusaka'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Malabo',
                'Africa/Malabo',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Africa/Malabo'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Maputo',
                'Africa/Maputo',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Africa/Maputo'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Maseru',
                'Africa/Maseru',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Africa/Maseru'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Mbabane',
                'Africa/Mbabane',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Africa/Mbabane'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Mogadishu',
                'Africa/Mogadishu',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Africa/Mogadishu'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Monrovia',
                'Africa/Monrovia',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Africa/Monrovia'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Nairobi',
                'Africa/Nairobi',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Africa/Nairobi'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Ndjamena',
                'Africa/Ndjamena',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Africa/Ndjamena'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Niamey',
                'Africa/Niamey',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Africa/Niamey'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Nouakchott',
                'Africa/Nouakchott',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Africa/Nouakchott'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Ouagadougou',
                'Africa/Ouagadougou',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Africa/Ouagadougou'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Porto-Novo',
                'Africa/Porto-Novo',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Africa/Porto-Novo'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Sao_Tome',
                'Africa/Sao_Tome',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Africa/Sao_Tome'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Tripoli',
                'Africa/Tripoli',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Africa/Tripoli'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Tunis',
                'Africa/Tunis',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Africa/Tunis'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Africa/Windhoek',
                'Africa/Windhoek',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Africa/Windhoek'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Adak',
                'America/Adak',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Adak'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Anchorage',
                'America/Anchorage',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Anchorage'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Anguilla',
                'America/Anguilla',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Anguilla'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Antigua',
                'America/Antigua',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Antigua'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Araguaina',
                'America/Araguaina',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Araguaina'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Argentina/Buenos_Aires',
                'America/Argentina/Buenos_Aires',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Argentina/Buenos_Aires'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Argentina/Catamarca',
                'America/Argentina/Catamarca',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Argentina/Catamarca'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Argentina/Cordoba',
                'America/Argentina/Cordoba',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Argentina/Cordoba'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Argentina/Jujuy',
                'America/Argentina/Jujuy',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Argentina/Jujuy'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Argentina/La_Rioja',
                'America/Argentina/La_Rioja',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Argentina/La_Rioja'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Argentina/Mendoza',
                'America/Argentina/Mendoza',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Argentina/Mendoza'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Argentina/Rio_Gallegos',
                'America/Argentina/Rio_Gallegos',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Argentina/Rio_Gallegos'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Argentina/Salta',
                'America/Argentina/Salta',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Argentina/Salta'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Argentina/San_Juan',
                'America/Argentina/San_Juan',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Argentina/San_Juan'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Argentina/San_Luis',
                'America/Argentina/San_Luis',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Argentina/San_Luis'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Argentina/Tucuman',
                'America/Argentina/Tucuman',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Argentina/Tucuman'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Argentina/Ushuaia',
                'America/Argentina/Ushuaia',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Argentina/Ushuaia'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Aruba',
                'America/Aruba',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Aruba'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Asuncion',
                'America/Asuncion',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Asuncion'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Atikokan',
                'America/Atikokan',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Atikokan'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Bahia',
                'America/Bahia',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Bahia'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Bahia_Banderas',
                'America/Bahia_Banderas',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Bahia_Banderas'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Barbados',
                'America/Barbados',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Barbados'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Belem',
                'America/Belem',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Belem'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Belize',
                'America/Belize',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Belize'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Blanc-Sablon',
                'America/Blanc-Sablon',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Blanc-Sablon'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Boa_Vista',
                'America/Boa_Vista',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Boa_Vista'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Bogota',
                'America/Bogota',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Bogota'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Boise',
                'America/Boise',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Boise'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Cambridge_Bay',
                'America/Cambridge_Bay',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Cambridge_Bay'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Campo_Grande',
                'America/Campo_Grande',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Campo_Grande'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Cancun',
                'America/Cancun',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Cancun'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Caracas',
                'America/Caracas',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Caracas'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Cayenne',
                'America/Cayenne',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Cayenne'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Cayman',
                'America/Cayman',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Cayman'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Chicago',
                'America/Chicago',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Chicago'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Chihuahua',
                'America/Chihuahua',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Chihuahua'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Costa_Rica',
                'America/Costa_Rica',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Costa_Rica'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Creston',
                'America/Creston',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Creston'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Cuiaba',
                'America/Cuiaba',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Cuiaba'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Curacao',
                'America/Curacao',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Curacao'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Danmarkshavn',
                'America/Danmarkshavn',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Danmarkshavn'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Dawson',
                'America/Dawson',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Dawson'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Dawson_Creek',
                'America/Dawson_Creek',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Dawson_Creek'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Denver',
                'America/Denver',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Denver'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Detroit',
                'America/Detroit',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Detroit'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Dominica',
                'America/Dominica',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Dominica'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Edmonton',
                'America/Edmonton',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Edmonton'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Eirunepe',
                'America/Eirunepe',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Eirunepe'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/El_Salvador',
                'America/El_Salvador',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/El_Salvador'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Fortaleza',
                'America/Fortaleza',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Fortaleza'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Glace_Bay',
                'America/Glace_Bay',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Glace_Bay'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Godthab',
                'America/Godthab',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Godthab'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Goose_Bay',
                'America/Goose_Bay',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Goose_Bay'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Grand_Turk',
                'America/Grand_Turk',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Grand_Turk'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Grenada',
                'America/Grenada',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Grenada'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Guadeloupe',
                'America/Guadeloupe',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Guadeloupe'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Guatemala',
                'America/Guatemala',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Guatemala'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Guayaquil',
                'America/Guayaquil',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Guayaquil'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Guyana',
                'America/Guyana',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Guyana'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Halifax',
                'America/Halifax',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Halifax'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Havana',
                'America/Havana',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Havana'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Hermosillo',
                'America/Hermosillo',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Hermosillo'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Indiana/Indianapolis',
                'America/Indiana/Indianapolis',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Indiana/Indianapolis'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Indiana/Knox',
                'America/Indiana/Knox',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Indiana/Knox'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Indiana/Marengo',
                'America/Indiana/Marengo',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Indiana/Marengo'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Indiana/Petersburg',
                'America/Indiana/Petersburg',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Indiana/Petersburg'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Indiana/Tell_City',
                'America/Indiana/Tell_City',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Indiana/Tell_City'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Indiana/Vevay',
                'America/Indiana/Vevay',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Indiana/Vevay'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Indiana/Vincennes',
                'America/Indiana/Vincennes',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Indiana/Vincennes'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Indiana/Winamac',
                'America/Indiana/Winamac',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Indiana/Winamac'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Inuvik',
                'America/Inuvik',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Inuvik'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Iqaluit',
                'America/Iqaluit',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Iqaluit'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Jamaica',
                'America/Jamaica',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Jamaica'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Juneau',
                'America/Juneau',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Juneau'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Kentucky/Louisville',
                'America/Kentucky/Louisville',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Kentucky/Louisville'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Kentucky/Monticello',
                'America/Kentucky/Monticello',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Kentucky/Monticello'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Kralendijk',
                'America/Kralendijk',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Kralendijk'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/La_Paz',
                'America/La_Paz',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/La_Paz'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Lima',
                'America/Lima',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Lima'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Los_Angeles',
                'America/Los_Angeles',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Los_Angeles'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Lower_Princes',
                'America/Lower_Princes',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Lower_Princes'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Maceio',
                'America/Maceio',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Maceio'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Managua',
                'America/Managua',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Managua'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Manaus',
                'America/Manaus',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Manaus'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Marigot',
                'America/Marigot',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Marigot'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Martinique',
                'America/Martinique',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Martinique'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Matamoros',
                'America/Matamoros',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Matamoros'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Mazatlan',
                'America/Mazatlan',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Mazatlan'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Menominee',
                'America/Menominee',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Menominee'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Merida',
                'America/Merida',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Merida'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Metlakatla',
                'America/Metlakatla',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Metlakatla'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Mexico_City',
                'America/Mexico_City',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Mexico_City'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Miquelon',
                'America/Miquelon',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Miquelon'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Moncton',
                'America/Moncton',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Moncton'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Monterrey',
                'America/Monterrey',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Monterrey'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Montevideo',
                'America/Montevideo',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Montevideo'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Montreal',
                'America/Montreal',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Montreal'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Montserrat',
                'America/Montserrat',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Montserrat'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Nassau',
                'America/Nassau',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Nassau'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/New_York',
                'America/New_York',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/New_York'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Nipigon',
                'America/Nipigon',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Nipigon'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Nome',
                'America/Nome',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Nome'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Noronha',
                'America/Noronha',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Noronha'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/North_Dakota/Beulah',
                'America/North_Dakota/Beulah',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/North_Dakota/Beulah'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/North_Dakota/Center',
                'America/North_Dakota/Center',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/North_Dakota/Center'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/North_Dakota/New_Salem',
                'America/North_Dakota/New_Salem',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/North_Dakota/New_Salem'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Ojinaga',
                'America/Ojinaga',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Ojinaga'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Panama',
                'America/Panama',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Panama'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Pangnirtung',
                'America/Pangnirtung',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Pangnirtung'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Paramaribo',
                'America/Paramaribo',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Paramaribo'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Phoenix',
                'America/Phoenix',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Phoenix'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Port_of_Spain',
                'America/Port_of_Spain',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Port_of_Spain'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Port-au-Prince',
                'America/Port-au-Prince',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Port-au-Prince'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Porto_Velho',
                'America/Porto_Velho',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Porto_Velho'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Puerto_Rico',
                'America/Puerto_Rico',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Puerto_Rico'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Rainy_River',
                'America/Rainy_River',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Rainy_River'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Rankin_Inlet',
                'America/Rankin_Inlet',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Rankin_Inlet'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Recife',
                'America/Recife',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Recife'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Regina',
                'America/Regina',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Regina'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Resolute',
                'America/Resolute',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Resolute'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Rio_Branco',
                'America/Rio_Branco',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Rio_Branco'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Santa_Isabel',
                'America/Santa_Isabel',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Santa_Isabel'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Santarem',
                'America/Santarem',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Santarem'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Santiago',
                'America/Santiago',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Santiago'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Santo_Domingo',
                'America/Santo_Domingo',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Santo_Domingo'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Sao_Paulo',
                'America/Sao_Paulo',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Sao_Paulo'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Scoresbysund',
                'America/Scoresbysund',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Scoresbysund'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Shiprock',
                'America/Shiprock',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Shiprock'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Sitka',
                'America/Sitka',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Sitka'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/St_Barthelemy',
                'America/St_Barthelemy',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/St_Barthelemy'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/St_Johns',
                'America/St_Johns',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/St_Johns'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/St_Kitts',
                'America/St_Kitts',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/St_Kitts'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/St_Lucia',
                'America/St_Lucia',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/St_Lucia'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/St_Thomas',
                'America/St_Thomas',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/St_Thomas'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/St_Vincent',
                'America/St_Vincent',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/St_Vincent'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Swift_Current',
                'America/Swift_Current',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Swift_Current'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Tegucigalpa',
                'America/Tegucigalpa',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Tegucigalpa'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Thule',
                'America/Thule',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Thule'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Thunder_Bay',
                'America/Thunder_Bay',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Thunder_Bay'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Tijuana',
                'America/Tijuana',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Tijuana'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Toronto',
                'America/Toronto',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Toronto'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Tortola',
                'America/Tortola',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Tortola'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Vancouver',
                'America/Vancouver',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Vancouver'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Whitehorse',
                'America/Whitehorse',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Whitehorse'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Winnipeg',
                'America/Winnipeg',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Winnipeg'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Yakutat',
                'America/Yakutat',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Yakutat'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'America/Yellowknife',
                'America/Yellowknife',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'America/Yellowknife'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Antarctica/Casey',
                'Antarctica/Casey',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Antarctica/Casey'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Antarctica/Davis',
                'Antarctica/Davis',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Antarctica/Davis'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Antarctica/DumontDUrville',
                'Antarctica/DumontDUrville',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Antarctica/DumontDUrville'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Antarctica/Macquarie',
                'Antarctica/Macquarie',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Antarctica/Macquarie'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Antarctica/Mawson',
                'Antarctica/Mawson',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Antarctica/Mawson'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Antarctica/McMurdo',
                'Antarctica/McMurdo',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Antarctica/McMurdo'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Antarctica/Palmer',
                'Antarctica/Palmer',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Antarctica/Palmer'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Antarctica/Rothera',
                'Antarctica/Rothera',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Antarctica/Rothera'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Antarctica/South_Pole',
                'Antarctica/South_Pole',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Antarctica/South_Pole'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Antarctica/Syowa',
                'Antarctica/Syowa',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Antarctica/Syowa'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Antarctica/Vostok',
                'Antarctica/Vostok',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Antarctica/Vostok'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Arctic/Longyearbyen',
                'Arctic/Longyearbyen',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Arctic/Longyearbyen'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Aden',
                'Asia/Aden',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Asia/Aden'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Almaty',
                'Asia/Almaty',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Asia/Almaty'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Amman',
                'Asia/Amman',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Asia/Amman'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Anadyr',
                'Asia/Anadyr',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Asia/Anadyr'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Aqtau',
                'Asia/Aqtau',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Asia/Aqtau'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Aqtobe',
                'Asia/Aqtobe',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Asia/Aqtobe'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Ashgabat',
                'Asia/Ashgabat',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Asia/Ashgabat'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Baghdad',
                'Asia/Baghdad',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Asia/Baghdad'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Bahrain',
                'Asia/Bahrain',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Asia/Bahrain'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Baku',
                'Asia/Baku',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Asia/Baku'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Bangkok',
                'Asia/Bangkok',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Asia/Bangkok'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Beirut',
                'Asia/Beirut',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Asia/Beirut'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Bishkek',
                'Asia/Bishkek',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Asia/Bishkek'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Brunei',
                'Asia/Brunei',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Asia/Brunei'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Choibalsan',
                'Asia/Choibalsan',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Asia/Choibalsan'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Chongqing',
                'Asia/Chongqing',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Asia/Chongqing'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Colombo',
                'Asia/Colombo',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Asia/Colombo'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Damascus',
                'Asia/Damascus',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Asia/Damascus'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Dhaka',
                'Asia/Dhaka',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Asia/Dhaka'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Dili',
                'Asia/Dili',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Asia/Dili'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Dubai',
                'Asia/Dubai',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Asia/Dubai'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Dushanbe',
                'Asia/Dushanbe',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Asia/Dushanbe'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Gaza',
                'Asia/Gaza',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Asia/Gaza'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Harbin',
                'Asia/Harbin',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Asia/Harbin'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Hebron',
                'Asia/Hebron',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Asia/Hebron'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Ho_Chi_Minh',
                'Asia/Ho_Chi_Minh',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Asia/Ho_Chi_Minh'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Hong_Kong',
                'Asia/Hong_Kong',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Asia/Hong_Kong'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Hovd',
                'Asia/Hovd',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Asia/Hovd'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Irkutsk',
                'Asia/Irkutsk',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Asia/Irkutsk'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Jakarta',
                'Asia/Jakarta',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Asia/Jakarta'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Jayapura',
                'Asia/Jayapura',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Asia/Jayapura'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Jerusalem',
                'Asia/Jerusalem',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Asia/Jerusalem'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Kabul',
                'Asia/Kabul',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Asia/Kabul'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Kamchatka',
                'Asia/Kamchatka',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Asia/Kamchatka'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Karachi',
                'Asia/Karachi',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Asia/Karachi'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Kashgar',
                'Asia/Kashgar',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Asia/Kashgar'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Kathmandu',
                'Asia/Kathmandu',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Asia/Kathmandu'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Kolkata',
                'Asia/Kolkata',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Asia/Kolkata'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Krasnoyarsk',
                'Asia/Krasnoyarsk',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Asia/Krasnoyarsk'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Kuala_Lumpur',
                'Asia/Kuala_Lumpur',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Asia/Kuala_Lumpur'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Kuching',
                'Asia/Kuching',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Asia/Kuching'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Kuwait',
                'Asia/Kuwait',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Asia/Kuwait'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Macau',
                'Asia/Macau',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Asia/Macau'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Magadan',
                'Asia/Magadan',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Asia/Magadan'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Makassar',
                'Asia/Makassar',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Asia/Makassar'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Manila',
                'Asia/Manila',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Asia/Manila'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Muscat',
                'Asia/Muscat',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Asia/Muscat'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Nicosia',
                'Asia/Nicosia',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Asia/Nicosia'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Novokuznetsk',
                'Asia/Novokuznetsk',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Asia/Novokuznetsk'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Novosibirsk',
                'Asia/Novosibirsk',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Asia/Novosibirsk'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Omsk',
                'Asia/Omsk',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Asia/Omsk'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Oral',
                'Asia/Oral',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Asia/Oral'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Phnom_Penh',
                'Asia/Phnom_Penh',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Asia/Phnom_Penh'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Pontianak',
                'Asia/Pontianak',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Asia/Pontianak'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Pyongyang',
                'Asia/Pyongyang',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Asia/Pyongyang'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Qatar',
                'Asia/Qatar',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Asia/Qatar'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Qyzylorda',
                'Asia/Qyzylorda',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Asia/Qyzylorda'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Rangoon',
                'Asia/Rangoon',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Asia/Rangoon'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Riyadh',
                'Asia/Riyadh',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Asia/Riyadh'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Sakhalin',
                'Asia/Sakhalin',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Asia/Sakhalin'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Samarkand',
                'Asia/Samarkand',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Asia/Samarkand'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Seoul',
                'Asia/Seoul',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Asia/Seoul'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Shanghai',
                'Asia/Shanghai',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Asia/Shanghai'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Singapore',
                'Asia/Singapore',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Asia/Singapore'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Taipei',
                'Asia/Taipei',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Asia/Taipei'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Tashkent',
                'Asia/Tashkent',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Asia/Tashkent'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Tbilisi',
                'Asia/Tbilisi',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Asia/Tbilisi'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Tehran',
                'Asia/Tehran',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Asia/Tehran'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Thimphu',
                'Asia/Thimphu',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Asia/Thimphu'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Tokyo',
                'Asia/Tokyo',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Asia/Tokyo'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Ulaanbaatar',
                'Asia/Ulaanbaatar',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Asia/Ulaanbaatar'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Urumqi',
                'Asia/Urumqi',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Asia/Urumqi'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Vientiane',
                'Asia/Vientiane',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Asia/Vientiane'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Vladivostok',
                'Asia/Vladivostok',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Asia/Vladivostok'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Yakutsk',
                'Asia/Yakutsk',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Asia/Yakutsk'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Yekaterinburg',
                'Asia/Yekaterinburg',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Asia/Yekaterinburg'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Asia/Yerevan',
                'Asia/Yerevan',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Asia/Yerevan'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Atlantic/Azores',
                'Atlantic/Azores',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Atlantic/Azores'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Atlantic/Bermuda',
                'Atlantic/Bermuda',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Atlantic/Bermuda'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Atlantic/Canary',
                'Atlantic/Canary',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Atlantic/Canary'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Atlantic/Cape_Verde',
                'Atlantic/Cape_Verde',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Atlantic/Cape_Verde'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Atlantic/Faroe',
                'Atlantic/Faroe',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Atlantic/Faroe'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Atlantic/Madeira',
                'Atlantic/Madeira',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Atlantic/Madeira'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Atlantic/Reykjavik',
                'Atlantic/Reykjavik',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Atlantic/Reykjavik'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Atlantic/South_Georgia',
                'Atlantic/South_Georgia',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Atlantic/South_Georgia'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Atlantic/St_Helena',
                'Atlantic/St_Helena',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Atlantic/St_Helena'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Atlantic/Stanley',
                'Atlantic/Stanley',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Atlantic/Stanley'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Australia/Adelaide',
                'Australia/Adelaide',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Australia/Adelaide'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Australia/Brisbane',
                'Australia/Brisbane',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Australia/Brisbane'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Australia/Broken_Hill',
                'Australia/Broken_Hill',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Australia/Broken_Hill'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Australia/Currie',
                'Australia/Currie',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Australia/Currie'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Australia/Darwin',
                'Australia/Darwin',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Australia/Darwin'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Australia/Eucla',
                'Australia/Eucla',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Australia/Eucla'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Australia/Hobart',
                'Australia/Hobart',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Australia/Hobart'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Australia/Lindeman',
                'Australia/Lindeman',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Australia/Lindeman'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Australia/Lord_Howe',
                'Australia/Lord_Howe',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Australia/Lord_Howe'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Australia/Melbourne',
                'Australia/Melbourne',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Australia/Melbourne'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Australia/Perth',
                'Australia/Perth',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Australia/Perth'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Australia/Sydney',
                'Australia/Sydney',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Australia/Sydney'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Amsterdam',
                'Europe/Amsterdam',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Europe/Amsterdam'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Andorra',
                'Europe/Andorra',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Europe/Andorra'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Athens',
                'Europe/Athens',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Europe/Athens'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Belgrade',
                'Europe/Belgrade',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Europe/Belgrade'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Berlin',
                'Europe/Berlin',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Europe/Berlin'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Bratislava',
                'Europe/Bratislava',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Europe/Bratislava'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Brussels',
                'Europe/Brussels',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Europe/Brussels'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Bucharest',
                'Europe/Bucharest',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Europe/Bucharest'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Budapest',
                'Europe/Budapest',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Europe/Budapest'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Chisinau',
                'Europe/Chisinau',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Europe/Chisinau'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Copenhagen',
                'Europe/Copenhagen',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Europe/Copenhagen'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Dublin',
                'Europe/Dublin',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Europe/Dublin'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Gibraltar',
                'Europe/Gibraltar',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Europe/Gibraltar'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Guernsey',
                'Europe/Guernsey',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Europe/Guernsey'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Helsinki',
                'Europe/Helsinki',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Europe/Helsinki'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Isle_of_Man',
                'Europe/Isle_of_Man',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Europe/Isle_of_Man'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Istanbul',
                'Europe/Istanbul',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Europe/Istanbul'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Jersey',
                'Europe/Jersey',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Europe/Jersey'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Kaliningrad',
                'Europe/Kaliningrad',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Europe/Kaliningrad'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Kiev',
                'Europe/Kiev',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Europe/Kiev'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Lisbon',
                'Europe/Lisbon',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Europe/Lisbon'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Ljubljana',
                'Europe/Ljubljana',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Europe/Ljubljana'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/London',
                'Europe/London',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Europe/London'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Luxembourg',
                'Europe/Luxembourg',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Europe/Luxembourg'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Madrid',
                'Europe/Madrid',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Europe/Madrid'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Malta',
                'Europe/Malta',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Europe/Malta'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Mariehamn',
                'Europe/Mariehamn',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Europe/Mariehamn'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Minsk',
                'Europe/Minsk',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Europe/Minsk'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Monaco',
                'Europe/Monaco',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Europe/Monaco'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Moscow',
                'Europe/Moscow',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Europe/Moscow'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Oslo',
                'Europe/Oslo',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Europe/Oslo'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Paris',
                'Europe/Paris',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Europe/Paris'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Podgorica',
                'Europe/Podgorica',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Europe/Podgorica'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Prague',
                'Europe/Prague',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Europe/Prague'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Riga',
                'Europe/Riga',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Europe/Riga'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Rome',
                'Europe/Rome',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Europe/Rome'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Samara',
                'Europe/Samara',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Europe/Samara'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/San_Marino',
                'Europe/San_Marino',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Europe/San_Marino'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Sarajevo',
                'Europe/Sarajevo',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Europe/Sarajevo'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Simferopol',
                'Europe/Simferopol',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Europe/Simferopol'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Skopje',
                'Europe/Skopje',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Europe/Skopje'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Sofia',
                'Europe/Sofia',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Europe/Sofia'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Stockholm',
                'Europe/Stockholm',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Europe/Stockholm'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Tallinn',
                'Europe/Tallinn',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Europe/Tallinn'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Tirane',
                'Europe/Tirane',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Europe/Tirane'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Uzhgorod',
                'Europe/Uzhgorod',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Europe/Uzhgorod'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Vaduz',
                'Europe/Vaduz',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Europe/Vaduz'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Vatican',
                'Europe/Vatican',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Europe/Vatican'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Vienna',
                'Europe/Vienna',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Europe/Vienna'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Vilnius',
                'Europe/Vilnius',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Europe/Vilnius'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Volgograd',
                'Europe/Volgograd',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Europe/Volgograd'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Warsaw',
                'Europe/Warsaw',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Europe/Warsaw'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Zagreb',
                'Europe/Zagreb',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Europe/Zagreb'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Zaporozhye',
                'Europe/Zaporozhye',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Europe/Zaporozhye'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Europe/Zurich',
                'Europe/Zurich',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Europe/Zurich'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Indian/Antananarivo',
                'Indian/Antananarivo',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Indian/Antananarivo'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Indian/Chagos',
                'Indian/Chagos',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Indian/Chagos'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Indian/Christmas',
                'Indian/Christmas',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Indian/Christmas'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Indian/Cocos',
                'Indian/Cocos',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Indian/Cocos'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Indian/Comoro',
                'Indian/Comoro',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Indian/Comoro'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Indian/Kerguelen',
                'Indian/Kerguelen',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Indian/Kerguelen'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Indian/Mahe',
                'Indian/Mahe',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Indian/Mahe'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Indian/Maldives',
                'Indian/Maldives',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Indian/Maldives'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Indian/Mauritius',
                'Indian/Mauritius',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Indian/Mauritius'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Indian/Mayotte',
                'Indian/Mayotte',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Indian/Mayotte'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Indian/Reunion',
                'Indian/Reunion',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Indian/Reunion'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Apia',
                'Pacific/Apia',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Pacific/Apia'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Auckland',
                'Pacific/Auckland',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Pacific/Auckland'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Chatham',
                'Pacific/Chatham',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Pacific/Chatham'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Chuuk',
                'Pacific/Chuuk',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Pacific/Chuuk'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Easter',
                'Pacific/Easter',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Pacific/Easter'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Efate',
                'Pacific/Efate',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Pacific/Efate'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Enderbury',
                'Pacific/Enderbury',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Pacific/Enderbury'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Fakaofo',
                'Pacific/Fakaofo',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Pacific/Fakaofo'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Fiji',
                'Pacific/Fiji',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Pacific/Fiji'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Funafuti',
                'Pacific/Funafuti',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Pacific/Funafuti'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Galapagos',
                'Pacific/Galapagos',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Pacific/Galapagos'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Gambier',
                'Pacific/Gambier',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Pacific/Gambier'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Guadalcanal',
                'Pacific/Guadalcanal',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Pacific/Guadalcanal'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Guam',
                'Pacific/Guam',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Pacific/Guam'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Honolulu',
                'Pacific/Honolulu',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Pacific/Honolulu'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Johnston',
                'Pacific/Johnston',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Pacific/Johnston'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Kiritimati',
                'Pacific/Kiritimati',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Pacific/Kiritimati'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Kosrae',
                'Pacific/Kosrae',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Pacific/Kosrae'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Kwajalein',
                'Pacific/Kwajalein',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Pacific/Kwajalein'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Majuro',
                'Pacific/Majuro',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Pacific/Majuro'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Marquesas',
                'Pacific/Marquesas',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Pacific/Marquesas'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Midway',
                'Pacific/Midway',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Pacific/Midway'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Nauru',
                'Pacific/Nauru',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Pacific/Nauru'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Niue',
                'Pacific/Niue',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Pacific/Niue'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Norfolk',
                'Pacific/Norfolk',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Pacific/Norfolk'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Noumea',
                'Pacific/Noumea',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Pacific/Noumea'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Pago_Pago',
                'Pacific/Pago_Pago',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Pacific/Pago_Pago'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Palau',
                'Pacific/Palau',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Pacific/Palau'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Pitcairn',
                'Pacific/Pitcairn',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Pacific/Pitcairn'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Pohnpei',
                'Pacific/Pohnpei',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Pacific/Pohnpei'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Port_Moresby',
                'Pacific/Port_Moresby',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Pacific/Port_Moresby'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Rarotonga',
                'Pacific/Rarotonga',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Pacific/Rarotonga'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Saipan',
                'Pacific/Saipan',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Pacific/Saipan'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Tahiti',
                'Pacific/Tahiti',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Pacific/Tahiti'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Tarawa',
                'Pacific/Tarawa',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Pacific/Tarawa'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Tongatapu',
                'Pacific/Tongatapu',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Pacific/Tongatapu'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Wake',
                'Pacific/Wake',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Pacific/Wake'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));

insert into rhnKickstartTimezone (id, label, name, install_type)
        select sequence_nextval('rhn_ks_timezone_id_seq'),
                'Pacific/Wallis',
                'Pacific/Wallis',
                (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9')
        from dual
        where not exists (select 1 from rhnKickstartTimezone
                           where label = 'Pacific/Wallis'
                             and install_type = (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label = 'rhel_9'));
  07070100000EFB000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005200000000susemanager-schema/upgrade/susemanager-schema-4.3.15-to-susemanager-schema-4.3.16 07070100000EFC000081B400000000000000000000000167AE1114000000F6000000000000000000000000000000000000007700000000susemanager-schema/upgrade/susemanager-schema-4.3.15-to-susemanager-schema-4.3.16/001-remove-kickstart-below-rhel6.sql    DELETE FROM rhnKickstartTimezone WHERE install_type in (SELECT IT.id FROM rhnKSInstallType IT WHERE IT.label in ('rhel_2.1', 'rhel_3', 'rhel_4', 'rhel_5'));

DELETE FROM rhnKSInstallType WHERE label in ('rhel_2.1', 'rhel_3', 'rhel_4', 'rhel_5');
  07070100000EFD000081B400000000000000000000000167AE11140000004A000000000000000000000000000000000000007D00000000susemanager-schema/upgrade/susemanager-schema-4.3.15-to-susemanager-schema-4.3.16/001-varchar-length-suseRecurringAction.sql  alter table suseRecurringAction alter column cron_expr type varchar(120);
  07070100000EFE000081B400000000000000000000000167AE1114000001D3000000000000000000000000000000000000006F00000000susemanager-schema/upgrade/susemanager-schema-4.3.15-to-susemanager-schema-4.3.16/002-remove-cluster_admin.sql    
DELETE FROM rhnUserExtGroupMapping WHERE int_group_type_id IN (SELECT id FROM rhnusergrouptype WHERE label = 'cluster_admin');
DELETE FROM rhnUserGroupMembers WHERE user_group_id IN (SELECT G.id FROM rhnusergroup G, rhnusergrouptype GT WHERE G.group_type = GT.id AND GT.label = 'cluster_admin');
DELETE FROM rhnUserGroup WHERE group_type IN (SELECT id FROM rhnusergrouptype WHERE label = 'cluster_admin');
DELETE FROM rhnUserGroupType WHERE label = 'cluster_admin';
 07070100000EFF000081B400000000000000000000000167AE111400000040000000000000000000000000000000000000007800000000susemanager-schema/upgrade/susemanager-schema-4.3.15-to-susemanager-schema-4.3.16/100-suseContentFilter-null-values.sql   ALTER TABLE susecontentfilter ALTER COLUMN value DROP NOT NULL;
07070100000F00000081B400000000000000000000000167AE1114000000CF000000000000000000000000000000000000007700000000susemanager-schema/upgrade/susemanager-schema-4.3.15-to-susemanager-schema-4.3.16/900-add-pane-subwarn-rhnInfoPane.sql    insert into RHNINFOPANE(ID,LABEL,ACL) 
select sequence_nextval('rhn_info_pane_id_seq'),'subscription-warning', null  
where not exists( select label from RHNINFOPANE where label = 'subscription-warning');  
 07070100000F01000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005200000000susemanager-schema/upgrade/susemanager-schema-4.3.16-to-susemanager-schema-4.3.17 07070100000F02000081B400000000000000000000000167AE1114000000B2000000000000000000000000000000000000006D00000000susemanager-schema/upgrade/susemanager-schema-4.3.16-to-susemanager-schema-4.3.17/001-rhnCPU-enhancement.sql  ALTER TABLE rhnCpu
    ADD COLUMN IF NOT EXISTS nrcore   NUMERIC DEFAULT (1),
    ADD COLUMN IF NOT EXISTS nrthread NUMERIC DEFAULT (1),
    ALTER COLUMN nrsocket SET DEFAULT 1;
  07070100000F03000081B400000000000000000000000167AE11140000029A000000000000000000000000000000000000007500000000susemanager-schema/upgrade/susemanager-schema-4.3.16-to-susemanager-schema-4.3.17/002-deregister-foreign-systems.sql  update suseSCCRegCache
   set server_id = NULL
 where server_id in (select s.id
                       from rhnserver s
                       join rhnservergroupmembers sgm on s.id = sgm.server_id
                       join rhnservergroup sg on sgm.server_group_id = sg.id
                       join rhnservergrouptype sgt on sg.group_type = sgt.id
                      where sgt.label = 'foreign_entitled');

-- trigger sending virualization host data to SCC for the first time
update susesccregcache
   set scc_reg_required = 'Y'
 where server_id in (
	select distinct host_system_id
         from rhnvirtualinstance
        where host_system_id is not null);
  07070100000F04000081B400000000000000000000000167AE11140000071B000000000000000000000000000000000000007500000000susemanager-schema/upgrade/susemanager-schema-4.3.16-to-susemanager-schema-4.3.17/003-update-sccregcache-trigger.sql  drop trigger if exists rhn_cpu_up_trig on rhnCpu;
create trigger
rhn_cpu_up_trig
after update on rhnCpu
for each row
when (OLD.nrcpu is distinct from NEW.nrcpu OR OLD.nrsocket is distinct from NEW.nrsocket OR OLD.nrcore is distinct from NEW.nrcore OR OLD.nrthread is distinct from NEW.nrthread)
execute procedure rhn_cpu_up_trig_fun();


create or replace function rhn_ram_up_trig_fun() returns trigger as
$$
begin
        update suseSCCRegCache
           set scc_reg_required = 'Y'
         where server_id = new.server_id;
        return new;
end;
$$ language plpgsql;

drop trigger if exists rhn_ram_up_trig on rhnRam;
create trigger
rhn_ram_up_trig
after update on rhnRam
for each row
when (OLD.ram is distinct from NEW.ram)
execute procedure rhn_ram_up_trig_fun();

create or replace function rhn_virtinst_iud_trig_fun() returns trigger
as
$$
begin
        if tg_op='INSERT' or tg_op='UPDATE' then
                if new.host_system_id is not null and new.virtual_system_id is not null then
                        update suseSCCRegCache
                           set scc_reg_required = 'Y'
                         where server_id = new.host_system_id;
                end if;
                return new;
        end if;
        if tg_op='DELETE' then
                if old.host_system_id is not null and old.virtual_system_id is not null then
                        update suseSCCRegCache
                           set scc_reg_required = 'Y'
                         where server_id = old.host_system_id;
                end if;
                return old;
        end if;
end;
$$ language plpgsql;

drop trigger if exists rhn_virtinst_iud_trig on rhnVirtualInstance;
create trigger
rhn_virtinst_iud_trig
after insert or update or delete on rhnVirtualInstance
execute procedure rhn_virtinst_iud_trig_fun();
 07070100000F05000081B400000000000000000000000167AE111400000633000000000000000000000000000000000000007600000000susemanager-schema/upgrade/susemanager-schema-4.3.16-to-susemanager-schema-4.3.17/004-system-profile-refresh-task.sql 
INSERT INTO rhnTaskoBunch (id, name, description, org_bunch)
 SELECT sequence_nextval('rhn_tasko_bunch_id_seq'), 'system-profile-refresh-bunch', 'Refresh System Profiles of all registered servers', null
 WHERE NOT EXISTS ( SELECT 1 FROM rhnTaskoBunch WHERE name = 'system-profile-refresh-bunch');
 
-- Once a month at the 15th at 5am

INSERT INTO rhnTaskoSchedule (id, job_label, bunch_id, active_from, cron_expr)
  SELECT sequence_nextval('rhn_tasko_schedule_id_seq'), 'system-profile-refresh-default',
	 (SELECT id FROM rhnTaskoBunch WHERE name='system-profile-refresh-bunch'),
	 current_timestamp, '0 0 5 15 * ?'
  WHERE NOT EXISTS ( SELECT 1 FROM rhnTaskoSchedule WHERE job_label = 'system-profile-refresh-default');
 
INSERT INTO rhnTaskoTask (id, name, class)
  SELECT sequence_nextval('rhn_tasko_task_id_seq'), 'system-profile-refresh', 'com.redhat.rhn.taskomatic.task.SystemProfileRefreshTask'
  WHERE NOT EXISTS ( SELECT 1 FROM rhnTaskoTask WHERE name = 'system-profile-refresh');

 
INSERT INTO rhnTaskoTemplate (id, bunch_id, task_id, ordering, start_if)
  SELECT sequence_nextval('rhn_tasko_template_id_seq'),
         (SELECT id FROM rhnTaskoBunch WHERE name='system-profile-refresh-bunch'),
         (SELECT id FROM rhnTaskoTask WHERE name='system-profile-refresh'),
         0,
         null
  WHERE NOT EXISTS ( SELECT 1 FROM rhnTaskoTemplate 
	              WHERE bunch_id = ( SELECT id FROM rhnTaskoBunch WHERE name = 'system-profile-refresh-bunch' )
                        AND task_id = (SELECT id FROM rhnTaskoTask WHERE name = 'system-profile-refresh'));

commit;
 07070100000F06000081B400000000000000000000000167AE1114000001A0000000000000000000000000000000000000006D00000000susemanager-schema/upgrade/susemanager-schema-4.3.16-to-susemanager-schema-4.3.17/010-add-pkey-taskQueue.sql  ALTER TABLE rhnTaskQueue ADD COLUMN IF NOT EXISTS id NUMERIC;
CREATE SEQUENCE IF NOT EXISTS rhn_task_queue_id_seq START WITH 1;
UPDATE rhnTaskQueue SET id = nextval('rhn_task_queue_id_seq') WHERE id IS NULL;
ALTER TABLE rhnTaskQueue ALTER COLUMN id SET NOT NULL;

ALTER TABLE rhnTaskQueue DROP CONSTRAINT IF EXISTS rhn_task_queue_id_pk;
ALTER TABLE rhnTaskQueue ADD CONSTRAINT rhn_task_queue_id_pk PRIMARY KEY (id);
07070100000F07000081B400000000000000000000000167AE111400000511000000000000000000000000000000000000006D00000000susemanager-schema/upgrade/susemanager-schema-4.3.16-to-susemanager-schema-4.3.17/011-update-queue_image.sql  --
-- Copyright (c) 2017 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
--

CREATE OR REPLACE FUNCTION
queue_image(image_id_in IN NUMERIC, immediate_in IN NUMERIC DEFAULT 1)
RETURNS VOID
AS
$$
DECLARE
    org_id_tmp NUMERIC;
BEGIN
    IF immediate_in > 0
    THEN
          PERFORM update_image_needed_cache(image_id_in);
    ELSE
          SELECT org_id INTO STRICT org_id_tmp FROM suseImageInfo WHERE id = image_id_in;

          INSERT
            INTO rhnTaskQueue
                 (id, org_id, task_name, task_data)
          SELECT nextval('rhn_task_queue_id_seq'),
                 org_id_tmp,
                 'update_image_errata_cache',
                 image_id_in
          WHERE NOT EXISTS
            (SELECT 1 FROM rhnTaskQueue
               WHERE org_id = org_id_tmp
               AND task_name = 'update_image_errata_cache'
               AND task_data = image_id_in
            );
    END IF;
END;
$$ LANGUAGE plpgsql;
   07070100000F08000081B400000000000000000000000167AE1114000006BF000000000000000000000000000000000000006E00000000susemanager-schema/upgrade/susemanager-schema-4.3.16-to-susemanager-schema-4.3.17/012-update-queue_server.sql --
-- Copyright (c) 2008--2015 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-- 
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation. 
--
--
--
--

-- the next two views are basically the same.  the first, though, has an outer join to
-- the errata stuff, in case there are packages the server needs that haven't been
-- errata'd (ie, the fringe case)


CREATE OR REPLACE FUNCTION
queue_server(server_id_in IN NUMERIC, immediate_in IN NUMERIC DEFAULT 1)
RETURNS VOID
AS
$$
DECLARE
    org_id_tmp NUMERIC;
BEGIN
    IF immediate_in > 0
    THEN
          PERFORM rhn_server.update_needed_cache(server_id_in);
    ELSE
          SELECT org_id INTO STRICT org_id_tmp
          FROM rhnServer WHERE id = server_id_in;

          INSERT
            INTO rhnTaskQueue
                 (id, org_id, task_name, task_data)
          SELECT nextval('rhn_task_queue_id_seq'),
                 org_id_tmp,
                 'update_server_errata_cache',
                 server_id_in
          WHERE NOT EXISTS
            (SELECT 1 FROM rhnTaskQueue
               WHERE org_id = org_id_tmp
               AND task_name = 'update_server_errata_cache'
               AND task_data = server_id_in
            );
    END IF;
END;
$$ LANGUAGE plpgsql;
 07070100000F09000081B400000000000000000000000167AE11140000007D000000000000000000000000000000000000007100000000susemanager-schema/upgrade/susemanager-schema-4.3.16-to-susemanager-schema-4.3.17/020-taskorun-paths-removal.sql  ALTER TABLE rhnTaskoRun DROP COLUMN IF EXISTS std_output_path;
ALTER TABLE rhnTaskoRun DROP COLUMN IF EXISTS std_error_path;
   07070100000F0A000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005200000000susemanager-schema/upgrade/susemanager-schema-4.3.17-to-susemanager-schema-4.3.18 07070100000F0B000081B400000000000000000000000167AE111400001261000000000000000000000000000000000000007100000000susemanager-schema/upgrade/susemanager-schema-4.3.17-to-susemanager-schema-4.3.18/000-ptf-package-visibility.sql  -- New view with all the packages excluding those that are part of a PTF
CREATE OR REPLACE VIEW susePackageExcludingPartOfPtf AS
  WITH ptfPackages AS (
      SELECT pp.package_id
        FROM rhnpackagecapability pc
                  INNER JOIN rhnpackageprovides pp ON pc.id = pp.capability_id
       WHERE pc.name = 'ptf-package()'
  )
  SELECT pkg.*
    FROM rhnpackage pkg
            LEFT JOIN ptfPackages ptf ON pkg.id = ptf.package_id
   WHERE ptf.package_id IS NULL
;

-- Update the view for the newest package to exclude packages part of a PTF
create or replace view
rhnChannelNewestPackageView
as
SELECT channel_id,
       name_id,
       evr_id,
       package_arch_id,
       package_id
FROM (
      SELECT channel_id,
             name_id,
             evr_id,
             package_arch_id,
             build_time,
             max(package_id) as package_id,
             ROW_NUMBER() OVER(PARTITION BY name_id, channel_id, package_arch_id ORDER BY build_time DESC) rn
      FROM (
            SELECT m.channel_id          as channel_id,
                   p.name_id             as name_id,
                   p.evr_id              as evr_id,
                   m.package_arch_id     as package_arch_id,
                   p.id                  as package_id,
                   p.build_time          as build_time
            FROM (select max(pe.evr) AS max_evr,
                         cp.channel_id,
                         p.name_id,
                         p.package_arch_id
                    from rhnPackageEVR                           pe,
                         susePackageExcludingPartOfPtf            p,
                         suseChannelPackageRetractedStatusView   cp
                   where p.evr_id = pe.id
                     and cp.package_id = p.id
                     and NOT cp.is_retracted
                   group by cp.channel_id, p.name_id, p.package_arch_id) m,
                 rhnPackageEVR       pe,
                 rhnPackage          p,
                 rhnChannelPackage   chp
            WHERE m.max_evr = pe.evr
                AND m.name_id = p.name_id
                AND m.package_arch_id = p.package_arch_id
                AND p.evr_id = pe.id
                AND chp.package_id = p.id
                AND chp.channel_id = m.channel_id
      ) latest_packages
      group by channel_id, name_id, evr_id, package_arch_id, build_time
) n
WHERE rn = 1;

-- Update the function to refresh the updatable packages to exclude those that are part of a PTF from the results
UPDATE pg_settings
   SET setting = 'rhn_server,' || setting
 WHERE name = 'search_path';

    create or replace function update_needed_cache(
        server_id_in in numeric
  ) returns void as $$
    begin
      delete from rhnServerNeededCache
        where server_id = server_id_in;
      insert into rhnServerNeededCache
             (server_id, errata_id, package_id, channel_id)
        (select distinct sp.server_id, x.errata_id, p.id, x.channel_id
           FROM (SELECT sp_sp.server_id, sp_sp.name_id,
            sp_sp.package_arch_id, max(sp_pe.evr) AS max_evr
                   FROM rhnServerPackage sp_sp
                   join rhnPackageEvr sp_pe ON sp_pe.id = sp_sp.evr_id
                  GROUP BY sp_sp.server_id, sp_sp.name_id, sp_sp.package_arch_id) sp
           join susePackageExcludingPartOfPtf p ON p.name_id = sp.name_id
           join rhnPackageEvr pe ON pe.id = p.evr_id AND (sp.max_evr).type = (pe.evr).type AND sp.max_evr < pe.evr
           join rhnPackageUpgradeArchCompat puac
              ON puac.package_arch_id = sp.package_arch_id
        AND puac.package_upgrade_arch_id = p.package_arch_id
           join rhnServerChannel sc ON sc.server_id = sp.server_id
           join rhnChannelPackage cp ON cp.package_id = p.id
              AND cp.channel_id = sc.channel_id
           left join (SELECT ep.errata_id, ce.channel_id, ep.package_id
                        FROM rhnChannelErrata ce
                        join rhnErrataPackage ep
               ON ep.errata_id = ce.errata_id
      join rhnServerChannel sc_sc
               ON sc_sc.channel_id = ce.channel_id
           WHERE sc_sc.server_id = server_id_in) x
             ON x.channel_id = sc.channel_id AND x.package_id = cp.package_id
     left join rhnErrata e on x.errata_id = e.id
          where sp.server_id = server_id_in
            and (x.errata_id IS NULL or e.advisory_status != 'retracted')); -- packages which are part of a retracted errata should not be installed
  end$$ language plpgsql;

-- restore the original setting
UPDATE pg_settings
   SET setting = overlay( setting placing '' FROM 1 FOR (LENGTH('rhn_server') + 1) )
 WHERE name = 'search_path';
   07070100000F0C000081B400000000000000000000000167AE111400001E93000000000000000000000000000000000000007900000000susemanager-schema/upgrade/susemanager-schema-4.3.17-to-susemanager-schema-4.3.18/001-update-function-create_new_org.sql  
create or replace function create_new_org
(
        name_in      in varchar,
        password_in  in varchar
        --org_id_out   out number
) returns numeric
as
$$
declare
        ug_type                 numeric;
        group_val               numeric;
        new_org_id              numeric;
        org_id_out		numeric;
begin

        select nextval('web_customer_id_seq') into new_org_id from dual;

        insert into web_customer (
                id, name
        ) values (
                new_org_id, name_in
        );

        select nextval('rhn_user_group_id_seq') into group_val from dual;

        select  id
        into    ug_type
        from    rhnUserGroupType
        where   label = 'org_admin';

        insert into rhnUserGroup (
                id, name,
                description,
                max_members, group_type, org_id
        ) values (
                group_val, 'Organization Administrators',
                'Organization Administrators for Org ' || name_in,
                NULL, ug_type, new_org_id
        );

        select nextval('rhn_user_group_id_seq') into group_val from dual;

        select  id
        into    ug_type
        from    rhnUserGroupType
        where   label = 'system_group_admin';

        insert into rhnUserGroup (
                id, name,
                description,
                max_members, group_type, org_id
        ) values (
                group_val, 'System Group Administrators',
                'System Group Administrators for Org ' || name_in,
                NULL, ug_type, new_org_id
        );


        select nextval('rhn_user_group_id_seq') into group_val from dual;

        select  id
        into    ug_type
        from    rhnUserGroupType
        where   label = 'activation_key_admin';

        insert into rhnUserGroup (
                id, name,
                description,
                max_members, group_type, org_id
        ) values (
                group_val, 'Activation Key Administrators',
                'Activation Key Administrators for Org ' || name_in,
                NULL, ug_type, new_org_id
        );

        select nextval('rhn_user_group_id_seq') into group_val from dual;

        select  id
        into    ug_type
        from    rhnUserGroupType
        where   label = 'channel_admin';

        insert into rhnUserGroup (
                id, name,
                description,
                max_members, group_type, org_id
        ) values (
                group_val, 'Channel Administrators',
                'Channel Administrators for Org ' || name_in,
                NULL, ug_type, new_org_id
        );

	if new_org_id = 1 then
            select nextval('rhn_user_group_id_seq') into group_val from dual;

            select  id
            into    ug_type
            from    rhnUserGroupType
            where   label = 'satellite_admin';

            insert into rhnUserGroup (
                    id, name,
                    description,
                    max_members, group_type, org_id
            ) values (
                    group_val, 'SUSE Manager Administrators',
                    'SUSE Manager Administrators for Org ' || name_in,
                    NULL, ug_type, new_org_id
            );
        end if;

        select nextval('rhn_user_group_id_seq') into group_val from dual;

        select  id
        into    ug_type
        from    rhnUserGroupType
        where   label = 'config_admin';

        insert into rhnUserGroup (
                id, name,
                description,
                max_members, group_type, org_id
        ) values (
                group_val, 'Configuration Administrators',
                'Configuration Administrators for Org ' || name_in,
                NULL, ug_type, new_org_id
        );

        select nextval('rhn_user_group_id_seq') into group_val from dual;

        select  id
        into    ug_type
        from    rhnUserGroupType
        where   label = 'image_admin';

        insert into rhnUserGroup (
                id, name,
                description,
                max_members, group_type, org_id
        ) values (
                group_val, 'Image Administrators',
                'Image Administrators for Org ' || name_in,
                NULL, ug_type, new_org_id
        );

        select nextval('rhn_user_group_id_seq') into group_val from dual;

        -- there aren't any users yet, so we don't need to update
        -- rhnUserServerPerms

        insert into rhnServerGroup
                ( id, name, description, group_type, org_id )
                select nextval('rhn_server_group_id_seq'), sgt.name, sgt.name,
                        sgt.id, new_org_id
                from rhnServerGroupType sgt
                where sgt.label = 'bootstrap_entitled';

        insert into rhnServerGroup
                ( id, name, description, group_type, org_id )
                select nextval('rhn_server_group_id_seq'), sgt.name, sgt.name,
                        sgt.id, new_org_id
                from rhnServerGroupType sgt
                where sgt.label = 'enterprise_entitled';

        insert into rhnServerGroup
                ( id, name, description, group_type, org_id )
                select nextval('rhn_server_group_id_seq'), sgt.name, sgt.name,
                        sgt.id, new_org_id
                from rhnServerGroupType sgt
                where sgt.label = 'salt_entitled';

        insert into rhnServerGroup
                ( id, name, description, group_type, org_id )
                select nextval('rhn_server_group_id_seq'), sgt.name, sgt.name,
                        sgt.id, new_org_id
                from rhnServerGroupType sgt
                where sgt.label = 'foreign_entitled';

        insert into rhnServerGroup
                ( id, name, description, group_type, org_id )
                select nextval('rhn_server_group_id_seq'), sgt.name, sgt.name,
                        sgt.id, new_org_id
                from rhnServerGroupType sgt
                where sgt.label = 'virtualization_host';

        insert into rhnServerGroup
                ( id, name, description, group_type, org_id )
                select nextval('rhn_server_group_id_seq'), sgt.name, sgt.name,
                        sgt.id, new_org_id
                from rhnServerGroupType sgt
                where sgt.label = 'container_build_host';

        insert into rhnServerGroup
                ( id, name, description, group_type, org_id )
                select nextval('rhn_server_group_id_seq'), sgt.name, sgt.name,
                        sgt.id, new_org_id
                from rhnServerGroupType sgt
                where sgt.label = 'osimage_build_host';

        insert into rhnServerGroup
                ( id, name, description, group_type, org_id )
                select nextval('rhn_server_group_id_seq'), sgt.name, sgt.name,
                        sgt.id, new_org_id
                from rhnServerGroupType sgt
                where sgt.label = 'monitoring_entitled';

        insert into rhnServerGroup
                ( id, name, description, group_type, org_id )
                select nextval('rhn_server_group_id_seq'), sgt.name, sgt.name,
                        sgt.id, new_org_id
                from rhnServerGroupType sgt
                where sgt.label = 'ansible_control_node';

        insert into suseImageStore (id, label, uri, store_type_id, org_id)
        values (
            nextval('suse_imgstore_id_seq'),
            'SUSE Manager OS Image Store',
            new_org_id || '/',
            (SELECT id FROM suseImageStoreType WHERE label = 'os_image'),
            new_org_id
        );

        org_id_out := new_org_id;

	-- Returning the value of OUT parameter
        return org_id_out;

end;
$$
language plpgsql;
 07070100000F0D000081B400000000000000000000000167AE11140000028B000000000000000000000000000000000000007B00000000susemanager-schema/upgrade/susemanager-schema-4.3.17-to-susemanager-schema-4.3.18/100-rhnChannelComps-revert_drop_uidx.sql    -- Drop the indexes
DROP INDEX IF EXISTS rhn_channelcomps_cid_ctype_uq;
DROP INDEX IF EXISTS rhn_channelcomps_cid_ctype_idx;
ALTER TABLE rhnChannelComps DROP CONSTRAINT IF EXISTS rhn_channelcomps_cid_ctype_filename_uq;

-- Delete outdated (archived) comps entries,
-- keeping only the latest for each type, per channel
DELETE FROM rhnChannelComps c
WHERE EXISTS (
    SELECT 1
    FROM rhnChannelComps
    WHERE id != c.id
        AND channel_id = c.channel_id
        AND last_modified >= c.last_modified
        AND comps_type_id = c.comps_type_id
);

CREATE UNIQUE INDEX rhn_channelcomps_cid_ctype_uq ON rhnChannelComps(channel_id, comps_type_id);
 07070100000F0E000081B400000000000000000000000167AE111400000040000000000000000000000000000000000000007800000000susemanager-schema/upgrade/susemanager-schema-4.3.17-to-susemanager-schema-4.3.18/100-suseContentFilter-null-values.sql   ALTER TABLE susecontentfilter ALTER COLUMN value DROP NOT NULL;
07070100000F0F000081B400000000000000000000000167AE111400001432000000000000000000000000000000000000007200000000susemanager-schema/upgrade/susemanager-schema-4.3.17-to-susemanager-schema-4.3.18/400-update-recurring-action.sql --
-- Copyright (c) 2023 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
BEGIN;

CREATE TABLE IF NOT EXISTS suseInternalState
(
  id                NUMERIC NOT NULL
                    CONSTRAINT suse_internal_state_id_pk PRIMARY KEY,
  name              VARCHAR(128) NOT NULL,
  label             VARCHAR(128) NOT NULL
);

DELETE FROM suseInternalState;

INSERT INTO suseInternalState (id, name, label)
         VALUES (1, 'certs', 'Certificates');

INSERT INTO suseInternalState (id, name, label)
         VALUES (2, 'channels', 'Channels');

INSERT INTO suseInternalState (id, name, label)
         VALUES (3, 'hardware.profileupdate', 'Hardware Profile Update');

INSERT INTO suseInternalState (id, name, label)
         VALUES (4, 'packages', 'Packages');

INSERT INTO suseInternalState (id, name, label)
         VALUES (5, 'packages.profileupdate', 'Package Profile Update');

INSERT INTO suseInternalState (id, name, label)
         VALUES (6, 'uptodate', 'Update System');

INSERT INTO suseInternalState (id, name, label)
         VALUES (7, 'util.syncbeacons', 'Sync Beacons');

INSERT INTO suseInternalState (id, name, label)
         VALUES (8, 'util.syncall', 'Sync All');

INSERT INTO suseInternalState (id, name, label)
         VALUES (9, 'util.syncgrains', 'Sync Grains');

INSERT INTO suseInternalState (id, name, label)
         VALUES (10, 'util.syncmodules', 'Sync Modules');

INSERT INTO suseInternalState (id, name, label)
         VALUES (11, 'util.syncstates', 'Sync States');

CREATE TABLE IF NOT EXISTS suseRecurringHighstate
(
  rec_id            NUMERIC NOT NULL
                    CONSTRAINT suse_recurring_highstate_id_pk PRIMARY KEY
                    CONSTRAINT suse_recurring_action_highstate_id_fk
                      REFERENCES suseRecurringAction(id)
                      ON DELETE CASCADE,
  test_mode         CHAR(1) NOT NULL
                    DEFAULT 'N'
);

ALTER TABLE suseRecurringAction ADD COLUMN IF NOT EXISTS test_mode CHAR(1) DEFAULT 'N' NOT NULL;
INSERT INTO suseRecurringHighstate (rec_id, test_mode)
         SELECT id, test_mode FROM suseRecurringAction
         WHERE NOT EXISTS (SELECT id FROM suseRecurringHighstate);
ALTER TABLE suseRecurringAction DROP COLUMN IF EXISTS test_mode;

ALTER TABLE suseRecurringAction ADD COLUMN IF NOT EXISTS action_type VARCHAR(32) NULL;
UPDATE suseRecurringAction SET action_type = 'HIGHSTATE' WHERE action_type IS NULL;
ALTER TABLE suseRecurringAction ALTER COLUMN action_type SET NOT NULL;

CREATE TABLE IF NOT EXISTS suseRecurringState
(
  rec_id            NUMERIC NOT NULL
                    CONSTRAINT suse_recurring_state_id_pk PRIMARY KEY
                    CONSTRAINT suse_recurring_action_state_id_fk
                      REFERENCES suseRecurringAction(id)
                      ON DELETE CASCADE,
  test_mode         CHAR(1) NOT NULL
                    DEFAULT 'N'
);

CREATE TABLE IF NOT EXISTS suseRecurringStateConfig
(
  id                NUMERIC NOT NULL
                    CONSTRAINT suse_recurring_state_config_id_pk PRIMARY KEY,
  rec_id            NUMERIC NOT NULL
                    CONSTRAINT suse_recurring_state_config_state_id_fk
                      REFERENCES suseRecurringState(rec_id)
                      ON DELETE CASCADE,
  state_id          NUMERIC
                    CONSTRAINT suse_recurring_state_intstate_id_fk
                      REFERENCES suseInternalState(id)
                      ON DELETE CASCADE,
  confchan_id       NUMERIC
                    CONSTRAINT suse_recurring_state_confchan_id_fk
                      REFERENCES rhnConfigChannel(id)
                      ON DELETE CASCADE,
  position          NUMERIC NOT NULL
);

ALTER TABLE suseRecurringStateConfig 
  DROP CONSTRAINT IF EXISTS suse_rec_state_conf_rec_id_pos_uq;

ALTER TABLE suseRecurringStateConfig
  ADD CONSTRAINT suse_rec_state_conf_rec_id_pos_uq UNIQUE (rec_id, position);

CREATE SEQUENCE IF NOT EXISTS suse_recurring_state_config_id_seq;

CREATE UNIQUE INDEX IF NOT EXISTS suse_rec_state_conf_rec_id_state_id_uq
  ON suseRecurringStateConfig(rec_id, state_id)
  WHERE confchan_id IS NULL AND state_id IS NOT NULL;

CREATE UNIQUE INDEX IF NOT EXISTS suse_rec_state_conf_rec_id_confchan_id_uq
  ON suseRecurringStateConfig(rec_id, confchan_id)
  WHERE state_id IS NULL AND confchan_id IS NOT NULL;

UPDATE rhnTaskoBunch SET description='Schedules actions for minion/group/org' 
  WHERE name='recurring-state-apply-bunch';
UPDATE rhnTaskoBunch SET name='recurring-action-executor-bunch'
  WHERE name='recurring-state-apply-bunch';

UPDATE rhnTaskoTask SET name='recurring-action-executor'
  WHERE name='recurring-state-apply';
UPDATE rhnTaskoTask SET class='com.redhat.rhn.taskomatic.task.RecurringActionJob'
  WHERE class='com.redhat.rhn.taskomatic.task.RecurringStateApplyJob';

COMMIT;

  07070100000F10000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005200000000susemanager-schema/upgrade/susemanager-schema-4.3.18-to-susemanager-schema-4.3.19 07070100000F11000081B400000000000000000000000167AE111400000531000000000000000000000000000000000000007600000000susemanager-schema/upgrade/susemanager-schema-4.3.18-to-susemanager-schema-4.3.19/200-payg-add-computation-tables.sql CREATE TABLE IF NOT EXISTS susePaygDimensionComputation
(
    id                   NUMERIC NOT NULL
                            CONSTRAINT susePaygDimensionComputation_pk PRIMARY KEY,
    timestamp            TIMESTAMPTZ DEFAULT (current_timestamp) NOT NULL,
    success              BOOLEAN
);

CREATE SEQUENCE IF NOT EXISTS susePaygDimensionComputation_id_seq;

CREATE INDEX IF NOT EXISTS susePaygDimensionComputation_timestamp_idx
    ON susePaygDimensionComputation (timestamp DESC);

DO $$
BEGIN
    IF NOT EXISTS (SELECT 1 FROM pg_type WHERE typname = 'billing_dimension_t') THEN
        CREATE TYPE billing_dimension_t AS ENUM (
            'managed_systems',
            'monitoring'
        );
    ELSE
        RAISE NOTICE 'type "billing_dimension_t" already exists, skipping';
    END IF;
END $$;

CREATE TABLE IF NOT EXISTS susePaygDimensionResult
(
    id                NUMERIC NOT NULL
                          CONSTRAINT susePaygDimensionResult_id_pk PRIMARY KEY,
    computation_id    NUMERIC NOT NULL
                          CONSTRAINT susePaygDimensionResult_computation_fk
                              REFERENCES susePaygDimensionComputation (id),
    dimension         billing_dimension_t NOT NULL,
    count             NUMERIC NOT NULL
);

CREATE SEQUENCE IF NOT EXISTS susePaygDimensionResult_id_seq;
   07070100000F12000081B400000000000000000000000167AE1114000006C3000000000000000000000000000000000000006A00000000susemanager-schema/upgrade/susemanager-schema-4.3.18-to-susemanager-schema-4.3.19/201-payg-taskomatic.sql ALTER TABLE rhntaskotask ALTER COLUMN class TYPE varchar(120);

INSERT INTO rhnTaskoBunch (id, name, description, org_bunch)
SELECT sequence_nextval('rhn_tasko_bunch_id_seq'), 'payg-dimension-computation-bunch',
       'Compute the dimensions data required for PAYG billing', null
WHERE NOT EXISTS (
        SELECT 1 FROM rhnTaskoBunch
        WHERE name = 'payg-dimension-computation-bunch'
    );

INSERT INTO rhnTaskoSchedule (id, job_label, bunch_id, active_from, cron_expr)
SELECT sequence_nextval('rhn_tasko_schedule_id_seq'), 'payg-dimension-computation-default',
       (SELECT id FROM rhnTaskoBunch WHERE name='payg-dimension-computation-bunch'),
       current_timestamp, '0 45 * ? * * *'
WHERE NOT EXISTS (
        SELECT 1 FROM rhnTaskoSchedule
        WHERE job_label = 'payg-dimension-computation-default'
    );

INSERT INTO rhnTaskoTask (id, name, class)
SELECT sequence_nextval('rhn_tasko_task_id_seq'), 'payg-dimension-computation',
       'com.redhat.rhn.taskomatic.task.payg.PaygComputeDimensionsTask'
WHERE NOT EXISTS (
        SELECT 1 FROM rhnTaskoTask
        WHERE name = 'payg-dimension-computation'
    );

INSERT INTO rhnTaskoTemplate (id, bunch_id, task_id, ordering, start_if)
SELECT sequence_nextval('rhn_tasko_template_id_seq'),
       (SELECT id FROM rhnTaskoBunch WHERE name='payg-dimension-computation-bunch'),
       (SELECT id FROM rhnTaskoTask WHERE name='payg-dimension-computation'),
       0, null
WHERE NOT EXISTS (
        SELECT 1 FROM rhnTaskoTemplate
        WHERE bunch_id = (SELECT id FROM rhnTaskoBunch WHERE name = 'payg-dimension-computation-bunch')
          AND task_id = (SELECT id FROM rhnTaskoTask WHERE name = 'payg-dimension-computation')
          AND ordering = 0
    );
 07070100000F13000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005200000000susemanager-schema/upgrade/susemanager-schema-4.3.19-to-susemanager-schema-4.3.20 07070100000F14000081B400000000000000000000000167AE111400000389000000000000000000000000000000000000006800000000susemanager-schema/upgrade/susemanager-schema-4.3.19-to-susemanager-schema-4.3.20/000-payg-products.sql   CREATE TABLE IF NOT EXISTS susePaygProduct
(
    id                          NUMERIC NOT NULL
                                CONSTRAINT susePaygProduct_pk PRIMARY KEY,
    credentials_id              NUMERIC NOT NULL
                                CONSTRAINT susePaygProduct_credentials_id_fk
                                REFERENCES suseCredentials (id)
                                ON DELETE CASCADE,
    name                        VARCHAR(256),
    version                     VARCHAR(256),
    arch                        VARCHAR(256),
    created                     TIMESTAMPTZ DEFAULT (current_timestamp) NOT NULL,
    modified                    TIMESTAMPTZ DEFAULT (current_timestamp) NOT NULL
);

CREATE SEQUENCE IF NOT EXISTS susePaygProduct_id_seq;

CREATE UNIQUE INDEX IF NOT EXISTS susePaygProduct_credentials_product_uq
    ON susePaygProduct (credentials_id, name, version, arch);
   07070100000F15000081B400000000000000000000000167AE1114000001BA000000000000000000000000000000000000007300000000susemanager-schema/upgrade/susemanager-schema-4.3.19-to-susemanager-schema-4.3.20/001-add-rhui-credential-type.sql    DO $$
  BEGIN
    IF EXISTS (SELECT 1 FROM information_schema.tables WHERE table_name = 'susecredentialstype') THEN
      insert into suseCredentialsType (id, label, name)
        select sequence_nextval('suse_credtype_id_seq'), 'rhui', 'Red Hat Update Infrastructure'
        where not exists(select 1 from suseCredentialsType where label = 'rhui');
    ELSE
      RAISE NOTICE 'suseCredentialsType does not exists';
    END IF;
  END;
$$;

  07070100000F16000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005000000000susemanager-schema/upgrade/susemanager-schema-4.3.2-to-susemanager-schema-4.3.3   07070100000F17000081B400000000000000000000000167AE111400000B11000000000000000000000000000000000000006800000000susemanager-schema/upgrade/susemanager-schema-4.3.2-to-susemanager-schema-4.3.3/001-add-sql-pillars.sql   --
-- Copyright (c) 2021 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

CREATE TABLE IF NOT EXISTS suseSaltPillar
(
    id NUMERIC NOT NULL
        CONSTRAINT suse_salt_pillar_id_pk PRIMARY KEY,
    server_id NUMERIC
              CONSTRAINT suse_salt_pillar_sid_fk
              REFERENCES rhnServer (id)
              ON DELETE CASCADE,
    group_id NUMERIC
             CONSTRAINT suse_salt_pillar_gid_fk
             REFERENCES rhnServerGroup (id)
             ON DELETE CASCADE,
    org_id NUMERIC
           CONSTRAINT suse_salt_pillar_oid_fk
           REFERENCES web_customer (id)
           ON DELETE CASCADE,
    category VARCHAR NOT NULL,
    pillar JSONB NOT NULL,
    UNIQUE (server_id, category),
    UNIQUE (group_id, category),
    UNIQUE (org_id, category),
    CONSTRAINT suse_salt_pillar_only_one_target CHECK (
      ( server_id is not null and group_id is null and org_id is null ) or
      ( server_id is null and group_id is not null and org_id is null ) or
      ( server_id is null and group_id is null and org_id is not null ) or
      ( server_id is null and group_id is null and org_id is null)
    )
);

CREATE SEQUENCE IF NOT EXISTS suse_salt_pillar_id_seq;

CREATE INDEX IF NOT EXISTS suse_salt_pillar_server_id_idx ON suseSaltPillar (server_id);
CREATE INDEX IF NOT EXISTS suse_salt_pillar_group_id_idx ON suseSaltPillar (group_id);
CREATE INDEX IF NOT EXISTS suse_salt_pillar_org_id_idx ON suseSaltPillar (org_id);
CREATE INDEX IF NOT EXISTS suse_salt_pillar_category_idx ON suseSaltPillar (category);

CREATE OR REPLACE FUNCTION minion_pillars(
  mid VARCHAR
) RETURNS TABLE (pillar JSONB) LANGUAGE plpgsql
AS $$
DECLARE
  sid NUMERIC;
BEGIN
  SELECT server_id INTO sid FROM suseMinionInfo WHERE minion_id = mid;
  RETURN QUERY
  SELECT p.pillar from suseSaltPillar AS p WHERE (p.server_id is NULL AND p.group_id is NULL AND p.org_id is NULL)
       OR (p.org_id = (SELECT s.org_id FROM rhnServer AS s WHERE s.id = sid))
       OR (p.group_id IN (SELECT g.server_group_id FROM rhnServerGroupMembers AS g WHERE g.server_id = sid))
       OR (p.server_id = sid)
       ORDER BY CASE WHEN p.org_id IS NULL AND p.group_id IS NULL and p.server_id is NULL THEN 0 ELSE 1 END, p.org_id NULLS LAST, p.group_id ASC NULLS LAST, p.server_id ASC NULLS FIRST;
END
$$;
   07070100000F18000081B400000000000000000000000167AE1114000000CA000000000000000000000000000000000000007800000000susemanager-schema/upgrade/susemanager-schema-4.3.2-to-susemanager-schema-4.3.3/100-playbook-action-flushcache-flag.sql   ALTER TABLE rhnActionPlaybook ADD COLUMN IF NOT EXISTS
    flush_cache CHAR(1) DEFAULT ('N') NOT NULL
        CONSTRAINT rhn_action_playbook_flushcache_ck
            CHECK (flush_cache IN ('Y', 'N'));
  07070100000F19000081B400000000000000000000000167AE1114000003A6000000000000000000000000000000000000007400000000susemanager-schema/upgrade/susemanager-schema-4.3.2-to-susemanager-schema-4.3.3/400-rhnactionpackagedetails-idx.sql   --
-- Copyright (c) 2021 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

DROP INDEX IF EXISTS rhn_act_eud_aid_idx;

DELETE FROM rhnactionpackagedetails d1
 where d1.id > any (SELECT d2.id
                      FROM rhnactionpackagedetails d2
	             WHERE d1.action_id = d2.action_id);

CREATE UNIQUE INDEX IF NOT EXISTS rhn_act_eud_aid_uq
    ON rhnActionPackageDetails (action_id);
  07070100000F1A000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005200000000susemanager-schema/upgrade/susemanager-schema-4.3.20-to-susemanager-schema-4.3.21 07070100000F1B000081B400000000000000000000000167AE1114000002EC000000000000000000000000000000000000007B00000000susemanager-schema/upgrade/susemanager-schema-4.3.20-to-susemanager-schema-4.3.21/001-improve-ubuntu-errata-processing.sql    INSERT INTO rhnTaskoTask (id, name, class)
     SELECT sequence_nextval('rhn_tasko_task_id_seq')
                , 'ubuntu-errata'
                , 'com.redhat.rhn.taskomatic.task.UbuntuErrataTask'
      WHERE NOT EXISTS (SELECT id FROM rhnTaskoTask WHERE name = 'ubuntu-errata');

INSERT INTO rhnTaskoTemplate (id, bunch_id, task_id, ordering, start_if)
    SELECT sequence_nextval('rhn_tasko_template_id_seq')
                , tb.id
                , tt.id
                , 1
                , 'FINISHED'
      FROM rhnTaskoBunch tb, rhnTaskoTask tt
    WHERE tb.name = 'repo-sync-bunch'
                AND tt.name = 'ubuntu-errata'
                AND NOT EXISTS (SELECT id FROM rhnTaskoTemplate WHERE bunch_id = tb.id AND task_id = tt.id);
07070100000F1C000081B400000000000000000000000167AE111400000060000000000000000000000000000000000000007600000000susemanager-schema/upgrade/susemanager-schema-4.3.20-to-susemanager-schema-4.3.21/002-add-serverneededcache-index.sql CREATE INDEX IF NOT EXISTS rhn_snc_seid_idx
    ON rhnServerNeededCache (server_id, errata_id);
07070100000F1D000081B400000000000000000000000167AE111400000368000000000000000000000000000000000000007100000000susemanager-schema/upgrade/susemanager-schema-4.3.20-to-susemanager-schema-4.3.21/100-add-qrtz-missing-table.sql  --
-- add missing simprop_triggers table
-- it was part of 0100-quartz-schema-upgrade.sql but was missing in qrtz.sql
--
CREATE TABLE IF NOT EXISTS qrtz_simprop_triggers
 (
    SCHED_NAME VARCHAR(120) NOT NULL,
    TRIGGER_NAME VARCHAR(200) NOT NULL,
    TRIGGER_GROUP VARCHAR(200) NOT NULL,
    STR_PROP_1 VARCHAR(512) NULL,
    STR_PROP_2 VARCHAR(512) NULL,
    STR_PROP_3 VARCHAR(512) NULL,
    INT_PROP_1 INT NULL,
    INT_PROP_2 INT NULL,
    LONG_PROP_1 BIGINT NULL,
    LONG_PROP_2 BIGINT NULL,
    DEC_PROP_1 NUMERIC(13,4) NULL,
    DEC_PROP_2 NUMERIC(13,4) NULL,
    BOOL_PROP_1 BOOL NULL,
    BOOL_PROP_2 BOOL NULL,
    CONSTRAINT PK_SIMPROP_TRIGGERS PRIMARY KEY (SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP),
    CONSTRAINT FK_SIMPROP_TRIGGERS FOREIGN KEY (SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP)
    REFERENCES QRTZ_TRIGGERS(SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP)
);
07070100000F1E000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005200000000susemanager-schema/upgrade/susemanager-schema-4.3.21-to-susemanager-schema-4.3.22 07070100000F1F000081B400000000000000000000000167AE111400000000000000000000000000000000000000000000005B00000000susemanager-schema/upgrade/susemanager-schema-4.3.21-to-susemanager-schema-4.3.22/.gitkeep    07070100000F20000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005200000000susemanager-schema/upgrade/susemanager-schema-4.3.22-to-susemanager-schema-4.3.23 07070100000F21000081B400000000000000000000000167AE111400000085000000000000000000000000000000000000007500000000susemanager-schema/upgrade/susemanager-schema-4.3.22-to-susemanager-schema-4.3.23/200-revert-changelogdata-index.sql  drop index if exists rhn_pkg_cld_ntt_idx;
create index if not exists rhn_pkg_cld_nt_idx
    on rhnPackageChangeLogData (name, time);
   07070100000F22000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005200000000susemanager-schema/upgrade/susemanager-schema-4.3.23-to-susemanager-schema-4.3.24 07070100000F23000081B400000000000000000000000167AE111400000897000000000000000000000000000000000000006D00000000susemanager-schema/upgrade/susemanager-schema-4.3.23-to-susemanager-schema-4.3.24/100-update-credentials.sql  DO $$
  BEGIN
    IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name = 'susecredentials' AND column_name = 'type') THEN
        ALTER TABLE susecredentials
            ADD COLUMN type VARCHAR(128) DEFAULT ('scc') NOT NULL
                                            CONSTRAINT rhn_type_ck
                                            CHECK (type IN ('scc', 'vhm', 'registrycreds', 'cloudrmt', 'reportcreds', 'rhui'));

        UPDATE susecredentials cc
           SET type = ct.label
          FROM susecredentials c
                    INNER JOIN susecredentialstype ct ON c.type_id = ct.id
         WHERE cc.id = c.id;

        ALTER TABLE susecredentials
            DROP COLUMN type_id;

        ALTER TABLE susecredentials
            ALTER COLUMN username DROP NOT NULL;

        ALTER TABLE susecredentials
            ALTER COLUMN password DROP NOT NULL;

        ALTER TABLE susecredentials
            ADD CONSTRAINT cred_type_check CHECK (
                CASE type
                    WHEN 'scc' THEN
                        username is not null and username <> ''
                            and password is not null and password <> ''
                    WHEN 'cloudrmt' THEN
                        username is not null and username <> ''
                            and password is not null and password <> ''
                            and url is not null and url <> ''
                    WHEN 'vhm' THEN
                        username is not null and username <> ''
                            and password is not null and password <> ''
                    WHEN 'registrycreds' THEN
                        username is not null and username <> ''
                            and password is not null and password <> ''
                    WHEN 'reportcreds' THEN
                        username is not null and username <> ''
                            and password is not null and password <> ''
                END
            );
    ELSE
      RAISE NOTICE 'type column already exists for susecredentials. Table is already up to date.';
    END IF;
  END;
$$;

DROP TABLE IF EXISTS susecredentialstype;

DROP SEQUENCE IF EXISTS suse_credtype_id_seq;
 07070100000F24000081B400000000000000000000000167AE1114000000CC000000000000000000000000000000000000007300000000susemanager-schema/upgrade/susemanager-schema-4.3.23-to-susemanager-schema-4.3.24/101-indexes-for-system-views.sql    CREATE INDEX IF NOT EXISTS rhn_package_nid_evrid_idx ON rhnPackage (name_id, evr_id);
CREATE INDEX IF NOT EXISTS rhn_sp_sien_idx ON rhnServerPackage USING btree (server_id, installtime, evr_id, name_id);
07070100000F25000081B400000000000000000000000167AE111400000117000000000000000000000000000000000000007E00000000susemanager-schema/upgrade/susemanager-schema-4.3.23-to-susemanager-schema-4.3.24/200-change-sys-profile-refresh-schedule.sql -- Once a month at the 2nd Saturday at 5am
UPDATE rhnTaskoSchedule
  SET cron_expr = '0 0 5 ? * SAT#2'
WHERE job_label = 'system-profile-refresh-default'
  AND bunch_id = (SELECT id FROM rhnTaskoBunch WHERE name='system-profile-refresh-bunch')
  AND cron_expr = '0 0 5 15 * ?';

 07070100000F26000081B400000000000000000000000167AE11140000020E000000000000000000000000000000000000007500000000susemanager-schema/upgrade/susemanager-schema-4.3.23-to-susemanager-schema-4.3.24/300-reboot-required-any-distro.sql  ALTER TABLE suseMinionInfo ADD COLUMN IF NOT EXISTS reboot_required_after TIMESTAMPTZ;

DO $$ 
BEGIN 
    IF EXISTS (
        SELECT column_name 
        FROM information_schema.columns 
        WHERE table_name = 'suseminioninfo' AND column_name = 'reboot_needed'
    ) THEN
        UPDATE suseMinionInfo
        SET reboot_required_after = CASE
            WHEN reboot_needed = 'Y' THEN CURRENT_TIMESTAMP
            ELSE NULL
        END;
    END IF;
END $$;

ALTER TABLE suseMinionInfo DROP COLUMN IF EXISTS reboot_needed;  07070100000F27000081B400000000000000000000000167AE1114000000BB000000000000000000000000000000000000007000000000susemanager-schema/upgrade/susemanager-schema-4.3.23-to-susemanager-schema-4.3.24/301-enable-pillar-refresh.sql   INSERT INTO rhnTaskQueue (id, org_id, task_name, task_data)
SELECT nextval('rhn_task_queue_id_seq'), id, 'upgrade_satellite_all_systems_pillar_refresh', 0
FROM web_customer
WHERE id = 1;
 07070100000F28000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005200000000susemanager-schema/upgrade/susemanager-schema-4.3.24-to-susemanager-schema-4.3.25 07070100000F29000081B400000000000000000000000167AE1114000000AE000000000000000000000000000000000000007900000000susemanager-schema/upgrade/susemanager-schema-4.3.24-to-susemanager-schema-4.3.25/100-add-internal-state-update-salt.sql  INSERT INTO suseInternalState (id, name, label)
  SELECT 12, 'update-salt', 'Update Salt'
   WHERE NOT EXISTS (
	SELECT 1 FROM suseInternalState
         WHERE id = 12
   );
  07070100000F2A000081B400000000000000000000000167AE1114000000B5000000000000000000000000000000000000007600000000susemanager-schema/upgrade/susemanager-schema-4.3.24-to-susemanager-schema-4.3.25/200-enable-all-systems-sync-all.sql INSERT INTO rhnTaskQueue (id, org_id, task_name, task_data)
SELECT nextval('rhn_task_queue_id_seq'), id, 'upgrade_satellite_all_systems_sync_all', 0
FROM web_customer
WHERE id = 1;
   07070100000F2B000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005200000000susemanager-schema/upgrade/susemanager-schema-4.3.25-to-susemanager-schema-4.3.26 07070100000F2C000081B400000000000000000000000167AE11140000124C000000000000000000000000000000000000006B00000000susemanager-schema/upgrade/susemanager-schema-4.3.25-to-susemanager-schema-4.3.26/001-add-package-keys.sql    insert into rhnPackageKey (id, key_id, key_type_id, provider_id) (select sequence_nextval('rhn_pkey_id_seq'), '5054e4a45a6340b3', lookup_package_key_type('gpg'), lookup_package_provider('Red Hat Inc.') from dual where not exists (select 1 from rhnPackageKey where key_id = '5054e4a45a6340b3'));

insert into rhnPackageKey (id, key_id, key_type_id, provider_id) (select sequence_nextval('rhn_pkey_id_seq'), 'bc4d06a08d8b756f', lookup_package_key_type('gpg'), lookup_package_provider('Oracle Inc.') from dual where not exists (select 1 from rhnPackageKey where key_id = 'bc4d06a08d8b756f'));

insert into rhnPackageKey (id, key_id, key_type_id, provider_id) (select sequence_nextval('rhn_pkey_id_seq'), 'a7dd07088b4efbe6', lookup_package_key_type('gpg'), lookup_package_provider('Oracle Inc.') from dual where not exists (select 1 from rhnPackageKey where key_id = 'a7dd07088b4efbe6'));

insert into rhnPackageKey (id, key_id, key_type_id, provider_id) (select sequence_nextval('rhn_pkey_id_seq'), '8efe1bc4d4ade9c3', lookup_package_key_type('gpg'), lookup_package_provider('SUSE LLC') from dual where not exists (select 1 from rhnPackageKey where key_id = '8efe1bc4d4ade9c3'));

insert into rhnPackageKey (id, key_id, key_type_id, provider_id) (select sequence_nextval('rhn_pkey_id_seq'), '97a636db0bad8ecc', lookup_package_key_type('gpg'), lookup_package_provider('SUSE LLC') from dual where not exists (select 1 from rhnPackageKey where key_id = '97a636db0bad8ecc'));

insert into rhnPackageKey (id, key_id, key_type_id, provider_id) (select sequence_nextval('rhn_pkey_id_seq'), 'f74f09bc3fa1d6ce', lookup_package_key_type('gpg'), lookup_package_provider('SUSE LLC') from dual where not exists (select 1 from rhnPackageKey where key_id = 'f74f09bc3fa1d6ce'));

insert into rhnPackageKey (id, key_id, key_type_id, provider_id) (select sequence_nextval('rhn_pkey_id_seq'), 'a1bfc02bd588dc46', lookup_package_key_type('gpg'), lookup_package_provider('SUSE LLC') from dual where not exists (select 1 from rhnPackageKey where key_id = 'a1bfc02bd588dc46'));

insert into rhnPackageKey (id, key_id, key_type_id, provider_id) (select sequence_nextval('rhn_pkey_id_seq'), '46dfa05c6f5da62b', lookup_package_key_type('gpg'), lookup_package_provider('SUSE LLC') from dual where not exists (select 1 from rhnPackageKey where key_id = '46dfa05c6f5da62b'));

insert into rhnPackageKey (id, key_id, key_type_id, provider_id) (select sequence_nextval('rhn_pkey_id_seq'), '09461c70af5425f7', lookup_package_key_type('gpg'), lookup_package_provider('SUSE LLC') from dual where not exists (select 1 from rhnPackageKey where key_id = '09461c70af5425f7'));

insert into rhnPackageKey (id, key_id, key_type_id, provider_id) (select sequence_nextval('rhn_pkey_id_seq'), '9c214d4065176565', lookup_package_key_type('gpg'), lookup_package_provider('openSUSE') from dual where not exists (select 1 from rhnPackageKey where key_id = '9c214d4065176565'));

insert into rhnPackageKey (id, key_id, key_type_id, provider_id) (select sequence_nextval('rhn_pkey_id_seq'), '3c90731ed78c6b69', lookup_package_key_type('gpg'), lookup_package_provider('openSUSE') from dual where not exists (select 1 from rhnPackageKey where key_id = '3c90731ed78c6b69'));

insert into rhnPackageKey (id, key_id, key_type_id, provider_id) (select sequence_nextval('rhn_pkey_id_seq'), '35a2f86e29b700a4', lookup_package_key_type('gpg'), lookup_package_provider('openSUSE') from dual where not exists (select 1 from rhnPackageKey where key_id = '35a2f86e29b700a4'));

insert into rhnPackageKey (id, key_id, key_type_id, provider_id) (select sequence_nextval('rhn_pkey_id_seq'), '8a49eb0325db7ae0', lookup_package_key_type('gpg'), lookup_package_provider('openSUSE') from dual where not exists (select 1 from rhnPackageKey where key_id = '8a49eb0325db7ae0'));

insert into rhnPackageKey (id, key_id, key_type_id, provider_id) (select sequence_nextval('rhn_pkey_id_seq'), '177086fab0f9c64f', lookup_package_key_type('gpg'), lookup_package_provider('SUSE LLC') from dual where not exists (select 1 from rhnPackageKey where key_id = '177086fab0f9c64f'));

insert into rhnPackageKey (id, key_id, key_type_id, provider_id) (select sequence_nextval('rhn_pkey_id_seq'), '2ae81e8aced7258b', lookup_package_key_type('gpg'), lookup_package_provider('AlmaLinux') from dual where not exists (select 1 from rhnPackageKey where key_id = '2ae81e8aced7258b'));

insert into rhnPackageKey (id, key_id, key_type_id, provider_id) (select sequence_nextval('rhn_pkey_id_seq'), 'd36cb86cb86b3716', lookup_package_key_type('gpg'), lookup_package_provider('AlmaLinux') from dual where not exists (select 1 from rhnPackageKey where key_id = 'd36cb86cb86b3716'));

07070100000F2D000081B400000000000000000000000167AE1114000000BB000000000000000000000000000000000000007000000000susemanager-schema/upgrade/susemanager-schema-4.3.25-to-susemanager-schema-4.3.26/200-enable-pillar-refresh.sql   INSERT INTO rhnTaskQueue (id, org_id, task_name, task_data)
SELECT nextval('rhn_task_queue_id_seq'), id, 'upgrade_satellite_all_systems_pillar_refresh', 0
FROM web_customer
WHERE id = 1;
 07070100000F2E000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005200000000susemanager-schema/upgrade/susemanager-schema-4.3.26-to-susemanager-schema-4.3.27 07070100000F2F000081B400000000000000000000000167AE1114000003FA000000000000000000000000000000000000008500000000susemanager-schema/upgrade/susemanager-schema-4.3.26-to-susemanager-schema-4.3.27/100-replace-susePackageExcludingPartOfPtf-view.sql  ALTER TABLE rhnPackage
    ADD COLUMN IF NOT EXISTS is_ptf
        BOOLEAN DEFAULT (FALSE),
    ADD COLUMN IF NOT EXISTS is_part_of_ptf
        BOOLEAN DEFAULT (FALSE);

CREATE INDEX IF NOT EXISTS rhn_package_is_ptf_idx ON rhnPackage (is_ptf);
CREATE INDEX IF NOT EXISTS rhn_package_is_part_of_ptf_idx ON rhnPackage (is_part_of_ptf);

UPDATE rhnPackage SET is_ptf = TRUE WHERE id IN (
    SELECT DISTINCT pk.id
    FROM rhnpackage pk
        INNER JOIN rhnpackageprovides pp ON pk.id = pp.package_id
        INNER JOIN rhnpackagecapability pc ON pp.capability_id = pc.id
    WHERE pc.name = 'ptf()');

UPDATE rhnPackage SET is_part_of_ptf = TRUE WHERE id IN (
    SELECT DISTINCT pk.id
    FROM rhnpackage pk
        INNER JOIN rhnpackageprovides pp ON pk.id = pp.package_id
        INNER JOIN rhnpackagecapability pc ON pp.capability_id = pc.id
    WHERE pc.name = 'ptf-package()');

CREATE OR REPLACE VIEW susePackageExcludingPartOfPtf AS
  SELECT pkg.*
    FROM rhnpackage pkg
   WHERE pkg.is_part_of_ptf = FALSE
;
  07070100000F30000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005200000000susemanager-schema/upgrade/susemanager-schema-4.3.27-to-susemanager-schema-4.3.28 07070100000F31000081B400000000000000000000000167AE111400000204000000000000000000000000000000000000007E00000000susemanager-schema/upgrade/susemanager-schema-4.3.27-to-susemanager-schema-4.3.28/000-convert-reportdb-users-to-lowercase.sql --
-- Copyright (c) 2024 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
UPDATE susecredentials
   SET username = LOWER(username)
 WHERE type = 'reportcreds';
07070100000F32000081B400000000000000000000000167AE111400000C27000000000000000000000000000000000000009300000000susemanager-schema/upgrade/susemanager-schema-4.3.27-to-susemanager-schema-4.3.28/100-rename-suseProductSCCRepository-into-suseChannelTemplate.sql    --
-- Copyright (c) 2024 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--

CREATE TABLE IF NOT EXISTS
suseChannelTemplate
(
    id                     BIGINT CONSTRAINT suse_chantpl_id_pk PRIMARY KEY
                                  GENERATED ALWAYS AS IDENTITY,
    product_id             NUMERIC NOT NULL
                                  CONSTRAINT suse_chantpl_pid_fk
                                  REFERENCES suseProducts (id)
                                  ON DELETE CASCADE,
    root_product_id        NUMERIC NOT NULL
                                  CONSTRAINT suse_chantpl_rpid_fk
                                  REFERENCES suseProducts (id)
                                  ON DELETE CASCADE,
    repo_id                NUMERIC NOT NULL
                                  CONSTRAINT suse_chantpl_rid_fk
                                  REFERENCES suseSCCRepository (id)
                                  ON DELETE CASCADE,
    channel_label          VARCHAR(128) NOT NULL,
    parent_channel_label   VARCHAR(128),
    channel_name           VARCHAR(256) NOT NULL,
    mandatory              BOOLEAN DEFAULT FALSE NOT NULL,
    update_tag             VARCHAR(128),
    gpg_key_url            VARCHAR(256),
    gpg_key_id             VARCHAR(14),
    gpg_key_fp             VARCHAR(50),
    created                TIMESTAMPTZ
                           DEFAULT (current_timestamp) NOT NULL,
    modified               TIMESTAMPTZ
                           DEFAULT (current_timestamp) NOT NULL
);

CREATE UNIQUE INDEX IF NOT EXISTS suse_chantpl_pid_rpid_rid_uq
ON suseChannelTemplate (product_id, root_product_id, repo_id);

CREATE INDEX IF NOT EXISTS suse_chantpl_rpid_idx
ON suseChannelTemplate (root_product_id);

CREATE INDEX IF NOT EXISTS suse_chantpl_chl_idx
ON suseChannelTemplate (channel_label);

DO $$
  BEGIN
    IF EXISTS (SELECT 1 FROM information_schema.tables WHERE table_name = 'suseproductsccrepository') THEN

      INSERT INTO suseChannelTemplate (product_id, root_product_id, repo_id, channel_label, parent_channel_label, channel_name,
                                      mandatory, update_tag, gpg_key_url, gpg_key_id, gpg_key_fp)
        SELECT product_id, root_product_id, repo_id, channel_label, parent_channel_label, channel_name,
               CASE mandatory WHEN 'Y' THEN true ELSE false END AS mandatory, update_tag, gpg_key_url, gpg_key_id, gpg_key_fp
          FROM suseProductSCCRepository
      ORDER BY id;

    ELSE
       RAISE NOTICE 'suseProductSCCRepository does not exists';
    END IF;
  END;
$$;

DROP INDEX IF EXISTS suse_prdrepo_pid_rpid_rid_uq;
DROP INDEX IF EXISTS suse_prdrepo_chl_idx;
DROP SEQUENCE IF EXISTS suse_prdrepo_id_seq;
DROP TABLE IF EXISTS suseProductSCCRepository CASCADE;
 07070100000F33000081B400000000000000000000000167AE1114000002D2000000000000000000000000000000000000007D00000000susemanager-schema/upgrade/susemanager-schema-4.3.27-to-susemanager-schema-4.3.28/200-create-table-suseServerSAPWorkload.sql  --
-- Copyright (c) 2025 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--

CREATE TABLE IF NOT EXISTS suseServerSAPWorkload (
    id BIGINT CONSTRAINT suse_sap_workload_id_pk PRIMARY KEY GENERATED ALWAYS AS IDENTITY,
    sap_system_id VARCHAR NOT NULL,
    instance_type VARCHAR NOT NULL,
    server_id NUMERIC NOT NULL REFERENCES rhnServer(id) ON DELETE CASCADE
);
  07070100000F34000081B400000000000000000000000167AE11140000024A000000000000000000000000000000000000007800000000susemanager-schema/upgrade/susemanager-schema-4.3.27-to-susemanager-schema-4.3.28/201-add-columns-to-suseMinionInfo.sql   --
-- Copyright (c) 2025 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--

ALTER TABLE suseMinionInfo ADD COLUMN IF NOT EXISTS
    container_runtime VARCHAR;

ALTER TABLE suseMinionInfo ADD COLUMN IF NOT EXISTS
    uname VARCHAR;
  07070100000F35000081B400000000000000000000000167AE1114000003D2000000000000000000000000000000000000007800000000susemanager-schema/upgrade/susemanager-schema-4.3.27-to-susemanager-schema-4.3.28/202-update-trigger-suseMinionInfo.sql   --
-- Copyright (c) 2025 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--

create or replace function suse_minion_info_up_trig_fun() returns trigger as
$$
begin
        update suseSCCRegCache
           set scc_reg_required = 'Y'
         where server_id = new.server_id;
	return new;
end;
$$ language plpgsql;

drop trigger if exists suse_minion_info_up_trig on suseMinionInfo;

create trigger
suse_minion_info_up_trig
after update on suseMinionInfo
for each row
when (OLD.container_runtime is distinct from NEW.container_runtime OR OLD.uname is distinct from NEW.uname)
execute procedure suse_minion_info_up_trig_fun();
  07070100000F36000081B400000000000000000000000167AE11140000048B000000000000000000000000000000000000007F00000000susemanager-schema/upgrade/susemanager-schema-4.3.27-to-susemanager-schema-4.3.28/203-create-trigger-suseServerSAPWorkload.sql    --
-- Copyright (c) 2025 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--

create or replace function suse_server_sap_workload_up_trig_fun() returns trigger as
$$
begin
        if (TG_OP = 'DELETE') then
            update suseSCCRegCache
            set scc_reg_required = 'Y'
            where server_id = old.server_id;
            return null;
        else
            update suseSCCRegCache
            set scc_reg_required = 'Y'
            where server_id = new.server_id;
            return new;
        end if;
end;
$$ language plpgsql;

drop trigger if exists suse_server_sap_workload_up_trig on suseServerSAPWorkload;

create trigger
suse_server_sap_workload_up_trig
after insert or update or delete on suseServerSAPWorkload
for each row
execute procedure suse_server_sap_workload_up_trig_fun();
 07070100000F37000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005000000000susemanager-schema/upgrade/susemanager-schema-4.3.3-to-susemanager-schema-4.3.4   07070100000F38000081B400000000000000000000000167AE111400000B42000000000000000000000000000000000000006400000000susemanager-schema/upgrade/susemanager-schema-4.3.3-to-susemanager-schema-4.3.4/001-centos8-eol.sql   --- After CentOS8 EoL, we need to use the EL8 client tools for all EL8 clones
CREATE OR REPLACE PROCEDURE public.el8_ctools_for_all (v_source_url_el8 VARCHAR, v_source_url_centos8 VARCHAR, v_repo_label_regex VARCHAR, v_channel_label_regex VARCHAR)
AS $$
BEGIN
    -- If we have CentOS8 or EL8 client tools channels, we may need to create the EL8 repository
    IF EXISTS (SELECT id FROM rhnchannel WHERE label ~ v_channel_label_regex) THEN
        -- If the EL8 repo does not exist, create one, using the existing CentOS repo as template
        -- as it will be the one in use
        RAISE NOTICE USING MESSAGE = 'There are EL/CentOS client tools channels';
        IF NOT EXISTS (SELECT id FROM rhnContentSource WHERE source_url=v_source_url_el8) THEN
            RAISE NOTICE USING MESSAGE = 'EL8 client tools repo does not exist, creating it';
            INSERT INTO rhnContentSource (
               id,
               org_id,
               type_id,
               source_url,
               label,
               metadata_signed)
            VALUES (
               nextval('rhn_chan_content_src_id_seq'),
               (SELECT org_id FROM rhnContentSource WHERE source_url=v_source_url_centos8),
               500,
               v_source_url_el8,
               REPLACE((SELECT label FROM rhnContentSource WHERE source_url=v_source_url_centos8), 'CentOS', 'AlmaLinux'),
               'N');
        END IF;
        -- Make sure CentOS8 and EL8 client tools channels are all using the EL8 repository
        RAISE NOTICE USING MESSAGE = 'Adjusting client tools channels to use EL client tools repo';
        UPDATE rhnChannelContentSource SET source_id=(SELECT id FROM rhnContentSource WHERE source_url=v_source_url_el8)
        WHERE source_id IN (SELECT id FROM rhnContentSource WHERE rhnContentSource.label ~ v_repo_label_regex);
    END IF;
    COMMIT;
END;
$$
LANGUAGE plpgsql;

-- Stable
CALL public.el8_ctools_for_all(
  'https://download.opensuse.org/repositories/systemsmanagement:/Uyuni:/Stable:/EL8-Uyuni-Client-Tools/EL_8/',
  'https://download.opensuse.org/repositories/systemsmanagement:/Uyuni:/Stable:/CentOS8-Uyuni-Client-Tools/CentOS_8/',
  E'^External - Uyuni Client Tools for (AlmaLinux|CentOS|Rocky Linux|Oracle Linux) 8 \\([A-Za-z0-9_]+\\)$',
  '^(almalinux|centos|rockylinux|oraclelinux)8-uyuni-client-[A-Za-z0-9_]+$'
);

-- Master
CALL public.el8_ctools_for_all(
  'https://download.opensuse.org/repositories/systemsmanagement:/Uyuni:/Master:/EL8-Uyuni-Client-Tools/EL_8/',
  'https://download.opensuse.org/repositories/systemsmanagement:/Uyuni:/Master:/CentOS8-Uyuni-Client-Tools/CentOS_8/',
  E'^External - Uyuni Client Tools for (AlmaLinux|CentOS|Rocky Linux|Oracle Linux) 8 \\([A-Za-z0-9_]+\\) \\(Development\\)$',
  '^(almalinux|centos|rockylinux|oraclelinux)8-uyuni-client-devel-[A-Za-z0-9_]+$'
);

DROP PROCEDURE public.el8_ctools_for_all;
  07070100000F39000081B400000000000000000000000167AE111400001258000000000000000000000000000000000000006D00000000susemanager-schema/upgrade/susemanager-schema-4.3.3-to-susemanager-schema-4.3.4/002-use_almalinux_mirror.sql  UPDATE rhnContentSource SET source_url = 'https://mirrors.almalinux.org/mirrorlist/8/baseos'
  WHERE id = (SELECT id FROM rhnContentSource WHERE label LIKE 'External - AlmaLinux 8 (%)' LIMIT 1) AND
  NOT EXISTS (SELECT id FROM rhnContentSource WHERE source_url='https://mirrors.almalinux.org/mirrorlist/8/baseos');

UPDATE rhnChannelContentSource SET source_id=(SELECT id FROM rhnContentSource
  WHERE source_url='https://mirrors.almalinux.org/mirrorlist/8/baseos')
  WHERE source_id IN (SELECT id FROM rhnContentSource WHERE rhnContentSource.label LIKE 'External - AlmaLinux 8 (%)');

DELETE FROM rhnContentSource WHERE label LIKE 'External - AlmaLinux 8 (%)' AND NOT source_url='https://mirrors.almalinux.org/mirrorlist/8/baseos';

UPDATE rhnContentSource SET label = 'External - AlmaLinux 8'
  WHERE id = (SELECT id FROM rhnContentSource WHERE label LIKE 'External - AlmaLinux 8 (%)');


UPDATE rhnContentSource SET source_url = 'https://mirrors.almalinux.org/mirrorlist/8/appstream'
  WHERE id = (SELECT id FROM rhnContentSource WHERE label LIKE 'External - AlmaLinux 8 AppStream (%)' LIMIT 1) AND
  NOT EXISTS (SELECT id FROM rhnContentSource WHERE source_url='https://mirrors.almalinux.org/mirrorlist/8/appstream');

UPDATE rhnChannelContentSource SET source_id=(SELECT id FROM rhnContentSource
  WHERE source_url='https://mirrors.almalinux.org/mirrorlist/8/appstream')
  WHERE source_id IN (SELECT id FROM rhnContentSource WHERE rhnContentSource.label LIKE 'External - AlmaLinux 8 AppStream (%)');

DELETE FROM rhnContentSource WHERE label LIKE 'External - AlmaLinux 8 AppStream (%)' AND NOT source_url='https://mirrors.almalinux.org/mirrorlist/8/appstream';

UPDATE rhnContentSource SET label = 'External - AlmaLinux 8 AppStream'
  WHERE id = (SELECT id FROM rhnContentSource WHERE label LIKE 'External - AlmaLinux 8 AppStream (%)');


UPDATE rhnContentSource SET source_url = 'https://mirrors.almalinux.org/mirrorlist/8/extras'
  WHERE id = (SELECT id FROM rhnContentSource WHERE label LIKE 'External - AlmaLinux 8 Extras (%)' LIMIT 1) AND
  NOT EXISTS (SELECT id FROM rhnContentSource WHERE source_url='https://mirrors.almalinux.org/mirrorlist/8/extras');

UPDATE rhnChannelContentSource SET source_id=(SELECT id FROM rhnContentSource
  WHERE source_url='https://mirrors.almalinux.org/mirrorlist/8/extras')
  WHERE source_id IN (SELECT id FROM rhnContentSource WHERE rhnContentSource.label LIKE 'External - AlmaLinux 8 Extras (%)');

DELETE FROM rhnContentSource WHERE label LIKE 'External - AlmaLinux 8 Extras (%)' AND NOT source_url='https://mirrors.almalinux.org/mirrorlist/8/extras';

UPDATE rhnContentSource SET label = 'External - AlmaLinux 8 Extras'
  WHERE id = (SELECT id FROM rhnContentSource WHERE label LIKE 'External - AlmaLinux 8 Extras (%)');


UPDATE rhnContentSource SET source_url = 'https://mirrors.almalinux.org/mirrorlist/8/ha'
  WHERE id = (SELECT id FROM rhnContentSource WHERE label LIKE 'External - AlmaLinux 8 High Availability (%)' LIMIT 1) AND
  NOT EXISTS (SELECT id FROM rhnContentSource WHERE source_url='https://mirrors.almalinux.org/mirrorlist/8/ha');

UPDATE rhnChannelContentSource SET source_id=(SELECT id FROM rhnContentSource
  WHERE source_url='https://mirrors.almalinux.org/mirrorlist/8/ha')
  WHERE source_id IN (SELECT id FROM rhnContentSource WHERE rhnContentSource.label LIKE 'External - AlmaLinux 8 High Availability (%)');

DELETE FROM rhnContentSource WHERE label LIKE 'External - AlmaLinux 8 High Availability (%)' AND NOT source_url='https://mirrors.almalinux.org/mirrorlist/8/ha';

UPDATE rhnContentSource SET label = 'External - AlmaLinux 8 High Availability'
  WHERE id = (SELECT id FROM rhnContentSource WHERE label LIKE 'External - AlmaLinux 8 High Availability (%)');


UPDATE rhnContentSource SET source_url = 'https://mirrors.almalinux.org/mirrorlist/8/powertools'
  WHERE id = (SELECT id FROM rhnContentSource WHERE label LIKE 'External - AlmaLinux 8 PowerTools (%)' LIMIT 1) AND
  NOT EXISTS (SELECT id FROM rhnContentSource WHERE source_url='https://mirrors.almalinux.org/mirrorlist/8/powertools');

UPDATE rhnChannelContentSource SET source_id=(SELECT id FROM rhnContentSource
  WHERE source_url='https://mirrors.almalinux.org/mirrorlist/8/powertools')
  WHERE source_id IN (SELECT id FROM rhnContentSource WHERE rhnContentSource.label LIKE 'External - AlmaLinux 8 PowerTools (%)');

DELETE FROM rhnContentSource WHERE label LIKE 'External - AlmaLinux 8 PowerTools (%)' AND NOT source_url='https://mirrors.almalinux.org/mirrorlist/8/powertools';

UPDATE rhnContentSource SET label = 'External - AlmaLinux 8 PowerTools'
  WHERE id = (SELECT id FROM rhnContentSource WHERE label LIKE 'External - AlmaLinux 8 PowerTools (%)');

07070100000F3A000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005000000000susemanager-schema/upgrade/susemanager-schema-4.3.4-to-susemanager-schema-4.3.5   07070100000F3B000081B400000000000000000000000167AE11140000004F000000000000000000000000000000000000006C00000000susemanager-schema/upgrade/susemanager-schema-4.3.4-to-susemanager-schema-4.3.5/001-add-ssh-port-minion.sql   ALTER TABLE suseMinionInfo ADD COLUMN IF NOT EXISTS
    ssh_push_port NUMERIC;
 07070100000F3C000081B400000000000000000000000167AE111400000028000000000000000000000000000000000000007300000000susemanager-schema/upgrade/susemanager-schema-4.3.4-to-susemanager-schema-4.3.5/002-remove-minion_pillars_func.sql    DROP FUNCTION IF EXISTS minion_pillars;
07070100000F3D000081B400000000000000000000000167AE11140000008E000000000000000000000000000000000000006700000000susemanager-schema/upgrade/susemanager-schema-4.3.4-to-susemanager-schema-4.3.5/003-pillar-upgrade.sql    INSERT INTO rhnTaskQueue (org_id, task_name, task_data)
SELECT id, 'upgrade_satellite_pillars_from_files', 0
FROM web_customer
WHERE id = 1;

  07070100000F3E000081B400000000000000000000000167AE11140000004C000000000000000000000000000000000000006500000000susemanager-schema/upgrade/susemanager-schema-4.3.4-to-susemanager-schema-4.3.5/010-apply-states.sql  ALTER TABLE rhnActionApplyStates ADD COLUMN IF NOT EXISTS
    pillars TEXT;
07070100000F3F000081B400000000000000000000000167AE1114000000FE000000000000000000000000000000000000006800000000susemanager-schema/upgrade/susemanager-schema-4.3.4-to-susemanager-schema-4.3.5/020-server-path-idx.sql   
DROP INDEX IF EXISTS rhn_serverpath_sid_pos_uq;

ALTER TABLE rhnServerPath DROP CONSTRAINT IF EXISTS rhn_serverpath_sid_pos;
ALTER TABLE rhnServerPath ADD CONSTRAINT rhn_serverpath_sid_pos UNIQUE
    (server_id, position) DEFERRABLE INITIALLY DEFERRED;
  07070100000F40000081B400000000000000000000000167AE1114000002B1000000000000000000000000000000000000006D00000000susemanager-schema/upgrade/susemanager-schema-4.3.4-to-susemanager-schema-4.3.5/030-add-rights-to-errata.sql  --
-- Copyright (c) 2021 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

ALTER TABLE rhnErrata ADD COLUMN IF NOT EXISTS
    rights VARCHAR(100);
   07070100000F41000081B400000000000000000000000167AE111400000744000000000000000000000000000000000000008300000000susemanager-schema/upgrade/susemanager-schema-4.3.4-to-susemanager-schema-4.3.5/030-rhnChannelNewestPackageView-fix-duplicates.sql    create or replace view
rhnChannelNewestPackageView
as
SELECT channel_id,
       name_id,
       evr_id,
       package_arch_id,
       package_id
FROM (
      SELECT channel_id,
             name_id,
             evr_id,
             package_arch_id,
             build_time,
             max(package_id) as package_id,
             ROW_NUMBER() OVER(PARTITION BY name_id, channel_id, package_arch_id ORDER BY build_time DESC) rn
      FROM (
            SELECT m.channel_id          as channel_id,
                   p.name_id             as name_id,
                   p.evr_id              as evr_id,
                   m.package_arch_id     as package_arch_id,
                   p.id                  as package_id,
                   p.build_time          as build_time
            FROM (select max(pe.evr) AS max_evr,
                         cp.channel_id,
                         p.name_id,
                         p.package_arch_id
                    from rhnPackageEVR                           pe,
                         rhnPackage                              p,
                         suseChannelPackageRetractedStatusView   cp
                   where p.evr_id = pe.id
                     and cp.package_id = p.id
                     and NOT cp.is_retracted
                   group by cp.channel_id, p.name_id, p.package_arch_id) m,
                 rhnPackageEVR       pe,
                 rhnPackage          p,
                 rhnChannelPackage   chp
            WHERE m.max_evr = pe.evr
                AND m.name_id = p.name_id
                AND m.package_arch_id = p.package_arch_id
                AND p.evr_id = pe.id
                AND chp.package_id = p.id
                AND chp.channel_id = m.channel_id
      ) latest_packages
      group by channel_id, name_id, evr_id, package_arch_id, build_time
) n
WHERE rn = 1;
07070100000F42000081B400000000000000000000000167AE11140000036A000000000000000000000000000000000000007E00000000susemanager-schema/upgrade/susemanager-schema-4.3.4-to-susemanager-schema-4.3.5/100-change-rhnPackageCapability-name-type.sql DO $$
    BEGIN
        IF (SELECT data_type FROM information_schema.columns WHERE table_name = 'rhnpackagecapability' AND column_name = 'name') != 'text' THEN
            DROP INDEX IF EXISTS rhn_pkg_cap_name_version_uq;
            DROP INDEX IF EXISTS rhn_pkg_cap_name_uq;

            ALTER TABLE rhnPackageCapability ALTER COLUMN name TYPE text;

            CREATE UNIQUE INDEX rhn_pkg_cap_name_version_uq
                ON rhnPackageCapability USING btree (sha512(replace(name, E'\\', E'\\\\')::bytea), version)
             WHERE version IS NOT NULL;

            CREATE UNIQUE INDEX rhn_pkg_cap_name_uq
                ON rhnPackageCapability USING btree (sha512(replace(name, E'\\', E'\\\\')::bytea))
             WHERE version IS NULL;
        ELSE
          RAISE NOTICE 'rhnPackageCapability column name is already of type text.';
        END IF;
    END;
$$;
  07070100000F43000081B400000000000000000000000167AE11140000013C000000000000000000000000000000000000007900000000susemanager-schema/upgrade/susemanager-schema-4.3.4-to-susemanager-schema-4.3.5/200-regenerate-Release-for-deb-repos.sql  INSERT INTO rhnRepoRegenQueue (id, channel_label, reason, force)
(SELECT sequence_nextval('rhn_repo_regen_queue_id_seq'),
        C.label,
        'Regenerate Release as flat',
        'Y'
 FROM rhnChannel AS C
     LEFT JOIN rhnChannelArch AS CA ON
         (CA.id=C.channel_arch_id)
 WHERE CA.label LIKE '%-deb');
07070100000F44000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005000000000susemanager-schema/upgrade/susemanager-schema-4.3.5-to-susemanager-schema-4.3.6   07070100000F45000081B400000000000000000000000167AE111400000000000000000000000000000000000000000000005900000000susemanager-schema/upgrade/susemanager-schema-4.3.5-to-susemanager-schema-4.3.6/.gitkeep  07070100000F46000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005000000000susemanager-schema/upgrade/susemanager-schema-4.3.6-to-susemanager-schema-4.3.7   07070100000F47000081B400000000000000000000000167AE111400000B42000000000000000000000000000000000000006400000000susemanager-schema/upgrade/susemanager-schema-4.3.6-to-susemanager-schema-4.3.7/001-centos8-eol.sql   --- After CentOS8 EoL, we need to use the EL8 client tools for all EL8 clones
CREATE OR REPLACE PROCEDURE public.el8_ctools_for_all (v_source_url_el8 VARCHAR, v_source_url_centos8 VARCHAR, v_repo_label_regex VARCHAR, v_channel_label_regex VARCHAR)
AS $$
BEGIN
    -- If we have CentOS8 or EL8 client tools channels, we may need to create the EL8 repository
    IF EXISTS (SELECT id FROM rhnchannel WHERE label ~ v_channel_label_regex) THEN
        -- If the EL8 repo does not exist, create one, using the existing CentOS repo as template
        -- as it will be the one in use
        RAISE NOTICE USING MESSAGE = 'There are EL/CentOS client tools channels';
        IF NOT EXISTS (SELECT id FROM rhnContentSource WHERE source_url=v_source_url_el8) THEN
            RAISE NOTICE USING MESSAGE = 'EL8 client tools repo does not exist, creating it';
            INSERT INTO rhnContentSource (
               id,
               org_id,
               type_id,
               source_url,
               label,
               metadata_signed)
            VALUES (
               nextval('rhn_chan_content_src_id_seq'),
               (SELECT org_id FROM rhnContentSource WHERE source_url=v_source_url_centos8),
               500,
               v_source_url_el8,
               REPLACE((SELECT label FROM rhnContentSource WHERE source_url=v_source_url_centos8), 'CentOS', 'AlmaLinux'),
               'N');
        END IF;
        -- Make sure CentOS8 and EL8 client tools channels are all using the EL8 repository
        RAISE NOTICE USING MESSAGE = 'Adjusting client tools channels to use EL client tools repo';
        UPDATE rhnChannelContentSource SET source_id=(SELECT id FROM rhnContentSource WHERE source_url=v_source_url_el8)
        WHERE source_id IN (SELECT id FROM rhnContentSource WHERE rhnContentSource.label ~ v_repo_label_regex);
    END IF;
    COMMIT;
END;
$$
LANGUAGE plpgsql;

-- Stable
CALL public.el8_ctools_for_all(
  'https://download.opensuse.org/repositories/systemsmanagement:/Uyuni:/Stable:/EL8-Uyuni-Client-Tools/EL_8/',
  'https://download.opensuse.org/repositories/systemsmanagement:/Uyuni:/Stable:/CentOS8-Uyuni-Client-Tools/CentOS_8/',
  E'^External - Uyuni Client Tools for (AlmaLinux|CentOS|Rocky Linux|Oracle Linux) 8 \\([A-Za-z0-9_]+\\)$',
  '^(almalinux|centos|rockylinux|oraclelinux)8-uyuni-client-[A-Za-z0-9_]+$'
);

-- Master
CALL public.el8_ctools_for_all(
  'https://download.opensuse.org/repositories/systemsmanagement:/Uyuni:/Master:/EL8-Uyuni-Client-Tools/EL_8/',
  'https://download.opensuse.org/repositories/systemsmanagement:/Uyuni:/Master:/CentOS8-Uyuni-Client-Tools/CentOS_8/',
  E'^External - Uyuni Client Tools for (AlmaLinux|CentOS|Rocky Linux|Oracle Linux) 8 \\([A-Za-z0-9_]+\\) \\(Development\\)$',
  '^(almalinux|centos|rockylinux|oraclelinux)8-uyuni-client-devel-[A-Za-z0-9_]+$'
);

DROP PROCEDURE public.el8_ctools_for_all;
  07070100000F48000081B400000000000000000000000167AE1114000001F6000000000000000000000000000000000000007700000000susemanager-schema/upgrade/susemanager-schema-4.3.6-to-susemanager-schema-4.3.7/002-rhnActionImage-delete-set-null.sql    ALTER TABLE public.rhnactionimagebuild DROP CONSTRAINT rhn_act_image_build_ip_fk;
ALTER TABLE public.rhnactionimagebuild ADD CONSTRAINT rhn_act_image_build_ip_fk FOREIGN KEY (image_profile_id) REFERENCES suseimageprofile(profile_id) ON DELETE SET NULL;
ALTER TABLE public.rhnactionimageinspect DROP CONSTRAINT rhn_act_image_inspect_is_fk;
ALTER TABLE public.rhnactionimageinspect ADD CONSTRAINT rhn_act_image_inspect_is_fk FOREIGN KEY (image_store_id) REFERENCES suseImageStore(id) ON DELETE SET NULL;
  07070100000F49000081B400000000000000000000000167AE1114000003EF000000000000000000000000000000000000007400000000susemanager-schema/upgrade/susemanager-schema-4.3.6-to-susemanager-schema-4.3.7/050-add-additional-packagearchs.sql   insert into rhnChannelArch (id, label, name, arch_type_id) select
  sequence_nextval('rhn_channel_arch_id_seq'), 'armel-deb', 'armel-deb', lookup_arch_type('deb') from dual
where not exists (select 1 from rhnChannelArch where label = 'armel-deb');

insert into rhnChannelArch (id, label, name, arch_type_id) select
  sequence_nextval('rhn_channel_arch_id_seq'), 'riscv64-deb', 'riscv64-deb', lookup_arch_type('deb') from dual
where not exists (select 1 from rhnChannelArch where label = 'riscv64-deb');

insert into rhnChannelArch (id, label, name, arch_type_id) select
  sequence_nextval('rhn_channel_arch_id_seq'), 'ppc64el-deb', 'ppc64el-deb', lookup_arch_type('deb') from dual
where not exists (select 1 from rhnChannelArch where label = 'ppc64el-deb');

insert into rhnChannelArch (id, label, name, arch_type_id) select
  sequence_nextval('rhn_channel_arch_id_seq'), 's390x-deb', 's390x-deb', lookup_arch_type('deb') from dual
where not exists (select 1 from rhnChannelArch where label = 's390x-deb');
 07070100000F4A000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005000000000susemanager-schema/upgrade/susemanager-schema-4.3.7-to-susemanager-schema-4.3.8   07070100000F4B000081B400000000000000000000000167AE111400000297000000000000000000000000000000000000007C00000000susemanager-schema/upgrade/susemanager-schema-4.3.7-to-susemanager-schema-4.3.8/001-add-suseMinionInfo-created-modified.sql   ALTER TABLE suseMinionInfo ADD COLUMN IF NOT EXISTS
    created   TIMESTAMPTZ
                  DEFAULT (current_timestamp) NOT NULL;

ALTER TABLE suseMinionInfo ADD COLUMN IF NOT EXISTS
    modified  TIMESTAMPTZ
                  DEFAULT (current_timestamp) NOT NULL;

CREATE OR REPLACE function suse_minion_info_mod_trig_fun() RETURNS TRIGGER AS
$$
BEGIN
        new.modified := current_timestamp;
        RETURN new;
END;
$$ language plpgsql;

DROP TRIGGER IF EXISTS suse_minion_info_mod_trig ON suseMinionInfo;

CREATE TRIGGER
suse_minion_info_mod_trig
BEFORE INSERT OR UPDATE ON suseMinionInfo
FOR EACH ROW
EXECUTE PROCEDURE suse_minion_info_mod_trig_fun();
 07070100000F4C000081B400000000000000000000000167AE1114000002B9000000000000000000000000000000000000006B00000000susemanager-schema/upgrade/susemanager-schema-4.3.7-to-susemanager-schema-4.3.8/002-fix-china-timezone.sql    -- Copyright (c) 2022 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--

UPDATE rhnTimezone SET olson_name='Asia/Shanghai' WHERE olson_name='Asia/Beijing';
   07070100000F4D000081B400000000000000000000000167AE111400001968000000000000000000000000000000000000006E00000000susemanager-schema/upgrade/susemanager-schema-4.3.7-to-susemanager-schema-4.3.8/300-payg-database-changes.sql --
-- Copyright (c) 2021 SUSE LLC
--
--  This software is licensed to you under the GNU General Public License,
--  version 2 (GPLv2). There is NO WARRANTY for this software, express or
--  implied, including the implied warranties of MERCHANTABILITY or FITNESS
--  FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
--  along with this software; if not, see
--  http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
--  Red Hat trademarks are not licensed under GPLv2. No permission is
--  granted to use or replicate Red Hat trademarks that are incorporated
--  in this software or its documentation.
--

---------------------------------
-- payg ssh connection data table
---------------------------------
CREATE TABLE IF NOT EXISTS susePaygSshData
(
    id                   NUMERIC                                 NOT NULL
        CONSTRAINT susePaygSshData_pk PRIMARY KEY,
    description          VARCHAR(255),
    host                 VARCHAR(255)                            NOT NULL,
    port                 NUMERIC,
    username             VARCHAR(32)                             NOT NULL,
    password             VARCHAR(32),
    key                  text,
    key_password         VARCHAR(32),
    bastion_host         VARCHAR(255),
    bastion_port         NUMERIC,
    bastion_username     VARCHAR(32),
    bastion_password     VARCHAR(32),
    bastion_key          text,
    bastion_key_password VARCHAR(32),
    status               CHAR(1) DEFAULT ('P')               NOT NULL
        CONSTRAINT suse_payg_ssh_data_status_ck
            CHECK (status in ('P', 'E', 'S')),
    error_message       text,
    created              TIMESTAMPTZ DEFAULT (current_timestamp) NOT NULL,
    modified             TIMESTAMPTZ DEFAULT (current_timestamp) NOT NULL
);

CREATE SEQUENCE IF NOT EXISTS susePaygSshData_id_seq;

CREATE UNIQUE INDEX IF NOT EXISTS susePaygSshData_host_uq
    ON susePaygSshData (host);

---------------------------
-- add rmt cloud host table
---------------------------
CREATE TABLE IF NOT EXISTS suseCloudRmtHost
(
    id               NUMERIC                                 NOT NULL
        CONSTRAINT suseCloudRmtHost_pk PRIMARY KEY,
    hostname         VARCHAR(255)                            NOT NULL,
    ip_address       VARCHAR(39)                             NOT NULL,
    ssl_cert         text,
    created          TIMESTAMPTZ DEFAULT (current_timestamp) NOT NULL,
    modified         TIMESTAMPTZ DEFAULT (current_timestamp) NOT NULL,
    payg_ssh_data_id NUMERIC                                 NOT NULL,
    CONSTRAINT payg_ssh_data_id_fk
        FOREIGN KEY (payg_ssh_data_id) REFERENCES susePaygSshData (id)
);

CREATE SEQUENCE IF NOT EXISTS susecloudrmthost_id_seq;

---------------------------
-- Add new credentials type
---------------------------
DO $$
  BEGIN
    IF EXISTS (SELECT 1 FROM information_schema.tables WHERE table_name = 'susecredentialstype') THEN
      insert into suseCredentialsType (id, label, name)
        select sequence_nextval('suse_credtype_id_seq'), 'cloudrmt', 'Cloud RMT network'
        where not exists(select 1 from suseCredentialsType where label = 'cloudrmt');
    ELSE
      RAISE NOTICE 'suseCredentialsType does not exists';
    END IF;
  END;
$$;

--------------------------------
-- Update suse credentials Table
--------------------------------
alter table susecredentials add column if not exists extra_auth bytea;

-- Add link from credentials to payg ssh data
alter table susecredentials
    add column if not exists payg_ssh_data_id NUMERIC;

ALTER TABLE susecredentials
DROP CONSTRAINT IF EXISTS suse_credentials_payg_ssh_data_id_fk;

ALTER TABLE susecredentials
    ADD CONSTRAINT suse_credentials_payg_ssh_data_id_fk
        FOREIGN KEY (payg_ssh_data_id) REFERENCES susePaygSshData(id);

ALTER TABLE susecredentials
DROP CONSTRAINT IF EXISTS suse_credentials_payg_ssh_data_id_uq;

ALTER TABLE susecredentials
    ADD CONSTRAINT suse_credentials_payg_ssh_data_id_uq unique (payg_ssh_data_id);

----------------
-- add new tasks
----------------
INSERT INTO rhnTaskoTask (id, name, class)
  select sequence_nextval('rhn_tasko_task_id_seq'), 'update-payg-auth', 'com.redhat.rhn.taskomatic.task.payg.PaygUpdateAuthTask'
  WHERE NOT EXISTS (
            SELECT 1 FROM rhnTaskoTask WHERE
                name = 'update-payg-auth'
    );

INSERT INTO rhnTaskoTask (id, name, class)
  select sequence_nextval('rhn_tasko_task_id_seq'), 'update-payg-hosts', 'com.redhat.rhn.taskomatic.task.payg.PaygUpdateHostsTask'
  WHERE NOT EXISTS (
        SELECT 1 FROM rhnTaskoTask WHERE
                name = 'update-payg-hosts'
    );

INSERT INTO rhnTaskoBunch (id, name, description, org_bunch)
select sequence_nextval('rhn_tasko_bunch_id_seq'), 'update-payg-data-bunch', 'Runs update-payg-data
Parameters:
- integer parameter payg instance ID
- without parameter updates data for all instances', null
    WHERE NOT EXISTS ( SELECT 1 FROM rhnTaskoBunch WHERE name = 'update-payg-data-bunch');

INSERT INTO rhnTaskoTemplate (id, bunch_id, task_id, ordering, start_if)
  select sequence_nextval('rhn_tasko_template_id_seq'),
        (SELECT id FROM rhnTaskoBunch WHERE name = 'update-payg-data-bunch'),
        (SELECT id FROM rhnTaskoTask WHERE name = 'update-payg-auth'),
        0,
        null
  WHERE NOT EXISTS
      ( SELECT 1 FROM rhnTaskoTemplate
          WHERE bunch_id = ( SELECT id FROM rhnTaskoBunch WHERE name = 'update-payg-data-bunch' )
          and task_id = (SELECT id FROM rhnTaskoTask WHERE name = 'update-payg-auth'));

INSERT INTO rhnTaskoTemplate (id, bunch_id, task_id, ordering, start_if)
 select sequence_nextval('rhn_tasko_template_id_seq'),
        (SELECT id FROM rhnTaskoBunch WHERE name = 'update-payg-data-bunch'),
        (SELECT id FROM rhnTaskoTask WHERE name = 'update-payg-hosts'),
        1,
        null
  WHERE NOT EXISTS
    ( SELECT 1 FROM rhnTaskoTemplate
      WHERE bunch_id = ( SELECT id FROM rhnTaskoBunch WHERE name = 'update-payg-data-bunch' )
      and task_id = (SELECT id FROM rhnTaskoTask WHERE name = 'update-payg-hosts'));

-- need to add new schedule
INSERT INTO rhnTaskoSchedule (id, job_label, bunch_id, active_from, cron_expr)
  select sequence_nextval('rhn_tasko_schedule_id_seq'), 'update-payg-default',
       (SELECT id FROM rhnTaskoBunch WHERE name='update-payg-data-bunch'),
       current_timestamp, '0 0/10 * * * ?'
  WHERE not exists (
        SELECT 1 FROM rhnTaskoSchedule
        WHERE job_label = 'update-payg-default'
  );
07070100000F4E000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005000000000susemanager-schema/upgrade/susemanager-schema-4.3.8-to-susemanager-schema-4.3.9   07070100000F4F000081B400000000000000000000000167AE111400000409000000000000000000000000000000000000006600000000susemanager-schema/upgrade/susemanager-schema-4.3.8-to-susemanager-schema-4.3.9/310-suseImageInfo.sql ALTER TABLE suseImageInfo ADD COLUMN IF NOT EXISTS obsolete       CHAR(1) DEFAULT ('N') NOT NULL;

ALTER TABLE suseImageInfo ADD COLUMN IF NOT EXISTS built          CHAR(1) DEFAULT ('N') NOT NULL;

ALTER TABLE suseImageInfo ADD COLUMN IF NOT EXISTS pillar_id      NUMERIC
                        CONSTRAINT suse_imginfo_pillar_fk
                        REFERENCES suseSaltPillar (id)
                        ON DELETE SET NULL;

ALTER TABLE suseImageInfo ADD COLUMN IF NOT EXISTS log            TEXT;

UPDATE suseImageInfo SET built='Y' WHERE id IN (SELECT DISTINCT image_info_id FROM suseImageInfoPackage);

CREATE OR REPLACE FUNCTION suse_image_info_image_removed_trig_fun() RETURNS TRIGGER AS $$
BEGIN
  DELETE FROM suseSaltPillar WHERE id = OLD.pillar_id;
  RETURN OLD;
END $$ LANGUAGE PLPGSQL;

DROP TRIGGER IF EXISTS suse_image_info_image_removed_trig ON suseImageInfo;
CREATE TRIGGER suse_image_info_image_removed_trig AFTER DELETE ON suseImageInfo
  FOR EACH ROW EXECUTE PROCEDURE suse_image_info_image_removed_trig_fun();

   07070100000F50000081B400000000000000000000000167AE11140000114D000000000000000000000000000000000000006C00000000susemanager-schema/upgrade/susemanager-schema-4.3.8-to-susemanager-schema-4.3.9/320-suseImageRepoDigest.sql   DO $$
    BEGIN
        IF EXISTS
            (
                SELECT 1
                FROM information_schema.columns
                WHERE table_name='suseimagerepodigest' AND column_name='image_history_id'
            )
        THEN
            CREATE TEMP TABLE tmpImageDigest AS
                 SELECT name,
                   version,
                   image_type,
                   org_id,
                   store_id,
                   revision_num,
                   suseImageBuildHistory.created,
                   suseImageBuildHistory.modified,
                   repo_digest
                 FROM suseImageInfo
                     LEFT JOIN suseImageBuildHistory ON suseImageInfo.id = suseImageBuildHistory.image_info_id
                     LEFT JOIN suseImageRepoDigest ON suseImageBuildHistory.id = suseImageRepoDigest.image_history_id;

            CREATE TEMP TABLE tmpImageHistory AS
            SELECT name,
                   version,
                   image_type,
                   checksum_id,
                   image_arch_id,
                   org_id,
                   profile_id,
                   store_id,
                   build_server_id,
                   external_image,
                   revision_num,
                   curr_revision_num,
                   suseImageBuildHistory.created,
                   suseImageBuildHistory.modified
                 FROM suseImageInfo
                     LEFT JOIN suseImageBuildHistory ON suseImageInfo.id = suseImageBuildHistory.image_info_id;

            INSERT INTO suseImageInfo (
                  id,
                  name,
                  version,
                  image_type,
                  image_arch_id,
                  org_id,
                  profile_id,
                  store_id,
                  build_server_id,
                  external_image,
                  curr_revision_num,
                  created,
                  modified,
                  obsolete
                )
                SELECT sequence_nextval('suse_imginfo_imgid_seq'),
                       name,
                       version,
                       image_type,
                       image_arch_id,
                       org_id,
                       profile_id,
                       store_id,
                       build_server_id,
                       external_image,
                       revision_num,
                       created,
                       modified,
                       'Y'
                     FROM tmpImagehistory
                         WHERE revision_num != curr_revision_num;


            DROP TABLE suseImageRepoDigest;
            DROP SEQUENCE suse_img_repodigest_id_seq;
            DROP TABLE suseImageBuildHistory;

            CREATE TABLE suseImageRepoDigest
            (
                id             NUMERIC NOT NULL
                                 CONSTRAINT suse_rdigest_id_pk PRIMARY KEY,
                image_info_id    NUMERIC NOT NULL,
                repo_digest    VARCHAR(255) NOT NULL,
                created        TIMESTAMPTZ
                                 DEFAULT (current_timestamp) NOT NULL,
                modified       TIMESTAMPTZ
                                 DEFAULT (current_timestamp) NOT NULL,
                CONSTRAINT suse_rdigest_imginfo_fk FOREIGN KEY (image_info_id)
                    REFERENCES suseImageInfo (id) ON DELETE CASCADE
            );


            CREATE SEQUENCE suse_img_repodigest_id_seq;

            INSERT INTO suseImageRepoDigest (id, image_info_id, repo_digest, created, modified)
                   SELECT sequence_nextval('suse_img_repodigest_id_seq'), suseImageInfo.id, repo_digest, tmpImageDigest.created, tmpImageDigest.modified
                       FROM suseImageInfo, tmpImageDigest
                          WHERE suseImageInfo.name = tmpImageDigest.name
                            AND suseImageInfo.version = tmpImageDigest.version
                            AND suseImageInfo.image_type = tmpImageDigest.image_type
                            AND suseImageInfo.org_id = tmpImageDigest.org_id
                            AND suseImageInfo.store_id = tmpImageDigest.store_id
                            AND suseImageInfo.curr_revision_num = tmpImageDigest.revision_num;

            DROP TABLE tmpImageDigest;
            DROP TABLE tmpImageHistory;

        END IF;
    END
$$ LANGUAGE plpgsql;
   07070100000F51000081B400000000000000000000000167AE1114000002A0000000000000000000000000000000000000006600000000susemanager-schema/upgrade/susemanager-schema-4.3.8-to-susemanager-schema-4.3.9/330-suseImageFile.sql CREATE TABLE IF NOT EXISTS suseImageFile
(
    id             NUMERIC NOT NULL
                     CONSTRAINT suse_imgfile_fileid_pk PRIMARY KEY,
    image_info_id  NUMERIC NOT NULL,
    file           TEXT NOT NULL,
    type           VARCHAR(16) NOT NULL,
    external       CHAR(1) DEFAULT ('N') NOT NULL,
    created        TIMESTAMPTZ
                     DEFAULT (current_timestamp) NOT NULL,
    modified       TIMESTAMPTZ
                     DEFAULT (current_timestamp) NOT NULL,

    CONSTRAINT suse_imgfile_imginfo_fk FOREIGN KEY (image_info_id)
        REFERENCES suseImageInfo (id) ON DELETE CASCADE
);

CREATE SEQUENCE IF NOT EXISTS suse_image_file_id_seq;
07070100000F52000081B400000000000000000000000167AE11140000060F000000000000000000000000000000000000006A00000000susemanager-schema/upgrade/susemanager-schema-4.3.8-to-susemanager-schema-4.3.9/340-suseImageOverview.sql drop view suseImageOverview;

create or replace view
suseImageOverview
(
    org_id,
    image_id,
    image_name,
    image_version,
    image_type,
    checksum_id,
    modified,
    image_arch_name,
    build_action_id,
    inspect_action_id,
    profile_id,
    store_id,
    build_server_id,
    curr_revision_num,
    external_image,
    obsolete,
    built,
    security_errata,
    bug_errata,
    enhancement_errata,
    outdated_packages,
    installed_packages
)
as
select
    i.org_id, i.id, i.name, i.version, i.image_type, i.checksum_id, i.modified,
    ( select name from rhnServerArch where id = i.image_arch_id), i.build_action_id,
    i.inspect_action_id, i.profile_id, i.store_id, i.build_server_id, i.curr_revision_num,
    i.external_image, i.obsolete, i.built,
    ( select count(*) from rhnImageErrataTypeView ietv
      where
            ietv.image_id = i.id
        and ietv.errata_type = 'Security Advisory'),
    ( select count(*) from rhnImageErrataTypeView ietv
      where
            ietv.image_id = i.id
        and ietv.errata_type = 'Bug Fix Advisory'),
    ( select count(*) from rhnImageErrataTypeView ietv
      where
            ietv.image_id = i.id
        and ietv.errata_type = 'Product Enhancement Advisory'),
    ( select count(distinct p.name_id) from rhnPackage p, rhnImageNeededPackageCache inpc
      where
            inpc.image_id = i.id
        and p.id = inpc.package_id),
    (select count(*) from suseImageInfoPackage iip
     where
            iip.image_info_id = i.id)
from
    suseImageInfo i
;
 07070100000F53000081B400000000000000000000000167AE1114000006C8000000000000000000000000000000000000006B00000000susemanager-schema/upgrade/susemanager-schema-4.3.8-to-susemanager-schema-4.3.9/350-suseDeltaImageInfo.sql    CREATE TABLE IF NOT EXISTS suseDeltaImageInfo
(
    source_image_id NUMERIC NOT NULL
                     CONSTRAINT suse_deltaimg_source_fk
                     REFERENCES suseImageInfo (id) ON DELETE CASCADE,

    target_image_id NUMERIC NOT NULL
                     CONSTRAINT suse_deltaimg_target_fk
                     REFERENCES suseImageInfo (id) ON DELETE CASCADE,

    pillar_id       NUMERIC
                     CONSTRAINT suse_deltaimg_pillar_fk
                       REFERENCES suseSaltPillar (id)
                       ON DELETE SET NULL,

    file           TEXT NOT NULL,

    created        TIMESTAMPTZ
                     DEFAULT (current_timestamp) NOT NULL,
    modified       TIMESTAMPTZ
                     DEFAULT (current_timestamp) NOT NULL,

    CONSTRAINT suse_deltaimg_pk PRIMARY KEY (source_image_id, target_image_id)
);

CREATE OR REPLACE FUNCTION suse_delta_image_info_mod_trig_fun() RETURNS TRIGGER AS
$$
BEGIN
        new.modified := current_timestamp;
        return new;
END;
$$ LANGUAGE PLPGSQL;

DROP TRIGGER IF EXISTS suse_delta_image_info_mod_trig ON suseDeltaImageInfo;
CREATE TRIGGER suse_delta_image_info_mod_trig BEFORE INSERT OR UPDATE ON suseDeltaImageInfo
  FOR EACH ROW EXECUTE PROCEDURE suse_delta_image_info_mod_trig_fun();

CREATE OR REPLACE FUNCTION suse_delta_image_info_image_removed_trig_fun() RETURNS TRIGGER AS $$
BEGIN
  DELETE FROM suseSaltPillar WHERE id = OLD.pillar_id;
  RETURN OLD;
END $$ LANGUAGE PLPGSQL;

DROP TRIGGER IF EXISTS suse_delta_image_info_image_removed_trig ON suseDeltaImageInfo;
CREATE TRIGGER suse_delta_image_info_image_removed_trig AFTER DELETE ON suseDeltaImageInfo
  FOR EACH ROW EXECUTE PROCEDURE suse_delta_image_info_image_removed_trig_fun();
07070100000F54000041FD00000000000000000000000267AE111400000000000000000000000000000000000000000000005100000000susemanager-schema/upgrade/susemanager-schema-4.3.9-to-susemanager-schema-4.3.10  07070100000F55000081B400000000000000000000000167AE1114000000AE000000000000000000000000000000000000006F00000000susemanager-schema/upgrade/susemanager-schema-4.3.9-to-susemanager-schema-4.3.10/001-drop-rhnSatelliteInfo.sql    DROP TRIGGER IF EXISTS rhn_satellite_info_mod_trig ON rhnSatelliteInfo;

DROP FUNCTION IF EXISTS rhn_satellite_info_mod_trig_fun();

DROP TABLE IF EXISTS rhnSatelliteInfo;


  07070100000F56000081B400000000000000000000000167AE111400000273000000000000000000000000000000000000006B00000000susemanager-schema/upgrade/susemanager-schema-4.3.9-to-susemanager-schema-4.3.10/001-rhnProxyInfo-port.sql    ALTER TABLE rhnProxyInfo
    ADD COLUMN IF NOT EXISTS ssh_port NUMERIC,
    ADD COLUMN IF NOT EXISTS created  TIMESTAMPTZ DEFAULT (current_timestamp) NOT NULL,
    ADD COLUMN IF NOT EXISTS modified TIMESTAMPTZ DEFAULT (current_timestamp) NOT NULL;


CREATE OR REPLACE FUNCTION rhn_proxy_info_mod_trig_fun() RETURNS TRIGGER AS
$$
BEGIN
    new.modified := current_timestamp;
    return new;
END;
$$ LANGUAGE PLPGSQL;

DROP TRIGGER IF EXISTS rhn_proxy_info_mod_trig ON rhnProxyInfo;

CREATE TRIGGER rhn_proxy_info_mod_trig BEFORE INSERT OR UPDATE ON rhnProxyInfo
    FOR EACH ROW EXECUTE PROCEDURE rhn_proxy_info_mod_trig_fun();
 07070100000F57000081B400000000000000000000000167AE1114000008D1000000000000000000000000000000000000007100000000susemanager-schema/upgrade/susemanager-schema-4.3.9-to-susemanager-schema-4.3.10/002-add-suseUyuniServerInfo.sql  --
-- Copyright (c) 2022 SUSE LLC
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--

DO $$
  BEGIN
    IF EXISTS (SELECT 1 FROM information_schema.tables WHERE table_name = 'susecredentialstype') THEN
      insert into suseCredentialsType (id, label, name)
        select sequence_nextval('suse_credtype_id_seq'), 'reportcreds', 'Reporting DB Credentials'
         where not exists(select 1 from suseCredentialsType where label = 'reportcreds');
    ELSE
      RAISE NOTICE 'suseCredentialsType does not exists';
    END IF;
  END;
$$;


CREATE TABLE IF NOT EXISTS suseMgrServerInfo
(
    server_id          NUMERIC NOT NULL
                           CONSTRAINT suse_mgr_info_sid_fk
                               REFERENCES rhnServer (id),
    mgr_evr_id         NUMERIC
                           CONSTRAINT suse_mgr_info_peid_fk
                               REFERENCES rhnPackageEVR (id),
    report_db_cred_id  NUMERIC
                           CONSTRAINT suse_mgr_info_creds_fk
                               REFERENCES suseCredentials (id)
                               ON DELETE SET NULL,
    report_db_name     VARCHAR(128),
    report_db_host     VARCHAR(256),
    report_db_port     NUMERIC DEFAULT (5432) NOT NULL,
    report_db_last_synced TIMESTAMPTZ,
    created            TIMESTAMPTZ
                           DEFAULT (current_timestamp) NOT NULL,
    modified           TIMESTAMPTZ
                           DEFAULT (current_timestamp) NOT NULL,
    CONSTRAINT suse_mgr_info_sid_uq UNIQUE (server_id)
)
;

create or replace function suse_mgr_info_mod_trig_fun() returns trigger as
$$
begin
	new.modified := current_timestamp;
	       
	return new;
end;
$$ language plpgsql;

DROP TRIGGER IF EXISTS suse_mgr_info_mod_trig ON suseMgrServerInfo;
CREATE TRIGGER suse_mgr_info_mod_trig
before insert or update on suseMgrServerInfo
for each row
execute procedure suse_mgr_info_mod_trig_fun();
   07070100000F58000081B400000000000000000000000167AE1114000027B1000000000000000000000000000000000000006700000000susemanager-schema/upgrade/susemanager-schema-4.3.9-to-susemanager-schema-4.3.10/003-delete_server.sql    --
-- Copyright (c) 2008--2012 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--
--
--
-- This deletes a server.  All codepaths which delete servers should hit this
-- or delete_server_bulk()

create or replace
function delete_server (
        server_id_in in numeric
) returns void
as
$$
declare
         servergroups cursor for
                select  server_id, server_group_id
                from    rhnServerGroupMembers sgm
                where   sgm.server_id = server_id_in;

         configchannels cursor for
                select  cc.id
                from    rhnConfigChannel cc,
                        rhnConfigChannelType cct,
                        rhnServerConfigChannel scc
                where   1=1
                        and scc.server_id = server_id_in
                        and scc.config_channel_id = cc.id
                        -- these config channel types are reserved
                        -- for use by a single server, so we don't
                        -- need to check for other servers subscribed
                        and cct.label in
                                ('local_override','server_import')
                        and cct.id = cc.confchan_type_id;

begin
        -- filelists
        delete from rhnFileList where id in (
	select	spfl.file_list_id
	  from	rhnServerPreserveFileList spfl
	 where	spfl.server_id = server_id_in
			and not exists (
				select	1
				from	rhnServerPreserveFileList
				where	file_list_id = spfl.file_list_id
					and server_id != server_id_in
				union all
				select	1
				from	rhnKickstartPreserveFileList
				where	file_list_id = spfl.file_list_id
			)
        );

	for configchannel in configchannels loop
		perform rhn_config.delete_channel(configchannel.id);
	end loop;

	for sgm in servergroups loop
		perform rhn_server.delete_from_servergroup(
			sgm.server_id, sgm.server_group_id);
	end loop;


        -- we're handling this instead of letting an "on delete
        -- set null" do it so that we don't run the risk
        -- of setting off the triggers and killing us with a
        -- mutating table

        -- this is merge of two single updates:
        --  update ... set old_server_id = null where old_server_id = server_id_in;
        --  update ... set new_server_id = null where new_server_id = server_id_in;
        -- so we scan rhnKickstartSession table only once
        update rhnKickstartSession
                set old_server_id = case when old_server_id = server_id_in then null else old_server_id end,
                    new_server_id = case when new_server_id = server_id_in then null else new_server_id end
                where old_server_id = server_id_in
                   or new_server_id = server_id_in;

        perform rhn_channel.clear_subscriptions(server_id_in, 1);

        -- A little complicated here, but the goal is to
        -- delete records from rhnVirtualInstace only if we don't
        -- care about them anymore.  We don't care about records
        -- in rhnVirtualInstance if we are deleting the host
        -- system and the virtual system is already null, or
        -- vice-versa.  We *do* care about them if either the
        -- host or virtual system is still registered because we
        -- still want them to show up in the UI.
    -- If there's a newer row in rhnVirtualInstance with the same
    -- uuid, this guest must have been re-registered, so we can clean
    -- this data up.

        delete from rhnVirtualInstance vi
              where (host_system_id = server_id_in and virtual_system_id is null)
                 or (virtual_system_id = server_id_in and host_system_id is null)
                 or (vi.virtual_system_id = server_id_in and vi.modified < (select max(vi2.modified)
                    from rhnVirtualInstance vi2 where vi2.uuid = vi.uuid));

        -- this is merge of two single updates:
        --  update ... set host_system_id = null where host_system_id = server_id_in;
        --  update ... set virtual_system_id = null where virtual_system_id = server_id_in;
        -- so we scan rhnVirtualInstance table only once
        update rhnVirtualInstance
           set host_system_id = case when host_system_id = server_id_in then null else host_system_id end,
               virtual_system_id = case when virtual_system_id = server_id_in then null else virtual_system_id end
         where host_system_id = server_id_in
            or virtual_system_id = server_id_in;

        -- this is merge of two single updates:
        --  update ... set old_host_system_id = null when old_host_system_id = server_id_in;
        --  update ... set new_host_system_id = null when new_host_system_id = server_id_in;
        -- so we scan rhnVirtualInstanceEventLog table only once
        update rhnVirtualInstanceEventLog
           set old_host_system_id = case when old_host_system_id = server_id_in then null else old_host_system_id end,
               new_host_system_id = case when new_host_system_id = server_id_in then null else new_host_system_id end
         where old_host_system_id = server_id_in
            or new_host_system_id = server_id_in;

        -- archive related actions, only if they have no other servers assigned
        update rhnAction set archived = 1 where id in (
            select action_id from rhnServerAction sa
            where not exists (
                select server_id from rhnServerAction
                where action_id = sa.action_id and server_id != server_id_in
            )
        );

        -- We're deleting everything with a foreign key to rhnServer
        -- here, now.  I'm hoping this will help aleviate our deadlock
        -- problem.

        delete from rhnActionApplyStatesResult where server_id = server_id_in;
        delete from rhnActionConfigChannel where server_id = server_id_in;
        delete from rhnActionConfigRevision where server_id = server_id_in;
        delete from rhnActionPackageRemovalFailure where server_id = server_id_in;
        delete from rhnClientCapability where server_id = server_id_in;
        delete from rhnCpu where server_id = server_id_in;
        -- there's still a cascade here, because the constraint keeps the
        -- table locked for too long to rebuild it.  Ugh...
        delete from rhnDevice where server_id = server_id_in;
        delete from rhnProxyInfo where server_id = server_id_in;
        delete from rhnRam where server_id = server_id_in;
        delete from rhnRegToken where server_id = server_id_in;
        delete from suseMgrServerInfo where server_id = server_id_in;
        -- this cascades to rhnActionConfigChannel and rhnActionConfigFileName
        delete from rhnServerAction where server_id = server_id_in;
        delete from rhnServerActionPackageResult where server_id = server_id_in;
        delete from rhnServerActionScriptResult where server_id = server_id_in;
        delete from rhnServerActionVerifyResult where server_id = server_id_in;
        delete from rhnServerActionVerifyMissing where server_id = server_id_in;
        -- counts are handled above.  this should be a delete_ function.
        delete from rhnServerChannel where server_id = server_id_in;
        delete from rhnServerConfigChannel where server_id = server_id_in;
        delete from rhnServerCustomDataValue where server_id = server_id_in;
        delete from rhnServerDMI where server_id = server_id_in;
        delete from rhnServerEvent where server_id = server_id_in;
        delete from rhnServerFQDN where server_id = server_id_in;
        delete from rhnServerHistory where server_id = server_id_in;
        delete from rhnServerInfo where server_id = server_id_in;
        delete from rhnServerInstallInfo where server_id = server_id_in;
        delete from rhnServerLocation where server_id = server_id_in;
        delete from rhnServerLock where server_id = server_id_in;
        delete from rhnServerNeededCache where server_id = server_id_in;
        delete from rhnServerNotes where server_id = server_id_in;
        -- I'm not removing the foreign key from rhnServerPackage; that'll
        -- take forever.  Do the delete anyway.
        delete from rhnServerPackage where server_id = server_id_in;
        delete from rhnServerTokenRegs where server_id = server_id_in;
        delete from rhnSnapshotTag where server_id = server_id_in;
        -- this cascades to:
        --   rhnSnapshotChannel, rhnSnapshotConfigChannel, rhnSnapshotPackage,
        --   rhnSnapshotConfigRevision, rhnSnapshotServerGroup,
        --   rhnSnapshotTag.
        -- We may want to consider delete_snapshot() at some point, but
        --   I don't think we need to yet.
        delete from rhnSnapshot where server_id = server_id_in;
        delete from rhnUserServerPrefs where server_id = server_id_in;
        -- hrm, this one's interesting... we _probably_ should delete
        -- everything for the parent server_id when we delete the proxy,
        -- but we don't currently.
        delete from rhnServerPath where server_id_in in (server_id, proxy_server_id);
        delete from rhnUserServerPerms where server_id = server_id_in;

        delete from rhnServerNetInterface where server_id = server_id_in;

        delete from rhnServerUuid where server_id = server_id_in;

        delete from rhnPushClient where server_id = server_id_in;

        -- now get rhnServer itself.
        delete
        from    rhnServer
                where id = server_id_in;

        delete
        from    rhnSet
        where   label = 'system_list'
                and element = server_id_in;
end;
$$
language plpgsql;
   07070100000F59000081B400000000000000000000000167AE11140000502F000000000000000000000000000000000000006800000000susemanager-schema/upgrade/susemanager-schema-4.3.9-to-susemanager-schema-4.3.10/004-rhn_server.pkb.sql   -- oracle equivalent source sha1 87bc50785a1b2a5e639cdc7371aa5c1b435adaa2
--
-- Copyright (c) 2008--2014 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--
--
--
--

-- create schema rhn_server;

--update pg_setting
update pg_settings set setting = 'rhn_server,' || setting where name = 'search_path';

    create or replace function system_service_level(
    	server_id_in in numeric,
	service_level_in in varchar
    ) returns numeric as $$
    declare
    ents cursor is
      select label from rhnServerEntitlementView
      where server_id = server_id_in;

    retval numeric := 0;

    begin
         for ent in ents loop
            retval := rhn_entitlements.entitlement_grants_service (ent.label, service_level_in);
            if retval = 1 then
               return retval;
            end if;
         end loop;

         return retval;

    end$$ language plpgsql;


    create or replace function can_change_base_channel(server_id_in IN NUMERIC)
    returns numeric
    as $$
    declare
    	throwaway numeric;
    begin
    	-- the idea: if we get past this query, the server is
	-- neither sat nor proxy, so base channel is changeable

	select 1 into throwaway
	  from rhnServer S
	 where S.id = server_id_in
	   and not exists (select 1 from suseMgrServerInfo SI where SI.server_id = S.id)
	   and not exists (select 1 from rhnProxyInfo PI where PI.server_id = S.id);

        if not found then
	    return 0;
        end if;

	return 1;
    end$$ language plpgsql;

    create or replace function set_custom_value(
    	server_id_in in numeric,
	user_id_in in numeric,
	key_label_in in varchar,
	value_in in varchar
    ) returns void
    as $$
    declare
    	key_id_val numeric;
    begin
    	select CDK.id into strict key_id_val
	  from rhnCustomDataKey CDK,
	       rhnServer S
	 where S.id = server_id_in
	   and S.org_id = CDK.org_id
	   and CDK.label = key_label_in;

	begin
	    insert into rhnServerCustomDataValue (server_id, key_id, value, created_by, last_modified_by)
	    values (server_id_in, key_id_val, value_in, user_id_in, user_id_in);
	exception
	    when UNIQUE_VIOLATION
	    	then
		update rhnServerCustomDataValue
		   set value = value_in,
		       last_modified_by = user_id_in
		 where server_id = server_id_in
		   and key_id = key_id_val;
	end;

    end$$ language plpgsql;

    create or replace function bulk_set_custom_value(
    	key_label_in in varchar,
	value_in in varchar,
	set_label_in in varchar,
	set_uid_in in numeric
    )
    returns integer
    as $$
    declare
        i integer;
        server record;
    begin
        i := 0;
        for server in (
           SELECT user_id, label, element, element_two
	     FROM rhnSet
	    WHERE label = set_label_in
	      AND user_id = set_uid_in
	) loop
	    if rhn_server.system_service_level(server.element, 'management') = 1 then
	    	perform rhn_server.set_custom_value(server.element, set_uid_in, key_label_in, value_in);
            i := i + 1;
	    end if;
	end loop;
    return i;
    end$$ language plpgsql;

    create or replace function bulk_snapshot_tag(
    	org_id_in in numeric,
        tagname_in in varchar,
	set_label_in in varchar,
	set_uid_in in numeric
    ) returns void
    as $$
    declare
        server record;
    	snapshot_id numeric;
    begin
        for server in (
           SELECT user_id, label, element, element_two
	     FROM rhnSet
	    WHERE label = set_label_in
	      AND user_id = set_uid_in
	    ) loop
	    if rhn_server.system_service_level(server.element, 'management') = 1 then
	    	    select max(id) into snapshot_id
	    	    from rhnSnapshot
	    	    where server_id = server.element;

	    	    if snapshot_id is null then
		    	perform rhn_server.snapshot_server(server.element, 'tagging system:  ' || tagname_in);

			select max(id) into snapshot_id
			from rhnSnapshot
			where server_id = server.element;
		    end if;

		-- now have a snapshot_id to work with...
		begin
		    perform rhn_server.tag_snapshot(snapshot_id, org_id_in, tagname_in);
		exception
		    when UNIQUE_VIOLATION
		    	then
			-- do nothing, be forgiving...
			null;
		end;
	    end if;
	end loop;
    end$$ language plpgsql;

    create or replace function tag_delete(
    	server_id_in in numeric,
	tag_id_in in numeric
    ) returns void
    as $$
    declare
    	snapshots cursor is
		select	snapshot_id
		from	rhnSnapshotTag
		where	tag_id = tag_id_in;
	tag_id_tmp numeric;
    begin
    	select	id into tag_id_tmp
	from	rhnTag
	where	id = tag_id_in
	for update;

	delete
		from	rhnSnapshotTag
		where	server_id = server_id_in
			and tag_id = tag_id_in;
	for snapshot in snapshots loop
		return;
	end loop;
	delete
		from rhnTag
		where id = tag_id_in;
    end$$ language plpgsql;

    create or replace function tag_snapshot(
        snapshot_id_in in numeric,
	org_id_in in numeric,
	tagname_in in varchar
    ) returns void
    as $$
    begin
    	insert into rhnSnapshotTag (snapshot_id, server_id, tag_id)
	select snapshot_id_in, server_id, lookup_tag(org_id_in, tagname_in)
	from rhnSnapshot
	where id = snapshot_id_in;
    end$$ language plpgsql;

    create or replace function bulk_snapshot(
    	reason_in in varchar,
	set_label_in in varchar,
	set_uid_in in numeric
    ) returns void
    as $$
    declare
        server record;
    begin
        for server in (
           SELECT user_id, label, element, element_two
	     FROM rhnSet
	    WHERE label = set_label_in
	      AND user_id = set_uid_in
	    ) loop
	    if rhn_server.system_service_level(server.element, 'management') = 1 then
	    	perform rhn_server.snapshot_server(server.element, reason_in);
	    end if;
	end loop;
    end$$ language plpgsql;

    create or replace function snapshot_server(
    	server_id_in in numeric,
	reason_in in varchar
    ) returns void
    as $$
    declare
    	snapshot_id_v numeric;
	revisions cursor is
		select distinct
			cr.id
		from	rhnConfigRevision	cr,
			rhnConfigFileName	cfn,
			rhnConfigFile		cf,
			rhnConfigChannel	cc,
			rhnServerConfigChannel	scc
		where	1=1
			and scc.server_id = server_id_in
			and scc.config_channel_id = cc.id
			and cc.id = cf.config_channel_id
			and cf.id = cr.config_file_id
			and cr.id = cf.latest_config_revision_id
			and cf.config_file_name_id = cfn.id
			and cf.id = lookup_first_matching_cf(scc.server_id, cfn.path);
	locked integer;
    begin
    	select nextval('rhn_snapshot_id_seq') into snapshot_id_v;

	insert into rhnSnapshot (id, org_id, server_id, reason) (
		select	snapshot_id_v,
			s.org_id,
			server_id_in,
			reason_in
		from	rhnServer s
		where	s.id = server_id_in
	);
	insert into rhnSnapshotChannel (snapshot_id, channel_id) (
		select	snapshot_id_v, sc.channel_id
		from	rhnServerChannel sc
		where	sc.server_id = server_id_in
	);
	insert into rhnSnapshotServerGroup (snapshot_id, server_group_id) (
		select	snapshot_id_v, sgm.server_group_id
		from	rhnServerGroupMembers sgm
		where	sgm.server_id = server_id_in
	);
        locked := 0;
        <<iloop>>
        while true loop
            begin
                insert into rhnPackageNEVRA (id, name_id, evr_id, package_arch_id)
                select nextval('rhn_pkgnevra_id_seq'), sp.name_id, sp.evr_id, sp.package_arch_id
                from rhnServerPackage sp
                where sp.server_id = server_id_in
                        and not exists
                        (select 1
                                from rhnPackageNEVRA nevra
                                where nevra.name_id = sp.name_id
                                        and nevra.evr_id = sp.evr_id
                                        and (nevra.package_arch_id = sp.package_arch_id
                                            or (nevra.package_arch_id is null
                                                and sp.package_arch_id is null)));
                exit iloop;
            exception when unique_violation then
                if locked = 1 then
                    raise;
                else
                    lock table rhnPackageNEVRA in exclusive mode;
                    locked := 1;
                end if;
            end;
        end loop;
	insert into rhnSnapshotPackage (snapshot_id, nevra_id) (
                select distinct snapshot_id_v, nevra.id
                from    rhnServerPackage sp, rhnPackageNEVRA nevra
                where   sp.server_id = server_id_in
                        and nevra.name_id = sp.name_id
                        and nevra.evr_id = sp.evr_id
                        and (nevra.package_arch_id = sp.package_arch_id
                            or (nevra.package_arch_id is null
                                and sp.package_arch_id is null))
	);

	insert into rhnSnapshotConfigChannel ( snapshot_id, config_channel_id ) (
		select	snapshot_id_v, scc.config_channel_id
		from	rhnServerConfigChannel scc
		where	server_id = server_id_in
	);

	for revision in revisions loop
		insert into rhnSnapshotConfigRevision (
				snapshot_id, config_revision_id
			) values (
				snapshot_id_v, revision.id
			);
	end loop;
    end$$ language plpgsql;

    create or replace function remove_action(
    	server_id_in in numeric,
	action_id_in in numeric
    ) returns void
    as $$
    declare
    	-- this really wants "nulls last", but 8.1.7.3.0 sucks ass.
	-- instead, we make a local table that holds our
	-- list of ids with null prereqs.  There's surely a better way
	-- (an array instead of a table maybe?  who knows...)
	-- but I've got code to do this handy that I can look at ;)
    	chained_actions cursor is
                with recursive r(id, prerequisite) as (
			select	id, prerequisite
			from	rhnAction
			where id = action_id_in
		union all
			select	r1.id, r1.prerequisite
			from	rhnAction r1, r
			where r.id = r1.prerequisite
		)
		select * from r
		order by prerequisite desc;
	sessions cursor is
		select	s.id
		from	rhnKickstartSession s
		where	server_id_in in (s.old_server_id, s.new_server_id)
			and s.action_id = action_id_in
			and not exists (
				select	1
				from	rhnKickstartSessionState ss
				where	ss.id = s.state_id
					and ss.label in ('failed','complete')
			);
	chain_ends numeric[];
	i numeric;
	prereq numeric := 1;
    begin
	select	prerequisite
	into	prereq
	from	rhnAction
	where	id = action_id_in;

	if prereq is not null then
		perform rhn_exception.raise_exception('action_is_child');
	end if;

        chain_ends := '{}';
	i := 1;
	for action in chained_actions loop
		if action.prerequisite is null then
			chain_ends[i] := action.id;
			i := i + 1;
		else
			delete from rhnServerAction
				where server_id = server_id_in
				and action_id = action.id;
		end if;
	end loop;

	delete from rhnServerAction
		where server_id = server_id_in
		and action_id = any(chain_ends);

	for s in sessions loop
		update rhnKickstartSession
			set 	state_id = (
					select	id
					from	rhnKickstartSessionState
					where	label = 'failed'
				),
				action_id = null
			where	id = s.id;
		perform set_ks_session_history_message(s.id, 'failed', 'Kickstart cancelled due to action removal');
	end loop;
    end$$ language plpgsql;

    create or replace function check_user_access(server_id_in in numeric, user_id_in in numeric)
    returns numeric
    as $$
    declare
    	has_access numeric;
    begin
    	-- first check; if this returns no rows, then the server/user are in different orgs, and we bail
        select 1 into has_access
	  from rhnServer S,
	       web_contact wc
	 where wc.org_id = s.org_id
	   and s.id = server_id_in
	   and wc.id = user_id_in;

        if not found then
          return 0;
        end if;

	-- okay, so they're in the same org.  if we have an org admin, they get a free pass
    	if rhn_user.check_role(user_id_in, 'org_admin') = 1
	then
	    return 1;
	end if;

    	select 1 into has_access
	  from rhnServerGroupMembers SGM,
	       rhnUserServerGroupPerms USG
	 where SGM.server_group_id = USG.server_group_id
	   and SGM.server_id = server_id_in
	   and USG.user_id = user_id_in;

        if not found then
          return 0;
        end if;

	return 1;
    end$$ language plpgsql;

    create or replace function insert_into_servergroup (
		server_id_in in numeric,
		server_group_id_in in numeric
    ) returns void
    as $$
    declare
		group_type numeric;
	begin
		-- this will rowlock the servergroup we're trying to change;
		-- we probably need to lock the other one, but I think the chances
		-- of it being a real issue are very small for now...
		select	sg.group_type
		into	group_type
		from	rhnServerGroup sg
		where	sg.id = server_group_id_in
		for update of sg;

		insert into rhnServerGroupMembers(server_id, server_group_id)
		values (server_id_in, server_group_id_in);

		update rhnServerGroup
		set current_members = current_members + 1
		where id = server_group_id_in;

		if group_type is null then
			perform rhn_cache.update_perms_for_server_group(server_group_id_in);
		end if;

		return;
	end$$ language plpgsql;

	create or replace function insert_into_servergroup_maybe (
		server_id_in in numeric,
		server_group_id_in in numeric
	) returns numeric as $$
    declare
		retval numeric := 0;
		servergroups cursor is
			select	s.id	server_id,
					sg.id	server_group_id
			from	rhnServerGroup	sg,
					rhnServer		s
			where	s.id = server_id_in
				and sg.id = server_group_id_in
				and s.org_id = sg.org_id
				and not exists (
					select	1
					from	rhnServerGroupMembers sgm
					where	sgm.server_id = s.id
						and sgm.server_group_id = sg.id
				);
	begin
		for sgm in servergroups loop
			perform rhn_server.insert_into_servergroup(sgm.server_id, sgm.server_group_id);
			retval := retval + 1;
		end loop;
		return retval;
	end$$ language plpgsql;

	create or replace function insert_set_into_servergroup (
		server_group_id_in in numeric,
		user_id_in in numeric,
		set_label_in in varchar
	) returns void
        as $$
    declare
		servers cursor is
			select	st.element	id
			from	rhnSet		st
			where	st.user_id = user_id_in
				and st.label = set_label_in
				and exists (
					select	1
					from	rhnUserManagedServerGroups umsg
					where	umsg.server_group_id = server_group_id_in
						and umsg.user_id = user_id_in
					)
				and not exists (
					select	1
					from	rhnServerGroupMembers sgm
					where	sgm.server_id = st.element
						and sgm.server_group_id = server_group_id_in
				);
	begin
		for s in servers loop
			perform rhn_server.insert_into_servergroup(s.id, server_group_id_in);
		end loop;
	end$$ language plpgsql;

    create or replace function delete_from_servergroup (
    	server_id_in in numeric,
	server_group_id_in in numeric
    ) returns void
    as $$
    declare

		oid numeric;
		label varchar;
		group_type numeric;
	begin
		select	sg.group_type, sg.org_id
		into	group_type,	oid
		from	rhnServerGroupMembers	sgm,
			rhnServerGroup		sg
		where	sg.id = server_group_id_in
		and 	sg.id = sgm.server_group_id
		and 	sgm.server_id = server_id_in
		for update of sg;

		if not found then
			perform rhn_exception.raise_exception('server_not_in_group');
		end if;

		delete from rhnServerGroupMembers
		where server_group_id = server_group_id_in
		and	server_id = server_id_in;

		update rhnServerGroup
		set current_members = current_members - 1
		where id = server_group_id_in;

		-- do group_type is null first
		if group_type is null then
			perform rhn_cache.update_perms_for_server_group(server_group_id_in);
		end if;

	end$$ language plpgsql;

	create or replace function delete_set_from_servergroup (
		server_group_id_in in numeric,
		user_id_in in numeric,
		set_label_in in varchar
	) returns void
        as $$
        declare
		servergroups cursor is
			select	sgm.server_id, sgm.server_group_id
			from	rhnSet st,
					rhnServerGroupMembers sgm
			where	sgm.server_group_id = server_group_id_in
				and st.user_id = user_id_in
				and st.label = set_label_in
				and sgm.server_id = st.element
				and exists (
					select	1
					from	rhnUserManagedServerGroups usgp
					where	usgp.server_group_id = server_group_id_in
						and usgp.user_id = user_id_in
				);
	begin
		for sgm in servergroups loop
			perform rhn_server.delete_from_servergroup(sgm.server_id, server_group_id_in);
		end loop;
	end$$ language plpgsql;

	create or replace function clear_servergroup (
		server_group_id_in in numeric
	) returns void
        as $$
        declare
		servers cursor is
			select	sgm.server_id	id
			from	rhnServerGroupMembers sgm
			where	sgm.server_group_id = server_group_id_in;
	begin
		for s in servers loop
			perform rhn_server.delete_from_servergroup(s.id, server_group_id_in);
		end loop;
	end$$ language plpgsql;

	create or replace function delete_from_org_servergroups (
		server_id_in in numeric
	) returns void
        as $$
        declare
		servergroups cursor is
			select	sgm.server_group_id id
			from	rhnServerGroup sg,
					rhnServerGroupMembers sgm
			where	sgm.server_id = server_id_in
				and sgm.server_group_id = sg.id
				and sg.group_type is null;
	begin
		for sg in servergroups loop
			perform rhn_server.delete_from_servergroup(server_id_in, sg.id);
		end loop;
	end$$ language plpgsql;

	create or replace function get_ip_address (
		server_id_in in numeric
	) returns varchar as $$
        declare
		interfaces cursor is
			select	ni.name as name, na4.address as address
			from	rhnServerNetInterface ni,
			        rhnServerNetAddress4 na4
			where	server_id = server_id_in
		                and ni.id = na4.interface_id
				and na4.address != '127.0.0.1';
		addresses cursor is
			select	address ip_addr
			from	rhnServerNetInterface
      			left join rhnServerNetAddress4
      			on rhnServerNetInterface.id = rhnServerNetAddress4.interface_id
			where	server_id = server_id_in
				and address != '127.0.0.1'
				and is_primary = 'Y';
	begin
		for addr in addresses loop
			return addr.ip_addr;
		end loop;
		for iface in interfaces loop
			return iface.address;
		end loop;
		return NULL;
	end$$ language plpgsql;

    create or replace function update_needed_cache(
        server_id_in in numeric
	) returns void as $$
    begin
      delete from rhnServerNeededCache
        where server_id = server_id_in;
      insert into rhnServerNeededCache
             (server_id, errata_id, package_id, channel_id)
        (select distinct sp.server_id, x.errata_id, p.id, x.channel_id
           FROM (SELECT sp_sp.server_id, sp_sp.name_id,
		        sp_sp.package_arch_id, max(sp_pe.evr) AS max_evr
                   FROM rhnServerPackage sp_sp
                   join rhnPackageEvr sp_pe ON sp_pe.id = sp_sp.evr_id
                  GROUP BY sp_sp.server_id, sp_sp.name_id, sp_sp.package_arch_id) sp
           join rhnPackage p ON p.name_id = sp.name_id
           join rhnPackageEvr pe ON pe.id = p.evr_id AND (sp.max_evr).type = (pe.evr).type AND sp.max_evr < pe.evr
           join rhnPackageUpgradeArchCompat puac
	            ON puac.package_arch_id = sp.package_arch_id
		    AND puac.package_upgrade_arch_id = p.package_arch_id
           join rhnServerChannel sc ON sc.server_id = sp.server_id
           join rhnChannelPackage cp ON cp.package_id = p.id
	            AND cp.channel_id = sc.channel_id
           left join (SELECT ep.errata_id, ce.channel_id, ep.package_id
                        FROM rhnChannelErrata ce
                        join rhnErrataPackage ep
			         ON ep.errata_id = ce.errata_id
			join rhnServerChannel sc_sc
			         ON sc_sc.channel_id = ce.channel_id
		       WHERE sc_sc.server_id = server_id_in) x
             ON x.channel_id = sc.channel_id AND x.package_id = cp.package_id
	   left join rhnErrata e on x.errata_id = e.id
          where sp.server_id = server_id_in
            and (x.errata_id IS NULL or e.advisory_status != 'retracted')); -- packages which are part of a retracted errata should not be installed
	end$$ language plpgsql;
-- restore the original setting
update pg_settings set setting = overlay( setting placing '' from 1 for (length('rhn_server')+1) ) where name = 'search_path';
 07070100000F5A000081B400000000000000000000000167AE1114000071F8000000000000000000000000000000000000006900000000susemanager-schema/upgrade/susemanager-schema-4.3.9-to-susemanager-schema-4.3.10/005-rhn_channel.pkb.sql  -- oracle equivalent source sha1 31306ef50aaa30b52c7dd02adcb94ab66de8fb25
--
-- Copyright (c) 2008--2018 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--
--
--
--

-- create schema rhn_channel;

--update pg_setting
update pg_settings set setting = 'rhn_channel,' || setting where name = 'search_path';

    -- this "emulates" cursor server_base_subscriptions defined in oracle/rhn_channel.pks
    create or replace function server_base_subscriptions(server_id_in NUMERIC)
    returns boolean as $$
    begin
      return exists(SELECT C.id FROM rhnChannel C, rhnServerChannel SC
		    WHERE C.id = SC.channel_id
		      AND SC.server_id = server_id_in
		      AND C.parent_channel IS NULL);
    end$$ language plpgsql;

    -- this "emulates" cursor server_base_subscriptions defined in oracle/rhn_channel.pks
    create or replace function check_server_subscription(server_id_in NUMERIC, channel_id_in NUMERIC)
    returns boolean as $$
    begin
      return exists(SELECT channel_id FROM rhnServerChannel WHERE server_id = server_id_in AND channel_id = channel_id_in);
    end$$ language plpgsql;


    CREATE OR REPLACE FUNCTION subscribe_server(server_id_in IN NUMERIC, channel_id_in NUMERIC, immediate_in NUMERIC default 1, user_id_in in numeric default null) returns void
    AS $$
    declare
        channel_parent_val      rhnChannel.parent_channel%TYPE;
        parent_subscribed       BOOLEAN;
        server_has_base_chan    BOOLEAN;
        server_already_in_chan  BOOLEAN;
        channel_family_id_val   NUMERIC;
        allowed                 numeric;
    BEGIN
        if user_id_in is not null then
            allowed := rhn_channel.user_role_check(channel_id_in, user_id_in, 'subscribe');
        else
            allowed := 1;
        end if;

        if allowed = 0 then
            perform rhn_exception.raise_exception('no_subscribe_permissions');
        end if;
        
        server_already_in_chan := rhn_channel.check_server_subscription(server_id_in, channel_id_in);

        IF server_already_in_chan
        THEN
            RETURN;
        END IF;

        SELECT parent_channel INTO channel_parent_val FROM rhnChannel WHERE id = channel_id_in;

        IF channel_parent_val IS NOT NULL
        THEN
            -- child channel; if attempting to cross-subscribe a child to the wrong base, silently ignore
            parent_subscribed := rhn_channel.check_server_subscription(server_id_in, channel_parent_val);

            IF NOT parent_subscribed
            THEN
                RETURN;
            END IF;
        ELSE
            -- base channel
            server_has_base_chan := rhn_channel.server_base_subscriptions(server_id_in);

            IF server_has_base_chan
            THEN
                perform rhn_exception.raise_exception('channel_server_one_base');
            END IF;
        END IF;

        channel_family_id_val := rhn_channel.family_for_channel(channel_id_in);
        IF channel_family_id_val IS NULL
        THEN
            perform rhn_exception.raise_exception('channel_subscribe_no_family');
        END IF;

        insert into rhnServerHistory (id,server_id,summary,details) (
            select  nextval('rhn_event_id_seq'),
                    server_id_in,
                    'subscribed to channel ' || SUBSTR(c.label, 0, 106),
                    c.label
            from    rhnChannel c
            where   c.id = channel_id_in
        );

        INSERT INTO rhnServerChannel (server_id, channel_id) VALUES (server_id_in, channel_id_in);

        perform queue_server(server_id_in, immediate_in);

        update rhnServer
           set channels_changed = current_timestamp
         where id = server_id_in;
    END$$ language plpgsql;

    create or replace function guess_server_base(
        server_id_in in numeric
    ) RETURNS numeric as $$
    declare
        server_cursor cursor for
            select s.server_arch_id, s.release, s.org_id
              from rhnServer s
             where s.id = server_id_in;
    -- Cursor that fetches all the possible base channels for a
    -- (server_arch_id, release, org_id) combination
        base_channel_cursor cursor(
                release_in varchar,
                server_arch_id_in numeric,
                org_id_in numeric
        ) for
                select distinct c.*
                from    rhnOrgDistChannelMap                       odcm,
                                rhnServerChannelArchCompat      scac,
                                rhnChannel                                      c
                where   c.parent_channel is null
                        and c.id = odcm.channel_id
                        and c.channel_arch_id = odcm.channel_arch_id
                        and odcm.release = release_in
                        and odcm.for_org_id = org_id_in
                        and scac.server_arch_id = server_arch_id_in
                        and scac.channel_arch_id = c.channel_arch_id;

    begin
        for s in server_cursor loop
            for channel in base_channel_cursor(s.release,
                s.server_arch_id, s.org_id)
            loop
                return channel.id;
            end loop;
        end loop;
        -- Server not found, or no base channel applies to it
        return null;
    end$$ language plpgsql;

    -- Private function
    create or replace function normalize_server_arch(server_arch_in in varchar)
    returns varchar
    as $$
    declare
        suffix VARCHAR(128) := '-redhat-linux';
    begin
        if server_arch_in is NULL then
            return NULL;
        end if;
        if position('-' IN server_arch_in) > 0
        then
            -- Suffix already present
            return server_arch_in;
        end if;
        return server_arch_in || suffix;
    end$$ language plpgsql;

    --
    -- Raises:
    --   server_arch_not_found
    --   no_subscribe_permissions
    create or replace function base_channel_for_release_arch(
        release_in in varchar,
        server_arch_in in varchar,
        org_id_in in numeric default -1,
        user_id_in in numeric default null
    ) returns numeric as $$
    declare
        server_arch varchar(256) := rhn_channel.normalize_server_arch(server_arch_in);
        server_arch_id numeric;
    begin
        -- Look up the server arch
            select id
              into server_arch_id
              from rhnServerArch
             where label = server_arch;
            if not found then
                perform rhn_exception.raise_exception('server_arch_not_found');
            end if;

        return rhn_channel.base_channel_rel_archid(release_in, server_arch_id,
            org_id_in, user_id_in);
    end$$ language plpgsql;

    create or replace function base_channel_rel_archid(
        release_in in varchar,
        server_arch_id_in in numeric,
        org_id_in in numeric default -1,
        user_id_in in numeric default null
    ) returns numeric as $$
    declare
        denied_channel_id numeric := null;
        valid_org_id numeric := org_id_in;
        valid_user_id numeric := user_id_in;
        channel_subscribable numeric;
    -- Cursor that fetches all the possible base channels for a
    -- (server_arch_id, release, org_id) combination
        base_channel_cursor cursor(
                release_in varchar,
                server_arch_id_in numeric,
                org_id_in numeric
        ) for
                select distinct c.*
                from    rhnOrgDistChannelMap                       odcm,
                                rhnServerChannelArchCompat      scac,
                                rhnChannel                                      c
                where   c.parent_channel is null
                        and c.id = odcm.channel_id
                        and c.channel_arch_id = odcm.channel_arch_id
                        and odcm.release = release_in
                        and odcm.for_org_id = org_id_in
                        and scac.server_arch_id = server_arch_id_in
                        and scac.channel_arch_id = c.channel_arch_id;

    begin
        if org_id_in = -1 and user_id_in is not null then
            -- Get the org id from the user id

                select org_id
                  into valid_org_id
                  from web_contact
                 where id = user_id_in;

                if not found then
                    -- User doesn't exist
                    -- XXX Only list public stuff for now
                    valid_user_id := null;
                    valid_org_id := -1;
                end if;
        end if;

        for c in base_channel_cursor(release_in, server_arch_id_in, valid_org_id)
        loop
            -- This row is a possible match
            if valid_user_id is null then
                -- User ID not specified, so no user to channel permissions to
                -- check
                return c.id;
            end if;

            -- Check user to channel permissions
            select rhn_channel.loose_user_role_check(c.id, user_id_in, 'subscribe')
              into channel_subscribable;

            if channel_subscribable = 1 then
                return c.id;
            end if;

            -- Base channel exists, but is not subscribable; keep trying
            denied_channel_id := c.id;
        end loop;

        if denied_channel_id is not null then
            perform rhn_exception.raise_exception('no_subscribe_permissions');
        end if;
        -- No base channel applies
        return NULL;
    end$$ language plpgsql;

    CREATE OR REPLACE FUNCTION clear_subscriptions(server_id_in IN NUMERIC, deleting_server IN NUMERIC default 0) returns void
    AS $$
    declare
        server_channels cursor(server_id_in numeric) for
                select  s.org_id, sc.channel_id, cfm.channel_family_id
                from    rhnServer s,
                        rhnServerChannel sc,
                        rhnChannelFamilyMembers cfm
                where   s.id = server_id_in
                        and s.id = sc.server_id
                        and sc.channel_id = cfm.channel_id
                order by cfm.channel_family_id;
        last_channel_family_id rhnChannelFamilyMembers.channel_family_id%type := -1;
        last_channel_org_id    rhnServer.org_id%type := -1;
    BEGIN
        for channel in server_channels(server_id_in)
        loop
                perform rhn_channel.unsubscribe_server(server_id_in, channel.channel_id, 1, 1, deleting_server);
        end loop;
    END$$ language plpgsql;

    CREATE OR REPLACE FUNCTION unsubscribe_server(server_id_in IN NUMERIC, channel_id_in NUMERIC, immediate_in NUMERIC default 1, unsubscribe_children_in numeric default 0,
                                 deleting_server in numeric default 0) returns void
    AS $$
    declare
        channel_family_id_val   NUMERIC;
        server_org_id_val       NUMERIC;
        server_already_in_chan  BOOLEAN;
        channel_family_is_proxy cursor(channel_family_id_in numeric) for
                select  1
                from    rhnChannelFamily
                where   id = channel_family_id_in
                    and label = 'SMP';
        channel_family_is_satellite cursor(channel_family_id_in numeric) for
                select  1
                from    rhnChannelFamily
                where   id = channel_family_id_in
                    and label IN ('SMS', 'SMS-X86', 'SMS-Z', 'SMS-PPC');
        child record;
    BEGIN
        -- In PostgreSQL recursion with opened cursors is not allowed so we use
        -- FOR IN SELECT form which is ok.
        FOR child IN select  c.id
                from    rhnChannel                      c,
                                rhnServerChannel        sc
                where   1=1
                        and c.parent_channel = channel_id_in
                        and c.id = sc.channel_id
                        and sc.server_id = server_id_in
        LOOP
            if unsubscribe_children_in = 1 then
                perform rhn_channel.unsubscribe_server(server_id_in,
                                                       child.id,
                                                       immediate_in,
                                                       unsubscribe_children_in,
                                                       deleting_server);
            else
                perform rhn_exception.raise_exception('channel_unsubscribe_child_exists');
            end if;
        END LOOP;

        server_already_in_chan := rhn_channel.check_server_subscription(server_id_in, channel_id_in);

        IF NOT server_already_in_chan
        THEN
            RETURN;
        END IF;

   if deleting_server = 0 then
      insert into rhnServerHistory (id,server_id,summary,details) (
          select  nextval('rhn_event_id_seq'),
                server_id_in,
             'unsubscribed from channel ' || SUBSTR(c.label, 0, 106),
             c.label
          from    rhnChannel c
          where   c.id = channel_id_in
      );
   end if;

   DELETE FROM rhnServerChannel WHERE server_id = server_id_in AND channel_id = channel_id_in;

   if deleting_server = 0 then
        perform queue_server(server_id_in, immediate_in);

        update rhnServer
           set channels_changed = current_timestamp
         where id = server_id_in;
   end if;

        channel_family_id_val := rhn_channel.family_for_channel(channel_id_in);
        IF channel_family_id_val IS NULL
        THEN
            perform rhn_exception.raise_exception('channel_unsubscribe_no_family');
        END IF;

        for ignore in channel_family_is_satellite(channel_family_id_val) loop
                delete from suseMgrServerInfo where server_id = server_id_in;
        end loop;

        for ignore in channel_family_is_proxy(channel_family_id_val) loop
                delete from rhnProxyInfo where server_id = server_id_in;
        end loop;
        SELECT org_id INTO server_org_id_val
          FROM rhnServer
         WHERE id = server_id_in;

    END$$ language plpgsql;

    CREATE OR REPLACE FUNCTION family_for_channel(channel_id_in IN NUMERIC)
    RETURNS NUMERIC
    AS $$
    declare
        channel_family_id_val NUMERIC;
    BEGIN
        SELECT channel_family_id INTO channel_family_id_val
          FROM rhnChannelFamilyMembers
         WHERE channel_id = channel_id_in;

        IF NOT FOUND THEN
          RETURN NULL;
        END IF;

        RETURN channel_family_id_val;
    END$$ language plpgsql;

    create or replace function unsubscribe_server_from_family(server_id_in in numeric,
                                             channel_family_id_in in numeric)
    returns void
    as $$
    begin
        delete
        from    rhnServerChannel rsc
        where   rsc.server_id = server_id_in
            and channel_id in (
                select  rcfm.channel_id
                from    rhnChannelFamilyMembers rcfm
                where   rcfm.channel_family_id = channel_family_id_in);
    end$$ language plpgsql;

    create or replace function get_org_id(channel_id_in in numeric)
    returns numeric
    as $$
    declare
        org_id_out numeric;
    begin
        select org_id into strict org_id_out
            from rhnChannel
            where id = channel_id_in;

            return org_id_out;
    end$$ language plpgsql;

    create or replace function get_cfam_org_access(cfam_id_in in numeric, org_id_in in numeric)
    returns numeric
    as $$
    begin
      if exists(
                        select  1
                        from    rhnOrgChannelFamilyPermissions cfp
                        where   cfp.org_id = org_id_in
      ) then
                return 1;
      else
                return 0;
      end if;
    end$$ language plpgsql;

    create or replace function get_org_access(channel_id_in in numeric, org_id_in in numeric)
    returns integer
    as $$
    begin
        -- the idea: if we get past this query,
        -- the org has access to the channel, else not
        if exists(
        select 1
          from rhnChannelFamilyMembers CFM,
               rhnOrgChannelFamilyPermissions CFP
         where cfp.org_id = org_id_in
           and CFM.channel_family_id = CFP.channel_family_id
           and CFM.channel_id = channel_id_in)
        then
          return 1;
        else
          return 0;
        end if;
    end$$ language plpgsql;

    create or replace function rhn_channel.user_role_check(channel_id_in in numeric, user_id_in in numeric, role_in in varchar)
    returns numeric
    as $$
    declare
        result NUMERIC;
    begin
        SELECT
          INTO result
          CASE
            WHEN suseChannelUserRoleView.deny_reason IS NULL THEN 1
            ELSE 0
            END
          FROM suseChannelUserRoleView
          WHERE channel_id = channel_id_in AND
            user_id = user_id_in AND
            role = role_in;

         if result IS NULL then
           result := 0;
         end if;

         RETURN result;
    end$$ language plpgsql;

    --
    -- For multiorg phase II, this function simply checks to see if the user's
    -- has a trust relationship that includes this channel by id.
    --
    create or replace function shared_user_role_check(channel_id in numeric, user_id in numeric, role in varchar)
    returns numeric
    as $$
    declare
      n numeric;
      oid numeric;
    begin
      oid := rhn_user.get_org_id(user_id);
      select 1 into n
      from rhnSharedChannelView s
      where s.id = channel_id and s.org_trust_id = oid;

      if not found then
        return 0;
      end if;

      return 1;
    end$$ language plpgsql;

    -- same as above, but returns 1 if user_id_in is null
    -- This is useful in queries where user_id is not specified
    create or replace function loose_user_role_check(channel_id_in in numeric, user_id_in in numeric, role_in in varchar)
    returns numeric
    as $$
    begin
        if user_id_in is null then
            return 1;
        end if;
        return rhn_channel.user_role_check(channel_id_in, user_id_in, role_in);
    end$$ language plpgsql;

    -- directly checks the table, no inferred permissions
    create or replace function direct_user_role_check(channel_id_in in numeric, user_id_in in numeric, role_in in varchar)
    returns numeric
    as $$
    declare
        throwaway numeric;
    begin
        -- the idea: if we get past this query, the user has the role, else no
        select 1 into throwaway
          from rhnChannelPermissionRole CPR,
               rhnChannelPermission CP
         where CP.user_id = user_id_in
           and CP.channel_id = channel_id_in
           and CPR.label = role_in
           and CP.role_id = CPR.id;

      if not found then
        return 0;
      end if;

      return 1;
    end$$ language plpgsql;

    -- check if an org has a certain setting
    create or replace function org_channel_setting(channel_id_in in numeric, org_id_in in numeric, setting_in in varchar)
    returns numeric
    as $$
    declare
        throwaway numeric;
    begin
        -- the idea: if we get past this query, the org has the setting
        select 1 into throwaway
          from rhnOrgChannelSettingsType OCST,
               rhnOrgChannelSettings OCS
         where OCS.org_id = org_id_in
           and OCS.channel_id = channel_id_in
           and OCST.label = setting_in
           and OCS.setting_id = OCST.id;

      if not found then
        return 0;
      end if;

      return 1;
    end$$ language plpgsql;

    CREATE OR REPLACE FUNCTION channel_priority(channel_id_in IN numeric)
    RETURNS numeric
    AS $$
    declare
         channel_name varchar(256);
         priority numeric;
         end_of_life_val timestamptz;
         org_id_val numeric;
    BEGIN

        select name, end_of_life, org_id
        into channel_name, end_of_life_val, org_id_val
        from rhnChannel
        where id = channel_id_in;

        if end_of_life_val is not null then
          return -400;
        end if;

        if channel_name like 'Red Hat Enterprise Linux%' or channel_name like 'RHEL%' then
          priority := 1000;
          if channel_name not like '%Beta%' then
            priority := priority + 1000;
          end if;

          priority := priority +
            case
              when channel_name like '%v. 5%' then 600
              when channel_name like '%v. 4%' then 500
              when channel_name like '%v. 3%' then 400
              when channel_name like '%v. 2%' then 300
              when channel_name like '%v. 1%' then 200
              else 0
            end;

          priority := priority +
            case
              when channel_name like 'Red Hat Enterprise Linux (v. 5%' then 60
              when (channel_name like '%AS%' and channel_name not like '%Extras%') then 50
              when (channel_name like '%ES%' and channel_name not like '%Extras%') then 40
              when (channel_name like '%WS%' and channel_name not like '%Extras%') then 30
              when (channel_name like '%Desktop%' and channel_name not like '%Extras%') then 20
              when channel_name like '%Extras%' then 10
              else 0
            end;

          priority := priority +
            case
              when channel_name like '%)' then 5
              else 0
            end;

          priority := priority +
            case
              when channel_name like '%32-bit x86%' then 4
              when channel_name like '%64-bit Intel Itanium%' then 3
              when channel_name like '%64-bit AMD64/Intel EM64T%' then 2
              else 0
            end;
        elsif channel_name like 'Red Hat Desktop%' then
            priority := 900;

            if channel_name not like '%Beta%' then
               priority := priority + 50;
            end if;

          priority := priority +
            case
              when channel_name like '%v. 4%' then 40
              when channel_name like '%v. 3%' then 30
              when channel_name like '%v. 2%' then 20
              when channel_name like '%v. 1%' then 10
              else 0
            end;

          priority := priority +
            case
              when channel_name like '%32-bit x86%' then 4
              when channel_name like '%64-bit Intel Itanium%' then 3
              when channel_name like '%64-bit AMD64/Intel EM64T%' then 2
              else 0
            end;

        elsif org_id_val is not null then
          priority := 600;
        else
          priority := 500;
        end if;

      return -priority;

    end$$ language plpgsql;

    -- this could certainly be optimized to do updates if needs be
    create or replace function refresh_newest_package(channel_id_in in numeric,
                                      caller_in in varchar default '(unknown)',
                                      package_name_id_in in numeric default null)
    returns void
    as $$
    -- procedure refreshes rows for name_id = package_name_id_in or
    -- all rows if package_name_id_in is null
    begin
        delete from rhnChannelNewestPackage
              where channel_id = channel_id_in
                and (package_name_id_in is null
                     or name_id = package_name_id_in);
        insert into rhnChannelNewestPackage
                (channel_id, name_id, evr_id, package_id, package_arch_id)
                (select channel_id,
                        name_id, evr_id,
                        package_id, package_arch_id
                   from rhnChannelNewestPackageView
                  where channel_id = channel_id_in
                    and (package_name_id_in is null
                         or name_id = package_name_id_in)
                );
        insert into rhnChannelNewestPackageAudit (channel_id, caller)
             values (channel_id_in, caller_in);
        update rhnChannel
           set last_modified = greatest(current_timestamp,
                                        last_modified + interval '1 second')
         where id = channel_id_in;
    end$$ language plpgsql;

   create or replace function update_channel ( channel_id_in in numeric, invalidate_ss in numeric default 0,
                              date_to_use in timestamptz default current_timestamp ) returns void
   as $$
   declare
   channel_last_modified timestamptz;
   last_modified_value timestamptz;

   snapshots cursor for
   select  snapshot_id id
   from    rhnSnapshotChannel
   where   channel_id = channel_id_in;

   begin

      select last_modified
      into channel_last_modified
      from rhnChannel
      where id = channel_id_in;

      last_modified_value := date_to_use;

      if last_modified_value <= channel_last_modified then
          last_modified_value := last_modified_value + interval '1 second';
      end if;

      update rhnChannel set last_modified = last_modified_value
      where id = channel_id_in;

      if invalidate_ss = 1 then
        for snapshot in snapshots loop
            update rhnSnapshot
            set invalid = lookup_snapshot_invalid_reason('channel_modified')
            where id = snapshot.id;
        end loop;
      end if;

   end$$ language plpgsql;

   create or replace function update_channels_by_package ( package_id_in in numeric, date_to_use in timestamptz default current_timestamp ) returns void
   as $$
   declare
   channels cursor for
   select channel_id
   from rhnChannelPackage
   where package_id = package_id_in
   order by channel_id;

   begin
      for channel in channels loop
         -- we want to invalidate the snapshot assocated with the channel when we
         -- do this b/c we know we've added or removed or packages
         perform rhn_channel.update_channel ( channel.channel_id, 1, date_to_use );
      end loop;
   end$$ language plpgsql;


   create or replace function update_channels_by_errata ( errata_id_in numeric, date_to_use in timestamptz default current_timestamp ) returns void
   as $$
   declare
   channels cursor for
   select channel_id
   from rhnChannelErrata
   where errata_id = errata_id_in
   order by channel_id;

   begin
      for channel in channels loop
         -- we won't invalidate snapshots, b/c just changing the errata associated with
         -- a channel shouldn't invalidate snapshots
         perform rhn_channel.update_channel ( channel.channel_id, 0, date_to_use );
      end loop;
   end$$ language plpgsql;

   create or replace function update_needed_cache(channel_id_in in numeric) returns void
   as $$
   declare
   server record;
   image record;
   begin
      -- we intentionaly do a loop here instead of one huge select
      -- b/c we want to break update into smaller transaction to unblock other sessions
      -- querying rhnServerNeededCache
      for server in (
                select sc.server_id as id
                  from rhnServerChannel sc
                 where sc.channel_id = channel_id_in
                 order by id asc
      ) loop
         perform queue_server(server.id, 0); -- NOT IMMEDIATE
      end loop;
      for image in (
        select ic.image_info_id as id
          from suseImageInfoChannel ic
         where ic.channel_id = channel_id_in
        order by id asc
      ) loop
         perform queue_image(image.id, 0);
      end loop;
   end$$ language plpgsql;

    create or replace function set_comps(channel_id_in in numeric, path_in in varchar, comps_type_id_in in numeric, timestamp_in in varchar) returns void
    as $$
    declare
    row record;
    begin
        for row in (
            select relative_filename, last_modified
            from rhnChannelComps
            where channel_id = channel_id_in
            and comps_type_id = comps_type_id_in
            ) loop
            if row.relative_filename = path_in
                and row.last_modified = to_timestamp(timestamp_in, 'YYYYMMDDHH24MISS') then
                return;
            end if;
        end loop;
        delete from rhnChannelComps
        where channel_id = channel_id_in and comps_type_id = comps_type_id_in;
        insert into rhnChannelComps (id, channel_id, relative_filename, comps_type_id, last_modified, created, modified)
        values (sequence_nextval('rhn_channelcomps_id_seq'), channel_id_in, path_in, comps_type_id_in, to_timestamp(timestamp_in, 'YYYYMMDDHH24MISS'), current_timestamp, current_timestamp);
    end$$ language plpgsql;

-- restore the original setting
update pg_settings set setting = overlay( setting placing '' from 1 for (length('rhn_channel')+1) ) where name = 'search_path';
07070100000F5B000081B400000000000000000000000167AE111400000C86000000000000000000000000000000000000006C00000000susemanager-schema/upgrade/susemanager-schema-4.3.9-to-susemanager-schema-4.3.10/006-hub-reporting-task.sql   
INSERT INTO rhnTaskoBunch (id, name, description, org_bunch)
SELECT sequence_nextval('rhn_tasko_bunch_id_seq'), 'mgr-update-reporting-hub-bunch',
       'Update Reporting DB with data from other susemanager servers', null
WHERE NOT EXISTS (
        SELECT 1 FROM rhnTaskoBunch
        WHERE name = 'mgr-update-reporting-hub-bunch'
    );

INSERT INTO rhnTaskoSchedule (id, job_label, bunch_id, active_from, cron_expr)
SELECT sequence_nextval('rhn_tasko_schedule_id_seq'), 'update-reporting-hub-default',
       (SELECT id FROM rhnTaskoBunch WHERE name='mgr-update-reporting-hub-bunch'),
       current_timestamp, '0 30 1 ? * *'
WHERE NOT EXISTS (
        SELECT 1 FROM rhnTaskoSchedule
        WHERE job_label = 'update-reporting-hub-default'
    );

INSERT INTO rhnTaskoTask (id, name, class)
SELECT sequence_nextval('rhn_tasko_task_id_seq'), 'mgr-update-reporting-hub',
       'com.redhat.rhn.taskomatic.task.HubReportDbUpdateTask'
WHERE NOT EXISTS (
        SELECT 1 FROM rhnTaskoTask
        WHERE name = 'mgr-update-reporting-hub'
    );

INSERT INTO rhnTaskoTemplate (id, bunch_id, task_id, ordering, start_if)
SELECT sequence_nextval('rhn_tasko_template_id_seq'),
       (SELECT id FROM rhnTaskoBunch WHERE name='mgr-update-reporting-hub-bunch'),
       (SELECT id FROM rhnTaskoTask WHERE name='mgr-update-reporting-hub'),
       0, null
WHERE NOT EXISTS (
        SELECT 1 FROM rhnTaskoTemplate
        WHERE bunch_id = (SELECT id FROM rhnTaskoBunch WHERE name = 'mgr-update-reporting-hub-bunch')
          AND task_id = (SELECT id FROM rhnTaskoTask WHERE name = 'mgr-update-reporting-hub')
          AND ordering = 0
    );


INSERT INTO rhnTaskoBunch (id, name, description, org_bunch)
SELECT sequence_nextval('rhn_tasko_bunch_id_seq'), 'mgr-update-reporting-bunch',
       'Update Reporting DB with current data', null
WHERE NOT EXISTS (
        SELECT 1 FROM rhnTaskoBunch
        WHERE name = 'mgr-update-reporting-bunch'
    );

INSERT INTO rhnTaskoSchedule (id, job_label, bunch_id, active_from, cron_expr)
SELECT sequence_nextval('rhn_tasko_schedule_id_seq'), 'update-reporting-default',
       (SELECT id FROM rhnTaskoBunch WHERE name='mgr-update-reporting-bunch'),
       current_timestamp, '0 0 0 ? * *'
WHERE NOT EXISTS (
        SELECT 1 FROM rhnTaskoSchedule
        WHERE job_label = 'update-reporting-default'
    );

INSERT INTO rhnTaskoTask (id, name, class)
SELECT sequence_nextval('rhn_tasko_task_id_seq'), 'mgr-update-reporting',
       'com.redhat.rhn.taskomatic.task.ReportDbUpdateTask'
WHERE NOT EXISTS (
        SELECT 1 FROM rhnTaskoTask
        WHERE name = 'mgr-update-reporting'
    );

INSERT INTO rhnTaskoTemplate (id, bunch_id, task_id, ordering, start_if)
SELECT sequence_nextval('rhn_tasko_template_id_seq'),
       (SELECT id FROM rhnTaskoBunch WHERE name='mgr-update-reporting-bunch'),
       (SELECT id FROM rhnTaskoTask WHERE name='mgr-update-reporting'),
       0, null
WHERE NOT EXISTS (
        SELECT 1 FROM rhnTaskoTemplate
        WHERE bunch_id = (SELECT id FROM rhnTaskoBunch WHERE name = 'mgr-update-reporting-bunch')
          AND task_id = (SELECT id FROM rhnTaskoTask WHERE name = 'mgr-update-reporting')
          AND ordering = 0
    );
commit;
  07070100000F5C000081B400000000000000000000000167AE111400000F35000000000000000000000000000000000000007200000000susemanager-schema/upgrade/susemanager-schema-4.3.9-to-susemanager-schema-4.3.10/006-update-rhnServerOverview.sql --
-- Copyright (c) 2008--2013 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--
--
--
DROP VIEW rhnServerOverview;

create or replace view
rhnServerOverview
(
    org_id,
    server_id,
    server_name,
    modified,
    server_admins,
    group_count,
    channel_id,
    channel_labels,
    history_count,
    security_errata,
    bug_errata,
    enhancement_errata,
    outdated_packages,
	config_files_with_differences,
    last_checkin_days_ago,
    last_checkin,
    pending_updates,
    os,
    release,
    server_arch_name,
    locked,
    proxy_id,
    mgr_server_id
)
as
select
    s.org_id, s.id, s.name, s.modified,
    ( select count(user_id) from rhnUserServerPerms ap
      where server_id = s.id ),
    ( select count(server_group_id) from rhnVisibleServerGroupMembers
      where server_id = s.id ),
    ( select C.id
        from rhnChannel C,
	     rhnServerChannel SC
       where SC.server_id = S.id
         and SC.channel_id = C.id
	 and C.parent_channel IS NULL),
    coalesce(( select C.name
        from rhnChannel C,
	     rhnServerChannel SC
       where SC.server_id = S.id
         and SC.channel_id = C.id
	 and C.parent_channel IS NULL), '(none)'),
    ( select count(id) from rhnServerHistory
      where
            server_id = S.id),
    ( select count(*) from rhnServerErrataTypeView setv
      where
            setv.server_id = s.id
        and setv.errata_type = 'Security Advisory'),
    ( select count(*) from rhnServerErrataTypeView setv
      where
            setv.server_id = s.id
        and setv.errata_type = 'Bug Fix Advisory'),
    ( select count(*) from rhnServerErrataTypeView setv
      where
            setv.server_id = s.id
        and setv.errata_type = 'Product Enhancement Advisory'),
    ( select count(distinct p.name_id) from rhnPackage p, rhnServerNeededCache snc
      where
             snc.server_id = S.id
	 and p.id = snc.package_id
	 ),
    ( select count(*)
        from rhnActionConfigRevision ACR
             INNER JOIN rhnActionConfigRevisionResult ACRR on ACR.id = ACRR.action_config_revision_id
       where ACR.server_id = S.id
         and ACR.action_id = (
              select MAX(rA.id)
                from rhnAction rA
                     INNER JOIN rhnServerAction rSA on rSA.action_id = rA.id
                     INNER JOIN rhnActionStatus rAS on rAS.id = rSA.status
                     INNER JOIN rhnActionType rAT on rAT.id = rA.action_type
               where rSA.server_id = S.id
                 and rAS.name in ('Completed', 'Failed')
                 and rAT.label = 'configfiles.diff'
         )
         and ACR.failure_id is null
         and ACRR.result is not null
        ),
    ( select date_diff_in_days(checkin, current_timestamp) from rhnServerInfo where server_id = S.id ),
    ( select TO_CHAR(checkin, 'YYYY-MM-DD HH24:MI:SS') from rhnServerInfo where server_id = S.id ),
    ( select count(1)
        from rhnServerAction
       where server_id = S.id
         and status in (0, 1)),
    os,
    release,
    ( select name from rhnServerArch where id = s.server_arch_id),
    coalesce((select 1 from rhnServerLock SL WHERE SL.server_id = S.id), 0),
    ( select pxy.server_Id from rhnProxyInfo pxy where pxy.server_id = S.id),
    ( select mgrs.server_Id from suseMgrServerInfo mgrs where mgrs.server_id = S.id)
from
    rhnServer S
;
   07070100000F5D000081B400000000000000000000000167AE1114000000F7000000000000000000000000000000000000007900000000susemanager-schema/upgrade/susemanager-schema-4.3.9-to-susemanager-schema-4.3.10/010-alllow-vendor-change-constrains.sql  -- take care that the check exists. We might have lost it in the past
ALTER TABLE rhnActionDup DROP CONSTRAINT IF EXISTS rhn_actiondup_avc_ck;
ALTER TABLE rhnActionDup ADD CONSTRAINT rhn_actiondup_avc_ck CHECK (allow_vendor_change in ('Y', 'N'));
 07070100000F5E000081B400000000000000000000000167AE11140000008C000000000000000000000000000000000000007000000000susemanager-schema/upgrade/susemanager-schema-4.3.9-to-susemanager-schema-4.3.10/020-suseimagefile-checksum.sql   ALTER TABLE suseImageFile
  ADD COLUMN IF NOT EXISTS checksum_id NUMERIC
  CONSTRAINT suse_fileinfo_chsum_fk
  REFERENCES rhnChecksum (id);
07070100000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000B00000000TRAILER!!!                                                                                                                                                                                                                                                                                                                                                                                                                                                                